text
stringlengths
8
267k
meta
dict
Q: android reading from a text file I have a java class where it reads some data from a text file using a buffered reader and returns that data as a hash map: import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; public class FrequencyLoader { public FrequencyLoader() throws FileNotFoundException { } public HashMap<String, Double> loadUnigramFrequencies() throws FileNotFoundException, IOException { HashMap<String, Double> unigramFrequencies = new HashMap<String, Double>(); String line; String[] splittedLine; BufferedReader bf = new BufferedReader(new FileReader("unigramFrequencies.txt")); while ((line = bf.readLine()) != null) { splittedLine = line.split("\\s"); unigramFrequencies.put(splittedLine[0].trim(), Double.parseDouble(splittedLine[1].trim())); } return unigramFrequencies; } } I want to use that in my android application but when I create an instance of this class and try to execute the loadUnigramFrequencies() function in the android Activity class I am getting an error that the application has stopped unexpectedly. I am trying to run it on Samsung Galaxy S2. Should the file be placed somewhere in the android project rather than on the disk? if yes then where? A: without a bit of logcat it is a bit trivial. unigramFrequencies.put(splittedLine[0].trim(), Double.parseDouble(splittedLine[1].trim())) here for instance could be raised a null pointer execption if splittedLine[0] or splittedLine[1] is null, or parseDouble could arise a number format execption A: I think the error might well be there : BufferedReader bf = new BufferedReader(new FileReader("unigramFrequencies.txt")); You should provide an absolute path here and first make sure that the file exists before accessing it or handle the exception. If this file is some final asset, you should place it in your project assets folder and get a filereader from there. Example (from here): AssetFileDescriptor descriptor = getAssets().openFd("unigramFrequencies.txt"); FileReader reader = new FileReader(descriptor.getFileDescriptor()); Note that your unigramFrequencies.txt file should be present in your <project>/assets/ directory A: This is searching for a needle in the hay stack. I recommend you to first learn how to use debugging in Android: http://www.droidnova.com/debugging-in-android-using-eclipse,541.html Also some exception handling wouldn't hurt: http://en.wikibooks.org/wiki/Java_Programming/Throwing_and_Catching_Exceptions The following line of code is very wrong, and it seems you don't understand file storage in android: new FileReader("unigramFrequencies.txt") Here it is explained: http://developer.android.com/guide/topics/data/data-storage.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7568795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: blackberry screen orientation change i want to set my application in Portrait mode as default . so how to implement it ? all screen of the application set default as Portrait mode .. A: Check this BlackBerry UI guide: Specifying the orientation and direction of the screen A: This set default portrait mode: public void disableOrientationChange() { int directions = Display.DIRECTION_NORTH; UiEngineInstance engineInstance = Ui.getUiEngineInstance(); if (engineInstance != null) { engineInstance.setAcceptableDirections(directions); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7568798", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: iText Document Vertical Alignment I'm trying to vertically align a table in my document to the bottom of the page. I've set the vertical alignment of the table to BOTTOM but that just makes the cells align to the bottom of the table itself. How can I make the Document itself vertically aligned to the bottom? Thanks A: After many days of searching.. my solution was to wrap my table in an outer table with 1 cell. Set the cell to the height of the page minus the two margins and set vertical alignment to the bottom. Add all content you want bottom justified to this table. Full example, error code omitted for brevity public void run() { try { Document document = new Document(PageSize.LETTER, 10.0f, 10.0f, 36.0f, 36.0f); PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream("test.pdf")); document.open(); PdfPTable outerTable = new PdfPTable(1); outerTable.setWidthPercentage(100.0f); PdfPCell cell = new PdfPCell(); cell.setMinimumHeight(document.getPageSize().getHeight() - 36.0f - 36.0f); cell.setVerticalAlignment(Element.ALIGN_BOTTOM); cell.addElement(createTable()); outerTable.addCell(cell); document.add(outerTable); document.newPage(); document.close(); } catch (Exception e) { e.printStackTrace(); } } public PdfPTable leftTable() { PdfPTable table = new PdfPTable(1); for (int i = 0; i < 50; i++) { table.addCell("Cell: " + i); } return table; } public PdfPTable middleTable() { PdfPTable table = new PdfPTable(1); for (int i = 0; i < 10; i++) { table.addCell("Cell: " + i); } return table; } public PdfPTable rightTable() { PdfPTable table = new PdfPTable(1); for (int i = 0; i < 100; i++) { table.addCell("Cell: " + i); } return table; } public PdfPTable createTable() { PdfPTable table = new PdfPTable(3); table.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM); table.addCell(leftTable()); table.addCell(middleTable()); table.addCell(rightTable()); return table; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7568803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Get the selected row in DataGridViewRow event in C# I am using the DataGridView bound to a database. I have a button that is disabled. When a row is selected, not by clicking in a cell but on the row selection pane, I want to respond to an event and enable that button. A: Well, there's the RowHeaderMouseClick event. From there, you can get e.RowIndex to determine which row the click occurred on. A: protected override void Render(System.Web.UI.HtmlTextWriter writer) { AddRowSelectToGridView(gridView); base.Render(writer); } private void AddRowSelectToGridView(GridView gv) { try { foreach (GridViewRow row in gv.Rows) { row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';"; row.Attributes["onmouseout"] = "this.style.textDecoration='none';"; row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(gv, "Select$" + row.RowIndex.ToString(), true)); } } catch (Exception ex) { } } try this code,u can select the row.. A: Arguably the 'correct' event to use to detect when a DataGridView row is selected is SelectionChanged. dataGridView1.SelectionChanged += new EventHandler(dataGridView1_SelectionChanged); void dataGridView1_SelectionChanged(object sender, EventArgs e) { // code that happens after selection } The problem with this event is that the event signature only has a plain EventArgs with not special information about the DataGridView. Also this responds to any source of the selection changing, not only the row header being selected. Depending on your exact needs the bemused's answer of RowHeaderMouseClick could well be better.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568806", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Jquery problems with some chars in strings I'm having troubles with some string chars like 'c++', when trying manipulating that i receive an error: uncaught exception: Syntax error, unrecognized expression: + Is there some way of declaring strings or somenthing more that can be usefull to this case? In this case i pass var k = 'c++' to a function which prints that var in this way: $('#wrapper').html('<span>'+k+'</span>'); A: Are you eval'ing the above code? As it stands what you have there works fine if it's just included in a page with var k = "c++". If you are going to eval the string, then you should surround 'k' with quotes and also escape any quotes that might be in it. A: That code looks fine. Runs with no problem here That is not the line of code causing the error
{ "language": "en", "url": "https://stackoverflow.com/questions/7568809", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Xcode 4 external build project and debugging I've got a makefile based project set up that builds my code on multiple platforms. On my Mac I want to use Xcode for debugging though. I've set up an Xcode as an External Build Project I can run the application from within Xcode. The output is shown in Xcode and if the app crashes it drops in to the debugger, but when running the debugger cannot locate the source files, so I just see assembly output. How can I tell Xcode where to locate the source? I also cannot set breakpoints, but I think that this is all the same problem. A: I was able to fix the issue of not stopping at breakpoints by setting a custom working directory for the executable. Before this change I was able to build successfully using the external scons system from Xcode 4. My code would run when called from XCode but breakpoints would be ignored. Then in XCode, Go to Product -> Edit Scheme... CHeck 'use custom working directory' and I set this to the same directory as the executable. Breakpoints then started working. A: * *Ensure -g is included in the compiler options in the makefile. *Set a custom working directory in the scheme, set the executable if this hasn't already been set. *Ensure that the project isn't pulling in dylibs that haven't been compiled with -g. You might need a build step to run make install if the project builds dylibs as well as the main target. *Make sure that "strip" isn't being called. There are environment vars that xcode set that allow you to keep a working makefile when used outside xcode. Just had this problem and this worked (Xcode 4.6) (got source debugging and working breakpoints) A: In "Project Navigator" (the file-folder icon just below the "Run" button), right click and select "Add Files To your-project". Browse to the top level folder where you would normally run the external build, and click Add.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Git diff - how to quit the diff listing How do you quit git diff listing? There is an <END> marker at the bottom of the screen, and everything I do which appears to quit the diff listing, then shows an <END> marker at the bottom of the screen again. A: The default pager for git is less. To quit less, hit q.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568811", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "125" }
Q: Instance value in view is diplayed after page refresh(Production) I'm using rails 2.3.4 & ruby 1.8.7 I'm trying to print a instance variable in my application. The instance variable is getting initialized in a method in deal_portal/base_controller.rb, while the view is rendered from a method in deal_portal/mobile_controller. When I view the page, the value of instance variable is not present, but once the page is refreshed the value is displayed. What could be the cause of delay as this happens only in production EDIT: deal_portal/base_controller.rb def validate_trans @voucher_urls = payment_info["voucher_urls"] end deal_portal/mobile_controller.rb class DealPortal::MobileController < DealPortal::BaseController def payment_success render :template => "deal_portal/mobile/payment_success.html.erb" end end deal_portal/mobile_native_app_controller.rb class DealPortal::MobileNativeAppController < DealPortal::BaseController before_filter :validate_trans, :only => [:payment_success] end Now in the view file payment_success.html.erb after the puchase is made, the @voucher_urls is not displayed and after refreshing the page, it becomes visible.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568814", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why no tail() or head() method in List to get last or first element? I recently had a discussion with a collegue why the List interface in Java doesn't have a head() and tail() method. In order to implement such a functionality would have to write a wrapper that looked something like this: public E head() { if (underlyingList == null || underlyingList.isEmpty()) return null; return underlyingList.get(0); } public E tail() { if (underlyingList == null || underlyingList.isEmpty()) return null; return underlyingList.get(underlyingList.size()-1); } I'm not aware of all List implementations but I assume that at least in LinkedList and ArrayList it should be pretty trivial to get the last and first element (constant time). So the question is: Is there a specific reason why it is not a good idea to provide a tail method to any List implementation? A: If you want to process a list recursively, which is often what head/tail are used for in functional programming, you can use an Iterator. Integer min(Iterator<Integer> iterator) { if ( !iterator.hasNext() ) return null; Integer head = iterator.next(); Integer minTail = min(iterator); return minTail == null ? head : Math.min(head, minTail); } A: The List inteface has subList which is almost head and tail. You can wrap it as follows public List head(List list) { return list.subList(0, 1); } public List tail(List list) { return list.subList(1, list.size()); } Edit Following the answer by @Pablo Grisafi, here is a Java quick sort implementation - not generic and not efficient. As expected head() should return an element - not list. public class QSort { public static List<Integer> qsort(List<Integer> list) { if (list.isEmpty()) { return list; } else { return merge( qsort(lesser (head(list), tail(list))), head(list), qsort(greater( head(list), tail(list))) ); } } private static Integer head(List<Integer> list) { return list.get(0); } private static List<Integer> tail(List<Integer> list) { return list.subList(1, list.size()); } private static List<Integer> lesser(Integer p, List<Integer> list) { return list.stream().filter(i -> i < p).collect(toList()); } private static List<Integer> greater(Integer p, List<Integer> list) { return list.stream().filter(i -> i >= p).collect(toList()); } private static List<Integer> merge(List<Integer> lesser, Integer p, List<Integer> greater) { ArrayList list = new ArrayList(lesser); list.add(p); list.addAll(greater); return list; } public static void main(String[] args) { System.out.println(qsort(asList(7, 1, 2, 3, -1, 8, 4, 5, 6))); } } A: As far as I can tell, List doesn't have an element method. LinkedList, however, has getFirst() and getLast(), which do as you describe. A: In my humble opinion, tail and head are more familiar with people with a functional background. When you start passing functions around, they are incredible useful, that's why most functional languages have them implemented and even have shortcut notation to refer to them, like in haskell or even in scala (even if it's not THAT functional, I know) In the "(almost) everything is an object but methods are made in a procedural way" java world, when passing around functions is at least hard and always awkward, head/tail methods are not so useful. For example, check this haskell implementation of quicksort: quicksort :: Ord a => [a] -> [a] quicksort [] = [] quicksort (p:xs) = (quicksort lesser) ++ [p] ++ (quicksort greater) where lesser = filter (< p) xs greater = filter (>= p) xs It relies, among other things, on the ability to easily separate head and tail, but also on being able to filter a collection using a predicate. A java implementation (check http://www.vogella.de/articles/JavaAlgorithmsQuicksort/article.html) looks totally different, it is way lower level, and doesn't rely on separating head and tail. Note: The next sentence is totally subjective and based on my personal experience and may be proven wrong, but I think it's true: Most algorithms in functional programming rely on head/tail, in procedural programming you rely on accessing an element in a given position A: Java Collections Framework is written by Joshua Bloch. One of his API design principles is: High power-to-weight ratio. tail() and head() can be implemented by get() and size(), so it's not necessary to add tail() and head() to a very general interface java.util.List. Once users use the methods, you don't have chance to remove them and you have to maintain these unnecessary methods forever. That's bad. A: there are always choices one must make in good API design. there are lots of methods that could be added to the API, however, you have to find the fine line between making the API usable for most people and making it too cluttered and redundant. as it is, you can implement the tail method as you have shown in an efficient way for most List implementations, and LinkedList already has a getLast() method. A: peekLast method is already defined in Deque interface. Moreover, It's obligatory for deque to have such a functionality. So, there's no point to define it in List or any other interface. It's just convenient to split the functionality. If you need random access then you should implement List. If you need to access the tail efficiently then you should implement Deque. You can easily implement both of them (LinkedList does this, actually). A: You should use a List, to make it easier. When you use recursion on a list you have to think like this... The list has an head(the first element) and a tail(all the other elements except the head). With recursion you need to do what you want on the head and then call the function on the tail, so that you always have a list with size = size - 1 public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(); list.add(11); list.add(12); list.add(0); list.add(3); list.add(1); list.add(4); list.add(11); System.out.println(countOccurrences(list, 11)); } public static int countOccurrences(List<Integer> list, int n) { if (list.size() == 0) {//if list is empty return 0 return 0; }else { if(list.get(0) == n) {//if head of list is equal to n add 1 and call the function on the tail of the list return 1 + countOccurrences(list.subList(1, list.size()), n); }else {//else if it's not equal to n call the function on the tail of the list without adding 1 return countOccurrences(list.subList(1, list.size()), n); } } } A: You can get those on Stream which is available on list: head myList.stream().findFirst() // Optional<T>, return empty for empty list tail (traditional meaning) myList.stream().skip(1).collect(toList()) // or don't collect & continue with a Stream last (possibly dangerous if the list is infinite!): myList.stream().reduce((a,b) -> b) // Optional<T>, return empty for empty list A: head() is provided via list.iterator().next(), list.get(0), etc. It is only reasonable to provide tail() if the list is doubly linked with a tail pointer, or based on an array, etc., Neither of these aspects is specified for the List interface itself. Otherwise it could have O(N) performance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568819", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: iPhone: get image from camera without UIImagePickerController Please help me with my question. Is there any way to get image from camera without UIImagePickerController? I need to render current image(from camera) into image on my view and update it by timer. May be AVCaptureStillImageOutput? I didn't find any examples. Any ideas? A: Yes, you can do it easily using AVCamCaptureManager and AVCamRecorder classes. Apple has a demo program build on its developer site here. It is named AVCam. In simple words what it does is when you click to open the camera, it calls the classes and methods which are responsible for opening the iPhone's camera and record video or capture audio. It calls the same classes which are called by UIImagePickerController. I hope it helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SSRS PDF compression When I generate a PDF with MS Reporting Services (server side), the resulting file is 5 times larger in size when compared to the same PDF from another program. The report contains 1 page with a JPG image of 20kb and text ('Arial' 10px). PDF rendered in SSRS: 150kb with the image removed: 120kb without image or text: 30kb PDF from other system: 30 kb Are there any compression settings? thanks A: There are no pdf export options. A workaround could be using a PDF virtual printer, and "print" the report instead of using export
{ "language": "en", "url": "https://stackoverflow.com/questions/7568837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Problem with getElementsByTagName in IE 8 I have problem this script dont working in IE 8 in Firefox is everything OK. <html> <style type="text/css"> lip{ position:absolute; } </style> <body> <ul><lip>3<input type = "checkbox" name = "LH3" id ='lhpz12' value="ANO"></lip></ul> <script type="text/javascript"> var listElements = document.getElementsByTagName("lip"); var element = listElements[0]; element.style.fontSize = "24px"; element.style.color = "green"; element.style.left = "100px"; element.style.top = "100px"; </script> </body> </html> A: LIP isnt a valid tag, use something like a span or div. A: In IE, those tags aren't until you create one in JavaScript. You should use a span here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568838", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: display all the files and the directory of the each file under a root folder recursively i want to display all the files and the directory of each file under a root directory recursively the output should look like this filename ---> the directory which contains that file for example filename.jpg--->c:\workspace the filename.jpg is in c:\workspace i.e :the path is c:\workspace\filename.txt there are many files in each directory A: Remember that filenames with the same name will be overridden in this solution (you need a Map<String, List<File>> to allow this): public static void main(String[] args) throws Exception { Map<String, File> map = getFiles(new File(".")); for (String name : map.keySet()) if (name.endsWith(".txt")) // display filter System.out.println(name + " ---> " + map.get(name)); } private static Map<String, File> getFiles(File current) { Map<String, File> map = new HashMap<String, File>(); if (current.isDirectory()) { for (File file : current.listFiles()) { map.put(file.getName(), current); map.putAll(getFiles(file)); } } return map; } Example output: test1.txt ---> . test2.txt ---> .\doc test3.txt ---> .\doc\test A: You can use Apache Commons Fileutils: public static void main(String[] args) throws IOException { File rootDir = new File("/home/marco/tmp/"); Collection<File> files = FileUtils.listFiles(rootDir, new String[] { "jpeg", "log" }, true); for (File file : files) { String path = file.getAbsolutePath(); System.out.println(file.getName() + " -> " + path.substring(0, path.lastIndexOf('/'))); } } The first argument of listFiles is the directory from which you want to start searching, the second argument is an array of Strings giving the desired file extensions, and the third argument is a boolean saying if the search is recursive or not. Example output: visicheck.jpeg -> /home/marco/tmp connettore.jpeg -> /home/marco/tmp sme2.log -> /home/marco/tmp/sme2_v2_1/log davmail_smtp.jpeg -> /home/marco/tmp
{ "language": "en", "url": "https://stackoverflow.com/questions/7568839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: save get values using arrayList java In my example, I try to get val(0) and val(1) each time. After for loop I need to save my values to use them for other calculations: String[] columns = { "col1" , "col2" }; String[] y = { "TEST", "BUG" ,"ENH" }; List<int[]> values = new ArrayList<int[]>(); for (int j = 0; j < y.length; j++) { // do some actions for(int[] v : values) { //v is the array for one iteration, use it like this: int col1 = v[0]; int col2 = v[1]; values .add(v); } } System.out.prinln(values) =>gives : [] Out of for loop, my values are raised, how do can I do to get my values after for? Thanks A: for (int value : values) { // do something with value } A: I don't understand the question either, but, here's my best guess at interpreting what the question is trying to do: String[] columns = {"col1" , "col2"}; String[] y = { "TEST", "BUG" ,"ENH"}; int[][] values = new int[y.length][columns.length]; // 2D array for (int j = 0; j < y.length; j++) { for (k = 0; k < columns.length; k++) { values[j][k] = table.getVal(j, columns[k]); } } A: Without knowing the structure of 'table', your data in the int array 'values' should be readily accessible via a for loop: for (int v: value) { //use 'v' here } or directly: values[0]; values[1]; ...etc However, it might simply be a language barrier here preventing us from understanding the true problem. A: If you want to get the values of all iterations after the loop, you first have to provide a fitting data structure. An easy way might be to use a 2-dimensional array: int[][] values = new int[y.length][columns.length]; However, I'd recommend using a collection instead (assuming the original values has to be an array): List<int[]> values = new ArrayList<int[]>(); Then fill that in your loop, either using array index y or just adding a new array in each iteration. After the loop you can then iterate over the result, like this: for(int[] v : values) { //v is the array for one iteration, use it like this: int col1 = v[0]; int col2 = v[1]; //or like this for(int value : v) { //value is the value of one column in one iteration } } UPDATE: In your updated code you're not putting anything into the list. Note that you still have to create an array per iteration, get the values from your source (IIRC it was named table) and put them into the array, then add the array to the list using values.add(...). Also note that the loop I added above is meant to read the values later, it doesn't show you how to fill the list in the first place.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568840", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Retrieve comboBox displayed values I am trying to retrieve the displayed values of all items present in a comboBox. First case: if the comboBox has been filled using a DataSource: comboBox.DataSource = myDataSet.Tables[0]; comboBox.DisplayMember = "value"; comboBox.ValueMember = "id"; ...I use this code: foreach (DataRowView rowView in comboBox.Items) { String value = rowView.Row.ItemArray[1].ToString(); // 1 corresponds to the displayed members // Do something with value } Second case: if the comboBox has been filled with the comboBox.Items.Add("blah blah"), I use the same code, except I have to look in the first dimension of the ItemArray: foreach (DataRowView rowView in comboBox.Items) { String value = rowView.Row.ItemArray[0].ToString(); // 0 corresponds to the displayed members // Do something with value } Now I would like to be able to retrieve all values without knowing the scheme used to fill the comboBox. Thus, I don't know if I have to use ItemArray[0] or ItemArray[1]. Is it possible? How could I do that? A: You can try something like this: string displayedText; DataRowView drw = null; foreach (var item in comboBox1.Items) { drw = item as DataRowView; displayedText = null; if (drw != null) { displayedText = drw[comboBox1.DisplayMember].ToString(); } else if (item is string) { displayedText = item.ToString(); } } A: The Combobox would be populated with the DataSource property in the first case. Therefore its DataSource won't be null. In the second case, it would be null. So you could do an if-else with (comboBox1.DataSource==null) and then accordingly use ItemArray[0] or ItemArray[1]. A: Leito, you could check to see if the DataSource is a DataTable or not to determine which action to take. if (comboBox.DataSource is DataTable) { // do something with ItemArray[1] } else { // do something with ItemArray[0] }
{ "language": "en", "url": "https://stackoverflow.com/questions/7568845", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do I check for an ID value in more than one table if not exists(SELECT 1 FROM MYTABLE1 WHERE ID=@ID) BEGIN END I want to check for this ID value in MYTABLE2 as well..how should I write the IF condition ?? i want to check that a certain ID doesnt exist in any of the two tables. A: You could use an UNION ALL: IF NOT EXISTS (SELECT 1 FROM (SELECT ID FROM MyTable1 UNION ALL SELECT ID FROM MyTable2) Table WHERE ID = @ID) BEGIN ... END A: You could do the following: if (not exists(SELECT 1 FROM MYTABLE1 WHERE ID=@ID)) AND (not exists(SELECT 1 FROM MYTABLE2 WHERE ID=@ID)) BEGIN END A: Depends on what you want - If you want to check that the ID exists in either ONE of the tables then use UNION ALL. you could use JNK's answer. If you want to check that the ID exists in both tables then use INNER JOIN. If not exists (select top 1 from table1 a inner join Table2 b on a.ID = b.ID where a.ID = @ID) BEGIN END Hope this helps. A: SELECT blah.ID FROM MYTABLE1 as blah WHERE blah.ID IN (some range of ints) If you get no results then you know it does not exist
{ "language": "en", "url": "https://stackoverflow.com/questions/7568847", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to show the new value when EditTextPreference is changed I have two PreferenceActivity in my PreferenceActivity. My issue is when I update an item, new value is not reflected in the screen. public class HostSettingActivity extends PreferenceActivity { private final String MY_DEBUG_TAG = "SettingActivity"; SharedPreferences sharedPrefs; @Override protected void onCreate(Bundle savedInstanceState) { Log.i(MY_DEBUG_TAG, "HostSettingActivity Started"); super.onCreate(savedInstanceState); sharedPrefs = getPreferenceManager().getSharedPreferences(); setPreferenceScreen(createPreferenceHierarchy()); } @Override protected void onDestroy() { super.onDestroy(); Log.e(MY_DEBUG_TAG, "On Destroy"); } private PreferenceScreen createPreferenceHierarchy() { // Root PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this); PreferenceCategory dialogBasedPrefCat = new PreferenceCategory(this); dialogBasedPrefCat.setTitle("Host Settings"); root.addPreference(dialogBasedPrefCat); EditTextPreference hostPreference = new EditTextPreference(this); hostPreference.setKey("host"); hostPreference.setDialogTitle("Host"); hostPreference.setDefaultValue("http://example.com"); hostPreference.setSummary("Set host"); dialogBasedPrefCat.addPreference(hostPreference); EditTextPreference portPreference = new EditTextPreference(this); portPreference.setKey("port"); portPreference.setDialogTitle("Port"); portPreference.setDefaultValue("8080"); portPreference.setSummary("Set port"); dialogBasedPrefCat.addPreference(portPreference); hostPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { EditTextPreference etp = (EditTextPreference) preference; String newHostValue = newValue.toString(); Log.i(MY_DEBUG_TAG, "New Host: "+newHostValue); etp.setText(newHostValue); return true; } }); return root; } } A: Call preference.notifyChanged(); when its data changed and it should be redrawn. A: I was confused between setText and setTitle public boolean onPreferenceChange(Preference preference, Object newValue) { EditTextPreference etp = (EditTextPreference) preference; String newHostValue = newValue.toString(); Log.i(MY_DEBUG_TAG, "New Host: "+newHostValue); etp.setTitle(newHostValue); return true; } has done what I want
{ "language": "en", "url": "https://stackoverflow.com/questions/7568848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: DotNetOpenAuth SignInWithTwitter sample doesn't work I use DotNetOpenAuth 3.4.7 with valid consumer key and secret. When I try to sign in with twitter on localhost (\Samples\OAuthConsumer\SignInWithTwitter.aspx) it crashes with following exception. The remote server returned an error: (401) Unauthorized. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Net.WebException: The remote server returned an error: (401) Unauthorized. Source Error: Line 190: } Line 191: Uri callback = MessagingUtilities.GetRequestUrlFromContext().StripQueryArgumentsWithPrefix("oauth_"); Line 192: var request = TwitterSignIn.PrepareRequestUserAuthorization(callback, null, redirectParameters); Line 193: return TwitterSignIn.Channel.PrepareResponse(request); Line 194: } Source File: C:\Users\Andrey\Downloads\DotNetOpenAuth-3.4.7.11121\DotNetOpenAuth-3.4.7.11121\Samples\DotNetOpenAuth.ApplicationBlock\TwitterConsumer.cs Line: 192 TwitterConsumer latest update is Mar 07, 2010. (https://github.com/AArnott/dotnetopenid/blob/v3.4/samples/DotNetOpenAuth.ApplicationBlock/TwitterConsumer.cs) Is this sample still alive? A: It's my bad. I didn't specify the callback url in app profile.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: UITextField with auto wrapping I am trying to make UITextField with auto text wrapping, but I can't do it. A: Use UITextView much easier http://developer.apple.com/library/IOS/#documentation/UIKit/Reference/UITextView_Class/Reference/UITextView.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7568851", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Restart animated GIF as background-image Is it possible to restart an animated GIF used as background-image? Consider this HTML: <div id="face"> <div id="eyes"></eyes> </div> And this style: #eyes.blink { background-image:url('blink.gif'); } I would like the blink.gif animation to play every time I add the class blink to #eyes, not just the first time. I expected this to work: function startBlink() { $('#eyes').addClass('blink'); } function stopBlink() { $('#eyes').removeClass('blink'); } The problem is that both Firefox and WebKit browser do not play a background-image GIF animation again once it has played once. Adding/removing the class blink only works the first time. A: I've found you can also add a ?+Math.random() to the end of the picture src and it'll reload the .gif. A: There is an alternative that does not reload the GIF every time and waste bandwidth. It involves storing the GIF as Base64 in memory (circumventing browser cache), and uses the FileReader API (which seems to be supported in all modern browsers). Note that loading images this way is subject to cross-origin policy (unlike the image reload solutions.) Update: Browser caching is getting smarter about caching background image data URI's, causing the animation not to start over. I found I had to add a cache-busting random string to the data url now (which according to the DataURI Scheme, should be considered an optional attribute. Tested in Chrome & IE Edge.) See it in action: http://jsfiddle.net/jcward/nknLrtzL/10/ Here's how it works. This function loads the image as a Base64-encoded string. function toDataUrl(url, callback) { var xhr = new XMLHttpRequest(); xhr.onload = function() { var reader = new FileReader(); reader.onloadend = function() { callback(reader.result); } reader.readAsDataURL(xhr.response); }; xhr.open('GET', url); xhr.responseType = 'blob'; // IE11, set responseType must come after .open() xhr.send(); } Then, any time you want to restart the GIF animation, change the background-image property to none, then the base64 string (in some browsers, you need to re-add the child to trigger the update without a setTimeout): $div.css({backgroundImage: "none"}); $div.parent().add($div); // Some browsers need this to restart the anim // Slip in a cache busting random number to the data URI attributes $div.css({backgroundImage: "url("+img_base64.replace("image/gif","image/gif;rnd="+Math.random())+")"}); Thanks to this answer for the toDataURL function (with fix for IE11.) A: I combined several parts of the solution to make one whole solution that solves (hopefully) all problems: * *Determine the background-image URL of an element (from css background-image) *Trigger a restart for that image WITHOUT reloading it from the web *Restarting it in all places (without touching each individually) *Making sure the target is repainted without artifacts after restarting the animation In my solution i create helper images that are added to the body but hidden in a way so they are still rendered by the browser but won't interact with the page visually using position: absolute; left: -5000px;. A reference to our helper images is cached in resetHelperImages so we can reuse them for the same image in subsequent calls. I am using jQuery for my example, but it could be adapted to work without jQuery, too. Tested in: Chrome (Version 43.0.2357.130 m) var resetHelperImages = {}; function restartAnimation(elem) { elem = $(elem); for (var i = 0; i < elem.length; i++) { var element = elem[i]; // code part from: http://stackoverflow.com/a/14013171/1520422 var style = element.currentStyle || window.getComputedStyle(element, false); // var bgImg = style.backgroundImage.slice(4, -1).replace(/"/g, ''); var bgImg = style.backgroundImage.match(/url\(([^\)]+)\)/)[1].replace(/"/g, ''); // edit: Suggestion from user71738 to handle background-images with additional settings var helper = resetHelperImages[bgImg]; // we cache our image instances if (!helper) { helper = $('<img>') .attr('src', bgImg) .css({ position: 'absolute', left: '-5000px' }) // make it invisible, but still force the browser to render / load it .appendTo('body')[0]; resetHelperImages[bgImg] = helper; setTimeout(function() { helper.src = bgImg; }, 10); // the first call does not seem to work immediately (like the rest, when called later) // i tried different delays: 0 & 1 don't work. With 10 or 100 it was ok. // But maybe it depends on the image download time. } else { // code part from: http://stackoverflow.com/a/21012986/1520422 helper.src = bgImg; } } // force repaint - otherwise it has weird artefacts (in chrome at least) // code part from: http://stackoverflow.com/a/29946331/1520422 elem.css("opacity", .99); setTimeout(function() { elem.css("opacity", 1); }, 20); } .myBgImageClass { background-image: url('http://i410.photobucket.com/albums/pp184/OllieMarchant/Countup.gif'); width: 100px; height: 150px; background-size: 100%; background-repeat: no-repeat; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="myBgImageClass"></div> <button onclick="restartAnimation($('.myBgImageClass'))">restart</button> A: You can get the animated gif to replay by reloading it. This isn't ideal for bandwidth, especially if your image is large, but it will force a restart of the animation. In my example I'm adding and removing it onclick of <div id="animated">: $('#animated').click(function() { /* Reference to the clicked element and toggle the .go class */ var $div = $(this); $div.toggleClass('go'); /* Start the animated gif */ if ($div.hasClass('go')) { /* Create an <img> element and give it the animated gif as a src. To force a reload we add a date parameter to the URL */ var img = document.createElement('img'); img.src = "http://yoursite.com/animated.gif?p" + new Date().getTime(); /* Once the image has loaded, set it as the background-image */ $(img).load(function(){ $div.css({backgroundImage: "url("+img.src+")"}); }); /* Remove the background-image */ } else { $div.css({backgroundImage: "none"}); } }) Demo of it in action. A: Have you considered using the same image twice called blink.gif and blink2.gif, adding two classes for them and toggling between classes? <div id="face"> <div id="eyes"></eyes> </div> .blink { background-image:url('blink.gif'); } .blink2 { background-image:url('blink2.gif'); } function MakeBlink() { if ($('#eyes').hasClass('blink')) { $('#eyes').removeClass('blink').addClass('blink2'); } else { $('#eyes').removeClass('blink2').addClass('blink'); } } A: Just because I still need this every now and then I figured the pure JS function I use might be helpful for someone else. This is a pure JS way of restarting an animated gif, without reloading it. You can call this from a link and/or document load event. <img id="img3" src="../_Images/animated.gif"> <a onClick="resetGif('img3')">reset gif3</a> <script type="text/javascript"> // reset an animated gif to start at first image without reloading it from server. // Note: if you have the same image on the page more than ones, they all reset. function resetGif(id) { var img = document.getElementById(id); var imageUrl = img.src; img.src = ""; img.src = imageUrl; }; </script> On some browsers you only need to reset the img.src to itself and it works fine. On IE you need to clear it before resetting it. This resetGif() picks the image name from the image id. This is handy in case you ever change the actual image link for a given id because you do not have to remember to change the resetGiF() calls. --Nico A: For some reason this works: // Append the image to the page var i = new Image(); i.src = 'some.gif'; document.body.appendChild(i); // Now execute this line and the gif will restart // (anywhere it appears on the page, including CSS backgrounds) i.src = 'some.gif'; This requires an actual image DOM element to be appended to the page, but you can hide it with visibility: hidden. This doesn't require the image to be downloaded over the network multiple times. I only tested this in Firefox and Chrome. Not sure about other browsers. A: Regarding this answer posted by Frederic Leitenberger, I found it to work wonderfully. However, it breaks down if your background-image has multiple, layered parts, like this: background-image: url(https://upload.wikimedia.org/wikipedia/commons/5/53/Google_%22G%22_Logo.svg), radial-gradient(ellipse at center, rgba(255,255,255,1) 0%, rgba(255,255,255,1) 50%, rgba(255,255,255,0) 80%); To get around this limitation, I modified the line that finds the background image url, like so: var bgImg = style.backgroundImage.match(/url\(([^\)]+)\)/)[1].replace(/"/g, ''); This uses a regular expression to extract just the URL portion of the background-image. I would have added this as a comment to the linked answer, but I'm a noob without reputation, so was blocked from doing so. Those with adequate rep may want to add the line to the actual answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Change .NET CLR time zone without using registry I'd like to change the default time zone of a .NET CLR without using the registry or changing my OS time zone. Is there a way? EDIT: It looks like the .NET CLR just doesn't support having a default time zone different than the OS's (unlike the JVM). In other words I'd like this statement to return something other than my OS's time zone: TimeZoneInfo timeZoneInfo = TimeZoneInfo.Local; Console.Out.WriteLine("timeZoneInfo = {0}", timeZoneInfo); The reason I'd like to do this is to run a .NET GUI with the time zone of my users (London) rather than the time zone of my machine (Chicago). For example, you can change a Java runtime's time zone by adding to the commandline: -Duser.timezone="Europe/Berlin" So, for example, if you want DateTime.Now to return a different time zone, you can't without changing all the references to DateTime.Now to something else, which is what I was hoping to avoid in the first place. A: You are asking about getting a different result for the time zone setting, but I am assuming in the end you are interested in getting the time returned in another time zone by default. The .NET framework supports UTC, local, and also a generic time value without a sense of time zone. See the DateTimeKind enumeration. When dealing with time values I normally use UTC for everything internally and convert to a specific zone when interacting with the user. So, to answer your question the only way I know to get a local time returned in another time zone is to change the time zone of the machine. That begin said, to get your desired effect you could write a utility class that gets the time in UTC then use a configuration parameter to store an offset to apply before returning it. A: Instead of relying on the CLR/framework to give you time zone information, you should rely on a an external source of information for working with time zones. I recommend using the public info time zone database (also known as the tz or Olson database). While it doesn't claim to have 100% accuracy, I've found it as accurate for anything that I need to use. There are .NET classes that can parse this database, namely the ZoneInfo (tz database / Olson database) .NET API. Note that there isn't a binary distribution, you'll have to download the latest version and compile it yourself. Using this library, you find the time zone that you want (they are represented in ZoneInfo objects) for the region you are looking in, then you can give it a DateTime to perform various functions on it (like get the UTC offset on that date, get the current local time, UTC time, etc). Note, this is more accurate than the .NET API IMO, in that it requires you to provide a date to get time zone information for; various regions have changed rules regarding UTC offsets over time, and the tz database along with the ZoneInfo API do a good job of representing that history and producing results accurately. Don't worry about there not being any changes in the API since 2009; at the time of this writing, it currently parses all of the files in the latest data distrubition (I actually ran it against the ftp://elsie.nci.nih.gov/pub/tzdata2011k.tar.gz file on September 25, 2011 — in March 2017, you'd retrieve it from ftp://ftp.iana.org/tz/releases/tzdata2017a.tar.gz).
{ "language": "en", "url": "https://stackoverflow.com/questions/7568864", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to stop getting mouse click events in flex I have made a hierarchy in which there is a main page, using add element i have attached a component mxml of type group. There is a single button on main page when clicked it should add children of type group in that group type mxml component along with two buttons. Now using one of buttons i am attaching another component mxml type group. the problem is even they overlap i can still excess the children groups of first group component mxml. how can i stop this mouse events to happen. A: I think those kind of events usually bubble up to parent components. You can try using the following code in your mouse click event listener to stop further propagation: private function onMouseClicked(event: MouseEvent): void { event.stopPropagation(); ... do whatever you wanted when smth was clicked ... } A: By setting enabled, mouseChildren, mouseEnabled to false, you will disable the entire component and it's children. example below private var myPreviousGroupComponent:Group = null; function addNewGroup():void { if(myPreviousGroupComponent != null) { myPreviousGroupComponent.enabled = false; myPreviousGroupComponent.mouseChildren = false; myPreviousGroupComponent.mouseEnabled = false; } var newGroup:Group = new Group(); addElement(newGroup); myPreviousGroupComponent = newGroup; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7568871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ModelAndView returns no data to jsp views I am using Spring MVC 3, NetBeans I have the following model, public class MarketPlace { private String status; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } private String category; public String getCategory() { return category; } and this is my controller method, @RequestMapping(value = "/ListApplication.htm", method = RequestMethod.GET) public ModelAndView ShowForm(HttpServletRequest request) { ModelAndView mav = new ModelAndView("ListApplication"); mav.addObject("apps", marketPlaceService.listApplications()); return mav; } the marketPlaceService.listApplications() method returns List. and here is my view, <c:forEach items="${apps}" var="item"> <p>Template Name: ${item.templateName}</p> <p>Description: ${item.description}</p> <p>Category: ${item.category}</p> <p><img " src="${item.templateLogo}" border="0" alt="" /></div></td></p> <br><br> </c:forEach> From debugging I see at least 20 records in the list but the jsp view shows nothing. Edit: Interestingly, this code is working, protected ModelAndView handleRequestInternal( HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView mav = new ModelAndView("ListApplication"); mav.addObject("apps", marketPlaceService.listApplications()); return mav; } Can anyone tells me the reason. A: Your <img> tag is badly formed: <img " src="${item.templateLogo}" border="0" alt="" /> Should be: <img src="${item.templateLogo}" border="0" alt="" /> You also have </div></td> after the <img/> tag which shouldn't be there. Not sure about the template name, description and category though... Maybe the typo in the <img> tag is causing the jstl to not be filtered correctly. A: This is answer that I found so fast, @RequestMapping(value = "/ListApplication.htm", method = RequestMethod.GET) public String ShowForm(HttpServletRequest request, ModelMap m) { m.addObject("apps", marketPlaceService.listApplications()); return "ListApplication"; } Any further improvement is welcome. However, addObject is seems to be deprecated, any alternative?
{ "language": "en", "url": "https://stackoverflow.com/questions/7568878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: php works on wamp but not on 000webhost I have a php file that works perfectly with WAMP server, but when Im trying the 000webhost server I get errors. i.e. error on line 11 at column 1: Extra content at the end of the document. however under the error I get the right answer to the query, but not in the format I asked for. can anyone help? here is the code: <?php mysql_connect("localhost","root",""); mysql_select_db("ataxi"); $src= $_GET['src']; $dest = $_GET['dest']; $day= $_GET['day']; $hour = $_GET['hour']; $luggage= $_GET['luggage']; $query="SELECT price, estime FROM prices WHERE src='$src' and dest='$dest' and day='$day' and hour='$hour' and luggage=$luggage;"; $result= mysql_query($query) or die("error:".$query); header('Content-type: application/xml; charset="utf-8"',true); echo "<table>\n"; while ($row= mysql_fetch_array($result)) { echo "<record>\n"; echo "<price>".$row['price']."</price>\n"; echo "<estime>".$row['estime']."</estime>\n"; echo "</record>\n"; } echo "</table>\n"; ?> A: 000webhost appends analytics code by default. It could be wreaking havoc on your XML. You can disable it by going to: http://members.000webhost.com/analytics.php. A: First: I doubt 000webhost are giving you root access? Second: You can't submit header requests after already outputting to the screen, put the header line at the top of your script.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable to launch CameraCaptureTask or PhotoChooserTask while debugging with device I'm trying to debug my application on the connected device*(Dell Venue Pro WP 7.0)* but whenever I try to launch CameraCaptureTask or PhotoChooserTask in my app then nothing happens. Everytime I've to disconnect the device from the Zune and then app works fine. But I want to debug my app on device. I'm not able to figure out what is happening there. No Exception , No Errors ? A: You can't use the Camera or the Photo Chooser while you're connected with Zune. Instead, connect the device, shut-down Zune, and start WPConnect.exe, and then you can deploy&debug, and still use the Camera, Photo or even Music if you want to. You can find WPConnect in either the x86 or x64 folder in C:\Program Files\Microsoft SDKs\Windows Phone\v7.1\Tools\WPConnect
{ "language": "en", "url": "https://stackoverflow.com/questions/7568884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Does Selenium support headless browser testing? I'm looking at Selenium Server at the moment, and I don't seem to notice a driver that supports headless browser testing. Unless I'm mistaken, it doesn't support it. If you're on X, you can create a virtual framebuffer to hide the browser window, but that's not really a headless browser. Can anyone enlighten me? Does Selenium support headless browser testing? A: Headless browsers are a bad idea. They get you some testing, but nothing like what a real user will see, and they mask lots of problems that only real browsers encounter. You're infinitely better off using a "headed" browser (i.e., anything but HTMLUnit) on a headless environment (e.g., Windows, or Linux with XVFB). A: I notice that you say that using an X framebuffer isn't a true headless solution, however, for most, I think it would be acceptable. In addition to that, this service will help get that going for you if you are interested in that as a solution. A: Selenium does support headless browser testing in a way. Docker Selenium is maintained by SeleniumHQ. Those docker containers come with xvfb support with them out of the box. There are tools like PhantomJS that you can hook up with Selenium. However, it's not officially supported by Selenium itself. Much like what others have described, PhantomJS isn't really recommended. The whole point of Selenium is to automate browsers. But why automate a browser no one uses? I never understood how that was overlooked so often by developers.. A: Yes. Selenium support headless browser testing and it's more faster as well as convient for big amount of test-cases execution. ChromeOptions cromeOptions = new ChromeOptions(); //Location of browser binary/.exe file cromeOptions.setBinary("/usr/bin/google-chrome-stable"); cromeOptions.addArguments("--headless"); cromeOptions.addArguments("--no-sandbox"); cromeOptions.addArguments("--disable-gpu"); cromeOptions.addArguments("--window-size=1920,1080"); WebDriver webDriver = new ChromeDriver(cromeOptions); A: you need not use PhantomJS as an alternative to Selenium. Selenium includes a PhantomJS webdriver class, which rides on the GhostDriver platform. Simply install the PhantomJS binary to your machine. in python, you can then use: from selenium import webdriver dr = webdriver.PhantomJS() and voila. A: The WebDriver API has support for HTMLUnit as the browser for your testing. Ruby people have been using Capybara for a while for their headless selenium testing so it is definitely doable. A: I know this is a old post. Thought it will help others who are looking for an answer. You can install a full blown firefox in any linux distribution using XVFB. This makes sure your testing is performed in a real browser. Once you have a headless setup, you can use webdriver of your choice to connect and run testing. A: Yes ,selenium supports headless browser testing...but i found HTMLUnit failing most times...I was searching for an alternative...PhantomJs was really good.you can definitely give it a try it was very fast when compared to other browsers...It is really good for smoke testing... http://phantomjs.org/ A: With ruby and macOS: brew install phantomjs then: driver = Selenium::WebDriver.for :phantomjs A: Here's a "modern answer" on how to use Selenium with xvfb and Firefox driver in an Ubuntu Linux environment running Django/Python: # install xvfb and Firefox driver sudo su apt-get install -y xvfb firefox wget https://github.com/mozilla/geckodriver/releases/download/v0.19.1/geckodriver-v0.19.1-linux64.tar.gz tar -x geckodriver -zf geckodriver-v0.19.1-linux64.tar.gz -O > /usr/bin/geckodriver chmod +x /usr/bin/geckodriver # install pip modules pip install selenium pip install PyVirtualDisplay You can then follow the Django LiveServerTestCase instructions. To use the driver you just installed, do something like this: from pyvirtualdisplay import Display from selenium.webdriver.firefox.webdriver import WebDriver driver = WebDriver(executable_path='/usr/bin/geckodriver') display = Display(visible=0, size=(800, 600)).start() # add your testing classes here... driver.quit() display.stop() A: Yes Selenium supports headless browser testing.Headless browsers are faster than real time browsers. A: Install chromeDriver and google-chrome-stable version on the linux server, where the tests will be triggered and add the same binaries in your code. code snippet: private static String driverPath = "/usr/bin/chromedriver"; static { System.setProperty("webdriver.chrome.driver", driverPath); options = new ChromeOptions(); options.setBinary("/usr/bin/google-chrome-stable"); options.addArguments("headless"); driver = new ChromeDriver(options); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7568899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "73" }
Q: meta tag in ASP.NET MVC 3 How can I put meta tag to work only for one page. If I want to put it .aspx file, where is right place. Thanks. A: Since you haven't said yet, I'm assuming you're using the Razor engine (the "default" for new MVC3 projects). In that case, you just need to insert a new section into your layout view, and only render that section if you need to insert a meta tag. For example, working from the stock New ASP.NET MVC 3 Project template, you would edit your Views\Shared\_Layout.cshtml file, and before the closing </head> tag, do something like this: @this.RenderSection("MetaContent", false) </head> Then, in any of your views that you needed to, add this: @section MetaContent { <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" /> } If you're still using the ASPX layout engine for some reason, you can accomplish the same thing using the <asp:ContentPlaceHolder> tags in your master page and <asp:Content> tags in your views. EDIT: Since you're using the ASP.NET Forms layout engine still, here's the same basic idea as above in aspx syntax: In your master page, you add the tag: <asp:ContentPlaceHolder ID="MetaContent" runat="server" /> </head> And in your .aspx views, you add a new content section (you should already have at least two -- a title and a body): <asp:Content ID="Meta" ContentPlaceHolderID="MetaContent" runat="server"> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" /> </asp:Content> A: I was going to suggest exactly what Michael said (+1). Another option would be to put a boolean in the ViewBag, something like: ViewBag.ForceIE8Mode = true; For pages that you want to force into IE8 Mode. and then in your view, wrap the meta tag in a conditional. either @if(ViewBag.ForceIE8Mode == true) { <meta... /> } or <% if(ViewBag.ForceIE8Mode == true) { %> <meta... /> <% } %>
{ "language": "en", "url": "https://stackoverflow.com/questions/7568911", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Losing attachments in Axis2 response I'm trying to send an attachment to client from Axis2 web service. The problem is that the message context, which client receives from the service, does not contain any attachments, though the last one seems to add it. Here is the brief code of both sides. Service: MessageContext inMC = MessageContext.getCurrentMessageContext(); OperationContext operationContext = inMC.getOperationContext(); MessageContext outMC = operationContext.getMessageContext(WSDLConstants.MESSAGE_LABEL_OUT_VALUE); DataHandler handler = new DataHandler (new FileDataSource("C://goods.xml")); String attachID = outMC.addAttachment(handler); OMElement idElem = factory.createOMElement("doc", ns); idElem.addAttribute("href", "cid:" + attachID, ns); Client (trying to receive attachment): MessageContext mcResponse = operationClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE); SOAPBody body = mcResponse.getEnvelope().getBody(); OMElement attachElem = body.getFirstChildWithName (new QName("doc")); String attachID = attachElem.getAttributeValue (new QName("href")); attachID = attachID.replaceFirst("cid:", ""); DataHandler dataHandler = mcResponse.getAttachment(attachID); getAttachment() method returns null. In case of debugging the client application, IDE shows, that attachment map in input message context does not contain any elements (size=0). The OMElement object (idElem), which contains attachment id, is received and read by client normally (debug showed cid). The parameters enableSwA, cacheAttachments, attachmentDIR, sizeThreshold are set both in services.xml and programming part of client. What is wrong with the message context? Thanks a lot for any suggestions. Upd: TCPmon showed the following content. Request to service: <?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body><getXMLFile xmlns="http://axis2.apache.org"><filename>goods.xml</filename></getXMLFile></soapenv:Body></soapenv:Envelope> I guess it's ok :) Response from service: 109 <?xml version='1.0' encoding='UTF-8'?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body><doc href="cid:d06f3b36afdfcbd2e135ecfbcad05ee602661262b059ed38@apache.org"></doc></soapenv:Body></soapenv:Envelope> 0 I apologize for a bit simple questions, but where the attachment should be reflected? I guess, if the service send an attachment, the SOAP message contains binary data, isn't it? I checked also for putting the attachment into message context on service side - it's OK, I can get it there back from context after adding. A: you can use tcpmon[1] to trace the http message and isolate the problem. Anyway the better method for handling attachments is to use MTOM. Which can be used with data binding frameworks like ADB[2], or with POJO as well. thanks, Amila. [1] http://ws.apache.org/commons/tcpmon/ [2] http://amilachinthaka.blogspot.com/2009/01/using-mtom-with-axis2.html A: The problem was solved. The trouble was on the service side. TCPmon showed there was no attachments in responce message. However, the same example service works fine. After checking and comparing every operation on my service, it came out that programming part is not the reason either. The only one was left - service settings. So, the reason is that settings fields in service.xml file on the service, which require boolean type, does not allow any additional symbols. My mistake: Incorrect: <parameter name="enableSwA"> true </parameter> Correct: <parameter name="enableSwA">true</parameter>
{ "language": "en", "url": "https://stackoverflow.com/questions/7568913", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adb stopped by some reason? Sometimes my adb disconnected. Why i am getting like this : - [2011-09-27 17:39:43 - adb] [2011-09-27 17:39:43 - adb]This application has requested the Runtime to terminate it in an unusual way. [2011-09-27 17:39:43 - adb]Please contact the application's support team for more information. [2011-09-27 17:39:49 - DeviceMonitor]Adb connection Error:An existing connection was forcibly closed by the remote host [2011-09-27 17:39:51 - DeviceMonitor]Connection attempts: 1 [2011-09-27 17:39:53 - DeviceMonitor]Connection attempts: 2 [2011-09-27 17:39:55 - DeviceMonitor]Connection attempts: 3 [2011-09-27 17:39:57 - DeviceMonitor]Connection attempts: 4 [2011-09-27 17:39:58 - DeviceMonitor]Connection attempts: 5 [2011-09-27 17:40:00 - DeviceMonitor]Connection attempts: 6 [2011-09-27 17:40:02 - DeviceMonitor]Connection attempts: 7 [2011-09-27 17:40:04 - DeviceMonitor]Connection attempts: 8 [2011-09-27 17:40:06 - DeviceMonitor]Connection attempts: 9 [2011-09-27 17:40:08 - DeviceMonitor]Connection attempts: 10 [2011-09-27 17:40:10 - DeviceMonitor]Connection attempts: 11 Any help appreciated? A: Due to some reason sometimes adb gets disconnected, so in that case you have to reset the adb. Go to DDMS->Devices and you will see reset adb option in View Menu besides Screen Capture option. A: Another way to restart the adb is through terminal or command line. Depending on if you have adb in your path just type: $ adb kill-server $ adb start-server If adb is not in your path then: $ path-to-sdk/platform-tools/adb kill-server $ path-to-sdk/platform-tools/adb start-server Hope this helps! A: Loose connection of the cable connecting the device i hope. A: Go to DDMS->Devices and you will see restart adb option in View Menu besides Screen Capture option. A: In preferences change the android/DDMS log settings from "error" to "debug". After this you should be able to use the Reset adb option.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568916", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I test android application for network errors? I have content management application that uses TCP/IP to fetch data. I would like to test this application for several network problems like packet loss and connection lost. Is there some easy way to emulate network problems to test Android application? In DDMS there is some connection and latency setting for device, hovewer it looks like this is not working. I can set denied or unregistered but fetching from server is untouched. I'm using Windows for development. I have tried so far: F8 - 3G icon disappears, however I'm still able to download data. DDMS, Change of Telephony status - 3G icon disappears, however I'm still able to download data. Settings, Mobile networks, Data enabled false - 3G icon disappears, however I'm still able to download Airplane mode - 3G icon disappears, however I'm still able to download Dev tools - Wifi toggle - I'm getting errors: 09-27 16:43:31.353: ERROR/Connectivity(518): EVENT_TOGGLE_WIFI 09-27 16:43:31.363: ERROR/WifiService(62): Failed to load Wi-Fi driver. A: for testing the lost of internet connexion for example , you can desactivate the 3G connection from your emulator by pressing F8. for example; launch your application , and then while downloading data, try to disable the connection by pressing F8 , and then you can see the reaction of your app A: I don't think you have to worry about packet loss with a TCP connection given that the delivery is reliable (lost packets are already handled and re-sent). If you are using an emulator you can set the latency in the Telephony Status section of the Emulator Control tab in DDMS. A: You can use Android Dev Tools App. It's by default on Emulator, and you can copy/install it on real device. It has option (among others) to toggle Wifi periodically by some given times.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to fix JSLint "missing new" error Code below passed through JSLint causes an error: Problem at line 8 character 9: Missing 'new'. ResizeGrid(); How to fix? "use strict"; var ResizeGrid; function t() { var x; if (x) { ResizeGrid(); } } A: You should name functions with a lower case initial letter, unless they are intended as constructors. If they are intended as constructors, you should be calling them with new. A: Tick Tolerate uncapitalized constructors or rename to resizeGrid(); to prevent lint from assuming its a function constructor (although calling an undefined var like that will raise other errors).
{ "language": "en", "url": "https://stackoverflow.com/questions/7568929", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Full body background with Twitter Bootstrap I am trying to work on a new project using Twitter's Bootstrap framework, but I am having an issue. I want a full body background, yet the background seems to be limited to the height of the container div. here is the HTML/CSS code: <!doctype html> <html lang="en"> <head> <meta charset='UTF-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'> <link rel="stylesheet" href="http://twitter.github.com/bootstrap/1.3.0/bootstrap.min.css"> <title>Bootstrap Issue</title> <style> body { background: black; } .container { background: white; } </style> </head> <body> <div class="container"> <h1> Hello, World!</h1> </div> </body> </html> How can I get the body to take up the entire screen? A: Set the height of html and body to be 100% in the CSS. html, body { height: 100%; } Then it should work. The problem is that the height of body is automatically calculated to be the height of the contents, rather than the height of the whole screen. A: /* here is a pure CSS solution */ <style type="text/css"> html, body { height: 100%; width: 100%; padding: 0; margin: 0; } #full-screen-background-image { z-index: -999; min-height: 100%; min-width: 1024px; width: 100%; height: auto; position: fixed; top: 0; left: 0; } #wrapper { position: relative; width: 800px; min-height: 400px; margin: 100px auto; color: #333; } a:link, a:visited, a:hover { color: #333; font-style: italic; } a.to-top:link, a.to-top:visited, a.to-top:hover { margin-top: 1000px; display: block; font-weight: bold; padding-bottom: 30px; font-size: 30px; } </style> <body> <img src="/background.jpg" id="full-screen-background-image" /> <div id="wrapper"> <p>Content goes here...</p> </div> </body> A: You need to either add this: html { background: transparent } Or, set the "page background" (background: black) on html instead, which is fine to do. Why? Inside Bootstrap, there's this: html,body{background-color:#ffffff;} (bear in mind the default background value is transparent) For more information on why this matters, see: What is the difference between applying css rules to html compared to body? Note that this is no longer an issue with Bootstrap 3+. A: <style> body { background: url(background.png); } .container { background: ; } </style> this works for a background image if you want it A: best solution would be .content{ background-color:red; height: 100%; min-height: 100vh; } its automatically take veiwport height(vh) in bootstrap.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "32" }
Q: How to pass userpref variables in an igoogle widget Hi I've made my igoogle app simple though it is basically using an xml/php file and getting a series of articles and displaying them. Simple and nice. Now I just need to finish it off with passing how many stories the use would like to show. I've got the dropdown working for when they click edit settings in the google area but I'm at a loss on how to pass the information back to my php/xml file and display the number of stories the user has selected. Can anyone help. A: do a <form> with auto-submit <select name='myfield' onchange='this.form.submit()'> <option .... > ... </select> </form> then you got $_POST['myfield'] A: There is a brief document about working with userpref. it may help you. Check this Google document and also they listed how to deal with remote content in two type GET AND POST, check this document also working with remote content
{ "language": "en", "url": "https://stackoverflow.com/questions/7568932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I implement an Objective-C singleton that is compatible with ARC? How do I convert (or create) a singleton class that compiles and behaves correctly when using automatic reference counting (ARC) in Xcode 4.2? A: if you want to create other instance as needed.do this: + (MyClass *)sharedInstance { static MyClass *sharedInstance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedInstance = [[MyClass alloc] init]; // Do any other initialisation stuff here }); return sharedInstance; } else,you should do this: + (id)allocWithZone:(NSZone *)zone { static MyClass *sharedInstance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedInstance = [super allocWithZone:zone]; }); return sharedInstance; } A: This is a version for ARC and non-ARC How To use: MySingletonClass.h @interface MySingletonClass : NSObject +(MySingletonClass *)sharedInstance; @end MySingletonClass.m #import "MySingletonClass.h" #import "SynthesizeSingleton.h" @implementation MySingletonClass SYNTHESIZE_SINGLETON_FOR_CLASS(MySingletonClass) @end A: In exactly the same way that you (should) have been doing it already: + (instancetype)sharedInstance { static MyClass *sharedInstance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedInstance = [[MyClass alloc] init]; // Do any other initialisation stuff here }); return sharedInstance; } A: This is my pattern under ARC. Satisfies new pattern using GCD and also satisfies Apple's old instantiation prevention pattern. @implementation AAA + (id)alloc { return [self allocWithZone:nil]; } + (id)allocWithZone:(NSZone *)zone { [self doesNotRecognizeSelector:_cmd]; abort(); } + (instancetype)theController { static AAA* c1 = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^ { c1 = [[super allocWithZone:nil] init]; // For confirm... NSLog(@"%@", NSStringFromClass([c1 class])); // Prints AAA NSLog(@"%@", @([c1 class] == self)); // Prints 1 Class real_superclass_obj = class_getSuperclass(self); NSLog(@"%@", @(real_superclass_obj == self)); // Prints 0 }); return c1; } @end A: Read this answer and then go and read the other answer. You must first know what does a Singleton mean and what are its requirements, if you don't understand it, than you won't understand the solution--at all! To create a Singleton successfully you must be able to do the following 3: * *If there was a race condition, then we must not allow multiple instances of your SharedInstance to be created at the same time! *Remember and keep the value among multiple invocations. *Create it only once. By controlling the entry point. dispatch_once_t helps you to solve a race condition by only allowing its block to be dispatched once. Static helps you to “remember” its value across any number of invocations. How does it remember? It doesn't allow any new instance with that exact name of your sharedInstance to be created again it just works with the one that was created originally. Not using calling alloc init (i.e. we still have alloc init methods since we are an NSObject subclass, though we should NOT use them) on our sharedInstance class, we achieve this by using +(instancetype)sharedInstance, which is bounded to only be initiated once, regardless of multiple attempts from different threads at the same time and remember its value. Some of the most common system Singletons that come with Cocoa itself are: * *[UIApplication sharedApplication] *[NSUserDefaults standardUserDefaults] *[NSFileManager defaultManager] *[NSBundle mainBundle] *[NSOperations mainQueue] *[NSNotificationCenter defaultCenter] Basically anything that would need to have centralized effect would need to follow some sort of a Singleton design pattern. A: Alternatively, Objective-C provides the +(void)initialize method for NSObject and all its sub-classes. It is always called before any methods of the class. I set a breakpoint in one once in iOS 6 and dispatch_once appeared in the stack frames. A: Singleton Class : No one can create more than one object of class in any case or through any way. + (instancetype)sharedInstance { static ClassName *sharedInstance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedInstance = [[ClassName alloc] init]; // Perform other initialisation... }); return sharedInstance; } // You need need to override init method as well, because developer can call [[MyClass alloc]init] method also. that time also we have to return sharedInstance only. -(MyClass)init { return [ClassName sharedInstance]; } A: There are two issues with the accepted answer, which may or may not be relevant for your purpose. * *If from the init method, somehow the sharedInstance method is called again (e.g. because other objects are constructed from there which use the singleton) it will cause a stack overflow. *For class hierarchies there is only one singleton (namely: the first class in the hierarchy on which the sharedInstance method was called), instead of one singleton per concrete class in the hierarchy. The following code takes care of both of these problems: + (instancetype)sharedInstance { static id mutex = nil; static NSMutableDictionary *instances = nil; //Initialize the mutex and instances dictionary in a thread safe manner static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ mutex = [NSObject new]; instances = [NSMutableDictionary new]; }); id instance = nil; //Now synchronize on the mutex //Note: do not synchronize on self, since self may differ depending on which class this method is called on @synchronized(mutex) { id <NSCopying> key = (id <NSCopying>)self; instance = instances[key]; if (instance == nil) { //Break allocation and initialization into two statements to prevent a stack overflow, if init somehow calls the sharedInstance method id allocatedInstance = [self alloc]; //Store the instance into the dictionary, one per concrete class (class acts as key for the dictionary) //Do this right after allocation to avoid the stackoverflow problem if (allocatedInstance != nil) { instances[key] = allocatedInstance; } instance = [allocatedInstance init]; //Following code may be overly cautious if (instance != allocatedInstance) { //Somehow the init method did not return the same instance as the alloc method if (instance == nil) { //If init returns nil: immediately remove the instance again [instances removeObjectForKey:key]; } else { //Else: put the instance in the dictionary instead of the allocatedInstance instances[key] = instance; } } } } return instance; } A: #import <Foundation/Foundation.h> @interface SingleTon : NSObject @property (nonatomic,strong) NSString *name; +(SingleTon *) theSingleTon; @end #import "SingleTon.h" @implementation SingleTon +(SingleTon *) theSingleTon{ static SingleTon *theSingleTon = nil; if (!theSingleTon) { theSingleTon = [[super allocWithZone:nil] init ]; } return theSingleTon; } +(id)allocWithZone:(struct _NSZone *)zone{ return [self theSingleTon]; } -(id)init{ self = [super init]; if (self) { // Set Variables _name = @"Kiran"; } return self; } @end Hope above code will help it out. A: if you need to create singleton in swift, class var sharedInstance: MyClass { struct Singleton { static let instance = MyClass() } return Singleton.instance } or struct Singleton { static let sharedInstance = MyClass() } class var sharedInstance: MyClass { return Singleton.sharedInstance } you can use this way let sharedClass = LibraryAPI.sharedInstance
{ "language": "en", "url": "https://stackoverflow.com/questions/7568935", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "178" }
Q: Can flowcharts with crosslines be noted as OPML? Is there a standard to reference cross-lines in a mindmap or flowchart in OPML.For example with anchors and links. It seems that flowchart editors online such as gliffy can import OPML but export is only xml, not OPML. Put simply: can this flowchart be coded in OPML, or is OPML limited to outlining without cross references? A: Put simply: can this flowchart be coded in OPML...? Yes, but you'd have to come up with your own conventions for how to encode it, and no outline software would know how take advantage of the convention. The absolute simplest encoding would be a triple store, which you usually think of as a table of 3 columns, but in OPML could look like this: * *level 1: subject: just list every node in the network * *level 2: predicate: list the types of arcs coming out of each node. * *level 3: object: list the end points for each type of arc for the subject node. You probably also want to give the nodes a key so you're not repeating the same long labels over and over again (just like normalizing a database). In the specific example you gave, it might look like this: * *#1 * *text: * *is there a problem? *ifso: * *#2 *else: * *#3 *#2 * *text: * *"Pour yourself a drink." *next: * *#4 *#3 * *text: * *"Excellent! This calls for a drink." (etc.) If you want to know more about this concept, RDF is a generalized standard for projecting graphs into a tree structure. You can absolutely lift RDF up into OPML, but RDF-specific tools can take advantage of the graph structure and actually do something with it, whereas outliners only deal with trees and probably can't take advantage of the extra information. However, there are some outlining tools that are built on a graph model. Tinderbox for mac is one example.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568936", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to configure routes for a profile controller? I'm trying to configure a route to display a profile page about the user. At the moment, I've created a custom controller for this page using: I generated my controller using: rails g controller user-profile and I made corresponding views. I'm trying to do something like this: /user-profile/:id I'm using devise. How do I configure the route for this? A: I would do it this way (the resulting profile will be public): Add the route: match "/user-profile/:id" => "user-profile#show" Add the related action in your controller: def show @user = User.find(params[:id]) end You're then free to use the @user variable in app/views/user-profile/show.html.erb.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568937", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Calling a method which throws FileNotFoundException I'm pretty sure this is an easy one but I could not find a straight forward answer. How do I call a method with a throws FileNotFoundException? Here's my method: private static void fallingBlocks() throws FileNotFoundException A: You call it, and either declare that your method throws it too, or catch it: public void foo() throws FileNotFoundException // Or e.g. throws IOException { // Do stuff fallingBlocks(); } Or: public void foo() { // Do stuff try { fallingBlocks(); } catch (FileNotFoundException e) { // Handle the exception } } See section 11.2 of the Java Language Specification or the Java Tutorial on Exceptions for more details. A: You just call it as you would call any other method, and make sure that you either * *catch and handle FileNotFoundException in the calling method; *make sure that the calling method has FileNotFoundException or a superclass thereof on its throws list. A: You simply catch the Exception or rethrow it. Read about exceptions. A: Not sure if I get your question, just call the method: try { fallingBlocks(); } catch (FileNotFoundException e) { /* handle */ } A: Isn't it like calling a normal method. The only difference is you have to handle the exception either by surrounding it in try..catch or by throwing the same exception from the caller method. try { // --- some logic fallingBlocks(); // --- some other logic } catch (FileNotFoundException e) { // --- exception handling } or public void myMethod() throws FileNotFoundException { // --- some logic fallingBlocks(); // --- some other logic } A: You call it like any other method too. However the method might fail. In this case the method throws the exception. This exception should be caught with a try-catch statement as it interrupts your program flow.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568940", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using OData (server side) with Mono We have pure OData service (.Net 4, hosted in IIS) which works fine. We want to deploy this service on Linux. Is it possible to use OData with Mono? Have anyone had such experience? A: I also wanted to use odata for our project, but i seems that they don't support odata. Under http://www.mono-project.com/WCF_Development you will find the entry "Data Services". under not supported Components with no plan to support * *WorkflowServices. we have no plan to work on WF3. There are WF4-based WCF stuff in System.ServiceModel, which is in different story (though no plan for this either). *RIA Services. Basically there are Silverlight SDK assemblies that are to be embedded in the app, so we don't have to bother much. *WSHttpBinding and its dependencies *Federation (I'm not sure what it is supposed to do.) *Silverlight PollingDuplex binding element. *WSDualHttpBinding (post-WSHttpBinding work) *MSMQ stack: Msmq bindings and MsmqIntegration. *Data Services. *Net peer channel improvements. A: You can use Owin Self Host with HttpListener on mono. Then host your asp.net web api odata 4 app on top of that. Works like a charm (-: But, be careful about following issue: https://github.com/odata/odata.net/issues/165
{ "language": "en", "url": "https://stackoverflow.com/questions/7568942", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Measure string size in Bytes in php I am doing a real estate feed for a portal and it is telling me the max length of a string should be 20,000 bytes (20kb), but I have never run across this before. How can I measure byte size of a varchar string. So I can then do a while loop to trim it down. A: You can use mb_strlen() to get the byte length using a encoding that only have byte-characters, without worring about multibyte or singlebyte strings. For example, as drake127 saids in a comment of mb_strlen, you can use '8bit' encoding: <?php $string = 'Cién cañones por banda'; echo mb_strlen($string, '8bit'); ?> You can have problems using strlen function since php have an option to overload strlen to actually call mb_strlen. See more info about it in http://php.net/manual/en/mbstring.overload.php For trim the string by byte length without split in middle of a multibyte character you can use: mb_strcut(string $str, int $start [, int $length [, string $encoding ]] ) A: PHP's strlen() function returns the number of ASCII characters. strlen('borsc') -> 5 (bytes) strlen('boršč') -> 7 (bytes) $limit_in_kBytes = 20000; $pointer = 0; while(strlen($your_string) > (($pointer + 1) * $limit_in_kBytes)){ $str_to_handle = substr($your_string, ($pointer * $limit_in_kBytes ), $limit_in_kBytes); // here you can handle (0 - n) parts of string $pointer++; } $str_to_handle = substr($your_string, ($pointer * $limit_in_kBytes), $limit_in_kBytes); // here you can handle last part of string .. or you can use a function like this: function parseStrToArr($string, $limit_in_kBytes){ $ret = array(); $pointer = 0; while(strlen($string) > (($pointer + 1) * $limit_in_kBytes)){ $ret[] = substr($string, ($pointer * $limit_in_kBytes ), $limit_in_kBytes); $pointer++; } $ret[] = substr($string, ($pointer * $limit_in_kBytes), $limit_in_kBytes); return $ret; } $arr = parseStrToArr($your_string, $limit_in_kBytes = 20000); A: Further to PhoneixS answer to get the correct length of string in bytes - Since mb_strlen() is slower than strlen(), for the best performance one can check "mbstring.func_overload" ini setting so that mb_strlen() is used only when it is really required: $content_length = ini_get('mbstring.func_overload') ? mb_strlen($content , '8bit') : strlen($content); A: You have to figure out if the string is ascii encoded or encoded with a multi-byte format. In the former case, you can just use strlen. In the latter case you need to find the number of bytes per character. the strlen documentation gives an example of how to do it : http://www.php.net/manual/en/function.strlen.php#72274 A: Do you mean byte size or string length? Byte size is measured with strlen(), whereas string length is queried using mb_strlen(). You can use substr() to trim a string to X bytes (note that this will break the string if it has a multi-byte encoding - as pointed out by Darhazer in the comments) and mb_substr() to trim it to X characters in the encoding of the string.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "66" }
Q: Help with file download in asp.net protected void imgbtn_BBDownload_Click(object sender, EventArgs e) { Response.ContentType = "application/exe"; Response.AppendHeader("Content-Disposition","attachment; filename=bb.exe"); Response.TransmitFile( Server.MapPath("~/Resources/bb.exe") ); Response.End(); } I want to download the bb.exe file which is inside a Resource folder. I have a login form in the same screen, instead of downloading the file, the username password validation is done and the validiation summary username and password is required is shown. what is wrong with the code. Or if these is any easy method to do, pls suggest. thanks A: By default all controls on page are validated, since all controls validation group is same (i.e., blank). Add validation group to login / password / submit button controls. It will then validate only when u click login button but not download file click button.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568961", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can't select from a successfully created #temp table DECLARE @tmp_tab VARCHAR(20) SELECT @TMP_TAB = '#TMP_TAB_BANK' + CAST(USER_ID(USER) AS NVARCHAR) + CAST(@@SPID AS NVARCHAR) EXEC('CREATE TABLE ' + @TMP_TAB + (ID INT NULL, NAME VARCHAR NULL)') //Break point EXEC('select * from ' + @TMP_TAB) I'm working in SQL Server 2005. In the code above I decide what to name my temp table. Then I create the temp table. If I run just these codes I receive Commands completed successfully message. However if I execute the last line of code to retrieve the data (well, I know it's empty) I get invalid object name '#TMP_TAB_BANK157' Why can't I fetch records from a just created table? If the temp table was not created then why don't I get any warning? A: #TEMP tables are only available from the context they are created in. If you create #temp1 in one spid or connection, you can't access it from any other scope, except for child scopes. If you create the #TEMP table in dynamic SQL, you need to select from it in the same scope. Alternatives are: * *##GLOBAL temp tables, which have their own risks. *Real tables
{ "language": "en", "url": "https://stackoverflow.com/questions/7568968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: cupsenable cupsdisable I have a web application that is run as www-data. I need to have cupsenable and cupsdisable accessible for that user. Its a server that isn't connected to the internet and is running a small internal application and i NEED to be able to give the users the ability to re-enable a printer. I have already made the executables permissions world executable. Testing with ... sudo -u www-data /usr/sbin/cupsenable laser_01 cupsenable: Operation failed: client-error-forbidden A: I just needed to add the user to the lpadmin group. I was over thinking this. A: It seems like you don't have a problem with the execute-permissions. You must be permitted to administrate cups. So it isn't enough to modify your sudo-rules. In fact i rolled back my sudo-modifications after configuring cups correctly. Try to edit your /etc/cups/cups-files.conf: You can define a SystemGroup. All groups added here match the policy rules @SYSTEM in cupsd.conf. Add the group(s) of your user(s) here and restart cups. * *Find out the group of your user www-data. *Then add it, seperated by whitespace, to the SystemGroup in your cups.files.conf. *Restart cups. That worked for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568979", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does FreeBSD support memory mapped files? I am using a FreeBSD OS, I want to write into a file which is on the disk, but, it will take a lot of time, so, I was suggested to use Memory mapped file. But, I am in a dilemma whether FreeBSD supports it or no???.. Please, somebody can guide me??.. I am programming in C++. A: Any UNIX (Posix compliant OS) has mmap, so yes FreeBSD has it. STL does not exist as such. (see e.g. What's the difference between "STL" and "C++ Standard Library"?) You mean: Does the C++ standard library 'have' it? No, the C++ standard library does not directly provide/wrap support for mmap. However, you can have a look here: * *mmap() vs. reading blocks *Boost::Iostreams already has a mapped_file: boost::iostreams::mapped_file A: Yes, FreeBSD has memory mapped files. No, the STL does not include any special support for them. Consider using Boost.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568985", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: SQL Query seems to be executing twice Possible Duplicate: Insert query on page load, inserts twice? I'm hoping someone can help with a problem that's driving me up the wall. I've searched but found nothing directly answering this. I have a problem on a website where an SQL INSERT query seems to run twice but only on some occasions. It's a simple shopping site. On my product page there is an 'Add To Cart' button. On pressing this a user is taken to the Cart page, and various variable are passed across. An INSERT query is run when the page loads and the results are displayed in the shopping cart. This all works fine most of the time, but on some occasions, the product is added to the database twice. The problem is not related to any specific product. Since it works OK the majority of the time, I'm pretty confident the code is OK. The only thing I can say is that I have not as yet seen the problem outside of Firefox. Some people have suggested turning of the 'Disable Cache' via Toolbar, which I have, but still getting problems. Very grateful for any suggestions. A: What happens when you reload the cart page? Does the POST operation happen again - it could be that if there's a hang while the page is loading (which can happen with Firefox - particularly on Macs - something to do with its caching system) the user might be hitting reload and therefore resending the page data and running in INSERT query again. IF this is the case... ... the best idea is probably to add in a step that deals with the database that outputs nothing (no output means no caching). So your "add to basket" form posts the data to a database handling script which performs the operations and then does a simple header("location:...") to pass the user off to the "display cart" page. That way the script that performs the database operations displays nothing and is never cached - and the user can hit reload on the "display cart" page as often as they like and it'll just reload their existing cart. A: Firstly, though it's not going to sound very helpful, the problem will be with your code, not with Firefox, PHP, or MySQL. I've been through exactly what you're going through, and been sure it must be a bug, but something this obvious would have been fixed by now. To help you narrow down where the bug is occurring, it would be worth logging various points in your code, so you can see how it flows through. It may help to log the SQL queries as well, so you can see if they are being called in quick succession, or whether it is a loop of some sort where something else occurs before the second call. As the insert is done in PHP, this is all carried out server-side, so the chances of it being browser-specific are pretty slim. There's a lot of help on this site, but to give you any more concrete advice you'll need to post code, and a bit more detail about the flow of the application. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7568987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Android - Exception when updating table in database I get one exception "SQLiteException: cannot commit - no transaction is active". This exception is occur when i try to update my table in DataBase . I don't know why this exception is occur & what was the meaning of this exception. So if any one know then please tell me how I can resolve this exception. In code when I replace update query to insert query then no error occur. My update query is like e.g ContentValues cVal=new ContentValues(); cVal.put("search", 0); int count=sqLiteDatabaseWrite.update("TableName", cVal, null,null); OR also try this sqLiteDatabaseWrite.execSQL("update TableName set search=0"); In both case error occur. Here I print my logcat. Thank You android.database.sqlite.SQLiteException: cannot commit - no transaction is active at android.database.sqlite.SQLiteStatement.native_executeSql(Native Method) at android.database.sqlite.SQLiteStatement.executeUpdateDelete(SQLiteStatement.java:89) at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1928) at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1859) at android.database.sqlite.SQLiteDatabase.endTransaction(SQLiteDatabase.java:683) at android.database.sqlite.SQLiteStatement.releaseAndUnlock(SQLiteStatement.java:266) at android.database.sqlite.SQLiteStatement.executeUpdateDelete(SQLiteStatement.java:96) at android.database.sqlite.SQLiteDatabase.updateWithOnConflict(SQLiteDatabase.java:1824) at android.database.sqlite.SQLiteDatabase.update(SQLiteDatabase.java:1775) at com.ScentSational.SearchProducts.insertIntoProductTable(SearchProducts.java:609) at com.ScentSational.SearchProducts.parseSearchXml(SearchProducts.java:434) at com.ScentSational.SearchProducts$Async_SearchParsing.doInBackground(SearchProducts.java:780) at com.ScentSational.SearchProducts$Async_SearchParsing.doInBackground(SearchProducts.java:1) at android.os.AsyncTask$2.call(AsyncTask.java:252) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) at java.util.concurrent.FutureTask.run(FutureTask.java:137) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1081) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:574) at java.lang.Thread.run(Thread.java:1020)
{ "language": "en", "url": "https://stackoverflow.com/questions/7568988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to see the Exception thrown by the Blackberry Application I am new to Blackberry Development. In my app it is throwing an Exception,it is showing on simulator. I want to know how can I see this exception in detail like 'Logcat' in Android. Thanks in Advance A: Try like this: try { //write code here; } catch(final Exception e) { UiApplication.getUiApplication().invokeLater(new Runnable() { public void run() { Dialog.alert("Exception: "+e.getMessage()); System.exit(0);//if you want to close the application; } }); } Enough; If you have doubts come on StackOverFlow chat room name "Life for Blackberry" to clarify Your and our doubts A: try{ ...... ..... } catch(Exception ce){ System.out.println(ce.getMessage()); } if you are using ECLIPSE just run the application in DEBUG mode.... Then check for whichever exception occured in console pane.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Sql injection script This title of the question may seem to be previously asked and answered but its different scenario for me. I use this script to stop sql injection in my ASP site. As per my knowledge or injecting script i have tried everything . Is it still possible to break through this code or do you feel this is fine . Here is the script <% Function IsInject(strCheck, boolForm) IsInject = False If Not boolForm And Len(strCheck) > 50 Then IsInject = True ' Dim sCmdList, arrCmds, i If boolForm Then sCmdList = "declare,varchar,convert,delete,create,is_srvrolemember,ar(,cast(" Else sCmdList = "update,union,select,drop,declare,varchar,convert,delete,create,is_srvrolemember,ar(,cast(,char(" End If arrCmds = Split(sCmdList, ",") For i = 0 To UBound(arrCmds) If Instr(UCase(CStr(strCheck)), UCase(arrCmds(i))) > 0 Then IsInject = True Exit For End If Next Erase arrCmds End Function Function CleanInject(strClean, boolInt) If boolInt Then CleanInject = CInt(strClean) Else CleanInject = Replace(strClean, "'", "''") End Function '----------------------------------------------------------- 'redirect user if specific IP 'Dim ipaddress, bFBIRedirect, sInjectType bFBIRedirect = True ipaddress = Request.ServerVariables("REMOTE_ADDR") Select Case ipaddress Case "90.120.206.10" Case Else bFBIRedirect = False End Select If bFBIRedirect Then Response.Redirect "http://www.fbi.gov" '----------------------------------------------------------- 'Dim bIsInject, sHackString bIsInject = False If Not bInject Then ' Dim qsItm For Each qsItm In Request.QueryString If IsInject(Request.QueryString(qsItm), False) Then bIsInject = True sHackString = qsItm & "=" & Request.QueryString(qsItm) sHackType = "QueryString" sInjectType = "qs-" & Request.QueryString(qsItm) Exit For End If Next End If If Not bInject Then ' Dim frmItm ' For Each frmItm In Request.Form ' If IsInject(Request.Form(frmItm), True) Then ' bIsInject = True ' sHackString = Request.Form(frmItm) ' sHackString = frmItm & "=" & Request.Form(frmItm) ' sHackType = "Form" ' Exit For ' End If ' Next End If If bIsInject Then Session("hacktype") = sHackType Session("hackstr") = sHackString Session("thepagefrom") = Request.ServerVariables("PATH_INFO") Session("theip") = Request.ServerVariables("REMOTE_ADDR") ' Dim arrWhereAt, iWhereAt, sRedirect arrWhereAt = Split(Request.ServerVariables("PATH_INFO"), "/") iWhereAt = UBound(arrWhereAt) sRedirect = "unknownerror.asp?ip=" & Request.ServerVariables("REMOTE_ADDR") & "&err=" & sInjectType & "&pg=" & Request.ServerVariables("PATH_INFO") If iWhereAt = 1 Then sRedirect = "../" & sRedirect If iWhereAt = 2 Then sRedirect = "../../" & sRedirect If iWhereAt = 3 Then sRedirect = "../../../" & sRedirect Response.Redirect sRedirect End If %> A: rather doing that I think I would use ADO Parameter object when creating SQL queries, the second best thing is to do type conversion of the inputfields for the dynamic SQL queries, such as converting strings to SQL strings (replace any ' with two ''), making sure number is a number etc. A: Using blacklists to remove commands is not really a good idea. You have to make sure you cover all possible commands, and still someone might sneak something past. This would also probably fail if you get data from a user that is not an attack, but still contains an attack string. Example "Back in the days of the Soviet Union". As Nikolai suggests, see if you can find some type of prepared statements to use. Or find a really good library to properly escape data for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568995", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: WCF Async Service Proxy. Does 'EndXXX' close the connection? I'm currently segregating the interface definition of a WCF web service and sorting out the client to depend on these interfaces rather than the generated service client class. The pattern that's currently being used reads like this - var client = new ServiceClient(); client.DoSomethingCompleted += (o,args) => { client.CloseAsync(); //Do Something } client.DoSomething(); Nice and simple. As soon as the client returns, close the connection. By depending on the interface of the proxy you lose out on the generated events and have to use the Async Begin/End pattern. Now it would read - //client is now an IDoSomethingable client.BeginDoSomething(new AsyncCallback((result) => { var somethingDone = client.EndDoSomething(result); }),null); So my question is does the client get closed when 'EndDoSomething' is called or am I missing something since there doesn't appear to be an explicit way to close it. Much thanks in advance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568998", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Getting data from MailChimp using SilverLight I have created my own silverlight API to get/set data from/to MailChimp. It was working fine, but today I am getting an error. Example code is : string MailChimpURL = "https://us2.api.mailchimp.com/1.3/?method=lists&apikey=my_api_key-us2"; HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(MailChimpURL)); request.BeginGetResponse(new AsyncCallback(ReadCallback), request); private void ReadCallback(IAsyncResult asynchronousResult) { HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult); using (StreamReader streamReader1 = new StreamReader(response.GetResponseStream())) { string resultString = streamReader1.ReadToEnd(); } } This works fine with http but gives error when using https. The error which https is for yesterday. Months back it was working fine for both http and https. Now its only working for http. Is this a problem in my code or this from MailChimp. A: I don't think you are showing us the true exception. The exception you are seeing when inspecting the AsyncWaitHandle property you will always get when debugging because Siverlight does not support that property. You really need to place some error handling in your ReadCallBack so you can report back to the UI in a friendly way anything that may have gone wrong.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568999", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: WordPress template for Orchard I am looking for a charity template to help my friend to make a website for a non-profit organization. But I don't know how to program in PHP, I already know ASP.Net MVC 3 and C#. I found out a nice template: http://osc4.template-help.com/wordpress_30418/ but is just for wordpress, does anybody know if is possible to adapt it to use with ASP.Net MVC, or Orchard? Best regards, Tito A: It would require a lot of work. You should be able to strip away the php and fill in the appropriate Orchard code. Your first goal could be to do remove the PHP. Then mock in the HTML to get it to look right then change it to use Razor. The top is flash.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: basic git understanding problems Situation I've never before used git or any other version control. Now I've got a web-project that needs to have a stable and a developement version, with both running on the same server in different directories. * *Stable: /var/www/afod/afod *Development: /var/www/afod_dev/afod Now I want to use git to sync changes from the dev-version into the stable-version and as I've never before used VC-systems I don't seem to get how to do this. What I have done until now I created a git repository in /var/www/afod/afod and cloned it into the dev directory via: cd /var/www/afod_dev/afod git clone /var/www/afod/afod Now I've got 2 repositories which I want to keep synchronised using git pull on the stable-version side. The problem(s) I've already got 2 branches, web and dev. But as it seems git pull in the stable-version syncs from both branches. But I only want to sync the changes to the stable version, that I have already merged to the web-branch in the dev-version. total confusion I hope I could somehow point out my problem. I seem to have a basic understanding problem of how git works, but it seems to be the right software to do what I want to do. I basically want to have a branch that is automatically synced into the stable version and other branches I merge into it. But the developement must be in a different directory than the stable version is. Concerning the first answer from Billy Moon Well, stable and dev are hosted under a different domain in a different apache vserver. It wouldn't make any sense to work on a dev-branch that is in the directory people see when they browse the site. So my idea was to clone the repository and then sync these. Do I get something wrong here? How do you deal with such configurations? A: Branches I think you are on the right track, but a llittle confused with the idea of a branch. You can visualize a branch as two branches on a tree. Both have the same trunk, source, but the tips are different. The differences are between the same code base and can be minor or major. When you run the command git checkout <branch_name> you are telling git you want different tips of the tree to be active, copied into the working directory. In your case, one branch has the development code, and the other has your stable code. To get the code from the dev branch into the web branch, you use git merge <branch_to_pull_in> This combines the tips of those two branches so their content is the same. For more information on branches in general, Here is a generic non git page. Possible Solution Below is a solution that could work for you. There are other possible work flows, but this is one of the simplest ones. Clone your development repository into /var/www/afod/afod. Than from within /var/www/afod/afod run git checkout web and from your devfolder, ensure that you are on the dev branch. git branch should have a line like this * dev. You now have two different branches of the same repository checked out into different subfolders. Do your work in dev as you have. Once you feel it is stable, from within your dev folder run git checkout web. Than, git merge dev. This will merge those changes into your web branch. Now from within /var/www/afod/afod run git pull. This will pull your chnages into the production server. Both dev and web will be pulled over, but only the one that is checked out will be in your working directory. When you want to work in the dev branch again, run git checkout dev from within the dev folder. A: I think stable and development should be branches, not separate repositories. Here is a great tutorial on basic git and how a simple workflow can work: http://www.ralfebert.de/tutorials/git/
{ "language": "en", "url": "https://stackoverflow.com/questions/7569011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Unicode literals causing invalid syntax The following code: s = s.replace(u"&", u"&amp;") is causing an error in python: SyntaxError: invalid syntax removing the u's before the " fixes the problem, but this should work as is? I'm using Python 3.1 A: On Python 3, strings are unicode. There is no need to (and as you've discovered, you can't) put a u before the string literal to designate unicode. Instead, you have to put a b before a byte literal to designate that it isn't unicode. A: The u is no longer used in Python 3. String literals are unicode by default. See What's New in Python 3.0. You can no longer use u"..." literals for Unicode text. However, you must use b"..." literals for binary data. A: In Python3.3+ unicode literal is valid again, see What’s New In Python 3.3: New syntax features: New yield from expression for generator delegation. The u'unicode' syntax is accepted again for str objects.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569014", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Sample Concurrency projects in Java I finished reading the first seven chapters of Java Concurrency in Practice. Can you give me any ideas of sample projects so that my ideas will become solidified ? A: How about implementing your own 'thread safe' list and then making multiple threads add, get, and remove elements from it? Liberal use of System.out would show you just how interesting it can get when multiple threads work on the same data structure. A: This guy has a great set of tutorials on concurrency. jenkov tutorials One interesting exercise try to create a "fair" lock using nothing but the simplest java language constructs. It allows you to become intimately familiar with all the paranoia inducing aspects of threads(race conditions, missed signals, etc.) and helps us come to terms with why the prospect of writing multi-threaded applications keep me up at night.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Oauth client initialization in python for tumblr API using Python-oauth2 I'm new to Oauth. In the past for twitter applications written in Python i used python-oauth2 library to initialize client like this: consumer = oauth.Consumer(key = CONSUMER_KEY, secret = CONSUMER_SECRET) token = oauth.Token(key = ACCESS_KEY, secret = ACCESS_SECRET) client = oauth.Client(consumer, token) That was easy because twitter provides both CONSUMER and ACCESS keys and secrets. But now i need to do the same for tumblr. The problem is that tumblr provides only CONSUMER_KEY, CONSUMER_SECRET and these urls: Request-token URL http://www.tumblr.com/oauth/request_token Authorize URL http://www.tumblr.com/oauth/authorize Access-token URL http://www.tumblr.com/oauth/access_token Using this data how can i initialize client to access tumblr API? UPD jterrace suggested a code i tried to use before. The problem with it is oauth_callback. If i don't specify any, api returns error "No oauth_callback specified", but if i do specify some url like "http://example.com/oauthcb/" and follow the link http://www.tumblr.com/oauth/authorize?oauth_token=9ygTF..., then press Allow button, tumblr doesn't show any PIN code page, it immediately redirects to that callback url, which is useless since it's desktop application. Why PIN code isn't shown? UPD 2 Tumblr API doesn't support PIN code authorization. Use xAuth instead - https://groups.google.com/group/tumblr-api/browse_thread/thread/857285e6a2b4268/15060607dc306c1d?lnk=gst&q=pin#15060607dc306c1d A: If you just want to gain an access-token/secret to sign, you could just setup your callback URL as: http://localhost/blah * *Fireup the CLI-app (after modifying the callback-url, secret and token ofcourse) *Follow the link in your browser *Allow app *View addressbar of the page you've been redirected to in the browser after allowing your app. It should look something like: http://localhost/blah?oauth_token=xxxxxxxxxxxxxxxxxxxxxxxxxx0123456789ABCDEFGHIJKLMN&oauth_verifier=XXXXXXXXXXXXXXXXXXXXXXXXX0123456789abcdefghijklmn Use the value of the query-parameter 'oauth_verifier' as your PIN: XXXXXXXXXXXXXXXXXXXXXXXXX0123456789abcdefghijklmn The CLI should print out your oauth-token and oauth-token-secret. HTH! Got this working for tumblr in this way :) A: First, import the oauth2 module and set up the service's URL and consumer information: import oauth2 REQUEST_TOKEN_URL = 'http://www.tumblr.com/oauth/request_token' AUTHORIZATION_URL = 'http://www.tumblr.com/oauth/authorize' ACCESS_TOKEN_URL = 'http://www.tumblr.com/oauth/access_token' CONSUMER_KEY = 'your_consumer_key' CONSUMER_SECRET = 'your_consumer_secret' consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET) client = oauth2.Client(consumer) Step 1: Get a request token. This is a temporary token that is used for having the user authorize an access token and to sign the request to obtain said access token. resp, content = client.request(REQUEST_TOKEN_URL, "GET") request_token = dict(urlparse.parse_qsl(content)) print "Request Token:" print " - oauth_token = %s" % request_token['oauth_token'] print " - oauth_token_secret = %s" % request_token['oauth_token_secret'] Step 2: Redirect to the provider. Since this is a CLI script we do not redirect. In a web application you would redirect the user to the URL below. print "Go to the following link in your browser:" print "%s?oauth_token=%s" % (AUTHORIZATION_URL, request_token['oauth_token']) # After the user has granted access to you, the consumer, the provider will # redirect you to whatever URL you have told them to redirect to. You can # usually define this in the oauth_callback argument as well. oauth_verifier = raw_input('What is the PIN? ') Step 3: Once the consumer has redirected the user back to the oauth_callback URL you can request the access token the user has approved. You use the request token to sign this request. After this is done you throw away the request token and use the access token returned. You should store this access token somewhere safe, like a database, for future use. token = oauth2.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(oauth_verifier) client = oauth2.Client(consumer, token) resp, content = client.request(ACCESS_TOKEN_URL, "POST") access_token = dict(urlparse.parse_qsl(content)) print "Access Token:" print " - oauth_token = %s" % access_token['oauth_token'] print " - oauth_token_secret = %s" % access_token['oauth_token_secret'] print Now that you have an access token, you can call protected methods with it. EDIT: Turns out that tumblr does not support the PIN authorization method. Relevant post here. A: Have a look at https://github.com/ToQoz/Pyblr It uses oauth2 and urllib to provide a nice wrapper for exactly what you're trying to do. A: It seems that what you're trying to do is access an OAuth 1 API with an OAuth 2 client. See https://github.com/simplegeo/python-oauth2 and look for “three-legged OAuth example”. A: had this problem with oauth2 and facebook. @deepvanbinnen's answer lead me into the right direction. facebook actually redirected to a page similar to this 'http://localhost/blah?code=AQAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX#_=_' using then the ' AQAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX#_=_ as the PIN actually got me the access to the requested facebook account. A: @jterrance's answer is good. However, realize it is a one _time_ manual procedure to get the access token. The access token is the key that you use for all subsequent API calls. (That's why he recommends saving the access token in a database.) The string referred to as 'PIN' (aka the verification key) is not necessarily a number. It can be a printable string in any form. That verification key is displayed on the authorization page at the URL printed in step 2 then pasted into the prompt for a the 'PIN'.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569018", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: One loader for all activities Im building an Android application. It parses a feed which is stored in a DB. Each activity of the app is able to get this data from the DB. Every activity can also call the Service, and make it refresh the data. When this is done I would like to display a loader. While the Service is downloading, the user is still free to navigate between activities. My question is; how can I display a loader that runs in all activities the user navigates to? Thanks a lot :) A: Here's what I would try to do since it seems to be an uncommon task to me: I would try to setup a translucent PopupWindow which contains a progress indicator. I would trigger / dismiss this popup to be displayed / or not whenever there's a need to indicate the loading progress... A: You could try something like: * *Place a "global loader view" in all your activities. *When you start/return to an activity, fire an AsyncTask which will be used to handle updates of the global loader *Override onPreExecute() to prepare the global loader (e.g. setting its state to the current level if the service has been downloading for a while) *Override onProgressUpdate() and use it to update the state of the global loader by asking the Service for the current state (load percentage or something) *In doInBackground you implement: while( service.isLoading() ) { publishProgress( service.getLoadPercentage() ) // Maybe add a Thread.sleep() here. } *Override onPostExecute to set the visibility of the global loader to View.GONE. You might need to implement a way of killing the AsyncTask if the user switches away from the activity when the loading is not finished yet.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569021", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Circle Detection I need help developing a circle detection algorithm to detect snooker balls. Does anyone know any algorithms that can be implemented in C and open cv? I'm having trouble getting this done A: OpenCV 2.3 comes with HoughCircles. The C++ API for OpenCV 2.1 also implements the function: http://opencv.willowgarage.com/documentation/cpp/imgproc_feature_detection.html#HoughCircles
{ "language": "en", "url": "https://stackoverflow.com/questions/7569023", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Z-Index Absolute positioning - Using Z-Index to always appear at the top when panel is behind I am quite accustomed to CSS but I have a problem and would like to know if there is a solution. If I have a div with relative positioning and z-index:2 and another div next to it with z-index:1. Is there a way to have an element in the second DIV rise on top of the first. Z-index:3 will not do it because it is inside an element at z-index 2. .div1 { position:relative; z-index:2 } .div2 { position:relative; z-index:1 } .inner element { position:relative; z-index:3 } Any ideas. Marvellous A: Assuming I understood your question correctly - No, the element you want on top will have to have a higher z-index. http://jsfiddle.net/Wgsqd/ A: You would have to use javascript to access the left and top coordinates of the relatively positioned element, and then set its position to absolute to free the element of its parent's z-index. If you're using JQuery var top = $(".inner").position().top(); var left = $(".inner").position().left(); $(".inner").css({ position: "absolute", top: top, left: left });
{ "language": "en", "url": "https://stackoverflow.com/questions/7569037", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: WCF, WAS, IIS and ports Hi, I have worked with WCF for a while now but there is somthing Im not clear on. When hosting a WCF service in IIS the standard protocol will be http and the default port is 80. Its possible to change this portnr if needed. Then its also possible to host a WCF service in IIS using the TCP protocol(WAS). The WCF service will however still publish its mex on port 80 on http prootocol but how do I see the port nr for the WCF TCP communication? I Supose that I will have to open first the port nr for the mex(usually port 80) and then also the WAS(WCF TCP in IIS) port? BestRegards A: You can see which port TCP will use by going into the website configuration in IIS and looking at the site bindings, then looking for (or adding, if necessary) the net.tcp binding. Here is the documentation on how to configure bindings. If I remember correctly, the default port is 808.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Borland vs. MingW/GCC compilation speeds.. I'm a long time Borland users ( since Turbo C ) ( until BC5.2 ). I've been using MingW/GCC with CodeBlocks for about a year now, mainly for the extra support esp. native 64bit integers. Anyway, I have a query regarding compilation speeds. I have a C (Win32) file which is apx 60,000 lines in length. On Borland 5.2 this file takes apx 3-5 seconds to compile. On GCC it takes a bit over 35 seconds. The GCC command line options I am using are. -std=c99 -s -O2 (ive also tried -O) The final exe size is pretty much the same +/- 50kB. Why the big difference in compilation time ? and is there a way to speed up GCC to be comparable to BC5.2 ? A: Borland's compilers were designed from inception to be fast, at least according to marketing and benchmarking published at the time, and widely acknowledged in the industry. They target a single architecture, the x86 family. gcc was not designed to be fast. It is designed to: * *target code for multiple architectures, from embedded controllers to supercomputers *be hosted on multiple architectures *keep pace with the ever changing C++ language standard The divergence of the intended use undoubtedly affects its performance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Want to store photos like photo application I would like to store severals photos like photo application, however i don't know exactly the objects what i need. If anyone know how to implement this way i'm interested. A link to give you an idea: http://blog.photobox.fr/wp-content/uploads/2010/07/Album-iPhone5.jpg thank you in advance. A: You can try the PhotoViewer provided in three20 framework. It is exact replica of the Photos app of iPhone, if that's what you're looking for. You can find a tutorial here. A: go to this link it help u https://github.com/kirbyt/KTPhotoBrowser A: Having spoken to an Apple engineer on some of the optimizations that they went through on the Photos app, I can give you a couple of tips: * *They never display back the original photo. Because of a photo's size, they only take the original photo and save off a number of optimized thumbnail images. *The example image you show does not contain a series of thumbnail images. Each row is actually a single image. For selection, an overlay is placed in the exact size and dimension of the thumbnail image to give the impression that you are selecting a particular image. This could be accomplished by using a table view, but it more likely just a scroll view.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569047", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: findpreference undefined type I am trying to set a value to a ListPreference and always get the error message: The method findPreference(String) is undefined for the type new DialogInterface.OnClickListener(){} This is my code: ListPreference lp = (ListPreference) findPreference("enableTranslations"); lp.setValue(""); Thanks A: You simply call findPreference in wrong place (in OnClickListener). Call it in method of class that has findPreference method (PreferenceManager or PreferenceActivity) or on object of such type.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SSH with Paramiko : failing to read data Below is my driver information where I need to pull the data(Firmware Version) using ssh script as show below. ncmdvstk:~ $ ssh admin@153.88.127.21 Password: MSM760 V. 5.3.6.18-01-9124 (C) 2010 Hewlett-Packard Development Company, L.P. CLI> enable CLI# show system info [CPU info] [Mem in fo] Firmware Version: 5.3.6.18-01-9124 Load 1min: 0.34 Total RAM: 9 This is the program I am using to read all the data first in "data" variable, so that later i can split n get info i need but where as no data it's printing in print data: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('153.88.127.21', username='admin',password='catfish') stdin, stdout, stderr = ssh.exec_command("enable") stdin.write('show system info \n') data = stdout.read() print data Please correct me on getting the data. A: You need to add a call to stdin.flush() after the stdin.write() otherwise the input you're sending will stay buffered.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569050", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: In what situations would I specify operation as unchecked? For example: int value = Int32.MaxValue; unchecked { value += 1; } In what ways would this be useful? can you think of any? A: Use unchecked when: * *You want to express a constant via overflow (this can be useful when specifying bit patterns) *You want arithmetic to overflow without causing an error The latter is useful when computing a hash code - for example, in Noda Time the project is built with checked arithmetic for virtual everything apart from hash code generation. When computing a hash code, it's entirely normal for overflow to occur, and that's fine because we don't really care about the result as a number - we just want it as a bit pattern, really. That's just a particularly common example, but there may well be other times where you're really happy for MaxValue + 1 to be MinValue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: ipojo custom handlers - auto attached handlers - issue in attaching to specific components I have an issues concerning the custom auto handlers in ipojo. I have created an handler (say Handler-Auto), I want this handler to be auto attached to a POJO component instances (say Comp-1) without touching the metadata of POJO components. To achieve this, we need to set the "org.apache.felix.ipojo.handler.auto.primitive" variable in the system property with the list of handlers as specified in the below link: https://issues.apache.org/jira/browse/FELIX-2594?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel#issue-tabs The problem is, when I do like this, my handler (Handler-Auto) is attached to all the components or instances that are created or deployed over the system. To intercept methods or fields from a particular component we need to add filter at the handler. But its too late to add filter after attaching handlers with all unnecessary stuffs. Instead of attaching the handler to all the components, Is there anyway that, this handler (Handler-Auto) can me made to be attached to a specific components or instances ? as per the user wish. It would be great if we have this feature and it ll become very dynamic. Please help if there is any other way to do this or what could be the solution to achieve this ?? thanks for your help in advance! Thanks, Sadish
{ "language": "en", "url": "https://stackoverflow.com/questions/7569057", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Regex to extract paragraph I am attempting to write a regex in Python to extract part of a paragraph. In the below paragraph, the part I wish to extract is bolded. Proposal will boost bailout fund, inject cash into banks and cut Greek debt says reports. My regex and output as follows, >>> text = 'Proposal will boost bailout fund, inject cash into banks and cut Greek debt says reports.' >>> pattern = re.compile(r'(boost bailout)+?([\s\S]*?)(debt)+?') >>> print re.findall(pattern, text) [('boost bailout', ' fund, inject cash into banks and cut Greek ', 'debt')] Although it does extract the correct section, is it right that the extraction is separated into 3 parts in a tuple and not just a single line such as the below? [('boost bailout fund, inject cash into banks and cut Greek debt')] A: use re.search(reg, text).group(0) or (your case): pattern.search(text).group(0) A: From the documentation: If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless they touch the beginning of another match. -- http://docs.python.org/library/re.html If you want one match, do: #!/usr/bin/env python import re text = 'Proposal will boost bailout fund, inject cash into banks and cut Greek debt says reports.' pattern = re.compile(r'boost bailout[\s\S]*?debt') print re.findall(pattern, text) A: Your pattern is incorrect: (boost bailout)+ means : the string 'boost bailout' repeated several times, which is certainly not what is wanted. If you put several pairs of parens in the pattern, you'll obtain several catching groups. The correct pattern, if you want only to extract all the text between 'boost bailout' and the LAST string 'debt' is: pattern = r'boost bailout.+debt' and the regex is reg = re.compile(r'boost bailout.+debt',re.DOTALL) re.DOTALL is a flag that makes the dot symbol matching every character, comprised the newlines: it replaces [\s\S]. But if you want to extract between 'boost bailout' and FIRST appearance of 'debt', it must be pattern = r'boost bailout.+?debt' Also, use reg.search(text).group() instead of reg.findall(text) that produces a list of one element. Note that pattern defined by pattern = r'boost bailout.+?debt' is a string object, and that reg defined by reg = re.compile(pattern) is a RegexObject object. What deserves the name regex is the RegexObject, what deserves the name pattern is the string. A: You are returned a tuple because, as you can read in the Python documentation for the re module, parentheses create capture groups, which may then be retrieved separately. In order to avoid this you should use a non capturing group: (?: ... )
{ "language": "en", "url": "https://stackoverflow.com/questions/7569069", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Stored procedure error on CALL I am trying to call a procedure which compiles successfully but on calling I get this error: Query: call proc5 Error Code: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NULL' at line 1 This is my Stored procedure: DELIMITER $$ CREATE DEFINER = `root` @`localhost` PROCEDURE `proc5` () BEGIN DECLARE done BOOL DEFAULT FALSE ; DECLARE tablename VARCHAR (100) ; DECLARE tracktables CURSOR FOR SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'db1' ; DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = TRUE ; OPEN tracktables ; myloop : LOOP FETCH tracktables INTO tablename ; IF done THEN CLOSE tracktables ; LEAVE myloop ; END IF ; SET @s = CONCAT( 'INSERT INTO db2.test1 SELECT * FROM ', @tablename ) ; PREPARE stmt1 FROM @s ; EXECUTE stmt1 ; DEALLOCATE PREPARE stmt1 ; END LOOP ; END $$ DELIMITER ; Actually, I want to select all the tables from a database and insert those tables into one table which is in another database using MySQL Cursors. And when I call this stored procedure I get the above error. A: The problem is that you are mixing declared variables and impromtu @vars. var -> tablename does not equal var -> @tablename. Change the set line to: SET @s = CONCAT( 'INSERT INTO db2.test1 SELECT * FROM `' ,tablename ,'`' ) ; Now it should work. The backticks ` should not be needed, but are there just in case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Android-jQM: MyWebViewClient::shouldOverrideUrlLoading() not working with local URI I'm using Android's WebViewClient to handle <a> clicks of my jquerymobile page. It is working fine when my target is some full url like <a href="http://stackoverflow.com"> but if my target is local script for eg. <a href="test.html">, I'm not event getting the call to my shouldOverrideUrlLoading. thanks, nehatha A: I could find the solution doing this: <a href="file.php?number=<?=time();?>" ... data-ajax='false'>Link</a> Hope it works for you. Cheers
{ "language": "en", "url": "https://stackoverflow.com/questions/7569073", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java FTP file get issue I have a application that runs as a schedule.It connect to ftp server and get files from remote folder.scheduler runs in every 5min time.Sometimes when there are lot of files in remote location, scheduler runs again while first cycle is running.In such situation some times it download 0 size files even actual file size is greater than 0 in remote location.Does anyone have any idea why this happen? below is the code to import files. private void importEDIFiles(String host, String user, String password, String path, String road) { try { String edi824Path = path + "/" + EDI_824_FOLDER; FTPBroker ftpBroker = new FTPBroker(host, user, password, edi824Path); FTPClient client = ftpBroker.makeFTPConeection(); String os = client.getSystemName(); client.setFileTransferMode(FTP.ASCII_FILE_TYPE); File edi824File = null; File edi824Filebak = null; ArrayList<FTPFile> files; try { FTPFile[] ftpfiles = client.listFiles(); logger.info("\t" + ftpfiles.length + " files are in ftp location "); if (ftpfiles.length > 0) { files = removeZeroFiles(ftpfiles); for(int x=0;x<files.size();x++){ logger.info("name ---"+files.get(x).getName()); logger.info("size ----"+files.get(x).getSize()); } String ftpFile = null; logger.info("\t" + files.size() + " downloading from " + road + " rail road."); for (int i = 0; i < files.size(); i++) { ftpFile = files.get(i).getName(); logger.info("\t" + ftpFile + " is downloading...."); // logger.info("\t" + ftpFile + " size ...." + ftpFile.isEmpty()); String source = destinationFilePath + pathSeparator + road + pathSeparator + ftpFile; String target = edi_824backupFilePath + pathSeparator + road + pathSeparator + ftpFile; edi824File = new File(source); edi824Filebak = new File(target); FileOutputStream fosout = new FileOutputStream(source); boolean isRetrieved = client.retrieveFile(ftpFile, fosout); logger.debug("isRetrieved : " + isRetrieved); FileUtils.copyFile(edi824File,edi824Filebak); fosout.flush(); fosout.close(); boolean isDelete = client.deleteFile(ftpFile); logger.debug("isDelete : " + isDelete); } } else { logger.info("No files to Pull in the FTP Location for " + user); //throw new RuntimeException("No files to Pull in FTP Location."); } } catch (Exception e) { logger.error(e,e); e.printStackTrace(); } finally { client.logout(); client.disconnect(); } } catch (Exception ex) { logger.error(ex, ex); ex.printStackTrace(); } } A: you can use a flag boolean isRunning(), setRunning(boolean ), and synchronize your code so that two or more threads would not run the same method at the same time
{ "language": "en", "url": "https://stackoverflow.com/questions/7569076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails custom Twitter Bootstrap modal for delete method, Problem with callback Following code does destroy records as intended, but the callback is inherited from one modal to the next one. So while a record is properly deleted, Rails keeps looking to delete the formerly deleted ones as well. I'm using a Twitter Bootstrap modal window, that sits in a Rails view template and is shown when a standard Rails delete method is fired, replacing the regular javascript dialog. How to clear the callback after it has been fired? $.rails.allowAction = function(element) { var message = element.data('confirm'), answer = false, callback; if (!message) { return true; } if ($.rails.fire(element, 'confirm')) { myCustomConfirmBox(message, function() { callback = $.rails.fire(element, 'confirm:complete', [answer]); if(callback) { var oldAllowAction = $.rails.allowAction; $.rails.allowAction = function() { return true; }; element.trigger('click'); $.rails.allowAction = oldAllowAction; } }); } return false; } function myCustomConfirmBox(message, callback) { $('#dialog-confirm').modal('show'); $('#dialog-confirm button.primary').click(function(){ callback(); $('#dialog-confirm').modal('hide'); }); } edit: Since I'm using the same base modal over and over again for any delete action, the callbacks queue up. So when a delete action has been cancelled before, it will still be triggered on another delete instance of a different object, since the callback is still valid. Bottom line: How to clear the callback queue? A: Turns out it is a bad idea to fiddle with the native delete method/callback for various reasons. My workaround solution is as follows. Have a "delete" button in your view, with some JS data values: #delete button in view template link_to "delete", "#", :class => "delete_post", "data-id" => YOUR_POST_ID, "data-controls-modal" => "YOUR_MODAL_LAYER", #more bootstrap options here… Bootstrap opens the modal window. Inside that, have another "delete" button with "remote" set, so the action will use JS. #delete button in modal window link_to "delete", post_path(0), :method => :delete, :class => "btn primary closeModal", :remote => true CloseModal is another :class for me to know when to close the bootstrap modal window. I've put an additional function for that in my application.js. Note, the default path has a nil value, we'll attach the real post ID to be deleted via JS in the next step via the "data-id" param: #application.js $('a.delete_post').live('click', function(){ _target = $(this).data('id'); $('#YOUR_MODAL_LAYER .primary').attr('href', '/posts/' + _target); }); The destroy action in our Posts controller will use JS to render an animation for the deleted post: #posts_controller.rb def destroy @post = Post.find(params[:id]) @post.destroy respond_to do |format| # format.html { redirect_to(posts_url) } format.js { render :content_type => 'text/javascript' } end end Insert here effects as you please. In this example we are simply fading out the deleted post: #views/posts/destroy.js $("div#post-<%= params[:id] %>").fadeOut(); Altogether this works really smoothly!
{ "language": "en", "url": "https://stackoverflow.com/questions/7569081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C# windows forms textbox wordwrap not working I have a multiline textbox on my Windows Form. I am writing a very long string separated by '\r'. WHen I set wordwrap = true, it wraps off as expected. BUT when I set wordwrap to false it also wraps off but after a greater length. However, I don't want it to wrap at all. I have tried changing MaxLength to a huge number - but it makes no difference. A: Just to confirm (as it wasn't clear as the original commentator's name changed): Switching to a RichTextBox will fix word wrap on really long lines.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: org.xml.sax.SAXParseException: Content is not allowed in prolog Yes, I know that general forms of this question have been asked time and time again. However, I couldn't find anything that helped me solve my problem, so am posting this question which is specifically about my problem. I am trying to figure out why I am getting a SAXParseException (Content is not allowed in prolog.) as the OpenSAML library is trying to parse some XML. The most useful hints I found pointed toward an errant BOM at the beginning of the file, but there's nothing like that. I also wrote a quick-and-dirty C#.NET routine to read the whole file as an array of bytes, iterate over it and tell me if any of them were >=0x80 (it found none). The XML is marked as utf-8. I am hoping that someone can provide me with a bit of insight as to what might be going wrong. The initial portion of the XML file, as a hex dump, is (note the use of 0A as a newline; removing the line feed character entirely has no apparent effect): 000000000 3C 3F 78 6D 6C 20 76 65-72 73 69 6F 6E 3D 22 31 |<?xml version="1| 000000010 2E 30 22 20 65 6E 63 6F-64 69 6E 67 3D 22 55 54 |.0" encoding="UT| 000000020 46 2D 38 22 3F 3E 0A 3C-6D 64 3A 45 6E 74 69 74 |F-8"?>.<md:Entit| 000000030 79 44 65 73 63 72 69 70-74 6F 72 20 78 6D 6C 6E |yDescriptor xmln| 000000040 73 3A 6D 64 3D 22 75 72-6E 3A 6F 61 73 69 73 3A |s:md="urn:oasis:| 000000050 6E 61 6D 65 73 3A 74 63-3A 53 41 4D 4C 3A 32 2E |names:tc:SAML:2.| 000000060 30 3A 6D 65 74 61 64 61-74 61 22 20 |0:metadata" | The stack trace for the root cause exception is: org.xml.sax.SAXParseException: Content is not allowed in prolog. org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source) org.apache.xerces.util.ErrorHandlerWrapper.fatalError(Unknown Source) org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source) org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source) org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source) org.apache.xerces.impl.XMLScanner.reportFatalError(Unknown Source) org.apache.xerces.impl.XMLDocumentScannerImpl$PrologDispatcher.dispatch(Unknown Source) org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source) org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source) org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source) org.apache.xerces.parsers.XMLParser.parse(Unknown Source) org.apache.xerces.parsers.DOMParser.parse(Unknown Source) org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source) org.opensaml.xml.parse.BasicParserPool$DocumentBuilderProxy.parse(BasicParserPool.java:665) my.Unmarshaller.unmarshall(Unmarshaller.java:39) ... internal calls omitted for brevity ... javax.servlet.http.HttpServlet.service(HttpServlet.java:621) javax.servlet.http.HttpServlet.service(HttpServlet.java:722) The code that tries to do the unmarshalling is (type names fully qualified here; hopefully I am not leaving out something important): package my; public class Unmarshaller { protected static org.opensaml.xml.parse.ParserPool parserPool; static { org.opensaml.xml.parse.BasicParserPool _parserPool; _parserPool = new org.opensaml.xml.parse.BasicParserPool(); _parserPool.setNamespaceAware(true); Unmarshaller.parserPool = _parserPool; } public Unmarshaller() { try { org.opensaml.DefaultBootstrap.bootstrap(); } catch (org.opensaml.xml.ConfigurationException e) { throw new java.lang.RuntimeException (e); } } public Object unmarshall(String xml) throws org.opensaml.xml.io.UnmarshallingException { assert xml != null; assert !xml.isEmpty(); assert Unmarshaller.parserPool != null; org.w3c.dom.Document doc; try { doc = (parserPool.getBuilder()) .parse( // <<<====== line 39 in original source code is here new org.xml.sax.InputSource( new java.io.StringReader(xml) ) ); } catch (org.xml.sax.SAXException e) { throw new org.opensaml.xml.io.UnmarshallingException(e); } catch (java.io.IOException e) { throw new org.opensaml.xml.io.UnmarshallingException(e); } catch (org.opensaml.xml.parse.XMLParserException e) { throw new org.opensaml.xml.io.UnmarshallingException(e); } // ... remainder of function omitted for brevity ... } } A: I can't see anything wrong with the XML fragment in the file dump. And I believe you when you say that the XML file validates. However, you have not presented water-tight evidence that the XML that the parser sees is valid. For instance: * *You might be trying to parse a different file to the one that you have dumped. (These things have been known to happen ...). *Alternatively, there might be something wrong with the way that you are getting the XML into that String that you then parse. Try dumping the first few lines of the String that provides the parser source stream. A: There are cases where the SAMLReponses are Base64 encoded, the consumers (Controller or Servlets) need to decode in order to resolve the issue of "Content is not allowed in prolog" Below is the code snippet: // code snippet String responseMessage = httpServletRequest.getParameter("SAMLResponse"); byte[] decoded = Base64.decode(responseMessage); ByteArrayInputStream is = new ByteArrayInputStream(decoded); // write your xml parsing logic here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Removing block from returned html in C# I am returning html contents (page layout) in a variable but want to remove <script>blabla</script> tags and contents within these tags. How can I do this? A: You really need to parse the HTML. Try using the Html Agility Pack which should make this pretty straightforward, for example: HtmlDocument doc = new HtmlDocument(); doc.Load("HTMLPage1.htm"); foreach (var node in doc.DocumentNode.SelectNodes("//script")) { node.Remove(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7569095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: why do I see different filters in GraphEdit & GraphStudio I am using both GraphEdit & GraphStudio to process videos. However, there are some filters which are visible via GraphEdit only and vice versa. For example: ffdshow is available in GraphStudio but not in GraphEdit, MainConcept filters are visible inGrpahEdit but not in GraphStudio. Has anyone come across this problem before? Aliza A: There might be a few reasons for this, most obvious is if you are confusing Win32 and x64 versions of the applications. Provided that there is no confusion, note that some filters are blacklisting themselves to be not available in specific applications/processes. For example, MainConcept might want to enable their filters for GraphEdit as a demo mode for developers, so that they could make sure the filters are good and pay for commercial version where filters are also available for applications. In general, when there is no special intention to selectively disable filters for specific applications, fitlers are equally available to all applications using DirectShow API.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Resize Image PNG With transparence I want to resize an image PNG with transparence plz help. Here is the code : function resize($width,$height) { $new_image = imagecreatetruecolor($width, $height); imagealphablending($new_image, false); imagesavealpha($new_image,true); $transparent = imagecolorallocatealpha($new_image, 255, 255, 255, 127); imagefilledrectangle($new_image, 0, 0, $width, $height, $transparent); imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight()); $this->image = $new_image; } A: Try this UPDATED function createThumb($upfile, $dstfile, $max_width, $max_height){ $size = getimagesize($upfile); $width = $size[0]; $height = $size[1]; $x_ratio = $max_width / $width; $y_ratio = $max_height / $height; if( ($width <= $max_width) && ($height <= $max_height)) { $tn_width = $width; $tn_height = $height; } elseif (($x_ratio * $height) < $max_height) { $tn_height = ceil($x_ratio * $height); $tn_width = $max_width; } else { $tn_width = ceil($y_ratio * $width); $tn_height = $max_height; } if($size['mime'] == "image/jpeg"){ $src = ImageCreateFromJpeg($upfile); $dst = ImageCreateTrueColor($tn_width, $tn_height); imagecopyresampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height,$width, $height); imageinterlace( $dst, true); ImageJpeg($dst, $dstfile, 100); } else if ($size['mime'] == "image/png"){ $src = ImageCreateFrompng($upfile); // integer representation of the color black (rgb: 0,0,0) $background = imagecolorallocate($src, 0, 0, 0); // removing the black from the placeholder imagecolortransparent($src, $background); // turning off alpha blending (to ensure alpha channel information // is preserved, rather than removed (blending with the rest of the // image in the form of black)) imagealphablending($src, false); // turning on alpha channel information saving (to ensure the full range // of transparency is preserved) imagesavealpha($src, true); $dst = ImageCreateTrueColor($tn_width, $tn_height); imagecopyresampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height,$width, $height); Imagepng($dst, $dstfile); } else { $src = ImageCreateFromGif($upfile); $dst = ImageCreateTrueColor($tn_width, $tn_height); imagecopyresampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height,$width, $height); imagegif($dst, $dstfile); } } A: There a simple to use, open source library called PHP Image Magician. It uses GD and supports transparency Example of basis usage: $magicianObj = new imageLib('racecar.png'); $magicianObj -> resizeImage(100, 200, 'crop'); $magicianObj -> saveImage('racecar_small.png');
{ "language": "en", "url": "https://stackoverflow.com/questions/7569100", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: windows form validation issues (.net2.0 ) I need help with some things regarding windows form validation: * *closing form using standard form closing button (X) triggers validation of all controls. Is there a way to supress it when closing form using this button, and force it only when pressing my own button? *validation of textbox (possibly other controls, I tested only textboxes) wont invoke when i change text (value) programatically. I need to type text directly into textbox if I want validation to be triggered later, before form is closed. How to tell the form that some control needs validation (but not to trigger it immedidately)? Thanks. EDIT: (1) solved, using this answer. (2) now, after i set AutoValidate property to false and added ValidateChildren() to my button, only 1 control is being validated with its current value, values of all other controls are revert to value binded to them from DataSource object . I checked it in Validating event - only first control validating keeps its current value, after this validation is finished, other controls' values are replaced with values from DataSource object. I don't understand why. Any clues? A: Try this, maybe it could help you. ( for 1) In the Forms Load event you can put this.ControlBox = false;. This will hide your X button with the other buttons at the top. The Form has a Form1_FormClosing event. In that Event you could call the triggers you need. Put a button on the form, and in button_Click event you type this.Close().
{ "language": "en", "url": "https://stackoverflow.com/questions/7569102", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Casting to Collection With this: public class Widget : IWidget {} Why does collection2 == null here: var collection1 = collectionView.SourceCollection as ObservableCollection<Widget>; var collection2 = collectionView.SourceCollection as ObservableCollection<IWidget>; Where SourceCollection is ObservableCollection<Widget> A: if the collection is declared as ObservableCollection<Widget> it cannot be cast to ObservableCollection<IWidget>. I believe this is possible in .NET 4 but not 3.5 or less - CORRECTION - refer Adam's comment below. For the above to work you must declare the list as ObservableCollection<IWidget> then both casts will work. You should always use the interface type where possible anyway. As an aside when you use the 'as' keyword this is called safe casting. It will return null if the cast is not possible. Explicit casting ... ie (ObservableCollection<IWidget>) collectionView.SourceCollection will throw an exception if the cast is not possible.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: build_association working? I have two models with a one-to-one association. class User < ActiveRecord::Base has_one :setting end class Setting < ActiveRecord::Base belongs_to :user end Each model has plenty of fields and user is used quite extensively by a non rails external server, which is why I have separated the tables. I am trying to use the build_association but all I get is undefined method `build_setting' for nil:NilClass. I want to do this because I want a single form with fields from both models to setup a new user. In my user controllers new method I try this: def new @user = User.new @setting = @user.setting.build_setting respond_to do |format| format.html # new.html.erb format.xml { render :xml => @user } end end Which throws: NoMethodError in UsersController#new undefined method `build_setting' for nil:NilClass Why? According to the api docs this is the way to do it. Doing this seems to work, but its not the right way (or is it?): def new @user = User.new @setting = Setting.new @user.setting=@setting respond_to do |format| format.html # new.html.erb format.xml { render :xml => @user } end end A: You need to use: @setting = @user.build_setting This is after an edit, so if you like this answer, accept Mahesh's below. A: In your users model add class User < ActiveRecord::Base has_one :setting validates_associated :setting end and then use @setting = @user.build_setting
{ "language": "en", "url": "https://stackoverflow.com/questions/7569107", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Deploy war on tomcat to another folder name I'd like know is there a way to deploy war copied to webapps folder with another name, of course automatically, and with minimal configuration some xml files. Example: I have a.war and want AServer folder and service but don't "a" folder and service Thanks Pavel EDIT 29.9.11 (7:30): I have something like this for copying in server.xml <Context docBase="a" path="/AServer" reloadable="true" source="org.eclipse.jst.jee.server:a" /> it's be good if exist some parameters thats delete a folder or some other xml thats disable starting "a" server EDIT 29.9.11 (14:53) I found some way. Added deployIgnore="a.war, a" parameters to server.xml - Host and Context is almost same and almost working (doesn't read a context in conf/Catalina/localhost), but still a folder exist to and probably this is not a good way. <Context docBase="a" path="/AServer" reloadable="true" /> Have someone better way? A: Unzip the a.war file, move it to AServer, and remove the a.war file and folder. There are ant takss for unzipping, moving and deleting that can automate this. A: From Tomcat's The Context Container documentation: path ... This attribute must only be used when statically defining a Context in server.xml. In all other circumstances, the path will be inferred from the filenames used for either the .xml context file or the docBase. One solution is renaming the war file. Another is unzipping it to the AServer folder as @mooreds suggested.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Strange popup behaviour When I click on the link 'alert' then the message will only popup once, which is correct. Strangely if I click on the link 'dialog' and then on the link 'alert' then the message is popping up twice consecutively, which is incorrect. How can I fix this so that the message will only be displayed once? HTML <p id="test"><a href="#">alert</a></p> <a href="#" onclick="showDialog()">dialog</a> jQuery $(function() { $("p#test a").click(function() { alert('alert'); }); } function showDialog(){ $("<div class='popupDialog'>Loading...</div>").dialog({ closeOnEscape: true, height: 'auto', modal: true, title: 'About Ricky', width: 'auto' }).bind('dialogclose', function() { jdialog.dialog('destroy'); } A: You can try this script. <script type="text/javascript"> $(document).ready(function () { $("p#test a").click(function () { alert('alert'); }); }); function showDialog1() { $("<div class='popupDialog'>Loading...</div>").dialog()({ closeOnEscape: true, height: 'auto', modal: true, title: 'About Ricky', width: 'auto' }).bind('dialogclose', function () { $(this).dialog('destroy'); }); } <script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7569109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: I want to retrieve the sub form values I have a SplitContainer, and in its right panel I have a Form. I want to retrieve the values of the TextBoxes of the form when I click on a button outside the Form, but inside the panel. How to do it? A: May be you are having a UserControl in the Right panel of the SplitContainer. In you that userControl class write a public method to get values. public string GetValueOfTheTextBox() { return textBox.Text; } Add the userControl the SplitContainer. MyUserControl myUserControl = new MyUserControl(); //Add this to the splitContainer right panel. From out side of the MyUserControl class you can call GetValueOfTheTextBox method. string text = myUserControl.GetValueOfTheTextBox(); A: You need to reference the other form. Let's say you have Form1 and Form2. Form2 has all of the text boxes on it. Form1.cs - Button1_Click(): // Create an instance of Form2 (the form containing the textBox controls). Form2 frm2 = new Form2(); // Make a call to the public property which will return the textBox's text. textBox1.Text = frm2.TextBox1; Form2.cs: 1.Make a textBox control and name it 'textBox1'. 2.Create a public property that will return an reference of textBox1. public string TextBox1 { get { return textBox1.Text; } } So, what exactly are we doing here? * *From Form1.cs we are making a call to the Public property 'TextBox1' in Form2.cs. *The Public property TextBox1 in Form2.cs returns the text from the Form2.textBox1 control - which is the control you want the text of. A: If Form2 is the form / user control inside the panel, create public properties to "get" the value of each textbox, and then refer to those properties in the parent form (Form1). For instance, if Form2 has textboxes for first name and last name, create properties to get their value: public string FirstName { get { return txtFirstName.Text; } } public string LastName { get { return txtLastName.Text; } } Then in Form1, assuming form2 is the instance of Form2 that you inserted into the panel, you can refer to those properties like this: string firstName = form2.FirstName; string lastName = form2.LastName;
{ "language": "en", "url": "https://stackoverflow.com/questions/7569111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Storing a Dictionary in isolated storage I'm hitting a server and getting some data, am parsing this data and storing it in a Dictionary<TKey, TValue>. I store this Dictionary<TKey, TValue> list in Isolated storage. Now, the problem is whenever am trying retrieve the Dictionary<TKey, TValue> (in 2nd run) what ever I have stored in the 1st run, the values for each key in the bean would have become null. I dunno whether the way am storing the Dictionary<TKey, TValue> is wrong. Code sample: CacheManager.getInstance().PersistData(CacheManager.SERVICE_TABLE, dictionaryList); public void PersistData(string storageName, object dict) { try { PersistDataStore.Add(storageName, dict); PersistDataStore.Save(); } catch (Exception ex) { } } A: I got the solution to the problem, the members of the dictionary dict must be serialized. i.e., using System.Runtime.Serialization; [DataContact] public class classname() { [datamember] public int propertyname; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7569112", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Can't start activity from class I am trying to start an activity from a normal class and I can't figure out how it is done, if it can be done. On an itemClick I want to start an activity that extends the ListView class to show a list of options. Also the class that receives the onItemClick is not an activity. I will post the code to try to visualize what i mean. This is my onClick method in the class that wants to start a an activity. public void onClick(View v) { if (v.equals(this)) { notifyObservers(this.getId()); } else if(v.equals(editButton) || v.equals(deleteButton)) { This is where I want to start the activity to show my ListView... } } This is my class that extends the ListView class. public class ProfileSettings extends ListActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String[] mainSettings = getResources().getStringArray(R.array.mainSettings); setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, mainSettings)); ListView lv = getListView(); lv.setTextFilterEnabled(true); lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Do something } }); } } Thanks in advance! A: I think this may help you: "Pass the context of the activity via constructor to your class or make a static context in your activity. With the context you can start activities like you would start them within the activity class." class First extends Activity { ... Second test = new Second(this); test.start(); ... } class Second { private Context mContext; ... public Second(Context c) { this.mContext = c; } ... public start() { mContext.startActivity(...); } } for more detail check http://www.anddev.org/view-layout-resource-problems-f27/starting-an-activity-from-a-non-activity-class-t14483.html A: Try this in your onClick Intent i = new Intent(this, ProfileSettings.class); startActivity(i); EDIT: Also dont forget to add the activity to your manifest.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569114", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there an MbUnit equivalent in Java? Specifically, I am looking for the same ease of defining parameterized and combinatorial unit tests. Thanks. P.S. Please, do not suggest JUnit. Its parameterized and theory features do not even reach the ancles of the respective features in MbUnit. EDIT Here is a very short description of the features of MbUnit that I would like to have in java: * *FactoryAttribute - allows to get parameters from a method or property at run-time. *RowAttribute - allows to get compile time parameters to all of the parameters of the test. *ColumnAttribute - allows to get compile time parameters to a specific parameter. Mixing and matching the Factory and Column attributes allows to create combinatorial tests easily. The Factory attribute can be attached to the test method itself or to the indvidual parameters. In addition, the test method can be generic and the output produced by the Factory method can be fed into that parameter as well, making it possible to use different generic type argument for different test iterations.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: access divs of same class name using javascript I have the following html code- <div class="search_results">...</div> <div class="search_results">...</div> <div class="search_results">...</div> The divs are automatically generated by a javasciprt function. Is there a way to access only the first div/or a specific div of the same class name "search_results" with javascript? A: You can use getElementsByClassName which returns a NodeList (which is an array-like object). You can then access individual elements of that using normal array syntax. This example will return the first element: var firstDiv = document.getElementsByClassName("search_results")[0]; Or, you could use querySelector, which returns the first element found: var firstDiv = document.querySelector(".search_results"); If you want to return all matched elements, you can use querySelectorAll, which returns a NodeList, like getElementsByClassName. A: Use getElementsByClassName or querySelector (if available): function findElementsByTagNameAndClassName(tag, class_name) { if(typeof document.querySelector !== 'undefined') { return document.querySelector(tag + ' .' + class_name); } var els = document.getElementsByClassName(class_name); var result = []; for(var i = 0; i < els.length; ++i) { if(els[i].nodeName === tag) { result.push(els[i]); } } return result; } var firstDiv = findElementsByTagNameAndClassName('div', 'search_results')[0]; A: If you use JQuery $(".search_results").first(). Else you need to use document.getElementsByClassName("search_results")[0]; A: If you're using JQuery: $("div.search_results").first() for later versions of JQuery and $("div.search_results")[0] for older ones. No Jquery: document.getElementsByClassName A: If you want to access a specific instance, you will want to add an id attribute to the elements, for example: <div class="search_results" id="result_1">...</div> <div class="search_results" id="result_2">...</div> <div class="search_results" id="result_3">...</div> If that's not an option, you can access the n'th item with the classname (starting from 0) using var divN = document.getElementsByClassName("search_results")[n];
{ "language": "en", "url": "https://stackoverflow.com/questions/7569118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to properly implement multiple subview operations in IPAD I am creating an iPAD app. I have got a MAIN VIEW controller which covers the whole screen. And I have another class DROP-DOWN Class which i will be using to mimic the functionality of a drop-down as in Windows OS components. For that I am using a simple button, a scroll view and a few labels. I instantiate an object of that class and use it in my MAIN VIEW controller. To create the effect of a drop down, I alter the instance's views frame on the touch up of the button in toggle mode.(Click once, frame increased, click again frame decreased). The creation part was fine, and the function to toggle to worked fine when implemented on a single instance of the DROP DOWN object. But the problem comes when I instantiate these objects thru a for loop. The views seem to just vanish on button click. Here is the code within the dropdowns. - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor redColor]; UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(10,54,100,50)]; scrollView.contentSize = CGSizeMake(50, 100); for (int i = 0; i< 10; i++) { UILabel *newLable = [[UILabel alloc]initWithFrame:CGRectMake(0, 10*i, 100, 10)]; [newLable setFont:[UIFont boldSystemFontOfSize:10]]; newLable.text = [NSString stringWithFormat:@"Testing %i",i]; [scrollView addSubview:newLable]; } scrollView.backgroundColor = [UIColor greenColor]; [self.view addSubview:scrollView]; } -(IBAction)btnClicked:(id)sender { if (!isOpen) { oldRect = self.view.frame; CGRect newFrame = self.view.frame; newFrame.size = CGSizeMake(190, 200); NSLog(@"New Frame - %f,%f,%f,%f",self.view.frame.origin.x,self.view.frame.origin.y,self.view.frame.size.height,self.view.frame.size.width); self.view.frame = newFrame; } else { self.view.frame = oldRect; NSLog(@"Old Frame - %f,%f,%f,%f",self.view.frame.origin.x,self.view.frame.origin.y,self.view.frame.size.height,self.view.frame.size.width); } isOpen = !isOpen; } And here is how this is called from the main view. - (void)viewDidLoad { [super viewDidLoad]; [self performSelector:@selector(drawTheFilters)]; } -(void)drawTheFilters { for (int i = 0; i<5 ; i++) { DropDownView *dropView = [[DropDownView alloc]initWithNibName:@"DropDownView" bundle:[NSBundle mainBundle]]; CGRect newFrame = dropView.view.frame; newFrame.origin = CGPointMake(200*i, 200); dropView.view.frame = newFrame; [self.view addSubview:dropView.view]; NSLog(@"Frame %i, %f,%f,%f,%f",i,dropView.view.frame.origin.x,dropView.view.frame.origin.y,dropView.view.frame.size.height,dropView.view.frame.size.width); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7569121", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to integrate skype feature in my native app I want to integrate Skype APIs in my native app. Is that possible? I have Googled around and couldn't find a way to start. I know there are APIs available for Mac OS X. Can I make use of those APIs for my iPhone app? I know it is possible, as many apps like Nimbuzz have integrated Skype APIs in their iPhone apps. A: Skype has a Public API which you can reference. This page has a wealth of information on how to use the API and the various commands. There is no public framework which abstracts it any further so you'll need to investigate how to make the actual commands by deconstructing the various wrappers. I don't think Skype wants to particularly bring their API wrappers to the iPhone because you'd be competing directly with their own application. They do provide Cocoa wrappers but those are in the form of a framework and you can't have your own custom frameworks in an iPhone Application (only Apple approved ones). Also relevant: Skype bans Nimbuzz and fring while faking stats A: SkypeKit sounds like what you want. A: SkypeKit prohibits development on iOS devices. What may be of use to you is the URI scheme, This should let you open the skype App on your iPhone and place a call. For additional help visit the Skype Developer Forum
{ "language": "en", "url": "https://stackoverflow.com/questions/7569125", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Redirect a domain invisibly I have a customer who wants his domain to be redirected to some other site. For example: www.hisdomaine.com => www.him.somewysiwyghost.com the redirection should be transparent so www.hisdomain.com/somefolder should translate to www.him.somesysiwyghost.com/somefolder important to him is, www.him.somewysiwyghost.com should never be visible to the user. the user should see www.hisdomain.com. because of this frames aren't an option. also frames are not the best options for SEO. I tried using mod_rewrite for this, using this rule: RewriteRule (.*) http://www.him.somewysiwyghost.com/$1 [L] It works fine, except the URI translates to www.him.somewysiwyghost.com so the user could see it. How could I translate invisibly? A: You should use mod_proxy as such in a vhost: <VirtualHost *:80> ServerName hisdomaine.com ServerAlias www.hisdomaine.com ProxyPass / http://www.him.somesysiwyghost.com ProxyPassReverse / http://www.him.somesysiwyghost.com ProxyPreserveHost On <Location /> Order allow,deny Allow from all </Location> </VirtualHost> A: In that case I think you have to transfer the domain on the other server and park it. I don't think that you can do something like that via .htaccess. Another solution, but not so good is to use a full screen iFrame to display the other site.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Django template for loop. Member before I want to create such loop: {% for object in objects %} {% if object.before != object %} {{ object }} this is different {% else %} {{ object }} this is the same {% endfor %} Based on https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#for I can't. Is there really no simple way to do this? Or I just need to use counter and check for objects[counter-1]? P.S. .before is theoretical and objects is simple query list. I want to take and do something with the loop member that encountered before current loop member. A: Check ifchanged template tag A: There is a "simple way" to do this: write a custom template tag. They're really not hard. This would probably do the trick (untested): @register.simple_tag def compare_objects(object_list): comparisons = [] for i in range(1, len(object_list)): if object_list[i] > object_list[i-1]: comparisons.append('bigger') else: comparisons.append('smaller') return comparisons A: The built-in template tags and filters don't make it easy (as of Django 1.4), but it is possible by using the with tag to cache variables and the add, slugify, and slice filters to generate a new list with only one member. The following example creates a new list whose sole member is the previous member of the forloop: {% for item in list %} {% if not forloop.first %} {% with forloop.counter0|add:"-1" as previous %} {% with previous|slugify|add:":"|add:previous as subset %} {% with list|slice:subset as sublist %} <p>Current item: {{ item }}</p> <p>Previous item: {{ sublist.0 }}</p> {% endwith %} {% endwith %} {% endwith %} {% endif %} {% endfor %} This isn't an elegant solution, but the django template system has two faults that make this hack unavoidable for those who don't what to write custom tags: * *Django template syntax does not allow nested curly parenthesis. Otherwise, we could do this: {{ list.{{ forloop.counter|add:-1 }} }} *The lookup operator does not accept values stored using with (and perhaps for good reason) {% with forloop.counter|add:-1 as index %} {{ list.index }} {% endwith %} A: This code should work just fine as a django template, as long as object has a property or no-argument method called before, and objects is iterable (and '<' is defined). {% for object in objects %} {% if object.before < object %} this is bigger {% else %} this is smaller {% endfor %}
{ "language": "en", "url": "https://stackoverflow.com/questions/7569133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What's the fastest way to check that entry exists in database? I'm looking for the fastest way to check that entry exists... All my life, I did with something like this... SELECT COUNT(`id`) FROM `table_name` Some people don't use COUNT(id), but COUNT(*). Is that faster? What about LIMIT 1? P.S. With id I meant primary key, of course. Thanks in an advice! A: In most situations, COUNT(*) is faster than COUNT(id) in MySQL (because of how grouping queries with COUNT() are executed, it may be optimized in future releases so both versions run the same). But if you only want to find if at least one row exists, you can use EXISTS simple: ( SELECT COUNT(id) FROM table_name ) > 0 a bit faster: ( SELECT COUNT(*) FROM table_name ) > 0 much faster: EXISTS (SELECT * FROM table_name) A: If you aren't worried about accuracy, explain select count(field) from table is incredibly fast. http://www.mysqlperformanceblog.com/2007/04/10/count-vs-countcol/ This link explains the difference between count(*) and count(field). When in doubt, count(*) As for checking that a table is not empty... SELECT EXISTS(SELECT 1 FROM table)
{ "language": "en", "url": "https://stackoverflow.com/questions/7569137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: sending data to xml api of webservice Im trying to write a python script that basically interacts with a webservice that uses an xml api. The request method is POST. Usually I would write a request of the form request(url, data, headers) - however, in the case of an xml api it would not work. Also something like data.encode('utf-8') or urllib.urlencode(data) would not work as the data is not a dict. In this case, data is xml so how am i supposed to sent it over? [EDIT] When I send a string of XML I get a urllib2.HTTPError: HTTP Error 415: Unsupported Media Type Exception. Is there any other way I'm supposed to send the data? Also, the API I am using the Google Contacts API. I'm trying to write a script that adds a contact to my gmail account. A: You probably need to set proper Content-Type header, for XML it would probably be: application/xml So something like this should get you going: request = urllib2.Request( 'xml_api.example.com' ) request.add_header('Content-Type', 'application/xml') response = urllib2.urlopen(request, xml_data_string) Hope that helps :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7569138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jQuery validation has stopped working Here's the form that was formerly working. I just went back to it today and for some weird reason, it stopped validating. Would appreciate if anyone could take a look. Thank you. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <title>Simple Form Validation</title> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#form1").validate({ rules: { name: "required",// simple rule, converted to {required:true} email: {// compound rule required: true, email: true }, url: { url: true }, comment: { required: true } }, messages: { comment: "Please enter a comment.", name: " * Required.", email: "* Required" } }); }); </script> <style type="text/css"> * { font-family: Verdana; font-size: 11px; line-height: 14px; } .submit { margin-left: 125px; margin-top: 10px;} .label { display: block; float: left; width: 120px; text-align: right; margin-right: 5px; } .form-row { padding: 5px 0; clear: both; width: 700px; } label.error { width: 250px; display: block; float: left; color: red; padding-left: 10px; } input[type=text], textarea { width: 250px; float: left; } textarea { height: 50px; } </style> </head> <body> <form id="form1" method="post" action=""> <div class="form-row"><span class="label">Name *</span><input type="text" name="name" /></div> <div class="form-row"><span class="label">E-Mail *</span><input type="text" name="email" /></div> <div class="form-row"><span class="label">URL</span><input type="text" name="url" /></div> <div class="form-row"><span class="label">Your comment *</span><textarea name="comment" ></textarea></div> <div class="form-row"><input class="submit" type="submit" value="Submit"></div> </form> </body> </html> A: It looks like it works to me. http://jsfiddle.net/fYgXD/
{ "language": "en", "url": "https://stackoverflow.com/questions/7569139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Which thread class except System.Threading in C# i can use in windows phone development? Is there another c# class for threads, which works faster ? A: Based on your comment, you are using the Thread class in the System.Threading namespace. Based on that, none of the classes are going to make the code that executes on the thread any faster; the best you can do is optimize the performance of the mechanism that you use for your situation. That said, there are some things to be aware of: * *The Thread class probably has the most overhead; every time you create one, it creates a new managed thread, which might create a new OS thread. This is not an inconsequential operation. *Using the ThreadPool class to schedule operations can be faster in terms of starting your operation, as it keeps a cache of threads already created so you don't have to pay that penalty. The trade-off here is that a) many classes in the .NET framework use the ThreadPool to schedule tasks, and your task will be placed in a queue; there's no way to force it to execute immediately when placed in the ThreadPool. *The Task and Task<TResult> classes in the System.Threading.Tasks namespace run on top of the ThreadPool (this can be configured otherwise, to run with new Thread instances every time, for example), so you gain those benefits, but at the same time, there is overhead for cancellation, continuation, etc, etc. You gain ease-of-use here (much in my opinion), with minimal overhead. In the end, you will have to measure what is best for your application and apply that solution; like most, there is no one-size-fits-all solution. A: For most circumstances using your own instances of the Thread class is going to be slower than using work items in the ThreadPool. It would take some extraordinary circumstances for you to find an advantage using the Thread class directly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: “Index was outside the bounds of the array” when run outside of the IDE I've just started learning C# and had created this simple configuration file generator for a Minecraft launcher, just as something to do. I'm having trouble when trying to run the application independently from Visual C# 2010 - it spits out "Index and length must refer to a location within the string. Parameter name:length" on first run (when the blank text file is created) and "index was outside the bounds of the array" if I start it again after this. I'm confused as to why this is happening - it isn't giving me any line numbers, and it only happens when I don't run the application through the IDE (whether I run a debug build or release build). Any help is much appreciated. I apologise for my possibly horrible coding - I'm a beginner with this language. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Minecraft_Launcher_Config { public partial class mcwindow : Form { private void outputText(string outtext) { output.Text = outtext; } private string encrypt(string text, int key) { string newText = ""; for (int i = 0; i < text.Length; i++) { int charValue = Convert.ToInt32(text[i]); charValue ^= key; newText += char.ConvertFromUtf32(charValue); } return newText; } public mcwindow() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { string iuser = ""; string ipass = ""; string imem = "1024"; string iserver = ""; if (System.IO.File.Exists("config.cfg")) { System.IO.StreamReader configFile = new System.IO.StreamReader("config.cfg"); string[] iconfig = System.IO.File.ReadAllLines("config.cfg"); iuser = iconfig[0]; ipass = iconfig[1]; imem = iconfig[2]; iserver = iconfig[3]; configFile.Close(); outputText("Successfully loaded and decrypted config!"); } else { System.IO.StreamWriter configwrite = new System.IO.StreamWriter("config.cfg"); configwrite.Close(); outputText("Welcome to Frohman's Minecraft Launcher Config!"); } username.Text = iuser; memselect.Value = int.Parse(imem); int OKey = Convert.ToInt32(username.Text.Substring(0, 1)); string unenpassword = encrypt(ipass, OKey); password.Text = unenpassword; } private void label1_Click(object sender, EventArgs e) { } private void label4_Click(object sender, EventArgs e) { } private void saveexit_Click(object sender, EventArgs e) { if (username.Text != "" & password.Text != "") { outputText("Saving and exiting!"); int IKey = Convert.ToInt32(username.Text[0]); string enpassword = encrypt(password.Text, IKey); string outString = username.Text + System.Environment.NewLine + enpassword + System.Environment.NewLine + memselect.Value + System.Environment.NewLine + serverip.Text; System.IO.StreamWriter configwrite = new System.IO.StreamWriter("config.cfg"); configwrite.WriteLine(outString); configwrite.Close(); System.Threading.Thread.Sleep(150); Environment.Exit(0); } else { outputText("You're missing some data!"); } } private void password_TextChanged(object sender, EventArgs e) { } } } A: This code: string[] iconfig = System.IO.File.ReadAllLines("config.cfg"); iuser = iconfig[0]; ipass = iconfig[1]; imem = iconfig[2]; iserver = iconfig[3]; ... will throw the exception you've talked about if the file contains fewer than 4 lines. Is that what's happening, perhaps? (You do talk about it creating a blank file.) Note that you're also opening the file with a StreamReader but for no purpose, given that you're also just calling ReadAllLines which will open it separately. When you write out the file with this code: System.IO.StreamWriter configwrite = new System.IO.StreamWriter("config.cfg"); configwrite.WriteLine(outString); configwrite.Close(); that's only writing out a single line, assuming outString doesn't contain any linebreaks... so I'm not sure how this could ever work, even in the IDE.) (Note that if you do want to use StreamReader and StreamWriter, you should use using statements so that the file handle gets closed even if there are exceptions. You don't need to use StreamReader or StreamWriter here though - you could use File.WriteAllLines or File.WriteAllText.) Finally, encryption should not be done over text. You will usually end up with garbled text which could easily contain invalid code units etc. Generally if you want to encrypt text, you convert it to binary, apply a standard encryption algorithm (don't write your own) and then if you want text out of it, you convert it to base64 with Convert.ToBase64String. A: First of All dont Use StreamReader if you already used File.ReadAllLines it might close the File and make it Impossible for method File.readAllLines. Try to load the Config File with the Full Path like string[] iconfig = System.IO.File.ReadAllLines(@"MyPath\config.cfg"); Than to be Sure test if(iconfig.length >= 4) //Proceed With Config And last if you wish to use Configuration than use Application.Setting A: String.SubString will throw an ArgumentOutOfRangeException if startIndex plus length indicates a position not within this instance. During your first run you call this code: iuser=""; ... username.Text = iuser; memselect.Value = int.Parse(imem); int OKey = Convert.ToInt32(username.Text.Substring(0, 1)); username.Text.Substring(0, 1) is outside of the bounds of the array when you have an empty string.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569141", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Office Template - Embedded VB Script Inactive/Unspported? First off, this might be the simplest questions on this site depending on the answer. Question: Is Embedded VB scripts supported in Office Word templates (.dot/.dotx)? If not, thank you! If it is, why is this not working: http://postimage.org/image/2uubobv38/ It works flawlessly in a .doc format but not when i try to save it as a template. I'm running Office 2007 but 2003 doesn't work either, is there something special you need to enable for using embedded scripts in a .dot file? I don't know if this is the proper forum for questions like this, but i really don't know anywhere else to turn regarding programming in general so.. help? A: Ok so after some logical debugging (read: days), i found out that it IS supported, just not in the "traditional" way of thinking. In a normal document, you apparently use the Open() function to load things when opening the document, because that's what you do, you open the document. When using embedded scripts in a .dot file, you're not opening the file.. you are creating a new instance of the .dot file so the function you should be using is New(): Private Sub Document_New() UserForm1.Show End Sub This should show you form from "opening" a .dot file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Nested tool-bar button in xul I am having a toolbar-button with type "menu-button". Can I have two toolbar-buttons inside this one? A: Since you would like to have a button inside a menu-button, here you go. But, this is not a pretty good UI. <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <window id="main-window"> <toolbox id="navigator-toolbox"> <toolbar id="xulschoolhello-toolbar" toolbarname="xulschoolhello.toolbarName.label;" customizable="true" mode="icons" context="toolbar-context-menu" defaultset="xulschoolhello-hello-world-button" insertbefore="PersonalToolbar" /> <hbox> <row> <button flex="1" type="menu" label="Menu"> <menupopup> <menuitem label="Option 1" oncommand="setText('menu-text','Option 1');" /> <menuitem label="Option 2" oncommand="setText('menu-text','Option 2');" /> <menuitem label="Option 3" oncommand="setText('menu-text','Option 3');" /> <menuitem label="Option 4" oncommand="setText('menu-text','Option 4');" /> </menupopup> </button> </row> <row> <button flex="1" type="menu-button" label="MenuButton" oncommand="alert('Button was pressed!');"> <menupopup> <menuitem label="Option A" oncommand="setText('menu-text','Option A');" /> <menuitem label="Option B" oncommand="setText('menu-text','Option B');" /> <menuitem label="Option C" oncommand="setText('menu-text','Option C');" /> <menuitem label="Option D" oncommand="setText('menu-text','Option D');" /> </menupopup> </button></row> </hbox> <hbox pack="center"> <description id="menu-text" value="Testing" /> </hbox> </toolbox> </window> </window>
{ "language": "en", "url": "https://stackoverflow.com/questions/7569151", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Why do we have multiple declarations for main in C? C does not support function overloading. How can we then have 3 prototypes for main? What is the historical reason for having 3 prototypes? A: There are only two prototypes for main that a standard-conforming C implementation is required to recognize: int main(void) and int main(int, char *[]). This is not overloading, since there can still only be one main per program; having a void foo(int, double) in one program and a char *foo(FILE *) in another isn't overloading either. The reason for the two prototypes is convenience: some applications want command-line arguments, while others don't bother with them. All other prototypes, such as void main(void) and int main(int, char *[], char *[]), are compiler/platform-dependent extensions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569154", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Dont allow password field to copy I have this field: <form:label path="password"><spring:message code="label.password"/></form:label> <form:password path="password" id="password"/> Now what can I do to make sure this password field value cannot be copied? A: In (almost) all conformant browsers, inputs that are type="password" should not have any copy functionality. See: http://jsfiddle.net/6BUGx/ A: Just put, <input type="password" value="" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7569155", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WordPress and jQuery UI I like to know if there is already installed in WordPress the jQuery UI for the administration panel. If not then I have to load it. If is loaded how can I use it ? A: You can include jquery by including the following in header.php <?php wp_enqueue_script("jquery"); wp_enqueue_script('jquery-ui-core'); php wp_head(); ?> Source
{ "language": "en", "url": "https://stackoverflow.com/questions/7569165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get View object on which animation was started......? I have 3 image view in which i started same animation (translate) I have animation listener, in onAnimationEnd(Animation animation) method, I want to know on which image view the animation is ended..? From animation object how can I know in which it was started..? Thanks in advance..! A: Well you can not know what is the object on which the animation ended. The whole purpose of the AnimationListener is to listen to the Animation and not to the object. Solution 1- Create your own Animation class and save in it a reference to the object which is animating. This will allow you to cast the Animation to YourAnimation in the function onAnimationEnd and get the reference. 2- A simpler solution is to create your own AnimationListener that holds a reference of the Object that is animated. For example: public class MyAnimationListener implements AnimationListener { ImageView view; public void setImage(ImageView view) { this.view = view; } public void onAnimationEnd(Animation animation) { // Do whatever you want } public void onAnimationRepeat(Animation animation) { } public void onAnimationStart(Animation animation) { } } So when you want to animate your ImageView: You do the following: MyAnimationListener listener = new MyAnimationListener(); listener.setImage(myImage); myAnimation.setAnimationListener(listener);
{ "language": "en", "url": "https://stackoverflow.com/questions/7569166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: State of XML support in Scala 2.9.x I'm currently starting to look into using Scala's XML support for business critical processes. In that regard I would like to know what the current state of the standard XML library in Scala is. I have read some "old" articles relating to Scala 2.7 and the 2.8 trunk, where it was stated that the XML handling would be threadsafe for scala 2.8, and that there was several bugs in version 2.7.x. Some critique has also been giving on the XML class hierachy, but I guess that's a matter of taste. So I would like if somebody could answer the question, what is the current state of the Scala XML library for version 2.9.x? Thanks in advance. A: Scala XML is stable, supported and won’t go away for a very long time. Nonetheless, there are some design criticisms made and a few people sat down and decided to write a better alternative from scratch, Anti-XML. If everything works out, you will have an additional choice in the future. A: Scales Xml is my answer to that question. Its not that I had found the quirks of Scala XML to be bad, but the approach itself didn't sit with me well and prompted the question "what if you separated the content from the tree and unified push and pull". After much playing I discovered many cool ways to leverage the type system in order to make XML usage simpler for a number of activities, more correct and faster than Scala XML. You very quickly realise, when writing an alternative library, just how much thought and effort went into Scala XML. Its killer features are: * *Provided with the default library *In built XML syntax for simple out of the box usage its hard to beat (although I'm confident I've done that ^_^). Its important that other younger alternatives like Anti-XML have appeared as choice is often what drives innovation. I'd just advise users to look at what they really need rather than assuming the alternatives automatically provide the best choice. A: There is an alternative library available for XML in Scala, Anti-XML. From the home page: Anti-XML is a proposed replacement for the scala.xml package in the Scala standard library. The standard package is outdated and beyond fixing. We need to start over, on solid foundations and unburdened by backward compatibility. Anti-XML aims for quality in three major areas: Usability, Reliability, Performance If you're looking at using XML seriously, then it's worth looking at Anti-XML. The source is available here: https://github.com/djspiewak/anti-xml A: Let me answer this way: * *Open XML issues (those assigned to the XML Team -- there might be others) *Alternative XML libraries in Scala Or, putting it into words, many people are not satisfied. After all, people are writing full blown alternatives instead of trying to "fix" the library. And, speaking of fixing, I had a fix which turned an operation from O(n^2) to O(n) submitted for so long that, when someone opened the very same issue again, I didn't even remember having opened it before. Mind you, Lift uses standard library XML, and, as far as I know, so do most of the other web frameworks (I suspect Play doesn't), so it's not like it's unusable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569172", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }