teleren/devto huggingface dataset:
How your program's functions are handled in memory ?
Tags: linux, c, x86, memory
Published: 2023-12-29 15:40:54

Because i always forget how the kernel is handling the program's functions in the call stack , i'll write about it so i come back after months or someone else will :) .

So hello , let's do it in C in a x86-64bits machine, why ? because it's my favorite language .

first , when you compile your C code ( gcc -c main main.c ), you get an object file main.o that will be linked later ( manually or dynamically ) with other already compiled standard code ( like your famous printf() ) , you get an executable file , ELF64 in my case.
okay , when you disassemble either with objdump or gdb , you can see the assembly code of your program :
gdb ./main
disassemble function

you'll find some sections like .text , .bss or .data , heap and the stack these are the sections of the virtual address space of your program .

what concern us is the .text section , it contains the code ( instructions to be executed [ for example int x = 3 will have the equivalent of movl  $0x3,-0x4(%rbp)]) 

okay , good , what concerns us is how the functions main() and function() are handled in the stack (the section where the functions resides) .

before , the CPU unit has some special registers called %rbp , %rsp ( the base pointer and the stack pointer ) to manipulate the scope of the functions.

%rbp : is used to access the memory words by adding values to it like the example we had : movl  $0x3,-0x4(%rbp)
%rsp : will always points to the top of the stack.

so the first thing we need to do is to push the value of the old %rbp ( because it's used by other functions to do the same thing , in this case the main() function which called the function() ) .

then , we push the return address to the stack so the main() function resumes it's execution where it stopped ( in this case it will return to line 13). , this information is retrieved from register r14 in ARM processors for example.

then we'll put the new value of the base pointer %rbp ( the one we said used for accessing memory words in the scope ) to the value of %rsp , so the top of the stack .

this process of handling the %rbp and %rsp is called function prologue and it's done in each function start ( as you see in the assembly code ) .

this is how it's done with the initialization of the function scope in multiple architectures and systems similarly.
 
now we'll use the function call stack by putting the local variables , the function parameters etc , these specific details follows calling conventions:
https://lnkd.in/eUNNAiXH

one of the conventions to follow in x64 architectures for example is SYSTEM V
the registers used for function parameters handling 
The first is placed in rdi, the second in rsi, the third in rdx, and then rcx, r8 and r9. Only the 7th argument and onwards are passed on the stack , the left most parameter is passed first on the stack , and then the old value of the base pointer , then it's followed by the local variables of the function.
Angular SSR Redirection issue
Published: 2023-12-29 15:38:51

Hi,

We have requirement of changing our domain and need to redirect all old application to new Urls. We are currently implemented Angular SSR and implemented the redirection (303) logic in Server.ts file. The redirection works fine. However , we have ended up with big issue that even after redirection, the application continue to run in locally and calls the APIs, including sessions in Angular Client side App.

I am new to Angular and wonder how can address this issue?

Please find the code snippet of the implementation. 

 

```
server.get('*', (req, res) => {
        const dateTime = new Date();
        const request = require('request');
        if (dateTime.getHours() === 3) {
            vanityUrlResponse = null;
        }
        if (!vanityUrlResponse) {
            // Need to make the URL generic
            request(vanityUrlService, function(error, response, body) {
                if (!error && response.statusCode == 200) {
                    vanityUrlResponse = JSON.parse(body);
                    redirectUrl(vanityUrlResponse, req, res);
                }
            });
        } else {
            redirectUrl(vanityUrlResponse, req, res);
        }
        if (req.path == '/sitemap') {
            //refresh sitemap on nav
            fetchSiteMap(siteMapConfig);
        }
        if (req.path.includes('.')) {
            res.send(200);
        } else {
            res.render(indexHtml, {
                req,
                providers: [
                    { provide: APP_BASE_HREF, useValue: req.baseUrl },
                    { provide: REQUEST, useValue: req },
                    { provide: RESPONSE, useValue: res },
                ],
            });
        }
    });

    return server;
}

function redirectUrl(vanityUrlResponse, req, res) {
    const redirectRule = vanityUrlResponse.find(obj => obj.sourceUri == req.path);
    if (redirectRule != null) {
        res.redirect(301, redirectRule.desination);
    }
}
```
 

I will definitely appreciate your help on this regard.

Regards,
Faisal
Quarkus. Quando optar pelo Nativo ou JVM?
Tags: java, quarkus, jvm, nativeimage
Published: 2023-12-29 15:33:50

Pra iniciar esta conversa, penso que essa decisão é bem necessária quando se fala em perfomance e entrega de produtos escaláveis e flexiveis. Principalmente quando estamos falando sobre o quanto de recurso lógico (memória, processamento) será consumido _versus _ quanto de recurso financeiro seu bolso está disposto a manter. 
Sabemos que os principais serviços em cloud, podem gerar uma bola de neve quando não configurados da forma correta. Mas por uma visão otimista, que tal tentar evitar o problema na concepção do projeto? 

O que podemos entender à respeito de uma maneira prática:

**Quarkus Nativo:**

**Compilação Nativa:** O Quarkus nativo permite a compilação do código fonte para um executável nativo, o que melhora significativamente o tempo de inicialização e o consumo de recursos. Isso é especialmente crucial em ambientes de contêineres e serverless.
**Menor Footprint:**Projetos Quarkus nativos têm um footprint menor, resultando em tamanhos de imagem de contêiner mais compactos. Isso é vantajoso em ambientes em nuvem, onde a eficiência no uso de recursos é fundamental.
Tempo de Inicialização Rápido:A compilação nativa contribui para tempos de inicialização extremamente rápidos, o que é crucial em cenários de microservices onde a elasticidade e a rápida resposta são essenciais.
**GraalVM:** O Quarkus nativo geralmente utiliza a GraalVM para compilação nativa, proporcionando otimizações significativas.

**Quarkus modo JVM:**

**Flexibilidade do Código Fonte:** Projetos executados na JVM oferecem uma gama mais ampla de opções de frameworks e bibliotecas, devido à vasta adoção da JVM. Isso permite uma maior flexibilidade na escolha de tecnologias.

**JIT Compilation:** Ao contrário da compilação nativa, a JVM usa a compilação Just-In-Time (JIT), o que pode resultar em um tempo de inicialização ligeiramente mais longo, mas oferece otimizações dinâmicas durante a execução.

**Ecossistema Java Padrão:** Projetos JVM se beneficiam do vasto ecossistema Java, incluindo uma ampla variedade de bibliotecas e ferramentas estabelecidas.

**Facilidade de Desenvolvimento:** O desenvolvimento em projetos JVM pode ser mais simples, pois há uma grande quantidade de ferramentas e recursos disponíveis para facilitar o processo de desenvolvimento.

Em resumo, a escolha entre Quarkus nativo e uma API na JVM depende dos requisitos específicos do projeto. Projetos que demandam alta eficiência em termos de recursos e tempo de inicialização podem se beneficiar do Quarkus nativo, enquanto projetos que valorizam a flexibilidade e o ecossistema Java podem optar por APIs na JVM.
Até a próxima.
Workhy
Published: 2023-12-29 15:31:46

We define Workhy in three words, Convenient, Safe, and Affordable We understand your needs and start working towards making your dreams come true. We are at your service to offer convenience while establishing your company, managing your financial processes, and growing your business.


[USA company registration](https://workhy.com/)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1ko6u1i53z1n0trrxk42.jpg)
How to install Flutter on a MacBook
Tags: flutter, tutorial, beginners
Published: 2023-12-29 15:13:00

I'm going to use Flutter for the first time and dive into the world of mobile development 📱.

(As usual) I had some issues installing Flutter on my MacBook 🙄. So I reset my MacBook, which was long overdue, and set up the technical environment from scratch, using the package manager from the beginning.

And I'm glad I did. Finally the installations are running smooth as butter 🧈.

## Environment

Device | Chip | Operation System | CommandLine Tool
--- | --- | --- | ---
MacBook Air | Apple M1 | macOS Sonoma 14.1.2 | HomeBrew

## Installation process

After installing Flutter, by running the command 

`brew install --cask flutter`,

everything worked smoothly. I then run

`flutter doctor`,

which provided instruction on how to move further.

![Console output showing instructions on how to install flutter](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zw67058m4y7wg3e10esk.png)

Here are the commands I ran:

- `sudo softwareupdate --install-rosetta --agree-to-license`

- `brew install --cask android-studio`

- `sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer`

- `sudo xcodebuild -runFirstLaunch`

- `brew install cocoapods`

- `xcodebuild -downloadPlatform iOS`

- `path/to/sdkmanager --install "cmdline-tools;latest"`

- `flutter doctor --android-licenses`

- `flutter config --android-sdk`

Now, when running `flutter doctor` again, everything is setup.

![Successful installation of Flutter.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/00rmvae8jtgqrysjqx1f.png)

**Tip 💡:** In case you have problems with `Android toolchain - develop for Android devices` and the error `cmdline-tools component is missing`, check out my article about [Android cmdline tools component is missing - Flutter Installation](https://dev.to/yuridevat/android-cmdline-tools-component-is-missing-flutter-installation-issue-30e3)

---

_Thanks for your reading and time. I really appreciate it._
TLE Tales: When Unordered_map Bites You
Tags: programming, competativeprogramming, datastructures, learning
Published: 2023-12-29 14:58:05

Hey, fellow devs👋!

I just tackled a [problem](https://codeforces.com/contest/1915/problem/E) that taught me a valuable lesson about time complexity: always consider the worst-case scenario, even when average-case performance seems good ⚠️.

**_Here's the gist:_**

- Problem: Find a subarray with a sum of zero.
- Constraints
  - Array size: 1 to 2*10^5
  - Element range: 1 to 10^9
  - Total sum of elements: ≤ 2*10^5

**_My initial approach:_**

- Used unordered_map to store sums for efficient lookup.
- Average-case time complexity: O(1) ✨
- Worst-case time complexity of entire code: O(n) (this led to the TLE)

**_The TLE surprise:_**

- Got a Time Limit Exceeded (TLE) verdict, specifically during lookup operations in the unordered_map.
- Why? The worst-case lookup time in unordered_map can be linear O(n), so with the given constraint worst-case complexity of the program becomes O(n^2).

**_The solution:_**

- Switched to map (ordered_map with worst-case complexity O(log n)):
  - Now Worst-case time complexity of my code become: O(nlogn), O(n) to traverse the array and O(long) for lookup.
  - Accepted solution!

**_Key takeaways:_**

just look at the complexity of ordered and unordered_map 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xlrswj4j1wrpvhz6axdy.png)

This complexity tells you a lot about when to use which data structure, map stores the data in a sorted manner while unordered will not, here we do not need sorted data which's why in the first attempt I went with unordered_map but later I realized my mistake and correct it.

instead of 10^5 if the number of elements is 10^9 then our ordered_map will not work so, 

- Always analyze worst-case time complexity, especially when dealing with large inputs.
- Don't rely solely on average-case performance.
- Choose data structures wisely based on problem constraints and potential worst-case scenarios.


Happy coding!!
How to Fix Cloud Run Jobs Logging
Tags: googlecloud, serverless, programming, logging
Published: 2023-12-29 14:49:21

Google Cloud Run is a great product and became even better after allowing you to use it to run background Jobs:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mzk8kyx0nzx2jdp3o8h8.png)

Recently it became even more flexible allowing users to override a bunch execution args:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/750z1ckxoo4kqrbybz4m.png)

But at the time this blog post was written, it lacks a bit on some developer tooling, for instance automatically showing logs in [Google Cloud Logging](https://cloud.google.com/logging?hl=en).

If you set up your application and instrument it to run in Google Cloud Run, the logs are automatically set as a `gce_instance` resource type. Then if you go in Google Cloud Console, and jump into the Logs of a Cloud Run Job, you see nothing... because it expects it to live under a `cloud_run_job` resource type.

This most likely happens since this feature is kinda new, so I'd imagine this will be fixed, but in meanwhile, here's some Python sample code that fixes this behavior:

```
import google.cloud.logging
from google.cloud.logging.handlers import CloudLoggingHandler
from google.cloud.logging_v2.handlers import setup_logging
from google.cloud.logging_v2.resource import Resource
from google.cloud.logging_v2.handlers._monitored_resources import retrieve_metadata_server, _REGION_ID, _PROJECT_NAME

client = google.cloud.logging.Client()

cloud_run_job = os.environ.get("CLOUD_RUN_JOB")
if cloud_run_job:
    region = retrieve_metadata_server(_REGION_ID)
    project = retrieve_metadata_server(_PROJECT_NAME)

    # build a manual resource object
    cr_job_resource = Resource(
        type="cloud_run_job",
        labels={
            "job_name": cloud_run_job,
            "location": region.split("/")[-1] if region else "",
            "project_id": project,
        },
    )
    labels = {"run.googleapis.com/execution_name": os.environ.get("CLOUD_RUN_EXECUTION")}
    handler = CloudLoggingHandler(client, resource=cr_job_resource, labels=labels)
    setup_logging(handler)
```

Hope it helps!
I LOST MY CRYPTO, HOW DO I RECOVER IT? OMEGA CRYPTO RECOVERY SPECIALIST CAME THROUGH
Tags: reactnative, webdev
Published: 2023-12-29 14:38:12

Omega Crypto Recovery Specialist has a proven track record of successful crypto recovery. With over 22 years of experience in the industry, the company has helped numerous clients recover their lost or stolen crypto assets. The company's team of experts has a deep understanding of the complex workings of the blockchain and the various cryptocurrencies, allowing them to recover lost assets efficiently.

Fast Contact;
Webpage; omegarecoveryspecialist .c om
Mail; omegaCryptos@consultant .c o m

Whasapp; +1 (701, 660 (04 75
Arrow Function vs Normal Function in JS
Tags: javascript, beginners, webdev, learning
Published: 2023-12-29 14:37:22

In Javascript, event handlers take callback as second argument followed by event name as first argument. The callback function can be either a normal function or an arrow function. But they do not behave completely similar. Let's look at the differences and the possible pitfall in different usage.

## Normal Function

First let's look at an example with normal function as callback.


```html
<div id="someId" data-mycolor="red">
   Change my font color.
</div>
```

```js
function changeColor() {
  this.style.color = this.dataSet.mycolor;
}

const divElement = document.querySelector('#someId');
divElement.addEventListener('click', changeColor);
```

In the above piece of code, the color of the font inside the div element is changed successfully because the **_'this'_** keyword used inside a normal function declaration refers to the **receiver object** of the callback function. In this case, it refers to the divElement.

Now let's take a look at the example with arrow function as callback.

## Arrow Function

First let's look at an example with normal function as callback.


```html
<div id="someId" data-mycolor="red">
  Change my font color.
</div>
```

```js
const changeColor = () => {
  this.style.color = this.dataSet.mycolor;
}

const divElement = document.querySelector('#someId');
divElement.addEventListener('click', changeColor);
```

Here the color change is not done properly due to the fact that _**'this'**_ keyword inside an arrow function refers to current surrounding lexical scope which here in case refers to **window** object in browser. It does not have the property dataSet thus resulting in TypeError. The similar functionality can be achieved through event object passed to the callback.

## TakeAway:

**this** keyword in arrow function does not refer to the receiver object as in normal function definition instead refers to the current surrounding lexical scope. So use them with care.
Do you wish to Mater HTTPS??
Published: 2023-12-29 14:28:30

Are you a Software developer?
Have you wondered 
- how HTTPS works?
- How it aids with web security
- What the hell is SSL/TLS

We miss or ignore understanding the fascinating idea behind HTTPS; Its worth knowing. 

I have compiled - best easy to grasp videos on YT of prominent educators that one could finish over a hot cup of coffee; 

These are enough to feed the curiosity;

## What is HTTPS?

{% embed https://www.youtube.com/watch?v=clK8Wf4-F5k&list=PLQnljOFTspQW4yHuqp_Opv853-G_wAiH-&index=8 %}

## What are this digital signatures?

{% embed https://www.youtube.com/watch?v=s22eJ1eVLTU %}

## Know important stuffs about SSL/TLS & HTTPS

{% embed https://www.youtube.com/watch?v=0TLDTodL7Lc %}

{% embed https://www.youtube.com/watch?v=r1nJT63BFQ0 %}

{% embed https://www.youtube.com/watch?v=3coPpYJgFro %}

## The TLS handshake

{% embed https://www.youtube.com/watch?v=86cQJ0MMses %}

{% embed https://www.youtube.com/watch?v=64geP_LAZ5U %}

## What the hell is a Certificate Authority?

{% embed https://www.youtube.com/watch?v=x_I6Qc35PuQ %}


## The TLS & HTTPS option in IIS

{% embed https://www.youtube.com/watch?v=BFwTpQeblgs&list=PLQnljOFTspQW4yHuqp_Opv853-G_wAiH-&index=29 %}


## What is SHA?

{% embed https://www.youtube.com/watch?v=DMtFhACPnTY %}
How to use BigQuery Query Caching with Dynamic Wildcard Tables
Tags: bigdata, googlecloud, bigquery, python
Published: 2023-12-29 14:21:11

**The Problem: Caching does not work with wildcard tables**

From BigQuery [official docs](https://cloud.google.com/bigquery/docs/querying-wildcard-tables):

![Wildcard Limitation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yftawqstn59z5o16xllp.png)

Let's say you have some tables named `my_data_2023_*`, where the asterisk represents various months. You want to analyze data across all these tables. Since BigQuery doesn't know automatically when new tables were created, it will invalidate any available cache and run a fresh query, so cache won't be used.

> Just for reference, it's not a good practice to use date sharded tables:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rp6ubodygndz0ghvlf3h.png)
Recently I faced a scenario where tables where dynamically created based on a business domain field, the date example is only for illustration purposes, if you are using sharded tables, the better solution is to migrate it to BigQuery partitions instead.

**The Solution: Union THEM ALL!**

Enter the BigQuery Information Schema:

The BigQuery `INFORMATION_SCHEMA` views are read-only, system-defined views that provide metadata information about your BigQuery objects.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lgs7bbuuapa7ofyhuxgk.png)

We can use the `tables` view to dynamically generate a list of all tables matching our pattern (e.g., `my_data_2023_*`). Then, we leverage UNION to combine individual queries for each identified table.

Here's a sample using Python:
```
from google.cloud import bigquery

client = bigquery.Client()

# Specify the dataset and wildcard pattern
dataset_id = "your-project.your_dataset"
wildcard_pattern = "my_data_2023_"

# Query the INFORMATION_SCHEMA to get matching table names
query = f"""
    SELECT table_name
    FROM `{dataset_id}.INFORMATION_SCHEMA.TABLES`
    WHERE table_name LIKE '{wildcard_pattern}%'
"""

rows = list(client.query(f"SELECT table_name FROM `{dataset_id}.INFORMATION_SCHEMA.TABLES` "
                                f"where table_name like '{your_table_prefix_}%'"))

if not rows:
    return

view_query = __create_sql(dict(rows[0])["table_name"])
for row in table_names[1:]:
    view_query = f"""
    {view_query}
    UNION ALL
    {__create_sql(dict(row['table_name'])}
"""
```

I omitted the `__create_sql` function, which is just a logic that creates a complex SQL based on each table name, with the generated SQL then you can use it to create a BigQuery view:

```    
view = bigquery.Table(table_ref)
view.view_query = view_query
client.create_table(view, exists_ok=True)
```
Hope that helps, cheers!
Find ip address in Linux (video version)
Tags: linux, devops, tutorial
Published: 2023-12-29 14:16:42

Dear Guys,

Our YouTube channel is your ultimate resource for comprehensive tutorials, expert tips, and engaging content that simplifies the world of Linux.

[Subscribe to our youtube channel here](https://www.youtube.com/@davidcao483) and embark on an enriching Linux learning experience with us.

Thank you!

{% embed https://www.youtube.com/watch?v=3PF4bfnvmQE %}