> This is part 1 of 4 of the full documentation (pages 1–100 of 341).
> The content is paginated: fetch every part to see all of it.
> Next part: https://digitalgarden.batamladen.com/llms-full.txt/1
> Page index: https://digitalgarden.batamladen.com/llms.txt

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
This site has an agentic ask interface you may use to query the documentation dynamically by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://digitalgarden.batamladen.com/index.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

---

# Welcome

**Hey 👋🏼 My name is Mladen.**\
These are my public notes on cybersecurity, privacy, programming and the IT sphere in general. This space also serves as a personal track for the machines and CTFs I’ve completed. ( *+ virtual bookshelf page is in progress!*)

Besides finishing my master's degree, I teach kids Scratch and Python, helping them take their first steps into programming.<br>

**Here are some spaces that you might be interested in:**

<table data-view="cards"><thead><tr><th data-type="content-ref"></th></tr></thead><tbody><tr><td><a href="https://digitalgarden.batamladen.com/notes/">Notes</a></td></tr><tr><td><a href="https://digitalgarden.batamladen.com/writeups/">WriteUps</a></td></tr><tr><td><a href="https://digitalgarden.batamladen.com/bookshelf/">Bookshelf</a></td></tr><tr><td><a href="https://digitalgarden.batamladen.com/articles/">Articles</a></td></tr></tbody></table>


# Intro

## Notes

This space is created to be a second brain :brain: for the things I am learning, so I can come back here and remind myself about a certain topic if I need to.

The whole point of this notes is to keep things simple and understandable for me and hopefully for someone else as well.

Sharing the things I'm learning.

{% hint style="info" %}
I have taken this notes based on my own understandings and there might be something that I did not fully understand. Do not use the information here for any illegal activities, this is only for educational purpose.
{% endhint %}

***

#### Check out my other projects and content about things I am passionate about below😄

<img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2Fgxk1tRiSCjNYkDzcRgai%2Ficon.png?alt=media&amp;token=b5bb8761-d283-42e6-a351-a6604705a02f" alt="" data-size="line">  [**Armadillo**](https://github.com/batamladen/Armadillo) - An Encryption App

<img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FL6NJI0jdVlM90NaAtOMO%2Finstagram%20(1).png?alt=media&amp;token=c8745823-54ed-4849-9c3a-4e603f3ef2f4" alt="" data-size="line"> [**PythonHub**](https://www.instagram.com/_python_hub/) **-** Instagram Page

:robot: [**Webort**](https://batamladen.github.io/Webort/index.html) - Portfolio Website Generator

***

## **Social**

[Linkedin](https://www.linkedin.com/in/mladen-nikolov-1b4720200/) <img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FkSutgEHh4sdtlanmL8nD%2Fimage.png?alt=media&amp;token=14ed6a3a-99fc-4c3b-b8e9-0aa2173f5359" alt="" data-size="line">

[GitHub](https://github.com/batamladen) <img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2F25rz7FfH0gy4F4YLiRrh%2Fimage.png?alt=media&amp;token=8ca9a91c-16ad-48f6-bf90-46e80e59e9bd" alt="" data-size="line">

[Instagram](https://www.instagram.com/bata_mladen/) <img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FDjK8ZFkwze3ODCnYDfZE%2Fimage.png?alt=media&amp;token=04d215a9-8306-4651-ba3a-bb02771b99ca" alt="" data-size="line">


# DNS

Domain Name System

## **What is DNS**

DNS (Domain Name System) plays a crucial role in how the internet functions. The DNS allows us to search for domain names like [www.facebook.com](http://www.facebook.com) and reach the web servers that the hosting provider has assigned the IP address.

With DNS we do not have to remember all the IP addresess for our favorite sites. Its a lot easier to remember the names, that is why DNS is so important.

{% hint style="success" %}
Defnition:\
DNS is a system for resolving computer names into IP addresses, and it does not have a central database.
{% endhint %}

Its like a big phone book where the information is distributed over thousand of name servers globally placed.

### Types of DNS

There are several types of DNS servers used worldwide:

* DNS root server
* Authoritative name server
* Non-authoritative name server
* Caching server
* Forwarding server
* Resolver

<table><thead><tr><th width="192">Server Type</th><th>Description</th></tr></thead><tbody><tr><td>DNS Root Server</td><td>The root servers of the DNS are responsible for the top-level domains (TLD) such as .com, .net... As the last instance, they are only requested if the name server does not respond. Thus, a root server is a central interface between users and content on the Internet, as it links domain and IP address. There are 13 such root servers around the globe.</td></tr><tr><td>Authoritative Nameserver</td><td>Authoritative name servers hold authority for a particular zone. They only answer queries from their area of responsibility, and their information is binding. If an authoritative name server cannot answer a client's query, the root name server takes over at that point.</td></tr><tr><td>Non-authoritative Nameserver</td><td>Non-authoritative name servers are not responsible for a particular DNS zone. Instead, they collect information on specific DNS zones themselves, which is done using recursive or iterative DNS querying.</td></tr><tr><td>Caching DNS Server</td><td>Caching DNS servers cache information from other name servers for a specified period. The authoritative name server determines the duration of this storage.</td></tr><tr><td>Forwarding Server</td><td>Forwarding servers perform only one function: they forward DNS queries to another DNS server.</td></tr><tr><td>Resolver</td><td>Resolvers are not authoritative DNS servers but perform name resolution locally in the computer or router.</td></tr></tbody></table>

The DNS does not only store information about the IP address conected to the domain name, but can hold information such as, what is the host that is served as the email server for this specific domain name. Or what is the name of the host

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FLz3fNtZnHeCOiQKL2WYT%2FUntitled.png?alt=media&amp;token=dc1bfbe2-1d60-4b05-82cf-f3782c9a5ef9" alt=""><figcaption></figcaption></figure>

DNS is mainly unencrypted. Devices on the local WLAN and Internet providers can therefore hack in and spy on DNS queries. Since this poses a privacy risk, there are now some solutions for DNS encryption. By default, IT security professionals apply `DNS over TLS` (`DoT`) or `DNS over HTTPS` (`DoH`) here. In addition, the network protocol `DNSCrypt` also encrypts the traffic between the computer and the name server.

### **records of a DNS setting:**

<table><thead><tr><th width="142">DNS Record</th><th>Description</th></tr></thead><tbody><tr><td>A</td><td>Returns an IPv4 address of the requested domain as a result.</td></tr><tr><td>AAAA</td><td>Returns an IPv6 address of the requested domain.</td></tr><tr><td>MX</td><td>Returns the responsible mail servers as a result.</td></tr><tr><td>NS</td><td>Returns the DNS servers (nameservers) of the domain.</td></tr><tr><td>TXT</td><td>This record can contain various information. The all-rounder can be used, e.g., to validate the Google Search Console or validate SSL certificates. In addition, SPF and DMARC entries are set to validate mail traffic and protect it from spam.</td></tr><tr><td>CNAME</td><td>This record serves as an alias. If the domain www.hackthebox.eu should point to the same IP, and we create an A record for one and a CNAME record for the other.</td></tr><tr><td>PTR</td><td>The PTR record works the other way around (reverse lookup). It converts IP addresses into valid domain names.</td></tr><tr><td>SOA</td><td>Provides information about the corresponding DNS zone and email address of the administrative contact.</td></tr></tbody></table>

### get info for dns nzm

```bash
dig soa www.inlanefreight.com

```

***

## **Default Config**

### **All DNS servers work with three different types of configuration files:**

1. local DNS configuration files
2. zone files
3. reverse name resolution files

### look local DNS configuration on a bind9 server

```bash
root@bind9# cat /etc/bind/named.conf.local
root@bind9# cat /etc/bind/db.domain.com
```

### reverse name resolution zone file

```bash
root@bind9:~# cat /etc/bind/db.10.129.14
```

***

## **Dangerous Settings**

<table><thead><tr><th width="167">Options</th><th>Description</th></tr></thead><tbody><tr><td>allow-query</td><td>Defines which hosts are allowed to send requests to the DNS server.</td></tr><tr><td>allow-recursion</td><td>Defines which hosts are allowed to send recursive requests to the DNS server.</td></tr><tr><td>allow-transfer</td><td>Defines which hosts are allowed to receive zone transfers from the DNS server.</td></tr><tr><td>zone-statistics</td><td>Collects statistical data of zones.</td></tr></tbody></table>

***

## **Footprinting**

The footprinting at DNS servers is done as a result of the requests we send. So, first of all, the DNS server can be queried as to which other name servers are known. We do this using the NS record and the specification of the DNS server we want to query using the `@` character. This is because if there are other DNS servers, we can also use them and query the records. However, other DNS servers may be configured differently and, in addition, may be permanent for other zones.

### dig NS query

```
dig ns inlanefreight.htb @10.129.14.128
```

### dig version query

```
dig CH TXT version.bind 10.129.120.85
```

### view all available records

```
dig any inlanefreight.htb @10.129.14.128
```

{% hint style="warning" %} <mark style="color:orange;">**Note:**</mark> We can use the option `ANY` to view all available records. This will cause the server to show us all available entries that it is willing to disclose. It is important to note that not all entries from the zones will be shown.
{% endhint %}

### DIG - AXFR Zone Transfer

```
dig axfr inlanefreight.htb @10.129.14.128
```

### DIG - AXFR Zone Transfer - Internal

```
dig axfr internal.inlanefreight.htb @10.129.14.128
```

The individual `A` records with the hostnames can also be found out with the help of a brute-force attack. To do this, we need a list of possible hostnames, which we use to send the requests in order. Such lists are provided, for example, by [SecLists](https://github.com/danielmiessler/SecLists/blob/master/Discovery/DNS/subdomains-top1million-5000.txt).

An option would be to execute a `for-loop` in Bash that lists these entries and sends the corresponding query to the desired DNS server.

### bash script for Subdomain Brute Forcing

```bash
for sub in $(cat /opt/useful/SecLists/Discovery/DNS/subdomains-top1million-110000.txt);do dig $sub.inlanefreight.htb @10.129.14.128 | grep -v ';\|SOA' | sed -r '/^\s*$/d' | grep $sub | tee -a subdomains.txt;done
```

Many different tools can be used for this, and most of them work in the same way. One of these tools is, for example [DNSenum](https://github.com/fwaeytens/dnsenum).

### DNSenum usage

```
dnsenum --dnsserver 10.129.14.128 --enum -p 0 -s 0 -o subdomains.txt -f /opt/useful/SecLists/Discovery/DNS/subdomains-top1million-110000.txt inlanefreight.htb
```

{% hint style="warning" %} <mark style="color:orange;">**note:**</mark> for host brute forcing we can use the /home/kali/Downloads/SecList/Discovery/DNS/fience-host.txt file
{% endhint %}


# Oracle TNS

(Oracle Transparent Network Substrate)

Port: 1521,1522 (can be changed)

***

## **About**

The **Oracle Transparent Network Substrate** (TNS) server is a communication protocol that facilitates communication between Oracle databases and applications over networks.

TNS supports various networking protocols between Oracle databases and client applications, such as `IPX/SPX` and `TCP/IP` protocol stacks.

It is a popular opinion in managing large and complex databases. In addition to the security it has a encryption mechanism ensuringing security of the data transmitted. Over time, TNS has been updated to support newer technologies, including `IPv6` and `SSL/TLS` encryption

Oracle TNS is often used with other Oracle services like Oracle DBSNMP, Oracle Databases, Oracle Application Server, Oracle Enterprise Manager, Oracle Fusion Middleware, web servers, and many more.

***

## **Footprinting**

The TNS inclued a few basic security futures such as username/password authentication, and the listener will use Oracle Net Services to encrypt the communication between the client and the server.

The configuration files for TNS are tnsnames.ora and listener.ora. which are tippicaly located in `$ORACLE_HOME/network/admin`.

**tnsnames.ora** file contains the necessary information for clients to connect to the service.

**listener.ora** file is a server-side configuration file that defines the listener process's properties and parameters, which is responsible for receiving incoming client requests and forwarding them to the appropriate Oracle database instance.

In short, the client-side Oracle Net Services software uses the `tnsnames.ora` file to resolve service names to network addresses, while the listener process uses the `listener.ora` file to determine the services it should listen to and the behavior of the listener.

The oracle databases can be protected by using a so called  so-called PL/SQL Exclusion List (PlsqlExclusionList). Whitch is basically a user-defined blacklist that needs to be placed in $ORACLE\_HOME/sqldeveloper.

***

### **Vulnerabilities**

There have been made many changes for the default installation of Oracle services. For example, Oracle 9 has a default password, `CHANGE_ON_INSTALL`, whereas Oracle 10 has no default password set. The Oracle DBSNMP service also uses a default password, `dbsnmp`. Another example would be that many organizations still use the `finger` service together with Oracle, which can put Oracle's service at risk and make it vulnerable when we have the required knowledge of a home directory.

A nice to have tool for Oracle TNS is ODAT (Oracle Database Attacking Tool), a pentest enumeration tool for oracle databases.

Here is a nice lil bash script to download the ODAT

```python
#!/bin/bash

sudo apt-get install libaio1 python3-dev alien -y
git clone https://github.com/quentinhardy/odat.git
cd odat/
git submodule init
git submodule update
wget https://download.oracle.com/otn_software/linux/instantclient/2112000/instantclient-basic-linux.x64-21.12.0.0.0dbru.zip
unzip instantclient-basic-linux.x64-21.12.0.0.0dbru.zip
wget https://download.oracle.com/otn_software/linux/instantclient/2112000/instantclient-sqlplus-linux.x64-21.12.0.0.0dbru.zip
unzip instantclient-sqlplus-linux.x64-21.12.0.0.0dbru.zip
export LD_LIBRARY_PATH=instantclient_21_12:$LD_LIBRARY_PATH
export PATH=$LD_LIBRARY_PATH:$PATH
pip3 install cx_Oracle
sudo apt-get install python3-scapy -y
sudo pip3 install colorlog termcolor pycrypto passlib python-libnmap
sudo pip3 install argcomplete && sudo activate-global-python-argcomplete
```

***

### Enumeration

nmap scan&#x20;

```bash
sudo nmap -p1521 -sV 10.129.204.235 --open
```

nmap scan with NDE script&#x20;

```bash
sudo nmap -p1521 -sV 10.129.204.235 --open --script oracle-sid-brute
```

usage of ALL modules from odat tool&#x20;

```bash
./odat.py all -s 10.129.204.235
```

To connect to a oracle sql we use SQL Plus. Here is the syntax for connecting using sqlplus:

```sh
sqlplus username/password@ip_address/SID
```

***

**To navigate through a database we will need to know some commands:**

[Database SQL Language Quick Reference](https://docs.oracle.com/cd/E11882_01/server.112/e41085/sqlqraa001.htm#SQLQR985)


# FTP


# SMB


# Routing Protocols

Routing is one of the most fundamental areas of networking that an administrator has to know. Routing protocols determine how your data gets to its destination and helps to make that routing process as smooth as possible. However, there are so many different types of routing protocol that it can be very difficult to keep track of them all!

Routing protocols can be split in 2 categories:

* [Dynamic](/notes/services/routing-protocols/dynamic)
* [Static](/notes/services/routing-protocols/static)


# Dynamic

Dynamic routing protocols, as their name suggests, are used to dynamically exchange routing information between routers. Their implementation allows network topologies to dynamically adjust to changing network conditions, and to ensure that efficient and redundant routing continues in spite of any changes.

{% hint style="success" %}
**Definition:**\
Dynamic routing is a mechanism through which routing information is exchanged between routers to determine the optimal path between network devices. A routing protocol is used to identify and announce network paths.
{% endhint %}

Compared to statically configuring routing in topology, the implementation of dynamic routing protocols vastly improves the scalability of networks.

The first dynamic routing protocol was the [Exterior Gateway Protocol (EGP)](/notes/services/routing-protocols/dynamic/egp)

***

## Dynamic protocols categories:

* [Interior Gateway Protocol (IGP)](/notes/services/routing-protocols/dynamic/igp)
* [Exterior Gateway Protocol (EGP)](/notes/services/routing-protocols/dynamic/egp)


# IGP

**IGPs** are routing protocols that exchange routing information with other routers within a single autonomous system (AS). An AS is defined as one network or a collection of networks under the control of one enterprise.

All the IGP protocols can be classified into the following:

* [Distance Vector](/notes/services/routing-protocols/dynamic/igp/distance-vector)
* [Link-State](/notes/services/routing-protocols/dynamic/igp/link-state)
* [Hybrid](/notes/services/routing-protocols/dynamic/igp/hybrid)


# Distance Vector

Metric: Hop Count

All routing protocols use an algorithm or set of algorithms to calculate and distribute routing information.&#x20;

A distance vector protocol (DVP) is a dynamic routing protocol that uses an algorithm based on the work of Bellman, Ford, and Fulkerson known as **vector distance** or the Bellman-Ford algorithm.&#x20;

Distance Vector protocols are:

* [RIP](/notes/services/routing-protocols/dynamic/igp/distance-vector/rip)
* [IGRP](/notes/services/routing-protocols/dynamic/igp/distance-vector/igrp)

The idea behind the DVP algorithm is that each router on the network (routing domain or process) compiles a list of the networks it can reach and sends the list to their directly connected neighbors. \
The routers then create routing tables based on what they can reach directly and indirectly, using their neighbor routers as gateways. If multiple paths exist, the router only keeps the best one. This route is chosen based on the protocol's particular metric for determining the best route. Routing protocols each use different route metrics to choose the best route.

***

## Pros & Cons

### <mark style="color:green;">Pros:</mark>

**Distance Vector Routing Protocols** offer simplicity and ease of implementation, making them ideal for smaller networks or those with limited administrative expertise. These protocols require less router resources, making them suitable for hardware-constrained devices.&#x20;

### <mark style="color:red;">Cons:</mark>

However, they suffer from slower convergence times compared to[ link-state protocols](/notes/services/routing-protocols/dynamic/igp/link-state), as routing updates are exchanged periodically and must propagate throughout the network. Additionally, their reliance on hop count as the primary metric can lead to routing loops and scalability challenges in larger and more complex networks. Despite these limitations, distance vector protocols remain a viable option for simple network setups where ease of configuration outweighs scalability concerns.

<table data-view="cards"><thead><tr><th></th><th></th></tr></thead><tbody><tr><td><mark style="color:green;"><strong>Pros:</strong></mark></td><td><ul><li>Simplicity</li><li>Ease of Implementation</li><li>Low Router Resource Consumption</li></ul></td></tr><tr><td><mark style="color:red;">Cons:</mark></td><td><ul><li>Slow Convergence</li><li>Routing Loops</li><li>Count-to-Infinity Problem</li></ul></td></tr></tbody></table>


# RIP

## **What is RIP?**

**Routing Information Protocol** (RIP) is a dynamic routing protocol that uses hop count as a routing metric to find the best path between the source and the destination network. It is a distance-vector routing protocol that  works on the Network layer of the OSI model. \
RIP uses port number 520. <br>

### **Hop Count**&#x20;

Hop count is the number of routers occurring in between the source and destination network. The path with the lowest hop count is considered as the best route to reach a network and therefore placed in the routing table. RIP prevents routing loops by limiting the number of hops allowed in a path from source and destination. The maximum hop count allowed for RIP is 15 and a hop count of 16 is considered as network unreachable.&#x20;

***

## Commands:


# IGRP


# Link-State

Metric: Cost

## What is Link-State?

Link state protocols (LSPs) are based on a different algorithm than DVPs. LSPs are based on a graph theory algorithm called Dijkstra's algorithm, named after its creator E.W. Dijkstra.&#x20;

The algorithm works like this:\
The premise is that a collection of points is seen as a tree; one point is the base and the shortest path to all other points as the pathway. The cost of the path is the sum of the path costs between the source point and the terminus point. Whereas DVPs are interested in the shortest route, LSPs are interested in the operational status of all of the links in the network. Each host compiles a "map" of the routing domain from its own point of view.

Link-State protocols are:

* [OSPF](/notes/services/routing-protocols/dynamic/igp/link-state/ospf)
* [ISIS](/notes/services/routing-protocols/dynamic/igp/link-state/is-is)

***

## Pros & Cons

### <mark style="color:red;">Cons:</mark>

Link-State's limiting aspect is the memory required by the router to compile the shortest path distances needed for the routing table. On a small network consisting of 20 or so routers, these computations are manageable, but on a network of 100 or more, these calculations can cripple a small router with limited CPU and memory. \
LS Protocols are complex which can make them difficult to troubleshoot, and there is a problem with flooding[^1].

### <mark style="color:green;">Pros:</mark>

On the other hand, LS protocols have fast convergence time because each router has its own complete map of the network. They have more efficient usage of network resources because they only send updates when there is a change in the network topology, reducing the amount of traffic.\
Also, LS protocols can handle large networks.

<table data-view="cards"><thead><tr><th></th><th></th></tr></thead><tbody><tr><td><mark style="color:green;"><strong>Pros:</strong></mark></td><td><ul><li>Fast Convergence</li><li><strong>Efficient Resource Usage</strong></li><li><strong>Scalability</strong></li></ul></td></tr><tr><td><mark style="color:red;"><strong>Cons:</strong></mark></td><td><ul><li><strong>Memory Requirements</strong></li><li><strong>Complexity</strong></li><li><strong>Flooding Issues</strong></li></ul></td></tr></tbody></table>

[^1]: Flooding is a common issue with link state protocols. It occurs when a link state advertisement (LSA) is transmitted by a router and forwarded by other routers to all their neighbors, including the originating router.


# OSPF

**Open shortest path first** (OSPF) is a **link-state routing protocol** that is used to find the best path between the source and the destination router using its own shortest path first (SPF) algorithm. A link-state routing protocol is a protocol that uses the concept of triggered updates, i.e., if there is a change observed in the learned routing table then the updates are triggered only, not like the distance-vector routing protocol where the routing table is exchanged at a period of time.&#x20;

In an OSPF protocol, routers have different roles. Whitch are:

1. **Backbone router –** The area 0 is known as backbone area and the routers in area 0 are known as backbone routers. If the routers exists partially in the area 0then also it is a backbone router.
2. **Internal router –** An internal router is a router which have all of its interfaces in a single area.
3. **Area Boundary Router (ABR) –** The router which connects backbone area with another area is called Area Boundary Router. It belongs to more than one area. The ABRs, therefore, maintain multiple link-state databases that describe both the backbone topology and the topology of the other areas.
4. **Area Summary Border Router (ASBR) –** When an OSPF router is connected to a different protocol like EIGRP or Border Gateway Protocol, or any other routing protocol then it is known as AS. The router which connects two different AS (in which one of the interfaces is operating OSPF) is known as Area Summary Border Router. These routers perform redistribution. ASBRs run both OSPF and another routing protocol, such as RIP or BGP. ASBRs advertise the exchanged external routing information throughout their AS.

{% hint style="info" %}
**Note:**

A router can be backbone router and Area Boundary Router at the same time i.e a router can perform more than one role at a time.
{% endhint %}

***

## Commands:


# IS-IS


# Hybrid

Metric: Composite Metric (such as: bandwidth, delay, load, reliability, and MTU (Maximum Transmission Unit))


# EIGRP


# EGP

**EGPs** are routing protocols that are used to transfer routing information between routers in different autonomous systems.\
These protocols are more complex and [BGP](/notes/services/routing-protocols/dynamic/egp/path-vector/bgp) is the only EGP protocol that you’re likely to encounter.


# Path Vector

A **path-vector routing protocol** is a network[ routing protocol ](/notes/services/routing-protocols)which maintains the path information that gets updated dynamically. Updates that have looped through the network and returned to the same node are easily detected and discarded. This algorithm is sometimes used in Bellman–Ford routing algorithms to avoid "Count to Infinity" problems.

It is different from the[ distance vector routing](/notes/services/routing-protocols/dynamic/igp/distance-vector) and [link state routing](/notes/services/routing-protocols/dynamic/igp/link-state). Each entry in the routing table contains the destination network, the next router and the path to reach the destination.

The only Path Vector protocol is:

* [BGP](/notes/services/routing-protocols/dynamic/egp/path-vector/bgp)


# BGP


# Static

A static route is routing information that is manually configured on the routing device.

As the name says, this kind of routing information is fixed in the routing table, so it does not change when there is a networking event or a change to the network.\
Witch means if a problem occurs, and there is another path a packet can be sent, it wont be until a worker manually does not change the route.

***

## Advantages and Limitations

There are some advantages to static routing, and it can and should be used in some scenarios. However, static routing does have its limitations, and this is why [dynamic routing](/notes/services/routing-protocols/dynamic) was developed. &#x20;

For example, static routing uses very little CPU and memory resources, since no algorithms are run to determine the next hop. \
On small networks, where there are two or three routers, there are very few options for what route-specific packets should take. Implementing static routing is more than sufficient in such cases, and is often simpler to implement.

However, as networks get larger, and potential paths to specific destinations become more numerous, static routing becomes more unwieldy to administrate.


# MariaDB/MySQL

port: 3306

## What is MariaDB?

MariaDB is an open-source relational database management system (RDBMS) that is a fork of MySQL. It was created by the original developers of MySQL after concerns arose over Oracle Corporation's acquisition of MySQL. MariaDB aims to maintain high compatibility with MySQL, ensuring that users and applications can easily transition from MySQL to MariaDB without significant changes.

The commands are the same as for MySQL.

***

## Installation

Install MariaDB

```sh
sudo apt install mariadb-server
```

Enable MariaDB

```bash
sudo systemctl enable mariadb
```

Start MariaDB

```bash
sudo systemctl start mariadb
```

***

## Connect to MariaDB

### Local

```bash
mysql -u root -pP4SSw0rd -h 10.129.14.128
```

### Remote

```bash
mysql -h <Hostname> -u root
mysql -h <Hostname> -u root@localhost
```

-u : user\
-p : password\
-h : host ip

***

## Footprinting

***

## Commands

{% tabs %}
{% tab title="Start" %}

```sql
show databases;    # see all databases on the device
use <database>;    # use a database
connect <database>;    # 
show tables;    # display tables in current database
describe <table_name>;    # see detailed info about the table
show columns from <table>;    # see detailed info about table  
```

{% endtab %}

{% tab title="Create Table" %}

```
CREATE TABLE <table name> (
    <Column Name> <Type>,
    <Column Name> <Type>
);
```

column datatypes:

VARCHAR(50) : \
INT :\
DATETIME :\
REAL :&#x20;

***

### Example

```sql
CREATE TABLE SHIPS (
    NAME VARCHAR(50),
    CLASS VARCHAR(50),
    LAUNCHED INT
);

CREATE TABLE BATTLES (
    NAME VARCHAR(50),
    DATE DATETIME
);

CREATE TABLE CLASSES (
    CLASS VARCHAR(50),
    TYPE VARCHAR(2),
    COUNTRY VARCHAR(20),
    NUMGUNS INT,
    BORE REAL,
    DISPLACEMENT INT
);

CREATE TABLE OUTCOMES (
    SHIP VARCHAR(50),
    BATTLE VARCHAR(50),
    RESULT VARCHAR(10)
);

```

{% endtab %}

{% tab title="Insert In Tables" %}

```sql
INSERT INTO <table_name> (<column>, <column>, <column>) VALUES
('values', 'values', values),
('values', 'values', values),
('values', 'values', values);
```

***

Example:

```sql
INSERT INTO SHIPS (NAME, CLASS, LAUNCHED) VALUES
('USS Constitution', 'Constitution', 1797),
('HMS Victory', 'Victory', 1765),
('USS Arizona', 'Pennsylvania', 1915);

INSERT INTO BATTLES (NAME, DATE) VALUES
('Battle of Tripoli', '1804-08-03'),
('Battle of Trafalgar', '1805-10-21'),
('Pearl Harbor', '1941-12-07');

INSERT INTO CLASSES (CLASS, TYPE, COUNTRY, NUMGUNS, BORE, DISPLACEMENT) VALUES
('Constitution', 'BB', 'USA', 90, 1.2, 2200),
('Victory', 'BB', 'UK', 104, 1.4, 3500),
('Pennsylvania', 'BB', 'USA', 100, 1.3, 3300);

INSERT INTO OUTCOMES (SHIP, BATTLE, RESULT) VALUES
('USS Constitution', 'Battle of Tripoli', 'Victory'),
('HMS Victory', 'Battle of Trafalgar', 'Victory'),
('USS Arizona', 'Attack on Pearl Harbor', 'Sunk');
```

{% endtab %}

{% tab %}

```sql
SELECT * FROM <table_name>;
```

***

Example:

```sql
SELECT * FROM SHIPS;
SELECT * FROM BATTLES;
SELECT * FROM CLASSES;
SELECT * FROM OUTCOMES;
```

{% endtab %}

{% tab title="Untitled" %}

```sql
SELECT SHIPS.NAME, SHIPS.CLASS, CLASSES.TYPE, CLASSES.COUNTRY
FROM SHIPS
JOIN CLASSES ON SHIPS.CLASS = CLASSES.CLASS;
```

{% endtab %}
{% endtabs %}


# Java


# GUI

A Java GUI (Graphical User Interface) is a visual interface that allows users to interact with a Java program. It includes graphical components such as buttons, text fields, labels, and more, which users can interact with using a mouse, keyboard, or touch screen.

In Java, GUIs are typically created using the Swing or JavaFX libraries. These libraries provide classes and methods to create windows, dialogs, and various types of components, as well as manage events such as button clicks or mouse movements. GUI programming in Java involves creating these components, arranging them on a screen, and adding functionality to them using event handling.

The GUI is made in a separate class file in Java, but would be nice if it is in the same package at the class/es that you want to interact with.

Below is a explanation on using the set of Switch classes and components from the javax.switch package.

{% content-ref url="/pages/pXX60k6ojEO2hRumcBSF" %}
[SWING](/notes/programming/java/gui/swing)
{% endcontent-ref %}


# SWING

To start building our GUI with swing we first import it:

```java
import javax.swing.*
```

While at it, we can import a few more useful packages and classes that we will use:

```java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
```

`java.awt.*` contains classes for creating GUI components like buttons, windows etc.

`java.awt.event.ActionEvent` classrepresents an action event that happens when a user interacts with a GUI component, like clicking a button.

`java.awt.event.ActionListener` interface is used to handle such action events. When a component, such as a button, generates an action event, the ActionListener's **`actionPerformed`** method is called. This method contains the code that responds to the event, allowing you to define what should happen when the user interacts with the component.

So when import what we need, under the class line we should create the following objects witch are used for creating the GUI window. All of this objects have to be used for a GUI.

The objects that can be used for creating a simple GUI with swing are JFrame, JPanel, JButton, JLabel.

```java
public class CoffeeShopGUI
    static private JFrame frame;
    static private JPanel panel;
    static private JButton viewMenuButton;
    static private JButton orderButton;
    static private JButton seeBasketButton;
    static private JButton seeBillButton;
    static private JButton payAndExitButton;
```

Here, frame is the window, panel is a box in the window that holds the buttons, and a button is a button🙂 A good practice is to call the objects like this at the top of the class, and use private and static.

Next thing to remember is that everything related to the window settings is written in the java constructor of the class, because the constructor is where you initialize the frame and set its properties before making it visible.

## **Window Setting-up**

```java
public CoffeeShopGUI() {
				//creating the frame object
        frame = new JFrame();
        //creating the panel object
        panel = new JPanel();

				//creating the buttons objects with text on the buttons
        viewMenuButton = new JButton("View Menu");
        orderButton = new JButton("Order");
        seeBasketButton = new JButton("See Basket");
        seeBillButton = new JButton("See Bill");
        payAndExitButton = new JButton("Pay and Exit");
```

```java
        viewMenuButton.addActionListener(this);
        orderButton.addActionListener(this);
        seeBasketButton.addActionListener(this);
        seeBillButton.addActionListener(this);
        payAndExitButton.addActionListener(this);
```

In this code snippet, **`this`** refers to the current object, which is assumed to implement the **`ActionListener`** interface. The **`addActionListener`** method is used to register the current object as an action listener for multiple buttons.

When a button is clicked, an action event is generated, and the **`actionPerformed`** method of the action listener (in this case, the current object) is called. By registering the current object as the action listener for multiple buttons, you can handle the action events from these buttons in a single **`actionPerformed`** method, which can differentiate between the buttons based on the event source.

```java
        panel.setBorder(BorderFactory.createEmptyBorder(30, 40, 30, 40));
        panel.setLayout(new GridLayout(0, 1));
        panel.add(viewMenuButton);
        panel.add(orderButton);
        panel.add(seeBasketButton);
        panel.add(seeBillButton);
        panel.add(payAndExitButton);
```

Here the buttons are added to the panel, dont mind the first 2 rows i dont getthe mesurements as well, saw a lot of people just writing this numbers.

```java
        //add the panel in the center of the frame
        frame.add(panel, BorderLayout.CENTER);
        //Some exit settings
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //set title
        frame.setTitle("Coffee Shop");
        //always write this dunno why
        frame.pack(); 
        //make the window visable on screen
        frame.setVisible(true);
```

## **Functionality**

```java
    public static void main(String[] args) {
        new CoffeeShopGUI();
```

In the main method of the GUI create a new constructor.

```java
    public void actionPerformed(ActionEvent e) {
        String action = e.getActionCommand();
```

The **`actionPerformed`** method is called when an action event occurs, such as a button click. It takes an **`ActionEvent`** parameter (**`e`**), which provides information about the event. The **`getActionCommand()`** method of the **`ActionEvent`** class retrieves the command string associated with the event, which is often the text displayed on a button or the action command set for other components. This allows you to determine which component triggered the event and take appropriate action based on that information.

Now we can use a **`switch`** statement to call the appropriate function depending on what the user clicks.

```java
   public void actionPerformed(ActionEvent e) {
        String action = e.getActionCommand();

        switch (action) {
            case "View Menu":
                displayMenu();
                break;
            case "Order":
                order();
                break;
            case "See Basket":
                displayBasket();
                break;
            case "See Bill":
                displayTotalPrice();
                break;
            case "Pay and Exit":
                payAndExit();
                break;
            default:
                break;
        }
    }

```

the last thing left is to use the object from the main coffee shop code and call the functions that we defined from there.

```java
private void displayMenu() {
        CoffeeShop.displayMenu();
    }

    private void order() {
        Scanner input = new Scanner(System.in);
        CoffeeShop.order(input);
        input.close();
    }

    private void displayBasket() {
        CoffeeShop.displayBasket();
    }

    private void displayTotalPrice() {
        CoffeeShop.displayTotalPrice();
    }

    private void payAndExit() {
		    //pop-up message window
        JOptionPane.showMessageDialog(frame, "Payment received! Thank you for visiting Mladen's Coffee Shop!");
        System.exit(0);
    }
}

```

And like that, using swing we made our simple GUI for our Coffe Shop.

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2F3OPfhUxAJLcahkQYfaZc%2FUntitled.png?alt=media&amp;token=68595cbc-6a18-450f-b5fd-b35537bddbf5" alt=""><figcaption></figcaption></figure>

***

## **CheetSheets**

<details>

<summary><strong>Window</strong></summary>

Creating the window of the GUI in swing is done with JFrame.

```java
JFrame frame = new JFrame(); //create frame object 
frame.setSize(350,200) //width and height of the window 
frame.setTitle(”Title”) //Set a title above the window frame.setDefaultCloseOperation(JFrame.*EXIT_ON_CLOSE*); //exit the window when ‘x’ is pressed 
frame.add(panel); //add objects to the frame like button, panels, labels 
frame.setVisible(true); //set the frame visible, always put this on end of gui code
```

</details>

<details>

<summary><strong>Panel</strong></summary>

Panel is the place where we put button, labels… And is created with JPanel.

```java
JPanel panel = new JPanel(); //create panel object 
panel.setLayout(null); //creates the panel as big as the frame 
panel.add(button); //add’s an object to the panel
```

</details>

<details>

<summary>Button</summary>

Buttons take action when clicked thanks to the ActionListener and perform specific task defined in the ActionListener method, and its created with JButton.

```java
private static JButton *button* //Creates button object 
button = new JButton(”text on button”) //create button and add text on it 
Button.setBounds(140, 90, 80, 25); //button coordinates and dimension (x, y, width, height) the 0 on the axis is in top left 
Button.addActionListener(new *class name*()); //add function to button when clicked 
public class loginPage implements ActionListener { //this needs to be added to the class to act as a ActionListener 
panel.add(button); //add the button to the panel on the defined coordinates
```

</details>

<details>

<summary><strong>Label</strong></summary>

Label is a field where we can put some text or pictures on the panel, and is created with JLabel.

```java
private static JLabel label; //Creates 
label object label = new JLabel(); /create label and add text to it 
label.setBounds(20, 20, 80, 25); //label coordinates and dimension (x, y, width, height) the 0 on the axis is in top left 
label.setHorizontalAlignment(SwingConstants.*CENTER*); //set the label coordinate 0 in center
label.setText(”some text”) //mesage printed on the label label.setFont(new Font("Arial", Font.*BOLD*, 24)); //set the font and size for the label 
label.setIcon(image_variable_name); //place a image in the label 
panel.add(label); //add label to the panel on defined coordinates
```

</details>

<details>

<summary><strong>Text Input Box</strong></summary>

Text box is a box in whitch you can write anything. And it is created with the JTextField.

```java
private static JTextField userText; //text input field object 
userText = new JTextField(); //create the field 
userText.setBounds(100, 20, 165, 25); //text field coordinates and dimension (x, y, width, height) the 0 on the axis is in top left 
userText.getText(); //get input in the field by user
```

</details>

<details>

<summary><strong>Password Input Box</strong></summary>

Password box is a box in whitch you can write anything but the difference is that dots are displayed insead of the letters. This is thanks to the java developers that created the swing library and the JpasswordField method that we used. And yeah, it is created with the JPasswordField.

```java
private static JPasswordField pass Text; //password (dots) input field object 
passText = new JPasswordField(); //create the field pass
Text.setBounds(100, 20, 165, 25); //text field coordinates and dimension (x, y, width, height) the 0 on the axis is in top left
```

</details>

<details>

<summary><strong>Image</strong></summary>

Images can be added using swing using the JLabel objects and with this command: *label.setIcon(ImageIcon variable name that holds the image path)*

```
static ImageIcon variable_name = new ImageIcon("C:\\Image\\Path\\image.pn");
```

</details>


# Examples/Projects

Projects made in Java with code/s and video example.


# Rock Paper Scissors

```java
package RPS;

import java.awt.*;
import java.util.Random;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class RPSGUI implements ActionListener{
    private static JFrame frame;
    private static JPanel panel;
    private static JLabel result;
    private static JLabel your_move;
    private static JLabel comp_move;
    private static JLabel score;
    private static JButton button1;
    private static JButton button2;
    private static JButton button3;

    private static Random random = new Random();

    static ImageIcon rock1 = new ImageIcon("C:\\Users\\HP\\Downloads\\rock1.png");
    static ImageIcon rock2 = new ImageIcon("C:\\Users\\HP\\Downloads\\rock2.png");
    static ImageIcon paper1 = new ImageIcon("C:\\Users\\HP\\Downloads\\paper1.png");
    static ImageIcon paper2 = new ImageIcon("C:\\Users\\HP\\Downloads\\paper2.png");
    static ImageIcon sizors1 = new ImageIcon("C:\\Users\\HP\\Downloads\\scissors1.png");
    static ImageIcon sizors2 = new ImageIcon("C:\\Users\\HP\\Downloads\\scissors2.png");

    static ImageIcon resizeImage(ImageIcon icon, int width, int height) {
        Image img = icon.getImage();
        Image resizedImg = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        return new ImageIcon(resizedImg);
    }

    static int human_choice;
    static int human_points = 0;
    static int comp_points = 0;

    public static void main(String[] args) {

        frame = new JFrame();
        panel = new JPanel();

        frame.setSize(250, 380);
        frame.setTitle("Rock, Paper, Sizors");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(panel);

        panel.setLayout(null);

        button1 = new JButton("Rock");
        button1.setBounds(69, 250, 100, 25);
        button1.addActionListener(new RPSGUI());
        panel.add(button1);

        button2 = new JButton("Paper");
        button2.setBounds(69, 280, 100, 25);
        button2.addActionListener(new RPSGUI());
        panel.add(button2);

        button3 = new JButton("scissors");
        button3.setBounds(69, 310, 100, 25);
        button3.addActionListener(new RPSGUI());
        panel.add(button3);

        your_move = new JLabel();
        your_move.setBounds(-106, 50, 250, 250);
        panel.add(your_move);

        comp_move = new JLabel();
        comp_move.setBounds(43, 50, 250, 250);
        panel.add(comp_move);

        result = new JLabel();
        result.setBounds(35, 70, 160, 40);
        result.setHorizontalAlignment(SwingConstants.CENTER);
        panel.add(result);

        score = new JLabel(human_points + ":" + comp_points);
        score.setBounds(35, 20, 160, 40);
        score.setHorizontalAlignment(SwingConstants.CENTER);
        score.setFont(new Font("Arial", Font.BOLD, 24));
        panel.add(score);

        frame.setVisible(true);

        }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == button1) {
            human_choice = 0;
        } else if (e.getSource() == button2) {
            human_choice = 1;
        } else if (e.getSource() == button3) {
            human_choice = 2;
        }

        if (human_choice != -1) {
            int comp_choice = random.nextInt(3);
            updateLabels(human_choice, comp_choice);
        }
    }

    private void updateLabels(int human_choice, int compChoice) {

        if (human_choice == 0) {
            your_move.setIcon(resizeImage(rock1, 300, 300));
        } else if (human_choice == 1) {
            your_move.setIcon(resizeImage(paper1, 300,300));
        } else if (human_choice == 2) {
            your_move.setIcon(resizeImage(sizors1,300,300));
        }

        if (compChoice == 0) {
            comp_move.setIcon(resizeImage(rock2,300,300));
        } else if (compChoice == 1) {
            comp_move.setIcon(resizeImage(paper2,300,300));
        } else if (compChoice == 2) {
            comp_move.setIcon(resizeImage(sizors2,300,300));
        }

        String resultText = getResultText(human_choice, compChoice);
        result.setText(resultText);

        if (resultText.equals("You win!")) {
            human_points++;
        }
        if (resultText.equals("Computer wins!")) {
            comp_points++;
        }
        score.setText(human_points + ":" + comp_points);
    }

    private String getResultText(int humanChoice, int compChoice) {
        String[] results = {"It's a draw!", "Computer wins!", "You win!"};
        int resultIndex = (compChoice - humanChoice + 3) % 3;
        return results[resultIndex];

    }
}
```

{% embed url="<https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FAZAF1J3EzSDrLgwIvnjb%2FROCK_P~1.MP4?alt=media&token=1d35e2dc-fb93-491a-b919-59127dc16c35>" fullWidth="false" %}


# Login Page

Below is a simple login page code that prompts if login is successful or not based on the user input.

```java
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class loginPage implements ActionListener {

    private static JFrame frame;
    private static JPanel panel;
    private static JLabel userLabel;
    private static JTextField userText;
    private static JLabel passLabel;
    private static JPasswordField passText;
    private static JButton loginButton;
    private static JLabel success;

    public static void main(String[] args) {

        frame = new JFrame();
        panel = new JPanel();

        frame.setSize(350,200);
        frame.setTitle("Login Page");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(panel);

        panel.setLayout(null);

        userLabel = new JLabel("User");
        userLabel.setBounds(20, 20, 80, 25);
        panel.add(userLabel);

        userText = new JTextField();
        userText.setBounds(100, 20, 165, 25);
        panel.add(userText);

        passLabel = new JLabel("Password");
        passLabel.setBounds(20, 50, 80, 25);
        panel.add(passLabel);

        passText = new JPasswordField();
        passText.setBounds(100, 50, 165, 25);
        panel.add(passText);

        loginButton = new JButton("Login");
        loginButton.setBounds(140, 90, 80, 25);
        loginButton.addActionListener(new loginPage());
        panel.add(loginButton);

        success = new JLabel("");
        success.setBounds(57, 120, 250, 25);
        success.setHorizontalAlignment(SwingConstants.CENTER);
        panel.add(success);

        frame.setVisible(true);

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String user = userText.getText();
        String pass = passText.getText();
        System.out.println(user + ", " + pass);

        if (user.equals("Mladen") && pass.equals("mladen123")) {
            success.setText("Login Successful");
        } else {
            success.setText("Invalid User or Password");
        }
    }
}
```

{% embed url="<https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FXP6Tp1EsbZjxUxTG6Fnl%2Flogin.mp4?alt=media&token=aaa0cef3-1183-4679-9947-2f9cfdae22cd>" %}


# Hangman

{% tabs %}
{% tab title="Hangman.java" %}

```java
package Hangman;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import static Hangman.Wordlist.WORD_LIST;

public class Hangman implements ActionListener {

    static final Random RANDOM = new Random();

    static String chosenWord;
    int wordLength;
    static int lives = 6;

    static List<Character> display = new ArrayList<>();
    List<Character> wrongGuesses = new ArrayList<>();

    static JFrame frame;
    static JPanel panel;
    static JLabel wordDisplay;
    static JLabel hangmanArt;
    static JLabel hearths;
    static JLabel input_message;
    static JTextField input;

    public Hangman() {
        chosenWord = WORD_LIST.get(RANDOM.nextInt(WORD_LIST.size()));
        wordLength = chosenWord.length();
        lives = 6;

        frame = new JFrame();
        frame.setTitle("Hangman");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(330, 350);
        frame.setLocationRelativeTo(null);


        panel = new JPanel();
        panel.setLayout(null);
        panel.setBackground(Color.WHITE);

        wordDisplay = new JLabel();
        wordDisplay.setBounds(200, 70, 300, 50);

        StringBuilder startDisplay = new StringBuilder();
        for (int i = 0; i < chosenWord.length(); i++) {
            startDisplay.append("_ ");
        }
        wordDisplay.setText(startDisplay.toString());
        panel.add(wordDisplay);

        hangmanArt = new JLabel();
        hangmanArt.setBounds(20, 20, 150, 200);
        hangmanArt.setIcon(Art.hangman0);
        panel.add(hangmanArt);

        hearths = new JLabel();
        hearths.setText("Lives: " + String.valueOf(lives));
        hearths.setBounds(200, 20, 50, 20);
        panel.add(hearths);

        input = new JTextField();
        input.setBounds(104, 257, 20, 20);
        input.addActionListener(this);
        panel.add(input);

        input_message = new JLabel("Enter a letter : ");
        input_message.setBounds(20, 250, 100, 30);
        panel.add(input_message);

        JOptionPane.showMessageDialog(null, "To win, guess the word before the person is hung.");

        frame.add(panel);
        frame.setVisible(true);


    }


    public static void main(String[] args) {
        new Hangman();
    }

    public static void updateLabel(char guess) {
        if (chosenWord.contains(String.valueOf(guess))) {
            // Update wordDisplay
            StringBuilder displayString = new StringBuilder();
            for (int i = 0; i < chosenWord.length(); i++) {
                char c = chosenWord.charAt(i);
                if (display.contains(c)) {
                    displayString.append(c).append(' ');
                } else if (c == guess) {
                    displayString.append(c).append(' ');  // Print the guessed letter
                    display.add(c);  // Add the guessed letter to the display list
                } else {
                    displayString.append("_ ");
                }
            }
            wordDisplay.setText(displayString.toString());

            if (displayString.indexOf("_") == -1) {
                JOptionPane.showMessageDialog(null, "Congratulations. you guessed the word: " + chosenWord);
            }

        } else {
            lives--;
            hearths.setText("Lives: " + lives);

            if (lives == 6) {
                hangmanArt.setIcon(Art.hangman0);
            } else if (lives == 5) {
                hangmanArt.setIcon(Art.hangman1);
            } else if (lives == 4) {
                hangmanArt.setIcon(Art.hangman2);
            } else if (lives == 3) {
                hangmanArt.setIcon(Art.hangman3);
            } else if (lives == 2) {
                hangmanArt.setIcon(Art.hangman4);
            } else if (lives == 1) {
                hangmanArt.setIcon(Art.hangman5);
            } else {
                hangmanArt.setIcon(Art.hangman6);
                JOptionPane.showMessageDialog(null, "You lost. The correct word was: " + chosenWord);
            }
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String guess = input.getText();
        if (guess.length() == 1 && Character.isLetter(guess.charAt(0))) {
            char guessedLetter = guess.charAt(0);
            updateLabel(guessedLetter);
            input.setText(""); // Clear the input field after each guess
        } else {
            JOptionPane.showMessageDialog(null, "Please enter a single letter.");
            input.setText(""); // Clear the input field if invalid input
        }
    }
}

```

{% endtab %}

{% tab title="Wordlist.java" %}

```java
package Hangman;

import java.util.List;
import java.util.Arrays;
public class Wordlist {

    public static final List<String> WORD_LIST = Arrays.asList(
            "абонамент", "багажник", "валута", "галактика", "деветнадесет", "експеримент", "жълт", "заплата",
            "изпратен", "квартира", "лаборатория", "минимум", "наблюдение", "обектив", "парти", "резерват",
            "същество", "таблетка", "университет", "философия", "химия", "централен", "червено", "шест",
            "щастие", "ъгълник", "юноша", "яйце", "автомат", "брошура", "вестник", "глобус", "дърво",
            "език", "живот", "змия", "играч", "колело", "лилаво", "момче", "надпис", "очила", "пешеходец",
            "робот", "синьо", "телефон", "улица", "фотоапарат", "хотел", "цвете", "черно", "шапка", "щура",
            "ъглов", "юниор", "як", "автор", "бар", "вятър", "град", "диаметър", "ежедневен", "земя",
            "илюстрация", "книга", "лист", "мозък", "напред", "осветление", "пари", "ръка", "свят", "тъмно",
            "учебник", "филм", "храна", "цар", "човек", "шкаф", "щанд", "ъгъл", "юли", "яхта", "автобус",
            "баланс", "вълк", "галерия", "джоб", "езда", "жълъд", "завод", "изграден", "клуб", "лампа",
            "музика", "набор", "образ", "пари", "рецепт", "свещ", "трактор", "успех", "филтър", "хранене",
            "цел", "чаша", "шпагат", "щастлив", "ълцер", "ювелир", "якор", "авторитет", "бариера", "вълна",
            "гама", "диамант", "ежедневие", "защита", "идеал", "колега", "линейка", "модел", "награда", "облик",
            "парад", "ракия", "святлина", "такси", "услуга", "финал", "хаос", "център", "чек", "шуба", "щур",
            "ъгълът", "юла", "ябълка", "авиация", "барут", "вълшебник", "газ", "диверсия", "ежегоден", "звезда",
            "избор", "коледа", "лира", "май", "надежда", "облачно", "парк", "ракета", "сграда", "тайна",
            "убийство", "фактор", "хвърляне", "център", "чиния", "шампион", "щат", "ърнест", "юни", "ярост",
            "август"


    );
}
```

{% endtab %}

{% tab title="Art.java" %}

```java
package Hangman;

import javax.swing.ImageIcon;

public class Art {
    static ImageIcon hangman0 = new ImageIcon("C:\\path\\to\\file\\hangman0.PNG");
    static ImageIcon hangman1 = new ImageIcon("C:\\path\\to\\file\\hangman1.PNG");
    static ImageIcon hangman2 = new ImageIcon("C:\\path\\to\\file\\hangman2.PNG");
    static ImageIcon hangman3 = new ImageIcon("C:\\path\\to\\file\\hangman3.PNG");
    static ImageIcon hangman4 = new ImageIcon("C:\\path\\to\\file\\hangman4.PNG");
    static ImageIcon hangman5 = new ImageIcon("C:\\path\\to\\file\\hangman5.PNG");
    static ImageIcon hangman6 = new ImageIcon("C:\\path\\to\\file\\hangman6.PNG");


}


```

{% endtab %}
{% endtabs %}

{% embed url="<https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FAojgdfIZUcLDjsDRzdrT%2F%D1%85%D0%B0%D0%BD%D0%B3%D0%BC%D0%B0%D0%BD.mp4?alt=media&token=683f1095-bede-4069-b07f-8aa7603d6d69>" %}


# Coffee Shop

{% tabs %}
{% tab title="main.java" %}

```java
package CoffeeShop;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;

public class CoffeeShopGUI implements ActionListener {
    private JFrame frame;
    private JPanel panel;
    private static JLabel label;
    private JButton viewMenuButton;
    private JButton orderButton;
    private JButton seeBasketButton;
    private JButton seeBillButton;
    private JButton payAndExitButton;

    public CoffeeShopGUI() {
        frame = new JFrame();
        panel = new JPanel();

        viewMenuButton = new JButton("View Menu");
        orderButton = new JButton("Order");
        seeBasketButton = new JButton("See Basket");
        seeBillButton = new JButton("See Bill");
        payAndExitButton = new JButton("Pay and Exit");
        label = new JLabel("");

        viewMenuButton.addActionListener(this);
        orderButton.addActionListener(this);
        seeBasketButton.addActionListener(this);
        seeBillButton.addActionListener(this);
        payAndExitButton.addActionListener(this);

        panel.setBorder(BorderFactory.createEmptyBorder(50, 50, 50, 50));
        panel.setLayout(new GridLayout(0, 1));
        panel.add(viewMenuButton);
        panel.add(orderButton);
        panel.add(seeBasketButton);
        panel.add(seeBillButton);
        panel.add(payAndExitButton);

        frame.setSize(400,200);
        frame.add(panel, BorderLayout.CENTER);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("Coffee Shop");
        frame.pack();

        frame.setVisible(true);
    }

    public static void main(String[] args) {
        new CoffeeShopGUI();
    }

    public void actionPerformed(ActionEvent e) {
        String action = e.getActionCommand();

        switch (action) {
            case "View Menu":
                displayMenu();
                break;
            case "Order":
                order();
                break;
            case "See Basket":
                displayBasket();
                break;
            case "See Bill":
                displayTotalPrice();
                break;
            case "Pay and Exit":
                payAndExit();
                break;
            default:
                break;
        }
    }

    private void displayMenu() {
        CoffeeShop.displayMenu();
    }

    private void order() {
        Scanner input = new Scanner(System.in);
        CoffeeShop.order(input);
        input.close();
    }

    private void displayBasket() {
        CoffeeShop.displayBasket();
    }

    private void displayTotalPrice() {
        CoffeeShop.displayTotalPrice();
    }

    private void payAndExit() {
        JOptionPane.showMessageDialog(frame, "Payment received! Thank you for visiting Mladen's Coffee Shop!");
        System.exit(0);
    }
}
```

{% endtab %}
{% endtabs %}

{% embed url="<https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FYoaZJDzCTCqgHNbTcoXX%2Fcoffee%20shop.mp4?alt=media&token=88b17910-1c1a-42fd-82c8-7042494b825b>" %}


# Simple Rulette

{% tabs %}
{% tab title="rulette.java" %}

```java
package Roulette;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;

public class Roulette {
    private static int startMoney = 100;
    private static List<Integer> numbers = new ArrayList<>();
    private static List<String> colors = new ArrayList<>();
    private static List<Integer> bets = new ArrayList<>();
    private static List<Integer> amounts = new ArrayList<>();

    public static void main(String[] args) {
        setupWheel();

        System.out.println("Welcome to the table!");
        while (true) {
            String userInput = getUserInput("\noptions: \n1. place bet\n2. spin wheel\n3. leave the table\n");

            switch (userInput) {
                case "1":
                    placeBet();
                    break;
                case "2":
                    spinWheel();
                    break;
                case "3":
                    leaveTable();
                    break;
                default:
                    System.out.println("Not a valid option");
                    break;
            }
        }
    }

    private static void setupWheel() {
        for (int i = 0; i <= 36; i++) {
            numbers.add(i);
        }


        colors.add("red");
        colors.add("black");
    }

    private static void placeBet() {
        int bet = getIntegerInput("Enter the number you want to bet on (0-36): ");
        if (bet < 0 || bet > 36) {
            System.out.println("Invalid number. Please choose a number between 0 and 36.");
            return;
        }

        int amount = getIntegerInput("Enter the amount you want to bet: ");
        if (amount > startMoney) {
            System.out.println("Not enough money.");
            return;
        }

        bets.add(bet);
        amounts.add(amount);
        startMoney -= amount;
        System.out.println("Bet placed on " + bet + " with amount $" + amount + ". You have $" + startMoney + " left.");
    }

    private static void spinWheel() {
        Random random = new Random();
        int winningNumber = numbers.get(random.nextInt(numbers.size()));
        String winningColor = winningNumber % 2 == 0 ? "red" : "black";

        System.out.println("The ball landed on " + winningNumber + " (" + winningColor + ")");

        for (int i = 0; i < bets.size(); i++) {
            int bet = bets.get(i);
            int amount = amounts.get(i);
            if (bet == winningNumber) {
                startMoney += amount * 35;
                System.out.println("Congratulations! You won $" + amount * 35 + ".");
            } else if (bet % 2 == 0 && winningNumber % 2 == 0 || bet % 2 != 0 && winningNumber % 2 != 0) {
                startMoney += amount * 2;
                System.out.println("Congratulations! You won $" + amount * 2 + ".");
            } else {
                System.out.println("You lost $" + amount + ".");
            }
        }

        bets.clear();
        amounts.clear();
        System.out.println("You have $" + startMoney + " left.");
    }

    private static void leaveTable() {
        System.out.println("\n===================");
        System.out.println("You are leaving the table with $" + startMoney + ", \nsee you next time!");
        System.exit(0);
    }

    private static String getUserInput(String message) {
        Scanner scanner = new Scanner(System.in);
        System.out.print(message);
        return scanner.nextLine();
    }

    private static int getIntegerInput(String message) {
        while (true) {
            try {
                return Integer.parseInt(getUserInput(message));
            } catch (NumberFormatException e) {
                System.out.println("Invalid input. Please enter a valid number.");
            }
        }
    }
}

```

{% endtab %}

{% tab title="board.csv" %}

```csv
number,color
1,red
2,black
3,red
4,black
5,red
6,black
7,red
8,black
9,red
10,black
11,black
12,red
13,black
14,red
15,black
16,red
17,black
18,red
19,red
20,black
21,red
22,black
23,red
24,black
25,red
26,black
27,red
28,black
29,black
30,red
31,black
32,red
33,black
34,red
35,black
36,red
```

{% endtab %}
{% endtabs %}


# Python

Python is one of the top programming languages in the world, widely used in fields such as AI, machine learning, data science, and web development.


# Turtle Module

{% tabs %}
{% tab title="shape\_and\_color.py" %}

```python
#importing
import turtle

#create the turtle object
mladen = turtle.Turtle()

#change turtle shape (circle, triangle, turtle...)
mladen.shape("turtle")

#change lone and turtle color
mladen.color("blue") #changes line and turtle to blue
mladen.color("blue", "black") #blue line, black turtle

turtle.colormode(255) #change to use RGB colors
mladen.color(120,50,20)
```

{% endtab %}

{% tab title="screen.py" %}

```python
#import turtle

#create screen object
wn = turtle.Screen()

#change background
wn.bgcolor("black")

turtle.colormode(255) #change mode so we can use RGB
wn.bgcolor(200,40,20) #RGB color code

#change background as picture(image needs to be GIF extension, and needs to be in the same package as the py. file)
wn.bgpic("python.gif")

#change title
wn.title("Mladen The Turtle")
```

{% endtab %}

{% tab title="movement.py" %}

```python
#the turtle starts in HOME position whitch is 0,0. It also starts facing the east.

import turtle
mladen = turtle.Turtle

#change start position
mladen.setheading(90) #change the angle of the start position (90 - north | 180 - west | 270 - south | 360 - east)

#movement
#depending on the start position, when we use forward command, it will move in that direction

#forward (go in the direction the turtle is headed)
mladen.forward(100)
mladen.fd(100) #shorter

#backward(move in the opposite direction of the turtle position)
mladen.backward(100)
mladen.bk(100)
```

{% endtab %}

{% tab title="circle.py" %}

```python
import turtle

mladen = turtle.Turtle()

#dra a circle, add radius as an argument
mladen.circle(50)
mladen.circle(-50)

#clear picture and get turtle to home position
mladen.reset()

#semi-circle, redius + angle as arguemnts
mladen.circle(100,180)
mladen.reset()

#draw other shapes with "steps"
mladen.circle(100, steps=6)
```

{% endtab %}

{% tab title="goto, up\_down.py" %}

```python
import turtle

mladen = turtle.Turtle()

#start drawing from a different position (put the turtles pen up lol)
mladen.goto(0, -100)

#get turtle pen up, away from the paper
mladen.up()
mladen.goto(0,200)

#get turtle pen down, back on the paper
mladen.down()
mladen.circle(-100, steps=6)

```

{% endtab %}

{% tab title="reset, undo, pause.py" %}

```python
import turtle

mladen = turtle. Turtle()

#undo a drawing process
mladen.undo()

#reset the screen ad get turtle to home position
mladen.reset()

#pause the screen when draing is done
turtle.done()
```

{% endtab %}

{% tab title="square, fillcolor, speed.py" %}

```python
import turtle

mladen = turtle.Turtle()

#draw a square manually
mladen.forward(100)
mladen.left(90)
mladen.forward(100)
mladen.left(90)
mladen.forward(100)
mladen.left(90)
mladen.forward(100)
mladen.left(90)

#draw a square woth a for statement and range() command
for i in range(4):
    mladen.forward(100)
    mladen.left(90)

#hide the turtle
mladen.hideturtle() #if we want to hide the turtle from begginging, use command before starting of the drawing
mladen.showturtle()

#chage speed of the turtle (0-fastest, 10 fast, 6 normal, 3 slow, 1 slowest)
mladen.speed(6)

#fill collor
mladen.begin_fill() #at the start of drawing a shape
mladen.end_fill() #at the end of drawing a shape
mladen.fillcolor("red")

mladen.begin_fill()
mladen.fillcolor("red")
for i in range(4):
    mladen.backward(100)
    mladen.left(90)
mladen.end_fill()




```

{% endtab %}
{% endtabs %}


# Examples/Projects

Projects made in Python with code/s and video example.


# Simple Snake Game

```python
from tkinter import *
import random

GAME_WIDTH = 650
GAME_HEIGHT = 650
SPEED = 100
SPACE_SIZE = 50
BODY_PARTS = 3
SNAKE_COLOR = "#00FF00"
FOOD_COLOR = "#FF0000"
BACHGROUND_COLOR = "#000000"

class Snake:

    def __init__(self):

        self.body_size = BODY_PARTS
        self.coordinates = []
        self.squares = []

        for i in range(0, BODY_PARTS):
            self.coordinates.append([0, 0])

        for x,y in self.coordinates:
            square = canvas.create_rectangle(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=SNAKE_COLOR, tag="snake")
            self.squares.append(square)

class Food:

    def __init__(self):

        x = random.randint(0,(GAME_WIDTH / SPACE_SIZE)-1) * SPACE_SIZE
        y = random.randint(0,(GAME_HEIGHT / SPACE_SIZE)-1) * SPACE_SIZE

        self.cordinates = [x,y]

        canvas.create_oval(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=FOOD_COLOR, tag="food" )

def next_turn(snake, food):

    x, y = snake.coordinates[0]

    if direction == "up":
        y -= SPACE_SIZE
    elif direction == "down":
        y += SPACE_SIZE
    elif direction == "left":
        x -= SPACE_SIZE
    elif direction == "right":
        x += SPACE_SIZE

    snake.coordinates.insert(0, (x, y))

    square = canvas.create_rectangle(x, y, x+ SPACE_SIZE, y + SPACE_SIZE, fill=SNAKE_COLOR)

    snake.squares.insert(0, square)

    if x == food.cordinates[0] and y == food.cordinates[-1]:
        global score
        score += 1
        label.config(text="Score:{}".format(score))
        canvas.delete("food")
        food = Food()

    else:
        del snake.coordinates[-1]

        canvas.delete(snake.squares[-1])

        del snake.squares[-1]

    if check_collisions(snake):
        game_over()

    else:
        window.after(SPEED, next_turn, snake, food)

def change_direction(new_direction):
    global direction

    if new_direction == 'left':
        if direction != 'right':
            direction = new_direction

    elif new_direction == 'right':
        if direction != 'left':
            direction = new_direction

    if new_direction == 'up':
        if direction != 'down':
            direction = new_direction

    if new_direction == 'down':
        if direction != 'up':
            direction = new_direction


def check_collisions(snake):

    x,y = snake.coordinates[0]

    if x < 0 or x >= GAME_WIDTH:
        return True
    elif y < 0 or y >= GAME_HEIGHT:
        return True

    for body_part in snake.coordinates[1:]:
        if x == body_part[0] and y == body_part[1]:
            return True


    return False

def game_over():
    canvas.delete(ALL)
    canvas.create_text(canvas.winfo_width()/2, canvas.winfo_height()/2, font=('consolas',70), text="game over", fill="red", tag="game over" )

window = Tk()
window.title("Snake Game")
window.resizable(False, False)

score = 0
direction = "down"

label = Label(window, text="Score:{}".format(score), font=("consolas", 40))
label.pack()

canvas = Canvas(window, bg=BACHGROUND_COLOR, height=GAME_HEIGHT, width=GAME_WIDTH)
canvas.pack()

window.update()

window_width = window.winfo_width()
window_height = window.winfo_height()
screen_width = window.winfo_screenwidth()
screen_height  = window.winfo_screenheight()

x = int((screen_width/2) - (window_width/2))
y = int((screen_height/2) - (window_height/2))

window.geometry(f"{window_width}x{window_height}+{x}+{y}")

window.bind('<Left>', lambda event: change_direction('left'))
window.bind('<Up>', lambda event: change_direction('up'))
window.bind('<Right>', lambda event: change_direction('right'))
window.bind('<Down>', lambda event: change_direction('down'))


snake = Snake()
food = Food()

next_turn(snake, food)

window.mainloop()
```

{% embed url="<https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FpcUPjEWAYOCrUlRowT4y%2FSnake%20Game.mp4?alt=media&token=3b6d5446-4f9d-46e0-a4df-8cb0c6e44e73>" %}


# Simple Slot

```python
import random

MAX_LINES = 3
MAX_BET = 100
MIN_BET = 1

ROWS = 3
COLS = 3

symbol_count = {
    "A": 2,
    "B": 4,
    "C": 6,
    "D": 8
}

symbol_value = {
    "A": 5,
    "B": 4,
    "C": 3,
    "D": 2
}


def check_winnings(columns, lines, bet, values):
    winnings = 0
    winning_lines = []
    for line in range(lines):
        symbol = columns[0][line]
        for column in columns:
            symbol_to_check = column[line]
            if symbol != symbol_to_check:
                break
        else:
            winnings += values[symbol] * bet
            winning_lines.append(line + 1)

    return winnings, winning_lines


def get_slot_machine_spin(rows, cols, symbols):
    all_symbols = []
    for symbol, symbol_count in symbols.items():
        for _ in range(symbol_count):
            all_symbols.append(symbol)

    columns = []
    for _ in range(cols):
        column = []
        current_symbols = all_symbols[:]
        for _ in range(rows):
            value = random.choice(current_symbols)
            current_symbols.remove(value)
            column.append(value)

        columns.append(column)

    return columns


def print_slot_machine(columns):
    for row in range(len(columns[0])):
        for i, column in enumerate(columns):
            if i != len(columns) - 1:
                print(column[row], end=" | ")
            else:
                print(column[row], end="")

        print()


def deposit():
    while True:
        amount = input("What would you like to deposit? $")
        if amount.isdigit():
            amount = int(amount)
            if amount > 0:
                break
            else:
                print("Amount must be greater than 0.")
        else:
            print("Please enter a number.")

    return amount


def get_number_of_lines():
    while True:
        lines = input(
            "Enter the number of lines to bet on (1-" + str(MAX_LINES) + ")? ")
        if lines.isdigit():
            lines = int(lines)
            if 1 <= lines <= MAX_LINES:
                break
            else:
                print("Enter a valid number of lines.")
        else:
            print("Please enter a number.")

    return lines


def get_bet():
    while True:
        amount = input("What would you like to bet on each line? $")
        if amount.isdigit():
            amount = int(amount)
            if MIN_BET <= amount <= MAX_BET:
                break
            else:
                print(f"Amount must be between ${MIN_BET} - ${MAX_BET}.")
        else:
            print("Please enter a number.")

    return amount


def spin(balance):
    lines = get_number_of_lines()
    while True:
        bet = get_bet()
        total_bet = bet * lines

        if total_bet > balance:
            print(
                f"You do not have enough to bet that amount, your current balance is: ${balance}")
        else:
            break

    print(
        f"You are betting ${bet} on {lines} lines. Total bet is equal to: ${total_bet}")

    slots = get_slot_machine_spin(ROWS, COLS, symbol_count)
    print_slot_machine(slots)
    winnings, winning_lines = check_winnings(slots, lines, bet, symbol_value)
    print(f"You won ${winnings}.")
    print(f"You won on lines:", *winning_lines)
    return winnings - total_bet


def main():
    balance = deposit()
    while True:
        print(f"Current balance is ${balance}")
        answer = input("Press enter to play (q to quit).")
        if answer == "q":
            break
        balance += spin(balance)

    print(f"You left with ${balance}")


main()

```

{% embed url="<https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FAB0GEFTjiEKZOAxmJTzm%2FSimple%20Slot.mp4?alt=media&token=26581f19-2b27-49f3-8dd9-70c9bcce1e77>" %}


# Simple Rulette

A rulette game without the green zero.

{% tabs %}
{% tab title="main.py" %}

```python
import csv
import random

start_money = int(input("How much money do you have?: $"))
numbers_bet = []
colors_bet = []
number_money_in_bet = []
color_money_in_bet = []

def place_bet():
    global start_money
    global numbers_bet
    global colors_bet
    global number_money_in_bet

    print("\nPlace your bet:")
    print("1. Bet on numbers")
    print("2. Bet on red")
    print("3. Bet on black")

    bet_option = int(input("Choose an option (1-3): "))

    if bet_option == 1:
        number_bet = int(input("Enter the number you want to bet on (1-36): "))
        numbers_bet.append(number_bet)
        number_bet_amount = int(input("Enter the amount you want to bet: $"))
        number_money_in_bet.append(number_bet_amount)
        sum(number_money_in_bet)

        if start_money - number_bet_amount <0:
            print("Not enough money")

        elif 1 <= number_bet <= 36:
            start_money -= number_bet_amount
            print("--------------------")
            print(f"You placed a bet of ${number_bet_amount} on number {number_bet}.")
            print(f"You have ${start_money} left")
        else:
            print("Invalid number. Please choose a number between 0 and 36.")

    elif bet_option == 2 or bet_option == 3:
        color_bet = "red" if bet_option == 2 else "black"
        colors_bet.append(color_bet)
        color_bet_amount = int(input("Enter the amount you want to bet: $"))
        color_money_in_bet.append(color_bet_amount)

        if start_money - color_bet_amount <0:
            print("Not enough money")
        else:
            start_money -= color_bet_amount
            print("--------------------")
            print(f"You placed a bet of ${color_bet_amount} on {color_bet}.")
            print(f"You have ${start_money} left")

    else:
        print("Invalid option. Please choose a valid option (1-3).")


def spin_wheel():
    global start_money
    global numbers_bet
    global colors_bet
    global number_money_in_bet
    global color_money_in_bet

    print("\nSpinning the wheel, no more bets.")

    with open('Board.csv', 'r') as file:
        reader = csv.DictReader(file)
        rows = list(reader)

    random_row = random.choice(rows)
    print("The ball landed on:")
    print(random_row)

    if int(random_row["number"]) in numbers_bet:
        start_money = start_money + (number_money_in_bet[numbers_bet.index(int(random_row["number"]))] * 35) #i used chatgpt for this line,
        print(f"Congratulations! Your {random_row['number']} bet wins!")                                     #i did not know how to multiply the numbers we bet on and 35, because the numbers are in a list
    elif random_row["color"] in colors_bet:
        start_money = start_money + (color_money_in_bet[colors_bet.index(random_row["color"])] * 2)          #also for this one line, i have no clue what [colors_bet.index(random_row["color"])] does but the code works :)
        print(f"Congratulations! Your {random_row['color']} bet wins!")
    else:
        print("Unlucky")

    print(f"You have ${start_money} left")
    numbers_bet.clear()
    colors_bet.clear()
    number_money_in_bet.clear()
    color_money_in_bet.clear()


def leave_table():
    print("\n===================")
    print(f"You are leaving the table with ${start_money}, \nsee you next time!")
    exit()


print("Welcome to the table!")
while True:
    user_input = input("\noptions: \n1. place bet "
                                  "\n2. spin wheel "
                                  "\n3. leave the table\n")

    if user_input == "1":
        place_bet()
    elif user_input == "2":
        spin_wheel()
    elif user_input == "3":
        leave_table()
    else:
        print("Not a valid option")
```

{% endtab %}

{% tab title="Board.csv" %}

```csv
number,color
1,red
2,black
3,red
4,black
5,red
6,black
7,red
8,black
9,red
10,black
11,black
12,red
13,black
14,red
15,black
16,red
17,black
18,red
19,red
20,black
21,red
22,black
23,red
24,black
25,red
26,black
27,red
28,black
29,black
30,red
31,black
32,red
33,black
34,red
35,black
36,red
```

{% endtab %}
{% endtabs %}

{% embed url="<https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FcVzhFCXJ8put0tOWjYU2%2F0511%20(1).mp4?alt=media&token=553437b2-a3a8-4143-b149-b3d0232c7939>" %}


# Supermarket

{% tabs %}
{% tab title="main.py" %}

```python
import csv

Chart = []
Price = []

def see_products():
    with open("products.csv", "r") as file:
        csv_reader = csv.reader(file)
        next(csv_reader)

        for line in csv_reader:
            print(line)

def add_to_chart():
    while True:
        user_product = input("Enter product: ")

        with open("products.csv", "r") as file:
            csv_reader = csv.reader(file)
            product_found = False

            for row in csv_reader:
                if row and len(row) >= 2 and user_product.lower() == row[1].lower():
                    quantity = int(input(f"How many {user_product}s do you want to add? "))
                    total_price = float(row[2].replace('$', '')) * quantity
                    Chart.append((user_product, quantity))
                    Price.append(total_price)
                    print(f"Successfully added {quantity} {user_product}s | Total Price: ${total_price:.2f}")
                    product_found = True
                    break

            if product_found:
                break
            else:
                print("Product not found")

def checkout():
    if not Chart:
        print("Your chart is empty. Add some products before checking out.")
        return
    total_price = sum(Price)

    print("\n===== Checkout =====")
    print("Your Chart:")
    for (product, quantity), price in zip(Chart, Price):
        print(f"{product} x{quantity}: ${price:.2f}")

    print("\nTotal Price: ${:.2f}".format(total_price))
    print("Thank you for shopping at Martin's supermarket!")
    exit()



print("\nWelcome to Mladen's supermarket \n---------------------------------")
print("To see available products write 'p' \n"
      "To add product to chart write 'add' \n"
      "To checkout write 'c'")

while True:
    user_input = input("What would you like to do? (p,add,c): ")

    if user_input.lower() == 'p':
        see_products()
    elif user_input.lower() == 'add':
        add_to_chart()
    elif user_input.lower() == 'c':
        checkout()

    else:
        print("Invalid input. Please try again.")

```

{% endtab %}

{% tab title="add\_to\_chart.py" %}

```python
import csv

Chart = []
user_product = input("Enter product: ")

with open("products.csv", "r") as file:
    csv_reader = csv.reader(file)

    for row in csv_reader:
        if row and len(row) >= 2 and user_product.lower() == row[1].lower():
            Chart.append(row)
            print("Successfully added product")
```

{% endtab %}

{% tab title="products.csv" %}

```csv
Category,Product,Price
Meat,Chicken,9$
Meat,Ham,14$
Meat,Salami,8.50$
Meat,Sausages,9.50$
Meat,Bacon,6$
Meat,Rib,13$
Bakery,Bread,1$
Bakery,Pizza,2$
Bakery,Salami Roll,0.60$
Bakery,Donut,1$
Bakery,Croasan,0.80$
Beer,Bira Moretti,3.20$
Beer,Bud Light,4$
Beer,Corona,3.50$
Beer,Stella Artois,4$
Beer,Heineken,2$
Beer,Budweiser,3.50$
Beer,Burgasko,1.50$
Juice,Coca-Cola,1$
Juice,Fanta,1$
Juice,Pepsi,1$
Juice,7 up,1$
Juice,Apple Juice,1$
Juice,Orange Juice,1$
Fruits,Apple,0.20$
Fruits,Avocado,0.60$
Fruits,Blueberrys,2.20$
Fruits,Banana,0.20$
Fruits,Grapefruit,0.50$
Fruits,Lemon,0.20$
Fruits,Strawberries,1.60$
Vegetables,Carrot,0.20$
Vegetables,Peas,2$
Vegetables,Broccoli,0.20$
Vegetables,Cucumber,0.30$
Vegetables,Tomato,0.30$
Vegetables,Mushrooms,3$
Hygiene,Shampoo,4$
Hygiene,Soap,1.20$
Hygiene,Toothbrush,2$
Hygiene,Hand sanitizer,1$
Hygiene,Deodorant,2$
Hygiene,Baby Wipes,2$
Hygiene,Toothpaste,2$

```

{% endtab %}
{% endtabs %}

{% embed url="<https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2Fb9XH7UgQ2ORveXJjT5n9%2FSupermarket.mp4?alt=media&token=fb4a2188-63c2-40d6-8e13-b8633b997b41>" %}


# Brand Name Generator

{% tabs %}
{% tab title="main.py" %}

```python
print("Welcome to the random Band name generator")

city = input("What is the name of the city you grow up?\n")
pet = input("What is the name of your pet?\n")
band_name = "your band name can be: " + city + " " + pet

print(band_name)
```

{% endtab %}

{% tab title="Second Tab" %}

{% endtab %}
{% endtabs %}

{% embed url="<https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FUhWQduNXNSJGLOmhyBdE%2F0703.mp4?alt=media&token=f48e271a-fca4-41e5-a6be-6c3f3d06728e>" %}


# Tip Calculator

Calculates how much money should everyone give + tip for waiter

{% tabs %}
{% tab title="main.py" %}

```python
print("Welcome to the tip calculator")

total_bill = float(input("What was the total bill?: "))
tip_percentage = int(input("What percentage tip would you like to give?: "))
amount_of_people = int(input("How many people to split the bill?: "))

result = (total_bill + (total_bill * tip_percentage/100)) / amount_of_people

print(result)
```

{% endtab %}

{% tab title="Second Tab" %}

{% endtab %}
{% endtabs %}

{% embed url="<https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FbTqiiDRWLmv3fJxQh7Y5%2Fday2.mp4?alt=media&token=240e4d00-3ab5-4ffd-8428-7a452df79aca>" %}


# Tresure Island

Find the right way

{% tabs %}
{% tab title="main.py" %}

```python
print("Welcome to the tresure island!")
print("Your mission is to find the tessure.\n")

print("You are walking ang getting near a crossroad, do you go on it or continue ahead?")
choice_1 = input("(go on it / continue): ")

if choice_1 == "go on it":
    print("\nYou didn't look and a car hit you.")
    exit()

else:
    print("\nYou see a smoke on the left and a huge tree on the right. Where do u go?")
    choice_2 = input("(smoke / tree): ")

    if choice_2 == "smoke":
        print("\nYou went in the middle of a gang war and got a bullet in your head.")
        exit()

    elif choice_2 == "tree":
        print("\nAn elf came to you saying he will help you find the treasure. Do you accept the help?")
        choice_3 = input("(yes / no): ")

        if choice_3 == "yes":
            print("\nHe took you to the 'X' spot and asks to take the showel and dig the treaure, do you give him the showel?")
            choice_4 = input("(yes / no): ")

            if choice_4 == "yes":
                print("\nHe used the showel and hit you in the head.")
                exit()

            elif choice_4 == "no":
                print("\nYou reject and kill him with the showel now that you know where the 'X' is.")

                print("You're thinking if its better to dig up the elf first or the 'X' spot.")
                choice_6 = input("(elf first/ X spot first): ")

                if choice_6 == "elf first":
                    print("\nWhile digging a hole for the elf, a group of elfs pushes you in it and digs you up.")
                    exit()

                elif choice_6 == "X spot first":
                    print("\nYou found the reasure and went home with it!!!")


        elif choice_3 == "no":
            print("\nYou walk to the tree alone and after some time find a 'X' spot. Do you dig it?")
            choice_5 = input("(yes / no ): ")

            if choice_5 == "yes":
                print("\nYou found the treasure!!!")

            elif choice_5 == "no":
                print("\nYou continue to search and a group of elfs kills you.")
                exit()


```

{% endtab %}

{% tab title="Second Tab" %}

{% endtab %}
{% endtabs %}

{% embed url="<https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FCKN3NxX7i8s0dRwhxdTH%2Fday3.mp4?alt=media&token=fc98a8ac-7399-4eae-86de-e948dcad85bb>" %}


# Rock, Paper, Scissors

{% tabs %}
{% tab title="main.py" %}

```python
import random

rock = '''
    _______
---'   ____)
      (_____)
      (_____)
      (____)
---.__(___)
'''

paper = '''
    _______
---'   ____)____
          ______)
          _______)
         _______)
---.__________)
'''

scissors = '''
    _______
---'   ____)____
          ______)
       __________)
      (____)
---.__(___)
'''


human_sign = " "
comp_sign = " "
result = ["Draw", "You Win", "Comp Wins"]


choice = int(input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors.\n: "))

if choice == 0:
    human_sign = rock
elif choice == 1:
    human_sign = paper
elif choice == 2:
    human_sign = scissors
else:
    print("Invalid input")


comp_choice = random.randint(0, 2)

if comp_choice == 0:
    comp_sign = rock
elif comp_choice == 1:
    comp_sign = paper
elif comp_choice == 2:
    comp_sign = scissors
else:
    print("Invalid input")

print("You:\n" + human_sign)
print("Comp:\n" + comp_sign)


def result_calculation():
    result_index = (choice - comp_choice + 3) % 3
    return result[result_index]

print (result_calculation())
```

{% endtab %}

{% tab title="Second Tab" %}

{% endtab %}
{% endtabs %}

{% embed url="<https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2F0rHyHE2axkHvbTDsNSsT%2F0705(3).mp4?alt=media&token=b5a3bb01-4913-4199-aed8-934c7fb7adf1>" %}


# Password Generator

define character length, symbols and nbers for a password generator, and it tells you if it is a good password.

{% tabs %}
{% tab title="main.py" %}

```python
import random

print("Welcome to the Password Generator!")

letters_number = int(input("What length do you want your password to be?: "))
symbols_number = int(input("How many symbols would you like in your password?: "))
numbers_number = int(input("How many numbers would you like in your password?: "))

letters = ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'a', 's', 'd',
           'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm']

symbols = ['!', '@', '#', '%', '^', '&', '*', '(', ')',
           '_', '-', '/', '*', '+', '~', '`']

numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']

#add upercase
def password_strength():

    if letters_number <= 5:
        print("Password Strength: Weak")

    if letters_number > 5  and symbols_number < 1 and numbers_number > 0:
        print("Password Strength: Medium")

    if letters_number >= 7 and symbols_number > 0 and numbers_number >= 2:
        print("Password Strength: Strong")


slice_end = (symbols_number + numbers_number)

password = []

for i in range(letters_number):
    password.append(random.choice(letters))

for j in range(symbols_number):
    password.append(random.choice(symbols))

for k in range(numbers_number):
    password.append(random.choice(numbers))

del password[0:slice_end]
random.shuffle(password)

final_password = ''.join(password)
print("\nFinal Password: " + final_password)


if symbols_number > letters_number:
    print("Error: Amount of desired symbols greather than password length")
if numbers_number > letters_number:
    print("Error: Amount of desired numbers greather than password length")
if numbers_number > (letters_number - symbols_number):
    print("Error: Desired password length: ", letters_number, ", amount of desired symbols and numbers:", (symbols_number + numbers_number))
#add "very strong" if user wants uppercase leeters with the symbols and numbers

password_strength()
```

{% endtab %}

{% tab title="Second Tab" %}

{% endtab %}
{% endtabs %}


# Reeborg's World

Online pythom maze game.

Link: <https://reeborg.ca/reeborg.html?lang=en&mode=python&menu=worlds%2Fmenus%2Freeborg_intro_en.json&name=Maze&url=worlds%2Ftutorial_en%2Fmaze1.json>

***

## Lost in a maze

Reeborg was exploring a dark maze and the battery in its flashlight ran out.

Write a program using an if/elif/else statement so Reeborg can find the exit. The secret is to have Reeborg follow along the right edge of the maze, turning right if it can, going straight ahead if it can’t turn right, or turning left as a last resort.

***

### What you need to know

* The functions **move()** and **turn\_left()**.
* Either the test front\_is\_clear() or wall\_in\_front(), right\_is\_clear() or wall\_on\_right(), and at\_goal().
* How to use a while loop and if/elif/else statements.
* It might be useful to know how to use the negation of a test (not in Python).

***

## Difficulty level

4/10

A robot located at (x, y) = (1, 5) carries no objects.

***

## Goal to achieve:

The final position of the robot must be (x, y) = (6, 4)

***

{% embed url="<https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FNcw7MDsfb24EZuOzI7XQ%2F0705.mp4?alt=media&token=5a0f44b0-a6ee-4c5b-9dc1-98c7d5132ca7>" %}


# Hangman

Guess the word before the man is hung!

{% tabs %}
{% tab title="art" %}

```python
stages = ['''
  +---+
  |   |
  O   |
 /|\  |
 / \  |
      |
=========
''', '''
  +---+
  |   |
  O   |
 /|\  |
 /    |
      |
=========
''', '''
  +---+
  |   |
  O   |
 /|\  |
      |
      |
=========
''', '''
  +---+
  |   |
  O   |
 /|   |
      |
      |
=========
''', '''
  +---+
  |   |
  O   |
  |   |
      |
      |
=========
''', '''
  +---+
  |   |
  O   |
      |
      |
      |
=========
''', '''
  +---+
  |   |
      |
      |
      |
      |
=========
''']

logo2 = '''
█▀▀ █▀█ █▀█ █▀▄   █░█░█ █▀█ █▀█ █▄▀ █
█▄█ █▄█ █▄█ █▄▀   ▀▄▀▄▀ █▄█ █▀▄ █░█ ▄
'''

logo3 = '''
█░█░█ █▀▀ █░░ █▀▀ █▀█ █▀▄▀█ █▀▀   ▀█▀ █▀█ ▀
▀▄▀▄▀ ██▄ █▄▄ █▄▄ █▄█ █░▀░█ ██▄   ░█░ █▄█ ▄

██╗░░██╗░█████╗░███╗░░██╗░██████╗░███╗░░░███╗░█████╗░███╗░░██╗
██║░░██║██╔══██╗████╗░██║██╔════╝░████╗░████║██╔══██╗████╗░██║
███████║███████║██╔██╗██║██║░░██╗░██╔████╔██║███████║██╔██╗██║
██╔══██║██╔══██║██║╚████║██║░░╚██╗██║╚██╔╝██║██╔══██║██║╚████║
██║░░██║██║░░██║██║░╚███║╚██████╔╝██║░╚═╝░██║██║░░██║██║░╚███║
╚═╝░░╚═╝╚═╝░░╚═╝╚═╝░░╚══╝░╚═════╝░╚═╝░░░░░╚═╝╚═╝░░╚═╝╚═╝░░╚══╝'''
```

{% endtab %}

{% tab title="wordlist" %}

```
WORDLIST = ['computer', 'banana', 'elephant', 'guitar', 'oxygen', 'jacket', 'diamond', 'pancake',
            'unicorn', 'bicycle', 'lighthouse', 'telescope', 'password', 'avalanche', 'crocodile',
            'fireworks', 'keyboard', 'kangaroo', 'zebra', 'pyramid', 'galaxy', 'octopus', 'tambourine',
            'helicopter', 'tornado', 'pineapple', 'parrot', 'waterfall', 'cocktail', 'volcano', 'avalanche',
            'squirrel', 'flamingo', 'cactus', 'dinosaur', 'rocket', 'umbrella', 'vampire', 'coconut',
            'haystack', 'tiramisu', 'igloo', 'origami', 'moonlight', 'gondola', 'toucan', 'saxophone',
            'oasis', 'yo-yo', 'espresso']

```

{% endtab %}

{% tab title="main" %}

```python
import random
import art
from wordlist import WORDLIST

lives = 6
used_letters = []
word = []

chosen_word = random.choice(WORDLIST)
word.extend(chosen_word)

welcome_message = art.logo3
win_message = art.logo2
start_photo = art.stages[lives]

print(welcome_message)
print("To win, guess the word!")
print(start_photo)

# Initialize displayed_word with underscores
displayed_word = ['_' for _ in chosen_word]

while lives != 0:
    print("\nused_letters: ", used_letters)
    print(' '.join(displayed_word))
    guess_letter = input("Guess a letter: ").lower()

    if not guess_letter.isalpha() or len(guess_letter) != 1:
        print("Input only a single letter.")
        continue

    if guess_letter not in used_letters:
        used_letters.append(guess_letter)
    else:
        print("Letter already used")
        continue

    if guess_letter in chosen_word:
        for index, letter in enumerate(chosen_word):
            if letter == guess_letter:
                displayed_word[index] = guess_letter
    else:
        lives -= 1
        start_photo = art.stages[lives]

    print(start_photo)

    if '_' not in displayed_word:
        print("Congratulations! You've guessed the word!")
        print(win_message)
        break

if lives == 0:
    print("You've run out of lives. The word was:", ''.join(chosen_word))

```

{% endtab %}
{% endtabs %}

{% embed url="<https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FC14YX0B0DkjrNvX1CYqo%2Fday7.mp4?alt=media&token=3a8a28ad-a67f-47f4-b095-52beb89d6b5e>" %}


# Cesar Chiper

Cesar encryptor and decryptor

{% tabs %}
{% tab title="main" %}

```python
from art import logo

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
            'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd',
            'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
            't', 'u', 'v', 'w', 'x', 'y', 'z']



def cesar(start_text, shift_amount, chiper_direction):
    end_text = ""

    if chiper_direction == "decode":
        shift_amount *= -1

    for char in start_text:
        if char.isalpha():
            position = alphabet.index(char)
            new_position = position + shift_amount
            end_text += alphabet[new_position]

        else:
            end_text += char

    print(f"Here's the {chiper_direction} result: {end_text}\n")


run = True

while run:
    print(logo)
    direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
    text = input("Type your message:\n").lower()
    shift = int(input("Type the shift number:\n"))

    if shift > 26:
        shift = shift % shift == 0

    cesar(text, shift, direction)

    choice = input("Do you want to run this program again?\nType 'yes' or 'no': ")
    if choice == "no":
        run = False
        print("Goodbye")
```

{% endtab %}

{% tab title="art" %}

```python
logo = """           
░█████╗░░█████╗░███████╗░██████╗░█████╗░██████╗░  ░█████╗░██╗██████╗░██╗░░██╗███████╗██████╗░
██╔══██╗██╔══██╗██╔════╝██╔════╝██╔══██╗██╔══██╗  ██╔══██╗██║██╔══██╗██║░░██║██╔════╝██╔══██╗
██║░░╚═╝███████║█████╗░░╚█████╗░███████║██████╔╝  ██║░░╚═╝██║██████╔╝███████║█████╗░░██████╔╝
██║░░██╗██╔══██║██╔══╝░░░╚═══██╗██╔══██║██╔══██╗  ██║░░██╗██║██╔═══╝░██╔══██║██╔══╝░░██╔══██╗
╚█████╔╝██║░░██║███████╗██████╔╝██║░░██║██║░░██║  ╚█████╔╝██║██║░░░░░██║░░██║███████╗██║░░██║
░╚════╝░╚═╝░░╚═╝╚══════╝╚═════╝░╚═╝░░╚═╝╚═╝░░╚═╝  ░╚════╝░╚═╝╚═╝░░░░░╚═╝░░╚═╝╚══════╝╚═╝░░╚═╝        
"""
```

{% endtab %}
{% endtabs %}


# Auction

{% tabs %}
{% tab title="main" %}

```python
from art import ITEMS
import random


item = random.choice(ITEMS)
print(item)


play = True
bidders = {}
while play:

    name = input("What is your name?: ")
    bid_amount = input("What is your bid?: ")
    more_bidders = input("Are there any more bidders?: ")
    bidders[name] = bid_amount


    if more_bidders == 'no':
        play = False
    else:
        continue

highest_bidder = max(bidders, key=bidders.get)
highest_bid = bidders[highest_bidder]
print(f"\nThe highest bidder is {highest_bidder} with a bid of ${highest_bid}.")



```

{% endtab %}

{% tab title="art" %}

```python
ITEMS = [
    '''
                                                        
                                                    
                                                    
                       :=**#######****++=--:.       
                   :*##+-----====----==+%%%%%#.     
               .-*#%%%%%%%%%%@@@%%%%%%@@@@%*--#+    
         ..:----::::::::.......:.::::::--------:.   
    ::----:::-======--------============-:.::--::.  
   ...:--#%%%%*.----------------------.=#%%##=.::.  
  :--::=%***=*##:::::::::::::::::::::.*#**=+*##.:.  
  =%#::%#+=::-*%:.:.................:-%**:::=#@-:.  
   .:::=#***=*#+.                     =#**+=*#:     
         :*#*+.                        .+#**=       
                                                    ''',
    '''
                                                                                      
                                                            
       !
       !
       ^
      / \
     /___\
    |=   =|
    |     |
    |     |
    |     |
    |     |
    |     |
    |     |
    |     |
    |     |
    |     |
   /|##!##|\
  / |##!##| \
 /  |##!##|  \
|  / ^ | ^ \  |
| /  ( | )  \ |
|/   ( | )   \|
    ((   ))
   ((  :  ))
   ((  :  ))
    ((   ))
     (( ))
      ( )
       .           
                                                            ''',
    '''
                 _
           /(_))
         _/   /
        //   /
       //   /
       /\__/
       \O_/=-.
   _  / || \  ^o
   \\/ ()_) \.
    ^^ <__> \()
      //||\\
     //_||_\\  ds
    // \||/ \\
   //   ||   \\
  \/    |/    \/
  /     |      \
 /      |       \
 '''
]
```

{% endtab %}
{% endtabs %}


# Continuous Calculator

Calculator taht adds up on the last result

{% tabs %}
{% tab title="main" %}

```python
def multiplication(a, b):
    multiplication_result = a * b
    return multiplication_result

def devision(a, b):
    devision_result = a / b
    return devision_result

def sum(a, b):
    sum_result = a + b
    return sum_result

def subtraction(a, b):
    subtraction_result = a - b
    return subtraction_result

run = True

first_number = int(input("1st number: "))

while run:
    first_operation = input("Choose operation (+, -, *, /): ")
    second_number = int(input("2nd number: "))

    operations = {
        '+' : sum,
        '-' : subtraction,
        '*' : multiplication,
        '/' : devision
    }

    calculation = operations[first_operation]
    answer = calculation(first_number, second_number)
    print(f"{first_number} {first_operation} {second_number} = {answer}")

    next = input(f"Type 'y' to continue calculation with {answer}, or type 'n' to exit: ")

    if next == 'y':
        run = True
        first_number = answer
    elif next == 'n':
        run = False
    else:
        print("Invalid input")
        run = False
        print("\nGoodbye")

```

{% endtab %}
{% endtabs %}


# BlackJack Game

{% tabs %}
{% tab title="main" %}

```python
from replit import clear
from art import logo
import random

def blackjack_game():

    def start_deal(cards):
        shuffle = random.choice(cards)
        return shuffle

    def player_loss(player, cpu):
        if sum(player) != 21 and sum(cpu) == 21:
            return True
        elif sum(player) == 21 and sum(cpu) == 21:
            return True

    def done_playing():
        player_sum = sum(player_cards)
        cpu_sum = sum(cpu_cards)
        print(f"Your hand is: {player_cards}, a total of {player_sum}")
        print(f"Comp hand is: {cpu_cards}, a total of {cpu_sum}")

        if sum(cpu_cards) > 21:
            print("The comp got a burst you win!")
        elif player_loss(player_cards, cpu_cards):
            print("You lose.")
        elif sum(player_cards) == 21 and sum(cpu_cards) != 21:
            print("You win!")
        elif sum(player_cards) > 21:
            print("It's a burs you lose.")
        elif player_sum == cpu_sum:
            print("You win!")
        else:
            print("You lose!")

        play_again = input("Do you want to play again? (y / n): ")

        if play_again == 'y':
            clear()
            blackjack_game()
        else:
            if play_again == 'n':
                print("Goodbye.")


    def keep_playing():
        shuffled = start_deal(cards)
        player_cards.append(shuffled)
        cpu_cards.append(start_deal(cards))
        player_sum = sum(player_cards)
        cpu_sum = sum(cpu_cards)

        if 11 in player_cards and player_sum >= 21:
            ace = player_cards.index(11)
            player_cards[ace] = 1
            player_sum = sum(player_cards)
        print(f"Your hand is: {player_cards}, a total of {player_sum}.")
        print(f"The computer's hand is {cpu_cards}, a total of {cpu_sum}.")
        if player_sum > 21:
            print("It's a bust, you lose.")
            play_again = input("Do you want to play again? Type 'y' or 'n': ")
            if play_again == 'y':
                clear()
                blackjack_game()
            elif play_again == 'n':
                print("Thanks for playing. Goodbye.")
        if player_sum <= 21:
            hit = input("Type 'y' to get another card, type 'n' to pass: ")
            if hit == 'y':
                keep_playing()
            elif hit == 'n':
                done_playing()


    print(logo)
    cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
    player_cards = []
    cpu_cards = []
    player_cards.append(start_deal(cards))
    player_cards.append(start_deal(cards))
    cpu_cards.append(start_deal(cards))

    print(f"Your cards: {player_cards}")
    print(f"The computer's first card: {cpu_cards}")
    hit = input("Type 'y' to get another card, type 'n' to pass: ")

    if hit == 'n':
        done_playing()
    elif hit == 'y':
        keep_playing()

blackjack_game()
```

{% endtab %}

{% tab title="art" %}

```python
logo =  """
.------.            _     _            _    _            _    
|A_  _ |.          | |   | |          | |  (_)          | |   
|( \/ ).-----.     | |__ | | __ _  ___| | ___  __ _  ___| | __
| \  /|K /\  |     | '_ \| |/ _` |/ __| |/ / |/ _` |/ __| |/ /
|  \/ | /  \ |     | |_) | | (_| | (__|   <| | (_| | (__|   < 
`-----| \  / |     |_.__/|_|\__,_|\___|_|\_\ |\__,_|\___|_|\_\\
      |  \/ K|                            _/ |                
      `------'                           |__/           
"""
```

{% endtab %}
{% endtabs %}


# Guess The Number

Guess the number while the computer is giving you high/low hints

{% tabs %}
{% tab title="main" %}

```python
from art import logo
import random

def play_game():
    difficulty_easy = 10
    difficulty_hard = 5

    number_picker = random.randint(1, 100)

    print("\nWelcome to \n" + logo)
    print("I'm thinking of a number between 1 and 100, try to guess it!")

    difficulty = input("Choose a difficulty. Type 'easy' or 'hard': ")

    if difficulty == 'easy':
        lives = difficulty_easy
        while lives != 0:
            print("\nYou have", lives, "guesses left")
            guess = int(input("Take a guess: "))

            if guess == number_picker:
                print("Correct! The number was ", number_picker)
                break
            elif guess < number_picker:
                print("Higher")
                lives -= 1
            elif guess > number_picker:
                print("Lower")
                lives -= 1

    elif difficulty == 'hard':
        lives = difficulty_hard
        while lives != 0:
            print("\nYou have", lives, "guesses left")
            guess = int(input("Take a guess: "))

            if guess == number_picker:
                print("Correct! The number was ", number_picker)
                break
            elif guess < number_picker:
                print("Higher")
                lives -= 1
            elif guess > number_picker:
                print("Lower")
                lives -= 1

    if lives == 0:
        print(f"\nSorry, you've run out of guesses. The number was {number_picker}.")

while True:
    play_game()
    play_again = input("Do you want to play again? ('yes' / 'no'): ").lower()
    if play_again != 'yes':
        print("Goodbye.")
        break

```

{% endtab %}

{% tab title="art" %}

```python
logo = """
█████▀███████████████████████████████████████████████████████████████████████████████████████
█─▄▄▄▄█▄─██─▄█▄─▄▄─█─▄▄▄▄█─▄▄▄▄███─▄─▄─█─█─█▄─▄▄─███▄─▀█▄─▄█▄─██─▄█▄─▀█▀─▄█▄─▄─▀█▄─▄▄─█▄─▄▄▀█
█─██▄─██─██─███─▄█▀█▄▄▄▄─█▄▄▄▄─█████─███─▄─██─▄█▀████─█▄▀─███─██─███─█▄█─███─▄─▀██─▄█▀██─▄─▄█
▀▄▄▄▄▄▀▀▄▄▄▄▀▀▄▄▄▄▄▀▄▄▄▄▄▀▄▄▄▄▄▀▀▀▀▄▄▄▀▀▄▀▄▀▄▄▄▄▄▀▀▀▄▄▄▀▀▄▄▀▀▄▄▄▄▀▀▄▄▄▀▄▄▄▀▄▄▄▄▀▀▄▄▄▄▄▀▄▄▀▄▄▀
"""
```

{% endtab %}
{% endtabs %}


# Higher Lower

guess who has more insta followers

{% tabs %}
{% tab title="main.py" %}

```python
from replit import clear
import time




def play_game():
    print(art.logo)
    score = 0
    game_continue = True

    first_person = random.choice(list(people.items()))
    second_person = random.choice(list(people.items()))

    while game_continue:
        while first_person == second_person:
            second_person = random.choice(list(people.items()))

        clear()
        print(f"Score: {score}")
        time.sleep(2)
        print(f"\nCompare A: {first_person[0]}")
        print(art.vs)
        print(f"Compare B: {second_person[0]}")

        answer = input("Who do you think has more followers (A / B): ").upper()

        first_person_followers = first_person[1]
        second_person_followers = second_person[1]

        if (first_person_followers > second_person_followers and answer == 'A') or (
                second_person_followers > first_person_followers and answer == 'B'):
            score += 1
            print("Correct!")
            time.sleep(2)
            first_person = second_person
            second_person = random.choice(list(people.items()))
        else:
            game_continue = False
            print("Incorrect! Your score was:", score)
            time.sleep(2)


while True:
    play_game()
    play_again = input("Play again? (yes / no): ").lower()

    if play_again == 'no':
        break

```

{% endtab %}

{% tab title="art.py" %}

```python
logo = """    __  ___       __             
   / / / (_)___ _/ /_  ___  _____
  / /_/ / / __ `/ __ \/ _ \/ ___/
 / __  / / /_/ / / / /  __/ /    
/_/ ///_/\__, /_/ /_/\___/_/     
   / /  /____/_      _____  _____
  / /   / __ \ | /| / / _ \/ ___/
 / /___/ /_/ / |/ |/ /  __/ /    
/_____/\____/|__/|__/\___/_/     
"""

vs = """ _    __    
| |  / /____
| | / / ___/
| |/ (__  ) 
|___/____(_)
"""
```

{% endtab %}

{% tab title="game\_data.py" %}

```python
people = {
    "Neymar, football player, from Brasil" : 223000000,
    "Ronaldo, football player, from Porugal" : 635000000,
    "Messi, football player, from Argentina" : 503000000,
    "Yamal, football player, from Spain" : 16800000,
    "Mbappe, football player, from France" : 120000000,
    "Erling Haaland, football player, from Norway" : 38500000,
    "Jude Belingham, football player, from England" : 35100000
}
```

{% endtab %}
{% endtabs %}


# Coffee Machine

Order your coffee

{% tabs %}
{% tab title="main.py" %}

```python
from menu import Menu, MenuItem
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine

#list of drinks
espresso = MenuItem("espresso", 50, 0, 18, 1.5)
latte = MenuItem("latte", 200, 150, 24, 2.5)
cappuccino = MenuItem("cappuccino", 250, 100, 24, 3.0)

#For ordering drinks and checking if drink is available
menu = Menu()

#Printing report of all resources, checking if resources are sufficien. making coffee
coffee_maker = CoffeeMaker()

#Printing report and taking payment
money_machine = MoneyMachine()

on = True
while on:
    choice = input(f"What would you like? Choose between espresso, latte or cappuccino: ")
    if choice == 'off':
        print("Have a nice day!")
        on = False
    elif choice == 'report':
        coffee_maker.report()
        money_machine.report()
    else:
        coffee_choice = menu.find_drink(choice)
        if coffee_maker.is_resource_sufficient(espresso) and money_machine.make_payment(espresso.cost):
            coffee_maker.make_coffee(coffee_choice)


```

{% endtab %}

{% tab title="coffee\_maker.py" %}

```python
class CoffeeMaker:
    """Models the machine that makes the coffee"""
    def __init__(self):
        self.resources = {
            "water": 300,
            "milk": 200,
            "coffee": 100
        }

    def report(self):
        """Prints a report of all resources"""
        print(f"Water: {self.resources['water']}ml")
        print(f"Milk: {self.resources['milk']}ml")
        print(f"Coffee: {self.resources['coffee']}g")

    def is_resource_sufficient(self, drink):
        """Returns True when order can be made, False if ingredients are insufficient"""
        can_make = True
        for item in drink.ingredients:
            if drink.ingredients[item] > self.resources[item]:
                print(f"Sorry there is not enought {item}.")
                can_make = False
        return can_make

    def make_coffee(self,order):
        """Deducts the required ingredients from the resources"""
        for item in order.ingredients:
            self.resources[item] -= order.ingredients[item]
        print(f"Here is your {order.name} ☕️. Enjoy! ")
```

{% endtab %}

{% tab title="menu.py" %}

```python
class MenuItem:
    """Models each Menu Item."""
    def __init__(self, name, water, milk, coffee, cost):
        self.name = name
        self.cost = cost
        self.ingredients = {
            "water": water,
            "milk": milk,
            "coffee": coffee
        }

class Menu:
    """Models the Menu with drinks."""
    def __init__(self):
        self.menu = [
            MenuItem(name="latte", water=200, milk=150, coffee=24, cost=2.5),
            MenuItem(name="espresso", water=50, milk=0, coffee=18, cost=1.5),
            MenuItem(name="cappuccino", water=250, milk=50, coffee=24, cost=3),
        ]

    def get_items(self):
        """Returns all the names of the available menu items"""
        options = ""
        for item in self.menu:
            options += f"{item.name}/"
        return options

    def find_drink(self, order_name):
        """Searches the menu for a particular drink by name. Returns that item if it exists, othervise None"""
        for item in self.menu:
            if item.name == order_name:
                return item
        print("Sorry that item is not available")
```

{% endtab %}

{% tab title="money\_machine.py" %}

```python
class MoneyMachine:

    CURRENCY = "$"

    COIN_VALUES = {
        "quarters": 0.25,
        "dimes": 0.10,
        "nickles": 0.05,
        "pennies": 0.01
    }

    def __init__(self):
        self.profit = 0
        self.money_recived = 0

    def report(self):
        """prints the current profit"""
        print(f"Money: {self.CURRENCY}{self.profit}")

    def process_coins(self):
        """Returns the total calculated from coins inserted"""
        print("Please insert coins.")
        for coin in self.COIN_VALUES:
            self.money_recived += int(input(f"How many {coin}?: ")) * self.COIN_VALUES[coin]
        return self.money_recived

    def make_payment(self,cost):
        """Returns True when payment is accepted, or False if insufficient"""
        self.process_coins()
        if self.money_recived > cost:
            change = round(self.money_recived - cost, 2)
            print(f"Here is {self.CURRENCY}{change} in change.")
            self.profit += cost
            self.money_recived = 0
            return True
        else:
            print("Sorry that's not enough money. Money refunded.")
            self.money_received = 0
            return False
```

{% endtab %}
{% endtabs %}


# Coffee Machine (easy)

Order your coffee

{% tabs %}
{% tab title="main.py" %}

```python
MENU = {
    "espresso": {
        "ingredients": {
            "water": 100,
            "milk": 0,
            "coffee": 75
        },
        "cost": 2.5
    },
    "latte": {
        "ingredients": {
            "water": 80,
            "milk": 80,
            "coffee": 55
        },
        "cost": 2
    },
    "cappuccino": {
        "ingredients": {
            "water": 100,
            "milk": 50,
            "coffee": 65
        },
        "cost": 1.5
    }
}

resources = {
    "water": 500,
    "milk": 500,
    "coffee": 500
}

money = 0

def what_would_you_like():
    pick = input("What would you like? (espresso, latte, cappuccino): ").lower()

    if pick in MENU:
        return pick
    elif pick == 'off':
        machine_off()
    elif pick == 'report':
        report()
    else:
        print("Invalid coffee pick")
        return None

def machine_off():
    print("Turning off the machine...")
    exit()

def report():
    print(f"Water: {resources['water']}ml")
    print(f"Milk: {resources['milk']}ml")
    print(f"Coffee: {resources['coffee']}g")
    print(f"Money: ${money}")

def resources_check(coffee_choice):
    ingredients = MENU[coffee_choice]['ingredients']
    for item in ingredients:
        if ingredients[item] > resources[item]:
            print(f"Sorry. Not enough {item} in the machine.")
            return False
    return True

def add_coins():
    print("Insert coins:")
    quarters = int(input("quarters: ")) * 0.25
    dimes = int(input("dimes: ")) * 0.10
    nickels = int(input("nickels: ")) * 0.05
    pennies = int(input("pennies: ")) * 0.01
    total = quarters + dimes + nickels + pennies
    return total

def process_transaction(coffee_choice, money_received):
    global money
    coffee_cost = MENU[coffee_choice]['cost']
    if money_received >= coffee_cost:
        change = round(money_received - coffee_cost, 2)
        print(f"Here is ${change} in change.")
        money += coffee_cost
        return True
    else:
        print(f"Not enough money. You need ${coffee_cost - money_received} more.")
        print("Money refunded.")
        return False

def ingredients_deduction(coffee_choice):
    ingredients = MENU[coffee_choice]['ingredients']
    for item in ingredients:
        resources[item] -= ingredients[item]

def coffee_machine():
    while True:
        choice = what_would_you_like()
        if choice is None:
            continue
        if choice == 'report':
            report()
            continue
        if choice == 'off':
            machine_off()
            continue
        if resources_check(choice):
            money_received = add_coins()
            if process_transaction(choice, money_received):
                ingredients_deduction(choice)
                print(f"Here is your {choice}. Enjoy!")

if __name__ == "__main__":
    coffee_machine()
```

{% endtab %}
{% endtabs %}


# Questionnare

{% tabs %}
{% tab title="main.py" %}

```python
from question_model import Question
from data import question_data
from quiz_brain import QuizBrain

question_bank = []
for question in question_data:
    question_text = question["text"]
    question_answer = question["answer"]
    new_queston = Question(question_text, question_answer)
    question_bank.append(new_queston)

quiz = QuizBrain(question_bank)

while quiz.still_has_questions():
    quiz.next_question()

print(f"Thanks for completing that!\nYour final score is: {quiz.score}/{quiz.question_number}")
```

{% endtab %}

{% tab title="data.py" %}

```python
question_data = [
    {"text": "A slug's blood is green.", "answer": "True"},
    {"text": "The loudest animal is the African Elephant.", "answer": "False"},
    {"text": "Approximately one quarter of human bones are in the feet.", "answer": "True"},
    {"text": "The total surface area of a human lungs is the size of a football pitch.", "answer": "True"},
    {"text": "In West Virginia, USA, if you accidentally hit an animal with your car, you are free to take it home "
             "to eat.", "answer": "True"},
    {"text": "In London, UK, if you happen to die in the House of Parliament, you are entitled to a state funeral."
        , "answer": "False"},
    {"text": "It is illegal to pee in the Ocean in Portugal.", "answer": "True"},
    {"text": "You can lead a cow down stairs but not up stairs.", "answer": "False"},
    {"text": "Google was originally called 'Backrub'.", "answer": "True"},
    {"text": "Buzz Aldrin's mother's maiden name was 'Moon'.", "answer": "True"},
    {"text": "No piece of square dry paper can be folded in half more than 7 times.", "answer": "False"},
    {"text": "A few ounces of chocolate can to kill a small dog.", "answer": "True"}

]
```

{% endtab %}

{% tab title="question\_model.py" %}

```python
class Question:

    def __init__(self, text, answer):
        self.text = text
        self.answer = answer
```

{% endtab %}

{% tab title="quiz\_brain.py" %}

```python
class QuizBrain:

    def __init__(self, question_list):
        self.question_number = 0
        self.question_list = question_list
        self.score = 0

    def still_has_questions(self):
        return self.question_number < len(self.question_list)

    def next_question(self):
        current_question = self.question_list[self.question_number]
        self.question_number += 1
        user_answer = input(f"Q.{self.question_number}: {current_question.text} (True/False): ")
        self.check_answer(user_answer, current_question.answer)

    def check_answer(self, user_answer, correct_answer):
        if user_answer.lower() == correct_answer.lower():
            print("You got it right!")
            self.score += 1
        else:
            print("That is incorrect")
        print(f"The correct answer was: {correct_answer}.")
        print(f"Your current score is {self.score}/{self.question_number}.")
        print("\n")
```

{% endtab %}
{% endtabs %}


# Circle Drawings

A turtle drawing circles

{% tabs %}
{% tab title="main.py" %}

```python
import turtle
import random
from circle import draw_circle

COLORS = [(236, 69, 96), (220, 50, 10), (180, 43, 96), (157, 128, 36), (20, 156, 51), (100,150,200)]
turtle.colormode(255)

t = turtle.Turtle()

start_x = -250
start_y = -250
x_axis = start_x
y_axis = start_y

t.speed(6)
t.shape("turtle")


for row in range(10):
    for col in range(10):
        color_picker = random.choice(COLORS)
        t.up()
        t.goto(x_axis, y_axis)
        t.down()
        t.begin_fill()
        t.fillcolor(color_picker)
        draw_circle(t)
        t.end_fill()
        x_axis += 50
    x_axis = start_x
    y_axis += 50

turtle.done()

```

{% endtab %}

{% tab title="circle.py" %}

<pre class="language-python"><code class="lang-python"><strong>def draw_circle(turtle):
</strong>    turtle.circle(20)
</code></pre>

{% endtab %}
{% endtabs %}


# Turtle Race

Turtles racing. Bet on 'em

{% tabs %}
{% tab title="main.py" %}

```python
import turtle
import random

wn = turtle.Screen()
wn.setup(width=800, height=600)

COLORS = ["blue", "red", "yellow", "green", "black", "orange", "pink", "purple"]
SPEED = [0, 1, 3, 6, 10]
NUM_TURTLES = 8
user_bet = wn.textinput(title="Make your bet", prompt="Which turtle will win the race? Enter a color: ")

def create_turtle(color, y_position):
    t = turtle.Turtle()
    t.speed(0)
    t.hideturtle()
    t.shape("turtle")
    t.color(color)
    t.penup()
    t.goto(-350, y_position)
    t.showturtle()
    return t

# Initialize turtles
turtles = []
start_y = -250
for i in range(NUM_TURTLES):
    color_picker = COLORS[i]
    speed_picker = random.choice(SPEED)
    t = create_turtle(color_picker, start_y + i * 50)
    t.speed(speed_picker)
    turtles.append(t)

# Start the race
race_on = True
while race_on:
    for t in turtles:
        t.forward(random.randint(1, 20))

        if t.xcor() >= 350:
            race_on = False
            winning_turtle = t.color()[0]
            if winning_turtle == user_bet:
                print(f"You've won! The {winning_turtle} turtle is the winner!")
            else:
                print(f"You've lost! The {winning_turtle} turtle is the winner!")
            break

wn.exitonclick()

```

{% endtab %}

{% tab title="racers.py" %}

```python
import turtle
import random

COLORS = ["blue", "red", "yellow", "green", "black", "orange", "pink"]
SPEED = [0, 1, 3, 6, 10]
random_color = random.choice(COLORS)
random_speed = random.choice(SPEED)

def turtles(t, number):

    for racer in range(number):
        y_axis = -250
        t.shape("turtle")
        t.up()
        t.color(random_color)
        t.goto(-250, y_axis)
        t.speed(random_speed)
        t.forward(1000)
        for range in number:
            y_axis += 50

```

{% endtab %}
{% endtabs %}


# Snake Game (easy)

{% tabs %}
{% tab title="main.py" %}

```python
from turtle import Screen, Turtle
from snake import Snake
import time

screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("Snake Game")
screen.tracer(0)

snake = Snake()

screen.listen()
screen.onkey(snake.up, "Up")
screen.onkey(snake.down, "Down")
screen.onkey(snake.left, "Left")
screen.onkey(snake.right, "Right")

game_is_on = True

while game_is_on:
    screen.update()
    time.sleep(0.1)

    snake.move()

screen.exitonclick()
```

{% endtab %}

{% tab title="snake.py" %}

```python
from turtle import Turtle
START_POSITION = [(0,0), (-20, 0), (40,0)]
MOVE_DISTANCE = 20
UP = 90
DOWN = 270
LEFT = 180
RIGHT = 0


class Snake:

    def __init__(self):
        self.segments = []
        self.create_snake()
        self.head = self.segments[0]

    def create_snake(self):
        for position in START_POSITION:
            new_segment = Turtle("square")
            new_segment.color("white")
            new_segment.penup()
            new_segment.goto(position)
            self.segments.append(new_segment)

    def move(self):
        for seg_num in range(len(self.segments) - 1, 0 , -1):
            new_x = self.segments[seg_num - 1].xcor()
            new_y = self.segments[seg_num - 1].ycor()
            self.segments[seg_num].goto(new_x, new_y)
        self.head.forward(MOVE_DISTANCE)

    def up(self):
        if self.head.heading() != DOWN:
            self.head.setheading(UP)

    def down(self):
        if self.head.heading() != UP:
            self.head.setheading(DOWN)

    def left(self):
        if self.head.heading() != RIGHT:
            self.head.setheading(LEFT)

    def right(self):
        if self.head.heading() != LEFT:
            self.head.setheading(RIGHT)
```

{% endtab %}
{% endtabs %}


# Snake Game (OOP)

{% tabs %}
{% tab title="main.py" %}

```python
import time

screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("Snake Game")
screen.tracer(0)

snake = Snake()
food = Food()
scoreboard = Scoreboard()

screen.listen()
screen.onkey(snake.up, "Up")
screen.onkey(snake.down, "Down")
screen.onkey(snake.left, "Left")
screen.onkey(snake.right, "Right")
scoreboard.start_scorebord()


game_is_on = True
while game_is_on:
    screen.update()
    time.sleep(0.1)
    snake.move()

    if snake.head.distance(food) < 15:
        scoreboard.increase_scoreboard()
        snake.extend()
        food.refresh()

    if snake.head.xcor() > 290 or snake.head.xcor() < -295 or snake.head.ycor() > 295 or snake.head.ycor() < -295:
        game_is_on = False
        scoreboard.game_over()

    for segment in snake.segments[1:]:
        if snake.head.distance(segment) < 10:
            game_is_on = False
            scoreboard.game_over()

screen.exitonclick()
```

{% endtab %}

{% tab title="food.py" %}

```python
from turtle import Turtle
import random

class Food(Turtle):

    def __init__(self):
        super().__init__()
        self.shape("circle")
        self.penup()
        self.shapesize(stretch_len=0.5, stretch_wid=0.5)
        self.color("red")
        self.speed(0)
        self.refresh()

    def refresh(self):
        random_x = random.randint(-28, 28) * 10
        random_y = random.randint(-28, 28) * 10
        self.goto(random_x, random_y)
```

{% endtab %}

{% tab title="scoreboard.py" %}

```python
from turtle import Turtle

ALINGMENT = 'center'
FONT = ('Times New Roman', 24, 'bold')


class Scoreboard(Turtle):

    def __init__(self):
        super().__init__()
        self.score = 0
        self.hideturtle()
        self.penup()
        self.color("White")
        self.goto(0,260)

    def start_scorebord(self):
        self.write(arg=f"Score: {self.score}", align=ALINGMENT, font=FONT)

    def increase_scoreboard(self):
        self.clear()
        self.score +=1
        self.start_scorebord()

    def game_over(self):
        self.goto(0,0)
        self.write(arg="GAME OVER", align=ALINGMENT, font=FONT)

```

{% endtab %}

{% tab title="snake.py" %}

```python
from turtle import Turtle
START_POSITION = [(0,0), (-20, 0), (40,0)]
MOVE_DISTANCE = 20
UP = 90
DOWN = 270
LEFT = 180
RIGHT = 0


class Snake:

    def __init__(self):
        self.segments = []
        self.create_snake()
        self.head = self.segments[0]

    def create_snake(self):
        for position in START_POSITION:
            self.add_segment(position)

    def add_segment(self, position):
            new_segment = Turtle("square")
            new_segment.color("white")
            new_segment.penup()
            new_segment.goto(position)
            self.segments.append(new_segment)

    def extend(self):
        self.add_segment(self.segments[-1].position())

    def move(self):
        for seg_num in range(len(self.segments) - 1, 0 , -1):
            new_x = self.segments[seg_num - 1].xcor()
            new_y = self.segments[seg_num - 1].ycor()
            self.segments[seg_num].goto(new_x, new_y)
        self.head.forward(MOVE_DISTANCE)

    def up(self):
        if self.head.heading() != DOWN:
            self.head.setheading(UP)

    def down(self):
        if self.head.heading() != UP:
            self.head.setheading(DOWN)

    def left(self):
        if self.head.heading() != RIGHT:
            self.head.setheading(LEFT)

    def right(self):
        if self.head.heading() != LEFT:
            self.head.setheading(RIGHT)
```

{% endtab %}
{% endtabs %}


# Tennis

{% tabs %}
{% tab title="main.py" %}

```python
import time

screen = turtle.Screen()
screen.setup(800, 600)
screen.bgcolor("black")
screen.title("Ping Pong")
screen.tracer()

r_paddle = Paddle((350, 0))
l_paddle = Paddle((-350, 0))
ball = Ball()
scoreboard = Scoreboard()

screen.listen()
screen.onkeypress(r_paddle.go_up, "Up")
screen.onkeypress(r_paddle.go_down, "Down")
screen.onkeypress(l_paddle.go_up, "w")
screen.onkeypress(l_paddle.go_down, "s")

game_on = True
while game_on:
    time.sleep(ball.move_speed)
    screen.update()
    ball.move()

    if ball.ycor() > 280 or ball.ycor() < -280:
        ball.bounce_y()

    if ball.distance(r_paddle) < 50 and ball.xcor() > 320 or ball.distance(l_paddle) < 50 and ball.xcor() < -320:
        ball.bounce_x()

    if ball.xcor() > 380:
        ball.reset_position()
        scoreboard.l_point()

    if ball.xcor() < -380:
        ball.reset_position()
        scoreboard.r_point()

screen.exitonclick()
```

{% endtab %}

{% tab title="ball.py" %}

```python
from turtle import Turtle

class Ball(Turtle):

    def __init__(self):
        super().__init__()
        self.shape("circle")
        self.color("white")
        self.penup()
        self.move_speed = 0.005
        self.x_move = 10
        self.y_move = 10

    def move(self):
        new_x = self.xcor() + self.x_move
        new_y = self.ycor() + self.y_move
        self.goto(new_x, new_y)

    def bounce_x(self):
        self.x_move *= -1
        self.move_speed *= 1

    def bounce_y(self):
        self.y_move *= -1
        self.move_speed *= 1

    def reset_position(self):
        self.home()
        self.move_speed = 0.005
        self.bounce_x()

```

{% endtab %}

{% tab title="paddle.py" %}

```python
from turtle import Turtle

class Paddle(Turtle):

    def __init__(self,position):
        super().__init__()
        self.shape("square")
        self.color("white")
        self.shapesize(stretch_wid=5, stretch_len=1)
        self.penup()
        self.goto(position)

    def go_up(self):
        new_y = self.ycor() + 20
        self.goto(self.xcor(), new_y)

    def go_down(self):
        new_y = self.ycor() - 20
        self.goto(self.xcor(), new_y)



```

{% endtab %}

{% tab title="scoreboard.py" %}

```python
from turtle import Turtle

class Scoreboard(Turtle):

    def __init__(self):
        super().__init__()
        self.color("white")
        self.penup()
        self.hideturtle()
        self.l_score = 0
        self.r_score = 0
        self.update()

    def update(self):
        self.clear()
        self.goto(-100, 190)
        self.write(self.l_score, align="center", font=("Times New Roman", 80, "normal"))
        self.goto(100,190)
        self.write(self.r_score, align="center", font=("Times New Roman", 80, "normal"))

    def l_point(self):
        self.l_score += 1
        self.update()

    def r_point(self):
        self.r_score += 1
        self.update()

```

{% endtab %}
{% endtabs %}


# Cross The Road

{% tabs %}
{% tab title="main.py" %}

```python
import time
import turtle
from turtle import Turtle
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard

screen = turtle.Screen()
screen.setup(width=600, height=600)
screen.tracer(0)

player = Player()
car_manager = CarManager()
scoreboard = Scoreboard()

screen.listen()
screen.onkeypress(player.go_up, "Up")

game_is_on = True
while game_is_on:
    time.sleep(0.05)
    screen.update()

    car_manager.create_car()
    car_manager.move_cars()

    #Detect collision with car
    for car in car_manager.all_cars:
        if car.distance(player) <20:
            game_is_on = False
            scoreboard.game_over()

    #Detect successful crossing
    if player.is_at_finish_line():
        player.go_to_start()
        car_manager.level_up()
        scoreboard.increse_level()

```

{% endtab %}

{% tab title="car\_manager.py" %}

```python
from turtle import Turtle
import random

COLORS = ["red", "orange", "yellow", "blue", "purple"]
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 10

class CarManager:

    def __init__(self):
        self.all_cars = []
        self.car_speed = STARTING_MOVE_DISTANCE

    def create_car(self):
        random_choice = random.randint(1, 6)
        if random_choice == 1:
            new_car = Turtle("square")
            new_car.penup()
            new_car.color(random.choice(COLORS))
            random_y = random.randint(-220, 250)
            new_car.goto(300, random_y)
            self.all_cars.append(new_car)

    def move_cars(self):
        for car in self.all_cars:
            car.backward(self.car_speed)

    def level_up(self):
        self.car_speed += MOVE_INCREMENT
```

{% endtab %}

{% tab title="player.py" %}

```python
from turtle import Turtle

STARTING_POSITION = (0, -250)
MOVE_DISTANCE = 10
FINISH_LINE_Y = 280

class Player(Turtle):

    def __init__(self):
        super().__init__()
        self.shape("turtle")
        self.color("black")
        self.penup()
        self.go_to_start()
        self.setheading(90)

    def go_up(self):
        self.forward(MOVE_DISTANCE)

    def go_to_start(self):
        self.goto(STARTING_POSITION)

    def is_at_finish_line(self):
        if self.ycor() > FINISH_LINE_Y:
            return True
        else:
            return False
```

{% endtab %}

{% tab title="scoreboard.py" %}

```python
from turtle import Turtle

FONT = ("Courier", 24, "normal")


class Scoreboard(Turtle):

    def __init__(self):
        super().__init__()
        self.level = 1
        self.hideturtle()
        self.penup()
        self.goto(-280, 250)
        self.update_scoreboard()

    def update_scoreboard(self):
        self.clear()
        self.write(f"Level:  {self.level}", align="left", font=FONT)

    def increse_level(self):
        self.level += 1
        self.update_scoreboard()

    def game_over(self):
        self.goto(0, 0)
        self.write(f"GAME OVER", align="center", font=FONT)
```

{% endtab %}
{% endtabs %}


# Write The States

{% tabs %}
{% tab title="main.py" %}

```python
import turtle
import pandas

data = pandas.read_csv("50_states.csv")
screen = turtle.Screen()
screen.title("U.S. States Game")
image = "blank_states_img.gif"
screen.addshape(image)
turtle.shape(image)

t = turtle.Turtle()
t.hideturtle()
t.penup()

guessed_states = []
states_list = data.state.to_list()

while len(guessed_states) < 50:
    answer = screen.textinput(title=f"{len(guessed_states)}/50 States Guessed", prompt="Name a State").title()

    if answer == "Exit":
        missing_states = []
        for state in states_list:
            if state not in guessed_states:
                missing_states.append(state)
        new_data = pandas.DataFrame(missing_states)
        new_data.to_csv("states_to_learn.csv")
        break

    if answer in states_list:
        if answer not in guessed_states:
            guessed_states.append(answer)
            check_answer = data[data.state == answer]
            x_axis, y_axis = int(check_answer.x), int(check_answer.y)
            t.goto(x_axis, y_axis)
            t.write(f"{answer}")
```

{% endtab %}

{% tab title="50\_states.csv" %}

```csv
state,x,y
Alabama,139,-77
Alaska,-204,-170
Arizona,-203,-40
Arkansas,57,-53
California,-297,13
Colorado,-112,20
Connecticut,297,96
Delaware,275,42
Florida,220,-145
Georgia,182,-75
Hawaii,-317,-143
Idaho,-216,122
Illinois,95,37
Indiana,133,39
Iowa,38,65
Kansas,-17,5
Kentucky,149,1
Louisiana,59,-114
Maine,319,164
Maryland,288,27
Massachusetts,312,112
Michigan,148,101
Minnesota,23,135
Mississippi,94,-78
Missouri,49,6
Montana,-141,150
Nebraska,-61,66
Nevada,-257,56
New Hampshire,302,127
New Jersey,282,65
New Mexico,-128,-43
New York,236,104
North Carolina,239,-22
North Dakota,-44,158
Ohio,176,52
Oklahoma,-8,-41
Oregon,-278,138
Pennsylvania,238,72
Rhode Island,318,94
South Carolina,218,-51
South Dakota,-44,109
Tennessee,131,-34
Texas,-38,-106
Utah,-189,34
Vermont,282,154
Virginia,234,12
Washington,-257,193
West Virginia,200,20
Wisconsin,83,113
Wyoming,-134,90
```

{% endtab %}

{% tab title="blank\_states\_img.gif" %}

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2F7MlKrXnO6u7Kb7wdgPsk%2Fimage.png?alt=media&amp;token=8a371533-6072-4d59-ac7b-cb48ee6fc2e2" alt=""><figcaption></figcaption></figure>

{% endtab %}
{% endtabs %}


# Phonetic Alphabet

{% tabs %}
{% tab title="main.py" %}

```python
import pandas as pd

data = pd.read_csv("nato_phonetic_alphabet.csv")

phonetic_dict = {row.letter: row.code for (index, row) in data.iterrows()}


def generate_phonetic():
    word = input("Enter a word: ").upper()
    try:
        output_list = [phonetic_dict[letter] for letter in word]
    except KeyError:
        print("Sorry, only letters in the alphabet please.")
        generate_phonetic()
    else:
        print(output_list)

generate_phonetic()
```

{% endtab %}

{% tab title="nato\_phonetoc\_alphabet.csv" %}

```csv
letter,code
A,Alfa
B,Bravo
C,Charlie
D,Delta
E,Echo
F,Foxtrot
G,Golf
H,Hotel
I,India
J,Juliet
K,Kilo
L,Lima
M,Mike
N,November
O,Oscar
P,Papa
Q,Quebec
R,Romeo
S,Sierra
T,Tango
U,Uniform
V,Victor
W,Whiskey
X,X-ray
Y,Yankee
Z,Zulu
```

{% endtab %}
{% endtabs %}


# Miles to KM Converter

{% tabs %}
{% tab title="main.py" %}

```python
from tkinter import *

def miles_to_km():
    calc_num = float(num_miles.get()) * 1.609
    answer_label.config(text=round(calc_num, 2))

window = Tk()
window.title("Miles to KM")
window.config(padx=20, pady=20)

miles_label = Label(text="Miles", font="Arial")
miles_label.grid(column=2,row=0)
miles_label.config(padx=10, pady=20)

km_label = Label(text="KM", font="Arial")
km_label.grid(column=2, row=1)
km_label.config(padx=10, pady=10)

equal_label = Label(text="Equals", font="Arial")
equal_label.grid(column=0, row=1)
equal_label.config(padx=10, pady=10)

answer_label = Label(text="0", font="Arial")
answer_label.grid(column=1, row=1)
answer_label.config(padx=10, pady=10)

num_miles = Entry(width=10)
num_miles.grid(column=1, row=0)

calculate_button = Button(text="Calculate", command=miles_to_km)
calculate_button.grid(column=1, row=2)

window.mainloop()
```

{% endtab %}
{% endtabs %}


# Pomodoro Timer

{% tabs %}
{% tab title="main.py" %}

```python
from tkinter import *
import math

PINK = "#e2979c"
RED = "#e7305b"
GREEN = "#9bdeac"
YELLOW = "#f7f5dd"
FONT_NAME = "Courier"
WORK_MIN = 25
SHORT_BREAK_MIN = 5
LONG_BREAK_MIN = 20

reps = 0
timer = None

def reset_timer ():
    window.after_cancel(timer)
    canvas.itemconfig(timer_text, text="00:00")
    title_label.config(text="Timer", font=(FONT_NAME, 50, "bold"), fg=GREEN, bg=YELLOW)
    check_label.config(text="")
    global reps
    reps = 0
def start_timer():
    global reps
    reps += 1

    work_sec = WORK_MIN * 60
    short_break_sec = SHORT_BREAK_MIN * 60
    long_break_sec = LONG_BREAK_MIN * 60

    if reps % 8 == 0:
        title_label.config(text="Break", fg=RED)
        count_down(long_break_sec)
    elif reps % 2 == 0:
        title_label.config(text="Break", fg=PINK)
        count_down(short_break_sec)
    else:
        title_label.config(text="Work", fg=GREEN)
        count_down(work_sec)


def count_down(count):
    count_min = math.floor(count / 60)
    count_sec = count % 60
    if count_sec < 10:
        count_sec = f"0{count_sec}"
    canvas.itemconfig(timer_text, text=f"{count_min}:{count_sec}")
    if count > 0:
        global timer
        timer = window.after(1000, count_down, count - 1)
    else:
        start_timer()
        marks = ""
        for _ in range(math.floor(reps / 2)):
            marks += "✔"
        check_label.config(text=marks)


window = Tk()
window.title("Pomodoro")
window.config(padx=100, pady=50, bg=YELLOW)

canvas = Canvas(width=200, height=224, bg=YELLOW, highlightthickness=0)
tomato_pgn =  PhotoImage(file="tomato.png")
canvas.create_image(100, 112, image=tomato_pgn)
timer_text = canvas.create_text(100, 130, text="00:00", fill="white", font=(FONT_NAME, 35, "bold"))
canvas.grid(column=1, row=1)

title_label = Label(text="Timer", font=(FONT_NAME, 50, "bold"),fg=GREEN, bg=YELLOW)
title_label.grid(column=1, row=0)

check_label = Label(font=(FONT_NAME, 20, "bold"), fg=GREEN, bg=YELLOW)
check_label.grid(column=1, row=3)

start_button = Button(text="Start", command=start_timer)
start_button.grid(column=0, row=2)

reset_button = Button(text="Reset", command=reset_timer)
reset_button.grid(column=2, row=2)


window.mainloop()
```

{% endtab %}

{% tab title="tomato.pgn" %}

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2Flq6npipAl0Y90xa0tMHJ%2Fimage.png?alt=media&amp;token=92ad2453-46b5-47fc-ae27-236111c27be5" alt=""><figcaption></figcaption></figure>
{% endtab %}
{% endtabs %}


# Clicker

{% tabs %}
{% tab title="main.py" %}

```python
import tkinter as tk

clicks = 0  # Global variable to store the click count

def sayHi():
    global clicks
    clicks += 1
    label.config(text=f"Clicks: {clicks}")

# Window
win = tk.Tk()
win.geometry("200x100")
win.title("Clicker")

# Label
label = tk.Label(win, text="Clicks: 0", font=("Arial", 12))
label.pack(pady=10)

# Button
b = tk.Button(win, text="Click here", command=sayHi)
b.pack(side=tk.BOTTOM)

win.mainloop()


```

{% endtab %}
{% endtabs %}


# Armabillo

Encryption App

{% tabs %}
{% tab title="main.py" %}

```python
import tkinter as tk
import constants
from chipers import caesar_cipher

def center_window(window, width, height):
    screen_width = window.winfo_screenwidth()
    screen_height = window.winfo_screenheight()
    x = (screen_width // 2) - (width // 2)
    y = (screen_height // 2) - (height // 2)
    window.geometry(f"{width}x{height}+{x}+{y}")


def process_text(mode):
    """
    Handles the encryption or decryption process when a button is clicked.
    :param mode: "encrypt" or "decrypt".
    """
    text = input_field.get()  # Get text from the input field
    cipher_type = cipher_var.get()  # Get selected cipher type

    if cipher_type == "Caesar Cipher":
        result = caesar_cipher(text, mode=mode)  # Encrypt or decrypt the text (shift is defined in the function)
    else:
        result = "Cipher not implemented yet"  # Placeholder for other ciphers

    # Display the result in the output field
    output_field.config(state="normal")  # Temporarily enable the field
    output_field.delete(0, tk.END)  # Clear any existing text
    output_field.insert(0, result)  # Insert the new result
    output_field.config(state="readonly")  # Set back to read-only



# Window
win = tk.Tk()
win.geometry("500x700")
win.title("Armadilo")
win.configure(bg="black")

center_window(win, 500, 700)

# Load images properly
logo_image = tk.PhotoImage(file=constants.logo)  # Load armadillo.png
logo_letters = tk.PhotoImage(file=constants.logo_letters)  # Load armadillo name.png

# Name Label
name_label = tk.Label(win, image=logo_letters, bg="black")
name_label.place(x=0, y=-120)

# Logo Label
logo_label = tk.Label(win, image=logo_image, bg="black")
logo_label.place(x=0, y=-400)

#input feild
input_message = tk.Label(win, text="Input Text:", bg="black", fg="white")
input_message.place(x=100, y=230)

input_field = tk.Entry(win, bg="white", fg="black", font=("Arial", 14), width=30)
input_field.place(x=100, y=250)

# Output Field
input_message = tk.Label(win, text="Output:", bg="black", fg="white")
input_message.place(x=100, y=330)

output_field = tk.Entry(win, bg="white", fg="black", font=("Arial", 14), width=30, state="readonly")
output_field.place(x=100, y=350)

# Cipher Selection
cipher_var = tk.StringVar(value="Choose Chiper")  # Default cipher
cipher_menu = tk.OptionMenu(win, cipher_var, "Caesar Cipher", "Vigenère Cipher")
cipher_menu.place(x=100, y=400)

#Encrypt Button
encrypt_button = tk.Button(win, text="Encrypt", bg="gray", fg="black", font=("Arial", 12), command=lambda: process_text("encrypt"))
encrypt_button.place(x=100, y=450)

decrypt_button = tk.Button(win, text="Decrypt", bg="gray", fg="black", font=("Arial", 12), command=lambda: process_text("decrypt"))
decrypt_button.place(x=200, y=450)


win.mainloop()

```

{% endtab %}

{% tab title="constants.py" %}

```python

logo_letters = r"C:\Users\HP\PycharmProjects\pythonProject1\Projects vezbanje\Armadilo\assets\armadilo name.png"
logo = r"C:\Users\HP\PycharmProjects\pythonProject1\Projects vezbanje\Armadilo\assets\armadillo.png"
armadillo_gif = r"C:\Users\HP\PycharmProjects\pythonProject1\Projects vezbanje\Armadilo\assets\armadillo.gif"
```

{% endtab %}

{% tab title="chipers.py" %}

```python

def caesar_cipher(text, shift=3, mode="encrypt"):
    """
    Encrypts or decrypts text using the Caesar cipher.

    :param text: The input text to process.
    :param shift: The number of positions to shift each character (default is 3).
    :param mode: "encrypt" or "decrypt".
    :return: The processed text.
    """
    result = ""
    for char in text:
        if char.isalpha():  # Only shift alphabetic characters
            shift_amount = shift if mode == "encrypt" else -shift
            shifted = ord(char) + shift_amount
            if char.islower():
                if shifted > ord('z'):
                    shifted -= 26
                elif shifted < ord('a'):
                    shifted += 26
            elif char.isupper():
                if shifted > ord('Z'):
                    shifted -= 26
                elif shifted < ord('A'):
                    shifted += 26
            result += chr(shifted)
        else:
            result += char  # Non-alphabetic characters remain unchanged
    return result


```

{% endtab %}
{% endtabs %}


# Assembly


# Assembly 8086 (16-bit)


# Assembly 8086 basics


# Basic Concepts

## Programming Languages

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FtBO1wJXTwp19vhmmtRjA%2Fprograming%20languages.png?alt=media&amp;token=b6fbe129-c021-4d2a-8f83-78f98fc2561b" alt=""><figcaption></figcaption></figure>

Types of programming languages:

* Imperative - **Imperative Languages**: These languages are about giving direct instructions to the computer on *how* to achieve a result, step by step. Imagine following a recipe—imperative languages tell the computer exactly what to do in each step, often using things like variables (for storing data) and loops (for repeating actions). Examples include C and Java.
* Declarative - Instead of giving step-by-step instructions, these languages describe *what the end result should look like*, without specifying how to get there. In a way, it's like telling someone the destination without giving them the directions. Examples of this are **logical programming languages** (such as Prolog and SQL), where you define facts and rules, and the system figures out how to use them to solve problems.

***

## Algorithms

An algorithm is a list of instructions that are applied to solve problems or various tasks. If we have an algorithm for solving a task, a programming language can be used to implement it.

<mark style="background-color:yellow;">Algorythms ane programs, and vice versa - every program is an algorythm.</mark>

We use block schemas to describe and algorythm, that consits of start block, end block, decision block, action block, input and output block.

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FEmBkwUI15INjSj4wtgS3%2Fblock%20schemas.png?alt=media&amp;token=7decaca0-c2e0-4888-a4d6-60a155206844" alt=""><figcaption></figcaption></figure>

***

## Translators

A translator is a program used to convert the source code into object code (machine understandable code).

<mark style="color:yellow;">Assembler</mark> translates the assembly language into object code. Assembly is a low-level programming language. In assemblt the intructions that are used are the instructions provided by the processor instruction set.

<mark style="color:yellow;">The interprete</mark>r translates the program (source code) into object code, but one instruction at a time. The program is executed line by line sequentially.

<mark style="color:yellow;">The compiler</mark> takes the program (source code) as a whole and translates it into object code all at once. This process is called compilation. Once converted, the object code can be run at any time. The action it performs to create an executable file from the object file is called a link, and the program that performs this action is called a linker. For a compiled program and already linked program to be executed, we do not need to have a compiler at runtime.

***

## Positional Number Systems

* Binary - 0, 1
* Octal - 0, 1, 2, 3, 4, 5, 6, 7
* Decimal - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
* Hexidecimal - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f

<div align="left"><figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FGJkLZ6p0PVgUMFu8F1Pt%2Fimage.png?alt=media&amp;token=8eeae656-73f2-47cf-aaf4-7ea544421af1" alt=""><figcaption></figcaption></figure></div>

#### Binary Coded Decimal

fore example:\
1 in decimal is 0001 in binary \
2 is 0010 \
3 is 0011 \
4 is 0100 ...

***

## Computer Architecture

Types of **computer architectures**—the way computers are structured to perform tasks.

1. **According to the Word Length**: The term *"word"* as a term in microprocessor technology represents the amount of information that a processor's general purpose data register can process simultaneously. Its length is measured in bits.

8-bit architectures (Motorola 6800, 1974; Intel 8080, 1974; …) 16-bit architectures (Intel 8086 1976; Intel 80286 …) 32-bit architectures (Motorola 68000, 1979; Intel 80386, 80486 (1989) …) 64-bit architectures (Intel 80486 -> Pentium …)

2. **According to the Processor Architecture**: This refers to how a processor’s instructions (commands it can execute) are designed and organized. There are a few key types:

* **CISC (Complex Instruction Set Computer)**: CISC processors have a large set of complex instructions. Each instruction can perform multiple operations, which can make programming simpler but may require more processing power and time for each instruction.
* **RISC (Reduced Instruction Set Computer)**: RISC processors use a smaller, simpler set of instructions, each designed to execute very quickly. This simplicity helps RISC processors perform tasks faster, as they complete each instruction in just one or a few cycles.
* **ARM (Advanced RISC Machine)**: ARM is a specific type of RISC architecture known for its power efficiency and is widely used in mobile devices like smartphones and tablets.

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FwF627Ifmkbz4YZTFJNSC%2FCISC.png?alt=media&amp;token=896f730e-2262-420d-a188-dc270aba2f9e" alt=""><figcaption><p>CISC</p></figcaption></figure>

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FXaISsuPqs9bQdGw7CJf5%2FRISC.png?alt=media&amp;token=9baff37e-d723-40e3-8ebb-7800bf1a727a" alt=""><figcaption><p>RISC</p></figcaption></figure>

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FfOXPNSYH0GdiMXQgl0jd%2FARM.png?alt=media&amp;token=61694589-c177-4c7a-a3e0-2e2491bee2f6" alt=""><figcaption><p>ARM</p></figcaption></figure>

3. **According to the Organization of Memory**: This category looks at how data is stored in memory, particularly how the bytes are ordered in multi-byte data types (like integers or floating points).

* **Big Endian**: In this system, the most significant byte (the “big end”) is stored first in memory. For example, in a 4-byte number, the byte with the highest value is at the lowest memory address. Big - highest, End - last value (last value at top)
* **Little Endian**: Here, the least significant byte (the “little end”) is stored first. This means the byte with the lowest value is at the lowest memory address. Little - lowest, End - last value (last value at lowest)
* **Bi-endianness**: Some systems are *bi-endian*, meaning they can switch between Big Endian and Little Endian modes depending on the situation, making them more flexible for compatibility.

***

## CPU Clock Speed

CPU clock speed is the number of cycles a CPU performs per second. Measured in GHz, and it determines how quickly a CPU can execute instructions.

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FKDWjIayg5CC135NHkTcD%2FCPU%20clock.png?alt=media&amp;token=590cea79-fc91-4a0a-944f-8ce6c2b30d6f" alt=""><figcaption></figcaption></figure>

***

## Introduction To Assembly Programming

Assembly language is a low-level programming language, specific to a computer architecture.

❑ Assembly language provides a human-readable representation of the machine code or binary code that a computer's central processing unit (CPU) can execute.&#x20;

❑ It serves as a bridge between high-level programming languages and the binary machine code that a computer's CPU understands.&#x20;

❑ Assembly language is often used in situations where precise control over hardware and performance optimization are critical.&#x20;

❑ It is commonly used for developing device drivers, firmware, embedded systems, and certain system-level programming tasks.&#x20;

❑ Assembly language programming can be complex and less accessible than highlevel programming languages.

### Key Characteristics

* Represents a symbolic representation of machine code (mov, add, …).
* **Low-level language** - it operates at a level very close to the computer's hardware. Each assembly language instruction corresponds to a specific machine-level operation.
* **Provides direct access to a computer's hardware** - Assembly language allows programmers to have precise control over a computer's hardware. It can directly interact with registers, memory, and input/output devices.
* **Specific to CPU Architecture** - Assembly language is specific to the architecture of a particular CPU or microprocessor. Different CPUs have their own assembly languages, and code written for one CPU may not be compatible with another.
* **Efficiency** - assembly programs can be highly efficient and fast (they provide a level of control and optimization not easily achieved in high-level languages).
* **Limited Abstraction** - assembly language provides a minimal level of abstraction, making it a powerful choice for system-level programming, embedded systems, and tasks that require direct manipulation of hardware.
* **Assembler** - to convert human-readable assembly code into machine code, an assembler is used. The assembler translates assembly language instructions into binary machine code.
* **Registers and Memory** - assembly language typically involves the use of CPU registers for temporary storage and memory for data and program storage. Instructions specify how data is moved between registers and memory.

### Components

Instructions -> Mnemonics for basic operations (e.g., MOV, ADD, JMP) Registry -> Small, fast storage locations within the CPU Memory Addressing -> How data is accessed in memory Flow Control .-> Loops and branching instructions

***

## Key take-outs

There are different CPU architectures – 8-bit, 16-bit, 32-bit, and etc. Every CPU has its own clock speed. Every CPU has its own instruction set. Some architectures provide simple and fast instructions Some architectures provide complicated and slow fast instructions. Assembly language is a low level programming language.


# Intel 8086 Architecture

## High level Overwiev

* It lunched in 1979
* It was the first 16-bit microprocessor
* and it has 40 pins
* it uses +5v powersupply
* has \~29.000 transistors (semiconductors)
* has up to 1MB memory, witch is a lot for what it is used.
* Memory address ranges from 00000(16) to FFFFF(16)
* little-endian organization

**Mem organization**

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FJ2uCcBlT3YcyZbhVvdWr%2Fmem%20org%20for%208086.png?alt=media&amp;token=a7a1cb0b-7dc0-4144-ab37-1fceccb72d30" alt=""><figcaption></figcaption></figure>

**Pins**

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FgZPsc9Cis81RcTjChvU7%2Fpins.png?alt=media&amp;token=3cdbe9b5-f702-4471-ab2c-3ce7e73e50fb" alt=""><figcaption></figcaption></figure>

***

## Block Diagram

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FjcrTYHsLHUNqYKAASOWd%2Fblock%20dia.png?alt=media&amp;token=f9d2cefc-ffa3-44c1-99f4-bf8703783dab" alt=""><figcaption></figcaption></figure>

Two main units of the 8086 processor:&#x20;

* **BIU** – Bus Interface Unit Fetching instructions from memory and decoding them Manages the data transfer between the microprocessor and the memory or I/O devices (I/O – Input/Output) Provides a full 16-bit bi-directional data bus and 20-bit address bus
* **EU** – Execution Unit Executes the instructions

***

### BIU (Bus Interface Unit)

The **BIU** is responsible for handling all data transfers between the **CPU** and **memory** or **I/O devices**. It does this by managing the **B-bus** and **C-Bus**<br>

**BIU Contains:**&#x20;

* [Instruction Queue](#instruction-queue)
* [Segment Registers](#segment-registers)
* [Instruction Pointer (IP)](#instruction-pointer-ip)
* [Address Summer](#address-summer)
* Bus control Logic

**So how the BIU works is:** \
It captures **six instruction bytes** ahead of its current memory, and the instructions a re stored in a Queue (group of registers). And the Queue has FIFO organization, whitch means if MOV command is written first and than ADD, the MOV will be executed first, bcs it was first written-first queued.

JMP and CALL functions are not used when loaded but when they are called, and other instructions ate loaded extend them

Feature of fetching the next instruction while the current instruction is executing is called **pipelining**

***

#### Segment Registers

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2F6SBTBEjHBmVR4uUKQfE1%2FPasted%20image%2020241115143717.png?alt=media&amp;token=181a9b16-7c9f-4885-b705-b3fc24311950" alt=""><figcaption></figcaption></figure>

**Segment registers** are a set of **16-bit registers** in x86 processors that hold the **base addresses of memory segments**.

Segment registers are essential for **memory segmentation** in 16-bit processors, allowing the CPU to access a 1 MB memory space with 16-bit addresses

Each segment register contains starting address of a segment (called also: Base address or Segment base)

**Memory Segmentation**

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2F8Rdrne9Ib31nC5TjyYvO%2FPasted%20image%2020241115143353.png?alt=media&amp;token=9207d218-ad64-496b-a12f-d46da512cf3b" alt=""><figcaption></figcaption></figure>

**Memory segmentation** is a memory management technique used in computer systems, especially in early processors like the Intel 8086, to divide memory into distinct **segments**. Each segment represents a logical section of memory with a specific purpose, which helps organize data, code, and the stack, allowing for more efficient memory access and usage. Segmentation enables the CPU to access a **larger memory space** than it could with a single flat address space.

Memory segmentation allows memory addressing capacity to be 1mb .

***

Internal architecture of 8086 allows usage of 4 active segments with the help of the following four segment registers:

* CS - Code Segment&#x20;
* DS - Data Segment
* SS - Stack Segment
* ES - Extra Segment<br>

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FOSYhJz9aC2t4vuve48R5%2FPasted%20image%2020241115143540.png?alt=media&amp;token=c8b876d1-6770-4ce1-b717-68cf0c9d4b45" alt=""><figcaption></figcaption></figure>

***

#### Address Summer

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FDQRJY5O9EXWzRBiotidk%2Fadress%20summer.png?alt=media&amp;token=f5790f82-a032-4649-9691-f56d96f42894" alt=""><figcaption></figcaption></figure>

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FlbpLpOjSrEjikfUhAtcm%2Fadress%20summer%202.png?alt=media&amp;token=c4c48a4f-6db5-47ea-bfb8-fd0bd410a22d" alt=""><figcaption></figcaption></figure>

* The **CS** register holds the upper 16-bits of the starting address of the segment from which the BIU is currently fetching the instruction code byte.
* The **SS** register is used for the upper 16-bits of the starting address for the program stack
* **ES** register and **DS** register are used to hold the upper 16-bits of the starting address of the two memory segments, which are used for data.

***

#### Instruction Pointer (IP)

The instruction pointer register holds the 16-bit address of the next Code byte within the code segment. The value contained in the IP is referred to as an **offset**.

This value must be offset from (added to) the segment base address in CS to produce the required 20-bit physical address.

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2F6A8PKfl3NopHUZsZQGbz%2FInstruction%20Poiner.png?alt=media&amp;token=4b8586b8-c75d-4b53-8fee-1607489802e7" alt=""><figcaption></figcaption></figure>

***

#### Instruction Queue

The **instruction queue** is a buffer that holds a **6-byte queue** of instructions. This prefetches instructions from memory to reduce the time the processor waits for instructions, allowing faster execution.

***

### **EU (Execution Unit)**

The execution unit tells the BIU from where to fetch instructions or data. Decodes instructions and executes instructions.

It contains:

* [Control Circuity](#control-circuitry-instruction-decoder-alu)
* Instruction Decoder
* Arithmetic Logic Unit (ALU)
* [Flag Register](#flag-register)
* [General Purpose Registers](#general-purpose-registers)
* Pointers and Index Registers

***

#### Control Circuitry, Instruction Decoder, ALU:

▪ The control circuitry in the EU directs the internal operations. ▪ A decoder in the EU translates the instructions fetched from memory into a series of actions which the EU performs. ▪ ALU is 16-bit. It can add, subtract, AND, OR, XOR, increment, decrements, complement and shift binary numbers.

!\[\[Control Circuit, Instruction Decoder, ALU.png]]

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FwAI5O1HdbXWT0N6ZHC25%2FControl%20Circuit%2C%20Instruction%20Decoder%2C%20ALU.png?alt=media&amp;token=ee3ec06d-9f45-417f-b4aa-3223b0772245" alt=""><figcaption></figcaption></figure>

***

#### Flag Register

▪ A special purpose 16-bit register. ▪ There are 9 valid flag bits. ▪The flag bits are changed to 0 or 1 depending on the value of result after arithmetic or logical operations. ▪ The flag bits can be divided into two sections – control flags and status flags

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FJlKmdFoLL9PZse476kwA%2FPasted%20image%2020241115152703.png?alt=media&amp;token=5a82dda7-9c63-4ada-92e3-a96f8ed49950" alt=""><figcaption></figcaption></figure>

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FWdIUPri9YhQI2zks7SgO%2FFlag%20Register.png?alt=media&amp;token=c03afeca-0021-40eb-b30f-a2fdfacdf432" alt=""><figcaption></figcaption></figure>

<table><thead><tr><th width="260">Flag</th><th>Bit.</th><th>Description</th></tr></thead><tbody><tr><td>CF (Carry Flag)</td><td>0</td><td>Set if an arithmetic operation generates a carry out or borrow into the most significant bit</td></tr><tr><td>PF (Parity Flag)</td><td>2</td><td>Set if the result of an operation has an even number of 1-bits; used for error checking</td></tr><tr><td>AF (Auxiliary Carry Flag)</td><td>4</td><td>Set if there is a carry or borrow between the lower and upper nibbles (used in BCD arithmetic)</td></tr><tr><td>ZF (Zero Flag)</td><td>6</td><td>Set if the result of an operation is zero</td></tr><tr><td>SF (Sign Flag)</td><td>7</td><td>Set if the result of an operation is negative (most significant bit is 1).</td></tr><tr><td>TF (Trap Flag)</td><td>8</td><td>Enables single-step mode for debugging, causing an interrupt after each instruction</td></tr><tr><td>IF (Interrupt Flag)</td><td>9</td><td>Controls the ability to respond to interrupts; if set, the CPU will respond to maskable interrupts</td></tr><tr><td>DF (Direction Flag)</td><td>10</td><td>Controls the ability to respond to interrupts; if set, the CPU will respond to maskable interruptst</td></tr><tr><td>OF (Overflow Flag)</td><td>11</td><td>Set if an arithmetic operation generates a result too large to fit in the destination operand</td></tr></tbody></table>

***

#### General Purpose Registers

* 8 general purpose registers (8-bits each) labelled: AH, AL, BH, BL, CH, CL, DH, and DL.
* Can be used individually for temporary storage of 8-bit data.
* The AL register is also called accumulator.
* Certain pairs of these general-purpose registers can be used together to store 16-bit data, such as AX, BX, CX and DX.

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FMGbTtOpP8fwWed2gqsRY%2FGeneral%20purpose%20registers.png?alt=media&amp;token=ffd2842d-d78b-461e-99b6-39bcb8466f44" alt=""><figcaption></figcaption></figure>

***

### Instruction Set

Intel 8086 microprocessor supports 8 types of instructions:&#x20;

* Data Transfer Instructions
* Arithmetic Instructions&#x20;
* Bit Manipulation Instructions
* String Instructions&#x20;
* Program Execution Transfer Instructions (Branch & Loop Instructions)&#x20;
* Processor Control Instructions ▪ Iteration Control Instructions&#x20;
* Interrupt Instructions

***

#### MOV

copies the second operand (source) to the first operand (destination)

**Syntax:**&#x20;

MOV operand1, operand2\
(destionation) (source)

**Important:**&#x20;

* Never mix an 8-bit register with 16-bit, it is not allowed.
* Code segment register (CS) and Instruction Pointer (IP) are never used as destination.&#x20;
* Segment with segment is not allowed.&#x20;
* Memory with memory is not allowed.&#x20;
* When used immediate with memory you must use (byteptr) of&#x20;
* 8-bit or (wordptr) of 16-bit for the instructions.&#x20;
* Also used for the instructions have one operand as memory

**Example 1:** \
mov ES, DS (Incorrect)\
\
mov AX, DS \
mov ES, AX (correct)

Example 2: \
mov \[SI],\[0xF900]         (Incorrect)\
\
mov BX, \[0xF900] \
mov \[SI], BX                     (correct)


# Assembly Language Basics

## Assembly Language Basics

In Assembly Language:&#x20;

* syntax
* data types&#x20;
* addressing modes&#x20;

are essential for writing efficient and correct programs.

***

### Syntax

* Assembly language syntax is mnemonic and symbolic, making it readable and understandable.&#x20;
* Instructions are represented by mnemonics like MOV, ADD, SUB, JMP, etc. ▪ Instructions can have operands that specify the data to be operated on.&#x20;
* Operands can be <mark style="color:yellow;">registers, memory locations, or immediate values</mark>.&#x20;
* Labels are used for defining addresses in the program and creating jump targets.&#x20;
* Comments start with a semicolon ( ; ) and are used for documentation.

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FbzdQ83jiow1a5kzTTzJ5%2Fimage.png?alt=media&amp;token=36bd49f3-a15d-45a9-9258-9817f0b239da" alt=""><figcaption></figcaption></figure>

***

### Data Types

In 8086 Assembly, there is no strict type system as in high-level languages, but data is classified based on size and purpose.<br>

Common data types include:&#x20;

* Byte (8 bits): Represented as DB (Define Byte).&#x20;
* Word (16 bits): Represented as DW (Define Word).&#x20;
* Doubleword (32 bits): Represented as DD (Define Doubleword).&#x20;
* Quadword (64 bits): Represented as DQ (Define Quadword).

Data types are used for defining **variables, constants, and memory allocation**.

***

### Addressing Modes

Addressing modes determine how an operand's address is calculated.

Common addressing modes include:

* **Immediate:** Operand is a constant value ( <mark style="color:yellow;">MOV AX, 5</mark> ).&#x20;
* **Register:** Operand is a value stored in a register ( <mark style="color:yellow;">MOV AX, BX</mark> ).&#x20;
* **Direct:** Operand is the address of a memory location ( <mark style="color:yellow;">MOV AL, \[1000h]</mark> ).&#x20;
* **Indirect:** Operand is a register that holds the address of the memory location ( <mark style="color:yellow;">MOV AL, \[BX]</mark> ).&#x20;
* **Indexed:** Operand is an indexed memory location using a base register and an index register ( <mark style="color:yellow;">MOV AL, \[BX+SI]</mark> ).&#x20;
* **Base-Indexed:** Operand is a combination of base and index registers ( <mark style="color:yellow;">MOV AL, \[BX+SI+10h]</mark> ).
* **Scaled Indexed:** Operand is an indexed memory location with a scaling factor ( <mark style="color:yellow;">MOV AL, \[BX+SI \* 2]</mark> ).

***

### Rules for writing code

The code consists of:

* **Mnemonics**
  * Mnemonics are Machine Instructions&#x20;
  * Mnemonics are abbreviations&#x20;
  * Example: MOV, ADD, SUB, IMUL
* **Operands**
  * Operands are Data or Addresses&#x20;
  * Types of Operands: Registers, Memory, Constants&#x20;
  * Example: MOV AX, \[BX]
* **Comments**
  * &#x20;Enhance Code Readability&#x20;
  * Used for documenting important parts of the code&#x20;
  * Ignored by the Assembler Everything from the character ' ; ' till the end of the line is ignored by Assembler&#x20;
  * Example: ; This is a Comment

***

### Syntax Rules

Assembly is case **insensitive** (big or small letters, its the same)

* **Rule:** If an identifier is present in the label field, always start that identifier in column one of the source line.&#x20;
* **Rule:** All operands should start in the same column. Generally, this should be column 17 (the second tab stop) or some other convenient position&#x20;
* **Rule:** All mnemonics should start in the same column. Generally, this should be column 25 (the third tab stop) or some other convenient position.

**Exception:** If a mnemonic (typically a macro) is longer than seven characters and requires an operand, you have no choice but to start the operand field beyond column 25 (this is an exception assuming you've chosen columns 17 and 25 for your mnemonic and operand fields, respectively).&#x20;

**Guideline:** Try to always start the comment fields on adjacent source lines in the same column&#x20;

**Guideline:** Use blank lines to separate special blocks of code from the surrounding code. Use an aesthetic looking row of asterisks or dashes if you need a stronger separation between two blocks of code (do not overdo this, however)

***

### Example Code:

```
GetFileRecords: mov    dx, offset DTA                          ;Set up DTA
                DOS    SetDTA
		mov    dx, FileSpec
		mov    cl, 37h
		DOS    FindFirstFile
		jc     FileNotFound

;              ********************************************* 
		mov    di, offset fileRecords  ;DI -> storage for file names 
		mov    bx, offset files        ;BX -> array of files 
		sub    bx, 2                   ;Special case for 1st iteration
				
```

***

## Error Handling

Assembly Errors:&#x20;

* **Undefined symbol:** Program refers to a label that does not exist&#x20;
  * **How to fix:** check spelling of both the definition and access
* **Undefined opcode or pseudo-op**&#x20;
  * **How to fix:** check the spelling/availability of the instruction
* **Addressing mode not available**&#x20;
  * **How to fix:** look up the addressing modes available for the instruction
* **Expression error**&#x20;
  * **How to fix:** check parentheses, start with a simpler expression
* **Phasing Error:** occurs when the value of a symbol changes from pass1 to pass2&#x20;
  * **How to fix:** first remove any undefined symbols, then remove forward references
* **Address error**&#x20;
  * **How to fix:** use org pseudo-op’s to match available memory.

***

### Data Types - Byte, Word, Doubleword, Quadword

**Byte Data Type** \
Represents 8 Bits (1 Byte) \
Example: DB 65 ; (Decimal Byte Value)

**Word Data Type** \
Represents 16 Bits (2 Bytes) \
Example: DW 1234 ; (Decimal Word Value)

**Doubleword Data Type** \
Represents 32 Bits (4 Bytes) \
Example: DD 12345678h ; (Hex Doubleword Value)

**Quadword Data Type** (no native instructions or directives to directly declare Quadword (64-bit) data types) \
Represents 64 Bits (8 Bytes) \
Example: DQ 123456789ABCDEFh ; (Hex Quadword Value)

***

### Data Type Conversion

Maintaining Data Integrity

CBW - convert byte to word extends the sign bit of AL into the AH register. This preserves the number 's sign

```nasm
byte_val SBYTE -101 
mov al, byte_val                 ; AL = 9Bh
cbw                              ; AX = FF9Bh
```

CWD - convert word to doubleword extends the sign bit of AX into the DX register:

```nasm
word_val SWORD -101 
mov ax, word_val                    ; FF9Bh ; AX = FF9Bh
cwd                                 ; DX:AX = FFFFh:FF9Bh
```

***

## Addressing Modes

Different Ways to Specify Operand Locations -> Immediate, Register, Direct, Indirect, Indexed, Based Indexed

**Immediate Addressing Mode** - Operand as Constants \
MOV AX, 42

**Register Addressing Mode** - Operand is a Register \
MOV BX, AX

**Direct Addressing Mode** - Operand is a Memory Location \
MOV AL, \[SI]

**Indirect Addressing Mode** - Register Holds Memory Address \
MOV DL, \[BX]

**Indexed Addressing Mode** - Operand as Indexed Memory Location \
MOV AL, \[BX+SI]

**Based Indexed Addressing Mode** - Combination of Base and Index Registers \
MOV AH, \[BX+SI+10h]

***

### Calculate the Sum of Two Numbers

Example 1:

```nasm
MOV AX, 2340h
MOV BX, 4008h 
ADD AX, BX
```

Example 2:

```nasm
Number1 DW 2340h          ; h -> hex number
Number2 DW 4008h          ; h -> hex number
Result DW ?

MOV AX, Number1 
MOV BX, Number2 
ADD AX, BX  ;  
MOV Result, AX
```

***

Few registers – additional info

**Register SP - stack pointer** (16 bits) It points to the topmost item of the stack. If the stack is empty the stack pointer will be (FFFE)h. Its offset address is relative to the stack segment.

**Register BP- base pointer** (16 bits) It is primarily used in accessing parameters passed by the stack. Its offset address is relative to the stack segment.

**Register SI - source index** (16bits) It is used in the pointer addressing of data and as a source in some string-related operations. Its offset is relative to the data segment.

**Register DI - destination index** (16 bits) It is used in the pointer addressing of data and as a destination in some stringrelated operations. Its offset is relative to the extra segment.

***

### Example – Accessing array elements

```
Array DW 10, 20, 30, 40, 50 ; Define an array of 16-bit integers 
Index DW 2                  ; Index for element access (e.g., access the third element) 
Result DW ?                 ; Storage for the accessed element
```

```
; Load the array index into a register 
MOV BX, Index
```

```
; Calculate the offset in the array based on the index 
MOV CX, 2                   ; Each element in the array is 2 bytes (16 bits) 
MUL CX                      ; Multiply the index by 2 to get the offset 
MOV SI, AX                  ; Store the offset in SI
```

```
; Access the array element and store it in Result 
MOV AX, Array[SI] ; Load the element at the calculated offset 
MOV Result, AX
```

***

## Microsoft Macro Assembler (MASM)

The assembler contains as its front-end a macro processor.

The macro processor scans the source file for macro definitions and macro calls written in Macro Processor Language (MPL).

**Macro calls are expanded** according to macro definitions, and the resulting source assembly language is assembled by the assembler.

By using MPL, you can create macros specific to your application that can generate sequences of assembly language instructions or directives.

The macro processor is a very powerful string replacement facility that can help to simplify a programming task. Repeatedly used code sequences can be replaced by a simple macro call. Also, frequently used assembler directive statements can be replaced by macro calls.

***

### MASM Directives

MASM uses Directives – instructions to the Assembler Indicate how an operand or section of a program is to be processed by the assembler.

**DB (Define Byte)** \
**DW (Define Word)** \
**DD (Define Double Word)**\
very often used to define and store memory data. With these directives, we give a symbolic name of a memory location and at the same time we define its size.

**ARRAY DW 100 DUP(0**) \
reserve 100 words of storage in memory, give it the name “ARRAY”, and initialize those 100 words with 0000.

**ARRAY DW 100 DUP(0)** \
reserve 100 words of storage in memory, give it the name “ARRAY”, and initialize those 100 words with 0000.

**ARRAY DW 100 DUP(?)** \
reserve 100 words of storage in memory, give it the name “ARRAY”, and the Assembled does not initialize them with anything.

**ORG** \
ORG (Origin) directive is an indication on where to put the next piece of code/data, related to the current segment. changes the starting offset address of the data in the data segment to a desired location the origin of data or the code must be assigned to an absolute offset address with the ORG statement

```
ORG 0000h 
DataX DB  28 
DataY DB 45
ORG 0020h 
DataZ DB 86 

// 0000 -> 1Ch
// 0001 -> 2Dh
// 0020 -> 56h
```

**ASSUME** the name of the logical segment it should use for a specified segment. It instructs the Assembler what names are chosen for the code, data, extra, stack segments

```
ASSUME DS:data , CS:code, SS:stack
```

**EQU**\
equates a numeric, ASCII, or label to another label Each time the assembler finds the given name in the program, it will replace the name with the value or symbol we equated with that name.

```
CONTROL_WORD EQU 11001001               ; replacement 
MOV AX, CONTROL_WORD                    ; assignment

COUNT EQU 10 
CONST EQU 20H 
MOV AH, COUNT 
MOV AL, CONST
```

\
**PROC** \
indicate start and end of a procedure (subroutine)

```
PROCONVERT PROC FAR 

; identifies the start of a procedure named PROCONVERT and tells the Assembler that the procedure is far (in a segment with a different name from the one that contains the instruction that calls the procedure.)
```

The PROC directive, which indicates the start of a procedure, must also be followed with a NEAR or FAR

A NEAR procedure is one that resides in the same code segment as the program, often considered to be local A FAR procedure may reside at any location in the memory system, considered global

The term global denotes a procedure that can be used by any program. Local defines a procedure that is only used by the current program.

***

### Model Types:

Tiny – All data and code fit in one segment. Tiny programs are written in .COM, which means the program must be originated at location 100h.

Small – Contains two segments – One DS (64KB) and one CS (64KB)

Medium – Contains one DS segment (64KB) and any number of CS for large programs.

Compact – Contains one CS (64KB) for the program and any number of DS contain the data

Large – Allows any number of CS and DS

Huge – same as Large, but the DS segments may contain more than 64KB each

Tiny programs are written in **.COM**, which means <mark style="background-color:yellow;">**the program must be originated at location 100h**</mark>**.**

COM programs in DOS are set up: \
The **first 256 bytes contain management data** for the operating system and the command line (which can be re-used as 128-byte data transfer buffer), and **the program code starts after it.**

So ORG 100h forces the toolchain to build a program that fits the memory layout of COM programs.

***

### MASM – structure of a main module with full segment directives

```
assume ds:data, cs:code 
data segment 

data ends 

code segment 
START: 
    nop          ; code here

code ends 
end START
```

***

### Assembler Phases

Phase 1 - Analysis The Analysis Phase validates the syntax of the code, checks for errors, and creates a symbol table.

Phase 2 – Synthesis The Synthesis Phase converts the assembly language instructions into machine code, using the information from the Analysis Phase.

These two phases work together to produce the final machine code that can be executed by the computer. The combination of these two phases makes the Assembler an essential tool for transforming assembly language into machine code, ensuring high-quality and error-free software.


# Memory and Register Organization (part 1)

## Memory Types

The intel 8086 microprocessor has a few memory types used for different purposes. Witch are: RAM, ROM, Cache, Virtual Memory

### RAM

A type of computer memory that provides read and write access to data quickly and efficiently. It is volatile memory, meaning that it loses its contents when the power is turned off.

▪ **Primary Working Memory**&#x20;

▪ **Temporary Storage** - Programs and data that are actively used or manipulated during the execution of a program are loaded into RAM for quick access and modification. It loses its stored information when the power is turned off.&#x20;

▪ **Higher Speed Access** - provides faster access times compared to other types of storage like hard drives or solid-state drives.&#x20;

▪ **Intermediate between Registers and Permanent Storage** - It acts as an intermediate storage level between the processor's registers and the slower, more permanent storage devices.&#x20;

▪ **Stack Operation** - storing local variables, return addresses, and other data during subroutine calls and function executions. Variable Storage: RAM is used for storing variables and data structures during program execution.&#x20;

▪ **Efficient Data Access** - Its random access nature allows for efficient retrieval of data at any memory location&#x20;

▪ **Cache Interaction** - RAM interacts with the CPU cache hierarchy, influencing the speed of data retrieval.&#x20;

▪ **Upgradable** - RAM is often expandable, allowing users to upgrade the memory capacity of the system to meet the requirements of more demanding applications.

***

### ROM (Random Access Memory)

ROM is a type of non-volatile memory that retains its content even when the power is turned off. It is called "read-only" because, in most cases, the data stored in ROM cannot be easily modified or overwritten.

**Types:**

▪ **Mask ROM** - The data is permanently written during the manufacturing process.&#x20;

▪ **Programmable ROM (PROM)** - Users can write data once using special programming equipment.&#x20;

▪ **Erasable Programmable ROM (EPROM**) - Allows for reprogramming after exposure to ultraviolet light.&#x20;

▪ **Electrically Erasable Programmable ROM (EEPROM)** - Can be electrically erased and reprogrammed.<br>

**Roles:**

▪ **Firmware Storage** - ROM is commonly used to store firmware, which is a type of software that is embedded in hardware and is responsible for low-level control of specific devices.&#x20;

▪ **Permanent Instructions** - Critical system instructions, such as the BIOS (Basic Input/Output System) or firmware of peripheral devices, are often stored in ROM.

**Critical instructions:**

▪ **BIOS (Basic Input/Output System)** - The BIOS is a crucial piece of firmware stored in ROM that initializes hardware components during the boot process and provides low-level services to the operating system.&#x20;

▪ **Bootloader** - The initial bootloader, responsible for loading the operating system into memory, is often stored in ROM

**System Initialization:**

▪ **Power-On Self-Test (POST)** - ROM contains instructions for the POST, a diagnostic process performed during system startup to ensure that essential hardware components are functioning correctly.&#x20;

▪ **Initialization Routines** - Instructions for initializing system components, such as memory, storage devices, and input/output interfaces, are stored in ROM.

***

### Cache

The Intel 8086 microprocessor is an older architecture, and it does not have the concept of Level 1 (L1) and Level 2 (L2) caches as found in modern processors. The idea of multiple cache levels became more prevalent in later processor architectures.

No L1 or L2 Cache Designation:

▪ The 8086 does not have an explicit Level 1 (L1) or Level 2 (L2) cache as found in modern processors.&#x20;

▪ Cache hierarchy, as we know it today, became a more prevalent concept in later processor architectures.&#x20;

▪ The 8086 interacts directly with main memory, fetching instructions and data as needed during program execution.&#x20;

▪ Memory access times are influenced by the speed of the RAM (Random Access Memory) used in the system.&#x20;

▪ The 8086 uses a segmented memory model with 20-bit addressing, allowing access to a maximum of 1 MB of memory.&#x20;

▪ Segments and offsets are used to specify memory addresses, providing a mechanism for addressing different parts of memory.

#### Level 1 Cache

The L1 cache is located close to the CPU, typically directly on the CPU die.&#x20;

**Size** - It small and mesured in kilobytes. \
**Speed** - L1 cache operates at speeds closely to the CPU clock speed. \
**Purpose** - It serves as a quick access storage unit, minimizing the time the CPU spends waiting for data from slower levels of memory.

#### Level 2 Cache

L2 cache is positioned further from the CPU compared to L1 but is still located on the CPU die mostly.

**Size** - L2 is larger than L1 and is mesured in megabytes. L2 cache is positioned further from the CPU compared to L1 but is still located on the CPU die.\
**Speed** - While not as fast as the L1 cache, the L2 is still faster than the main memory. \
**Purpose** - L2 cache acts as a secondary cache level, offering more storage space for frequently accessed data and instructions, reducing the need to fetch data from slower main memory.

***

### Virtual Memory

The Intel 8086 processor is an older architecture and does not have native support for virtual memory in the way modern processors and operating systems do.

Virtual memory is a feature that allows a computer to compensate for physical memory shortages by temporarily transferring data from random access memory (RAM) to disk storage. This enables the execution of larger programs or multiple programs concurrently.

***

## Addressing Modes

### Immediate Addressing Mode

▪ Syntax: IMMEDIATE DATA \
▪ Description: The operand is a constant value or immediate data. The data is directly specified in the instruction.

Example:

```
MOV AX, 1234h         ;Moves the immediate value 1234h into the AX register
```

***

### Register Addresing Mode

▪ Syntax: REGISTER \
▪ Description: The operand is the content of a register.

Example:

```
MOV AX, BX         ;Moves the content of the BX register into the AX register
```

***

### Direct Addressing Mode

▪ Syntax: MEMORY \
▪ Description: The operand is the content of a memory location. The effective address is directly specified in the instruction.

Example:

```
MOV AX, [1234h]        ;Moves the content of the memory location addressed by                            1234h into the AX register
```

***

### Register Indirect Addressing Mode

▪ Syntax: \[REGISTER] \
▪ Description: The operand is the content of the memory location addressed by the content of a register.

Example:

```
MOV AX, [BX]         ;Moves the content of the memory location addressed by the                        content of the BX register into the AX register.
```

***

### Base-Register Addressing Mode

▪ Syntax: \[BASE REGISTER + DISPLACEMENT] \
▪ Description: The operand is at the memory location obtained by adding a displacement to the content of a base register.

Example:

```
MOV AX, [SI + 10        ;Moves the content of the memory location addressed by                            (SI + 10) into the AX register.
```

***

### Indexed Addressing Mode

▪ Syntax: \[BASE REGISTER + INDEX REGISTER + DISPLACEMENT] \
▪ Description: The operand is at the memory location obtained by adding a displacement to the sum of the contents of a base register and an index register.

Example:

```
MOV AX, [BX + SI + 20]      ;Moves the content of the memory location addressed                               by (BX + SI + 20) into the AX register
```

***

### Based Indexed Addressing Mode:

▪ Syntax: \[BASE REGISTER + INDEX REGISTER + DISPLACEMENT] \
▪ Description: Similar to indexed addressing, but an additional base register is used for a segment address.

Example:

```
MOV AX, [ES:BX + DI + 30]         ;Moves the content of the memory location                                         addressed by (ES:BX + DI + 30) into the AX                                       register. ES:BX specifies a memory location                                      that is the value contained in BX "distance"                                     from the start of the segment ES
```

***

### Relative Addressing Mode:

▪ Syntax: LABEL \
▪ Description: Used with branch instructions, where the operand is a label representing a target memory address.

Example: LABEL: MOV AX, 10 CMP AX, 3456h JMP LABEL

```
 LABEL: 
 MOV AX, 10 
 CMP AX, 3456h 
 
 JMP LABEL          ;Jumps to the instruction at the specified label
```

***

## Registers

Registers in the **Intel 8086** microprocessor are small, fast storage locations within the CPU that hold data, addresses, or instructions temporarily while they are being processed. Registers are essential for performing arithmetic and logical operations, controlling program execution, and accessing memory.

The Intel 8086 has **14 registers**, which can be categorized into the following types:

1. General-Purpose Registers
2. Segment Registers
3. Pointer and Index Registers
4. Instruction Pointer
5. Flags Register

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FxtwTNP4mtTjF4NnKRXeE%2Fregisters%20table.png?alt=media&amp;token=af61fba9-fa98-4a80-9fcc-51e54467b578" alt=""><figcaption></figcaption></figure>

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2F4lm6USGKKAHntbV09VCL%2Fintel%208086%20scheme.png?alt=media&amp;token=3ef598dd-d131-4cac-8727-9fcc261a0642" alt=""><figcaption><p>intel 8086 scheme</p></figcaption></figure>

***

### General purpose Registers

These are used for arithmetic, logic, data transfer, and other general operations. Each register is 16 bits and can be divided into two 8-bit parts: high (H) and low (L).

* **AX (Accumulator Register):**
  * Used for arithmetic and data transfer instructions.
  * **AH** (high 8 bits) and **AL** (low 8 bits).
* **BX (Base Register):**
  * Often used as a base register for addressing memory.
  * **BH** and **BL**.
* **CX (Count Register):**
  * Used as a counter in loop and shift/rotate instructions.
  * **CH** and **CL**.
* **DX (Data Register):**
  * Used in I/O operations and for extended precision in multiplication/division.
  * **DH** and **DL**.

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FcLXPrrMhdWiK6e7WsEbc%2Fdata%20registers.png?alt=media&amp;token=eab52237-a59b-4236-9fee-b0be7daeb949" alt=""><figcaption></figcaption></figure>

***

#### AX

The primary accumulator for arithmetic and logic operations.

**Special Features**:

* Some instructions implicitly use AX (e.g., `MUL`, `DIV`, `IN`, `OUT`).
* It is often the fastest and most optimized register for certain operations.

Examples of instructions utilizing the AX register:

MOV (move)

```
# to add
```

ADD (addition)

```
# to add
```

SUB (subtraction)

```
# to add
```

MUL (multiply)

```
# to add
```

IMUL (singed multiply)

```
# to add
```

DIV (divide)

```
# to add
```

INC (increment)

```
# to add
```

DEC (decrement)

```
# to add
```

CMP (compare)

```
# to add
```

AND (logical and)

```
# to add
```

OR (logical or)

```
# to add
```

XOR (logical xor)

```
# to add
```

SHL

```
# to add
```

SHR

```
# to add
```

***

#### BX

General-purpose register with a versatile role in addressing memory locations and manipulating data.

**Special Features**:

* Can be combined with segment registers to compute effective addresses.

Examples of instructions utilizing the CX register:

MOV (move)

```
# to add
```

ADD (addition)

```
# to add
```

SUB (subtraction)

```
# to add
```

MUL (multiply)

```
# to add
```

IMUL (singed multiply)

```
# to add
```

DIV (divide)

```
# to add
```

INC (increment)

```
# to add
```

DEC (decrement)

```
# to add
```

CMP (compare)

```
# to add
```

AND (logical and)

```
# to add
```

OR (logical or)

```
# to add
```

XOR (logical xor)

```
# to add
```

SHL

```
# to add
```

SHR

```
# to add
```

LEA (Load Effective Address)

```
# to add
```

MOVSB (string operation)

```
# to add
```

***

#### CX

The primary accumulator for arithmetic and logic operations.

**Special Features**:

* Instructions like `REP`, `LOOP`, `SHR`, and `ROL` rely on CX implicitly.
* Reducing CX by one is done automatically in looping constructs.

Examples of instructions utilizing the CX register:

MOV (move)

```
# to add
```

ADD (addition)

```
# to add
```

SUB (subtraction)

```
# to add
```

MUL (multiply)

```
# to add
```

IMUL (singed multiply)

```
# to add
```

DIV (divide)

```
# to add
```

INC (increment)

```
# to add
```

DEC (decrement)

```
# to add
```

CMP (compare)

```
# to add
```

AND (logical and)

```
# to add
```

OR (logical or)

```
# to add
```

XOR (logical xor)

```
# to add
```

SHL

```
# to add
```

SHR

```
# to add
```

LOOP

```
MOV CX, 5 
LOOP_START: 
	; The code here 

LOOP LOOP_START
```

LODSW (string operation)

```
LODSW
```

***

#### DX

The primary accumulator for arithmetic and logic operations.

**Special Features**:

* In division (`DIV`) and multiplication (`MUL`), DX stores the **most significant bits** of the result.
* Used as an **address pointer** in certain operations.

Examples of instructions utilizing the DX register:

MOV (move)

```
# to add
```

ADD (addition)

```
# to add
```

SUB (subtraction)

```
# to add
```

MUL (multiply)

```
# to add
```

IMUL (singed multiply)

```
# to add
```

DIV (divide)

```
# to add
```

INC (increment)

```
# to add
```

DEC (decrement)

```
# to add
```

CMP (compare)

```
# to add
```

AND (logical and)

```
# to add
```

OR (logical or)

```
# to add
```

XOR (logical xor)

```
# to add
```

SHL

```
# to add
```

SHR

```
# to add
```

**Input and Output**

```
MOV DX, 03F8h 
OUT DX, AL

;Specifies the I/O port address in DX and outputs the contents of AL to that port
```

**Interrupt Vector Table**

```
MOV DX, 0013h 
MOV AX, 10h 
INT 21h

;Specifies the video mode in DX before calling an interrupt 
(e.g., INT 21h for DOS services).
```

***

### Pointer and Index Registers

SI (Source Index) and DI (Destination Index)

Two 16-bit registers – usually used in string manipulation operations. Often used in conjunction with string instructions to facilitate the movement of data between memory locations.

These registers simplify the process of moving and manipulating strings in memory, which is a common task in assembly language programming.

SI and DI, along with CX (the count register), are often used in combination to perform efficient block transfers and comparisons.

***

#### SI (Source Index)

**Purpose** - SI is commonly used as an index or pointer to the source data in memory during string operations. \
**Usage** - Instructions like MOVSB (move byte from address pointed by SI to address pointed by DI) or SCASB (scan byte at address pointed by DI and compare with AL) often involve the SI register.

Example:

```
MOV SI, 1000h        ; SI points to the source string in memory 
MOV AL, [SI]         ; AL is loaded with the byte at the memory location pointed                        by SI
```

***

DI (Destination Index)

**Purpose** - DI is commonly used as an index or pointer to the destination data in memory during string operations. \
**Usage** - Instructions like MOVSB (move byte from address pointed by SI to address pointed by DI) or STOSB (store AL at the address pointed by DI) often involve the DI register.

Example:

```
MOV DI, 2000h        ; DI points to the destination string in memory     
MOV [DI], AL         ; The byte in AL is stored at the memory location pointed                          by DI
```

***

### Control Register

### IP (Instruction Pointer Register)

The Instruction Pointer (IP) is a 16-bit register. The IP register specifically points to the memory address of the next instruction to be executed by the CPU. Together with the Code Segment (CS) register, the IP forms the effective address of the next instruction.


# Memory and Register Organization (part 2)

## Control Registers

### IP (Instruction Pointer Register)

The Instruction Pointer (IP) is a 16-bit register. \
The IP register specifically points to the memory address of the next instruction to be executed by the CPU. \
Together with the Code Segment (CS) register, the IP forms the effective address of the next instruction.

* **Pairing with Code Segment (CS):**&#x20;
  * The IP register works in conjunction with the Code Segment (CS) register to form the complete memory address of the next instruction.&#x20;
  * The combination of CS:IP is used to specify the address of the next instruction to be fetched and executed.
* **Segmented Memory Model:**&#x20;
  * The 8086 architecture employs a segmented memory model where memory is divided into segments.&#x20;
  * The CS register holds the segment base address, and the IP register holds the offset within that segment.
* **Program Counter Concept:**&#x20;
  * The IP register is often referred to as the Program Counter (PC) in other processor architectures.&#x20;
  * Certain instructions, such as jumps (e.g., JMP), calls (e.g., CALL), and returns (e.g., RET), can modify the value of the IP register.
* **Interrupts:**&#x20;
  * When an interrupt occurs, the IP register is typically pushed onto the stack as part of the interrupt handling process. The IP value is later restored during the interrupt return process.

***

### Flag Registry

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FgK5nOjZXgips6OQagFSa%2FPasted%20image%2020241115152703.png?alt=media&amp;token=dcdb91fa-79de-4c25-9dba-83f2bbceddef" alt=""><figcaption></figcaption></figure>

The FLAGS register in the Intel 8086 microprocessor is a 16-bit register that contains various flags, each of which indicates a specific condition or status resulting from the execution of instructions. The FLAGS register plays a crucial role in program control and decision-making.

***

#### Carry Flag (CF) - bit 0

Purpose: Indicates whether an arithmetic operation resulted in a carry out of the most significant bit. Affected by: Arithmetic instructions like ADD, ADC, SUB, SBB, etc.

#### Parity Flag (PF) – bit 2

Purpose: Indicates whether the number of set bits in the result is even. Affected by: Generally unaffected by direct instructions; arithmetic and logical operations indirectly affect it.

#### Auxiliary Carry Flag (AF) - bit 4

Purpose: Indicates whether there was a carry out of the low nibble (4 bits) during an arithmetic operation. Affected by: Arithmetic instructions.

#### Zero Flag (ZF) – bit 6

Purpose: Set if the result of an operation is zero; cleared otherwise. Affected by: Arithmetic and logical operations, as well as comparison instructions.

#### Sign Flag (SF) – bit 7

Purpose: Reflects the sign (positive or negative) of the result of an operation. Affected by: Arithmetic operations.

#### Trap Flag (TF) – bit 8

Purpose: Used for single-step debugging; enables the CPU to execute one instruction at a time. Affected by: Debugging instructions.

#### Interrupt Flag (IF) – bit 9

Purpose: Enables or disables interrupts. Affected by: STI (Set Interrupt) and CLI (Clear Interrupt) instructions.

#### Direction Flag (DF) – bit 10

Purpose: Determines the direction of string operations; if set, the string is processed from high memory to low memory, and vice versa if cleared. Affected by: STD (Set Direction) and CLD (Clear Direction) instructions.

#### Overflow Flag (OF) – bit 11

Purpose: Indicates whether an arithmetic operation resulted in an overflow (result too large to be represented in the destination operand). Affected by: Arithmetic operations like ADD, SUB, etc.

***

#### Examples

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FBv5kJsBIu8i51ARg5Q6h%2Fflags%20example.png?alt=media&amp;token=b1562848-1480-4a29-8f40-5b4614544046" alt=""><figcaption></figcaption></figure>

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FpTkyiG7Vz9iHQ2JW76Fq%2Fflags%20example%202.png?alt=media&amp;token=b1b7068f-dbc5-4ea4-a025-b844762785c5" alt=""><figcaption></figcaption></figure>

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FGPjyAOgAjLFf0PJdwUFf%2Fflags%20exampe%203.png?alt=media&amp;token=e53c9dc0-b9d5-444c-8e25-3815a0a6bf8e" alt=""><figcaption></figcaption></figure>

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2F9TpV1lltrTeH59HDQGnk%2Fflags%20example%204.png?alt=media&amp;token=e3f02767-991c-42d7-9fd2-f3f05b5862a1" alt=""><figcaption></figcaption></figure>

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FR4J7pU5xf7xRBHRf9bb2%2Fflags%20example%205.png?alt=media&amp;token=44c82eb8-95b6-4d88-aa9e-ed91f19bc55c" alt=""><figcaption></figcaption></figure>

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FIepvBGj81ImAJUXHfe8K%2Fflags%20example%207.png?alt=media&amp;token=65211b38-6b78-46f5-8789-7b42ef95123e" alt=""><figcaption></figcaption></figure>

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FTZrxOYdvuzqvM6Ojeopr%2Fflags%20registry%206.png?alt=media&amp;token=df07b7dd-937a-401c-8c38-06f2d4611507" alt=""><figcaption></figcaption></figure>

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2F61FrR3H9bo5mU46Im2ab%2Fflags%20example%208.png?alt=media&amp;token=f50cf3a2-221c-476a-ae13-faf5a38a894d" alt=""><figcaption></figcaption></figure>

***

## Segment Registers

* DS - Data Segment Points the segment where the data is stored
* CS - Code Segment Points the start segment of the executable code
* SS - Stack segment point to the base address of the segment that contains the program stack. The stack is a region of memory used for storing temporary data, return addresses, and local variables during subroutine calls.
* EX - Extra Segment Used for extra storage

***

## Extended Registers and Special Purpose Registers

* **SI (Source Index)**: String operations and data movement. One of the index registers used primarily in string operations. It is often paired with the Extra Segment (ES) register for source data.
* **DI (Destination Index)**: String operations and data movement.
* **SP (Stack Pointer)**: Managing the stack during function calls and returns. SP role is crucial for managing the program stack. It keeps track of the top of the stack, and various instructions use it for stack-related operations.
* **BP (Base Pointer)**: A reference point for local variables and parameters. Commonly used in function calls. BP is often used as a reference point within the stack frame for accessing local variables and parameters. It provides a convenient way to access data within a function's stack frame. Each function has local memory associated with it to hold incoming parameters, local variables, and (in some cases) temporary variables. This region of memory is called a stack frame and is allocated on the process' stack. The BP register is particularly useful for providing a stable reference point within the stack frame, facilitating efficient access to local data.


# Data Transfer & Algoritmic Operations

## Data Transfer

### Instruction MOV

The MOV (Move) instruction in Intel 8086 assembly language is used to transfer data between registers, memory locations, and immediate values.

**The syntax:** <mark style="color:yellow;">MOV destination, source</mark>

destination - This is where the data will be moved to. It can be a register or a memory location. \
source - This is the source of the data. It can be another register, a memory location, or an immediate value.

```nasm
MOV AX, BX         ; Move the contents of register BX into register AX
MOV CX, 10         ; Move the immediate value 10 into register CX
MOV DX, [SI]       ; Move the contents of the memory location addressed by                          ; the contents of SI into register DX

MOV [DI], AX       ; Move the contents of register AX into the memory location ;                      addressed by the contents of DI 

MOV [BX], 20       ; Move the immediate value 20 into the memory location                             addressed by the contents of BX

```

***

### Instruction XCHG

The XCHG (Exchange) instruction in Intel 8086 assembly language is used to swap the contents of two operands. This operation is often used for tasks such as sorting elements in an array or managing data in a program.

**The syntax:** <mark style="color:yellow;">XCHG destination, source</mark>

destination - This is one of the operands involved in the exchange operation. It can be a register or a memory location. \
source - This is the other operand involved in the exchange operation. It can be another register or a memory location.

```nasm
XCHG AX, BX          ; Swap the contents of registers AX and BX 
XCHG CX, [SI]        ; Swap the contents of register CX and the memory location                         addressed by the contents of SI

XCHG [DI], [BX]     ; Swap the contents of the memory locations addressed by                           the contents of DI and BX

```

***

### Instruction PUSH & POP

The PUSH and POP instructions in Intel 8086 assembly language are used to push data onto the stack and pop data from the stack, respectively.

**The syntax:** <mark style="color:yellow;">PUSH source</mark>

source - This is the operand whose value is to be pushed onto the stack. It can be a register or a memory location

**The syntax:** <mark style="color:yellow;">POP destination</mark>

destination - This is where the value popped from the stack will be stored. It can be a register or a memory location

```nasm
PUSH AX             ; Push the contents of register AX onto the stack
POP BX              ; Pop the value from the stack and store it in register BX
; MOV BX, AX 

PUSH [SI]           ; Push the contents of the memory location addressed by SI ;                       onto the stack

POP [DI]            ; Pop the value from the stack and store it in the memory                          location addressed by DI

PUSH 10             ; Push the immediate value 10 onto the stack 
POP CX              ; Pop the value from the stack and store it in register CX
;MOV CX, 10
```

The PUSH instruction pushes the specified value onto the stack. The POP instruction retrieves the top value from the stack and stores it in the specified destination.

These instructions are fundamental for managing the stack, especially in procedures and subroutine calls, where they are used to save and restore register values.

***

### Instruction LEA

LEA (Load Effective Address) instruction in Intel 8086 assembly language is used to load a memory address into a register.

The syntax: <mark style="color:yellow;">LEA destination, source</mark>

destination - This is the register that will receive the effective address. It cannot be a memory location. \
source - This is the operand whose address will be loaded into the destination register. It can be a memory location specified by an offset or an indexed address.

```nasm
LEA SI, [BX + 10]   ; SI is the destination register that will receive the                             effective address. [BX + 10] is the source, representing a                       memory location calculated as the sum of the contents of                         register BX and the immediate value 10.
```

The LEA instruction is often used to perform address calculations without accessing memory, making it useful for scenarios where you need to calculate addresses for array indexing or accessing data structures. It does not actually fetch data from memory; it only loads the calculated address into the specified register.

***

### String instruction MOVS

The MOVS (Move String) instruction in Intel 8086 assembly language is used for block memory transfers, commonly used for copying a string of bytes from one location to another.

The syntax: <mark style="color:yellow;">MOVS destination, source</mark>

destination - This is the destination memory address where the string will be copied. \
source - This is the source memory address from where the string will be copied.

```nasm
MOV SI, 1000h       ; Set the source index to memory address 1000h 
MOV DI, 2000h       ; Set the destination index to memory address 2000h 
MOV CX, 10          ; Set the count of bytes to copy 

MOVS                ; Copy the string of 10 bytes from [SI] to [DI]
```

***

### String instruction LODS

The LODS (Load String) instruction in Intel 8086 assembly language is used for loading a byte or word from the source string into the accumulator (AL or AX).

**The syntax:**

For loading a byte: <mark style="color:yellow;">LODSB</mark>

For loading a word: <mark style="color:yellow;">LODSW</mark>

The LODS instruction automatically increments or decrements the source index (SI register) based on the direction flag in the flags register. If the direction flag is set, the index is decremented; If the flag is clear, the index is incremented.

```nasm
MOV SI, 1000h      ; Set the source index to memory address 1000h
MOV CX, 10         ; Set the count of bytes to load
LODSB              ; Load a byte from [SI] into AL
```

**SI** is the source index pointing to the memory address of the source string. **CX** is the count of bytes to be loaded. **LODSB** is the instruction that loads a byte from the source string into the AL register. After execution, SI is incremented or decremented based on the direction flag, and CX is decremented.

**Similarly, you can use LODSW to load a word (two bytes) into the AX register.**

***

### String instruction STOS

The STOS (Store String) instruction in Intel 8086 assembly language is used for storing a byte or word from the accumulator (AL or AX) into the destination string.

**The syntax:**

For loading a byte: <mark style="color:yellow;">STOSB</mark>

For loading a word: <mark style="color:yellow;">STOSW</mark>

The STOS instruction automatically increments or decrements the destination index (DI register) based on the direction flag in the flags register. If the direction flag is set, the index is decremented; If the flag is clear, the index is incremented.

```nasm
MOV DI, 2000h      ; Set the destination index to memory address 2000h 
MOV CX, 10         ; Set the count of bytes to store 
STOSB              ; Store the byte in AL into [DI] 
```

**DI** is the destination index pointing to the memory address of the destination string. **CX** is the count of bytes to be stored. **STOSB** is the instruction that stores a byte from the accumulator (AL) into the destination string. After execution, DI is incremented or decremented based on the direction flag, and CX is decremented.

**Similarly, you can use STOSW to store a word (two bytes) from the accumulator (AX) into the destination string.**

***

## Arithmetic Operations

When working with these operations, it's important to consider operand sizes, handle overflow conditions, and interpret the flags in the flags register for conditional branching.

### Instruction ADD

Adds the source operand to the destination operand and stores the result in the destination.

The syntax: <mark style="color:yellow;">ADD destination, source</mark>

destination - This is the operand to which the source operand will be added. It can be a register or a memory location. \
source - This is the operand that will be added to the destination operand. It can be another register, a memory location, or an immediate value.

```nasm
ADD AX, BX      ; Add the contents of register BX to register AX 
ADD CX, 10      ; Add the immediate value 10 to register CX
ADD [SI], BX    ; Add the contents of register BX to the memory location                           addressed by SI 
ADD [DI], 20    ; Add the immediate value 20 to the memory location                                addressed by DI
```

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FGckKdpCRRCikfHvExzep%2FPasted%20image%2020241215105233.png?alt=media&amp;token=a16835c5-cf3d-4e3e-8cff-65335fb53423" alt=""><figcaption></figcaption></figure>

***

### Instruction SUB

Subtracts the source operand from the destination operand and stores the result in the destination.

The syntax: <mark style="color:yellow;">SUB destination, source</mark>

destination - This is the operand from which the source operand will be subtracted. It can be a register or a memory location. \
source - This is the operand that will be subtracted from the destination operand. It can be another register, a memory location, or an immediate value.

```nasm
SUB AX, BX  
SUB CX, 10  
SUB [SI], BX 
SUB [DI], 20
```

***

### Instruction INC

Increments the value of the destination operand by 1.

The syntax: <mark style="color:yellow;">INC destination</mark>

destination - This is the operand (register or memory location) whose value will be incremented.

```nasm
INC AX       ; Increment the value in register AX by 1
INC [SI]     ; Increment the value in the memory location addressed by SI by 1
INC CX       ; Increment the value in register CX by 1 (16-bit mode)
INC AL 
INC BH
```

***

### Instruction DEC

Decrements the value of the destination operand by 1.

The syntax: <mark style="color:yellow;">DEC destination</mark>

destination - This is the operand (register or memory location) whose value will be decremented.

***

### Instruction MUL

Multiplies the accumulator (AL for byte multiplication, AX for word multiplication) by the source operand, storing the result in the double-length register pair (AX:DX for word multiplication).

The syntax: <mark style="color:yellow;">MUL source</mark>

source - This is the operand that will be multiplied with the accumulator (AL for byte multiplication, AX for word multiplication).

The MUL instruction performs multiplication, and the result is stored in the specified destination register (AX for byte multiplication, DX:AX for word multiplication). If the result is larger than the destination size, the overflow is stored in the overflow flag (OF), and the carry flag (CF) is also affected.

Keep in mind that MUL is an unsigned multiplication instruction. If you need to perform signed multiplication, you should use the IMUL instruction. Additionally, care should be taken to handle overflow conditions appropriately, especially when dealing with large values.

```nasm
MOV AX, 1000h ; Load AX with a value 
MOV BX, 5     ; Load BX with a value 
MUL BX        ; Multiply AX by BX, result in AX (and DX if needed) 
MOV AX, 2000h ; Load AX with a value
MOV SI, 2     ; Load SI with an index
MUL [SI]      ; Multiply AX by the contents of the memory ; location addressed                   by SI
```

***

### Instruction DIV

Divides the double-length register pair (AX:DX for word division) by the divisor operand, storing the quotient in the accumulator and the remainder in the doublelength register pair.

The syntax: <mark style="color:yellow;">DIV divisor</mark>

divisor - This is the operand by which the double-length register pair (AX:DX for word division) is divided. The result is stored in the accumulator (AL for quotient) and the double-length register pair (DX:AX for remainder).

The DIV instruction performs unsigned division, and the result is stored in the specified destination registers (AL for quotient, DX for remainder). If the quotient is too large to fit in the destination register (AL), an overflow condition occurs, and the program should be designed to handle it.

It's essential to ensure that the divisor is not zero before executing the DIV instruction to avoid a divide-by-zero error.

```nasm
MOV AX, 2000h   ; Load AX with a value 
MOV BX, 10      ; Load BX with a value (divisor) 
DIV BX          ; Divide AX (and DX) by BX, result in AX (quotient) and DX                       (remainder) 

MOV AX, 3000h   ; Load AX with a value 
MOV SI, 3       ; Load SI with an index
DIV [SI]        ; Divide AX (and DX) by the contents of the memory location                        addressed by SI
```

***

### Instruction IMUL

Performs signed multiplication of the source operand and the destination operand, storing the result in the destination.

The syntax: <mark style="color:yellow;">IMUL destination, source</mark>

destination - This is the operand to be multiplied. It can be a register or a memory location. source - This is the multiplier. It can be another register, a memory location, or an immediate value.

The IMUL instruction performs signed multiplication, and the result is stored in the destination register (AX for byte multiplication, DX:AX for word multiplication). If the result is larger than the destination size, the overflow is stored in the overflow flag (OF), and the carry flag (CF) is also affected.

Unlike MUL, which performs unsigned multiplication, IMUL is used for signed multiplication. Additionally, care should be taken to handle overflow conditions appropriately, especially when dealing with large values.

***

### Instruction IDIV

Performs signed division of the double-length register pair (AX:DX for word division) by the signed divisor operand, storing the quotient in the accumulator and the remainder in the double-length register pair.

The syntax: <mark style="color:yellow;">IDIV divisor</mark>

divisor - This is the operand by which the double-length register pair (AX:DX for word division) is divided. The result is stored in the accumulator (AL for quotient) and the double-length register pair (DX:AX for remainder).

The IDIV instruction performs signed division, and the result is stored in the specified destination registers (AL for quotient, DX for remainder). If the quotient is too large to fit in the destination register (AL), an overflow condition occurs, and the program should be designed to handle it.

It's essential to ensure that the divisor is not zero before executing the IDIV instruction to avoid a divide-by-zero error. Additionally, like with IMUL, care should be taken to handle overflow conditions appropriately, especially when dealing with large values.

***

### Instruction NEG

The NEG (Negate) instruction in Intel 8086 assembly language is used to change the sign of a number. It essentially performs two's complement negation on the specified operand.

The syntax: <mark style="color:yellow;">NEG destination</mark>

destinations - This is the operand (register or memory location) whose value will be negated.

The NEG instruction changes the sign of the specified operand by performing two's complement negation. If the operand is initially positive, NEG makes it negative, and vice versa. The flags in the flags register are affected, including the overflow flag (OF), which is set if the original value was the most negative representable number.

The NEG instruction is commonly used in scenarios where sign reversal is needed, such as in arithmetic calculations or data processing.

```nasm
MOV AX, 1000h      ; Load AX with a value 
NEG AX             ; Negate the value in register AX

MOV [SI], 2000h    ; Load the memory location addressed by SI with a value 
NEG [SI]           ; Negate the value in the memory location addressed by SI 
MOV CX, -500   
NEG CX             ; Load CX with a signed value ; Negate the value in register                       CX (16-bit mode)
```

1000(16) => => F000h

1000(16) => 0001 0000 0000 0000 (2) = 4096(10) 2(16) = 65536-4096 = F000h

***

### Instruction CMP

Compares two operands by subtracting operand2 from operand1, setting the flags without storing the result. The CMP (Compare) instruction in Intel 8086 assembly language is used to compare two operands. It subtracts the second operand from the first operand but does not store the result; instead, it updates the flags in the flags register based on the result of the subtraction.

The syntax: <mark style="color:yellow;">CMP operand1, operand2</mark>

operand1 - The first operand in the comparison. \
operand2 - The second operand in the comparison.

After the CMP instruction is executed, the flags register is updated, providing information about the relationship between the two operands. Commonly used flags include the zero flag (ZF), sign flag (SF), and overflow flag (OF), among others.

The CMP instruction is often followed by conditional jump instructions (e.g., JE, JG, JL) based on the flags' state to control program flow.

```nasm
MOV AX, 1000h   ; Load AX with a value 
MOV BX, 2000h   ; Load BX with another value 
CMP AX, BX      ; Compare AX and BX 

MOV CX, 500     ; Load CX with a value 
CMP CX, 300     ; Compare CX and the immediate value 300

MOV SI, 1000h   ; Load SI with an index 
MOV AX, 2000h   ; Load AX with a value 
CMP AX, [SI]    ; Compare AX and the contents of the memory ; location addressed                   by SI
```


# Control Structures

## Branching

(Conditional branching and jumps)

**Definition** Conditional branching is a fundamental concept in assembly language programming that allows the flow of execution to be changed, based on the evaluation of a condition.

In the context of the 8086 microprocessor, this involves making decisions to either continue executing the next instruction in sequence or to jump to a different part of the code based on the status of specific flags.

**Purpose** Enables implementation of control structures such as if-then-else conditions, loops, and switches which are essential for creating logical pathways in code.

The Intel 8086 microprocessor evaluates conditions using the flags in the flag register, particularly the zero flag (ZF), carry flag (CF), sign flag (SF), overflow flag (OF), and parity flag (PF). These flags are set or cleared by arithmetic, logical, and comparison operations.

***

### JMP (Jump)

The JMP instruction is used to transfer control to another location in the program unconditionally. It simply transfers execution to the specified target address.

For example:

```nasm
JMP label_1     ; go to the label1 and continue from there
;code
;code

label_1:
;more code
```

***

### JE (Jump If Equal)

The JE instruction is used to jump to a target address if the **Zero Flag (ZF)** is set (indicating that the result of a previous operation was zero or equal). It is often used in conditional branching for equality checks.

For example:

```nasm
JE label2     ; if ZF==1 go to the label2 and continue from there
… 
… 

label2:
…
```

***

JNE (Jump If Not Equal)

The JNE instruction is used to jump to a target address if the <mark style="color:red;">**Zero Flag (ZF)**</mark> is clear (indicating that the result of a previous operation was not zero or not equal). It is used for inequality checks.

For example:

```nasm
JNE label3     ; if ZF==0 go to the label3 and continue from there
…
…

label3:
…
```

***

### JG (Jump If Greater)

The JG instruction is used to jump to a target address if the <mark style="color:red;">**Zero Flag (ZF)**</mark> is clear, and the <mark style="color:red;">**Sign Flag (SF)**</mark> and <mark style="color:red;">**Overflow Flag (OF)**</mark> are the same (indicating a signed greater-than comparison).

For example:

```nasm
JG label4      ;if ZF==0 and SF==OF go to the label4 and continue from there
…
…

label4:
…
```

***

### JGE (Jump If Greater or Equal)

The JGE instruction is used to jump to a target address if the <mark style="color:red;">**Zero Flag (ZF)**</mark> is set, or the <mark style="color:red;">**Sign Flag (SF)**</mark> and <mark style="color:red;">**Overflow Flag (OF)**</mark> are the same (indicating a signed greaterthan-or-equal comparison).

For example:

```nasm
JGE label5    ; if ZF==1 (or SF==OF) go to the label5 and continue from there
…
…

label5:
…
```

***

### JL (Jump If Less)

The JL instruction is used to jump to a target address if the <mark style="color:red;">**Zero Flag (ZF)**</mark> is clear, and the <mark style="color:red;">**Sign Flag (SF)**</mark> and <mark style="color:red;">**Overflow Flag (OF)**</mark> are different (indicating a signed less-than comparison).

For example:

```nasm
JL label6    ; if ZF==0 (and SF!=OF) go to the label6 and continue from there
…
…

label6:
…
```

***

### JLE (Jump If Less or Equal)

The JLE instruction is used to jump to a target address if the <mark style="color:red;">**Zero Flag (ZF)**</mark> is set, or the <mark style="color:red;">**Sign Flag (SF)**</mark> and <mark style="color:red;">**Overflow Flag (OF)**</mark> are different (indicating a signed less-thanor-equal comparison).

For example:

```nasm
JLE label7     ; if ZF=1 (or SF!=OF) go to the label7 and continue from there
…
…

label7:
…
```

***

### Other Branching Instructions

▪ <mark style="color:orange;">**JE/JZ**</mark> <mark style="color:orange;"></mark><mark style="color:orange;">(Jump if Equal/Zero)</mark>: Jump if the Zero Flag (ZF) is set (indicating that the operands are equal, or the result of the last operation was zero).

▪ <mark style="color:orange;">**JNE/JNZ**</mark> <mark style="color:orange;"></mark><mark style="color:orange;">(Jump if Not Equal/Not Zero)</mark>: Jump if the Zero Flag (ZF) is clear (indicating that the operands are not equal, or the result of the last operation was not zero).

▪ <mark style="color:orange;">**JG**</mark> <mark style="color:orange;"></mark><mark style="color:orange;">(Jump if Greater)</mark>: Jump if the Zero Flag (ZF) is clear, and the Sign Flag (SF) and Overflow Flag (OF) are the same (indicating a signed greater-than comparison).

▪ <mark style="color:orange;">**JGE/JNL**</mark> <mark style="color:orange;"></mark><mark style="color:orange;">(Jump if Greater or Equal/Not Less)</mark>: Jump if the Zero Flag (ZF) is set, or the Sign Flag (SF) and Overflow Flag (OF) are the same (indicating a signed greater-than-or-equal comparison).

▪ <mark style="color:orange;">**JL/JNGE**</mark> <mark style="color:orange;"></mark><mark style="color:orange;">(Jump if Less/Not Greater or Equa</mark>l): Jump if the Zero Flag (ZF) is clear, and the Sign Flag (SF) and Overflow Flag (OF) are different (indicating a signed less-than comparison).

▪ <mark style="color:orange;">**JLE/JNG**</mark> <mark style="color:orange;"></mark><mark style="color:orange;">(Jump if Less or Equal/Not Greater)</mark>: Jump if the Zero Flag (ZF) is set, or the Sign Flag (SF) and Overflow Flag (OF) are different (indicating a signed less-than-or-equal comparison).

▪ <mark style="color:orange;">**JC**</mark> <mark style="color:orange;"></mark><mark style="color:orange;">(Jump if Carry)</mark>: Jump if the Carry Flag (CF) is set (indicating a carry or borrow occurred in an arithmetic operation).

▪ <mark style="color:orange;">**JNC/JNB**</mark> <mark style="color:orange;"></mark><mark style="color:orange;">(Jump if No Carry/Not Below):</mark> Jump if the Carry Flag (CF) is clear (indicating no carry or borrow occurred).

▪ <mark style="color:orange;">**JO**</mark> <mark style="color:orange;"></mark><mark style="color:orange;">(Jump if Overflow)</mark>: Jump if the Overflow Flag (OF) is set (indicating signed overflow occurred in an arithmetic operation).

▪ <mark style="color:orange;">**JNO**</mark> <mark style="color:orange;"></mark><mark style="color:orange;">(Jump if No Overflow)</mark>: Jump if the Overflow Flag (OF) is clear (indicating no signed overflow occurred).

▪ <mark style="color:orange;">**JS**</mark> <mark style="color:orange;"></mark><mark style="color:orange;">(Jump if Sign)</mark>: Jump if the Sign Flag (SF) is set (indicating the result is negative).

▪ <mark style="color:orange;">**JNS**</mark> <mark style="color:orange;"></mark><mark style="color:orange;">(Jump if No Sign)</mark>: Jump if the Sign Flag (SF) is clear (indicating the result is non-negative or positive).

▪ <mark style="color:orange;">**JP/JPE**</mark> <mark style="color:orange;"></mark><mark style="color:orange;">(Jump if Parity/Parity Even)</mark>: Jump if the Parity Flag (PF) is set (indicating an even number of set bits in the result).

▪ <mark style="color:orange;">**JNP/JPO**</mark> <mark style="color:orange;"></mark><mark style="color:orange;">(Jump if No Parity/Parity Odd)</mark>: Jump if the Parity Flag (PF) is clear (indicating an odd number of set bits in the result).

▪ <mark style="color:orange;">**JB/JNAE**</mark> <mark style="color:orange;"></mark><mark style="color:orange;">(Jump if Below/Not Above or Equal)</mark>: Jump if the Carry Flag (CF) is set (indicating an unsigned less-than comparison).

▪ <mark style="color:orange;">**JAE/JNB**</mark> <mark style="color:orange;"></mark><mark style="color:orange;">(Jump if Above or Equal/Not Below)</mark>: Jump if the Carry Flag (CF) is clear (indicating an unsigned greater-than-or-equal comparison).

▪ <mark style="color:orange;">**JBE/JNA**</mark> <mark style="color:orange;"></mark><mark style="color:orange;">(Jump if Below or Equal/Not Above)</mark>: Jump if the Carry Flag (CF) is set or the Zero Flag (ZF) is set (indicating an unsigned less-than-or-equal comparison).

▪ <mark style="color:orange;">**JA/JNBE**</mark> <mark style="color:orange;"></mark><mark style="color:orange;">(Jump if Above/Not Below or Equal)</mark>: Jump if the Carry Flag (CF) is clear and the Zero Flag (ZF) is clear (indicating an unsigned greater-than comparison).

***

## Looping

### For Loop

A for loop is typically implemented <mark style="color:yellow;">using a combination of instructions like MOV, CMP, JNZ, and loop control variables</mark>. The loop control variable <mark style="color:yellow;">is typically decremented or incremented within the loop body</mark> until a certain condition is met.

For loop repeats a block of code a fixed number of times.

In Intel 8086 assembly language, a for loop can be implemented using the CX register as a loop counter.

Here's an example of a simple for loop that counts from 1 to 5:

```nasm
mov cx, 5        ; Initialize CX with the loop count (5)
mov ax, 18 

for_loop: 
cmp cx, ax       ; Bitwise CX with itself – to check if zero
jz loop_end      ; Check if CX is zero (end of loop)

…                ; for body

inc cx           ; Increment CX
jmp for_loop     ;continue looping

loop_end:        ; Code after the loop 
int 0x21         ;terminate program
```

**The For Loop Block Diagram**

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2Fax9FPkeWskQuXFH7p7Bf%2FPasted%20image%2020241222124744.png?alt=media&amp;token=2386c307-516c-4c00-8ed9-b62b7f87af4c" alt=""><figcaption></figcaption></figure>

***

### While Loop

A while loop can be implemented using a combination of instructions such as <mark style="color:yellow;">CMP, JZ, and loop control variables</mark>. The loop continues **as long as a specified condition is true**.

A while loop is used to repeat a specific block of code an **unknown number of times**, until a condition is met.

```nasm
count db 5            ; Define a byte variable 'count' with an initial value of 5
mov cx, 20            ; Load 20 into the CX register

while_loop:
mov ax, [count]
test cx, ax           ; bitwise check -> CX AND AX
jz while_loop_end     ; Jump to 'while_loop_end' if CX is zero

…                     ; loop body

dec cx 
jmp while_loop

while_loop_end:       ; If (CX AND AX) is zero, the loop terminates                                    ; Continue with the rest of your program here

int 21h               ; Terminate program
```

**The While-Loop block diagram**

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FAXMjyg8Zc4OR8Bzn2ugq%2FPasted%20image%2020241222124830.png?alt=media&amp;token=fe76a20c-1acc-44be-96f4-12dff9dc1248" alt=""><figcaption></figcaption></figure>

***

### Do-While Loop

A do-while loop can be implemented using a combination of instructions like **JMP, CMP, and JZ**. The loop body is executed at least once, and then the condition is checked to determine if the loop should continue.

```nasm
mov cx, 1             ; Initialize CX with the loop count (5)

do_while_loop: 
...                   ; Loop body

dec cx                
jz loop_end           ; Check if CX is zero (end of loop)

jmp do_while_loop     ; Continue looping

loop_end:             ; Code after the loop
int 21h               ; Terminate the program
```

**Do-While Loop block diagram**

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FQz1ZZFET5OQ4NKIlNWnv%2FPasted%20image%2020241222124950.png?alt=media&amp;token=801fb425-5236-4447-bd42-8a08a62d5f57" alt=""><figcaption></figcaption></figure>

***

### Infinite Loop

An infinite loop is created using an <mark style="color:yellow;">unconditional jump instruction</mark> (e.g., JMP), causing the program to continuously execute a block of code <mark style="color:yellow;">until manually interrupted or terminated</mark>.

```nasm
loop_start: 
mov ah, 9                        ; AH = 9 indicates print string function
mov dx, hello_msg                ; DX points to the address of the message
int 21h                          ; Call the DOS interrupt to print the message

jmp loop_start                   ; Infinite loop: Jump back to 'loop_start’
hello_msg db "Hello, World!", 0  ; Null-terminated message

int 20h                          ; Terminate the program
```

***

### Nested Loops

Nested loops can <mark style="color:yellow;">be implemented by using multiple loop control variables and appropriately placed labels and jump instructions</mark>. This allows creation of more complex looping structures.

***

### Looping with Counters

Looping can also be controlled using loop counters. <mark style="color:yellow;">The CX register is commonly used as a loop counter in Intel 8086 assembly language</mark>. You can decrement or increment the counter in each iteration and use conditional jumps (e.g., JNZ or JZ) to control the loop.

```nasm
mov cx, 10            ; Initialize CX with the loop count (10) 

loop_start: 
dec cx                ; Decrement CX

jz loop_end           ; Check if CX is zero (end of loop)
 
 
jmp loop_start        ; Continue looping  
 
loop_end:             ; Code after the loop 
int 20h               ; Terminate the program
```

***

### Break Statement

A break statement can be implemented using conditional jumps and labels to exit a loop prematurely based on a certain condition.

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FyVFBBKydpPyJhL9u0YzM%2FPasted%20image%2020241222124442.png?alt=media&amp;token=fdf0653a-73d7-45cc-9588-ab17b2eaf050" alt=""><figcaption></figcaption></figure>

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2F1omD3OGUrSUrYWEdwA0b%2FPasted%20image%2020241222124513.png?alt=media&amp;token=b90fda51-9e09-4146-9d11-80de6d765dea" alt=""><figcaption></figcaption></figure>

***

### Continue Statement

A continue statement can be implemented using conditional jumps and labels to skip the current iteration of a loop and proceed to the next iteration based on a certain condition.

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FASMuf21UOh1OGSzV66nK%2FPasted%20image%2020241222124538.png?alt=media&amp;token=a868692c-d749-4790-afdd-127940ace6e8" alt=""><figcaption></figcaption></figure>

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FO64VcOUnUxZuMerSZ8n5%2FPasted%20image%2020241222124551.png?alt=media&amp;token=6bb7a5fc-6b73-42d6-b966-ef39dfeb272a" alt=""><figcaption></figcaption></figure>

***

### Looping with Arrays

Use loops to iterate over arrays or data structures, performing operations on each element or item in the array.

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FXyNlsTHYfOgV2kgAHHRq%2FPasted%20image%2020241222124623.png?alt=media&amp;token=6e58fc4b-6508-4faa-bbac-6cba9606cdc1" alt=""><figcaption></figcaption></figure>

***

### Looping with Strings

Loops can be used for string manipulation, iterating over characters in a string, and performing string-related operations.

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FRdXXgbwONvd9Y9eHL91Z%2FPasted%20image%2020241222124648.png?alt=media&amp;token=8231adb8-252f-4d0d-bcd2-b12baa52b884" alt=""><figcaption></figcaption></figure>


# Examples/Projects


# Assembly Basics Tasks

{% tabs %}
{% tab title="Task 01.asm" %}

```nasm
; Task 01: add two numbers

; Direct addressing
MOV AL, 0x10
MOV BL, 0x20

ADD AL, BL


; With Variables
X DB 0x10
Y DB 0x20
RESULT DB ?

MOV AL, X
MOV BL, Y

ADD AL, BL

MOV DI OFFSET[RESULT]
MOV DI AL
```

{% endtab %}

{% tab title="Task 02.asm" %}

```nasm
; Task 02: Subtract Two Numbers

; Direct addressing
MOV AL, 0x10
MOV BL, 0x20

SUB BL, AL


; With Variables
X DB 0x10
Y DB 0x20
RESULT DB ?

MOV AL, X
MOV BL, Y

SUB BL, AL

MOV DI, OFFSET RESULT
MOV DI BL
```

{% endtab %}

{% tab title="Task 03.asm" %}

```nasm
; Task 03: Multiply Two Numbers

MOV AL 10
MOV BL 3
MUL BL


; With Variables
DATA SEGMENT
X DB 10
Y DB 3
RESULT DB ?
DATA ENDS

CODE SEGMENT
ASSUME CS:CODE, DS:DATA

START:
    MOV AX, DATA        
    MOV DS, AX           

    MOV AL, X
    MOV BL, Y

    MUL BL

    MOV DI, OFFSET RESULT
    MOV [DI], AL 

    ; Terminate program (for DOS emulator)
    MOV AX, 4C00H
    INT 21H

END START
CODE ENDS
```

{% endtab %}

{% tab title="Task 04.asm" %}

```nasm
; Task 04: Divide Two Numbers

; Direct addressing
MOV AL, 10
MOV BL, 5

DIV AL,BL


;With Variables
DATA SEGMENT
X DB 10
Y DB 5
RESULT DB ?
DATA ENDS

CODE SEGMENT
ASSUME CS:CODE. DS:DATA

START:
    MOV AX, DATA
    MOV DS, AX

    MOV AL, X
    MOV BL, Y

    DIV AL, BL

    MOV DI, OFFSET RESULT
    MOV [DI], AL


CODE ENDS  
END START
```

{% endtab %}

{% tab title="Task 05.asm" %}

```nasm
; Task 05: Swap Two Numbers

DATA SEGMENT
NUM1 DW 0x1001
NUM2 DW 0x2002
DATA ENDS

CODE SEGMENT
ASSUME CS:CODE, DS:DATA

START: 
    MOV AX, DATA
    MOV DS, AX

    MOV AX, NUM1
    MOV BX, NUM2

    MOV DX, AX
    MOV AX, BX
    MOV BX, DX

    MOV NUM1, AX
    MOV NUM2, BX

    MOV AX, 4C00H
    INT 21H

CODE ENDS
END START
```

{% endtab %}
{% endtabs %}


# Addition of two 8-bit numbers

{% tabs %}
{% tab title="First Tab" %}

```
data segment
a db 09h
b db 0fh 
c dw ?
data ends


code segment
assume cs:code, ds:data
start:

mov ax, data
mov ds, ax

mov al, a
mov bl, b
add al, bl
mov c, ax

mov ah,4ch
int 21h

code ends 
end start 
```

{% endtab %}
{% endtabs %}

## Understand the code

### Data Segment:

data segment: This section defines the variables.&#x20;

<mark style="color:yellow;">**a db 09h**</mark>**:** Declares an 8-bit byte variable a initialized to 09h (hexadecimal).&#x20;

<mark style="color:yellow;">**b db 02h**</mark>**:** Declares an 8-bit byte variable b initialized to 02h.&#x20;

<mark style="color:yellow;">**c dw ?**</mark>**:** Declares a 16-bit word variable c to store the sum. We use a 16-bit variable to handle potential overflow if the sum exceeds 255 (FFh).

### Code Segment:

<mark style="color:yellow;">**code segment**</mark>**:** This section contains the program instructions. ; assume cs:code,ds:data: Tells the assembler that the cs register points to the code segment and the ds register points to the data segment.&#x20;

<mark style="color:yellow;">**start**</mark>**:** The label marking the program’s entry point.&#x20;

<mark style="color:yellow;">**mov ax,data**</mark>**:** Loads the address of the data segment into the ax register.&#x20;

<mark style="color:yellow;">**mov ds,ax**</mark>**:** Sets the ds register to point to the data segment. This is crucial for accessing the variables a and b.&#x20;

<mark style="color:yellow;">**mov al,a**</mark>**:** Loads the value of a (09h) into the al register (the lower 8 bits of ax).&#x20;

<mark style="color:yellow;">**mov bl,b**</mark>**:** Loads the value of b (02h) into the bl register (the lower 8 bits of bx).&#x20;

<mark style="color:yellow;">**add al,bl**</mark>**:** Adds the contents of bl to al. The result (0Bh) is stored in al.&#x20;

<mark style="color:yellow;">**mov c,ax**</mark>**:** Moves the contents of ax (which now contains the sum in its lower byte, al) into the variable c.&#x20;

<mark style="color:yellow;">**int 3**</mark>**:** The breakpoint instruction halts execution for debugging purposes.


# Addition of two 16-bit numbers

{% tabs %}
{% tab title="code.asm" %}

```
data segment 
a dw 0202h
b dw 0408h
c dw ?
data ends


code segment
assume cs:code, ds:data
start:

mov ax, data
mov ds, ax
mov ax, a 
mov bx, b
add ax, bx
mov c, ax

int 3

code ends
end start
```

{% endtab %}

{% tab title="flowchart.pgn" %}

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FfYG3jOtV5asRq5alwdxk%2Fflowchart1.PNG?alt=media&amp;token=50e97f44-6d81-4d06-9595-a022595446e1" alt=""><figcaption></figcaption></figure>
{% endtab %}
{% endtabs %}

## Understand the code

### Data Segment&#x20;

<mark style="color:yellow;">**a dw 0202h**</mark>: This line declares a 16-bit word variable named a and initializes it with the hexadecimal value 0202.&#x20;

<mark style="color:yellow;">**b dw 0408h**</mark>: Similarly, this declares a 16-bit word variable b and initializes it with the hexadecimal value 0408.&#x20;

<mark style="color:yellow;">**c dw ?**</mark>: This declares a 16-bit word variable c but does not initialize it. It will store the result of the addition operation.

### Code Segment&#x20;

<mark style="color:yellow;">**mov ax,data**</mark>**:** This instruction moves the address of the data segment into the AX register.

**mov ds,ax**: This sets the Data Segment (DS) register to the value in AX, effectively making the data segment accessible for data operations.

<mark style="color:yellow;">**mov ax,a**</mark>**:** This moves the value of a (0202h) into the AX register.

<mark style="color:yellow;">**mov bx,b**</mark>**:** This moves the value of b (0408h) into the BX register.

<mark style="color:yellow;">**add ax,bx**</mark>**:** This adds the contents of BX to the contents of AX. The result (060Ah) is stored in AX. ; mov c,ax: This moves the result from AX to the variable c.&#x20;

<mark style="color:yellow;">**int 3**</mark>**:** This is a breakpoint instruction that causes the program to halt, allowing for debugging and inspection of registers and memory.

### Overall Functionality&#x20;

The code performs the following steps:&#x20;

<mark style="color:yellow;">**Initialization**</mark>**:** Sets up the data segment and initializes variables a and b. ; Addition: Loads the values of a and b into registers AX and BX, respectively. Adds the two values and stores the result in AX.

<mark style="color:yellow;">**Result Storage**</mark>**:** Stores the result from AX into the variable c.&#x20;

<mark style="color:yellow;">**Program Termination**</mark>**:** Halts the program execution using the int 3 instruction.&#x20;

In essence, this code adds two 16-bit hexadecimal numbers (0202h and 0408h) and stores the result (060Ah) in the variable c.


# Display "Hello"

{% tabs %}
{% tab title="code.asm" %}

```
data segment
string db "Hello"
data ends

code segment
assume cs:code, ds:data
start:

mov ax, data
mov ds, ax

mov sp, 0d000h
mov bx, offset string
mov cx, 0005h

move:
mov ah, 02h
mov dl,[bx]
int 21h
inc bx
dec cx 
jnz move

mov ax, 4c00h
int 21h

code ends
end start
```

{% endtab %}
{% endtabs %}


# Flags Practice

## CF (Carry Flag)

When we have two 8-bit numbers in a calculation, and the result is more than 8 bits (9 for example) than the carry flag is 1\
If we have two 16-bit numbers in a calculation, and the result is more than 16 bits (17) than the carry flag is 1

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FQn0CUgFOzt0QyjzgI8tL%2Fimage.png?alt=media&amp;token=5b37a2a5-cc66-400f-9f05-63465cc98058" alt=""><figcaption></figcaption></figure>

***

## ZF (Zero Flag)&#x20;

When the result is 0, zero flag is 1

***

## SF (Sign Flag)

If the result in a calculation has the MSB (most significant bit) 1, than the sign flag is 1. \
If we have a carry flag up, a bigger result than 8-bit, the carry flag does not determine the sign flag, the sign flag is 1 only if the msb of the 8-bit is 1.

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2F5F86ffpx5M2fNJ2gr0EW%2Fimage.png?alt=media&amp;token=fca431c4-3bf7-42bd-824a-a2af2e79db73" alt=""><figcaption></figcaption></figure>

***

## Overflow Flag

This flag is up if in a calculation, the MSB of the first number is different than the result MSB.

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FlDNX0iGc5JsFWZSTsDRq%2Fimage.png?alt=media&amp;token=5acb8e0c-5da3-4343-bced-875344b68075" alt=""><figcaption></figcaption></figure>

***

## Parity Flag

If the number of 1s in the result is paired (2, 4, 6, 8) the flag is up \
If we have 16-bit situation, the Least significant byte is looked (last 8 bits)

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FX9oVyWxGoMYkXUX9wVbs%2Fimage.png?alt=media&amp;token=f0bb37a2-0830-4b4c-ab12-c5c36454c01f" alt=""><figcaption></figcaption></figure>


# Reverse a String

{% tabs %}
{% tab title="code.asm" %}

```nasm
DATA SEGMENT
	InputString db "Hello00!", 0, '$'  ; Null-terminated string to be reversed
	
DATA ENDS

CODE SEGMENT
	ASSUME CS:CODE, DS:DATA

	START:

	MOV AX, DATA        		    ; Load data segment address
	MOV DS, AX

	LEA SI, InputString  		    ; Load address of the input string (SI points to the beginning)


	; Calculate the length
	LEA SI, InputString
	MOV CX, -1
DO:
    	LODSB
    	INC CX
    	CMP AL, 0
    	JNE DO


    	MOV DI, OFFSET InputString
    	ADD DI, CX
	DEC DI

	; Reverse the string
	MOV SI, OFFSET InputString	    ; Reset SI to the beginning

reverseLoop:
	CMP SI, DI             		    ; Compare SI and DI to check if we've reached the middle
	JAE done               		    ; If SI >= DI, the string is reversed

	MOV AL, [SI]           		    ; Load character from the beginning
	MOV AH, [DI]           		    ; Load character from the end
	MOV [SI], AH           		    ; Swap characters
	MOV [DI], AL
	INC SI                 		    ; Move SI forward
	DEC DI                 		    ; Move DI backward
	JMP reverseLoop

done:
	; Print the reversed string
	MOV AH, 09h            		    ; Function code for string output
	MOV DX, OFFSET InputString  	    ; DS:DX points to the reversed string; The string must ends with '$'
	INT 21h                		    ; Display the reversed string


    	MOV AX, 4C00h           	    ; Function code for program termination
    	INT 21h                 	    ; Trigger software interrupt 21h (DOS)

CODE ENDS
END START	
```

{% endtab %}
{% endtabs %}


# Simple Arithmetic

{% tabs %}
{% tab title="code.asm" %}
Takes two 8-bit numbers as input from the user\
Adds the numbers and stores the result in the AX register. \
Multiplies the numbers and stores the result in the BX register. \
Displays the results.

```nasm
DATA SEGMENT 
    MSG1 DB "Enter first number (0-9): $"
    MSG2 DB "Enter second number (0-9): $"
    RESULT_SUM DB "Sum is: $"
    Result_MUL DB "Product is: $"
DATA ENDS

CODE SEGMENT
    ASSUME CS:CODE, DS:DATA
    START:
        MOV AX, DATA
        MOV DS, AX

        ; Prompt for the first number
        MOV AH, 09H
        LEA DX, MSG1
        INT 21H

        ; Read the first number
        MOV AH, 01H
        INT 21H
        SUB AL, '0'
        MOV BL,AL

        ; Prompt for the second number
        MOV AH, 09H
        LEA DX, MSG2
        INT 21H

        ; Read the first number
        MOV AH, 01H
        INT 21H
        SUB AL, '0'
        MOV BH,AL

        ; Calculate sum
        MOV AL,BL
        ADD AL, BH
        ADD AL, '0'

        ; Display sum
        MOV AH, 09H
        LEA DX, RESULT_SUM
        INT 21H
        MOV DL, AL
        MOV AH,02H
        INT 21H

        ; Calculate product
        MOV AL, BL
        MUL BH
        ADD AL, '0'

        ; Display product
        MOV AH, 09H
        LEA DX, RESULT_MUL
        INT 21H
        MOV DL, AL
        MOV AH, 02H
        INT 21H

        ; Exit program
        MOV AX, 4C00H
        INT 21H
CODE ENDS
END START
```

{% endtab %}
{% endtabs %}


# Assembly x86 (32-bit)


# KQL


# Cheet-Sheet

### Commands

<table><thead><tr><th width="179.8828125">Command</th><th>Description</th><th width="259.48046875">Example Usage</th></tr></thead><tbody><tr><td>where</td><td>searches for the word we specify in the field we specify in the table we specify</td><td>Table Name<br>| where {field name} == '{what we are searching for}'</td></tr><tr><td>take</td><td>takes the specified amount of rows and displays them</td><td>Table Name<br>| take 10</td></tr><tr><td>limit</td><td>Same as 'take' command</td><td></td></tr><tr><td>contains</td><td></td><td></td></tr><tr><td>has</td><td></td><td></td></tr><tr><td>startswith</td><td></td><td></td></tr><tr><td>endswith</td><td></td><td></td></tr><tr><td>distinct</td><td></td><td></td></tr><tr><td>count</td><td></td><td></td></tr><tr><td>sort</td><td></td><td></td></tr><tr><td>order</td><td>Same as 'sort' command</td><td></td></tr><tr><td>project</td><td></td><td></td></tr><tr><td>project-reorder</td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr></tbody></table>

### Operators

| Operator | Desc | Example |
| -------- | ---- | ------- |
| ==       |      |         |
| !=       |      |         |
| =\~      |      |         |
| >        |      |         |
| >=       |      |         |
| <        |      |         |
| <=       |      |         |
|          |      |         |
| and      |      |         |
| or       |      |         |

### renaming fields


# Intro


# pipes | where | take

### pipes

Basic as it is, pipes are used in every query language.

Pipes take the output of the previous command and serve it as input in the next command.

#### Example

```
Table Name
| first command
| second command
```

The goal it to narrow our search to exactly what we need.

***

### where

The where command is used to select entry's from specific fields.

#### Example

Customers table:

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2F24zfnkWt4xqWJDRdfOAL%2FPasted%20image%2020260211131803.png?alt=media&amp;token=79b51d86-4930-490b-a5bc-4058237c4faa" alt=""><figcaption></figcaption></figure>

The table has 18000+ records.

If we want to search for customers that have the name 'Peter' and are from 'Europe' we would use the where command with the 'First name' and the 'ContinentName' fields.

```kql
Customers
| where FirstName == "Peter"
| where ContinentName == "Europe"
```

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FTORAmSi2wWX6ZERp7k6m%2FPasted%20image%2020260211131953.png?alt=media&amp;token=e26afddf-011b-410b-9392-b4d90d2f0842" alt=""><figcaption></figcaption></figure>

***

### take

Nothing special of a command, just takes the amount of rows you specify.

#### Example

```
Customers
| take 10
```

This takes the first 10 rows of the 'Customers' table.

***

### Different Data Bases

If we use one database, we can specify all the tables that we want in that db.

But if we have a second db and we want to search a table from there? We can specify it like this:

```
cluster('cluster name').database('db name').table('table name')
| normal piped commands
```

#### Example

If we have a few queries for the 'ContosoSales' db, and want to search smth from the 'Samples' db as well, we can do it like this:

```
cluster('help').database('Samples').table('PopulationData')
| where State == "ARKANSAS"
```

Just specify the exact 'path' that leads to the table you want and thats it, the pipe commands below are syntax'd the same as always.

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FCaudT7c08AVaspSXbuXa%2FPasted%20image%2020260211132547.png?alt=media&amp;token=80305f74-a7e3-44d1-8be6-538e9eb9b744" alt=""><figcaption></figcaption></figure>


# Syntax and Query Structure

### Some important rules:

1. You can put as many spaces you want btw the pipe and the command

```kql
cluster('help').database('SecurityLogs').Email
|     where subject == "jasade"
```

2. You can put many pipe commands in one line

```kql
cluster('help').database('SecurityLogs').Email
| where subject == "jasade" | sort by event_time asc
```

3. Double slash to comment '//'

```kql
//this is a comment
cluster('help').database('SecurityLogs').Email
| where subject == "jasade" | sort by event_time asc
```

4. KQL is mostly case-sensitive
5. No quotes around field names

### Comparison operators

* `==` equals to

* `!=` not equal to

```
Table
| where FIrstName != "peter" //all people not named peter are returned
```

* \=\~ not case sensitive

```kql
Table
| where FIrstName =~ "peter" //all uppercase, lowercase, combined is returned
```

### Query order

How you filter your data matters!

If you filter first for the random 10 rows with 'take 10' and after that you search for all the users named 'peter' you wont get the same result as if you first searched for the name peter and than took random 10 rows.


# contains | has | startswith | endswith

### contains

contains command is case-insensitive, its similar to the '==' sign but the difference is that the '==' sign expect exact mathces while contains returns parts as well.

#### example

```kql
cluster('help').database('SecurityLogs').InboundBrowsing
| where user_agent contains 'firefox'
```

this query will return rows with the example below:

'firefox'

'abcfirefox'

'firefox/1'

'abcfirefox/1'

while == would return only fields with exact match.

***

### has

has command is also case-insensitive, it is similar to contains, but does not return delimeters like contains does.

Delimeter examples: / . \[ { ( , < space

Strings in KQL are tokenized, meaning if you use fire,fox this is read by kql as

```kql
fire
fox
```

so == would not work here if we dont enter the exact string.

#### example

```kql
cluster('help').database('SecurityLogs').InboundBrowsing
| where user_agent has 'firefox'
```

this query will return rows with the example below:

'firefox' :white\_check\_mark:

'abcfirefox' :x:

'firefox/1' :white\_check\_mark:

'abcfirefox/1' :x:

Why has does not return abcfirefox/1 but return firefox/1?

beacuse kql reads the words like this because of the delimeters:

```kql
// abcfirefox/1 is read:
abcfirefox
1

//firefox/1 is read:
firefox
1
```

So has will return the rows that contain firefox/1 but not abcfirefox/1.

***

### startswith & endswith

this commands are case-insensitive (not case-sensitive) and are the same thing as if you use asteriks (\*) in your searches.

#### example

```kql
cluster('help').database('SecurityLogs').InboundBrowsing
| where user_agent startswith 'fire'
```

this will return all the rows that have the user\_agent field string starting whit "fire"

```kql
cluster('help').database('SecurityLogs').InboundBrowsing
| where user_agent endswith 'fox'
```

this will return all the rows that have the user\_agent field string ending whit "fox"

***

### negatives

all of the comands above can be used with the ! symbol to search for queries that DO NOT contain what we search for.

***

### case-sensitive

To make the contains and has commands case sensitive just add '\_cs' to the commands syntax.

This method is faster since it uses less resources.

```kql
cluster('help').database('SecurityLogs').InboundBrowsing
| where user_agent has_cs 'Firefox'

cluster('help').database('SecurityLogs').InboundBrowsing
| where user_agent contains_cs 'Firefox'
```

***

### practice

Lets write a query that will return all the websites that use https from the table InboundBrowsing from the 'url' field.

It does not make sense to use == here since the url field never contains only http.

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2Fl8aRNHtaavBP3XkHTc5r%2Fimage.png?alt=media&amp;token=f4cd2d92-e5c2-4a5a-8549-fe08315cabfa" alt=""><figcaption></figcaption></figure>

It also makes no sense in using contains since it includes everything after http, this it will return all the https websites as well.

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FxeSGiLRkM9rK8XDy4Msb%2Fimage.png?alt=media&amp;token=523f06e7-63ac-4833-90b0-7b84420d4c2a" alt=""><figcaption></figcaption></figure>

\
That's why we will use has command, since it searches for the exact string we enter no matter if there are other strings, and it wont return fields containing https.

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FIQ5lNrv7vfEwSxLMAYKp%2Fimage.png?alt=media&amp;token=60a3a43d-38c3-4e7f-b3c1-a1a112c3820d" alt=""><figcaption></figcaption></figure>

***

#### do it yourself

from the SecurityLogs database, from the InboundBrowsing table, find all the iphone users.


# distinct | count | sort | order

### sort by

sort command returns our query in order based on the field of interest that we specify.\
We can specify if we want and asc or desc order.

The order is defined by the type of value contained in the field, but if there are numbers and letter if we sort in ascending order we will get results starting from '0' and going to letter 'z'

FunFact: capital letters are odered before small letters in ascending order.

***

### order by

This is the same as sort by just different syntax for people comming from SQL.

***

### distinct

Helps us find unique values in any field.

```
cluster('help').database('SecurityLogs').ProcessEvents
| where parent_process_name == 'excel.exe'
| distinct parent_process_name
```

result:

```
CMD.exe
cmd.exe
sc.exe
explorer.exe
conhost.exe
```

***

### count

Returns the number of rows as a result.

```
cluster('help').database('SecurityLogs').ProcessEvents
| where parent_process_name == 'excel.exe'
| distinct parent_process_name
| count
```

result:

```
5
```

***

### Homework

from the help cluster, the SecurityLog database, Employees table, sort the table by role name, from A-Z


# project | project-reorder | renaming fields

### project

The project command shows us just the fields we selected. Because sometimes whole tables can be overwhelming and we maybe need just a few fields from there.

```
VMComputer
| where OperatingSystemFamily == "Windows"
| project HostName, OperatingSystemFamily, Cpus
```

***

### project-reorder

This command is kinda a spin-off of the project command, it reorders the fields that we specify at the beginning of the table, but does not remove the other fields.

```
VMComputer
| where OperatingSystemFamily == "Windows"
| project-reorder HostName, OperatingSystemFamily, Cpus
```

As a result the HostName, OperatingSystemFamily, Cpus fields would be at the beginnig and than the rest of the fields from the table.

***

### renaming fields

Renaming the fields is easy with the project command.

Its just like specifying a variable.

Write the name you want before the field name and connect them with = sign.

```
VMComputer
| where OperatingSystemFamily == "Windows"
| project Host=HostName, OS=OperatingSystemFamily, Cpus
```

As a result, the HostName and OperatingSystemFamily fields would be renamed.


# and | or | limit | top

### and

and is a boolean or logical operator.

instead of using a command 2 times, you can use `and` to simplify the query.

```kql
VMConnection
| where ProcessName =="python3"
| where SourceIp == "127.0.0.1"
```

:x:

```kql
VMConnection
| where ProcessName =="python3"
    and SourceIp == "127.0.0.1"
```

:white\_check\_mark:

***

### or

or is also a boolean or logical operator.

It is used when we need at least one condition correct.

```kql
VMConnection
| where RemoteLatitude >= 60 or ResponseTimeMax > 1000
```

***

### and or combination

We can use the operators in combination with each other using parenthasis to define the query nice.

```kql
WindowsFirewall
| where (DestinationPort == '80' and Protocol == "TCP") or DestinationIP startswith "20"
| project DestinationPort, Protocol, DestinationIP
```

Here we search for destination port 80 and protocol tcp rows to be returned, or rows where destination ip starts with '20'.

Any of the two conditions meet is returned.

***

### limit

As we have the sort by command and the order by command do the same thing,\
so do take and limit do the same thing.

limit command does the same thing as take, it takes the defined number and returnes random rows.

```kql
VMConnections
| take 10
| limit 10
// both do the same thing.
```

***

### top

while take gives random results.\
top gives a set number or records based on how the dataset is ordered.

```
SigninLogs
| top 10 by TimeGenerated desc
```

```
VMConnection
| where * has '389'
| top 10 by TimeGenerated desc
```


# Working with time in KQL

You want to define the time at the beginning at the query since it will drasticaly cut off a lot of logs.

It is used with the `where` command and the `TimeGenerated` field and a time command (ago, between, now\...)

### ago

if used with > the ago will return logs NEWER than time defined.

if used with < the ago will return logs OLDER than time defined.

#### syntax

```
where TimeGenerated [operator] ago([number][d=days, m=minutes, s=seconds])
```

Example:

```
FileCreationEvents
| where TimeGenerated > ago(1d)
```

result: empty

example:

```
FileCreationEvents
| where TimeGenerated < ago(1d)
```

result:

|                            |              |               |
| -------------------------- | ------------ | ------------- |
| 2022-01-03 20:08:12.451382 | B5HS-LAPTOP  | 15.jpg        |
| 2022-01-03 20:09:25.180969 | AXFE-DESKTOP | resources.pri |
| etc                        | etc          | etc           |

***

### between

the kql accept a few options to define the date time.

#### syntax:

```
where TimeGenerated [operator] between (datetime(date) .. datetime(date))
```

#### Example

```
SignInLOgs
| where TimeGenerated between (datetime(2025-7-5T02:00:00) .. datetime(2025-7-6T15:00:00))
```

You can define only date no time

```
SignInLOgs
| where TimeGenerated between (datetime(2025-7-5) .. datetime(2025-7-6))
```

***

### now

now function means... now like... current time.

#### Syntax

```
where TimeGenerated between (datetime() .. now())
```

#### Example

```
SignInLOgs
| where TimeGenerated between (datetime(2025-7-5) .. now())
```

```
SignInLOgs
| where TimeGenerated between (datetime(2025-7-5) .. now(-4))
```


# search | extend | getschema

### search

the search command searches the whole table, not specific fields.

It can also search whole databases.

It takes a lot of resources. Thats why search is best used with a specific timeframe defined using\
`| where TimeGenerated ...`

#### syntax&#x20;

```
search "String_of_interes"
```

### examples

```
search "Google"
```

#### search in specific table

```
VMConnections
| search "Google"
```

The query above is the same as using has

```
VMConnections
| where * has "Google"
```

#### search in a specific table and field

```
VMConnections
| search Website: "Google"
```

```
VMConnections
| search Website: "Google" or IP: "192.168.15.*"
```

#### other example

```
VMConnections
| search "*Google"
```

```
VMConnections
| search "Google*"
```

```
VMConnections
| search "*Google*"
```

#### search for word and display all table names where its found

<pre><code>search "Google"
<strong>| distinct $table    //shows unique tables where google is found
</strong></code></pre>

#### search for word in specific tables

```
search in (table1, table2) "Google"
```

***

### extend

extend command is used to create a new field that does not exist.\
We learned before how to rename a field, this includes the smilar process.

In the example below we see fields "Quantity" and "QuantityUnit"

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FQFSuNCG1k7fU6PQpPdUV%2Fimage.png?alt=media&amp;token=567e78ec-6db6-4c5a-81de-f322c0d726b3" alt=""><figcaption></figcaption></figure>

Lets create a ne field called "GB", where we will use the Quantity field and divide it with 1000, and put the new values in our new field GB.

```
Usage
| extend GB=Quantity/1000
```

***

### getschema

getschema command is used to get the datatypes from the fields, and more info about a specific table in general.

Its good for troubleshooting.

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FTPqfsyQibOg72hYp5nsE%2Fimage.png?alt=media&amp;token=f67c2afd-12f3-4f4b-8958-16985f84aba3" alt=""><figcaption></figcaption></figure>


# Data Types

#### getschema

You can use this commmand piped at the end of any table to see the table schema.

```kql
VMComputer
| getschema
```

#### List of KQL datatypes

* Bool
* Datetime
* Dynamec
* GUID
* Int
* Long
* Real
* String
* Timespan
* Decimal

***

#### Bool

Field that has either Yes No or null value.

#### Datetime

Represents an instance of time. It represents data + time but can display only date or only time as well. UTC is default timezone.

#### Decimal

128bit lenght decimal number.

Slower procesing time for this datatype than regular number.

#### Dynamic

dynamic in KQL is a flexible data type that can store **JSON-like data** instead of a single value.

```kql
let x = dynamic({
    "Name": "Mladen",
    "Age": 25,
    "Skills": ["KQL", "Sentinel"]
});
```

You can than access the values liek this:

```
x.Name
x.Skills[0]
```

Dynamic datatype is heavy, and does not work with some operators.

#### GUID

Not common, global unique identifier.

Ussualy a unique string datatype.

#### Int

Integeer

32bits and represent a whole number. No decimals

#### Long

64bits in size. not used that much only in special situation.

#### Real

64bits in size, but allow for a decimal point and more ised than a decimal type.

#### String

Mostu used datatype. Sequence of unicode chars.

Is btw brackets. Can contain kletters, numbers and symbols

Special chars ( / )

if you want to notate someone, you can use a slash before the quotes so that the quotes print as well.

```kql
print("John said /'KQL is cool/'!")
```

#### Timespan

Messures the lenght of time btw two intervals.

Can be messured in days, hours, muinutes, second, miliseconds...

Example:

```
SigninLogs
| project TimeGenerated, CreatedDateTime
| extend Difference = TimeGenerated - CreatedDateTime
| getschema
```

We can see that the difference column got a "timespan" datatype.

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FeeAdOI8dJWHh7o0KB1ka%2Fimage.png?alt=media&amp;token=7c8e837e-7369-49ad-9342-9aecdf2824c5" alt=""><figcaption></figcaption></figure>

***

### Null

Sometimes a field is blank, if its a string datatype, than its just empty, if it anything else its 'Null'

```
SiginLogs
| where TimeGenerated ≥ ago(3d)
| where isnull(MfaDetail)
| project-reorder Timegenerated, MfaDetails
```

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FuNEJPB55Q3VjvU1ZIYhC%2Fimage.png?alt=media&amp;token=0594b80f-f0ee-4e18-9f8d-f7129e333ba8" alt=""><figcaption></figcaption></figure>

```
SigninLogs
| where TimeGenerated >= ago(3d)
| extend IsEmpty = isempty(ResultDescription)
| project TimeGenerated, IsEmpty, ResultDescription
| take 100
```

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2Fs1OMuzoYXUoJdJ4vZiG0%2Fimage.png?alt=media&amp;token=ed68ebcd-c6cf-4092-b782-f314439b0399" alt=""><figcaption></figcaption></figure>

***

### Casting

A term used when changing a datatype from one to another

Below we have 2 integers, we will chnage them to string datatypes.

```
VMComputer
| project Field1=Cpus, Field2=CpuSpeed
| extend AdditionOffFields1and2 = Field1 + Field2

```

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FS03Lqwiz4QtWr1VpDaeW%2Fimage.png?alt=media&amp;token=d316d1ec-cb60-455a-8bfe-87c3b882d07b" alt=""><figcaption></figcaption></figure>

```
VMComputer
| project tostring (Field1=Cpus), (Field2=CpuSpeed)
| extend AdditionOffFields1and2 = Field1 + Field2
```

Since we changed datatypes now we can not perform math operations on the strings.

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FTsGvDUVEBhfH1rUKgwCi%2Fimage.png?alt=media&amp;token=470d33f4-6023-4c62-a400-8a4a223153ef" alt=""><figcaption></figcaption></figure>


# summarize | count() | min | max | make\_set

### Summarize

It takes a bunch of rows and **collapses them** into a summary, using aggregation functions (like `count()`, `sum()`, `avg()`, `max()`, etc.).

**Basic syntax:**

```
Table
| summarize <aggregation> by <grouping column(s)>

```

***

#### summarize by count()

summarize by count() prints all the UNIQUE values in the specified column just like `distinct` command does, BUT in addition to that it also hows how many times the unique value was mentined in the table.

```kql
DeviceEvents
| project DeviceName, ActionType
| summarize count() by DeviceName
```

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2Fyw5X8LdiFcvexgRpopuF%2Fimage.png?alt=media&amp;token=228b2b7e-ee72-4dd5-9212-02fbc983cad6" alt=""><figcaption></figcaption></figure>

***

### make\_set

It collects **all the distinct values** of a column into a single **array** (a list), per group. Duplicates are removed automatically (that's the "set" part — like a math set, unique values only).

To best understand this here is a practical example.

We have a **NetworkLogs** table

| country | domain      |
| ------- | ----------- |
| US      | example.com |
| US      | example.com |
| US      | test.com    |
| DE      | foo.net     |
| DE      | foo.net     |
| DE      | example.com |
| BG      | example.com |

When we use only summarize count() by country we can see all the distinct rows of the country column and now many times each value is repeated.

```
NetworkLogs
| summarize count() by country
```

| country | count\_ |
| ------- | ------- |
| US      | 3       |
| DE      | 3       |
| BG      | 1       |

Now if we add the `make_set` function to the `count()` function we will get the values that are either unique or repeated with the distinct countries.

```
NetworkLogs
| summarize count(), make_set(domain) by country
```

| country | count\_ | set\_domain                  |
| ------- | ------- | ---------------------------- |
| US      | 3       | \["example.com", "test.com"] |
| DE      | 3       | \["foo.net", "example.com"]  |
| BG      | 1       | \["example.com"]             |

***

### min() & max()

* **`min(col)`** → returns the **smallest** value in each group
* **`max(col)`** → returns the **largest** value in each group

They work on **numbers, dates/times, and even text** (for text, they are put in an alphabetical order A->Z and lenght does not matter here).

Example:

Lets use the `SigninLogs` table.

| user  | TimeGenerated    | BytesSent |
| ----- | ---------------- | --------- |
| alice | 2026-07-23 08:00 | 500       |
| alice | 2026-07-23 09:30 | 1200      |
| alice | 2026-07-23 11:00 | 300       |
| bob   | 2026-07-23 07:15 | 800       |
| bob   | 2026-07-23 10:45 | 2000      |

Lets see the min and max bytes sent by each user:

```
SigninLogs
| summarize min(BytesSent), max(BytesSent) by user
```

| user  | min\_BytesSent | max\_BytesSent |
| ----- | -------------- | -------------- |
| alice | 300            | 1200           |
| bob   | 800            | 2000           |

We can use min and max for time values as well.

```
SigninLogs
| summarize FirstSeen = min(TimeGenerated), LastSeen = max(TimeGenerated) by user
```

| user  | FirstSeen        | LastSeen         |
| ----- | ---------------- | ---------------- |
| alice | 2026-07-23 08:00 | 2026-07-23 11:00 |
| bob   | 2026-07-23 07:15 | 2026-07-23 10:45 |


# summarize | bin |dcount |avg | countif

### bin

**`bin()`** groups values into buckets (bins) of a specified size.

When using bin we should specify 2 params, the column that we want to make buckets of and the timeframe.

```
DeviceEvents
| summarize count() by bin(Timestamp,1h)
```

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2Fuv6ti9K2nUjcreU8EKAh%2Fimage.png?alt=media&amp;token=d5995fb6-70da-4983-90fe-fea0b904a782" alt=""><figcaption></figcaption></figure>

another example:

Guest sign-ins in the past month separated by day

```
SigninLogs
| where Timestamp >= ago(30d)
| where UserType == 'Guest'
| summarize count() by bin(TimeGenerated, 1h)
| sort by TimeGenerated asc
```

***

### avg()

**`avg()`** = calculates the **average (mean)** value of a column.

| Response Time |
| ------------- |
| 100           |
| 200           |
| 300           |

```
| summarize avg(ResponseTime)
```

Result: 200

Example:

```kql
VMConnection
| project TimeGenerated, BytesSent
| summarize count(), min(BytesSent), max(BytesSent) by bin(TimeGenerated, 1h)
| sort by TimeGenerated asc
```

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2F9mZhIxLQFa3WSc9dLGet%2Fimage.png?alt=media&amp;token=7a89f571-1254-4b13-9a41-266417f80aa6" alt=""><figcaption></figcaption></figure>

if we now add the avg, it will add another field that will display the average maxbytes sent per count.

```
VMConnection
| project TimeGenerated, BytesSent
| summarize count(), min(BytesSent), max(BytesSent), avg(BytesSent) by bin(TimeGenerated, 1h)
| sort by TimeGenerated asc
```

***

### countif

**`countif()`** = counts only the rows where a condition is true.

| User    | Result  |
| ------- | ------- |
| Alice   | Failed  |
| Bob     | Failed  |
| Charles | Success |
| David   | Success |

```
| summarize countif(Result == "Failed")
```

Returns: `2`

Example:

Find the total number of bytes in each hourly bucket, also count records that have value more than 0.

```
VMConnection
| project TimeGenerated, BytesSent
| summarize RecordsPerHour=count(), RecordsGreatherThanZero=countif(BytesSent > 0), min(BytesSent), max(BytesSent), TotalBytesSent=sum(BytesSent), avg(BytesSent) by bin(TimeGenerated, 1h)
| sort by TimeGenerated asc
```

<figure><img src="https://2490252025-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUwIKQPujWqWSVFxQaX98%2Fuploads%2FwGMA9XHj5dM6TCV8LF6H%2Fimage.png?alt=media&amp;token=a1b2f1bc-37cc-480e-94e5-a89df39b3a2b" alt=""><figcaption></figcaption></figure>


# Cryptography Intro

## **History**

Since the time that people overcame literacy, they needed protection for the information they were writing and sending. It was necesery that only the sender and receiver knew how to understand the written information, and with that, a lot of people started to show interest in hiding written information, and the result was…a lot of great crypting methods. For that time.

Cryptography is about as old as the ancient pyramids.

## **Cryptography in Antiquity**

The ancient Egyptians used a symbolic language. In 1998, a text written on stone slabs was deciphered. This text is over 6000 years old and is called the "Great Arcanum of Tarot." In it, the principles of the Universe are interpreted in a symbolic form, speaking of absolute and relative truth.

In ancient China, complex physical methods were invented to protect messages. Messages were hidden in secret compartments of the body.

European cryptography emerged in Greece. A significant impetus for its development was the fact that in Greece, for the first time, the European alphabet was finally formed (8th century BC). Until that moment, scripts that were poorly suited for cryptography had been widely used.

Two types of ciphers were used in ancient cryptography: substitution and transposition. A historical example of a substitution cipher is the Caesar cipher.

### **Cesar chiper**

The letters were moved 3 letters in right for decryption. For encryption, move them to the left an you would get the full understandable message.

### **Scital**

This was a method of sending hidden messages only if the reciever knew the exact R of the diametar needed. So when the script was rolled up on the cilindar a message could be seen.

### **Disk of Eney**

It was a plate with letter writen all over the edges of it, and a hole above every letter. A knit would be put through the hole of the letters, and when pulled, following the knit would show the letters in order.

### **Polybius square**

Polybius square is a simple method and it has only 25 spaces because in that time ‘i’ and ;j; were the same letter. Here is an example:

HELLO = 2315313134

## **Cryptography in Middle age**

In the Middle Ages, cryptography persisted despite widespread illiteracy and the decline of scientific and artistic endeavors. Encryption methods included simple substitution ciphers, such as the Caesar cipher, and more complex systems using foreign alphabets. Notable figures in medieval cryptography include Saint Boniface, Roger Bacon, and Geoffrey Chaucer, who used encryption in their writings and diplomatic missions. Cryptographic practices were also observed in regions like Iraq, Tibet, Nigeria, and Thailand. Arab scholars made significant contributions to cryptography, developing methods for cryptanalysis and frequency analysis. Their works laid the foundation for modern cryptographic techniques. Encryption methods were closely guarded secrets, with cryptographers often facing destruction of their work to protect the secrecy of their ciphers.

## **Cryptography in Renesanse**

During the Renaissance, cryptography advanced significantly with the work of scholars like Leon Alberti, Johannes Trithemius, and Giovanni Battista Bellaso. Alberti introduced a cipher based on a disk, considered fit for kings. Trithemius, a German scholar, proposed the "Ave Maria" cipher and a periodic shifting key cipher. Bellaso, an Italian, published "The Cipher of Signor Bellaso" in 1553, introducing a method for multialphabetic encryption using a memorable key or password. Another significant figure, Giovanni de la Porta, contributed to cryptography by combining ideas from Alberti, Trithemius, and Bellaso to create a mixed alphabet square and a method for bigram substitution. These developments laid the foundation for modern cryptography, including the use of complex tables for encryption and the concept of multialphabetic substitution.

## **Cryptography in new and modern world**

During the Renaissance, cryptography was more of an art practiced by individuals, but its scientific foundations began to emerge with the development of serious methods for mathematical research. The six basic requirements for a cryptosystem were first outlined in the book "Military Cryptography" by Auguste Kerckhoffs (published in 1883). These requirements shaped the design of cryptographically secure systems:

1. **Security**: The system must be secure even if the attacker knows the system (except for the key).
2. **Inconvenience**: The compromise of the system should not inconvenience the correspondents.
3. **Key Management**: The key should be easily communicable and memorable without written notes, and correspondents should be able to change the key at will.
4. **Applicability**: The system should be applicable to telegraph communication.
5. **Portability**: The system should be portable, requiring only one person to operate it.
6. **Usability**: The system should be easy to use, without requiring a long list of rules or causing significant mental stress.

Dr. Auguste Kerckhoffs, a Dutch linguist and cryptographer, formulated these requirements. His work laid the foundation for modern cryptography by emphasizing the importance of key management, ease of use, and resilience against attacks.

Claude Shannon, an American mathematician and electronic engineer, made exceptional contributions to applying mathematical methods to cryptography. In 1944, Shannon completed the development of the theory of secret communications, and in 1945, he prepared the classified report "The Mathematical Theory of Cryptography," which was declassified and published in 1949. This report presented the theory of secret ciphers as mathematical models of ciphers.

Shannon's concepts of theoretical and practical secrecy allowed for the quantitative assessment of cryptographic qualities and the attempt to construct perfect or nearly perfect ciphers. His concept of redundancy in messages led to the idea that encryption should remove redundancy to make cryptanalysis more difficult.

Shannon also introduced the concept of the "operational characteristics" of a cipher, approaching a practical evaluation of its robustness. His work laid the foundation for modern cryptography, emphasizing the importance of strong keys, minimal redundancy in messages, and operational efficiency.

***

## **Basic cryptographic terms:**

* **Cryptographic resilience**: This concept characterizes the cipher itself, determining its resistance to decryption. It defines the duration required for decryption.
* **Cryptosystem**: A set of reversible transformations that convert plaintext into ciphertext and vice versa.
* **Encryption**: Some type of transformation that protects data from being revealed without the knowledge of a special key.
* **Key**: Specific information that encrypts data.
* **Cipher**: A set of reversible transformations that convert plaintext into ciphertext.
* **Decryption**: The process of converting ciphertext into plaintext with a known key and algorithm.
* **Imitation protection**: Protection against false data, adding an imitation-attachment to the encrypted data.




---

[Next Page](https://digitalgarden.batamladen.com/llms-full.txt/1)

