[{"content":"Intro 🚪 Learning a new language is always a fun filled and mind opening experience, and I can\u0026rsquo;t describe how excited I am right now🤓. This year 2023, I\u0026rsquo;ve chosen Rust 🦀 as the language to learn as part of the yearly Language Challenge goals.\nAlthough you may already have some knowledge of the Rust programming language, in this section, I will still introduce Rust and provide some information about it.\nRust is a systems programming language that was developed by Mozilla.\nThe syntax of the language looks like that of C++, because of the namespaces, semicolons to terminate statements, and pointers.\nIt also looks a bit like Swift especially with the way variable types, function return types and generics are defined. Both of the languages also have implicit function return, the keyword self, safe typing and optional types, and so on.\nWhy Rust? 🦀 Popularity and Love Rust has been gaining momentum in the dev space for the past few years. According to the Jetbrain\u0026rsquo;s 2022 Developer Survey and the Stackoverflow survey, Rust is the most promising programming language and for the past 2 years now, it has been one of the most loved programming languages by a very large margin.\nLinux Linus Torvalds, the creator of Linux, has been a huge fan of Rust. He has also been a huge advocate for Rust and has been pushing for it to be used in Linux kernel development. As a backend developer who uses Linux, I think it\u0026rsquo;s smart to learn Rust at this point in time.\nSpeed I love reading Medium posts daily and it\u0026rsquo;s so rare not to see an article benchmarking Rust against other languages. Rust is known to be a fast language, and it\u0026rsquo;s time I witnessed this first hand.\nCompiler Rust has a very powerful compiler that helps you catch errors before they even happen, I have read all of these from daily feeds, a couple of times last year and I couldn\u0026rsquo;t wait to see this in action.\nMemory Management The main reason for learning Rust is to actually learn about memory management in Rust. It\u0026rsquo;s method of memory management has been used in several notes and articles that I\u0026rsquo;ve read in people\u0026rsquo;s work and if anything, I want to be able to understand what they are talking about.\nAside all these points, at first glance, I didn\u0026rsquo;t like the Rust syntax. Frankly, I think I will still continue using Golang for most of my projects, but there is always something to be gained from learning a new language.\nRelationship with Go ❤️ (LOTY2022) Go and Rust actually have a lot in common, at least from what I\u0026rsquo;ve experienced.\nTheir compilers will scream at you when you create a variable you don\u0026rsquo;t use. They are both compiled languages, known for speed and strong focus on performance. They are both modern languages with modern syntax that is easy to read and write. The usecases for Rust and Go also intersects as they are both used for low-level systems programming. Differences Rust beats Go in terms of Generics in my opinion because \u0026lt;T\u0026gt; definitely looks better than [T]. Rust compiler is stricter than Go\u0026rsquo;s compiler Rust is more complex, and might slow developers down for very large projects because of the strictness and memory issues that might arise. Go has more usecases than Rust, and is more popular than Rust. Plan, Execution and Review Without spending too much time talking about the languages themselves, let\u0026rsquo;s talk about my learning plan and progress so far.\nStudy Plan 📚 The Rust language has a very detailed documentation on their official website. That is my starting point. I will be reading the documentation and following along with the examples. I will also be reading the Rust book. Since I do not plan to use Rust for any of my projects, I might solve some algos with Rust on Exercism at least.\nDay 1 in summary 📅 Today is the first day of the Language Challenge and I have already spent a lot of time reading the Rust documentation. I installed the Rust toolchain with brew so that I can update it easily, should a new version be released. I also installed the VSCode extension for Rust. I have also read the Rust book and I am currently on the fourth chapter where the reference and borrowing concepts are introduced.\nI think it\u0026rsquo;s a memory management model that makes sense, and I am looking forward to learning more about it.\nReview 📊 My take on Rust so far is that it requires focus and attention to detail compared to other programming language and I think this is why folks say it\u0026rsquo;s a bit complex. I won\u0026rsquo;t be blogging my progress daily because I don\u0026rsquo;t want to bore you with the details, but I will be posting a summary of my progress at the end of the month.\nThanks for reading, and I hope you enjoyed this post. If you have any questions, feel free to reach out to me on Twitter or LinkedIn. Also, don\u0026rsquo;t forget to like the post if you enjoyed it.\nPeace ✌️\n","permalink":"https://blog.lordvidex.me.uk/notes/rust-day-one/","summary":"It\u0026rsquo;s not just about \u003ccode\u003eprintln!(\u0026quot;Hello, world!\u0026quot;).. 🤌\u003c/code\u003e","title":"Rust: Day One Reflections"},{"content":"I wrote this article because I took a sit back and I couldn\u0026rsquo;t even remember anything from PHP aside the fact that I used a lot of dollar signs $$$. In this post, I will mostly be documenting in chronological order, the tools I learnt since I started programming. (At least the ones I can remember)\nFinding myself LOGO LOGO programming was taught in early secondary school years as part of school curriculum. I remember drawing very basic shapes with LOGO. In fact, it felt more like maths than programming because we actually had to calculate angles and shape functions before actually drawing them. I was pretty good at maths and learning LOGO was cool. I\u0026rsquo;d say, it created a spark in me to learn more about programming.\nHTML / CSS It was also compulsory to learn HTML in Computer Science in Junior School. The curriculum only actually covered basics, but my friends and I built some websites with HTML/CSS then. I remember building a download site that hosted all the images on my computer. The site was really bad, because I wrote all the pages by hand, copied and pasted blocks repeatedly. W3Schools was a very good guide to learn HTML and CSS.\nSchool happened, so I had a brief pause\nPHP There was a Wordpress workshop two years before I graduated from secondary school that actually ended abruptly, if I remember correctly. I dug the source code for most of the things and started learning PHP myself from a very scanty PHP manual. It was actually the only resource I had then, but at the time, it was enough.\nPHP was the first programming language with which I practiced my knowledge of control flow and flowcharts in programming.\nWhy did I stop PHP? Python was starting to gain hype and I was advised to learn it by my Physics teacher.\nPython Unlike PHP, I was able to find a lot of resources on python. Python was actually very easy to learn for me. I used certain materials that I still recommend to people that have reached me to learn programming as a guide to learning python.\nAutomate the Boring Stuff with Python by Al Sweigart link Beyond the Basics with Python by Al Sweigart link some material I can no longer find anywhere on the internet // TODO: Solved a lot of hacker rank problems with python Making games with Python and Pygame link\nI loved games a lot, so I was curious and very interested to learn the act of making one with my newly developed skill. Did I get heart broken? It took me sometimes to actually realise how unfit and very difficult it would be to make a game with pygame, even though it was fun to learn. It was at this point I chose to study Software Engineering instead of Medicine. I mean, it made sense because I was interested and curious mostly about programming and tech stuff.\nThe Journey Git / Github and Version Control I started using git and github very early and that is why I have a lot of repositories on github. I really cannot recall how I started using git and github but I started pretty early. This is good because, over time, I could share my progress with friends and keep track of changes on the projects I worked on. I also tried other repositories like Gitlab and Bitbucket, but I still prefer Github.\nJava / Android Development In my first year at the University of Lagos, I met a lot of friends and seniors who had interest in programming like I did. I joined Engineering Career Expo and learned Android development with Java. I still regard Java as my native language till date. I learnt a lot while learning Java and I think most things in Java made a lot of sense compared to the languages I have used previously. This dates back to 2018.\nJavaScript, Node and ExpressJS I learnt backend web development with ExpressJS. This was the first ever server that I built, and I created and exposed endpoints that were consumed by the apps I was building at the time. I really never learnt Javascript actively, it just kind of clicked. I had to take some tutorials to learn ExpressJS on the other hand because the concepts of server and the whole backend was strange at the time.\nFlutter and Dart A friend recommended Flutter to me and I agreed to look into Flutter because it was built by Google and also because it promised to build cross-platform mobile applications. This meant that learning Flutter would actually make me write both Android and iOS apps, so I gave it a shot and it was a very long shot 😂 (because I still use it to date). I immediately started using Flutter because:\nbuilding UI is wayyy easier than building natively with Java I was using a 4gb ram lenovo laptop at the time and using Android Studio was a pain. (At least, I got to use vscode with Flutter). Java II The funny thing was that I never really learned Java the first time. Yes! I built some applications with Java, but I was only focused on the Android Framework and never used Java for things like data structures and algorithms for example. I didn\u0026rsquo;t even understand how many of the libraries I used, worked in-depth.\nIn Kazan Federal University, Java was officially taught in-depth this time and I learnt super fast, because of my previous experience building Android applications. This time around, I learnt in-depth concepts ranging from data structures, algorithms, Object Oriented Programming, Generics, Concurrency and Threading, Design patterns, Architectures, and so on.\nJava set the foundation to professional programming for me. I learnt a lot of things that I still use till date and I am happy I started with Java. Thing is, my choice of languages since Java has been influenced by the fact that I learnt Java first because I am more inclined to learn languages that are similar to Java.\nAt this point, learning new languages has been breeze for me. I can learn a new language in less than a week or two, and I can build a simple application with it. I have learnt a lot of languages since then, but I will only be highlighting the ones I have used extensively.\nKotlin I had a very short experience with Kotlin. I guess every Java developer must have tried some Kotlin at some time. I used Kotlin only for some Codeforces contest.\nPostgreSQL NoSQL database was my bread and beans then. I used MongoDB and Firebase a lot. I actually knew some SQL before it was taught in school, but I never knew things like normalization and other relational db concepts. PostgreSQL was reintroduced as a course in my second year and I went really deep into SQL concepts. Most importantly, I learnt how to use PostgreSQL with Java and I also learnt how to use it with Node.js. I used PostgreSQL for a lot of projects and I still use it to date.\niOS Development (Swift / Objective-C) I picked iOS development as my technical area of specialty from my second year at the University to augment my Flutter skills with native development. I learnt extensively, iOS development with Swift and I can boast of middle level experience with Swift and iOS development.\nI also learnt Objective-C on my own, because I was curious to see how much of an improvement Swift was, when compared with Objective-C.\nI have built a lot of applications with Swift and some of them are available on my repo on Github.\nI also had my second year summer internship with a company as an iOS developer.\nBefore I move to other languages, I think Swift is one of the most properly designed programming languages I have used. Furthermore, I\u0026rsquo;ll explain how iOS development was easy but complex at the same time:\nAs a beginner, one is abstracted away from serious swift code and can use the Layout Builder to build a decent app in Xcode. When moving up the ladder and getting better, you have to do everything without the layout builder altogether and also learn about ARC memory management model.\nAltogether, I really enjoyed iOS development, Xcode, and the Swift programming style guide. I think Swift is a very good language to learn for beginners and I recommend it to anyone that wants to learn programming practically.\nTypeScript Finally, developers were starting to see what I saw wrong in Javascript. I jumped on the train when Typescript came on board and some of the projects I worked on, at Paytrybe were built with Typescript.\nTypescript is a very nice language and I always advice backend developers to check out NestJS. Nest is a progressive Node.js framework that uses Typescript and makes backend development a breeze. It utilises the power of decorators, generics, interfaces, dependency injection and many other OOP stuff and best practices, that JS was missing.\nIf I had to build a LTS server in the shortest possible time, I\u0026rsquo;d use NestJS.\nGo I started learning Go programming language in the summer of 2022 and my growth in the language has been extremely rapid. First, I learnt the syntax in less than two days, but I guess everyone has similar experiences learning Go because Go is a very simplistic and yet very powerful language. It\u0026rsquo;s easy to get addicted to Go because it combines the best of many worlds. Currently, this is my go-to programming languge (Sorry Java 🫠). I explained the reasons why I started learning Go here in my other article.\nLearning Go means that I had to learn about containerization, microservices, tooling and profiling.. Go is very fascinating, and there is so much to learn writing Go. I have built a lot of end user applications as well as open source libraries in Go. I have also contributed to several open source Go libraries. You can check them out in my Github repo.\nDocker Docker! Docker!! Docker!!! These days, it\u0026rsquo;s impossible to not see a post about Docker. I used Docker before Go, but I never saw the need for containerization until Go. I use Docker greatly for spinning up containers for integration testing, maintaining singular application environment / workflow and application deployment. In production, I also have some applications running on Docker swarm.\nLinux / Operating Systems I took operating systems as a course in my third year in the university and we covered a lot of Unix specific concepts which includes Networking, File systems, security, containerization, etc. All of these concepts came in handy because I deployed most of my server instances on linux machines.\nOthers In no specific order, I\u0026rsquo;ll like to name other concepts, popular architectural patterns that I appreciated, used and I think are notable mentions in my journey:\nMVC, MVVM architectural patterns in iOS / Android development. Clean Architecture, DDD, BLOC, Redux, TDD, animations in Flutter. SOLID principles, SPRING, Enterprise development in Java. Package Oriented Programming (POP), microservices, error handling, profiling and tooling, optimization, concurrency techniques, Docker, (omg testingggg) and other low level system stuffs in Go. Tips and Tricks to learning new languages I cannot guarantee that my method will work for everyone, but I found out that since I already know most programming principles and techniques, all that is required to learn a new language is to learn the syntax and the language specifics. Hence I do the following:\nCheck out the language on learnxinyminutes.com Read the official documentation of the language.\nSome languages actually have very good documentation for example: Swift releases a new version of The Swift Programming language ebook in the Books app on MacOS. link Go has a very good documentation on go.dev as well as playgrounds. Typescript as well has a very good documentation. I solve some algorithms and data structure problems with the language to familiarise myself more with the language syntax and libraries. Personally, I use Exercism to learn a new language. Finally and most importantly, reaching out to the community is the best way to learn a language, because you can ask questions and learn from the rich experience of developers that have been using the language for a long time. In fact, they can recommend the best materials to learn the language. ","permalink":"https://blog.lordvidex.me.uk/posts/my-programming-toolbox/","summary":"\u003cp\u003eI wrote this article because I took a sit back and I couldn\u0026rsquo;t even remember anything from PHP aside the fact that I used a lot of dollar signs $$$. In this post, I will mostly be documenting in chronological order, the tools I learnt since I started programming. \u003cem\u003e(At least the ones I can remember)\u003c/em\u003e\u003c/p\u003e\n\u003ch1 id=\"finding-myself\"\u003eFinding myself\u003c/h1\u003e\n\u003ch2 id=\"logo\"\u003eLOGO\u003c/h2\u003e\n\u003cp\u003e\u003ca href=\"https://en.wikipedia.org/wiki/Logo_(programming_language)\"\u003eLOGO\u003c/a\u003e programming was taught in early secondary school years as part of school curriculum. I remember drawing very basic shapes with LOGO. In fact, it felt more like maths than programming because we actually had to calculate angles and shape functions before actually drawing them. I was pretty good at maths and learning LOGO was cool. I\u0026rsquo;d say, it created a spark in me to learn more about programming.\u003c/p\u003e","title":"My Programming Toolbox"},{"content":"Intro 🚪 Go is an open source programming language supported by Google. It has gained it\u0026rsquo;s grounds in the programming world due to it\u0026rsquo;s simplicity and speed. It is a statically typed language with a syntax similar to C. It is a great language for building command line interfaces (CLI), Cloud/DevOp tools, Networking and Backend server applications. In this article, I will be giving an overview of how I built the gomeasure tool with Go.\nThe Journey 🚲 I\u0026rsquo;ve always wanted to build a CLI tool but ideas have not been forthcoming until one fateful day at work meeting. There was a need to calculate the weight (files count) of directories in a project. Hence, I wrote a simple Go script which evolved into the gomeasure CLI tool.\nWhy I built with Go? 🤔 I chose Go because of the following reasons:\nI was learning go at the time I\u0026rsquo;ve developed the habit of learning at least one new programming language every year. I started learning Go in 2022 and I wanted to build something with it.\nGo has a rich standard library and inbuilt tools for building fast elegant CLIs. The flag, os and fmt packages are enough for building a simple CLI tool. This provides flag parsing out of the box compared to other languages like Java where I would have parsed arguments manually. Anyways, I extended these packages with the github.com/spf13/cobra package which made building even easier.\nCollaboration and community. I learnt and built the tool with a friend, Ahmed Helali. We both have a passion for open source and we wanted to build something together.\nSmall binaries Go binaries are very small in size. The typical size of a Go binary is 2-5 MB. This is a great advantage because the binary has a small memory footprint (we don\u0026rsquo;t want a memory hog), there is no dependency overhead and binaries can be easily shared.\nCross-platform support (Windows, Linux, Mac) Go is a compiled language and it compiles to a single binary file which can be run on any platform. This is unlike interpreted languages like Python and JavaScript which require a runtime environment to run. This makes Go a good choice for building CLIs. I built the tool for various platforms in a CI/CD environment and it worked on all platforms without issues.\nStructure of a CLI program 🏗 As developers, we use CLI programs every day ranging from git, docker, kubectl, etc. A typical CLI program has the following structure:\n\u0026lt;program\u0026gt; [command] [arguments] [flags] e.g.\ngomeasure line /path/to/file -v\nI employed the following model for the gomeasure CLI tool:\nIn the docs, \u0026lt;\u0026gt; means a required argument and [] means an optional argument. [command] is a sub-command of the program. e.g. line in gomeasure line is a sub-command of gomeasure. sub-commands have required arguments and optional flags. e.g. gomeasure line /path/to/file -v has a required argument /path/to/file and an optional flag -v.\nHere, it is obvious that the arguments are necessary for the subcommand to carry out the expected action while the flags tells it how to. gomeasure has a help sub-command which displays the help message for the program. e.g. gomeasure help displays the help message for the program. The help message is also accessible from the --help flag. e.g. gomeasure line --help displays the help message for the line sub-command. Flags or options that have a single dash - are short flags. e.g. -v is a short flag and is equivalent to --verbose. Short flags can be combined. e.g. -v -s is equivalent to -vs. Flags or options that have a double dash -- are long flags. e.g. --verbose is a long flag. Introduction to Cobra 🐍 Cobra is a package built by Steve Francia for building powerful modern CLI applications in Go. It provides a simple interface to create powerful modern CLI interfaces and it is used in production grade softwares like Kubernetes, Hugo and Github CLI, to name a few. Cobra provides a generator to create a CLI skeleton which can be customized to suit your needs. I used the generator to create the gomeasure CLI tool.\nCobra out of the box use the structure described above.\nCreating gomeasure with Cobra and Go 🛠 Project structure The project structure is as follows:\n. ├── LICENSE ├── README.md ├── bin │ └── gomeasure ├── .goreleaser.yaml ├── cmd │ ├── file.go │ ├── line.go │ └── root.go ├── dist/ ├── go.mod ├── go.sum ├── main.go ├── pkg │ ├── runner.go │ └── runner_test.go LICENSE is the license file. README.md is the readme file. bin is the directory where the compiled binary is stored. cmd is the directory where the CLI commands are stored. dist is the directory where the compiled binaries for various platforms are stored. go.mod is the go module file. go.sum is the go module checksum file. main.go is the entry point of the program. pkg is the directory that contains the business logic of the software. .goreleaser.yaml is the goreleaser configuration file. Cobra and the cmd/ directory The scope of cobra is limited to the cmd/ directory because this is where each sub-command is defined and flags are parsed.\nThe most important class in the cobra package is the cobra.Command class. It is used to define a sub-command and its flags. An example of how we used it to define the file sub-command is shown below: var fileCmd = \u0026amp;cobra.Command{ Use: \u0026#34;file \u0026lt;directory\u0026gt;\u0026#34;, Short: \u0026#34;processes the number of files in a directory\u0026#34;, Long: `gomeasure file processes and returns the number of files in a directory / project.`, Run: func(cmd *cobra.Command, args []string) { // ... }, } Cobra also helps to parse flags and it automatically resolves conflicts between flags. An example of how we used it to parse the --verbose flag is shown below: // cmd/root.go rootCmd.PersistentFlags().BoolVarP(\u0026amp;isVerbose, \u0026#34;verbose\u0026#34;, \u0026#34;v\u0026#34;, false, \u0026#34;--desc--\u0026#34;) You can check out the cobra documentation at https://github.com/spf13/cobra.\nThe runner.go file The runner.go file contains the business logic of the program. It contains the Runner struct which contains fields that helps to specify what the program has to do.\nThis file also contains the Result struct which is returned from the Run method of the Runner struct. The Result struct contains the result of the program execution.\nDeployment and CI/CD with Github Actions I used Github Actions to build and deploy the program. The workflow is as follows:\nThe workflow is triggered when a new release is created. The workflow builds the program for various platforms using goreleaser. The `.goreleaser.yaml file contains instructions on how and where to deploy releases. The workflow then creates a new release and uploads the compiled binaries to the github releases section and on brew (for macOS). Roadmap for gomeasure 🛣 More subcommands 🤖 I plan to improve the tool by adding more sub-commands and more flags to the existing sub-commands to make it more useful.\nUnit Testing omg 🥵 I plan to add unit tests to the *.go files. It is actually a highly recommended practice to write unit tests in the Go community.\nDocker image 🐳 I plan to create a docker image release for the tool so that it can be used in a docker container.\nConclusion I\u0026rsquo;ve made the project open source and I would love to see contributions from the community.\nDon\u0026rsquo;t forget to star🌟 the repository on Github if you found gomeasure useful.\nHelpful Links gomeasure on Github gomeasure on pkg.go.dev Go website Cobra Github Repository Interesting read on CLI The Go programming language and it\u0026rsquo;s usecases ","permalink":"https://blog.lordvidex.me.uk/posts/creating-go-cli/","summary":"\u003ch2 id=\"intro-\"\u003eIntro 🚪\u003c/h2\u003e\n\u003cp\u003eGo is an open source programming language supported by Google. It has gained it\u0026rsquo;s grounds in the programming world due to it\u0026rsquo;s simplicity and speed. It is a statically typed language with a syntax similar to C. It is a great language for building command line interfaces (CLI), Cloud/DevOp tools, Networking and Backend server applications. In this article, I will be giving an overview of how I built the \u003ccode\u003egomeasure\u003c/code\u003e tool with Go.\u003c/p\u003e","title":"Creating CLI in Go"},{"content":"Have you ever striven to get the Fanatic gold badge on stack overflow? OR Has your progress reset when you were on the 99th streak? OR Have you ever wanted to automate your browsers to open a website periodically?\nTHEN, this article might help you !!\nIntroduction The Fanatic badge is earned by visiting the stack overflow website consecutively for 100 days.\nProblem Visiting the stack overflow website routinely can prove difficult if you have no need to visit the website for just one day, or when you are on a code break / vacation.\nSolution I solved this issue by creating a cron job that opens my stack overflow profile while my system is on.\nI will provide two solutions for Mac OS Monterey (here) and Ubuntu 20.04 Linux OS (here) respectively because I have tested the scripts on these platforms.\nLet’s Code # Mac OS Create an alias for your browser in terminal (I use Google Chrome) and save this in ~/.zshrc terminal configuration file $ echo alias chrome=\u0026#34;open -a \u0026#39;Google Chrome\u0026#39;\u0026#34; \u0026gt;\u0026gt; ~/.zshrc Create a sh script that opens your stack overflow profile (or opens any website you want) and save as cronjob.sh. View gist on GitHub 2.5. Run zsh cronjob.sh and make sure it opens up your stack overflow page on Google Chrome.\nDefine and set the cron job a. The below command opens a list of cron jobs in vim where each line represents a cron job\n$ crontab -e b. Press i to enter insert mode and on a new line enter:\n0 01,11,23 * * * zsh /path/to/script/cronjob.sh ** Note: Change /path/to/script/cronjob.sh to the absolute path of the script file created in (step 2) .\nThe above command can be interpreted in the following way:\n0 - 0 minutes 01,11,23 - 1, 11 and 23 hours respectively # my active times * - all days of the month (1-31) * - all months (1-12) * - all days of the week (0-6) # this cron time config is followed by the command to be run c. Press Esc to exit from insert mode and press :wq to save and quit the vim environment. \\\nd. You should get a message like this:\ncrontab: installing new crontab e. You can check your cron jobs by entering the following command\n$ crontab -l # displays list of cron jobs # Ubuntu The default browser of Ubuntu 20.04 is Firefox BUT I will be using Google Chrome because of errors i encountered while running Firefox from cron, also, the default shell on Linux is bash. The commands to enter are basically similar with those entered above for Mac OS. But I’ll reiterate for clarity and reference purposes.\nTest google-chrome, cron and bash $ google-chrome https://stackoverflow.com # this should open your page BUT if it does not install chrome # with this guide: https://itsfoss.com/install-chrome-ubuntu/ $ crontab -l # this should list your cron jobs $ bash --version # prints out your bash version Create a bash script to open Google Chrome and save as cronjob.sh View gist on GitHub 2.5. Run bash cronjob.sh and make sure it opens up your stack overflow page on Google Chrome.\nDefine and set the cron job $ crontab -e # you might be prompted to select an editor, pick you favorite Enter on a new line the following command 0 01,11,23 * * * bash /path/to/cronjob.sh The above command can be interpreted in the following way: 0 - 0 minutes 01,11,23 - 1, 11 and 23 hours respectively # my active times * - all days of the month (1-31) * - all months (1-12) * - all days of the week (0-6) # this cron time config is followed by the command to be run You should get a message like this: crontab: installing new crontab You can check your cron jobs by entering the following command $ crontab -l # displays list of cron jobs Conclusion Cron jobs are really cool and powerful when properly used. Also, they are easy to setup and manage. You can run your .py, .swift, .java scripts (not just shell scripts) from cron.\nThere is a catch anyways.\ngotcha\nCron jobs would not wake your system from sleep mode. So you have to use a cron time configuration that best suits you i.e. when your system is going to be switched on. Read more on creating cron jobs at crontab.guru.\nUPDATE Today is the 4th of July and I’ve gotten the badge, use CRON job today!😌\nCheers🥂🎉\n","permalink":"https://blog.lordvidex.me.uk/posts/stack-overflow-fanatic-badge/","summary":"Automating your browser with “cron” and shell scripts ( Linux | MacOS )","title":"Getting the Fanatic badge on Stack Overflow the PRO way"},{"content":"C Speed?\nI started competitive programming in C++ because it is the most common language on competitive programming sites out there. Of course, due to the famous STL library and the speed you get out of a C++ program. Switching to Java for writing algorithms has been a totally nice experience, and I found some ways to increase the speed of your Java algorithm in contests and projects generally.\nWhy write in Java? You use Java everyday for day-to-day tasks like Android or server-side development or probably Java was your first love. :)) Me simping for a programming language, D:)\nMost Data Structures you’ll need are easier to implement and readily available in the java.util.* package or java.io.* as opposed to C++ for example, where you have to import all the libraries you will need from STL or alternatively #include \u0026lt;bits/stdc++.h\u0026gt; header file which contains all the major classes you will need. The downside is that this header file is not present in C compilers like Microsoft Visual Studio C++ or Xcode’s Clang compiler.\nMost of the Java algorithms you will write will be bug free because the syntax is human friendly and the IDE will most times save you from yourself. There is also the wonderful debugging experience you get from popular IDEs like IntelliJ.\nExtensive documentation, age, libraries, resources and the ability to peek at the source code.\nWHY NOT? Let’s get down to the speed tips:\n1. Improve your IO operations It is far easier to receive input from the terminal with Java\u0026rsquo;s Scanner class but it is relatively slower than using BufferedReader because :\nBufferedReader has larger buffer than Scanner: 8KB to 1KB\nScanner uses regular expressions internally to read and parse Strings to their types in functions nextDouble() , nextInt() ,etc.. which we use when reading numbers from file for example, and well, regExp is slow.\nBelow is a demo showing the time taken by Scanner and BufferedReader respectively to read in integers from a file containing 2,000,000 numbers.\nScanner Implementation speed::: 1.53 s user, 0.15s system, 1.289 total\nEquivalent BufferedReader implementation\nLet’s first define a static class named FastScanner , which contains a BufferedReader and a StringTokenizer\nView gist on GitHub now you can add methods to return common types like int , double , char[] etc and don’t forget to always close the BufferedReader.\nFull content of FastScanner class is present at the bottom of page\nYou can add methods to the FastScanner class to your requirement, in most contests, you’ll deal with integers, long, double, char[] ,strings.\n# speed test VOILA!!!! this is x4 faster now\nWhat about outputs?\nI use the PrintWriter class in place of the traditional **System.out.println(), **it is roughly twice faster, nothing much… but speed is speed :)\n** An important performance tip will be to group pieces of Strings together to form a single String (using StringBuilder()) before printing out from the output stream.\n2. Use primitive types where necessary in place of Objects Primitive values are stored in the stack, in the computer memory WHILE Objects are stored in the **heap. The most important thing to know about them in terms of speed is that, the stack **is a faster memory area than the **heap, **hence we have to consider this in our algorithms and use primitive types instead of object types when and where possible. The test here is actually going to be a short one:\nThis is like x40+ time difference in nanoTime just summing up numbers from 0 to 999. More complex tasks will cause greater variations in time\n3. Use Arrays in place of ArrayLists where necessary Arrays should be used in place of ArrayLists where necessary especially when the **size **of the array is known. Aside the speed of using Arrays over ArrayLists, it is actually more convenient to get a value in the array using arr[i][j] instead of arr.get(i).get(j) for Lists.\nEven though the ArrayList was also initialised with the **size, **Array will of course be faster because of point 2 above. NOTE that you should use ArrayList when you don’t know the number of items that will be stored, because Lists are mutable.\n4. Know when to use String “+” operator, StringBuilder and char[] Manipulating Strings is a very important part of algorithms and data structure. This is the simple rule I follow when working with Strings:\nWhen printing or storing already known String values, concatenate them using “+”. For example, in String myString = \u0026#34;I \u0026#34;+\u0026#34;am \u0026#34;+\u0026#34;a \u0026#34;+\u0026#34;Java Champion!\u0026#34;; // and in System.out.println(\u0026#34;I \u0026#34;+\u0026#34;am \u0026#34;+\u0026#34;a \u0026#34;+\u0026#34;Java Champion!\u0026#34;); The String “I am a Java Champion!” is actually stored as a single String value in the String pool, and it doesn’t make sense here creating a StringBuilder for something like this.\nUse StringBuilder when you are repeatedly adding, removing, or replacing Characters/Strings.\nAVOID using “+=” on Strings within loops.\nUse char[] when you’ll be mutating characters in the string a lot but the size of this string never changes. For example, getting all possible word permutations of Strings that can be formed from the word “javastrings”. There are 9979200 possible permutations and using a char[] would make it really easy to swap characters without having to rebuild a new string.\nString str = \u0026#34;foobar\u0026#34;; //! `.toCharArray()` converts strings to character arrays char[] characters = str.toCharArray(); //! characterArrays can be converted back to Strings // using `String.valueOf()`; String finalString = String.valueOf(characters); Finally… These optimisations will make your algos run faster. However, your algorithm has to be effective in the first place. Irrespective of programming language, time complexity and space complexity of an algorithm must be OPTIMAL.\nMy template for competitive programming in Java: View gist on GitHub Happy coding !! ✌️🤖👨🏽‍💻\nReferences: Difference between scanner and BufferedReader class in java\nhttps://www.geeksforgeeks.org/stringtokenizer-class-java-example-set-1-constructors/\nhttps://www.guru99.com/stack-vs-heap.html\nOriginal FastScanner template gotten from @agminadur\n","permalink":"https://blog.lordvidex.me.uk/posts/faster-java-algorithms/","summary":"Unlocking the C speed in your Java program","title":"Writing faster Java algorithms"},{"content":"compiler directives special line of code with meaning only to certain compilers\nfortran : !$OMP\nc++ /c : #pragma omp\nthis means that the directives are ignored when compiled normally.\ndirectives contain additional information through clauses e.g.\n#pragma omp parallel [clauses] clauses are comma or space separated Parallel Region defines a seciton of a program uses the fork/join model every thread executes the statement insdie the parallel region the master thread waits at the end of the region Shared and Private data inside a parallel region, we have private or shared all thread see the same copy of shared variables all threads can read or write shared variables each thread has its own copy of private variables, (invisible to others) a private var can only be r/w by it\u0026rsquo;s thread Synchronisation Barrier Critical region Atomic update Barrier all threads must arrive at a barrier before any thread can proceed past e.g. delimiting phases of computation Critical a section of code which only one thread at a time can enter e.g. modification of shared variables atomic update an update to a variable which can be performed at a time e.g. modification of shared variables\nNotable envs, set this to as env to change number of threads OMP_NUM_THREADS\nhow to get the number of threads\n#include \u0026lt;omp.h\u0026gt; int omp_get_num_threads(); shared and private variables types: clauses shared(list) private(list) default(shared|none)\non entry private vars are uninited\nvars declared inside the scope of || are automatically private\nafter || region ends, original var is unaffected by any changes to private copies\nin c++ objects are created using the default constructor\nnot specifying a DEFAULT clasuse is the same as specifying DEFAULT(SHARED).\nalways use default(none) because the compiler will complain and this will help prevent race conditions.\nExamples: #pragma omp parallel default(none) private(i, myid) shared(a,n) { myid = omp_get_thread_num() + 1; for (int i = 0; i \u0026lt; n; i++) { a[i,myid]= 1.0; } } multi line directives we use a backslash in c++ and the backslash must be the last character on that line.\n#pragma omp parallel default(none) \\ private (i,myid) shared(a,n) initialising private variables type: clause we can use firstprivate instead of private to init firstprivate(list)\nit has uncommon use cases in c++ the default copy constructor is called to create and init the new object example: int main() { int i = 10; #pragma omp parallel firstprivate(i) { i++; printf(\u0026#34;%d\\n\u0026#34;, i); // prints 11 11 11 11 11 ... (for each thread) } printf(\u0026#34;The final value of i is %d \\n\u0026#34;, i); // prints 10 return 0; } Reductions a reduction produces a single value from associative ops such as add, x, max, min, and, or all thread reduce into a private copy, then reduce all these to give final result type: clause reduction(op:list) example:\nint main() { int i = 10; #pragma omp parallel reduction(+:i) // 0 is inited { i++; printf(\u0026#34;%d\\n\u0026#34;, i); // prints 1 } printf(\u0026#34;The final value of i is %d \\n\u0026#34;, i); // 18 return 0; } Work Sharing directives directives which appear inside a parallel region and indicate how work should be shared out between threads\nParallel for loops single directive master directive Parallel for loops divides iter between threads there is a sync point at the end of the loop. all threads must finish their iter before any thread can proceed. there are restrictions in c++ it must be of form for(var i=0;\u0026lt;\u0026gt;;\u0026lt;\u0026gt;) and the body must not mutate the counter. example\n#pragma omp parallel { #pragma omp for for(int i=0;i\u0026lt;n;i++) { } } however there is a shorthand which combines the parallel and the for part #pragma omp parallel for\nClauses for directives can take private, firstprivate and reduction clauses. parallel loop index is private by default while other loop indices are not. parallel for can take all clauses available for parallel directive. parallel for != parallel != for Schedule Clause gives a variety of options for specifying which loop iter are executed by which thread schedule(kind[,chunksize]) where kind is one of (static, dynamic, guided, auto, runtime) and chunksize is an integer expression with +ve value. static with no chunksize, the iteration space is divided and one chunk is assigned to each thread (block schedule) e.g. 1,2,3,4 with chunksize, each iteration space is divided into chunks each of chunksize iterations, and these chunks are assigned cyclically to each thread in order (block cyclic schedule). schedule(static,2) 1,2,1,2,3,3 dynamic it divides iter space into chunks of size chunksize and assigns them to threads on a first-come-first-served basis.\nie. as a thread finishes a chunk, it is assigned the next chunk in the list. it defaults to 1 chunksize when not provided guided similar to dynamic, but the chunks start off large and gets smaller exponentially. the size of the next chunk is proportional to the number of remaining iter / the no of threads. chunksize is min size of chunks when no chunksize is specified, it defaults to 1 auto lets the runtime decide if the parallel loop is executed many times, the runtime can evolve a good schedule which has good balance and low overheads. Choosing a schedule static best for load balanced loops static, n good for loops with mild or smooth load imbalance, but can induce overheads dynamic, useful if iterations have widely varying loads but runs data locality guided often less expensive than DYNAMIC, but beware of loops where the first iterations are the most expensive. auto if executed many times over. Single Directive indicates that a block of code is to be executed by a single thread only the first thread to reach the SINGLE directive will exec the block there is a sync point at the end of the block: all the other threads wait until block has been executed #pragma omp single [clauses] e.g.\n#pragma omp parallel { setup(x); // all the threads do this #pragma omp single // all of them block while the first thread to enter executes this block { input(y); // only one thread does this, others wait } work(x, y); // every thread resumes } single directive can take private and firstprivate clauses. directive must contain a structured block; cannot branch in and out of it. e.g. break; Master directive indicates that a block of code should be exec by the master thread (thread 0) only. like single but instead of first thread, only master thread. N.B. there is no sync point at the end of the block i.e. other threads skip the block and continue execing. #pragma omp master Barrier Directive no threads can proceed past a barrier until all the other threads have arrived. code can deadlock if a thread is stuck note that there is implicit barrier at the end of for, section and single directives. Example int main() { float arr[8], brr[8]; int myid, neighb; #pragma omp parallel private(myid, neighb) default(shared) { myid = omp_get_thread_num(); neighb = myid - 1; if (myid == 0) { neighb = omp_get_num_threads() - 1; } arr[myid] = float(myid) * 3.5; #pragma omp barrier // all threads wait for owner to write to a before checking neighbours { brr[myid] = arr[neighb] + 4; printf(\u0026#34;i am %d and the value of brr[myid] is %f\\n\u0026#34;, myid, brr[myid]); } } return 0; } Critical section a block of code which can be executed by only one thread at a time. #pragma omp critical { } Atomic directive used to protect a single update to a shared variable applies to a single statement statement must have one of the forms x=x op expr, x = expr op x, x = intr(x, expr) or x = intr(expr, x) op is one of +, *, -, /, ..and.., .or., .eqv., or .negv. intr is one of max, min, iand, ior, ieor example\n// since vertices are shared by edges, to prevent race conditions when updating vertices, action has to be atomic. // atomic \u0026gt; critical here because the array is not locked, // but instead, only the memory at ith edge is locked #pragma omp parallel for for(j = 0; j \u0026lt; nedges; j++) { #pragma omp atomic degree[edge[j].vertex1]++; #pragma omp atomic degree[edge[j].vertex2]++; } Lock Routines #include \u0026lt;omp.h\u0026gt; void omp_init_lock(omp_lock_t *lock); void omp_set_lock(omp_lock_t *lock); int omp_test_lock(omp_lock_t *lock); void omp_unset_lock(omp_lock_t *lock); void omp_destroy_lock(omp_lock_t *lock); Nested parallelism if a parallel directive is encountered within another parallel it will create new threads OMP_NESTED=FALSE/TRUE ","permalink":"https://blog.lordvidex.me.uk/notes/omp/","summary":"OMP directives with examples","title":"OMP overview"},{"content":" it is a convention for daemon progams to end in the letter d systemctl command is used to manage units e.g. display available units systemctl -t help Listing service units systemctl list-units --type=service [--all] systemctl list-unit-files --type=service # + installed but not enabled Viewing service states systemctl status \u0026lt;name.type\u0026gt;\nsystemctl status sshd.service\nVerifying the status of a service systemctl is-active sshd.service\n... is-enabled ... ... is-failed ...\nService controls systemctl start ... systemctl stop ... systemctl restart ... systemctl reload ... # just reloads config files without restart. This does not change pid systemctl reload-or-restart ... # reloads if possible, otherwise restarts systemctl list-dependencies ... # displays hierarchy mapping Masking and Unmasking This prevents a service from starting by crating a symlink to /dev/null. systemctl mask ... systemctl unmask ... Enabling services to start / stop at boot starting / stopping on a running system does not guarantee that the service auto starts/stops when the system reboots.\nGRUB2 - GRand Unified Bootloader v2\nselecting a target to boot at runtime # systemctl isolate \u0026lt;target\u0026gt; # e.g. systemctl isolate multi-user.target get and set the default target (persistent) systemctl get-default # systemctl set-default \u0026lt;target\u0026gt; e.g. systemctl set-default multi-user.target # graphical.target systemctl reboot # reboots to cli interface instead of gui ","permalink":"https://blog.lordvidex.me.uk/notes/systemd/","summary":"managing services and changing default targets","title":"systemd"},{"content":"Modes 3 SELinux modes:\nEnforcing Permissive Disabled Contexts Contexts of SELinux: user, role, type and sensitivity\nweb server: httpd_t, /var/www/html: httpd_sys_content_t,\n{/tmp, /var/tmp}: tmp_t ports : http_port_t\nCommon commands setenforce [1(Enforcing),0(Permissive)] getenforce setting at boot time, by setting kernel args of enforcing=0. You can disable selinux by setting selinux=0\nthe /etc/selinux/config file contains boot configurations for selinux\nSELINUX=enforcing|permissive|disabled SELINUXTYPE=targeted|minimum|mls the moved file maintains its original label while the copied file inherits the label from the /var/www/html directory.\nMore commands Commands to change the SELinux context of a file: semanage fcontext restorecon chcon\nchcon - changes the security context on the file, stored in the file system. it does not save when restorecon is run, changes made by chcon is lost. chcon -t httpd_sys_content_t /virtual semanage fcontext can -a \u0026ndash;add, -d \u0026ndash;delete, -l \u0026ndash;list SELinux file contexts e.g. semanage fcontext -a -t httpd_sys_content_t \u0026#39;/virtual(/.*)?\u0026#39; restorecon sets the SELinux file contexts as defined in semanage restorecon -Rv /custom SELinux booleans\ngetsebool -a [name] - to get the selinux boolean setsebool \u0026lt;name\u0026gt; \u0026lt;on|off\u0026gt; - to change the value of the boolean (sudo) semanage boolean -l - does the same as getsebool (sudo) semanage boolean -l -C (to check diff between current and default) (sudo) Solving and Investigating Issues /var/log/messages and /var/log/audit/audit.log receive se linux error messages\nsealert -a /var/log/audit/audit.log sealert shows the target file, target context and possible fix ausearch is a tool that can query the audit daemon logs based for events based on different search criteria. e.g. ausearch -m AVC -ts recent\n","permalink":"https://blog.lordvidex.me.uk/notes/linux/selinux/","summary":"Security in linux","title":"SELinux"},{"content":"Mounting and Unmounting File Systems Mounting File Systems Manually mount \u0026lt;file_system\u0026gt; There are two ways to specify file_system on a disk partition name of device in /dev uuid Command lsblk list the details of block devices available\n/mnt is the a temporary mount point\nMounting by UUID use lsblk -fp to get the full path and uuid of devices mount UUID=\u0026#34;3242424-4242-4242424\u0026#34; /mnt/data use fdisk -l to view disks currently on your machine Automatic mounting of Removable Storage Devices if on GUI, removable device is mounted at /run/media/\u0026lt;USER\u0026gt;/\u0026lt;LABEL\u0026gt;.\nUnmounting File Systems shutdown unmounts all file systems automatically to unmount a file system umount /mnt/data # if pwd is /mnt/data, it will error because shell is still using the directory as current wd. lsof list all open files and processes accessing them. Useful for finding which process is preventing umount lsof /mnt/data parted /dev/\u0026lt;id\u0026gt; print parted /dev/\u0026lt;id\u0026gt; mklabel gpt # make a gpt partition table i) parted /dev/\u0026lt;id\u0026gt; ii) mkpart # to make a new partition #alternative one-liner parted /dev/\u0026lt;id\u0026gt; mkpart \u0026lt;name\u0026gt; xfs 2048s 1000MB # parted device mkpart name fs_type start_sector end_sector udevadm settle # to wait for system to detect the new partition and to create the ass. device file under the /dev Deleting Partitions parted print rm \u0026lt;number\u0026gt; Creating File Systems there are two common file systems in rhel \u0026ldquo;xfs\u0026rdquo; and \u0026ldquo;ext4\u0026rdquo; mkfs.xfs /dev/sdb\nMounting File Systems we have looked at the manual way of mounting file system\nmount \u0026lt;device\u0026gt; \u0026lt;location\u0026gt; Managing Swap Space an area of a disk under the control of the Linux kernel memory management subsystem. The kernel uses swap space to supp. the system RAM by holding inactive pages of memory. The combined system RAM plus swap space is called virtual memory. RAM and swap space recommendations RAM Swap Space Swap Space if allowing for Hibernation 2GiB or less 2x ram 3x ram 2 \u0026lt; x \u0026lt; 8 = ram 2x ram 8 \u0026lt; x \u0026lt; 64 \u0026gt;= 4gb 1.5x ram \u0026gt;64 \u0026gt;= 4gb Hiberation is not recommended Creating a swap space create a partition with a fs type of linux-swap parted /dev/sdb print mkpart \u0026gt; swap1 # name \u0026gt; linux-swap # fs type \u0026gt; 1001MB # start \u0026gt; 1257MB # end $ udevadm settle # to wait for the partition to be created creating a swap signature to the device mkswap /dev/sdb2 # to setup swapspace Activating a Swap space free OR swapon --show # to inspect the available swap spaces. swapon /dev/sdb2 # swapoff deactivates a swapspace free the /etc/fstab file is where configurations about disks and swap spaces are loaded from start time of the machine.\nUUID=\u0026lt;uuid\u0026gt; swap swap defaults 0 0 Setting the swap space priority by default the system uses swap spaces in series. However, swap spaces until it is full, then it uses the second swap space. However, you can define a priority for each swap space to force that order. the default is -2.\nUUID=adsfdsfdsafdsafsdf swap swap pri=4 0 0 UUID=asdfsdafsdafsdfsda swap swap pri=10 0 0 the highest priority is used. ","permalink":"https://blog.lordvidex.me.uk/notes/linux/mounting_unmounting_fs/","summary":"\u003ch1 id=\"mounting-and-unmounting-file-systems\"\u003eMounting and Unmounting File Systems\u003c/h1\u003e\n\u003ch2 id=\"mounting-file-systems-manually\"\u003eMounting File Systems Manually\u003c/h2\u003e\n\u003cp\u003emount \u0026lt;file_system\u0026gt; \u003clocation\u003e\u003c/p\u003e\n\u003cul\u003e\n\u003cli\u003eThere are two ways to specify file_system on a disk partition\u003c/li\u003e\n\u003c/ul\u003e\n\u003cul\u003e\n\u003cli\u003ename of device in /dev\u003c/li\u003e\n\u003cli\u003euuid\u003c/li\u003e\n\u003c/ul\u003e\n\u003cp\u003e\u003cstrong\u003eCommand \u003ccode\u003elsblk\u003c/code\u003e list the details of block devices available\u003c/strong\u003e\u003c/p\u003e\n\u003cp\u003e\u003ccode\u003e/mnt\u003c/code\u003e is the a temporary mount point\u003c/p\u003e\n\u003ch2 id=\"mounting-by-uuid\"\u003eMounting by UUID\u003c/h2\u003e\n\u003cul\u003e\n\u003cli\u003euse \u003ccode\u003elsblk -fp\u003c/code\u003e to get the full path and uuid of devices\u003c/li\u003e\n\u003c/ul\u003e\n\u003cdiv class=\"highlight\"\u003e\u003cpre tabindex=\"0\" class=\"chroma\"\u003e\u003ccode class=\"language-bash\" data-lang=\"bash\"\u003e\u003cspan class=\"line\"\u003e\u003cspan class=\"cl\"\u003emount \u003cspan class=\"nv\"\u003eUUID\u003c/span\u003e\u003cspan class=\"o\"\u003e=\u003c/span\u003e\u003cspan class=\"s2\"\u003e\u0026#34;3242424-4242-4242424\u0026#34;\u003c/span\u003e /mnt/data\n\u003c/span\u003e\u003c/span\u003e\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\u003cul\u003e\n\u003cli\u003euse \u003ccode\u003efdisk -l\u003c/code\u003e to view disks currently on your machine\u003c/li\u003e\n\u003c/ul\u003e\n\u003ch2 id=\"automatic-mounting-of-removable-storage-devices\"\u003eAutomatic mounting of Removable Storage Devices\u003c/h2\u003e\n\u003cp\u003eif on GUI, removable device is mounted at \u003ccode\u003e/run/media/\u0026lt;USER\u0026gt;/\u0026lt;LABEL\u0026gt;\u003c/code\u003e.\u003c/p\u003e","title":"Mounting and Unmounting file systems"}]