text
stringlengths
8
267k
meta
dict
Q: xsel for windows equivalent API or command line? Is there an API or command line utility that returns the currently selected text from either active window or even globally, like the linux utility "xsel" ? * *I don't mind getting less than 100% success. *i know that each window can have its own text selection, but it's negligible for now. *For now the only solution/workaround i have is to sendkeys "ctrl+c" and read from clipboard, but that's bad solution for 2 obvious reasons. *I know how to do it on MS-Word, but that's 1% of the cases. thanks edit From this discussion i learn that there are too many technologies to select text. so i'll fall back to using clipboard. thanks anyway. i'm leaving this question open for a while in case somebody have a miracle. A: this is a solution i compiled from several sources. * *it will work only on simple text controls. for the other types of text there are other solutions, but for simplicity i'll use the clipboard. (for a complete code, declarations and dependencies, google for "SendMessage hWndCaret") If hWndCaret <> 0 Then 'first, get all text nLength = SendMessage(hWndCaret, WM_GETTEXTLENGTH, 0&, ByVal 0&) If nLength <> 0 Then buff = Space$(nLength + 1) res = SendMessage(hWndCaret, WM_GETTEXT, nLength + 1, ByVal buff) If res <> 0 Then Txt = Left$(buff, res) End If ' then If nLength <> 0 Then buff = Space$(nLength + 1) res = SendMessage(hWndCaret, EM_GETSEL, VarPtr(StartPos), EndPos) selection = Mid(Txt, StartPos + 1, EndPos - StartPos) End If End If A: Check if the program supports accessible interface like IAccessible/IAccClientDocMgr or TextPattern_GetSelection/TextRange_GetText. Many software need to implement accessible to sell to the US government because of the Americans with Disabilities Act. You can call AccessibleObjectFromWindow or AutomationElement::FromHandle on a window. It looks like nobody documents their accessible object tree, and if there is an API exists, then the API is the preferred way to get information from the program. E.g. you should use Q249232 to get IHTMLDocumnent2 if the application is IE. There are significant changes in IE7 and IE8's assessible tree when inspected in UI spy. For other programs you may be out of luck. I cannot find the selection in the login email edit when using UISpy. Accessiblility depends on the good will of programmers to implement accessibility in their programs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java serialization - Android deserialization I have tried implementing cross platform serialization between Java and Android. I have used Serializable, and having my code in Android in the same package as in desktop Java. Source: java-desktop serializing Student student=new Student(); student.setName("John"); student.setSurname("Brown"); student.setNumber(776012345); try { FileOutputStream fout = new FileOutputStream("thestudent.dat"); ObjectOutputStream oos = new ObjectOutputStream(fout); oos.writeObject(student); oos.close(); } catch (Exception e) { e.printStackTrace(); } } Source: Android - deserializing File file=new File(getExternalFilesDir(null), "thestudent.dat"); try { FileInputStream fint = new FileInputStream(file); ObjectInputStream ois = new ObjectInputStream(fint); Student stud=(Student) ois.readObject(); ois.close(); } catch (Exception e) { e.printStackTrace(); } } Student is a class, which implements Serializable. On desktop I serialize instance of student to "thestudent.dat". I put this file on SD card at Android device and I am trying to deserialize it. I am getting error java.lang.ClassCastException: javaserializace.Student. But why? I have same package when serializing, same package when deserializing. All what is different is project name. Do you see any solution? Edited - source of Student class: public class Student implements Serializable { private String name; private String surname; private int number; private char gender; private int age; private long rc; private int id; public Student(){ ; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public char getGender() { return gender; } public void setGender(char gender) { this.gender = gender; } public int getId() { return id; } public void setId(int id) { this.id = id; } public long getRc() { return rc; } public void setRc(long rc) { this.rc = rc; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } } A: I am certain that two versions of Student on Both sides are not same. Because the exception is java.lang.ClassCastException: javaserializace.Student. which indicates that Java has successfully deserialized the object but while typecasting it to Student on receiver side, it is throwing exception because types are not same. A quick way to debug this is to invoke getClass() on received Student object and getName() on Student class on receiver. I am sure that in this case both are different. And solution will be to ensure that Student on receiver side is of same type. A: I don't see any problem with the code you post. My guess is that Student is not in the same exact package on both sides. So if it is "com.acme.Student" on desktop, it should also be that on Android. Also its good idea to add serialVersionUID in case your Student changes in the future. A: I would recommend using something like Kryo or Protocol Buffers for your serialization. It would be much faster with smaller payload. The only downside is that you need to include an additional jar.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: problems to transform sqlite data in object I'm learning to open jobs on Android SQLite. I want to display the text of a spinner filled via a cursor. The problem when I use the: nameOfSPinner.getSelectedItem().toString(); It displays the numbers of the selected index and not the data. To solve this problem, I thought I could take all the information and store it in an object array, then fill the spinner with that information. (Is there a better approach?) By the time I take what is written in the index and display it in the object, my app crashes with a NullPointerException. I feel that there are basic object-oriented programming that I did not understand but I do not see anything. public Objet[] getObjetDescription2(){ Cursor c = bdd.query("nom de la table", new String[] {"rowid _id", "description", "id"},null, null, null, null, null); return nomFonction(c); } private Objet[] nomFonction(Cursor c){ //si aucun élément n'a été retourné dans la requête, on renvoie null if (c.getCount() == 0) return null; //Sinom on se place sur le premier élément c.moveToFirst(); int compteur = c.getCount(); Objet[] objet = new Objet[100]; int i = 0; do{ //on lui affecte toutes les infos grâce aux infos contenues dans le Cursor objet[i].setDescription(c.getString(2)); objet[i].setId(c.getInt(1)); i++; }while(i >= compteur); //On ferme le cursor c.close(); return objet; } A: Objet[] objet = new Objet[100]; This creates a new array that can hold 100 Objet instances. It does not create any Objet instance: all the slots are initially null. So you need to create the objects explicitly in your loop: objet[i] = new Objet(); objet[i].setDescription(c.getString(2)); ... Also your loop structure is both unusual and incorrect (try simulating it on paper with compteur == 2). Use a simple for loop. for (i=0; i<compteur; i++) { ... } And you're not advancing the cursor anywhere in there. You'll need to call moveToNext() somewhere.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Minimum credential for WMI parameters Monitoring? I'm developing a big project to monitor a remote machine's performance parameters like CPU,Memory,Diskspace through C# WMI. I want to use the minimum possible credentials to connect the remote machines. Because I don't want to bother my client to ask for the super-user credentials. Its sure that if I disabled the firewall and use the super user credentials, WMI is fine; but resource monitoring in such environment means giving lots of space to the system intrusion for the hacker. So, my main question is what is the minimum system vulnerabilities that we can expose for the remote machine for such monitoring? A: Best is to setup a domain user account that have WMI access and all, set it up in the Active Directory (This includes pushing updated firewall rules to all machines etc, enable your user for WMI monotoring on the machines). Typically this user can't do anything else, not perform a local logon etc. Then in your code just do Impersonation with that user.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Error inflating animation resource I read this example and I'm trying to use it. I put this in drawable folder as somth.xml: <animation-list android:id="selected" android:oneshot="false"> <item android:drawable="@drawable/img1" android:duration="50" /> <item android:drawable="@drawable/img2" android:duration="50" /> </animation-list> I also put it in anim folder I try to add header like: <?xml version="1.0" encoding="utf-8"?> But give me an error like this: Error in an XML file: aborting build. What is wrong? A: Strange, it seems that android:id is not a valid attribute for frame animations. Try removing that attribute and/or adding xmlns:android="http://schemas.android.com/apk/res/android" to <animation-list>. A: had you inserted required drawable? or you can clean and build the project Eclipse>Project>clean
{ "language": "en", "url": "https://stackoverflow.com/questions/7528354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# - winform - How to encrypt endpoint address in app.config Possible Duplicate: WCF Encryption solution for App.config viewable to a client? In my application, I use a webservice to authenticate member, I found out that .NET store endpoint address of the webservice in app.exe.config file. So I think it's very easy if someone can create another web service and change the configuation file, he can login to my app. Please help, Thanks Now I'll implement something like this to source this._dataService = new DataServiceSoapClient(); if (this._dataService.Endpoint.ListenUri.ToString() != "myURLofWebservice") { //error } I think it solves my problem Thank you all for your helps A: Well, it is also easy to use http sniffer to see, where application does requests, so encrypting endpoint address is also not a solution. I think better way to do this, that webservice would sign request using private key and application would check signature using public key. There are many examples of this, like http://blogs.msdn.com/b/alejacma/archive/2008/02/21/how-to-sign-a-message-and-verify-a-message-signature-c.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7528356", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Implications of adding enctype="multipart/form-data" in a master page? We have one master page for an entire asp.net 2.0 site, which contains the form tag. Are there any implications to adding enctype to the form tag? One page needs to be able to upload a file, and I believe this is required in order for that to function properly. Do we need to re-test the entire site after making this change? Prior to this, the form tag was simply: <form id="form1" runat="server"> A: You can use code to programmatically set the attributes of form tag. And you can put the code in a proper page event such as "Init" event. e.g. public partial class test_TestContentPage : System.Web.UI.Page { protected void Page_Init(object sender, EventArgs e) { this.Form.Enctype = "multipart/form-data"; } } A: We did that a while back and never gave it another thought. Our main app has literally hundreds of pages all with various input controls (text, multiline, drop down lists, checkboxes, etc) and we've never seen an issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Embed python/dsl for scripting in an PHP web application I'm developing an web based application written in PHP5, which basically is an UI on top of a database. To give users a more flexible tool I want to embed a scripting language, so they can do more complex things like fire SQL queries, do loops and store data in variables and so on. In my business domain Python is widely used for scripting, but I'm also thinking of making a simple Domain Specific Language. The script has to wrap my existing PHP classes. I'm seeking advise on how to approach this development task? Update: I'll try scripting in the database using PLPGSQL in PostgreSQL. This will do for now, but I can't use my PHP classes this way. Lua approach is appealing and seems what is what I want (besides its not Python). A: How about doing the scripting on the client. That will ensure maximum security and also save server resources. In other words Javascript would be your scripting platform. What you do is expose the functionality of your backend as javascript functions. Depending on how your app is currently written that might require backend work or not. Oh and by the way you are not limited to javascript for the actual language. Google "compile to javascript" and first hit should be a list of languages you can use. A: If you are not bound to python, you could use for example Lua as scripting language. Lua is a very lightweight language, easy to learn, and developed with embedding in mind. There are already at least two PHP extensions available, which nicely embed Lua into PHP and therefore provide the possibility to allow access between PHP and Lua part of your application. Have a look at: http://pecl.php.net/package/lua This one also has some nice examples: http://phplua.3uu.de/ I've already used the latter one a bit for simple experiments and it works quite good. A: Security, security, security! Just wanted to get that out of the way. What you seem to be trying to do sounds pretty scary but it is your foot to shoot. Also, what you seem to be trying to do is mix two different server-side languages unless there is an implementation of Python that runs on top of PHP that I am not aware of (PHPython?). If you are willing to have your PHP code invoke Python in some way, you should be able to do this pretty easily with something like eval() or exec(). See how to input python code in run time and execute it? As for wrapping your PHP classes, I'm not sure you can accomplish that exactly. You could mirror your PHP classes with Python classes and use something like JSON to transport the data between the two. A: I don't know any prefab solutions. But pypy, a Python implementation written in RPython, has a sandboxing feature, which enables you to run the untrusted code. But if some obvious DSL can be designed for your domain, that might be the easier solution. A: You could do it without Python, by ie. parsing the user input for pre-defined "tags" and returning the result. A: You have two choices: * *Do your logic in PHP on the frontend using a MVC *Defer your logic to the backend If you're doing your logic on the frontend, you can look into a PHP5 MVC framework, such as Zend If you're deferring your logic, you can use any scripting language you like. For example, you can use SQLAlchemy with Python to access your database.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Implementing mbsnrtowcs in terms of mbsrtowcs In an almost complete effort to port libc++ to Windows, I need the function mbsnrtowcs, and thought that the easiest way would be to implement it in terms of mbsrtowcs: size_t mbsnrtowcs( wchar_t *__restrict__ dst, const char **__restrict__ src, size_t nmc, size_t len, mbstate_t *__restrict__ ps ) { char* nmcsrc = new char[nmc+1]; strncpy( nmcsrc, *src, nmc ); nmcsrc[nmc] = '\0'; const size_t result = mbsrtowcs( dst, &nmcsrc, len, ps ); delete[] nmcsrc; return result; } The problem here is that mbsrtowcs needs &nmcsrc to be of type const char**, which is isn't, because it is a string I just copied the first nmc elements into, and appended a \0 character to. How can I work around this? Strictly speaking, this is compiled as C++, so perhaps a const_cast would do little harm here? I also have access to c++0X (libc++ is/requires a subset c++0x). Edit: the Clang error message reads: M:\Development\Source\libc++\src\support\win32\support.cpp:37:27: error: no matching function for call to 'mbsrtowcs' const size_t result = mbsrtowcs( dst, &nmcsrc, len, ps ); ^~~~~~~~~ M:/Development/mingw64/bin/../lib/clang/3.0/../../../x86_64-w64-mingw32/include\wchar.h:732:18: note: candidate function not viable: no known conversion from 'char **' to 'const char **restrict' for 2nd argument; size_t __cdecl mbsrtowcs(wchar_t * __restrict__ _Dest,const char ** __restrict__ _PSrc,size_t _Count,mbstate_t * __restrict__ _State) __MINGW_ATTRIB_DEPRECATED_SEC_WARN; ^ EDIT2: To fix what was wrong Re. Matthieu, I have changed my naive implementation like so: size_t mbsnrtowcs( wchar_t *__restrict__ dst, const char **__restrict__ src, size_t nmc, size_t len, mbstate_t *__restrict__ ps ) { char* local_src = new char[nmc+1]; char* nmcsrc = local_src; strncpy( nmcsrc, *src, nmc ); nmcsrc[nmc] = '\0'; const size_t result = mbsrtowcs( dst, const_cast<const char **>(&nmcsrc), len, ps ); // propagate error if( nmcsrc == NULL ) *src = NULL; delete[] local_src; return result; } And I have added a FIXME saying that the proper way to do this would be implementing it via mbrtowc. A: There is an issue here (not really related to the const I think). mbsrtowcs might set *src to NULL. mbsnrtowcs is supposed to do the same, of course. However for you here it causes a 2 bugs: * *Because you created a local alias, if mbsrtowcs set *src to NULL it is not reflected for the caller of mbsnrtowcs *mbsnrtowcs has a memory leak if nmcsrc is set to NULL Perhaps that simply biting the bullet and implementing mbsnrtowcs in terms of mbrtowc would be more efficient ? If you need to implement both (as I guess you do), you could also reverse the problem on its head and implement mbsrtowcs in terms of mbsnrtowcs simply by calling strlen at the beginning without loss of generality (and avoid the copy). A: There's no problem, since the function expects a more restrictive interface. So you can just cast the pointer: const size_t result = std::mbsrtowcs(dst, const_cast<const char **>(&nmcsrc), len, ps); I'm not sure about restrict; you may need to add that to the cast as well (not on GCC, though) - that's a compiler-dependent matter, though, as there is no restrict in C++.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I stop getting a 'product is undefined' Javascript error in Magento Product page? I have a custom magento store and I though everything was ok but i am having JS errors only on the product pages, and only on IE8! If you view this page in IE8: http://www.guitarfood.com/featured-products/lava-mini-coil-guitar-patch-lead-purple.html You will get a lot of JS errors to do with Magento. I think this is because I am using a jQuery image gallery, and Magento uses prototype. (Even though i have the no conflict set up - and it works as I use a slider on the hoe page with no errors.) I removed this jQuery gallery plug in and the page worked fine. So i thought i would add a prototype based gallery plugin, but then i get a 'product is undefined' JS error in IE8? Here is the other version: http://dev.guitarfood.com/featured-products/planet-waves-pw-vg-01-varigrip.html Ideally i would like to keep the jQuery slider from the original URL. Does anyone have any ideas - i'm all out, and it's driving me mad. A: You may want to try this approach for no conflict instead of inline: Take a look at: http://www.magentocommerce.com/wiki/4_-_themes_and_template_customization/javascript_related/how_to_use_jquery_1.2.6_lastest_with_prototype#jquery
{ "language": "en", "url": "https://stackoverflow.com/questions/7528364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Customizing plone login for two factor authentication I am new to plone and python. But here comes a scenario where i want to customize an existing plone installation login to include two factor auth from Duo-Security. What is the easiest way to accomplish this ? For this requirement,what are the areas i need to explore ? If anyone has done this before,please give me some pointers. A: The authentication in Plone is very flexible and modular. After a short search I found out that there not a product that already provides this kind of auth, so you need to write a custom PAS (Pluggable Authentication Service) plugin. More info: * *http://plone.org/documentation/manual/developer-manual/users-and-security/pluggable-authentication-service *http://plone.org/documentation/manual/developer-manual/archetypes/appendix-practicals/b-org-creating-content-types-the-plone-2.5-way/writing-a-custom-pas-plug-in A: See PlonePAS. Additionally, see the following packages as an example. * *https://github.com/collective/collective.googleauthenticator *https://github.com/collective/collective.smsauthenticator
{ "language": "en", "url": "https://stackoverflow.com/questions/7528368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Mercurial: roll back a patch? I was trying to create a patch for review. I should have done $ diff -u oldfile newfile > tiny.patch, but instead I did hg qnew 404.patch. Now my log looks like this: changeset: 2913:82fc6e8ec5aa tag: 404.patch tag: qbase tag: qtip tag: tip user: xxxxxx date: Fri Sep 23 12:09:53 2011 +0100 summary: [mq]: 404.patch changeset: 2912:87e6ed84fe2f tag: qparent user: xxxxxx date: Fri Sep 23 10:45:10 2011 +0100 summary: Change that I want to keep How can I get rid of the top changeset? I mean delete, kill, remove from history - I just don't want it in the log. hg rollback gives me no rollback information available. Thanks! A: Just run hg qpop -a To pop off the unwanted patch, then hg qdelete 404.patch to delete it, then start again.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528372", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: openLDAP N Way Multimaster Does anyone know what the maximum number of nodes can be configured in a OpenLDAP N Way Multimaster configuration? I have been looking through the internet and all I see in the number of database transactions replicated and not the actual number of nodes that can be used to communicate with each other. A: I have confirmed, there is no limitation in nodes with N way mirror mode configuration in OpenLDAP. Just some information related to mirror-mode, Mirror mode is not Multiple master replication as some people thinks. This is because writes have to go to just one of the mirror nodes at a time. Refer arguments against mirror-mode in http://www.openldap.org/doc/admin24/guide.html#MirrorMode%20replication
{ "language": "en", "url": "https://stackoverflow.com/questions/7528380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error with WCF client when using reference types I am using a WCF driven silverlight application. The web services use reference types such as StringBuilder. However, while passing a StringBuilder or a DateTime object to & from service, the state of the object gets lost. Is it not possible to update the state of the parameter/return type passed through a web service, if so, then what am I missing ? I have verified my application, and my code is working fine otherwise (eg, if I use string or any other primitive types for updation via WCF service) myObj //[myObj Is-A StringBuilder / Has-A StringBuilder, or any other 'reference' object type] referenceObj.MethodAsync(myObj); // pass on to server-ignoring the values for now server end : no ref/out and Simple assignment/append of Value of/inside the object. Object state is updated. //receive in the delegate .. MethodCompletedEventArgs e){ myObj = e.Result; // Expect here,the updated value A: WCF is not remoting. It's only used to transport information back and forth. Update You are still thinking that WCF is a drop in replacement to remoting. Reference types are not transfered with their references as they did in .NET Remoting. They are treated as value types. The object received from the server is NOT the same object as the one existing in the server. Hence, changing the object client side will not change it server side. You need to send it back and update the server-side object manually. A: When passing over a service boundary, the data is essentially copied. Changes made at the other end are entirely lost, and do not go back to the caller. If you want the changes, then either: * *return those values in the response *(in some cases) add ref to the parameter - the engine may use this to propagate the data back to the caller (note that in this case it will swap the object, not merge the changes) (the first of the two is easier to reason about, and will work more consistently) A: When passing over a service boundary, the data is serialized (copied). To ensure your class is serializable, add the [Serialize] keyword to the class. If you are using an object that can't be serialized, the complier will issue an error. As Marc said, WCF is not remoting. Under COM, all data was passed by value, but to "help" out developers, it used underlying mechanism on the return to return the value, then create a reference to it under the covers. Rather than help though, this caused a lot of problems that most developers could never figure out. WCF changed all that, and everything is now passed by value. HTH
{ "language": "en", "url": "https://stackoverflow.com/questions/7528382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to fill parent when drawing on canvas I have a custom view (android) which draws a custom progress bar. I want the progress bar to fill its parent view (width). The problem that I have is that I don't know how the custom view can get its real limits. it needs to know the width limits in order to display different colors in the right ratio. I've implemented onMeasure() in the following way: @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(widthMeasureSpec, 15); } Then, in my onDraw(), when I call getWidth() I get: 1073742246. How can I know the real parent bounds? obviously I did something wrong here... the view layout params are set to MATCH_PARENT/FILL_PARENT and I can draw on the entire area but I don’t know the real width in order to draw the bars in the right proportion. Thanks, Noam A: widthMeasureSpec includes other information than just the width in pixels. It looks like onMeasure is trying to pass you 422px as width with the mode MeasureSpec.EXACTLY. Use MeasureSpec.getSize(widthMeasureSpec); to get the actual width in pixels. For more details, please see http://developer.android.com/reference/android/view/View.MeasureSpec.html A: This value contains the needed width, but it also contains MeasureSpec flags. Use MeasureSpec.getSize() to strip the flags.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I prevent auto scroll to a certain element when I click on that? I have a page where when I click on a menu item, it will load the content using anchor tag navigation. This means I use # on the address bar to prevent loading the whole page using ajax. My problem is that whenever I click on a menu button, before the new content is loaded, the window automatically scrolls to the position of the menu item I clicked. I know this can be "solved" by window.scrollTo(0,0) but I don't want to see scroll jumping around whenever I load a content. note: I have no idea where this is happening so I can't really post my code... A: $('.link').click(function(ev){ //....Ajax stuff ev.preventDefault(); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7528384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: dropdown output my MYSQL data properly using JS function I have a JS/PHP piece of code that selects from a database, does some things with the ID's of the tables and outputs the data in a dropdown. My JS currently appends myfile.php?cat=X&projectID=Y correctly and i'm grabbing the variables correctly, but when I select the second dropdown it doesn't output the name, it only appends the ID to the title and variable.. function reload(form) { var val=form.cat.options[form.cat.options.selectedIndex].value; var val2=form.cat2.options[form.cat2.options.selectedIndex].value; self.location='add-recharge.php?cat=' + val + '&projectID=' + val2; } The PHP <? @$cat=$_GET['cat']; if(strlen($cat) > 0 and !is_numeric($cat)){ echo "Data Error"; exit; } //MYSQL stuff echo "<select name='cat' onchange=\"reload(this.form)\"><option value=''>Select a client</option>"; while($noticia2 = mysql_fetch_array($quer2)) { if($noticia2['clientID']==@$cat){echo "<option selected value='$noticia2[clientID]'>$noticia2[clientName]</option>"."<BR>";} else{echo "<option value='$noticia2[clientID]'>$noticia2[clientName]</option>";} } echo "</select>"; echo "&nbsp;<span class='req'><img src='/images/essentialInput.png' alt='*' title='*' border='0' /></span>"; echo "&nbsp; &nbsp;<span class='label'>Project</span>" . "&nbsp;"; echo "<select name='cat2' onchange=\"reload(this.form)\"><option value=''>Select a project</option>"; while($noticia = mysql_fetch_array($quer)) { echo "<option value='$noticia[projectID]'>$noticia[projectName]</option>"; } echo "</select>"; echo $intClientID; //echo "<br /><br /><br /><br />"; ?> How do I get it to update it with projectName and not reload with 'Select project' ? A: Try using: var val=form.cat.value; var val2=form.cat2.value; EDIT Apologies, I misunderstood the question. You need some form of if/else logic in your PHP similar to that used on the Client select, but dependent on the projectID. Something like: if( $_GET['projectID'] == $noticia[projectID] ){ echo "<option selected value='$noticia[projectID]'>$noticia[projectName]</option>"; } else { echo "<option value='$noticia[projectID]'>$noticia[projectName]</option>"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7528390", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL Select default value in a query from a table I have a query which I want to have a default value from a table (you could call it a vlookup in excel). My query looks like this: select stamdata_sd.id_sd AS id_sd, stamdata_sd.Type_sd AS Type_sd from stamdata_sd; I want the Type_sd field in the query to be a default value from a table called type_ty. Something like this: select stamdata_sd.id_sd AS id_sd, stamdata_sd.Type_sd default(selected from a table called type_ty, where the pk id_ty is the higest) AS Type_sd from stamdata_sd; So, when i make a new record in the query, the field Type_sd is auto filled with the newest instance in the type_ty table. How am I able to write such a query? A: You could use the ANSI-Standard COALESCE function. This function will test its arguments in order, and return the first of them that is not null. It would be something in this shape: select stamdata_sd.id_sd AS id_sd, COALESCE(stamdata_sd.Type_sd, (select max(t.name_of_colum) from type_ty t) ) AS Type_sd from stamdata_sd A: So, when i make a new record in the query, the field type_sd is auto filled with the newest instans in the type_ty table. It seems you want the INSERT statement to grab a particular value from some other table: insert into ZOO(animal) values ( {the most recently added animal in the ANIMALS table} ) One way to grab the most recently added row in a table is to use a TIMESTAMP column, which is updated with the value corresponding to "now" when the row is inserted: create table ANIMALS(id integer primary key autoincrement, animal text, creationdate timestamp) N.B. How databases handle timestamps varies, so treat the above as pseudo-code. insert into ANIMALS(animal) values('lion') would result in something like this: 1, lion, 2011-09-23 08:00:05.123 You can get the most recently added animal like this (assuming that no two records are created at exactly the same millisecond): select animal from ANIMALS where creationdate = (select max(creationdate) from ANIMALS) Thus: insert into ZOO(animal) select animal from ANIMALS where creationdate = (select max(creationdate) from ANIMALS) A: I think this is a really bad design. Your table will always have incorrect data in it. And it will always have some nulls in a column that should probably be NOT NULL. If I were you, I'd try writing a BEFORE INSERT and BEFORE UPDATE triggers to make sure the right data always goes into the base table. You can SELECT the current value from your type_ty table. The use of a BEFORE INSERT trigger is obvious. But you also want to make sure good data goes into that column should a user try to set it to NULL or to an empty string. So you need a BEFORE UPDATE trigger, too. There are also good ways to handle this in client code, after first fixing the data and constraints in the base table. Client code can require a value once a session, which it can use as the current value, or it can remember the last value used and insert it into the user interface (where it might be overtyped with a different value). You could store the current value in a cookie. Lots of ways.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to db:migrate after db:schema:load I have a production db, that I prepare with rake db:create db:schema:load db:seed I also include migrations, when delivering my product, so that existing installations can be updated. After schema:load only the version of the latest migration is stored in schema_migrations, so when I run db:migrate, the migrator tries to run all other migrations that are not yet in schema_migrations. Is there a good way, to deal with this, that does not require me, to collapse migrations (because that is unfortunately out of the question - just like db:migrate as the preparation step)? A: Just don't db:schema:load, pass migrations instead: rake db:create db:migrate db:seed Please keep in mind that in big/long projects passing migrations is a hard way. You should tru to keep your seeds.rb updated and use you way. Old migrations tends to fail because of incompatible model changes (in respect to old migrations) as the project evolutes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Setting font type for live wallpaper causes screen to go black I have this code void drawText2(Canvas c) { DisplayMetrics metrics = new DisplayMetrics(); Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay(); display.getMetrics(metrics); int screenwidth = metrics.widthPixels; int screenheight = metrics.heightPixels; Paint paint = new Paint(); paint.setStyle(Paint.Style.FILL); paint.setColor(Color.BLACK); paint.setTextSize(150); paint.setAntiAlias(true); paint.setTypeface(Typeface.DEFAULT_BOLD); Bitmap.createBitmap(100, 100, Bitmap.Config.RGB_565); float x = screenwidth/2; float y = screenheight/2; c.drawText("32", x, y, paint); } Which works fine, but if I add in the following line Typeface GC=Typeface.createFromAsset(getAssets(),"fonts/ADarling.ttf"); as well as change the line paint.setTypeface(Typeface.DEFAULT_BOLD); to paint.setTypeface(Typeface.create(GC, 0)); It will use the font and everything seems to be working fine, but randomly the wallpaper will go black, and stay that way for a few minutes then it will appear again, and will continue to do this. Am I using the code wrong? A: Try to initialize the font once only(do not load it everytime drawText2() called) private Typeface myFont; public myConstructor() { /* ... */ Typeface GC = Typeface.createFromAsset(getAssets(),"fonts/ADarling.ttf"); myFont = Typeface.create(GC, Typeface.NORMAL); /* ... */ } void drawText2(Canvas c) /* ... */ paint.setTypeface(myFont); /* ... */ } Also the following line is not needed: Bitmap.createBitmap(100, 100, Bitmap.Config.RGB_565); A: Heres a wild stab in the dark:) You should check that your code for setting the font is in the same thread as the initialization code for the font. There are some known issues in this area, especially if you are setting up things in java then usings the NDK to adjust the font. This is because Java and the NDK operate in slightly different threads, and a thread safe memory allocation system is used. Just a thought, which may not apply to you. Tony
{ "language": "en", "url": "https://stackoverflow.com/questions/7528397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sharepoint 2007 to 2010 Upgrade - Visual Problem I migrated the site from sharepoint 2007 to 2010, also did visual upgrade UIversion to 4. When I view some of lists there is still 2007 visual skin, although the others are shown in 2010 skin. What could be the reason? A: The reason is some of the pages are customized so they are unghosted in the database. Try reset to site definition option from Site Settings. You can also build a tool to do it programmatically using these API: SPFile.RevertContentStream http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spfile.revertcontentstream.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7528398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: EF Code First binding to listbox I would appreciate it if somebody could tell me how to bind a listbox to the entity framework (EF code first). I'm using prism and mef. There are two views, one with a button and another with a listbox. (each in their own prism region). By clicking the button I create a new Employee object and insert it to the database via the entity framework. The problem is that my listbox doesn't show me the newly added Employee object in the list. What should be changed to make this work? Some parts of the code: MainView: <Grid> <StackPanel> <TextBlock Text="Hello From MainView (Core Module)" /> <ListBox ItemsSource="{Binding Employees, Mode=TwoWay}"> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding FirstName}" /> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </StackPanel> </Grid> MainViewModel: namespace EmployeeViewer.Core.ViewModels { [Export] [PartCreationPolicy(CreationPolicy.NonShared)] public class MainViewModel : NotificationObject { private IUnitOfWork _UnitOfWork; [ImportingConstructor] public MainViewModel(IUnitOfWork unitOfWork) // IEventAggregator eventAggregator { this._UnitOfWork = unitOfWork; Init(); } private void Init() { this.Employees = new ObservableCollection<Employee>(_UnitOfWork.EmployeeRepository.Get()); //this.Employees = new BindingList<Employee>(_UnitOfWork.EmployeeRepository.Get().ToList()); } public ObservableCollection<Employee> Employees { get; set; } //public BindingList<Employee> Employees { get; set; } } } Get method from GenericRepository: public virtual IEnumerable<TEntity> Get( Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null, string includeProperties = "") { IQueryable<TEntity> query = _DbSet; if (filter != null) { query = query.Where(filter); } foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { query = query.Include(includeProperty); } if (orderBy != null) { return orderBy(query).AsEnumerable();//.ToList(); } else { return query.AsEnumerable();//.ToList(); } } Via an ICommand (implemented as RelayCommand) in another region and view, I create and insert a new Employee object to the Entity Framework code first. public ICommand AddEmployeeCommand { get { return _AddEmployeeCommand; } } private void AddEmployee() { _UnitOfWork.EmployeeRepository.Insert(new Employee() { FirstName = "Test", LastName = "Via cmd" }); _UnitOfWork.Save(); } A: After searching on Bing.com I found out that EF has a Local property. In case you are looking for a solution here is what I did: I added a new Method to my GenericRepository: public virtual ObservableCollection<TEntity> GetSyncedEntityItems() { return _DbSet.Local; } This is the most important part: .Local gives you an ObservableCollection which is in sync with the EF!. In my ViewModel I do this: this.Employees = _UnitOfWork.EmployeeRepository.GetSyncedEntityItems(); And adding a new Employee to the EF will cause my other View to update: private void AddEmployee() { _UnitOfWork.EmployeeRepository.Insert(new Employee() { FirstName = "Test", LastName = "Via cmd" }); _UnitOfWork.Save(); } I don't know if this is the best solution, if there are better options, please do let me know! A: You need to fire INotifyPropertyChanged.PropertyChanged, I assume NotificationObject will have a nice way to do that. When your Employees property goes from null to a list with items, your View needs to be notified so it can update. Once the Employees property is not null, new items added will automatically update the View (b/c of ObservableCollection).
{ "language": "en", "url": "https://stackoverflow.com/questions/7528400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What code in a class should be belongs in the constructor, method I'm new to oop and was trying to understand where the appropriate location to put code in a class is. So far as I understand there's three main areas you can put your code: * *At the beginning of the class (Ex. Instance variables declared at the class level outside of the constructor or methods) *In the Constructor *In the Method What is protocol as far as the type/kinds of code that should go in each of those sections? A: It's kind of up to you. Different patterns / design standards dictate different approaches. Usually, a constructor only 'asks' for the things essential to the object (like a database connection), and store that in properties of the object. In any case, you want to keep your constructor small, and as flexible as possible - you never know in which ways you might use the object in the future! So, while for instance it might seem like a good idea at this time to load some data from your database in the constructor, it's usually better to put these kinds of things in methods, so they can be skipped at will later. A: * *Attributes should only define static or const values directly. Other values can be defined in constructor/methods. *The constructor should only define values that are required for the class/object to work properly (you can also call methods from the constructor). *Methods can define everthing else. *There is also a destructor.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528402", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: suggestions for json Is the correct usage? Which one you need to use. Below I share the sample codes. I need a recommendation for. { "__bc" : 1, "_payload" : null, "_plugin" : [.........], "_debug" : "on", "_content" : [ "html":{<form name=\"signin\" id=\"signin\" action=\"javascript:;\" onsubmit=\"return false\"><label id=\"username\">username:</label> <input type=\"text\" name=\"username\" id="\username\"/></form>} ] } or standart html; <form name="signin" id="signin" action="javascript:;" onsubmit="return false"> <label id="username">username:</label> <input type="text" name="username" id="username"/> </form> A: I would use JSON. You want to keep the markup separate. jQuery has a function .data(key,value) for storing values in the DOM. For example: $('form').data(formdata, {name: "signin", id: "signin"}); This stores a JSON in the form element. It is retrieved by specifying the key: $('form').data(form data); //returns {name: "signin", id: "signing"} You should get the general idea from this example. The documentation for .data(key,value) is here. Hope this helps. A: here you can validate your json. Your's is not valid. This should be valid: { "__bc": 1, "_payload": null, "_plugin": [], "_debug": "on", "_content": { "html": "<formname=\"signin\"id=\"signin\"action=\"javascript: ;\"onsubmit=\"returnfalse\"><labelid=\"username\">username: </label><inputtype=\"text\"name=\"username\"id=\"username\"/></form>" } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7528403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: iOS in-app purchase item not returned in products but only in invalidProductIdentifiers in sandbox. How to debug? I am adding in-app purchasing to my app. I have followed all the steps that Apple outlines here (http://developer.apple.com/library/ios/#technotes/tn2259/_index.html see Q&A #6 especially) as well as in the In-App Programming Guide. The problem is that when I send a product request in during testing on my test iPod Touch, the response shows it in the invalidProductIdentifiers and not a valid product. My App does have a specific non wild card App ID. My profile I am using to sign the app has the App ID explicitly in it and does not use a wild card. The in-app purchase item is a standard non-consumable non-subscription item (enabling enhanced functionality). I added it in the store as an in-app item for my app. It has been set to be cleared for sale. (It is at state "waiting for screen shot upload"). I copied and pasted the in-app item id from iTunes Connect and pasted it into my app to make sure that I did not spell anything wrong. I have searched on StackOverflow and using Bing and Google for clues on how to diagnose this problem and basically all the answers were to check the app id, item id, signing profile, etc. No error is being returned and the product request successfully completes so there is no NSError object to query. How can one diagnose the problem and debug this? Thanks A: One thing to check that you didn't mention: Did you install the build by running from Xcode with your device connected via USB? You can't connect to the sandbox store using an ad hoc deployment. If you haven't already, take a look at Troy Brandt's exhaustive list of invalid product ID issues. A: Deleted the app. It worked instantly in my case! A: I just found a quick way to solve the invalid product ID problem, at least to my case after I've tried Troy Brandt's exhaustive list of invalid product ID issues, but still get 2 invalid product ids out of 4. The solution is to delete all IAP and restart with different IAPs, withe brand new reference IDs and product IDs, then I deleted the app in testing device. After these, everything worked. Apple should be shamed to make IAP so difficult to implement.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: CSS 100% height problem I'm working on a new template and I'm having a 100% height issue, tried various style combinations but cant get it to work. Here is the link, the light beige area should extend below the end of the left content but it doesn't. What's messing my layout up? It's probably a clearing issue but how & where? Thanks. A: that's because 100% is relative to the viewport, you want it to be relative to the document. you need to add an element and clear:both, after the page's div, and remove the height:100% A: OK first off, you have four declarations for the stylesheets, they only need to appear once in the head section of your page. What I suggest you do as an overall approach on div layouts is sketch out the containers you want with a 1 pixel coloured border, then, using firebug and firefox you can adjust the design to how you want dynamically and see how it behaves. Once you have that down, refine it and add your images.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528411", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How I can run MessageBox.Show() from App.xaml.cs Can I run MessageBox.Show() from App.xaml.cs, so it is shown on current page. Please provide some code to this solution, or some other solution. I need to show some system message which is relevant for whole application. A: Not sure, but would this not work? Deployment.Current.Dispatcher.BeginInvoke(() => { MessageBox.Show(""); } ); You could also use the navigation data that is available in App.xaml.cs to determine the current Page and execute on that page. I guess whatever you come up with, the app needs to be in a stable state, you probably can't do this when your handling (unhandled) exception. You should tell us a bit more so we understand why you want to do this. It seems that seomthing is wrong with your setup if you have to call MessageBox.Show from App.xaml.cs A: A simple approach would be... public partial class App : Application { public static void ShowBox(string msg) { MessageBox.Show(msg); } } And then from a window, or any other part of your application... public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); App.ShowBox("Hello!"); ... Since the 'ShowBox' method is static, you can just call into it from anywhere. Of course it goes without saying that this isn't really the 'cleanest' or most robust approach, but it will work. A: What I understood from your question is you are looking for a way to display message from App.xaml.cs when some event occurs else where in your application. You can have observer pattern implemented with App.xaml.cs registered for an event which may be triggered by your custom page. Having said that, in long run I suggest you to use messaging framework for this purpose. Most of the MVVM frameworks come with messaging framework. They are easy to use with no or little learning curve. * *MVVM Light *Simple MVVM *PRISM from MS patterns & practices. (for larger applications) This is Not just an MVVM framework. *Ultra light MVVM there are many more such frameworks. A: I used this extract from this link http://www.c-sharpcorner.com/UploadFile/c25b6d/message-dialog-in-windows-store-apps/ private async void Delete_Click(object sender, RoutedEventArgs e) { var messageDialog = new Windows.UI.Popups.MessageDialog("Are you sure you want to permanently delete this record?"); messageDialog.Commands.Add(new UICommand("Yes", (command) => { //Do delete })); messageDialog.Commands.Add(new UICommand("No", (command) => { //Do Nothing })); //default command messageDialog.DefaultCommandIndex = 1; await messageDialog.ShowAsync(); } A: Had no luck with the other solutions, found: CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync Works on windows phone 8.1 for calling a MessageDialog to ui thread from App.xaml.cs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528415", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: JavascriptObject to string gwt I have become a great fan of the JavaScriptOverlayTypes. so lets say, I have the followin JSON object: { "product": { "name": "Widget", "prices": { "minQty": 1, "price": 12.49 } } } So I write my class for products and one for prices. Now if somethings wents wrong when analysing the "price JavascriptObject", I want to print it as the following: { "minQty": 1, "price": 12.49 } but I havent found a possibilty yet to confert the "price JavascriptObject" backt to a string. Is there a possibilty to do this? Regards, Stefan A: new JSONObject(priceJso).toString() Beware of performance thugh, as it'll create a JSONValue object for each property of the object (and recursively of course), and I'm not sure the GWT compiler is able to optimize things much. In your case, as an "error path", it should be OK though. A: JsonUtils has a nice function for it: String jsonString = JsonUtils.stringify(priceJson); Which has the native implementation: public static native String stringify(JavaScriptObject obj) /*-{ JSON.stringify(obj); }-*/;
{ "language": "en", "url": "https://stackoverflow.com/questions/7528416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How this document is able to detect a cookie when it didn't set at all? This is one script that sets the cookie with some html file. window.onload=init; function init() { var userName=""; if(document.cookie != "") { username=document.cookie.split("=")[1]; document.getElementById("name_field").value = username; } document.getElementById("name_field").onblur = setCookie; } function setCookie() { var exprDate = new Date(); exprDate.setMonth(exprDate.getMonth() + 6); var username = document.getElementById("name_field").value; document.cookie = "username=" + username + ";path=/;expires=" + exprDate.toGMTString(); } This is another script with some different html file, (that had not saved a cookie in the past) that checks if there is a cookie saved with this document. window.onload = initTest; function initTest() { if(document.cookie == "") alert("No,cookies stored !"); else alert("cookies found !"); } To my surprise the result when i run the 2nd html file with the second script,is cookies found Why is that ? When that document has not saved a cookie then how come document.cookie != "" ? A: Cookies are set per domain and/or path. Examples: * *http://www.example.com/foo.html Cookie: x=x; max-age=3600; is visible at http://www.example.com/*, but not at http://other.example.com/ *http://www.example.com/foo.html Cookie: x=x; max-age=3600; domain=.example.com is visible at http://*.example.com/* and http://example.com/* *https protocols-only: Cookie: x=x; max-age=3600; secure *The path can be changed to the current path, or any parent directory. The default path is the current directory. E.g.: x=x; max-age=3600; path=/
{ "language": "en", "url": "https://stackoverflow.com/questions/7528422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: dynamically href link to next sibling on ul tree Im using Javascript, but not Jquery or other frameworks. Id rather lose the weight as there are only a few functions in the program. I am trying something a bit like this guy: Get the next href in a list in another file with jQuery? I will have a load of separate HTML pages but they will be linked to their Siblings. I am basically looking for a dynamic way to do previous and next links for each page, to link to their siblings. For example: <ul><li>1 <ul><li>a</li> <li>b</li></ul></li> <li>2 <ul><li>c</li> <li>d</li></ul></li> <ul> If Im on page b the next will take me to c. And if I'm on c the same button will take me to d etc. I should be able to generate the href for the next page using something form this page: How to get first href link of li in a ul list in jQuery For example var url = $("ul a:eq(0)").attr("href"); But how would I find some sort of .this in the < ul > tree the page Im on right now, so I know to go to the next link? Is there some sort of find this html on ul ? A: Break the problem down: * *Analyse what page you're on (possibly using the window.location object) *Find that node in the menu *Find the next and previous nodes *Generate your links
{ "language": "en", "url": "https://stackoverflow.com/questions/7528426", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: pdo_mysql error suddenly appears on drupal based website? My drupal based website was working fine till yesterday but suddenly from no where today an error appeared Fatal error: Undefined class constant 'MYSQL_ATTR_USE_BUFFERED_QUERY' in /.../includes/database/mysql/database.inc on line 43 I didn't even changed or updated anything since yesterday, it suddenly appears from no where, before that it was working fine On line 43 of database.inc this was written PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => TRUE, I googled and got some idea that this is some sort of PDO_MYSQL error, i have not much idea why this error suddenly arrived Can anyone please help me out Additional information * *Linux Shared Webhosting *DRUPAL 7 *Apache version 2.2.20 *PHP version 5.2.17 *MySQL version 5.0.92-community-log *cPanel Version 11.30.3 (build 5) A: According to a lot of different sources the pdo_mysql extension must be missing from your PHP installation. Either add it in php.ini or ask your hosting provider to do it for you. Links: * *Fatal error in D7 HEAD while running 'drush update' *Drupal 7: PHP fatal error 'Undefined class constant MYSQL_ATTR_USE_BUFFERED_QUERY' when trying to install on MySQL database * Fatal Error: Undefined class constant 'MYSQL_ATTR_USE_BUFFERED_QUERY' They all say the same thing...install the pdo_mysql extension. Sounds like your hosting provider has disabled it! A: This can also be due to a permissions issue. Sometimes, given the use of SuPHP or other configurations in which the apache (or other server) user can't run a file, you'll get this sort of error and PDO_MYSQL: will already be installed and operational. If you have root access to the box, try doing a sudo php /path/to/your/php/script.php or recursively chown the directory to the appropriate apache user (usually apache or www-data) or the user who's home directory your files are resting in (the case in most shared servers). chown -R apache:apache /path/to/web/files A: I had exactly the same problem. My site suddenly went down. I started looking at installing php extension php_pdo_mysql.dll from cPanel PHP PEAR as suggested above, but this failed. I started a live chat with my host (Justhost) and it tuned out they had upgraded their php version. They fixed it in 2 minues.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528428", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Array Sorting using array $sortPattern= array(1,2,8,4); $toSort = array(2,4,8,18,16,26); Now, we have to sort $toSort array according to $sortPattern. We should have the result $result = array(2,8,4,18,16,26); Does anyone know the function to do this, or should we have to write our own function to perform this? A: Yes, you would have to write your own sort function, and apply it with usort(). In your callback, you would do something like: if ( $a == $b ) { return 0; } elseif ( array_search( $a, $sortPattern ) < array_search( $b, $sortPattern ) { return -1; } else { return 1; } A: What influence does $sortPattern have on $toSort ? It looks like maybe: $result = array_merge( array_intersect($sortPattern, $toSort), // 2, 8, 4 array_diff($toSort, $sortPattern) // 18, 16, 26 );
{ "language": "en", "url": "https://stackoverflow.com/questions/7528429", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: xCode3 and run-time errors line highlighting? I'm used to xCode 4, but I need to use xCode 3 for a project. when I get a run-time error, xcode3 doesn't highlight the code line where the issue is. Shouldn't it show me instead ? Check this screenshot: I've written this code to make the app to crash and I'm stepping forward with the debugger. The current code is highlighted, but if I step over further, I don't see any line highlighted. A: Try turning on NSZombieEnabled, malloc stack logging, and guard malloc (env variable, or by checking the boxes in the xcode debug menu and it should give you a lote more usefuly info about the exception. Check out this article for more info on NSZombieEnabled. This one for MallocStackLogging info More info on guard malloc here Sometimes exceptions dont break at the bad line of code because the message causing the error isnt actually where the problem takes place, it usually throws the exception somewhere in the framework code, which is why you will see a bunch of assembly when gdb finally pauses execution. If this happens, you can run: (gdb) info malloc-history 0x123456 Where 0x123456 is the address of the object that gets sent a message after being released, and it will display a much more helpful stack trace.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Windows Azure Service Bus - A general question Lets say I have a Silverlight application that currently talks to a WebRole in Windows Azure. Is the Silverlight application also able to directly talk to the service bus without a "controller" component which takes the commands coming from the client and routes them to the worker roles in the Service bus? A: The Silverlight application is able to communicate with the Service Bus directly as stated here: http://www.microsoft.com/windowsazure/features/servicebus Support of REST and HTTP Access from non-.NET platforms But I'm not sure you want to let your Silverlight app do that, because on the very same page there is the price list for concurrent connections starting at 3.99$ per connection. EDIT: As Clemens Vasters commented below, there are changes to the price model for connections. More info here: http://msdn.microsoft.com/en-us/library/windowsazure/hh667438.aspx#BKMK_SBv2FAQ2_1 A: The Service Bus Samples include a sample on how to use SB within a Silverlight application.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: .Net load file or assembly error I am trying to run a .Net application's .exe file from bin/Debug folder but it gives me an error like Cannot load file or assembly "Mysql.Data version=6.2.2.0",culture=neutral publicKeyToken=c5.... or one of its dependencies.The system cannot find the file specified" I haven't worked on .Net before can anyone help ??? A: It tells you the problem; it can't find Mysql.Data.dll. There are two (main) ways it can get this: * *installed into the GAC (a pain to do, frankly) *in the same folder (bin/Debug in this case) to achieve the latter, simply expand "references" in the solution explorer, find Mysql.Data, and then (in the properties pane) ensure "Copy Local" is set to "True". Then rebuild, and the file should appear. A: maybe you need to install the mysql connector. it also intalls everything you need into the gac. you can download it here http://www.mysql.com/downloads/connector/net/6.3.html#downloads cheers
{ "language": "en", "url": "https://stackoverflow.com/questions/7528435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: UI Thread Block I have created a simple WPF Application and added a button to the default window. When I click on the button, a simulated long working method(simulated using a Thread.Sleep(15000) is called. I am trying to make the button execute asynchronously however despite following online examples, the button and entire window locks as soon as I click and remains so until the Thread.Sleep(...) finishes. Any ideas why this is happening? Here is the code: private void button1_Click(object sender, RoutedEventArgs e) { DoSomeAsyncWork(); } private void DoSomeAsyncWork() { System.Windows.Threading.Dispatcher.Run(); Thread thread = new System.Threading.Thread( new System.Threading.ThreadStart( delegate() { Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => Thread.Sleep(15000))); } )); thread.Start(); } A: By using BeginInvoke you are actually executing the code on the UI thread. You only need to use this when you are updating your UI from the background worker thread. If you simply have: Thread thread = new System.Threading.Thread( new System.Threading.ThreadStart( delegate() { Thread.Sleep(15000); } )); I think it will work. However, you aren't raising a "Work Completed" event so you have no way of knowing when (or indeed if) the thread has finished. Look into the BackgroundWorker class. This does a lot of the heavy lifting for you. You just need to plug in your code to the DoWork method. A: You are putting the long operation back into the UI thread. Let me comment your example: Thread thread = new System.Threading.Thread( new System.Threading.ThreadStart( delegate() { // here we are in the background thread Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => { // here we are back in the UI thread Thread.Sleep(15000); })); } )); So, you should modify your example like this: Thread thread = new System.Threading.Thread( new System.Threading.ThreadStart( delegate() { // here we are in the background thread Thread.Sleep(15000); // <-- do the long operation here Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => { // here we are back in the UI thread // do stuff here that needs to update the UI after the operation finished })); } )); As others have mentioned, it's easier to use the BackgroundWorker class. Here's an example: private void DoSomeAsyncWork() { BackgroundWorker bw = new BackgroundWorker(); bw.DoWork += (sender, args) => { // do your lengthy stuff here -- this will happen in a separate thread Thread.Sleep(15000); } bw.RunWorkerCompleted += (sender, args) => { if (args.Error != null) // if an exception occurred during DoWork, MessageBox.Show(args.Error.ToString()); // do your error handling here // do any UI stuff after the long operation here ... } bw.RunWorkerAsync(); // start the background worker } A: You should use BackgroundWorker. * *http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx *http://www.tanguay.info/web/index.php?pg=codeExamples&id=232
{ "language": "en", "url": "https://stackoverflow.com/questions/7528437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Can the ordinary android view extend with GLSurfaceView? I am trying to use the GLSurfaceView to draw image in my android ordinary view. But I heard that the a view can't extends other view. Really, Can I do this? A: To avoid the diamond problem, the Java language only allows you to extend one class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528438", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: MongoDB-Native NodeJS Update Fails I have a MongoDB 2.0 install along with NodeJS 0.4.11 and I'm trying to do upserts into a database. Here's the code: var mongo = require('mongodb'); var db = new mongo.Db('db', new mongo.Server('localhost', 27017, {}), {}); var updatecmd = JSON.parse(JSON.stringify("{ id : " + jsonObj.VisitorID + "}")); console.log(updatecmd); var insertObject = JSON.parse(JSON.stringify(temp)); col.update(updatecmd, insertObject, {upsert:true}, function(err, r){console.log(err.stack); console.log(r);}); col.save() works just fine, but when I change it to col.update, I get the following error: TypeError: Object.keys called on non-object at Function.keys (native) at Function.calculateObjectSize (/home/admin/node_modules/mongodb/lib/mongodb/bson/bson.js:76:34) at [object Object].toBinary (/home/admin/node_modules/mongodb/lib/mongodb/commands/update_command.js:43:112) at [object Object].send (/home/admin/node_modules/mongodb/lib/mongodb/connection.js:257:32) at [object Object].executeCommand (/home/admin/node_modules/mongodb/lib/mongodb/db.js:746:18) at Collection.update (/home/admin/node_modules/mongodb/lib/mongodb/collection.js:421:26) at addtoobject (/home/admin/mongoscript.js:127:9) at /home/admin/mongoscript.js:103:4 at EventEmitter.<anonymous> (/home/admin/node_modules/lazy/lazy.js:62:13) at EventEmitter.<anonymous> (/home/admin/node_modules/lazy/lazy.js:46:19) I get that error for every single piece of content. When I do col.save(insertObject, function(err,r){}); It works just fine. A: Not 100% sure if this is the issue, although it looks likely: var updatecmd = JSON.parse(JSON.stringify("{ id : " + jsonObj.VisitorID + "}")); This will output a string, not an object. Drop the call to stringify, or better still just build the object. E.g.: var ID = 123, oldupdatecmd = JSON.parse(JSON.stringify("{ id : " + ID + "}")), // "{id : 123}" newupdatecmd = { id : ID }; // {id : 123} <-- An Object, not a string Pretty sure the first parameter is supposed to be an object, and that's what the error looks like: Object.keys called on non-object
{ "language": "en", "url": "https://stackoverflow.com/questions/7528440", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iPhone Detect Volume Keys press. I need to detect when the user presses the hardware volume keys, (App Store safe approach) I have tried a number of things with no luck. Do you know how to implement such functionality? At present I am registering for notifications, however they don't seem to get called. Here's my code: AudioSessionInitialize(NULL, NULL, NULL, NULL); NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; [notificationCenter addObserver:self selector:@selector(volumeChanged:) name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil]; And the receiver method is: -(void)volumeChanged:(NSNotification *)notification{ NSLog(@"YAY, VOLUME WAS CHANGED");} Any tips would be greatly appreciated. A: You need to start an audio session before the notification will fire: AudioSessionInitialize(NULL, NULL, NULL, NULL); AudioSessionSetActive(true); Now you can subscribe to the notification: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(volumeChanged:) name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil]; To get the volume: float volume = [[[notification userInfo] objectForKey:@"AVSystemController_AudioVolumeNotificationParameter"] floatValue]; You will need to store the volume and compare it to the previous value you got from a notification to know which button was pressed. This solution will still adjust the system volume when the user presses the volume key, and show the volume overlay. If you want to avoid changing the system volume and showing the overlay (in essence completely repurpose the volume keys), see this answer
{ "language": "en", "url": "https://stackoverflow.com/questions/7528443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Foreign key from bit to int Is it possible to create a foreign key where type of the first column is bit but type of the referenced column is int? A: No. create table X ( c int primary key ) create table Y ( c bit references X ) Returns: Msg 1778, Level 16, State 0, Line 1 Column 'X.c' is not the same data type as referencing column 'Y.c' in foreign key 'FK__Y__c__34C8D9D1'. Msg 1750, Level 16, State 0, Line 1 Could not create constraint. See previous errors. Also see the relevant section in BOL: * *The REFERENCES clause of a column-level FOREIGN KEY constraint can list only one reference column. This column must have the same data type as the column on which the constraint is defined. *The REFERENCES clause of a table-level FOREIGN KEY constraint must have the same number of reference columns as the number of columns in the constraint column list. The data type of each reference column must also be the same as the corresponding column in the column list.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Add a module (not package) to buildout for Plone Is there a way to add a simple module (e.g. mymodule.py) which resides in the src/ directory to buildout for Plone 4? To be more specific, I have a former module I used as an ExternalMethod in Plone 2.5, and I'm trying to use it in Plone 4 without creating a package or using paster and creating an egg. How would I do this? A: See http://pypi.python.org/pypi/plone.recipe.zope2instance You can just the extra_paths option. That would allow it to be imported from other code. A: You have three options: * *you could put it in a skin layer and use it with the Aquisition. But, if you used to use it as an ExternalMethod, I suppose it needs to be executed by a not-restricted python *make a package using the paster template "plone" for a basic package. *put it into /<buildout-root>/parts/instance/Extensions or /<buildout-root>/parts/client1/Extensions You can find a similar question here. edit: it turns out that the last option is not suitable...so you have only 2 options + the one from @djay
{ "language": "en", "url": "https://stackoverflow.com/questions/7528450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to get the X509Certificate from a client request I have a web-service which I secured using certificates. Now, I want to identify the client by looking at the certificate thumbprint. This means that I have a list of thumbprints on my service somewhere that are linked to some user. Actually, my first question (a little off-topic) is: is this a good approach or should I still introduce some username password construction? Second question is: how can I get the certificate that the client used to connect to the web-service so I can read the thumbprint at the service side. I did read a lot about it (like this post:How do I get the X509Certificate sent from the client in web service?) but could not find an answer. I have no HTTPContext, so that is not an option. In the post mentioned above is spoken about Context.Request.ClientCertificate.Certificate but I guess they mean the HTTPContext there as well. Also adding <serviceHostingEnvironment aspNetCompatibilityEnabled="true" /> to the web.config is also not an option. A: I don't think there is anything wrong with this approach, as long as this service is used in an environment where you can control certificate distribution and ensure they are stored securely. Assuming this is a WCF service, you can get the certificate the client is presenting using a class that inherits from ServiceAuthorizationManager. Something like this will do the job: public class CertificateAuthorizationManager : ServiceAuthorizationManager { protected override bool CheckAccessCore(OperationContext operationContext) { if (!base.CheckAccessCore(operationContext)) { return false; } string thumbprint = GetCertificateThumbprint(operationContext); // TODO: Check the thumbprint against your database, then return true if found, otherwise false } private string GetCertificateThumbprint(OperationContext operationContext) { foreach (var claimSet in operationContext.ServiceSecurityContext.AuthorizationContext.ClaimSets) { foreach (Claim claim in claimSet.FindClaims(ClaimTypes.Thumbprint, Rights.Identity)) { string tb = BitConverter.ToString((byte[])claim.Resource); tb = tb.Replace("-", ""); return tb; } } throw new System.Security.SecurityException("No client certificate found"); } } You then need to change your configuration at the server to use this authorization manager: <system.serviceModel> <behaviors> <serviceBehaviors> <behavior name="MyServerBehavior"> <serviceAuthorization serviceAuthorizationManagerType="myNamespace.CertificateAuthorizationManager, myAssembly"/> ... </behavior> </serviceBehaviors> </behaviors> ... </system.serviceModel> A: this is how we do this in the constructor of our webservice: if (OperationContext.Current.ServiceSecurityContext.AuthorizationContext.ClaimSets == null) throw new SecurityException ("No claimset service configured wrong"); if (OperationContext.Current.ServiceSecurityContext.AuthorizationContext.ClaimSets.Count <= 0) throw new SecurityException ("No claimset service configured wrong"); var cert = ((X509CertificateClaimSet) OperationContext.Current.ServiceSecurityContext. AuthorizationContext.ClaimSets[0]).X509Certificate; //this contains the thumbprint cert.Thumbprint
{ "language": "en", "url": "https://stackoverflow.com/questions/7528455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: CSS styling BODY tag issue I havent done any CSS / HTML development in a long time and im having some issues with styling the body tag using CSS. What im aiming to do is have the HTML tag styled with a background colour, then styling the body tag to be 80% width and a different background colour which all works fine. The problem is that the background colour only goes one screen height down then ends and I cant seem to figure out why! My CSS is: body { width: 80%; margin-left:auto; margin-right: auto; min-height:100%; height:100%; background-color: #FFFFFF; border-radius: 20px; -moz-border-radius: 20px } html { background-color: #000000; height: 100% } header,nav,article { display: block } nav { float: left; width: 20% } article { float: right; width: 79% } Any suggestions would be great, thanks. EDIT: After all the suggestions here the best result i could get with my CSS looks like this: #content { width: 80%; margin-left:auto; margin-right: auto; height:100%; min-height:500px; background-color: #FFFFFF; border-radius: 20px; -moz-border-radius: 20px; } html,body { background-color: #000000; margin:0; padding:0; height: 100%; } header,nav,article { display: block } nav { float: left; width: 20% } article { float: right; width: 79% } Its still not doing what I want but this is the CSS that works best with the wrapper so far A: the background colour only goes one screen height down then ends and I cant seem to figure out why! Here's why: body { height:100%; } html { height: 100%; } Ask yourself: 100% of what? The answer is not 100% of the content. Percentage heights always refer to a percentage of the height of the parent element. Since you have not set any explicit heights (in pixels), the browser uses the height of the viewport and calculates the height body to be 100% of that. The viewport is the viewable area inside your browser. Since your content extends below this area (i.e., you have to scroll down to see it all), it ends up outside the body and therefore outside the background color set on the body. If you don't specify a height for html or body, they will only be as tall as the content, but the background for html will still fill the viewport. So the solution is this: html { height:100%; /* sets html to height of viewport (bg color will still cover viewport) */ } body { /* don't set explicit height */ min-height:100%; /* expands body to height of html, but allows it to expand further if content is taller than viewport */ } You don't need any additional content elements; the body behaves like any other element. Only html is a bit different since its background-color will cover the whole viewport even if the calculated height is different from the viewport or any child elements. You may need some hacks to handle older browsers that don't understand min-height. A: This is the case because you've explicitly set the height of the body element to 100%; you only need the min-height attribute if it should always be at least one screen high. I would also not resize the body element to 80% width, I'd rather use a element inside the body for this. A: There might be a few issues: Firstly, try swapping min-height and height because by setting height after min-height you are effectively overriding min-height. Secondly, check your browser, ie 7 and below I belive don't support min-height, try w3schools examples to see if theirs work properly on your browser. Thirdly, you may want to wrap your content in either content tabs for html5 (with ie hack) or in a div class="content" because ie. again won't display the body tag correctly. Lastly, I'd set min-height to an arbritary amount for example 500px because 100% will just make sure it is large enough to hold the content within. height: 100%; min-height: 500px; A: Give the body only a background color and put a wrapping div around your content. Styling this wrapping div is the better way if you want center the complete content as set bodies width to 80%. The way with the wrapping div makes the round corner also easier. An example of the resulting html: <body> <div id="wrapper"> .... Your content .... </div> <!-- end of #wrapper --> </body>
{ "language": "en", "url": "https://stackoverflow.com/questions/7528460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to keep something shown while hovering over a div? (jQuery) I'm having trouble with jQuery. Please have a look at this page. I've created a sliding image viewer which when hovered over shows a div with the class "paging". The problem I'm having is I want the div to be shown when hovering over it as well, as it now doesn't. This is the javascipt which makes the div appear: (I removed two irrelevant lines from this code) $(".image_reel a").hover( function() { $(".paging").fadeIn('fast'); }, function() { $(".paging").fadeOut('fast'); }); Any ideas? Thanks for the help. A: You have to clear the animation queue to avoid the "blinking" http://api.jquery.com/clearQueue/ A: you could try: $(".image_reel").hover(/*...*/); that should work if the .paging is inside the .image_reel
{ "language": "en", "url": "https://stackoverflow.com/questions/7528463", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to access getSharedPreferences from another class? I have build 2 projects my main one and a twitter posting one. I have imported the twitter one into the main and am now trying to hook it up. Below is the import code. The problem is I know I am missing something possibly to do with the context? I have just summarised what is contained in my main project below so you understand better (Hopefully). import com.tweet.t.TweetToTwitterActivity; TweetToTwitterActivity twitter = new TweetToTwitterActivity(); twitter.buttonLogin(v); Here is the TweetToTwitterActivity public class TweetToTwitterActivity extends Activity { private SharedPreferences mPrefs; /** Twitter4j object */ private Twitter mTwitter; private RequestToken mReqToken; public void buttonLogin(View v) { mPrefs = getSharedPreferences("twitterPrefs", MODE_PRIVATE); // Load the twitter4j helper mTwitter = new TwitterFactory().getInstance(); // Tell twitter4j that we want to use it with our app mTwitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET); if (mPrefs.contains(PREF_ACCESS_TOKEN)) { Log.i(TAG, "Repeat User"); loginAuthorisedUser(); } else { Log.i(TAG, "New User"); loginNewUser(); } } The Logcat produces this error 09-23 11:27:40.034: ERROR/AndroidRuntime(229): java.lang.NullPointerException 09-23 11:27:40.034: ERROR/AndroidRuntime(229): at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:146) 09-23 11:27:40.034: ERROR/AndroidRuntime(229): at com.tweet.t.TweetToTwitterActivity.buttonLogin(TweetToTwitterActivity.java:74) and point to this line. mPrefs = getSharedPreferences("twitterPrefs", MODE_PRIVATE); A: getSharedPreferences() is a method of the Context class. You are just creating an instance of TweetToTwitterActivity which extends Activity but this activity is not presently started. One way to solve this will be to pass a Context object also to buttonLogin: Change public void buttonLogin(View v) to public void buttonLogin(View v, Context context) and mPrefs = getSharedPreferences("twitterPrefs", MODE_PRIVATE); to mPrefs = context.getSharedPreferences("twitterPrefs", MODE_PRIVATE); and twitter.buttonLogin(v); to twitter.buttonLogin(v, this); A: Hemant is right. mPrefs = getSharedPreferences("twitterPrefs", MODE_PRIVATE); for doing this you need TweetToTwitterActivity Activity and not just an instance. So an Activity never gets created when you use new keyword. only OS can create an Activity for ya. so twitter.buttonLogin(v, YourCurrentActvity.this); and public void buttonLogin(View v, Context context) { mPrefs = context.getSharedPreferences("twitterPrefs", MODE_PRIVATE); // Load the twitter4j helper mTwitter = new TwitterFactory().getInstance(); // Tell twitter4j that we want to use it with our app mTwitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET); if (mPrefs.contains(PREF_ACCESS_TOKEN)) { Log.i(TAG, "Repeat User"); loginAuthorisedUser(); } else { Log.i(TAG, "New User"); loginNewUser(); } } A: try to pass like this twitter.buttonLogin(v,Activityname.this) then in called function change like this public void buttonLogin(View v,Context this) { this.getSharedPreferences("twitterPrefs", MODE_PRIVATE); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7528470", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Please suggest ways to start building Business Analytics solutions using existing mysql databases I believe there are three layers to build up- 1) Presentation Layer/Data Visualization Layer 2) Constucting olap server(like mondrian) to access mysql database and produce results. 3)Using Olap Client API(olap4j) to build OLAP cubes that store intermediate data. Is this approach correct or is there any thing wrong with it? Please suggest. Thanks in Advance A: Not quite. * *Build your data warehouse to Kimball standards. (Using ETL e.g. PDI/Kettle) *Create your mondrian schema using schema workbench *Get a BI Server up and running and publish your schema. You can then publish your schema and start doing analytics. *Optional but recommended - Install Saiku. If you can't do option 1 then Mondrian isnt for you. However you may be able to fake-up a kimball style schema with db views etc, but it wont work well for large amounts of data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528473", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C++ object instantiation and scope I'm coming (very recently) from C#, where I am used to instantiating objects like this: Phone myPhone = new Phone(); simply writing Phone myPhone; essentially creates a holder for a class, but it is yet to be initialised so to speak. now I'm writing a small class in C++ and I have a problem. Here is the pseudo code: Phone myPhone; void Initialise() { myPhone = new Phone(); } void DoStuff() { myPhone.RingaDingDong(); { In fact this is a little misleading as the above code is what I would LIKE to have, because I want to be able to put all my initialisation code for lots of things into one neat place. My problem is that the line inside initialise is unnecessary in C++, because before that, a new instance is already created and initialised by the very first line. On the other hand if I put the just the first line inside Initialise() I can no longer access it in DoStuff. It is out of scope, (not to mention the differences between using 'new' or not in C++). How can you create simply a holder for a class variable so I can initialise it in one place, and access it in another? Or am I getting something fundamentally wrong? Thanks in advance! A: You can use the new operator on a pointer: Phone *myPhone; void Initialise() { myPhone = new Phone(); } void DoStuff() { myPhone->RingaDingDong(); } The only two changes are the added * in the declaration of myPhone and the -> instead of . when accessing RinaDingDong(). You will also have to free it since new is allocating memory: void destroy() { delete myPhone; } Note that if you do this myPhone will be a pointer to a Phone not an actual Phone. A: If your Phone constructor takes no parameters then your life is pretty simple - you don't need to new up the phone in the Initialize method. It will be created for you when the object is created and the lifetime will be managed for you. If you need to get parameters to it, and it doesn't have an Initialize() method or some set methods, then you may need to use a pointer (which can sometimes be null) and have Initialize() call new and pass in those parameters. Your other code needs to check if the pointer is null before using it. Also you need to manage lifetime (by writing the big 3) or use a smart pointer such as shared_ptr from C++11. This should not be your first choice. A: I think you need to brush a bit on pointers. What you are trying to do is possible with pointers. My problem is that the line inside initialise is unnecessary in C++, because before that, a new instance is already created and initialised by the very first line. This is incorrect. The comment provided by you only holds good for constructors. From your puesdo code, the function initialize is a global function and is not a member function of a class. On the other hand if I put the just the first line inside Initialise() I can no longer access it in DoStuff. It is out of scope, (not to mention the differences between using 'new' or not in C++). Please refer any book on pointers, you can have a global pointer and initialize with new. This can be used in doStuff A: If your coming from C#, you know that you have two types of object: class and struct. The class are copied, assigned and passed to function by reference. So, they are using a reference semantic. The class are also allocated in the heap (using new). The struct are implementing a value copy semantic. Struct are allocated on the stack (int, double and other built-in type are struct). You cannot treat struct polymorphicaly. In C++ you haven't got this difference. Class and struct are essentially the same (a part the default access level). It is not the declaration of the class to determinate the copy semantic but it is the declaration of the instance to a class. If you create a pointer the behaviour is very similar to a class in c#. If you create an object the semantic will be similar to a struct in c#. C++ has also reference, you should read about the difference between pointers and references. A: Kate Gregory's answer is the right one, but I wanted to elaborate a little bit. One of the more powerful ideas in C++ is that stack-allocated objects are owned by their containing scope. For example, if you want to write a class which contains a phone, you'd just write this: class Secretary { Phone myPhone; }; And now every time a Secretary is created, a Phone object is automatically initialized with its default constructor. More importantly, whenever a Secretary object is destroyed, its contained Phone object is also destroyed. If you want to use a different constructor for the Phone, you can use initializer lists in Secretary's constructor: class Secretary { private: // members Phone myPhone; Phone myCellPhone; public: // methods Secretary() : myPhone("phone constructor", 12, " args") {} }; In this case myPhone is initialized using its 3-argument constructor, and myCellPhone is initialized using its default constructor as usual.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Flex: downloading files directly to the disk Is there a way to download some files directly to the user disk, without browsing? (assuming they give permission of course). FileReference does this, but does not allow to directly save files to the hard disk (if not through browsing). Is there some way around? A: To clarify, for people reading about file downloads in flash, it is possible to save to the local hard drive in Flash Player 10+ (e.g. running from a web browser, as well as in AIR). More specific information can be found in my answer in this question: Flex 3 file download - Without URLRequest To address enzo.rivello's question, saving must be performed in response to a user gesture (click or keypress) and the user must browse and select where the file is saved (i.e. through the file browser window). This is for security reasons, so the user has control over what is accessed on their hard drive.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528475", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What happens to local variables in this recursive call? In a complicated code, I found a weird behavior: apparently Lua doesn't treat local variables the same as C and Java (I'm not surprised but I don't know HOW it treats them anyway!) I read PIL and Lua-users.org but none doesn't mention what happens to local variables in recursion. It caused me to develop the following test code: function addN(n) local ret="" if n>0 then ret=ret..addN(n-1) print("for n="..n.." ret='"..ret.."'") else print("n reached 0") end return ret end print("Final result='"..addN(9).."'") Expected result: Final result='987654321' But I get: Final result='' Why? How can I reach the expected result? A: You are not actually concatenating n anywhere. Try something like: ret = tostring(n)..addN(n-1)
{ "language": "en", "url": "https://stackoverflow.com/questions/7528476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: magento, help to understand default product Template code I am a novice in magento but am trying to learn it in the least possible time. I Was going through: http://alanstorm.com/layouts_blocks_and_templates which says: File: app/design/frontend/base/default/template/catalog/product/list.phtml contains : <?php $_productCollection=$this->getLoadedProductCollection() ?> <?php if(!$_productCollection->count()): ?> <div class="note-msg"> <?php echo $this->__("There are no products matching the selection.") ?> </div> <?php else: ?> The getLoadedProductCollection method can be found in the Template’s Block, Mage_Catalog_Block_Product_List ... and from there: File: app/code/core/Mage/Catalog/Block/Product/List.php ... public function getLoadedProductCollection() { return $this->_getProductCollection(); } ... After that , the aforementioned page writes : The block’s _getProductCollection then instantiates models and reads their data, returning a result to the template. I am just at a loss here. _getProductCollection() has this line: if (is_null($this->_productCollection)) 1) Does _productCollection mean the protected variable $_productCollection ? if (is_null($this->_productCollection)) { $layer = $this->getLayer(); 2) What is the explanation of $layer = $this->getLayer() plz? After that I get: if ($this->getShowRootCategory()) { $this->setCategoryId(Mage::app()->getStore()->getRootCategoryId()); } 3) Where is the method getShowRootCategory() ? 4)What approach can help me understand the pros and cons of the line : $this->setCategoryId(Mage::app()->getStore()->getRootCategoryId()); 5) My questions may sound so easy to many. But can you refer to any online resource to learn all these things and others as a beginner of magento? Good Luck A: This if (is_null($this->_productCollection)) is a caching technique that is common to OOP code as methods cache their variables in object context and if the methods are called multiple times against same object or within the same object then it delivers the cached variable instead of asking it all over from database again. you can answer your other questions by grepping the codebase or finding the methods you are curious about from source code. Sometimes a method is a magic method (set, get) and you won't find a method definition behind that grep ' getRootCategoryId' app/code/ -rsn app/code/core/Mage/Core/Model/Store/Group.php:275: public function getRootCategoryId() app/code/core/Mage/Core/Model/Store.php:850: public function getRootCategoryId() and the very basic grep patterns to use are: * *use [space]methodname( to find the methods and where they are defined in codebase *use >methodname( to find where this method is called in codebase *use >setMethodName( to find where magic methods are set if you wonder why there is no definition for getSomeVariable() in your codebase A: 1) Yes. 2) Mage_Catalog_Block_Product_List::getLayer() returns catalog layer model (Mage_Catalog_Model_Layer). It is used in the code below. 3) It is magic method, almost all magento classes extend Varien_Object class. Read more about Varien_Object in this article. 4) Sorry, don't understand what this question about. 5) To avoid such questions you should read official development guide first and only after understanding it you should read Alan Storm's articles (which are slightly outdated, btw).
{ "language": "en", "url": "https://stackoverflow.com/questions/7528479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: why would this text is stored as empty in a text mysql field %3Cimg+src%3D%27http%3A%2F%2Fmnmstatic.net%2Fcache%2F15%2F15%2Fthumb-1381820.jpg%27+width%3D%2760%27+height%3D%2760%27+alt%3D%27%27+class%3D%27thumbnail%27+style%3D%27float%3Aright%3Bmargin-left%3A+3px%27+align%3D%27right%27+hspace%3D%273%27%2F%3E%3Cp%3EAunque+se+haya+dado+marcha+atr%C3%A1s%2C+lo+que+ha+ocurrido+en+RTVE+es+muy+serio.+Seg%C3%BAn+Gabilondo%2C+este+asunto+nos+permite+ver+con+claridad+por+d%C3%B3nde+va+la+pol%C3%ADtica+y+por+d%C3%B3nde+va+el+pensamiento+del+PP+entorno+a+la+libertad+de+informaci%C3%B3n.%3C%2Fp%3E%3Cp%3E%3Cstrong%3Eetiquetas%3C%2Fstrong%3E%3A+tve%2C+i%C3%B1aki+gabilondo%3C%2Fp%3E%3Cp%3E%3Ca+href%3D%22http%3A%2F%2Fmenea.me%2Ftm7w%22%3E%3Cimg+src%3D%22http%3A%2F %2Fwww.meneame.net%2Fbackend%2Fvote_com_img.php%3Fid%3D1381820%22+alt%3D%22votes%22+width %3D%22200%22+height%3D%2216%22%2F%3E%3C%2Fa%3E%3C%2Fp%3E%3Cp%3E%26%23187%3B%26nbsp%3B%3Ca+href%3D%22http%3A%2F%2Fblogs.cadenaser.com%2Fla-voz-de-inaki%2F2011%2F09%2F23%2Ftve-acorralada%2F%22+onmousedown%3D%22this.href%3D%27http%3A%2F%2Fwww.meneame.net%2Fbackend%2Fgo.php%3Fid%3D1381820%27%3B+return+true%22+%3Enoticia+original%3C%2Fa%3E%3C%2Fp%3E This would be the text containded of a RSS file $item->description wich I'm trying to store in my MySQL database, but it stores an empty string. This sample of text is been under an echo right before the $mysql query. Is it because its preceded by %3C? The full script would be: $filename = "http://www.ofertasybonos.com/blog/?feed=rss2"; $feed = simplexml_load_file($filename); // Iterate through the list and create the unordered list $n = false; foreach ($feed->channel->item as $item) { $user = "ofertasybonos"; $pass = "ofertasybono"; $title = urlencode($item->title); if(strlen($item->description)>6000){ $notes = urlencode(substr($item->description, 6000).'..' ); }else{ $notes = urlencode($item->description); } $url = urlencode($item->link); $tags = ''; $tags .= urlencode(urlencode($item->category)); if($tags=='') $tags = urlencode("ofertas, bonos"); $params = "nombre=$user&pass=$pass&url=$url&tags=$tags&notes=$notes&title=$title"; $res = file_get_contents ("http://domain.com/API/public/autosave.php?$params"); /*this file getContents stores in database*/ $n = true; } this is how is (supoused to be) stored Recive data form file_get_contents $texto = urldecode($_GET['notes']); Store in database $insert = "INSERT INTO links (nombre, coment, url, iduser,fecha,priv) VALUES ('$b','$r_int','$texto ','$id_tmp',NOW(),'$priv')"; Any idea why the text is stored empty? A: I don't know if that is the correct solution, but if you try serialize the data ? Method to serialize your data is serialize(); http://php.net/manual/en/function.serialize.php Method to unserialize your data is unserialize(); http://www.php.net/manual/en/function.unserialize.php A: You forgot $ in front of of texto $insert = "INSERT INTO links (nombre, coment, url, iduser,fecha,priv) VALUES ('$b','$r_int','$texto','$id_tmp',NOW(),'$priv')";
{ "language": "en", "url": "https://stackoverflow.com/questions/7528486", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: jQuery Getting original 'this' object I'm creating a follow button, and I'm switching the class names to give the button a different look. Unfortunately, my classes don't seem to be being swapped because the 'this' object appears to be changing in the code. How do I get the original object that I selected so that I can swap the classes? // Follow button $('input.follow_user_button').live('click', function() { $.ajax({ type: "POST", url: "ajax/follow.php", data: { follow_user_id: $(this).attr('data-follow-user-id') }, dataType: "json", success: function(follow_response) { if (follow_response.result == "success") { if (follow_response.action == "success_follow") { // Set the follow button to followed class style THIS DOESNT WORK $(this).attr('value', 'Unfollow').removeClass('follow_button_follow').addClass('follow_button_unfollow'); } else if (follow_response.action == "deleted_follow") { // Set the follow button to the unfollowed class style THIS DOESNT WORK $(this).attr('value', 'Follow').removeClass('follow_button_unfollow').addClass('class', 'follow_button_follow'); } } else if (follow_response.result == "failure") { alert(follow_response.error_message); } }, error: function() { alert("Sorry there was an error, please refresh and try again."); } }); }); Kind regards, Luke A: You should store the $(this) before the $.ajax, e.g. var self = $(this); $.ajax({ ... success: function() { self.attr(...); } }); Don't use the $(this) too many times, this is overkill to do, put it into a variable, then use it for later reference.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: simplexml cache file I am loading an XML file which is pretty heavy and contains a lot of data, and I am only using a small amount of it. This is causing my site to take ages to load. http://www.footballadvisor.net/ Can anyone advice me on a resolution to this, is there a way in simplexml that I can cache the file for a period of time? My site is in PHP. Thanks in advance Richard A: You wouldn't do it directly with simplexml. What you'd need to use is the other file functions (fopen or file_get_contents), save the file or extract the bits you need and save it. If enough time has passed since the last time it was checked (or if enough time passed that new data would be available) you could delete the cached data and check again.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android: Implement azimuth orientation sliding view I am trying to create a ruler view based on azimuth compass orientation value. The idea is to place a small view at the bottom of a camera view which slides to the left or to the right according to the azimuth value obtained from the "orientation" sensor. Something like this: My main conceptual problem is to understand how I can wrap up the bar if I keep rotating the phone in the same direction. I am looking for ideas on how to solve this problem! Can this problem be solved with Bitmaps? Which classes/tools are suitable for this? Are there any examples on how to do this? Thank you!
{ "language": "en", "url": "https://stackoverflow.com/questions/7528492", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Flash overlay in IE I have a flash player on my website and I would like to add an overlay where I can insert HTML. The idea is that the div containing the flash will animate its opacity to 0.5 before display the HTML. I got this working great in Google Chrome and Firefox, but as always, IE is giving me a headache. I set wmode to opaque (and also tried transparent), but IE is behaving strangely. To make my div show on top of the flash video, I set its position to absolute and give it higher z-index than any other element. The problem is that IE9 does not show the HTML I append to my div from jQuery. Fair enough, I can live with adding it from PHP in a hidden div. However, the big problems are that IE will not let me animate the flash player's opacity unlike Chrome and Firefox (and possibly other browsers) as well as let me interact with the flash player. When the overlay is displayed, the player is no longer responding when I click on it. Some workarounds are needed for IE, but I have not been able to find a workaround for the opacity fading so far. Now for the code. DOM: <div class="videoPaths" style="z-index: 9999;"> This is the overlay container </div> <div class="videoWrapper"> <script src="swfobject/swfobject.js"></script> <div id="VideoPlayer" class="embedded-video"> <div class="no-flash">You don't have flash</div> </div> <script>swfobject.embedSWF("http://url.com/v.swf", "VideoPlayer", "590", "332", "9.0.0", "/swfobject/expressInstall.swf", {}, {wmode:'opaque', allowscriptaccess:'always', allowfullscreen:'true', FlashVars:'token=my_token&photo%5fid=my_id'}, {id:'VideoPlayer', name:'VideoPlayer'});</script> </div> JavaScript (jQuery): -- simplied for illustration purposes // Animate opacity to 0.5 $('.videoWrapper').animate({ opacity: 0.5 }, { duration: 1000, queue: false, complete: function() { showOverlay(); } }); function showOverlay() { // Show overlay text $('.videoPaths').html('<h2>This is the overlay text I want to show</h2>'); } CSS: .videoPaths { position: absolute; top: 100px; text-align: center; width: 590px; } In the code above, the HTML that I append with jQuery is not shown, but like I said, I can fix that by adding it directly into the DOM, because then IE displays it. However, I would like the opacity animation to work, but IE9 does not appreciate it. Also, when doing like this, I cannot click on the player to start/stop the playback. Any ideas? Any suggestions are greatly appreciated. Thank you in advance! A: "When the overlay is displayed, the player is no longer responding when I click on it" Yes, this is what happens when an html element is positioned on top of a swf; the swf is obscured so it can't be interacted with. "IE will not let me animate the flash player's opacity unlike Chrome and Firefox" IE is in general really bad at animating opacity, particularly IE8 (in my experience). The rendering engine actually seems to have gotten worse with later versions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: QT Creator - cross platform compiling Compiling for Windows, Mac and Linux! Is the only way to do this.... is to install QT Creator on each OS and compile its own version? (Currently running QT Creator under Mac OSX) A: Qt Creator is just the automation tool, it will create Makefile and adjacent files for you. If you want to cross-compile, simply extend your Makefile so it could be possible to cross-compile, for example, via: export TARGET=i686-mingw32 CXX=$TARGET-g++ RANLIB=$TARGET-ranlib AR=$TARGET-ar make -f Makefile.mingw Reference is here. Please note, you will need to have entire toolchain for every target, including libraries. This is a separate topic, but hopefully there is a whole bunch of articles out there. Btw, most Linux distro's have mingw32 toolchain available, and I believe there should be one for OSX too. Also, you might be highly interested in tmake - it was originally developed to autogenerate Makefiles for building Qt. A: Qt Creator is only an IDE, not a compiler. You can configure it to use whatever compiler you like, including a cross-compiler (for instance GCC cross-compiler).
{ "language": "en", "url": "https://stackoverflow.com/questions/7528499", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: JQuery slideToggle timeout I have simple html page: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script src="http://code.jquery.com/jquery-latest.js"></script> <script> $(document).ready(function() { $("button").click(function() { $("div").slideToggle("slow"); }); }); </script> <style> div { width:400px; } </style> </head> <body> <button>Toggle</button> <div style="border: 1px solid"> This is the paragraph to end all paragraphs. You should feel <em>lucky</em> to have seen such a paragraph in your life. Congratulations! </div> </body> </html> I need to hide the div panel automaticaly after 10 seconds if my mouse cursor isn't over the panel. How can I do it (change the code above) to implement that? Thanks A: Check http://jsfiddle.net/XRYLk/3/ I added mouseleave so in case the mouse was over it when first function fires up, it will set timer on mouseleave. jQuery: $("button").click(function() { $("div").slideToggle("slow"); }); setTimeout(hidepanel, 4000); function hidepanel(){ if($('div').is(':hover') === false){ $('div').slideToggle(); } } $('div').mouseleave(function(){ setTimeout(hidepanel, 4000); }); A: Try this code if($('.to_hide').css("display") == "block") { $(".to_hide").mouseout(function(){ setTimeout(hidepara,10000); }) } function hidepara() { $(".to_hide").hide(); } Working sample http://jsfiddle.net/kaYLG/ A: This is a very simple solution. Idea is, if you don't move your mouse over the div-container.. it will slideUp() the container itself in 2000ms (I put 2000ms, because its boring to wait 10sec). <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script src="http://code.jquery.com/jquery-latest.js"></script> <style> div {width: 400px; border: 1px solid;} </style> </head> <body> <div> This is the paragraph to end all paragraphs. You should feel <em>lucky</em> to have seen such a paragraph in your life. Congratulations! </div> <script> $(document).ready(function () { var mouseover_to = setTimeout(function () { $("div").slideUp("slow"); }, 2000); // Change it to 10000 to be 10sec $('div').mouseover(function () { clearTimeout(mouseover_to); }); }); </script> </body> </html> [ View output ] * *First it will wait till the document is ready *It will start the countdown to 2000ms with setTimeout() and sets it as resource to mouseover_to variable. *However, if mouseover() is detected over the div then the countdown will be canceled with clearTimeout(), thanks to the help of the resource mouseover_to
{ "language": "en", "url": "https://stackoverflow.com/questions/7528503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Possible: Insert my own HTML(whole website) into an iframe I have all a websites HTML stored in a javascript string & I want to place it inside an iframe. How can I place that HTML string into the iframe & make it show the website? I have tried this.src = HTML_STR; this.innerHTML = HTML_STR; but they dont show the HTML_STR. I understand that this maybe silly because instead of having the websites HTML in a string I could just set the iframes src to the website & show the website that way. BUT the reason I am doing this is because its a website updater. So I want to get the website (that I am updating) HTML, convert all the elements with the class "updatable" to textareas(so they can be updated) then show that HTML in the iframe. The other reason for using an iframe & not just chucking the HTML in a div, is because each website imports a .css style sheet & I dont want their css file to affect my updater websites css or have my updater .css affect the websites HTML look thus if I show the website in an iframe each websites css wont affect each other. For example if updater.css has the following it will affect all the p elements in the other websites html: p { background-color: red; width: 50%; } So is there a way to insert my own HTML into an iframe. Or is there another way to achieve what I am trying to do. A: Assuming that you want to write to the iframe from the parent, you could do this: var ifrm = document.getElementById('myFrame'); ifrm = (ifrm.contentWindow) ? ifrm.contentWindow : (ifrm.contentDocument.document) ? ifrm.contentDocument.document : ifrm.contentDocument; ifrm.document.open(); ifrm.document.write('Hello World!'); ifrm.document.close(); Here's a working jsFiddle. Original code taken from here and here. A: You could try doing document.write(yourHTMLString); inside the iframe. Another way could be that you just use JavaScript to replace your updatable elements with textareas inside the original HTML when a certain button is clicked.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528504", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: mysql_query producing ERR_EMPTY_RESPONSE We recently had PHP version upgraded to 5.3.3 on our server (running Wordpress) and since then the mysql_query function started hanging the server, producing the error Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data in Google Chrome. The connection parameters are correct and error logging is also turned on but nothing appears. What could be wrong? What should I check? UPDATE: The code: function query( $query ) { if ( ! $this->ready ) return false; // some queries are made before the plugins have been loaded, and thus cannot be filtered with this method if ( function_exists( 'apply_filters' ) ) $query = apply_filters( 'query', $query ); $return_val = 0; $this->flush(); // Log how the function was called $this->func_call = "\$db->query(\"$query\")"; // Keep track of the last query for debug.. $this->last_query = $query; if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) $this->timer_start(); // use $this->dbh for read ops, and $this->dbhwrite for write ops // use $this->dbhglobal for gloal table ops unset( $dbh ); if( defined( 'WP_USE_MULTIPLE_DB' ) && WP_USE_MULTIPLE_DB ) { if( $this->blogs != '' && preg_match("/(" . $this->blogs . "|" . $this->users . "|" . $this->usermeta . "|" . $this->site . "|" . $this->sitemeta . "|" . $this->sitecategories . ")/i",$query) ) { if( false == isset( $this->dbhglobal ) ) { $this->db_connect( $query ); } $dbh =& $this->dbhglobal; $this->last_db_used = "global"; } elseif ( preg_match("/^\\s*(alter table|create|insert|delete|update|replace) /i",$query) ) { if( false == isset( $this->dbhwrite ) ) { $this->db_connect( $query ); } $dbh =& $this->dbhwrite; $this->last_db_used = "write"; } else { $dbh =& $this->dbh; $this->last_db_used = "read"; } } else { $dbh =& $this->dbh; $this->last_db_used = "other/read"; } $this->result = @mysql_query( $query, $dbh ); $this->num_queries++; if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() ); // If there is an error then take note of it.. if ( $this->last_error = mysql_error( $dbh ) ) { $this->print_error(); return false; } if ( preg_match( "/^\\s*(insert|delete|update|replace|alter) /i", $query ) ) { $this->rows_affected = mysql_affected_rows( $dbh ); // Take note of the insert_id if ( preg_match( "/^\\s*(insert|replace) /i", $query ) ) { $this->insert_id = mysql_insert_id($dbh); } // Return number of rows affected $return_val = $this->rows_affected; } else { $i = 0; while ( $i < @mysql_num_fields( $this->result ) ) { $this->col_info[$i] = @mysql_fetch_field( $this->result ); $i++; } $num_rows = 0; while ( $row = @mysql_fetch_object( $this->result ) ) { $this->last_result[$num_rows] = $row; $num_rows++; } @mysql_free_result( $this->result ); // Log number of rows the query returned // and return number of rows selected $this->num_rows = $num_rows; $return_val = $num_rows; } return $return_val; } The line that causes the error is $this->result = @mysql_query( $query, $dbh ); I am currently investigating the value of $dbh. mysql_query without parameters produced a warning, so at least it is working.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528508", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: tableView reloadData not working: cellForRowAtIndexPath not called I have this problem cellForRowAtIndexPath is not called by reloadingData. I have spent a lot of time with this. I xib file dataSource and delegate are connected to File's Owner. Any idea is welcome. This is my code : *cellForRowAtIndexPath* - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; cell.backgroundColor = [UIColor clearColor]; cell.selectionStyle = UITableViewCellSelectionStyleGray; cell.backgroundView.opaque = NO; //cell.alpha = 0.65; cell.textLabel.backgroundColor = [UIColor clearColor]; cell.textLabel.opaque = NO; cell.textLabel.textColor = [UIColor whiteColor]; cell.textLabel.highlightedTextColor = [UIColor whiteColor]; cell.textLabel.font = [UIFont boldSystemFontOfSize:18]; cell.detailTextLabel.backgroundColor = [UIColor clearColor]; cell.detailTextLabel.opaque = NO; cell.detailTextLabel.textColor = [UIColor whiteColor]; cell.detailTextLabel.highlightedTextColor = [UIColor whiteColor]; cell.detailTextLabel.font = [UIFont systemFontOfSize:14]; NSString *temp = [distanceArray objectAtIndex:indexPath.row]; if([checkMarkArray count] != 0){ NSString *checkString = [checkMarkArray objectAtIndex:0]; NSLog(@" checkString %@",checkString); if ([temp isEqualToString:checkString ]) { cell.accessoryView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"checked.png"]] autorelease]; } else { cell.accessoryView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"unchecked.png"]] autorelease]; } } } // Set up the cell... [[cell textLabel] setText: [distanceArray objectAtIndex:indexPath.row]] ; return cell; } didSelectRowAtIndexPath**** - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath]; cellText = selectedCell.textLabel.text; NSLog(@"%@",cellText); [checkMarkArray removeAllObjects]; if([[tableViewDistance cellForRowAtIndexPath:indexPath] accessoryType] == UITableViewCellAccessoryCheckmark) { //global array to store selected object [checkMarkArray removeObject:[distanceArray objectAtIndex:indexPath.row]]; NSLog(@"array %@",checkMarkArray); [tableViewDistance cellForRowAtIndexPath:indexPath].accessoryView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"unchecked.png"]] autorelease]; [[tableViewDistance cellForRowAtIndexPath:indexPath] setAccessoryType:UITableViewCellAccessoryNone]; [self.tableViewDistance reloadData]; } else { [checkMarkArray addObject:[distanceArray objectAtIndex:indexPath.row]]; NSLog(@"array again %@",checkMarkArray); [tableViewDistance cellForRowAtIndexPath:indexPath].accessoryView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"checked.png"]] autorelease]; [[tableViewDistance cellForRowAtIndexPath:indexPath] setAccessoryType:UITableViewCellAccessoryCheckmark]; [self.tableViewDistance reloadData]; } tableViewDistance.delegate = self; tableViewDistance.dataSource = self; [self.tableViewDistance reloadData]; } *viewDidLoad*** - (void)viewDidLoad { distanceArray= [[NSMutableArray alloc] initWithObjects:@"20 Kilomètres", @"40 Kilomètres", @"60 Kilomètres",@"80 Kilomètres",nil]; NSLog(@"distance %@",distanceArray); tableViewDistance.backgroundColor=[UIColor clearColor]; checkMarkArray = [[NSMutableArray alloc] init]; [super viewDidLoad]; // Do any additional setup after loading the view from its nib. } A: I've found some weak parts in your code: * *You should set cell.accessoryView out of if (cell == nil){} *In - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath you can use tableView and not use tableViewDistance (may be it is nil?) *In - (void)viewDidLoad you should call first [super viewDidLoad]; and then make customizations. Hope that will help you. Gl A: connect Your tableView outlet (UITableView *tableViewDistance) to Your Xib TableView. A: Try to call [tableView reloadData]; instead of [self.tableViewDistance reloadData]; A: Based on your comment to the question, you want to have only one cell selected at a time, so you want to deselect the previously selected cell and select the one currently selected. You can use the -indexPathForSelectedRow method of UITableView to find the selected row: - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // For multiselect, use an array to store the checked state instead of using the tableView's state. [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow]]; [self.tableView cellForRowAtIndexPath:indexPath].accessoryView = ...; } You will also want to implement tableView:didDeselectRowAtIndexPath:: - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath { [self.tableView cellForRowAtIndexPath:indexPath].accessoryView = ...; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7528512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ant build.xml file doesn't exist After the installation of my ant in my windows 7 . In cmd i typed ant -v it's given the ant version but it says the following also. Buildfile: build.xml does not exist! Build failed What's the problem in the system. How i can rectify this issue? A: You should use ant -version command instead. The -v option is equivalent of -verbose option. See Command-line Options Summary A: may be you can specify where the buildfile is located and then invoke desired action. Eg: ant -file {BuildfileLocation/build.xml} -v A: You have invoked Ant with the verbose (-v) mode but the default buildfile build.xml does not exist. Nor have you specified any other buildfile for it to use. I would say your Ant installation is fine. A: If I understand correctly, you assumed that -v is the "print version" command. Check the documentation, that is not the case -- instead ant -v is running ant build in verbose mode. So ant is trying to perform your build, based on the build.xml file, which is obviously not there. To answer your question explicitly: there is probably nothing wrong with both the system nor ant installation. A: If you couldn't find the build.xml file in your project then you have to build it to be able to debug it and get your .apk you can use this command-line to build: android update project -p "project full path" where "Project full path" -- Give your full path of your project location after this you will find the build.xml then you can debug it. A: this one works in ubuntu This command will cre android update project -p "project full path" A: There may be two situations. * *No build.xml is present in the current directory *Your ant configuration file has diffrent name. Please see and confim the same. In the case one you have to find where your build file is located and in the case 2, You will have to run command ant -f <your build file name>. A: I have still this issue i have my build.xml file inside the sample folder . A: Using ant debug after building build.xml file : in your cmd your root should be your project at first then use the ant debug command e.g: c:\testApp>ant debug A: Please install at ubuntu openjdk-7-jdk sudo apt-get install openjdk-7-jdk on Windows try find find openjdk
{ "language": "en", "url": "https://stackoverflow.com/questions/7528517", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "52" }
Q: Java, ports, sockets, piping a connection through a programme I need to pipe a connection between two programs on different devices in my LAN. I.e., I have device A that should connect to device B:portX in my LAN. The problem is that i cannot connect them to each other directly. What i have to do is to make device A connect to a server, and have that server connect to device B. On my server i listen to the port "portX", and when i get the connection, i connect to device B on the same port. Then i have to channel the data from A to B through the server, but for some reason device B doesn't do what it should do when it receives the data (commands) from A. How can I do this? Here is how i have been trying to do this: public class Main { public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(8000); } catch (IOException e) { System.err.println("Could not listen on port: 8000."); System.exit(1); } Socket clientSocket = null; try { clientSocket = serverSocket.accept(); System.err.println("connection accepted"); } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); } Socket remoteSocket = null; try { remoteSocket = new Socket("192.168.1.74", 8000); } catch (Exception e) { System.out.println("Failed to connect to device B"); } PrintWriter remoteOut = new PrintWriter(remoteSocket.getOutputStream(), true); BufferedReader remoteIn = new BufferedReader(new InputStreamReader( remoteSocket.getInputStream())); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader( clientSocket.getInputStream())); String inputLine; System.out.println("Hi, we are before the while"); int inputChar = 0; while ((inputChar = in.read()) >= 0) { remoteOut.println(inputChar); System.out.println(inputChar); } System.out.println("We are after the while"); out.close(); in.close(); remoteIn.close(); remoteOut.close(); clientSocket.close(); serverSocket.close(); remoteSocket.close(); } } Thanks in advance, Timofey A: I created a version that uses the NIO channels. The benefit of this approach is that you can use a single Thread to manage what is coming in from multiple sources. I don't need to necessarily know what the protocol is between the two services because we are just copying bytes. If you wanted to just use plain old sockets, you would need to use a mutex and 2 threads to read/write data between the two sockets (sockets are not thread-safe). NOTE: There may be better ways to handle the error conditions than just dropping the connections and creating new ones. import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.*; import java.util.Set; /** * Socket Gateway for SO Question 7528528 * User: jhawk28 * Date: 9/26/11 * Time: 9:03 PM * <p/> * http://stackoverflow.com/questions/7528528/java-ports-sockets-piping-a-connection-through-a-programme */ public class Gateway { public static void main(String[] args) throws IOException { // Set up Server Socket and bind to the port 8000 ServerSocketChannel server = ServerSocketChannel.open(); SocketAddress endpoint = new InetSocketAddress(8000); server.socket().bind(endpoint); server.configureBlocking(false); // Set up selector so we can run with a single thread but multiplex between 2 channels Selector selector = Selector.open(); server.register(selector, SelectionKey.OP_ACCEPT); ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { // block until data comes in selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); for (SelectionKey key : keys) { if (!key.isValid()) { // not valid or writable so skip continue; } if (key.isAcceptable()) { // Accept socket channel for client connection ServerSocketChannel channel = (ServerSocketChannel) key.channel(); SocketChannel accept = channel.accept(); setupConnection(selector, accept); } else if (key.isReadable()) { try { // Read into the buffer from the socket and then write the buffer into the attached socket. SocketChannel recv = (SocketChannel) key.channel(); SocketChannel send = (SocketChannel) key.attachment(); recv.read(buffer); buffer.flip(); send.write(buffer); buffer.rewind(); } catch (IOException e) { e.printStackTrace(); // Close sockets if (key.channel() != null) key.channel().close(); if (key.attachment() != null) ((SocketChannel) key.attachment()).close(); } } } // Clear keys for next select keys.clear(); } } public static void setupConnection(Selector selector, SocketChannel client) throws IOException { // Connect to the remote server SocketAddress address = new InetSocketAddress("192.168.1.74", 8000); SocketChannel remote = SocketChannel.open(address); // Make sockets non-blocking (should be better performance) client.configureBlocking(false); remote.configureBlocking(false); client.register(selector, SelectionKey.OP_READ, remote); remote.register(selector, SelectionKey.OP_READ, client); } } A: Your problem is that you are using a PrintWriter as your forwarding mechanism. You read in a char and then write out the char + a newline. Try switching it to a remoteOut.print(inputChar); A better solution would just read the character and then write out the character (you can use a BufferedWriter). commons-io already has copy methods that do this sort of thing in IOUtils
{ "language": "en", "url": "https://stackoverflow.com/questions/7528528", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP Pear - adding variables to $body message This is my HTML form, which is inside a little box on my site. <form name="contactform" action="contact/form-mailer.php" method="post"> <p>*Name: <input name="Name" id="Name" size="25"></p> <p>*Pickup from: <input name="pfrom" id="pform" size="25"></p> <p>*Destination: <input name="destin" id="destin" size="25"></p> <p>*E-mail: <input name="Email" id="Email" size="25"></p> <p>*Phone: <input name="Phone" id="Phone" size="25"></p> <p><input type="submit" value="Submit" name="submitform"><input type="reset" value="Reset" name="reset"></p> </form> And this is my current PHP for sending the mail using PEAR. I haven't added all of the variables into the $body yet, as I've just been trying to get it to actually work. <?php // Include the Mail package //require "Mail.php"; include 'Mail.php'; // Identify the sender, recipient, mail subject, and body $sender = "XXXXXX"; $recipient = "XXXXXX"; $subject = "FORM"; $body = $name; // Even when seting $name in the PHP file it still doesn't show! // Identify the mail server, username, password, and port $server = "ssl://smtp.gmail.com"; $username = "XXXXXXXX"; $password = "XXXXXXXX"; $port = "465"; // Get form var's $name = "Test"; // I set $name to "Test" in the PHP and still the variable does not appear in the email. $destin = $_POST['destin']; $email = $_POST['Email']; $pfrom = $_POST['pfrom']; // Set up the mail headers $headers = array( "From" => $sender, "To" => $recipient, "Subject" => $subject ); // Configure the mailer mechanism $smtp = Mail::factory("smtp", array( "host" => $server, "username" => $username, "password" => $password, "auth" => true, "port" => 465 ) ); // Send the message $mail = $smtp->send($recipient, $headers, $body); if (PEAR::isError($mail)) { echo ($mail->getMessage()); } ?> So I have no idea why this isn't working. I need body to be like this $body = $name . " wants to go to " . $destin . " from " . $pfrom; But it just doesn't pickup any variables, regardless of whether I am trying to get them from the HTML form or set them in the PHP file itself. I was expecting this to be really easy, but this has stumped me for over a day now. Very frustrating. I can find no example anywhere that shows you how to do it, and only a handful have asked this exact question and received no definitive answer. A: In the code you posted, you attempted to set the value of $body on line 13, but did not set the value of $name until line 22. $name is null at the time you assign it to $body, so $body does not contain the values you are hoping for. To fix this problem, move the $body = ... line below the other assignments. Something like this: ... // Get form var's $name = "Test"; // I set $name to "Test" in the PHP and still the variable does not appear in the email. $destin = $_POST['destin']; $email = $_POST['Email']; $pfrom = $_POST['pfrom']; // Populate $body $body = $name . " wants to go to " . $destin . " from " . $pfrom; ... A: You have not mention where you have kept your php code file? Is it contact folder? and also look after the file location of Mail.php. This file must be under contact folder.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528530", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: persistence.xml cache property warning I'm using eclipse indigo for EE developement to develop an SE project, just to take benefit from the JPA project support. I created a JPA project, here's the properties of my persistence.xml file: <properties> <property name="eclipselink.persistence-context.reference-mode" value="WEAK" /> <property name="eclipselink.cache.shared.default" value="false"/> <property name="eclipselink.cache.size.default" value="5000"/> <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver" /> <property name="javax.persistence.jdbc.url" value="jdbc:derby:DB;create=true;" /> <property name="eclipselink.ddl-generation" value="create-tables" /> <property name="eclipselink.ddl-generation.output-mode" value="both" /> </properties> a warning appears : "eclipselink.cache.shared.default" is a legacy entity caching property. Consider migration to JPA 2.0 and EclipseLink cache settings via annotation or XMLmapping file I'm using the last release of eclipseLink (2.3.0), and here's a link to EL documentation, where there's an example for setting the property onto the persistence.xml file. Does anybody knows the reason of the warning? Note that i used the same property in a normal java project, and there were no warnings, it appeared only when used the JPA project. A: It just wants to inform about use of EclipseLink Entity caching. Instead it suggests that you could use cache which is part of JPA 2.0. Usage is described among other sources here: http://en.wikibooks.org/wiki/Java_Persistence/Caching And why it does so, is probably best explained in the request to add such a message: https://bugs.eclipse.org/bugs/show_bug.cgi?id=294077
{ "language": "en", "url": "https://stackoverflow.com/questions/7528541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Error validating CDATA elements with DTD - XML I'm trying to validate some xml with a DTD I'm writing but I always get a validation error on the elements with CDATA data types. Like this <!ELEMENT title (#CDATA)> I've tried validating using textmate xml validation (XMLlint) and online validators (w3Schools) and I always get this error: error: ContentDecl : Name or '(' expected Can anybody explain what's going on here? Cheers Example of full xml and dtd (I took this from here so I'd expect it to be valid): <?xml version="1.0"?> <!DOCTYPE bookstore [ <!ELEMENT bookstore (name,topic+)> <!ELEMENT topic (name,book*)> <!ELEMENT name (#PCDATA)> <!ELEMENT book (title,author)> <!ELEMENT title (#CDATA)> <!ELEMENT author (#CDATA)> <!ELEMENT isbn (#PCDATA)> <!ATTLIST book isbn CDATA "0"> ]> <bookstore> <name>Mike's Store</name> <topic> <name>XML</name> <book isbn="123-456-789"> <title>Mike's Guide To DTD's and XML Schemas<</title> <author>Mike Jervis</author> </book> </topic> </bookstore> A: Well, the example was a bad one, there's no such thing as (#CDATA) for the element content model. <!DOCTYPE bookstore [ <!ELEMENT bookstore (name,topic+)> <!ELEMENT topic (name,book*)> <!ELEMENT name (#PCDATA)> <!ELEMENT book (title,author)> <!ELEMENT title (#PCDATA)> <!ELEMENT author (#PCDATA)> <!ELEMENT isbn (#PCDATA)> <!ATTLIST book isbn CDATA "0"> ]> <bookstore> <name>Mike's Store</name> <topic> <name>XML</name> <book isbn="123-456-789"> <title>Mike's Guide To DTD's and XML Schemas</title> <author>Mike Jervis</author> </book> </topic> </bookstore> UPDATE: The W3C XML specification, http://www.w3.org/TR/2008/REC-xml-20081126, clearly does not allow #CDATA in the content model for elements. Start at production 45 and follow throught to production 51.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Javascript - how to avoid long/ugly if/else statements? I'm learning Javascript (mainly using JQuery) and was wondering if somebody could help me. I've written an if/else statement that checks to see if a particular string appears in the URL, then posts a forms content to a particular php script depending on the string. Q: The code I'm using works, BUT feels clumsy and unnecessarily long! - I figure there MUST be a simpler way to write this!? I've had a look around but most answers just seem to provide code without anything to help me understand how it was done.. What I'm trying to achieve is: * *A user completes one of 4 signup forms (prereg1.html, prereg2.html, prereg3.html, prereg4.html) *Depending on the URL, the if/else statement sends the form data to a corresponding PHP script (add_prereg1.php, add_prereg2.php etc.) which adds the data to an email list database (hosted by campaign monitor) note: My php knowledge is pretty poor too - because the campaign monitor lists each have unique IDs, the only way I can get the php to post the form data in the right list is to have 4 separate 'prereg.php' scripts. I'm sure there is a way to get the php script to figure out which list to post to based on the variables passed by the javasscript but this is a bit beyond me at this stage! Any pointers welcome.. Anyhow here is the if/else statement: if (document.location.href.indexOf('prereg1') > -1) { $.ajax({ type: "POST", url: "bin/add_prereg1.php", data: 'name=' + name + '&email=' + email }); } else { if (document.location.href.indexOf('prereg2') > -1) { $.ajax({ type: "POST", url: "bin/add_prereg2.php", data: 'name=' + name + '&email=' + email }); } else { if (document.location.href.indexOf('prereg3') > -1) { $.ajax({ type: "POST", url: "bin/add_prereg3.php", data: 'name=' + name + '&email=' + email }); } else { if (document.location.href.indexOf('prereg4') > -1) { $.ajax({ type: "POST", url: "bin/add_prereg4.php", data: 'name=' + name + '&email=' + email }); } } } } Thanks for any help. A: You could use a for loop: for (var i = 1; i <= 4; i++) { if (document.location.href.indexOf('prereg' + i) > -1) { $.ajax({ type: "POST", url: "bin/add_prereg" + i +".php", data: 'name=' + name + '&email=' + email }); break; } } A: Consider this: var match = window.location.href.match( /prereg(\d)/ ); if ( match ) { $.ajax({ type: 'POST', url: 'bin/add_prereg' + match[1] + '.php', data: 'name=' + name + '&email=' + email }); } Live demo: http://jsfiddle.net/4MWDm/ You simply search the string for the sequence "prereg" followed by a digit. The parens capture the digit, so you can access it with [1]. Btw use window.location instead of document.location. document.location was originally a read-only property, although Gecko browsers allow you to assign to it as well. For cross-browser safety, use window.location instead. Source: https://developer.mozilla.org/en/DOM/document.location A: Almost all statements are the same, so you can generalize. * *Use the ~ trick - it returns falsy for -1 and thruthy otherwise. This is useful in combination with indexOf. *Next, the ?: works like this: a ? b : c returns b if a is truthy and c if a is falsy. Admittedly, setting the number variable is still kind of repetitive. var href = location.href, // so that you don't have to // write 'location.href' but only 'href' number = ~href.indexOf('prereg1') ? 1 : ~href.indexOf('prereg2') ? 2 // if the first ~ returned falsy : ~href.indexOf('prereg3') ? 3 // etc. : ~href.indexOf('prereg4') ? 4 // etc. : null; // if all returned falsy if(number) { // if not null (null is falsy so won't pass the 'if') $.ajax({ type: "POST", url: "bin/add_prereg" + number + ".php", // insert number data: 'name=' + name + '&email=' + email }); } A: Using regular expressions you can simplify it to something like: document.location.href.match(/prereg(.)/); var index = RegExp.$1: $.ajax({ type: "POST", url: "bin/add_prereg" + index + ".php", data: 'name=' + name + '&email=' + email }); A: No need to have a loop you can get the index from url itself according to your code, var url=document.location.href; var startIndex=url.indexOf('prereg'); var index= url.substring(startIndex+5,1);//make sure your index is correct (not tested by me) $.ajax({ type: "POST", url: "bin/add_prereg" + i +".php", data: 'name=' + name + '&email=' + email }); A: First of all you can simply use else if { ... } instead of else { if { ... } }. The way you're doing things in your code is a little bit too complicated for my taste. I'd rather write a function that extracts the "prereg" parts from the location string and then wrap up the jQuery $.ajax call after that (this way you wouldn't need to copy the code into all the then-blocks, since the only difference is the URL for the AJAX request). If you have the string ("prereg1", "prereg2", etc.) extracted correctly, you can also use a switch statement instead of the if/else-cascade. If the URL is the only different it's not really worth doing any kind of flow-control in my opinion. A: You can use the switch as known from other programming languages such as PHP as you mentioned switch (document.location.href) { case 'prereg1': // Your code here break; case 'prereg2': // Your code here break; case 'prereg3': // Your code here break; case 'prereg4': // Your code here break; } It doesn't really help with the rest of your code, which would still be repetitive, but in regards to all of the nested if/else statements, switches are more readable. A: if document.location.href.indexOf('prereg') > -1) { $.ajax({ type: "POST", url: "bin/add_" + document.location.href + ".php", data: 'name=' + name + '&email=' + email }); } A: You could use a regular expression to pull the required piece out of the url like this: var re=new RegExp(/prereg\d/); var postUrl = 'bin/add_' + re.exec(document.location.href) + '.php'; $.ajax({ type: "POST", url: postUrl , data: 'name=' + name + '&email=' + email }); A: Just grab the number from the html filename, and construct your URL with it: $.ajax({ var pagename = location.pathname; var formid = pagename.substring(7,10); var myurl = "bin/add_prereg" + formid + ".php"; type: "POST", url: myurl, data: 'name=' + name + '&email=' + email });
{ "language": "en", "url": "https://stackoverflow.com/questions/7528549", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is it possible to change the class of a Ruby object? Is it possible to change the class of a Ruby object once it has been instantiated, something like: class A end class B end a = A.new a.class = B or similar. (the above code does not run as class is a read only variable) I know this is not advisable, a bit strange, and not something I plan on doing, but is it possible? A: No, this is not possible from within ruby. It is theoretically possible from within a C extension by changing the klass pointer of the given object, but it should be noted that this will be completely implementation-specific, will not work for immediate types (i.e. you definitely can't change the class of e.g. a fixnum), and might blow up in various ways. A: When I needed to convert from the built-in String class to a custom class called MyString, I did it via the following: class MyString < String #Class body here end class String def to_MyS MyString.new self end end foo = "bar" puts foo.class #=> String foo = foo.to_MyS puts foo.class #=> MyString A: simple answer, no: NoMethodError: undefined method `class=' for #<A:0x91a758> however you can delete methods and mix in modules and such so as to leave an object that looks totally different...
{ "language": "en", "url": "https://stackoverflow.com/questions/7528552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: String null check I have tried this for 2 hours , but I've given up. I am checking the value of a String this way: if(value.equals("")||value.length()<0||value==null) { value = "Anynomous" } But still the string is printing the value null. Please see this program code here <HTML> <BODY> <%! String value ; %> <% value = (String)request.getAttribute("retunval"); System.out.println("Inside New fgdf JSP"); if(value.equals("")||value.length()<0||value==null) value = "Anonymuos"; %> Hello <%=value%> <BR> </BR> <BR> </BR> <a href="Test.jsp">Try Again</a> </BODY> </HTML> A: Check whether value is null first. Otherwise value.equals() will throw a NullPointerException. if (value == null || value.equals("")) { value = "Anonymous"; } A: First you need to reorder your if condition, otherwise you could run into NPEs. Additionally, the string length can never be lower than 0, so that check is not needed: value==null||value.equals("") Alternatively, if you can use Apache Commons Lang you could use StringUtils.isEmpty(value) which handles all the relevant cases for you. A: You need to add ||value.equals("null") Somewhere something already did a toString() on the null value. Note the other answers as well - but this is the cause of the specific problem you're reporting. So you'd end up with, as one option: if ( value==null || value.isEmpty() || "null".equals(value) ) Because of the null-check, inverting the .equals() isn't necessary in this case - but it's a good habit to get into. A: i think value = (String)request.getAttribute("retunval"); is returning you a "null" string. When you try to do if tests that you have mentioned, it will return false because you are not checking value.equals("null") so that's why you get output as null. A: if(value.equals("")||value.length()<0||value==null) value = "Anynomous" The second and third condition can never evaluate to true! (A String's length can never be less than zero, and if value was null, value.equals("") would have caused a NullPointerException) try this instead: if(value==null||"".equals(value)) A: value.length()<0 will never be true - use value.length()==0 instead. However, in this case, the previous check (value.equals("")) is equivalent to this one, so you can omit it. Apart from this, the condition should detect empty/null strings (except that the null check should be first, to avoid dereferencing a null pointer). Is it possible that value contains the text "null"? A: Is it possible that the value of the string is 'null'? (That is, not null, but a string which reads 'null') A: Reorder as Thomas and ig0774 suggested or use the StringUtils.isEmpty() method of Apache Commons Lang. A: Use this : if(value == null || value.trim().length() <=0 || value.trim().equals("null")){ value ="Ananymous"; } A: I think this would be the best condition to check for it if(value==null || value.trim().length()==0 || value.equals("null")) it also eliminate fact if value=" " contains spaces.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: InternalInsonsistencyException in ios sdk4.3 Since I started using the IOS SDK4.3; not only have I experienced frequent crashes, I have also come across this very bad crash when I want to debug some apps: Error Log: "Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle (loaded)' with name 'MainWindow''" I have once escaped this horror by selecting a lower iPhone simulator version, but not all the time. What could actually cause this? A: Probably, MainWindow.xib no longer exists in your project.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Aggregate (count) occurences of values over arbitrary timeframe I have a CSV file with timestamps and certain event-types which happened at this time. What I want is count the number of occurences of certain event-types in 6-minutes intervals. The input-data looks like: date,type "Sep 22, 2011 12:54:53.081240000","2" "Sep 22, 2011 12:54:53.083493000","2" "Sep 22, 2011 12:54:53.084025000","2" "Sep 22, 2011 12:54:53.086493000","2" I load and cure the data with this piece of code: > raw_data <- read.csv('input.csv') > cured_dates <- c(strptime(raw_data$date, '%b %d, %Y %H:%M:%S', tz="CEST")) > cured_data <- data.frame(cured_dates, c(raw_data$type)) > colnames(cured_data) <- c('date', 'type') After curing the data looks like this: > head(cured_data) date type 1 2011-09-22 14:54:53 2 2 2011-09-22 14:54:53 2 3 2011-09-22 14:54:53 2 4 2011-09-22 14:54:53 2 5 2011-09-22 14:54:53 1 6 2011-09-22 14:54:53 1 I read a lot of samples for xts and zoo, but somehow I can't get a hang on it. The output data should look something like: date type count 2011-09-22 14:54:00 CEST 1 11 2011-09-22 14:54:00 CEST 2 19 2011-09-22 15:00:00 CEST 1 9 2011-09-22 15:00:00 CEST 2 12 2011-09-22 15:06:00 CEST 1 23 2011-09-22 15:06:00 CEST 2 18 Zoo's aggregate function looks promising, I found this code-snippet: # aggregate POSIXct seconds data every 10 minutes tt <- seq(10, 2000, 10) x <- zoo(tt, structure(tt, class = c("POSIXt", "POSIXct"))) aggregate(x, time(x) - as.numeric(time(x)) %% 600, mean) Now I'm just wondering how I could apply this on my use case. Naive as I am I tried: > zoo_data <- zoo(cured_data$type, structure(cured_data$time, class = c("POSIXt", "POSIXct"))) > aggr_data = aggregate(zoo_data$type, time(zoo_data$time), - as.numeric(time(zoo_data$time)) %% 360, count) Error in `$.zoo`(zoo_data, type) : not possible for univariate zoo series I must admit that I'm not really confident in R, but I try. :-) I'm kinda lost. Could anyone point me into the right direction? Thanks a lot! Cheers, Alex. Here the output of dput for a small subset of my data. The data itself is something around 80 million rows. structure(list(date = structure(c(1316697885, 1316697885, 1316697885, 1316697885, 1316697885, 1316697885, 1316697885, 1316697885, 1316697885, 1316697885, 1316697885, 1316697885, 1316697885, 1316697885, 1316697885, 1316697885, 1316697885, 1316697885, 1316697885, 1316697885, 1316697885, 1316697885, 1316697885), class = c("POSIXct", "POSIXt"), tzone = ""), type = c(2L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 2L)), .Names = c("date", "type"), row.names = c(NA, -23L), class = "data.frame") A: We can read it using read.csv, convert the first column to a date time binned into 6 minute intervals and add a dummy column of 1's. Then re-read it using read.zoo splitting on the type and aggregating on the dummy column: # test data Lines <- 'date,type "Sep 22, 2011 12:54:53.081240000","2" "Sep 22, 2011 12:54:53.083493000","2" "Sep 22, 2011 12:54:53.084025000","2" "Sep 22, 2011 12:54:53.086493000","2" "Sep 22, 2011 12:54:53.081240000","3" "Sep 22, 2011 12:54:53.083493000","3" "Sep 22, 2011 12:54:53.084025000","3" "Sep 22, 2011 12:54:53.086493000","4"' library(zoo) library(chron) # convert to chron and bin into 6 minute bins using trunc # Also add a dummy column of 1's # and remove any leading space (removing space not needed if there is none) DF <- read.csv(textConnection(Lines), as.is = TRUE) fmt <- '%b %d, %Y %H:%M:%S' DF <- transform(DF, dummy = 1, date = trunc(as.chron(sub("^ *", "", date), format = fmt), "00:06:00")) # split and aggregate z <- read.zoo(DF, split = 2, aggregate = length) With the above test data the solution looks like this: > z 2 3 4 (09/22/11 12:54:00) 4 3 1 Note that the above has been done in wide form since that form constitutes a time series whereas the long form does not. There is one column for each type. In our test data we had types 2, 3 and 4 so there are three columns. (We have used chron here since its trunc method fits well with binning into 6 minute groups. chron does not support time zones which can be an advantage since you can't make one of the many possible time zone errors but if you want POSIXct anyways convert it at the end, e.g. time(z) <- as.POSIXct(paste(as.Date.dates(time(z)), times(time(z)) %% 1)) . This expression is shown in a table in one of the R News 4/1 articles except we used as.Date.dates instead of just as.Date to work around a bug that seems to have been introduced since then. We could also use time(z) <- as.POSIXct(time(z)) but that would result in a different time zone.) EDIT: The original solution binned into dates but I noticed afterwards that you wish to bin into 6 minute periods so the solution was revised. EDIT: Revised based on comment. A: You are almost all the way there. All you need to do now is create a zoo-isch version of that data and map it to the aggregate.zoo code. Since you want to categorize by both time and by type your second argument to aggregate.zoo must be a bit more complex and you want counts rather than means so your should use length(). I do not think that count is a base R or zoo function and the only count function I see in my workspace comes from pkg:plyr so I don't know how well it would play with aggregate.zoo. length works as most people expect for vectors but is often surprises people when working with data.frames. If you do not get what you want with length, then you should see if NROW works instead (and with your data layout they both succeed): With the new data object it is necessary to put the type argument first. AND it surns out the aggregate/zoo only handles single category classifiers so you need to put in the as.vector to remove it zoo-ness: with(cured_data, aggregate(as.vector(x), list(type = type, interval=as.factor(time(x) - as.numeric(time(x)) %% 360)), FUN=NROW) ) # interval x #1 2011-09-22 09:24:00 12 #2 2011-09-22 09:24:00 11 This is an example modified from where you got the code (an example on SO by WizaRd Dirk): Aggregate (count) occurences of values over arbitrary timeframe tt <- seq(10, 2000, 10) x <- zoo(tt, structure(tt, class = c("POSIXt", "POSIXct"))) aggregate(as.vector(x), by=list(cat=as.factor(x), tms = as.factor(index(x) - as.numeric(index(x)) %% 600)), length) cat tms x 1 1 1969-12-31 19:00:00 26 2 2 1969-12-31 19:00:00 22 3 3 1969-12-31 19:00:00 11 4 1 1969-12-31 19:10:00 17 5 2 1969-12-31 19:10:00 28 6 3 1969-12-31 19:10:00 15 7 1 1969-12-31 19:20:00 17 8 2 1969-12-31 19:20:00 16 9 3 1969-12-31 19:20:00 27 10 1 1969-12-31 19:30:00 8 11 2 1969-12-31 19:30:00 4 12 3 1969-12-31 19:30:00 9
{ "language": "en", "url": "https://stackoverflow.com/questions/7528571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to change number of decimal places and add decimal button iPhone Calculator? So, look at the following code below- my first question is, how can I make it so there is only 0, 1, or 2 decimal places or make it automatically have however many decimal places are there? the second question is, how would I add a decimal button to the calculator? it has +-/*, how would I add a decimal button? Tutorial I used is here http://www.youtube.com/watch?v=Ihw0cfNOrr4 and here is my code- viewcontroller.h #import <UIKit/UIKit.h> @interface calcViewController : UIViewController { float result; IBOutlet UILabel *calculatorScreen; int currentOperation; float currentNumber; } -(IBAction)buttonDigitPressed:(id)sender; -(IBAction)buttonOperationPressed:(id)sender; -(IBAction)cancelInput; -(IBAction)cancelOperation; @end in the .m #import "calcViewController.h" @implementation calcViewController -(IBAction)buttonDigitPressed:(id)sender { currentNumber = currentNumber *10 + (float)[sender tag]; calculatorScreen.text = [NSString stringWithFormat:@"%2f", currentNumber]; } -(IBAction)buttonOperationPressed:(id)sender { if (currentOperation ==0) result = currentNumber; else { switch (currentOperation) { case 1: result = result + currentNumber; break; case 2: result = result - currentNumber; break; case 3: result = result * currentNumber; break; case 4: result = result / currentNumber; break; case 5: currentOperation = 0; break; } } currentNumber = 0; calculatorScreen.text = [NSString stringWithFormat:@"%2f", result]; if ([sender tag] ==0) result=0; currentOperation = [sender tag]; } -(IBAction)cancelInput { currentNumber =0; calculatorScreen.text = @"0"; } -(IBAction)cancelOperation { currentNumber = 0; calculatorScreen.text = @"0"; currentOperation = 0; } A: you can use this on the output. Float *number = 2.2f; NSLog(@"%.2f",number); A: Another thing you want to take note about the point is that you do not want to have multiple point in your calculation, e.g. 10.345.1123.5. Simply put, you want it to be a legal float number as well. With that said, you can use a IBAction (remember to link it to your storyboard or xib file) -(IBAction)decimalPressed:(UIButton *)sender { NSRange range = [self.display.text rangeOfString:@"."]; if (range.location ==NSNotFound){ self.display.text = [ self.display.text stringByAppendingString:@"."]; } self.userIsInTheMiddleOfEnteringANumber = YES; } While it might be possible we are doing on the same project, it could also be entirely different (you starting from scratch by yourself) so i will go through some of the codes you could replace UIButton with the default id, but it is better to static replace it to make clear clarification for yourself, or anyone else who view your code. NSRange as the name implies, mark the range, and the range will be ur display text of calculation (e.g. 1235.3568), and the range of string it is targeting in this case is "." therefore, if NSNotfound (rangeOfString "." is not found in the text range) you will append the current display text with "." with the function stringByAppendingString:@".", there is no else, so no function will take place if "." is already found, which solve the problem of multiple point on the display. userIsInTheMiddleOfEnteringANumber is a BOOL to solve the problem of having 0 in ur display (e.g. 06357), if you have a method to change it, then replace my method name with your own. Regarding the display, as I'm using a different approach compared to yours, I'm unable to give any help or guide in that aspect. A: This is my solution: ViewController.h #import <UIKit/UIKit.h> @interface ViewController : UIViewController { float result; IBOutlet UILabel *TextInput; int currentOperation; float currentNumber; BOOL userInTheMiddleOfEnteringDecimal; } - (IBAction)buttonDigitPressed:(id)sender; - (IBAction)buttonOperationPressed:(id)sender; - (IBAction)cancelInput; - (IBAction)cancelOperation; - (IBAction)dotPressed; @end Viewcontroller.m #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } - (IBAction)buttonDigitPressed:(id)sender { if(!userInTheMiddleOfEnteringDecimal) { currentNumber = currentNumber*10 + (float)[sender tag]; TextInput.text = [NSString stringWithFormat:@"%d",(int)currentNumber]; } else{ TextInput.text= [TextInput.text stringByAppendingString:[NSString stringWithFormat:@"%d",[sender tag]]]; currentNumber = [TextInput.text floatValue]; } } - (IBAction)buttonOperationPressed:(id)sender { if (currentOperation == 0) result = currentNumber; else { switch (currentOperation) { case 1: result = result + currentNumber; break; case 2: result = result - currentNumber; break; case 3: result = result * currentNumber; break; case 4: result = result / currentNumber; break; case 5: currentOperation = 0; break; default: break; } } currentNumber = 0; TextInput.text = [NSString stringWithFormat:@"%.2f",result]; if ([sender tag] == 0) result = 0; currentOperation = [sender tag]; userInTheMiddleOfEnteringDecimal = NO; } -(IBAction)cancelInput{ currentNumber = (int)(currentNumber/10); TextInput.text = [NSString stringWithFormat:@"%.2f",currentNumber];; } -(IBAction)cancelOperation{ currentNumber = 0; TextInput.text = @"0"; userInTheMiddleOfEnteringDecimal = NO; } - (IBAction)dotPressed{ if(!userInTheMiddleOfEnteringDecimal){ userInTheMiddleOfEnteringDecimal = YES; TextInput.text= [TextInput.text stringByAppendingString:@"."]; } } @end Hope this helps.. This includes the decimal point in the button...
{ "language": "en", "url": "https://stackoverflow.com/questions/7528587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: select specific cells and place data in other cells excel I'm looking for a function from which i can select specific cells and place them in the other columns. For example, I have data in the following form: - Food Processor - 756 - 890 - Washing Machine - 290 - 900 - Mixer - 123 - 893 Now, i want the data in the following form in separate columns: - Food Processor - Washing Machine - Mixer in one column And the prices in two separate columns. How do i do that? Thank you! A: If you data there was in A1:A9 and you needed every 3rd row in column B then in B1 =OFFSET($A$1,3*(ROW()-1),0) and copy down will give you the 3 records you want from A1,A4,A7 in B1, B2, B3
{ "language": "en", "url": "https://stackoverflow.com/questions/7528590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C# Render color in image as transparent I'm displaying a .bmp file in a Form. Is there any way to render the color black as transparent? A: You could try myBitmap.MakeTransparent(Color.Black)
{ "language": "en", "url": "https://stackoverflow.com/questions/7528595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make ClickOnce target .NET 2.0 and not 3, 3.5 or 4 I've got a simple ClickOnce application - it only targets .NET 2.0, but in the prerequisites I've got to select .NET 3.5 as a minimum prerequisite, whereas I really want to have .NET 2.0 as a prerequisite. I'm in Visual Studio 2010... What do I do? A: Right click on the project, select Properties and then Application. Make sure the target framework is .NET Framework 2.0 (Repeat the operation if your solution contains more than one project.) Then select Publish. Click on the prerequisites button and make sure that if the setup program creation is selected, on .NET Framework 2.0 is checked. That should do it. A: You can copy the .NET 2.0 bootstrapper package from Visual Studio 2008's folders to Visual Studio 2010's folders and it will magically show up and work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: System.currentTimeMillis() is a good choice for this? I'm still not sure how System.currentTimeMillis() work, but I want to use it for a game server to handle Banned accounts. For example, in data base I will have a "bannTime" which will equal (System.currentTimeMillis() + How_much_time_to_ban_in_ms ) in the user's data. When the user will login, it will always check if it's OK using this: if(bannTime==-1)return; if(System.currentTimeMillis()>bannTime){ // It's ok you can long in removeBanFromDataBase(); }else{ // You can not login, you have to wait: (bannTime - System.currentTimeMillis()) return; } What I need to know is: Is it safe to use System.currentTimeMillis() like this as long as the code will always run on one machine ? Even if I reboot the machine, System.currentTimeMillis() will keep incrementing and never go back or start from zero ? Never ? And what If I change the local time and date on the machine, System.currentTimeMillis() will change too ? A: System.currentTimeMillis() will never reset to 0. It is the number of milliseconds since the Epoch, way back at midnight, January 1, 1970. This approach is fine, and it's often easier to do maths with milliseconds, as you're finding out. Ref: http://download.oracle.com/javase/6/docs/api/ edit: good point Spycho, the currentTimeMillis() response is based on the system clock, not magic, so changing the system time back by a couple of days would make the number decrease. But not in normal practice. If you're using time to ban users, you will probably want to use an NTP service to keep your system clock correct (if you're not already). A: System.currentTimeMillis() may go back (or leap forward) if the system clock is changed. A: If this code is running on the server side you should be fine. Due to leap seconds (or manual clock changes) the time on the server can change, but it shouldn't change by such a large amount that it actually matters if the ban is revoked too early. You should, of course, ensure that the server is set to get its time via NTP, so that it's always as accurate as possible, and correctly set on reboot. A: System.currentTimeMillis() is always the actual time, in milliseconds since midnight 1st January 1970 UTC, according to the local system. If you change the time on the machine, the output of System.currentTimeMillis() will also change. The same applies if you change the machine's timezone but leave the time unchanged. System.currentTimeMillis() will never reset to zero (unless you change the machine's time to be whatever the time was in the machine's timezone at 00:00:00.000 on 1st January 1970). System.currentTimeMillis() should be fine for what you want to do. A: you could use a combination of that in addition to writing a file on the system and storing the timestamp/related information in the file A: You may like to set a `reboot counter (or program restart counter),' which is persistent (in db or file), to distinguish time-stamps recorded in different boot sessions. And then record your time-stamp by the combination of System.currentTimeMillis() and the counter's value When the reboot counters are different for two time-stamps, you may deal it differently from normal cases. Maybe launching a time synchronizing routine or something. A: When using System.currentTimeMillis() you are getting the time of the System, in other words the time of the machine you are running your code on. So when you restart your machine, you will still get its time that will increment even when the machine is turned off for sure. But when you change the time of the machine, System.currentTimeMillis() will get you the new time, the time you changed. So when the time is changed you will get wrong time. I used this in many classes without holding the matter of changing the clock. You can just use it with only this risk. But I find it a very good choice to work on. A: An alternative would be to use System.nanoTime() because a) its more accurate and b) its monotonically increasing. However its slightly more cumbersome to work in nano-seconds, and its highly unlikely to make any real difference, unless your system clock varies wildly by seconds or more. (In which case you are likely to have other problems) A: just test this code. change time while running this code. System.currentTimeMillis() stops printing out when system time is set back. it starts printing again when time > time_before_setting_back while (true){ System.out.println(System.currentTimeMillis()); try { Thread.sleep(1000); } catch ( InterruptedException e ) { e.printStackTrace(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7528602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Multiple Annimations created by CSS transitions on iOS only Very perplexing problem has arisen. The following webpage has a search input at the top that when focus a changes class attributes with a series of transition effects. Some JQuery the binds the focus event and displays a tooltip. On iOS the transition happens 3 times before it finally settles in focus and the tooltip never appears. Here is the link in question http://www.golfbrowser.com/WebObjects/header.html Any ideas why? Marvellous As REQUESTED JQUery $('#header .search input').blur(function(){ $('#header .results').removeClass('visible'); }); $('#search').focus(function(){ if($(this).val() == '' || $(this).val() == $(this).attr('placeholder')){ $('.suggestion').addClass('visible'); }}); $('#search').blur(function(){ $('#header .suggestion').removeClass('visible'); }); CSS #header .search input { height:32px; width:60px; background:url(header/magglass.png) 2px 5px no-repeat; padding-left:28px; margin-right:5px; font-family:"Helvetica Neue", "Myriad Pro", Arial; font-weight:bold; font-size:13px; color:#FFF; float:left; background-color:#454545; border:0px; border-bottom-left-radius:10px; border-bottom-right-radius:0px; border-top-left-radius:0px; border-top-right-radius:0px; -moz-border-radius-bottomleft:10px; -moz-border-radius-bottomright:0px; -moz-border-radius-topright:0px; -moz-border-radiustopleft:0px; opacity:0.75;filter:alpha(opacity=75); text-decoration:none; display:block; -webkit-transition-property:all; -webkit-transition-duration:500ms; -moz-transition-property:all; -moz-transition-duration:500ms; -webkit-transition-delay:1000ms; -moz-transition-delay:1000ms; outline:none; -moz-box-sizing: content-box; -webkit-box-sizing: content-box; box-sizing: content-box; } #header .search input:focus { width:220px; background-color:#FFF; border-color:#FFF; color:#222; opacity:1.0;filter:alpha(opacity=100); -webkit-transition-delay:0ms; -moz-transition-delay:0ms; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7528608", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I take listener methods out of their scope in Java? public class SomeClass { public void SomeMethod() { GridView gv = new GridView(this); gv.setOnClickListener(new GridView.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub } }); } // Define onClick here and reference it somehow above? } How can I take the onClick method out of that block of code into the root of the class? Like you can do it on C#, for instance. A: create the following inner class class click implements OnClicklIstener { public void onClick(View v) { // do your stuff } } and gv.setOnClickListener(new click()); A: Easy, just implement the OnClickListener interface. public class SomeClass extends Activity implements OnClickListener // Implement the OnClickListener callback public void onClick(View v) { // check the view type : Use View v to check which view is this called for using getId () } ... Note that you have to check which view has been clicked before doing your handling. A: You can declare a Listener as any other class attribute: public class HomeActivity extends Activity { public void SomeMethod() { GridView gv = new GridView(this); gv.setOnClickListener(gridClickedListener); } private GridView.OnClickListener gridClickedListener = new GridView.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub } }); } Or implement the OnClickListener (or other) interfaces, but you will need to know which which view was clicked (switch inside the OnClick handler) if several views will report to this listener. I tend not to use this approach - it looks less readable for me. A: Like this: public class SomeClass { public void SomeMethod() { GridView gv = new GridView(this); gv.setOnClickListener(new GridView.OnClickListener() { @Override public void onClick(View view) { SomeClass.this.onClick(view); } }); } public void onClick(View view) { // implement me please } } A: public class SomeClass extends Activity implements View.OnClickListener { GridView gv; public void SomeMethod() { gv = new GridView(this); gv.setOnClickListener(this); } @Override public void onClick(View v) { if(v==gv) { // do something when the button is clicked } } A: Won't this work? public class SomeClass implements GridView.OnClickListener { public void SomeMethod() { GridView gv = new GridView(this); gv.setOnClickListener(this); } @Override public void onClick(View arg0) { // TODO Auto-generated method stub } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7528610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make two side by side Qt Windows sticky and act like a single window? I am trying to implement a scenario where two Qt windows will be placed side by side and they will be kind of sticky to each other. By dragging one of them, the other also gets dragged. Even when doing an alt-tab they should behave like a single window. Any help or pointer will be extremely helpful. -Soumya A: What you describe sounds like it's a good fit for a "docking" scenario. You're probably most familiar with docking from toolbars; where you can either float a toolbar on its own or stick it to any edge of an app's window. But Qt has a more generalized mechanism: http://doc.qt.io/qt-5/qtwidgets-mainwindows-dockwidgets-example.html http://doc.qt.io/qt-5/qdockwidget.html It won't be a case where multiple top level windows are moved around in sync with their own title bars and such. The top-level windows will be merged into a single containing window when they need to get "sticky". But IMO this is more elegant for almost any situation, and provides the properties you seem to be seeking. A: Install a event filter on the tracked window with QObject::installEventFilter() and filter on QEvent::Move You can then change the position of tracking window whenever your filter is called with that event type. A: I found a way to keep two windows anchored: when the user moves a window, the other follows, keeping its relative position to the moved one. It is a bit of a hack, because it assumes that the event QEvent::NonClientAreaMouseButtonPress is sent when the user left clicks on the title bar, holding it pressed while he moves the window, and releasing it at the end, so that QEvent::NonClientAreaMouseButtonRelease is sent. The idea is to use the QWidget::moveEvent event handler of each window to update the geometry of the other, using QWidget::setGeometry. But the documentation states that: Calling setGeometry() inside resizeEvent() or moveEvent() can lead to infinite recursion. So I needed to prevent the moveEvent handler of the windows which was not moved directly by the user, to update the geometry of the other. I achieved this with result via QObject::installEventFilter, intercepting the summentioned events. When the user clicks on the title bar of WindowOne to start a move operation, WindowOne::eventFilter catches its QEvent::NonClientAreaMouseButtonPress and sets the public attribute WindowTwo::skipevent_two to true. While the user is moving WindowOne, WindowTwo::moveEvent is called upon the setGeometry operation, performed on WindowTwo from WindowOne::moveEvent. WindowTwo::moveEvent checks WindowTwo::skipevent_two, and if it is true, returns without performing a setGeometry operation on WindowOne which would cause infinite recursion. As soon as the user releases the left mouse button, ending the window move operation, WindowOne::eventFilter catches QEvent::NonClientAreaMouseButtonRelease and sets back the public attribute WindowTwo::skipevent_two to false. The same actions are performed if the user clicks the titlebar of WindowTwo, this time causing WindowOne::skipevent_one attribute to be set to true and preventing WindowOne::moveEvent to perform any setGeometry operation on WindowTwo. I believe this solution is far from being clean and usable. Some problems: * *I am not sure when and why QEvent::NonClientAreaMouseButtonRelease and QEvent::NonClientAreaMouseButtonRelease are dispatched, apart from the case considered above. *When/if one window is resized without user interaction or without the proper mouse clicks from the user, probably everything will go the infinite recursion way. *There is no guarantee that those mouse events will be dispatched the same way in the future. *Free space for more... Proof of concept: https://github.com/Shub77/DockedWindows
{ "language": "en", "url": "https://stackoverflow.com/questions/7528612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Problem in remove sqlite connection in QT I've got following error when i want to remove my QSqlDatabase that connected to the Sqltie: QSqlDatabasePrivate::removeDatabase: connection 'cnnDFP' is still in use, all queries will cease to work. *cnnDFP is my connection name How can i fix this? please help me A: You're not showing you're code, so it is difficult to guess what is wrong. Anyway, have you read the documentation: http://doc.qt.io/qt-5/qsqldatabase.html#removeDatabase? Did you close all the queries before trying to remove the connection?
{ "language": "en", "url": "https://stackoverflow.com/questions/7528615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to reduce the time in executing Selenium test cases? I'm writing the Selenium test cases for each screen to test the different scenarios. In our project for each build in Jenkins, its Selenium test cases (QA) also runs automatically. My problem is even though it's automated, it's taking a lot of time to run. I have 380 test cases and it's taking 20-25 minutes. How can I reduce the time? Are there any other ways or techniques to follow? A: you can check for the Selenium grid option, which will help you to run the tests in parallel. http://selenium-grid.seleniumhq.org/ A: In the 380 testcases you have , check if all the testcases are really required . If all the testcases are required , check if u are having any repeated validations and see if you can remove any one of them . If you are using wait time in your testcases , see if you can reduce the wait times with out affecting the output of the testcases . The best thing would be to split them in to seperate groups and run them in different machines using Grid . Or use TestNg/JUnit to run the testCases parallely . In TestNg , in the testng.xml file , u can use the following to run them in parallel <suite name="ParallelTests" verbose="5" parallel="methods" thread-count="10">
{ "language": "en", "url": "https://stackoverflow.com/questions/7528619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: symfony2 API authentication and routing I followed the instructions for creating a custom authentication provider: http://symfony.com/doc/current/cookbook/security/custom_authentication_provider.html app/config/security: firewalls: wsse_protection: pattern: ^/api/.* wsse: true main: pattern: ^/ form_login: provider: fos_userbundle logout: true anonymous: true Now I have some Actions in the Controllers with routes. e.g: ExampleController with listAction routing: example_list: pattern: /example/list defaults: { ... } Do I have to copy all the routes to example_api_list? Because api/example/list didnt work (no route found for /api/example/list). I thought the pattern from the firewall is a prefix for all defined routes. A: The firewall isn't a prefix, it's a regular expression that matches against incoming routes. In this case, anything starting with /api will be matched by your wsse_protection firewall, and everything that falls through will be matched by your main firewall. To create routes under /api/*, you'll have to define the routing separately.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528621", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CodeIgniter Template Library I am using CodeIgniter with Template Library and have set up my template view file. Part of my template that doesn't change from page to page displays data from a database. What is the best way to include this data in my template? A: If the content doesn't change very often, something like the user's name, I would store it in the session and call it from there. Otherwise, if you really need to query it on every page request, I would create a base controller (MY_Controller) then create and assign a protected var that you can access from your controllers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL ERROR When i join 2 tables Sorry let me revise. I have a three tables: events_year • EventID • YearID • id Date • YearID • Year Event • EventID • EventName • EventType i want to dispay a record from the three tables like so: EventName - Year: Marathon - 2008 i linked it to a table called "members" which contains a ID number field (members-id) so i can limit the results to members id = $un(which is a username from a session) I need to join the three tables and limit the results to the specific ID number record Here is my portion of the code: $query = "SELECT * FROM members JOIN events_year ON members.id = events_year.id "; "SELECT * FROM Event JOIN events_year ON Event.EventID = events_year.EventID WHERE username = '$un'"; "SELECT * FROM Date JOIN events_year ON Date.YearID = events_year.YearID WHERE username = '$un'"; $results = mysql_query($query) or die(mysql_error()); while ($row = mysql_fetch_array($results)) { echo $row['Year']; echo " - "; echo $row['Event']; echo "<br>"; } A: the notices are almost self-explaining. There are no 'Year' and 'EventName' fields in the resultset. It's difficult (or: impossible) to tell why this happens as you haven't given your table-structure, but i guess this: 'Year' is a field of the date-table, 'EventName' is a field of the event-table - you're only selecting from members so this fields don't occur. I don't understand why there are three sql-statements but only one is assigned to a variable - the other two are just standing there and do nothing. Please explain this and put more information into your question about what you're trying to achive, what your table-structure looks like and whats your expected result. I think what you really wanted to do is some kind of joined query, so please take a look at the documentation to see how this works. finally, i think your query should look like this: SELECT * FROM members INNER JOIN events_year ON members.id = events_year.id INNER JOIN Event ON Event.EventID = events_year.EventID INNER JOIN ´Date´ ON ´Date´.YearID = events_year.YearID WHERE members.username = '$un' A: Does the field 'Year' exist in the query output ? I suspect not. A: the string $query is only using the first line of text: "SELECT * FROM members JOIN events_year ON members.id = events_year.id "; and not the others. The query itself is not returning any fields that are called Year or EventName. Do a var_dump($row) to find out what is being returned.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528631", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Drupal - Attach files automatically by name to nodes i need better file attachement function. Best would be that if you upload files to FTP and have a similar name as the name of the node (containing the same word), so they appear under this node (to not have to add each file separately if you need to have more nodes below). Can you think of a solution? Alternatively, some that will not be as difficult as it always manually add it again. Dan. A: This would take a fair bit of coding. Basically you want to implement hook_cron() and run a function that loops through every file in your FTP folder. The function will look for names of files that have not already been added to any node and then decide which node to add them to. Bear in mind there will be a delay once you upload your files until they are attached to the node until the next cron job runs. This is not a good solution and if I could give you any advice it would be not to do it - The reason you upload files through the Drupal interface is so that they are tracked in the files table and can be re-used. Also the way you're proposing leaves massive amounts of ambiguity as to which file will go where. Consider this: You have two nodes, one about cars and one about motorcycle sidecars. Your code will have to be extremely complex to make the decision of which node to add to if the file you've uploaded is called 'my-favourite-sidecar.jpg'.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528639", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating a JSON response from Google Application Engine Purely as an academic exercise I wanted to convert one of my existing GAE applets to return the response back to Android in JSON and parse it accordingly. The original XML response containing a series of booleans was returned thus: StringBuilder response = new StringBuilder(); response.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); response.append("<friend-response><added>"); response.append(friendAdded); response.append("</added><removed>"); response.append(friendRemoved); response.append("</removed><found>"); response.append(friendFound); response.append("</found></friend-response>"); I want to replace this with a JSON response that looks something like this: { "friendResponse" : [ { "added":true, "removed":false, "found":true } ]} I think I can generate the array contents as follows (I haven't tested it yet) but I don't know how to create the top-level friendResponse array itself. I can't seem to find any good examples of creating JSON responses in Java using the com.google.appengine.repackaged.org.json library. Can anyone help put me on the right path? boolean friendAdded, friendRemoved, friendFound; /* Omitted the code that sets the above for clarity */ HttpServletResponse resp; resp.setContentType("application/json"); resp.setHeader("Cache-Control", "no-cache"); JSONObject json = new JSONObject(); try { //How do I create this as part of a friendResponse array? json.put("added", friendAdded); json.put("removed", friendRemoved); json.put("found", friendFound); json.write(resp.getWriter()); } catch (JSONException e) { System.err .println("Failed to create JSON response: " + e.getMessage()); } A: You need to use JSONArray to create the (single-element) array that will store your object: try { JSONObject friendResponse = new JSONObject(); friendResponse.put("added", friendAdded); friendResponse.put("removed", friendRemoved); friendResponse.put("found", friendFound); JSONArray friendResponseArray = new JSONArray(); friendResponseArray.put(friendResponse); JSONObject json = new JSONObject(); json.put("friendResponse", friendResponseArray); json.write(resp.getWriter()); } catch (JSONException e) { System.err .println("Failed to create JSON response: " + e.getMessage()); } A: You can use GSON: https://sites.google.com/site/gson/gson-user-guide#TOC-Object-Examples With this framework, you can serialize an object to json, and vice versa.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: In bash, how can I have a set of arguments in any random order? Like a key-value pair? Example: ./myscript --ip 192.168.1.1 --port 1985 or another possible ./myscript --port 1985 --ip 192.168.1.1 I want to allow my script to take a set of arguments, in any order ./myscript a b c d ./myscript d c b a ./myscript b d a c Etcetera A: You can use getopts to parse command-line arguments. This tutorial is quite useful to get started with. A: This simple script takes the port number with p and ip address with i parameter. while getopts "i:p:" option; do case $option in i ) ip_address=$OPTARG echo "ip address: $ip_address" ;; p ) port_number=$OPTARG echo "port number: $port_number" ;; esac done Can be executed in either ways: ./myscript -i 192.168.1.1 -p 1985 or ./myscript -p 1985 -i 192.168.1.1 When executed it prints: ip address: 192.168.1.1 port number: 1985 Also as mentioned at http://wiki.bash-hackers.org/howto/getopts_tutorial Note that getopts is not able to parse GNU-style long options (--myoption) or XF86-style long options (-myoption) So you cannot use long strings as --port or --ip directly with getopts. However additional workarounds available as described in this link: http://www.bahmanm.com/blogs/command-line-options-how-to-parse-in-bash-using-getopt A: take a look at getopts getopts: getopts optstring name [arg] Parse option arguments. Getopts is used by shell procedures to parse positional parameters as options. OPTSTRING contains the option letters to be recognized; if a letter is followed by a colon, the option is expected to have an argument, which should be separated from it by white space. Each time it is invoked, getopts will place the next option in the shell variable $name, initializing name if it does not exist, and the index of the next argument to be processed into the shell variable OPTIND. OPTIND is initialized to 1 each time the shell or a shell script is invoked. When an option requires an argument, getopts places that argument into the shell variable OPTARG. getopts reports errors in one of two ways. If the first character of OPTSTRING is a colon, getopts uses silent error reporting. In this mode, no error messages are printed. If an invalid option is seen, getopts places the option character found into OPTARG. If a required argument is not found, getopts places a ':' into NAME and sets OPTARG to the option character found. If getopts is not in silent mode, and an invalid option is seen, getopts places '?' into NAME and unsets OPTARG. If a required argument is not found, a '?' is placed in NAME, OPTARG is unset, and a diagnostic message is printed. If the shell variable OPTERR has the value 0, getopts disables the printing of error messages, even if the first character of OPTSTRING is not a colon. OPTERR has the value 1 by default. Getopts normally parses the positional parameters ($0 - $9), but if more arguments are given, they are parsed instead. Exit Status: Returns success if an option is found; fails if the end of options is encountered or an error occurs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Can't get Flixel preloader working via flash IDE I'm currently trying to work with flixel library via Flash IDE. Everything is okay except the preloader - it just doesn't work. I suppose the flash IDE does not support the directive [Frame(factoryClass="Preloader")], which flixel uses when being compiled in flex builder to create a preloader. Any way to get the flixel preloader working with ide (without modifying flixel sources)? UPD: Also, i want to avoid using frames. A: The [Frame] metdata tag is ignored by the Flash IDE compiler, but all that instruction does is to place all the code with the exception of the Preloader class (in your example, or whatever is the defined 'factoryClass') onto the second frame. Since you have a timeline right there in the Flash IDE, you can put the instantiation of the Preloader class definition into the first frame for yourself, and add the rest of the code onto the second frame. Remember to put a stop on the second frame. Alternatively, and probably a better solution, is to get a copy of Flash Builder, FDT or Flash Develop, all of which should respect your [Frame] metadata, or can very easily with the right flags. More information about the [Frame] metadata can be found here: http://www.bit-101.com/blog/?p=946 (which is probably where Flixel got the idea from in the first place). Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: GlassFish redirect www to non-www domain Is it possible to redirect users from www.domain.com to domain.com? I'm running GlassFish 3.1.1 with JSF/EJB app in root context (/). It would be also nice to keep context path/params: www.domain.com/subpage/title/ -> domain.com/subpage/title/ A: Redirect from docroot to an external url in glassfish discusses three ways to do this - every single one requires some extra efforts: * *Modify the DNS mapping in your DNS server; *Use UrlRewriteFilter; or *Put a web server - like apache httpd - in front of glassfish.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528656", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: M2M in Open Source Is there any open source(it may be c,c++ and java) for machine to machine communication ? I would like to make communication between my hospital ECG device and my pc. Serial port with Linux platform Thanks -Anlon A: M2M is a generic term. there is no standard protocol or medium to implement a machine-to-machine communication. thus ou have to search for yourself which communication mean would best fit your need, depending on your device. basically any communication channel can be considered a m2m channel: serial port, usb port, ethernet, also gsm/sms for gsm enabled devices. as for the protocol, it depends on the protocol used by your device (you won't be able to modify your ecg device to fit a specific protocol of your choice, you will have to stick to what format the data comes out of your device). A: There's currently an initiave at Eclipse Foundation to start to gather efforts around Open Source M2M and 2 projects from this initiative are starting: 1 about tooling (Koneki) and 1 about M2M protocol (Paho). A: You might be interested in trying out Mihini, a project recently added to the Eclipse M2M initiative that provides an open-source embedded framework for M2M. It allows to really easily do serial communication with Linux. I don't know what protocol your ECG is talking, but there's e.g. built-in support for the Modbus protocol in Mihini.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528662", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: pin drop animation The default pin drop animation doesn't work in my app, here is some code I wrote: - (void)viewDidLoad { /* some code... */ [theMapView addAnnotation:addAnnotation]; [addAnnotation release]; } - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation{ MKPinAnnotationView *annoView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"current"]; annoView.animatesDrop = YES; annoView.pinColor = MKPinAnnotationColorGreen; return annoView; } Right now the pin just appear in the screen as default red one without any animation, the MKMapViewDelegate protocol has been adopted, anyone can see what's wrong here? A: First use: [yourMap_view setDelegate:self]; in ViewDidLoad Then call this for the drop animation : - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation { MKPinAnnotationView *pinView = nil; if(annotation!= map_view.userLocation) { static NSString *defaultPin = @"pinIdentifier"; pinView = (MKPinAnnotationView*)[map_view dequeueReusableAnnotationViewWithIdentifier:defaultPin]; if(pinView == nil) pinView = [[[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:defaultPin]autorelease]; pinView.pinColor = MKPinAnnotationColorPurple; //Optional pinView.canShowCallout = YES; // Optional pinView.animatesDrop = YES; } else { [map_view.userLocation setTitle:@"You are Here!"]; } return pinView; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7528665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How can I rewrite s domain name to the original IDN not the punycode? I have bought an IDN domain name with non-latin characters. It is good but when I access the domain name, the address bar shows the punycode for the domain not the actual domain which will be hard for any user to remember. Is there is anyway I can rewrite the domain name to the original IDN not the punycode? example: IDN = افلاماونلاين.com punycode that show in address bar = xn--mgbaaa1ksacgkcs1a.com A: The way that address bar is displayed is dependent on browser, its version, and possibly the used locale: * *regardless of the locale, I see افلاماونلاين.com in Opera 11 *I see xn--mgbaaa1ksacgkcs1a.com in Firefox 6 and Chrome 14 in my default locale (cs_CZ) *however, when I set locale to ar in Chrome, it shows the original version of the IDN (like Opera) *IE6 dies a horrible death (as expected) *IE7 shows the punycoded version *IE8 shows the punycoded version + an information button listing both versions So, I'm afraid that there's not much that you can do about this as the site owner, unfortunately.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Get a leaf nodes by recursive query I have a categories structure as follows I want to select leaf node. i mean the the categories who don't have sub categories. In my database monitor, cpu, novels and comics will be answer. Any help will be appreciated. Edit : I tried this. public function get_valid_categories($parent) { $has_childs = false; foreach($this->categories as $key => $value) { if ($value['parent'] == $parent) { if ($has_childs === false) { $has_childs = true; } else { $this->valid_categories[] = $value['name']; } $this->get_valid_categories($key); } } if ($has_childs === true) { return $this->valid_categories ; } } and i m calling this function as follows get_valid_categories(0); A: You don't need a recursive query for this. How about the following SQL: select t1.* from table t1 left join table t2 on t1.id = t2.parent_id where t2.id is null This takes the rows in your table and self-joins to get each row's children. It then filters out those rows that have no children by checking for t2.id is null. A: Well, there are probably many possible solutions but here is the first one that came to my mind: SELECT * FROM categories WHERE id NOT IN ( SELECT DISTINCT(parent_id) FROM categories ) Not so elegant as using joins, but can be an alternative solution for the problem. Hope that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528672", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problem comparing arrays of Strings with nested loops This is the problem I am trying to solve: I have two arrays of Strings ("matches" and "visibleObjects"). I would like to search through all the words in the array "matches" to see if there is at least one word from the array "visibleObjects". If this condition is satisfied, I'd like to search through the words in "matches" again this time looking for at least a word from the array "actionWords". This is what I have, where "testDir" is just a debug string that gets printed: protected void Action(){ boolean actionWord = false; String target = null; testDir = "first stage"; firstLoop: for(String word : matches) { testDir += " " + word; for(String hint : visibleObjects) { testDir += " " + hint; if(word.equals(hint)) { target = word; //found a matching word testDir = "Hint found"; break firstLoop; } } } if(target != null) { testDir = "stage two"; secondLoop: for(String word : matches) { for(String action : actionWords) { if(word.equals(action)) { actionWord = true; //found one word from the actionWords array testDir = "Acion OK"; break secondLoop; } } } } if(actionWord){ testDir = target; performAction(target); } } All I get printed is the first word from the array matches and all the words from the array visibleObject once, so it doesnt get past the second loop.... Is this code right? Can anyone spot the bug? Thanks for your help! A: You stop the outer loop on the first match (break firstLoop;) - and I assume that is not what you want, do you? Instead do one of the following: * *continue the outer loop instead of stopping it (continue firstLoop;) *break the inner loop only (break;) A: The code seems to work fine for me: public static void main(String[] args) { String[] matches = { "a", "b", "c" }; String[] visibleObjects = { "c", "d", "e" }; String target = null; firstLoop: for (String word : matches) { for (String hint : visibleObjects) { if (word.equals(hint)) { target = word; break firstLoop; } } } System.out.println(target); } This prints out c. If you have no match it would print null. Note that you could also use one loop and the List.contains(...) method, like this List<String> l = Arrays.asList(visbleObjects) for (String word : matches) { if (l.contains(word)) { target = word; break; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7528677", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to delete an already existing layout on a widget? You must first delete the existing layout manager (returned by layout()) before you can call setLayout() with the new layout. from http://doc.qt.io/qt-5.9/qwidget.html#setLayout Which function is used for deleting the previous layout? A: This code deletes the layout, all its children and everything inside the layout 'disappears'. qDeleteAll(yourWidget->findChildren<QWidget *>(QString(), Qt::FindDirectChildrenOnly)); delete layout(); This deletes all direct widgets of the widget yourWidget. Using Qt::FindDirectChildrenOnly is essential as it prevents the deletion of widgets that are children of widgets that are also in the list and probably already deleted by the loop inside qDeleteAll. Here is the description of qDeleteAll: void qDeleteAll(ForwardIterator begin, ForwardIterator end) Deletes all the items in the range [begin, end] using the C++ delete > operator. The item type must be a pointer type (for example, QWidget *). Note that qDeleteAll needs to be called with a container from that widget (not the layout). And note that qDeleteAll does NOT delete yourWidget - just its children. Now a new layout can be set. A: I want to remove the current layout, replace it with a new layout but keep all widgets managed by the layout. I found that in this case, Chris Wilson's solution does not work well. The layout is not always changed. This worked for me: void RemoveLayout (QWidget* widget) { QLayout* layout = widget->layout (); if (layout != 0) { QLayoutItem *item; while ((item = layout->takeAt(0)) != 0) layout->removeItem (item); delete layout; } } A: Chris Wilson's answer is correct, but I've found the layout does not delete sublayouts and qwidgets beneath it. It's best to do it manually if you have complicated layouts or you might have a memory leak. QLayout * layout = new QWhateverLayout(); // ... create complicated layout ... // completely delete layout and sublayouts QLayoutItem * item; QLayout * sublayout; QWidget * widget; while ((item = layout->takeAt(0))) { if ((sublayout = item->layout()) != 0) {/* do the same for sublayout*/} else if ((widget = item->widget()) != 0) {widget->hide(); delete widget;} else {delete item;} } // then finally delete layout; A: You just use delete layout; like you would with any other pointer you created using new. A: From Qt6's docs: The following code fragment shows a safe way to remove all items from a layout: QLayoutItem *child; while ((child = layout->takeAt(0)) != nullptr) { ... delete child->widget(); // delete the widget delete child; // delete the layout item } This assumes takeAt() has been correctly implemented in the QLayout subclass. Follow link for details.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528680", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: pygame.MOUSEBUTTONDOWN ERROR? I am trying to capture the MOUSEBUTTONDWON and MOUSEBUTTONUP events seperately to help me with my click and drag code. But when press the mouse button down the event is also captured by the pygame.MOUSEBUTTONUP event! The code is located below: import pygame LEFT = 1 running = 1 screen = pygame.display.set_mode((320, 200)) while running: event = pygame.event.poll() if event.type == pygame.QUIT: running = 0 elif event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT: print "You pressed the left mouse button at (%d, %d)" % event.pos elif event.type == pygame.MOUSEBUTTONUP and event.button == LEFT: print "You released the left mouse button at (%d, %d)" % event.pos screen.fill((0, 0, 0)) pygame.display.flip() When I click the left mouse button down both the statements are printed when they shouldn't be. Any idea why this happens? A: Your problem could be because you have a problem Pygame installation. Reinstall Pygame. Try this link instead of the one on the official website: link. Make sure that you download the installer for the version of Python you are using, as well as the amount of bits you installed Python in. You can get the version of Python by loading up the interpreter, and looking at the top line that reads something like: Python 2.7.2 (default, Jun 12 2011, 15:08:59) [XXXXXXXXXXXXXXXXXXXXXX] on win32 Where the version number is on the left, and the number of bits are on the right.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528681", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Clean way to save observers on CoreData objects? I am wondering if it would be possible to save and restore the observer of keyPaths of CoreData Entities. Example: I have 300 Employees in my managedObjectContext. When I insert them the first time i call addObserver: .. for all of them, so that some Object gets notified if someValue changes. Now I'm calling saveAction: to save. I close the App. When I restart, whats a good way to restore the 300 x addObserver? Thanks. Regards. EDIT: Aka, what is the best way to add observers when unarchiving CoreData entities? Custom init() in the Model Class? just fetching all Entities of Employee in a for loop and then call addObserver on them? A: It seems like the best way to do things like this would be subclass NSManagedObject for your Employee entity and override the awakeFromFetch and awakeFromInsert methods. the awakeFromInsert gets called when you first insert the entity, so you could move your existing code to add the observers to there. The awakeFromFetch is where you would add the observers when fetching.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528682", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Django partial update I have two threads, one which runs something like update t set ColA=foo and the other runs update t set ColB=foo. If they were doing raw SQL statements there would be no contention, but since Django gets and saves the entire row, a race condition can occur. Is there any way to tell Django that I just want to save a certain column? A: You are correct that save will update the entire row but Django has an update which does exactly what you describe. https://docs.djangoproject.com/en/stable/ref/models/querysets/#update A: Update old topic. Now, we have update_fields argument with save: If save() is passed a list of field names in keyword argument update_fields, only the fields named in that list will be updated. https://docs.djangoproject.com/en/stable/ref/models/instances/#specifying-which-fields-to-save product.name = 'Name changed again' product.save(update_fields=['name']) A: I think your only option to guarantee this is to write the raw SQL by hand by using Manager.raw() or a cursor depending on which one is more appropriate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528683", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: LINQ Generic Join and Entity Framework My requirement is to implement a Generic Join method which would IQueryable Join . I have used the Join method as shown below : public static IQueryable Join(this IQueryable outer, IEnumerable inner, string outerSelector, string innerSelector, string resultsSelector, params object[] values) { if (inner == null) throw new ArgumentNullException("inner"); if (outerSelector == null) throw new ArgumentNullException("outerSelector"); if (innerSelector == null) throw new ArgumentNullException("innerSelector"); if (resultsSelector == null) throw new ArgumentNullException("resultsSelctor"); System.Linq.Expressions.LambdaExpression outerSelectorLambda = DynamicExpression.ParseLambda(outer.ElementType, null, outerSelector, values); System.Linq.Expressions.LambdaExpression innerSelectorLambda = DynamicExpression.ParseLambda(inner.AsQueryable().ElementType, null, innerSelector, values); System.Linq.Expressions.ParameterExpression[] parameters = new System.Linq.Expressions.ParameterExpression[] { System.Linq.Expressions.Expression.Parameter(outer.ElementType, "outer"), System.Linq.Expressions.Expression.Parameter(inner.AsQueryable().ElementType, "inner") }; System.Linq.Expressions.LambdaExpression resultsSelectorLambda = DynamicExpression.ParseLambda(parameters, null, resultsSelector, values); return outer.Provider.CreateQuery( System.Linq.Expressions.Expression.Call( typeof(Queryable), "Join", new Type[] { outer.ElementType, inner.AsQueryable().ElementType, outerSelectorLambda.Body.Type, resultsSelectorLambda.Body.Type }, outer.Expression, inner.AsQueryable().Expression, System.Linq.Expressions.Expression.Quote(outerSelectorLambda), System.Linq.Expressions.Expression.Quote(innerSelectorLambda), System.Linq.Expressions.Expression.Quote(resultsSelectorLambda))); } //The generic overload. public static IQueryable<T> Join<T>(this IQueryable<T> outer, IEnumerable<T> inner, string outerSelector, string innerSelector, string resultsSelector, params object[] values) { return (IQueryable<T>)Join((IQueryable)outer, (IEnumerable)inner, outerSelector, innerSelector, resultsSelector, values); } I have used the Join method as shown below : var q = Join(e1, e2, "Company_ID", "Company_ID", "new ( outer.Company_ID as CompanyId)" ); But i get the error as shown below : No generic method 'Join' on type 'System.Linq.Queryable' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic. Please Help . A: outerSelectorLambda.Body.Type Shouldn't this be Body.ReturnType ? This return statement is too big. Break it up and look at the types with the debugger.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528695", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is UNSET() compatible with autoload Using Amazon MWS code config.ini.php to set up classes for MarketplaceWebServices. This used autoload defintions to create variables using new. As we are using different authorization credentials for different Amazon sites I have needed to change the details beteen sites. The use of UNSET() unset($service); before $service = new MarketplaceWebService_Client( $AWS_ACCESS_KEY_ID, $AWS_SECRET_ACCESS_KEY, $config, APPLICATION_NAME, APPLICATION_VERSION ); results in $service not being an object on being called the second time. Which brings me to the question "Is UNSET() compatible with autoload ?" A: unset() has nothing to do with autoloading, and will not interfer with it. Once the class is loaded using an autoloader, unset()ing an instance will not cause it to not be available any longer. If that were the case, you'd get an error about MarketplaceWebService_Client not being an avaliable class. A: Is UNSET() compatible with autoload ? Yes. (Simple question, simple answer.) A: Running the following demonstrates that unset should work OK with autoload. The test class didn't use __contruct(). So it looks like something in MarketplaceWebService_Client MWS is upsetting the apple cart. $shipping_calc = new shipping_calc(); echo "ORIG \$shipping_calc=" . print_r($shipping_calc, true); unset($shipping_calc); echo "UNSET() \$shipping_calc=" . print_r($shipping_calc, true); $shipping_calc = new shipping_calc(); echo "NEW \$shipping_calc=" . print_r($shipping_calc, true);
{ "language": "en", "url": "https://stackoverflow.com/questions/7528699", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: json_encode does not print the array name I'm not experienced with json_encode and am trying to return an arrray of array which should be called aaData - for DataTables with server-side processing. The output should be like: { "sEcho": 3, "iTotalRecords": 57, "iTotalDisplayRecords": 57, "aaData": [ [ "Gecko", "Firefox 1.0", "Win 98+ / OSX.2+", "1.7", "A" ], [ "Gecko", "Firefox 1.5", "Win 98+ / OSX.2+", "1.8", "A" ], ... ] } but the actuall output of my PostgreSQL 8.4-driven PHP-script if (isset($_REQUEST['json'])) { $aaData = array(); while ($row = $sth->fetch(PDO::FETCH_NUM)) { array_push($aaData, $row); } print json_encode($aaData); } is actually missing outside brackets (object like?) and the aaData name: [ [ .... ], [ .... ], [ .... ] ] How would you do this best? A: If you want it to have aaData as the name, then you'll need to give your array an associative index, like so: if (isset($_REQUEST['json'])) { $arr['aaData'] = array(); while ($row = $sth->fetch(PDO::FETCH_NUM)) { array_push($arr['aaData'], $row); } print json_encode($arr); } A: Another option is to use the code in the question but change one line: print json_encode(array('aaData' => $aaData)); A: To explain the root of your problem: The name of the variable, $aaData, has nothing to do with the data itself. Thus, json_encode does not serialize it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }