Exemplo n.º 1
0
        public void testNonRecursiveFiltering()
        {
            var ow = new ObjectWriter(db);
            ObjectId aSth = ow.WriteBlob("a.sth".getBytes());
            ObjectId aTxt = ow.WriteBlob("a.txt".getBytes());
            DirCache dc = DirCache.read(db);
            DirCacheBuilder builder = dc.builder();
            var aSthEntry = new DirCacheEntry("a.sth");
            aSthEntry.setFileMode(FileMode.RegularFile);
            aSthEntry.setObjectId(aSth);
            var aTxtEntry = new DirCacheEntry("a.txt");
            aTxtEntry.setFileMode(FileMode.RegularFile);
            aTxtEntry.setObjectId(aTxt);
            builder.add(aSthEntry);
            builder.add(aTxtEntry);
            builder.finish();
            ObjectId treeId = dc.writeTree(ow);


            var tw = new GitSharp.Core.TreeWalk.TreeWalk(db);
            tw.setFilter(PathSuffixFilter.create(".txt"));
            tw.addTree(treeId);

            var paths = new LinkedList<string>();
            while (tw.next())
            {
                paths.AddLast(tw.getPathString());
            }

            var expected = new LinkedList<string>();
            expected.AddLast("a.txt");

            Assert.AreEqual(expected, paths);
        }
Exemplo n.º 2
0
 protected override void addParticles(LinkedList<Particle> pl)
 {
     //top
     for (int a = 0; a < 2; a++)
     {
         pl.AddLast(new Particle(new Vector2(position.X - (w / 2) +
             ((float)ParticleEngine.r.NextDouble() * w), position.Y - h / 2),0.1f,Color.White));
     }
     //right
     for (int a = 0; a < 2; a++)
     {
         pl.AddLast(new Particle(new Vector2(position.X + (w / 2), position.Y - (h / 2) +
             ((float)ParticleEngine.r.NextDouble() * h)),0.1f,Color.White));
     }
     //down
     for (int a = 0; a < 2; a++)
     {
         pl.AddLast(new Particle(new Vector2(position.X - (w / 2) +
             ((float)ParticleEngine.r.NextDouble() * w), position.Y + h / 2),0.1f,Color.White));
     }
     //left
     for (int a = 0; a < 2; a++)
     {
         pl.AddLast(new Particle(new Vector2(position.X - (w / 2), position.Y - (h / 2) +
             ((float)ParticleEngine.r.NextDouble() * h)),0.1f,Color.White));
     }
 }
Exemplo n.º 3
0
        public override void PreGo(double time)
        {
            toGo = new LinkedList<double>();
            toGoTime = time;
            IVehicle nextVehicle = null;
            foreach (var vehicle in vehicles)
            {
                var lookAhead = vehicle.LookAhead;
                var position = vehiclePosition[vehicle];

                if (nextVehicle == null)
                {
                    if (length - position > lookAhead)
                    {
                        toGo.AddLast(length - position);
                    }
                    else
                    {
                        toGo.AddLast(length - position + outputPaths[0].ObstacleDistance(lookAhead - (length - position)));
                    }
                }
                else
                {
                    toGo.AddLast(vehiclePosition[nextVehicle] - vehiclePosition[vehicle] - nextVehicle.Length);
                }

                nextVehicle = vehicle;
            }
        }
Exemplo n.º 4
0
 public override LinkedListNode<Token> GetLastNode(LinkedList<Token> lToken, LinkedListNode<Token> current)
 {
     //Find the partner
     if(current.Previous.Value.Type == TokenType.ROUND_BRANCE_OPEN)
         return current.Previous.Value.Partner;
     return current;
 }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            List<int> list = new List<int>
            {
                3,2,
            }; // 3, 2

            list.Add(5); // 3, 2, 5
            list.Add(6); // 3, 2, 5, 6
            list.Remove(5); // 3, 2, 6

            Queue<int> queue = new Queue<int>();
            queue.Enqueue(3);// 3
            queue.Enqueue(8);// 3, 8
            queue.Dequeue(); // 8

            Stack<int> stack = new Stack<int>();
            stack.Push(2); // 2
            stack.Push(7); // 7, 2
            stack.Push(8); // 8, 7, 2
            stack.Pop();   // 7, 2

            foreach (var i in stack)
            {
                Console.WriteLine(i);
            }

            LinkedList<int> linkedList = new LinkedList<int>();
            linkedList.AddFirst(9); // 9
            linkedList.AddAfter(linkedList.Find(9), 5); // 9, 5
            linkedList.Remove(9); // 5

            Console.Read();
        }
Exemplo n.º 6
0
		public PriorityQueue()
		{
			for(int i = 0; i < _queues.Length; ++i)
			{
                _queues[i] = new LinkedList<IHasWorkItemPriority>();
			}
		}
Exemplo n.º 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="InterruptManager"/> class.
        /// </summary>
        public InterruptManager()
        {
            interruptHandlers = new LinkedList<IHardwareDevice>[MaxInterrupts];

            for (int i = 0; i < MaxInterrupts; i++)
                interruptHandlers[i] = new LinkedList<IHardwareDevice>();
        }
Exemplo n.º 8
0
        public TypeMap CreateTypeMap(Type sourceType, Type destinationType, IMappingOptions options,
            MemberList memberList)
        {
            var sourceTypeInfo = GetTypeInfo(sourceType, options);
            var destTypeInfo = GetTypeInfo(destinationType, options.ShouldMapProperty, options.ShouldMapField, new MethodInfo[0]);

            var typeMap = new TypeMap(sourceTypeInfo, destTypeInfo, memberList);

            foreach (var destProperty in destTypeInfo.PublicWriteAccessors)
            {
                var members = new LinkedList<MemberInfo>();

                if (MapDestinationPropertyToSource(members, sourceTypeInfo, destProperty.Name, options))
                {
                    var resolvers = members.Select(mi => mi.ToMemberGetter());
                    var destPropertyAccessor = destProperty.ToMemberAccessor();

                    typeMap.AddPropertyMap(destPropertyAccessor, resolvers.Cast<IValueResolver>());
                }
            }
            if (!destinationType.IsAbstract() && destinationType.IsClass())
            {
                foreach (var destCtor in destTypeInfo.Constructors.OrderByDescending(ci => ci.GetParameters().Length))
                {
                    if (MapDestinationCtorToSource(typeMap, destCtor, sourceTypeInfo, options))
                    {
                        break;
                    }
                }
            }
            return typeMap;
        }
Exemplo n.º 9
0
        public EventDevelopment(DevelopmentState a_backState, LinkedList<Event> a_events)
        {
            if (a_events == null)
            {
                throw new ArgumentNullException();
            }
            m_numOfAddedEvents = 0;
            m_state = State.neutral;
            m_backState = a_backState;
            m_buttonList = new LinkedList<Button>();
            m_guiList = new LinkedList<GuiObject>();
            m_buttonsToAdd = new Stack<Button>();
            m_buttonsToRemove = new Stack<Button>();

            m_eventsToRemove = new Stack<Button>();
            m_eventsToAdd = new Stack<Event>();
            m_events = new Dictionary<Button, Event>();
            m_effects = new Dictionary<Button, EventEffect>();
            m_triggers = new Dictionary<Button, EventTrigger>();
            m_stateButtons = new Stack<LinkedList<Button>>();

            foreach (Event t_e in a_events)
            {
                addEvent(t_e);
            }
        }
Exemplo n.º 10
0
 public ImagesGridSystemLogic(LinkedList<Image> images, ImageShareDbContext cntx1, ApplicationDbContext cntx2, int columns)
 {
     ImageShareDatabase = cntx1;
     UsersDatabase = cntx2;
     Columns = columns;
     Images = new LinkedList<Image>(images);
 }
 public VirtualPrinter()
 {
     ana = new GCodeAnalyzer(true);
     output = new LinkedList<string>();
     extruderTemp[0] = extruderTemp[1] = extruderTemp[2] = 0;
     extruderOut[0] = extruderOut[1] = extruderOut[2] = 0;
 }
Exemplo n.º 12
0
  public Curve(Molecule mol, Vector2 pos, Camera VectroCam = null)
  {
    _mol = mol;
    _label = mol.getName();
    _points = new LinkedList<Vector2>();
    //_pts = new Vector2[_maxPoints];
    _pts = new List<Vector2>();
    _minY = 0;
    _maxY = 0;
    _color = new Color(UnityEngine.Random.Range(0f, 1f), UnityEngine.Random.Range(0f, 1f), UnityEngine.Random.Range(0f, 1f));
    //_line = new VectorLine(mol.getName(), _pts, _color, null, 2.0f, LineType.Continuous, Joins.Weld);
    _line = new VectorLine(mol.getName(), _pts, 2.0f, LineType.Continuous, Joins.Weld);
    _line.color = _color;
    _isEnabled = true;
    _vectroCam = VectroCam;
//     _pos = pos;

//     _lines = new VectorLine[_maxPoints];
//     _linesTypes = new _linesTypes[_maxPoints - 1];

    VectorManager.useDraw3D = true;
    if (_vectroCam != null)
      //Vectrosity.VectorLine.SetCamera(_vectroCam);
      Vectrosity.VectorLine.SetCamera3D(_vectroCam);
    else
      Logger.Log("No Camera set for the Graph Window.", Logger.Level.ERROR);
  }
Exemplo n.º 13
0
 public GameState()
     : base()
 {
     m_champions = new Dictionary<string, Champion>();
     m_guiList.AddLast(m_championInfo = new LinkedList<GuiObject>());
     m_gameGui = new GUI();
 }
Exemplo n.º 14
0
 // constructor with the test type and Assignment already set
 public Tester(int type, int aID)
 {
     this.aID = aID;
     this.type = type;
     this.tested = 0;
     this.reports = new LinkedList<Report>();
 }
Exemplo n.º 15
0
 /// <summary>
 /// Indexes the specified events.
 /// </summary>
 /// <param name="events">The events.</param>
 /// <param name="predicateIndex">Index of the predicate.</param>
 /// <returns></returns>
 protected List<ComparableEvent> Index(LinkedList<Event> events, Dictionary<string, int> predicateIndex)
 {
     Dictionary<string, int> outcomeMap = new Dictionary<string, int>();
     int numberOfEvents = events.Count;
     int outcomeCount = 0;
     List<ComparableEvent> eventsToCompare = new List<ComparableEvent>(numberOfEvents);
     List<int> indexedContext = new List<int>();
     for (int eventIndex = 0; eventIndex < numberOfEvents; eventIndex++)
     {
         Event ev = events.First.Value;
         events.RemoveFirst();
         string[] eventContext = ev.Context;
         int outcomeId;
         string outcome = ev.Outcome;
         if (outcomeMap.ContainsKey(outcome))
         {
             outcomeId = outcomeMap[outcome];
         }
         else
         {
             outcomeId = outcomeCount++;
             outcomeMap[outcome] = outcomeId;
         }
         UpdateIndexedContextList(indexedContext, predicateIndex, eventContext);
         ProcessIndexedContextList(indexedContext, eventsToCompare, eventContext, outcomeId, outcome);
         indexedContext.Clear();
     }
     OutcomeLabels = ToIndexedStringArray(outcomeMap);
     PredicateLabels = ToIndexedStringArray(predicateIndex);
     return eventsToCompare;
 }
Exemplo n.º 16
0
        public static void CsvLoadTripRoutes(string filename, bool lngFirst)
        {
            // load trip routes
            Dictionary<string, LinkedList<Waypoint>> routes = new Dictionary<string, LinkedList<Waypoint>>();
            using (CsvFileReader reader = new CsvFileReader(filename))
            {
                CsvRow row = new CsvRow();
                while (reader.ReadRow(row, ','))
                {
                    string routeID = row[0];
                    double distance = 0;
                    double lat = Convert.ToDouble(lngFirst ? row[2] : row[1]);
                    double lng = Convert.ToDouble(lngFirst ? row[1] : row[2]);
                    if (routes.ContainsKey(routeID))
                        distance = routes[routeID].First.Value.GetDistance(new Location(lat, lng, "null"));
                    Waypoint waypoint = new Waypoint(lat, lng, TimeSpan.Parse(row[3]), distance, row[4].Replace("\"", ""));

                    // Scenario #1
                    if (!routes.ContainsKey(routeID))
                        routes[routeID] = new LinkedList<Waypoint>();
                    routes[routeID].AddLast(waypoint);

                }
            }
            foreach (LinkedList<Waypoint> w in routes.Values)
            {
                Route r = new Route(w.ToArray());
                string key = Route.GetKey(r.start, r.end);
                MapTools.routes.Add(key, r);
            }
        }
 public GradingAssignmentForm()
 {
     InitializeComponent();
     currentAssignment = null;
     currentResponseList = null;
     DeletedAdjustments = new LinkedList<int>();
 }
Exemplo n.º 18
0
        static void Main(string[] args)
        {
            Parser p = new Parser();
            string[] codeLines = p.readFile("code.ivaron"); //Read code
            //LinkedList<Token> list = new LinkedList<Token>();
            LinkedList<Token> list = new LinkedList<Token>();
            try {
                list = Tokenizer.tokenize(codeLines); //Tokenize code
            } catch(Exception e) {
                Console.WriteLine(e.Message);
            }

            if(list.Count > 0) {
                LinkedListNode<Token> token = list.First;
                while(token != null ) {
                    Console.Write(token.Value.value + " ");
                    if(token.Value.value == "{" || token.Value.value == ";") {
                        Console.Write("\n");
                    }
                    token = token.Next;
                }
            }

            TheCompiler.compile(list.First);
            // Keep the console window open in debug mode.
            Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();
        }
Exemplo n.º 19
0
    /*!
    \brief Load all the proprieties from a file
    \param The path of the file
    \return The list of ActiveTranportProprieties. If the list is empty this function return null
       */
    public LinkedList<ActiveTransportProprieties> loadActiveTransportProprietiesFromFile(string filePath)
    {
        LinkedList<ActiveTransportProprieties>      propsList = new LinkedList<ActiveTransportProprieties>();
        ActiveTransportProprieties                  prop;

        MemoryStream ms = Tools.getEncodedFileContent(filePath);
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(ms);

        XmlNodeList ATsLists = xmlDoc.GetElementsByTagName("activeTransports");
        foreach (XmlNode ATsNodes in ATsLists)
          {
        foreach (XmlNode ATNode in ATsNodes)
          {
            if (ATNode.Name == "ATProp")
              {
                prop = loadActiveTransportProprieties(ATNode);
                propsList.AddLast(prop);
              }
          }
          }

        if (propsList.Count == 0)
          return null;
        return propsList;
    }
Exemplo n.º 20
0
        public GVDKarla(ObstacleGrid grid)
        {
            this.grid = grid;

            open = new IntervalHeap<GridCellValue>();
            ties = new LinkedList<GridCell>();
            dist = new float[grid.NumColumns, grid.NumRows];
            distNew = new float[grid.NumColumns, grid.NumRows];
            parent = new GridCell[grid.NumColumns, grid.NumRows];
            tie = new GridCell[grid.NumColumns, grid.NumRows];
            obst = new int[grid.NumColumns, grid.NumRows];
            valid = new HashSet<int>();
            voro = new bool[grid.NumColumns, grid.NumRows];

            for (int c = grid.NumColumns - 1; c >= 0; c--)
                for (int r = grid.NumRows - 1; r >= 0; r--)
                {
                    dist[c, r] = float.PositiveInfinity;
                    distNew[c, r] = float.PositiveInfinity;
                    parent[c, r] = GridCell.Unknown;
                    tie[c, r] = GridCell.Unknown;
                    obst[c, r] = -1;
                    voro[c, r] = false;
                }
        }
Exemplo n.º 21
0
  protected override DNABit produceDNABit()
  {
    LinkedList<BioBrick> deviceBricks = new LinkedList<BioBrick>();
    string[] bricks = new string[]{promoterName, rbsName, geneName, terminatorName};

    foreach(string brickName in bricks)
    {
      BioBrick brick = AvailableBioBricksManager.get().getBioBrickFromAll(brickName);
      if(brick != null) {
        deviceBricks.AddLast(brick);
      } else {
        Logger.Log("PickableDeviceRef4Bricks::produceDNABit failed to add brick with name "+brickName+"!", Logger.Level.WARN);
      }
    }

        if(ExpressionModule.isBioBricksSequenceValid(deviceBricks))
        {
            ExpressionModule deviceModule = new ExpressionModule(deviceName, deviceBricks);
            LinkedList<ExpressionModule> deviceModules = new LinkedList<ExpressionModule>();
            deviceModules.AddLast(deviceModule);
            Device result = Device.buildDevice(deviceName, deviceModules);
            return result;
        } else {
            Logger.Log("PickableDeviceRef4Bricks::produceDNABit failed to produce DNABit - BioBrick sequence is incorrect: list="+Logger.ToString<BioBrick>(deviceBricks), Logger.Level.WARN);
            return null;
        }
  }
        public Solution()
        {
            Name = string.Empty;

            BusinessObjectFiles = new LinkedList<string>();
            BusinessObjects = new LinkedList<Node>();
        }
        public override LogParseResult Parse()
        {
            LinkedList<LogParseResultEntry> result = new LinkedList<LogParseResultEntry>();

            BlissHiveLogContainer blissHiveLogContainer = (BlissHiveLogContainer)this.container;

            foreach( BlissHiveLogSurvivor survivor in blissHiveLogContainer.survivorContainer.survivors ){
                for( int i = 0; i < survivor.inventories.Count - 1; i++ ){
                    BlissHiveLogInventory inv = survivor.inventories.ElementAt(i);
                    BlissHiveLogInventory nextInv = survivor.inventories.ElementAt(i + 1);

                    LinkedList<BlissHiveLogActivityItem> changedItems =
                        BlissHiveLogInventory.GetItemDifference(inv, nextInv);

                    changedItems = BlissHiveLogInventory.AddSurvivor(survivor, changedItems);

                    BlissHiveSurvivorActivityLogParseResultEntry change =
                        new BlissHiveSurvivorActivityLogParseResultEntry(nextInv.originalLogEntry);
                    change.changedItems = changedItems;

                    result.AddLast(change);
                }
            }

            this.onParseProgressListeners = null;
            return new LogParseResult(result);
        }
Exemplo n.º 24
0
 public LinkedList<SpotLight> getConnectedSpotLights()
 {
     if (m_connectedToAll)
     {
         LinkedList<GameObject>[] t_allGO = Game.getInstance().getState().getObjectList();
         LinkedList<SpotLight> t_ret = new LinkedList<SpotLight>();
         foreach (LinkedList<GameObject> t_llgo in t_allGO)
         {
             if (t_llgo != null)
             {
                 foreach (GameObject t_GO in t_llgo)
                 {
                     if (t_GO is SpotLight)
                     {
                         t_ret.AddLast((SpotLight)t_GO);
                     }
                 }
             }
         }
         return t_ret;
     }
     else
     {
         return m_connectedSpotLights;
     }
 }
Exemplo n.º 25
0
        /**
         * Bu metot içerisinde String olarak gönderilen rakamlar
         * ayrılır ve rakam olmayanlar aradan silinir.
         * Daha sonra MergeSort çağırılarak bu rakamlar sıralanır
         * ve sırasıyla ekrana yazılır.
         *
         * @param  elements arka arkaya , ile ayrılmış rakamlar
         */
        static void islemYap(String elements)
        {
            String[] elementArray = elements.Split(',');
            int elementCount = elementArray.Length;
            LinkedList<int> integerElements = new LinkedList<int>();

            int forcounter = 0;
            foreach (String element in elementArray)
            {
                try
                {
                    integerElements.AddLast(int.Parse(element));
                    forcounter++;
                }
                catch (FormatException fe)
                {
                    //Rakam olmayanları elemek için
                }
            }

            int[] integerArray = integerElements.ToArray<int>();

            //Elemanları sıralayalım
            integerArray = MergeSort(integerArray);

            foreach (int i in integerArray)
            {
                Console.WriteLine(i);
            }
        }
Exemplo n.º 26
0
        public TokenStream(IEnumerable<LexicToken> tokens)
        {
            if (tokens == null)
                throw new ArgumentNullException("tokens");

            this.tokens = new LinkedList<LexicToken>(tokens);
        }
Exemplo n.º 27
0
        public DispatchManager(
            object sender, // Agent reference for callbacks
            Options options, WaterFlowManager incomingFlowManager, 
            IOWorker ioWorker, 
            LogCallback logCallback, LogEventArgs.LogLevel logLevel)
        {
            this.sender = sender;
            this.incomingFlowManager = incomingFlowManager;
            this.ioWorker = ioWorker;

            this.logCallback = logCallback;
            this.logLevel = logLevel;

            messageQueue = new LinkedList<IncomingMessage>();

            objectMap = new Dictionary<string, IncomingMessageHandler>();
            anyObjectCallback = null;

            int numOfThreads = options.dispatcherThreads;

            dispatchers = new List<Thread>();
            for (int i = 0; i != numOfThreads; ++i)
            {

                Thread th = new Thread((new Dispatcher(this)).run);
                th.Name = "YAMI4 message dispatcher";
                th.IsBackground = true;
                th.Start();
                dispatchers.Add(th);
            }
        }
Exemplo n.º 28
0
        public static LinkedList<int> SumLists(this LinkedList<int> number1, LinkedList<int> number2)
        {
           
            var node1 = number1.Last;
            var node2 = number2.Last;
            var result = new LinkedList<int>();
            var carry = 0;
            while (true)
            {
                if (node1 == null && node2 == null && carry == 0)
                {
                    break;
                }

                var val1 = node1?.Value ?? 0;
                var val2 = node2?.Value ?? 0;

                var sum = val1 + val2 + carry;
                carry = sum / 10;
                result.AddFirst(sum%10);
                
                node1 = node1?.Previous;
                node2 = node2?.Previous;
            }
            return result;
        }
Exemplo n.º 29
0
        public static void CalculateTime(LinkedList<string> list, int k)
        {
            // Add
            var startAdding = DateTime.Now;
            string test = "Test string";
            for (int i = 0; i < k; i++)
            {
                list.AddFirst(test);
            }
            var finishAdding = DateTime.Now;
            Console.WriteLine("Addition time (" + k + " elements) : " + list.GetType() + "  " + (finishAdding - startAdding));

            // Search
            var startSearch = DateTime.Now;
            for (int i = 0; i < k; i++)
            {
                bool a = list.Equals(test);
            }
            var finishSearch = DateTime.Now;
            Console.WriteLine("Search time (" + k + " elements) : " + list.GetType() + "  " + (finishSearch - startSearch));

            // Remove
            k = 1000000;
            var startRemoving = DateTime.Now;
            for (int i = 0; i < k; i++)
            {
                list.Remove(test);
            }
            var finishRemoving = DateTime.Now;
            Console.WriteLine("Removal time (" + k + " elements) : " + list.GetType() + "  " + (finishRemoving - startRemoving) + "\n");
        }
Exemplo n.º 30
0
        public bool MoveNext()
        {
            if (personLinkedList == null) {
                    personLinkedList = new LinkedList<Person>();

                personLinkedList.AddLast(new Person {personId = 1, personName = "xxx", personLocation = "chennai"} );
                    personLinkedList.AddLast(new Person {personId = 2, personName = "YYY", personLocation = "chennai"} );
                    personLinkedList.AddLast(new Person {personId = 3, personName = "ZZZ", personLocation = "chennai"} );
                }
                if (currentObj == null && personLinkedList.First != null)
                {

                    currentObj = personLinkedList.First;
                    return true;
                }
                if ( currentObj.Next!=null)
                {
                    currentObj = currentObj.Next;
                    return true;
                }
                else
                {
                    return false;
                }
        }
Exemplo n.º 31
0
 public Top10Listener(int capacity)
 {
     this.capacity = capacity;
     this.traces   = new LinkedList <string>();
 }
 public static void BadSink(LinkedList <int> dataLinkedList)
 {
     int data = dataLinkedList.Last.Value;
     /* POTENTIAL FLAW: Create a HashSet using data as the initial size.  data may be very large, creating memory issues */
     HashSet <int> intHashSet = new HashSet <int>(data);
 }
        public void Remove_NullHead_ThrowsInvalidOperation()
        {
            var list = new LinkedList <int>();

            Assert.Throws <InvalidOperationException>(() => list.Remove(0));
        }
Exemplo n.º 34
0
 protected SqlSnapshotStore()
 {
     QueryMapper       = new DefaultSnapshotQueryMapper(Context.System.Serialization);
     PendingOperations = new LinkedList <CancellationTokenSource>();
 }
Exemplo n.º 35
0
        public static void MinimizeHopcroft(Automaton a)
        {
            a.Determinize();
            IList<Transition> tr = a.Initial.Transitions;
            if (tr.Count == 1)
            {
                Transition t = tr[0];
                if (t.To == a.Initial && t.Min == char.MinValue && t.Max == char.MaxValue)
                {
                    return;
                }
            }

            a.Totalize();

            // Make arrays for numbered states and effective alphabet.
            HashSet<State> ss = a.GetStates();
            var states = new State[ss.Count];
            int number = 0;
            foreach (State q in ss)
            {
                states[number] = q;
                q.Number = number++;
            }

            char[] sigma = a.GetStartPoints();

            // Initialize data structures.
            var reverse = new List<List<LinkedList<State>>>();
            foreach (State s in states)
            {
                var v = new List<LinkedList<State>>();
                Initialize(ref v, sigma.Length);
                reverse.Add(v);
            }

            var reverseNonempty = new bool[states.Length, sigma.Length];

            var partition = new List<LinkedList<State>>();
            Initialize(ref partition, states.Length);

            var block = new int[states.Length];
            var active = new StateList[states.Length, sigma.Length];
            var active2 = new StateListNode[states.Length, sigma.Length];
            var pending = new LinkedList<IntPair>();
            var pending2 = new bool[sigma.Length, states.Length];
            var split = new List<State>();
            var split2 = new bool[states.Length];
            var refine = new List<int>();
            var refine2 = new bool[states.Length];

            var splitblock = new List<List<State>>();
            Initialize(ref splitblock, states.Length);

            for (int q = 0; q < states.Length; q++)
            {
                splitblock[q] = new List<State>();
                partition[q] = new LinkedList<State>();
                for (int x = 0; x < sigma.Length; x++)
                {
                    reverse[q][x] = new LinkedList<State>();
                    active[q, x] = new StateList();
                }
            }

            // Find initial partition and reverse edges.
            foreach (State qq in states)
            {
                int j = qq.Accept ? 0 : 1;

                partition[j].AddLast(qq);
                block[qq.Number] = j;
                for (int x = 0; x < sigma.Length; x++)
                {
                    char y = sigma[x];
                    State p = qq.Step(y);
                    reverse[p.Number][x].AddLast(qq);
                    reverseNonempty[p.Number, x] = true;
                }
            }

            // Initialize active sets.
            for (int j = 0; j <= 1; j++)
            {
                for (int x = 0; x < sigma.Length; x++)
                {
                    foreach (State qq in partition[j])
                    {
                        if (reverseNonempty[qq.Number, x])
                        {
                            active2[qq.Number, x] = active[j, x].Add(qq);
                        }
                    }
                }
            }

            // Initialize pending.
            for (int x = 0; x < sigma.Length; x++)
            {
                int a0 = active[0, x].Size;
                int a1 = active[1, x].Size;
                int j = a0 <= a1 ? 0 : 1;
                pending.AddLast(new IntPair(j, x));
                pending2[x, j] = true;
            }

            // Process pending until fixed point.
            int k = 2;
            while (pending.Count > 0)
            {
                IntPair ip = pending.RemoveAndReturnFirst();
                int p = ip.N1;
                int x = ip.N2;
                pending2[x, p] = false;

                // Find states that need to be split off their blocks.
                for (StateListNode m = active[p, x].First; m != null; m = m.Next)
                {
                    foreach (State s in reverse[m.State.Number][x])
                    {
                        if (!split2[s.Number])
                        {
                            split2[s.Number] = true;
                            split.Add(s);
                            int j = block[s.Number];
                            splitblock[j].Add(s);
                            if (!refine2[j])
                            {
                                refine2[j] = true;
                                refine.Add(j);
                            }
                        }
                    }
                }

                // Refine blocks.
                foreach (int j in refine)
                {
                    if (splitblock[j].Count < partition[j].Count)
                    {
                        LinkedList<State> b1 = partition[j];
                        LinkedList<State> b2 = partition[k];
                        foreach (State s in splitblock[j])
                        {
                            b1.Remove(s);
                            b2.AddLast(s);
                            block[s.Number] = k;
                            for (int c = 0; c < sigma.Length; c++)
                            {
                                StateListNode sn = active2[s.Number, c];
                                if (sn != null && sn.StateList == active[j, c])
                                {
                                    sn.Remove();
                                    active2[s.Number, c] = active[k, c].Add(s);
                                }
                            }
                        }

                        // Update pending.
                        for (int c = 0; c < sigma.Length; c++)
                        {
                            int aj = active[j, c].Size;
                            int ak = active[k, c].Size;
                            if (!pending2[c, j] && 0 < aj && aj <= ak)
                            {
                                pending2[c, j] = true;
                                pending.AddLast(new IntPair(j, c));
                            }
                            else
                            {
                                pending2[c, k] = true;
                                pending.AddLast(new IntPair(k, c));
                            }
                        }

                        k++;
                    }

                    foreach (State s in splitblock[j])
                    {
                        split2[s.Number] = false;
                    }

                    refine2[j] = false;
                    splitblock[j].Clear();
                }

                split.Clear();
                refine.Clear();
            }

            // Make a new state for each equivalence class, set initial state.
            var newstates = new State[k];
            for (int n = 0; n < newstates.Length; n++)
            {
                var s = new State();
                newstates[n] = s;
                foreach (State q in partition[n])
                {
                    if (q == a.Initial)
                    {
                        a.Initial = s;
                    }

                    s.Accept = q.Accept;
                    s.Number = q.Number; // Select representative.
                    q.Number = n;
                }
            }

            // Build transitions and set acceptance.
            foreach (State s in newstates)
            {
                s.Accept = states[s.Number].Accept;
                foreach (Transition t in states[s.Number].Transitions)
                {
                    s.Transitions.Add(new Transition(t.Min, t.Max, newstates[t.To.Number]));
                }
            }

            a.RemoveDeadTransitions();
        }
Exemplo n.º 36
0
 public LinkedTreeList(LinkedList <LinkedTree <T> > list)
 {
     this.list = list;
 }
Exemplo n.º 37
0
 /// <summary>
 /// Constructor, only factory can instantiates nodes.
 /// </summary>
 /// <param name="nodeId">[in] The id of the node.</param>
 /// <param name="factory">[in] Poiter to the Factory the node belongs to.</param>
 public ArrayRankSpecifierSyntax(uint nodeId, Factory factory) : base(nodeId, factory)
 {
     SizesContainer = new LinkedList <uint>();
 }
Exemplo n.º 38
0
        public static List <string> Words(string imgdata, int freq, int length)
        {
            #region words freqency

            String fullbook = String.Copy(imgdata);

            // remove numbers and punctuation
            fullbook = Regex.Replace(fullbook.ToString(), "\\.|;|-|_|:,|[0-9]|'", "");

            // create collection of words
            MatchCollection wordCollection = Regex.Matches(fullbook, @"[\w]+", RegexOptions.Multiline);

            // create linked list for words
            LinkedList <string> wordList = new LinkedList <string>();

            // create hash table
            Hashtable frequencyHash = new Hashtable();

            // create linked list for unique words
            LinkedList <string> uniqueWord = new LinkedList <string>();

            // populate wordList with content of collection

            for (int idx = 0; idx < wordCollection.Count; idx++)
            {
                wordList.AddLast(wordCollection[idx].ToString().ToLower().Trim());
            }

            // populate hashtable of word frequency
            // for everyword in full word list
            foreach (var word in wordList)
            {
                // if unique linked list does not contain a word. add it as a key, and set the value to 1
                // if unique linked list contains the word increment the value
                if (uniqueWord.Contains(word))
                {
                    int wordCount = int.Parse(frequencyHash[word].ToString());
                    wordCount++;
                    frequencyHash[word] = wordCount;
                }
                else
                {
                    uniqueWord.AddLast(word);
                    frequencyHash.Add(word, 1);
                }
            }
            // sort hash table
            var ret = new List <DictionaryEntry>(frequencyHash.Count);


            foreach (DictionaryEntry entry in frequencyHash)
            {
                ret.Add(entry);
            }

            // sort dictonary based on frequency
            ret.Sort(
                (x, y) =>
            {
                IComparable comparable = x.Value as IComparable;
                if (comparable != null)
                {
                    return(comparable.CompareTo(y.Value));
                }
                return(0);
            }
                );

            // extract only keys ; keys are words
            List <string> keys = new List <string>();
            for (int idx = 0; idx < ret.Count; idx++)
            {
                string ky = ret[idx].Key.ToString();
                if ((Int32.Parse(ret[idx].Value.ToString()) >= freq) && (ky.Length > length))
                {
                    keys.Add(ky);
                }
            }

            // sort the words
            keys.Sort();



            return(keys);

            #endregion
        }
Exemplo n.º 39
0
 protected virtual void ExtractLinks(BulkLoadContext context, BulkLoadItem item, LinkedList <BulkItemLink> links)
 {
     foreach (var field in item.Fields)
     {
         ExtractLinks(context, item, field, links);
     }
 }
Exemplo n.º 40
0
 public SchedulerQueue()
 {
     _queue = new LinkedList <Event>();
 }
Exemplo n.º 41
0
 public Evaluator(LinkedList <T> input, LinkedList <LinkedListNode <T> >[] operations)
 {
     Input      = input;
     Operations = operations;
 }
Exemplo n.º 42
0
        protected virtual void ExtractLinks(BulkLoadContext context, BulkLoadItem item, BulkField field, LinkedList <BulkItemLink> links)
        {
            if (string.IsNullOrWhiteSpace(field.Value))
            {
                return;
            }
            if (IgnoredFields.Value.Contains(field.Name))
            {
                return;
            }

            var ids = IdRegex.Value.Matches(field.Value).Cast <Match>()
                      .Select(x =>
            {
                ID id;
                return(ID.TryParse(x.Value, out id) ? id : (ID)null);
            })
                      .Concat(LinkRegex.Value.Matches(field.Value).Cast <Match>().Select(x =>
            {
                Guid guid;
                return(Guid.TryParse(x.Value, out guid) ? new ID(guid) : (ID)null);
            }))
                      .Where(x => x != (ID)null);

            foreach (var link in ids
                     .Select(x => new BulkItemLink(
                                 context.Database, new ID(item.Id), new ID(field.Id),
                                 context.Database, x, x.ToString())))
            {
                link.ItemAction = item.LoadAction;
                links.AddLast(link);
            }
        }
Exemplo n.º 43
0
    /// <summary>
    /// 各セルから全衝突可能リストを作成する
    /// </summary>
    /// <param name="elem">検索を開始する要素のindex</param>
    /// <param name="collisionList">衝突可能性のあるリストを格納する</param>
    /// <param name="colStac">衝突検知用のスタック</param>
    /// <returns><c>true</c>, if collision list was gotten, <c>false</c> otherwise.</returns>
    bool GetCollisionList(int elem, List <T> collisionList, LinkedList <T> colStac)
    {
        // 空間内のオブジェクト同士の衝突リスト作成
        // ルート空間からはじめ、その子空間へと移動しながら、「衝突可能性のある」オブジェクト同士の
        // ペアとなるリストを作成する
        // 結果は「collisionList」に格納される。
        // なお、リストは「ペア」構造となっていて、
        // 完成したリストからはふたつずつ取り出して衝突の詳細判定を行う想定。

        // ルート空間に登録されているリンクリストの最初の要素を取り出す
        TreeData <T> data = _cellList[elem].FirstData;

        // データがなくなるまで繰り返す
        while (data != null)
        {
            // まず、リンクリストの次を取り出す
            TreeData <T> next = data.Next;
            while (next != null)
            {
                // 衝突リスト作成
                collisionList.Add(data.Object);
                collisionList.Add(next.Object);
                next = next.Next;
            }

            // 衝突スタックと衝突リスト作成
            foreach (var obj in colStac)
            {
                collisionList.Add(data.Object);
                collisionList.Add(obj);
            }

            data = data.Next;
        }

        bool child = false;

        // 子空間に移動
        int objNum = 0;
        int nextElem;

        // 小空間を巡る
        // 例えば、8分木の場合は子空間は8分割される
        // つまり、8回ループすることで小空間を網羅する
        for (int i = 0; i < _divisionNumber; i++)
        {
            nextElem = elem * _divisionNumber + 1 + i;

            // 空間分割数以上 or 対象空間がない場合はスキップ
            bool needsSkip = (nextElem >= _cellNum ||
                              _cellList[nextElem] == null);
            if (needsSkip)
            {
                continue;
            }

            // 子空間への処理がまだ済んでいない場合は処理を行う
            // 同空間内のオブジェクトをスタックに追加した上で小空間の衝突リストを作成する
            // ただし、一度セットアップが済んでいる場合は本処理をスキップし、小空間の検索のみを実行する
            // (同空間のオブジェクト追加は一度のみ行う必要があるため)
            if (!child)
            {
                // 同空間のオブジェクトをスタックに積む
                data = _cellList[elem].FirstData;
                while (data != null)
                {
                    colStac.AddLast(data.Object);
                    objNum++;
                    data = data.Next;
                }
            }

            child = true;

            // 子空間を検索
            GetCollisionList(nextElem, collisionList, colStac);
        }

        // スタックからオブジェクトを外す
        // 計測したobjNum個数分、スタックから取り除く(=子空間検索用に追加した分)
        if (child)
        {
            for (int i = 0; i < objNum; i++)
            {
                colStac.RemoveLast();
            }
        }

        return(true);
    }
Exemplo n.º 44
0
        /// <summary>
        /// Evaluates the operator.
        /// </summary>
        /// <param name="Left">Left value.</param>
        /// <param name="Right">Right value.</param>
        /// <returns>Result</returns>
        public virtual IElement Evaluate(IElement Left, IElement Right)
        {
            ISet Set;

            if ((Set = Right as ISet) != null)
            {
                return(this.Evaluate(Left, Set));
            }
            else if (Right.IsScalar)
            {
                throw new ScriptRuntimeException("Right operand in an IN operation must be a set.", this);
            }
            else
            {
                if (Left.IsScalar)
                {
                    LinkedList <IElement> Elements = new LinkedList <IElement>();

                    foreach (IElement E in Right.ChildElements)
                    {
                        Elements.AddLast(this.Evaluate(Left, E));
                    }

                    return(Right.Encapsulate(Elements, this));
                }
                else
                {
                    ICollection <IElement> LeftChildren  = Left.ChildElements;
                    ICollection <IElement> RightChildren = Right.ChildElements;

                    if (LeftChildren.Count == RightChildren.Count)
                    {
                        LinkedList <IElement>  Elements = new LinkedList <IElement>();
                        IEnumerator <IElement> eLeft    = LeftChildren.GetEnumerator();
                        IEnumerator <IElement> eRight   = RightChildren.GetEnumerator();

                        try
                        {
                            while (eLeft.MoveNext() && eRight.MoveNext())
                            {
                                Elements.AddLast(this.Evaluate(eLeft.Current, eRight.Current));
                            }
                        }
                        finally
                        {
                            eLeft.Dispose();
                            eRight.Dispose();
                        }

                        return(Left.Encapsulate(Elements, this));
                    }
                    else
                    {
                        LinkedList <IElement> LeftResult = new LinkedList <IElement>();

                        foreach (IElement LeftChild in LeftChildren)
                        {
                            LinkedList <IElement> RightResult = new LinkedList <IElement>();

                            foreach (IElement RightChild in RightChildren)
                            {
                                RightResult.AddLast(this.Evaluate(LeftChild, RightChild));
                            }

                            LeftResult.AddLast(Right.Encapsulate(RightResult, this));
                        }

                        return(Left.Encapsulate(LeftResult, this));
                    }
                }
            }
        }
Exemplo n.º 45
0
 public LinkedList(T value, LinkedList <T> nextNode = null)
 {
     this.Value    = value;
     this.NextNode = nextNode;
 }
Exemplo n.º 46
0
        /// <summary>
        /// Configure the media type tables so that Json Light is the first JSON format in the table.
        /// </summary>
        /// <remarks>
        /// This is only used in V4 and beyond.
        /// </remarks>
        private void AddJsonLightMediaTypes()
        {
            var optionalParameters = new[]
            {
                new
                {
                    ParameterName = MimeConstants.MimeMetadataParameterName,
                    Values        = new[] { MimeConstants.MimeMetadataParameterValueMinimal, MimeConstants.MimeMetadataParameterValueFull, MimeConstants.MimeMetadataParameterValueNone }
                },
                new
                {
                    ParameterName = MimeConstants.MimeStreamingParameterName,
                    Values        = new[] { MimeConstants.MimeParameterValueTrue, MimeConstants.MimeParameterValueFalse }
                },
                new
                {
                    ParameterName = MimeConstants.MimeIeee754CompatibleParameterName,
                    Values        = new[] { MimeConstants.MimeParameterValueFalse, MimeConstants.MimeParameterValueTrue }
                },
            };

            // initial seed for the list will be extended in breadth-first passes over the optional parameters
            var mediaTypesToAdd = new LinkedList <MediaType>();

            mediaTypesToAdd.AddFirst(ApplicationJsonMediaType);

            foreach (var optionalParameter in optionalParameters)
            {
                // go through each one so far and extend it
                for (LinkedListNode <MediaType> currentNode = mediaTypesToAdd.First; currentNode != null; currentNode = currentNode.Next)
                {
                    MediaType typeToExtend = currentNode.Value;
                    foreach (string valueToAdd in optionalParameter.Values)
                    {
                        var extendedParameters = new List <KeyValuePair <string, string> >(typeToExtend.Parameters ?? Enumerable.Empty <KeyValuePair <string, string> >())
                        {
                            new KeyValuePair <string, string>(optionalParameter.ParameterName, valueToAdd)
                        };

                        var extendedMediaType = new MediaType(typeToExtend.TypeName, typeToExtend.SubTypeName, extendedParameters);

                        // always match more specific things first
                        mediaTypesToAdd.AddBefore(currentNode, extendedMediaType);
                    }
                }
            }

            List <MediaTypeWithFormat> JsonMediaTypeWithFormatList = new List <MediaTypeWithFormat>();
            MediaTypeWithFormat        applicationJson             = null;

            foreach (MediaType mediaType in mediaTypesToAdd)
            {
                var mediaTypeWithFormat = new MediaTypeWithFormat {
                    Format = ODataFormat.Json, MediaType = mediaType
                };
                if (mediaType == ApplicationJsonMediaType)
                {
                    applicationJson = mediaTypeWithFormat;
                }
                else
                {
                    JsonMediaTypeWithFormatList.Insert(0, mediaTypeWithFormat);
                }
            }

            if (applicationJson != null)
            {
                JsonMediaTypeWithFormatList.Insert(0, applicationJson);
            }

            this.AddForJsonPayloadKinds(JsonMediaTypeWithFormatList);
        }
Exemplo n.º 47
0
        private unsafe bool FindEyesFromDifferenceImage(FastBitmap img, FastBitmap differenceImage, out EyeData leftEye, out EyeData rightEye)
        {
            leftEye  = null;
            rightEye = null;

            if (thresholdElapsedTime < 0)
            {
                thresholdElapsedTime = 0;
                stopwatch.Reset();
                stopwatch.Start();
            }
            else
            {
                thresholdElapsedTime += stopwatch.ElapsedMilliseconds / 1000f;
                stopwatch.Reset();
                stopwatch.Start();
            }

            FastBitmap.ConnectedComponentsResults ccResults = differenceImage.FindConnectedComponents(100, 2, 10);


            if (ccResults.NumberOfComponents >= 2 && ccResults.NumberOfComponents <= MaxNumberOfConnectedComponents)
            {
                LinkedList <BlinkVector> vectors = GetBlinkVectors(ccResults);

                if (vectors.Count > 0)
                {
                    float       minDistanceSquared = float.PositiveInfinity;
                    BlinkVector bestVector         = null;
                    float       mahalanobisDistanceSquaredThreshold = MahalanobisDistanceSquaredThreshold;
                    float       minimumNcc = MinimumNcc;

                    foreach (BlinkVector v in vectors)
                    {
                        float tempDistSquared = v.GetMahalanobisDistanceSquared(AverageVector, InverseCovarianceMatrix);
                        if (tempDistSquared < minDistanceSquared)
                        {
                            bestVector         = v;
                            minDistanceSquared = tempDistSquared;
                        }
                    }

                    if (minDistanceSquared <= mahalanobisDistanceSquaredThreshold)
                    {
                        try
                        {
                            float ncc = HorizontalFlipNccTemplateMatch(img, ccResults.Centers[bestVector.LeftEyeLabel], ccResults.Centers[bestVector.RightEyeLabel]);

                            if (ncc > minimumNcc)
                            {
                                leftEye  = new EyeData(ccResults.Centers[bestVector.LeftEyeLabel], ccResults.BoundingBoxes[bestVector.LeftEyeLabel]);
                                rightEye = new EyeData(ccResults.Centers[bestVector.RightEyeLabel], ccResults.BoundingBoxes[bestVector.RightEyeLabel]);
                                return(true);
                            }
                            return(false);
                        }
                        catch (ArgumentOutOfRangeException) { }
                    }
                }
            }
            return(false);
        }
Exemplo n.º 48
0
        private void CreateMenuRoot()
        {
            ICollection <Section> root = new LinkedList <Section>();

            root.Add(_profileSection);

            var teamEvents = ViewModel.TeamEvents
                             .Where(_ => ViewModel.ShowTeamEvents)
                             .Select(team => new MenuElement(team.Name, team.GoToCommand, AtlassianIcon.Blogroll.ToImage()));

            var eventsSection = new Section {
                HeaderView = new MenuSectionView("Events")
            };

            eventsSection.Add(new MenuElement(ViewModel.Username, ViewModel.GoToMyEvents, AtlassianIcon.Blogroll.ToImage()));
            eventsSection.AddAll(teamEvents);
            root.Add(eventsSection);

            root.Add(_repoSection);

            if (ViewModel.PinnedRepositories.Any())
            {
                _favoriteRepoSection = new Section {
                    HeaderView = new MenuSectionView("Favorite Repositories")
                };
                _favoriteRepoSection.AddAll(ViewModel.PinnedRepositories.Select(x => new PinnedRepoElement(x)));
                root.Add(_favoriteRepoSection);
            }
            else
            {
                _favoriteRepoSection = null;
            }

            if (ViewModel.ExpandTeamsAndGroups)
            {
                if (ViewModel.Groups.Count > 0)
                {
                    var groupsTeamsSection = new Section {
                        HeaderView = new MenuSectionView("Groups")
                    };
                    groupsTeamsSection.AddAll(ViewModel.Groups.Select(
                                                  g => new MenuElement(g.Name, g.GoToCommand, AtlassianIcon.Group.ToImage())));
                    root.Add(groupsTeamsSection);
                }
                if (ViewModel.Teams.Count > 0)
                {
                    var groupsTeamsSection = new Section {
                        HeaderView = new MenuSectionView("Teams")
                    };
                    groupsTeamsSection.AddAll(ViewModel.Teams.Select(
                                                  g => new MenuElement(g.Name, g.GoToCommand, AtlassianIcon.Group.ToImage())));
                    root.Add(groupsTeamsSection);
                }
            }
            else
            {
                var groupsTeamsSection = new Section {
                    HeaderView = new MenuSectionView("Collaborations")
                };
                groupsTeamsSection.Add(new MenuElement("Groups", ViewModel.GoToGroupsCommand, AtlassianIcon.Group.ToImage()));
                groupsTeamsSection.Add(new MenuElement("Teams", ViewModel.GoToTeamsCommand, AtlassianIcon.Userstatus.ToImage()));
                root.Add(groupsTeamsSection);
            }

            root.Add(_infoSection);
            Root.Reset(root);
        }
        /// <summary>
        /// calculate route distance by search the shortest route between the from vertex of the two edges
        /// this method may be not accurate.
        /// <returns></returns>
        private Edgespp RouteDistance(Point p1, Edge e1, Point p2, Edge e2, Graph g)
        {
            double routeDis = 0;

            Point  p1_prj = e1.projectFrom(p1);
            Vertex e1_to  = e1.To;
            double dis1   = p1_prj.DistanceFrom(e1_to.toPoint());

            Point  p2_prj  = e2.projectFrom(p2);
            Vertex e2_from = e2.From;
            double dis2    = p2_prj.DistanceFrom(e2_from.toPoint());

            if (e1 == e2)
            {
                return(new Edgespp(p1_prj.DistanceFrom(p2_prj), new List <Edge>()
                {
                    e1
                }));
            }
            else if (e1_to.ID == e2_from.ID)
            {
                routeDis = dis1 + dis2;
                return(new Edgespp(routeDis, new List <Edge>()
                {
                    e1, e2
                }));
            }
            else
            {
                Dijkstra dij = new Dijkstra(g);

                LinkedList <Vertex> shortestPath_vertices = dij.ShortestPath_ScoreValue(e1_to, e2_from, _distance_limit);

                //Route rs = getminRoute(F, e1.ID, e2.ID, p1, p2);

                if (shortestPath_vertices == null)
                {
                    return(null);
                }

                List <Edge> shortestPath_edges = dij.MakeShortestPath_EdgeList();

                //List<Edge> shortestPath_edges = rs.getPath_EdgeList(m_graph);

                for (int i = 0; i < shortestPath_edges.Count; i++)
                {
                    routeDis += shortestPath_edges[i].Length;
                }

                if (shortestPath_edges.Contains(e1))
                {
                    routeDis -= dis1;
                    shortestPath_edges.Remove(e1);
                }
                else
                {
                    routeDis += dis1;
                }

                if (shortestPath_edges.Contains(e2))
                {
                    routeDis -= dis2;
                    shortestPath_edges.Remove(e2);
                }
                else
                {
                    routeDis += dis2;
                }

                return(new Edgespp(routeDis, shortestPath_edges));
            }
        }
Exemplo n.º 50
0
 public static LinkedListNode <int> Add(LinkedList <int> myLList, int n)
 {
     return(myLList.AddFirst(n));
 }
Exemplo n.º 51
0
 public Node(long distance)
 {
     Distance      = distance;
     TotalDistance = distance;
     Nodes         = new LinkedList <Node>();
 }
Exemplo n.º 52
0
        // Displays tree with proper spacing
        public string DisplayTree()
        {
            if (root == null)
            {
                return("");
            }
            string output = "";
            // list containing all nodes on current level, begins with just root
            LinkedList <SplayTreeNode <T> > currentNodes = new LinkedList <SplayTreeNode <T> >();
            LinkedList <SplayTreeNode <T> > sortedNodes  = new LinkedList <SplayTreeNode <T> >();

            currentNodes.AddLast(root);
            bool empty = false;

            // iterates until no nodes on next floor
            while (empty == false)
            {
                // keeps track if any non-null nodes were added to next floor
                empty = true;
                // list of nodes on next floor
                LinkedList <SplayTreeNode <T> > next = new LinkedList <SplayTreeNode <T> >();
                // iterates through nodes on current floor
                foreach (SplayTreeNode <T> node in currentNodes)
                {
                    // enqueues each node's children into list of nodes on next floor
                    // enqueues 2 null nodes when encountering a null node
                    if (node != null)
                    {
                        if (node.left != null || node.right != null)
                        {
                            empty = false;
                        }
                        next.AddLast(node.left);
                        next.AddLast(node.right);
                    }
                    else
                    {
                        next.AddLast(node);
                        next.AddLast(node);
                    }
                    // enqueues current node into list of all nodes
                    sortedNodes.AddLast(node);
                }
                // replaces list of current floor nodes with list of next floor nodes
                currentNodes = next;
            }
            // counters to keep track of current level and number of nodes added
            int level      = 1;
            int nodesAdded = 1;

            // outputs blank spaces for first level
            output += new string(' ', (int)((sortedNodes.Count - 1) / Math.Pow(2, level - 1)));
            //iterates through list of all nodes
            foreach (SplayTreeNode <T> node in sortedNodes)
            {
                // if number of nodes added exceeds 2^level increase the level and outputs initial spacing for level
                if (nodesAdded == Math.Pow(2, level))
                {
                    level++;
                    output += "\n\n";
                    output += new string(' ', (int)((sortedNodes.Count - 1) / Math.Pow(2, level - 1)) - 1);
                }
                // adds value of node/empty node indicator to level and appropriate spacing based on level and total number of nodes
                // adds value of node(trunicated to length 2) or empty node indicator to output and appropriate spacing based on level and total number of nodes
                if (node != null)
                {
                    string value = node.value.ToString();
                    if (value.Length > 2)
                    {
                        value = value.Substring(0, 2);
                    }
                    while (value.Length < 2)
                    {
                        value = " " + value;
                    }
                    output += value;
                }
                else
                {
                    output += "[]";
                }
                output += new string(' ', 2 * (int)((sortedNodes.Count - 1) / Math.Pow(2, level - 1)));
                nodesAdded++;
            }
            return(output);
        }
        static void Main()
        {
            // Join Unicode
            Console.OutputEncoding = Encoding.Unicode;

            // set size of console
            Console.SetWindowSize(80, 60);
            Console.SetBufferSize(80, 60);

            #region Hashtable
#if false
            Hashtable ht = new Hashtable();
            {
                List <string> keys = new List <string>();
                for (int i = 0; i < rnd.Next(10, 28); i++)
                {
                    // на випадок повторень ключа
                    try
                    {
                        keys.Add(GetFullName());
                        ht.Add(keys.Last(), GetProduct());
                    }
                    catch (ArgumentException)
                    {
                        keys.RemoveAt(i--);
                    }
                }

                // виведення
                foreach (var i in keys)
                {
                    GetRes(i, (string)ht[i]);
                }
            }
#endif
            #endregion

            #region ListDictionary
#if false
            ListDictionary ld = new ListDictionary();
            {
                List <string> keys = new List <string>();
                for (int i = 0; i < rnd.Next(10, 28); i++)
                {
                    // на випадок повторень ключа
                    try
                    {
                        keys.Add(GetFullName());
                        ld.Add(keys.Last(), GetProduct());
                    }
                    catch (ArgumentException)
                    {
                        keys.RemoveAt(i--);
                    }
                }

                // виведення
                foreach (var i in keys)
                {
                    GetRes(i, (string)ld[i]);
                }
            }
#endif
            #endregion

            #region HybridDictionary
#if false
            HybridDictionary hd = new HybridDictionary();
            {
                List <string> keys = new List <string>();
                for (int i = 0; i < rnd.Next(10, 28); i++)
                {
                    // на випадок повторень ключа
                    try
                    {
                        keys.Add(GetFullName());
                        hd.Add(keys.Last(), GetProduct());
                    }
                    catch (ArgumentException)
                    {
                        keys.RemoveAt(i--);
                    }
                }

                // виведення
                foreach (var i in keys)
                {
                    GetRes(i, (string)hd[i]);
                }
            }
#endif
            #endregion

            #region SortedList
#if false
            SortedList <string, string> sl = new SortedList <string, string>();
            for (int i = 0; i < rnd.Next(10, 28); i++)
            {
                try
                {
                    sl.Add(GetFullName(), GetProduct());
                }
                catch (ArgumentException)
                {
                    i--;
                }
            }

            // виведення
            foreach (var i in sl)
            {
                GetRes(i.Key, i.Value);
            }
#endif
            #endregion

            #region OrderedDictionary
#if false
            OrderedDictionary od = new OrderedDictionary();
            {
                List <string> keys = new List <string>();
                for (int i = 0; i < rnd.Next(10, 28); i++)
                {
                    try
                    {
                        keys.Add(GetFullName());
                        od.Add(keys.Last(), GetProduct());
                    }
                    catch (ArgumentException)
                    {
                        keys.RemoveAt(i--);
                    }
                }

                // виведення
                foreach (var i in keys)
                {
                    GetRes(i, (string)od[i]);
                }
            }
#endif
            #endregion

            #region StringDictionary
#if false
            StringDictionary sd = new StringDictionary();
            {
                List <string> keys = new List <string>();
                for (int i = 0; i < rnd.Next(10, 28); i++)
                {
                    try
                    {
                        keys.Add(GetFullName());
                        sd.Add(keys.Last(), GetProduct());
                    }
                    catch (ArgumentException)
                    {
                        keys.RemoveAt(i--);
                    }
                }

                // виведення
                foreach (var i in keys)
                {
                    GetRes(i, sd[i]);
                }
            }
#endif
            #endregion

            #region NameValueCollection
#if false
            NameValueCollection nvc = new NameValueCollection();
            for (int i = 0; i < rnd.Next(10, 28); i++)
            {
                nvc.Add(GetFullName(), GetProduct());
            }

            // виведення
            foreach (var i in nvc.AllKeys)
            {
                GetRes(i, nvc[i]);
            }
#endif
            #endregion

            #region List
#if false
            List <Customer> list = new List <Customer>();
            for (int i = 0; i < rnd.Next(10, 28); i++)
            {
                list.Add(GetCustomer());
            }

            // виведення
            foreach (var i in list)
            {
                GetRes(i.FullName, i.CategoryProdact);
            }
#endif
            #endregion

            #region Dictionary
#if false
            Dictionary <string, string> d = new Dictionary <string, string>();
            for (int i = 0; i < rnd.Next(10, 28); i++)
            {
                try
                {
                    d.Add(GetFullName(), GetProduct());
                }
                catch (ArgumentException)
                {
                    i--;
                }
            }

            // виведення
            foreach (var i in d)
            {
                GetRes(i.Key, i.Value);
            }
#endif
            #endregion

            #region SortedDictionary
#if false
            SortedDictionary <string, string> sd = new SortedDictionary <string, string>();
            for (int i = 0; i < rnd.Next(10, 28); i++)
            {
                try
                {
                    sd.Add(GetFullName(), GetProduct());
                }
                catch (ArgumentException)
                {
                    i--;
                }
            }

            // виведення
            foreach (var i in sd)
            {
                GetRes(i.Key, i.Value);
            }
#endif
            #endregion

            #region LinkedList
#if false
            LinkedList <Customer> ll = new LinkedList <Customer>();
            for (int i = 0; i < rnd.Next(10, 28); i++)
            {
                ll.AddLast(GetCustomer());
            }

            // виведення
            foreach (var i in ll)
            {
                GetRes(i.FullName, i.CategoryProdact);
            }
#endif
            #endregion

            #region ArrayList
#if false
            ArrayList al = new ArrayList();
            for (int i = 0; i < rnd.Next(10, 28); i++)
            {
                al.Add(GetCustomer());
            }

            // виведення
            foreach (var i in al)
            {
                GetRes(((Customer)i).FullName, ((Customer)i).CategoryProdact);
            }
#endif
            #endregion

            #region Queue
#if false
            Queue <Customer> q = new Queue <Customer>();
            List <Customer>  l = new List <Customer>();
            for (int i = 0; i < rnd.Next(10, 28); i++)
            {
                l.Add(GetCustomer());
                q.Enqueue(l.Last());
            }

            // виведення
            foreach (var i in l)
            {
                GetRes(i.FullName, i.CategoryProdact);
            }
            Console.WriteLine();
#if false
            foreach (var i in q)
            {
                GetRes(i.FullName, i.CategoryProdact);
            }
#if false    // можна отримати доступ і після проходження всього перебору
            {
                Customer i = q.Dequeue();
                GetRes(i.FullName, i.CategoryProdact);
            }
#endif
#endif
#if true
            while (q.Count > 0)
            {
                Customer i = q.Dequeue();
                GetRes(i.FullName, i.CategoryProdact);
            }
#endif
#endif
            #endregion

            #region Stack
#if true
            Stack <Customer> s = new Stack <Customer>();
            List <Customer>  l = new List <Customer>();
            for (int i = 0; i < rnd.Next(10, 28); i++)
            {
                l.Add(GetCustomer());
                s.Push(l.Last());
            }

            // виведення
            foreach (var i in l)
            {
                GetRes(i.FullName, i.CategoryProdact);
            }
            Console.WriteLine();
#if false
            foreach (var i in s)
            {
                GetRes(i.FullName, i.CategoryProdact);
            }
#if true    // можна отримати доступ і після проходження всього перебору
            {
                Customer i = s.Pop();
                GetRes(i.FullName, i.CategoryProdact);
            }
#endif
#endif
#if true
            while (s.Count > 0)
            {
                Customer i = s.Pop();
                GetRes(i.FullName, i.CategoryProdact);
            }
#endif
#endif
            #endregion

            // repeat
            DoExitOrRepeat();
        }
Exemplo n.º 54
0
 /// <summary>
 /// Attempt to compile the inputted token as this object
 /// </summary>
 /// <param name="rootStatement"></param>
 /// <param name="strings"></param>
 public virtual void Compile(CompiledStatement parent, string token, LinkedList <string> tokens, LinkedList <string> lines)
 {
 }
Exemplo n.º 55
0
        /// <summary>
        /// Main calculation engine
        /// </summary>
        /// <param name="tokenList">Tokens in linked list</param>
        /// <param name="maxDepth">Maximum depth level of brackets</param>
        /// <returns>Sum of the math expression</returns>
        public double Calculate(LinkedList <Token> tokenList, int maxDepth)
        {
            double result = 0.0;

            // Process based on depth level
            for (int iDepth = maxDepth; iDepth >= 0; iDepth--)
            {
                LinkedListNode <Token> currentNode = tokenList.First;

                // Process multiplication and division first
                while (currentNode != null)
                {
                    LinkedListNode <Token> nextNode = currentNode.Next;

                    if (currentNode.Value.Depth == iDepth)
                    {
                        switch (currentNode.Value.Operation)
                        {
                        case Operation.Multiply:
                            currentNode.Next.Value.Number = currentNode.Previous.Value.Number * currentNode.Next.Value.Number;
                            tokenList.Remove(currentNode.Previous);
                            tokenList.Remove(currentNode);
                            break;

                        case Operation.Divide:
                            currentNode.Next.Value.Number = currentNode.Previous.Value.Number / currentNode.Next.Value.Number;
                            tokenList.Remove(currentNode.Previous);
                            tokenList.Remove(currentNode);
                            break;
                        }
                    }
                    currentNode = nextNode;
                }

                // Go back to first node
                currentNode = tokenList.First;

                // Process add and subtract
                while (currentNode != null)
                {
                    LinkedListNode <Token> nextNode = currentNode.Next;

                    if (currentNode.Value.Depth == iDepth)
                    {
                        switch (currentNode.Value.Operation)
                        {
                        case Operation.Add:
                            currentNode.Next.Value.Number = currentNode.Previous.Value.Number + currentNode.Next.Value.Number;
                            tokenList.Remove(currentNode.Previous);
                            tokenList.Remove(currentNode);
                            break;

                        case Operation.Subtract:
                            currentNode.Next.Value.Number = currentNode.Previous.Value.Number - currentNode.Next.Value.Number;
                            tokenList.Remove(currentNode.Previous);
                            tokenList.Remove(currentNode);
                            break;
                        }
                    }
                    currentNode = nextNode;
                }
            }

            if (tokenList.First.Value != null)
            {
                int roundToDecimal = int.Parse(_configuration.GetSection("RoundToDecimal").Value);
                result = Math.Round(tokenList.First.Value.Number, roundToDecimal);
            }

            return(result);
        }
Exemplo n.º 56
0
 /// <inheritdoc cref="LavaQueue{T}" />
 public LavaQueue()
 {
     _random = new Random();
     _linked = new LinkedList <T>();
 }
Exemplo n.º 57
0
        private static void Random(int run_times, int parent_no)
        {
            //hold city numbers
            LinkedList <int> cities_no      = new LinkedList <int>();
            LinkedList <int> init_cities_no = new LinkedList <int>();

            Double temp_distance = 0.0, total_distance = 0.0;

            //Map.Entry<Integer, LinkedList<Double>> entry : main_locations.entrySet()

            foreach (int key in main_locations.Keys)
            {
                init_cities_no.add(key);
            }
            cities_no.addAll(init_cities_no);
            int recheck_counter = 0, success_counter = 0;

            //clear path on each run
            path.Clear();
            for (int x = 0; x < parent_no; x++)
            {
                Console.WriteLine("=====================");
                String t_path = "";
                start_location = 1;
                temp_distance  = 0.0;
                if (recheck_counter == run_times || success_counter == parent_no)
                {
                    break;
                }

                if (cities_no.Count == 0)
                {
                    cities_no.addAll(init_cities_no);
                }

                for (;;)
                {
                    if (cities_no.Count == 1)
                    {
                        temp_distance += nn(start_location, 1);
                        Console.WriteLine("Travelling from city " + start_location + " to city " + 1);
                        t_path += start_location;
                        if (temp_distance < total_distance || total_distance == 0.0)
                        {
                            total_distance           = temp_distance;
                            best_generation_distance = total_distance;
                            best_generation          = "Parent";
                            best_genertion_path      = t_path;
                            path.add(t_path);
                            success_counter += 1;
                        }
                        else
                        {
                            recheck_counter += 1;
                        }
                        Console.WriteLine("Total Distance is " + temp_distance);
                        cities_no.Clear();
                        break;
                    }

                    int random_city = sr.Next(cities_no.Count);
                    //make sure random city is not the current city
                    if (cities_no.get(random_city) == start_location)
                    {
                        for (;;)
                        {
                            random_city = sr.Next(cities_no.Count);
                            if (cities_no.get(random_city) != start_location)
                            {
                                break;
                            }
                        }
                    }
                    temp_distance += nn(start_location, cities_no.get(random_city));
                    t_path        += start_location + ",";
                    Console.WriteLine("Travelling from city " + start_location + " to city " + cities_no.get(random_city));
                    int prev_start_loc = start_location;
                    start_location = cities_no.get(random_city);
                    cities_no.remove(cities_no.indexOf(prev_start_loc));
                }
            }
            foreach (String s in path)
            {
                Console.WriteLine("Parent : " + s);
            }
            if (path.Count != parent_no)
            {
                Random(run_times, parent_no);
            }
            else
            {
                for (int i = 0; i <= genertions; i++)
                {
                    //GA(path,"both");
                    GA(path, "single point");
                }

                Console.WriteLine("================================");
                Console.WriteLine("Shortest Distance " + best_generation_distance + " Gotten in " + best_generation + " With a City Travel Path of " + best_genertion_path);
                Console.WriteLine("================================");
            }
        }
 public FlatArray(object input)
 {
     _FlatArray = new LinkedList<int>();
     _input = input;
 }
Exemplo n.º 59
0
        private static String mutation(String child_path, int parent_length)
        {
            String result       = "";
            int    fail_counter = 0;

            for (;;)
            {
                //create a list to hold city_no to be used to prevent travelling to the same city twice
                LinkedList <int> cities      = new LinkedList <int>();
                LinkedList <int> init_cities = new LinkedList <int>();
                LinkedList <int> cities_index_to_be_mutated = new LinkedList <int>();
                int cities_no_to_be_mutated_count           = 0;
                for (int i = 1; i <= parent_length; i++)
                {
                    init_cities.add(i);
                }
                cities.addAll(init_cities);

                //converted mutation to method, so adjustments had to be made
                LinkedList <int> children = new LinkedList <int>();
                foreach (String s in child_path.Split(','))
                {
                    children.add(Convert.ToInt32(s));
                }
                //mutation phase
                //phase 1: get duplicates
                for (int i = 0; i < children.Count; i++)
                {
                    if (cities.Contains(children.get(i)))
                    {
                        cities.remove(cities.indexOf(children.get(i)));
                    }
                    else
                    {
                        cities_index_to_be_mutated.add(i);
                        //Console.WriteLine("Duplicate City " + children.get(i) + " At Index " + i);
                        cities_no_to_be_mutated_count += 1;
                    }
                }
                //Console.WriteLine("Cities size is " + cities.Count);

                //phase 2: replace duplicates
                for (int i = 0; i < cities_no_to_be_mutated_count; i++)
                {
                    int replace_city = sr.Next(cities.Count);

                    children.remove(cities_index_to_be_mutated.get(i));
                    children.add(cities_index_to_be_mutated.get(i), cities.get(replace_city));
                    cities.remove(cities.indexOf(cities.get(replace_city)));
                }

                //phase 3: Swapping
                //swap 4 indexes in the children randomly in 2s
                LinkedList <int> swapped_indexes = new LinkedList <int>();
                for (int i = 0; i < 2; i++)
                {
                    int swap_index_1 = sr.Next(parent_length - 2 + 1) + 1;
                    int swap_index_2 = sr.Next(parent_length - 4 + 1) + 1;
                    //keep on generating indexes until 2 different indexes that arent already swapped are created.
                    for (;;)
                    {
                        if ((swap_index_1 != swap_index_2 && (!swapped_indexes.Contains(swap_index_1) || !swapped_indexes.Contains(swap_index_2))))
                        {
                            break;
                        }
                        swap_index_1 = sr.Next(parent_length - 2 + 1) + 1;
                        swap_index_2 = sr.Next(parent_length - 4 + 1) + 1;
                    }
                    int prev_value_index1 = children.get(swap_index_1);
                    int prev_value_index2 = children.get(swap_index_2);

                    children.remove(swap_index_1);
                    children.add(swap_index_1, prev_value_index2);
                    //second random index
                    children.remove(swap_index_2);
                    children.add(swap_index_2, prev_value_index1);

                    swapped_indexes.add(swap_index_1);
                    swapped_indexes.add(swap_index_2);
                }

                result = "";
                //Console.WriteLine("Corrected Child :");
                foreach (int i in children)
                {
                    result += i + ",";
                    //Console.Write(i+" ");
                }
                //Console.WriteLine("");

                result        = result.Substring(0, result.Length - 1);
                fail_counter += 1;

                if (!unique.Contains(result) || fail_counter == _10P)
                {
                    if (fail_counter != _10P)
                    {
                        unique.add(result);
                    }

                    break;
                }
                //Console.WriteLine(result.Substring(0, result.Length - 1));
                //Environment.Exit(0);
            }
            return(result);
        }
Exemplo n.º 60
0
 public ProgramPack(string name, string description)
 {
     Name = name;
     Description = description;
     Programs = new LinkedList<ProgramSetting>();
 }