private static void Search(int collectionSize, int searchItemsCount)
        {
            Console.WriteLine($"V množině o velikost {collectionSize:n0} hledáno {searchItemsCount:n0}x:");

            #region Sample data
            var sw = new System.Diagnostics.Stopwatch();
            var list = new List<Guid>();
            var dictionary = new Dictionary<Guid, object>();
            foreach (var guid in Enumerable.Range(0, collectionSize).Select(g => Guid.NewGuid()))
            {
                list.Add(guid);
                dictionary.Add(guid, null);
            }
            var lookup = list.ToLookup(i => i);
            var sortedArray = list.ToArray();
            Array.Sort(sortedArray);

            // vytvoření sample-dat, které budeme hledat
            var rand = new Random();
            var hledane = Enumerable.Range(0, searchItemsCount).Select(g => (rand.NextDouble() > 0.5) ? Guid.NewGuid() : list[rand.Next(list.Count)]).ToList();

            #endregion

            // Contains = sekvenční vyhledávání = O(n)
            sw.Start();
            int found = hledane.Count(t => list.Contains(t));
            sw.Stop();
            Console.WriteLine($"\tList<>.Contains():          Nalezeno {found:n0}x, čas {sw.ElapsedTicks,10:n0} ticks");

            // binární půlení = O(log(n))
            sw.Restart();
            found = hledane.Count(t => Array.BinarySearch<Guid>(sortedArray, t) >= 0);
            sw.Stop();
            Console.WriteLine($"\tArray.BinarySearch<>():     Nalezeno {found:n0}x, čas {sw.ElapsedTicks,10:n0} ticks");

            // Dictionary = Hashtable, O(1)
            sw.Restart();
            found = hledane.Count(t => dictionary.ContainsKey(t));
            sw.Stop();
            Console.WriteLine($"\tDictionary<>.ContainsKey(): Nalezeno {found:n0}x, čas {sw.ElapsedTicks,10:n0} ticks");

            // Dictionary = Hashtable, O(1)
            sw.Restart();
            found = hledane.Count(i => lookup.Contains(i));
            sw.Stop();
            Console.WriteLine($"\tLINQ ILookup:               Nalezeno {found:n0}x, čas {sw.ElapsedTicks,10:n0} ticks");

            Console.WriteLine();
        }
Exemple #2
0
        static private void WorkerEvents()
        {
            Tuple<EventDelegate, IPlugin> cEvent;
			System.Diagnostics.Stopwatch cWatch = new System.Diagnostics.Stopwatch();
            while (true)
            {
                try
                {
                    cEvent = _aqEvents.Dequeue();

					cWatch.Reset();
					cWatch.Restart();
					cEvent.Item1(cEvent.Item2);
					cWatch.Stop();
					if (40 < cWatch.ElapsedMilliseconds)
						(new Logger()).WriteDebug3("duration: " + cWatch.ElapsedMilliseconds + " queue: " + _aqEvents.nCount);
					if (0 < _aqEvents.nCount)
						(new Logger()).WriteDebug3(" queue: " + _aqEvents.nCount);
                }
                catch (System.Threading.ThreadAbortException)
                {
                    break;
                }
                catch (Exception ex)
                {
                    (new Logger()).WriteError(ex);
                }
            }
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Indata
            WR_Structure structure = null;
            bool go = false;
            List<int> modes = new List<int>();
            double sFac = 0;

            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();

            if (!DA.GetData(0, ref structure)) { return; }
            if (!DA.GetData(1, ref go)) { return; }
            if (!DA.GetDataList(2, modes)) { return; }
            if (!DA.GetData(3, ref sFac)) { return; }

            if (go)
            {
                _resElems = new List<ResultElement>();
                _log.Clear();
                watch.Restart();

                // Solve
                WR_ModeShapeOptimizer optimizer = new WR_ModeShapeOptimizer(structure);

                watch.Stop();

                _log.Add(String.Format("Initialising: {0}ms", watch.ElapsedMilliseconds));

                watch.Restart();

                //Run
                optimizer.Run(modes, sFac);

                watch.Stop();

                _log.Add(String.Format("Run mode shape optimization: {0}ms", watch.ElapsedMilliseconds));

                watch.Restart();

                // Extract results
                List<WR_IElement> elems = structure.GetAllElements();
                for (int i = 0; i < elems.Count; i++)
                {

                    if (elems[i] is WR_Element3d)
                    {
                        WR_Element3d el3d = (WR_Element3d)elems[i];
                        ResultElement re = new ResultElement(el3d);
                        _resElems.Add(re);
                    }
                }

                watch.Stop();

                _log.Add(String.Format("Extract results: {0}ms", watch.ElapsedMilliseconds));

            }
            DA.SetDataList(0, _log);
            DA.SetDataList(1, _resElems);
        }
 static void Main(string[] args) {
   var stopWatch = new System.Diagnostics.Stopwatch();
   stopWatch.Restart();
   run();
   stopWatch.Stop();
   Console.WriteLine(string.Format("Elapsed Time: {0:0.000} seconds", stopWatch.Elapsed.TotalSeconds));      
 }
        static private void WorkerEvents()
        {
            Tuple<EventDelegate, Effect, Effect> cEvent;
			System.Diagnostics.Stopwatch cWatch = new System.Diagnostics.Stopwatch();
			while (true)
			{
				try
				{
					cEvent = _aqEvents.Dequeue();
					cWatch.Reset();
					cWatch.Restart();
					cEvent.Item1(cEvent.Item2, cEvent.Item3);
					(new Logger()).WriteDebug3("event sended [hc = " + cEvent.Item3.GetHashCode() + "][" + cEvent.Item1.Method.Name + "]");
					cWatch.Stop();
					if (40 < cWatch.ElapsedMilliseconds)
						(new Logger()).WriteDebug3("duration: " + cWatch.ElapsedMilliseconds + " queue: " + _aqEvents.nCount);
					if (0 < _aqEvents.nCount)
						(new Logger()).WriteDebug3(" queue: " + _aqEvents.nCount);
                }
                catch (System.Threading.ThreadAbortException)
                {
                    break;
                }
                catch (Exception ex)
                {
                    (new Logger()).WriteError(ex);
                }
            }
        }
Exemple #6
0
        public static void Main1()
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();

            string path = "../../../Databases/";
            int NumberOfRecords = 1000000;
            Random rnd = new Random();
            Console.WriteLine("Start Universal Index");

            PType tp_table_element = new PTypeRecord(
                new NamedType("name", new PType(PTypeEnumeration.sstring)),
                new NamedType("age", new PType(PTypeEnumeration.integer)));
            IBearingTableImmutable table = new TableViewImmutable(path + "table", tp_table_element);
            sw.Restart();
            bool tobuild = false;
            if (tobuild)
            {
                table.Fill(Enumerable.Range(0, NumberOfRecords).Select(i =>
                    (object)(new object[] {i.ToString(), i == NumberOfRecords/2 ? -1 : i})));
                sw.Stop();
                Console.WriteLine("Load Table of {0} elements ok. Duration {1}", NumberOfRecords, sw.ElapsedMilliseconds);
            }
            IIndexImmutable<string> s_index = new IndexViewImmutable<string>(path + "s_index")
            {
                Table = (IBearingTable) table,
                KeyProducer = va => (string)((object[])va)[0]
            };
            if (tobuild)
            {
                sw.Restart();
                s_index.Build();
                sw.Stop();
                Console.WriteLine("s_index Build ok. Duration {0}", sw.ElapsedMilliseconds);
            }
            sw.Restart();
            int cnt = 0;
            for (int i = 0; i < 1000; i++)
            {
                int c = s_index.GetAllByKey(rnd.Next(NumberOfRecords - 1).ToString()).Count();
                if (c > 1) Console.WriteLine("Unexpected Error: {0}", c);
                cnt += c;
            }
            sw.Stop();
            Console.WriteLine("1000 GetAllByKey ok. Duration={0} cnt={1}", sw.ElapsedMilliseconds, cnt);
        }
        static void Main(string[] args)
        {
            LinkedList<int> list = new LinkedList<int>();

              int i = 1;
              while (i <= 100000)
              {
            list.AddLast(i);
            i++;
              }

              System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
              Console.WriteLine("Measurements in ticks");
              int loopsCounter;

              #region foreach
            loopsCounter = 0;
            timer.Restart();
            foreach (int j in list)
            {
              loopsCounter++;
              int x = j;
            }
            timer.Stop();
            Console.WriteLine("{0,-8}: {1,8} (items count: {2})", "foreach", timer.ElapsedTicks, loopsCounter);
              #endregion

              #region nodes
            loopsCounter = 0;
            timer.Restart();
            LinkedListNode<int> node = list.First;
            while (node != null)
            {
              loopsCounter++;
              int y = node.Value;
              node = node.Next;
            }
            timer.Stop();
            Console.WriteLine("{0,-8}: {1,8} (items count: {2})", "nodes", timer.ElapsedTicks, loopsCounter);
              #endregion

              Console.ReadLine();
        }
        public void TestBasicLineSymbolizer()
        {
            var p = new SharpMap.Data.Providers.ShapeFile(@"d:\\daten\GeoFabrik\\roads.shp", false);
            var l = new SharpMap.Layers.VectorLayer("roads", p);
            //l.Style.Outline = new System.Drawing.Pen(System.Drawing.Color.Firebrick, 5);
            l.Style.Line = new System.Drawing.Pen(System.Drawing.Color.Gold, 1);
            l.Style.EnableOutline = false;
            var m = new SharpMap.Map(new System.Drawing.Size(1440,1080)) {BackColor = System.Drawing.Color.Cornsilk};
            m.Layers.Add(l);

            m.ZoomToExtents();

            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            m.GetMap();

            sw.Stop();
            System.Console.WriteLine(string.Format("Rendering old method: {0}ms", sw.ElapsedMilliseconds));
            sw.Restart();
            var bmp = m.GetMap();
            sw.Stop();
            System.Console.WriteLine(string.Format("Rendering old method: {0}ms", sw.ElapsedMilliseconds));
            bmp.Save("NDSRoads1.bmp");


            var cls = new SharpMap.Rendering.Symbolizer.CachedLineSymbolizer();
            //cls.LineSymbolizeHandlers.Add(new SharpMap.Rendering.Symbolizer.PlainLineSymbolizeHandler { Line = new System.Drawing.Pen(System.Drawing.Color.Firebrick, 5) });
            cls.LineSymbolizeHandlers.Add(new SharpMap.Rendering.Symbolizer.PlainLineSymbolizeHandler { Line = new System.Drawing.Pen(System.Drawing.Color.Gold, 1) });

            l.Style.LineSymbolizer = cls;
            sw.Restart();
            bmp = m.GetMap();
            sw.Stop();
            System.Console.WriteLine(string.Format("Rendering new method: {0}ms", sw.ElapsedMilliseconds));
            bmp.Save("NDSRoads2.bmp");

        }
Exemple #9
0
 public void Execute()
 {
     System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
     sw.Restart();
     try
     {
         OnExecute();
     }
     catch(Exception e)
     {
         LastError = e;
     }
     sw.Stop();
     UserTime = sw.Elapsed.TotalMilliseconds;
 }
        public void TestPlainPolygonSymbolizer()
        {
            var provider = new SharpMap.Data.Providers.ShapeFile(
                "..\\..\\..\\WinFormSamples\\GeoData\\World\\countries.shp", true);
            var l = new SharpMap.Layers.Symbolizer.PolygonalVectorLayer("Countries", provider);
            l.Symbolizer = new ModifiedBasicPolygonSymbolizer
                {
                    Fill = new System.Drawing.Drawing2D.HatchBrush(
                            System.Drawing.Drawing2D.HatchStyle.WideDownwardDiagonal, 
                            System.Drawing.Color.Red /*,
                            System.Drawing.Color.LightPink*/),
                    UseClipping = false,
                    //Outline = System.Drawing.Pens.AliceBlue
                };

            var m = new SharpMap.Map(new System.Drawing.Size(1440, 1080)) { BackColor = System.Drawing.Color.Cornsilk };
            m.Layers.Add(l);

            m.ZoomToExtents();

            var sw = new System.Diagnostics.Stopwatch();
            var img = m.GetMap();
            
            sw.Start();
            img = m.GetMap();
            img.Save("PolygonSymbolizer-1.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
            sw.Stop();
            System.Console.WriteLine(string.Format("Rendering new method:{0}ms", sw.ElapsedMilliseconds));

            l.Symbolizer = new SharpMap.Rendering.Symbolizer.BasicPolygonSymbolizer()
            {
                Fill = new System.Drawing.Drawing2D.HatchBrush(
                        System.Drawing.Drawing2D.HatchStyle.WideDownwardDiagonal,
                        System.Drawing.Color.Red/*,
                        System.Drawing.Color.LightPink*/),
                UseClipping = false,
                //Outline = System.Drawing.Pens.AliceBlue
            };

            sw.Restart();
            img = m.GetMap();
            img.Save("PolygonSymbolizer-2.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
            sw.Stop();
            System.Console.WriteLine(string.Format("Rendering new method:{0}ms", sw.ElapsedMilliseconds));
        
        }
Exemple #11
0
        static void Main(string[] args)
        {
            var context = new SoftUniEntities();
            var totalCount = context.Employees.Count();
            var stopWatch = new System.Diagnostics.Stopwatch();

            stopWatch.Start();
            var names = GetNamesWithNativeQuery(context);
            stopWatch.Stop();
            Console.WriteLine("Native: {0}", stopWatch.Elapsed);
            //Console.WriteLine(string.Join(", ", names));

            stopWatch.Restart();
            var names2 = GetNamesWithLinqQuery(context);
            stopWatch.Stop();
            Console.WriteLine("Linq: {0}", stopWatch.Elapsed);
            //Console.WriteLine(string.Join(", ", names2));
        }
Exemple #12
0
        public void TryJaggedArraySpeed()
        {
            int[][] jaggedArray;

            var sw = new System.Diagnostics.Stopwatch();

            for (int iterations = 0; iterations < Iterations; iterations++)
            {
                jaggedArray = new int[2][];

                for (int i = 0; i < 2; i++)
                {
                    jaggedArray[i] = new int[3];
                }
            }

            TestContext.WriteLine("jagged creation: " + sw.Elapsed);

            jaggedArray = new int[2][];

            for (int i = 0; i < 2; i++)
            {
                jaggedArray[i] = new int[3];
            }

            TestContext.WriteLine("jaggedArray rank:" + jaggedArray.Rank);

            sw.Restart();

            for (int iterations = 0; iterations < Iterations; iterations++)
                for (int i = 0; i < 2; i++)
                    for (int j = 0; j < 2; j++)
                    {
                        int tmp = jaggedArray[i][j];

                        jaggedArray[i][j] = i * j;
                    }

            TestContext.WriteLine("jagged array access & replace time: " + sw.Elapsed);
        }
Exemple #13
0
        public void SpeedTest()
        {
            string dsdPath = Utility.GetPath("lib\\StructureSample.xml");
            const int smallLoopCount = 1;
            const int bigLoopCount = 1000;
            var list = new List<decimal>();
            var list2 = new List<TimeSpan>();
            for (int i = 0; i < bigLoopCount; i++)
            {
                var stopWatch = new System.Diagnostics.Stopwatch();
                stopWatch.Start();

                for (int j = 0; j < smallLoopCount; j++)
                {
                    using (var reader = XmlReader.Create(dsdPath))
                    {
                        while (reader.Read())
                        { }
                    }
                }

                stopWatch.Stop();
                long ticks = stopWatch.ElapsedTicks;
                stopWatch.Restart();
                for (int k = 0; k < smallLoopCount; k++)
                {
                    var message = StructureMessage.Load(dsdPath);
                }

                stopWatch.Stop();
                Console.Write((decimal)stopWatch.ElapsedTicks / ticks);
                list.Add((decimal)stopWatch.ElapsedTicks / ticks);
                list2.Add(stopWatch.Elapsed);
                Console.WriteLine(" : {0}", stopWatch.Elapsed);
            }

            Console.WriteLine("Average: {0}", list.Average());
            Console.WriteLine("Average Time: {0}", TimeSpan.FromTicks((long)list2.Select(i => i.Ticks).Average()));
        }
		/// <summary>
		/// User has clicked button to search the log files based on the given pattern, so 
		/// let's up an set of tasks to run this in the background so we don't lock the UI.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void cmdSearch_Click(object sender, RoutedEventArgs e)
		{
			this.txtblkResults.Text = "";      // clear previous results...

			this.cmdSearch.IsEnabled = false;  // disable button until we are done:
			this.spinnerWait.Visibility = System.Windows.Visibility.Visible;
			this.spinnerWait.Spin = true;

			var sw = new System.Diagnostics.Stopwatch();  // start clock:
			sw.Restart();

			//
			// search all the files listed in the listbox:
			//
			List<string> filenames = new List<string>();

			foreach (DisplayFileName dfn in this.lstFiles.Items)
				filenames.Add(dfn.FullFileName);

			string pattern = this.txtPattern.Text;

			// create a task to make the call so we don't lock up the UI:
			Task<int> search = Task.Factory.StartNew<int>(() =>
				{
					return SearchFiles(filenames, pattern);
				}
			);

			//
			// When the search task finishes, update the UI.  We another task to wait for the result 
			// so that we don't lock up the UI waiting --- but this has to be a separate task since
			// any UI work must be done by the thread that owns the UI (the main thread):
			//
			Task UpdateUI = search.ContinueWith((antecedent) =>
				{
					try
					{
						int hits = antecedent.Result;

						var timeinMS = sw.ElapsedMilliseconds;  // stop clock:
						double time = timeinMS / 1000.0;  // convert to secs:

						string results = string.Format("Hits:\t{0:#,##0}\nFiles:\t{1:#,##0}\nTime:\t{2:#,##0.00} secs\n",
							hits,
							lstFiles.Items.Count,
							time);

						this.txtblkResults.Text = results;
					}
					catch (AggregateException ae)
					{
						this.txtblkResults.Text = "";

						ae = ae.Flatten();
						foreach (Exception ex in ae.InnerExceptions)
							this.txtblkResults.Text += string.Format("**Error: '{0}'\n", ex.Message);
					}
					catch (Exception ex)
					{
						this.txtblkResults.Text = string.Format("**Error: '{0}'\n", ex.Message);
					}

					// reset UI:
					this.spinnerWait.Spin = false;
					this.spinnerWait.Visibility = System.Windows.Visibility.Collapsed;

					this.cmdSearch.IsEnabled = true;  // re-enable button:
				},

				TaskScheduler.FromCurrentSynchronizationContext()  // must run on current (UI) thread:
			);
		}
Exemple #15
0
        public static void Test3()
        {
            //var ii = IndirectInvokerBuilder.Create();
            var ii = IndirectInvokerBuilder.Create(ProxyCtor.GetModuleBuilder());
            var sample = new Sample2();
            var isample = (ISample)sample;
            var mixin = new ProxyMixin.Mixins.InterceptorMixin<Sample2, ISample>(ProxyMixin.ProxyCtor.IndirectInvoker);
            var proxy = ProxyMixin.Ctors.InterceptorCtor.Create<Sample2, ISample>(sample, mixin);
            var foo = new Foo();
            //var mi = typeof(Sample).GetInterfaceMap(typeof(ISample)).TargetMethods[0];
            var mi = typeof(Sample).GetMethod("Ref");

            var invoker = MethodInfoInvoker.Create(mi, ii);

            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            for (int i = 0; i < 1000000; i++)
            {
                //proxy.Virtual(41, "qq");
                var args = invoker.CreateParameters((Sample)sample, 44, foo, "eee", isample);
                //var args = invoker.CreateParameters((Sample)sample, 41, "qqq");
                invoker.Invoke(args);
            }
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);

            sw.Restart();
            for (int i = 0; i < 1000000; i++)
            {
                //isample.Virtual(41, "qq");
                var fooBase = (FooBase)foo;
                sample.Ref(44, ref fooBase, "eee", ref isample);
                //var args2 = new Object[] { 41, "qq" };
                //mi.Invoke(sample, args2);
            }
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);
        }
Exemple #16
0
		public static DataTable GetProvList(DateTime dt) {
			if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
				return Meth.GetTable(MethodBase.GetCurrentMethod(),dt);
			}
#if DEBUG
			_elapsedTimeProvList="";
			System.Diagnostics.Stopwatch stopWatch=new System.Diagnostics.Stopwatch();
			System.Diagnostics.Stopwatch stopWatchTotal=new System.Diagnostics.Stopwatch();
			_elapsedTimeProvList="Elapsed time for GetProvList:\r\n";
			stopWatch.Restart();
			stopWatchTotal.Restart();
#endif
			Random rnd=new Random();
			string rndStr=rnd.Next(1000000).ToString();
			string command;
			command="DROP TABLE IF EXISTS tempdash"+rndStr+@";";
			Db.NonQ(command);
#if DEBUG
			stopWatch.Stop();
			_elapsedTimeProvList+="DROP TABLE: "+stopWatch.Elapsed.ToString()+"\r\n";
			stopWatch.Restart();
#endif
			command=@"CREATE TABLE tempdash"+rndStr+@" (
				ProvNum bigint NOT NULL PRIMARY KEY,
				production decimal NOT NULL,
				income decimal NOT NULL
				) DEFAULT CHARSET=utf8";
			Db.NonQ(command);
#if DEBUG
			stopWatch.Stop();
			_elapsedTimeProvList+="CREATE TABLE: "+stopWatch.Elapsed.ToString()+"\r\n";
			stopWatch.Restart();
#endif
			//providers
			command=@"INSERT INTO tempdash"+rndStr+@" (ProvNum)
				SELECT ProvNum
				FROM provider WHERE IsHidden=0
				ORDER BY ItemOrder";
			Db.NonQ(command);
#if DEBUG
			stopWatch.Stop();
			_elapsedTimeProvList+="providers: "+stopWatch.Elapsed.ToString()+"\r\n";
			stopWatch.Restart();
#endif
			//production--------------------------------------------------------------------
			//procs
			command=@"UPDATE tempdash"+rndStr+@" 
				SET production=(SELECT SUM(ProcFee*(UnitQty+BaseUnits)) FROM procedurelog 
				WHERE procedurelog.ProvNum=tempdash"+rndStr+@".ProvNum
				AND procedurelog.ProcStatus="+POut.Int((int)ProcStat.C)+@"
				AND ProcDate="+POut.Date(dt)+")";
			Db.NonQ(command);
#if DEBUG
			stopWatch.Stop();
			_elapsedTimeProvList+="production - procs: "+stopWatch.Elapsed.ToString()+"\r\n";
			stopWatch.Restart();
#endif
			//capcomplete writeoffs were skipped
			//adjustments
			command=@"UPDATE tempdash"+rndStr+@" 
				SET production=production+(SELECT IFNULL(SUM(AdjAmt),0) FROM adjustment 
				WHERE adjustment.ProvNum=tempdash"+rndStr+@".ProvNum
				AND AdjDate="+POut.Date(dt)+")";
			Db.NonQ(command);
#if DEBUG
			stopWatch.Stop();
			_elapsedTimeProvList+="production - adjustments: "+stopWatch.Elapsed.ToString()+"\r\n";
			stopWatch.Restart();
#endif
			//insurance writeoffs
			if(PrefC.GetBool(PrefName.ReportsPPOwriteoffDefaultToProcDate)) {//use procdate
				command=@"UPDATE tempdash"+rndStr+@" 
					SET production=production-(SELECT IFNULL(SUM(WriteOff),0) FROM claimproc 
					WHERE claimproc.ProvNum=tempdash"+rndStr+@".ProvNum
					AND ProcDate="+POut.Date(dt)+@" 
					AND (claimproc.Status=1 OR claimproc.Status=4 OR claimproc.Status=0) )";//received or supplemental or notreceived
			}
			else {
				command=@"UPDATE tempdash"+rndStr+@" 
					SET production=production-(SELECT IFNULL(SUM(WriteOff),0) FROM claimproc 
					WHERE claimproc.ProvNum=tempdash"+rndStr+@".ProvNum
					AND DateCP="+POut.Date(dt)+@" 
					AND (claimproc.Status=1 OR claimproc.Status=4) )";//received or supplemental 
			}
			Db.NonQ(command);
#if DEBUG
			stopWatch.Stop();
			_elapsedTimeProvList+="production - writeoffs: "+stopWatch.Elapsed.ToString()+"\r\n";
			stopWatch.Restart();
#endif
			//income------------------------------------------------------------------------
			//patient income
			command=@"UPDATE tempdash"+rndStr+@" 
				SET income=(SELECT SUM(SplitAmt) FROM paysplit 
				WHERE paysplit.ProvNum=tempdash"+rndStr+@".ProvNum
				AND DatePay="+POut.Date(dt)+")";
			Db.NonQ(command);
#if DEBUG
			stopWatch.Stop();
			_elapsedTimeProvList+="income - patient: "+stopWatch.Elapsed.ToString()+"\r\n";
			stopWatch.Restart();
#endif
			//ins income
			command=@"UPDATE tempdash"+rndStr+@" 
				SET income=income+(SELECT IFNULL(SUM(InsPayAmt),0) FROM claimproc 
				WHERE claimproc.ProvNum=tempdash"+rndStr+@".ProvNum
				AND DateCP="+POut.Date(dt)+")";
			Db.NonQ(command);
#if DEBUG
			stopWatch.Stop();
			_elapsedTimeProvList+="income - insurance: "+stopWatch.Elapsed.ToString()+"\r\n";
			stopWatch.Restart();
#endif
			//final queries
			command="SELECT * FROM tempdash"+rndStr+@"";
			DataTable table=Db.GetTable(command);
#if DEBUG
			stopWatch.Stop();
			_elapsedTimeProvList+="SELECT * : "+stopWatch.Elapsed.ToString()+"\r\n";
			stopWatch.Restart();
#endif
			command="DROP TABLE IF EXISTS tempdash"+rndStr+@";";
			Db.NonQ(command);
#if DEBUG
			stopWatch.Stop();
			stopWatchTotal.Stop();
			_elapsedTimeProvList+="DROP TABLE: "+stopWatch.Elapsed.ToString()+"\r\n";
			_elapsedTimeProvList+="Total: "+stopWatchTotal.Elapsed.ToString();
			if(_showElapsedTimesForDebug) {
				System.Windows.Forms.MessageBox.Show(_elapsedTimeProvList);
			}
#endif
			return table;
		}
Exemple #17
0
      public void T190_FID_PutGetCorrectness(int cnt, int tbls)
      {
        
        var sw = new System.Diagnostics.Stopwatch();
        var dicts = new ConcurrentDictionary<FID, string>[tbls];
        for(var i = 0; i<dicts.Length; i++) dicts[i] = new ConcurrentDictionary<FID, string>();
        var notInserted = 0;
        using (var cache = makeCache())
        {
            sw.Start();
            Parallel.For(0, cnt, (i) =>
            {
               var t = i % tbls;
               var tbl = cache.GetOrCreateTable<FID>(t.ToString());

               var key = FID.Generate();
               var data = NFX.Parsing.NaturalTextGenerator.Generate(0);

               var pr = tbl.Put(key, data);
               dicts[t].TryAdd(key, data);
               if (pr!=PutResult.Inserted)
                 Interlocked.Increment(ref notInserted);
            });
        

            var elapsed = sw.ElapsedMilliseconds;
            var inserted = cnt - notInserted;
            Console.WriteLine("Population of {0:n0} in {1:n0} msec at {2:n0}ops/sec", cnt, elapsed, cnt /  (elapsed / 1000d) );
            Console.WriteLine("  inserted: {0:n0} ({1:n0}%)", inserted, (int) (100 * (inserted / (double)cnt) ) );
            Console.WriteLine("  not-inserted: {0:n0} ({1:n0}%)", notInserted, (int) (100 * (notInserted) / (double)cnt));
            sw.Restart();

             var found = 0;
             var notfound = 0;

            for(var i=0; i< tbls; i++)
            {
             var tbl = cache.GetOrCreateTable<FID>(i.ToString()); 
             var dict = dicts[i];
            
             Parallel.ForEach(dict, (kvp)=>
             {
                var data = tbl.Get( kvp.Key );
                if (data!=null)
                {
                  Assert.AreEqual(data, kvp.Value );
                  Interlocked.Increment(ref found);
                }
                else
                  Interlocked.Increment(ref notfound);
             });
            }
            
            elapsed = sw.ElapsedMilliseconds;
            var totalGot = found + notfound;
            Console.WriteLine("Got of {0:n0} in {1:n0} msec at {2:n0}ops/sec", totalGot, elapsed, totalGot /  (elapsed / 1000d) );
            Console.WriteLine("  found: {0:n0} ({1:n0}%)", found, (int) (100 * (found / (double)totalGot) ) );
            Console.WriteLine("  not-found: {0:n0} ({1:n0}%)", notfound, (int) (100 * (notfound) / (double)totalGot));

            Assert.IsTrue( (found / (double)inserted) > 0.9d);
        }//using cache
      }
        /// <summary>
        /// 検量線データの取得
        /// </summary>
        private bool GetCalibrationCurve()
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();

            //検量線の取得
            KD_Command command_KD = null;
            for (int chIndex = 1; chIndex <= DataCommon.Constants.MAX_CHANNELCOUNT ; chIndex++)
            {
                SystemSetting.CalibrationTables[chIndex - 1] = null;

                // 現在刺さっているボードがB/R以外ならば検量線取得しない。
                //if (RealChannelKindList[chIndex - 1] != DataCommon.ChannelKindType.B &&
                //    RealChannelKindList[chIndex - 1] != DataCommon.ChannelKindType.R)
                if (SystemSetting.HardInfoStruct.BoardInfos[chIndex - 1].ChannelKind != DataCommon.ChannelKindType.B &&
                    SystemSetting.HardInfoStruct.BoardInfos[chIndex - 1].ChannelKind != DataCommon.ChannelKindType.R)
                {
                    SystemSetting.CalibrationTables[chIndex - 1] = new CalibrationTable();
                    continue;
                }

                this.ShowCommunicationCommentEvent("MSG_COMM_COMMENT_CALIBRATION", chIndex);

                command_KD = (KD_Command)KD_Command.CreateSendData(KD_Command.SubCommandType.R);
                command_KD.Channel = (byte)chIndex;

                command_KD = (KD_Command)comm.SendAndWaitResponse(command_KD, CommRM3000.TIMEOUTDEFAULT);

                //通信成功かつACKならば情報受信待ち
                if (command_KD != null && command_KD.Result != CommandBase_RM.CMM_NAK)
                {
                    sw.Restart();

                    while (SystemSetting.CalibrationTables[chIndex - 1] == null)
                    {
                        System.Threading.Thread.Sleep(10);

                        if (sw.ElapsedMilliseconds >= 10000)
                        {
                            return false;
                        }
                    }
                }
                else
                {
                    return false;
                }
            }

            //温度補償データの取得
            TD_Command command_TD = null;

            for (int chIndex = 1; chIndex <= DataCommon.Constants.MAX_CHANNELCOUNT ; chIndex++)
            {
                                
                SystemSetting.CalibrationTables[chIndex - 1].Base_TempCalibrationCurveList = null;

                // 現在刺さっているボードがB/R以外ならば検量線取得しない。
                //if (RealChannelKindList[chIndex-1] != DataCommon.ChannelKindType.B &&
                //    RealChannelKindList[chIndex-1] != DataCommon.ChannelKindType.R) 
                if (SystemSetting.HardInfoStruct.BoardInfos[chIndex - 1].ChannelKind != DataCommon.ChannelKindType.B &&
                    SystemSetting.HardInfoStruct.BoardInfos[chIndex - 1].ChannelKind != DataCommon.ChannelKindType.R) 
                    continue;

                this.ShowCommunicationCommentEvent("MSG_COMM_COMMENT_TEMP", chIndex);

                command_TD = (TD_Command)TD_Command.CreateSendData(TD_Command.SubCommandType.R);
                command_TD.Channel = (byte)chIndex;

                command_TD = (TD_Command)comm.SendAndWaitResponse(command_TD, CommRM3000.TIMEOUTDEFAULT);

                //通信成功かつACKならば情報受信待ち
                if (command_TD != null && command_TD.Result != CommandBase_RM.CMM_NAK)
                {
                    sw.Restart();

                    while (SystemSetting.CalibrationTables[chIndex - 1].Base_TempCalibrationCurveList == null)
                    {
                        System.Threading.Thread.Sleep(10);
                        
                        if (sw.ElapsedMilliseconds >= 10000)
                        {
                            return false;
                        }
                    }

                    //補償線を生成
                    bool ret = SystemSetting.CalibrationTables[chIndex - 1].CreateCalibrationTable();

                    if (!ret)
                        return false;

                    //テスト用プリント
                    foreach (CalibrationCurve cc in SystemSetting.CalibrationTables[chIndex - 1].Calc_CalibrationCurveList)
                    {
                        System.Diagnostics.Debug.Print(cc.ToString());
                    }
                }
                else
                {
                    return false;
                }

            }

            //検量線データを出力
            SystemSetting.CalibrationTables.OutputCSV(CommonLib.SystemDirectoryPath.SystemPath);


            return true;
        }
        public void TestSpeed()
        {
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Start();
            var results = GetSolutionsFiles(null);
            watch.Stop();
            System.Diagnostics.Debug.WriteLine("FileList.files");
            System.Diagnostics.Debug.WriteLine("    time : " + watch.ElapsedMilliseconds);
            System.Diagnostics.Debug.WriteLine("    count : " + results.Count());

            watch.Restart();
            var resultsOld = FileList.files;
            watch.Stop();
            System.Diagnostics.Debug.WriteLine("FileList.filesOld");
            System.Diagnostics.Debug.WriteLine("    time : " + watch.ElapsedMilliseconds);
            System.Diagnostics.Debug.WriteLine("    count : " + resultsOld.Count());
        }
Exemple #20
0
        private void UpdateThread()
        {
            var watch = new System.Diagnostics.Stopwatch();
            watch.Start();

            while (Running)
            {
                var deltaTime = (float)watch.Elapsed.TotalSeconds;
                watch.Restart();

                InputManager.Update();

                // Run update tasks
                UpdateTasks.Execute(deltaTime);

                // Create render commands
                GameWorld.Camera.Viewport.X = WindowProvider.Width;
                GameWorld.Camera.Viewport.Y = WindowProvider.Height;

                Renderer.Render(GameWorld.GraphicsStage, GameWorld.Camera, deltaTime);
            }
        }
        private void Test()
        {
            string s1 = "我要学习{0}";
            string s2 = "C#";

            int max = 10000000;

            watch.Restart();
            for (int i = 0; i < max; i++)
            {
                string s3 = string.Format(s1, s2);
            }
            watch.Stop();
            Console.WriteLine($"string.Format:{watch.ElapsedMilliseconds}");



            watch.Restart();
            for (int i = 0; i < max; i++)
            {
                string s3 = s1.Replace("{0}", s2);
            }
            watch.Stop();
            Console.WriteLine($"string.Replace:{watch.ElapsedMilliseconds}");



            #region 比较结果 用Replace 替换比Format 要快

            /*
             *
             * string.Format:1347
             * string.Replace:688
             *
             *
             *
             * string.Format:1197
             * string.Replace:683
             *
             *
             *
             * string.Format:1023
             * string.Replace:628
             *
             *
             *
             * string.Format:1007
             * string.Replace:638
             *
             *
             *
             * string.Format:1037
             * string.Replace:616
             *
             *
             *
             * string.Format:1047
             * string.Replace:593
             *
             *
             *
             * string.Format:1020
             * string.Replace:606
             *
             *
             *
             * string.Format:1059
             * string.Replace:626
             *
             *
             *
             * string.Format:1059
             * string.Replace:604
             *
             *
             *
             * string.Format:1053
             * string.Replace:621
             *
             *
             *
             *
             */

            #endregion
        }
Exemple #22
0
		public static List<List<int>> GetProdInc(DateTime dateFrom,DateTime dateTo) {
			if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
				return Meth.GetObject<List<List<int>>>(MethodBase.GetCurrentMethod(),dateFrom,dateTo);
			}
#if DEBUG
			_elapsedTimeProdInc="";
			System.Diagnostics.Stopwatch stopWatch=new System.Diagnostics.Stopwatch();
			System.Diagnostics.Stopwatch stopWatchTotal=new System.Diagnostics.Stopwatch();
			_elapsedTimeProdInc="Elapsed time for GetProdInc:\r\n";
			stopWatch.Restart();
			stopWatchTotal.Restart();
#endif
			string command;
			command=@"SELECT procedurelog.ProcDate,
				SUM(procedurelog.ProcFee*(procedurelog.UnitQty+procedurelog.BaseUnits))-IFNULL(SUM(claimproc.WriteOff),0)
				FROM procedurelog
				LEFT JOIN claimproc ON procedurelog.ProcNum=claimproc.ProcNum
				AND claimproc.Status='7' /*only CapComplete writeoffs are subtracted here*/
				WHERE procedurelog.ProcStatus = '2'
				AND procedurelog.ProcDate >= "+POut.Date(dateFrom)+@"
				AND procedurelog.ProcDate <= "+POut.Date(dateTo)+@"
				GROUP BY MONTH(procedurelog.ProcDate)";
			DataTable tableProduction=Db.GetTable(command);
#if DEBUG
			stopWatch.Stop();
			_elapsedTimeProdInc+="tableProduction: "+stopWatch.Elapsed.ToString()+"\r\n";
			stopWatch.Restart();
#endif
			command=@"SELECT AdjDate,
				SUM(AdjAmt)
				FROM adjustment
				WHERE AdjDate >= "+POut.Date(dateFrom)+@"
				AND AdjDate <= "+POut.Date(dateTo)+@"
				GROUP BY MONTH(AdjDate)";
			DataTable tableAdj=Db.GetTable(command);
#if DEBUG
			stopWatch.Stop();
			_elapsedTimeProdInc+="tableAdj: "+stopWatch.Elapsed.ToString()+"\r\n";
			stopWatch.Restart();
#endif
			if(PrefC.GetBool(PrefName.ReportsPPOwriteoffDefaultToProcDate)) {//use procdate
				command="SELECT "
					+"claimproc.ProcDate," 
					+"SUM(claimproc.WriteOff) "
					+"FROM claimproc "
					+"WHERE claimproc.ProcDate >= "+POut.Date(dateFrom)+" "
					+"AND claimproc.ProcDate <= "+POut.Date(dateTo)+" "
					+"AND (claimproc.Status=1 OR claimproc.Status=4 OR claimproc.Status=0) " //received or supplemental or notreceived
					+"GROUP BY MONTH(claimproc.ProcDate)";
			}
			else {
				command="SELECT "
					+"claimproc.DateCP," 
					+"SUM(claimproc.WriteOff) "
					+"FROM claimproc "
					+"WHERE claimproc.DateCP >= "+POut.Date(dateFrom)+" "
					+"AND claimproc.DateCP <= "+POut.Date(dateTo)+" "
					+"AND (claimproc.Status=1 OR claimproc.Status=4) "//Received or supplemental
					+"GROUP BY MONTH(claimproc.DateCP)";
			}
			DataTable tableWriteoff=Db.GetTable(command);
#if DEBUG
			stopWatch.Stop();
			_elapsedTimeProdInc+="tableWriteoff: "+stopWatch.Elapsed.ToString()+"\r\n";
			stopWatch.Restart();
#endif
			command="SELECT "
				+"paysplit.DatePay,"
				+"SUM(paysplit.SplitAmt) "
				+"FROM paysplit "
				+"WHERE paysplit.IsDiscount=0 "
				+"AND paysplit.DatePay >= "+POut.Date(dateFrom)+" "
				+"AND paysplit.DatePay <= "+POut.Date(dateTo)+" "
				+"GROUP BY MONTH(paysplit.DatePay)";
			DataTable tablePay=Db.GetTable(command);
#if DEBUG
			stopWatch.Stop();
			_elapsedTimeProdInc+="tablePay: "+stopWatch.Elapsed.ToString()+"\r\n";
			stopWatch.Restart();
#endif
			command="SELECT claimpayment.CheckDate,SUM(claimproc.InsPayamt) "
				+"FROM claimpayment,claimproc WHERE "
				+"claimproc.ClaimPaymentNum = claimpayment.ClaimPaymentNum "
				+"AND claimpayment.CheckDate >= " + POut.Date(dateFrom)+" "
				+"AND claimpayment.CheckDate <= " + POut.Date(dateTo)+" "
				+" GROUP BY claimpayment.CheckDate ORDER BY checkdate";
			DataTable tableIns=Db.GetTable(command);
#if DEBUG
			stopWatch.Stop();
			stopWatchTotal.Stop();
			_elapsedTimeProdInc+="tableIns: "+stopWatch.Elapsed.ToString()+"\r\n";
			_elapsedTimeProdInc+="Total: "+stopWatchTotal.Elapsed.ToString();
			if(_showElapsedTimesForDebug) {
				System.Windows.Forms.MessageBox.Show(_elapsedTimeProdInc);
			}
#endif
			//production--------------------------------------------------------------------
			List<int> listInt;
			listInt=new List<int>();
			for(int i=0;i<12;i++) {
				decimal prod=0;
				decimal adjust=0;
				decimal inswriteoff=0;
				DateTime datePeriod=dateFrom.AddMonths(i);//only the month and year are important
				for(int j=0;j<tableProduction.Rows.Count;j++)  {
				  if(datePeriod.Year==PIn.Date(tableProduction.Rows[j][0].ToString()).Year
						&& datePeriod.Month==PIn.Date(tableProduction.Rows[j][0].ToString()).Month)
					{
		 			  prod+=PIn.Decimal(tableProduction.Rows[j][1].ToString());
					}
   			}
				for(int j=0;j<tableAdj.Rows.Count; j++){
				  if(datePeriod.Year==PIn.Date(tableAdj.Rows[j][0].ToString()).Year
						&& datePeriod.Month==PIn.Date(tableAdj.Rows[j][0].ToString()).Month)
					{
						adjust+=PIn.Decimal(tableAdj.Rows[j][1].ToString());
					}
   			}
				for(int j=0;j<tableWriteoff.Rows.Count; j++){
					if(datePeriod.Year==PIn.Date(tableWriteoff.Rows[j][0].ToString()).Year
						&& datePeriod.Month==PIn.Date(tableWriteoff.Rows[j][0].ToString()).Month)
					{
						inswriteoff+=PIn.Decimal(tableWriteoff.Rows[j][1].ToString());
					}
				}
				listInt.Add((int)(prod+adjust-inswriteoff));
			}
			List<List<int>> retVal=new List<List<int>>();
			retVal.Add(listInt);
			//income----------------------------------------------------------------------
			listInt=new List<int>();
			for(int i=0;i<12;i++) {
				decimal ptincome=0;
				decimal insincome=0;
				DateTime datePeriod=dateFrom.AddMonths(i);//only the month and year are important
				for(int j=0;j<tablePay.Rows.Count;j++) {
					if(datePeriod.Year==PIn.Date(tablePay.Rows[j][0].ToString()).Year
						&& datePeriod.Month==PIn.Date(tablePay.Rows[j][0].ToString()).Month) 
					{
						ptincome+=PIn.Decimal(tablePay.Rows[j][1].ToString());
					}
				}
				for(int j=0;j<tableIns.Rows.Count;j++) {//
					if(datePeriod.Year==PIn.Date(tableIns.Rows[j][0].ToString()).Year
						&& datePeriod.Month==PIn.Date(tableIns.Rows[j][0].ToString()).Month) 
					{
						insincome+=PIn.Decimal(tableIns.Rows[j][1].ToString());
					}
				}
				listInt.Add((int)(ptincome+insincome));
			}
			retVal.Add(listInt);
			return retVal;
		}
Exemple #23
0
        private static void OnRenderFrame()
        {
            watch.Stop();
            float deltaTime = (float)watch.ElapsedTicks / System.Diagnostics.Stopwatch.Frequency;

            watch.Restart();

            // perform rotation of the cube depending on the keyboard state
            if (autoRotate)
            {
                xangle += deltaTime / 2;
                yangle += deltaTime;
            }
            if (right)
            {
                yangle += deltaTime;
            }
            if (left)
            {
                yangle -= deltaTime;
            }
            if (up)
            {
                xangle -= deltaTime;
            }
            if (down)
            {
                xangle += deltaTime;
            }

            // set up the viewport and clear the previous depth and color buffers
            Gl.Viewport(0, 0, width, height);
            Gl.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

            // make sure the shader program and texture are being used
            Gl.UseProgram(program);
            Gl.BindTexture(glassTexture);

            // set up the model matrix and draw the cube
            program["model_matrix"].SetValue(Matrix4.CreateRotationY(yangle) * Matrix4.CreateRotationX(xangle));
            program["enable_lighting"].SetValue(lighting);

            Gl.BindBufferToShaderAttribute(cube, program, "vertexPosition");
            Gl.BindBufferToShaderAttribute(cubeNormals, program, "vertexNormal");
            Gl.BindBufferToShaderAttribute(cubeUV, program, "vertexUV");
            Gl.BindBuffer(cubeQuads);

            Gl.DrawElements(BeginMode.Quads, cubeQuads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);


            //Draw window
            Gl.BindTexture(kacaTexture);

            // set up the model matrix and draw the cube
            program["model_matrix"].SetValue(Matrix4.CreateRotationY(yangle) * Matrix4.CreateRotationX(xangle));
            program["enable_lighting"].SetValue(lighting);

            Gl.BindBufferToShaderAttribute(window, program, "vertexPosition");
            Gl.BindBufferToShaderAttribute(windowNormals, program, "vertexNormal");
            Gl.BindBufferToShaderAttribute(windowUV, program, "vertexUV");
            Gl.BindBuffer(windowQuads);

            Gl.DrawElements(BeginMode.Quads, windowQuads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);

            //drawwheel
            Gl.BindTexture(rodaTexture);

            Gl.BindBufferToShaderAttribute(wheel1, program, "vertexPosition");
            Gl.BindBufferToShaderAttribute(wheel1Normals, program, "vertexNormal");
            Gl.BindBufferToShaderAttribute(wheel1UV, program, "vertexUV");
            Gl.BindBuffer(wheel1Quads);

            Gl.DrawElements(BeginMode.TriangleStrip, wheel1Quads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);
            Gl.BindBufferToShaderAttribute(wheel11, program, "vertexPosition");
            Gl.DrawElements(BeginMode.TriangleStrip, wheel1Quads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);
            Gl.BindBufferToShaderAttribute(wheel21, program, "vertexPosition");
            Gl.DrawElements(BeginMode.TriangleStrip, wheel1Quads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);
            Gl.BindBufferToShaderAttribute(wheel31, program, "vertexPosition");
            Gl.DrawElements(BeginMode.TriangleStrip, wheel1Quads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);
            Gl.BindBufferToShaderAttribute(wheel41, program, "vertexPosition");

            Gl.DrawElements(BeginMode.TriangleStrip, wheel1Quads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);
            Gl.BindBufferToShaderAttribute(wheel111, program, "vertexPosition");
            Gl.DrawElements(BeginMode.TriangleStrip, wheel1Quads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);
            Gl.BindBufferToShaderAttribute(wheel211, program, "vertexPosition");
            Gl.DrawElements(BeginMode.TriangleStrip, wheel1Quads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);
            Gl.BindBufferToShaderAttribute(wheel311, program, "vertexPosition");
            Gl.DrawElements(BeginMode.TriangleStrip, wheel1Quads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);
            Gl.BindBufferToShaderAttribute(wheel411, program, "vertexPosition");

            Gl.DrawElements(BeginMode.TriangleStrip, wheel1Quads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);
            Gl.BindBufferToShaderAttribute(wheel112, program, "vertexPosition");
            Gl.DrawElements(BeginMode.TriangleStrip, wheel1Quads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);
            Gl.BindBufferToShaderAttribute(wheel212, program, "vertexPosition");
            Gl.DrawElements(BeginMode.TriangleStrip, wheel1Quads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);
            Gl.BindBufferToShaderAttribute(wheel312, program, "vertexPosition");
            Gl.DrawElements(BeginMode.TriangleStrip, wheel1Quads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);
            Gl.BindBufferToShaderAttribute(wheel412, program, "vertexPosition");

            Gl.DrawElements(BeginMode.TriangleStrip, wheel1Quads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);
            Gl.BindBufferToShaderAttribute(wheel2, program, "vertexPosition");
            Gl.DrawElements(BeginMode.TriangleStrip, wheel1Quads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);
            Gl.BindBufferToShaderAttribute(wheel3, program, "vertexPosition");
            Gl.DrawElements(BeginMode.TriangleStrip, wheel1Quads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);
            Gl.BindBufferToShaderAttribute(wheel4, program, "vertexPosition");
            Gl.DrawElements(BeginMode.TriangleStrip, wheel1Quads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);

            Glut.glutSwapBuffers();
        }
Exemple #24
0
        /// <summary>
        /// 查找到指定的表达式 没有则返回空
        /// </summary>
        /// <param name="IndexPageUrl">索引页面</param>
        /// <param name="ContentPageUrls">分析用的一个页面</param>
        /// <returns>查找到指定的表达式 没有则返回空</returns>
        public string GetPathExpression(ListPageContentUrl IndexPageUrl, System.Collections.Generic.IEnumerable <ListPageContentUrl> ContentPageUrls)
        {
            //得到当前所有的 XML分析结果
            List <XMLDocuentAnalyseEntity> xdoms = ParsPageUrlsToXDocuments(IndexPageUrl, ContentPageUrls);

            //对得到的XML内容进行分胡 取出有效的表达式
            var groups = xdoms.GroupBy(p => p.Expression);

            if (groups.Count() > 0)
            {
                //按表达式排序后的结果
                var groupOrder = groups.OrderBy(p => p.Key.Length);

                string express = groupOrder.Last().Key;

                if (express.Length > 0)
                {
                    //表达式
                    var xpathArr = express.Split('/').ToList();
                    //如果最后一个是文字节点则直接删除
                    if (xpathArr.Last().StartsWith("#"))
                    {
                        xpathArr.Remove(xpathArr.Last());
                        express = string.Join("/", xpathArr.ToArray());
                    }
                }
                //如果表达式有效
                if (!(express.Contains("&") || express.Contains("\"")))
                {
                    if (IndexPageUrl.Url.ToString() == this.IndexPageUrl.Url.ToString())
                    {
                        //返回表达式
                        return(PathExpression = express);
                    }
                    else
                    {
                        return(express);
                    }
                }
                else
                {
                    System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
                    stopwatch.Restart();
                    PathExpression = express = GetValidaXpath(from p in xdoms
                                                              select new ExpressionEntity
                    {
                        Expression = p.Expression,
                    });
                    stopwatch.Stop();

                    System.Diagnostics.Debug.WriteLine("运行  GetValidaXpath 时间为" + stopwatch.ElapsedMilliseconds);



                    return(PathExpression);
                }
                xdoms.ForEach((p) =>
                {
                    p.BaseUrlObject  = null;
                    p.Content        = null;
                    p.Expression     = null;
                    p.HtmlDocument   = null;
                    p.IndexPageUrl   = null;
                    p.OriginContent  = null;
                    p.PageTitle      = null;
                    p.XmlParseConten = null;
                });

                //清空数据
                xdoms.Clear();
            }



            return("");
        }
Exemple #25
0
        private int LoadVideo()
        {
            {
                var _videoFile = new MediaFile();
                _videoFile.Resolution     = MediaFile.ResolutionOption.Full;
                _videoFile.OutputRGBImage = false;
                _videoFile.OutputYImage   = false;
                _videoFile.OutputYData    = true;
                _videoFile.Open(_filenames.videoFilename);

                var fieldsBetweenAveragedLogoFrames = _videoFile.FieldsPerSecond;

                // Fill with maps of 127s
                const int EDGE_MAP_AVERAGE_COUNT = 29;// 100;
                var       edgeMapList            = new LinkedList <ImageProcessing.YDataFloat>();

                var stopwatch = new System.Diagnostics.Stopwatch();
                stopwatch.Start();
                var stopwatchRestartedForLogoZone = false;

                Task taskLogoDetect = null;

                int fieldNumberFPS        = 0;
                int fieldNumber           = 0;
                int fieldNumberEdgeMapAvg = (EDGE_MAP_AVERAGE_COUNT - 1) * fieldsBetweenAveragedLogoFrames / -2;
                int lastPrintSeconds      = 0;

                //return 0;

                // --------------- Start logo detection ---------------
                // Get Logo detection base frame
                ImageProcessing.YDataFloat logoDetectionFrame;
                float logoDetectionFrameAverage;
                float logoDetectionFrameMaximum;
                {
                    if (System.IO.File.Exists(_filenames.logoFilename))
                    {
                        Console.WriteLine("Loading logo from file: " + System.IO.Path.GetFileName(_filenames.logoFilename));
                        var image = new System.Drawing.Bitmap(_filenames.logoFilename);
                        logoDetectionFrame = ImageProcessing.YDataFloat.FromBitmap(image);
                    }
                    else
                    {
                        // Skip the first 5% and last 15% of the recording

                        var firstFrame = (int)(_videoFile.TotalFields * Settings.LogoDetectSearch_StartPosition_Percentage / 100);
                        firstFrame -= (firstFrame % _videoFile.FieldsPerFrame);
                        var lastFrame = (int)(_videoFile.TotalFields * Settings.LogoDetectSearch_EndPosition_Percentage / 100);
                        lastFrame -= (firstFrame % _videoFile.FieldsPerFrame);

                        const int LOGO_DETECTION_FRAMES_TO_AVERAGE = 250;
                        var       frameInterval = (lastFrame - firstFrame) / LOGO_DETECTION_FRAMES_TO_AVERAGE;
                        frameInterval -= (frameInterval % _videoFile.FieldsPerFrame);
                        if (frameInterval < 2)
                        {
                            frameInterval = 2;
                        }

                        for (fieldNumber = firstFrame; fieldNumber < lastFrame; fieldNumber += frameInterval)
                        {
                            var frameField = _videoFile.GetVideoFrameField(fieldNumber, MediaFile.SeekModes.Accurate);
                            var yData      = frameField.YData;

                            if (taskLogoDetect != null)
                            {
                                taskLogoDetect.Wait();
                            }

                            taskLogoDetect = Task.Factory.StartNew(() =>
                            {
                                var yDataFloat = yData.GetFloatData();
                                //yDataFloat.GetBitmap().Save(@"D:\temp\image-" + fieldNumber.ToString("00000") + ".png", System.Drawing.Imaging.ImageFormat.Png);
                                var edgeData = ImageProcessing.ImageProcessor.GenerateEdgeDetectedImage(yDataFloat);
                                edgeMapList.AddLast(edgeData);
                                //edgeData.GetBitmap().Save(@"D:\temp\edgeData-" + fieldNumber.ToString("00000") + ".png", System.Drawing.Imaging.ImageFormat.Png);
                            });

                            long elapsedMilliseconds = stopwatch.ElapsedMilliseconds;
                            int  elapsedSeconds      = (int)(elapsedMilliseconds / 1000);
                            if (elapsedSeconds != lastPrintSeconds)
                            {
                                lastPrintSeconds = elapsedSeconds;
                                Console.WriteLine("Searching for logo: " + (100.0f * (fieldNumber - firstFrame) / (lastFrame - firstFrame)).ToString("00") + "%");
                            }
                        }
                        if (taskLogoDetect != null)
                        {
                            taskLogoDetect.Wait();
                        }

                        logoDetectionFrame = ImageProcessing.ImageProcessor.GenerateEdgeDetectionAverage(edgeMapList, Settings.LogoDetectSearch_EdgeOfFramePadding);
                        logoDetectionFrame.ToBitmap().Save(_filenames.logoFilename, System.Drawing.Imaging.ImageFormat.Png);
                    }

                    ImageProcessing.ImageProcessor.CalculateAverageAndMaximumCPU(logoDetectionFrame, out logoDetectionFrameAverage, out logoDetectionFrameMaximum);

                    if (logoDetectionFrameMaximum - logoDetectionFrameAverage < 5)
                    {
                        Console.WriteLine("No logo detected. Disabling logo processing.");
                        logoDetectionFrame = null;
                    }

                    edgeMapList.Clear();

                    Console.WriteLine("Logo Detection time taken: " + stopwatch.Elapsed.ToString());
                }
                // --------------- End logo detection ---------------

                stopwatch.Restart();
                fieldNumber    = 0;
                fieldNumberFPS = 0;
                var emptyEdgeMap   = ImageProcessing.YDataFloat.NewData(_videoFile.Width, _videoFile.Height / _videoFile.FieldsPerFrame, (float)byte.MaxValue, byte.MaxValue / 2.0f);
                var edgeMapAverage = ImageProcessing.YDataFloat.NewData(_videoFile.Width, _videoFile.Height / _videoFile.FieldsPerFrame, (float)byte.MaxValue, byte.MaxValue / 2.0f);

                while (edgeMapList.Count < EDGE_MAP_AVERAGE_COUNT)
                {
                    edgeMapList.AddLast(emptyEdgeMap);
                }

                var startAt = 0;
                fieldNumber           += startAt;
                fieldNumberEdgeMapAvg += startAt;

                while (fieldNumberEdgeMapAvg < _videoFile.TotalFields)
                //while ((fieldNumberEdgeMapAvg < _videoFile.TotalFields) && (fieldNumber < 500))
                {
                    MediaFile.FrameField frameField = null;

                    if (fieldNumber < _videoFile.TotalFields)
                    {
                        frameField = _videoFile.GetVideoFrameField(fieldNumber);
                        var yData = frameField.YData;

                        Field f = null;
                        while (Data.Fields.Count < fieldNumber)
                        {
                            f         = new Field(Data);
                            f.Invalid = true;
                            Data.Fields.Add(f);
                        }
                        if (Data.Fields.Count > fieldNumber)
                        {
                            f = Data.Fields[fieldNumber];
                        }
                        else
                        {
                            f     = new Field(Data);
                            f.PTS = frameField.PTS;
                            Data.Fields.Add(f);
                        }

                        // --------------
                        //Average and Max
                        float average = 0.0f;
                        float maximum = 0.0f;
                        ImageProcessing.ImageProcessor.CalculateAverageAndMaximumCPU(yData, out average, out maximum);
                        f.SetValue("Brightness_Avg", average);
                        f.SetValue("Brightness_Max", maximum);

                        // --------------
                        // Std Dev
                        float stdDev = 0.0f;
                        ImageProcessing.ImageProcessor.CalculateStandardDeviationCPU(yData, average, out stdDev);
                        f.SetValue("Brightness_StdDev", stdDev);
                    }

                    // --------------
                    // Edge detection
                    if ((logoDetectionFrame != null) && ((fieldNumber % fieldsBetweenAveragedLogoFrames) == 0))
                    {
                        if (taskLogoDetect != null)
                        {
                            taskLogoDetect.Wait();
                        }

                        var frameFieldCopy            = frameField;
                        var fieldNumberCopy           = fieldNumber;
                        var fieldNumberEdgeMapAvgCopy = fieldNumberEdgeMapAvg;

                        taskLogoDetect = Task.Factory.StartNew(() =>
                        {
                            var edgeDataNew = emptyEdgeMap;
                            var edgeDataOld = edgeMapList.First.Value;

                            if (frameFieldCopy != null)
                            {
                                var yDataFloat = frameFieldCopy.YData.GetFloatData();

                                //edgeDataNew = ImageProcessing.ImageProcessor.GenerateEdgeDetectedImage(yDataFloat);
                                edgeDataNew = ImageProcessing.ImageProcessor.GenerateEdgeDetectedImageAccel(ImageProcessing.ImageProcessor.AcceleratorTarget.DX9, yDataFloat);

                                //edgeDataNew.GetBitmap().Save(@"D:\temp\edgeMap-" + fieldNumberCopy.ToString("00000") + ".png", System.Drawing.Imaging.ImageFormat.Png);

                                frameFieldCopy.Dispose();
                            }

                            edgeMapList.RemoveFirst();
                            edgeMapList.AddLast(edgeDataNew);

                            ImageProcessing.ImageProcessor.AdvanceEdgeDetectionAverage(ref edgeMapAverage, edgeDataNew, edgeDataOld, EDGE_MAP_AVERAGE_COUNT);

                            if (fieldNumberEdgeMapAvgCopy == 0)
                            {
                                Console.WriteLine("Starting logo testing.");
                            }

                            if (fieldNumberEdgeMapAvgCopy >= 0)
                            {
                                //edgeMapAverage.GetBitmap().Save(@"D:\temp\edgeAvg-" + fieldNumberEdgeMapAvgCopy.ToString("00000") + ".png", System.Drawing.Imaging.ImageFormat.Png);

                                var f = Data.Fields[fieldNumberEdgeMapAvgCopy];

                                float logoDifference;

                                ImageProcessing.ImageProcessor.CalculateLogoDifference(edgeMapAverage, logoDetectionFrame, logoDetectionFrameAverage, logoDetectionFrameMaximum, out logoDifference);
                                f.SetValue("Logo_Difference", logoDifference);

                                //var diffMap = ImageProcessing.ImageProcessor.GenerateLogoDifferenceMap(edgeMapAverage, logoDetectionFrame, logoDetectionFrameAverage, logoDetectionFrameMaximum);
                                //diffMap.GetBitmap().Save(@"D:\temp\diffMap2-" + fieldNumberEdgeMapAvgCopy.ToString("00000") + ".png", System.Drawing.Imaging.ImageFormat.Png);
                            }
                        });
                    }
                    else
                    {
                        if (frameField != null)
                        {
                            frameField.Dispose();
                        }
                    }


                    fieldNumberFPS++;
                    fieldNumber++;
                    fieldNumberEdgeMapAvg++;

                    long elapsedMilliseconds = stopwatch.ElapsedMilliseconds;
                    int  elapsedSeconds      = (int)(elapsedMilliseconds / 1000);
                    if (elapsedSeconds != lastPrintSeconds)
                    {
                        lastPrintSeconds = elapsedSeconds;
                        var fps = fieldNumberFPS * 1000.0f / (float)elapsedMilliseconds;
                        if (fieldNumberEdgeMapAvg > 0)
                        {
                            if (!stopwatchRestartedForLogoZone)
                            {
                                stopwatchRestartedForLogoZone = true;
                                stopwatch.Restart();
                                fieldNumberFPS = 0;
                            }
                        }
                        Console.WriteLine("Frame: " + fieldNumber.ToString() + "  FPS: " + fps.ToString("0.00"));
                    }
                }

                if (taskLogoDetect != null)
                {
                    taskLogoDetect.Wait();
                }

                Console.WriteLine("Video processing time taken: " + stopwatch.Elapsed.ToString());
            }

            return(0);
        }
Exemple #26
0
        private static IEnumerator LoadCoroutine()
        {
            var stopwatch = System.Diagnostics.Stopwatch.StartNew();

            IsLoading = true;

            Debug.Log("Started loading GTA");

            // wait a few frames - to "unblock" the program, and to let other scripts initialize before
            // registering their loading steps
            yield return(null);

            yield return(null);

            // calculate total loading time
            m_totalEstimatedLoadingTime = m_loadingSteps.Sum(step => step.EstimatedTime);

            var stopwatchForSteps = new System.Diagnostics.Stopwatch();

            foreach (var step in m_loadingSteps)
            {
                // update description
                LoadingStatus = step.Description;
                yield return(null);

                stopwatchForSteps.Restart();

                var en = step.Coroutine;

                if (en != null)
                {
                    // this step uses coroutine

                    bool hasNext = true;

                    while (hasNext)
                    {
                        hasNext = false;
                        try {
                            hasNext = en.MoveNext();
                        } catch (System.Exception ex) {
                            HandleExceptionDuringLoad(ex);
                            if (step.StopLoadingOnException)
                            {
                                yield break;
                            }
                        }

                        // update description
                        LoadingStatus = step.Description;
                        yield return(null);
                    }
                }
                else
                {
                    // this step uses a function

                    try {
                        step.LoadFunction();
                    } catch (System.Exception ex) {
                        HandleExceptionDuringLoad(ex);
                        if (step.StopLoadingOnException)
                        {
                            yield break;
                        }
                    }
                }

                // step finished it's work

                step.TimeElapsed = stopwatchForSteps.ElapsedMilliseconds;

                m_currentStepIndex++;

                Debug.LogFormat("{0} - finished in {1} ms", step.Description, step.TimeElapsed);
            }

            // all steps finished loading

            HasLoaded = true;
            IsLoading = false;

            Debug.Log("GTA loading finished in " + stopwatch.Elapsed.TotalSeconds + " seconds");

            // notify all scripts
            F.SendMessageToObjectsOfType <MonoBehaviour>("OnLoaderFinished");
        }
Exemple #27
0
        public static void Main17()
        {
            Console.WriteLine("Start Main17: Testing indexes");
            //string path = ""; //"../../../";
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            Random        rnd       = new Random();
            int           cnt       = 0;
            Func <Stream> GenStream = () => new FileStream(dbpath + "Databases/f" + (cnt++) + ".bin",
                                                           FileMode.OpenOrCreate, FileAccess.ReadWrite);

            PType tp_person = new PTypeRecord(
                new NamedType("id", new PType(PTypeEnumeration.integer)),
                new NamedType("name", new PType(PTypeEnumeration.sstring)),
                new NamedType("years", new PType(PTypeEnumeration.integer)));

            BearingPure table = new BearingPure(tp_person, GenStream);
            //IndexKey32CompImmutable id_index = new IndexKey32CompImmutable(GenStream, table, obj =>
            //    new int[] { (int)((object[])obj)[0] }, null);
            //IndexKey32CompImmutable str_index = new IndexKey32CompImmutable(GenStream, table, obj =>
            //    new int[] { Hashfunctions.HashRot13((string)((object[])obj)[1]) }, null);

            Comparer <object> comp = Comparer <object> .Create(new Comparison <object>((object a, object b) =>
            {
                return(string.Compare((string)((object[])a)[1], (string)((object[])b)[1]));
            }));

            //IndexKey32CompImmutable str_index = new IndexKey32CompImmutable(GenStream, table, obj =>
            //    new int[] { Hashfunctions.First4charsRu((string)((object[])obj)[1]) }, comp);

            IndexViewImmutable nameview_index = new IndexViewImmutable(GenStream, table, comp, dbpath + "Databases/", 50_000_000);

            Comparer <object> comp_int = Comparer <object> .Create(new Comparison <object>((object a, object b) =>
            {
                return(((int)((object[])a)[0]).CompareTo((int)((object[])b)[0]));
            }));

            //IndexViewImm idview_index = new IndexViewImm(GenStream, table, comp_int, path + "Databases/", 50_000_000);


            int  nelements = 1_000_000;
            bool toload    = true;

            if (toload)
            {
                //table.Clear();
                //sw.Restart();
                //for (int i = 0; i < nelements; i++)
                //{
                //    table.AppendElement(new object[] { i, "" + i, 33 });
                //}
                //table.Flush();
                table.Load(Enumerable.Range(0, nelements).Select(i => new object[] { i, "" + i, 33 }));

                //id_index.Build();
                //str_index.Build();
                nameview_index.Build();
                //idview_index.Build();
                sw.Stop();
                Console.WriteLine($"Load ok. Duration={sw.ElapsedMilliseconds}");
            }
            else
            {
                sw.Restart();
                table.Refresh();
                //id_index.Refresh();
                //str_index.Refresh();
                nameview_index.Refresh();
                //idview_index.Refresh();
                sw.Stop();
                Console.WriteLine($"Refresh ok. Duration={sw.ElapsedMilliseconds}");
            }

            // Экспермент по поиску похожих
            Comparer <object> comp_like = Comparer <object> .Create(new Comparison <object>((object a, object b) =>
            {
                int len = ((string)((object[])b)[1]).Length;
                return(string.Compare((string)((object[])a)[1], 0, (string)((object[])b)[1], 0, len));
            }));

            //Comparer<object> comp_like = new CompaObjStrPar();

            int key = nelements * 2 / 3;

            //var obs = id_index.GetAllByKey(key);
            //var obs = str_index.GetAllByKey(Hashfunctions.HashRot13(""+key));
            //var obs = str_index.GetAllBySample(new object[] { -1, ""+key, -2 });
            key = key / 10;
            var obs = nameview_index.SearchAll(new object[] { -1, "" + key, -2 }, comp_like);

            //var obs = idview_index.BinarySearchAll(new object[] { key, null, -2 });
            foreach (var ob in obs)
            {
                Console.WriteLine(tp_person.Interpret(ob));
            }


            int nprobe = 1000;

            sw.Restart();
            int total = 0;

            for (int i = 0; i < nprobe; i++)
            {
                int k = rnd.Next(nelements);
                //var os = id_index.GetAllByKey(k);
                //var os = str_index.GetAllByKey(Hashfunctions.HashRot13("" + k)).Where(ob => (string)((object[])ob)[1] == "" + k);
                //var os = str_index.GetAllBySample(new object[] { -1, "" + k, -2 });
                var os = nameview_index.SearchAll(new object[] { -1, "" + k, -2 });
                //var os = nameview_index.SearchAll(new object[] { -1, "" + k, -2 }, comp_like);
                //var os = idview_index.BinarySearchAll(new object[] { k, null, -2 });

                total += os.Count();
            }
            sw.Stop();
            Console.WriteLine($"{nprobe} queries ok. Duration={sw.ElapsedMilliseconds} total = {total}");
        }
Exemple #28
0
        /// <summary>
        /// 网络模块复位处理线程
        /// </summary>
        private void NetWorkResetThread()
        {
            CommSendData          commdata     = new CommSendData();
            int                   iclientCount = 0;
            List <ClientConntion> lstConnetion;

            if (Directory.Exists("C:\\NetSource\\") == false)
            {
                Directory.CreateDirectory("C:\\NetSource\\");
            }
            string   strCur    = "";
            DateTime t_dayTime = new DateTime(1999, 1, 1);

            string[] strP = { "debug", "error", "info", "system", "warn" };
            int      i    = 0;

            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            for (; ;)
            {
                try
                {
                    sw.Restart();

                    #region 更新四舍五入标记、源码输出
                    try
                    {
                        System.Configuration.ConfigurationManager.RefreshSection("appSettings");
                        strCur = Basic.Framework.Configuration.ConfigurationManager.FileConfiguration.GetString("B4c5r", "1");
                        if (strCur.Trim() == "2")
                        {
                            Cache.B4c5r = true;
                        }
                        else
                        {
                            Cache.B4c5r = false;
                        }
                        strCur            = Basic.Framework.Configuration.ConfigurationManager.FileConfiguration.GetString("FeedTimeOut", "5");
                        Cache.FeedTimeOut = Convert.ToInt32(strCur);

                        strCur          = Basic.Framework.Configuration.ConfigurationManager.FileConfiguration.GetString("ShowYmOut", "0");
                        Cache.ShowYmOut = Convert.ToInt32(strCur);
                        if (Cache.ShowYmOut == 1)//有源码输出才进行相关的处理
                        {
                            while (Cache.LstCommData.Count > 0)
                            {
                                lock (Cache.LockCommData)
                                {
                                    commdata = Basic.Framework.Common.ObjectConverter.DeepCopy <CommSendData>(Cache.LstCommData[0]);
                                    Cache.LstCommData.RemoveAt(0);
                                }
                                ShowNetDataToComputer(commdata.data, commdata.Mac, commdata.Flag);
                            }
                        }
                        else//不带源码输出直接清空
                        {
                            lock (Cache.LockCommData)
                            {
                                Cache.LstCommData.Clear();
                            }
                        }

                        strCur = Basic.Framework.Configuration.ConfigurationManager.FileConfiguration.GetString("FeedComplexFailure", "1");
                        if (strCur == "1")
                        {
                            Cache.FeedComplexFailure = true;
                        }
                        else
                        {
                            Cache.FeedComplexFailure = false;
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error("更新四舍五入、源码输出标记错误:" + ex.Message);
                    }
                    #endregion

                    #region 如处于客户端模式,定期进行连接和关闭判断

                    iclientCount++;
                    strCur = Basic.Framework.Configuration.ConfigurationManager.FileConfiguration.GetString("ServerOrClient", "1");
                    if ((iclientCount >= 3) && (strCur == "1"))
                    {
                        iclientCount = 0;
                        if (OnExcuteDriverCommand != null)//修正一下,如果是第一次进来时,连接两次
                        {
                            DriverCommandEventArgs args         = new DriverCommandEventArgs();
                            DeviceResetCommand     resetcommand = new DeviceResetCommand();
                            args.CommandType = 2;
                            lstConnetion     = GetFzhIP();
                            args.JsonData    = Basic.Framework.Common.JSONHelper.ToJSONString(lstConnetion);
                            OnExcuteDriverCommand(this, args);
                        }
                    }

                    #endregion

                    #region   自动删除数据
                    //自动删除 20个月前的源码数据
                    if (t_dayTime.Day != DateTime.Now.Day)
                    {
                        t_dayTime = DateTime.Now;
                        try
                        {
                            DateTime dt = new DateTime();
                            foreach (string d in Directory.GetFileSystemEntries("C:\\NetSource\\"))
                            {
                                if (File.Exists(d))
                                {
                                    FileInfo fi = new FileInfo(d);
                                    if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
                                    {
                                        fi.Attributes = FileAttributes.Normal;
                                    }

                                    dt = new DateTime(Convert.ToInt32(fi.Name.Substring(0, 4)), Convert.ToInt32(fi.Name.Substring(4, 2)), Convert.ToInt32(fi.Name.Substring(6, 2)));
                                    if ((DateTime.Now - dt).TotalDays >= 20)
                                    {
                                        File.Delete(d);//直接删除其中的文件
                                    }
                                }
                            }
                            for (i = 0; i < 5; i++)
                            {
                                strCur = "C:\\log\\Sys.DataCollection.ConsoleHost\\" + strP[i];
                                //判断文件夹是否还存在
                                if (Directory.Exists(strCur))
                                {
                                    foreach (string f in Directory.GetFileSystemEntries(strCur))
                                    {
                                        strCur = f.ToString();
                                        strCur = strCur.Substring(strCur.LastIndexOf('\\') + 1);
                                        dt     = new DateTime(Convert.ToInt32(strCur.Substring(0, 4)), Convert.ToInt32(strCur.Substring(4, 2)), Convert.ToInt32(strCur.Substring(6, 2)));
                                        if ((DateTime.Now - dt).TotalDays >= 20)
                                        {
                                            foreach (string f1 in Directory.GetFileSystemEntries(f))
                                            {
                                                if (File.Exists(f1))
                                                {//如果有子文件删除文件
                                                    File.Delete(f1);
                                                }
                                            }
                                            Directory.Delete(f);
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Error("NetWorkReset【删除源码文件失败】" + ex.ToString());
                        }
                    }
                    #endregion
                    sw.Stop();
                    if (sw.ElapsedMilliseconds > 3000)
                    {//操作了3秒就输出日志出来
                        LogHelper.Info("网关超时判断:" + sw.ElapsedMilliseconds);
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Error("NetWorkReset【NetWorkResetThread】:" + ex.ToString());
                }
                Thread.Sleep(1000);
            }
        }
Exemple #29
0
 public void Restart() => _stopwatch.Restart();
Exemple #30
0
        private void button4_Click(object sender, EventArgs e)
        {
            Action fileProc = () =>
            {
                System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
                MathNet.Numerics.Control.LinearAlgebraProvider = new MathNet.Numerics.Algorithms.LinearAlgebra.Mkl.MklLinearAlgebraProvider();
                MathNet.Numerics.Control.NumberOfParallelWorkerThreads = Environment.ProcessorCount;
                addText("Обробка файлу вимірювань...\r\n");
                double[][] SGG_data = null;
                if (System.IO.File.Exists("sgg_data.bin"))
                {
                    SGG_data = IOFunc.binLoad_SGG_data("sgg_data.bin");
                }
                else
                {
                    SGG_data = Data.IOFunc.read_SGG_data(SphericalHarmonicAnalyze.Properties.Settings.Default.SGG_measures, new setProgressDel(addVal));
                    IOFunc.binwrite_SGG_data("sgg_data.bin", SGG_data);
                }
                addText("Дані вимірювань оброблено: {0} шт.\r\n", SGG_data.Length); Thread.Sleep(500);
                ReferenceSystem elipsoid = new ReferenceSystem(ReferenceSystem.Default.TideFree);
                elipsoid.gridParameters.cellSize = SphericalHarmonicAnalyze.Properties.Settings.Default.GridCellSize;
                elipsoid.gridParameters.coLatitudeBounds = SphericalHarmonicAnalyze.Properties.Settings.Default.minCoLatitude;
                elipsoid.maxDegree = SphericalHarmonicAnalyze.Properties.Settings.Default.modelMaxOrder;
                int greedColumnsCount, greedRowsCount;
                List<double[]> greed = MathFunc.generateGrid(elipsoid.gridParameters.cellSize, out greedColumnsCount, out greedRowsCount, elipsoid.gridParameters.coLatitudeBounds,180 - elipsoid.gridParameters.coLatitudeBounds);
                addText("Сітку згенеровано: {0} комірок \r\n", greed.Count);
                double avgR = MathFunc.getAvgRadius(SGG_data);
                List<int>[] map = MathFunc.getMappingOfPoints(elipsoid, SGG_data, greed.ToArray(), greedRowsCount, greedColumnsCount, avgR); sw.Stop(); addText("Точки віднесено до комірок сітки за: {0}.\r\n", sw.Elapsed.ToString());
                addText("Кількість клітинок сітки всього: {0}\r\n", greed.Count);
                int res1 = 0; foreach (var item in map) { res1 += item.Count; } addText("Використано вимірів: {0}\r\nСер радіус: {1}\r\n", res1, avgR);
                test.checkMap(SGG_data, map, greed, elipsoid);
                List<int>[] newMap = null;
                MathFunc.checkGreed(ref greed, map, out newMap);
                addText("Кількість клітинок сітки, в яких присутні дані вимірювань: {0}\r\n", greed.Count);
                map = newMap; newMap = null;
                IOFunc.writeGreedToCsvFileWithMeasureCount(greed, map, "greed_new_map.txt");
                double[] avgRadius; sw.Restart();
                double[] regularisedValues = MathFunc.regularization(SGG_data, greed.ToArray(), map, out avgRadius); sw.Stop(); addText("Регуляризація (на основі сферичної відстані) виконана за: {0}.\r\n", sw.Elapsed.ToString());
                IOFunc.writeGreedToCsvFileWithMeasureS(greed,regularisedValues, "greed_regular_grad.txt");
                avgRadius[0] = Math.Round(avgRadius[0]);
                elipsoid.satelliteSphere = avgRadius[0];
                addText("Середній радіус: {0,10:0.000}.\r\nМінімальний радіус: {1,10:0.0000}\r\nМаксимальний радіус:{2,10:0.0000}\r\n", avgRadius[0], avgRadius[1], avgRadius[2]);
                SGG_data = null; map = null;
                int[][] t_nm = MathFunc.get_nm(elipsoid.maxDegree);
                sw.Restart();
                MathNet.Numerics.LinearAlgebra.Double.DenseMatrix dm = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(greed.Count, (MathFunc.getArraySize(elipsoid.maxDegree) - 3) * 2 - (elipsoid.maxDegree-1));
                sw.Stop(); addText("Пам'ять для матриці коефіцієнтів виділено за: {0}.\r\n", sw.Elapsed.ToString());
                sw.Restart();
                int progress = 0;
                //Обчислення елементів матриці
                var p= Parallel.For(0, dm.RowCount, (i) =>
                {
                    double[] line = MathFunc.getCoefMatrixLineKoop(elipsoid, elipsoid.maxDegree, t_nm, elipsoid.satelliteSphere, greed[i][0], greed[i][1]);
                    lock (dm)
                    {
                         dm.SetRow(i,line);

                    }
                    progress++;
                    if (progress / 100D == Math.Round(progress / 100D)) {addVal(progress, dm.RowCount, "Визначено");}
                });

                if (!p.IsCompleted) { throw new Exception("Parallel.For"); };
                IOFunc.writeMatrixToMatLabFile(dm, @"matlab\A.mat","A");
                sw.Stop();
                richTextBox1.Invoke(new setProgressDel(addVal), new object[] { 0, dm.RowCount, "" });
                addText("Матриця {0} на {1} ({2}MB) згенерована за: {3,10}\r\n", dm.RowCount, dm.ColumnCount, dm.ColumnCount * dm.RowCount * 8 / 1000000,sw.Elapsed.ToString()/* + "\r\nЗапис у файл...\r\n"*/);
                if(true){
                GravityModel gm08 = new GravityModel(elipsoid.maxDegree);
                gm08.loadFromFile("GO_CONS_EGM_GCF_2.gfc", new setProgressDel(addVal));
                MathNet.Numerics.LinearAlgebra.Double.DenseVector dmL = new MathNet.Numerics.LinearAlgebra.Double.DenseVector(gm08.getGradientForGrid(elipsoid,greed));//regularisedValues);
                MathNet.Numerics.LinearAlgebra.Double.DenseVector dmL2;
                GravityModel gm = new GravityModel(elipsoid.maxDegree);
                    if (radioButton1.Checked) {
                    sw.Restart();
                    gm.loadFromFile(SphericalHarmonicAnalyze.Properties.Settings.Default.inGravityModel, new setProgressDel(addVal));
                    sw.Stop(); addText("Вихідна модель завантажена за: {0}.\r\n", sw.Elapsed.ToString());
                    sw.Restart();
                    dmL2 = new MathNet.Numerics.LinearAlgebra.Double.DenseVector(gm.getGradientForGrid(elipsoid,greed));
                    sw.Stop(); addText("Градієнти за вихідною моделлю обчислені для сітки за: {0}.\r\n", sw.Elapsed.ToString());
                }
                else
                {
                    sw.Restart();
                    gm = GravityModel.getNormalModel(elipsoid, elipsoid.maxDegree);
                    dmL2 = new MathNet.Numerics.LinearAlgebra.Double.DenseVector(gm.getGradientForGrid(elipsoid, greed));
                    sw.Stop(); addText("Нормальні градієнти обчислені для сітки за: {0}.\r\n", sw.Elapsed.ToString());
                }
                dmL = dmL - dmL2;
                dmL2 = null;
                IOFunc.writeMatrixToMatLabFile(dmL.ToColumnMatrix(), @"matlab\L.mat", "L");
                    sw.Restart();
                MathNet.Numerics.LinearAlgebra.Double.DenseVector dmLNormal = null;
                dmLNormal = (MathNet.Numerics.LinearAlgebra.Double.DenseVector)dm.TransposeThisAndMultiply(dmL);
                dmL = null;
                IOFunc.writeMatrixToMatLabFile(dmLNormal.ToColumnMatrix(), @"matlab\LNorm.mat", "LNorm");
                sw.Stop(); addText("Стовпчик вільних членів обчислений за: {0}.\r\n", sw.Elapsed.ToString());
                MathNet.Numerics.LinearAlgebra.Double.DenseMatrix dmANorm = null;
                sw.Restart();
                dmANorm = (MathNet.Numerics.LinearAlgebra.Double.DenseMatrix)dm.TransposeThisAndMultiply(dm); dm = null;
                sw.Stop(); addText("Нормальна матриця коефіціэнтів обчислена за: {0}.\r\n", sw.Elapsed.ToString());
                IOFunc.writeMatrixToMatLabFile(dmANorm, @"matlab\ANorm.mat", "ANorm");
                //dmLNormal = (MathNet.Numerics.LinearAlgebra.Double.DenseVector)dmLNormal.Multiply(5e-8);
                var x = dmANorm.Inverse();
                var res = (MathNet.Numerics.LinearAlgebra.Double.DenseVector)x.Multiply(dmLNormal);
                IOFunc.writeModeVectorlToTxtFile(res, elipsoid, @"matlab\_out.AL");
                addText(@"Результат за методом A\L знайдено...");
                x = null;
                GravityModel gm_R = new GravityModel(gm);
                gm_R.addDeltaCoef(res.ToArray()); res = null;
                double[] h = GravityModel.getGeoidHeight(elipsoid, gm_R, greed);
                double[] dg = GravityModel.getAnomaly(elipsoid, gm_R, greed);
                IOFunc.writeGeoidHeightsAndAnomalysToTxt(greed, h, dg, elipsoid, @"output\result_AL.txt");
                IOFunc.writeGravityModelToTxtFile(gm_R, @"output\model_AL.gcf");
                sw.Restart();
                addText(dmANorm.Rank().ToString() + "\r\n");
                dmANorm = null;
                dmLNormal = null;
                sw.Stop(); addText("Невідомі знайдено за: {0}.\r\n", sw.Elapsed.ToString());

            }
            };

            if (System.IO.File.Exists(SphericalHarmonicAnalyze.Properties.Settings.Default.inGravityModel)) {
            tabControl1.SelectedTab = tabControl1.TabPages[1];
            this.UseWaitCursor = true;
            ts = new CancellationTokenSource();
            ct = ts.Token;
            tsk = Task.Factory.StartNew(fileProc,ct);
            var setCur = Task.Factory.StartNew(() => { tsk.Wait(); this.UseWaitCursor = false; addText("Обчислення завершені!"); });
            richTextBox1.SaveFile(@"output\zvit.rtf");
            }
        }
Exemple #31
0
        static void Main(string[] args)
        {
            Random  rnd              = new Random(100);
            TestSet undirectedRep    = new TestSet();
            TestSet directedRep      = new TestSet();
            TestSet undirectedSimple = new TestSet();
            TestSet directedSimple   = new TestSet();
            Graph   g;

            #region undirected, with repetitions

            g = new AdjacencyListsGraph <HashTableAdjacencyList>(false, 5);
            g.AddEdge(0, 1, 1);
            g.AddEdge(1, 2, 1);
            g.AddEdge(0, 2, 1);
            g.AddEdge(3, 4, 1);
            undirectedRep.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 4, null));

            g = new AdjacencyListsGraph <HashTableAdjacencyList>(false, 5);
            g.AddEdge(0, 1, 1);
            g.AddEdge(1, 2, 1);
            g.AddEdge(2, 3, 1);
            g.AddEdge(3, 4, 1);
            undirectedRep.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 4, 6));

            g = new AdjacencyListsGraph <HashTableAdjacencyList>(false, 5);
            g.AddEdge(0, 1, 1);
            g.AddEdge(1, 2, 1);
            g.AddEdge(2, 3, 1);
            g.AddEdge(3, 4, 1);
            g.AddEdge(0, 4, 7);
            undirectedRep.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 4, 6));

            g = new AdjacencyListsGraph <HashTableAdjacencyList>(false, 5);
            g.AddEdge(0, 1, 2);
            g.AddEdge(1, 2, 2);
            g.AddEdge(2, 3, 2);
            g.AddEdge(3, 4, 2);
            g.AddEdge(2, 4, 5);
            undirectedRep.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 4, 9));

            g = new AdjacencyListsGraph <HashTableAdjacencyList>(false, 6);
            g.AddEdge(0, 1, 1);
            g.AddEdge(1, 2, 1);
            g.AddEdge(2, 3, 1);
            g.AddEdge(0, 4, 1);
            g.AddEdge(4, 5, 1);
            g.AddEdge(5, 3, 1);
            undirectedRep.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 3, 3));

            g = new AdjacencyListsGraph <HashTableAdjacencyList>(false, 100);
            for (int i = 0; i < 100; ++i)
            {
                for (int j = i + 1; j < 100; ++j)
                {
                    if (rnd.Next(10) <= 2)
                    {
                        g.AddEdge(i, j, 1 + rnd.Next(100));
                    }
                }
            }
            undirectedRep.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 99, 21));


            g = new AdjacencyListsGraph <HashTableAdjacencyList>(false, 100);
            for (int i = 0; i < 100; ++i)
            {
                for (int j = i + 1; j < 100; ++j)
                {
                    if (rnd.Next(10) <= 3)
                    {
                        g.AddEdge(i, j, 1 + rnd.Next(100));
                    }
                }
            }
            undirectedRep.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 99, 23));

            g = new AdjacencyListsGraph <HashTableAdjacencyList>(false, 1000);
            for (int i = 0; i < 1000; ++i)
            {
                for (int j = i + 1; j < 1000; ++j)
                {
                    if (rnd.Next(10) <= 3)
                    {
                        g.AddEdge(i, j, 1 + rnd.Next(100));
                    }
                }
            }
            undirectedRep.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 99, 6));

            #endregion

            #region directed, with repetitions

            g = new AdjacencyListsGraph <HashTableAdjacencyList>(true, 5);
            g.AddEdge(0, 1, 1);
            g.AddEdge(1, 2, 1);
            g.AddEdge(0, 2, 1);
            g.AddEdge(3, 4, 1);
            directedRep.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 4, null));

            g = new AdjacencyListsGraph <HashTableAdjacencyList>(true, 5);
            g.AddEdge(0, 1, 1);
            g.AddEdge(1, 2, 1);
            g.AddEdge(2, 3, 1);
            g.AddEdge(3, 4, 1);
            directedRep.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 4, null));

            g = new AdjacencyListsGraph <HashTableAdjacencyList>(true, 5);
            g.AddEdge(0, 1, 1);
            g.AddEdge(1, 2, 1);
            g.AddEdge(2, 3, 1);
            g.AddEdge(3, 4, 1);
            g.AddEdge(0, 4, 7);
            directedRep.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 4, 7));

            g = new AdjacencyListsGraph <HashTableAdjacencyList>(true, 5);
            g.AddEdge(0, 1, 2);
            g.AddEdge(1, 2, 2);
            g.AddEdge(2, 3, 2);
            g.AddEdge(3, 4, 2);
            g.AddEdge(2, 4, 5);
            directedRep.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 4, 9));


            g = new AdjacencyListsGraph <HashTableAdjacencyList>(true, 6);
            g.AddEdge(0, 1, 1);
            g.AddEdge(1, 2, 1);
            g.AddEdge(2, 3, 1);
            g.AddEdge(0, 4, 1);
            g.AddEdge(4, 5, 1);
            g.AddEdge(5, 3, 1);
            directedRep.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 3, 3));

            g = new AdjacencyListsGraph <HashTableAdjacencyList>(true, 100);
            for (int i = 0; i < 100; ++i)
            {
                for (int j = i + 1; j < 100; ++j)
                {
                    if (rnd.Next(10) <= 2)
                    {
                        g.AddEdge(i, j, 1 + rnd.Next(100));
                    }
                    if (rnd.Next(10) <= 2)
                    {
                        g.AddEdge(j, i, 1 + rnd.Next(100));
                    }
                }
            }
            directedRep.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 4, 24));

            g = new AdjacencyListsGraph <HashTableAdjacencyList>(true, 100);
            for (int i = 0; i < 100; ++i)
            {
                for (int j = i + 1; j < 100; ++j)
                {
                    if (rnd.Next(10) <= 2)
                    {
                        g.AddEdge(i, j, 1 + rnd.Next(100));
                    }
                    if (rnd.Next(10) <= 2)
                    {
                        g.AddEdge(j, i, 1 + rnd.Next(100));
                    }
                }
            }
            directedRep.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 99, 22));

            g = new AdjacencyListsGraph <HashTableAdjacencyList>(true, 1000);
            for (int i = 0; i < 1000; ++i)
            {
                for (int j = i + 1; j < 1000; ++j)
                {
                    if (rnd.Next(10) <= 3)
                    {
                        g.AddEdge(i, j, 1 + rnd.Next(100));
                    }
                    if (rnd.Next(10) <= 3)
                    {
                        g.AddEdge(j, i, 1 + rnd.Next(100));
                    }
                }
            }
            directedRep.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 99, 5));
            #endregion

            #region undirected, without repetitions

            g = new AdjacencyListsGraph <HashTableAdjacencyList>(false, 5);
            g.AddEdge(0, 1, 1);
            g.AddEdge(1, 2, 1);
            g.AddEdge(0, 2, 1);
            g.AddEdge(3, 4, 1);
            undirectedSimple.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 4, null));

            g = new AdjacencyListsGraph <HashTableAdjacencyList>(false, 5);
            g.AddEdge(0, 1, 1);
            g.AddEdge(1, 2, 1);
            g.AddEdge(2, 3, 1);
            g.AddEdge(3, 4, 1);
            undirectedSimple.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 4, null));

            g = new AdjacencyListsGraph <HashTableAdjacencyList>(false, 5);
            g.AddEdge(0, 1, 1);
            g.AddEdge(1, 2, 1);
            g.AddEdge(2, 3, 1);
            g.AddEdge(3, 4, 1);
            g.AddEdge(0, 4, 7);
            undirectedSimple.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 4, 7));

            g = new AdjacencyListsGraph <HashTableAdjacencyList>(false, 5);
            g.AddEdge(0, 1, 2);
            g.AddEdge(1, 2, 2);
            g.AddEdge(2, 3, 2);
            g.AddEdge(3, 4, 2);
            g.AddEdge(2, 4, 5);
            undirectedSimple.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 4, 9));


            g = new AdjacencyListsGraph <HashTableAdjacencyList>(false, 6);
            g.AddEdge(0, 1, 1);
            g.AddEdge(1, 2, 1);
            g.AddEdge(2, 3, 1);
            g.AddEdge(0, 4, 1);
            g.AddEdge(4, 5, 1);
            g.AddEdge(5, 3, 1);
            undirectedSimple.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 3, 3));

            g = new AdjacencyListsGraph <HashTableAdjacencyList>(false, 100);
            for (int i = 0; i < 100; ++i)
            {
                for (int j = i + 1; j < 100; ++j)
                {
                    if (rnd.Next(10) <= 2)
                    {
                        g.AddEdge(i, j, 1 + rnd.Next(100));
                    }
                }
            }
            undirectedSimple.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 99, 14));

            g = new AdjacencyListsGraph <HashTableAdjacencyList>(false, 100);
            for (int i = 0; i < 100; ++i)
            {
                for (int j = i + 1; j < 100; ++j)
                {
                    if (rnd.Next(10) <= 2)
                    {
                        g.AddEdge(i, j, 1 + rnd.Next(100));
                    }
                }
            }
            undirectedSimple.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 99, 29));

            g = new AdjacencyListsGraph <HashTableAdjacencyList>(false, 100);
            for (int i = 0; i < 100; ++i)
            {
                for (int j = i + 1; j < 100; ++j)
                {
                    if (rnd.Next(10) <= 2)
                    {
                        g.AddEdge(i, j, 1 + rnd.Next(100));
                    }
                }
            }
            undirectedSimple.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 99, 24));
            #endregion

            #region directed, without repetitions

            g = new AdjacencyListsGraph <HashTableAdjacencyList>(true, 5);
            g.AddEdge(0, 1, 1);
            g.AddEdge(1, 2, 1);
            g.AddEdge(0, 2, 1);
            g.AddEdge(3, 4, 1);
            directedSimple.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 4, null));

            g = new AdjacencyListsGraph <HashTableAdjacencyList>(true, 5);
            g.AddEdge(0, 1, 1);
            g.AddEdge(1, 2, 1);
            g.AddEdge(2, 3, 1);
            g.AddEdge(3, 4, 1);
            directedSimple.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 4, null));

            g = new AdjacencyListsGraph <HashTableAdjacencyList>(true, 5);
            g.AddEdge(0, 1, 1);
            g.AddEdge(1, 2, 1);
            g.AddEdge(2, 3, 1);
            g.AddEdge(3, 4, 1);
            g.AddEdge(0, 4, 7);
            directedSimple.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 4, 7));

            g = new AdjacencyListsGraph <HashTableAdjacencyList>(true, 5);
            g.AddEdge(0, 1, 2);
            g.AddEdge(1, 2, 2);
            g.AddEdge(2, 3, 2);
            g.AddEdge(3, 4, 2);
            g.AddEdge(2, 4, 5);
            directedSimple.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 4, 9));


            g = new AdjacencyListsGraph <HashTableAdjacencyList>(true, 6);
            g.AddEdge(0, 1, 1);
            g.AddEdge(1, 2, 1);
            g.AddEdge(2, 3, 1);
            g.AddEdge(0, 4, 1);
            g.AddEdge(4, 5, 1);
            g.AddEdge(5, 3, 1);
            directedSimple.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 3, 3));

            // Test 6
            g = new AdjacencyListsGraph <HashTableAdjacencyList>(true, 100);
            for (int i = 0; i < 100; ++i)
            {
                for (int j = i + 1; j < 100; ++j)
                {
                    if (rnd.Next(10) <= 2)
                    {
                        g.AddEdge(i, j, 1 + rnd.Next(100));
                    }
                    if (rnd.Next(10) <= 2)
                    {
                        g.AddEdge(j, i, 1 + rnd.Next(100));
                    }
                }
            }
            directedSimple.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 4, 29));

            g = new AdjacencyListsGraph <HashTableAdjacencyList>(true, 100);
            for (int i = 0; i < 100; ++i)
            {
                for (int j = i + 1; j < 100; ++j)
                {
                    if (rnd.Next(10) <= 2)
                    {
                        g.AddEdge(i, j, 1 + rnd.Next(100));
                    }
                    if (rnd.Next(10) <= 2)
                    {
                        g.AddEdge(j, i, 1 + rnd.Next(100));
                    }
                }
            }
            directedSimple.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 99, 23));

            g = new AdjacencyListsGraph <HashTableAdjacencyList>(true, 1000);
            for (int i = 0; i < 1000; ++i)
            {
                for (int j = i + 1; j < 1000; ++j)
                {
                    if (rnd.Next(10) <= 3)
                    {
                        g.AddEdge(i, j, 1 + rnd.Next(100));
                    }
                    if (rnd.Next(10) <= 3)
                    {
                        g.AddEdge(j, i, 1 + rnd.Next(100));
                    }
                }
            }
            directedSimple.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 99, 5));
            #endregion

            Console.WriteLine("Path with repetitions, undirected graphs");
            undirectedRep.PreformTests(true, false);
            Console.WriteLine("Path with repetitions, directed graphs");
            directedRep.PreformTests(true, false);
            Console.WriteLine("Path without repetitions, undirected graphs");
            undirectedSimple.PreformTests(true, false);
            Console.WriteLine("Path without repetitions, directed graphs");
            directedSimple.PreformTests(true, false);


            #region custom, additional tests
            RandomGraphGenerator rgg = new RandomGraphGenerator(1234);

            Console.WriteLine("Custom tests");

            Console.WriteLine("Timing a boilerplate task");
            long boilerplateTaskTimeElapsed = PerformBoilerplateTask();
            Console.WriteLine("Boilerplate task done. Results will be shown below");

            Console.WriteLine("Generating test cases, this may take a while...");

            #region custom undirected, with repetitions
            TestSet undirectedWithRepetitions = new TestSet();
            g = rgg.UndirectedGraph(typeof(AdjacencyMatrixGraph), 100, 0.8, 1, 100, true);
            undirectedWithRepetitions.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 99, 9));

            g = rgg.UndirectedGraph(typeof(AdjacencyMatrixGraph), 100, 0.5, 1, 100, true);
            undirectedWithRepetitions.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 99, 11));

            g = rgg.UndirectedGraph(typeof(AdjacencyMatrixGraph), 100, 0.2, 1, 100, true);
            undirectedWithRepetitions.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 99, 24));

            g = rgg.UndirectedGraph(typeof(AdjacencyMatrixGraph), 1000, 0.8, 1, 100, true);
            undirectedWithRepetitions.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 999, 4));

            g = rgg.UndirectedGraph(typeof(AdjacencyMatrixGraph), 1000, 0.2, 1, 100, true);
            undirectedWithRepetitions.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 999, 7));

            g = rgg.UndirectedGraph(typeof(AdjacencyMatrixGraph), 1000, 1, 1, 100, true);
            undirectedWithRepetitions.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 999, 4));

            g = rgg.UndirectedGraph(typeof(AdjacencyListsGraph <AVLAdjacencyList>), 1500, 0.75, 1, 100, true);
            undirectedWithRepetitions.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 1499, 3));

            g = rgg.UndirectedGraph(typeof(AdjacencyListsGraph <AVLAdjacencyList>), 1500, 0, 1, 100, true);
            undirectedWithRepetitions.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 1499, null));
            #endregion

            #region custom directed, with repetitions
            TestSet directedWithRepetitions = new TestSet();
            g = new AdjacencyMatrixGraph(true, 3);
            g.AddEdge(0, 1, 20);
            g.AddEdge(0, 2, 30);
            g.AddEdge(1, 2, 1);
            g.AddEdge(2, 1, 2);
            directedWithRepetitions.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 2, 30));

            g = rgg.DirectedGraph(typeof(AdjacencyMatrixGraph), 100, 0.8, 1, 100, true);
            directedWithRepetitions.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 99, 10));

            g = rgg.DirectedGraph(typeof(AdjacencyMatrixGraph), 100, 0.5, 1, 100, true);
            directedWithRepetitions.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 99, 14));

            g = rgg.DirectedGraph(typeof(AdjacencyMatrixGraph), 100, 0.2, 1, 100, true);
            directedWithRepetitions.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 99, 30));

            g = rgg.DirectedGraph(typeof(AdjacencyMatrixGraph), 1000, 0.8, 1, 100, true);
            directedWithRepetitions.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 999, 5));

            g = rgg.DirectedGraph(typeof(AdjacencyMatrixGraph), 1000, 0.2, 1, 100, true);
            directedWithRepetitions.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 999, 9));

            g = rgg.DirectedGraph(typeof(AdjacencyMatrixGraph), 1000, 1, 1, 100, true);
            directedWithRepetitions.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 999, 3));

            g = rgg.DirectedGraph(typeof(AdjacencyListsGraph <AVLAdjacencyList>), 1500, 0.75, 1, 100, true);
            directedWithRepetitions.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 1499, 4));

            g = rgg.DirectedGraph(typeof(AdjacencyListsGraph <AVLAdjacencyList>), 1500, 0, 1, 100, true);
            directedWithRepetitions.TestCases.Add(new RepSecondPathTestCase(10, g, 0, 1499, null));
            #endregion

            #region custom undirected, without repetitions
            TestSet undirectedWithoutRepetitions = new TestSet();
            g = rgg.UndirectedGraph(typeof(AdjacencyMatrixGraph), 100, 0.8, 1, 100, true);
            undirectedWithoutRepetitions.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 99, 8));

            g = rgg.UndirectedGraph(typeof(AdjacencyMatrixGraph), 100, 0.5, 1, 100, true);
            undirectedWithoutRepetitions.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 99, 11));

            g = rgg.UndirectedGraph(typeof(AdjacencyMatrixGraph), 100, 0.2, 1, 100, true);
            undirectedWithoutRepetitions.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 99, 20));

            g = rgg.UndirectedGraph(typeof(AdjacencyMatrixGraph), 1000, 0.8, 1, 100, true);
            undirectedWithoutRepetitions.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 999, 4));

            g = rgg.UndirectedGraph(typeof(AdjacencyMatrixGraph), 1000, 0.2, 1, 100, true);
            undirectedWithoutRepetitions.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 999, 9));

            g = rgg.UndirectedGraph(typeof(AdjacencyMatrixGraph), 1000, 1, 1, 100, true);
            undirectedWithoutRepetitions.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 999, 4));

            g = rgg.UndirectedGraph(typeof(AdjacencyListsGraph <AVLAdjacencyList>), 1500, 0.75, 1, 100, true);
            undirectedWithoutRepetitions.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 1499, 3));

            g = rgg.UndirectedGraph(typeof(AdjacencyListsGraph <AVLAdjacencyList>), 1500, 0, 1, 100, true);
            undirectedWithoutRepetitions.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 1499, null));
            #endregion

            #region custom directed, without repetitions
            TestSet directedWithoutRepetitions = new TestSet();
            g = new AdjacencyMatrixGraph(true, 3);
            g.AddEdge(0, 1, 20);
            g.AddEdge(0, 2, 30);
            g.AddEdge(1, 2, 1);
            g.AddEdge(2, 1, 2);
            directedWithoutRepetitions.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 2, 30));


            g = rgg.DirectedGraph(typeof(AdjacencyMatrixGraph), 100, 0.8, 1, 100, true);
            directedWithoutRepetitions.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 99, 6));

            g = rgg.DirectedGraph(typeof(AdjacencyMatrixGraph), 100, 0.5, 1, 100, true);
            directedWithoutRepetitions.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 99, 8));

            g = rgg.DirectedGraph(typeof(AdjacencyMatrixGraph), 100, 0.2, 1, 100, true);
            directedWithoutRepetitions.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 99, 12));

            g = rgg.DirectedGraph(typeof(AdjacencyMatrixGraph), 1000, 0.8, 1, 100, true);
            directedWithoutRepetitions.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 999, 4));

            g = rgg.DirectedGraph(typeof(AdjacencyMatrixGraph), 1000, 0.2, 1, 100, true);
            directedWithoutRepetitions.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 999, 6));

            g = rgg.DirectedGraph(typeof(AdjacencyMatrixGraph), 1000, 1, 1, 100, true);
            directedWithoutRepetitions.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 999, 4));

            g = rgg.DirectedGraph(typeof(AdjacencyListsGraph <AVLAdjacencyList>), 1500, 0.75, 1, 100, true);
            directedWithoutRepetitions.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 1499, 3));

            g = rgg.DirectedGraph(typeof(AdjacencyListsGraph <AVLAdjacencyList>), 1500, 0, 1, 100, true);
            directedWithoutRepetitions.TestCases.Add(new SimpleSecondPathTestCase(10, g, 0, 1499, null));
            #endregion

            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            long[] elapsedTime = new long[4];


            Console.WriteLine("Custom path with repetitions, undirected graphs");
            stopwatch.Start();
            undirectedWithRepetitions.PreformTests(true, false);
            stopwatch.Stop();
            elapsedTime[0] = stopwatch.ElapsedMilliseconds;

            Console.WriteLine("Custom path with repetitions, directed graphs");
            stopwatch.Restart();
            directedWithRepetitions.PreformTests(true, false);
            stopwatch.Stop();
            elapsedTime[1] = stopwatch.ElapsedMilliseconds;

            Console.WriteLine("Custom path without repetitions, undirected graphs");
            stopwatch.Restart();
            undirectedWithoutRepetitions.PreformTests(true, false);
            stopwatch.Stop();
            elapsedTime[2] = stopwatch.ElapsedMilliseconds;

            Console.WriteLine("Custom path without repetitions, directed graphs");
            stopwatch.Restart();
            directedWithoutRepetitions.PreformTests(true, false);
            stopwatch.Stop();
            elapsedTime[3] = stopwatch.ElapsedMilliseconds;

            Console.WriteLine(String.Empty);
            Console.WriteLine(String.Empty);
            Console.WriteLine("Performance metrics");

            for (int i = 0; i < elapsedTime.Length; i++)
            {
                Console.WriteLine("Test case {0}: {1,5} ms          ({2:F3} times the boilerplate time)", i + 1, elapsedTime[i], (double)elapsedTime[i] / boilerplateTaskTimeElapsed);
            }

            #endregion
        }
		///<summary>Generates a list of all the quality measures for 2014.  Performs all calculations and manipulations.  Returns list for viewing/output.</summary>
		public static List<QualityMeasure> GetAll2014(DateTime dateStart,DateTime dateEnd,long provNum) {
			if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
				return Meth.GetObject<List<QualityMeasure>>(MethodBase.GetCurrentMethod(),dateStart,dateEnd,provNum);
			}
			List<QualityMeasure> list=new List<QualityMeasure>();
			//add one of each type
			QualityMeasure measureCur;
			_measureWeightAssessAll=new QualityMeasure();
			_measureWeightAssess3To11=new QualityMeasure();
			_measureWeightAssess12To16=new QualityMeasure();
#if DEBUG
			System.Diagnostics.Stopwatch s=new System.Diagnostics.Stopwatch();
			System.Diagnostics.Stopwatch stot=new System.Diagnostics.Stopwatch();
			_elapsedtimetext="Elapsed time for each measure.\r\n";
			stot.Restart();
#endif
			for(int i=0;i<Enum.GetValues(typeof(QualityType2014)).Length;i++) {
#if DEBUG
				s.Restart();
#endif
				measureCur=GetEhrCqmData((QualityType2014)i,dateStart,dateEnd,provNum);
				measureCur.Type2014=(QualityType2014)i;
				measureCur.Id=GetId2014(measureCur.Type2014);
				measureCur.Descript=GetDescript2014(measureCur.Type2014);
				if(measureCur.ListEhrPats!=null) {
					if((QualityType2014)i==QualityType2014.Influenza) {
						//only have to count IsDenominator pats for influenza measure, all other measures will have every patient marked IsDenominator (denom=initial pat population)
						//influenza measure applies additional restriction to initial pat population, but ListEhrPats will still have IPP in it, but only some will be in denominator
						measureCur.Denominator=CalcDenominator2014(measureCur.ListEhrPats);
					}
					else if((QualityType2014)i==QualityType2014.MedicationsEntered) {
						//we have to count the number of encounters, not the number of patients, for the denominator count
						measureCur.Denominator=CalcDenominator2014_Encs(measureCur.DictPatNumListEncounters);
					}
					else {
						measureCur.Denominator=measureCur.ListEhrPats.Count;
					}
					if((QualityType2014)i==QualityType2014.MedicationsEntered) {
						measureCur.Numerator=CalcNumerator2014_Encs(measureCur.DictPatNumListEncounters);
						measureCur.Exceptions=CalcException2014_Encs(measureCur.DictPatNumListEncounters);
						measureCur.Exclusions=0;
					}
					else {
						measureCur.Numerator=CalcNumerator2014(measureCur.ListEhrPats);
						measureCur.Exclusions=CalcExclusions2014(measureCur.ListEhrPats);
						measureCur.Exceptions=CalcExceptions2014(measureCur.ListEhrPats);
					}
					measureCur.NotMet=measureCur.Denominator-measureCur.Exclusions-measureCur.Numerator-measureCur.Exceptions;
					//Reporting rate is (Numerator+Exclusions+Exceptions)/Denominator.  Percentage of qualifying pats classified in one of the three groups Numerator, Exception, Exclusion.
					measureCur.ReportingRate=0;
					if(measureCur.Denominator>0) {
						measureCur.ReportingRate=Math.Round(((decimal)((measureCur.Numerator+measureCur.Exclusions+measureCur.Exceptions)*100)/(decimal)(measureCur.Denominator)),1,MidpointRounding.AwayFromZero);
					}
					//Performance rate is Numerator/(Denominator-Exclusions-Exceptions).  Percentage of qualifying pats (who were not in the Exclusions or Exceptions) who were in the Numerator.
					measureCur.PerformanceRate=0;
					if(measureCur.Numerator>0) {
						measureCur.PerformanceRate=Math.Round(((decimal)(measureCur.Numerator*100)/(decimal)(measureCur.Denominator-measureCur.Exclusions-measureCur.Exceptions)),1,MidpointRounding.AwayFromZero);
					}
					measureCur.DenominatorExplain=GetDenominatorExplain2014(measureCur.Type2014);
					measureCur.NumeratorExplain=GetNumeratorExplain2014(measureCur.Type2014);
					measureCur.ExclusionsExplain=GetExclusionsExplain2014(measureCur.Type2014);
					measureCur.ExceptionsExplain=GetExceptionsExplain2014(measureCur.Type2014);
					measureCur.eMeasureNum=GetEMeasureNum(measureCur.Type2014);
					measureCur.eMeasureTitle=GetEMeasureTitle(measureCur.Type2014);
					measureCur.eMeasureVersion=GetEMeasureVersion(measureCur.Type2014);
					measureCur.eMeasureVNeutralId=GetEMeasureVNeutralId(measureCur.Type2014);
					measureCur.eMeasureVSpecificId=GetEMeasureVSpecificId(measureCur.Type2014);
					measureCur.eMeasureSetId=GetEMeasureSetId(measureCur.Type2014);
					measureCur.eMeasureIppId=GetEMeasureIppId(measureCur.Type2014);
					measureCur.eMeasureDenomId=GetEMeasureDenomId(measureCur.Type2014);
					measureCur.eMeasureDenexId=GetEMeasureDenexId(measureCur.Type2014);
					measureCur.eMeasureDenexcepId=GetEMeasureDenexcepId(measureCur.Type2014);
					measureCur.eMeasureNumerId=GetEMeasureNumerId(measureCur.Type2014);
				}
				list.Add(measureCur);
#if DEBUG
				s.Stop();
				_elapsedtimetext+=((QualityType2014)i).ToString()+": "+s.Elapsed.ToString()+"\r\n";
#endif
			}
#if DEBUG
			stot.Stop();
			_elapsedtimetext+="Total elapsed time: "+stot.Elapsed.ToString();
			System.Windows.Forms.MessageBox.Show(_elapsedtimetext);
#endif
			return list;
		}
Exemple #33
0
        private static void OnRenderFrame()
        {
            watch.Stop();
            float deltaTime = (float)watch.ElapsedTicks / System.Diagnostics.Stopwatch.Frequency;

            watch.Restart();

            // set up the viewport and clear the previous depth and color buffers
            Gl.Viewport(0, 0, width, height);
            Gl.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

            // perform rotation of the cube depending on the keyboard state
            if (autoRotate)
            {
                xangle += deltaTime / 2;
                yangle += deltaTime;
            }
            if (right)
            {
                yangle += deltaTime;
            }
            if (left)
            {
                yangle -= deltaTime;
            }
            if (up)
            {
                xangle -= deltaTime;
            }
            if (down)
            {
                xangle += deltaTime;
            }

            // make sure the shader program and texture are being used
            Gl.UseProgram(program);
            Gl.ActiveTexture(TextureUnit.Texture1);
            Gl.BindTexture(brickNormals);
            Gl.ActiveTexture(TextureUnit.Texture0);
            Gl.BindTexture(brickDiffuse);

            // set up the model matrix and draw the cube
            program["model_matrix"].SetValue(Matrix4.CreateRotationY(yangle) * Matrix4.CreateRotationX(xangle));
            program["enable_lighting"].SetValue(lighting);
            program["enable_mapping"].SetValue(normalMapping);

            Gl.BindBufferToShaderAttribute(cube, program, "vertexPosition");
            Gl.BindBufferToShaderAttribute(cubeNormals, program, "vertexNormal");
            Gl.BindBufferToShaderAttribute(cubeTangents, program, "vertexTangent");
            Gl.BindBufferToShaderAttribute(cubeUV, program, "vertexUV");
            Gl.BindBuffer(cubeTriangles);

            Gl.DrawElements(BeginMode.Triangles, cubeTriangles.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);

            // bind the font program as well as the font texture
            Gl.UseProgram(fontProgram.ProgramID);
            Gl.BindTexture(font.FontTexture);

            // draw the tutorial information, which is static
            information.Draw();

            Glut.glutSwapBuffers();
        }
Exemple #34
0
 //主框架程序入口
 public void MOEADprocedure(string configFilePath, string logName)
 {
     System.Diagnostics.Stopwatch time = new System.Diagnostics.Stopwatch();//记录程序运行时间
     string currentDirectory = System.Environment.CurrentDirectory;
     time.Start();
     prepareData(currentDirectory + configFilePath);
     time.Stop();
     Console.WriteLine("小区集合初始化完成,一共有"+slist.sectorList.Count+"个小区,总用时:" +time.Elapsed.TotalSeconds+"秒");
     time.Restart();
     interfori=check(delta2, ref ancestor);
     time.Stop();
     Console.WriteLine("初始干扰计算完成,初始全网总干扰为:" + ancestor.interf + "总用时:" + time.Elapsed.TotalSeconds + "秒");
     adduseablefcntocell();//给小区集合加上可用频点,可以以后改动条件针对不同背景
     List<int> highintefcelllist = SearchHighList(delta2,70);
        // List<int> highintefcelllist = new List<int>() {1,2,3 };
     Console.WriteLine("高干扰小区有:"+highintefcelllist.Count+"个");
     for (int i = 0; i < highintefcelllist.Count; i++)
     {
         Console.Write(ancestor.gene[highintefcelllist[i]]+" ");
     }
     Console.WriteLine();
     time.Restart();
     //if (SearchBetter(highintefcelllist))
     //{
     //    Console.WriteLine("找到更好的分配方案,一共用时 {0} 秒", time.Elapsed.TotalSeconds);
     //}
     //else
     //{
     //    Console.WriteLine("没找到,一共用时 {0} 秒", time.Elapsed.TotalSeconds);
     //}
       int count = 0;//频点变化个数统计
     //for (int i = 0; i < highintefcelllist.Count; i++)
     //{
     //    Console.Write(ancestor.gene[highintefcelllist[i]] + " ");
     //    if (ancestor.gene[highintefcelllist[i]] != ancestorori.gene[highintefcelllist[i]])
     //    {
     //        count++;
     //    }
     //}
     //Console.WriteLine();
     //Console.WriteLine("频点变化个数一共:"+count);
     //check(delta2,ref ancestor);
     //Console.WriteLine("全网最终优化解的总干扰为:"+ancestor.interf+"提升了"+(interfori-ancestor.interf)/interfori*100+"%");
     SearchBetter2(highintefcelllist);
     for (int i = 0; i < highintefcelllist.Count; i++)
     {
         Console.Write(ancestor.gene[highintefcelllist[i]] + " ");
         if (ancestor.gene[highintefcelllist[i]] != ancestorori.gene[highintefcelllist[i]])
         {
             count++;
         }
     }
     Console.WriteLine();
     Console.WriteLine("频点变化个数一共:"+count);
     check(delta2,ref ancestor);
     Console.WriteLine("全网最终优化解的总干扰为:"+ancestor.interf+"提升了"+(interfori-ancestor.interf)/interfori*100+"%");
 }
Exemple #35
0
        static void Main(string[] args)
        {
            Config.LoadConfig();
            Config.SetupLogging();

            bool logLevelIsVerbose = Log.IsEnabled(LogEventLevel.Verbose);

            InitRandom();

            // DB stuff will go here eventually

            server = new Server();

            // Load client-list dependent stuff after here
            simpleChat = new SimpleChat();

            // Last part of startup
            Commands.Ready();
            Console.WriteLine("Ready. Press enter to start:");
            Console.ReadLine();
            server.Start();
            Console.WriteLine("Running. Press 'q' to stop.");
            int counter   = 0;
            var stopwatch = new System.Diagnostics.Stopwatch();

            stopwatch.Start();

            while (running)
            {
                counter++;

                if (Console.KeyAvailable)
                {
                    if (Console.ReadKey(true).KeyChar == 'q')
                    {
                        running = false;
                        Log.Information("Shutdown started from console.");
                        server.clients.SendToAll("&RShutdown initiated from Console.&X");
                    }
                }


                if (stopwatch.ElapsedMilliseconds >= MAIN_TICKRATE)
                {
                    server.CheckConnectionsAlive(); // Check server connections and flag disconnected ones for client removal, then remove them

                    Log.Verbose("Tick. {clientsConnected} clients connected.", server.clients.Count);
                    if (stopwatch.ElapsedMilliseconds > (MAIN_TICKRATE * 2))
                    {
                        Log.Warning("LAG: {elapsedMilliseconds} ms : {cycles} cycles!", stopwatch.ElapsedMilliseconds, counter);
                    }

                    server.clients.GetAllInput();

                    // Game Update Stuff Happens Here
                    OnUpdate?.Invoke(null, null);


                    // End of this game update loop, send waiting data.
                    server.clients.FlushAll();
                    stopwatch.Restart();
                    counter = 0;
                }
                Thread.Sleep(10);
            }

            //Shutdown goes here

            foreach (var client in server.clients.GetClientList())
            {
                client.Status = ClientStatus.Disconnecting;
            }
            server.clients.FlushAll();
            server.Stop();

            Log.Information("Shutdown complete.");
            Log.CloseAndFlush();

            Console.WriteLine("Done.");
            Console.ReadLine();
        }
        // Driver
        static void Main(string[] args)
        {
            System.Diagnostics.Stopwatch sp = new System.Diagnostics.Stopwatch();
            int res;

            sp.Start(); res = howMany(2, 10); sp.Stop();
            Console.WriteLine("A=2, B=10 : {0} underprimes found in {1} ms", res, sp.ElapsedMilliseconds);
            sp.Restart(); res = howMany(100, 105); sp.Stop();
            Console.WriteLine("A=100, B=105 : {0} underprimes found in  in {1} ms", res, sp.ElapsedMilliseconds);
            sp.Restart(); res = howMany(17,17); sp.Stop();
            Console.WriteLine("A=17, B=17 : {0} underprimes found in  in {1} ms", res, sp.ElapsedMilliseconds);
            sp.Restart(); res = howMany(123, 456); sp.Stop();
            Console.WriteLine("A=123, B=456 : {0} underprimes found in  in {1} ms", res, sp.ElapsedMilliseconds);
            sp.Restart(); res = howMany(2, 100000); sp.Stop(); // 5600ms - Core 2 Duo
            Console.WriteLine("A=2, B=100000 : {0} underprimes found in  in {1} ms", res, sp.ElapsedMilliseconds);
        }
Exemple #37
0
        /// <summary>
        /// Initiates the meter readings by meter identifier.
        /// </summary>
        /// <param name="messages">Messages.</param>
        public static void InitiateMeterReadingsByMeterID(int messages)
        {
            var wallTime = new System.Diagnostics.Stopwatch();
            var client   = new MDM_Server();

            client.Url = "https://10.87.1.95/MultiSpeak/416/1/MDM_Server.asmx";
            StdOut(client.Url);

            //Add the security - once for the entire batch
            var header = new MultiSpeakMsgHeader {
                Company = "Spacely's Sprockets",
                UserID  = "niscmr",
                Pwd     = "niscmr",
                AppName = "TestApp for HAProxy"
            };

            client.MultiSpeakMsgHeaderValue = header;

            for (int i = 0; i < messages; i++)
            {
                try {
                    StdOut("********** NEW MESSAGE **********");
                    wallTime.Restart();
                    // Add fake meters
                    meterID[] meters =
                    {
                        new meterID {
                            meterNo              = "0",
                            objectID             = i.ToString(),
                            serviceType          = serviceType.Electric,
                            serviceTypeSpecified = true,
                            utility              = i + "_HA_Test",
                            //Value = "What is this for?"
                        }
                    };
                    LogRequest(meters, header);

                    string responseURL = "http://10.86.1.31/Simulators/MultiSpeak/416/MDM_Server.asmx";
                    //Where we send the results, need a test url for this...
                    //responseURL = "";  //Test this for empty url and error to be returned.
                    string transactionID = i.ToString();                     //Guid.NewGuid().ToString();
                    var    lifespan      = new expirationTime {
                        units = timeUnits.Hours,
                        Value = 1
                    };

                    //self-signed cert override
                    ServicePointManager.ServerCertificateValidationCallback = delegate(
                        object obj, X509Certificate certificate, X509Chain chain,

                        SslPolicyErrors errors) {
                        return(true);
                    };

                    var results = client.InitiateMeterReadingsByMeterID(meters, responseURL, transactionID, lifespan);

                    if (results != null)
                    {
                        foreach (var result in results)
                        {
                            StdOut("errorString\t: " + result.errorString);
                            StdOut("eventTime \t: " + result.eventTime);
                            StdOut("eventTimeSpecified \t: " + result.eventTimeSpecified);
                            StdOut("nounType \t: " + result.nounType);
                            StdOut("objectID \t: " + result.objectID);
                            StdOut("Value \t: " + result.Value);
                        }
                    }
                    //System.Threading.Thread.Sleep(1000);
                    wallTime.Stop();
                    StdOut("Wall Time | " + wallTime.Elapsed);
                    StdOut("********** END MESSAGE **********");
                } catch (Exception ex) {
                    StdOut("Exception TransactionID | (" + i + ") | " + ex.Message);
                    if (ex.InnerException != null)
                    {
                        StdOut("InnerException TransactionID | (" + i + ") | " + ex.Message);
                    }
                    wallTime.Stop();
                    StdOut("Wall Time | " + wallTime.Elapsed);
                    StdOut("********** END MESSAGE **********");
                }
            }             //end of loop
        }
		private CheckForUpdatesLoopResult SetupCheckForUpdatesLoop()
		{
			const int pulse = 1000;
			var pollingInterval = (long) _integrationSettings.CheckForUpdatesIntervalSeconds*1000;

			var stopWatch = new System.Diagnostics.Stopwatch();
			stopWatch.Start();

			do
			{
				if (!stopWatch.IsRunning) stopWatch.Restart();
				if (ShouldContinue)
				{
					while (stopWatch.ElapsedMilliseconds < pollingInterval)
					{
						if (!ShouldContinue) return CheckForUpdatesLoopResult.Exit;
						Thread.Sleep(pulse);
					}
				}
				try
				{
					stopWatch.Stop();

					//Now do the work
					var checkResults = _api.CheckForUpdates(_board.Id, _board.Version);

					if (checkResults == null) continue;

					OnBoardStatusChecked(new BoardStatusCheckedEventArgs {HasChanges = checkResults.HasUpdates});

					if (!checkResults.HasUpdates) continue;

					try
					{
						_boardLock.EnterUpgradeableReadLock();

						var boardChangedEventArgs = new BoardChangedEventArgs();

						if (checkResults.Events.Any(x => x.RequiresBoardRefresh))
						{
							boardChangedEventArgs.BoardWasReloaded = true;
							OnBoardChanged(boardChangedEventArgs);
							return CheckForUpdatesLoopResult.Continue;
						}

						//Now we need to spin through and update the board
						//and create the information to event
						foreach (var boardEvent in checkResults.Events)
						{
							try
							{
								switch (GetEventType(boardEvent.EventType))
								{
									case EventType.CardCreation:
										var addCardEvent = CreateCardAddEvent(boardEvent, checkResults.AffectedLanes);
										if (addCardEvent != null) boardChangedEventArgs.AddedCards.Add(addCardEvent);
										break;
									case EventType.CardMove:
										var movedCardEvent = CreateCardMoveEvent(boardEvent, checkResults.AffectedLanes);
										if (movedCardEvent != null) boardChangedEventArgs.MovedCards.Add(movedCardEvent);
										break;
									case EventType.CardFieldsChanged:
										var changedFieldsEvent = CreateCardUpdateEvent(boardEvent, checkResults.AffectedLanes);
										if (changedFieldsEvent != null) boardChangedEventArgs.UpdatedCards.Add(changedFieldsEvent);
										break;
									case EventType.CardDeleted:
										boardChangedEventArgs.DeletedCards.Add(CreateCardDeletedEvent(boardEvent));
										break;
									case EventType.CardBlocked:
										if (boardEvent.IsBlocked)
											boardChangedEventArgs.BlockedCards.Add(CreateCardBlockedEvent(boardEvent,
												checkResults.AffectedLanes));
										else
											boardChangedEventArgs.UnBlockedCards.Add(CreateCardUnBlockedEvent(boardEvent,
												checkResults.AffectedLanes));
										break;
									case EventType.UserAssignment:
										if (boardEvent.IsUnassigning)
											boardChangedEventArgs.UnAssignedUsers.Add(CreateCardUserUnAssignmentEvent(boardEvent,
												checkResults.AffectedLanes));
										else
											boardChangedEventArgs.AssignedUsers.Add(CreateCardUserAssignmentEvent(boardEvent,
												checkResults.AffectedLanes));
										break;
									case EventType.CommentPost:
										boardChangedEventArgs.PostedComments.Add(CreateCommentPostedEvent(boardEvent));
										break;
									case EventType.WipOverride:
										boardChangedEventArgs.WipOverrides.Add(CreateWipOverrideEvent(boardEvent,
											checkResults.AffectedLanes));
										break;
									case EventType.UserWipOverride:
										boardChangedEventArgs.UserWipOverrides.Add(CreateUserWipOverrideEvent(boardEvent));
										break;
									case EventType.AttachmentChange:
										var attachmentEvent = CreateAttachmentEvent(boardEvent);
										if (attachmentEvent != null) boardChangedEventArgs.AttachmentChangedEvents.Add(attachmentEvent);
										break;

									case EventType.CardMoveToBoard:
										boardChangedEventArgs.CardMoveToBoardEvents.Add(CreateCardMoveToBoardEvent(boardEvent));
										break;

									case EventType.CardMoveFromBoard:
										boardChangedEventArgs.CardMoveFromBoardEvents.Add(CreateCardMoveFromBoardEvent(boardEvent));
										break;

									case EventType.BoardEdit:
										boardChangedEventArgs.BoardEditedEvents.Add(CreateBoardEditedEvent(boardEvent));
										boardChangedEventArgs.BoardStructureChanged = true;
										break;

									case EventType.BoardCardTypesChanged:
										boardChangedEventArgs.BoardCardTypesChangedEvents.Add(new BoardCardTypesChangedEvent(boardEvent.EventDateTime));
										boardChangedEventArgs.BoardStructureChanged = true;
										break;

									case EventType.BoardClassOfServiceChanged:
										boardChangedEventArgs.BoardClassOfServiceChangedEvents.Add(
											new BoardClassOfServiceChangedEvent(boardEvent.EventDateTime));
										boardChangedEventArgs.BoardStructureChanged = true;
										break;

									case EventType.Unrecognized:
										//Console.Beep();
										break;
								}
							}
							catch (Exception ex)
							{
								OnClientError(new ClientErrorEventArgs
								{
									Exception = ex,
									Message = "Error processing board change event. " + ex.Message
								});
							}
						}

						OnBoardChanged(boardChangedEventArgs);

						_boardLock.EnterWriteLock();
						try
						{
							//we need to check to see if there is a need to refresh the entire board
							//if so, we need to refresh the entire board and raise the board refreshed event
							if (!checkResults.RequiresRefesh())
							{
								//since the board does not require a refresh, then just change the effected lanes
								ApplyBoardChanges(checkResults.CurrentBoardVersion, checkResults.AffectedLanes);
							}
							else
							{
								_board = checkResults.NewPayload;
								OnBoardRefresh(new BoardInfoRefreshedEventArgs {FromBoardChange = true});
							}
						}
						catch (Exception ex)
						{
							OnClientError(new ClientErrorEventArgs
							{
								Exception = ex,
								Message = "Error applying board changes or raising board refresh."
							});
						}
						finally
						{
							_boardLock.ExitWriteLock();
						}
					}
					catch (Exception ex)
					{
						OnClientError(new ClientErrorEventArgs {Exception = ex, Message = "Error processing board events."});
					}
					finally
					{
						_boardLock.ExitUpgradeableReadLock();
					}
				}
				catch (Exception ex)
				{
					OnClientError(new ClientErrorEventArgs {Exception = ex, Message = "Error checking for board events."});
				}
			} while (ShouldContinue);

			stopWatch.Stop();

			return CheckForUpdatesLoopResult.Exit;
		}
Exemple #39
0
        private void reading(object com)
        {
            int read_buffer = 64;
            int len = 0;
            byte[] buffer = new byte[read_buffer];
            System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
            timer.Start();
            byte2display = new Queue();
            try
            {
                while (true)
                {
                    if (active_com.BytesToRead >= read_buffer)
                    {
                        len = active_com.Read(buffer, 0, read_buffer);
                        byte2display.Enqueue(buffer.Clone());
                        timer.Restart();
                    }
                    if (timer.ElapsedMilliseconds >= 3000)
                    {
                        richTextBox1.Invoke(new Action(() => richTextBox1.ForeColor = Color.Black));
                        Disconnect();
                    }

                }
            }
            catch (COMException sd)
            {
                MessageBox.Show("Произошла ошибка - " + sd.Message + "\nПопробуйте выбрать другой СОМ порт.");
                reading_active.Abort();
                Thread.Sleep(50);
                display_active.Abort();
                Thread.Sleep(50);

                return;
            }

            timer.Stop();
        }
Exemple #40
0
		public static List<List<int>> GetProdProvs(DateTime dateFrom,DateTime dateTo) {
			if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
				return Meth.GetObject<List<List<int>>>(MethodBase.GetCurrentMethod(),dateFrom,dateTo);
			}
			Random rnd=new Random();
			string rndStr=rnd.Next(1000000).ToString();
			string command;
#if DEBUG
			_elapsedTimeProdProvs="";
			System.Diagnostics.Stopwatch stopWatch=new System.Diagnostics.Stopwatch();
			System.Diagnostics.Stopwatch stopWatchTotal=new System.Diagnostics.Stopwatch();
			_elapsedTimeProdProvs="Elapsed time for GetProdProvs:\r\n";
			stopWatch.Restart();
			stopWatchTotal.Restart();
#endif
			command="DROP TABLE IF EXISTS tempdash"+rndStr+@";";
			Db.NonQ(command);
#if DEBUG
			stopWatch.Stop();
			_elapsedTimeProdProvs+="DROP TABLE: "+stopWatch.Elapsed.ToString()+"\r\n";
			stopWatch.Restart();
#endif
			//this table will contain approx 12x3xProv rows if there was production for each prov in each month.
			command=@"CREATE TABLE tempdash"+rndStr+@" (
				DatePeriod date NOT NULL,
				ProvNum bigint NOT NULL,
				production decimal NOT NULL
				) DEFAULT CHARSET=utf8";
			Db.NonQ(command);
#if DEBUG
			stopWatch.Stop();
			_elapsedTimeProdProvs+="CREATE TABLE: "+stopWatch.Elapsed.ToString()+"\r\n";
			stopWatch.Restart();
#endif
			//procs. Inserts approx 12xProv rows
			command=@"INSERT INTO tempdash"+rndStr+@"
				SELECT procedurelog.ProcDate,procedurelog.ProvNum,
				SUM(procedurelog.ProcFee*(procedurelog.UnitQty+procedurelog.BaseUnits))-IFNULL(SUM(claimproc.WriteOff),0)
				FROM procedurelog USE INDEX(indexPNPD)
				LEFT JOIN claimproc ON procedurelog.ProcNum=claimproc.ProcNum
				AND claimproc.Status='7' /*only CapComplete writeoffs are subtracted here*/
				WHERE procedurelog.ProcStatus = '2'
				AND procedurelog.ProcDate >= "+POut.Date(dateFrom)+@"
				AND procedurelog.ProcDate <= "+POut.Date(dateTo)+@"
				GROUP BY procedurelog.ProvNum,MONTH(procedurelog.ProcDate)";
			Db.NonQ(command);
#if DEBUG
			stopWatch.Stop();
			_elapsedTimeProdProvs+="INSERT INTO: "+stopWatch.Elapsed.ToString()+"\r\n";
			stopWatch.Restart();
#endif
			
			//todo 2 more tables


			//get all the data as 12xProv rows
			command=@"SELECT DatePeriod,ProvNum,SUM(production) prod
				FROM tempdash"+rndStr+@" 
				GROUP BY ProvNum,MONTH(DatePeriod)";//this fails with date issue
			DataTable tableProd=Db.GetTable(command);
#if DEBUG
			stopWatch.Stop();
			_elapsedTimeProdProvs+="tableProd: "+stopWatch.Elapsed.ToString()+"\r\n";
			stopWatch.Restart();
#endif
			command="DROP TABLE IF EXISTS tempdash"+rndStr+@";";
#if DEBUG
			stopWatch.Stop();
			_elapsedTimeProdProvs+="DROP TABLE: "+stopWatch.Elapsed.ToString()+"\r\n";
			stopWatch.Restart();
#endif
			Db.NonQ(command);
			command=@"SELECT ProvNum
				FROM provider WHERE IsHidden=0
				ORDER BY ItemOrder";
			DataTable tableProv=Db.GetTable(command);
#if DEBUG
			stopWatch.Stop();
			stopWatchTotal.Stop();
			_elapsedTimeProdProvs+="SELECT ProvNum FROM provider: "+stopWatch.Elapsed.ToString()+"\r\n";
			_elapsedTimeProdProvs+="Total: "+stopWatchTotal.Elapsed.ToString();
			if(_showElapsedTimesForDebug) {
				System.Windows.Forms.MessageBox.Show(_elapsedTimeProdProvs);
			}
#endif
			List<List<int>> retVal=new List<List<int>>();
			for(int p=0;p<tableProv.Rows.Count;p++){//loop through each provider
				long provNum=PIn.Long(tableProv.Rows[p]["ProvNum"].ToString());
				List<int> listInt=new List<int>();//12 items
				for(int i=0;i<12;i++) {
					decimal prod=0;
					DateTime datePeriod=dateFrom.AddMonths(i);//only the month and year are important
					for(int j=0;j<tableProd.Rows.Count;j++)  {
						if(provNum==PIn.Long(tableProd.Rows[j]["ProvNum"].ToString())
							&& datePeriod.Month==PIn.Date(tableProd.Rows[j]["DatePeriod"].ToString()).Month
							&& datePeriod.Year==PIn.Date(tableProd.Rows[j]["DatePeriod"].ToString()).Year)
						{
		 					prod=PIn.Decimal(tableProd.Rows[j]["prod"].ToString());
							break;
						}
   				}
					listInt.Add((int)(prod));
				}
				retVal.Add(listInt);
			}
			return retVal;
		}
Exemple #41
0
        private void straight_read(object com)
        {
            int read_buffer = 17;
            int len = 0;
            byte[] buffer = new byte[read_buffer];
            byte mini_buffer = 0;
            byte[] temp = new byte[2];
            bool reset = false;
            System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
            timer.Start();
            packet legacy = new packet();
            Time reset_time = new Time(0, 0, 0);
            try
            {
                while (true)
                {
                    if (active_com.BytesToRead > 0)
                    {
                        mini_buffer = (byte)active_com.ReadByte();
                        if (mini_buffer == 10)
                        {
                            mini_buffer = (byte) active_com.ReadByte();
                            if (mini_buffer == 13)
                            {
                                while (active_com.BytesToRead < 17)
                                {
                                }
                                len = active_com.Read(buffer,0,17);

                                textBox13.Invoke(new Action(() => textBox13.Text = "" + buffer[0]));
                                textBox12.Invoke(new Action(() => textBox12.Text = "" + buffer[1]));
                                textBox11.Invoke(new Action(() => textBox11.Text = "" + buffer[2]));

                                temp[0] = buffer[5]; temp[1] = buffer[4];
                                textBox6.Invoke(new Action(() => textBox6.Text = string.Format("{0:F1}", (float)BitConverter.ToInt16(temp, 0) / 10)));
                                temp[0] = buffer[7]; temp[1] = buffer[6];
                                textBox5.Invoke(new Action(() => textBox5.Text = "" + BitConverter.ToInt16(temp, 0)));
                                temp[0] = buffer[9]; temp[1] = buffer[8];
                                textBox3.Invoke(new Action(() => textBox3.Text = "" + BitConverter.ToInt16(temp, 0)));
                                temp[0] = buffer[11]; temp[1] = buffer[10];
                                textBox7.Invoke(new Action(() => textBox7.Text = string.Format("{0:F1}",(float) BitConverter.ToInt16(temp, 0) / 10)));
                                temp[0] = buffer[14]; temp[1] = buffer[13];
                                textBox4.Invoke(new Action(() => textBox4.Text = "" + buffer[12] + " " + BitConverter.ToUInt16(temp, 0)));

                                if (((buffer[3] == 0) || (buffer[3] == 10)))// && (!reset))
                                {
                                    legacy.time_h = buffer[0];
                                    legacy.time_min = buffer[1];
                                    legacy.time_sec = buffer[2];
                                    legacy.status = buffer[3];
                                    temp[0] = buffer[5]; temp[1] = buffer[4];
                                    legacy.temp = BitConverter.ToInt16(temp, 0);
                                    temp[0] = buffer[7]; temp[1] = buffer[6];
                                    legacy.prok = BitConverter.ToInt16(temp, 0);
                                    temp[0] = buffer[9]; temp[1] = buffer[8];
                                    legacy.n = BitConverter.ToInt16(temp, 0);
                                    temp[0] = buffer[11]; temp[1] = buffer[10];
                                    legacy.vel = BitConverter.ToInt16(temp, 0);
                                    legacy.Km = buffer[12];
                                    temp[0] = buffer[14]; temp[1] = buffer[13];
                                    legacy.meter = BitConverter.ToUInt16(temp, 0);
                                    legacy.char_pulse = buffer[15];
                                    legacy.check_sum = buffer[16];
                                    reset = true;
                                    //reset_timereset_time = new Time(buffer[0], buffer[1], buffer[2]);

                                }
                                if ((buffer[3] != 0))// && (buffer[3]!=10))
                                    reset = false;

                                //reset_time.difference(buffer[0], buffer[1], buffer[2]);
                                if (buffer[2] >= legacy.time_sec)
                                    buffer[2] = (byte)(buffer[2] - legacy.time_sec);
                                else
                                {
                                    buffer[1] -= 1;
                                    buffer[2] = (byte)(60 + (buffer[2] - legacy.time_sec));
                                }
                                if (buffer[1] >= legacy.time_min)
                                    buffer[1] = (byte)(buffer[1] - legacy.time_min);
                                else
                                {
                                    buffer[0] -= 1;
                                    buffer[1] = (byte)(60 + (buffer[1] - legacy.time_min));
                                }
                                if (buffer[0] >= legacy.time_h)
                                    buffer[0] = (byte)(buffer[0] - legacy.time_h);

                                textBox10.Invoke(new Action(() => textBox10.Text = "" + (buffer[0])));
                                textBox9.Invoke(new Action(() => textBox9.Text = "" + (buffer[1])));
                                textBox8.Invoke(new Action(() => textBox8.Text = "" + (buffer[2])));

                                temp[0] = buffer[9]; temp[1] = buffer[8];
                                textBox1.Invoke(new Action(() => textBox1.Text = "" + (BitConverter.ToInt16(temp, 0) - legacy.n)));
                                temp[0] = buffer[14]; temp[1] = buffer[13];
                                textBox2.Invoke(new Action(() => textBox2.Text = "" + (buffer[12] - legacy.Km) + " " +
                                    (BitConverter.ToUInt16(temp, 0) - legacy.meter)));
                                textBox14.Invoke(new Action(() => textBox14.Text = "" + buffer[15]));
                            }
                        }
                        timer.Restart();
                    }
                    if (timer.ElapsedMilliseconds >= 3000)
                    {
                        richTextBox1.Invoke(new Action(() => richTextBox1.ForeColor = Color.Black));
                        Disconnect();
                    }
                }
            }
            catch (COMException sd)
            {
                MessageBox.Show("Произошла ошибка - " + sd.Message + "\nПопробуйте выбрать другой СОМ порт.");
                reading_active.Abort();
                Thread.Sleep(50);
                display_active.Abort();
                Thread.Sleep(50);

                return;
            }

            timer.Stop();
        }
Exemple #42
0
		///<summary>Only one dimension to the list for now.</summary>
		public static List<List<int>> GetAR(DateTime dateFrom,DateTime dateTo,List<DashboardAR> listDashAR) {
			if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
				return Meth.GetObject<List<List<int>>>(MethodBase.GetCurrentMethod(),dateFrom,dateTo,listDashAR);
			}
			//assumes that dateFrom is the first of the month and that there are 12 periods
			//listDashAR may be empty, in which case, this routine will take about 18 seconds, but the user was warned.
			//listDashAR may also me incomplete, especially the most recent month(s).
			string command;
			List<int> listInt;
			listInt=new List<int>();
			bool agingWasRun=false;
#if DEBUG
			_elapsedTimeAR="";
			System.Diagnostics.Stopwatch stopWatch=new System.Diagnostics.Stopwatch();
			System.Diagnostics.Stopwatch stopWatchTotal=new System.Diagnostics.Stopwatch();
			_elapsedTimeAR="Elapsed time for GetAR:\r\n";
			stopWatch.Restart();
			stopWatchTotal.Restart();
#endif
			for(int i=0;i<12;i++) {
				DateTime dateLastOfMonth=dateFrom.AddMonths(i+1).AddDays(-1);
				DashboardAR dash=null;
				for(int d=0;d<listDashAR.Count;d++) {
					if(listDashAR[d].DateCalc!=dateLastOfMonth) {
						continue;
					}
					dash=listDashAR[d];
				}
				if(dash!=null) {//we found a DashboardAR object from the database for this month, so use it.
					listInt.Add((int)dash.BalTotal);
					continue;
				}
				agingWasRun=true;
#if DEBUG
				stopWatch.Restart();
#endif
				//run historical aging on all patients based on the date entered.
				Ledgers.ComputeAging(0,dateLastOfMonth,true);
				command=@"SELECT SUM(Bal_0_30+Bal_31_60+Bal_61_90+BalOver90),SUM(InsEst) FROM patient";
				DataTable table=Db.GetTable(command);
#if DEBUG
				stopWatch.Stop();
				_elapsedTimeAR+="Ledgers.ComputeAging() #"+i+" : "+stopWatch.Elapsed.ToString()+"\r\n";
				stopWatch.Restart();
#endif
				dash=new DashboardAR();
				dash.DateCalc=dateLastOfMonth;
				dash.BalTotal=PIn.Double(table.Rows[0][0].ToString());
				dash.InsEst=PIn.Double(table.Rows[0][1].ToString());
				DashboardARs.Insert(dash);//save it to the db for later.
				listInt.Add((int)dash.BalTotal);//and also use it now.
			}
			if(agingWasRun) {
#if DEBUG
				stopWatch.Restart();
#endif
				Ledgers.RunAging();//set aging back to normal
#if DEBUG
				stopWatch.Stop();
				_elapsedTimeAR+="set aging back to normal: "+stopWatch.Elapsed.ToString()+"\r\n";
				stopWatch.Restart();
#endif
			}
#if DEBUG
			stopWatch.Stop();
			stopWatchTotal.Stop();
			_elapsedTimeAR+="Total: "+stopWatchTotal.Elapsed.ToString();
			if(_showElapsedTimesForDebug) {
				System.Windows.Forms.MessageBox.Show(_elapsedTimeAR);
			}
#endif
			List<List<int>> retVal=new List<List<int>>();
			retVal.Add(listInt);
			return retVal;
		}
Exemple #43
0
        public override void OnDraw(Graphics2D graphics2D)
        {
            double numSecondsSinceLastDraw = timeSinceLastDraw.Elapsed.TotalSeconds;

            timeSinceLastDraw.Restart();

            Button parentButton = (Button)Parent;

            double x = parentButton.Width / 2 - normalImage.Width / 2;
            double y = parentButton.Height / 2 - normalImage.Height / 2;

            if (!parentButton.Enabled)
            {
                graphics2D.Render(disabledImage, x, y);
                base.OnDraw(graphics2D);
                return;
            }

            if (parentButton.UnderMouseState == UI.UnderMouseState.FirstUnderMouse)
            {
                if (parentButton.MouseDownOnWidget)
                {
                    graphics2D.Render(pressedImage, x, y);
                }
                else
                {
                    if (NumSecondsToFade > 0)
                    {
                        if (hoverOpacity < 1)
                        {
                            graphics2D.Render(normalImage, x, y);
                        }
                        IRecieveBlenderByte oldBlender = null;
                        if (graphics2D.DestImage != null)
                        {
                            oldBlender = graphics2D.DestImage.GetRecieveBlender();
                            graphics2D.DestImage.SetRecieveBlender(new BlenderPolyColorPreMultBGRA(new Color(1, 1, 1, hoverOpacity)));
                        }
                        graphics2D.Render(hoverImage, x, y);
                        if (graphics2D.DestImage != null)
                        {
                            graphics2D.DestImage.SetRecieveBlender(oldBlender);
                        }
                    }
                    else
                    {
                        graphics2D.Render(hoverImage, x, y);
                    }
                }

                if (NumSecondsToFade > 0)
                {
                    hoverOpacity += numSecondsSinceLastDraw / NumSecondsToFade;
                }
                if (hoverOpacity > 1)
                {
                    hoverOpacity = 1;
                }
            }
            else
            {
                graphics2D.Render(normalImage, x, y);
                if (NumSecondsToFade > 0 && hoverOpacity > 0)
                {
                    IRecieveBlenderByte oldBlender = null;
                    if (graphics2D.DestImage != null)
                    {
                        oldBlender = graphics2D.DestImage.GetRecieveBlender();
                        graphics2D.DestImage.SetRecieveBlender(new BlenderPolyColorPreMultBGRA(new Color(1, 1, 1, hoverOpacity)));
                    }

                    graphics2D.Render(hoverImage, x, y);
                    if (graphics2D.DestImage != null)
                    {
                        graphics2D.DestImage.SetRecieveBlender(oldBlender);
                    }
                }

                if (NumSecondsToFade > 0)
                {
                    hoverOpacity -= numSecondsSinceLastDraw / NumSecondsToFade;
                }
                if (hoverOpacity < 0)
                {
                    hoverOpacity = 0;
                }
            }

            base.OnDraw(graphics2D);
        }
Exemple #44
0
		public static List<List<int>> GetNewPatients(DateTime dateFrom,DateTime dateTo) {
			if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
				return Meth.GetObject<List<List<int>>>(MethodBase.GetCurrentMethod(),dateFrom,dateTo);
			}
			Random rnd=new Random();
			string rndStr=rnd.Next(1000000).ToString();
#if DEBUG
			_elapsedTimeNewPatients="";
			System.Diagnostics.Stopwatch stopWatch=new System.Diagnostics.Stopwatch();
			System.Diagnostics.Stopwatch stopWatchTotal=new System.Diagnostics.Stopwatch();
			_elapsedTimeNewPatients="Elapsed time for GetNewPatients:\r\n";
			stopWatch.Restart();
			stopWatchTotal.Restart();
#endif
			string command;
			command="DROP TABLE IF EXISTS tempdash"+rndStr+@";";
			Db.NonQ(command);
#if DEBUG
			stopWatch.Stop();
			_elapsedTimeNewPatients+="DROP TABLE: "+stopWatch.Elapsed.ToString()+"\r\n";
			stopWatch.Restart();
#endif
			command=@"CREATE TABLE tempdash"+rndStr+@" (
				PatNum bigint NOT NULL PRIMARY KEY,
				dateFirstProc datetime NOT NULL
				) DEFAULT CHARSET=utf8";
			Db.NonQ(command);
#if DEBUG
			stopWatch.Stop();
			_elapsedTimeNewPatients+="CREATE TABLE: "+stopWatch.Elapsed.ToString()+"\r\n";
			stopWatch.Restart();
#endif
			//table full of individual patients and their dateFirstProcs.
			command=@"INSERT INTO tempdash"+rndStr+@" 
				SELECT PatNum, MIN(ProcDate) dateFirstProc 
				FROM procedurelog USE INDEX(indexPatNum)
				WHERE ProcStatus=2 GROUP BY PatNum
				HAVING dateFirstProc >= "+POut.Date(dateFrom)+" "
				+"AND dateFirstProc <= "+POut.Date(dateTo);
			Db.NonQ(command);
#if DEBUG
			stopWatch.Stop();
			_elapsedTimeNewPatients+="INSERT INTO: "+stopWatch.Elapsed.ToString()+"\r\n";
			stopWatch.Restart();
#endif
			command="SELECT dateFirstProc,COUNT(*) "
				+"FROM tempdash"+rndStr+@" "
				+"GROUP BY MONTH(dateFirstProc)";
			DataTable tableCounts=Db.GetTable(command);
#if DEBUG
			stopWatch.Stop();
			stopWatchTotal.Stop();
			_elapsedTimeNewPatients+="SELECT dateFirstProc,COUNT(*): "+stopWatch.Elapsed.ToString()+"\r\n";
			_elapsedTimeNewPatients+="Total: "+stopWatchTotal.Elapsed.ToString();
			if(_showElapsedTimesForDebug) {
				System.Windows.Forms.MessageBox.Show(_elapsedTimeNewPatients);
			}
#endif
			List<int> listInt=new List<int>();
			for(int i=0;i<12;i++) {
				int ptcount=0;
				DateTime datePeriod=dateFrom.AddMonths(i);//only the month and year are important
				for(int j=0;j<tableCounts.Rows.Count;j++) {
					if(datePeriod.Year==PIn.Date(tableCounts.Rows[j][0].ToString()).Year
						&& datePeriod.Month==PIn.Date(tableCounts.Rows[j][0].ToString()).Month)
					{
						ptcount+=PIn.Int(tableCounts.Rows[j][1].ToString());
					}
				}
				listInt.Add(ptcount);
			}
			List<List<int>> retVal=new List<List<int>>();
			retVal.Add(listInt);
			return retVal;
		}
        private IEnumerable <SearchItem> Evaluate(SearchExpressionContext c, SearchExpressionExecutionFlags flags)
        {
            var args = new List <SearchExpression>();

            foreach (var p in parameters)
            {
                var evalHints = p.evaluator.hints;
                if (evalHints.HasFlag(SearchExpressionEvaluationHints.AlwaysExpand) ||
                    (p.types.HasFlag(SearchExpressionType.Expandable) && evalHints.HasFlag(SearchExpressionEvaluationHints.ExpandSupported)))
                {
                    foreach (var exprItem in p.Execute(c, SearchExpressionExecutionFlags.Expand))
                    {
                        if (exprItem != null)
                        {
                            if (exprItem.data is SearchExpression expr)
                            {
                                args.Add(expr);
                            }
                            else
                            {
                                c.ThrowError($"cannot expand {p}");
                            }
                        }
                        else
                        {
                            yield return(null);
                        }
                    }
                }
                else if (p.types.HasFlag(SearchExpressionType.Expandable))
                {
                    foreach (var exprItem in p.Execute(c))
                    {
                        if (exprItem == null)
                        {
                            yield return(null);

                            continue;
                        }

                        if (exprItem.value != null)
                        {
                            if (Utils.TryGetNumber(exprItem.value, out var d))
                            {
                                args.Add(new SearchExpression(SearchExpressionType.Number, d.ToString().GetStringView(), Parsers.ConstantEvaluator));
                            }
                            else if (exprItem.value is string s)
                            {
                                args.Add(new SearchExpression(SearchExpressionType.Text, s.GetStringView(), Parsers.ConstantEvaluator));
                            }
                            else
                            {
                                c.ThrowError("Cannot expand parameters");
                            }
                        }
                        else
                        {
                            c.ThrowError("Cannot expand null value");
                        }
                    }
                }
                else
                {
                    args.Add(p);
                }
            }

            using (c.runtime.Push(this, args, flags))
            {
                var skipNull       = c.HasFlag(SearchExpressionExecutionFlags.ThreadedEvaluation) && !c.HasFlag(SearchExpressionExecutionFlags.PassNull);
                var executeContext = c.runtime.current;
                var timeoutWatch   = new System.Diagnostics.Stopwatch();
                timeoutWatch.Start();
                foreach (var r in evaluator.execute(executeContext))
                {
                    if (r != null)
                    {
                        timeoutWatch.Restart();
                        yield return(r);
                    }
                    else if (!skipNull)
                    {
                        if (timeoutWatch.Elapsed.TotalSeconds > 3.0d)
                        {
                            c.ThrowError("Timeout");
                        }
                        yield return(null);
                    }
                }
            }
        }