teleren/devto huggingface dataset:
Refactoring Ruby: Extract Method
Tags: refactoring, ruby
Published: 2023-10-10 15:31:45

---
title: Refactoring Ruby: Extract Method
published: true
description: Extract Method can be used when you have several expressions, a code fragment, that can be grouped together to add clarity to your ruby classes.
tags: refactoring, ruby
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2023-05-12 19:40 +0000
---
Last time, we looked at possibly one of the _smallest_ refactorings you can do, [Extract Variable](https://dev.to/jonlunsford/refactoring-ruby-extract-variable-1a0i). Let's take another tiny step and look at the _Extract Method_ pattern.

_Extract Method_ can be used when you have several expressions, a code fragment, that can be grouped together. Even if there is one expression that could be better explained with a well thought out method name, it’s still a good move.

Let’s use Extract method on the `Invoice#print` method:

**Before:**

```Ruby
class Invoice
  ...

  def print
    print_branding

    # print line items
    line_items.each do |line_item|
      puts "#{line_item.name}: #{line_item.price}"
    end

    # print subtotal
    puts "Subtotal: #{line_items.sum(&:price)}"
  end
end
```

**After:**

```Ruby
class Invoice
  ...

  def print
    print_branding
    print_line_items
    print_subtotal
  end

  private

  def print_line_items
    line_items.each do |line_item|
      puts "#{line_item.name}: #{line_item.price}"
    end
  end

  def print_subtotal
    puts "Subtotal: #{line_items.sum(&:price)}"
  end
end
```

The method before refactoring looks like:

```Ruby
def print
  print_branding
  # print line items
  line_items.each do |line_item|
    puts "#{line_item.name}: #{line_item.price}"
  end
  # print subtotal
  puts "Subtotal: #{line_items.sum(&:price)}"
end
```

Often times, if you see comments explaining what a code fragment does, it’s a smell indicating there is a method to be extracted.

The method after refactoring looks like:

```Ruby
def print
  print_branding
  print_line_items
  print_subtotal
end
```

Let’s walk through the steps used when applying Extract Method:

  1. Identify candidate fragments by looking for some common smells like, expressions that cluster together, comments explaining the intent, or if a good method name could add clarity.
  2. Turn those fragments into a method whose name explains the purpose of the method.

Reach for this when a method contains groups of seemingly un-related code fragments, or when better naming will make it easier for you or your coworkers to understand the intent of code.
Docker - Optimize Dockerfile Layering for Faster Builds
Tags: docker, programming, tutorial
Published: 2023-10-10 15:30:00

Optimizing your Dockerfile to minimize build times and reduce image size is important when building Docker images. One effective strategy for achieving this is to carefully manage Dockerfile layering. Docker caches layers during the build process, and understanding how layers work can help you create more efficient Dockerfiles.

Here are some tips for optimizing Dockerfile layering:

- **Order Instructions Wisely:** Place instructions in your Dockerfile from the least frequently to the most frequently. This way, Docker can reuse cached layers for the stable parts of your application, making builds faster.

- **Use Multi-Stage Builds:** Multi-stage builds are an excellent way to reduce image size by separating the build environment from the runtime environment. This also prevents unnecessary dependencies from being included in the final image.

- **Combine Commands:** Whenever possible, combine multiple commands into a single RUN instruction. For example, instead of having multiple RUN instructions for installing packages and cleaning up, combine them into one instruction.

   ```Dockerfile
   RUN apt-get update && \
       apt-get install -y package1 package2 && \
       apt-get clean && \
       rm -rf /var/lib/apt/lists/*
   ```

- **Use .dockerignore:** Create a `.dockerignore` file to exclude unnecessary files and directories from being copied into the image during the build. This reduces the size of the build context and speeds up the build process.

- **Leverage Build Cache:** Docker caches layers based on the contents of files. If a file hasn't changed, Docker will use the cached layer. Be cautious when changing files that have a broad impact to avoid invalidating the cache unnecessarily.

- **Avoid Using ADD for Files from URLs:** Use `COPY` instead of `ADD` when copying files from the local filesystem. `ADD` can also fetch files from URLs, which can lead to unexpected behavior and slower builds.

- **Minimize the Number of Layers:** Try to minimize the number of layers in your image by combining multiple commands into one. Fewer layers result in smaller image sizes and faster builds.

By optimizing Dockerfile layering, you can significantly reduce build times, improve developer productivity, and reduce the size of your Docker images, which is crucial for efficient image distribution and deployment.
Building a RESTful API with Flask: A Beginner's Guide
Tags: webdev, beginners, programming, tutorial
Published: 2023-10-10 15:24:13

**Introduction:**
Welcome to the exciting world of web development with Flask! If you're just starting out on your journey to master Flask, you've come to the right place. In this guide, we'll walk through the process of building a simple RESTful API using Flask, a lightweight and powerful web framework for Python.

**Prerequisites:**
Before we dive into coding, make sure you have Python installed on your machine. You can install Flask using pip:

```bash
pip install Flask
```

Setting up your project:
Let's create a new directory for our project and set up a virtual environment. This helps keep your project dependencies isolated.

```bash
mkdir flask-api
cd flask-api
python -m venv venv
```

Activate the virtual environment:

- On Windows:

```bash
venv\Scripts\activate
```

- On Unix or MacOS:

```bash
source venv/bin/activate
```

Now, let's create a simple Flask app. Create a file named `app.py` and add the following code:

```python
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

if __name__ == '__main__':
    app.run(debug=True)
```

Run your app:

```bash
python app.py
```

You should see your Flask app running at `http://127.0.0.1:5000/`. Open this URL in your browser, and you should see the "Hello, World!" message.

Building a RESTful API:
Now, let's turn our simple app into a RESTful API. We'll create endpoints for basic CRUD operations (Create, Read, Update, Delete).

1. **Creating Resources:**
   Let's create an endpoint to handle the creation of a resource. Update your `app.py` file:

```python
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/api/resource', methods=['POST'])
def create_resource():
    data = request.get_json()
    # Perform validation and save resource to the database
    # For now, let's just echo the data
    return jsonify(data), 201

if __name__ == '__main__':
    app.run(debug=True)
```

Test the endpoint using a tool like [Postman](https://www.postman.com/) or [curl](https://curl.se/):

```bash
curl -X POST -H "Content-Type: application/json" -d '{"name": "New Resource"}' http://127.0.0.1:5000/api/resource
```

2. **Reading Resources:**
   Let's add an endpoint to retrieve the created resource:

```python
@app.route('/api/resource/<int:resource_id>', methods=['GET'])
def get_resource(resource_id):
    # Fetch resource from the database based on resource_id
    # For now, let's just return a dummy response
    return jsonify({'id': resource_id, 'name': 'New Resource'}), 200
```

Test the endpoint:

```bash
curl http://127.0.0.1:5000/api/resource/1
```

Conclusion:
Congratulations! You've built a simple RESTful API with Flask. This is just the beginning—Flask offers a wide range of features to explore, such as request handling, authentication, and database integration.
Hacktoberfest #02
Tags: hacktoberfest23, beginners, opensource
Published: 2023-10-10 15:17:32

[Issue 2962](https://github.com/Seneca-CDOT/telescope/issues/2962) | [Pull Request](https://github.com/Seneca-CDOT/telescope/pull/3836)

**What was the issue about?**

The issue pertains to translating the 'About' page into different languages to enhance user-friendliness.

**What did I need to do to prepare the fix?**

I had to install `pnpm` since this project utilizes it instead of `npm`. Following that, I installed all the dependencies using `pnpm install`. Finally, I was able to run both the frontend and backend microservices locally with `pnpm services:start`.

To get started, I went through the documentation, including `README.md` and `CONTRIBUTING.md`. After reviewing the documentation, I also examined the issues and pull requests that were submitted by other contributors working on similar issues with different languages.

**Demo of the code before/after the fix**
**Before**
The previous version did not offer the option to view this page in Korean. 

**After**
![after](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ahnzvr328vbz5xk6jfjx.png)

**Were there aspects of the issue that I found difficult?**

After implementing the code, I attempted to run the program locally. I referred to an example pull request posted on GitHub and followed the guidelines using the exact same path, which resulted in an error. The issue was that the code had undergone extensive changes, including the changes in paths as well. Therefore, using the exact path turned out to be an incorrect choice. I had to navigate through several directories to find the correct path for running the program to see the changes I made.

**What did I find difficult? How did I overcome this?**

Because this issue pertained to translation, I had to find another Korean reviewer to assess my pull request. I accomplished this by using Slack to locate the person I needed.

**What was my process?** 

1. I communicated with the author to confirm if I could work on the issue.
2. Once confirmed, I forked the repository and cloned it to my local machine.
3. I switched to the different branch and implemented the necessary code changes.
4. After completing the task, I created a pull request for review.
5. I addressed the comments received and made the necessary changes.

**What did I learn?**

I learned that it is important for me to ask the questions I have. I realized that I don't have to struggle with problems by myself. I had a question about finding another Korean reviewer, so I asked the author and he gave a suggestion on how to find another reviewer. Since this was my first contribution, I was a bit intimidated to ask any questions, but I will do so again next time with a little less hesitation.

**Discussion of what I did to address your review comments.**
There are some comments I received after I pushed the PR. For example, one of the pieces of feedback was that I used a certain word that did not match the original context. What I did was read the original text again and try to translate it without injecting my own thoughts into it.
Hacktoberfest- The Gateway to Open Source
Tags: hacktoberfest23, hackathon, hacktoberfest, opensource
Published: 2023-10-10 15:06:45

Open source contributions have emerged as a significant and thriving ecosystem within the global tech community. It is a collaborative and decentralized approach to software development, where individuals and organizations contribute to projects by openly sharing code, ideas, and resources. Open Source is largely celebrated through pivotal programs like GSOC, Hacktoberfest,etc among others. The motivations behind participating in open source projects are diverse, driven by a combination of personal, professional, and ideological factors. 

Personally, as a first year engineering student, I was motivated by a desire to learn more about web development and open source communities in general . Hacktoberfest offered me the chance to work on real-world projects, collaborate with experienced peers, and gain hands-on experience with web development and machine learning.

Many open source enthusiasts are motivated by a sense of altruism and a desire to give back to the global tech community. As a young learner, Hacktoberfest gave me the same sense of paying it forward. It is not just the repsitories I worked with, but also the repos I studies, that allowed me a chance to update myself on the latest Technology.

Overall, it was a fun learning experience and I pledge to commit to participating in open source events like Hacktoberfest again
Play gallery block on hover/mouse rollover 7.1
Published: 2023-10-10 15:02:02

The term ["Right Click CPS Test"](https://clicktester.net/right-click-test/) doesn't seem to have a direct relevance to playing a gallery block on hover or mouse rollover in a website built on the Squarespace 7.1 platform. However, if you have questions or need assistance with implementing such interactive features on your website, please feel free to ask, and I'd be happy to help with that specific topic.
At RELIANOID, We Prioritize Employee Mental Health!
Published: 2023-10-10 14:46:47

In today's fast-paced world, caring for our employees' mental health is a top priority at RELIANOID. We understand that a healthy mind is the foundation for #creativity, #productivity, and overall #well-being. 

We're dedicated to nurturing a workplace where mental health matters:
Mental Health and Wellness Improvement Resources
Flexible Work Times and Locations
Open and Equal Communication
 Employee Assistance 
 Procedures and attention to avoid #burnout
Our #team is our most valuable asset, and we're committed to ensuring they feel supported, valued, and empowered every day. 
Join us at RELIANOID, where we are not just a company, but a #community that #cares! 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gcg2j69chnjw6zw46hs3.jpg)
#MentalHealthMatters #EmployeeWellness #RelianoidCares #WorkplaceWellbeing #JoinOurTeam #WeCare #WorldMentalHealthDay #MentalHealth #HealtyWork #Healthy World Health Organization (WHO)
Is it work like shopify too? Means can we install plugins and get latest feature update too like shopify give in few bucks?
Published: 2023-10-10 14:41:32

[Justelegance Shop](https://justelegance.de/collections) appears to be a platform for shopping related to elegance and fashion. While it may offer a variety of elegant products, it's important to note that it might not function like Shopify, which is a full-fledged e-commerce platform. Shopify allows users to install plugins, customize their online stores, and receive feature updates. To learn more about Justelegance Shop's specific features and capabilities, it's advisable to visit their website or contact their support team for detailed information.
Unable to build angular library
Tags: angular
Published: 2023-10-10 14:30:40

I have a angular library project where I am using third party UI library. Now I want to import theming but as per update we have to use @use to get the reference of style as per SaaS structure .
here Infragistics is UI library which I am using inside my angular library.

I am getting below  error  while building library project 

`Can't find stylesheet to import.
  ╷
1 │ @use 'igniteui-angular/theming' as *;
  │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  ╵
  projects\test-library\src\lib\test-component\test-component.component.scss 1:1  root stylesheet`

I am in desperate need of solution. Please help.
For a fistful of dollars: fine-tune LLaMA 2 7B with QLoRA
Tags: ai, huggingface, chatbots, aws
Published: 2023-10-10 18:04:22

---
title: For a fistful of dollars: fine-tune LLaMA 2 7B with QLoRA
published: true
date: 2023-10-10 14:28:51 UTC
tags: ai,huggingface,chatbots,aws
canonical_url: https://julsimon.medium.com/for-a-fistful-of-dollars-fine-tune-llama-2-7b-with-qlora-bfc22c44d0ca
---

![](https://cdn-images-1.medium.com/max/1024/1*5_OKEXV0NjvdmE1R7Bw3DA.jpeg)

Fine-tuning large language models doesn’t have to be complicated and expensive.

In this tutorial, I provide a step-by-step demonstration of the fine-tuning process for a LLaMA 2 7-billion parameter model. Thanks to LoRA, 4-bit quantization and a modest AWS GPU instance (g5.xlarge), total cost is just a fistful of dollars 🤠 🤠 🤠

{% youtube 5L4s9mi9eUc %}
Exploratory Data Analysis using Data Visualization Techniques.
Published: 2023-10-10 14:24:10

## Introduction
Think of what data is for a moment, from gathering it through sharing the final report with the domain or company to enable them make informed decision-making. 

Data collection has its dos and don'ts, and in order to make sense of the data so that you may derive insights, a method known as exploratory data analysis (EDA) must be used.

EDA aids in learning more about the data set and discovering patterns, trends, and connections between them. In order to obtain high-quality data, it also helps to discover missing values, outliers, and anomalies. 

We employ statistical functions and tools to complete all of this.

### What is EDA

Exploratory data analysis (EDA) is an approach of     analyzing data sets to summarize their main 
characteristics, often using statistical graphics 
and other data visualization methods this is according to [wikipedia](https://en.wikipedia.org/wiki/Exploratory_data_analysis)

With EDA, you may examine data, find patterns, anomalies, and outliers, as well as fill in missing values to get the proper data for insights and machine learning models (both supervised and unsupervised).

### Steps of performing EDA
      1. Understanding Domain
      2. Get the right libraries and Read file
      3. Cleaning Data & Preparing data
      4. Feature Engineering 
      5. Data Visualization & Interpretation

### Tools Used For EDA

There are a several tools used to do EDA, including Tableau, Power BI, and Python libraries, among many others. 

#### Python Libraries

      - Numpy
      - Pandas
      - Matplotlib
      - Seaborn

#### Others 
        
       Tableau
       PowerBI

### Statistical Function & Techniques for EDA tools
     - Clustering and Dimension
     - Univariate Viausalization
     - Bivariate Visualization
     - Multivaraite
     - K-means Clustering
     - Predictive Models

To get more understanding of how this techniques read through [IBM](https://www.ibm.com/topics/exploratory-data-analysis)

## Data Visualization in EDA

### Graphical techniques:

      Box plot, Histogram, Multi-vari chart
      Run chart, Pareto chart, 
      Scatter plot (2D/3D),Heat map
      Bar chart

### Dimensionality reduction:

    Multidimensional scaling
    Principal component analysis (PCA)
    Multilinear PCA
    Nonlinear dimensionality reduction (NLDR)
    Iconography of correlations

### Typical quantitative:

    Median polish
    Trimean
    Ordination

## Conclusion

This article may not include much information, but it will offer you a general idea of what to have and when to use certain tools and basic actions. EDA is essential for understanding data insights and obtaining clean data for modeling (ML). Google is your friend outside of this, though. 

      
      REMEMBER: "A picture is worth a thousand words"
Pre Filled Syringes Market Key Details and Outlook by Top Companies Till 2030
Published: 2023-10-10 14:21:50

TIP added a new research study on Global Pre Filled Syringes Market 2030 furnishes a market examination complete with a quantitative and subjective appraisal. The report offers key proposals, patterns, Size, Share, division, serious insight, and worldwide and territorial estimates. The report study investigates the size of the worldwide Pre Filled Syringes Market regarding volume and worth. The report covers market size breakdown, income, and development rate in significant portions. It gives a serious scene of significant players with the current business situation, and market focus status. The report gives an itemized investigation of the general market dependent on different kinds, applications, and end-use businesses. The report covers different patterns and market improvement for every one of the sections. Supported by market esteems and development gauges, the report distinguishes key development regions in the market that organizations can use their market position.
The List of Companies

1. Becton, Dickinson and Company
2. Gerresheimer
3. SCHOTT AG
4. West Pharmaceutical Services, Inc.
5. Baxter International Inc.
6. Terumo Corporation
7. Catalent, Inc.
8. Weigao Group
9. Vetter Pharma International GmbH
10. Nipro Corporation
 
The report aims to provide an additional illustration of the latest scenario, economic slowdown, and COVID-19 impact on the overall industry.
Key Offerings:
•	Market Size & Forecast by Revenue | 2030
•	Market Dynamics – Leading trends, growth drivers, restraints, and investment opportunities
•	Market Segmentation – A detailed analysis by product, types, end-user, applications, segments, and geography
•	Competitive Landscape – Top key vendors and other prominent vendors
RELIABLE HACKER
Tags: webdev, javascript, beginners, programming
Published: 2023-10-10 14:14:49

When I lost my Bitcoin of 162,000 Euro, I almost ran mad until someone I know introduced me to Wizard James Recovery, a Hacker who helped me recover all my lost Bitcoin. This hacker is very good at his job and very reliable. I was scammed by someone who pretended to be a Forex trader online and convinced me to invest in cryptocurrency. I couldn’t withdraw my profits or my initial investment and he kept requesting more fees, to cut the story short I lost all my money which was very depressing for me. I was discussing it with my friend when he told me about a professional hacker that goes by the name Wizard James Recovery. He gave me his contact information and I contacted him immediately at wizardjamesrecovery(@)usa . com. To my surprise, James was able to recover my money in 48 hours which was unbelievable. I am super excited because I didn’t imagine ever getting back my money. I know it's hard to trust most of the hackers when it comes to Bitcoin recovery, but for sure there are legit hackers, I will always spread the good news of Wizard James Recovery
Unlock the Power of Finality in Blockchain: Ensuring Trust, Security, and Immutable Records
Tags: blockchain, security, trust
Published: 2023-10-10 14:14:35

## What is finality in blockchain, and why does it matter?

![Blockchain](https://coinspectator.com/wp-content/uploads/2023/10/42f3681baee171ad51b17f4ff69bfbf6-vA44tC-150x150.jpeg)

Finality plays a crucial role in ensuring secure and irreversible transactions in blockchain. It is essential in preventing double-spending and fraud, while also maintaining the immutability of blockchain records.

For more information, [read the full article on Bites Insight](https://cointelegraph.com/explained/what-is-finality-in-blockchain-and-why-does-it-matter).

Check my profile on [Bites Insight](https://bitesapp.co?utm_source=devto) for the latest updates and stories.