Search Results

Search found 224 results on 9 pages for 'traversal'.

Page 8/9 | < Previous Page | 4 5 6 7 8 9  | Next Page >

  • 45 minutes to talk about C# [closed]

    - by Philip
    I have the opportunity to give a 45 minute talk on C# in the theory of programming languages class I'm taking. The college teaches Java almost exclusively, so that's what all the students are most familiar with. (There's a little C, assembly, Prolog and LISP as well.) I decide what to talk about. It seems to me the best approach is to focus on a few of the big, obvious differences between C# and Java. I don't intend it to be a recommendation to use C# -- there are reasons to use each, mostly because of their ecosystems. So I want to focus on C# as a language. I don't want to go too fast and end up listing a whole bunch of features without showing their usefulness. My current plan is this: Functions as first class objects. This is, in my opinion, one of the biggest differences between C# and Java. The professor briefly mentioned this notion and showed a LISP example, but many of the students have probably never used it. I can show real world examples where it's made my code more readable. Lambda expressions as concise syntax for anonymous functions. Obviously with examples to show how this is useful. The real hit-home examples will be at the end when it's combined with the rest. I don't see an advantage to first showing the old delegate syntax and then replacing it with lambdas -- most of us won't have ever seen delegates anyway so it would just be confusing. The yield keyword and how it's different from returning an array. I have the impression that a lot of C# developers aren't familiar with how to use this. It will likely be very foreign to Java developers. I have some examples from my own work where it was really useful, such as iterating over a tree traversal, or iterating over neighbors in a graph where the neighbors aren't stored in memory. In both cases, doing it in Java would likely mean returning a complete list -- with yield I can stop iterating if I find what I want early on, without using memory for superfluous lists or arrays. Extension methods as a way to write implementation on interfaces. We'll all be familiar with how interfaces don't allow method implementation, and how this leads to code duplication. I'll show a specific example of this and how the extension method can solve the problem. Demonstrate how the above can be combined by implementing some simple Linq methods and using them. Where, Select, First, maybe more depending on how much time is left. Ideas on which ones might 'hit home' the best? There are other things I could talk about such as generics, value types, properties and more. I haven't yet though of good ways to incorporate these. In the case of generics and value types, the advantages might not be obvious or as relevant. Properties are obviously useful, particularly since we're taught strict JavaBeans here, but I don't know if I could integrate it with the "path to Linq" discussion above without it feeling tacked on. So I'm looking for thoughts on how to talk about C#, and what to talk about. Even minor details. I'm sure there are more experienced C# developers than me here who have good insight about what's really important in the language, and what would miss the point.

    Read the article

  • Reading graph inputs for a programming puzzle and then solving it

    - by Vrashabh
    I just took a programming competition question and I absolutely bombed it. I had trouble right at the beginning itself from reading the input set. The question was basically a variant of this puzzle http://codercharts.com/puzzle/evacuation-plan but also had an hour component in the first line(say 3 hours after start of evacuation). It reads like this This puzzle is a tribute to all the people who suffered from the earthquake in Japan. The goal of this puzzle is, given a network of road and locations, to determine the maximum number of people that can be evacuated. The people must be evacuated from evacuation points to rescue points. The list of road and the number of people they can carry per hour is provided. Input Specifications Your program must accept one and only one command line argument: the input file. The input file is formatted as follows: the first line contains 4 integers n r s t n is the number of locations (each location is given by a number from 0 to n-1) r is the number of roads s is the number of locations to be evacuated from (evacuation points) t is the number of locations where people must be evacuated to (rescue points) the second line contains s integers giving the locations of the evacuation points the third line contains t integers giving the locations of the rescue points the r following lines contain to the road definitions. Each road is defined by 3 integers l1 l2 width where l1 and l2 are the locations connected by the road (roads are one-way) and width is the number of people per hour that can fit on the road Now look at the sample input set 5 5 1 2 3 0 3 4 0 1 10 0 2 5 1 2 4 1 3 5 2 4 10 The 3 in the first line is the additional component and is defined as the number of hours since the resuce has started which is 3 in this case. Now my solution was to use Dijisktras algorithm to find the shortest path between each of the rescue and evac nodes. Now my problem started with how to read the input set. I read the first line in python and stored the values in variables. But then I did not know how to store the values of the distance between the nodes and what DS to use and how to input it to say a standard implementation of dijikstras algorithm. So my question is two fold 1.) How do I take the input of such problems? - I have faced this problem in quite a few competitions recently and I hope I can get a simple code snippet or an explanation in java or python to read the data input set in such a way that I can input it as a graph to graph algorithms like dijikstra and floyd/warshall. Also a solution to the above problem would also help. 2.) How to solve this puzzle? My algorithm was: Find shortest path between evac points (in the above example it is 14 from 0 to 3) Multiply it by number of hours to get maximal number of saves Also the answer given for the variant for the input set was 24 which I dont understand. Can someone explain that also. UPDATE: I get how the answer is 14 in the given problem link - it seems to be just the shortest path between node 0 and 3. But with the 3 hour component how is the answer 24 UPDATE I get how it is 24 - its a complete graph traversal at every hour and this is how I solve it Hour 1 Node 0 to Node 1 - 10 people Node 0 to Node 2- 5 people TotalRescueCount=0 Node 1=10 Node 2= 5 Hour 2 Node 1 to Node 3 = 5(Rescued) Node 2 to Node 4 = 5(Rescued) Node 0 to Node 1 = 10 Node 0 to Node 2 = 5 Node 1 to Node 2 = 4 TotalRescueCount = 10 Node 1 = 10 Node 2= 5+4 = 9 Hour 3 Node 1 to Node 3 = 5(Rescued) Node 2 to Node 4 = 5+4 = 9(Rescued) TotalRescueCount = 9+5+10 = 24 It hard enough for this case , for multiple evac and rescue points how in the world would I write a pgm for this ?

    Read the article

  • Exchange Web Service (EWS) call fails under ASP.NET but not a console application

    - by Vince Panuccio
    I'm getting an error when I attempt to connect to Exchange Web Services via ASP.NET. The following code works if I call it via a console application but the very same code fails when executed on a ASP.NET web forms page. Just as a side note, I am using my own credentials throughout this entire code sample. "When making a request as an account that does not have a mailbox, you must specify the mailbox primary SMTP address for any distinguished folder Ids." I thought I might be able to fix the issue by specifying an impersonated user. exchangeservice.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "[email protected]"); But then I get a different error. "The account does not have permission to impersonate the requested user." The App Pool that the web application is running under is also my own account (same as the console application) so I have no idea what might be causing this issue. I am using .NET framework 3.5. Here is the code in full. var exchangeservice = new ExchangeService(ExchangeVersion.Exchange2010_SP1) { Timeout = 10000 }; var credentials = new System.Net.NetworkCredential("username", "pass", "domain"); exchangeservice.AutodiscoverUrl("[email protected]") FolderId rootFolderId = new FolderId(WellKnownFolderName.Inbox); var folderView = new FolderView(100) { Traversal = FolderTraversal.Shallow }; FindFoldersResults findFoldersResults = service.FindFolders(rootFolderId, folderView);

    Read the article

  • EWS 2010: Public Folder Problem using .NET

    - by Daniel
    I've recently coded a .NET Console app using C#. It's purpose was to read the emails within a specific folder, parse them for specific values and save them to a database. Our email system, at the time I originally coded this, was Exchange 2003. However, I was made aware we would soon be upgrading to Exchange 2010: ergo, I built the code to work in both environments. Following the migration to 2010, however, the app has broken. The app uses the EWS API for 2010 functionality. When it attempts to use the ExchangeService's FindFolders method to find the publicfoldersroot, it throws an exception. Here's the code: ExchangeService service = new ExchangeService(); FindFoldersResults findRootFldrs; service.UseDefaultCredentials = true; service.AutodiscoverUrl("[email protected]", delegate(string x) { return true; }); FolderView fview = new FolderView(100); fview.Traversal = FolderTraversal.Deep; if (findRootFldrsSub == null) { //Set to root to test local folders -- findRootFldrs = service.FindFolders(WellKnownFolderName.PublicFoldersRoot, fview); } The exception: "The mailbox that was requested doesn't support the specified RequestServerVersion" I've attempted: -Setting the exchangeservice to 2007 (throws an exception: "An internal server error occurred. The operation failed.") -Giving myself the highest level of permission to the Public Folder (no effect) -Manually setting my credentials (no effect) I can view the public folders in outlook; the publicfoldersroot property is available in the intellisense; the code works on local folders (I can parse my inbox). My current thinking is that it's a setting on the recent setup of Exchange 2010: unfortunately that isn't really my field.

    Read the article

  • Finding if a Binary Tree is a Binary Search Tree

    - by dharam
    Today I had an interview where I was asked to write a program which takes a Binary Tree and returns true if it is also a Binary Search Tree otherwise false. My Approach1: Perform an inroder traversal and store the elements in O(n) time. Now scan through the array/list of elements and check if element at ith index is greater than element at (i+1)th index. If such a condition is encountered, return false and break out of the loop. (This takes O(n) time). At the end return true. But this gentleman wanted me to provide an efficient solution. I tried but I was unsuccessfult, because to find if it is a BST I have to check each node. Moreover he was pointing me to think over recusrion. My Approach 2: A BT is a BST if for any node N N-left is < N and N-right N , and the INorder successor of left node of N is less than N and the inorder successor of right node of N is greater than N and the left and right subtrees are BSTs. But this is going to be complicated and running time doesn't seem to be good. Please help if you know any optimal solution. Thanks.

    Read the article

  • Jquery CheckBox Selection/Deselection optimally given X checkboxes

    - by Amitd
    Hi guys, I have suppose say 'X' check-boxes(any input elements) in a Form and "M" option selection indexes ("M" less than equal to "X"). then how do i select the "M" option indexes/values and deselect the rest of check-boxes optimally? i.e.Suppose I have 10 Checkboxes and 5 Option Indices(eg: 1,2,4,5,8) then i have to select checkboxes with given index . I could come up with the following code: HTML: <div id="Options"> <input id="choice_1" type="checkbox" name="choice_1" value="Option1"><label for="choice_1">Option1</label> <input id="choice_2" type="checkbox" name="choice_2" value="Option2"><label for="choice_2">Option2</label> <input id="choice_3" type="checkbox" name="choice_3" value="Option3"><label for="choice_3">Option3</label> .. ..till choice_10 </div> IN JS: //Have to select checkboxes with "Value" in choicesToSelect and give a selection //effect to its label var choicesToSelect={"Option1","Option9","Option3","Option4","Option2"}; selectHighlightCheckBoxes(choicesToSelect); function selectHighlightCheckBoxes(choices){ $.each( choices, function(intIndex, objValue) { //select based on id or value or some criteria var option = $("#Options :input[value=" + objValue + "]") ; if ($(option).is("input[type='radio']") || $(option).is("input[type='checkbox']")) { $(option).attr('checked', true); $(option).next('label:first').css({ 'border': '1px solid #FF0000', 'background-color': '#BEF781', 'font-weight': 'bolder' }); } else if ($(option).is("input[type='text']")) { $(option).css({ 'border': '1px solid #FF0000', 'background-color': '#BEF781', 'font-weight': 'bolder' }); } else { } } ); } But i want to also add effect to the rest (not in choicesToSelect array) also. (may be red color to those not in choiceToSelect) Can this be done in the one traversal/loop? Optimally? or Better way?

    Read the article

  • Help porting javascript function to jQuery - learning tool

    - by chibineku
    I am just learning jQuery and I wanted to see what I could do with the function below. This function adds or removes css classes to create a pull down menu (it is in fact Stu Nicholl's well known pull down menu). But I'm not getting very far (I've been learning jQuery for approximately an hoour now, so my DOM traversal isn't quite up there yet). I am curious to see how neat and elegant it can become using jQuery, and thought I'd see what you guys could come up with. Here is the existing function: var getEls = document.getElementById("menu").getElementsByTagName("LI"); var getAgn = getEls; for (var i=0; i<getEls.length; i++) { getEls[i].onclick=function() { for (var x=0; x<getAgn.length; x++) { getAgn[x].className=getAgn[x].className.replace("unclick", ""); getAgn[x].className=getAgn[x].className.replace("click", "unclick"); } if ((this.className.indexOf('unclick'))!=-1) { this.className=this.className.replace("unclick", "");; } else { this.className+=" click"; } } } } My first failure started like this: $(document).ready(function() { $('#menu > li').click(function() { $('#menu >li > ul').toggleClass('unclick'); }); }); That works as far as it goes, but the next bit proved tricky. So, if anyone feels like having a go, please be my guest :)

    Read the article

  • Java Iterators - Trying to get a for each loop to work

    - by CS Student
    So I have a Tree<E> class where E is the datatype held and organized by the tree. I'd like to iterate through the Tree like this, or in a way similar to this: 1. Tree<String> tree=new Tree<String>(); 2. ...add some nodes... 3. for (String s : tree) 4. System.out.println(s); It gives me an error on line 3 though. Incompatible types required: java.lang.String found: java.lang.Object The following works fine and as expected though, performing a proper in-order traversal of the tree and printing each node out as it should: for (TreeIterator<String> i = tree.iterator(); i.hasNext(); ) System.out.println(i.next()); Any idea what I'm doing wrong? Do you need to see more of the code?

    Read the article

  • PHP & cUrl - POST problems in while loop.

    - by Max Hoff
    I have a while loop, with cUrl inside. (I can't use curl_multi for various reasons.) The problem is that cUrl seems to save the data it POSTS after each loop traversal. For instance, if parameter X is One the first loop through, and if it's Two the second loop through, cUrl posts: "One,Two". It should just POST "Two".(This is despite closing and unsetting the curl handle.) Here's a simplified version of the code (with unecessary info stripped out): while(true){ // code to form the $url. this code is local to the loop. so the variables should be "erased" and made new for each loop through. $ch = curl_init(); $userAgent = 'Googlebot/2.1 (http://www.googlebot.com/bot.html)'; curl_setopt($ch,CURLOPT_USERAGENT, $userAgent); curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_POST,count($fields)); curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string); curl_setopt($ch, CURLOPT_FAILONERROR, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_AUTOREFERER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER,true); curl_setopt($ch, CURLOPT_TIMEOUT, 10); $html = curl_exec($ch); curl_close($ch); unset($ch); $dom = new DOMDocument(); @$dom->loadHTML($html); $xpath = new DOMXPath($dom); $resultTable = $xpath->evaluate("/html/body//table"); // $resultTable is 20 the first time through the loop, and 0 everytime thereafter becauset he POSTing doesn't work right with the "saved" parameters. What am I doing wrong here?

    Read the article

  • Using JQuery to traverse DOM structure, finding a specific <table> element located after HTML 'comme

    - by Shadow
    I currently have a website source code (no control over the source) which contains certain content that needs to be manipulated. This would be simple on the surface, however there is no unique ID attribute on the tag in question that can uniquely identify it, and therefore allow for further traversal. Here is a snippet of the source code, surrounding the tag in question. ... <td width="100%"> <!--This table snaps the content columns(one or two)--> <table border="0" width="100%"> ... Essentially, the HTML comment stuck out as an easy way to gain access to that element. Using the JQuery comment add-on from this question, and some help from snowlord comment below, I have been able to identify the comment and retrieve the following output using the 'dump' extension. $('td').comments().filter(":contains('This table snaps the content columns(one or two)')").dump(); returns; jQuery Object { 0 = DOMElement [ nodeName: DIV nodeValue: null innerHTML: [ 0 = String: This table snaps the content columns(one or two) ] ] } However I am not sure how to traverse to the sibling element in the DOM. This should be simple, but I haven't had much selector experience with JQuery. Any suggestions are appreciated.

    Read the article

  • Matab - Trace contour line between two different points

    - by Graham
    Hi, I have a set of points represented as a 2 row by n column matrix. These points make up a connected boundary or edge. I require a function that traces this contour from a start point P1 and stop at an end point P2. It also needs to be able trace the contour in a clockwise or anti-clockwise direction. I was wondering if this can be achieved by using some of matlabs functions. I have tried to write my own function but this was riddled with bugs and I have also tried using bwtraceboundary and indexing however this has problematic results as the points within the matrix are not in the order that create the contour. Thank you in advance for any help. Btw, I have included a link to a plot of the set of points. It is half the outline of a hand. The function would ideally trace the contour from ether the red star to the green triangle. Returning the points in order of traversal.

    Read the article

  • How do I find all paths through a set of given nodes in a DAG?

    - by Hanno Fietz
    I have a list of items (blue nodes below) which are categorized by the users of my application. The categories themselves can be grouped and categorized themselves. The resulting structure can be represented as a Directed Acyclic Graph (DAG) where the items are sinks at the bottom of the graph's topology and the top categories are sources. Note that while some of the categories might be well defined, a lot is going to be user defined and might be very messy. Example: On that structure, I want to perform the following operations: find all items (sinks) below a particular node (all items in Europe) find all paths (if any) that pass through all of a set of n nodes (all items sent via SMTP from example.com) find all nodes that lie below all of a set of nodes (intersection: goyish brown foods) The first seems quite straightforward: start at the node, follow all possible paths to the bottom and collect the items there. However, is there a faster approach? Remembering the nodes I already passed through probably helps avoiding unnecessary repetition, but are there more optimizations? How do I go about the second one? It seems that the first step would be to determine the height of each node in the set, as to determine at which one(s) to start and then find all paths below that which include the rest of the set. But is this the best (or even a good) approach? The graph traversal algorithms listed at Wikipedia all seem to be concerned with either finding a particular node or the shortest or otherwise most effective route between two nodes. I think both is not what I want, or did I just fail to see how this applies to my problem? Where else should I read?

    Read the article

  • Harvesting Dynamic HTTP Content to produce Replicating HTTP Static Content

    - by Neil Pitman
    I have a slowly evolving dynamic website served from J2EE. The response time and load capacity of the server are inadequate for client needs. Moreover, ad hoc requests can unexpectedly affect other services running on the same application server/database. I know the reasons and can't address them in the short term. I understand HTTP caching hints (expiry, etags....) and for the purpose of this question, please assume that I have maxed out the opportunities to reduce load. I am thinking of doing a brute force traversal of all URLs in the system to prime a cache and then copying the cache contents to geodispersed cache servers near the clients. I'm thinking of Squid or Apache HTTPD mod_disk_cache. I want to prime one copy and (manually) replicate the cache contents. I don't need a federation or intelligence amongst the slaves. When the data changes, invalidating the cache, I will refresh my master cache and update the slave versions, probably once a night. Has anyone done this? Is it a good idea? Are there other technologies that I should investigate? I can program this, but I would prefer a configuration of open source technologies solution Thanks

    Read the article

  • Getting Outlook calendar items based on subject

    - by EKS
    I'm trying to get a list of calendar objects from exchange and sorting them based on subject. The part of of getting the objects just based on date and sorting out via subject is in "code" is now working, but i want to do a sort on subject in the "sql" first, but im unable to make it work ( Currently getting error from exchange saying the query is wrong. The line I added is: + "AND lcase(\"urn:schemas:calendar:subject\") = 'onsite%' " What I want is the ability to catch all appointments that start with onsite, both in upper and lower case. strQuery = "<?xml version=\"1.0\"?>" + "<g:searchrequest xmlns:g=\"DAV:\">" + "<g:sql>SELECT \"urn:schemas:calendar:location\", \"urn:schemas:httpmail:subject\", " + "\"urn:schemas:calendar:dtstart\", \"urn:schemas:calendar:dtend\", " + "\"urn:schemas:calendar:busystatus\", \"urn:schemas:calendar:instancetype\" " + "FROM Scope('SHALLOW TRAVERSAL OF \"" + strCalendarURI + "\"') " + "WHERE NOT \"urn:schemas:calendar:instancetype\" = 1 " + "AND \"DAV:contentclass\" = 'urn:content-classes:appointment' " + "AND \"urn:schemas:calendar:dtstart\" > '2003/06/01 00:00:00' " //'" + DateString + "'" + "AND lcase(\"urn:schemas:calendar:subject\") = 'onsite' " + "ORDER BY \"urn:schemas:calendar:dtstart\" ASC" + "</g:sql></g:searchrequest>";

    Read the article

  • How should rules for Aggregate Roots be enforced?

    - by MylesRip
    While searching the web, I came across a list of rules from Eric Evans' book that should be enforced for aggregates: The root Entity has global identity and is ultimately responsible for checking invariants Root Entities have global identity. Entities inside the boundary have local identity, unique only within the Aggregate. Nothing outside the Aggregate boundary can hold a reference to anything inside, except to the root Entity. The root Entity can hand references to the internal Entities to other objects, but they can only use them transiently (within a single method or block). Only Aggregate Roots can be obtained directly with database queries. Everything else must be done through traversal. Objects within the Aggregate can hold references to other Aggregate roots. A delete operation must remove everything within the Aggregate boundary all at once When a change to any object within the Aggregate boundary is committed, all invariants of the whole Aggregate must be satisfied. This all seems fine in theory, but I don't see how these rules would be enforced in the real world. Take rule 3 for example. Once the root entity has given an exteral object a reference to an internal entity, what's to keep that external object from holding on to the reference beyond the single method or block? (If the enforcement of this is platform-specific, I would be interested in knowing how this would be enforced within a C#/.NET/NHibernate environment.)

    Read the article

  • How do I serialise a graph in Java without getting StackOverflowException?

    - by Tim Cooper
    I have a graph structure in java, ("graph" as in "edges and nodes") and I'm attempting to serialise it. However, I get "StackOverflowException", despite significantly increasing the JVM stack size. I did some googling, and apparently this is a well known limitation of java serialisation: that it doesn't work for deeply nested object graphs such as long linked lists - it uses a stack record for each link in the chain, and it doesn't do anything clever such as a breadth-first traversal, and therefore you very quickly get a stack overflow. The recommended solution is to customise the serialisation code by overriding readObject() and writeObject(), however this seems a little complex to me. (It may or may not be relevant, but I'm storing a bunch of fields on each edge in the graph so I have a class JuNode which contains a member ArrayList<JuEdge> links;, i.e. there are 2 classes involved, rather than plain object references from one node to another. It shouldn't matter for the purposes of the question). My question is threefold: (a) why don't the implementors of Java rectify this limitation or are they already working on it? (I can't believe I'm the first person to ever want to serialise a graph in java) (b) is there a better way? Is there some drop-in alternative to the default serialisation classes that does it in a cleverer way? (c) if my best option is to get my hands dirty with low-level code, does someone have an example of graph serialisation java source-code that can use to learn how to do it?

    Read the article

  • How to get the size of a binary tree ?

    - by Andrei Ciobanu
    I have a very simple binary tree structure, something like: struct nmbintree_s { unsigned int size; int (*cmp)(const void *e1, const void *e2); void (*destructor)(void *data); nmbintree_node *root; }; struct nmbintree_node_s { void *data; struct nmbintree_node_s *right; struct nmbintree_node_s *left; }; Sometimes i need to extract a 'tree' from another and i need to get the size to the 'extracted tree' in order to update the size of the initial 'tree' . I was thinking on two approaches: 1) Using a recursive function, something like: unsigned int nmbintree_size(struct nmbintree_node* node) { if (node==NULL) { return(0); } return( nmbintree_size(node->left) + nmbintree_size(node->right) + 1 ); } 2) A preorder / inorder / postorder traversal done in an iterative way (using stack / queue) + counting the nodes. What approach do you think is more 'memory failure proof' / performant ? Any other suggestions / tips ? NOTE: I am probably going to use this implementation in the future for small projects of mine. So I don't want to unexpectedly fail :).

    Read the article

  • c# - what approach can I use to extend a group of classes that include implemented methods? (see des

    - by Greg
    Hi, I want to create an extendible package I am writing that has Topology, Node & Relationship classes. The idea is these base classes would have the various methods in them necessary to base graph traversal methods etc. I would then like to be able to reuse this by extending the package. For example the base requirements might see Relationship with a parentNode & childNode. Topology would have a List of Nodes and List of Relationships. Topology would have methods like FindChildren(int depth). Then the usage would be to extend these such that additional attributes for Node and Relationships could be added etc. QUESTION - What would be the best approach to package & expose the base level classes/methods? (it's kind of like a custom collection but with multiple facets). Would the following concepts come into play: Interfaces - would this be a good idea to have ITopology, INode etc, or is this not required as the user would extend these classes anyway? Abstract Classes - would the base classes be abstract classes Custom Generic Collection - would some approach using this concept assist (but how would this work if there are the 3 different classes) thanks

    Read the article

  • Writing my own implementation of stl-like Iterator in C++.

    - by Negai
    Good evening everybody, I'm currently trying to understand the intrinsics of iterators in various languages i.e. the way they are implemented. For example, there is the following class exposing the list interface. template<class T> class List { public: virtual void Insert( int beforeIndex, const T item ) throw( ListException ) =0 ; virtual void Append( const T item ) =0; virtual T Get( int position ) const throw( ListException ) =0; virtual int GetLength() const =0; virtual void Remove( int position ) throw( ListException ) =0; virtual ~List() =0 {}; }; According to GoF, the best way to implement an iterator that can support different kinds of traversal is to create the base Iterator class (friend of List) with protected methods that can access List's members. The concrete implementations of Iterator will handle the job in different ways and access List's private and protected data through the base interface. From here forth things are getting confusing. Say, I have class LinkedList and ArrayList, both derived from List, and there are also corresponding iterators, each of the classes returns. How can I implement LinkedListIterator? I'm absolutely out of ideas. And what kind of data can the base iterator class retrieve from the List (which is a mere interface, while the implementations of all the derived classes differ significantly) ? Sorry for so much clutter. Thanks.

    Read the article

  • Dimensions of a collection, and how to traverse it in an efficient, elegant manner

    - by Bruce Ferguson
    I'm trying to find an elegant way to deal with multi-dimensional collections in Scala. My understanding is that I can have up to a 5 dimensional collection using tabulate, such as in the case of the following 2-Dimensional array: val test = Array.tabulate[Double](row,col)(_+_) and that I can access the elements of the array using for(i<-0 until row) { for(j<-0 until col) { test(i)(j) = 0.0 } } If I don't know a priori what I'm going to be handling, what might be a succinct way of determining the structure of the collection, and spanning it, without doing something like: case(Array(x)) => for(i<-1 until dim1) { test(i) = 0.0 } case(Array(x,y)) => for(i<-1 until dim1) { for(j<-1 until dim2) { test(i)(j) = 0.0 } } case(Array(x,y,z)) => ... The dimensional values n1, n2, n3, etc... are private, right? Also, would one use the same trick of unwrapping a 2-D array into a 1-D vector when dealing with n-Dimensional objects if I want a single case to handle the traversal? Thanks in advance Bruce

    Read the article

  • Simple Oracle File repository with folder hierarchy

    - by Ope
    I have an application that stores large amount of files (XML and binary) in folder hierarchies. Currently the main method is storing them in file system or using a legacy CMS, which we want to get rid of. The CMS supports Oracle and a customer wants to keep the files in Oracle because of enterprise policies (backup etc.) The question is: Is there a simple implementation of file repository with folder hierarchy for Oracle? What I am looking for is a small .Net component or example code (PL/SQL and/or .Net) that would have the following methods: Create, Delete, Exists Folder CRUD file Move and potentially Copy file or directory Access to files and folders with paths like "/root/folder1/folder2/file.xml" Ability to get all the files and folders in a folder and potentially also the entire directory tree Tree traversal, getting the parent, all children etc. needs to be fast. I need the implementation in .Net, but if it was just the stored procedures, I could create the .Net calling code. I have pointers to generic articles for creating hierarchies in DB, so if I need to do it from scratch, I know where to start. What I am asking here, is there already an implementation that I could take without doing this from scratch? It seems like such a generic requirement... If the answer is a CMS, Document management system or such it should be Open Source or at least quite cheap (some hundreds / server) and it should be possible to deploy it XCopy - hopefully only couple of DLL:s. I do not need - or want - a full featured big CMS with dozens of dlls and especially not an msi-installation. I have tried to google this, but the words "repository", "CMS", "file hierarchy" etc. give so many answers, the searches are pretty much useless. Thanks, OPe

    Read the article

  • AutoMapper strings to enum descriptions

    - by 6footunder
    Given the requirement: Take an object graph, set all enum type properties based on the processed value of a second string property. Convention dictates that the name of the source string property will be that of the enum property with a postfix of "Raw". By processed we mean we'll need to strip specified characters e.t.c. I've looked at custom formatters, value resolvers and type converters, none of which seems like a solution for this? We want to use AutoMapper as opposed to our own reflection routine for two reasons, a) it's used extensively throughout the rest of the project and b) it gives you recursive traversal ootb. -- Example -- Given the (simple) structure below, and this: var tmp = new SimpleClass { CountryRaw = "United States", Person = new Person { GenderRaw="Male" } }; var tmp2 = new SimpleClass(); Mapper.Map(tmp, tmp2); we'd expect tmp2's MappedCountry enum to be Country.UnitedStates and the Person property to have a gender of Gender.Male. public class SimpleClass1 { public string CountryRaw {get;set;} public Country MappedCountry {get;set;} public Person Person {get;set;} } public class Person { public string GenderRaw {get;set;} public Gender Gender {get;set;} public string Surname {get;set;} } public enum Country { UnitedStates = 1, NewZealand = 2 } public enum Gender { Male, Female, Unknown } Thanks

    Read the article

  • Script to check a shared Exchange calendar and then email detail

    - by SJN
    We're running Server and Exchange 2003 here. There's a shared calendar which HR keep up-to-date detailing staff who are on leave. I'm looking for a VB Script (or alternate) which will extract the "appointment" titles of each item for the current day and then email the detail to a mail group, in doing so notifying the group with regard to which staff are on leave for the day. The resulting email body should be: Staff on leave today: Mike Davis James Stead @Paul Robichaux - ADO is the way I went for this in the end, here are the key component for those interested: Dim Rs, Conn, Url, Username, Password, Recipient Set Rs = CreateObject("ADODB.Recordset") Set Conn = CreateObject("ADODB.Connection") 'Configurable variables Username = "Domain\username" ' AD domain\username Password = "password" ' AD password Url = "file://./backofficestorage/domain.com/MBX/username/Calendar" 'path to user's mailbox and folder Recipient = "[email protected]" Conn.Provider = "ExOLEDB.DataSource" Conn.Open Url, Username, Password Set Rs.ActiveConnection = Conn Rs.Source = "SELECT ""DAV:href"", " & _ " ""urn:schemas:httpmail:subject"", " & _ " ""urn:schemas:calendar:dtstart"", " & _ " ""urn:schemas:calendar:dtend"" " & _ "FROM scope('shallow traversal of """"') " Rs.Open Rs.MoveFirst strOutput = "" Do Until Rs.EOF If DateDiff("s", Rs.Fields("urn:schemas:calendar:dtstart"), date) >= 0 And DateDiff("s", Rs.Fields("urn:schemas:calendar:dtend"), date) < 0 Then strOutput = strOutput & "<p><font size='2' color='black' face='verdana'><b>" & Rs.Fields("urn:schemas:httpmail:subject") & "</b><br />" & vbCrLf strOutput = strOutput & "<b>From: </b>" & Rs.Fields("urn:schemas:calendar:dtstart") & vbCrLf strOutput = strOutput & "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>To: </b>" & Rs.Fields("urn:schemas:calendar:dtend") & "<br /><br />" & vbCrLf End If Rs.MoveNext Loop Conn.Close Set Conn = Nothing Set Rec = Nothing After that, you can do what you like with srtOutput, I happened to use CDO to send an email: Set objMessage = CreateObject("CDO.Message") objMessage.Subject = "Subject" objMessage.From = "[email protected]" objMessage.To = Recipient objMessage.HTMLBody = strOutput objMessage.Send S

    Read the article

  • CQRS - Benefits

    - by Dylan Smith
    Thanks to all the comments and feedback from the last post I think I have a better understanding now of the benefits of CQRS (separate from the benefits of Event Sourcing). I’m going to try and sum it up here, and point out some areas where I could still use some advice: CQRS Benefits Sounds like the primary benefit of CQRS as an architecture is it allows you to create a simpler domain model by sucking out everything related to queries. I can definitely see the benefit to this, in general the domain logic related to commands is the high-value behavior in the software, but the logic required to service the queries would add a lot of low-value “noise” to the domain model that would dilute the high-value (command) behavior – sorting, paging, filtering, pre-fetch paths, etc. Also the most appropriate domain structure for implementing commands might not be the most optimal for implementing queries. To paraphrase Greg, this usually results in a domain model that is mediocre at both, piss-poor at one, or more likely piss-poor at both commands and queries. Not only will you be able to simplify your domain model by pulling out all the query logic, but at least a handful of commands in most systems will probably be “pass-though” type commands with little to no logic that just generate events. If these can be implemented directly in the command-handler and never touch the domain model, this allows you to slim down the domain model even more. Also, if you were to do event sourcing without CQRS, you no longer have a database containing the current state (only the domain model would) which makes it difficult (or impossible) to support ad-hoc querying and/or reporting that is common in most business software. Of course CQRS provides some great scalability benefits, not only scalability but I have to assume that it provides extremely low latency for most operations, especially if you have an asynchronous event bus. I know Greg says that you get a 3x scaling (Commands, Queries, Client) of your ability to perform parallel development, but IMHO, it seems like it only provides 1.5x scaling since even without CQRS you’re going to have your client loosely coupled to your domain - which is still a great benefit to be able to realize. Questions / Concerns If all the queries against an aggregate get pulled out to the Query layer, what if the only commands for that aggregate can be handled in a “pass-through” manner with the command handler directly generating events. Is it possible to have an aggregate that isn’t modeled in the domain model? Are there any issues or downsides to this? I know in the feedback from my previous posts it was suggested that having one domain model handling both commands and queries requires implementing a lot of traversals between objects that wouldn’t be necessary if it was only servicing commands. My question is, do you include traversals in your domain model based on the needs of the code, or based on the conceptual domain model? If none of my Commands require a Customer.Orders traversal, but the conceptual domain includes the concept of a set of orders belonging to a customer – should I model that in my domain model or not? I like the idea of using the Query side of the architecture as a place to put junior devs where the risk of them screwing something up has minimal impact. But I’m not sold on the idea that you can actually outsource it. Like I said in one of my comments on my previous post, the code to handle a query and generate DTO’s is going to be dead simple, but the code to process events and apply them to the tables on the query side is going to require a significant amount of domain knowledge to know which events to listen for to update each of the de-normalized tables (and what changes need to be made when each event is processed). I don’t know about everybody else, but having Indian/Russian/whatever outsourced developers have to do anything that requires significant domain knowledge has never been successful in my experience. And if you need to spec out for each new query which events to listen to and what to do with each one, well that’s probably going to be just as much work to document as it would be to just implement it. Greg made the point in a comment that doing an aggregate query like “Total Sales By Customer” is going to be inefficient if you use event sourcing but not CQRS. I don’t understand why that would be the case. I imagine in that case you’d simply have a method/property on the Customer object that calculated total sales for that customer by enumerating over the Orders collection. Then the application services layer would generate DTO’s off of the Customers collection that included say the CustomerID, CustomerName, TotalSales, or whatever the case may be. As long as you use a snapshotting implementation, I don’t see why that would be anymore inefficient in a DDD+Event Sourcing implementation than in a typical DDD implementation. Like I mentioned in my last post I still have some questions about query logic that haven’t been answered yet, but before I start asking those I want to make sure I have a strong grasp on what benefits CQRS provides.  My main concern with the query logic was that I know I could just toss it all into the query side, but I was concerned that I would be losing the benefits of using CQRS in the first place if I did that.  I want to elaborate more on this though with some example situations in an upcoming post.

    Read the article

  • Vacations on Rodrigues 2014

    And now something completely different compared to the usual technical or community related articles here on this blog. Yes, this time I'm writing some lines on my (and my family's) activities during our long weekend stay on Rodrigues. So, please bear with me, it's eventually a bit more personal... Grab a soda, some popcorn and a cosy place to continue to read. var googleAlbumLink = "https://plus.google.com/photos/117698191428446859536/albums/6047895311458281985"; //optional----------------------- var mySlideWidth = 580; var mySlideHeight = 340; var mySlideDelay = 7000; //delay in milliseconds Special promotions during school holidays Originally, our children started to ask more frequently about going on the plane again. Obviously, after their aunty from Germany was around during May, they were really eager to travel again. So, we decided that it might be a great opportunity to book some vacations during their school holidays. And just in time the local hotels and hotel groups started to advertise their special promotions for citizens and residents. After collecting multiple brochures over several days, we got attracted by various hotel packages on Rodrigues - most interestingly the expenses for the stay and flight ticket were less compared to other resorts here on the main island. As we have been to Rodrigues already back in 2008, we followed up on this idea and got in touch with a couple travel agencies. Well, I have to report that you should be really careful about the promotions from some of them. We had a very negative experience with Shamal Travel Agency in Quatre Bornes regarding their adverts and the actual price levels and age definition for children. Please, stay away from them if you are interested in transparent cost and services. Anyway, after some arrangements with two other close families we managed to confirm our stay at the Cotton Bay Hotel in Rodrigues. Given the fact that we already stayed there, and the hotel has been renovated recently, and it is under new management all looked very promising and relaxed for our vacation. Counting the days... As we already booked in July our children were counting down the days. And it got more interesting as soon as they were on school holidays finally. Well, the day arrived and waking them up at 2:30 hrs wasn't a problem after all. Quite the opposite it was fascinating for us parents to watch them waiting for the transport and later on during the airport transfer. Despite the early hours both didn't fall asleep and it was all so exciting. We are taking the plane! Well organised by the Cotton Bay Hotel Honestly, it was a breeze and a smooth ride during our stay at the hotel. From the airport transfer, the cleanliness of our bungalow, the organisation of our day trips, and the SPA - all very well and enjoyable. The children had great fun, and although it was a bit too windy to plunge into the pool they had a lot of fun with other activities on the beach and at the Kid's Club. Oh, and we had our private petting zoo with cows, sheep and goats just close to the terrace. Some of us went to check out the SPA facilities and I have to admit that the services regarding Hammam and Sauna are better than at some other hotels in Mauritius. I don't know after how many months or years I was once again enjoying a very hot sauna. Little draw-back but nothing to worry about... There is no cold water or at least ice cubes to cool down the body, but hey there was a nice breeze coming over the hills. Some day trips to mention Based on a friend's recommendation we walked to a "restaurant" called Chez Solange & Robert. Hahaha, restaurant is widely stretched in this case, as we enjoyed a great BBQ with fresh lobster, whole fish, and pieces of chicken breast in an open cottage. Just some wooden structure covered with dried palm leaves on the roof - island feeling pure! The other day we went to the Giant Tortoise & Cave Reserve Francois Leguat to observe the giant Aldabra turtles and to visit the Grande Caverne. The biggest limestone cave on the island. Compared to our last visit this was a novelty after checking out the Caverne Partate. The formations of stalactites and stalagmites are very impressive and imaginative. Our guide had lots of funny terms and despite the low light conditions the kids had a great time wandering around on the narrow wooden paths and stairs. And last but not least, we decided to check out the Tyrodrig zip lines... Everyone was allowed to join the trip through the air, and our little ones stayed close to our field guides. But finally went on their own on the very last traversal. Puuuh, it was astounishing to glide over the valley, and for sure something to repeat next time. Impressions of our vacation on Rodrigues 2014   Next stay has been discussed already Oh yes, Rodrigues baby! We are going to come again! Tentative dates have been discussed already and now it's up to us to earn enough our next holiday on that wonderful remote piece of paradise. Eventually, a little bit longer than this time. We'll see...

    Read the article

< Previous Page | 4 5 6 7 8 9  | Next Page >