teleren/devto huggingface dataset:
dynamic stack
Published: 2024-03-19 16:24:57

```
#ifndef stack_hpp
#define stack_hpp

#include <iostream>
#include <assert.h>


class stack {

  class node {

  int _data;
  node *_next;

  public:

    node(int);

  int data() const { return _data; } //cual es el dato
  node *next() const { return _next; } // cual es el siguiente apuntador
  void next(node *p) { _next = p; } // cambia el siguiente ap
  };

  int n; // Capacity of stack
  int s; // Size of stack

  node *init; // Inicio de nodo

public:

  stack(int);
  ~stack();

  void push(int);
  int pop(void);
  int top(void);

  int capacity() const { return n; }
  int size() const { return s; }
/*
  bool full() const {
    if (s==n) return true;
    else return false;
  }
*/
  bool full() const { return s==n; }
  bool empty() const { return s==0; }

  void print();
};

#endif /* stack_hpp */
```

```
#include "stack.hpp"

  stack::node::node(int x) {
    _data = x;
    _next = nullptr;
  }

  stack::stack(int m){

    n = m;
    s = 0;
    
    init = nullptr;
  }

  stack::~stack(){
    
    while(init != nullptr) {
      node *p = init;
      init = init->next();
      delete p;
    }
      
  }


  void stack::push(int x){

    assert(!full());

    node *p = new node(x);

    p -> next(init);
    init = p;

    s++;
  }

  int stack::pop(){
    
    assert(!empty());

    int x = init -> data();
    
    node *p = init;

    init = p -> next();//init = init -> next();
    
    delete p;

    s--;
    
    return x;
  }

  int stack::top(){
  assert(!empty());
    return init -> data();
  }

  void stack::print(){

    node *p = init;
  std::cout << "[";
    while(p != nullptr){
      std::cout << p -> data() << " ";
      p = p -> next();
    }
  std::cout << "]" << std::endl;
  }
```

```
#include <iostream>
#include "stack.hpp"
using namespace std;

int main() {

  srand((unsigned) time(nullptr));

  stack s(10);

  while (!s.full()){
    int x = rand() % 101;

    cout << x << ": ";

    s.push(x);
    s.print();
  }

  cout << "La pila está llena\n\n";

  while (!s.empty()) {

    int x = s.pop();

    cout<< x << ": ";
    s.print();
  }

  cout << "La pila está vacia\n\n";

  for (int i = 0; i < 100; i++){
     // inserción
    if (rand () % 2 == 1){

      if (s.full()) cout << "Pila llena\n";
      else {
      int x = rand() % 101;

      cout << "ins " << x << ": ";
      s.push(x);
      s.print();
      }
      //extraccion
    } else {
      if (s.empty()) cout << "Pila vacia\n";
      else {
      int x = s.pop();

      cout << "out " << x << ": ";
      s.print();
      }
    }
  }

  return 0;
}
```
Soul RESTful and realtime server for SQLite, now with Authentication!
Tags: node, sqlite, api, rest
Published: 2024-03-19 16:24:55

Hey everyone,
I'm excited to share an update about Soul, an open source project I created that acts as a RESTful and realtime server for SQLite databases.

Soul makes it incredibly simple to add a backend to any project - just give it a SQLite database file and it will instantly serve up CRUD endpoints without any additional configuration. When I first launched Soul a while back, its core functionality was just this.

A few months ago, one of Soul's long time contributors approached me about adding authentication and authorization capabilities. We worked together to design an ACL system, and they implemented it. I'm pleased to share that Soul now has robust user authentication and role-based access control built right in.

The authentication works by defining "roles" that map tables to permitted CRUD operations. These roles can then be assigned to users. This allows you to easily control which users have create, read, update or delete access to specific tables. It couldn't be much simpler to set up authorization for your SQLite APIs.

I'm grateful for the contributions that have helped Soul grow. Please check it out at https://github.com/thevahidal/soul to see these new features in action and get started with your own minimal backend. The project is actively developed and I welcome any feedback on how Soul can better serve developers. I hope Soul continues to lower the barriers to adding secure REST and realtime capabilities to projects.

Cheers, Al.
My Journey Building Vidya: From Idea to Open Source
Tags: flutter, opensource, android, programming
Published: 2024-03-19 15:57:07

Hey there, fellow devs and tech enthusiasts! Today, I want to take you on a wild ride through my journey of building Vidya, a simple yet powerful note-taking app that has been my sidekick through thick and thin.

## **Chapter 1: Inception - The Birth of an Idea**

It all started on a lazy Sunday afternoon, as I found myself drowning in a sea of sticky notes, scribbled reminders, and forgotten to-do lists. Frustrated with the chaos that was my note-taking system, I decided enough was enough. Thus, the idea for Vidya was born - a sleek, intuitive app to help me tame the note-taking beast once and for all.

## **Chapter 2: The Grind - Coding, Coffee, and Creative Chaos**

Armed with nothing but my trusty laptop and a bottomless supply of coffee, I dove headfirst into the world of app development. From designing the user interface to wrangling with code, every day brought a new challenge and a new opportunity to learn and grow. Sure, there were moments of frustration and self-doubt, but with determination as my compass, I pressed on.

## **Chapter 3: The Big Reveal - Sharing Vidya with the World**

After weeks of late nights and countless cups of coffee, the moment of truth finally arrived - Vidya was ready to make its debut on the digital stage. With trembling hands and a racing heart, I shared Vidya with the world on GitHub, inviting fellow developers and note-taking aficionados to join me on this journey of innovation and collaboration. You can check it out [here](https://github.com/MatinMollapur01/vidya).

## **Chapter 4: The Future - What Lies Ahead for Vidya**

As I sit here, reflecting on the journey that brought Vidya to life, I can't help but feel a surge of excitement for what the future holds. With plans to add new features, improve functionality, and expand to new platforms, the sky's the limit for this little app that could. So here's to the next chapter of the Vidya saga - may it be filled with even more coffee-fueled coding sessions, moments of triumph, and endless possibilities.

And there you have it, folks - the story of Vidya, from humble beginnings to digital darling. I hope you enjoyed this behind-the-scenes peek into the making of my favorite app, and who knows? Maybe one day you'll find yourself contributing to Vidya, helping to shape its future and make a difference in the world of note-taking.

Until next time, **happy coding**!
Help in building real-time music streaming and syncing feature
Tags: webdev, react, realtime, webrtc
Published: 2024-03-19 15:28:36

Hi, I am trying to create a simple functionality, where a user creates a room with a roomID and another user joins that room with the same roomID, then the room owner can play a song and the other user will be able to listen to that song as well in sync. I am trying to do this in React.js. Any idea how can I do this?
Expert Mobile App Developers in NY? TechnBrains!
Published: 2024-03-19 15:18:17

Are you in New York and searching for [app developers near me](https://www.technbrains.com/locations/mobile-app-development-new-york)? TechnBrains is here for you! Specializing in custom iOS and Android mobile application development, we ensure the best user experience. Contact us today to bring your app idea to life!
Search
Published: 2024-03-19 15:16:10


Here we have a code with differents way to search a data, with binary search, random search, sequential Search and random ordered search.

Data Structures

```
#include <iostream>

int *arreglo (int n){
  int *a = new int[n];
  for (int i=0; i<n; i++) a[i] = rand() % (n*2) + 1;
  return a;
}

void print(int *a, int n){
  for (int i=0; i<n; i++)
    std::cout << a[i] << " ";
  printf("\n");
}

void swap(int &a, int &b){
  int c = a;
  a = b;
  b = c;
}

void bsort (int *a, int n){
  for (int k = n - 1; k > 0; k--)
    for(int i = 0; i < k; i++)
      if (a[i] > a[i+1]) swap(a[i], a[i+1]);
}

void shuffle(int *a, int n){
  for (int k = n - 1; k > 0; k--)
    swap(a[rand() % (k + 1)], a[k]);  
}

int cont;
bool search(int x, int *a, int n){
  for (int i = 0; i < n; i++){
    cont++;
    if (a[i]==x) return true;
  
  }
  return false;
}

bool randomSearch(int x, int *a, int n){

  do{

    int i = rand() % n;

    cont++;

    if (a[i] == x) return true;
    
  } while(true);
  
  return false;
}

bool sequentialSearch(int x, int *a, int n){

  int i = 0;
  
  while (i < n && a[i] < x) {
    cont++;
    i++;
  }
  return i < n && a[i] == x;
}

bool randomorderedsearch(int x, int *a, int n){

  int l = 0;
  int r = n-1;

  while(l <= r){
  
    int i = rand() % (r-(l-1)) + l;

    cont++;
    
    if (a[i] == x) return true;

    if (x < a[i]) r = i-1;
    else if (x > a[i]) l = i+1;
  }

  return false;
}

bool bsearch(int x, int *a, int n){

  int l = 0;
  int r = n-1;

  while(l <= r){

    int i = (l + r) / 2;

    cont++;

    if (a[i] == x) return true;

    if (x < a[i]) r = i-1;
    else if (x > a[i]) l = i+1;
  }

  return false;
}

int main(){

srand((unsigned) time(nullptr));

int n = 100;
int acumulado = 0;
int positivos = 0;
int acumulado_neg = 0;
int negativos = 0;
  
  for (int k = 0; k < 100; k++){
int *a = arreglo(n);
   int x = rand() % (n*2)+1;
  //int x = a[rand() % n];
    bsort(a,n);

  printf("\n\n");
  print(a,n);
  printf("\nDato que vamos a buscar: %i\n", x);
  cont = 0;


  if (bsearch(x, a, n)) {
    
  printf("Si está: %i\n", cont);
  acumulado += cont;
  positivos++;
    
  } else printf("No está: %i\n", cont);
    acumulado_neg+= cont;
    negativos++;
  
delete [] a;
  }
  printf("Esfuerzo promedio utilizado cuando el dato sí está: %f\n", (float)acumulado/positivos);
  printf("Esfuerzo promedio utilizado cuando el dato no está: %f\n", (float)acumulado_neg/negativos);
return 0;
}
```
Top 5 AI Image Upscalers Of 2024
Tags: ai, aiimage, aigenerated
Published: 2024-03-19 15:11:52

In today's digital world, the quality of images is crucial, whether you're a professional capturing nature's beauty or someone preserving cherished family memories. With technology advancing, AI image upscaling has become essential for enhancing photos. These tools are in high demand, offering innovative solutions for improving visual content.

As we delve into 2024, [AI image upscalers](https://www.techdogs.com/td-articles/trending-stories/top-5-ai-image-upscalers-of-2024) reign supreme in the realm of image enhancement. They cater to both professionals and amateurs, revolutionizing how we enhance, upscale, and enlarge our photographs. These top 5 AI Image Upscalers redefine image editing, promising remarkable pixel expansion capabilities and transformative upscaling techniques. Get ready to explore the future of image enhancement with these cutting-edge solutions!



In this [article](https://www.techdogs.com/td-articles/trending-stories/top-5-ai-image-upscalers-of-2024), we'll take you on a tour of five exceptional AI Image Upscalers that are revolutionizing the game in 2024. Click [here ](https://www.techdogs.com/td-articles/trending-stories/top-5-ai-image-upscalers-of-2024)and let's dive in and explore the magic of AI-driven Image Upscalers, dissecting the features that position these five tools at the forefront of the pack this year.

Explore our vast collection of [tech articles](https://www.techdogs.com/resource/td-articles) including [introductory guides](https://www.techdogs.com/resource/td-articles/curtain-raisers), product reviews, [trends ](https://www.techdogs.com/resource/td-articles/techno-trends)and more, stay up to date with the latest news, relish thought-provoking interviews and the hottest AI blogs, and tickle your funny bone with hilarious [tech memes](https://www.techdogs.com/resource/td-articles/tech-memes)!

Plus, get access to branded insights from industry-leading global brands through informative white papers, engaging case studies, in-depth reports, enlightening videos and exciting events and webinars.

Dive into [TechDogs](https://www.techdogs.com/)' treasure trove today and Know Your World of technology like never before!
Managing Files From the Command Line
Tags: ramadhanbersamaredhat, redhat, linux
Published: 2024-03-19 15:03:13

## 
The File-system Hierarchy
All files on a Linux system are stored on file systems, which are organized into a single inverted tree of directories, known as a file-system hierarchy. This tree is inverted because the root of the tree is said to be at the top of the hierarchy, and the branches of directories and subdirectories stretch below the root.

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

The / directory is the root directory at the top of the file-system hierarchy. The / character is also used as a _directory _separator in file names. For example, if etc is a subdirectory of the / directory, you could refer to that directory as /etc. Likewise, if the /etc directory contained a file named issue, you could refer to that file as /etc/issue.

Subdirectories of / are used for standardized purposes to organize files by type and purpose. This makes it easier to find files. For example, in the root directory, the subdirectory /boot is used for storing files needed to boot the system.

## Note
The following terms help to describe file-system directory contents:

- 
_static_ content remains unchanged until explicitly edited or reconfigured.

- 
_dynamic_ or variable content may be modified or appended by active processes.

- 
_persistent_ content remains after a reboot, like configuration settings.

- 
_runtime_ content is process- or system-specific content that is deleted by a reboot.

The following table lists some of the most important directories on the system by name and purpose.


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

## Important
In Red Hat Enterprise Linux 7 and later, four older directories in / have identical contents to their counterparts located in /usr:

- /bin and /usr/bin
- /sbin and /usr/sbin
- /lib and /usr/lib
- /lib64 and /usr/lib64

In earlier versions of Red Hat Enterprise Linux, these were distinct directories containing different sets of files.

In Red Hat Enterprise Linux 7 and later, the directories in / are symbolic links to the matching directories in /usr.
How to Create Custom Middleware in Laravel 11
Tags: laravel, laravel11, middleware, php
Published: 2024-03-19 14:56:11

In this article, we'll explore the process of creating custom middleware in Laravel 11. 

Laravel 11 introduces significant changes to middleware handling. In previous versions, you could register middleware in the Kernel.php file. 

However, with Laravel 11, you must define middleware in the app.php file.

Middleware provides a convenient mechanism for inspecting and filtering HTTP requests entering your application.

So, let's see laravel 11 creates custom middleware, how to customize default middleware in Laravel 11, and middleware in laravel 11.

> Step 1: Install Laravel 11

First, we'll install laravel 11 using the following command.

```
composer create-project --prefer-dist laravel/laravel laravel-11-example
``` 

> Step 2: Create Middleware

Now, we'll create middleware using the following command.

```
php artisan make:middleware IsAdmin
```

app/Http/Middleware/IsAdmin.php

```
<?php
  
namespace App\Http\Middleware;
  
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
  
class IsAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if (\Auth::user()->role_id != 1) {
            return response()->json('Opps! You do not have permission to access.');
        }

        return $next($request);
    }
}
``` 

> Step 3: Register Middleware

In this step, we will register our custom middleware in the app.php file, as illustrated in the code snippet below:

bootstrap/app.php

```
<?php
   
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
   
return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->alias([
            'isAdmin' => \App\Http\Middleware\IsAdmin::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();
```
 
> Step 4: Apply Middleware

In this step, we'll create two routes and apply the "isAdmin" middleware. Let's proceed by updating the code accordingly.

routes/web.php

```
<?php
  
use Illuminate\Support\Facades\Route;
  
Route::middleware(['isAdmin'])->group(function () {
    Route::get('/dashboard', function () {
        return 'Dashboard';
    });
      
    Route::get('/users', function () {
        return 'Users';
    });
});
``` 

> Step 5: Run the Laravel 11 Application

Run the laravel 11 application using the following command.

```
php artisan serve
``` 

---

You might also like:

#### **[Read Also: How to Create Custom Class in Laravel 11](https://techsolutionstuff.com/post/how-to-create-custom-class-in-laravel-11)**
Writing Tests Efficiently Using RSpec in Ruby on Rails
Tags: ruby, rails, testing, beginners
Published: 2024-03-19 14:43:09

<p>
As stated in the previous article, writing efficient tests using it is essential to guarantee the quality and stability of your code. RSpec is a very popular testing tool in Ruby, known for its readability and expressiveness. Below I will show efficient ways to write tests using RSpec.
</p>

<h3>Testing Organization</h3>

<p>
Break your tests into logical contexts using "describe" and "context".
</p>
<p>
Group related tests together using "describe" to describe the behavior of a class or method.
</p>
<p>
Use "context" to specify different scenarios within the same context.
</p>

<p>For example:</p>

```ruby
describe MyClass do
  context "when initialized" do
    it "has default attributes" do
      # test implementation
    end
  end

  context "when performing some action" do
    it "does something under certain conditions" do
      # test implementation
    end

    it "handles edge cases" do
      # test implementation
    end
  end
end
```

<h3>Clear expectations</h3>

<p>
Use "it" to describe expected behaviors.
</p>
<p>
Use "expect" to state expectations for the behavior.
</p>

<p>For example:</p>

```ruby
it "returns the sum of two numbers" do
  result = add(2, 3)
  expect(result).to eq(5)
end
```

<h3>Setup and Cleaning</h3>

<p>
Use "before" to configure the initial state of objects before testing.
</p>
<p>
Use "after" to clean up resources or state after each test runs.
</p>

<p>For example:</p>

```ruby
describe MyClass do
  before do
    @my_object = MyClass.new
  end

  it "performs some action" do
    # test implementation
  end

  after do
    # clean up resources
  end
end
```

<h3>Matchers</h3>

<p>
RSpec provides a variety of matchers for expressively testing expectations.
Some examples include "eq", "be_truthy", "be_falsey", "be_nil", "include", among others.
</p>

<p>For example:</p>

```ruby
it "checks if a number is even" do
  number = 4
  expect(number).to be_even
end
```

<h3>Mocks and Stubs</h3>

<p>
Use mocks and stubs to isolate the code under test from external dependencies.
Avoid tests that rely on external resources such as databases or APIs.
</p>

<p>For example:</p>

```ruby
it "sends an email when a new user signs up" do
  user = build(:user) # Using FactoryBot
  mailer = double("UserMailer")
  allow(UserMailer).to receive(:welcome_email).and_return(mailer)
  expect(mailer).to receive(:deliver_now)
  user.save
end
```

<h3>Conclusion</h3>

<p>
The practice of writing efficient tests using RSpec in Ruby on Rails is crucial to quality software development. The article covered several techniques and best practices for creating robust and reliable tests, ensuring that the code is functional, scalable, and easy to maintain.
</p>
Escrevendo Testes de maneira eficiente usando RSpec em Ruby on Rails
Tags: ruby, rails, testing, beginners
Published: 2024-03-19 14:38:26

<p>
Como dito no artigo anterior, escrever testes eficientes utilizando é fundamental para garantir a qualidade e a estabilidade do seu código. RSpec é uma ferramenta de teste muito popular em Ruby, conhecida por sua legibilidade e expressividade. Abaixo, mostrarei maneiras eficientes de escrever testes usando RSpec.
</p>

<h3>Organização dos Testes</h3>

<p>
Divida seus testes em contextos lógicos usando "describe" e "context".
</p>
<p>
Agrupe testes relacionados usando "describe" para descrever o comportamento de uma classe ou método.
</p>
<p>
Use "context" para especificar diferentes cenários dentro de um mesmo contexto.
</p>

<p>Por exemplo:</p>

```ruby
describe MyClass do
  context "when initialized" do
    it "has default attributes" do
      # test implementation
    end
  end

  context "when performing some action" do
    it "does something under certain conditions" do
      # test implementation
    end

    it "handles edge cases" do
      # test implementation
    end
  end
end
```

<h3>Expectativas claras</h3>

<p>
Utilize "it" para descrever comportamentos esperados.
</p>
<p>
Use "expect" para declarar as expectativas do comportamento.
</p>

<p>Por exemplo:</p>

```ruby
it "returns the sum of two numbers" do
  result = add(2, 3)
  expect(result).to eq(5)
end
```

<h3>Configuração e Limpeza</h3>

<p>
Use "before" para configurar o estado inicial dos objetos antes dos testes.
</p>
<p>
Utilize "after" para limpar recursos ou estado após a execução de cada teste.
</p>

<p>Por exemplo:</p>

```ruby
describe MyClass do
  before do
    @my_object = MyClass.new
  end

  it "performs some action" do
    # test implementation
  end

  after do
    # clean up resources
  end
end
```
<h3>Matchers</h3>

<p>
RSpec fornece uma variedade de matchers para testar expectativas de maneira expressiva.
Alguns exemplos incluem "eq", "be_truthy", "be_falsey", "be_nil", "include", entre outros.
</p>

<p>Por exemplo:</p>

```ruby
it "checks if a number is even" do
  number = 4
  expect(number).to be_even
end
```

<h3>Mocks e Stubs</h3>

<p>
Use mocks e stubs para isolar o código em teste de dependências externas.
Evite testes que dependem de recursos externos, como bancos de dados ou APIs.
</p>

<p>Por exemplo:</p>

```ruby
it "sends an email when a new user signs up" do
  user = build(:user) # Utilizando FactoryBot
  mailer = double("UserMailer")
  allow(UserMailer).to receive(:welcome_email).and_return(mailer)
  expect(mailer).to receive(:deliver_now)
  user.save
end
```

<h3>Conclusão</h3>

<p>
A prática de escrever testes eficientes usando RSpec no Ruby on Rails é crucial para o desenvolvimento de software de qualidade. O artigo abrangeu várias técnicas e práticas recomendadas para criar testes robustos e confiáveis, garantindo que o código seja funcional, escalável e fácil de manter.
</p>