teleren/devto huggingface dataset:
Adding a cache in Python
Tags: python, tutorial, beginners
Published: 2023-05-29 11:21:00

When we work on apis, especially to display informations, it oftenly comes to a point where we have many identical calls. So, to avoid an overutilization of our resources and gain speed, we can setup a cache directly in our Python code.

Today, we will see how to do it with **lru_cache**.

---

## Setup
Like a lot of python librairies, lru_cache is available through pip.

PIP - Lru_cache : https://pypi.org/project/lru_cache/

```bash
pip install lru_cache
```

---

## How to use it
```python
from cache import LruCache  
  
@LruCache(maxsize=2, timeout=1)  
def foo(num):  
	return num  
```

As you can see it, it's really easy to use it. You just have to **add an annotation above the function where you want to add cache.**

### Parameters
#### maxsize
`maxsize` is the **maximum of differents calls of the method which can be cached at the same time**.

"differents calls of the method" means that at least one parameter changed. 

*Example*
```python
foo(1) # Foo is called and its return is added in cache
foo(1) # Value directly returned from cache
foo(2) # Foo is called and its return is added in cache
foo(3) # Foo is called and its return is added in cache instead of the return of "foo(1)" as the max size is 2
foo(2) # Value directly returned from cache
```

If **no value is given for this parameter, so every different calls will be cached.**

#### timeout
`timeout` is **the number of seconds where the result of a call is stored** before calling again the method.

```python
foo(1) # Called at 10:00:00 - Foo is called and its return is added in cache
foo(1) # Called at 10:00:00 - Value directly returned from cache
foo(2) # Called at 10:00:00 - Foo is called and its return is added in cache
foo(2) # Called at 10:00:00 - Value directly returned from cache
foo(1) # Called at 10:00:01 - Value directly returned from cache
foo(1) # Called at 10:00:02 - Previous value expired, Foo is called and its return is added in cache
```

If **no values are given for this parameter, all the informations will be stored until a restart of the python app**.

---

## Invalidate cache
If you need to invalidate a value in your cache, you can use the following line:

```python
foo.invalidate(num)
```

---

And that's it! With only 3 lines, we are able to add cache and invalidate some data to increase our performances and reduce the resource usage!

I hope it will help you and if you have any questions *(there are not dumb questions)* or some points are not clear for you, don't hesitate to add your question in the comments or to contact me directly on  [LinkedIn](https://www.linkedin.com/in/maxime-guilbert-14b6a5128/).

---

<center><h3>You want to support me?</h3></center>
<a href="https://www.buymeacoffee.com/mxguilbert7" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" height="41" width="174"></a>
seo training classes
Published: 2023-05-29 11:15:58

If you're looking for [SEO training classes](https://w3beginners.com/seo-course-in-rawalpindi/), there are several options available to you. Here are a few suggestions:

Online SEO Courses: Many reputable websites and platforms offer online SEO courses that cater to different skill levels. Some popular options include Udemy, Coursera, Moz, and HubSpot Academy. These courses often cover various aspects of SEO, including keyword research, on-page optimization, link building, and analytics.

Local Workshops and Seminars: Check if there are any local marketing or digital agencies in your area that offer SEO training workshops or seminars. These events can provide hands-on learning experiences and networking opportunities with industry professionals.

Professional Associations and Organizations: Professional associations and organizations related to marketing and digital advertising often offer training programs and resources, including SEO-focused training. Examples include the Search Engine Marketing Professionals Organization (SEMPO) and the American Marketing Association (AMA).

Webinars and Online Tutorials: Keep an eye out for webinars and online tutorials conducted by industry experts or SEO agencies. These can provide valuable insights and practical tips on specific SEO topics or strategies.

In-Person University or College Courses: Some universities and colleges offer courses on digital marketing or web development that cover SEO as part of the curriculum. If you prefer an in-person learning experience, you can explore these options.

Before enrolling in any SEO training classes, consider your current knowledge level, budget, and preferred learning style. Also, research the course provider, read reviews, and ensure that the content is up to date, as SEO practices can evolve over time.
What is a stored procedure in SQL?
Tags: sql
Published: 2023-05-12 08:30:44

A stored procedure in SQL is a pre-written program that is stored in a database. It is a group of SQL statements that have been saved to the database, and can be called upon to perform a specific action. A stored procedure can be executed with a single call, which can save time and reduce the amount of code needed to perform a specific task.

Stored procedures can be used for a variety of tasks, including data validation, data manipulation, and database management. They can be created using SQL commands and are stored in the database server. They can be called by other programs or applications using a variety of programming languages.


Some of the benefits of using stored procedures include increased performance and security, as well as easier maintenance and management of the database. Stored procedures can be used to help ensure data integrity and consistency, as well as to improve the efficiency and effectiveness of database operations. They can also help to reduce the amount of code needed to perform a task, and can make it easier to maintain and manage the database over time.

Stored procedures offer several advantages over ad-hoc SQL queries. First, they can improve performance by reducing the amount of data that needs to be transmitted between the database server and the client application. This is because stored procedures are compiled and optimized by the database engine, which means that they can execute more quickly than equivalent SQL queries. By obtaining[ SQL Course](https://www.edureka.co/microsoft-sql-server-certification-training), you can advance your career in the field of SQL Servers. With this Certification, you can demonstrate your expertise in working with SQL concepts, including querying data, security, and administrative privileges, among others. This can open up new job opportunities and enable you to take on leadership roles in your organization.

Another benefit of stored procedures is that they can be used to enforce business rules and data validation. For example, a stored procedure can be written to ensure that certain fields in a database table are not left blank, or that certain values fall within a specific range. This helps to maintain the integrity of the data and prevent errors or inconsistencies from occurring.

Stored procedures can also improve security, since they can be used to control access to data by defining user roles and permissions. For example, a stored procedure can be written to restrict access to certain tables or data fields to specific users or groups.

In addition, stored procedures can make it easier to manage and maintain a database. This is because they can be updated and modified independently of the application code that uses them, which can make it easier to fix bugs or make changes to the database schema. They can also be used to encapsulate complex database logic, which can make it easier to understand and manage the code over time.
[TIL] Elixir Map/Keyword.get default value is eager
Tags: elixir, liveview, phoenix, todayilearned
Published: 2023-05-29 10:34:11

For some reason, maybe php/javascript i though that 

```elixir
Map.get(opts, :key, "default")
Keyword.get(opts, :key, "default")
```

The default value will only get evaluated if you there is no default value provided in the map/keyword list.

Considering it now it seems silly, but it's a little lesson i had to learn the hard way.

Here's what i did:

```elixir
Keyword.get(opts, :key, SomeRepo.total_products(user.id))
```

Which obviously calls the repo every time you are trying to access the :key, what i wanted is to only call the repo when the value is nil

And here's the fix to only evaluate the repo call if the keyword is set to nil

```elixir
show_intro? =
  opts
  |> Keyword.get(:show_intro?)
  |> show_intro?(user.id)

defp show_intro?(nil, id), do: Products.total_by_user(id) == 0
defp show_intro?(show, _), do: show
```
Unveiling the Hidden Secrets: Journey into the Enigmatic World of 30 Days Coding
Published: 2023-05-29 10:26:39

Welcome to 30 Days Coding, a thriving global community that brings together coders of all levels to support and inspire one another. Whether you’re a beginner taking your first steps into coding or an advanced developer seeking continuous growth, our community is here to help you unlock your true potential.

🚀Just click the enchanted link to start your journey: https://30dayscoding.com

🌟Collaborative Growth: At 30 Days Coding, we believe in the power of collaboration. Our community is filled with cream coders from around the world who are passionate about sharing their knowledge and experiences. No matter your skill level, you’ll find a supportive network eager to assist you on your coding journey.

💡Mentorship and Support: We value mentorship as a crucial aspect of our community. Seasoned coders generously offer their guidance and mentorship to help beginners gain confidence and assist advanced coders in pushing their boundaries. Together, we foster an environment where everyone can grow and thrive.

👨‍💻Challenges and Opportunities: To fuel your progress, we offer a range of coding challenges and opportunities. These challenges cater to all skill levels, from beginner-friendly exercises to advanced projects. Engaging in these challenges allows you to sharpen your skills, collaborate with fellow coders, and gain valuable experience.

👾Knowledge Sharing Hub: Our community serves as a hub for knowledge sharing. Members contribute informative articles, coding tutorials, and insights through our platform. You’ll have access to a wealth of resources that will broaden your understanding of different programming languages, frameworks, and industry trends.

🧑🏻‍🤝‍🧑🏻Global Connections: Joining 30 Days Coding means connecting with a global network of coders. Engage in discussions, exchange ideas, and build meaningful relationships with like-minded individuals. Through these connections, you’ll gain diverse perspectives and expand your professional network.

If you’re ready to take your coding journey to the next level, join 30 Days Coding today. Our global community offers an inclusive space for coders of all levels to support, learn, and grow together. Unleash your potential and embark on an exciting adventure with us. Together, we’ll achieve remarkable coding milestones and forge lasting connections. Join 30 Days Coding now and unlock a world of possibilities!
How to install Facebook Pixel on Magento 2
Tags: magento, magento2, magento2tutorial
Published: 2023-05-29 10:26:13

Greetings, fellow marketer! Are you prepared to elevate your Facebook advertising game and boost sales for your Magento 2 online store? If you are, then you're in luck because I'm here to assist you with the installation process of Facebook Pixel.

To begin with, let's delve into what Facebook Pixel is and why it holds significance. Essentially, it's a potent analytics tool that enables you to track user behavior on your website following their interaction with your Facebook ads. This valuable information grants you insights to optimize your ad campaigns and increase your return on investment (ROI).

Now, let's discuss **_How to install Facebook Pixel on Magento 2_** store. Don't fret, it's simpler than you may think! The initial step involves creating a Facebook Pixel ID, which serves as a unique identifier to track and analyze user behavior. To accomplish this, navigate to your Facebook Ads Manager and click on "Pixels" in the "Events Manager" section. From there, simply select "Create a Pixel" and follow the provided instructions to set it up.

For more information , please visit this :- **_[https://webguru.dev/how-to-install-facebook-pixel-on-magento-2/](https://webguru.dev/how-to-install-facebook-pixel-on-magento-2/)_**
How to Build a Grocery App with React Native
Tags: webdev
Published: 2023-05-29 10:10:04

A no-code or low-code platform that includes visual tools and pre-built components can be used to create a shopping app without coding. While React Native needs coding, there are tools that can help you construct a basic supermarket app without writing code. The following is a general summary of the steps you can take:


Choose a no-code/low-code platform:

Research and select a platform that supports mobile app development and offers visual app-building capabilities. Some popular options include Bubble, Adalo, Thunkable, and Appgyver.
Define the app's functionality:

Determine the core features you want to include in your grocery app, such as product listing, shopping cart, user authentication, payment integration, etc.
Design the user interface:

Use the platform's visual editor to create the app's screens and design the layout.
Utilize drag-and-drop tools to add components like buttons, text fields, product cards, etc., to the screens.
Set up data management:

Configure data sources to store and manage your grocery items, user information, and other relevant data.
Connect to external APIs or databases if required for retrieving product information or performing operations like payment processing.
Implement features:

Use the platform's visual tools to define the logic and behavior of your app.
Configure actions and events for user interactions, such as adding items to the cart, updating quantities, etc.
Customize app branding and styles:

Customize the app's appearance by selecting colors, fonts, and other visual elements provided by the platform.
Add your branding assets like a logo or icon to personalize the app.
Test the app:

Use the platform's preview functionality to test your app's behavior and ensure all features are working correctly.
Identify and fix any issues or bugs that arise during testing.
Publish and distribute:

Once you're satisfied with the app, follow the platform's instructions to publish your app.
Some platforms provide options to publish directly to app stores, while others may generate standalone APK or IPA files for distribution.
Maintain and update:

Monitor user feedback and make necessary updates or improvements to the app based on user suggestions or bug reports.
Regularly check for platform updates and implement them to ensure your app remains compatible and secure. Hope this article will help you to [build a grocery app](https://www.techgropse.com/grocery-delivery-app-development).
Get the Last Inserted Id Using Laravel Eloquent
Tags: laravel, beginners, programming, webdev
Published: 2023-05-29 09:57:16

**Introduction:**
When working with databases in #Laravel, it is often necessary to retrieve the ID of the last inserted record.

The ID can be useful for various purposes, such as linking related data or performing subsequent operations.

In this post, we will explore how to obtain the last inserted ID using Laravel’s Eloquent ORM, making it easier for you to work with database records in your Laravel applications.
**
Step 1: Save a Record Using Eloquent**
To begin, let’s assume that you have a model representing the table you want to insert data into. In this example, we’ll use a User model that corresponds to a users table.

To save a new record using Eloquent, you can use the following code:
```
$user = User::create([
        'name' => 'John Doe',
        'email' => 'johndoe@example.com',
]);
```
Make sure to replace User with the appropriate model class name for your application, and set the desired values for the record you want to insert.

**Step 2: Retrieve the Last Inserted ID**
After saving the record, you can retrieve the last inserted ID using the id property of the Eloquent model. Here’s an example:
```
$lastInsertedId = $user->id;
```
The id property will contain the last inserted ID value, which you can assign to a variable for further use in your application.


**Alternative Method – Using the _insertGetId_ Method**
Another way to retrieve the last inserted ID is by using the insertGetId method provided by Laravel’s query builder.

This method allows you to insert a record and immediately get the ID of the inserted row. Here’s an example:
```
$lastInsertedId = DB::table('users')->insertGetId([
    'name' => 'John Doe',
    'email' => 'johndoe@example.com',
]);
```
In this example, we are inserting a new record into the users table and assigning the last inserted ID to the **$lastInsertedId **variable.

Remember to replace 'users' with the appropriate table name for your application, and adjust the column names and values accordingly.

**Conclusion:**
Retrieving the last inserted ID is a common requirement when working with databases in Laravel applications. By using Laravel’s Eloquent ORM, you can easily obtain the ID of the last inserted record.

Whether you choose to retrieve the ID from the Eloquent model’s id property or use the insertGetId method of the query builder, both methods provide a straightforward way to access the last inserted ID value.

Incorporate these techniques into your Laravel projects to simplify working with database records and streamline your development process.

Let me know if this helps.
Migrating from Kubernetes to Docker Compose
Tags: devops, discuss, docker, kubernetes
Published: 2023-05-29 09:34:47

We're an outsourced developer specializing in e-comm and food tech, making cross-platform mobile and web. We have about 10 projects in development simultaneously, plus there are old ones that we support.

When we conceived all this “flipping” described in the article, we wanted to ensure that after each commit to the master branch, it would automatically expand. So that, if desired, you can independently deploy other branches, and deploy to production.

If anyone has similar needs - [here's](https://devfamily.hashnode.dev/migrating-from-kubernetes-to-docker-compose) the story of how it worked out for us. We would be glad if someone would share their experience in solving a similar problem
flutter text widget example
Tags: flutter, dart, widgets, text
Published: 2023-05-29 08:50:39

For Explanation watch the video :

{% embed https://youtu.be/G_foj-N-Rc0 %}

```
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const TextWidget(),
    );
  }
}

class TextWidget extends StatelessWidget {
  const TextWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Text Widget'),
      ),
      body: Container(
        child: Text(
          'Hi, How Are you?',
          style: TextStyle(
            fontSize: 40,
            color: Colors.red,
            fontWeight: FontWeight.bold,
            fontStyle: FontStyle.italic,
            letterSpacing: 3,
            wordSpacing: 10,
            backgroundColor: Colors.amber,
          ),
        ),
      ),
    );
  }
}

```
Create an AI Avatar or 3D Selfie
Tags: ai, 3d, avatar, selfie
Published: 2023-05-29 08:23:39

Easily create an amazing 3D Avatar or 3D Selfie with the [Qlone](https://www.qlone.pro) app on your iPhone!

With our new simple UI, you can seamlessly create beautifully looking 3D face scans! Here are some examples:

{% embed https://vimeo.com/831135337 %}
Autoscaling Live Streaming Server in Any Cloud Provider with HELM & Kubernetes
Published: 2023-05-29 08:12:39

[Helm](https://helm.sh/) is a powerful tool that simplifies the management of applications on Kubernetes. With Helm, you can easily deploy, upgrade, and control versions of your applications, all with just a few simple commands.

[Ant Media](https://antmedia.io) recently introduced a [Helm Chart](https://antmedia.io/easily-deploy-ant-media-server-on-kubernetes-with-helm/) to ease of deployment of [Ant Media Server](https://antmedia.io/docs/) using Kubernetes on any cloud provider network. The best part of it is to create an [Ant Media Server Cluster environment](https://antmedia.io/docs/category/clustering-and-scaling/) with just one click!

Helm supports installations on Ubuntu and other distros. Before installing Helm on any operating system, it is necessary to set up a Kubernetes cluster. Then you can proceed with using Helm Chart to deploy Ant Media Server in Kubernetes easily.

At last, you can even watch a [video ](https://youtu.be/FKX86Ng8Z7Y) about it as Ant Media team shot a video to explain in details as well.

Enjoy!
linux增大线程数上限
Published: 2023-05-29 07:56:36

- 1、打开`/etc/security/limits.conf `
- 2、在行尾添加
```
* soft nproc 1000000
* hard nproc 1000000
```
- 3、保存退出
- 4、重新登录服务器
- 5、校验是否成功修改
```
ulimit -a
```

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


  > 查看这行是否已经变成配置文件中修改的值了，如果是了到此为止；如果没有（AWS是不行的）继续进行下面的流程

- 6、打开 PAM 配置文件 /etc/pam.d/login，查看是否存在`session    required     pam_limits.so` 这一行，如果不存在，请添加；重新登录再次`ulimit -a`, 如果还不行，那么请看第 7 步

- 7、修改 `~/.bashrc`，在下面新增两行:
```
ulimit -n 1000000
ulimit -u 1000000
```
  > 保存重新登录，`ulimit -a` 能够发现在对应用户下已经生效了
OpenSSL 3 üzerinde Legacy destek verilebilmesi
Tags: openssl, legacy
Published: 2023-05-29 07:54:17

Çeşitli uygulamalar SSL desteği için OpenSSL 3 üzerinde Legacy desteğine ihtiyaç duyabilmektedir. Bu gibi uygulamalar genellikle aşağıdaki gibi bir hata dönmektedir.

> Error outputting keys and certificates 40A7244B497F0000:error:0308010C:digital envelope routines:inner_evp_generic_fetch:unsupported:../crypto/evp/evp_fetch.c:373:Global default library context, Algorithm (RC2-40-CBC : 0), Properties ()

Bu hata genellikle PFX uzantılı dosyaların anahtar ve sertifikalarına ayrılırken sorun olarak ortaya çıkmaktadır.

Çözüm olarak OpenSSL yapılandırma dosyası "/etc/ssl/openssl.cnf" içerisinde "[default_sect]" sekmesi olan yerde aşağıdaki gibi bir ifadenin olması sağlanması gerekmektedir.

```
[default_sect]
activate = 1
[legacy_sect]
activate = 1
```

Varsayılanda genellikle default_sect zaten aktif gelmesine rağmen legacy sect'in de aktife çekilmesi gerekmektedir. Sonrasında dosya içerisinde "[provider_sect]" aranarak varsa altına, yoksa açıklama olarak bulunan satırın altına aşağıdaki satırlar eklenmelidir.

```
[provider_sect]
default = default_sect
legacy = legacy_sect
```

Dosya kaydedilip çıkıldıktan sonra kullandığınız uygulama artık arkaplandaki openssl'i ve kütüphanelerini kullanıyorsa legacy desteğine sahip olmuş olacaktır.