text
stringlengths
8
267k
meta
dict
Q: JPA persists already persisted Objects from a ManyToMany relationship I have a @ManyToMany relationship between class A and class B : class A references a collection of class B instances, and this relationship is configured as CascadeType.ALL. So when a A is persisted with the entity manager, the B instances referenced by A are also persisted. Both A and B have an ID declared with the GenerationType.IDENTITY strategy to use the auto_inc from the MySQL database. The problem is : * *I create a new A *I load some existing B objects from entityManager using JPQL *I add the B objects to A's collection of Bs => JPA tries to persist the B objects though they are already persisted (they just have been loaded). I don't understand why it tries to persist them again, they have been properly loaded, and their auto generated id has been well loaded as well. The ManyToMany declaration : @ManyToMany(cascade={CascadeType.ALL}) @JoinTable(name = "ENTRY_ENTITIES", joinColumns = @JoinColumn(name = "ENTRY", referencedColumnName = "ID"), inverseJoinColumns = @JoinColumn(name = "ENTITY", referencedColumnName = "ID")) private List<Entity> entities; The Query to load existing objects from database : T result = (T) entityManager.createQuery("SELECT x FROM " + entityName + " x WHERE x.externalId='" + externalId + "'").getSingleResult(); The persisting : UserTransaction transaction = getTransaction(); try { transaction.begin(); entityManager.persist(entity); transaction.commit(); } catch (Throwable t) { Logger.getLogger(JpaDao.class.getName()).log(Level.SEVERE, null, t); } Thanks a lot for your help! A: I'm not absolutely sure that this is the cause of your problem, but you should include the whole thing inside of a transaction. Not just the persistence part: start transaction load B from DB create new A add B to A commit transaction As I said in my comments, you have other design and coding problems: * *CascadeType.ALL is wrong on a ManyToXxx association. You don't want all the Bs of an A deleted when you delete A, since those Bs are referenced by other As. This will lead to constraint violations (in the best case) or an inconsistent database (in the worst case, if you have no constraint defined) *Don't use string concatenation in your queries. Use parameterized queries. This will avoid quoting problems and injection attacks: SELECT x FROM A x WHERE x.externalId = :externalId A: Those B entities may be part of another persistence context at the point in time that you are adding them to A. Have you tried using the merge operation on the B entities after starting the transaction, before adding them to your A entity.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618527", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQLce 4.0 from enterprise library 5.0 ASP.NET 4.0 I have an MVC3 project in which I have to select/update data from SQLCE database using enterprise library 5.0. For this I have to add reference to SQLCE dll. If I reference the dll from SQLCE 4.0 , I get the error Could not load file or assembly 'System.Data.SqlServerCe, Version=3.5.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified. So I can only guess that enterprise library 5.0 is specifically looking for sqlce 3.5 dll. However if I reference the 3.5 dll in the project I get the error from ASP.NET that ASP.NET is not compatible with SQLCE . I did search the internet but I cant find a solution yet. can somebody give me some info please thanks A: You must recompile the Entrprise Library source, pointing it the the 4.0 ADO.NET Provider.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618530", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python: sequential calls to subprocess (in this case, espeak) I was wondering if there was a way to access espeak as you might in the command line: laptop:~$espeak say this line first say this line second ... Right now, the only ways I can do it in python is process = subprocess.Popen(['espeak'], stdin=subprocess.PIPE ), followed either by process.communicate(expression) or process.stdin.write(expression) process.stdin.close() The former blocks the rest of the program until espeak is finished, not desirable behavior, while the latter doesn't block but allows for the possibility of overlap, say if my program calls espeak twice too quickly. I was wondering if there was a way to call espeak like in the command line, where I could quickly input multiple things to speak, but it would only say the second thing after the first completed, for example. In particular, both of the examples above shut down espeak after a single expression. Is there a way to avoid this? Edit: The answer, given by ed., is to write with newlines at the end then flush process = subprocess.Popen(['espeak'], stdin=subprocess.PIPE ) process.stdin.write("say this line first\n") process.stdin.flush() process.stdin.write("say this line second\n") process.stdin.flush() process.stdin.close() A: You could try calling process.stdin.write(expression) where expression has a newline at the end, and don't call process.stdin.close() until you're done with espeak. If that doesn't work then add a process.stdin.flush() call after the write.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618533", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: bit vector implementation of sets while reading the chapter on basic operations on sets from the book of data structures by aho i came across the following line in the topic bit vector implementation of sets... if the universal set is sufficiently small so that a bit vector fits in one computer word, then union, intersection and difference can be performed by single logical operations in the language of the underlying machine.. a bit vector implementation of sets implies that a set is denoted by an array whose subscripts denote the elements of the set and the content of a subscript is one if it is the member of an array and zero if not....so member, insert and delete operations can be performed in a constant amount of time....but can anyone show me how intersection, union and difference can be performed by single logic operations as stated by the excerpt...plz give an example(or code) for any one of the three operations.... A: Lets suppose you have a computer with a 32-bit word and you want to represent sets over a domain with 32 elements. For example subsets of {0...31}. Sets are represented with a single integer in which bit# x is 1 if and only if x is in the set. So the set {0, 1, 17, 30} would be 01000000000000100000000000000011 We number bits from 31 to 0, left to right, by convention. With this representation: * *Intersection is a binary AND (x & y) *Union is a binary OR (x | y) *Set difference is a binary AND NOT (x & ~y) *Symmetric set difference is a binary XOR (x ^ y) A: Given sets s1 and s2, * *Intersection is s1 & s2 *Union is s1 | s2 *Difference is s1 & ~s2
{ "language": "en", "url": "https://stackoverflow.com/questions/7618535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to download upstream branches? I forked a repo on GitHub with many branches. All the branches show up on GitHub. I do this to download the repo: git clone git-repo-url cd git-repo git remote add upstream git-upstream-url git fetch upstream This all works fine, but when I try to checkout a branch, it doesn't work. I only have the master branch. What do I need to do to download the other branches? A: You can see the remote branches also by doing: git branch -a To checkout a branch, try: git checkout -b local-branch upstream/branch
{ "language": "en", "url": "https://stackoverflow.com/questions/7618542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: is serialized form string secure I use full of ajax requests in my mini networking site . whenever i want to supply some input like the user inputted text along with some important ids , i put them in a form and use '.serialize' to make it as a string and send it through '.getJSON' or '.post' . in the receiving php file 'parse_str' is used to make them seperate variables . Is this whole process secure ? I didnt have any other better idea . So please reply regarding this A: No this is not secure. For example, the serialized string for a password form could be in the format "username=hello&password=world" i.e. the serialized form string is still in plain text and can be sniffed in packets.. Be sure to get an SSL certificate and use HTTPS for any user authentication. A: The problem with security in user-submitted content is that it might contain code that, if not escaped properly, could cause problems. If you're submitting the information to a MySQL server, you should use mysql_real_escape_string. http://php.net/manual/en/function.mysql-real-escape-string.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7618543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Are RandomAccessFile writes asynchronous? Looking at the constructor of RandomAccessFile for the mode it says 'rws' The file is opened for reading and writing. Every change of the file's content or metadata must be written synchronously to the target device. Does this imply that the mode 'rw' is asynchronous? Do I need to include the 's' if I need to know when the file write is complete? A: Are RandomAccessFile writes asynchronous? The synchronous / asynchronous distinction refers to the guarantee that the data / metadata has been safely to disk before the write call returns. Without the guarantee of synchronous mode, it is possible that the data that you wrote may still only be in memory at the point that the write system call completes. (The data will be written to disk eventually ... typically within a few seconds ... unless the operating system crashes or the machine dies due to a power failure or some such.) Synchronous mode output is (obviously) slower that asynchronous mode output. Does this imply that the mode 'rw' is asynchronous? Yes, it is, in the sense above. Do I need to include the 's' if I need to know when the file write is complete? Yes, if by "complete" you mean "written to disc". A: That is true for RandomAccessFile and java.io classes when using multiple threads. The mode "rw" offers asynchronous read/write but you can use a synchronous mode for read and write operations.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to add checkboxes dynamically in android I need to create edittext fields dynamically in android. I have gone through the link and had written the button click action for it. That is when I click on the button the check boxes has to display. But when I am creating the checkbox object in the onclick action it is showing error. Can someone please tell me why is it showing error? My code : public class InflationActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ScrollView sv = new ScrollView(this); final LinearLayout ll = new LinearLayout(this); ll.setOrientation(LinearLayout.VERTICAL); sv.addView(ll); TextView tv = new TextView(this); tv.setText("Dynamic layouts ftw!"); ll.addView(tv); EditText et = new EditText(this); et.setText("weeeeeeeeeee~!"); ll.addView(et); Button b = new Button(this); b.setText("I don't do anything, but I was added dynamically. :)"); ll.addView(b); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub for(int i = 0; i < 20; i++) { CheckBox ch = new CheckBox(this); ch.setText("I'm dynamic!"); ll.addView(ch); } } }); this.setContentView(sv); } } A: Just change your listener to(perfectly working,I have tried): b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { for(int i = 0; i < 20; i++) { CheckBox cb = new CheckBox(getApplicationContext()); cb.setText("I'm dynamic!"); ll.addView(cb); } } }); Note the two changes: * *View.OnClickListener to OnClickListener *new CheckBox(this) to new CheckBox(getApplicationContext()) A: CheckBox ch = new CheckBox(this); change (this) to new CheckBox(your activity name.this); because if you pass this it will not take the Context of your activity because you code this line inside the click listener. A: It's a few years on from this question but the requirement has not changed... here is how I made it work on API 22. The slight variation is I have a floating action button (fab) on a main layout and a content layout which is where I dynamically create the LinearLayout. Note: b.setOnClickListener(new View.OnClickListener() and CheckBox ch = new CheckBox(v.getContext()); activity_main.xml <?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/AppTheme.AppBarOverlay"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" /> </android.support.design.widget.AppBarLayout> <include layout="@layout/content_main" /> <android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|end" android:layout_margin="@dimen/fab_margin" app:srcCompat="@android:drawable/ic_dialog_email" /> </android.support.design.widget.CoordinatorLayout> content_main.xml <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/layout_id" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context=".MainActivity" tools:showIn="@layout/activity_main" tools:layout_editor_absoluteY="81dp" tools:layout_editor_absoluteX="0dp"> </android.support.constraint.ConstraintLayout> MainActivity.java public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); final ViewGroup layout = (ViewGroup) findViewById(R.id.layout_id); ScrollView sv = new ScrollView(this); final LinearLayout ll = new LinearLayout(this); ll.setOrientation(LinearLayout.VERTICAL); sv.addView(ll); TextView tv = new TextView(this); tv.setText("Dynamic layouts! Plain Text"); ll.addView(tv); EditText et = new EditText(this); et.setText("This is edit text"); ll.addView(et); Button b = new Button(this); b.setText("This is a dynamically added button"); ll.addView(b); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub for(int i = 0; i < 20; i++) { CheckBox ch = new CheckBox(v.getContext()); ch.setText("I'm dynamic! "+i); ll.addView(ch); } } }); //this.setContentView(sv); // this causes the fab to fail layout.addView(sv); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); } A: CheckBox ch = new CheckBox(this); "this" is not the activity but the listener. You could use InflationActivity.this but you should use getApplicationContext(); or getBaseContext(). If you have a runtime error you must include the stacktrace from your log files. If your project cannot complile just change the this to what i suggested and will be ok. A: Try: holder.checkbox.performClick();
{ "language": "en", "url": "https://stackoverflow.com/questions/7618553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: In J2ME, How to set Header information with HttpConnection? I have used HttpConnection in J2ME for communication between server. I want to send some data to server with http header. Can anybody tel me how to set header information with HttpConnection. Any example. Thanks A: From http://www.j2mesalsa.com/elearning/networking.html : Set Header Information To set request header properties use setRequestProperty(String key, String value). Example: setRequestProperty( "User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0" ) Hope it helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding an item in list in flex Hi guys i have a list control in a component mxml file. I have created a function in main mxml file, i want to input a text string and add it to this list. How can i do that. Currently using this code public function add(event:MouseEvent):void { var name:String = mytextinputid.text; currentState = 'ChatScreen'; mylist.____ } Note that this function is in main and the mylist list control is in component mxml Best regards A: If you have assigned an id to your component, which I assume is mylist, you simply call myList.dataProvider.addItem(name); You should always have a dataProvider set to myList. Or else you can set one at run time. var myCollection:ArrayCollection = new ArrayCollection(); myCollection.addItem(name); myList.dataProvider = myCollection; OR you can specify a dataProvider from MXML <mx:List id="myList" dataProvider="{myCollection}"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/7618560", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to implement NIO with SSL in java? I want to implement SSL over my Java application using NIO. Have searched internet for same but not able to proceed. Sample implementation code would be a great help. A: With the SSLEngine, but be warned it's no joke. There is some sample code in the JDK but it makes some rather untenable assumptions, such as only one handshake per connection, client mode only, etc. Integration with a Selector is particularly problematic. A: Like Friek said, look at netty from Jboss. In their documentation section there is an example involving SSL. A: SSLEngine is the standard way of doing SSL/TLS with NIO in Java. But it is seriously hard to use, and not recommended for applications that just want a secure socket. There is fortunately at least one library alternative: TLS Channel wraps a SSLContext (or SSLEngine) and exposing a ByteChannel interface, doing the heavy lifting internally. (Disclaimer: I am the library's main author)
{ "language": "en", "url": "https://stackoverflow.com/questions/7618567", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Unable to drop database due to illegal character How can i drop a database containing the "-" symbol? mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | vms01 | | vms-0.1.0 | +--------------------+ 4 rows in set (0.00 sec) mysql> drop database vms-0.1.0; ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use n ear '-0.1.0' at line 1 mysql> A: You can quote identifiers (for example table and column names) with backticks: drop database `vms-0.1.0` See the documentation for more details: Schema Object Names. The identifier quote character is the backtick ("`"):
{ "language": "en", "url": "https://stackoverflow.com/questions/7618575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: onclick replace php included file I am not sure if what I am trying to do is possible but here it is. I have a header, inside that header is a php include for "login.php" On "login.php" is a link that takes the user to "forgot.php". What I would like to do is, instead of the user being taken to "forgot.php" is to just refresh the page with "login.php" include replaced with "forgot.php" or do some sort of content switch out, sort of like using an Iframe. I dont want to bring the user to a new page, I just want to switch out the content displayed inside my header. Thanks for any help you can provide, code samples appreciated. A: If you are trying to accomplish this without reloading the page you will need to use AJAX. If you want to just keep the login.php you can perhaps do something like: <a href="login.php?p=forgot">link</a> with php something like <? if ( isset($_GET['p']) && $_GET['p']=="forgot") { include('forgot.php'); } else { include('login.php'); } A: PHP is parsed in it's entirety before the page is displayed in a user's browser, therefore, things such as onclick() or onsubmit() that are featured in JavaScript (a client-side language) are not available in PHP. There would be a few solutions possible: 1) Use AJAX to submit a query to the server and replace the HTML content on the page with the result. 2) As you mentioned, use iFrames. 3) Have a hidden <div> on your login.php page that contains the HTML for forgot.php, and use a simple JavaScript onclick() method to swap the page contents. In this case, both "pages" would actually all be in the same file of login.php. A: You can't change the include statement from javascript because the script was already executed by the time you see your page in the browser. Use ajax to dinamically change the content of the page without refreshing. If you're using jquery the code would be pretty simple: <script type="text/javascript"> $(document).ready(function() { $('#link').click(function() { $.get('script.php', function(data) { $('#divOfContainer').html(data); }); }); }); </script> <div id="divOfContainer"><!-- the content to be fetched with ajax will be put here --></div> <a href="#" id="link">Link</a> A: I can think of two things: What I would do, assuming that the differences between your login.php and forgot.php aren't too different because you don't to change the page, is to put the html for the forgot.php just below the html for the login.php and hide the login.php html and show the forgot.php content. example: <div id = "login"> <!-- Login HTML --> </div> <div id = "forgot" style = "display:none" > <!-- forgot password HTML --> </div> <input type="button" value="Forgot Password?" onclick="forgot()" /> Javascript: function forgot(){ document.getElementById('login').style.display='none'; document.getElementById('forgot').style.display='block'; } Otherwise, you could use an ajax call to the page and insert the necessary elements. This would create a noticeable pause.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to set volume for chromeless youtube API? I have used chromeless youtube API for playing youtube videos through youtube ID and I have used to set volume player.setVolume = 50; and player.getVolume(); but its not updating. A: According to the API documentation, it is player.setVolume(50), not player.setVolume = 50. Member names with "set", like setSomething, are usually methods, not properties. If the volume was meant to be set using assignment, it would probably be just player.volume = 50, without "set".
{ "language": "en", "url": "https://stackoverflow.com/questions/7618579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Issue on sprintf in Matlab How to print in Matlab Like following.... 0.01000E+02 I have tried sprintf('%12.5e',[0.01000E+02]) it is giving me 1.00000e+000 A: You format is a bit specific. You should consider writing your own output function. But a few pointers: * *Make e large with upper *only 2 digits in exp number through a regexp. new_string = regexprep(old_string,'\d(\d{2})$','\1') *the thing with leading 0 in exp representation is not standard - so maybe multiply with 1e2, print the float and later attach the E+02. A: Something like ['0.0' strrep(sprintf('%12.5E',v*100), '.', '')] (with v your value) should work if I understand correctly your format.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Upgrade Cassandra Version Brisk How can I upgrade the cassandra version and thrift version in Brisk? Is there any tutorials kind of stuffs avalailble? I changed the build.properties file but on build, the version I mentioned couldn't be located at any repository. Im trying to upgrade because of Cassandra Insertion Error this issue im facing. I hope the comment mentioned there helps What is the latest version of cassandra that brisk supports? In support forums I see people mentioning, replace the jars. I don't understand where should I do that. Thanks for Help in advance Regards, Tamil A: Finally I found the way to upgrade Brisk's cassandra version. I Downloaded apache-cassandra-0.8.6-bin from apache site. Copied lib/apache-cassandra-0.8.6.jar and lib/apache-cassandra-thrift-0.8.6.jar to brisk-1.0~beta2-bin/resources/cassandra/lib/ and removed the older version's cassandra and thrift jars and just restarted brisk with ./brisk cassandra and tried this $ ./nodetool -h x.x.x.x version ReleaseVersion: 0.8.6 So, I hope there won't any compatability issues, since in a forum a brisk dev mentioned tat brisk core works independently against cassandra core. But I'm yet to know the way to do it by building from src rather replacing jars in bin Regards, Tamil
{ "language": "en", "url": "https://stackoverflow.com/questions/7618589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Order of evaluation of expression I've just read that order of evaluation and precedence of operators are different but related concepts in C++. But I'm still unclear how those are different but related?. int x = c + a * b; // 31 int y = (c + a) * b; // 36 What does the above statements has to with order of evaluation. e.g. when I say (c + a) am I changing the order of evaluation of expression by changing its precedence? A: The important part about order of evaluation is whether any of the components have side effects. Suppose you have this: int i = c() + a() * b(); Where a and b have side effects: int global = 1; int a() { return global++; } int b() { return ++global; } int c() { return global * 2; } The compiler can choose what order to call a(), b() and c() and then insert the results into the expression. At that point, precedence takes over and decides what order to apply the + and * operators. In this example the most likely outcomes are either * *The compiler will evaluate c() first, followed by a() and then b(), resulting in i = 2 + 1 * 3 = 5 *The compiler will evaluate b() first, followed by a() and then c(), resulting in i = 6 + 2 * 2 = 10 But the compiler is free to choose whatever order it wants. The short story is that precedence tells you the order in which operators are applied to arguments (* before +), whereas order of evaluation tells you in what order the arguments are resolved (a(), b(), c()). This is why they are "different but related". A: "Order of evaluation" refers to when different subexpressions within the same expression are evaulated relative to each other. For example in 3 * f(x) + 2 * g(x, y) you have the usual precedence rules between multiplication and addition. But we have an order of evaluation question: will the first multiplication happen before the second or the second before the first? It matters because if f() has a side effect that changes y, the result of the whole expression will be different depending on the order of operations. In your specific example, this order of evaluation scenario (in which the resulting value depends on order) does not arise. A: As long as we are talking about built-in operators: no, you are not changing the order of evaluation by using the (). You have no control over the order of evaluation. In fact, there's no "order of evaluation" here at all. The compiler is allowed to evaluate this expression in any way it desires, as long as the result is correct. It is not even required to use addition and multiplication operations to evaluate these expressions. The addition and multiplication only exist in the text of your program. The compiler is free to totally and completely ignore these specific operations. On some hardware platform, such expressions might be evaluated by a single atomic machine operation. For this reason, the notion of "order of evaluation" does not make any sense here. There's nothing there that you can apply the concept of "order" to. The only thing you are changing by using () is the mathematical meaning of the expression. Let's say a, b and c are all 2. The a + b * c must evaluate to 6, while (a + b) * c must evaluate to to 8. That's it. This is the only thing that is guaranteed to you: that the results will be correct. How these results are obtained is totally unknown. The compiler might use absolutely anything, any method and any "order of evaluation" as long as the results are correct. For another example, if you have two such expressions in your program following each other int x = c + a * b; int y = (c + a) * b; the compiler is free to evaluate them as int x = c + a * b; int y = c * b + x - c; which will also produce the correct result (assuming no overflow-related problems). In which case the actual evaluation schedule will not even remotely look like something that you wrote in your source code. To put it short, to assume that the actual evaluation will have any significant resemblance to what you wrote in the source code of your program is naive at best. Despite popular belief, built-in operators are not generally translated in their machine "counterparts". The above applies to built-in operators, again. Once we start dealing with overloaded operators, things change drastically. Overloaded operators are indeed evaluated in full accordance with the semantic structure of the expression. There's some freedom there even with overloaded operators, but it is not as unrestricted as in case of built-in operators. A: The answer is may or may not. The evaluation order of a, b and c depends on the compiler's interpretation of this formula. A: Consider the below example: #include <limits.h> #include <stdio.h> int main(void) { double a = 1 + UINT_MAX + 1.0; double b = 1 + 1.0 + UINT_MAX; printf("a=%g\n", a); printf("b=%g\n", b); return 0; } Here in terms of math as we know it, a and b are to be computed equally and must have the same result. But is that true in the C(++) world? See the program's output. A: I want to introduce a link worth reading with regard to this question. The Rules 3 and 4 mention about sequence point, another concept worth remembering.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: is there a javascript/jquery selector for text selected by mouse cursor? is there a jquery selector for text that is highlighted after its dragged over by the mouse cursor? For example, I want to select text that I've typed into my textarea field, click a button, which puts <p> tags around the text I've highlighted with my mouse cursor. A non-plugin solution would be preferred, thanks. A: There's a straight up javascript solution that's pretty nice... just use inputElement.selectionStart and inputElement.selectionEnd . It's helpful to note that this is just on Dom elements, so you'll have to take your jQuery selector for your textarea and add [0] to get the element itself, ie. $("#myTextArea")[0].selectionStart. From there you can do some string work and add in your <p> tags at the appropriate indexes. I haven't tested this, but it should work... var selStart = $("#myTextArea")[0].selectionStart; var selEnd = $("#myTextArea")[0].selectionEnd; var originalString = $("#myTextArea").val(); var segment_1 = originalString.substr(0,selStart); var segment_2 = originalString.substr(selStart,selEnd); var segment_3 = originalString.substr(selEnd,originalString.length); var finalString = segment_1 + "<p>" + segment_2 + "</p>" + segment_3; $("#myTextArea").val(finalString); A: Why dont you use php for this? PHP + jQuery will help you. Example form: <form action="highlight.php" method="post"> My textarea:<br /> <textarea cols="10" rows="10" name="textarea"></textarea> <input type="submit" value="Wrap <p> around" /> </form> PHP to process the form and wrap around it: <?php $text = $_POST['']; $wrap = '<p>'.$text.'</p>'; echo '<textarea cols="10" rows="10">'.$wrap.'</p>'; ?> You can remove echo $wrap, but i prefer you learn jQuery and how you can use it to execute a php script. I Dont have that much jQuery experience to tell you how, but learn it or google "How to execute php script with jquery" and im sure you will find something =)
{ "language": "en", "url": "https://stackoverflow.com/questions/7618591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Singleform with different database I want to make a form in php where there will be two categories. One for the Student profile details and another for the student's marks details. Now the main problem is all this will be in one single form means in one page and the categories like student details will be save in student detail table of the database and the marks will be save in another database called marks database. I also need CRUD for these two categories.So how to do that? Any suggestion and help will be highly appreciable. A: Well there is no direct link between a form and a database table, so what is your problem? Why don't you do the mysql_query() on each table one after another when you handle the form post? A: You can build your form like this in order to separate the tables: <input type="text" name="data[student][name]" /> <input type="text" name="data[category][name]" /> you PHP script then goes through the data and save it in the corresponding tables: foreach($_POST['data'] as $table=>$row){ // do your insert statemnet here (don't foregt to escape the Parameters!) }
{ "language": "en", "url": "https://stackoverflow.com/questions/7618594", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HTML Spreadsheet fixed headers and leftmost column I'm trying to create a spreadsheet similar to Google Docs Spreadsheet or Excel where you have a table full of data. How do I make it so when I scroll vertically, the first row stays fixed and when the user scrolls horizontally, the first column stays fixed? I'm not looking for a plugin, just how is this done using HTML/CSS? I've been looking at the code for Google Docs Spreadsheet, but I'm unable to pinpoint the solution. Can someone provide a simple example for this? For example: jsFiddle: http://jsfiddle.net/tYUwd/2/ In the jsFiddle, when you scroll horizontally, I'd like .row-header elements to be fixed. When you scroll vertically, .column-headers are to be fixed. A: I'm fairly certain this cannot currently be done with only HTML/CSS. You can do a fixed header or a pseudo fixed first column with just HTMl/CSS, but you need JavaScript to get both working together. I would suggest checking out this site: http://www.8164.org/the-big-table-issue/ I would also suggest checking out these two possible solutions: http://cross-browser.com/x/examples/xtable.php http://www.disconova.com/open_source/files/freezepanes.htm I've used the Freeze Panes solution before and it works great.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Web page rendering in IE7 I am working on a site which is displayed properly in IE8 (when browser mode is IE8 and document mode is IE8 standards) and rest of the other browsers like chrome, firefox, etc. Except it is not diaplyed properly in IE7. I have heard of meta tags which allow users to force document mode to be displayed in a particular browser. A: try adding the meta tag which will use Google Chrome Frame to render the page if chrome is installed in the machine. <meta http-equiv="X-UA-Compatible" content="chrome=1">
{ "language": "en", "url": "https://stackoverflow.com/questions/7618596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: unpack base64-encoded 32bit integer representing IP address I have a base64-encoded, 32-bit integer, that's an IP address: DMmN60 I cannot for the life of me figure out how to both unpack it and turn it into a quad-dotted representation I can actually use. Unpacking it with unpack('m') actually only gives me three bytes. I don't see how that's right either, but this is far from my expertise. A: Hello from the future (two years later) with Ruby 1.9.3. To encode: require 'base64' ps = "204.152.222.180" pa = ps.split('.').map { |_| _.to_i } # => [204, 152, 222, 180] pbs = pa.pack("C*") # => "\xCC\x98\xDE\xB4" es = Base64.encode64(s) # => "zJjetA==\n" To decode: require 'base64' es = "zJjetA==\n" pbs = Base64.decode64(es) # => "\xCC\x98\xDE\xB4" pa = pbs.unpack("C*") # => [204, 152, 222, 180] ps = pa.map { |_| _.to_s }.join('.') # => "204.152.222.180" Name explanation: * *ps = plain string *pa = plain array *pbs = plain binary string *es = encoded string For your example: Base64.decode64("DMmN60==").unpack("C*").map { |_| _.to_s }.join('.') # => "12.201.141.235" Just like @duskwuff said. Your comment above said that the P10 base64 is non-standard, so I took a look at: http://carlo17.home.xs4all.nl/irc/P10.html which defines: <base64> = 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P', 'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f', 'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v', 'w','x','y','z','0','1','2','3','4','5','6','7','8','9','[',']' It is the same as http://en.wikipedia.org/wiki/Base64 -- except that the last two characters are + and / in the normal Base64. I don't see how this explains the discrepancy, since your example did not use those characters. I do wonder, however, if it was due to some other factor -- perhaps an endian issue. A: Adding padding (DMmN60==) and decoding gives me the bytes: 0C C9 8D EB Which decodes to 12.201.141.235.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Running Scilab from pexpect I am trying to run scilab using the pexpect module with the following code: import pexpect c=pexpect.spawn('scilab-adv-cli -nb') c.expect('-->') When I do c.sendline('plot[1,2]') the plot shows up. But when I do c.sendline('[1 2]*[3]') c.expect('ans =') followed by c.before it gives me the following out put: ' =\r\n \r\n 3. 6. \r\n \r\n\x1b[?1h\x1b=-->[1 2]*[3]\r\n\x1b[?1l\x1b> ' How can the above output be sanitised to obtain only say 3. 6. in the above ? A: If all the output you want to read is that simple, then you can do: largenum = 1000 # flush any remaining output c.read_nonblocking(largenum) c.sendline('[1 2]*[3]') # discard unwanted lines until relevant line for i in range(3): next(c) # get answer (in this case, a single line) ans = next(c).strip() # discard rest of answer c.read_nonblocking(largenum) You probably know it, you are highly dependent on the way the scilab CLI outputs data. A: Or give a try to: http://forge.scilab.org/index.php/p/sciscipy/
{ "language": "en", "url": "https://stackoverflow.com/questions/7618601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I set up a deploy to server / sync with server goal in Maven? I'd running maven locally, and it's fantastic! The only issue that I have now is that I have a heavy stack and I have these Massive WAR files. Is there a good approach or best practice with regards to using Maven as a tool to sync your local dependencies with application running on the server? For example, can I somehow create a goal that uploads the POM, and tells Maven to rebuild on the server side? We're running linux on both sides. Jetty locally and Tomcat remotely. I'm sure the Apache guys thought of this... Your thoughts are much appreciated... A: One tool you could look into is cargo, which can take the generated artifact that you've built and install it to a remote server instance. Cargo can be integrated into your maven build. However, if you have multiple developers and just want the latest version of whatever is in the repository deployed to the server, I'd encourage you to at least investigate a continuous integration server and setting up a manual or nightly job to do deployments for you. A continuous integration server, such as Jenkins, can: * *Check SVN for any code changes (if you want to enable SVN polling) *Perform a checkout (or revert + update) to receive the latest code from SVN. *Build the WAR file using your maven build. *Use either the Jenkins Deploy Plugin or a post build step to deploy the final WAR. Letting Cargo do the deploy via maven during the build is also an option. Just some thoughts. I also highly recommend Nexus as an artifact repository. Since Jenkins is able to run your build as a Maven build, you can configure Jenkins to run the deploy goal and configure maven with the location of your deployed artifacts server (Nexus location) for the builds to be pushed to. A: I think the right way would be to install the resulting war (if neccessary one per server config) into a repository (not SVN, a Maven repository like Nexus). With that you can setup simple scripts or maven configs to deploy the artifacts on your test or production servers without the need to rebuild them on the server. Checkout the install plugin.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Custom VerticalSeekBar onSeekBarChangeListener implementation I have implemented the VerticalSeekBar using this unbelievably simple solution here: How can I get a working vertical SeekBar in Android? The problem is, I can't seem to set an onseekbarchangelistener in my UI Activity that uses this class. I can't for the life of me understand how to do this. I can do it from within the VerticalSeekBar class: if I add code inside the onTouch() method, it works. However I need an onTouch listener in my Activity. P.S. is there a particular reason why Android doesn't have a native vertical seekbar? Considering most phones are naturally portrait-mode devices, it makes sense to have bars running along the the length rather than the width of the screen. I have tried many VerticalSeekBar solutions from stackoverflow (love this site!), but the only solution that centers my SeekThumb graphic is the link supplied above. I have been working on getting a perfect vertical seekbar for months now. Any help would be a humansend! A: in VerticalSeekBar class, comment out this whole part: @Override public void setOnSeekBarChangeListener(OnSeekBarChangeListener mListener) { this.myListener = mListener; } A: instead you can do this SeekBar sb = (SeekBar)findViewById(R.your.id); sb.setOnSeekBarChangeListener(this); Eclipse would underline it and ask you to implement onseekbarchangelistener, you do that and implement the methods and you are good to go Good Luck !
{ "language": "en", "url": "https://stackoverflow.com/questions/7618603", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to enable Facebook apps for secure URL[https] users using same folder in server I have created a facebook application which can server both http and https users. As of now, I'm using two different folders on the server on each for https and https respectively. e.g. http://example.com/folder and https://example.com/folder_secure I personally feel that this may be unnecessary redundancy[though clueless of the workaround], is there anyway I can include code for both http and https in a single folder and set the canvas url and secure canvas url as something like http://example.com/folder and https://example.com/folder A: You are over-thinking this. HTTP and HTTPS are just access mechanisms, they don't necessarily go to different places. Configure your web server to use the same directories for both protocols and you'll be fine. EDIT The way a URL like https://example.com/folder_secure is translated into a file-path on the server like /var/www/html/folder is controlled by the configuration of the web server. You're going to have to read the manual for whatever server you're using. If it is Apache, the variable you need is DocumentRoot.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Return data from AsyncTask class How do I get the data from my AsyncTask? My MainActivity is calling the DataCall.getJSON function that triggers the AsyncTask but I am not sure how to get the data back to the original Activity. MainActivity with call to DataCall that should return a string and save it in state_data String state_data = DataCall.getJSON(spinnerURL,spinnerContentType); DataCall: public class DataCall extends Activity { private static final String TAG = "MyApp"; private class DownloadWebPageTask extends AsyncTask<String, Void, String> { protected String doInBackground(String... urls) { String response = ""; for (String url : urls) { DefaultHttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); try { HttpResponse execute = client.execute(httpGet); InputStream content = execute.getEntity().getContent(); BufferedReader buffer = new BufferedReader( new InputStreamReader(content)); String s = ""; while ((s = buffer.readLine()) != null) { response += s; } } catch (Exception e) { e.printStackTrace(); } } return response; } protected void onPostExecute(String result) { //THIS IS WHERE I NEED TO RETURN MY DATA TO THE MAIN ACTIVITY. (I am guessing) } } public void getJSON(String myUrlString, String contentType) { DownloadWebPageTask task = new DownloadWebPageTask(); task.execute(new String[] { "http://www.mywebsite.com/" + myUrlString }); } } A: The key for me was to create a class called URLWithParams or something because AsyncTask will allow only 1 type to be sent IN, and I needed both the URL and the params for the HTTP request. public class URLWithParams { public String url; public List<NameValuePair> nameValuePairs; public URLWithParams() { nameValuePairs = new ArrayList<NameValuePair>(); } } and then I send it to a JSONClient: public class JSONClient extends AsyncTask<URLWithParams, Void, String> { private final static String TAG = "JSONClient"; ProgressDialog progressDialog ; GetJSONListener getJSONListener; public JSONClient(GetJSONListener listener){ this.getJSONListener = listener; } @Override protected String doInBackground(URLWithParams... urls) { return connect(urls[0].url, urls[0].nameValuePairs); } public static String connect(String url, List<NameValuePair> pairs) { HttpClient httpclient = new DefaultHttpClient(); if(url == null) { Log.d(TAG, "want to connect, but url is null"); } else { Log.d(TAG, "starting connect with url " + url); } if(pairs == null) { Log.d(TAG, "want to connect, though pairs is null"); } else { Log.d(TAG, "starting connect with this many pairs: " + pairs.size()); for(NameValuePair dog : pairs) { Log.d(TAG, "example: " + dog.toString()); } } // Execute the request HttpResponse response; try { // Prepare a request object HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(pairs)); response = httpclient.execute(httpPost); // Examine the response status Log.i(TAG,response.getStatusLine().toString()); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String json = reader.readLine(); return json; } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override protected void onPostExecute(String json ) { getJSONListener.onRemoteCallComplete(json); } public interface GetJSONListener { public void onRemoteCallComplete(String jsonFromNet); } } Then call it from my main class like this public class BookCatalog implements GetJSONListener { private final String TAG = this.getClass().getSimpleName(); private String catalog_url = "URL"; private void getCatalogFromServer() { URLWithParams mURLWithParams = new URLWithParams(); mURLWithParams.url = catalog_url; try { JSONClient asyncPoster = new JSONClient(this); asyncPoster.execute(mURLWithParams); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void onRemoteCallComplete(String jsonBookCatalogList) { Log.d(TAG, "received json catalog:"); Log.d(TAG, jsonBookCatalogList); JSONObject bookCatalogResult; try { bookCatalogResult = (JSONObject) new JSONTokener(jsonBookCatalogList).nextValue(); JSONArray books = bookCatalogResult.getJSONArray("books"); if(books != null) { ArrayList<String> newBookOrdering = new ArrayList<String>(); int num_books = books.length(); BookCatalogEntry temp; DebugLog.d(TAG, "apparently we found " + Integer.toString(num_books) + " books."); for(int book_id = 0; book_id < num_books; book_id++) { JSONObject book = books.getJSONObject(book_id); String title = book.getString("title"); int version = book.getInt("price"); } } } catch (JSONException e) { e.printStackTrace(); } } } A: modify your AsyncTask as below: public class GetData extends AsyncTask<String, Void, String> { DataDownloadListener dataDownloadListener; public GetData() { //Constructor may be parametric } public void setDataDownloadListener(DataDownloadListener dataDownloadListener) { this.dataDownloadListener = dataDownloadListener; } @Override protected Object doInBackground(Object... param) { // do your task... return null; } @Override protected void onPostExecute(Object results) { if(results != null) { dataDownloadListener.dataDownloadedSuccessfully(results); } else dataDownloadListener.dataDownloadFailed(); } public static interface DataDownloadListener { void dataDownloadedSuccessfully(Object data); void dataDownloadFailed(); } } and use it in your Activity GetData getdata = new GetData(); getdata.setDataDownloadListener(new DataDownloadListener() { @SuppressWarnings("unchecked") @Override public void dataDownloadedSuccessfully(Object data) { // handler result } @Override public void dataDownloadFailed() { // handler failure (e.g network not available etc.) } }); getdata.execute(""); NOTE: For the people who are reading this. Please consider this post for the best and perhaps right implementation. A: Serialize it and then read it. The only way I'm aware of. A: Although i disagree creating a new activity for that simple task there is startActivityForResult() to get data from another activity. Check this. You can store your data to the Intent's extras. But still if you have a large amount of data you better off write it to a file get the result from the other activity that is done downloading and then read the file. A: Some options: a) Make your bean implement Serializable interface, you can then pass your bean through Intent. b) Implement Application interface (you need to make an entry in manifest), Have setter\getter method in your Application class. You can set your bean in Application from AsyncTask and later retrieve from Activity. A: Sorry for answering so late, i think by this time you might have solved this problem. when i was searching for something else, i came across your question. I'm pasting a link here which might of some help for others.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618614", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: no postback on specific page I am using asp.net Routes in the Global.asax: routes.MapPageRoute("Home", "home", "~/index.aspx"); routes.MapPageRoute("Profiles", "profile/{nick}/{profid}", "~/Profile.aspx"); I have in my master page a top menu, in which there is a LinkButton with OnClick event. Problem is, the postback works only on routed pages like "HOME" but not in the Profile (which is constructed out of /asdf/12345 instead of just /1235. When clicking the top menu LinkButton in the profile page I get 404 page. it doesnt even post to the page! what can be wrong? thanks A: Problem solved. I had to put in my Masterpage: this.form1.Action = Request.RawUrl; this fixed the form's action!
{ "language": "en", "url": "https://stackoverflow.com/questions/7618617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: flex 4.5.1:Access file from server I am working on flex mobile project using flex 4.5.1. I want to get data from file (which is placed on server) only if the file is modified. I think I can use blazeds for this purpose, But I dont know how to do this. I am searching it in internet. please guide me A: http://help.adobe.com/en_US/Flex/4.0/AccessingData/WSbde04e3d3e6474c46c45e7b4120d413dc14-8000.html http://www.switchonthecode.com/tutorials/flex-using-item-renderers hope the above links would help you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I implement client side http caching like a browser? I use a RESTFul service as a backend to my frontend. The service sets expires/etag/lastmodified headers on it's responses. What I'm looking for is a client-side(favorably java) library which can fetch data from the service and cache it in a pluggable caching backend like ehcache. What I also want to be able to do is automatically prime the cache using background worker threads as soon as an entry is invalidated. Also, it should be smart to do conditional GETs. I've come across http://hc.apache.org/httpcomponents-client-ga/tutorial/html/caching.html Is there any other library anyone knows about? Isn't this a fairly common problem? A: The situation with client side HTTP caches in Java is not particularly good. It is a non-trivial problem that has not been attacked by most of the HTTP client library developers. I think that is changing slowly, but I cannot provide a definite pointer. A good way to start is to look at the various implementations of JAX-RS that come with a client side API such as Jersey (this has no client side cache). It might be that Restlet has one or Restfulie, please check. Here is something I found via Google: http://xircles.codehaus.org/projects/httpcache4j You can also try to roll your own but you have to be careful to understand the caching headers (including Vary:) to get it right. A: The 4.0+ version of the Apache HttpComponents library comes with HTTP 1.1 cache support. You can use this with the Spring RestTemplate restful client as follows: CacheConfig cacheConfig = new CacheConfig(); cacheConfig.setMaxCacheEntries(1000); cacheConfig.setMaxObjectSize(8192); HttpClient cachingClient = new CachingHttpClient(new DefaultHttpClient(), cacheConfig); ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(cachingClient); RestTemplate rest = new RestTemplate(requestFactory); A: RestEasy features a client side caching mechanism which is trivial to get up and running if you are using such client. RegisterBuiltin.register(ResteasyProviderFactory.getInstance()); YourService proxy = ProxyFactory.create(YourService.class, url); LightweightBrowserCache cache = CacheFactory.makeCacheable(proxy); You first create a client proxy instance, then wrap it around the cache. That's it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to push the uinavigationcontroller into another uinavigationcontroller Currently i have an application that uses uinavigationcontroller but hides the navigationbar only in root view and i want to use this application as external library in some application and push this entire application as one menu item. But when i try to push this application in navigation stack it hides the navigation barand i am not able come to my previous list. How to show the back button in this case and How to push one uinavigationcontroller in some other navigationcontroller? please help me in this issue. A: The navigationController is applicable throughout the application.So,what u need to do is simply hide the navigation bvar in RootViewController and show it on the next view.This solves your problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Error trying to access a struct type using a pointer to a vector of structs #include <iostream> #include <vector> using namespace std; struct a_struct { int an_int; }; int main () { vector <vector <a_struct> > the_vec; vector <a_struct> * p_vs; p_vs = & the_vec[0]; *(p_vs)[0].an_int=0; //error: 'class __gnu_debug_def::vector<a_struct, //std::allocator<a_struct> >' has no member named 'an_int' } I can't figure out why I'm getting the above compile error. A: In C++, [] and . have higher precedence than *. Your last line *(p_vs)[0].an_int=0; when fully parenthesized, is *((p_vs[0]).an_int)=0; Since p_vs was declared as vector <a_struct> * p_vs; it is as if p_vs is an array of vector <a_struct> elements, so p_vs[0] is a vector<a_struct>. And vector<a_struct> objects indeed do not have a member an_int. Add some parens and you will get what you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618631", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Passenger installation error with Ruby under Debian squeeze I'm trying to install passenger: gem1.8 install passenger But i'm getting the error: Building native extensions. This could take a while... ERROR: Error installing passenger: ERROR: Failed to build gem native extension. /usr/bin/ruby1.8 extconf.rb extconf.rb:8:in `require': no such file to load -- mkmf (LoadError) from extconf.rb:8 Gem files will remain installed in /usr/lib/ruby/gems/1.8/gems/fastthread-1.0.7 for inspection. Results logged to /usr/lib/ruby/gems/1.8/gems/fastthread-1.0.7/ext/fastthread/gem_make.out So Now i've been told to install ruby1.8-dev but i have a dependency: Reading package lists... Done Building dependency tree Reading state information... Done Some packages could not be installed. This may mean that you have requested an impossible situation or if you are using the unstable distribution that some required packages have not yet been created or been moved out of Incoming. The following information may help to resolve the situation: The following packages have unmet dependencies: ruby1.8-dev : Depends: libc6-dev but it is not going to be installed E: Broken packages So i tried to install them both and got: The following packages have unmet dependencies: libc6-dev : Depends: libc6 (= 2.7-18lenny7) but 2.11.2-10 is to be installed So finally i tried to install issuing the command: apt-get install ruby1.8-dev libc6-dev libc6 But i get the same error. I also tried with "apt-get -f" What do i need to do? A: I think you might be missing this: sudo apt-get install build-essential
{ "language": "en", "url": "https://stackoverflow.com/questions/7618632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Routes in Codeigniter - Automatically I have a problem with Codeigniter routes. I would like to all registered users on my site gets its own "directory", for example: www.example.com/username1, www.example.com/username2. This "directory" should map to the controller "polica", method "ogled", parameter "username1". If I do like this, then each controller is mapped to this route: "polica/ogled/parameter". It's not OK: $route["(:any)"] = "polica/ogled/$1"; This works, but I have always manually entered info in routes.php: $route["username1"] = "polica/ogled/username1"; How do I do so that this will be automated? UPDATE: For example, I have controller with name ads. For example, if you go to www.example.com/ads/ there will be listed ads. If you are go to www.example.com/username1 there are listed ads by user username1. There is also controller user, profile, latest,... My Current routes.php: $route['oglasi'] = 'oglasi'; $route['(:any)'] = "polica/ogled/$1" $route['default_controller'] = 'domov'; $route['404_override'] = ''; I solved problem with this code: $route['oglasi/(:any)'] = 'oglasi/$1'; $route['(:any)'] = "polica/ogled/$1" $route['default_controller'] = 'domov'; $route['404_override'] = ''; Regards, Mario A: The problem with your route is that by using :any you match, actually...ANY route, so you're pretty much stuck there. I think you might have two solutions: 1)You can selectively re-route all your sites controller individually, like: $route['aboutus'] = "aboutus"; $route['where-we-are'] = "whereweare"; //And do this for all your site's controllers //Finally: $route['(:any)'] = "polica/ogled/$1"; All these routes must come BEFORE the ANY, since they are read in the order they are presented, and if you place the :any at the beginning it will happily skip all the rest. EDIT after comment: What I mean is, if you're going to match against ANY segment, this means that you cannot use any controller at all (which is, by default, the first URI segment), since the router will always re-route you using your defined law. In order to allow CI to execute other controllers (whatever they are, I just used some common web pages, but can be literally everything), you need to allow them by excluding them from the re-routing. And you can achieve this by placing them before your ANY rule, so that everytime CI passed through your routing rules it parses first the one you "escaped", and ONLY if they don't match anything it found on the URL, it passes on to the :ANY rule. I know that this is a code verbosity nonetheless, but they'll surely be less than 6K as you said. Since I don't know the actual structure of your URLs and of your web application, it's the only solution that comes to my mind. If you provide further information, such as how are shaped the regular urls of your app, then I can update my answer /end edit This is not much a pratical solution, because it will require a lot of code, but if you want a design like that it's the only way that comes to my mind. Also, consider you can use regexes as the $route index, but I don't think it can work here, as your usernames are unlikely matchable in this fashion, but I just wanted to point out the possibility. OR 2) You can change your design pattern slightly, and assign another route to usernames, something along the line of $route['user/(:any)'] = "polica/ogled/$1"; This will generate quite pretty (and semantic) URLs nonetheless, and will avoid all the hassle of escaping the other routes. A: view this: http://www.web-and-development.com/codeigniter-minimize-url-and-remove-index-php/ which includes remove index.php/remove 1st url segment/remove 2st url sigment/routing automatically.it will very helpful for you. A: I was struggling with this same problem very recently. I created something that worked for me this way: Define a "redirect" controller with a remap method. This will allow you to gather the requests sent to the contoller with any proceeding variable string into one function. So if a request is made to http://yoursite/jeff/ or http://yoursite/jamie it won't hit those methods but instead hit http://yoursite/ remap function. (even if those methods/names don't exist and even if you have an index function, it supersedes it). In the _Remap method you could define a conditional switch which then works with the rest of your code re-directing the user any way you want. You should then define this re-direct controller as the default one and set up your routes like so: $route['(.*)'] = "redirect/index/$1"; $route['default_controller'] = "redirect"; This is at first a bit of a problem because this will basically force everything to be re-directed to this controller no matter what and ultimately through this _remap switch. But what you could do is define the rules/routes that you don't want to abide to this condition above those route statements. i.e $route['myroute'] = "myroute"; $route['(.*)'] = "redirect/index/$1"; $route['default_controller'] = "redirect"; I found that this produces a nice system where I can have as many variable users as are defined where I'm able to redirect them easily based on what they stand for through one controller. A: Another way would be declaring an array with your intenal controllers and redirect everything else to the user controller like this in your routes.php file from codeigniter: $controllers=array('admin', 'user', 'blog', 'api'); if(array_search($this->uri->segment(1), $controllers)){ $route['.*'] = "polica/ogled/$1"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7618633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Best python solution to play ALL kinds of audio on Windows (and Linux)? I'm trying to write some scripts to play some of my music collection with python. Finding python modules that will play ogg and mp3 is not a problem. However, I'm having repeated failures with aac-encoded m4a files from iTunes (not DRM). pygame's audio machinery doesn't support them, so I tried pymedia: a = pymedia.player.Player() a.start() a.startPlayback("myM4a.m4a", format='aac') I've tried several versions of the last line of code, including omitting the format argument, changing the files to mp4, etc. mp3's work fine, however. pymedia even claims to support aac encoded files, but the project appears to have been abandoned anyway. Is there a good, up to date, solution for playing ALL types of audio in python? What is used by existing python media centers/players? I should add that I intend to use this primarily on windows, so windows support for the library is a must, but cross-platform would obviously be preferable. A: You should look at the gStreamer API. It has plugins for many major audio types, is used by many audio players including Banshee and Rhythmbox and it can run on Linux, Windows and Mac. It has Python bindings as well as bindings for many other languages: http://gstreamer.freedesktop.org/bindings/ A: MPlayer plays most known audio formats, and there's Python wrapper for it: http://code.google.com/p/python-mplayer/ And a list of audio codecs supported by MPlayer: http://www.mplayerhq.hu/DOCS/codecs-status.html#ac
{ "language": "en", "url": "https://stackoverflow.com/questions/7618640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What is causing a SIGSEGV on _updateNumSections in UITableView? We get the following every once in a while. We cannot recreate this error. Does anyone know what specifically causes this? It seems like the UITableView is in some odd state. I have ran Instruments to look for over-releasing memory, etc. but am not seeing much. Thread 0 Crashed: libobjc.A.dylib 0x3068f06b _objc_terminate + 103 libstdc++.6.dylib 0x30502e3d __cxxabiv1::__terminate(void (*)()) + 53 libstdc++.6.dylib 0x30502e91 std::terminate() + 17 libstdc++.6.dylib 0x30502f61 __cxa_throw + 85 libobjc.A.dylib 0x3068dc8b objc_exception_throw + 71 CoreFoundation 0x335141bf -[NSObject(NSObject) doesNotRecognizeSelector:] + 103 CoreFoundation 0x33513649 ___forwarding___ + 509 CoreFoundation 0x3348a180 _CF_forwarding_prep_0 + 48 UIKit 0x31bb2ff3 -[UITableViewRowData(UITableViewRowDataPrivate) _updateNumSections] + 67 UIKit 0x31bb2f53 -[UITableViewRowData invalidateAllSections] + 51 UIKit 0x31bb2d09 -[UITableView(_UITableViewPrivate) _updateRowData] + 65 UIKit 0x31bafab7 -[UITableView _rectChangedWithNewSize:oldSize:] + 111 UIKit 0x31bae833 -[UITableView setFrame:] + 159 UIKit 0x31bb5e0f -[UIView(Geometry) resizeWithOldSuperviewSize:] + 275 UIKit 0x31b820bd -[UIView(Geometry) resizeSubviewsWithOldSize:] + 121 UIKit 0x31b674e9 -[UIView(Geometry) setFrame:] + 337 UIKit 0x31bb5e0f -[UIView(Geometry) resizeWithOldSuperviewSize:] + 275 UIKit 0x31b820bd -[UIView(Geometry) resizeSubviewsWithOldSize:] + 121 UIKit 0x31b674e9 -[UIView(Geometry) setFrame:] + 337 UIKit 0x31bae9fd -[UIScrollView setFrame:] + 421 UIKit 0x31bb5e0f -[UIView(Geometry) resizeWithOldSuperviewSize:] + 275 UIKit 0x31b820bd -[UIView(Geometry) resizeSubviewsWithOldSize:] + 121 UIKit 0x31b674e9 -[UIView(Geometry) setFrame:] + 337 UIKit 0x31bb5e0f -[UIView(Geometry) resizeWithOldSuperviewSize:] + 275 UIKit 0x31b820bd -[UIView(Geometry) resizeSubviewsWithOldSize:] + 121 UIKit 0x31b674e9 -[UIView(Geometry) setFrame:] + 337 UIKit 0x31bb9193 -[UIViewControllerWrapperView setFrame:] + 63 UIKit 0x31bb5e0f -[UIView(Geometry) resizeWithOldSuperviewSize:] + 275 UIKit 0x31b820bd -[UIView(Geometry) resizeSubviewsWithOldSize:] + 121 UIKit 0x31b674e9 -[UIView(Geometry) setFrame:] + 337 UIKit 0x31bb5e0f -[UIView(Geometry) resizeWithOldSuperviewSize:] + 275 UIKit 0x31b820bd -[UIView(Geometry) resizeSubviewsWithOldSize:] + 121 UIKit 0x31b674e9 -[UIView(Geometry) setFrame:] + 337 UIKit 0x31b9922f -[UILayoutContainerView setFrame:] + 55 UIKit 0x31bb90a9 +[UIViewControllerWrapperView wrapperViewForView:frame:] + 225 UIKit 0x31bd6201 -[UITabBarController transitionFromViewController:toViewController:transition:shouldSetSelected:] + 105 UIKit 0x31bd618d -[UITabBarController transitionFromViewController:toViewController:] + 33 UIKit 0x31bd5a33 -[UITabBarController _setSelectedViewController:] + 187 UIKit 0x31c5aceb -[UITabBarController setSelectedViewController:] + 15 UIKit 0x31c5abe7 -[UITabBarController _tabBarItemClicked:] + 227 CoreFoundation 0x33480571 -[NSObject(NSObject) performSelector:withObject:withObject:] + 25 UIKit 0x31b7eec9 -[UIApplication sendAction:to:from:forEvent:] + 85 UIKit 0x31b7ee69 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 33 UIKit 0x31c5aa8b -[UITabBar _sendAction:withEvent:] + 271 CoreFoundation 0x33480571 -[NSObject(NSObject) performSelector:withObject:withObject:] + 25 UIKit 0x31b7eec9 -[UIApplication sendAction:to:from:forEvent:] + 85 UIKit 0x31b7ee69 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 33 UIKit 0x31b7ee3b -[UIControl sendAction:to:forEvent:] + 39 UIKit 0x31b7eb8d -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 357 UIKit 0x31bb8bd9 -[UIControl sendActionsForControlEvents:] + 17 UIKit 0x31c5a815 -[UITabBar(Static) _buttonUp:] + 81 CoreFoundation 0x33480571 -[NSObject(NSObject) performSelector:withObject:withObject:] + 25 UIKit 0x31b7eec9 -[UIApplication sendAction:to:from:forEvent:] + 85 UIKit 0x31b7ee69 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 33 UIKit 0x31b7ee3b -[UIControl sendAction:to:forEvent:] + 39 UIKit 0x31b7eb8d -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 357 UIKit 0x31b7f423 -[UIControl touchesEnded:withEvent:] + 343 UIKit 0x31b7dbf5 -[UIWindow _sendTouchesForEvent:] + 369 UIKit 0x31b7d56f -[UIWindow sendEvent:] + 263 UIKit 0x31b66313 -[UIApplication sendEvent:] + 299 UIKit 0x31b65c53 _UIApplicationHandleEvent + 5091 GraphicsServices 0x311a5e77 PurpleEventCallback + 667 CoreFoundation 0x334e7a97 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 27 CoreFoundation 0x334e983f __CFRunLoopDoSource1 + 167 CoreFoundation 0x334ea60d __CFRunLoopRun + 521 CoreFoundation 0x3347aec3 CFRunLoopRunSpecific + 231 CoreFoundation 0x3347adcb CFRunLoopRunInMode + 59 GraphicsServices 0x311a541f GSEventRunModal + 115 GraphicsServices 0x311a54cb GSEventRun + 63 UIKit 0x31b90d69 -[UIApplication _run] + 405 UIKit 0x31b8e807 UIApplicationMain + 671 MyApp 0x0009a188 main (main.m:5) A: Start by looking in your console log. There will be a message indicating which class has been sent updateNumSections. Make sure you aren't making calls to this table view on a background thread. That can cause these kinds of crazy crashes. Make sure your table view datasource isn't deallocating before the table view. A suspicion here would be an over-release (as you suggest), so run Static Analysis just to find the bone-headed stuff. Also make sure you're using accessors rather than using ivars directly (the #1 cause of over-releases). A: I had the same issue and like you suggested in your comment on Rob Napier's answer, it should be implemented in the tabBarController instead of on viewDidDisappear. Running Zombies in instruments will show you that a call to updateNumSections gets made to a deallocated object. For anyone looking up this issue, here is the code you should use in your tabViewController, given a navigationViewController that gets called within a tab that is no longer shown. - (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController { //Always go to the root controller when accessing a tab. //If any navigation controller that must remember its last state, change this for viewController == or != if ([viewController isKindOfClass:[UINavigationController class]]) { [(UINavigationController*)viewController popToRootViewControllerAnimated:YES]; //Do not use code on disappear, instead popToRoot on tab selection } } A: I am pretty sure I don't update table view on background thread. Thanks @Pierre-Francoys, I add a Zombies Option and it tell me the selector numberOfSectionsInTableView: sent to deallocated object. So I clear the dataSource and delegate of tableView in my viewController. And it works very well. - (void)dealloc { _tableView.dataSource = nil; _tableView.delegate = nil; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7618646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is my Image too far left-aligned in Firefox vs Chrome I have this code, which is behaving differently in firefox vs chrome. <h2>Presenting <span style="font-weight:bold">Analytics by </span> <div class="fi_logo"><img src="IMAGEURL" /></div> </h2> the class fi_logo referenced above is : .fi_logo { min-width: 35px; height: 35px; margin-left: 40px; position: absolute; top:-5px; left: 262px; float:right; } In firefox, there is an offset caused by margin-left in fi_logo between the image and the text(in h2). If i dont add the margin-left, then the image overlaps the text in chrome. So, in short, if i add the margin-left property, it works in chrome, whereas it causes a large offset in firefox. Any suggestions on how to solve this? A: Maybe if you set .fi_logo display:block A: Your image tag inside the div is not closed properly, and in the css the class definition is wrong; the class is defined by a dot (.); A: I think, your problem is with specific browser version. I checked it in FF 3.6.2, which return same result like Chrome A: Well it sounds like you still haven't sorted this out so I will make a little more commentary. I cannot say exactly what is causing the browser inconsistencies without doing a bunch of trial and error, but I think that the way to fix it is to rethink the way you are positioning the image. It seems awful convoluted to be positioning the img absolutely, floating it, and adding a left margin. Given all of that it is unclear what precisely you are even trying to accomplish with this code. If you edit your question to describe how you want the image positioned, I (or someone else) would be more than happy to recommend a good approach A: Here it is: http://jsfiddle.net/bikerabhinav/mpL79/2/ Use combination of position relative and absolute. Also, do not use div inside h2 - bad markup A: Your html is invalid. You cannot have a div inside a heading. I also question the float and absolute positioning on the same element. I also wonder if you are using a doctype.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Moq for c# training not working on first test in suite I'm new to c# as well and the Moq framework. I'm using VS 2010 express and NUnit In my [Setup] function, I have: this.mockAllianceController = new Mock<AllianceController>(); this.mockAllianceController.Setup(ac => ac.getAllies(this.currentRealm)).Returns(new List<string>()); ... this.testObj = new DiplomacyLogic(this.mockAllianceController.Object); The first test in the suite gets a null returned, while each test after that gets the empty list. What am I missing? Update: Code under test: public void ApplyRelations() { List<string> allies = this.AllianceController.getAllies(this.RealmName); foreach (string ally in allies) { ... } } public virtual List<string> getAllies(string realm) { ... } Two test cases: [Test] public void aTest() { this.testObj.ApplyRelations(); } [Test] public void bTest() { this.testObj.ApplyRelations(); } aTest will throw a NullReferenceException while bTest passes fine. Any help? A: It would be helpful if you also show the declaration of getAllies and what this.currentRealm is. But you probably want to change the line: this.mockAllianceController.Setup(ac => ac.getAllies(this.currentRealm)).Returns(new List<string>()); into this: this.mockAllianceController.Setup(ac => ac.getAllies(It.IsAny<string>())).Returns(new List<string>()); Note the It.IsAny<string>() as parameter for getAllies(). A: If AllianceController is a class and not an interface, you may want to do: this.mockAllianceController = new Mock<AllianceController>(); this.mockAllianceController.CallBase = True this means that you create a Mock object that will wrap an existing object and map all method calls to the original object by default (unless an explicit Setup has been called) (see http://code.google.com/p/moq/wiki/QuickStart#Customizing_Mock_Behavior) A: I think your setups is done in the wrong order and this causes the setup not to be valid in the first testrun and then in the second testrun the this.testObj = new DiplomacyLogic(this.mockAllianceController.Object); is already created and the setup is initilazed. This means you should initialize the DiplomacyLogic before the setup to get your desired result. I also included a teardown code so you get fresh objects for each test, this is good practice so that tests are not dependent on eachother. try the code below. [Setup] public void Setup() { this.mockAllianceController = new Mock<AllianceController>(); this.testObj = new DiplomacyLogic(this.mockAllianceController.Object); this.mockAllianceController.Setup(ac => ac.getAllies(this.currentRealm)).Returns(new List<string>()); } [TearDown] public void TearDown() { this.mockAllianceController = null; this.testObj = null; } I also think that the setup code should be in the testmethod insteed of setup and that is becasuse of other tests you might write will maby not use the same setup for just that method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618656", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to check whether NFC is enabled or not in android? How can i check whether NFC is enabled or not programmatically? Is there any way to enable the NFC on the device from my program? Please help me A: I might be a little late here, but I've implemented a 'complete' example with detection of * *NFC capability (hardware), and *Initial NFC state (enabled or disabled in settings), and *Changes to the state I've also added a corresponding Beam example which uses the nfcAdapter.isNdefPushEnabled() method introduced in later Android versions to detect beam state like in 2) and 3). A: Use PackageManager and hasSystemFeature("android.hardware.nfc"), matching the <uses-feature android:name="android.hardware.nfc" android:required="false" /> element you should have in your manifest. Since 2.3.3 you can also use NfcAdapter.getDefaultAdapter() to get the adapter (if available) and call its isEnabled() method to check whether NFC is currently turned on. A: NfcManager manager = (NfcManager) context.getSystemService(Context.NFC_SERVICE); NfcAdapter adapter = manager.getDefaultAdapter(); if (adapter != null && adapter.isEnabled()) { // adapter exists and is enabled. } You cannot enable the NFC programmatically. The user has to do it manually through settings or hardware button. A: This can be done simply using the following code: NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this); if (nfcAdapter == null) { // NFC is not available for device } else if (!nfcAdapter.isEnabled()) { // NFC is available for device but not enabled } else { // NFC is enabled } Remember that the user can turn off NFC, even while using your app. Source: https://developer.android.com/guide/topics/connectivity/nfc/nfc#manifest Although you can't programically enable NFC yourself, you can ask the user to enable it by having a button to open NFC settings like so: Intent intent if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { intent = new Intent(Settings.ACTION_NFC_SETTINGS); } else { Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS); } startActivity(intent); A: mNfcAdapter = NfcAdapter.getDefaultAdapter(this.getApplicationContext()); try { if (mNfcAdapter != null) { result = true; } } We can verify using NfcAdapter with context.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "36" }
Q: create edit text only accept or able to enter only alphabetical character from a-z only android i want to make a edit text in which can only be able to enter only alphabatical character means from a-z no other numeric or special charaacter are not allowed so how to do it? i had tried <EditText **android:inputType="text"** android:id="@+id/state" android:singleLine="true" android:layout_marginTop="50dip" android:layout_marginLeft="100dip" android:layout_height="40dip" android:layout_width="200dip" /> but it accept all the values means numeric and special character also.so how to restrict it means user can only enter a-z values. A: Type in your xml respective EditText.... android:digits="abcdefghijklmnopqrstuvwxyz" EditText will not accept digits or special character but alphabets only.. A: i did it using @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { for (int i = start; i < end; i++) { if (!Character.isLetter(source.charAt(i))) { return ""; } } return null; } }; EditText etcity= ((EditText) findViewById(R.id.city)); etcity.setFilters(new InputFilter[]{filter}); A: see the InputType in android this is the reference Input Type API A: If you want EditTest to have only characters with white spaces use this: android:digits="abcdefghijklmnopqrstuvwxyz " Note that white space at the end of abcd... string.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Regex with +(plus) and space pattern I have following sentence "my hooorrrr sssee strongggg" my regex is : "(h+o+r+s+e+) s+t+r+o+n+g+" it's only valid/match when the sentence is : "my hooorrrrsssee strongggg" any body can help ? i want to match no matter the space between word. example : "my h ooo rrr rss se eee stttro ngggg" and the other problem is when the some character replaced by number, like bellow : "my h 0o0 rrr rs555sss se ee333 stttr0 ngggg" a replaced by 4 b replaced by 8 s replaced by 5 i replaced by 1 o replaced by 0 any body can help ? Thanks A: Use * (space, asterisk) to allow optional spaces. (h[h ]*o[o ]*r[r ]*s[s ]*e[e ]*)s[s ]*t[t ]*r[r ]*o[o ]*n[n ]*g[g ]* You may also want to consider matching any whitespace with \s (which includes tab, for example) instead of just space. To allow numbers or letters use a character class such as [0o]. (h[h ]*[o0][o0 ]*r[r ]*[s5][s5 ]*[e3][e3 ]*)[s5][s5 ]*t[t ]*r[r ]*[o0][o0 ]*n[n ]*g[g ]* A: If you want to match whitespace then you need to include that in the regex. \s is the pattern that matches whitespace characters (that's space, tab, newline characters). r+ will match one or more r characters but will NOT look for whitespace. r+\s* with match one or more r characters followed by zero or more whitespace characters. You can build the rest of your expression from there. A: UPDATED 2: Based on the info in your question, you can use (updated to catch the cases that Tim Pietzcker pointed out!): [h][h ]*[o0][o 0]*[r][r ]*[s][s 5]*[e3][e 3]*[s5][s 5]*[t][t ]*[r][r ]*[o0][o 0]*[n][n ]*[g][g ]* I just realized that this makes the answer the same as Mark Byers, though! A: This matches each letter, followed by zero or more of the same letter or space h[h ]*o[o ]*r[r ]*s[s ]*e[e ]*s[s ]*t[t ]*r[r ]*o[o ]*n[n ]*g[g ]* With numbers as you specified... (e = 3, o = 0, s = 5) h[h ]*[o0][o 0]*r[r ]*[s5][s 5]*e[e 3]*[s5][s 5]*t[t ]*r[r ]*[o0][o 0]*n[n ]*g[g ]*
{ "language": "en", "url": "https://stackoverflow.com/questions/7618661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: aptana crashes on Mac OSX Lion Does anyone can tell me why aptana 3.0.4 crashes on Mac OSX Lion? Is this only my issue? I can't work with it at all. It freezes when I try to modify or open a file. A: 3.0.5 seems to be working for me, but the "Problems" view never reports any warnings or errors. I suspect it has something to do with Java on Lion since it has to be installed separate. http://support.apple.com/kb/dl1421
{ "language": "en", "url": "https://stackoverflow.com/questions/7618666", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Finishing an AsyncTask when requested I am creating a game where the user interacts with the GUI while the computer finds solutions to the puzzle in a background task. The user can choose to end the game any time, at which point I want to stop my background task and retrieve the solutions it found. This is all working fine except that I can't force the background task to end when the user chooses?!? When the user selects "Done" I have the following: computerSolutionTask.cancel(true); // ...disable some GUI buttons etc... while (computerSolutionTask.getStatus() != AsyncTask.Status.FINISHED){ // ...do nothing... } txt_computer.setText(computerSolutionTask.get()); And in my AsyncTask class I am checking "isCancelled()" regularly but it just seems to hang in the while loop I included above. I feel that I may be going about this whole thing a little incorrectly because I don't really want to cancel the background task I just want it to finish wherever it's up to and return what it has. This thread appears to be asking the same question I am but has no solution...I'm drawing blanks with all my research thus far and any help would be much appreciated. A: A running AsyncTask that is cancelled will never reach onPostExecute and so it will never 'finish'. You don't need to wait for it anyway, if your particular logic requires it use regular synchronization methods. A: You need to put the condition inside the doInBackground() method to check whether the AsyncTask is cancelled or in running state. protected Object doInBackground(Object... x) { while (/* condition */) { // work... if (isCancelled()) break; } return null; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7618668", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Handlebars inside of Markdown, inside of HAML I know that this is a very non-standard use case, but I'm chaining HAML, Markdown, and Handlebars (in SproutCore 2.0), and I'm 1 step away from 'beautiful' code. Intermingling HAML, Markdown, and Javascript is less ideal than it could be. If I wanted to add a post-filter to the entire output of HAML, replacing {{text}} with <script>{{text}}</script>, what would be the best way to do it? I could just hack on a post-build step after haml, but I'd like to turn it into something that I can give back to the SproutCore community. I want to replace %body javascript: {{handlebars}} With %body {{handlebars}} Which would give me <body> <script>{{handlebars}}</script> </body> However, I also want this to work when embedded within markdown. For example, %body markdown: # Hello, {{handlebars}} Currently, the only way to get this is %body markdown: # Hello, <script>{{handlebars}}</script> Which would product <body> <h1>Hello, <script>{{handlebars}}</script></h1> </body> A: Revisiting the same issue much, much later, it appears that there's not a good solution for this with HAML. However, Jade does just about everything that I want. http://jade-lang.com/ Input html script(type='text/x-handlebars') :markdown *Hello, {{handlebars}}!* Output <html> <script type="text/x-handlebars"><p><em>Hello, {{handlebars}}!</em></p> </script> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7618670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: php send email via gmail (php.ini) with php internal mail function (win7) Is there anyway to send email via gmail (or other free provider) in php. But I want to use php built in mail() function. This solution is only for dev and staging. Thanks A: You can, using PHPMailer. And also check here to know details you should provide in your script so that you be able to send using Gmail SMTP. Source Plenty of walk-throughs and pre-made scripts/classes if you just used google. Unless you want to make yours from scratch. A: If you don't want to use libraries but still want to send email via gmail, you have to setup SMTP server which sends email via Gmail. One very easy alternative is SSMTP. Setting up SSMTP is very easy. http://tombuntu.com/index.php/2008/10/21/sending-email-from-your-system-with-ssmtp/ Hope it helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to decrypt a PHP script in Objective C / iOS I've checked all the related Stack Overflow questions. Also checked the links in that answers but didn't got any usable solution. Here is my php script and I've nothing to do with this script (as I can't change the script). function encrypt($message,$secretKey) { return base64_encode( mcrypt_encrypt( MCRYPT_RIJNDAEL_256, $secretKey, $message, MCRYPT_MODE_ECB ) ); } I'm unable to decrypt it in Objective C. I've used a number of Categories like Strong Encryption for Cocoa / Cocoa Touch etc, also I followed this question How do I do base64 encoding on iOS? Here is the objective C codes that I used for decryption (found in cocoa-aes Category NSData+AES.h) - (NSData *)AESDecryptWithPassphrase:(NSString *)pass { NSMutableData *ret = [NSMutableData dataWithCapacity:[self length]]; unsigned long rk[RKLENGTH(KEYBITS)]; unsigned char key[KEYLENGTH(KEYBITS)]; const char *password = [pass UTF8String]; for (int i = 0; i < sizeof(key); i++) key[i] = password != 0 ? *password++ : 0; int nrounds = rijndaelSetupDecrypt(rk, key, KEYBITS); unsigned char *srcBytes = (unsigned char *)[self bytes]; int index = 0; while (index < [self length]) { unsigned char plaintext[16]; unsigned char ciphertext[16]; int j; for (j = 0; j < sizeof(ciphertext); j++) { if (index >= [self length]) break; ciphertext[j] = srcBytes[index++]; } rijndaelDecrypt(rk, nrounds, ciphertext, plaintext); [ret appendBytes:plaintext length:sizeof(plaintext)]; NSString* s = [[NSString alloc] initWithBytes:plaintext length:sizeof(plaintext) encoding:NSASCIIStringEncoding]; NSLog(@"%@",s); } return ret; } Also I tried this decoder - (NSData*) aesDecryptWithKey:(NSString *)key initialVector:(NSString*)iv { int keyLength = [key length]; if(keyLength != kCCKeySizeAES128) { DebugLog(@"key length is not 128/192/256-bits long"); ///return nil; } char keyBytes[keyLength+1]; bzero(keyBytes, sizeof(keyBytes)); [key getCString:keyBytes maxLength:sizeof(keyBytes) encoding:NSUTF8StringEncoding]; size_t numBytesDecrypted = 0; size_t decryptedLength = [self length] + kCCBlockSizeAES128; char* decryptedBytes = malloc(decryptedLength); CCCryptorStatus result = CCCrypt(kCCDecrypt, kCCAlgorithmAES128 , (iv == nil ? kCCOptionECBMode | kCCOptionPKCS7Padding : kCCOptionPKCS7Padding), keyBytes, keyLength, iv, [self bytes], [self length], decryptedBytes, decryptedLength, &numBytesDecrypted); if(result == kCCSuccess){ NSData* d=[NSData dataWithBytesNoCopy:decryptedBytes length:numBytesDecrypted]; NSLog(@"%@",[NSString stringWithUTF8String:[d bytes]]); return d; } free(decryptedBytes); return nil; } A: From the looks of it, that php function does two things. * *mcrypt using MCRYPT_RIJNDAEL_256 *base64 encodes the output of (1) That would by why simply using base64 doesn't work. I'm going to guess from the name that MCRYPT_RIJNDAEL_256 is just AES 256. Hope that helps. Edit: The code you added above looks ok. You just have to base64 decode the data first. The php script does this: * *aes encrypt *base64 encode So you want to do this in your cocoa app: * *base64 decode *aes decrypt If you're having trouble, you might want to play around and see if you can get cocoa to do the same thing as the php script: encrypt and base64 encode the data. If you can get the output of your encryption function to be the same as the output of the php encryption function, you're in a good place to get it decrypting.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618693", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Shiny GUI in Java Is there any library I can use to create shiny user interfaces in Java? e.g. The Intel Graphics & Media Control Panel is written in .Net. Intel Graphics & Media Control Panel I want to know how to create such UI in Java. A: Well you can use and customize your UI with Swing. Nowdays there is also JavaFx 2.0. Also there are a lot of extensions like those from SwingLabs,JGoodies,Jide,Glazed List and the amazing Substance look& feel ,Steel Series etc. Just google for this terms you get a lot of useful links. http://download.oracle.com/javafx/ http://www.jgoodies.com/ http://swingx.java.net/ http://java.net/projects/substance/ http://harmoniccode.blogspot.com/ Be aware is not easy and out of the box functionality but you can do anything. A: By default, Swing user interfaces use a look and feel called 'Metal'. You could try making your own look and feel to accomplish something similar.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SQL injection even when the variable is escaped The sql injection will work only when my query looks like below sample SELECT * FROM login WHERE id = $my_id_va; Assume if my query is SELECT * FROM login WHERE id = $my_id_va ORDER BY id DESC Than I will get following error #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order by id desc' at line 1 So, this 1 or 1=1; SHOW TABLES will not work, correct? My site was hacked successively many times. I want one quick answer: When my query looks like the following one, what ways or which types of query can they use to hack my site? SELECT * FROM login WHERE id = $my_id_va ORDER BY id DESC What are the ways to execute the show table in the following query SELECT * FROM login WHERE id = $my_id_va ORDER BY id DESC I am also using escaping function to handle the query string values, like mysql_real_escape_string($my_id_va). Yes, obviously this for single related hack, but not sure. Added some more SELECT EventActuallyCharged, EventDate FROM tblevent WHERE EventDate between '2011-07-21 or 1=1; SHOW TABLES --' and '2011-07-31' ORDER BY EventDate DESC but show table not worked A: If you are using PHP5, use parametarized query, use PDO. A: Int cast If id is a number, you can int-cast your variable as well. Integers are safe to use: $x = (int)$yourInputVar; $s = "select * from Table where id = $x"; mysql_real_escape_string If you want to pass a string, you can, and should, use mysql_real_escape_string, but this function escapes only those characters that are inside the string. You will still need to add quotes around the string, so: $x = mysql_real_escape_string('hello'); $s = "select * from Table where id = $x"; .. will result in the query: select * from Table where id = hello. This is obiously not a valid query, since hello should be in quotes. Change the query to: $x = mysql_real_escape_string('hello'); $s = "select * from Table where id = '$x'"; .. and everything works fine. You add the quotes around, and mysql_real_escape_string takes care of special characters inside the string, if any. Parameters Another solution is to use parameterized queries. This can by done using MySQLi or PDO. The advantage is that you only tell your database where a variable should be inserted, and the database takes care of the escaping yourself. It also may add a performance benefit, because these queries could be cached without their parameters, make a more efficient use of the query cache. This doesn't really work yet in current versions of MySQL, though. A: You are right that 1 or 1=1; SHOW TABLES will give a syntax error but this will work: 1 or 1=1 -- The -- comments out the rest of the query. In your case the value is an integer so instead of using mysql_real_escape_string you can use intval. A: If you set $my_id_va to: 1 or 1=1; SHOW TABLES -- The -- will comment out the rest of the command, effectively terminating it. I'm not sure what effect mysql_real_escape_string will have on the query. What you should be doing is parameterized queries. A: 1. First query somehow secured $sql = sprintf('SELECT * FROM login WHERE id = %d ORDER BY id DESC', mysql_real_escape_string($my_id_va)); 2. Second query somehow secured $sql = sprintf("SELECT EventActuallyCharged, EventDate FROM tblevent WHERE EventDate BETWEEN '%s' AND '%s' ORDER BY EventDate DESC", mysql_real_escape_string($start_date), mysql_real_escape_string($end_date)); Read the docs about sprintf if you don't understand it. However, as others have said, it would be very very secure if you would use parameterized queries with a class such as PDO or MySQLi.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618701", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Third Party Live chat module for .NET (same as like Facebook) I need to integrate private chat module in Asp.NET site.So, internal user can chat with other users. I would be appreciate, if anyone can suggest that type of modules Thanks in Advance. A: See here about rolling your own it shouldnt be too hard with the building blocks given ASP.NET Chat with WCF You can check out http://wcfchat.codeplex.com/ for a WCF implementation of chat.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Activity lifecycle - onCreate called on every re-orientation I have a simple activity that loads a bitmap in onCreate. I find that if I rotate the device I can see from the logs that onCreate called again. In fact, because all instance variables are set to default values again I know that the entire Activity has been re-instantiated. After rotating 2 times I get an FC because not enough memory can be allocated for the bitmap. (Are all instances of the activty still alive somewhere? Or does the GC not clean up fast enough?) @Override public void onCreate(Bundle savedInstanceState) { File externalStorageDir = Environment.getExternalStorageDirectory(); File picturesDir = new File(externalStorageDir, "DCIM/Camera"); File[] files = picturesDir.listFiles(new FilenameFilter(){ public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".jpg"); }}); if (files.length > 0) { Bitmap bm = BitmapFactory.decodeStream(new FileInputStream(files[0])); ImageView view = (ImageView) findViewById(R.id.photo); view.setImageBitmap(bm); } } From all that I read, onCreate should be called once during the lifetime of an application. Am I wrong about this? How can re-orienting the device cause the activity to be recreated? A: android:configChanges="keyboardHidden|orientation|screenSize" Caution: Beginning with Android 3.2 (API level 13), the "screen size" also changes when the device switches between portrait and landscape orientation. Thus, if you want to prevent runtime restarts due to orientation change when developing for API level 13 or higher (as declared by the minSdkVersion and targetSdkVersion attributes), you must include the "screenSize" value in addition to the "orientation" value. That is, you must decalare android:configChanges="orientation|screenSize". However, if your application targets API level 12 or lower, then your activity always handles this configuration change itself (this configuration change does not restart your activity, even when running on an Android 3.2 or higher device). From docs: http://developer.android.com/guide/topics/resources/runtime-changes.html A: Manifest XML activity Tag: android:configChanges="keyboardHidden|orientation"‍‍‍ @Override public void onConfigurationChanged(Configuration newConfig) { // TODO Auto-generated method stub super.onConfigurationChanged(newConfig); } Use the above code to perform changes related to orientation in your Activity Java Code Cheers!!! A: One of the most common and suggested “solutions” to dealing with orientation changes is to not deal with them. You can do this by setting the android:configChanges flag on your Activity in AndroidManifest.xml as shown below: <activity android:name=".MyActivity" android:label="@string/title_my_activity" android:configChanges="orientation|screenSize|keyboardHidden" /> This is NOT the correct way to deal with orientation changes. CORRECT way is to implement the onSaveInstanceState method (this could be in your Activity, Fragment or both) and place the values you need to save in the Bundle argument that gets passed to the method. It is nicely described here: http://code.hootsuite.com/orientation-changes-on-android/ While it may seem a bit tedious to implement, handling orientation changes properly provides you with several benefits: you will be able to easily use alternate layouts in portrait and landscape orientations, and you will be able to handle many exceptional states such as low memory situations and interruptions from incoming phone calls without any extra code. A: What happen when orientation changed Life Cycle of orientation onPause(); onSaveInstanceState(); onStop(); onDestroy(); onCreate(); onStart(); onResume(); ---- app recreated and now is running --- If you do long operation in onCreate() and want prevent re-create your activity add configChanges attribute in your mainfest <activity android:name=".MyActivity" android:configChanges="orientation|keyboardHidden|screenSize" android:label="@string/app_name"> screenSize if you targeting api >= 13 A: Activity is recreated after each rotation by default. You can override this behaviour with configChanges attribute of the activity tag in AndroidManifest. For further details and different options, see http://developer.android.com/guide/topics/resources/runtime-changes.html A: While the Manifest way may work, there is a better and proper solution for these types of problems. The ViewModel class. You should have a look here: https://developer.android.com/topic/libraries/architecture/viewmodel Basically, you extend the ViewModel class and define all the data members in it which we want to be unchanged over re creation of the activity (in this case orientation change). And provide relevant methods to access those from the Activity class. So when the Activity is re created, the ViewModel object is still there, and so are our data! A: Actvity Lifecycle when you rotate screen onPause onSaveInstanceState onStop onDestroy onCreate onStart onRestoreInstanceState onResume A: Kindly see my way of doing it:- http://animeshrivastava.blogspot.in/2017/08/activity-lifecycle-oncreate-beating_3.html snippet is:- @Override protected void onSaveInstanceState(Bundle b) { super.onSaveInstanceState(b); String str="Screen Change="+String.valueOf(screenChange)+"...."; Toast.makeText(ctx,str+"You are changing orientation...",Toast.LENGTH_SHORT).show(); screenChange=true; } @Override public void onCreate(Bundle b) { super.onCreate(b); ctx=getApplicationContext(); if(!screenChange) { String str="Screen Change="+String.valueOf(screenChange); // ... } } A: If you want to prevent FC from not enough memory, you need to deallocate resources in onStop() or onPause(). this allows you to use fresh memory in onCreate(). This is an alternate solution to preventing the recreation of the activity by using android:configChanges="keyboardHidden|orientation" As sometimes your activity's layout is different in portrait and landscape (layout, layout-land). preventing recreate on orientation change will prevent your activity from using the other orientation's layout. A: Yes, activity's onCreate() is called everytime when the orientation changes but you can avoid the re-creation of Activity by adding configChanges attribute of Activity in your AndroidManifest file in the activity tag. android:configChanges="keyboardHidden|orientation" A: On Create method will call everytime when you do orientation, to avoid this you have to use //Define Below in you Manifest file. <activity android:name="com.ecordia.activities.evidence.MediaAttachmentView" android:configChanges="keyboardHidden|orientation|screenSize" </activity> //Define Below in your activity. @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { //your code } else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { //your code } } It will works like a charm!! A: I had the same problem and I did some workaround Define didLoad boolean variable with false value private boolean didLoad = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity); if (!this.didLoad){ // Your code... this.didLoad = true; } A: I had the same problem, in which my onCreate is called multiple times when the screen orientation is changed. My problem got solved when i add android:configChanges="orientation|keyboardHidden|screenSize" in the activity tag in manifest
{ "language": "en", "url": "https://stackoverflow.com/questions/7618703", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "74" }
Q: Extract a .tgz into specific subfolder only if there are files in the tar that would extract to my CWD Most tar files extract into their own subfolder (because the people that write open source utilities are amazing people). Some extract into my cwd, which clutters everything up. I know there's a way to see what's in the tar, but I want to write a bash script that essentially guarantees I won't end up with 15 files extracted into my home folder. Any pointers? pseudo code: if [listing of tar files] has any file that doesn't have a '/' in it: mkdir [tar filename without extension] tar xzvf [tar filename] into [the new folder] else: tar xzvf [tar filename] into cwd EDIT: Both solutions are great, I chose the below solution because I was asking for a bash script, and it doesn't rely on extra software. However, on my own machine, I am using aunpack because it can handle many, many more formats. I am using it with a shell script that downloads and unpacks all at once. Here is what I am using: #!/bin/bash wget -o temp.log --content-disposition $1 old=IFS IFS=' ' r=`cat temp.log` rm temp.log for line in $r; do substring=$(expr "$line" : 'Saving to: `\(.*\)'\') if [ "$substring" != "" ] then aunpack $substring rm $substring IFS=$old exit fi done IFS=$old A: The aunpack command from the atool package does that: aunpack extracts files from an archive. Often one wants to extract all files in an archive to a single subdirectory. However, some archives contain multiple files in their root directories. The aunpack program overcomes this problem by first extracting files to a unique (temporary) directory, and then moving its contents back if possible. This also prevents local files from being overwritten by mistake. A: You can use combination of tar options to achieve this: tar option for listing is: -t, --list list the contents of an archive tar option to extract into different directory is: -C, --directory DIR change to directory DIR So in your script you can list the files & check if there are any files in the listing which do not have "/" and based on that output you can call tar with appropriate options. Sample for your reference is as follows: TAR_FILE=<some_tar_file_to_be_extracted> # List the files in the .tgz file using tar -tf # Look for all the entries w/o "/" in their names using grep -v # Count the number of such entries using wc -l, if the count is > 0, create directory if [ `tar -tf ${TAR_FILE} |grep -v "/"|wc -l` -gt 0 ];then echo "Found file(s) which is(are) not in any directory" # Directory name will be the tar file name excluding everything after last "." # Thus "test.a.sh.tgz" will give a directory name "test.a.sh" DIR_NAME=${TAR_FILE%.*} echo "Extracting in ${DIR_NAME}" # Test if the directory exists, if not then create it [ -d ${DIR_NAME} ] || mkdir ${DIR_NAME} # Extract to the directory instead of cwd tar xzvf ${TAR_FILE} -C ${DIR_NAME} else # Extract to cwd tar xzvf ${TAR_FILE} fi In some cases the tar file may contain different directories. If you find it a little annoying to look for different directories which are extracted by the same tar file then the script can be modified to create a new directory even if the listing contains different directories. The slightly advanced sample is as follows: TAR_FILE=<some_tar_file_to_be_extracted> # List the files in the .tgz file using tar -tf # Look for only directory names using cut, # Current cut option used lists each files as different entry # Count the number unique directories, if the count is > 1, create directory if [ `tar -tf ${TAR_FILE} |cut -d '/' -f 1|uniq|wc -l` -gt 1 ];then echo "Found file(s) which is(are) not in same directory" # Directory name will be the tar file name excluding everything after last "." # Thus "test.a.sh.tgz" will give a directory name "test.a.sh" DIR_NAME=${TAR_FILE%.*} echo "Extracting in ${DIR_NAME}" # Test if the directory exists, if not then create it # If directory exists prompt user to enter directory to extract to # It can be a new or existing directory if [ -d ${DIR_NAME} ];then echo "${DIR_NAME} exists. Enter (new/existing) directory to extract to" read NEW_DIR_NAME # Test if the user entered directory exists, if not then create it [ -d ${NEW_DIR_NAME} ] || mkdir ${NEW_DIR_NAME} else mkdir ${DIR_NAME} fi # Extract to the directory instead of cwd tar xzvf ${TAR_FILE} -C ${DIR_NAME} else # Extract to cwd tar xzvf ${TAR_FILE} fi Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7618711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Facing session issue in MVC application I am using Asp.Net Membership and when user enters correct username and password I sign him in using: FormsAuthentication.SetAuthCookie(String, Boolean) If I create a persistent cookie then I think my membership will still be able to work but my session data will be null. This is really annonying and introducing a whole lot of bugs in my application. How can I handle this? Should I handle global.asax's Application_AuthenticateRequest and check if the userId which I store in session is null and Membership.GetUser() is not null, then I should store ProviderUserKey (Guid) again in Session. Is this a reasonable approach or is there any better way of handling this? A: You must configure your session and authcookie's life-time in your web.config file. See: <forms timeout="5" /> <sessionState timeout="5" /> Forms are used for authentication and when it times out it will logout user. You can 'prevent' timeout by setting SlidingExpiration property to 'true' and it will renew forms ticket on user activity (read request to asp) if needed. This will keep user logged on while he is 'active' on your site. and When session times out you will lose data found in Session object. Your problem may may be of this issue. Your auth-cookie is alive, but the session is timed-out. User is logged-in, but the session-variables are destroyed! Check this configuration in your app. See this Q also A: I think, you need to use session for it instead of cookie. And according to me that should be not preferable to save ProviderUserKey in session or any where. Use global.asax(Application_AuthenticateRequest) for check authentication and based on that id, get ProviderUserKey from DB. Hope my comment is useful for you. A: sessions and authcookies are different. authcookies life-time can be set in forms timeout="5" config-section and sessions life-time should be set in sessionState timeout="5" config-section. It is possible that an auth-cookie is persist yet, but the session expires. Check this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I install PEAR::Mail for TYPO3 without pear or phar? In order to use the TYPO3 extension 'Direct Mail' with an external SMTP server, I need to install PEAR::Mail (http://pear.php.net/package/Mail/download/1.2.0). At least, that is what the text in the Direct Mail configuration tells me: Enable Sending through SMTP [SmtpEnabled] Send all emails not through sendmail but through an external SMTP account (requires PEAR::Mail to be installed on the system) I have neither pear nor phar available. How do I install the package after downloading it manually? A: The correct way You need to do everything the PEAR installer does - but manually. That is, read the package.xml file, note which files need to be extracted to which places (don't forget the baseinstalldir) and then extract the files. After that you need to resolve all dependencies and install the dependent packages in the correct version as noted in the package.xml file. Also do not forget to execute the replacement tasks as noted in the package.xml file. The fast way Extract the tgz, delete package.xml and adjust your include path. Then run fast and NEVER EVER ASK FOR HELP BECAUSE IT DOES NOT WORK.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I detect if the page is at the top? I want to make an event occur when the page scroll is at the top of the page. Also I need an if statement for it. I am a beginner with javascript so any help is appreciated. I am looking for something like this: if (at_the_top_of_the_page) { do_the_event_here } I think this is the right struckture for it. But I don't know what is the right code. I know that it will be in javascript. But I really don't know how... A: Elements have a scrollTop element that can be read or set. Make sure you're reading the correct element's scrollTop, the one that you're scrolling. ex: var div = document.getElementById('scrollable'); if(div.scrollTop==0){ //Top of element } A: Get the position of the scrollbar using this function Getpostion(){ var vscroll = document.body.scrollTop; alert(vscroll); } if vscroll is zero do your job. More details A: document.body.scrollTop === 0; A: You would have to use javascript. Get to learn a little bit of jQuery. A: To do the easy way: Include jquery library in your HTML document. And to check if the user is on top of the page var scrollPosition = $("body, html").scrollTop() if (scrollPosition == 0){ // top of the page }
{ "language": "en", "url": "https://stackoverflow.com/questions/7618721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: detect no disk space iPhone SDK Suppose I need to write many images to iPhone file system. And I need to find I have enough space to write image to disk. Is it possible using iPhone SDK? A: Yes, it is possible. See the following tutorial (found using the powerful "google" search engine) ;) http://iphoneincubator.com/blog/device-information/how-to-obtain-total-and-available-disk-space-on-your-iphone-or-ipod-touch Edit: added response re: writing UIImage to disk, with unknown available disk space: Try-Catch a bad way of doing things. Exceptions in cocoa are only for truly exceptionally circumstances (i.e. crash-worthy). If you write your image using NSData *imageData = [myImage UIImageJPEGRepresentation]; (or UIImagePNGRepresentation) and then NSError *error; BOOL success = [imageData writeToFile:(NSString *)path options:(NSDataWritingOptions)mask error:&error]; Your BOOL failed will tell you if it worked, and error will contain an NSError object with a description of the error (don't test for error != nil though, that'll crash occasionally).
{ "language": "en", "url": "https://stackoverflow.com/questions/7618722", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: jQuery Checkbox tree selected I have a checkbox tree using jQuery. Here's the code for tree_data.json : [{ "id":1, "text":"Administrator", "children":[{ "id":2, "text":"Cpanel", "state":"open", "children":[{ "id":3, "text":"Activator", "state":"closed", "children":[{ "text":"Delete" },{ "text":"Edit" },{ "text":"New" },{ "text":"View" }] }] }] }] and for the view is like this <table border="1" width="500"><tr><td> <ul id="tt" class="easyui-tree" url="data/tree_data.json" checkbox="true"> </ul> </td></tr> <tr><td>Your selected role are : </td></tr> </table> <table><tr><td>Your selected role are <input type="text" /></td></tr></table> the output for my view is like this: []Administrator []Cpanel []Activator []Delete []Edit []New []View I want to ask how to get my checkbox value. Example : if I checked "Delete" and "Edit" then Your selected role are : "Activator_Delete","Activator_Edit" Thanks for helping EDIT: I'm new to use jQuery, so please help me with giving me some example, not link Thanks A: Use the getChecked method of the easyui tree: var nodes = $('#tt').tree('getChecked'); Here's the .tree method list.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618731", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Represent one to many relationship on one report and get the many-table in a row instead of col My user wants a report which rows and columns of many-table repeats in a single row until all rows of many-table are finished. what is the best way to write query for that? i hope could get what i want ______________________________________________________________________________________ |table(1) | table(2) | |---------------|--------------------|--------------------|------|--------------------| |table(1) (row1)|table(2 of 1)(row 1)|table(2 of 1)(row 2)| .... |table(N of 1)(row X)| |---------------|--------------------|--------------------|------|--------------------| |table(1) (row2)|table(2 of 2)(row 1)|table(2 of 2)(row 2)| .... |table(N of 2)(row y)| |---------------|--------------------|--------------------|------|--------------------| |table(1) (row3)|table(2 of 3)(row 1)|table(2 of 3)(row 2)| .... |table(N of 3)(row Z)| |---------------|--------------------|--------------------|------|--------------------| ... ... ... A: These are the tools you need: * *Dynamic SQL *nested queries *rownum function *case when If possible, I would load the data from the database to your front end and change the representation there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Asp.net MVC3 validation I have asp.net MVC3 app where validations are done by adding validation attribute in model. e.g. [Required(ErrorMessage = "Required field")] [Display(Name = "SurveyName")] [DataType(DataType.Text)] public string SurveyName {get;set;} Then I create text box in view @Html.TextBoxFor(model => model.SurveyQuestions[i].SurveyName) and add validation message @Html.ValidationMessageFor(model => model.SurveyQuestions[i].SurveyName) Scenario here is I create 5 textbox with for loop with same model property Surveyname and I want to validate only first textbox and no validations for rest of the textbox. Is this possible? Edit: I used below code for rest of the textboxes but it validation occurs on these fields also. @Html.TextBox("SurveyQuestions[" + i + "].Question", @Model.SurveyQuestions[i].Question) A: So finally I got the solutions, though I think it's not the correct way. But it solved my issue. Steps I did to fix the issue - * *I observed Html for input fields for which there is an validation error. The input field will have additional attributes such as "data-val-required" and "data-val" *Then I added these fields to textbox which needs to be validated. *Then I added Html.Validation() for textbox with validation message. My final code looks like @if (i == 0) { @Html.TextBoxFor(model => model.SurveyQuestions[i].Question, new Dictionary<string, object> { { "data-val-required", "required" }, { "data-val", "true" }, { "title", "Question " + (i + 1) }, {"class","QuestionTextBox"} }) <br /> @Html.ValidationMessage("SurveyQuestions[0].Question", "At least one question is required.") } else { @Html.TextBoxFor(model => model.SurveyQuestions[i].Question, new { @class = "QuestionTextBox", @title = "Question " + (i + 1) }) } A: You need to create the first one with the following code as you did : @Html.TextBoxFor(model => model.SurveyQuestions[i].SurveyName) Then, use @Html.TextBox for the rest of it. You just need to hardcode the id and name attributes for your model property.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618736", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: troubling with find and replace function in files I know that it is not a programming question ? But i need a another help relating to find and replace function in php code editor. I am using eclipse and Dreamweaver and i have about 650 php files and would like to replace a string in all files without opening individual files. Could you guys Please help me that, is available any function in eclipse or Dreamweaver so that i can replace the string with specified string to all files ? There is also sub folders hierarchy. Any help or suggestion will be highly appreciated. A: In Eclipse, go to the Search menu, choose File..., enter the string to search and *.php in the file name pattern, then click the Replace... button. You may also click the Search button, and then right-click in the Search view and choose Replace All... or Replace selected... A: Googled it and, voila: http://www.avajava.com/tutorials/lessons/how-do-i-do-a-find-and-replace-in-multiple-files-in-eclipse.html Step by step instructions. A: In Dreamweaver, CTRL+F (or Edit > Find (and replace)) then choose whatever you want from "Find in:" dropdown menu. You have: * *Selected Text *Current Document *Open Documents *Folder... *Selected Files in Site *Entire Current Local Site For eclipse, check this: Search for all files in project containing the text 'querystring' in Eclipse
{ "language": "en", "url": "https://stackoverflow.com/questions/7618744", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: redirecting cycle based on user session I have a problem with redirecting to a page. It seems like it is redirecting itself multiple times. I have if(!isset($_SESSION)){ header("location:index.php"); exit(); } in my header. and my header is included in my index page and everywhere else. I know that since it is in the header, it will be redirected to index.php then it will the script again and over and over which is giving me problems. How would I prevent it to stop doing it right after redirecting? Or is there another way to check if user is logged in, if not, go to index.php? Thanks! A: You should not check for the SESSION array itself to be set in its entirety, for starter. You should just assign one or two indexes and check against them. In this way, you won't ever escape the redirect, since you're not even given the possibility to assign a SESSION.. You need to assign something like $_SESSION['authorized'] = TRUE; upon succesful login, and than, on every page, check if this index is set, is TRUE, and act accordingly. Also, you should redirect to a login page, or something like that...you should give the possibility to actually login to the user! Unless your login form isn't in the index page, of course, but you didn't specify that information... if(isset($_SESSION['authorized']) AND ($_SESSION['authorized'] === TRUE) { //ok, user is logged. Redirect somewhere else? Do something specific? } else { header("Location:index.php"); // or redirect to login.php, for example exit(); } Also, remember to call session_start() as the first thing in all your pages where you want Sessions to be used. A: You have just a logic flaw with your if statement. If the session handling would have been started, $_SESSION would exists. If not, it does not exists. But this is independent to whether you/the user makes use of a session or not. So the if statement is useless. Please read the PHP Manual to learn how sessions work in PHP. A: I figured it out, I knew that I had a if statement in my header, so while i'm trying to redirect to index.php, I still have that if statement and not having a session, i'm going to be redirecting myself in a never ending loop. What I did is just created a new header for index.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7618748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NetBeans: How to enable/disable specific tab in JTabedPane I am developing a small desktop application in Netbeans. on my UI i have a JTabbedPane having 3 tabs in it now i come across a situation where i need to temporarily disable 2nd and 3rd tab. How could i do that programatically. Rightnow i am using the following code but its not working: int n = jTabbedPane1.indexOfTab("Second Tab Name");// This line returns one as expected jTabbedPane1.getTabComponentAt(n).enable(false);// but i guess some un-expected thing happens here A: I believe what you are looking for is this. jTabbedPane1.setEnabledAt(n, false); A: you can simply use tabObject.setEnabledAt(index, enabled); tabObject :- is the JTabbedPane index would start from 0.So,you Should use 1 and 2 for the second and third tabs enabled is the Boolean value true for on and false for off. i think it helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7618749", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: wp7 insert XAML inside other XAML? How can i insert XMAL inside other XMAL? is this possible in wp7? If anyone know concept help me. thanks. A: Kind of like reusable components? A'la iframes in HTML? You might be interested in UserControls. Here's an excellent tutorial about. So first you create a new usercontrol eg. "MyUserControl.xaml" (File -> New item -> User Control) and add some components to it. Later on you can add a reference to it in another XAML file and use it simply: <MyProject:MyUserControl x:Name="something" /> It's all explained in the tutorial I linked :).
{ "language": "en", "url": "https://stackoverflow.com/questions/7618750", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Remove state maintenance of screens Android? I am very new developer for Android application so please ignore if there is some technical mistakes in my question. I have five screen (Home, SR-1, SR-2,SR-3,SR-4 ) in my Android application and I can switch any screen at give time. When we are pressing device back button it will take we to the previous screen where I was lastly. But whenever I am pressing Home it will take me to landing screen If in this state I am pressing device back button I will take me to previous view but I want to remove this state maintenance. (i.e. : When I am coming to Home and I pressed back button It will exit from my application) Thank you A: From android pressing back button should exit the app : Immediately after you start a new activity, using startActivity, make sure you call finish() so that the current activity is not stacked behind the new one. A: for each activity: you can add in AndroidManifest.xml <activity android:name="nameofActivity" android:noHistory="true"></activity>
{ "language": "en", "url": "https://stackoverflow.com/questions/7618751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Not worked true tooltip box in jQuery Don't know why the tooltip box(class .show_tooltip) shows up on the left when mouse enters on li a. I want to display each tooltip box on top of the same link that mouse is, i.e. just above/left of the link. Links have to be on the right just as they are now, so please do not change my html code) DEMO Example : Mouseover on "how": What can I do to get it like this? These codes are a small specimen part from my original code, which is quite long. CSS: .show_tooltip{ background-color: #E5F4FE; display: none; padding: 5px 10px; border: #5A5959 1px solid; position: absolute; z-index: 9999; color: #0C0C0C; /*margin: 0 0 0 0; top: 0; bottom: 0;*/ } HTML: <ul> <li> <div class="show_tooltip"> put returns between paragraphs </div> <a href="#">about</a> </li> <li> <div class="show_tooltip"> for linebreak add 2 spaces at end </div> <a href="#">how</a> </li> </ul> jQuery: $("li a").mouseenter(function(){ $(this).prev().fadeIn(); }).mousemove(function(e) { $('.tooltip').css('bottom', e.pageY - 10); $('.tooltip').css('right', e.pageX + 10); }).mouseout(function(){ $(this).prev().fadeOut(); }) A: is that you want --> DEMO change position: fixed; in .show_tooltip{} A: Firstly, you are making the markup complicated that way, but since you told not to modify the HTML, here's what you can do to place the tooltip just next to the link. Working Demo -> http://jsfiddle.net/bikerabhinav/AQh6y/8/ Explanation: Get the width of parent container (to act as the axis/base) var t = $('ul').outerWidth(); Get the left-offset of link : var l = $(this).offset(); Apply these to the CSS of tooltip. Position it absolutely: $("li a").mouseenter(function(){ var l = $(this).offset(); var t = $('ul').outerWidth(); $(this).prev().css({right:t+20-l.left,top:l.top}).fadeIn(); }).mousemove(function(e) { $('.tooltip').css('bottom', e.pageY - 10); $('.tooltip').css('right', e.pageX + 10); }).mouseout(function(){ $(this).prev().fadeOut(); }); PS: this is more of a hack basically, but I hope you get what I'm trying to do here. A much better way would be if you clean up the HTML
{ "language": "en", "url": "https://stackoverflow.com/questions/7618752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Integrate MVC 3 Razor with Asp.Net 4.0 in C# I have developed one ASP.NET (C#) web application in Framework 4. I want to integrate an external module which is developed in MVC 3 Razor. How can I integrate this MVC module with my existing ASP.NET web application? And also how to perform nevigation between them. Both have master page. please help me. give me any sample example if possible. thanks... A: Merge web.config & global.ascx with mvc. Add all folder in asp.net project To redirect to Razor view from web page use Response.RedirectToRoute("Default"); where Default Route is routes.MapRoute(<br /> "Default", // Route name<br /> "{controller}/{action}/{id}", // URL with parameters<br /> new { controller = "Home", action = "Index", id = "0" } // Parameter defaults<br /> );<br />
{ "language": "en", "url": "https://stackoverflow.com/questions/7618754", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Xcode: UIScrollView with Paging Tweak I found a great tutorial online that shows you how to page through different pages, well kind of. Here is the link to the tutorial here: http://www.iosdevnotes.com/2011/03/uiscrollview-paging/ The question I have is, how can I tweak his code so that instead of loading "colors" it loads different independent views or view controller files I create? Like I see it loads it's information from the NSArray, but how do you code it so that you include views or view controllers inside that array, and do you have to add anything else special to make this happen? Here is the code I'm referring to from his tutorial which is in the implementation file: - (void)viewDidLoad { [super viewDidLoad]; pageControlBeingUsed = NO; NSArray *colors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor greenColor], [UIColor blueColor], nil]; for (int i = 0; i < colors.count; i++) { CGRect frame; frame.origin.x = self.scrollView.frame.size.width * i; frame.origin.y = 0; frame.size = self.scrollView.frame.size; UIView *subview = [[UIView alloc] initWithFrame:frame]; subview.backgroundColor = [colors objectAtIndex:i]; [self.scrollView addSubview:subview]; [subview release]; } self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * colors.count, self.scrollView.frame.size.height); self.pageControl.currentPage = 0; self.pageControl.numberOfPages = colors.count; } A: As a quick thought, you could try creating an array or similar of views instead of colours. Then in the for loop get the views out of the array and use this in the addSubView: message. This would work for a few views but would not scale well. I do something similar to this but with UIImageViews to be able to scroll a few images.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does a MySQL index on columns (A,B,C) optimize for queries than just select/order by (A,B) only? Given a table with columns A,B,D,E,F. I have two queries: * *one that orders by A then B. *one that orders by A, then B, then C I want to add an index on (A,B,C) to speed up the second query. I'm thinking this will also speed up the first query. Is that correct? Or should I add a second index on (A,B)? Or am I oversimplifying the problem of performance-tuning here? A: Just put an index on all three of them. You don't need a second index.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618766", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to show jquery form validation plugin errors below the form fields I am using jQuery form validation plugin to verify the form.. It is working perfectly.. But problem is that it is showing error message next to form field in the same row.. I want to show this error message below the text field like first form in this example. I don't want to redefine error messages in validate function. What is the shortest way. I am applying plugin like this: $(".ValidateForm").validate(); Thanks A: Got my answer. I restricted the width of the <td></td> in which form element is rendered and error message is shown below the form fields because of low space.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618769", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I put together numbers in java? For some reason when I run the following code the program prints out "JDN4" or "JDN16" when at all times I want it to be printing "JDN" followed by three numbers ranging from 0-9; for example, "JDN123" or "JDN045" or "JDN206". What is wrong with the code? import java.util.*; public class Document2 { public static void main(String[] args) { String initials = "JDN"; int randomNumbers; Random generator = new Random(); int randomNumber1 = generator.nextInt(9); int randomNumber2 = generator.nextInt(9); int randomNumber3 = generator.nextInt(9); randomNumbers = randomNumber1 + randomNumber2 + randomNumber3; String userName = initials + randomNumbers; System.out.println("Your username is " + userName + "."); } } A: Your problem is randomNumbers is declared as an int, so when you use the + on the other ints, it will sum the integers rather than concatenate them. So, if we were to use your approach, we'd need a string: String userName = initials + randomNumber1 + randomNumber2 + randomNumber3; But it would be a lot easier just to generate a number from 0-999 and pad it with zeroes: int randomNumber = generator.nextInt(1000); String usernName = initials + String.format("%03d", randomNumber); Something else worth noting is that Random.nextInt(n) generates a random number between 0 (inclusive) and n (exclusive), so you probably should be doing .nextInt(10) if you want a number between 0 and 9. A: Suppose you have three numbers: int randomNumber1 = 3; int randomNumber2 = 4; int randomNumber3 = 5; int randomNumbers = randomNumber1 + randomNumber2 + randomNumber3; Do you expect randomNumbers to be 345? Or do you expect it to be 12? Now try this: String randomNumbers = "" + randomNumber1 + randomNumber2 + randomNumber3; What do you get this time? A: Try, String userName=String.format("%s%d%d%d",initials,randomNumber1,randomNumber2,randomNumber3); A: randomNumbers = randomNumber1 + randomNumber2 + randomNumber3; You're adding the numbers, not concatenating them. Suggested solution: use only 1 random number with generator.nextInt(1000); Or, you can go like: String userName = initials + randomNumer1 + randomNumber2 + randomNumber3; But I'm nearly sure you'll get 2 or even 3 times the same number, so you should use the first approach instead. A: You are adding the numbers here. randomNumbers = randomNumber1 + randomNumber2 + randomNumber3; If you want to achieve what you are looking for using this same method you could do. randomNumbers = randomNumber1 + (randomNumber2 * 10) + (randomNumber3 * 100); A: What's wrong is that the + operator does an addition, and not a concatenation when used on int variables. Use String randomNumbers = Integer.toString(randomNumber1) + Integer.toString(randomNumber2) + Integer.toString(randomNumber3); to convert the numbers into strings and concatenate them. A: You are adding three digits, that would at most give you 27. You want to concatenate the string representation of those digits. That said, why don't you simply generate a random number between 0 and 999?
{ "language": "en", "url": "https://stackoverflow.com/questions/7618772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get specific cell in Crystal Report I have a Crystal Report linked to table Customer in SQL Server database. My report generator will execute SELECT SQL and pass the result table into the report as data source. In the report, I have a field and I want this field to display the cell data at the specific row index and column index of the table (maybe I know the column name). For example, my field should display cell at row 3, column 2 of the data source. How can I do this using Crystal Report. The latest version now is 2011. A: First off, in order for the row number to have any meaning, you'll need to be querying the table with an ORDER BY clause (by sorting the report). Without it, you can't make any assumptions about the "original order of records" in the DB as there really is none. There are a few ways to get this field depending on where in the report you want to display it. If you simply want to show it in the details section, you can make use of a simple formula like this if rownumber = 3 then {table.column} If you'd like to display it instead in a footer, you could make use of a variable instead: whileprintingrecords; numbervar thedatavariable; if recordnumber = 3 then thedatavariable := {table.column} Throw that formula in the details section of the report and you're then free to use thedatavariable in your footers. Now for the column: If the column index is NOT dynamic you can just see which column corresponds... for example, if the table's columns are customer_id, customer_name then column 2 will always just be the customer name. If the index number will change, like via a parameter, you could make a formula like this select {?colIndexParameter} case 1 : {table.customer_id} case 2 : {table.customer_name} ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7618773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: grab image using mouse cordinates from screen I have searched a lot but i could not find any proper solution for my requirement. I want a functionalty in my website where user can select any area on browser or anywhere in desktop and convert the selected area into image. I know this can be done in windows form,there you do have options to track mouse movements and capture image from screen. I know if i wan this functionality in web i have to get cordinates via javascript and hen maybe make an ajax request to webservice and get my image. first of all i cannot find a proper way in javascript that will get me mousedown and mouseup coordinates. I have seen jquery 's Dragable and resizable div.I want something lke that for user to select the area which has to be converted to image. I can even get Origal mouse position,Current mouse position and the size of div using jquery dragable and reszable div. and Second i want some advice as to how i should grab the selected area as image. Kindly help me out. A: Not possible with JavaScript. Web pages are (intentionally!) not capable of tracking mouse movements outside the browser window, nor of reading an image off the user's desktop. A: You mean something similar to: http://www.screenr.com/record ? A: You can use the clientX and clientY of an event to get the mouse coordinates. For example: http://jsfiddle.net/yN3S5/1/ HTML: <p id="x" ></p> <p id="y" ></p> Javascript: document.onmousemove=function(e){ x=document.getElementById('x'); y=document.getElementById('y'); x.innerHTML=e.clientX; y.innerHTML=e.clientY; } A: First, to convert your page to image, there is a very cool library that can do that. Its use the canvas, and render on it the full page by reading it Get the code and see the examples from here. http://html2canvas.hertzen.com/ Once you have the page in canvas you can thn conver it to png and get a part of it by selecte it. See this example ! http://hertzen.com/experiments/jsfeedback/examples/dusky/index.html Click on the send feedback, then select an area on the page, then click on preview ! Its very near for what you ask, but instead make a red rectangle you cut this part of the image. more examples like the last one : http://hertzen.com/experiments/jsfeedback/ Forget to capture anything outside the browser.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618785", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WCF WebInvoke with query string parameters AND a post body I'm fairly new to web services and especially WCF so bear with me. I'm writing an API that takes a couple of parameters like username, apikey and some options, but I also need to send it a string which can be a few thousands words, which gets manipulated and passed back as a stream. It didn't make sense to just put it in the query string, so I thought I would just have the message body POSTed to the service. There doesn't seem to be an easy way to do this... My operation contract looks like this [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, UriTemplate="Method1?email={email}&apikey={apikey}"+ "&text={text}&quality={qual}", BodyStyle = WebMessageBodyStyle.Bare)] Stream Method1(string email, string apikey, string text, string qual); And this works. But it is the 'text' parameter I want to pull out and have in the post body. One thing I read said to have a stream as another parameter, like this: Stream Method1(string email, string apikey, string qual, Stream text); which I could then read in. But that throws an error saying that if I want to have a stream parameter, that it has to be the only parameter. So how can I achieve what I am trying to do here, or is it no big deal to send up a few thousand words in the query string? A: https://social.msdn.microsoft.com/Forums/vstudio/en-US/e2d074aa-c3a6-4e78-bd88-0b9d24b561d1/how-to-declare-post-parameters-in-wcf-rest-contract?forum=wcf Best answer I could find that tackles this issue and worked for me so I could adhere to the RESTful standards correctly A: A workaround is to not declare the query parameters within the method signature and just manually extract them from the raw uri. Dictionary<string, string> queryParameters = WcfUtils.QueryParameters(); queryParameters.TryGetValue("email", out string email); // (Inside WcfUtils): public static Dictionary<string, string> QueryParameters() { // raw url including the query parameters string uri = WebOperationContext.Current.IncomingRequest.UriTemplateMatch; return uri.Split('?') .Skip(1) .SelectMany(s => s.Split('&')) .Select(pv => pv.Split('=')) .Where(pv => pv.Length == 2) .ToDictionary(pv => pv[0], pv => pv[1].TrimSingleQuotes()); } // (Inside string extension methods) public static string TrimSingleQuotes(this string s) { return (s != null && s.Length >= 2 && s[0] == '\'' && s[s.Length - 1] == '\'') ? s.Substring(1, s.Length - 2).Replace("''", "'") : s; } A: Ended up solving simply by using WebServiceHostFactory
{ "language": "en", "url": "https://stackoverflow.com/questions/7618787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Counting a root's children in SQL Let's say I have a table with 3 columns: * *item ID 'ID' *parent ID 'ParentID' *item name 'Title' Now, how should I count how many children a Root has? A: SELECT COUNT(*) FROM T WHERE ParentID = @ParentID If you want descendants not just immediate children you would need a recursive CTE. ;WITH R AS ( SELECT ID FROM T WHERE ParentID = @RootID UNION ALL SELECT T.ID FROM T JOIN R ON R.ID = T.ParentID ) SELECT COUNT(*) FROM R
{ "language": "en", "url": "https://stackoverflow.com/questions/7618790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: make a friendly multi-language website Just to make things clear. I'm trying to figure out how to build a website with a language chooser. The language chooser is just refreshing the current page but altering the session variable "language" (if the user comes in for the first time I set it up to 'eng'). Now let's figure out the way the crawler is doing, it visits the site and the language is automatically chosen for it, so basically it recognizes the website language and classified it as 'eng'. I'm just not sure this is the right way to go building a multi-language website since the crawler won't be scanning the pages in a different set of language again, am I right ? (or maybe it can detect that the language has been modified and rescan all the pages...which sounds a bit fancy). So the pages won't be referencing in the search engines database. So what is the right way to build those kind of websites ? EDIT : I'm thinking about the mod_rewrite, do you think it's a great solution ? A: Solve this by making the language as a url attribute for instance: www.example.com/en/ www.example.com/fr/ Those will be able to crawl and handle content with different languages. more explained here A: I'm thinking about the mod_rewrite, do you think it's a great solution ? Yes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Date formatting in tr Locale, Windows 7 and Linux gives 2 results When the following code runs in Windows 7 it gives the month in Turkish but in Linux it gives the month in English: new SimpleDateFormat("dd MMMMMM", new Locale("tr")).format(date); * *Windows 7 - 23 Ağustos *Linux - 23 August I want the month in Turkish in Linux too! How do I do this? A: Java does not support Turkish writing on linux operating systems. You can reference the following documentation. Here Look under... 2.Enabled Writing Systems for Java Foundation Classes
{ "language": "en", "url": "https://stackoverflow.com/questions/7618808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Groovy - Strings with "$" Is there any way to by pass "$" keyword at runtime eg println $anish output will be $anish A: Either use single quoted strings: println '$anish' Or escape the dollar as Tom suggests println "\$anish" A: with a backslash println \$anish
{ "language": "en", "url": "https://stackoverflow.com/questions/7618811", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bigdecimal for financial calculations and non-terminating computations I'm sure this would be a simple question to answer but I can't for the life of me decide what has to be done. So here's it: assuming we follow the "best practice" of using BigDecimal for financial calculations, how can one handle stuff (computations) which throw an exception? As as example: suppose, I have to split a "user amount" for investing in bonds between "n" different entities. Now consider the case of user submitting $100 for investing to be split between 3 bonds. The equivalent code would look like: public static void main(String[] args) throws Exception { BigDecimal bd1 = new BigDecimal("100.0"); BigDecimal bd2 = new BigDecimal("3"); System.out.println(bd1.divide(bd2)); } But as we all know, this particular code snippet would throw an ArithmeticException since the division is non-terminating. How does one handle such scenarios in their code when using infinite precision data types during computations? TIA, sasuke UPDATE: Given that RoundingMode would help remedy this issue, the next question is, why is 100.0/3 not 33.33 instead of 33.3? Wouldn't 33.33 be a "more" accurate answer as in you expect 33 cents instead of 30? Is there any way wherein I can tweak this? A: The answer is to use one of the BigDecimal.divide() methods which specify a RoundingMode. For example, the following uses the rounding mode half even or bankers rounding (but half up or one of the other rounding modes may be more appropriate depending on requirements) and will round to 2 decimal places: bd1.divide(bd2, 2, RoundingMode.HALF_EVEN); A: divide has an overload that takes a rounding mode. You need to choose one. I believe "half even" is the most commonly used one for monetary calculations. A: bd1.divide(bd2, 5, BigDecimal.ROUND_FLOOR) It's an exemple, depending on the rounding you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How I could to forbid show of hidden/system files in TOpenDialog? I tried to write a program for safe deleting files. However, I have a problem with deleting system files (recycle bin etc.). Now my question is. Which way to hidden files (from users) at this dialog. Other files I add to listview and then rewrite them zeroes. After that I delete this files without recycle. A: The only way guaranteed to do this is to write your own open file dialog. But I'd advise that you find a better way of doing this, since that's considered pretty bad form. It just occurred to me, but what you could do (and I'm not saying it's easy or nice) is launch the open file dialog, then using the handle to the window gain access to the listbox, and manually remove any system files from that list per your own heuristics. It should work, but I can't guarantee that the items will remain removed (i.e. I think Windows will auto-refresh every so often), so you'll have to experiment and YMMV. Bottom line: find a different way of preventing the user from selecting them. Like Mat says, perhaps just give a message and leave it at that. Failing that, write your own dialog (yuck!).
{ "language": "en", "url": "https://stackoverflow.com/questions/7618816", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Rotate Arrow 180 degree android how can i rotate image with 180 degree like :: Thanks Nik A: Use this int w = oldBitmap.getWidth(); int h = oldBitmap.getHeight(); String filePath = null; Matrix mtx = new Matrix(); mtx.postRotate(180); oldBitmap = Bitmap.createBitmap(oldBitmap, 0, 0, w, h, mtx, true); Cheers!!!
{ "language": "en", "url": "https://stackoverflow.com/questions/7618817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Clone a dojo floating pane I am trying to clone the floating pane object as follows. var pFloatingPane = new dojox.layout.FloatingPane({ title: "A floating pane", resizable: true, dockable: true, style: "position:absolute;top:0;left:0;width:136px !important;height:100px;visibility:visible;", id: "pFloatingPane" }).placeAt(dojo.byId("gridContainer")); var secondPane = dojo.clone(pFloatingPane); but it gives the following error when I debug with chrome javscript debugging tool. Uncaught TypeError: Cannot read property 'id' of undefined But it works fine with following one eventhough i dont give an id at initializing point. var topContentPane1 = new dijit.layout.ContentPane( { region: "top", splitter: true, minSize : 10, maxSize : 84 }, document.createElement("div") ); var secondOne = dojo.clone(topContentPane1); can some one pls tell me how to resolve this problem. thanks in advance A: I'm not sure cloning Widgets is supported behaviour 1. They all have to have an unique ID (and one will be generated if you don't pass one yourself) and I could see that causing trouble. There are also no guarantees that widgets are free of cyclic references and the events like onClick, etc are likely to get messed up. Is there any special reason you want clone that prevents you from just using a simple solution like encapsulating the widget creation in a function? function make_pane(){ new dijit.layout.ContentPane({ //... }); } var first = make_pane(); var second = make_pane();
{ "language": "en", "url": "https://stackoverflow.com/questions/7618823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cursor code gives the error? When i use the cursor.moveToNext(); in my code then the application Force finishing activity when i am scrolling down the bottom but when i am remove cursor.moveToNext(); it works normally ? class NoteHolder { private Button b1 = null; private Button b2 = null; private Button b3 = null; NoteHolder(View row) { b1 = (Button) row.findViewById(R.id.one); b2 = (Button) row.findViewById(R.id.two); b3 = (Button) row.findViewById(R.id.three); } void populateFrom(Cursor c, NoteHelper helper) { b1.setText(helper.getNote(c)); c.moveToNext(); b2.setText(helper.getNote(c)); c.moveToNext(); b3.setText(helper.getNote(c)); } } Errors are ERROR/AndroidRuntime(622): FATAL EXCEPTION: main ERROR/AndroidRuntime(622): android.database.CursorIndexOutOfBoundsException: Index 16 requested, with a size of 16 ERROR/AndroidRuntime(622): at android.database.AbstractCursor.checkPosition(AbstractCursor.java:580) ERROR/AndroidRuntime(622): at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:214) ERROR/AndroidRuntime(622): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:41) ERROR/AndroidRuntime(622): at com.example.buttontest.ButtonTest$NoteHelper.getNote(ButtonTest.java:141) ERROR/AndroidRuntime(622): at com.example.buttontest.ButtonTest$NoteHolder.populateFrom(ButtonTest.java:105) ERROR/AndroidRuntime(622): at com.example.buttontest.ButtonTest$NoteAdapter.bindView(ButtonTest.java:71) ERROR/AndroidRuntime(622): at android.widget.CursorAdapter.getView(CursorAdapter.java:186) ERROR/AndroidRuntime(622): at android.widget.AbsListView.obtainView(AbsListView.java:1294) ERROR/AndroidRuntime(622): at android.widget.ListView.makeAndAddView(ListView.java:1727) ERROR/AndroidRuntime(622): at android.widget.ListView.fillDown(ListView.java:652) ERROR/AndroidRuntime(622): at android.widget.ListView.fillGap(ListView.java:623) ERROR/AndroidRuntime(622): at android.widget.AbsListView.trackMotionScroll(AbsListView.java:2944) ERROR/AndroidRuntime(622): at android.widget.AbsListView$FlingRunnable.run(AbsListView.java:2485) ERROR/AndroidRuntime(622): at android.os.Handler.handleCallback(Handler.java:587) ERROR/AndroidRuntime(622): at android.os.Handler.dispatchMessage(Handler.java:92) ERROR/AndroidRuntime(622): at android.os.Looper.loop(Looper.java:123) ERROR/AndroidRuntime(622): at android.app.ActivityThread.main(ActivityThread.java:4627) ERROR/AndroidRuntime(622): at java.lang.reflect.Method.invokeNative(Native Method) ERROR/AndroidRuntime(622): at java.lang.reflect.Method.invoke(Method.java:521) ERROR/AndroidRuntime(622): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) ERROR/AndroidRuntime(622): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) ERROR/AndroidRuntime(622): at dalvik.system.NativeStart.main(Native Method) A: when you get a Cursor returned from the database you should do an moveToFirst(); before trying to get data from it. try this void populateFrom(Cursor c, NoteHelper helper) { if (!c.moveToFirst()) return; //if no data dont do anything b1.setText(helper.getNote(c)); c.moveToNext(); b2.setText(helper.getNote(c)); c.moveToNext(); b3.setText(helper.getNote(c)); } A: Notice that the exception is being raised inside getNote, not in populateForm. You should be checking the return code of moveToNext(). If you're already past the end of the result set (i.e. there is no next), it will return false. In that case, you cannot access row data from that cursor (it effectively points nowhere). So you should not be calling getNote on that cursor since it's trying to retrieve data from it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating wifi scanning as a android service Currently writing a wifi positioning program and i need to scan the surrounding for active APs so as to calculate the current position of the user. However, user can set the time (0-10 secs) at which the app initiate WiFi scanning (for example, 5 sec, the program would initiate WiFi scanning every 5 secs). And from what is stated in [here] (http://developer.android.com/reference/android/app/Service.html#WhatIsAService) and it says "application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.". So was wondering whether it is best to create a Service in my program then running a TimerTask in this case? A: In this case, i would use Service and TimerTask like here
{ "language": "en", "url": "https://stackoverflow.com/questions/7618825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: store id and transfer to another php page I have a little question. On my site i use for few jquery functions , they get some data and transfer by GET method to php helper. This is not work when i want to use the data in another php page. For example i have jquery that store id of the anchor: $("#rightContent .users_list li a").live('click', function() { var id = $(this).attr('id'); $.get("getHelper",{'userId':id},function(data){ $('#user_rightContent').html(data); }); }); And in php file returned by "getHelper" i do: if(isset($_GET['userId'])){ $id = $_GET['userId']; //do something ); The anchor of the live click lead to another page displayed by another php file where i want to use this id by using helper... This is work only if i stay on same page... Can anybody help me in this problem? thanks for advice A: add return false at the end of live('click'.... live('click', function() { // code ... return false; } or do that live('click', function(e) { // code ... e.preventDefault(); } A: You're missing the extension on the filename. Try it with: $("#rightContent .users_list li a").live('click', function() { var id = $(this).attr('id'); $.get("getHelper.php",{'userId':id},function(data){ $('#user_rightContent').html(data); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7618830", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Data size and disk access Is there a benefit to aligning data to a certain size on storage? For example, if I have the option to use one byte to store information or 4 bytes, which is preferred (assuming that storage size doesn't matter, only optimization)? I ask this question mostly because I know that it "matters" if you're taking about in-memory values (and hence the reason why a .NET boolean is 4 bytes, for example, as per another question on this site). I don't think it would matter, but I am using the .NET framework (C# specifically). A: If you need to be able to get to any particular record in a file, you'll either need some sort of index or a fixed record size - but that's for the whole record rather than each individual part of the record. I wouldn't usually go to any great lengths to align data on 4 or 8 byte boundaries within storage. Of course, if you read a record at a time, to an aligned location in memory, then you end up with aligned data to perform any conversions on... so it can all end up being intertwined to some extent - but the conversion is likely to be one-off, rather than frequent access after conversion. Storage size matters for optimization of course - because reading less data from the disk will be cheaper than reading more (generally...). Unless you have specific requirements like fixed record sizes, I would just try to design the storage so that it's as easy to use as possible. If you have specific areas of concern for performance, you should profile those. For example, it may be more efficient to use UTF-16 to encode strings than UTF-8, as the encoding and decoding should require less work... even though it'll take more space. You should test these rather than making any assumptions though. Note that where you're loading the storage format from will make a big difference - over the network, from a mechanical disk, from a solid state drive... these will have different performance characteristics, which probably make it hard to design something which is fastest for all cases.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can't invoke a closure wrapped in a closure? If I wrap a closure in another closure, I can't invoke the nested closure. Why not? I think an example illustrates the problem best. This PHP code: function FInvoke($func) { $func(); } FInvoke(function () { echo "Direct Invoke Worked\n"; }); Works as expected and prints "Direct Invoke Worked". However, If I slightly modify it to add another level of indirection, it fails: function FInvoke($func) { $func(); } function FIndirectInvoke($func) { FInvoke(function () { $func(); }); } FIndirectInvoke(function () { echo "Never makes it here"; }); The failure message is "Fatal error: Function name must be a string in file.php on line X" A: you have to pass $func to the inner lambda using "use" keyword function FInvoke($func) { $func(); } function FIndirectInvoke($func) { FInvoke(function () use($func) { // <--- here $func(); }); } FIndirectInvoke(function () { echo "ok"; });
{ "language": "en", "url": "https://stackoverflow.com/questions/7618834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: alert another page I have an index.php. It has a log in function. Let's say I have 2 users A and B. Page1(index.php of user A) -with function(checks whether there are changes in the database, if yes: alert('message')) Page2(index.php of user B) -with button which when clicked should update the database I can already update the database, the function from page1 already works, it can detect changes, but only when you reload it. So I want to reload Page1 whenever page2 updates the database. I thought of just using setTimeout(something, timeInterval) in Page1 but it doesn't seem appropriate since the components of Page1 are flickering everytime it reloads. I want Page1 to reload if and only if there are changes in my database. I also thought of just putting the Page1's function inside an infinite while loop but it doesn't seem appropriate either, since the page just loads.. Another thing is, I was informed about JSON and REST. So I could just access the database from the script file. But I'm not that knowledgeable in it. Neither am I in jQuery. I've tried searching about refreshing a page from another but the answers I found were either vague or difficult for me. And my pages have the same name, they only differ with the user logged in. But If I can find a way to do this, then I'll just do something with my pages' names. Is there any other way I can do this? Thank you. A: When the page you want to update first loads, put the time in a variable by doing something = new Date().getTime(); Send an XMLHttpRequest to a php that checks if the databases last update time is newer than the time sent with the ajax call. If it is, return something that tells the javascript to refresh the page. If not, have the javascript make another call in a few seconds with setTimeout . It would be better if you learned the ropes of javascript before using jQuery, so I'll update this answer in a second with some script. edit 1: check out https://developer.mozilla.org/en/AJAX/Getting_Started Using jQuery for ajax calls is one of the most sensible uses of jQuery, but it's better if you know how it works too. A: So you basically need for the server to notify page1 when an update is available. What you are looking is called "comet". Check out this articles: comet wikipedia comet ajaxian Comet programing can be done using ajax or iframes A: Create pageC.php which should check if database has changed, and if so, output 1, else output nothing. Then with jQuery and AJAX... <!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <title>Quick AJAX test</title> <!-- needs to be url to jquery, can be locally, or via CDN --> <script type="text/javascript" src="jquery"></script> <script type="text/javascript"> // this executes all contained after page has fully loaded $(function(){ // define function to check for changed database function checkNew(){ // make AJAX GET request, and set callback function $.get('./pageC.php',function(data){ // check if the data returned (page content) is 1 if(data === '1') alert('The database has changed') // run the function to check again checkNew() }) } // call the checking function to initialise the loop checkNew() }) </script> </head> <body> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7618845", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Reorder an array based on values I need to reorder an array so that all slugs get loaded before parents, but only if a parent has a value that matches a slug value exactly. For example, take this array: Array ( [0] => Array ( [parent] => information_desk_3 [slug] => about_dream_portal_1 ) [1] => Array ( [parent] => forum [slug] => information_desk_3 ) [2] => Array ( [parent] => about_dream_portal_1 [slug] => testing_2 ) [3] => Array ( [parent] => testing_2 [slug] => information_desk_4 ) ) I need it so that it gets ordered as follows: Array ( [0] => Array ( [parent] => forum [slug] => information_desk_3 ) [1] => Array ( [parent] => information_desk_3 [slug] => about_dream_portal_1 ) [2] => Array ( [parent] => about_dream_portal_1 [slug] => testing_2 ) [3] => Array ( [parent] => testing_2 [slug] => information_desk_4 ) ) But the catch is, it needs to search through all slugs and reorder them so that the slugs come first in the array, before the parents that match the value of that slug. Please someone help me, I've been at it for hours now to no avail. A: Sounds like what you really have is a graph, and you want a partial ordering of nodes. That means you can solve the problem using standard graph algorithms. If you build a tree of items where each parent knows about all its children then you can do a breadth-first traversal of the tree to build your partially ordered output. In your example it's a very simple graph: forum -> information_desk_3 -> about_dream_portal_1 -> testing_2 -> information_desk_4 If you start at forum and walk down the tree adding nodes to the output list as you go then you'll wind up with the correct order. If you have multiple disjoint trees then it gets a little trickier, but still shouldn't be too hard. You just need to figure out which nodes are root nodes and then walk each tree in turn.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618847", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how can App Run on Full Screen Mode in android I have created an app when I run It into tab then it is not taken full screen,I have also done its property"Full Screen With No title bar"So it is coming without title. thanks A: you can add android:theme="@android:style/Theme.NoTitleBar.Fullscreen" to the AndroidManifest.xml
{ "language": "en", "url": "https://stackoverflow.com/questions/7618852", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: onchange event for element when I have no control over when it is changed I have a div element on a page that has other divs added to it when certain events happen. I do not know when these events happen, how they are triggered and how the other divs are added to the main div (its external so I have no idea whats happening all I have access to is the div). How would I "monitor" for changes to the main div so an event is triggered whenever a new div is added ? I know I can use setInterval (which is what I'm doing now), but I really do not want to use it unless absoluley necessary. I would love to something as simple as form elements do with onchange but I have not found such for divs. Example if text is not clear: wesite.com/index.html ( the only thing I have access to) <html> <head></head> <body> <div id="theDiv"> </div> </body> </html> and at times unknown to me divs get added to that div and it eventually looks like : <html> <head></head> <body> <div id="theDiv"> <div class="added"><p>Added Div</p></div> <div class="added"><p>Added Div</p></div> <div class="added"><p>Added Div</p></div> <div class="added"><p>Added Div</p></div> <div class="added"><p>Added Div</p></div> </div> </body> </html> And lets say I set up the event to trigger an alert, in this example I want to see an alert box every time a new div is added so by the time it looks like this I should have seen 5 alert boxes. Sorry if this is difficult to follow.. A: The easiest way is to intercept the calls that are adding the children to the DIVs. Is this not an option?
{ "language": "en", "url": "https://stackoverflow.com/questions/7618854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to to read a matrix from a given file? I have a text file which contains matrix of N * M dimensions. For example the input.txt file contains the following: 0,0,0,0,0,0,0,0,0,0 0,0,0,0,0,0,0,0,0,0 0,0,0,0,0,0,0,0,0,0 0,0,0,0,0,0,0,0,0,0 0,0,0,0,0,0,0,0,0,0 0,0,0,0,0,0,0,0,0,0 0,0,2,1,0,2,0,0,0,0 0,0,2,1,1,2,2,0,0,1 0,0,1,2,2,1,1,0,0,2 1,0,1,1,1,2,1,0,2,1 I need to write python script where in I can import the matrix. My current python script is: f = open ( 'input.txt' , 'r') l = [] l = [ line.split() for line in f] print l the output list comes like this [['0,0,0,0,0,0,0,0,0,0'], ['0,0,0,0,0,0,0,0,0,0'], ['0,0,0,0,0,0,0,0,0,0'], ['0,0,0,0,0,0,0,0,0,0'], ['0,0,0,0,0,0,0,0,0,0'], ['0,0,0,0,0,0,0,0,0,0'], ['0,0,2,1,0,2,0,0,0,0'], ['0,0,2,1,1,2,2,0,0,1'], ['0,0,1,2,2,1,1,0,0,2'], ['1,0,1,1,1,2,1,0,2,1']] I need to fetch the values in int form . If I try to type cast, it throws errors. A: Consider with open('input.txt', 'r') as f: l = [[int(num) for num in line.split(',')] for line in f] print(l) produces [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 2, 1, 0, 2, 0, 0, 0, 0], [0, 0, 2, 1, 1, 2, 2, 0, 0, 1], [0, 0, 1, 2, 2, 1, 1, 0, 0, 2], [1, 0, 1, 1, 1, 2, 1, 0, 2, 1]] Note that you have to split on commas. If you do have blank lines then change l = [[int(num) for num in line.split(',')] for line in f ] to l = [[int(num) for num in line.split(',')] for line in f if line.strip() != "" ] A: You can simply use numpy.loadtxt. Easy to use, and you can also specify your delimiter, datatypes etc. specifically, all you need to do is this: import numpy as np input = np.loadtxt("input.txt", dtype='i', delimiter=',') print(input) And the output would be: [[0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0] [0 0 2 1 0 2 0 0 0 0] [0 0 2 1 1 2 2 0 0 1] [0 0 1 2 2 1 1 0 0 2] [1 0 1 1 1 2 1 0 2 1]] A: You can do this: fin = open('input.txt','r') a=[] for line in fin.readlines(): a.append( [ int (x) for x in line.split(',') ] ) A: The following does what you want: l = [] with open('input.txt', 'r') as f: for line in f: line = line.strip() if len(line) > 0: l.append(map(int, line.split(','))) print l A: You should not write your csv parser, consider the csv module when reading such files and use the with statement to close after reading: import csv with open('input.txt') ad f: data = [map(int, row) for row in csv.reader(f)] A: Check out this small one line code for reading matrix, matrix = [[input() for x in range(3)] for y in range(3)] this code will read matrix of order 3*3. A: import numpy as np f = open ( 'input.txt' , 'r') l = [] l = np.array([ line.split() for line in f]) print (l) type(l) output: [['0'] ['0'] ['0'] ['0,0,0,0,0,0,0,0,0,0,0'] ['0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0'] ['0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0']] numpy.ndarray A: The following code converts the above input to matrix form: f = open ('input.txt' , 'r') l = [] l = [line.split() for line in f] l=np.array(l) l=l.astype(np.int)
{ "language": "en", "url": "https://stackoverflow.com/questions/7618858", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: Is it possible to use jquery to resize an image? Can I use JQuery to resize an image that is not on my local server? Lets say I have an image on www.example.com/dir/images/myImage.jpg And I want to resize the image on my server www.localhost.com Will it still work? A: You can load that image from example.com, and you can change the scale at which it is presented on your page, but you can't edit the file itself. You can either use the height and width tags that Masoud commented, or you can use CSS to edit that element's width+height properties. A: You can use jQuery to resize it like this: $('img#imageidhere').css({ 'width':'xxx', 'height':'yyy' }); However, this will only change the CSS which won't resize the image itself, as Chazbot said, this will only change the size in which it is presented on your page. I figured this was a more appropriate answer since you asked about jQuery and he gave you an answer in HTML and CSS. Here is an example of it in action: http://jsfiddle.net/qdWMv/ Guide to which method to use: CSS: You should use CSS to resize the image if it's only for the purpose of displaying an image on your page and you don't plan to change it. (or if you do plan to change it, you can set the default size using a CSS style on your page) jQuery Use jQuery like I suggested if you are going to dynamically change the display size of the image on the page dynamically for any reason. PHP PHP is the only method that will change the actual file itself. So if you actually need to change the size of the file itself for any reason then use PHP. A: If you have PHP5 and the HTTP stream wrapper enabled on your server, it's incredibly simple to copy it to a local file: copy('http://somedomain.com/file.jpeg', '/tmp/file.jpeg'); link from : Copy Image from Remote Server Over HTTP After copy and download the image you can resize image by using jquery image resizer i mostly use this jquery resizer or you can also used jquery thumbnail generator ..
{ "language": "en", "url": "https://stackoverflow.com/questions/7618859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Remove leading 0's for str(date) If I have a datetime object, how would I get the date as a string in the following format: 1/27/1982 # it cannot be 01/27/1982 as there can't be leading 0's The current way I'm doing it is doing a .replace for all the digits (01, 02, 03, etc...) but this seems very inefficient and cumbersome. What would be a better way to accomplish this? A: You could format it yourself instead of using strftime: '{0}/{1}/{2}'.format(d.month, d.day, d.year) // Python 2.6+ '%d/%d/%d' % (d.month, d.day, d.year) A: The datetime object has a method strftime(). This would give you more flexibility to use the in-built format strings. http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior. I have used lstrip('0') to remove the leading zero. >>> d = datetime.datetime(1982, 1, 27) >>> d.strftime("%m/%d/%y") '01/27/82' >>> d.strftime("%m/%d/%Y") '01/27/1982' >>> d.strftime("%m/%d/%Y").lstrip('0') '1/27/1982'
{ "language": "en", "url": "https://stackoverflow.com/questions/7618863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to set 3d flip animation for child of gridview i am working on animation, i want to give animation to the child view of costume grid view. and that animation like 3d Transition for chile(image view) of android. I am using the concept is as per http://www.inter-fuser.com/2009/08/android-animations-3d-flip.html. But i can not able to animate the imageview of gridview. Please help me. A: You have to apply setStaticTransformationsEnabled(true); at the constructor of your custom GridView. Then apply the transformations at the protected boolean getChildStaticTransformation(View child, Transformation t) and return true to that overriden function A: Since you are talking about 3D, i guess probably you should take a look at RenderScript and openGL. Regarding Renderscript,tutorial are at Part-I and Part-II For Best example for the usage of renderscript is Youtube and Books app for Honeycomb 3.0 and above. A: The flip animation in your link doesn't produce believable 3D flips. A simple rotation on the y-axis isn't sufficient. The zoom effect is also needed to create that nice iOS flip feel. For that, take a look at this example: https://code.google.com/p/android-3d-flip-view-transition. There is also a video here: http://youtu.be/52mXHqX9f3Y
{ "language": "en", "url": "https://stackoverflow.com/questions/7618871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Is there any difference between __typeof and typeof? There are more operators that work when we add __ to them too. what does __ mean? A: An identifier with double underscores is reserved for the implementation. typeof is a compiler specific extension to the language, so naming it __typeof ensures no user code has an identifier with the same name
{ "language": "en", "url": "https://stackoverflow.com/questions/7618873", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to make an installer for Android? [To avoid large download] I think the question is clear from the title, * *I have an Android program *It needs to read some data from a given path, say SDCARD/myAppData/data which is a large file *I think, I should allow users to download this large file while installing the App. OR, Say, they can download the file on PC, and then put it in SDCARD, and then the app will read from the SDCARD. (To save bandwidth for the mobile) I want to provide user a chance to choose a path for SDCARD or system memory..then the installer should install the data into the chosen path... and work.. normally. Any idea? Please explain... A: About number '2'... It READS or it WRITES data? Anyway, what I'd do is displaying a "choose your path" screen depending on a flag (it can be on a SharedPreference or SQLite). The flag will be turned on by default, and will only turn off once the path has been chosen (only then you'll follow the "real" application flow). This is the closest to an installer I can think about on Android.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Replaced third party code with git submodules, now I can't switch branches Here's the story: I have 2 git branches master and develop I'm currently on develop. I've long since had the source files of a third party library included in my repo in the directory Vendor/MGTwitterEngine. This code was already merged into master. Now, on branch develop, I've removed the library and replaced it with a git submodule and committed. The problem is I can no longer switch back to the master branch. If I try, I get the following error: The following untracked working tree files would be overwritten by checkout: Vendor/MGTwitterEngine/MGTwitterHTTPURLConnection.h Vendor/MGTwitterEngine/MGTwitterHTTPURLConnection.m Vendor/MGTwitterEngine/MGTwitterLibXMLParser.h Vendor/MGTwitterEngine/MGTwitterLibXMLParser.m Vendor/MGTwitterEngine/MGTwitterMessagesLibXMLParser.h Vendor/MGTwitterEngine/MGTwitterMessagesLibXMLParser.m Vendor/MGTwitterEngine/MGTwitterMessagesParser.h Vendor/MGTwitterEngine/MGTwitterMessagesParser.m ... Aborting git thinks the submodule files are "untracked" and won't replace them with the tracked, non-submodule files in the same location. How can I get around this issue? A: Unfortunately, I think this is just one of the drawbacks of using submodules. These problems are described in a section called "Issues with Submodules" in Pro Git, but in short, the simplest workaround is to move the submodule directory out of the way before switching to the master branch: mv Vendor Vendor.moved git checkout master Similarly, when you change to develop, you should do: git checkout develop mv Vendor.moved Vendor A: Now it can be made easier. Use command git checkout -f master.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: Phonegap Filetransfer API Not Work in SGS SII i'm newbie on phonegap, I am just trying transfer a file to my server via phonegap 1.0 Filetransfer API and work on android emulator Android 2.3.3 (API level 10) but don't work with real device ( samsung galaxy sII) bellow my code : document.addEventListener("deviceready",onDeviceReady,false); function onDeviceReady() { pictureSource=navigator.camera.PictureSourceType; destinationType=navigator.camera.DestinationType; } function capturePhoto() { navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 30, destinationType: destinationType.FILE_URI }); } function onPhotoURISuccess(imageURI) { $(".loading").show() var doit = $('a#sendkamera').attr('rel'); var smallImage = document.getElementById('smallImage'); smallImage.style.display = 'block'; smallImage.src = imageURI; var options = new FileUploadOptions(); options.fileKey="file"; //options.fileName="newfile.txt"; options.mimeType="image/jpeg"; var params = new Object(); params.value1 = "test"; params.value2 = "param"; options.params = params; var ft = new FileTransfer(); ft.upload(imageURI, "http://api.byur.in/android/upload/", win, fail, options); } function win(r) { console.log("Code = " + r.responseCode); console.log("Response = " + r.response); console.log("Sent = " + r.bytesSent); alert("Code = " + r.responseCode); alert("Response = " + r.response); alert("Sent = " + r.bytesSent); alert("Sukses"); $(".loading").hide() } function fail(error) { alert("An error has occurred: Code = " = error.code); } I don't understand, why this code can be successful with alert status code = -1, but when I look at the log server, I don't see the request. i try upload file via ajax and work on emulator but dont work with real device with error message status code = 0. bellow my code function capturePhoto() { navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 30 }); } function errorCallback(xhr, textStatus, errorThrown) { navigator.notification.beep(3); alert(textStatus + errorThrown + ' coba lagi di waktu mendatang'); alert(xhr.responseText); } function successIMG(imageData) { var doit = $('a#sendkamera').attr('rel'); $('.loading').show(); var data = {image: imageData}; var url = 'http://api.byur.in'+doit; $.ajax({url:url, type:'POST', data:data, success:function(data){ $('.loading').hide(); alert('sukses'); },error: errorCallback }); } I am not sure where I am going wrong. What can I do to fix this problem? thanks for your reply
{ "language": "en", "url": "https://stackoverflow.com/questions/7618878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP slugify method without using preg_replace() I am using following slugify method,in my local dev its working fine,but in my production server(CentOs) and the PCRE UTF8 supported but "No Unicode properties support". function slugify($text) { // replace non letter or digits by - $text = preg_replace('~[^\\pL\d]+~u', '-', $text); // trim $text = trim($text, '-'); // transliterate if (function_exists('iconv')) { $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text); } // lowercase $text = strtolower($text); // remove unwanted characters $text = preg_replace('~[^-\w]+~', '', $text); if (empty($text)) { return 'n-a'; } return $text; } And preg_replace is not working there,is there any method that can work as preg_replace,or any slugify muthod that can work as the above function. Thanks in advance. A: This sounds like the same issue described here: http://chrisjean.com/2009/01/31/unicode-support-on-centos-52-with-php-and-pcre/. I've run into it before myself, and that link is how I fixed it (or rather, how our sysadmin fixed it). Essentially, the \pL in the first regex will not run or compile if you do not have "Unicode properties support".
{ "language": "en", "url": "https://stackoverflow.com/questions/7618879", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: XPATH selecting node with attribute and text Given (no comments about the XML naming necessary): <config> <unit> <var name='model'>3100</var> <var name='type'>production</var> </unit> <unit> <var name='model'>0100</var> <var name='type'>test</var> </unit> </config> How can I construct an XPATH to select the node with the attribute "model" and the text 3100 using Ruby Nokogiri I'm trying: //var[@name='model' and text()='3100'] but getting "invalid predicate". Obviously that's just the XPATH with the Nokogiri calls omitted. I don't seem to be having any problems with the Nokogiri usage, so my request is just about fixing the XPATH. A: That works with nokogiri 1.5, Are you using a very old version?
{ "language": "en", "url": "https://stackoverflow.com/questions/7618880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to display offline OpenStreetMap using MapView on Android? How to display OpenStreetMap offline using MapView on Android? What should I do to load a map? A: Since OpenStreetMap contain a large amout of data, you need to select a subset of it and probably transform the OSM XML to your own vector format that require less storage. Then you need to render your own vector format on a canvas.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618883", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }