Wave changes

This commit is contained in:
2026-03-27 15:39:35 +00:00
parent cb3e4c5809
commit bddb928ec2
253 changed files with 7056 additions and 1727 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,17 @@
:PROPERTIES:
:ID: 9d1cfccc-8da7-41a3-b435-9857f0abe441
:END:
#+title: Leetcode Notes
#+filetags: :index:notes:leetcode:coding:
* Resources:
To work through:
- https://www.youtube.com/watch?v=lvO88XxNAzs&list=LL&index=1&ab_channel=stoneycodes
* Start
[[id:275988a8-59d8-40c8-a8b4-47118d6eb834][big-o-complexity]]
[[id:086ca3ca-39ec-4d37-b56d-b6d9f51e6873][how-to-solve-leetcode]]
[[id:93a43a24-6861-40c4-b45b-581977bb55cf][leetcode-arrays]]

View File

@@ -0,0 +1,54 @@
:PROPERTIES:
:ID: 347d2663-515b-4d9a-9ee9-7706ee86a845
:END:
#+title: Haskell Notes
#+filetags: :index:notes:haskell:coding:
* Haskell Notes
** Introduction
Haskell is a purely functional programming language with strong static typing and [[id:63456626-b34e-46d9-b85e-0f1f5724aa83][lazy_evaluation]] . It was named after the logician Haskell Curry. It is widely used in academia and industry for teaching and research as well as for writing industrial applications.
** Features of Haskell
- Purely Functional: Functions in Haskell are pure, meaning they don't have side effects.
- Strong Static Typing: Types are checked at compile time, reducing runtime errors.
- Lazy Evaluation: Expressions are not evaluated until their values are needed.
- Type Inference: Haskell can automatically infer types, making the code more concise.
- Concise Syntax: Haskell's syntax is clean and concise, making it easy to read and write.
** Getting Started with Haskell
- Installation: To get started with Haskell, you need to install the Glasgow Haskell Compiler (GHC). You can download it from [[https://www.haskell.org/downloads/][Download]]
- Basic Syntax:
- Comments: Single line comments start with `--`, and multi-line comments are enclosed within `{-` and `-}`.
- Modules: Code is organized into modules, which can be imported using the `import` keyword.
** Basic Concepts
- Functions: Functions are first-class citizens in Haskell. A function definition looks like this:
#+BEGIN_SRC haskell
add :: Int -> Int -> Int
add x y = x + y
#+END_SRC
This defines a function *add* that takes two integers and returns their sum.
- Types and Type Classes: Types are a crucial part of Haskell. You define types using the `data` keyword, and type classes using the `class` keyword.
** Example
Here's a simple example to demonstrate some basic features of Haskell:
#+BEGIN_SRC haskell
-- Define a new data type
data Shape = Circle Float | Rectangle Float Float
-- Define a function to calculate the area of a shape
area :: Shape -> Float
area (Circle r) = pi * r^2
area (Rectangle l w) = l * w
-- Example usage
main = do
let c = Circle 10
let r = Rectangle 5 7
print (area c)
print (area r)
#+END_SRC
This example defines a new data type Shape with two constructors, Circle and Rectangle, and a function area that calculates the area of a shape.

View File

@@ -0,0 +1,9 @@
:PROPERTIES:
:ID: 63456626-b34e-46d9-b85e-0f1f5724aa83
:END:
#+title: lazy_evaluation
#+filetags: :haskell:coding:notes:
See this article: [[https://medium.com/background-thread/what-is-lazy-evaluation-programming-word-of-the-day-8a6f4410053f][Lazy eval]]
There are two types of evaluation: strict and lazy

View File

@@ -0,0 +1,9 @@
:PROPERTIES:
:ID: 5a207a1c-6f02-40d5-b42e-38daaa0aec10
:END:
#+title: C Notes
#+filetags: :index:coding:notes:
[[id:efe0360d-8d81-4372-833d-ad58e67d17c6][socket_programming_in_c]]
[[id:d939e477-d1e9-43ea-960e-8727246d12a3][useful-c-imports]]

View File

@@ -0,0 +1,31 @@
:PROPERTIES:
:ID: efe0360d-8d81-4372-833d-ad58e67d17c6
:END:
#+title: socket_programming_in_c
#+filetags: :networking:coding:notes:
From: [[https://www.linuxhowtos.org/C_C++/socket.htm][Web Link]]
* Steps:
The steps involved in establishing a socket on the client side are as follows:
1. Create a socket with the socket() system call
2. Connect the socket to the address of the server using the connect() system call
3. Send and receive data. There are a number of ways to do this, but the simplest is to use the read() and write() system calls.
The steps involved in establishing a socket on the server side are as follows:
1. Create a socket with the socket() system call
2. Bind the socket to an address using the bind() system call. For a server socket on the Internet, an address consists of a port number on the host machine.
3. Listen for connections with the listen() system call
4. Accept a connection with the accept() system call. This call typically blocks until a client connects with the server.
5. Send and receive data
* Socket types:
When you create a socket, you must specify the *address domain* and the *socket type*, the client and server can only communicate if they are of the same type and in the same domain.
The two most common address domains:
- unix domain (they share common file system)
- internet domain
The two most common socket types:
- stream sockets (continuous stream of characters) - uses tcp
- datagram sockets (reads the entire messages at once) - uses dp

View File

@@ -0,0 +1,246 @@
:PROPERTIES:
:ID: 348df473-6443-4f4a-b366-95397b574989
:END:
#+title: web-port-notes
#+filetags: :index:docs:zzq:
* <2025-11-06 Thu> old sitemap for blogs:
(defun zz/2025-sitemap (title list)
"sitemap that lists 2025 links as bullet points with dates and tags."
(concat
"#+TITLE: " title "\n"
"#+OPTIONS: toc:nil num:nil \n\n"
"See the categories: @@html:<a href=\"../../categories.html\">Categories</a>@@\n\n"
"* 2025:\n"
(mapconcat
(lambda (entry)
(let* ((link (car entry))
;; extract relative file name from the link
(filename (if (string-match "\\[\\[file:\\([^]]+\\)\\]" link)
(match-string 1 link)
link))
(full-path (expand-file-name filename "~/master-folder/org_files/org_web/blogs/2025/"))
(date-str "no date")
(tags-str ""))
;; Get publish date
(let ((date (org-publish-find-date full-path org-publish-project-alist)))
(when date
(setq date-str (format-time-string "%d-%m-%Y %H:%M" date))))
;; Get FILETAGS from file buffer
(when (file-exists-p full-path)
(with-temp-buffer
(insert-file-contents full-path)
(org-mode)
(let* ((tags (cadr (assoc "FILETAGS" (org-collect-keywords '("FILETAGS"))))))
(when tags
(setq tags-str (mapconcat (lambda (tag)
(format "@@html:<a href=\"/tags/%s.html\"> <span class=\"post-tag\">%s</span> </a>@@" tag tag))
(split-string tags ":" t) ;; <- Splits by ":" and removes empty strings
" "))))))
;; Final line output
(format "- %s @@html:<span class=\"post-date\">%s</span>@@ %s" link date-str tags-str)))
(cdr list)
"\n")))
* Footnotes and sidenotes
Here is a list of macros:
#+begin_src emacs-lisp
(setq org-export-global-macros
(append
'(
("sidenote"
. "@@html:<label for=\"sn$1\" class=\"margin-toggle sidenote-number\"></label><input type=\"checkbox\" id=\"sn$1\" class=\"margin-toggle\"/><span class=\"sidenote\">$2</span>@@")
("epigraph" . "@@html:<div class=\"epigraph\"><blockquote>$1<footer>$2</footer></blockquote></div>@@")
("epigraph_single" . "@@html:<div class=\"epigraph\"><blockquote>$1</blockquote></div>@@")
("epigraph3" . "@@html:<div class=\"epigraph\"><blockquote>$1<footer>$2, <cite>$3</cite></footer></blockquote></div>@@")
("kbd" . "@@html:<kbd>$1</kbd>@@@@latex:\\texttt{$1}@@")
("margimg"
. "@@html:<aside class=\"marginnote\"><figure class=\"mn-fig\"><img src=\"$1\" alt=\"$2\" class=\"mn-img\" loading=\"lazy\" decoding=\"async\"/>$3</figure></aside>@@")
org-export-global-macros)))
#+end_src
They are used as follows:
{{{sidenote(1, The very first iteration of this website used the Angular framework\, only after a while I realised (as every Emacs lover does) that I want to make this an Emacs-centric project)}}}
Use footnotes as follows:
[fn:1]
then put them at the bottom with the respective information.
* Blorgz
** ideas:
### **Personal Growth & Self-Improvement**
1. **The Power of Journaling: How Writing Every Day Can Transform Your Life**
- Exploring the benefits of journaling for mental clarity, goal setting, and emotional processing.
2. **The Science of Happiness: What Really Makes Us Happy?**
- A deep dive into the psychology and neuroscience of happiness and how to apply it to daily life.
3. **Building a Growth Mindset: How to Shift from a Fixed to a Growth-Oriented Outlook**
- Practical steps and insights on adopting a growth mindset for personal and professional development.
4. **How to Set and Achieve Long-Term Goals**
- A structured approach to setting clear, actionable goals and staying motivated over time.
5. **Embracing Failure: How to Learn and Grow from Setbacks**
- Understanding the importance of failure and how to reframe it as an opportunity for growth.
### **Mental Health & Well-being**
6. **Dealing with Anxiety: Techniques to Cope and Build Resilience**
- Mindfulness, cognitive-behavioral strategies, and lifestyle changes that help manage anxiety.
7. **How to Build Emotional Intelligence (EQ) for Better Relationships**
- Tips for recognizing, understanding, and managing your own emotions, and how to navigate others' emotions.
8. **The Importance of Sleep for Mental and Physical Health**
- Why sleep is crucial for your overall well-being, along with tips for improving your sleep hygiene.
9. **How to Practice Self-Compassion and Be Kinder to Yourself**
- Exploring the importance of self-compassion and how to stop being your own harshest critic.
10. **Breaking the Cycle of Negative Self-Talk**
- How to identify, challenge, and reframe the negative thoughts that hold you back.
### **Lifestyle & Balance**
11. **Minimalism: How Decluttering Your Life Can Lead to More Freedom**
- A guide to adopting a minimalist lifestyle, including decluttering your home, work, and digital space.
12. **The Importance of Work-Life Balance and How to Achieve It**
- Strategies for maintaining a healthy balance between your career, personal life, and self-care.
13. **How to Create a Morning Routine That Sets You Up for Success**
- A step-by-step guide to designing a morning routine that boosts your productivity and mindset.
14. **The Power of Saying 'No': Setting Boundaries to Protect Your Time and Energy**
- How to say no gracefully and why its important for your mental health and well-being.
15. **Building Strong Relationships: The Art of Effective Communication**
- How to communicate more clearly and empathetically in both personal and professional settings.
### **Life Philosophy & Reflection**
16. **Living with Purpose: How to Find Your Lifes Meaning**
- A philosophical exploration of how to align your actions with your core values and life purpose.
17. **Stoicism for Modern Life: How Ancient Philosophy Can Help You Thrive Today**
- Applying Stoic principles to improve resilience, clarity, and calm in the face of challenges.
18. **The Concept of Ikigai: Finding Joy and Fulfillment in Your Work and Life**
- Exploring the Japanese philosophy of Ikigai and how to apply it for greater fulfillment and balance.
19. **How to Handle Life Transitions: Moving Forward with Confidence**
- Tips for navigating big life changes, from job shifts to personal transformations.
20. **The Importance of Gratitude: How to Cultivate a Daily Practice for a More Positive Life**
- The science behind gratitude and how to incorporate it into your daily life to increase happiness.
### **Productivity in Daily Life**
21. **Time Management for Busy People: How to Get More Done Without Burning Out**
- Techniques like time blocking, prioritization, and task batching to make your day more productive.
22. **Overcoming Overwhelm: How to Tackle Large Tasks Without Feeling Stressed**
- Breaking down big tasks into manageable chunks to prevent feelings of stress or burnout.
23. **The Importance of Play and Fun in a Productive Life**
- How leisure and play are just as important for mental health and long-term productivity.
24. **How to Stay Motivated During Long-Term Projects**
- Strategies for maintaining motivation and momentum over the course of a long, challenging task.
25. **Creating a Digital Detox: How to Unplug and Recharge**
- The benefits of taking time away from screens and how to implement a healthy digital detox.
** my emacs.config
- [[id:b2db0b0b-c179-43ab-9e2b-22bbaac69bcb][wp-emacs-config-blorg]]
** prefrontal-cortex
- [[id:b292f5c6-0c27-439c-8274-2150eb45e20d][wp-prefront-cortex-blorg]]
** new emacs config written on: <2025-02-14 Fri>
[[id:1ee754f9-f30f-4976-850b-d18d01a834d2][wp-new-emacs-config-blorg]]
** urge surfing: <2025-03-14 Fri>
[[id:cfc4ce06-7862-49b7-9a4f-e515d690cd38][wp-urge-surfing-blorg]]
** growth mindset
[[id:CD093B85-BF68-4EAB-AABE-733C7BFC99DE][wp-growth-mindset]] <2025-03-14 Fri>
** emotional intelligence
[[id:D02B89DC-84D0-4211-A902-B9399F4179CA][wp-emotional-intelligence]] <2025-03-16 Sun>
** reflection on week 12
[[id:8CD2F4C4-22C2-4ECC-8F5F-C4779F8AC0F1][wp-week-12-reflections]]
** sadness
[[id:462F091B-9156-48B3-8665-0BE36C95C182][wp-sadness]]
* Commits
** code:
You can add a commit detail by doing this:
#+begin_src elist
(insert-commit-template)
;; "SPC c i c"
#+end_src
** Commit on <2024-12-17 Tue>
*** Details
This commit was focused on getting the blog section ready. So far ive decided to go for a static approach, whereby the blogs are stored in a .json file and populated in an array. The 'slug' property is found in:
- the title of the file (blog)
- the metadata of the blog
- the metadata of the index.json
These three must be consistent
*** What to work on next:
- the rendering of the content of the blogs
- the github project population: match the blog page stylings.
*** Commit message:
"Worked on the blog page, did stylings and began to populate"
** Commit on <2024-12-18 Wed>
*** Details
Decided to change the way the blog is rendered. Using a json index object to display the list (slug is importnant), then blog detail is displayed as a rendered *HTML* from a markdown file. The scss was changed as well:
#+begin_src js
"node_modules/prismjs/themes/prism-dark.css"
#+end_src
this loads the theme for the code blocks.
*** What to work on next:
- the github project population: match the blog page stylings.
*** Commit message:
"continued work on blog page, stylings are done, the rendering changed from using json to md."
** Commit on <2024-12-20 Fri>
*** Details
Worked on the github project display, kept the same look as the blogs. Also done the about me section in the homepage (added some random ai generated info - need to change). Also done the contacts (set up a smpt gmail server)
*** What to work on next:
- Get rid of all the hardcoded blogs, and begin first blog.
*** Commit message:
"finished contact section - added smtp gmail server"
** Commit on <2025-01-01 Wed>
*** Details
Deployed (changed back to emailjs)
*** What to work on next:
*** Commit message:
** Commit on <2025-01-12 Sun>
*** Details
- added new blog: prefrontal cortex and self discipline
- added a estimated time to read
*** What to work on next:
more blogs
*** Commit message:
"added new blog"
** Commit on <2025-02-15 Sat>
*** Details
- added tags with persistency. Redid the whole UI (theme)
*** What to work on next:
- add a cv section
*** Commit message:
** Commit on <2025-03-14 Fri>
*** Details
- added quizzes and used firebase for storage
*** What to work on next:
- rendering of images , spending more time on blogs and creating quizzes
*** Commit message:

View File

@@ -0,0 +1,7 @@
:PROPERTIES:
:ID: b2db0b0b-c179-43ab-9e2b-22bbaac69bcb
:END:
#+title: wp-emacs-config-blorg
#+filetags: :zzq:blogs:
[[file:~/master-folder/projects/web-port/md-files/emacs_config.md][file]]

View File

@@ -0,0 +1,16 @@
:PROPERTIES:
:ID: ee6047b0-c878-4ec8-a1cf-9daf5c8f5b8e
:END:
#+title: Github Notes
#+filetags: :git:notes:
- [[id:74ec625c-3559-4570-8f6e-8272f4859ea7][Gitea Notes]]
* Cheat sheet
[[./assets/git-cheat-sheet-1.png]]
[[./assets/git-cheat-sheet-2.png]]
https://www.atlassian.com/git/tutorials/saving-changes/gitignore

View File

@@ -0,0 +1,7 @@
:PROPERTIES:
:ID: b292f5c6-0c27-439c-8274-2150eb45e20d
:END:
#+title: wp-prefront-cortex-blorg
#+filetags: :zzq:blogs:
[[file:~/master-folder/projects/web-port/md-files/prefrontal_cortex.md][file]]

View File

@@ -0,0 +1,130 @@
:PROPERTIES:
:ID: 1ee754f9-f30f-4976-850b-d18d01a834d2
:END:
#+title: wp-new-emacs-config-blorg
#+filetags: :zzq:blogs:
# Setting Up an Advanced Emacs Configuration for Productivity
I recently spoke about what Emacs is, and how it is useful for productivity. I wanted to write this up again and dive more into the other files that were stored in the `/scripts` directory , as well as how to set it up.
## Prerequisites
Before we begin, ensure you have Emacs installed. You can install Emacs using the following commands based on your operating system:
- **Ubuntu/Debian:** `sudo apt install emacs`
- **MacOS (Homebrew):** `brew install emacs`
- **Windows:** Use [MSYS2](https://www.msys2.org/) or install Emacs from [GNU Emacs](https://www.gnu.org/software/emacs/).
Additionally, ensure that `git` is installed to clone repositories and manage configurations.
## Download the Configuration Files
First let's walk through how to set this up.
Clone the repository or manually download the provided configuration files into your `~/.emacs.d/` directory:
```sh
mkdir -p ~/.emacs.d/
cd ~/.emacs.d/
```
The following file should be copied to `~/.emacs.d/`:
- `init.el`
And the following files should be copied into `~/.emacs.d/scripts`:
- `auto-comp.el`
- `custom-agenda.el`
- `displays.el`
- `keyboard.el`
- `shells.el`
- `window.el`
If you are using `git`, you can clone your repository directly:
```sh
git clone https://github.com/zainezq/dot-files/tree/main/emacs-config
```
## Understanding the Configuration
This configuration is modularised for easier maintenance. Each file handles a specific feature:
### `init.el`: The Core Configuration
The `init.el` file is the entry point of the configuration. It:
- Loads package management (MELPA, `use-package`)
- Imports additional modules (`displays`, `shells`, `auto-comp`, `window`, `keyboard`, `custom-agenda`)
- Configures UI elements such as themes, icons, and window behavior
- Sets up Org mode and language support
- Enables Evil mode for Vim-like keybindings
### `auto-comp.el`: Auto-Completion Setup
This file configures `company-mode` for autocompletion in Emacs. It:
- Loads `company-mode` and `company-box` for a better UI
- Sets the minimum prefix length and delay before suggestions appear
- Enables backend support for various modes
### `keyboard.el`: Custom Keybindings
This file sets up keybindings using the `general.el` package. Some useful shortcuts include:
- `SPC .` → Open file finder
- `SPC f c` → Open `init.el` for quick edits
- `SPC b b` → Switch buffers
- `SPC w 1` → Removes (not kills) all buffers except the current one
- `SPC t n` → Toggle NeoTree file explorer
### `window.el`: Window Management
Defines functions for moving buffers between splits using `windmove`. Functions include:
- `buf-move-up` → Swap buffers up
- `buf-move-down` → Swap buffers down
- `buf-move-left` → Swap buffers left
- `buf-move-right` → Swap buffers right
### `shells.el`: Shell and Terminal Integration
Configures:
- `vterm` as the primary terminal
- `eshell-toggle` for quick access to Eshell
- `vterm-toggle` for easy terminal toggling
### `custom-agenda.el`: Org Mode Enhancements
This file customises Org mode agendas. It:
- Configures custom agenda views
- Hides the Org agenda startup message
- Enables extra features such as displaying scheduled tasks
### `displays.el`: UI Enhancements
This file improves the visual experience in Emacs:
- Configures `dashboard.el` to show a custom startup screen, you may modify this to your liking, see: [Emacs Dashboard](https://github.com/emacs-dashboard/emacs-dashboard)
- Enables `neotree` for file navigation
- Hides unnecessary UI elements for a cleaner look
## Installing Dependencies
Open Emacs and run the following command to install missing packages:
```sh
M-x package-refresh-contents
M-x package-install-selected-packages
```
Alternatively, restart Emacs, and `use-package` will automatically install any missing dependencies.
If any issues arise, check `*Messages*` buffer (`M-x view-echo-area-messages`) or start Emacs with debugging mode enabled (`emacs --debug-init`). What I tend to do is whenever I encounter any errors, I run emacs in minimal mode: `emacs -Q`, this loads emacs without the init.el file (if I can't pinpoint the exact error).
## Final Notes
This configuration optimises Emacs for efficient navigation, organisation, and shell integration.
Everybodies configuration will differ based on their needs, so feel free to take and leave the parts as you wish!
For additional customisation, refer to the official package documentation:
- [General.el (Keybindings)](https://github.com/noctuid/general.el)
- [Evil Mode (Vim keybindings)](https://github.com/emacs-evil/evil)
- [Org Mode](https://orgmode.org/)
- [Neotree (File navigation)](https://github.com/jaypei/emacs-neotree)

View File

@@ -0,0 +1,69 @@
:PROPERTIES:
:ID: cfc4ce06-7862-49b7-9a4f-e515d690cd38
:END:
#+title: wp-urge-surfing-blorg
#+filetags: :blogs:zzq:
# Urge Surfing: Mastering the Art of Riding Your Impulses
By Zaine Qayyum
## Table of Contents
1. [Introduction](#introduction)
2. [What is Urge Surfing?](#what-is-urge-surfing)
3. [How Urge Surfing Works](#how-urge-surfing-works)
4. [Conclusion](#conclusion)
## Introduction
I've spoken about the internal components of 'self-discipline' in another blog, but if we take a look at this whole self-improvement topic from another angle, we can see that the underlying reason for us not being able to 'stick to things' is due to us giving in to our urges. That may sound trivial, and we may connect the dots that if we control our impulses, we can do xyz. However, that form of thinking requires a bit of explanation.
Psychologists have researched and found that opposing our urges is like making them stronger because we give it that 'attention' it wants (Wegner, 1994). In his Ironic Process Theory, Daniel Wegner demonstrated that trying to suppress thoughts such as resisting cravings or unwanted impulses paradoxically makes them more persistent (Wegner, Schneider, Carter, & White, 1987). Addiction research further emphasises this, where forcefully fighting cravings can intensify them rather than make them disappear.
But what if, instead of giving in or fighting them, we learned to ride them like a wave? This is the foundation of urge surfing, a mindfulness based technique developed by Dr. Alan Marlatt, which teaches individuals to observe their cravings without reacting to them, allowing them to naturally peak and fade.
## What is Urge Surfing?
Urge surfing is a concept that originated in addiction therapy and mindfulness practices. Developed by psychologist **Dr. Alan Marlatt**, it was designed to help people struggling with addictive behaviors by teaching them to observe their cravings rather than acting on them.
The fundamental aspect of the technique is based on the ideology that **urges are temporary** (so real), they rise, peak and then eventually fade away, which is where the term **surfing** intuitively comes from.
## How Urge Surfing Works
Urge surfing relies on mindfulness, where we recognise the urge, observe it, then let it fade away.
The process can be broken down into three main steps:
### 1. **Recognising the Urge**
The first step is to *identify the urge* as it arises. This means paying close attention to bodily sensations, thoughts, and emotions that signal a craving. For example:
- A sudden tension in the stomach when craving sweets.
- Restlessness and an urge to check social media.
- A racing heart and a compulsion to lash out in anger.
Acknowledging the urge early gives you the power to observe it rather than be consumed by it (kind of wanted to link this to "The Observer and the Observed").
### 2. **Riding the Wave**
Once you recognise the urge, the next step is to **observe it without reacting**. Imagine the urge as a wave in the ocean. rather than fighting it, you ride it by:
- *Breathing deeply*: In other words, focussing on slow deep breaths to achor yourself in the present moment
- *Noticing sensations*: Where do you feel the urge? Is it in your chest, hands, or stomach?
- *Labeling the urge*: Mentally note, "This is just a craving," or "This is just an impulse." This helps you distance yourself from it
- *Practicing non-judgment*: Don't label the urge as good or bad. Just observe it as it rises and falls
### 3. **Letting It Fade Away**
With time, urges *naturally subside*. Like waves, they reach a peak and then fade away. The trick behind this is accepting that they come and go, and this gives you a much better control over your impulses.
## The Science Behind Urge Surfing
Now you might be thinking "Hey you just spouted a bunch of things but where is the scientific correlation???". Let's take a look at the science behind it:
- *The 90-Second Rule*: Neuroscientist **Dr. Jill Bolte Taylor** suggests that most emotional reactions last about 90 seconds. If we can *sit with an urge* for that duration, it often begins to dissipate.
- *Neuroplasticity*: Every time we resist an impulse instead of acting on it, we *weaken the neural pathways* associated with that habit. Over time, the urges become less intense.
- *The Prefrontal Cortex*: Self-control is governed by the prefrontal cortex, the rational part of our brain. Practicing urge surfing strengthens this area, which improves discipline.
![Urge Surfing Diagram](./assets/urge-surfing.png)
*Source: [Link](https://www.thenourishedpath.com/blog/eating-mindfully-urge-surfing)*
## Conclusion
Urge surfing is truly a powerful technique when mastered, not only does it allow you to control your urges without giving in, it also helps you to become more self-disciplined. If you are interested in learning more about this, I would recommend reading the book "The Science of Self-Discipline" by Peter Hollins.

View File

@@ -0,0 +1,86 @@
:PROPERTIES:
:ID: CD093B85-BF68-4EAB-AABE-733C7BFC99DE
:END:
#+title: wp-growth-mindset
#+filetags: :blogs:zzq:
# Building a Growth Mindset
By Zaine Qayyum
---
This topic is something that I've been wanting to talk about for a while, and the reason is because of how important it is as human beings to have this **growth mindset**. You might ask "why? what is the need when I can just have a fixed mindset?". The answer is simple: having a growth mindset is essential for personal and professional success. This is what I wanted to talk about in this blog, and I hope you find it useful!
## Table of Contents
1. [What Is a Growth Mindset?](#what-is-a-growth-mindset)
2. [Why Does a Growth Mindset Matter?](#why-does-a-growth-mindset-matter)
3. [How to Develop a Growth Mindset](#how-to-develop-a-growth-mindset)
4. [Final Thoughts](#final-thoughts).
## What Is a Growth Mindset?
The term *growth mindset* was introduced by psychologist **Dr. Carol Dweck** in her research on motivation and learning. It refers to the belief that our abilities, intelligence, and talents can be developed through **effort, learning, and persistence**. Take for example the muscles in our body, we develop them through repeated "reps" and consistent effort. The same applies to our intelligence, talents, and abilities; we can develop them through effort, learning, and persistence.
This contrasts with a **fixed mindset**, where people believe their intelligence and talents are static traits, they either "have it" or they dont.
### Growth Mindset vs. Fixed Mindset
| Growth Mindset | Fixed Mindset |
|---------------|--------------|
| Challenges are opportunities to grow | Challenges are threats to avoid |
| Failure is a stepping stone for learning | Failure defines intelligence and worth |
| Effort is the path to mastery | If you have to try, you're not naturally talented |
| Constructive criticism is valuable | Criticism is a personal attack |
| Inspired by others' success | Feels threatened by others' success |
## Why Does a Growth Mindset Matter?
The question now might arise, "why does a growth mindset matter?"
Having a growth mindset is **not just motivational jargon,** but it has real benefits, here are some of them:
- **Increases resilience:** People with a growth mindset are more likely to persist in the face of challenges, which ultimately allows you to grow in multiple ways.
- **Encourages continuous learning:** Lifelong learning is something so valued and desired (subject for another blog?), and a growth mindset goes hand in hand with it.
- **Boosts performance:** Research shows that students and professionals with a growth mindset perform better over time. This "performance" can be related to arbitrary things like academic success, job performance, or personal growth.
- **Improves relationships:** It helps people handle feedback better and build stronger connections with others.
## How to Develop a Growth Mindset
### 1. **Reframe Failure as Learning**
Instead of viewing failure as proof of inadequacy, see it as feedback. Ask yourself:
- *What can I learn from this?*
- *How can I approach this differently next time?*
The questions I always ask myself are "What did I do that went well?" and "What can I do differently next time?"
### 2. **Challenges should be embraced**
A common trap of a fixed mindset is avoiding challenges to protect your self-esteem. Instead:
- Take on **new projects** that push your abilities.
- Step outside your **comfort zone** regularly.
- Remind yourself: *Every expert was once a beginner*.
### 3. **Use "Yet" to Change Your Self Talk**
Pay attention to your inner dialogue (yes we all have one, even if we don't realise it). If you catch yourself saying:
> *"I'm not good at this."*
Reframe it to:
> *"I'm not good at this **yet**."*
This small change can shift your perspective from **impossibility to potential**.
### 4. **Value Effort Over Talent**
Society often glorifies natural talent, but effort is what leads to mastery. Instead of aiming to be "the best," focus on:
- Developing **discipline and consistency**.
- Tracking your **progress** rather than comparing yourself to others.
- Celebrating small wins along the way.
## Final Thoughts
A **growth mindset** isnt something you "get" overnight, it takes a while to cultivate. Its a daily practice. It requires self awareness, patience, and a willingness to embrace discomfort. But once achieved, it can take you to unimaginable heights.
I honestly feel as though the best thing that worked for me was shifting my mindset, being positive about the situations I am in and learning to embrace the now.
I hope this inspires you even in the slightest :)
---

View File

@@ -0,0 +1,95 @@
:PROPERTIES:
:ID: D02B89DC-84D0-4211-A902-B9399F4179CA
:END:
#+title: wp-emotional-intelligence
#+filetags: :blogs:zzq:
# How to Build Emotional Intelligence (EQ) for Better Relationships
Someone asked me a while ago "bro, do you think I have emotional intelligence?", and after having that conversation, I thought to myself "what exactly does *mean* to have emotional intelligence? Emotional Intelligence (EQ) is the ability to recognise, understand, and manage your own emotions, as well as the emotions of others. I wanted to write out this post so that this can be better understood and applied to our daily lives.
---
## What is Emotional Intelligence (EQ)?
Emotional Intelligence is often broken down into five key components:
1. **Self-Awareness**: Recognising and understanding your own emotions.
2. **Self-Regulation**: Managing and controlling your emotional reactions.
3. **Motivation**: Harnessing emotions to pursue goals with energy and persistence.
4. **Empathy**: Understanding and sharing the feelings of others.
5. **Social Skills**: Building and maintaining healthy relationships through effective communication and conflict resolution.
Knowledge is of little use if not applied. These five components, one can say, are the building blocks for EQ.
---
## Why EQ Matters in Relationships
Relationships depend on emotional connection. Whether its with a partner, family member, friend, or colleague, EQ helps you:
- Communicate more effectively.
- Resolve conflicts constructively.
- Build trust and intimacy.
- Understand and meet the emotional needs of others.
Without emotional intelligence, you may not be able to *understand* the emotions of others, which can ultimately lead to conflicts.
---
## How to Build Emotional Intelligence for Better Relationships
Based on the 5 components of EQ, here are practical steps to develop your EQ and strengthen your relationships:
### **Self-Awareness**
- **Reflect on Your Emotions**: Take time each day to identify and label your emotions. Ask yourself, “What am I feeling right now, and why?”
- **Journal**: Writing about your emotions can help you process them and identify patterns in your reactions.
- **Seek Feedback**: Ask friends or family members how they perceive your emotional responses. This can provide valuable insights into blind spots.
### **Self-Regulation**
- **Pause Before Reacting**: When you feel a strong emotion, take a deep breath and give yourself a moment to respond thoughtfully rather than reacting impulsively.
- **Practice Stress Management**: Techniques like meditation, exercise, or deep breathing can help you stay calm in emotionally charged situations.
- **Set Boundaries**: Learn to say no and manage your emotional energy to avoid depletion.
### **Empathy**
- **Listen Actively**: Pay full attention when someone is speaking. Focus on their words, tone, and body language without interrupting or planning your response. There is a huge difference between active listening and passive listening.
- **Put Yourself in Their Shoes**: Try to understand the other persons perspective, even if you dont agree with it.
- **Validate Their Feelings**: Acknowledge their emotions by saying things like, “I understand why youd feel that way.”
### **Social Skills**
- **Communicate Clearly**: Use “I” statements to express your feelings without blaming others (e.g., “I feel upset when…”).
- **Practice Conflict Resolution**: Approach disagreements with a problem solving mindset rather than a confrontational one. Remember its you and them versus the problem, not each other!
- **Show Appreciation**: Regularly express gratitude and appreciation for the people in your life.
### **Motivation**
- **Set Personal Goals**: Identify what you want to achieve in your relationships and take steps to work toward those goals.
- **Stay Positive**: Focus on the good in your relationships and maintain a hopeful outlook, even during challenging times.
---
## Real-Life Examples of EQ in Action
There are many practical examples of EQ in action in our daily lives. Take work as an example, if you notice your colleague a little stressed, offer them support and ask if they need help! Not only will they feel grateful that they're being seen, you'll also strengthen your professional relationship with said colleague. Another one is in a platonic relationship, when a friend shares a problem, listen without judgement and offer empathy.
---
## The Long-Term Benefits of High EQ
Building emotional intelligence is a lifelong journey, but the rewards are immense. Over time, youll notice:
- Stronger, more meaningful relationships.
- Improved communication.
- Greater resilience in the face of challenges.
- A deeper understanding of yourself and others.
- Being able to actively listen to others.
---
## Final Thoughts
This whole thought and discussion stemmed from that single question. I find myself becoming more intrigued in the intricacies of relationships and human interaction. EQ is one of those components that make up a considerable portion of how we interact with others, without which relationships would become stale. Thank you for reading :)
---
*“Emotional intelligence is the key to both personal and professional success.” Daniel Goleman*

View File

@@ -0,0 +1,9 @@
:PROPERTIES:
:ID: 8CD2F4C4-22C2-4ECC-8F5F-C4779F8AC0F1
:END:
#+title: wp-week-12-reflection
#+filetags: :blogs:zzq:
# Week 12 reflections
12 out of the 52 weeks are now completed (following the [ISO-8601](https://en.wikipedia.org/wiki/ISO_8601)), and I guess this blog post will be a little different from the usual *information-centric* posts. 12 weeks having passed from this year means there's only 9 months left of 2025, and i've come to realise that time is moving *quick*. The question then arose, "how can I maximise the time that I have?", the answer to which isn't as simple as one may think. Albeit this, let's take a look at one particularly useful equation that may serve as a guide to modelling the value of time:

View File

@@ -0,0 +1,9 @@
:PROPERTIES:
:ID: ae343652-96fe-4341-8a36-ec3a1abd0dc6
:END:
#+title: java_moc
#+filetags: :moc:java:
Use this node for pom.xml: [[id:bcd41e87-120c-455c-8898-996ddaa41f75][maven-pom-file]]
Tests: [[id:7b8de14c-a73e-4c92-a403-a9a1c419c0b3][java-junit-testing]]

View File

@@ -0,0 +1,16 @@
:PROPERTIES:
:ID: 462F091B-9156-48B3-8665-0BE36C95C182
:END:
#+title: wp-sadness
#+filetags: :zzq:blogs:
Emotions. We all feel them on a daily basis. Happiness, anger, sadness, fear and disgust. They come and they go, sometimes for a long duration, and at other times merely for a few seconds. Sadness in particular is an interesting emotion; I say this for two reasons: the first is that it reminds us of what matters to us, and the second is that it makes you realise things about yourself that you never knew of before. Sadness is something that honestly makes you step out of your own body and view things in a different light, you become more perceptive despite the phyiscal and mental tang you feel. Should we strive to stop feeling sad? Who knows, some may say it's a part of who we are, others may counter and say that it's not a desired emotion. Regardless, we all have felt it at some point in our lives; the quantity of which varies across people, for some, it could be very minute and for some very large.
> "Some psychologists argue that sadness plays an evolutionary role—it slows us down, forces us to think, to reflect, to re-evaluate our priorities. Its the brains way of making us pause, take stock, and reorient ourselves."
There comes that word: *pause*. How important is it to sometimes just pause and reflect, to ponder over life and the things happening around us. When was the last time we sat in silence with no distractions, no phones, no people, nothing. We learn a lot when we tune in to our emotions, despite how much sadness may heart, and how much it makes us want to cry, we should always remember that this same sadness adds value to the happy moments in life. Like shadows on a painting, it gives dimension to our emotional world.
It reminds me of this verse in the noble Quran: فَإِنَّ مَعَ ٱلْعُسْرِ يُسْرًا which means: "So, surely with hardship comes ease." The hardship we face in life always has a positive aspect to it, sometimes we become too blinded and short sighted by the trials and tribulations that we forget to look at it from another angle.
Anyways I'll end this with this poetic touch:
> "Sadness doesnt shout. It whispers. It sits beside you in silence. It tugs at your sleeve when the world moves too fast. And in that quiet tug, you find pieces of yourself you forgot existed."

View File

@@ -0,0 +1,69 @@
:PROPERTIES:
:ID: bcd41e87-120c-455c-8898-996ddaa41f75
:END:
#+title: maven-pom-file
#+filetags: :guide:java:
* Doc Link
- [[https://maven.apache.org/guides/getting-started/maven-in-five-minutes.html][Link to apache doc]]
* Example of pom.xml
#+begin_src xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany.app</groupId>
<artifactId>my-app</artifactId>
<version>1.0-SNAPSHOT</version>
<name>my-app</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.release>17</maven.compiler.release>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>5.11.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<!-- Optionally: parameterized tests support -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
... lots of helpful plugins
</pluginManagement>
</build>
</project>
#+end_src
* Commands:
*FOR TESTING*
#+begin_src bash
mvn clean test
#+end_src
*COMPILING*
#+begin_src bash
mvn compile
#+end_src

View File

@@ -0,0 +1,8 @@
:PROPERTIES:
:ID: 0880f089-a5ad-49cd-8ce3-f020a5941313
:END:
#+title: Networking MOC
#+filetags: :moc:networking:
- [[id:99533f2d-a4e8-41d0-a605-c7d4cef6f995][self_hosting]]

View File

@@ -0,0 +1,21 @@
:PROPERTIES:
:ID: 086ca3ca-39ec-4d37-b56d-b6d9f51e6873
:END:
#+title: how-to-solve-leetcode
#+filetags: :leetcode:notes:
* Process:
- Read the problem twice to understand it
- Try think basically of different ways to solve the problem
- Think end-to-end (e2e) of the best solutions based on complexity
- Write the algorithm from patterns in drawing
- Code it out
- Try and improve it once you think you're finished
- Go through other solutions

View File

@@ -0,0 +1,351 @@
:PROPERTIES:
:ID: 93a43a24-6861-40c4-b45b-581977bb55cf
:END:
#+title: leetcode-arrays
#+filetags: :leetcode:notes:
* 217 - Contains Duplicate:
Given an integer array `nums`, return `true` if any value appears at least twice in the array, and return false if every element is distinct.
*Example 1:*
Input: nums = [1,2,3,1]
Output: true
Explanation: The element 1 occurs at the indices 0 and 3.
*Example 2:*
Input: nums = [1,2,3,4]
Output: false
Explanation: All elements are distinct.
*Example 3:*
Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true
*Constraints:*
1 <= nums.length <= 105
-109 <= nums[i] <= 109
** Attempt:
Two loops
Outer loop will go through each element, inner loop will check if the element in outer loop is repeated in the array.
#+begin_src python
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
for i in nums:
for j in nums[i:len(nums)]:
if i == j:
return True
return False
#+end_src
Works? Yes, but there is a better solution
** Solution:
Use a [[id:3a41407c-661e-416a-80d2-4c7a137d153a][python-set]]. The reason is it does not allow for duplicates (it is unique). The solution is as follows:
We create a set from the array, then check if the length of the two are different, if they are then this indicates that there are duplicate values in the array. This is O(N) and is faster than the nested loops solution above.
#+begin_src python
if len(set(nums)) == len(nums):
return False
else:
return True
#+end_src
* 268 - Missing Number
Given an array `nums` containing `n` distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
Example 1:
Input: nums = [3,0,1]
Output: 2
Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums.
Example 2:
Input: nums = [0,1]
Output: 2
Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums.
Example 3:
Input: nums = [9,6,4,2,3,5,7,0,1]
Output: 8
Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums.
Constraints:
n == nums.length
1 <= n <= 104
0 <= nums[i] <= n
All the numbers of nums are unique.
Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?
** Attempt
Sort the array, loop through it and check via the incrementor
#+begin_src python
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
for i in range(0, len(nums) + 1):
if i not in nums:
return i
#+end_src
Problem here is that sort operation is O(nlogn) - too slow.
** Solution
One optimised solution:
#+begin_src python
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
n = len(nums)
total_sum = n * (n + 1) // 2
actual_sum = sum(nums)
return total_sum - actual_sum
#+end_src
Another:
#+begin_src python
class Solution(object):
def missingNumber(self, nums):
return sum(range(len(nums) + 1)) - sum(nums)
#+end_src
This is O(N)
len = O(1)
Range object creation is O(1)
sum is O(N)
+1 in range(n) because n would be excluded otherwise. ie if you did range(2) you get [0,1]
Some extra notes:
[[id:125c81dc-c14f-4b4d-93c6-0a2b157735ac][python-dictionary]]
* 448 - Find all Numbers disappeared in an array
Given an array `nums` of `n` integers where `nums[i]` is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums.
Example 1:
Input: nums = [4,3,2,7,8,2,3,1]
Output: [5,6]
Example 2:
Input: nums = [1,1]
Output: [2]
Constraints:
n == nums.length
1 <= n <= 105
1 <= nums[i] <= n
Follow up: Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
** Attempt
Create a set, loop through the set (it wont have duplicate values), if the counter is not equal to the value in the set, add it to a new list.
#+begin_src python
class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
new_set = set(nums)
print(new_set)
new_list = []
for i in range(1, len(nums) + 1):
if i not in new_set:
new_list.append(i)
return new_list
#+end_src
Time: O(N) as iterating through the range and appending to new list if not in given list. O(N) space.
* 1 - Two Sum
Given an array of integers `nums` and an integer `target`, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
Constraints:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.
Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?
** Attempt
Outer loop and inner loop
#+begin_src python
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
ret = []
for i in range(0, len(nums) ):
for j in range(i + 1, len(nums) ):
if nums[i] + nums[j] == target:
ret.append(nums[i])
ret.append(nums[j])
return ret
#+end_src
Bad as its O(N^2)
** Solution
Use a hashmap and loop once
After looking through the logic:
#+begin_src python
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hm = {}
ret = []
for i in range(0, len(nums)):
if (target - nums[i]) not in hm:
hm.update({nums[i]: i})
else:
ret.append(i)
ret.append(hm.get(target - nums[i]))
return ret
#+end_src
[[~/master-folder/org_files/org_roam/assets/swappy-20250805-152411.png]]
Youtube solution:
#+begin_src python
hash_map = {}
for i , v in enumerate(nums):
if target - v in hash_map:
return i, hash_map[target - v]
else:
hash_map[v] = i
#+end_src
#+begin_src python
hashMap = {}
for indx, val in enumerate(nums):
diff = target - val
if diff in hashMap:
return [indx, hashMap[diff]]
hashMap[val] = indx
#+end_src
* 1365 - How Many Numbers Are Smaller Than the Current Number
Given the array `nums`, for each `nums[i]` find out how many numbers in the array are smaller than it. That is, for each `nums[i]` you have to count the number of valid j's such that j != i and nums[j] < nums[i].
Return the answer in an array.
Example 1:
Input: nums = [8,1,2,2,3]
Output: [4,0,1,1,3]
Explanation:
For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3).
For nums[1]=1 does not exist any smaller number than it.
For nums[2]=2 there exist one smaller number than it (1).
For nums[3]=2 there exist one smaller number than it (1).
For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).
Example 2:
Input: nums = [6,5,4,8]
Output: [2,1,0,3]
Example 3:
Input: nums = [7,7,7,7]
Output: [0,0,0,0]
Constraints:
2 <= nums.length <= 500
0 <= nums[i] <= 100
#+begin_src python
def smallerNumbersThanCurrent(nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
temp = sorted(nums)
d = {}
for i, num in enumerate(temp):
if num not in d:
d[num] = i
ret = []
for i in nums:
ret.append(d[i])
return ret
#+end_src

View File

@@ -0,0 +1,27 @@
:PROPERTIES:
:ID: 3a41407c-661e-416a-80d2-4c7a137d153a
:END:
#+title: python-set
#+filetags: :python:notes:
Sets are used to store multiple items in a single variable.
Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Tuple, and Dictionary, all with different qualities and usage.
A set is a collection which is unordered, unchangeable*, and unindexed.
*Note: Set items are unchangeable, but you can remove items and add new items.
Sets are written with curly brackets.
Example:
#+begin_src python
# Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)
#+end_src
Notes:
Sets are fast, Note that empty Set cannot be created through {}, it creates a dictionary, unless you include values.
set is implemented as a hash table, so you can expect lookup, insert, delete to be O(1) on average.

View File

@@ -0,0 +1,99 @@
:PROPERTIES:
:ID: 125c81dc-c14f-4b4d-93c6-0a2b157735ac
:END:
#+title: python-dictionary
#+filetags: :python:notes:
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
*As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.
Dictionaries are written with curly brackets, and have keys and values:
#+begin_src python
# Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
#+end_src
Iterating:
Iterate through Value
To iterate through all values of a dictionary in Python using .values(), you can employ a for loop, accessing each value sequentially. This method allows you to process or display each individual value in the dictionary without explicitly referencing the corresponding keys.
Example: In this example, we are using the values() method to print all the values present in the dictionary.
#+begin_src python :results output
# create a python dictionary
d = {"name": "Geeks", "topic": "dict", "task": "iterate"}
# loop over dict values
for val in d.values():
print(val)
#+end_src
Iterate through keys
In Python, just looping through the dictionary provides you its keys. You can also iterate keys of a dictionary using built-in `.keys()` method.
#+begin_src python :results output
# create a python dictionary
d = {"name": "Geeks", "topic": "dict", "task": "iterate"}
# default loooping gives keys
for keys in d:
print(keys)
# looping through keys
for keys in d.keys():
print(keys)
#+end_src
Iterate through both keys and values
You can use the built-in items() method to access both keys and items at the same time. items() method returns the view object that contains the key-value pair as tuples.
#+begin_src python :results output
# create a python dictionary
d = {"name": "Geeks", "topic": "dict", "task": "iterate"}
# iterating both key and values
for key, value in d.items():
print(f"{key}: {value}")
#+end_src
Sorting:
Lambda function accesses the key (item[0]) during sorting. It offers flexibility if you want to tweak the sorting logic later.
#+begin_src python :results output
import operator
a = {"Gfg": 5, "is": 7, "Best": 2, "for": 9, "geeks": 8}
res = dict(sorted(a.items(), key=lambda item: item[0]))
print(res)
#+end_src
#+RESULTS:
: {'Best': 2, 'Gfg': 5, 'is': 7, 'geeks': 8, 'for': 9}
Explanation: `lambda item: item[0]` sorts the dictionary by the first element of each tuple (the key).
[[id:3bbc6099-0187-4bf2-9282-97e5fa443f72][python-sorted-function]]
[[id:9d534e89-7f0b-494c-bff6-7b3be05b85d1][python-lambda]]

View File

@@ -0,0 +1,21 @@
:PROPERTIES:
:ID: 3bbc6099-0187-4bf2-9282-97e5fa443f72
:END:
#+title: python-sorted-function
#+filetags: :python:notes:functions:
Syntax
*sorted(iterable, key=key, reverse=reverse)*
Parameter Values
+-----------+---------------------------------------------------------------------------------------------+
| Parameter | Description |
+-----------+---------------------------------------------------------------------------------------------+
| iterable | Required. The sequence to sort, list, dictionary, tuple etc. |
+-----------+---------------------------------------------------------------------------------------------+
| key | Optional. A Function to execute to decide the order. Default is None |
+-----------+---------------------------------------------------------------------------------------------+
| reverse | Optional. A Boolean. False will sort ascending, True will sort descending. Default is False |
+-----------+---------------------------------------------------------------------------------------------+

View File

@@ -0,0 +1,36 @@
:PROPERTIES:
:ID: 9d534e89-7f0b-494c-bff6-7b3be05b85d1
:END:
#+title: python-lambda
#+filetags: :python:notes:functions:
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.
Syntax:
*lambda arguments : expression*
The expression is executed and the result is returned:
#+begin_src python :results output
# Add 10 to argument a, and return the result:
x = lambda a : a + 10
print(x(5))
# Multiply argument a with argument b and return the result:
y = lambda a, b : a * b
print(y(5, 6))
# Summarize argument a, b, and c and return the result:
z = lambda a, b, c : a + b + c
print(z(5, 6, 2))
#+end_src
#+RESULTS:
: 15
: 30
: 13