w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Linked List get method using recursive method
I got an error at get method in NonemptyListNode The error is that you don't have the return statement: public Object get(int index){ if(index+1 > this.size()) throw new IllegalArgumentException ("Out of Range"); else if(index == 0){ return myFirst; } else{ index = index-1; AbstractListNode l = this.myRest; l.get(index); /* * here you should have a return statement, if this else block * gets executed, no returns will be found. */ } }

Categories : Java

Using Recursive method in java
First of all I like to do something like this: public boolean contains(Comparable item) { return containsHelper(this.first, Comparable item); } private boolean containsHelper(Node node, Comparable item) { //base case if(node == null) { return false; } else { if(node.data.compareTo(item) == 0) { return true; } return containsHelper(node.next, item); } } This hides implementation details from the user and it stops your list from getting overridden when you run that method.

Categories : Java

Determining Big O for a recursive method
Depending on how you look at this, it's either O(1) because it will always take at most 7 iterations for positive inputs, you could say it will be O(lg n) because the number of iterations required will change relative to the lg base 2 of the input, or that it is undefined because the computation never completes for non-positive inputs. Take your pick!

Categories : Java

Recursive dataset method in c#
return dataset which is returned in recursive method, if(ds.Tables[0].Rows[0]["Coulumn1"].ToString()!=string.empty) { return GetTableInfo(str,d); } else { return ds; }

Categories : C#

Fixing a recursive method
You have to add one more array of bool where u will store which state have already been visited. Now you may come to following scenario: You are in state A. From state A you can go to states B and C. From state B you can go to state A <- this will be infinite loop. Also the memorization will increase calculation speed drastically. Hope I helped you.

Categories : Java

Simple recursive method
I guess that what you want could be achieved with: def all_feeds unless feeds.empty? feeds + feeds.map(&:all_feeds).flatten.compact end end Array#flatten makes the result one-dimensional, while Array#compact removes the nil components. For an explanation of the map(&:all_feeds) part, you can refer to this SO answer :)

Categories : Ruby On Rails

Recursive toString Method
It is somewhat bizarre, because the toString method's signature has no parameters, which means the need for another method. In a linked list, each node has data and a pointer to the next node. public String getData(Node n, String value) { if(n == null) { // We know we're at the end, so don't proceed. return value; } else { // n isn't empty, and ignoring the lack of stringbuilder value += n.getData(); // Make a recursive call with the next value in the list, and the new string. return getData(n.next(), value); } }

Categories : Java

Get list of results from recursive method
You can get a list of all files processed by ApplyAllFiles like this: static IEnumerable<string> ApplyAllFiles(string folder, Action<string> fileAction) { IEnumerable<string> files = Directory.GetFiles(folder); foreach (string file in files) { fileAction(file); } foreach (string subDir in Directory.GetDirectories(folder)) { try { files = files.Concat(ApplyAllFiles(subDir, fileAction)); } catch { // swallow, log, whatever } } return files; } But this will return an IEnumerable<string> to turn it into a string[] use this: var textfiles = ApplyAllFiles(t, ProcessFile).ToArray(); To only apply the specified action to certain files, you can pass in a

Categories : C#

Recursive method of reversing string
Don't use a while() loop inside the function. Also, you need to pass the string by reference if you want it to be modified. Here's your code with a little improvement :): void reverse(string& s,int i,int l) { static int j = 0; if (i < l) { char ch=s[i]; cout<<ch<<endl; reverse(s,i+1,l); cout<<"after="<<ch<<endl; s[j]=ch; j++; } cout<<s<<endl; }

Categories : C++

Sorting arrays in method and returning to main method
Code sponsored by Arrays.toString() and Arrays.sort(): public class ArraySort { public static void main(String args[]) { int t[] = {3, 5, 2}; // your reading part is fine, so I will skip it sortArrayWithoutCheating(t); System.out.println(Arrays.toString(t)); } public static void sortArrayWithoutCheating(int[] t) { // simplest O(n^2) sort for (int i = 0; i < t.length; i++) { for (int j = 0; j < i; j++) { if (t[i] < t[j]) { // swap t[i] and t[j] int temp = t[i]; t[i] = t[j]; t[j] = temp; } } } } public static void sortArray(int[] t)

Categories : Java

Method specification when returning class from a method in Java
It seems that you're supposed to return a new instance of VectorADT whose vector is the sum array you've computed. It's simply return new VectorADT(sum); This is a common operation in vector math. The sum of two vectors is a third vector whose components are the sum of the two corresponding components from the addend vectors.

Categories : Java

JavaScript object returning static method and himself as method
function foo() { return "foo"; } foo.bar = function() { return "bar"; }; Or, if you prefer: var foo = function() { return "foo"; }; foo.bar = function() { return "bar"; } JS functions are a type of object so you can assign properties/methods to them the same as for any other object.

Categories : Javascript

recursive method making issue in events
Ok, that's your code: http://jsfiddle.net/848AE/1/ Look in console (i change success event to failure, but it doesn't matter). function test(param) { console.log('------------------------------'); console.log('param = ' + param); var tt = [ "a", "b", "c" ]; for ( var i = 0; i < param; i++) { console.log('Before if-check, i = ' + i); if (tt[i] == "b") { console.log('Request start, after if-check i = ' + i); Ext.Ajax.request( { url : 'test.do', method : 'POST', failure: function(response) { console.log('Failure start, i = ' + i); test(1); console.log('Alert(i) = ' + i); } }); // break;

Categories : Javascript

Linked List Recursive removeAll method
I prefer to pass a reference to the previous when you remove to switch previous to the next something like this public void remove(T target){ removeAux(target,head, null); } public void removeAux(T target, Node current, Node previous) { //case base if(current == null) return; if (target.compareTo(current.data) == 0) { if (previous == null) { // is the head head = current.next; } else { //is not the head previous.next = current.next; } current = current.next; removeAux(target, current, previous); // previous doesn't change } else { removeAux(target, current.next, current); } } Check this answer graphically linked list may help you to think how to i

Categories : Java

Reverse ifstream input using recursive method
If I got it correct you want the Reverse function to return the separator at the end. The problem is the Reverse function doesn't necessarily return anything, since the last if statement doesn't evaluate to true if the character read at this recursion level is not a separator. The separator is not propagated back. You can fix this by introducing another variable. int Reverse(ifstream &inFile, int level) { int input = inFile.get(); int separator = 0; if (checkSeparator(input)) return input; else separator = Reverse(inFile, ++level); ... // remove the last if return separator; }

Categories : C++

Why does the field in my recursive Java method change?
Your problem is, that you are always modifying and inserting the same array into your result list. Since Java handles all objects per reference, you'll end up with a list containing the same array over and over again. So you need to either clone the array before adding it to the list: indexList.add(newLine.clone()); Or create the newLine array new every time you iterate your j-loop: for (int j = 0; j < endList.size(); j++) { Integer[] newLine = new Integer[numBins]; newLine[0] = i; Integer[] newLineEnd = endList.get(j); for (int k = 0; k < numBins - 1; k++) newLine[k + 1] = newLineEnd[k]; indexList.add(newLine); } // next j Regarding Objects versus primitives: Changing to int[] did not help because the array itself is still an Object and thus passed

Categories : Java

Recursive method of shrinking triangles in Python
If I were to guess, it is probably because you are calling the following twice (in drawTriangles()) and the value of the size variable does not change between these two calls. drawTriangle(size) drawTriangles(size / 2, depth - 1)

Categories : Python

Trying to remove auxiliary counter variable from recursive method
I believe this should work private long getPaths(Position p) { return (p.hasDown() ? getPaths(p.getDown()) : 0) + (p.hasRight() ? getPaths(p.getRight()) : 0) + ((p.getRow() == board.length - 1) && (p.getColumn() == board.length -1) ? 1 : 0); }

Categories : Java

Recursive method in Java that calculates factorials not working
This code doesn't compile. You're missing the return types on both of these methods. You should use public int fact... instead of public fact... Your parameters don't have types. It should probably be fact(int n) instead of fact(n) You don't need two functions to do this. You can use two if you want, but I just wanted to let you know it's unnecessary. You should probably google for "recursive factorial algorithm" to get more help.

Categories : Java

error: @tailrec annotated method contains no recursive calls
lastRecursive isn't tail recursive but lr is. This worked for me: object P01 { final def lastRecursive[A] (ls:List[A]):A = { @annotation.tailrec def lr[A] (l:List[A]):A = l match { case h :: Nil => h case _ :: tail => lr(tail) case _ => throw new NoSuchElementException } lr(ls) } }

Categories : Scala

saving state for a Java class that uses a recursive method
With recursion, part of the data is on stack, and stack cannot be saved that easily. If such functionality is required, rewrite everything using while loop together with the Stack or ArrayDeque data structure instead. This allows to save and restore the state without problems.

Categories : Java

Returning from input() method, in while loop within same method
You are recursively calling input(). If you say 'y' a few times then 'n' it will have to walk back down the stack for each call to input(). You will have to press 'n' or 'N' for each time it has input was called. Getting rid of some of the handy waving ifs might help...

Categories : C#

How to transform the several loops code of finding combination into recursive method?
void backtrack(int start, int depth) { if (depth < 5) { for (int i = start; i < 25; ++i) { backtrack(i + 1, depth + 1); } } } Seems like it would do the same as your nested loops.

Categories : C++

Recursive Tree Traversal Method With Return Type Array
public static List traversePreRecursive(Node node) { if (node == null) return new ArrayList(); List nodeValues = new ArrayList(); nodeValues.add(node.getValue()); nodeValues.addAll(traversePreRecursive(node.getLeft())); nodeValues.addAll(traversePreRecursive(node.getRight())); return nodeValues; }

Categories : Java

recursive function - help returning value when calling function
function find_percentile($search, $type, $score){ $max = null; $where = 0; foreach($search as $key=>$val){ if ($val[$type]== $score){ return $key; } else if($val[$type]>$max && $val[$type] < $score) { $where = $key; $max = $val[$type]; } } return $where; }

Categories : PHP

Creating a recursive method to remove specific objects from a 2D array [Updated]
You'll need to write a floodfill algorithm to accomplish this. Flood fill is used to fill in connected pixels of the same color in image editing programs like MSPaint or Photoshop. Here's how it works (Edited): Push starting point onto stack While stack not empty, get next point. If item at point is valid color, it will be set to null in your grid. If item at point is valid color, push all cardinal neighbors onto stack. I'll post some example code of the algorithm using your code above as much as possible. public void removeLikeColorsFrom(ColorShape[][] _tiles, int x, int y){ Color colorToReturn = _tiles[x][y].getColor(); Stack<Point> stack = new Stack<Point>(); stack.add(new Point(x,y)); while(!stack.empty()){ Point next = stack.pop(); //

Categories : Java

Getting undesired space between 2 divs
Use height auto for .metzo class .metzo { width:80%; height: auto; padding:0px; margin-left:10%; margin-right:10%; /*margin-bottom:5%;*/ text-align:center; }

Categories : HTML

Undo an undesired merge in SVN
You can undo a change by simply use a reverse range in your svn merge command: $ svn revert -R . #Remove all changes made $ svn update #and make sure up to date $ svn merge -r77691:77088 . This will get rid of changes from 77089 to 77691 from your working directory. Or you can undo the merge one revision at a time: $ svn merge -c -77691 . $ svn merge -c -77690 . $ svn merge -c -77689 .

Categories : Svn

CSS: Undesired result from fixed positioning?
Well, here we go on some explanation about each thing you asked (I believe that's better to you know what they do than just give you the code): position It's for determining how your element will be positioned in the page. It plays together with left, top, right and bottom properties. You have a few options here: static: The default behavior. The previously mentioned properties won't apply. fixed: Position the element relative to the screen viewport. It won't move when scrolling (your case!) absolute: Position the element relative to the closest positioned ancestor. relative: Lay out the element as it weren't positioned, and then adjust its position. z-index It's for arranging your element in the 3rd dimension; for example, if 2 elements are overlaped, the one which haves the bigger

Categories : HTML

jQuery undesired effect from 'tr td:first-child'
The problem here is that the selector $('.contentTable tr td:first-child') chooses every one of those elements and gets the text from all of them, resulting in 16 17 as you are seeing. My suggestion is to change a couple of things: Push the id into the array by adding an additional selector: $('.editable_content_td, .content_td a').each(function () { saveEdits.push($(this).text()); }); Then remove the code you have that is getting the id - the id should now be at the start of the array http://jsfiddle.net/NuLPC/8/

Categories : Jquery

Undesired scrolling when focusing textarea
For transitions you can use the following to detect the end of a transition via jQuery: $('.block').click(function () { $(this).bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){ $(this).children('textarea').focus(); }); $(this).toggleClass('show'); }); jsfiddle - http://jsfiddle.net/Cc25T/4/

Categories : Javascript

Undesired effects when calculating 2 amounts with jQuery
Your values are being interpreted as strings, not numbers. See what happens when you debug: So the comparisons are string comparisons ("alphabetically", "100" is before "20"). It's also doing string concatenation when you use the + operator. You need to convert the values to numbers before you use them, using Number(), parseFloat(), or parseInt(), depending.

Categories : Jquery

prevent undesired line wrapping in TextView
Add the following to your TextView definition: android:singleLine="true" edit: As pointed out, this is now deprecated, and so you should use android:inputType="text"

Categories : Android

Rails Link_to is linking to undesired view
IN YOUR : app/contorollers/exhibits_controller.rb def show @investigation = Investigation.find(params[:investigation_id]) @exhibit = Exhibit.find(params[:id]) end IN YOUR : app/views/exhibits/show.html.erb <%= link_to investigation_exhibit_path(@investigation, @exhibit) do %> Maybe, I think.

Categories : Ruby On Rails

Mouseenter and Mouseleave giving undesired results
It's something to do with the flipLock data attribute. If you mouseout too soon flipLock is true and the revert flip wont happen causing the next mouseover to start with the wrong content. So from then on you're flipping back and forth between the same content. If you remove the flipLock detection and return false and add stop to the animation call in flip it will revert properly. The animation looks a bit wonky though, I'm not sure what can be done about that. This works for me: http://jsfiddle.net/5JyVC/5/ If you move fast enough it will still mess up, not sure why that is, maybe multiple mouseover events? This is what the original flipLock intended to prevent I guess. Maybe flipLock should be more complex, when flipped, only allow flip backs and vice versa. The current implemenation

Categories : Javascript

Undesired results while merging list and tuples
it's because you're using the += operator. This modifies the list in place. In your code, you end up with a reference to fo['current'] stored in the total dictionary. When you modify it from total, the list fo also sees the modification because they are the same list. In this case, I'd probably use a defaultdict: import collections fo = {'current': [[1,23],[3,45],[5,65]]} pl = {'current': [(2,30),(3,33),(5,34)]} total = collections.defaultdict(list) for d in fo,pl: for key in d: total[key].extend(d[key]) total.default_factory = None #allow KeyErrors to happen print total # defaultdict(<type 'list'>, {'current': [[1, 23], [3, 45], [5, 65], (2, 30), (3, 33), (5, 34)]}) print fo # {'current': [[1, 23], [3, 45], [5, 65]]} print pl # {'current': [(2, 30), (3, 33), (5,

Categories : Python

Undesired result from SQL query in C# console application
Your two issues are: It's updating all the rows to be the same value This is because there isn't a where clause in your update statement. It's making the value double up. This is because of the line AccountTotal += CalculateIncome(); What this does is in the first run make it be 100 and the second loop around it makes it be 200.

Categories : C#

Types don't match between the anchor and the recursive part in column of recursive query
Try changing the query to cast the varchars to VARCHAR(MAX). Something like DECLARE @CategoryId AS int = 217; WITH Categories AS ( SELECT ParentCategoryId, CategoryName, CAST('' AS VARCHAR(MAX)) AS strCategory FROM Category WHERE CategoryId = @CategoryId UNION ALL SELECT c.ParentCategoryId, c.CategoryName, CAST((c.CategoryName + ': ' + cts.strCategory) AS VARCHAR(MAX)) AS strCategory FROM Category AS c JOIN Categories AS cts ON c.CategoryId = cts.ParentCategoryId ) SELECT TOP 1 CategoryName, LEN(CategoryName) AS strLength FROM Categories ORDER BY strLength DESC

Categories : SQL

FileUpload uploads undesired files on page refresh
You may want to track if the request is because of the page refresh. Please look at the following link for ideas on how to do that: Page Refresh Causes Duplicate POST in ASP.NET Applications

Categories : C#

Replacing illegal or undesired characters in requested URL before processing it .net
Looking for HttpUtility.UrlEncode The UrlEncode(String) method can be used to encode the entire URL, including query-string values. If characters such as blanks and punctuation are passed in an HTTP stream without encoding, they might be misinterpreted at the receiving end. URL encoding converts characters that are not allowed in a URL into character-entity equivalents; URL decoding reverses the encoding. For example, when the characters < and > are embedded in a block of text to be transmitted in a URL, they are encoded as %3c and %3e.

Categories : C#



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.