Search Results

Search found 441 results on 18 pages for 'nearest neighbor'.

Page 2/18 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • PHP Round Minute to nearest Quarter Hour

    - by Rob
    I need to round times down to the nearest quarter hour in PHP. The times are being pulled from a MySQL database from a datetime column and formatted like 2010-03-18 10:50:00. Example: 10:50 needs to be 10:45 1:12 needs to be 1:00 3:28 needs to be 3:15 etc. I'm assuming floor() is involved but not sure how to go about it. Thanks

    Read the article

  • Round prices up to nearest 5 after conversion in oscommerce

    - by Rhyso
    Hi there, A conversion question relating to prices in oscommerce: I am needing for a custom currency conversion to round the USD prices up to the nearest 5$ to avoid prices being displayed at silly prices such as $263. I am trying to convert to an int and round the following line : $curr-display_price($listing['products_price'], tep_get_tax_rate($listing['products_tax_class_id'])); ( as for some reason the price is displayed as a string, im guessing to include the currency sign) However not having much luck. Does anybody know where the root conversion takes place as it might be easier for me to round() or ceil() from there when it is a raw integer Or any other ideas of how I can round the conversion? Thanks for any help Rhys Thomas

    Read the article

  • SSRS Issue: Rounding to nearest .25

    - by D.R.
    I have an SSRS (2008) report that takes in a raw transactions, then groups and totals them. At the "Total" level, I would like to round the final numbers to the nearest .25, however I cannot find a method to do this. According to what I've read, the Round() function in SSRS only rounds to integers. I have found a couple ways to do it in SQL, but the problem is, I want to do all the calculations with the REAL numbers and just round the result so that I don't introduce a significant amount of error from the real numbers. Here's the best SQL solution I could find: dec(round(number * 4, 0)/4,11,2) as Nearest_Qtr Anyone know how I could do the equivalent in the actual SSRS report? Thanks in advance for the help!

    Read the article

  • help implementing All Nearest Smaller Values algorithm

    - by davit-datuashvili
    http://en.wikipedia.org/wiki/All_nearest_smaller_values this is site of the problem and here is my code but i have some trouble to implement it import java.util.*; public class stack{ public static void main(String[]args){ int x[]=new int[]{ 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 }; Stack<Integer> st=new Stack<Integer>(); for (int a:x){ while (!st.empty() && st.pop()>=a){ System.out.println( st.pop()); if (st.empty()){ break; } else{ st.push(a); } } } } } and here is pseudo code from site S = new empty stack data structure for x in the input sequence: while S is nonempty and the top element of S is greater than or equal to x: pop S if S is empty: x has no preceding smaller value else: the nearest smaller value to x is the top element of S push x onto S

    Read the article

  • Round time to 5 minute nearest SQL Server

    - by Drako
    i don't know if it can be usefull to somebody but I went crazy looking for a solution and ended up doing it myself. Here is a function that (according to a date passed as parameter), returns the same date and approximate time to the nearest multiple of 5. It is a slow query, so if anyone has a better solution, it is welcome. A greeting. CREATE FUNCTION [dbo].[RoundTime] (@Time DATETIME) RETURNS DATETIME AS BEGIN DECLARE @min nvarchar(50) DECLARE @val int DECLARE @hour int DECLARE @temp int DECLARE @day datetime DECLARE @date datetime SET @date = CONVERT(DATETIME, @Time, 120) SET @day = (select DATEADD(dd, 0, DATEDIFF(dd, 0, @date))) SET @hour = (select datepart(hour,@date)) SET @min = (select datepart(minute,@date)) IF LEN(@min) > 1 BEGIN SET @val = CAST(substring(@min, 2, 1) as int) END else BEGIN SET @val = CAST(substring(@min, 1, 1) as int) END IF @val <= 2 BEGIN SET @val = CAST(CAST(@min as int) - @val as int) END else BEGIN IF (@val <> 5) BEGIN SET @temp = 5 - CAST(@min%5 as int) SET @val = CAST(CAST(@min as int) + @temp as int) END IF (@val = 60) BEGIN SET @val = 0 SET @hour = @hour + 1 END IF (@hour = 24) BEGIN SET @day = DATEADD(day,1,@day) SET @hour = 0 SET @min = 0 END END RETURN CONVERT(datetime, CAST(DATEPART(YYYY, @day) as nvarchar) + '-' + CAST(DATEPART(MM, @day) as nvarchar) + '-' + CAST(DATEPART(dd, @day) as nvarchar) + ' ' + CAST(@hour as nvarchar) + ':' + CAST(@val as nvarchar), 120) END

    Read the article

  • c# find nearest match to array of doubles

    - by Scott
    Given the code below, how do I compare a List of objects's values with a test value? I'm building a geolocation application. I'll be passing in longitude and latitude and would like to have the service answer back with the location closest to those values. I started down the path of converting to a string, and formatting the values down to two decimal places, but that seemed a bit too ghetto, and I'm looking for a more elegant solution. Any help would be great. Thanks, Scott public class Location : IEnumerable { public string label { get; set; } public double lat { get; set; } public double lon { get; set; } //Implement IEnumerable public IEnumerator GetEnumerator() { return (IEnumerator)this; } } [HandleError] public class HomeController : Controller { private List<Location> myList = new List<Location> { new Location { label="Atlanta Midtown", lon=33.657674, lat=-84.423130}, new Location { label="Atlanta Airport", lon=33.794151, lat=-84.387228}, new Location { label="Stamford, CT", lon=41.053758, lat=-73.530979}, ... } public static int Main(String[] args) { string inLat = "-80.987654"; double dblInLat = double.Parse(inLat); // here's where I would like to find the closest location to the inLat // once I figure out this, I'll implement the Longitude, and I'll be set }

    Read the article

  • Calculating Nearest Match to Mean/Stddev Pair With LibSVM

    - by Chris S
    I'm new to SVMs, and I'm trying to use the Python interface to libsvm to classify a sample containing a mean and stddev. However, I'm getting nonsensical results. Is this task inappropriate for SVMs or is there an error in my use of libsvm? Below is the simple Python script I'm using to test: #!/usr/bin/env python # Simple classifier test. # Adapted from the svm_test.py file included in the standard libsvm distribution. from collections import defaultdict from svm import * # Define our sparse data formatted training and testing sets. labels = [1,2,3,4] train = [ # key: 0=mean, 1=stddev {0:2.5,1:3.5}, {0:5,1:1.2}, {0:7,1:3.3}, {0:10.3,1:0.3}, ] problem = svm_problem(labels, train) test = [ ({0:3, 1:3.11},1), ({0:7.3,1:3.1},3), ({0:7,1:3.3},3), ({0:9.8,1:0.5},4), ] # Test classifiers. kernels = [LINEAR, POLY, RBF] kname = ['linear','polynomial','rbf'] correct = defaultdict(int) for kn,kt in zip(kname,kernels): print kt param = svm_parameter(kernel_type = kt, C=10, probability = 1) model = svm_model(problem, param) for test_sample,correct_label in test: pred_label, pred_probability = model.predict_probability(test_sample) correct[kn] += pred_label == correct_label # Show results. print '-'*80 print 'Accuracy:' for kn,correct_count in correct.iteritems(): print '\t',kn, '%.6f (%i of %i)' % (correct_count/float(len(test)), correct_count, len(test)) The domain seems fairly simple. I'd expect that if it's trained to know a mean of 2.5 means label 1, then when it sees a mean of 2.4, it should return label 1 as the most likely classification. However, each kernel has an accuracy of 0%. Why is this? On a side note, is there a way to hide all the verbose training output dumped by libsvm in the terminal? I've searched libsvm's docs and code, but I can't find any way to turn this off.

    Read the article

  • Google maps nearest points avoiding rivers / by itinerary

    - by Karl Lacroix
    Here is the deal : I need to find the closest points from a point with a radius. For example, I need to get all the points in a 15 km radius. Thats easy with Google Maps Radius and all the examples on the web ;) The problem is that from my office, a point is under the 15km radius, but it's on the other side of a river, so the car itinerary is about 30 km (using a bridge)! Is there a simple solution to exclude those points or to calculate by intineraries ? I supposed that I'll need to calculate all itineraries with returned points? DirectionsRequest API? Thanks! :)

    Read the article

  • REGEX to extract word connected to nearest semicolon?

    - by John Kaybern
    I'm attempting to extract a series of data values from a text file. The values are in the format: <MODIFIER NAME1 VALUE; MODIFIER NAME2 VALUE;> For the purposes of the current task that I have, I only care about extracting the VALUE that is situated next to each semicolon. What would the REGEX command look like that would isolate each of these VALUES (preferably so that I backreference all values in the replacement part of my processing.) I believe that ^(.*?); is somehow used, but I'm not seeing how to isolate only the word that is attached to the semicolon in a group for backreference use. Thanks!

    Read the article

  • find nearest match to array of doubles

    - by Scott
    Given the code below, how do I compare a List of objects's values with a test value? I'm building a geolocation application. I'll be passing in longitude and latitude and would like to have the service answer back with the location closest to those values. I started down the path of converting to a string, and formatting the values down to two decimal places, but that seemed a bit too ghetto, and I'm looking for a more elegant solution. public class Location : IEnumerable { public string label { get; set; } public double lat { get; set; } public double lon { get; set; } //Implement IEnumerable public IEnumerator GetEnumerator() { return (IEnumerator)this; } } [HandleError] public class HomeController : Controller { private List<Location> myList = new List<Location> { new Location { label="Atlanta Midtown", lon=33.657674, lat=-84.423130}, new Location { label="Atlanta Airport", lon=33.794151, lat=-84.387228}, new Location { label="Stamford, CT", lon=41.053758, lat=-73.530979}, ... } public static int Main(String[] args) { string inLat = "-80.987654"; double dblInLat = double.Parse(inLat); // here's where I would like to find the closest location to the inLat // once I figure out this, I'll implement the Longitude, and I'll be set }

    Read the article

  • xpath nearest element to a given element

    - by nologo
    hi, having trouble returning an element using xpath.. i need to get the text from the 2nd TD.. <tr> <td> <label for="PropertyA">Some text here </label> </td> <td> TEXT!! </td> </tr> i'm able to find the label element but then im having trouble selecting the td following to return the text. this is how i select the label: "//label[@for='PropertyA']" thanks

    Read the article

  • Wikipedia A* pathfinding algorithm takes a lot of time

    - by Vee
    I've successfully implemented A* pathfinding in C# but it is very slow, and I don't understand why. I even tried not sorting the openNodes list but it's still the same. The map is 80x80, and there are 10-11 nodes. I took the pseudocode from here Wikipedia And this is my implementation: public static List<PGNode> Pathfind(PGMap mMap, PGNode mStart, PGNode mEnd) { mMap.ClearNodes(); mMap.GetTile(mStart.X, mStart.Y).Value = 0; mMap.GetTile(mEnd.X, mEnd.Y).Value = 0; List<PGNode> openNodes = new List<PGNode>(); List<PGNode> closedNodes = new List<PGNode>(); List<PGNode> solutionNodes = new List<PGNode>(); mStart.G = 0; mStart.H = GetManhattanHeuristic(mStart, mEnd); solutionNodes.Add(mStart); solutionNodes.Add(mEnd); openNodes.Add(mStart); // 1) Add the starting square (or node) to the open list. while (openNodes.Count > 0) // 2) Repeat the following: { openNodes.Sort((p1, p2) => p1.F.CompareTo(p2.F)); PGNode current = openNodes[0]; // a) We refer to this as the current square.) if (current == mEnd) { while (current != null) { solutionNodes.Add(current); current = current.Parent; } return solutionNodes; } openNodes.Remove(current); closedNodes.Add(current); // b) Switch it to the closed list. List<PGNode> neighborNodes = current.GetNeighborNodes(); double cost = 0; bool isCostBetter = false; for (int i = 0; i < neighborNodes.Count; i++) { PGNode neighbor = neighborNodes[i]; cost = current.G + 10; isCostBetter = false; if (neighbor.Passable == false || closedNodes.Contains(neighbor)) continue; // If it is not walkable or if it is on the closed list, ignore it. if (openNodes.Contains(neighbor) == false) { openNodes.Add(neighbor); // If it isn’t on the open list, add it to the open list. isCostBetter = true; } else if (cost < neighbor.G) { isCostBetter = true; } if (isCostBetter) { neighbor.Parent = current; // Make the current square the parent of this square. neighbor.G = cost; neighbor.H = GetManhattanHeuristic(current, neighbor); } } } return null; } Here's the heuristic I'm using: private static double GetManhattanHeuristic(PGNode mStart, PGNode mEnd) { return Math.Abs(mStart.X - mEnd.X) + Math.Abs(mStart.Y - mEnd.Y); } What am I doing wrong? It's an entire day I keep looking at the same code.

    Read the article

  • MPLS basic configuration

    - by Vineet Menon
    I want to test out MPLS VPN in my lab. I have 3 routers. 2 PEs and 1P router, all cisco 2921. Something like this, ----- ---- ----- | PE1 |.1____192.168.1.0____.2| P |.2____192.168.2.0____.1| PE2 | | | | | | | ----- ---- ----- lo0:10.1.1.1 lo0:10.1.1.2 lo0:10.1.1.3 Here's the configuration file for each of them, PE1 router hostname PE1 ! no ipv6 cef ip source-route ip cef ! ! ! ip vrf cust1 rd 100:100 route-target export 100:100 route-target import 100:100 ! ! interface Loopback0 ip address 10.1.1.1 255.255.255.255 ! interface GigabitEthernet0/0 ip address 192.168.1.1 255.255.255.0 duplex auto speed auto ! interface GigabitEthernet0/1 ip vrf forwarding cust1 ip address 172.16.1.1 255.255.255.0 duplex auto speed auto ! router ospf 1 network 10.1.1.1 0.0.0.0 area 0 network 192.168.1.0 0.0.0.255 area 0 ! router bgp 100 bgp log-neighbor-changes neighbor 10.1.1.3 remote-as 100 neighbor 10.1.1.3 update-source Loopback0 neighbor 172.16.1.2 remote-as 65001 ! address-family vpnv4 neighbor 10.1.1.3 activate neighbor 10.1.1.3 send-community extended exit-address-family For P router: hostname P ! no ipv6 cef ip source-route ip cef ! interface Loopback0 ip address 10.1.1.2 255.255.255.255 ! interface GigabitEthernet0/1 ip address 192.168.1.2 255.255.255.0 duplex auto speed auto ! interface GigabitEthernet0/2 ip address 192.168.2.2 255.255.255.0 duplex auto speed auto ! router ospf 1 network 10.1.1.2 0.0.0.0 area 0 network 192.168.1.0 0.0.0.255 area 0 network 192.168.2.0 0.0.0.255 area 0 ! For PE2 router: ! hostname PE2 ! no ipv6 cef ip source-route ip cef ! ! ! ip vrf cust1 rd 100:100 route-target export 100:100 route-target import 100:100 ! ! ! interface Loopback0 ip address 10.1.1.3 255.255.255.0 ! interface GigabitEthernet0/0 ip address 192.168.2.1 255.255.255.0 duplex auto speed auto ! interface GigabitEthernet0/1 ip vrf forwarding cust1 ip address 172.16.2.1 255.255.255.0 duplex auto speed auto ! router ospf 1 network 10.1.1.3 0.0.0.0 area 0 network 192.168.2.0 0.0.0.255 area 0 ! router bgp 100 bgp log-neighbor-changes neighbor 10.1.1.1 remote-as 100 neighbor 10.1.1.1 update-source Loopback0 neighbor 172.16.2.2 remote-as 65001 ! address-family vpnv4 neighbor 10.1.1.1 activate neighbor 10.1.1.1 send-community extended exit-address-family ! I am following this article form cisco. But things are not working properly. Any help would be appreciated.

    Read the article

  • Should I always be checking every neighbor when building voxel meshes?

    - by Raven Dreamer
    I've been playing around with Unity3d, seeing if I can make a voxel-based engine out of it (a la Castle Story, or Minecraft). I've dynamically built a mesh from a volume of cubes, and now I'm looking into reducing the number of vertices built into each mesh, as right now, I'm "rendering" vertices and triangles for cubes that are fully hidden within the larger voxel volume. The simple solution is to check each of the 6 directions for each cube, and only add the face to the mesh if the neighboring voxel in that direction is "empty". Parsing a voxel volume is BigO(N^3), and checking the 6 neighbors keeps it BigO(7*N^3)-BigO(N^3). The one thing this results in is a lot of redundant calls, as the same voxel will be polled up to 7 times, just to build the mesh. My question, then, is: Is there a way to parse a cubic volume (and find which faces have neighbors) with fewer redundant calls? And perhaps more importantly, does it matter (as BigO complexity is the same in both cases)?

    Read the article

  • How do I optimize searching for the nearest point?

    - by Rootosaurus
    For a little project of mine I'm trying to implement a space colonization algorithm in order to grow trees. The current implementation of this algorithm works fine. But I have to optimize the whole thing in order to make it generate faster. I work with 1 to 300K of random attraction points to generate one tree, and it takes a lot of time to compute and compare distances between attraction points and tree node in order to keep only the closest treenode for an attraction point. So I was wondering if some solutions exist (I know they must exist) in order to avoid the time loss looping on each tree node for each attraction point to find the closest... and so on until the tree is finished.

    Read the article

  • System.InvalidOperationException in Output Window

    - by user318068
    I constantly get the following message in my output/debug windows. The app doesn't crash but I was wondering what the deal with it is: A first chance exception of type 'System.InvalidOperationException' occurred in System.dll my code :sol.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Sol { public LinkedList<int> tower1 = new LinkedList<int>(); public LinkedList<int> tower2 = new LinkedList<int>(); public LinkedList<int> tower3 = new LinkedList<int>(); public static LinkedList<string> BFS = new LinkedList<string>(); public static LinkedList<string> DFS = new LinkedList<string>(); public static LinkedList<string> IDS = new LinkedList<string>(); public int depth; public LinkedList<Sol> neighbors; public Sol() { } public Sol(LinkedList<int> tower1, LinkedList<int> tower2, LinkedList<int> tower3) { this.tower1 = tower1; this.tower2 = tower2; this.tower3 = tower3; neighbors = new LinkedList<Sol>(); } public virtual void getneighbors() { Sol temp = this.copy(); Sol neighbor1 = this.copy(); Sol neighbor2 = this.copy(); Sol neighbor3 = this.copy(); Sol neighbor4 = this.copy(); Sol neighbor5 = this.copy(); Sol neighbor6 = this.copy(); if (temp.tower1.Count != 0) { if (neighbor1.tower2.Count != 0) { if (neighbor1.tower1.First.Value < neighbor1.tower2.First.Value) { neighbor1.tower2.AddFirst(neighbor1.tower1.First); neighbor1.tower1.RemoveFirst(); neighbors.AddLast(neighbor1); } } else { neighbor1.tower2.AddFirst(neighbor1.tower1.First); neighbor1.tower1.RemoveFirst(); neighbors.AddLast(neighbor1); } if (neighbor2.tower3.Count != 0) { if (neighbor2.tower1.First.Value < neighbor2.tower3.First.Value) { neighbor2.tower3.AddFirst(neighbor2.tower1.First); neighbor2.tower1.RemoveFirst(); neighbors.AddLast(neighbor2); } } else { neighbor2.tower3.AddFirst(neighbor2.tower1.First); neighbor2.tower1.RemoveFirst(); neighbors.AddLast(neighbor2); } } //------------- if (temp.tower2.Count != 0) { if (neighbor3.tower1.Count != 0) { if (neighbor3.tower2.First.Value < neighbor3.tower1.First.Value) { neighbor3.tower1.AddFirst(neighbor3.tower2.First); neighbor3.tower2.RemoveFirst(); neighbors.AddLast(neighbor3); } } else { neighbor3.tower1.AddFirst(neighbor3.tower2.First); neighbor3.tower2.RemoveFirst(); neighbors.AddLast(neighbor3); } if (neighbor4.tower3.Count != 0) { if (neighbor4.tower2.First.Value < neighbor4.tower3.First.Value) { neighbor4.tower3.AddFirst(neighbor4.tower2.First); neighbor4.tower2.RemoveFirst(); neighbors.AddLast(neighbor4); } } else { neighbor4.tower3.AddFirst(neighbor4.tower2.First); neighbor4.tower2.RemoveFirst(); neighbors.AddLast(neighbor4); } } //------------------------ if (temp.tower3.Count() != 0) { if (neighbor5.tower1.Count() != 0) { if (neighbor5.tower3.ElementAtOrDefault(0) < neighbor5.tower1.ElementAtOrDefault(0)) { neighbor5.tower1.AddFirst(neighbor5.tower3.First); neighbor5.tower3.RemoveFirst(); neighbors.AddLast(neighbor5); } } else { neighbor5.tower1.AddFirst(neighbor5.tower3.First); neighbor5.tower3.RemoveFirst(); neighbors.AddLast(neighbor5); } if (neighbor6.tower2.Count() != 0) { if (neighbor6.tower3.ElementAtOrDefault(0) < neighbor6.tower2.ElementAtOrDefault(0)) { neighbor6.tower2.AddFirst(neighbor6.tower3.First); neighbor6.tower3.RemoveFirst(); neighbors.AddLast(neighbor6); } } else { neighbor6.tower2.AddFirst(neighbor6.tower3.First); neighbor6.tower3.RemoveFirst(); neighbors.AddLast(neighbor6); } } } public override string ToString() { string str; str = "tower1" + tower1.ToString() + " tower2" + tower2.ToString() + " tower3" + tower3.ToString(); return str; } public Sol copy() { Sol So; LinkedList<int> l1 = new LinkedList<int>(); LinkedList<int> l2 = new LinkedList<int>(); LinkedList<int> l3 = new LinkedList<int>(); for (int i = 0; i <= this.tower1.Count() - 1; i++) { l1.AddLast(tower1.ElementAt(i)); } for (int i = 0; i <= this.tower2.Count - 1; i++) { l2.AddLast(tower2.ElementAt(i)); } for (int i = 0; i <= this.tower3.Count - 1; i++) { l3.AddLast(tower3.ElementAt(i)); } So = new Sol(l1, l2, l3); return So; } public bool Equals(Sol sol) { if (this.tower1.Equals(sol.tower1) & this.tower2.Equals(sol.tower2) & this.tower3.Equals(sol.tower3)) return true; return false; } public virtual bool containedin(Stack<Sol> vec) { bool found = false; for (int i = 0; i <= vec.Count - 1; i++) { if (vec.ElementAt(i).tower1.Equals(this.tower1) && vec.ElementAt(i).tower2.Equals(this.tower2) && vec.ElementAt(i).tower3.Equals(this.tower3)) { found = true; break; } } return found; } public virtual bool breadthFirst(Sol start, Sol goal) { Stack<Sol> nextStack = new Stack<Sol>(); Stack<Sol> traversed = new Stack<Sol>(); bool found = false; start.depth = 0; nextStack.Push(start); while (nextStack.Count != 0) { Sol sol = nextStack.Pop(); BFS.AddFirst("poped State:" + sol.ToString() + "level " + sol.depth); traversed.Push(sol); if (sol.Equals(goal)) { found = true; BFS.AddFirst("Goal:" + sol.ToString()); break; } else { sol.getneighbors(); foreach (Sol neighbor in sol.neighbors) { if (!neighbor.containedin(traversed) && !neighbor.containedin(nextStack)) { neighbor.depth = (sol.depth + 1); nextStack.Push(neighbor); } } } } return found; } public virtual bool depthFirst(Sol start, Sol goal) { Stack<Sol> nextStack = new Stack<Sol>(); Stack<Sol> traversed = new Stack<Sol>(); bool found = false; start.depth = 0; nextStack.Push(start); while (nextStack.Count != 0) { //Dequeue next State for comparison //And add it 2 list of traversed States Sol sol = nextStack.Pop(); DFS.AddFirst("poped State:" + sol.ToString() + "level " + sol.depth); traversed.Push(sol); if (sol.Equals(goal)) { found = true; DFS.AddFirst("Goal:" + sol.ToString()); break; } else { sol.getneighbors(); foreach (Sol neighbor in sol.neighbors) { if (!neighbor.containedin(traversed) && !neighbor.containedin(nextStack)) { neighbor.depth = sol.depth + 1; nextStack.Push(neighbor); } } } } return found; } public virtual bool iterativedeepening(Sol start, Sol goal) { bool found = false; for (int level = 0; ; level++) { Stack<Sol> nextStack = new Stack<Sol>(); Stack<Sol> traversed = new Stack<Sol>(); start.depth = 0; nextStack.Push(start); while (nextStack.Count != 0) { Sol sol = nextStack.Pop(); IDS.AddFirst("poped State:" + sol.ToString() + "Level" + sol.depth); traversed.Push(sol); if (sol.Equals(goal)) { found = true; IDS.AddFirst("Goal:" + sol.ToString()); break; } else if (sol.depth < level) { sol.getneighbors(); foreach (Sol neighbor in sol.neighbors) { if (!neighbor.containedin(traversed) && !neighbor.containedin(nextStack)) { neighbor.depth = sol.depth + 1; nextStack.Push(neighbor); } //end if } //end for each } //end else if } // end while if (found == true) break; } // end for return found; } } } Just wondering if I may be doing something wrong somewhere or something.

    Read the article

  • Optimizing Python code with many attribute and dictionary lookups

    - by gotgenes
    I have written a program in Python which spends a large amount of time looking up attributes of objects and values from dictionary keys. I would like to know if there's any way I can optimize these lookup times, potentially with a C extension, to reduce the time of execution, or if I need to simply re-implement the program in a compiled language. The program implements some algorithms using a graph. It runs prohibitively slowly on our data sets, so I profiled the code with cProfile using a reduced data set that could actually complete. The vast majority of the time is being burned in one function, and specifically in two statements, generator expressions, within the function: The generator expression at line 202 is neighbors_in_selected_nodes = (neighbor for neighbor in node_neighbors if neighbor in selected_nodes) and the generator expression at line 204 is neighbor_z_scores = (interaction_graph.node[neighbor]['weight'] for neighbor in neighbors_in_selected_nodes) The source code for this function of context provided below. selected_nodes is a set of nodes in the interaction_graph, which is a NetworkX Graph instance. node_neighbors is an iterator from Graph.neighbors_iter(). Graph itself uses dictionaries for storing nodes and edges. Its Graph.node attribute is a dictionary which stores nodes and their attributes (e.g., 'weight') in dictionaries belonging to each node. Each of these lookups should be amortized constant time (i.e., O(1)), however, I am still paying a large penalty for the lookups. Is there some way which I can speed up these lookups (e.g., by writing parts of this as a C extension), or do I need to move the program to a compiled language? Below is the full source code for the function that provides the context; the vast majority of execution time is spent within this function. def calculate_node_z_prime( node, interaction_graph, selected_nodes ): """Calculates a z'-score for a given node. The z'-score is based on the z-scores (weights) of the neighbors of the given node, and proportional to the z-score (weight) of the given node. Specifically, we find the maximum z-score of all neighbors of the given node that are also members of the given set of selected nodes, multiply this z-score by the z-score of the given node, and return this value as the z'-score for the given node. If the given node has no neighbors in the interaction graph, the z'-score is defined as zero. Returns the z'-score as zero or a positive floating point value. :Parameters: - `node`: the node for which to compute the z-prime score - `interaction_graph`: graph containing the gene-gene or gene product-gene product interactions - `selected_nodes`: a `set` of nodes fitting some criterion of interest (e.g., annotated with a term of interest) """ node_neighbors = interaction_graph.neighbors_iter(node) neighbors_in_selected_nodes = (neighbor for neighbor in node_neighbors if neighbor in selected_nodes) neighbor_z_scores = (interaction_graph.node[neighbor]['weight'] for neighbor in neighbors_in_selected_nodes) try: max_z_score = max(neighbor_z_scores) # max() throws a ValueError if its argument has no elements; in this # case, we need to set the max_z_score to zero except ValueError, e: # Check to make certain max() raised this error if 'max()' in e.args[0]: max_z_score = 0 else: raise e z_prime = interaction_graph.node[node]['weight'] * max_z_score return z_prime Here are the top couple of calls according to cProfiler, sorted by time. ncalls tottime percall cumtime percall filename:lineno(function) 156067701 352.313 0.000 642.072 0.000 bpln_contextual.py:204(<genexpr>) 156067701 289.759 0.000 289.759 0.000 bpln_contextual.py:202(<genexpr>) 13963893 174.047 0.000 816.119 0.000 {max} 13963885 69.804 0.000 936.754 0.000 bpln_contextual.py:171(calculate_node_z_prime) 7116883 61.982 0.000 61.982 0.000 {method 'update' of 'set' objects}

    Read the article

  • Recursively created linked lists with a class, C++

    - by Jon Brant
    I'm using C++ to recursively make a hexagonal grid (using a multiply linked list style). I've got it set up to create neighboring tiles easily, but because I'm doing it recursively, I can only really create all 6 neighbors for a given tile. Obviously, this is causing duplicate tiles to be created and I'm trying to get rid of them in some way. Because I'm using a class, checking for null pointers doesn't seem to work. It's either failing to convert from my Tile class to and int, or somehow converting it but not doing it properly. I'm explicitly setting all pointers to NULL upon creation, and when I check to see if it still is, it says it's not even though I never touched it since initialization. Is there a specific way I'm supposed to do this? I can't even traverse the grid without NULLs of some kind Here's some of my relevant code. Yes, I know it's embarassing. Tile class header: class Tile { public: Tile(void); Tile(char *Filename); ~Tile(void); void show(void); bool LoadGLTextures(); void makeDisplayList(); void BindTexture(); void setFilename(char *newName); char Filename[100]; GLuint texture[2]; GLuint displayList; Tile *neighbor[6]; float xPos, yPos,zPos; };` Tile Initialization: Tile::Tile(void) { xPos=0.0f; yPos=0.0f; zPos=0.0f; glEnable(GL_DEPTH_TEST); strcpy(Filename, strcpy(Filename, "Data/BlueTile.bmp")); if(!BuildTexture(Filename, texture[0]))MessageBox(NULL,"Texture failed to load!","Crap!",MB_OK|MB_ICONASTERISK); for(int x=0;x<6;x++) { neighbor[x]=NULL; } } Creation of neighboring tiles: void MakeNeighbors(Tile *InputTile, int stacks) { for(int x=0;x<6;x++) { InputTile->neighbor[x]=new Tile();InputTile->neighbor[x]->xPos=0.0f;InputTile->neighbor[x]->yPos=0.0f;InputTile->zPos=float(stacks); } if(stacks) { for(int x=0;x<6;x++)MakeNeighbors(InputTile->neighbor[x],stacks-1); } } And finally, traversing the grid: void TraverseGrid(Tile *inputTile) { Tile *temp; for(int x=0;x<6;x++) if(inputTile->neighbor[x]) { temp=inputTile->neighbor[x]; temp->xPos=0.0f; TraverseGrid(temp); //MessageBox(NULL,"Not Null!","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION); } } The key line is "if(inputTile-neighbor[x])" and whether I make it "if(inputTile-neighbor[x]==NULL)" or whatever I do, it just isn't handling it properly. Oh and I'm also aware that I haven't set up the list fully. It's only one direction now.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >