Nikola Brežnjak blog - Tackling software development with a dose of humor
  • Home
  • Daily Thoughts
  • Ionic
  • Stack Overflow
  • Books
  • About me
Home
Daily Thoughts
Ionic
Stack Overflow
Books
About me
  • Home
  • Daily Thoughts
  • Ionic
  • Stack Overflow
  • Books
  • About me
Nikola Brežnjak blog - Tackling software development with a dose of humor
Linux

50+ commands ChatGPT thinks you should know about Terminal aka Command Line

TL;DR

Hey there and happy Wednesday* 👋

*a day on which, historically, most people wed on; thus: Wed nes day
Not really, but it would be a fun fact actually 🙂

OK, back on point; in this post, I’m going to take you through the basics of using the Terminal aka (as the cool kids using Windows call it) the Command Line. We’ll cover some basic commands, why it’s super useful, and how you can start flexing your command line muscles in no time!

Reality Check

Nowadays, on your first day at a new tech job, you probably aren’t going to be asked to ‘just SSH into the server and deploy the latest build.’. However, that doesn’t mean that knowing the basics of moving around the Linux system is something you shouldn’t learn. If nothing else, it’ll give you additional knowledge; and that’s why you came into this industry, right?

Great, then let’s go 💪

Why Terminal, You Ask?

Yes, the command line can seem intimidating with its blinking cursor and lack of buttons, but it’s really not that scary. Think of it as a conversation with your computer – you just need to know the right words.

Installing the Terminal 😏

Usually, you don’t need to install it; it comes with your operating system. But if you’re on Windows, you might want to look into installing something like Git Bash or PowerShell for a better experience. Or, better yet (if you don’t have a Linux server handy), try it out in a sandbox…

Experimenting in the Sandbox

The best way to learn is by doing. Don’t be afraid to experiment with commands.

The worst that can happen? You might delete your whole system 🙂. So, I suggest using something like https://cocalc.com/ (there are many more options like this, Google them) to test it out in a so-called sandbox environment.

Essentials

1. Opening the Terminal

First things first. To start using the Terminal, you need to open it. On macOS, you’ll find it in Applications > Utilities. Windows folks, look for Command Prompt or PowerShell`. Linux users, you probably already know what you’re doing 🙂

2. The Basic Commands

  • pwd (Print Working Directory)
    • This command tells you where you are. It’s like asking, "Hey Terminal, where the heck am I in this file system maze?"
    • You’ll get an output something like: /home/nikola
  • ls (List)
    • Want to know what files are lurking in the current directory? Just type ls. It’s like peeking into a room to see what’s inside.
  • cd (Change Directory)
    • Need to move around? Use cd followed by the directory’s path. It’s your ‘teleport’ command.
    • If you press ENTER after just the cd command, it will place you in your home directory (/home/nikola in my case)
  • mkdir (Make Directory)
    • To create a new folder, use mkdir followed by the name you want to give it. It’s like conjuring a box out of thin air.
    • For example: mkdir newFolder

3. Editing and Viewing Files

  • touch
    • Create an empty file; for example: touch file.md
  • nano, vim, or emacs
    • These are text editors available right in the Terminal. It might not be as fancy as your VS Code, but it gets the job done. For example, to open the file file.md type nano file.md
    • If you’re really just starting out, go with nano, or be lost in vim forever
    • Jokes aside, there’s a certain level of satisfaction and productivity among folks that master vim
  • cat (Concatenate)
    • Want to quickly view the contents of a file? cat followed by the file name will display it for you. No need to open it in an editor.
    • Example: cat file.md

4. File Manipulation

  • cp (Copy)
    • Use this to copy files or directories.
    • Example: cp file.md file-copy.md
  • mv (Move)
    • Use this to move or rename files or directories.
    • Example: cp file.md file2.md
  • rm (Remove)
    • ⚠️ Be careful with this one as it deletes files or directories. There’s no going back, so use it wisely!

5. Getting Help

  • man (Manual)
    • Stuck with what a command does? Type man followed by the command, and you’ll get a detailed manual. It’s like asking for directions.
    • Example: man ls will give you all the info about the ls command

6. The Power Moves

  • echo
    • output to the console whatever you put in quotes
    • Example: echo "testing" will output ‘testing’ to the console output
  • >
    • redirect the output of a command to another file or program
    • Example: echo "testing" > file.md will overwrite the file.md with the word ‘testing’
    • If you want to append, instead of overwrite, use >>
  • grep
    • This command lets you search through files for specific text. It’s like having a searchlight.
    • Example: grep 'testing' file.md
  • | (Pipe)
    • This symbol is used to take the output of one command and use it as the input for another. It’s like connecting Lego blocks to build something cool.
    • Example: ls | grep "myFile"
    • this command sequence will list all files and directories, but only display those whose names include "myFile".

7. SSH and Remote Servers

  • ssh (Secure Shell)
    • This is how you remotely log into another machine. It’s like teleporting to a different computer.
    • Example: ssh -p port_number username@remote_host

8. Understanding File Paths

File paths can be tricky for beginners. Remember, there are absolute paths (which start from the root directory aka /) and relative paths (which start from your current directory). For example, /Users/nikola/Documents is an absolute path, while Documents from your home directory is a relative path.

If you’re currently positioned in /var/www, then doing cd Documents will probably give you an error that the Documents folder doesn’t exist. However, if you use the full path (cd /Users/nikola/Documents), it will work.

9. Advanced File Operations

  • find
    • A powerful tool for searching files and directories. It’s like having a GPS for your files.
    • Examples:
    • find . -name "filename.txt" – find files by name
    • find /path/to/search -name "*.txt" – find files with a specific parttern
    • find /path/to/search -size +100M – find files based on size
    • find /path/to/search -perm 644 – find files with a certain permission
  • locate
    • Used for finding the location of files and directories
    • Example: locate filename.md

10. Networking Commands

  • ping
    • Check if you can reach another computer or server.
    • Example: ping example.com
  • curl
    • Fetch data from or send data to a server, especially useful for testing APIs.
    • Examples:
    • curl http://example.com – fetch a web page
    • curl -O http://example.com/somefile.zip – download a file
    • curl -d "param1=value1&param2=value2" -X POST http://example.com/form – send POST data
    • curl -H "Content-Type: application/json" -X POST -d '{"username":"xyz","password":"xyz"}' http://example.com/api/login – pass headers
    • curl -b "name=value" http://example.com – use cookies

Additional things that could be useful to you

11. Exploring Environment Variables

  • Environment variables are key-value pairs used by your operating system to manage various system properties. They come in handy for storing data like file paths and configurations.
  • Example: use echo $VARIABLE_NAME to view the value of an environment variable, and export VARIABLE_NAME=value to set one.

12. File Compression and Archiving

  • tar, gzip, zip
    • These commands are used for compressing and decompressing files. They are crucial for managing file sizes and preparing data for transfer.

13. Remote File Transfer

  • scp (Secure Copy)
    • A command for securely transferring files between your local machine and a remote server. It’s like FedEx for your files.
    • Example: scp username@remote_host:/path/to/remote/file.txt /path/to/local/directory
  • rsync
    • A utility for efficiently transferring and synchronizing files across computer systems.
    • Example: rsync -av /path/to/local/dir username@remote_host:/path/to/remote/dir

14. Monitoring Disk Usage

  • df
    • Displays the amount of disk space used and available on your file systems.
  • du
    • Estimates the space used by files and directories.

15. Managing Processes

  • ps
    • Reports a snapshot of the current processes.
  • kill
    • Send a signal to a process, typically used to stop a process.

16. Networking and Port Management

  • netstat
    • Displays network connections, routing tables, and interface statistics.
  • ifconfig
    • Used to configure, or view the configuration of, a network interface.

17. Exploring System Logs

  • Logs are a goldmine of information. Use cat or less to view log files typically stored in /var/log and understand what’s happening under the hood.

18. Crontab for Scheduling Tasks

  • crontab is used for scheduling tasks to run at specific times. It’s like setting a smart alarm for your scripts.
    • Examples
    • with crontab -e command, you’ll be able to edit the crontab file
    • if you want to run a script /path/to/script.sh every day at 5:30 PM, you would add the following line: 30 17 * * * /path/to/script.sh

19. Command History

  • Your Terminal remembers your past commands. Use the history command to recall previous commands or Ctrl + R to search through your command history interactively.

20. Linking Directories with Symbolic Links:

  • ln -s
    • create symbolic links to files and directories. It’s like creating shortcuts.
    • Example: ln -s /path/to/original.txt /path/to/link.txt

21. Managing Users and Groups

  • useradd, usermod, groupadd
    • These commands are used for creating and modifying users and groups. They’re important for managing access on multi-user systems.

22. Disk Partitioning and Mounting

  • fdisk, mount
    • These commands are for managing disk partitions and mounting filesystems. They’re essential for organizing and accessing different storage devices.

23. Networking with nc and telnet

  • nc and telnet
    • These tools can be used for various network operations like port scanning, sending raw data to ports, etc.

24. Advanced Text Processing

  • cut, sort, uniq, tr
    • These text-processing commands are powerful tools for data analysis and manipulation in the command line. Check them out

25. System Information Commands

  • uname, lscpu, lshw
    • These commands provide detailed information about your system’s hardware and software configuration.

26. Learn/Customize Terminal Shortcuts

  • Learn keyboard shortcuts for your Terminal for efficiency.
  • Examples:
    • Ctrl + A to go to the beginning of the line
    • Ctrl + E for the end
    • Ctrl + K to delete from cursor to the end

27. Checking System Health and Resources

  • vmstat, iostat
    • Use these commands to monitor system performance and resource utilization.

28. Exploring System Services and Daemons

  • systemctl, service
    • These commands help you manage system services and daemons in Linux.

29. Filesystem Check and Repair

  • fsck
    • Check and repair Linux filesystems. It’s an essential tool for system maintenance.

30. Securely Deleting Files

  • shred
    • Securely delete files from your filesystem so that they are nearly impossible to recover.

13 additional things you could look into

  • Customizing Your Terminal
    • You can customize the look and feel of your Terminal. Play around with .bashrc or .zshrc (depending on your so-called shell) to change your prompt, add aliases for commands, or even add some fun colors.
    • Or, just install Oh My ZSH!
  • Scripting and Automation
    • Once you’re comfortable, start exploring shell scripting. You can automate repetitive tasks with simple scripts, making your life a whole lot easier.
  • Version Control with Git
    • The Terminal is a friend of Git, a popular version control system. Here’s one tutorial I wrote: Learn Git fast as if your job depends on it
  • Understanding Permissions
    • Files and directories have permissions that determine who can read, write, or execute them. Commands like chmod and chown help you manage these permissions.
  • System Information and Monitoring
    • top or htop
    • These commands give you a real-time overview of what your system is up to. It’s like a dashboard for your computer’s engine.
  • Working with Text
    • awk, sed
    • These are text-processing utilities. They’re complex but incredibly powerful for manipulating text files.
  • The Power of Wildcards
    • Learn how to use wildcards (*** and ?**) for matching file patterns. It’s like casting a net to catch specific files.
  • The Almighty Root User
    • Be cautious with the sudo command – it gives you root (administrator) privileges. With great power comes great responsibility.
  • Package Management
    • Get familiar with package managers like apt for Ubuntu or brew for macOS. They are like app stores for your Terminal.
  • Understanding Filesystem Hierarchy
    • Explore the standard filesystem hierarchy in Linux/Unix systems (/etc for configurations, /var for variable files, /home for user directories). It’s like learning the layout of a new city.
  • Understanding the Root Directory Structure
    • Each directory under / (root) in Unix-like systems has a specific purpose (/bin for binaries, /lib for libraries). Knowing this structure helps you navigate the filesystem more efficiently.
  • Exploring Regular Expressions
    • Regular expressions are patterns used to match character combinations in text. They are a powerful tool in command-line text processing.
  • Exploring Different Filesystems
    • Learn about different filesystems (ext4, NTFS, FAT32) and their characteristics.

Conclusion

There you have it – an extensive beginner’s guide to the Terminal, pushing well past the basics.

Remember, it’s all about practice and exploration. The command line is a powerful tool in your developer toolkit, so embrace it, play with it, and watch as your computer skills reach new heights.

Welcome to the club of command line aficionados, and as always, happy coding! 💪

Books

Tools of Titans by Tim Ferriss

Here are my highlights from a highly recommended book Tools of Titans by Tim Ferriss, broken down into few sections.

Just as a note for myself; of all the people (excluding the world-known like Schwarzeneger), I’d say that Derek Sivers peaked the most interest for me.

Personal Growth and Ambition

  • Routine in an intelligent man is a sign of ambition
  • The quality of your questions determines the quality of your life
  • You realize that you will never be the best looking, smartest, or most educated person in the room, but you can always compete on hard work
  • Never go to sleep without a request to your subconscious

Success and Life Balance

  • Success is about being the best dad who is always approachable and an expert in your field
  • Being busy is a form of laziness
  • Life shrinks or expands in proportion to one’s courage (to have the unpleasant conversations)
  • Most people will choose unhappiness over uncertainty (don’t be like most people)

Health and Well-being

  • Magnesium is one of the best anti-aging minerals
  • Depression may be the body’s way of saying you need to deal with something that’s making you sad
  • Full hip and ankle range of motion is crucial; fix it if you can’t squat all the way down
  • Give meditation an honest shot

Innovation and Creativity:

  • The goal isn’t to get good ideas, but to get enough bad ones so the good ones start showing up (divide your paper into columns for ideas and their first steps)
  • Perfectionism is the enemy of the idea muscle
  • Have fun with your creative process, or it won’t stick

Business and Entrepreneurship

  • In negotiation, he who cares the least wins
  • It’s not what you know, it’s what you do consistently
  • Money can always be regenerated. Time and reputation cannot.
  • What you choose to work on and who you work with are more important than how hard you work

Overcoming Challenges:

  • The dirty little secret is that every success was almost a failure
  • Perfectionism leads to procrastination, which leads to paralysis
  • Ask yourself: what am I continuing to do myself that I’m not good at?
  • Desire is a contract you make with yourself to be unhappy until you get what you want

(Unique) Concepts

  • The jar of awesome
  • Daily journaling (by adding a gratitude section)
  • Sauna (followed by a cold shower or a tub) FTW
  • Physchodelics (not something I’m keen on trying any time soon 🙂)
Leadership

8Questions™

TL;DR

In this post, I’ll share the infamous 8Questions™ that we use when onboarding a new team member. Each person sends the answers to these questions in a written form prior to the first 1on1 with their manager.

8Questions™

  • What is the last awesome thing you learned and what do you want to learn next?
  • Tell me about three (or more) things you’ve accomplished in the last year that you are proud of
  • What are a few things that you wanted to achieve in the previous year but didn’t get to yet?
  • What do you enjoy most about your job?
  • What is your current biggest frustration (if any)?
  • What are your aspirations for yourself and/or the company in the next 1-2 years?
  • In what ways do you think I can help you the most?
  • Is there anything else you want me to know/any concerns you have?
JavaScript

Using Puppeteer to automate ASC Analytics screenshots

TL;DR

I was trying to automate my manual process of logging into ASC (App Store Connect) and taking a screenshot of the crashes, and preparing a report that I do weekly. This blog post explains the exact steps of how I achieved that.

Why Puppeteer?

I’m not affiliated with it in any way, and I also tried Cypress and CasperJS but ran into rather weird problems during installation. Puppeteer just worked straight out of the box, and that’s why I continued down that path.

Install Puppeteer

On Puppeteer’s Github page it’s defined as:

a Node library which provides a high-level API to control Chrome or Chromium over the DevTools Protocol. Puppeteer runs headless by default, but can be configured to run full (non-headless) Chrome or Chromium.

Here are a few examples of what you can do with Puppeteer (although they say that you can automate almost everything that you do manually in the browser):

  • Crawl a SPA (Single-Page Application) and generate pre-rendered content, and take screenshots
  • Automate form submission, UI testing, keyboard input
  • Create an automated testing environment: run your tests directly in the latest version of Chrome

To install it, make sure you have Node.js installed, and then run npm install puppeteer in your terminal.

A simple example using Puppeteer

Here’s a simple example to get you started; create a google.js file and paste this code in it:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('https://google.com');
  await page.screenshot({ path: 'google-screenshot.png' });

  await browser.close();
})();

This script will navigate to https://google.com and save a screenshot in an image named google-screenshot.png.

Execute the script in the command line with: node google.js and you should get a PNG image of how the https://google.com page would look like in your browser:

Mind you, the text you’re seeing is Croatian, as that’s my locale setting.

Looks a bit ‘small’, doesn’t it? That’s because Puppeteer sets an initial page size to 800 × 600 px, which defines the screenshot size. The page size can be customized with Page.setViewport().

Here’s the code example that’s using 1920 x 1080 px viewport size:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  await page.setViewport({
    width: 1920,
    height: 1080,
    deviceScaleFactor: 1,
  });

  await page.goto('https://google.com');
  await page.screenshot({ path: 'google-screenshot.png' });

  await browser.close();
})();

Run it again with node google.js, and the screenshot should now look like this:

For more options (as I won’t go into explaining every API call of the final code) make sure to check their documentation.

The Code™

Below is the quick and dirty code that JustWorks™ in logging into your App Store Connect account (please make sure to edit the script with your credentials), navigating to the Analytics screen and taking a screenshot.

I say quick and dirty because there are a myriad of improvements that could be done on this code:

  • Cookie support (so you don’t have to log in and insert the OTP every time)
  • Typescript (for type safety, and other benefits)

The code is also available on Github, and if you’ve got the skills and the desire, please make those changes and create a PR.

const ACCOUNT = '[email protected]';
const PASSWORD = 'YourVeryMuchSuperStrongPa$$word';
const LOGIN_FRAME = '#aid-auth-widget-iFrame';
const ASC_URL = 'https://appstoreconnect.apple.com/';
const ANALYTICS_URL = 'https://appstoreconnect.apple.com/analytics';
const APP_CRASHES_URL = 'theSpecificUrlToYourSpecificApp'; //figure this out by copying the URL manually

const puppeteer = require('puppeteer');
const readline = require('readline');

const log = (msg) => {
    console.log(msg);
}

const clickSignInButton = async (frame) => {
    log('Clicked the Sign In button');

    const element = await frame.waitForSelector(
        '#stepEl > sign-in > #signin > .container > #sign-in:not(disabled)'
    );

    await element.click();
};

const clickTrustBrowser = async (frame) => {
    log('Clicked the Trust Browser button');

    const selector = 'button.trust-browser';
    const element = await frame.waitForSelector(selector);
    await element.click();
};

const askForVerificationCode = () => {
    log('Asking for verification code');

    const readlineInterface = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
    });

    return new Promise(resolve => {
        readlineInterface.question(
            'Please enter your code: ',
            answer => {
                console.log(`Thanks, you entered: ${answer}`);
                readlineInterface.close();
                resolve(answer);
            }
    );
  });
};

const login = async (page, user, password) => {
    log('Login page');
    const frameElement = await page.$(LOGIN_FRAME);
    if (!frameElement) {
        throw new Error(`Missing frame ${LOGIN_FRAME}`);
    }

    const frame = await frameElement.contentFrame();
    if (!frame) {
        throw new Error(`Missing frame ${LOGIN_FRAME}`);
    }

    const ACCOUNTInputSelector = '#account_name_text_field';
    await frame.waitForSelector(ACCOUNTInputSelector);

    await frame.focus(ACCOUNTInputSelector);
    await page.keyboard.type(user);

    await clickSignInButton(frame);

    const passwordInputSelector = '#password_text_field';
    await frame.waitForSelector(passwordInputSelector);
    await frame.waitForTimeout(2000);

    await frame.focus(passwordInputSelector);
    await page.keyboard.type(password);
    await clickSignInButton(frame);

    const verifyDeviceSelector = 'verify-phone';
    await frame.waitForSelector(`${verifyDeviceSelector}`);
    const isVerifyDevice = await frame.$(verifyDeviceSelector);

    if (isVerifyDevice) {
        log('Verify phone step');
        const verificationCode = await askForVerificationCode();
        await page.keyboard.type(verificationCode);
        await clickTrustBrowser(frame);
    }
};

const main = async () => {
    const browser = await puppeteer.launch({
        // set this to false if you want to open a browser instance and see what your
        // script is doing, where it's clicking, what it's filling out, etc.
        headless: false 
    });

    const page = await browser.newPage();
    await page.setViewport({
        // settings for my personal need, set this as you wish
        width: 1440,
        height: 815,
        deviceScaleFactor: 1,
    });

    log(`Oppening ${ASC_URL}`);
    await page.goto(ASC_URL);

    await page.waitForSelector(`${LOGIN_FRAME}`);
    await login(page, ACCOUNT, PASSWORD);

    await page.waitForNavigation({ waitUntil: 'networkidle2' });
    await page.waitForSelector('.main-nav-label');

    await page.goto(`${ANALYTICS_URL}`);
    await page.goto(`${APP_CRASHES_URL}`);

    await page.waitForNavigation({ waitUntil: 'networkidle2' });
    await page.waitForSelector('#appanalytics');
    // sometimes the selector will load, but not the whole content, so you may
    // want to play with the waitForTimeout. The argument is in mili seconds
    //await page.waitForTimeout(5000); 

    await page.screenshot({ path: 'app_analytics_crashes.png' });

    log('Closing the browser page');
    await browser.close();
};

main().catch(error => console.error(error));

When you run this code, in the terminal you should see this output:

➜ node apple.js               
Oppening https://appstoreconnect.apple.com/
Login page
Clicked the Sign In button
Clicked the Sign In button
Verify phone step
Asking for verification code
Please enter your code: 866216
Thanks, you entered: 866216
Clicked the Trust Browser button
Closing the browser page

The OTP code to log in to Apple, in my case, was sent to me via an SMS.

The screenshot (blurred for obvious reasons), looks like this in my case:

That’s great, but what if my login requires CAPTCHA?

In my particular case, the login was rather simple (except for the fact that I had to select the frame and search within it for the element IDs).

But, what if your login requires you to enter the CAPTCHA? You know, those "are you human" popups that you get when logging into some website. Then I had a ‘great idea’ – what if you make a service where people actually read and type these CAPTCHAs for you?

⚠️ Now, let me be very clear – just because something is possible to do automatically, it doesn’t give you the right to use that in a bad way (spammers be gone!). Do with this information what you wish, but don’t come crying back saying "he made me do it".

Yes, no drumrolls needed, as almost everything today – this also already exists. CAPTCHA solving software exists and it’s a thing, and I found a blog posts that reviews 10 CAPTCHA-solving software.

One that caught my eye was 2captcha.com, and I found a blog post that did a thorough teardown of the service. The reason that one caught my eye was that it seems that they offer their solution through libraries for most of the popular programming languages (Python, PHP, JS,Go, C#, Ruby).

A trip down the memory lane

Sorry for the sidetrack (and you can safely skip this section 😅), but I just remembered how, years ago, I attended a conference where Photomath’s (the app that solves math problems and shows you the steps of how to solve them) CEO was talking about how they’re solving the OCR problem (they supposedly had a breakthrough when they applied ML). They built an awesome business, that’s actually useful, and I saw that they recently integrated into Snapchat via their Snapchat Solver 🤯 . I digress, yes, but with that good ‘tech’, I see them integrated into everything and that makes me proud (since, at the time, they were a Croatian-based startup).

Conclusion

Hope this straight-to-the-point post (with one slight detour 😅) showed you how you can make use of the amazing Puppeteer for your (legit) purposes.

Stay safe and code on 💪

Daily Thoughts

Do it when you don’t feel like it

I get it.

Sometimes it’s just hard. Like, legit hard. To do.

To do what?

Well, really, anything that’s not easy.

You’re just stuck. You need a break. A break from being stuck.

But guess what?

That’s exactly the time when you need to do it. To do that thing that you’ve been dreading, or stalling or whatever.

These moments will define you and shape you into a person that does something even when you "don’t feel like it".

It will pay off.

Do it 💪


This is why I write these ‘daily thoughts’ posts.

Daily Thoughts

Self-mastery

No matter the level of achievement in external things, mastering oneself is the greatest one.


This is why I write these ‘daily thoughts’ posts.

Daily Thoughts

Writing well

Learning to write well is a skill that will come useful no matter the industry.


This is why I write these ‘daily thoughts’ posts.

Daily Thoughts, JavaScript

const life = change();

They (supposedly, originally, Heraclitus) say that the only true constant in life is change.

A JavaScript programmer in you might write that like this:

const life = change();

And, the trick in real life is that the function’s implementation regularly looks like this:

function change() {
    return Math.random();
}

However, when you’d try to output the value of the life constant (see it in action in JS Fiddle), it would be exactly that, a constant (no matter how many times you’d call it or output it).

Sidenote: if you’re puzzled by the fact that you can assign a function to a constant (or to a variable for that matter) before it was defined in the code, then go and learn about hoisting in JavaScript.

Now, you may write the above statement like this:

const life = function change() {
    return Math.random();
}

Now, if you call the life function (again, see it in action), it will return a different value every time you call it.

⚠️ JavaScript gurus among you may chuckle at assigning a function to a constant, but check this StackOverflow answer for its applicability – plus, you’ll learn (or, refresh your memory) about hoisting in JS.

Switching gears; the point of all this is that you can’t expect to be doing the same thing, and getting different results, and no matter what obstacles you face, the key to overcoming them is not in changing the event, but in changing yourself and how you react to it. And that itself is a process. A process that begins with the desire or acceptance to be teachable and improve for the better.

Hope you like this attempt at mixing programming with personal growth topics (for more, check my daily thoughts entries).

Stay safe, friends ❤️


This is why I write these ‘daily thoughts’ posts.

Daily Thoughts

Helping others

In the case of an air pressure type emergency on the ✈️, before helping others you should put the mask on first. The same goes for helping others in any other way; help yourself first. How can you help someone with something if you yourself don’t yet know the best way of doing that something?


This is why I write these ‘daily thoughts’ posts.

Daily Thoughts

The curious case of tomorrow

This may come as a shock to learn that (as reported here – and there are many similar reports, just Google them):

Fewer than 1 in 100 stroke survivors met all seven heart-health goals identified by the American Heart Association. And just 1 in 5 met four of those goals.

James Clear wrote the other day:

If you’d like to do something bold with your life, you will have to choose to do something bold on a specific day. There is no perfect day. There is no right time. For the trajectory to change, there has to be one day when you simply make the choice.

So, I really wonder, how sick and tired of something we need to be in order to change that something for the better?

Instead of waiting for tomorrow, why not start today?


This is why I write these ‘daily thoughts’ posts.

Page 3 of 51« First...«2345»102030...Last »

Recent posts

  • When espanso Breaks on Long Replacement Strings (and How to Fix It)
  • 2024 Top Author on dev.to
  • Hara hachi bun me
  • Discipline is also a talent
  • Play for the fun of it

Categories

  • Android (3)
  • Books (114)
    • Programming (22)
  • CodeProject (36)
  • Daily Thoughts (78)
  • Go (3)
  • iOS (5)
  • JavaScript (128)
    • Angular (4)
    • Angular 2 (3)
    • Ionic (61)
    • Ionic2 (2)
    • Ionic3 (8)
    • MEAN (3)
    • NodeJS (27)
    • Phaser (1)
    • React (1)
    • Three.js (1)
    • Vue.js (3)
  • Leadership (1)
  • Meetups (8)
  • Miscellaneou$ (78)
    • Breaking News (8)
    • CodeSchool (2)
    • Hacker Games (3)
    • Pluralsight (7)
    • Projects (2)
    • Sublime Text (2)
  • PHP (6)
  • Quick tips (41)
  • Servers (8)
    • Heroku (1)
    • Linux (3)
  • Stack Overflow (81)
  • Unity3D (9)
  • Windows (8)
    • C# (2)
    • WPF (3)
  • Wordpress (2)

"There's no short-term solution for a long-term result." ~ Greg Plitt

"Everything around you that you call life was made up by people that were no smarter than you." ~ S. Jobs

"Hard work beats talent when talent doesn't work hard." ~ Tim Notke

© since 2016 - Nikola Brežnjak