Recent Entries 10
- pattern minor 112d agosmall ticker class to execute a function at a regular invervalI have written the following ticker class. You can find a description and example usage in its comments. However, it kind of feels like I am using too many thread synchronization tools (`std::atomic`, `std::mutex` and `std::condition_variable`). Is there a way to simplify this? ``` #include #include #include #include #include #include // Executes a function f in a fixed interval (given in microseconds). // Call ticker::start() to run. // The ticker stops when ticker::stop() is called // or the instance runs out of scope. // // Example usage: // // void say_hi() // { // std::cout function; void start() { if ( running_flag_ ) { return; } running_flag_ = true; thread_ = std::thread( [this]() { thread_function(); } ); } ticker( const function& f, std::int64_t interval_us ) : f_( f ), interval_us_( interval_us ), running_flag_( false ), thread_(), stop_mutex_(), stop_cv_() {} void stop() { if ( !running_flag_ ) { return; } running_flag_ = false; { std::lock_guard lock( stop_mutex_ ); stop_cv_.notify_all(); } if ( thread_.joinable() ) { thread_.join(); thread_ = std::thread(); } } ~ticker() { stop(); } private: void thread_function() { auto last_time = std::chrono::high_resolution_clock::now(); while ( running_flag_ ) { auto current_time = std::chrono::high_resolution_clock::now(); const auto wake_up_time = last_time + std::chrono::microseconds{ interval_us_ }; while ( current_time lock( stop_mutex_ ); stop_cv_.wait_for( lock, sleep_time ); current_time = std::chrono::high_resolution_clock::now(); if ( !running_flag_ ) {
- pattern minor 112d agoCountdown timer in every table cellI am making countdown app with multiple records, so I am using UITableView to show that records and countdown dates. What I do is just take one timer and reload cells on every second. Is this a best approach to reload visible cells on every second or is there another better approach there? ``` updateCellContentsTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.updateCells), userInfo: nil, repeats: true) // MARK: Custom Functions func updateCells() { let indexPathsArray = tableView.indexPathsForVisibleRows for indexPath in indexPathsArray! { let cell = tableView.cellForRow(at: indexPath) as! CountdownTableViewCell cell.timeLeftLabel.text = progress + "hours:minutes:seconds" } } ```
- pattern minor 112d agoA simple clock in FORTHI try to program a stopwatch/countdown clock in FORTH with Gforth (and using Gforth-specific words). I'm a complete beginner and the following code is the basic stuff (going to add an alarm function / countdown option and more). For now the stopwatch counts from 00:00:00 (hh:mm:ss) up to 24:00:00 and - pressing space pauses the clock, pressing it again resumes the clock - pressing j/k sets the clock back/ahead one minute - pressing J/K sets the clock back/ahead one hour - pressing q quits the program Does my code follow best practices? Is it bad style for words like `move-clock-seconds-back` to return flags because they will be used in a `begin ... until` statement? ``` 1000000 constant million : sextal ( -- ) 6 base ! ; : hhmmss. ( ud -- ) drop million / 0 TYPE ; : pause-clock ( ud -- ud f ) utime begin 50 ms key? if key bl = ( pause is released ) else false ( clock keeps pausing ) then until utime d- d- false ; : move-clock-seconds-ahead ( u ud -- ud f ) million * 0 d- false ; : move-clock-seconds-back ( u ud -- ud f ) million * 0 d+ utime dmin false ; : get-elapsed-time ( ud -- ud ) 2dup utime 2swap d- ; : 24-hours-elapsed? ( ud -- f ) get-elapsed-time ( elapsed time fits in single integer ) drop 24 60 * 60 * million * u> ; : run-clock ( -- ) page ( clears the terminal ) utime ( returns a ud timestamp in microseconds ) begin 50 ms ( sleep for 50 ms ) get-elapsed-time 5 0 at-xy ( coordinates where to print output ) hhmmss. key? if key case bl of pause-clock endof [char] j of 60 move-clock-seconds-back endof [char] k of 60 move-clock-seconds-ahead endof [char] J of 60 60 * move-clock-seconds-back endof [char] K of 60 60 * move-clock-seconds-ahead endof [char] q of true endof false swap ( the char is now on top of the
- pattern minor 112d agoAngular 2 clock with RxJS ObservableI'm fairly new to Angular 2 and I started off with creating a clock for my app. I tried to stick to the official documentation tutorial. Folder structure: The CSS file is still empty and the HTML is not very spectacular: ``` {{time | date:'HH:mm' }} ``` The clock component itself looks like this: ``` import {Component} from "@angular/core"; import {ClockService} from "./clock.service"; @Component({ selector: 'clock', templateUrl: './clock.component.html', styleUrls: ['./clock.component.css'] }) export class Clock { time: Date; constructor(private clockService: ClockService) { } ngOnInit() { this.clockService.getClock().subscribe(time => this.time = time); } } ``` The most important part, however, is the service, which looks like this: ``` import {Injectable} from "@angular/core"; import {Observable} from "rxjs"; @Injectable() export class ClockService { private clock: Observable; constructor() { this.clock = Observable.interval(1000).map(tick => new Date()).share(); } getClock(): Observable { return this.clock; } } ``` Basically, I need a general review since this is my very first approach. However, what I'm really curious about is if I get the usage of the Observable right. Is it correct to store it as a private field like shown above? Am I doing the `.share()` correctly?
- pattern minor 112d agoJavaScript clockI am trying to build a clock. You can see the working code here. However, I feel like I can do much better in the JavaScript code. ``` var getDate = function getDate() { var date = new Date(); var month = date.getMonth(); var day = date.getDate(); var hour = date.getHours(); var minutes = date.getMinutes(); var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; var ampm = 'pm'; // by default, it is pm var showDate; var showTime; if (hour 12) { hour -= 12; } showDate = monthNames[month] + ' ' + day; showTime = hour + ':' + minutes + ampm; document.getElementById('js-date').innerHTML = showDate; document.getElementById('js-time').innerHTML = showTime; requestAnimationFrame(getDate); }; getDate(); ```
- pattern minor 112d ago“How are you spending your time on the computer?” Part 2In my previous question I got some pretty good suggestions which really improved the overall performance of the controls, but I decided to extend the application and add some more features : - You can enable/disable auto-updating. - You can select which processes you want to view currently available options are : - Default - shows all the processes. - Active - shows only active processes. - Foreground - show only foreground processes. - Upon minimizing the application will move to the tray bar (there is small bug there sometimes 2 icons will show, but the second will fade after few seconds.) - You can inspect processes, which shows 3 more additional properties : - Instances running - the amount of active instances of the process. - Process Path - the directory where the .exe is located. - Background Process - Indicates whether a process is background process or not (true/false). - Owner - the user that runs the process DOMAIN / user. - You can also terminate and refresh processes. - Searching options is available with auto suggest from the current shown list of processes. Note The application now requires administrator privileges as most processes are hidden if not run as administrator + it prevents most of the exceptions, tho there are few processes that will still deny access. That pretty much sums up all the new things and this is how the program looks like now : Let's start inspecting the code than. BufferedListView As suggested in the previous question's answer I'm not using a simple class that "extendeds" the `ListView` control by setting the `DoubleBuffered` property to true by default, to reduce flickering. ``` public sealed class BufferedListView : ListView { public BufferedListView() { DoubleBuffered = true; } protected override bool DoubleBuffered { get; set; } } ``` Extensions.cs The new extension methods : - `RemoveAll(this IDictionary)` with 2 overloads, it works the same way as a `List.Rem
- pattern critical 112d ago"How are you spending your time on the computer?"I've made a Windows Forms application to track all of the processes running on my machine and it also saves the time an application is "active", an active application is the one that is on focus currently e.g your browser right now + it also reminds me every now and then (every hour) how much time I've spent on the internet. Aside from that it shows all of your running processes with some basic information about them, there are also several different sorting options along with ascending/descending ordering. Here's how it looks: Update This line - winforms is not powerful seems to have caused quite some controversy and apparently I'm wrong. As pointed by CodyGray and proven by t3chb0t, windows forms can be really fast if the program is optimized properly and the controls are used the way they are meant to be used. It works on a single thread and winforms is not powerful so it takes 1-2 seconds to refresh the content which happens every 10 seconds, unless requested manually. Here is the main code: ``` public partial class Form1 : Form { private class ProcessInfo { public Process Process { get; } public TimeSpan TimeActive { get; set; } public ProcessInfo(Process process, TimeSpan timeActive) { Process = process; TimeActive = timeActive; } } private readonly Timer updateTimer = new Timer(); private readonly Timer focusTimeTimer = new Timer(); private Dictionary processesInfo = new Dictionary(); private List> orderedProcessesInfo; private Dictionary sortingActions; private Dictionary orderingActions; private bool isAscendingOrder = false; private static Dictionary processesActiveTime = new Dictionary(); private static readonly Func GetMemoryUsageInMB = p => (int) (p.WorkingSet64 / (1024 * 1024)); private static readonly Func GetRuntimeOfProcess = p => DateTime.Now - p.StartTime; private static readonly Func GetActiveTimeOfProcess = p =
- pattern minor 112d agoCalling a function every 40 second inside a while loopThis code invokes a function for every 40 seconds inside a loop. I am doubtful about this condition: ``` if ((time_left interval)) ``` Is only checking `(time_left interval`. Is this check required? ``` int print_timed_op() { time_t time_now; time_t time_left; time_t time_next_interval; int interval = 40, hit_count =10; //40 second interval, 10 times time_next_interval = time(0) + interval; //tight loop while (1) { sleep(1); time_now = time(0); time_left = time_next_interval - time_now; /* here time_left > interval check required ? */ if ((time_left interval)) { call_my_fuc(); time_next_interval = time(0) + interval; time_left = interval; hit_count--; } if(hit_count< 0) break; } return 0; } ``` Note: I don't want to use a Linux timer system call or any other method to invoke the function periodically.
- pattern minor 112d agoCountdown AppIndicatorI've decided to translate an old Unity AppIndicator I had written in C to Ruby, so I can practice coding with it (got a little bored with the completely beginner lessons I've been following, which I'll finish!). The C indicator itself was a bit raw, I kind of wrote it in an afternoon, so I think it reflected on the Ruby indicator as well. It's still a work in progress. For now the timer can be configured only through a configuration file (which is described in the README and in the example file). Once the file is set, the user can start the indicator, click on the icon, "Start timer..." and "Get from config file". The reason this window pops up is because I was thinking about making a more friendly UI where the user could input the same parameters. There are 4 parameters you can configure: Enable Notify and Notify Delay (issues `notify-send` calls to remind the user of how much time is left), Initial timer and Persistent timer (the former just sets at how many seconds will the timer start at and the latter will make the timer persistent once you close and open the app again). The persistent timer works by writing a file which has the epoch time when the timer is supposed to end, so it can resume. The icon color of the indicator changes in some ranges (over 10 minutes it is blue, over 5 minutes it's orange, below 5 minutes it's red and when it reaches 0 it's black). Once it reaches 0, nothing happens (I plan to implement some notification, maybe an alarm). GitHub repo ``` #!/usr/bin/ruby require 'ruby-libappindicator' # DEBUG FUNCTION DEBUG=true def debug(message) if DEBUG==true puts "DEBUG: "+message end end # SOME CONSTANTS BLUE_ICON_RANGE = 600 #10 minutes ORANGE_ICON_RANGE = 300 #5 minutes # So here is how it goes: Timer > 10 minutes icon is blue. 10 minutes > Timer > 5 minutes icon is orange. Timer 0) param_value_list = line.split("=") debug("Parameter: #{param_value_list[0]} - Val
- pattern minor 112d agoTrying MVVM on timer appCheck me: `Model` should do everything. That's where all functionalities and features are accommodated. It has some properties, that I can access and use. Theoretically, it could work as a standalone app (used via command prompt). `View` does nothing but looks (like a monitor: you always look at it, whereas the real work does your computer). `ViewModel` supply and modify `Model`'s output to the `View` and `View`'s user input to the `Model`. Am I right? I have written simple timer application, where I want to follow MVVM. There are `ToggleButton` whitch start or stop countdown and `Slider` to set time to count. `ToggleButton`'s content shows remaining time. `View` ``` ``` In `View`'s code behind I instantine `ViewModel` and set `DataContext` on it. `ViewModel` ``` class ViewModel: INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; Model MyModel; public ICommand Command { get; } public string TimeString { get { int timeInMin = MyModel.Time / 60; return timeInMin != 0 ? timeInMin + " min" : MyModel.Time + "s"; } } public int TimeInMs { get { return MyModel.Time; } set { MyModel.Time = value; } } public ViewModel() { MyModel = new Model(3600); Command = new ToggleCommand(MyModel.Start, MyModel.End); MyModel.PropertyChanged += (a,b)=> { PropertyChanged(this, new PropertyChangedEventArgs("")); }; } } ``` `Model` ``` class Model : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; Timer myTimer; int _time; public int Time { get { return _time; } set { _time = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Time")); } } public Model(int time) {