Search Results

Search found 1112 results on 45 pages for 'recursive'.

Page 18/45 | < Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >

  • How often is seq used in Haskell production code?

    - by Giorgio
    I have some experience writing small tools in Haskell and I find it very intuitive to use, especially for writing filters (using interact) that process their standard input and pipe it to standard output. Recently I tried to use one such filter on a file that was about 10 times larger than usual and I got a Stack space overflow error. After doing some reading (e.g. here and here) I have identified two guidelines to save stack space (experienced Haskellers, please correct me if I write something that is not correct): Avoid recursive function calls that are not tail-recursive (this is valid for all functional languages that support tail-call optimization). Introduce seq to force early evaluation of sub-expressions so that expressions do not grow to large before they are reduced (this is specific to Haskell, or at least to languages using lazy evaluation). After introducing five or six seq calls in my code my tool runs smoothly again (also on the larger data). However, I find the original code was a bit more readable. Since I am not an experienced Haskell programmer I wanted to ask if introducing seq in this way is a common practice, and how often one will normally see seq in Haskell production code. Or are there any techniques that allow to avoid using seq too often and still use little stack space?

    Read the article

  • How to determine if a 3D voxel-based room is sealed, efficiently

    - by NigelMan1010
    I've been having some issues with efficiently determining if large rooms are sealed in a voxel-based 3D rooms. I'm at a point where I have tried my hardest to solve the problem without asking for help, but not tried enough to give up, so I'm asking for help. To clarify, sealed being that there are no holes in the room. There are oxygen sealers, which check if the room is sealed, and seal depending on the oxygen input level. Right now, this is how I'm doing it: Starting at the block above the sealer tile (the vent is on the sealer's top face), recursively loop through in all 6 adjacent directions If the adjacent tile is a full, non-vacuum tile, continue through the loop If the adjacent tile is not full, or is a vacuum tile, check if it's adjacent blocks are, recursively. Each time a tile is checked, decrement a counter If the count hits zero, if the last block is adjacent to a vacuum tile, return that the area is unsealed If the count hits zero and the last block is not a vacuum tile, or the recursive loop ends (no vacuum tiles left) before the counter is zero, the area is sealed If the area is not sealed, run the loop again with some changes: Checking adjacent blocks for "breathable air" tile instead of a vacuum tile Instead of using a decrementing counter, continue until no adjacent "breathable air" tiles are found. Once loop is finished, set each checked block to a vacuum tile. Here's the code I'm using: http://pastebin.com/NimyKncC The problem: I'm running this check every 3 seconds, sometimes a sealer will have to loop through hundreds of blocks, and a large world with many oxygen sealers, these multiple recursive loops every few seconds can be very hard on the CPU. I was wondering if anyone with more experience with optimization can give me a hand, or at least point me in the right direction. Thanks a bunch.

    Read the article

  • Odd behavior when recursively building a return type for variadic functions

    - by Dennis Zickefoose
    This is probably going to be a really simple explanation, but I'm going to give as much backstory as possible in case I'm wrong. Advanced apologies for being so verbose. I'm using gcc4.5, and I realize the c++0x support is still somewhat experimental, but I'm going to act on the assumption that there's a non-bug related reason for the behavior I'm seeing. I'm experimenting with variadic function templates. The end goal was to build a cons-list out of std::pair. It wasn't meant to be a custom type, just a string of pair objects. The function that constructs the list would have to be in some way recursive, with the ultimate return value being dependent on the result of the recursive calls. As an added twist, successive parameters are added together before being inserted into the list. So if I pass [1, 2, 3, 4, 5, 6] the end result should be {1+2, {3+4, 5+6}}. My initial attempt was fairly naive. A function, Build, with two overloads. One took two identical parameters and simply returned their sum. The other took two parameters and a parameter pack. The return value was a pair consisting of the sum of the two set parameters, and the recursive call. In retrospect, this was obviously a flawed strategy, because the function isn't declared when I try to figure out its return type, so it has no choice but to resolve to the non-recursive version. That I understand. Where I got confused was the second iteration. I decided to make those functions static members of a template class. The function calls themselves are not parameterized, but instead the entire class is. My assumption was that when the recursive function attempts to generate its return type, it would instantiate a whole new version of the structure with its own static function, and everything would work itself out. The result was: "error: no matching function for call to BuildStruct<double, double, char, char>::Go(const char&, const char&)" The offending code: static auto Go(const Type& t0, const Type& t1, const Types&... rest) -> std::pair<Type, decltype(BuildStruct<Types...>::Go(rest...))> My confusion comes from the fact that the parameters to BuildStruct should always be the same types as the arguments sent to BuildStruct::Go, but in the error code Go is missing the initial two double parameters. What am I missing here? If my initial assumption about how the static functions would be chosen was incorrect, why is it trying to call the wrong function rather than just not finding a function at all? It seems to just be mixing types willy-nilly, and I just can't come up with an explanation as to why. If I add additional parameters to the initial call, it always burrows down to that last step before failing, so presumably the recursion itself is at least partially working. This is in direct contrast to the initial attempt, which always failed to find a function call right away. Ultimately, I've gotten past the problem, with a fairly elegant solution that hardly resembles either of the first two attempts. So I know how to do what I want to do. I'm looking for an explanation for the failure I saw. Full code to follow since I'm sure my verbal description was insufficient. First some boilerplate, if you feel compelled to execute the code and see it for yourself. Then the initial attempt, which failed reasonably, then the second attempt, which did not. #include <iostream> using std::cout; using std::endl; #include <utility> template<typename T1, typename T2> std::ostream& operator <<(std::ostream& str, const std::pair<T1, T2>& p) { return str << "[" << p.first << ", " << p.second << "]"; } //Insert code here int main() { Execute(5, 6, 4.3, 2.2, 'c', 'd'); Execute(5, 6, 4.3, 2.2); Execute(5, 6); return 0; } Non-struct solution: template<typename Type> Type BuildFunction(const Type& t0, const Type& t1) { return t0 + t1; } template<typename Type, typename... Rest> auto BuildFunction(const Type& t0, const Type& t1, const Rest&... rest) -> std::pair<Type, decltype(BuildFunction(rest...))> { return std::pair<Type, decltype(BuildFunction(rest...))> (t0 + t1, BuildFunction(rest...)); } template<typename... Types> void Execute(const Types&... t) { cout << BuildFunction(t...) << endl; } Resulting errors: test.cpp: In function 'void Execute(const Types& ...) [with Types = {int, int, double, double, char, char}]': test.cpp:33:35: instantiated from here test.cpp:28:3: error: no matching function for call to 'BuildFunction(const int&, const int&, const double&, const double&, const char&, const char&)' Struct solution: template<typename... Types> struct BuildStruct; template<typename Type> struct BuildStruct<Type, Type> { static Type Go(const Type& t0, const Type& t1) { return t0 + t1; } }; template<typename Type, typename... Types> struct BuildStruct<Type, Type, Types...> { static auto Go(const Type& t0, const Type& t1, const Types&... rest) -> std::pair<Type, decltype(BuildStruct<Types...>::Go(rest...))> { return std::pair<Type, decltype(BuildStruct<Types...>::Go(rest...))> (t0 + t1, BuildStruct<Types...>::Go(rest...)); } }; template<typename... Types> void Execute(const Types&... t) { cout << BuildStruct<Types...>::Go(t...) << endl; } Resulting errors: test.cpp: In instantiation of 'BuildStruct<int, int, double, double, char, char>': test.cpp:33:3: instantiated from 'void Execute(const Types& ...) [with Types = {int, int, double, double, char, char}]' test.cpp:38:41: instantiated from here test.cpp:24:15: error: no matching function for call to 'BuildStruct<double, double, char, char>::Go(const char&, const char&)' test.cpp:24:15: note: candidate is: static std::pair<Type, decltype (BuildStruct<Types ...>::Go(BuildStruct<Type, Type, Types ...>::Go::rest ...))> BuildStruct<Type, Type, Types ...>::Go(const Type&, const Type&, const Types& ...) [with Type = double, Types = {char, char}, decltype (BuildStruct<Types ...>::Go(BuildStruct<Type, Type, Types ...>::Go::rest ...)) = char] test.cpp: In function 'void Execute(const Types& ...) [with Types = {int, int, double, double, char, char}]': test.cpp:38:41: instantiated from here test.cpp:33:3: error: 'Go' is not a member of 'BuildStruct<int, int, double, double, char, char>'

    Read the article

  • Merging deletes in a Team Foundation Server baseless merge

    - by Justin Dearing
    I have two TFS branches that do not have a direct parent/child relationship in TFS. In a certain revision, 94 in my example, several items were deleted. I have been tasked with applying those deletes to the main branch. I'd like to do so through a baseless merge. I tried the following command to do so: tf merge /baseless /recursive /version:94 .\programs\program1 ..\Release\programs\program1 Most of the items in the tree were marked as "merge", and some were marked as "merge edit". However, none of the items were deleted at the destination. On a whim i tried to merge over a single delete like so: tf merge /baseless /recursive /version:94 .\programs\program1\source1.cs ..\Release\programs\program1\source1.cs I got the following error message: The item [TFS_PATH] does not exist at the specified version. How do I do this? Is there a way to avoid making all those deletes myself?

    Read the article

  • Functional Programming - Lots of emphasis on recursion, why?

    - by peakit
    I am getting introduced to Functional Programming [FP] (using Scala). One thing that is coming out from my initial learnings is that FPs rely heavily on recursion. And also it seems like, in pure FPs the only way to do iterative stuff is by writing recursive functions. And because of the heavy usage of recursion seems the next thing that FPs had to worry about were StackoverflowExceptions typically due to long winding recursive calls. This was tackled by introducing some optimizations (tail recursion related optimizations in maintenance of stackframes and @tailrec annotation from Scala v2.8 onwards) Can someone please enlighten me why recursion is so important to functional programming paradigm? Is there something in the specifications of functional programming languages which gets "violated" if we do stuff iteratively? If yes, then I am keen to know that as well. PS: Note that I am newbie to functional programming so feel free to point me to existing resources if they explain/answer my question. Also I do understand that Scala in particular provides support for doing iterative stuff as well.

    Read the article

  • How to generate all variations with repetitions of a string?

    - by Svenstaro
    I want to generate all variations with repetitions of a string in C++ and I'd highly prefer a non-recursive algorithm. I've come up with a recursive algorithm in the past but due to the complexity (r^n) I'd like to see an iterative approach. I'm quite surprised that I wasn't able to find a solution to this problem anywhere on the web or on StackOverflow. I've come up with a Python script that does what I want as well: import itertools variations = itertools.product('ab', repeat=4) for variations in variations: variation_string = "" for letter in variations: variation_string += letter print variation_string Output: aaaa aaab aaba aabb abaa abab abba abbb baaa baab baba babb bbaa bbab bbba bbbb Ideally I'd like a C++ program that can produce the exact output, taking the exact same parameters. This is for learning purposes, it isn't homework. I wish my homework was like that.

    Read the article

  • PyQt: Get the position of QGraphicsWidgets in a QGraphicsGridLayout

    - by Chris Phillips
    I have a fairly simple PyQt application in which I'm placing instances of a QGraphicsWidget in a QGraphicsGridLayout and want to connect the widgets with lines drawn with a QGraphicsPath. Unfortunately, no matter what I try, I always get (0, 0) back as the position for both the start and end widgets. I'm constructing the graph with a recursive function that adds widgets to the scene and layout. Once the recursive function is complete, the layout is added to a new widget, which is added to the scene to show everything. The edges are added to the scene as widgets are created. How do I get a non-zero position of any of the widgets in the grid layout?

    Read the article

  • Strange: Planner takes decision with lower cost, but (very) query long runtime

    - by S38
    Facts: PGSQL 8.4.2, Linux I make use of table inheritance Each Table contains 3 million rows Indexes on joining columns are set Table statistics (analyze, vacuum analyze) are up-to-date Only used table is "node" with varios partitioned sub-tables Recursive query (pg = 8.4) Now here is the explained query: WITH RECURSIVE rows AS ( SELECT * FROM ( SELECT r.id, r.set, r.parent, r.masterid FROM d_storage.node_dataset r WHERE masterid = 3533933 ) q UNION ALL SELECT * FROM ( SELECT c.id, c.set, c.parent, r.masterid FROM rows r JOIN a_storage.node c ON c.parent = r.id ) q ) SELECT r.masterid, r.id AS nodeid FROM rows r QUERY PLAN ----------------------------------------------------------------------------------------------------------------------------------------------------------------- CTE Scan on rows r (cost=2742105.92..2862119.94 rows=6000701 width=16) (actual time=0.033..172111.204 rows=4 loops=1) CTE rows -> Recursive Union (cost=0.00..2742105.92 rows=6000701 width=28) (actual time=0.029..172111.183 rows=4 loops=1) -> Index Scan using node_dataset_masterid on node_dataset r (cost=0.00..8.60 rows=1 width=28) (actual time=0.025..0.027 rows=1 loops=1) Index Cond: (masterid = 3533933) -> Hash Join (cost=0.33..262208.33 rows=600070 width=28) (actual time=40628.371..57370.361 rows=1 loops=3) Hash Cond: (c.parent = r.id) -> Append (cost=0.00..211202.04 rows=12001404 width=20) (actual time=0.011..46365.669 rows=12000004 loops=3) -> Seq Scan on node c (cost=0.00..24.00 rows=1400 width=20) (actual time=0.002..0.002 rows=0 loops=3) -> Seq Scan on node_dataset c (cost=0.00..55001.01 rows=3000001 width=20) (actual time=0.007..3426.593 rows=3000001 loops=3) -> Seq Scan on node_stammdaten c (cost=0.00..52059.01 rows=3000001 width=20) (actual time=0.008..9049.189 rows=3000001 loops=3) -> Seq Scan on node_stammdaten_adresse c (cost=0.00..52059.01 rows=3000001 width=20) (actual time=3.455..8381.725 rows=3000001 loops=3) -> Seq Scan on node_testdaten c (cost=0.00..52059.01 rows=3000001 width=20) (actual time=1.810..5259.178 rows=3000001 loops=3) -> Hash (cost=0.20..0.20 rows=10 width=16) (actual time=0.010..0.010 rows=1 loops=3) -> WorkTable Scan on rows r (cost=0.00..0.20 rows=10 width=16) (actual time=0.002..0.004 rows=1 loops=3) Total runtime: 172111.371 ms (16 rows) (END) So far so bad, the planner decides to choose hash joins (good) but no indexes (bad). Now after doing the following: SET enable_hashjoins TO false; The explained query looks like that: QUERY PLAN ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- CTE Scan on rows r (cost=15198247.00..15318261.02 rows=6000701 width=16) (actual time=0.038..49.221 rows=4 loops=1) CTE rows -> Recursive Union (cost=0.00..15198247.00 rows=6000701 width=28) (actual time=0.032..49.201 rows=4 loops=1) -> Index Scan using node_dataset_masterid on node_dataset r (cost=0.00..8.60 rows=1 width=28) (actual time=0.028..0.031 rows=1 loops=1) Index Cond: (masterid = 3533933) -> Nested Loop (cost=0.00..1507822.44 rows=600070 width=28) (actual time=10.384..16.382 rows=1 loops=3) Join Filter: (r.id = c.parent) -> WorkTable Scan on rows r (cost=0.00..0.20 rows=10 width=16) (actual time=0.001..0.003 rows=1 loops=3) -> Append (cost=0.00..113264.67 rows=3001404 width=20) (actual time=8.546..12.268 rows=1 loops=4) -> Seq Scan on node c (cost=0.00..24.00 rows=1400 width=20) (actual time=0.001..0.001 rows=0 loops=4) -> Bitmap Heap Scan on node_dataset c (cost=58213.87..113214.88 rows=3000001 width=20) (actual time=1.906..1.906 rows=0 loops=4) Recheck Cond: (c.parent = r.id) -> Bitmap Index Scan on node_dataset_parent (cost=0.00..57463.87 rows=3000001 width=0) (actual time=1.903..1.903 rows=0 loops=4) Index Cond: (c.parent = r.id) -> Index Scan using node_stammdaten_parent on node_stammdaten c (cost=0.00..8.60 rows=1 width=20) (actual time=3.272..3.273 rows=0 loops=4) Index Cond: (c.parent = r.id) -> Index Scan using node_stammdaten_adresse_parent on node_stammdaten_adresse c (cost=0.00..8.60 rows=1 width=20) (actual time=4.333..4.333 rows=0 loops=4) Index Cond: (c.parent = r.id) -> Index Scan using node_testdaten_parent on node_testdaten c (cost=0.00..8.60 rows=1 width=20) (actual time=2.745..2.746 rows=0 loops=4) Index Cond: (c.parent = r.id) Total runtime: 49.349 ms (21 rows) (END) - incredibly faster, because indexes were used. Notice: Cost of the second query ist somewhat higher than for the first query. So the main question is: Why does the planner make the first decision, instead of the second? Also interesing: Via SET enable_seqscan TO false; i temp. disabled seq scans. Than the planner used indexes and hash joins, and the query still was slow. So the problem seems to be the hash join. Maybe someone can help in this confusing situation? thx, R.

    Read the article

  • Best way to get the iframe object.

    - by Umar Siddique
    Hi, We are using too many iframes in out web application. In these iframes we load the pages which may also contains iframes and so on up to N level. Right now i'm using recursive function to find out the required iframe object in JavaScript. It works fine, The issue is when we create large dynamic pages which may contains up to 1000 iframes in it. In this case my recursive function takes too much time to find the required iframe object. How i can overcome this issue or these is any alternative of recursion in JavaScript. Thanks

    Read the article

  • Creating a spam list with a web crawler in python

    - by user313623
    Hey guys, I'm not trying to do anything malicious here, I just need to do some homework. I'm a fairly new programmer, I'm using python 3.0, and I having difficulty using recursion for problem-solving. I've been stuck on this question for quite a while. Here's the assignment: Write a recursive method spam(url, n) that takes a url of a web page as input and a non-negative integer n, collects all the email address contained in the web page and adds them to a global dictionary variable spam_dict, and then recursively calls itself on every http hyperlink contained in the web page. You will use a dictionary so only one copy of every email address is save; your dictionary will store (key,value) pairs (email, email). The recursive call should use the parameter n-1 instead of n. If n = 0, you should collect the email addresses but no recursive calls should be made. The parameter n is used to limit the recursion to at most depth n. You will need to use the solutions of the two above problems; you method spam() will call the methods links2() and emails() and possibly other functions as well. Notes: 1. running spam() directly will produce no output on the screen; to find your spam_dict, you will need to read the value of spam_dict, and you will also need to reset it to the empty dictionary before every run of spam. 2. Recall how global variables are used. Usage: spam_dict = {} spam('http://reed.cs.depaul.edu/lperkovic/csc242/test1.html',0) spam_dict.keys() dict_keys([]) spam_dict = {} spam('http://reed.cs.depaul.edu/lperkovic/csc242/test1.html',1) spam_dict.keys() dict_keys(['[email protected]', '[email protected]']) So far, I've written a function that traverses web pages and puts all the links in a nice little list, and what I wanted to do was call that functions. And why would I use recursion on a dictionary? And how? I don't understand how n ties into all of this. def links2(url): content = str(urlopen(url).read()) myparser = MyHTMLParser() myparser.feed(content) lst = myparser.get() mergelst = [] for link in lst: mergelst.append(urljoin(lst[0],link)) print(mergelst) Any input (except why spam is bad) would be greatly appreciated. Also, I realize that the above function could probably look better, if you have a way to do it, I'm all ears. However, all I need is the point is for the program to produce the proper output.

    Read the article

  • Installing my sdist from PyPI puts the files in the wrong places

    - by Tartley
    Hey. My problem is that when I upload my Python package to PyPI, and then install it from there using pip, my app breaks because it installs my files into completely different locations than when I simply install the exact same package from a local sdist. Installing from the local sdist puts files on my system like this: /Python27/ Lib/ site-packages/ gloopy-0.1.alpha-py2.7.egg/ (egg and install info files) data/ (images and shader source) doc/ (html) examples/ (.py scripts that use the library) gloopy/ (source) This is much as I'd expect, and works fine (e.g. my source can find my data dir, because they lie next to each other, just like they do in development.) If I upload the same sdist to PyPI and then install it from there, using pip, then things look very different: /Python27/ data/ (images and shader source) doc/ (html) Lib/ site-packages/ gloopy-0.1.alpha-py2.7.egg/ (egg and install info files) gloopy/ (source files) examples/ (.py scripts that use the library) This doesn't work at all - my app can't find its data files, plus obviously it's a mess, polluting the top-level /python27 directory with all my junk. What am I doing wrong? How do I make the pip install behave like the local sdist install? Is that even what I should be trying to achieve? Details I have setuptools installed, and also distribute, and I'm calling distribute_setup.use_setuptools() WindowsXP, Python2.7. My development directory looks like this: /gloopy /data (image files and GLSL shader souce read at runtime) /doc (html files) /examples (some scripts to show off the library) /gloopy (the library itself) My MANIFEST.in mentions all the files I want to be included in the sdist, including everything in the data, examples and doc directories: recursive-include data *.* recursive-include examples *.py recursive-include doc/html *.html *.css *.js *.png include LICENSE.txt include TODO.txt My setup.py is quite verbose, but I guess the best thing is to include it here, right? I also includes duplicate references to the same data / doc / examples directories as are mentioned in the MANIFEST.in, because I understand this is required in order for these files to be copied from the sdist to the system during install. NAME = 'gloopy' VERSION= __import__(NAME).VERSION RELEASE = __import__(NAME).RELEASE SCRIPT = None CONSOLE = False def main(): import sys from pprint import pprint from setup_utils import distribute_setup from setup_utils.sdist_setup import get_sdist_config distribute_setup.use_setuptools() from setuptools import setup description, long_description = read_description() config = dict( name=name, version=version, description=description, long_description=long_description, keywords='', packages=find_packages(), data_files=[ ('examples', glob('examples/*.py')), ('data/shaders', glob('data/shaders/*.*')), ('doc', glob('doc/html/*.*')), ('doc/_images', glob('doc/html/_images/*.*')), ('doc/_modules', glob('doc/html/_modules/*.*')), ('doc/_modules/gloopy', glob('doc/html/_modules/gloopy/*.*')), ('doc/_modules/gloopy/geom', glob('doc/html/_modules/gloopy/geom/*.*')), ('doc/_modules/gloopy/move', glob('doc/html/_modules/gloopy/move/*.*')), ('doc/_modules/gloopy/shapes', glob('doc/html/_modules/gloopy/shapes/*.*')), ('doc/_modules/gloopy/util', glob('doc/html/_modules/gloopy/util/*.*')), ('doc/_modules/gloopy/view', glob('doc/html/_modules/gloopy/view/*.*')), ('doc/_static', glob('doc/html/_static/*.*')), ('doc/_api', glob('doc/html/_api/*.*')), ], classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: Microsoft :: Windows', 'Programming Language :: Python :: 2.7', ], # see classifiers http://pypi.python.org/pypi?:action=list_classifiers ) config.update(dict( author='Jonathan Hartley', author_email='[email protected]', url='http://bitbucket.org/tartley/gloopy', license='New BSD', ) ) if '--verbose' in sys.argv: pprint(config) setup(**config) if __name__ == '__main__': main()

    Read the article

  • GCC ICE -- alternative function syntax, variadic templates and tuples

    - by Marc H.
    (Related to C++0x, How do I expand a tuple into variadic template function arguments?.) The following code (see below) is taken from this discussion. The objective is to apply a function to a tuple. I simplified the template parameters and modified the code to allow for a return value of generic type. While the original code compiles fine, when I try to compile the modified code with GCC 4.4.3, g++ -std=c++0x main.cc -o main GCC reports an internal compiler error (ICE) with the following message: main.cc: In function ‘int main()’: main.cc:53: internal compiler error: in tsubst_copy, at cp/pt.c:10077 Please submit a full bug report, with preprocessed source if appropriate. See <file:///usr/share/doc/gcc-4.4/README.Bugs> for instructions. Question: Is the code correct? or is the ICE triggered by illegal code? // file: main.cc #include <tuple> // Recursive case template<unsigned int N> struct Apply_aux { template<typename F, typename T, typename... X> static auto apply(F f, const T& t, X... x) -> decltype(Apply_aux<N-1>::apply(f, t, std::get<N-1>(t), x...)) { return Apply_aux<N-1>::apply(f, t, std::get<N-1>(t), x...); } }; // Terminal case template<> struct Apply_aux<0> { template<typename F, typename T, typename... X> static auto apply(F f, const T&, X... x) -> decltype(f(x...)) { return f(x...); } }; // Actual apply function template<typename F, typename T> auto apply(F f, const T& t) -> decltype(Apply_aux<std::tuple_size<T>::value>::apply(f, t)) { return Apply_aux<std::tuple_size<T>::value>::apply(f, t); } // Testing #include <string> #include <iostream> int f(int p1, double p2, std::string p3) { std::cout << "int=" << p1 << ", double=" << p2 << ", string=" << p3 << std::endl; return 1; } int g(int p1, std::string p2) { std::cout << "int=" << p1 << ", string=" << p2 << std::endl; return 2; } int main() { std::tuple<int, double, char const*> tup(1, 2.0, "xxx"); std::cout << apply(f, tup) << std::endl; std::cout << apply(g, std::make_tuple(4, "yyy")) << std::endl; } Remark: If I hardcode the return type in the recursive case (see code), then everything is fine. That is, substituting this snippet for the recursive case does not trigger the ICE: // Recursive case (hardcoded return type) template<unsigned int N> struct Apply_aux { template<typename F, typename T, typename... X> static int apply(F f, const T& t, X... x) { return Apply_aux<N-1>::apply(f, t, std::get<N-1>(t), x...); } }; Alas, this is an incomplete solution to the original problem.

    Read the article

  • Conflicting return types

    - by Adi
    I am doing a recursive program and I am getting an error about conflicting types: void* buddyMalloc(int req_size) { // Do something here return buddy_findout(original_index,req_size); // This is the recursive call } void *buddy_findout(int current_index,int req_size) { char *selected = NULL; if(front!=NULL) { if(current_index==original_index) { // Do something here return selected; } else { // Do Something here return buddy_findout(current_index+1,req_size); } } else { return buddy_findout(current_index-1,req_size); } } Error: buddy.c: At top level: buddy.c:76: error: conflicting types for ‘buddy_findout’ buddy.c:72: note: previous implicit declaration of ‘buddy_findout’ was here Please note the file buddy.c in which I am defining this does not contain main and is linked with several other .c files.

    Read the article

  • Create a triangle out of stars using only recursion

    - by Ramblingwood
    I need to to write a method that is called like printTriangle(5);. We need to create an iterative method and a recursive method (without ANY iteration). The output needs to look like this: * ** *** **** ***** This code works with the iterative but I can't adapt it to be recursive. public void printTriangle (int count) { int line = 1; while(line <= count) { for(int x = 1; x <= line; x++) { System.out.print("*"); } System.out.print("\n"); line++; } } I should not that you cannot use any class level variables or any external methods. Thanks.

    Read the article

  • conflicting types for a function return in C

    - by Adi
    Hi all, Here is my question : I am doing a recursive program and I am getting an error saying conflicting types: Code is : void* buddyMalloc(int req_size) { //Do something here// return buddy_findout(original_index,req_size); //This is the recursive fn I call// } void *buddy_findout(int current_index,int req_size) { char *selected = NULL; if(front!=NULL) { if(current_index==original_index) { //Do something here// return selected ; // } else { //Do Something here// return buddy_findout(current_index+1,req_size); } } else { return buddy_findout(current_index-1,req_size); } } In the above code , "I am getting error like : conflicting types of buddy_findout " Thanks for the help in advance aditya

    Read the article

  • heirarchial data from self referencing table in tree form

    - by Beta033
    Ii looks like this has been asked and answered in all the simple cases, excluding the one that i'm having trouble with. I've tried using a recursive CTE to generate this, however maybe a cursor would be better? or maybe a set of recursive functions will do the trick? Can this be done in a cte? consider the following table PrimaryKey ParentKey 1 NULL 2 1 3 6 4 7 5 2 6 1 7 NULL should yield PK 1 -2 --5 -6 --3 7 -4 where the number of - marks equal the depth, my primary difficulty is the ordering.

    Read the article

  • nodejs async.waterfall method

    - by user1513388
    Update 2 Complete code listing var request = require('request'); var cache = require('memory-cache'); var async = require('async'); var server = '172.16.221.190' var user = 'admin' var password ='Passw0rd' var dn ='\\VE\\Policy\\Objects' var jsonpayload = {"Username": user, "Password": password} async.waterfall([ //Get the API Key function(callback){ request.post({uri: 'http://' + server +'/sdk/authorize/', json: jsonpayload, headers: {'content_type': 'application/json'} }, function (e, r, body) { callback(null, body.APIKey); }) }, //List the credential objects function(apikey, callback){ var jsonpayload2 = {"ObjectDN": dn, "Recursive": true} request.post({uri: 'http://' + server +'/sdk/Config/enumerate?apikey=' + apikey, json: jsonpayload2, headers: {'content_type': 'application/json'} }, function (e, r, body) { var dns = []; for (var i = 0; i < body.Objects.length; i++) { dns.push({'name': body.Objects[i].Name, 'dn': body.Objects[i].DN}) } callback(null, dns, apikey); }) }, function(dns, apikey, callback){ // console.log(dns) var cb = []; for (var i = 0; i < dns.length; i++) { //Retrieve the credential var jsonpayload3 = {"CredentialPath": dns[i].dn, "Pattern": null, "Recursive": false} console.log(dns[i].dn) request.post({uri: 'http://' + server +'/sdk/credentials/retrieve?apikey=' + apikey, json: jsonpayload3, headers: {'content_type': 'application/json'} }, function (e, r, body) { // console.log(body) cb.push({'cl': body.Classname}) callback(null, cb, apikey); console.log(cb) }); } } ], function (err, result) { // console.log(result) // result now equals 'done' }); Update: I'm building a small application that needs to make multiple HTTP calls to a an external API and amalgamates the results into a single object or array. e.g. Connect to endpoint and get auth key - pass auth key to step 2 Connect to endpoint using auth key and get JSON results - create an object containing summary results and pass to step 3. Iterate over passed object summary results and call API for each item in the object to get detailed information for each summary line Create a single JSON data structure that contains the summary and detail information. The original question below outlines what I've tried so far! Original Question: Will the async.waterfall method support multiple callbacks? i.e. Iterate over an array thats passed from a previous item in the chain, then invoke multiple http requests each of which would have their own callbacks. e.g, sync.waterfall([ function(dns, key, callback){ var cb = []; for (var i = 0; i < dns.length; i++) { //Retrieve the credential var jsonpayload3 = {"Cred": dns[i].DN, "Pattern": null, "Recursive": false} console.log(dns[i].DN) request.post({uri: 'http://' + vedserver +'/api/cred/retrieve?apikey=' + key, json: jsonpayload3, headers: {'content_type': 'application/json'} }, function (e, r, body) { console.log(body) cb.push({'cl': body.Classname}) callback(null, cb, key); }); } }

    Read the article

  • Parallel Processing Simulation in Javascript

    - by le_havre
    Hello, I'm new to JavaScript so forgive me for being a n00b. When there's intensive calculation required, it more than likely involves loops that are recursive or otherwise. Sometimes this may mean having am recursive loop that runs four functions and maybe each of those functions walks the entire DOM tree, read positions and do some math for collision detection or whatever. While the first function is walking the DOM tree, the next one will have to wait its for the first one to finish, and so forth. Instead of doing this, why not launch those loops-within-loops separately, outside the programs, and act on their calculations in another loop that runs slower because it isn't doing those calculations itself? Retarded or clever? Thanks in advance!

    Read the article

  • Does the box API require case-sensitive booleans?

    - by Nick Chadwick
    I'm having some issues with the box.com developer API, and it seems that this is due to the API requiring lower-case booleans in request parameters. When I make a call to say, delete a folder, the URI my framework is generating looks like this: (DELETE) https://api.box.com/2.0/folders/1234?recursive=True This doesn't work, and the API throws an error. However, if I manually set the URI to this: (DELETE) https://api.box.com/2.0/folders/1234?recursive=true Everything seems to work just fine. I'd like to confirm that this is indeed the behavior, and if it is, I'd like to request box fix their API!

    Read the article

  • Counting vowels in a string using recursion

    - by Daniel Love Jr
    In my python class we are learning about recursion. I understand that it's when a function calls itself, however for this particular assignment I can't figure out how exactly to get my function to call it self to get the desired results. I need to simply count the vowels in the string given to the function. def recVowelCount(s): 'return the number of vowels in s using a recursive computation' vowelcount = 0 vowels = "aEiou".lower() if s[0] in vowels: vowelcount += 1 else: ??? I'm really not sure where to go with this, it's quite frustrating. I came up with this in the end, thanks to some insight from here. def recVowelCount(s): 'return the number of vowels in s using a recursive computation' vowels = "aeiouAEIOU" if s == "": return 0 elif s[0] in vowels: return 1 + recVowelCount(s[1:]) else: return 0 + recVowelCount(s[1:])

    Read the article

  • hierarchical data from self referencing table in tree form

    - by Beta033
    It looks like this has been asked and answered in all the simple cases, excluding the one that I'm having trouble with. I've tried using a recursive CTE to generate this; however maybe a cursor would be better? Or maybe a set of recursive functions will do the trick? Can this be done in a cte? consider the following table PrimaryKey ParentKey 1 NULL 2 1 3 6 4 7 5 2 6 1 7 NULL should yield PK 1 -2 --5 -6 --3 7 -4 where the number of - marks equal the depth, my primary difficulty is the ordering.

    Read the article

< Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >