Home Blog Page 17

How to convert celsius to fahrenheit formula

0
Convert Celsius to Fahrenheit

Hi Guys, Welcome to Proto Coders Point, In this article let’s checkout how to convert celsius to fahrenheit in all programming languages.

Here is a formula to convert a temperature from Celsius to Fahrenheit:

°F = (°C x 1.8) + 32

The temperature is expressed in degrees Celsius and degrees Fahrenheit in the equations above, respectively.

We have Temperature in form of Celsius, By using above formula, first simple multiple the Celsius temperature by 1.8 & then add 32. The Total we get is the temperature in Fahrenheit unit.

Example

To convert a temperature of 31 degrees Celsius to Fahrenheit, the formula used is as follows:

°F = (31 x 1.8) + 32 
°F = 55.8 + 32
°F = 87.8

Therefore, we get result after converting 30 degrees Celsius is equivalent to 87.8 degrees in Fahrenheit.


C Program to convert a temperature in Celsius to Fahrenheit

#include <stdio.h>

int main() {
    float celsius, fahrenheit;

    printf("Enter temperature in Celsius: ");
    scanf("%f", &celsius);

    fahrenheit = (celsius * 1.8) + 32;

    printf("%.2f Celsius is equivalent to %.2f Fahrenheit", celsius, fahrenheit);

    return 0;
}

C++ Program to convert a temperature in Celsius to Fahrenheit

#include <iostream>
using namespace std;

int main() {
    float celsius, fahrenheit;

    cout << "Enter temperature in Celsius: ";
    cin >> celsius;

    fahrenheit = (celsius * 1.8) + 32;

    cout << celsius << " Celsius is equivalent to " << fahrenheit << " Fahrenheit" << endl;

    return 0;
}

Java Program to convert a temperature in Celsius to Fahrenheit

import java.util.Scanner;

public class CelsiusToFahrenheit {
    public static void main(String[] args) {
        float celsius, fahrenheit;

        Scanner input = new Scanner(System.in);

        System.out.print("Enter temperature in Celsius: ");
        celsius = input.nextFloat();

        fahrenheit = (celsius * 1.8f) + 32;

        System.out.printf("%.2f Celsius is equivalent to %.2f Fahrenheit", celsius, fahrenheit);
    }
}

Python Program to convert a temperature in Celsius to Fahrenheit

celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 1.8) + 32
print("{:.2f} Celsius is equivalent to {:.2f} Fahrenheit".format(celsius, fahrenheit))

Javascript Program to convert a temperature in Celsius to Fahrenheit

let celsius = parseFloat(prompt("Enter temperature in Celsius: "));
let fahrenheit = (celsius * 1.8) + 32;
console.log(celsius + " Celsius is equivalent to " + fahrenheit.toFixed(2) + " Fahrenheit");

Dart Program to convert a temperature in Celsius to Fahrenheit

import 'dart:io';

void main() {
  stdout.write('Enter temperature in Celsius: ');
  double celsius = double.parse(stdin.readLineSync()!);

  double fahrenheit = (celsius * 1.8) + 32;

  print('$celsius Celsius is equivalent to ${fahrenheit.toStringAsFixed(2)} Fahrenheit');
}

GO Language Program to convert a temperature in Celsius to Fahrenheit

package main

import (
	"fmt"
)

func main() {
	var celsius float64
	fmt.Print("Enter temperature in Celsius: ")
	fmt.Scanln(&celsius)

	fahrenheit := (celsius * 1.8) + 32

	fmt.Printf("%.2f Celsius is equivalent to %.2f Fahrenheit", celsius, fahrenheit)
}

Kotlin Program to convert a temperature in Celsius to Fahrenheit

fun main() {
    print("Enter temperature in Celsius: ")
    val celsius = readLine()!!.toFloat()

    val fahrenheit = (celsius * 1.8) + 32

    println("%.2f Celsius is equivalent to %.2f Fahrenheit".format(celsius, fahrenheit))
}

Building Scalable Cloud Storage like AWS S3 Bucket Service

0
NodeJS - AWS S3 Bucket Like Service without using AWS
NodeJS - AWS S3 Bucket Like Service without using AWS

Now a days Cloud Storage has became an essential part of a modern world in software development, There are various third party service that provide cloud storage like AWS S3, Google Cloud Storage, Microsoft Azure Blob Storage, OpenStack Swift and more. But what if you want to build your own cloud storage system that can be crucial to make sure that the cloud storage service application runs smoothly and efficiently. In this Article we will learn how to build a scalable cloud storage system using NODEJS.

How to build cloud storage using NodeJS at backend

Building a fresh new cloud storage backend application using NodeJS is an challenging task, but no worry it’s possible to create our own NodeJS AWS S3 bucket like service without using any third party services.

Here are step to be follow:

  1. System Requirement: Start planning a system configuration that is need to work the cloud storage service smoothly, you need to configure system or Cloud Instance like RAM, Storage(amount of storage), Server speed, bandwidth and type of data user can store.
  2. Project Architecture: Based on the System Requirement, you can design the architecture on your cloud storage system project, Like you must decide on type of servers & where you are going to store the data(storage space), the mechanism to retrieval of data and a API for accessing system.
  3. Database: Select a database so that you can store metadata of files and folders that will get uploaded by the user. In our project we are using MongoDB a NoSQL database to store the record of upload files.
  4. Implement Features: Implement features such as creating a folder/bucket, getting list of all the folders, getting a list of files in a folder, downloading uploaded files from a folder using an API, and deleting a file from a given folder.
  5. Test and deployment: Test the cloud storage system to ensure it works as expected and deploy it to a server or cloud platform server instance.

Note: Building a secured cloud storage system from scratch is a complex process and you may need a complete dedicated team to make it secured. This project is for learning purpose only.


Creating a Cloud Storage Service Similar to AWS S3 Bucket using NodeJS

How to create node js project

Create a folder & open it in visual studio code, then to make it a NodeJS project run below command:

node init -y

the above command will convert a normal folder into nodejs project where it will create a file by name name “package.json”.


Installing node libraries

Below are list to nodejs libraries/module that are required to build cloud storage system:

  1. Express: Express is basically used in Node.js for creating application at backend and is used to created API’s.
  2. fs(file system): The fs (file system) module used to interact with file system like accessing file, reading content of file and writing to a file, FS library is an in-build NodeJS library to interact with system files.
  3. body-parser: The body-parser is middleware functionality used in Node.js applications usually used to parse incoming request bodies in a middleware before your handlers, and then allowing you to access request data in a more convenient way.
  4. crypto-js: Crypto-js is a node.js library basically used for data encryption and hashing technique it support algorithms such as AES,MD5-SHA-1, SHA-256 and more.
  5. path: The path module is used to get the file & directory paths in nodeJS.
  6. mongoose: Mongoose is a NodeJS Mongodb library that helps in communication with MongoDB database, it’s helps in creating schema model and to interact with MongoDB database server. Used to perform CRUD operation with mongodb database.
  7. multer: Multer is used to handle all the incoming file uploads, Multer is an middleware using which we can upload single and multiples files.

run below command to install all the above libraries into your nodejs project:

npm install express fs body-parser crypto-js path mongoose multer

NodeJS Project Structure for build cloud storage system

nodejs aws s3 bucket like service

Here in my node.js project I have create folder to give a proper structure to node project:

model: Here we have 2 database schema model i.e. user model & upload model.

middleware: In middleware folder will have functionality like user authentication using APIKEY & multer middleware that will help you in uploading files.

config: In this folder will have database connectivity configuration.

bucketFolder: is a root folder where user can create folders and upload files

routes: In router we will make use of express to create API routers that can perform event like Create a Bucket/Folder, Getting List of Bucket/Folder, Get list of files from particular bucket, upload file, download files and delete files.


API Routers created using Express routers

Below are the api route that will help user in performing event like:

  1. Creating a Bucket / Folder.
  2. Getting list of all bucket / Folder.
  3. Uploading Files to a Bucker / Folder.
  4. Getting list of Files from a particular bucket / Folder.
  5. Downloading Files from a Bucket.
  6. Deleting a file from a bucketing
  7. Deleting a bucket / Folder.

1. NodeJS API to Create a Folder

Video Tutorial

The below code will create a user desired folder. To achieve this we will make use of fs library with fs.mkdirSync(<folderName>) to create a folder. In below code first I am checking if folder exist with same name or no using fs.existsSync(), if not then use fs.mkdirSync then create.

const fs = require('fs');

// Create a Bucket 
router.post("/createFolderBucket", Auth.userAuthMiddleWare,async (req, res) => {
    const folderName = req.body.folderName;
    if (!folderName) {
        return res.json({ status: false, message: "Folder Name is Mandatory" });
    }
    const rootFolder = "bucketFolder";
    const folderpath = `${rootFolder}/${folderName}`;
    try {
        if (fs.existsSync(rootFolder)) {
            if (!fs.existsSync(folderpath)) {
                fs.mkdirSync(folderpath);
                return res.json({ status: true, success: "Directory created" });
            }
        } else {
            fs.mkdirSync(rootFolder);
            if (!fs.existsSync(folderpath)) {
                fs.mkdirSync(folderpath);
                return res.json({ status: true, success: "Directory/Folder created" });
            }
        }
        return res.json({ status: true, success: "Directory/Folder Already Exist" });
    } catch (error) {
        console.log(error);
    }
});

2. NodeJS API to get list of Folders

Video Tutorial

The below code will give us list of all folder, For this we will make use of fs.readdir() function to read files & folder exist within a given path and then we need to filter out and check if the file is directory or a file by using fs.statSync(filePath).isDirectory();.

const fs = require('fs');

// get Bucket List
router.get("/getAllFolderBucket", Auth.userAuthMiddleWare, async (req, res) => {
    //joining path of directory 
    const directoryPath = path.join('bucketFolder');
    
    //passsing directoryPath and callback function
    fs.readdir(directoryPath, (err, files) => {
        if (err) {
            console.error(err);
            return;
        }

        const directories = files.filter(file => {
            const filePath = path.join(directoryPath, file);
            return fs.statSync(filePath).isDirectory();
        });

        console.log(directories);
        return res.json({ status: true, success: directories });
    });
});

3. Node.JS API to Upload Any kind of file/document into a folder

Video Tutorial

The below api router has a ability to upload any kind of file into a folder, Here to upload a file we have made use of multer middleware that will upload a single file to a desired bucket/folder and the same uploaded file details(metadata) record is been stored into mongodb database.

const fs = require('fs');
const { upload } = require('../config/multerConfig')
const UploadModel = require('../model/uploads.model');

//Upload Files to a Bucket and store same to Mongo DB
router.post("/uploadFileInBucket", Auth.userAuthMiddleWare, upload().single("myFile"), async (req, res) => {
    if (req.file) {
        const filefullPath = req.file.destination + req.file.filename;
        const uploaded = new UploadModel({ userId: req.user._id, filename: req.file.filename, mimeType: req.file.mimetype, path: filefullPath });
        await uploaded.save();
        res.json({ status: true, success: "File Uploaded Successfully" });
    }
});

4. Getting list of all Files from a particular bucket / Folder.

Video Tutorial

The below code will give us list of all the files that exist in a folder, For this we will make use of fs.readdir() function to read files & folder exist within a given path and then we need to filter out the files by check if the file is a directory or a file by using fs.statSync(filePath).isFile().

// get list of all files from a Particular bucket
router.get("/getAllFilesFromParticularBucket", Auth.userAuthMiddleWare, async (req, res) => {
    try {
        const bucketName = req.body.bucketName;
        const directoryPath = path.join(`bucketFolder/${bucketName}`);
        fs.readdir(directoryPath, (err, files) => {
            if (err) {
                return res.json({ status: false, message: `${bucketName}, No Such Bucket Found` });
            }

            const allfiles = files.filter(file => {
                const filePath = path.join(directoryPath, file);
                return fs.statSync(filePath).isFile();
            });

            console.log(allfiles);
            return res.json({ status: true, filesList: allfiles });
        });
    } catch (error) {
        console.log("error------->>", error);
    }
});

5. Node.JS API to download a file from a bucket

Video Tutorial

The below API is but different, user can pass the folderName and fileName in API URL itself, and then the file will get downloaded from a directory by using fs.createReadStream with pipe response function.

//download a Files from a Bucket
router.get('/downloadFile/:filename/:folderName', Auth.userAuthMiddleWare, (req, res) => {

    const { filename, folderName } = req.params;
    const filePath = `bucketFolder/${folderName}/${filename}`;

    if (!fs.existsSync(filePath)) {
        return res.status(404).json({ message: 'File not found' });
    }
    res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
    const fileStream = fs.createReadStream(filePath);

    fileStream.pipe(res);
});

6. Node.JS API to delete a file from a folder

Video Tutorial

To delete any file from a folder in nodejs we make use of fs library unlink() function, that will simple delete a files.

// This will delete Files from a given Bucket/folder
router.post("/deleteFileBucket", async (req, res) => {
    const folderName = req.body.folderName;
    const fileName = req.body.fileName;
    if (!folderName) {
        return res.json({ status: false, message: "Folder Name is Mandatory" });
    }
    if (!fileName) {
        return res.json({ status: false, message: "File Name is Mandatory" });
    }
    const rootFolder = "bucketFolder";
    const folderpath = `${rootFolder}/${folderName}/${fileName}`;
    try {
        fs.unlink(folderpath, (err) => {
            if (err) {
                console.error(err);
                return;
            }
            console.log('File deleted successfully');
        });
        return res.json({ status: true, success: "File deleted successfully" });
    } catch (error) {
        return res.json({ status: false, success: error });
    }
});

7. Nodejs API to delete a folder

Video Tutorial

Note: the below api can only delete a folder is if it’s empty, if the folder is no empty then you need to first make it empty and then delete the folder.

To delete a folder we can make use of fs.rmdirSync() function, here you just need to pass folder path.

// Delete Folder/Bucket only if it Empty
router.post("/deleteFolderBucket", async (req, res) => {
    const folderName = req.body.folderName;
    if (!folderName) {
        return res.json({ status: false, message: "Folder Name is Mandatory" });
    }
    const rootFolder = "bucketFolder";
    const folderpath = `${rootFolder}/${folderName}`;
    try {
        if (fs.existsSync(rootFolder)) {
            if (fs.existsSync(folderpath)) {
                fs.rmdirSync(folderpath);
                return res.json({ status: true, success: "Directory Deleted" });
            }
        }
        return res.json({ status: false, success: "Directory Not Found" });
    } catch (error) {
        return res.json({ status: true, success: "Directory can't be deleted because it Not Empty" });
    }
});


Complete Source Code – Build cloud storage system like AWS using NodeJS

Clone the complete project from my github repository for free, please give a star for the repo.

Complete Playlist on create cloud storage system service using nodejs

https://www.youtube.com/playlist?list=PLGIDomk5-zo1mIKzW_M6oUoG5ZXL3mZ84

Dependency Injection in flutter using get it package

0
flutter dependencies injection
dependencies injection in flutter

Making an object’s dependencies, which are typically referred to as services, accessible through another object is a technique called dependency injection.

A quick search of the Dependency Injection in Flutter Community will give you a list of articles. All are very informative and offer libraries and service locators to implement Dependency Injection in flutter . This post will offer an alternative to implementing code and or annotations to supplying  DI in flutter app .

What Is Dependency Injection ?

Dependency Injection (DI) is a technique used to increase code reuse by reducing tight coupling between classes. The dependent classes and objects are supplied to or injected into your class rather than being created or instantiated by your class, maintaining a sort of external library to create and manage object creation in your project. These classes can now clearly concentrate on their actual application logic because you have decoupled object creation from your actual view and model. Furthermore, some of the classes that we construct are singletons as a result of you as well.


Why does Flutter use Dependency Injection?

so as to increase code reuse by reducing coupling between classes.

to design a class that is not dependent on anything else.

Additionally, it lessens the possibility that you will need to modify a class simply because one of its dependencies changed.
A class can become independent of its own dependencies by using dependency injection. Because every class can call any dependencies it requires, you can divide your application’s various components into more easily maintainable sections. By doing this, a loosely coupled application is produced, making it easier and quicker to fix bugs and add new features.


Advantages of dependency injection

Applications built with Flutter can benefit greatly from dependency injection. Some of the main advantages are as follows:

  1. The injection is offered everywhere.
  2. This method automatically tracks instances.
  3. Registration against interfaces is feasible.
  4. The streamlined setup code can be used.

Disadvantages of Dependency injection

While dependency injection has a number of advantages, there are also some potential disadvantages to take into account:

1): The top priority for dependency injection techniques is not disposing .

2) :It complies with lazy coding standards which makes development challenging  .

3): The fact that it is a global object adds to the complexity .

Overall, in spite of the fact that dependency injection can have many benefits. it may not always be the best choice but Before deciding whether dependency injection is the best course of action for your specific use case. It is necessary to consider its advantages and disadvantages.


Now implement the other side….. 

By developing a sample app, we will show you how to using  GetIt and Injectable to implement dependency injection in your  Flutter application . We will discuss the following :

Why use GetIt and Injectable?

This is a simple Service Locator for Dart and Flutter projects that includes some extra goodies that were heavily influenced by Splat. It can be used to access objects, such as those in your UI, instead of InheritedWidget or Provider.

Common Dependency Injection Techniques include:

i): The fundamental strategy we use to inject dependencies using constructors.

ii):  A class called Inherited Injection should extend from inherited widgets. (But passing objects without context becomes complex in this technique)

Now , implement Dependency Injection Through GetX

Installation

Step 1): Add this following dependencies project pubspec.yaml file:

get_it: ^any
get: ^any

Step 2): Then import it. after installing the package using the terminal command line:

flutter pub get

Step 3): import the file

import 'package:get_it/get_it.dart';

Step 4):  Create a locator.dart file :

Create a get_it instance

GetIt locator = GetIt();

Add this

import 'package:get_it/get_it.dart';

void setupLocator()
{
 /// doo here your logic
}

Step 5) : Use this given code and  set in the your project directory main.dart file to import locator and you can continue :

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

 When creating locators there are two ways to register class types using get_it . thorough explanation of this is provided below:

i) Factory: Each time your request for an instance of this class type is processed by the service provider, you will receive a fresh instance. This technique works well for registering view models that must execute the same logic upon startup or for models that must be fresh upon view opening.

ii) Singleton: You have two options for registering this method. You can either provide an implementation at the time of registration or a lama that will be called the first time your instance is requested. When this method is called, the locator will always return the single instance of your registered type that it has stored.

To register your classes, add a locator.dart file or use the code below:

void setupLocator()
{
// Add class here
locator.registerFactory(()=>AppInfo());
}

Step 7) : Next….. use the given code to add injectors or locators to the application screens:

var appInfo = locator<AppInfo>();

Usage

We have add dependency injection using getx

GetX Dependency Injection Techniques Have These Benefits:

  1. The streamlined setup code can be used.
  2. Registration against interfaces is feasible.
  3. Injection is accessible everywhere.
  4. This method automatically tracks instances.

To inject the object of the class use Get.put

When this method is used the dependency will load immediately and can be used directly by implementing below code 

 HomeController homeController = Get.put(HomeController());

Use “Get.find” to locate the controller in our application lifecycle following injection.

When multiple shared instances need to be updated separately, we can also use the Get.find tag property. Use the following code to accomplish this:

 HomeController homeNextController = Get.put(HomeController());

If the route using Get.put is removed from the navigation stack, the dependencies will also be deleted. Therefore, we must stop this from happening and maintain the dependencies in internal memory for the duration of the app session using permanent properties, as demonstrated below:

Get.put(Controller(), permanent: true);

The main three types of dependency injection are:

  • 1 Constructor Injection
  • 2 Property Injection
  • 3 Method Injection
1) Constructor Injection

a class’s function Object() is used to send dependencies to it ,  For an example  the class’s Object() function would accept the service as a parameter if the class required an instance of the authentication service.

class AuthenticationService {
  // Authentication service implementation
}
class UserRepository {
  AuthenticationService authService;
  UserRepository(this.authService);
  /// UserRepository implementation
}
2) Property Injection

Dependencies are set as properties of a class in the property injection method. For an example you would create a property for the service and set it when creating an object of the class .  if your class required an instance of an authentication service.

class AuthenticationService {
  ///  Authentication service implementation
}

class UserRepository {
  AuthenticationService authService;
  setAuthenticationService(AuthenticationService authService) {
    this.authService = authService;
  }
  /// UserRepository implementation
}
3) Service Locator

An object called a service locator keeps track of dependencies and gives users access to them. In this method  you would call up instances of dependencies as needed using a service locator.

class AuthenticationService {
  /// Authentication service implementation
}

class UserRepository {
  /// UserRepository implementation
}

class ServiceLocator {
  AuthenticationService getAuthenticationService() {
    return AuthenticationService();
  }

  UserRepository getUserRepository() {
    UserRepository repository = UserRepository();
    repository.setAuthenticationService(getAuthenticationService());
    return repository;
  }
}

Inside the global getIt object, we specified Auth as the actual implementation of AuthRepository.

With getIt, we can now access AuthRepository from anywhere in our UI code:

Future<void> _onClickSignIn() async {
  await getIt<AuthRepository>().signIn(email, password);
}
/// here add gorilllas app to appstate method


let’s start

Step 1): Create a UserData model :

class UserData {
  String name;
  String email;

  UserData({required this.name, required this.email});
}

Step 2): Create an interface for the UserRepository

abstract class UserRepository {
  Future<UserData> getUserData();
  Future<void> setUserData(UserData userData);
}

Step 3): The UserRepo known as UserRepository was injected . That uses  GetStorage in our application to store and retrieves the  user data.

import 'package:get_storage/get_storage.dart';
import 'user_data.dart';

class UserRepositoryImpl implements UserRepository {
  final storage = GetStorage();

  @override
  Future<UserData> getUserData() async {
    final data = storage.read('userData');
    if (data != null) {
      return UserData.fromJson(data);
    } else {
      return UserData(name: '', email: '');
    }
  }

  @override
  Future<void> setUserData(UserData userData) async {
    await storage.write('userData', userData.toJson());
  }
}

Step 4 ): Create a class that uses UserRepository to manage user data. Calling UserDataController now

import 'package:get/get.dart';
import 'package:get_it/get_it.dart';
import 'user_data.dart';
import 'user_repository.dart';

class UserDataController extends GetxController {
  final UserRepository _userRepository = GetIt.I<UserRepository>();
  Rx<UserData> userData = UserData(name: '', email: '').obs;

  @override
  void onInit() {
    super.onInit();
    getUserData();
  }

  Future<void> getUserData() async {
    userData.value = await _userRepository.getUserData();
  }

  Future<void> setUserData(UserData userData) async {
    await _userRepository.setUserData(userData);
    this.userData.value = userData;
  }
}

In this class we use GetIt inject the UserRepository instance and we use Rx<UserData> to make the user data observable .

Step 5): Establish dependencies Put it in the main Dart file:

import 'package:get_it/get_it.dart';
import 'user_repository.dart';
import 'user_repository_impl.dart';

void main() {
  GetIt.instance.registerLazySingleton<UserRepository>(() => UserRepositoryImpl());
  runApp(MyApp());
}

For this example code click here 👍

Conclusion

Flutter’s use of DI makes it simple to manage dependencies, testability, and provides a more scalable architecture. Dependencies can be easily swapped out during testing, mocked, or even have different implementations depending on the environment thanks to DI.

Overall, implementing DI in Flutter can result in cleaner, more maintainable code, aid in code separation and organization, and make it simpler to collaborate on bigger projects with multiple team members.

Is this a small example of dependency injection in flutter , you can modify this code by your needs.

Thanks for reading this article….. ❤️‍

Have a nice day…..

A Deep Dive into Flutter pdf package

0
flutter pdf

The PDF ( Portable Document Format) package is a  file format . software technology that enables reliable electronic document exchange and  display regardless of software, hardware and operating system. For many , different things, including electronic books, forms, manuals and PDF files are more used.

Programmers can create, edit, view and share PDF files with the use of the features and tools provided by the flutter PDF package.

Developers can work with PDF files in their Flutter applications thanks to the PDF package for Flutter, which is a collection of libraries. Developers can add annotations, images, and other components to PDF documents as well as create, read, and edit PDF files using the PDF package. Additionally, the package contains tools for rendering PDF files in Flutter programmers and for supporting zooming, panning, and scrolling inside PDF files. The PDF package for Flutter is a complete solution for working with PDF files in Flutter applications because it also supports security features like passwords and encryption.

Step 1): Configuring our pubspec.yaml

pdf: ^any

Step 2): installing the package

flutter pub get

Step 3): import the file

import 'package:pdf/pdf.dart';

Using the tools or features offered by the flutter  PDF package, users can create, edit, view, and share PDF files. Several significant features of the PDF package include:

Creation of PDF files:

The library enables programmers to create new PDF files , add pages with different page formats (like A4 size ), and embellish the pages with widgets like text, images, tables and charts etc.

/// Create a new PDF file
final pdf = pw.Document();

/// Add a new page in to the PDF document
pdf.addPage(
  pw.Page(
    pageFormat: PdfPageFormat.a4,
    build: (pw.Context context) {
      return pw.Center(
        child: pw.Text("PDF package explanation", style: pw.TextStyle(fontSize: 24)),
      );
    },
  ),
);

// Save the PDF document to disk
final bytes = await pdf.save();
final file = File('output.pdf');
await file.writeAsBytes(bytes);

With the help of the pdf library this code creates a new PDF file, adds a page, changes the page format to A4 size adds a centered text widget to the page and then save the PDF file to local storage under the name “pdfName.pdf.” In addition to supporting the addition of images, tables, charts, and annotations as well as fonts, colors, and styles, the pdf library provides many more features for working with PDF files.


Editing of PDF files:

// Open an existing PDF file
final bytes = File('input.pdf').readAsBytesSync();
final pdf = pw.Document().loadFromBytes(bytes);

// Get the first page of the PDF file
final page = pdf.pages[0];

// Modify the text on the first page of the PDF file
page.addText(
  pw.Text(
    'Modified text',
    style: pw.TextStyle(fontSize: 24),
  ),
);

// Save the modified PDF file to disk
final modifiedBytes = await pdf.save();
final modifiedFile = File('output.pdf');
await modifiedFile.writeAsBytes(modifiedBytes);

This code retrieves the first page of an existing PDF file from storage using the pdf library , modifies the text on that page and then saves the modified PDF file to storage with the name pdfName .pdf extention . The pdf library offers tools for adding and editing images, tables and annotations highlights , underlines etc…… as well as support for changing the font, color, and style.


Conversion of PDF files:

The Flutter pdf package also includes tools for converting PDF files to other formats like image, HTML or text etc……  Here is an example of code that turns a PDF file into an image using the pdf library:

/// Open an existing PDF file here
final bytes = File('input.pdf').readAsBytesSync();
final pdf = pw.Document().loadFromBytes(bytes);

/// Convert the PDF file to an image format
final image = await pdf.asImage(
  format: PdfPageFormat.a4,
  dpi: 300,
);

/// Save the image to storage
final pngBytes = await image.pngBytes;
final pngFile = File('output.png');
await pngFile.writeAsBytes(pngBytes);

The user can choose a PDF file have it converted file to an image and then see the image as a result of their selection in this code definition of a Flutter application with a single page. The PDF file is converted to a PNG image using the pdf library as Image method the result image is saved to a temporary directory in local storage  before being shown in the application .


Security features:

A number of security features are offered by the pdf package in Flutter to guard against unauthorized access and modification of PDF files. Encryption, password protection, and digital signatures are some of these security features.

Here show example of how to use Flutter pdf library to encrypt and password-protect a PDF file in flutter application :

To prevent unauthorized access, you can encrypt a PDF file with a password. An extensively used encryption standard, 128-bit AES encryption, is supported by the package.

pdf file can have set  various levels of permissions including printing , copying , editing, annotating etc . Both the user and the file owner can receive these permissions individually.

final _formKey = GlobalKey<FormState>();
  final _passwordController = TextEditingController();
  final _pdfController = TextEditingController();
  File _pdfFile;

  Future<void> _encryptPdf() async {
    // Open the PDF file
    final bytes = await _pdfFile.readAsBytes();
    final pdf = pw.Document().loadFromBytes(bytes);

    // Get the encryption parameters from the form
    final password = _passwordController.text;
    final userPerms = pw.Permissions(
      canPrint: true,
      canCopy: true,
      canModify: false,
      canAnnotate: true,
    );
    final ownerPerms = pw.Permissions(
      canPrint: true,
      canCopy: true,
      canModify: true,
      canAnnotate: true,
    );

    // Encrypt the PDF file with the specified password and permissions
    pdf.encrypt(
      userPassword: password,
      userPermissions: userPerms,
      ownerPassword: password,
      ownerPermissions: ownerPerms,
    );

    // Save the encrypted PDF file to disk
    final directory = await getTemporaryDirectory();
    final encryptedFile = File('${directory.path}/encrypted.pdf');
    await encryptedFile.writeAsBytes(pdf.save());

    // Display a dialog with the location of the encrypted file
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('PDF encrypted'),
        content: Text('The encrypted PDF file is located at:\n\n${encryptedFile.path}'),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
            },
            child: Text('OK'),
          ),
        ],
      ),
    );
  }

Annotation tools:

To highlight or annotate PDF documents, a variety of annotation tools are available in the Flutter PDF package. Several of the annotating tools included in the PDF package are as follows:

late PDFViewController _pdfViewController;

  void _addAnnotation() async {
    final page = await _pdfViewController.getCurrentPage();
    final point = await _pdfViewController.getPoint();

    await _pdfViewController.addTextAnnotation(
      page!,
      point!,
      "This is an example of a text annotation.",
    );
  }

OCR (Optical Character Recognition):

Text in scanned images or PDF files can be easily edited and searched thanks to OCR (Optical Character Recognition) technology. Using OCR, you can extract text from a PDF file for purposes such as editing, copying, and searching.

Here are the fundamental actions you can take:

1): Open the PDF file and read its content into a byte buffer using the Flutter dart:io library.

2): To extract the text from the PDF byte buffer, use a PDF parsing library like pdf or dart_pdf.

3): Remove any extraneous characters or formatting from the extracted text, such as page numbers, headers, and footers.

4): Depending on your needs, return the processed text as a string or list of strings.

To help you get started, here is some sample code:

import 'dart:io';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pdfwidgets;

void main() {
  /// Open the PDF file
  final file = File('path/to/pdf/file.pdf');
  final bytes = file.readAsBytesSync();

  /// Parse the PDF and extract the text
  final pdf = PdfDocument.openBytes(bytes);
  final pages = pdf.pages.map((page) => page.text).toList();

  /// Process the extracted text
  final processedPages = pages.map((page) {
    /// Remove any unwanted characters or formatting
    return page.replaceAll('\n', '').trim();
  }).toList();

  /// Print the processed text
  print("processedPages :: $processedPages");
}

Form filling and signing:

For many applications, the ability to fill out and sign forms in PDF files is a crucial component. Flutter’s PDF package includes tools for electronically filling out and signing PDF forms. This package makes it simple to create PDF forms, fill them out with user input, and add a digital signature. Checkboxes, radio buttons, and other form elements can also be added to PDF forms with the help of this package.

pdf.addPage(pw.Page(
  pageFormat: PdfPageFormat.a4,
  build: (context) {
    return pw.Center(
      child: pw.Form(
        child: pw.Column(
          children: [
            pw.Text('Name:'),
            pw.TextField(),
            pw.SizedBox(height: 20),
            pw.Text('Age:'),
            pw.TextField(),
            pw.SizedBox(height: 20),
            pw.Text('Gender:'),
            pw.RadioButtonGroup(
              options: ['Male', 'Female'],
            ),
            pw.SizedBox(height: 20),
            pw.Text('Country:'),
            pw.DropDown(
              items: ['USA', 'Canada', 'Mexico'],
            ),
            pw.SizedBox(height: 20),
            pw.Text('Comments:'),
            pw.TextField(),
          ],
        ),
      ),
    );
  }
));

Signature field can added using the pw.Signature widget provided by the pdf package.

pdf.addPage(pw.Page(
  pageFormat: PdfPageFormat.a4,
  build: (context) {
    return pw.Center(
      child: pw.Form(
        child: pw.Column(
          children: [
            pw.Text('Name:'),
            pw.TextField(),
            pw.SizedBox(height: 20),
            pw.Text('Age:'),
            pw.TextField(),
            pw.SizedBox(height: 20),
            pw.Text('Gender:'),
            pw.RadioButtonGroup(
              options: ['Male', 'Female'],
            ),
            pw.SizedBox(height: 20),
            pw.Text('Country:'),
            pw.DropDown(
              items: ['USA', 'Canada', 'Mexico'],
            ),
            pw.SizedBox(height: 20),
            pw.Text('Comments:'),
            pw.TextField(),
            pw.SizedBox(height: 20),
            pw.Text('Signature:'),
            pw.Signature(),
          ],
        ),
      ),
    );
  }
));

to obtain this example code, click here….


Conclusion

The PDF package can be used to create apps that run on both Android and iOS platforms making the development of cross platform software simple . The package includes support for multicolumn layouts , headers and footers and custom page sizes among other layout options for working with PDF files. Due to the package’s fast and effective PDF rendering capabilities, working with large PDF files doesn’t have to compromise performance.

Here is a brief description of a pdf package; modify it to suit your needs.

Thanks for reading this article…..

Have a beautiful day…… 

How to Create a New Branch in Git

0
How to Create New Branch in Git

We usually create a new branch in git repository, when we are working on a new project to be added into the codebase without affecting the current working code or when your current code has a bug and need to fix it on a testing server at such situation we simple create new branch git.

The best advantage in making a new git branch is that, we can alter our code & experiment with the codebase independently trial & error, without interfering with main codebase, then finally when testing is done and your git new branch work perfectly we can merge the changed of it to git main branch.

Additionally, By creating new branch in github repo allows your project team to freely test their own ideas & Implement new feature without the risk of breaking main branch codebase.


Git create branch

To make new branch in your github repository, run below commonds in root folder of your project:

git branch <branch-name>

Here, Replace ‘<branch-name>’, with a new branch name.

Example, I want to create a branch by my name “rajat-code”, use the below commands:

git branch rajat-code

This will create a branch by name “rajat-code”.

Note: The above cmd will simple create a new branch in git but will not automatically switch to new branch. To do so follow below step


git switch branch command

git checkout <branch-name>

Replace <branch-name> with you given new branch name.

Eg:

git checkout rajat-code

The 10 Best Programming Languages for AI Development

0
10 Best Programming Language for AI Development

The impact of AI on the globe has been far-reaching and unprecedented. Many individuals, particularly younger ones, don’t realize it because they assume AI has always existed in society. Around 37% of corporations and organizations now use AI. Recent years have seen the introduction of a wide range of algorithms, from specialized recommendation systems to interactive humanoid robots. Yet, the effects of these AI examples are limited to the global scale.

Artificial intelligence (AI) is used by businesses to improve production, management, and customer satisfaction, which is more relevant here. AI’s progress seems ideal, with its potential uses in areas such as analytical decision-making, automating, decreasing error rates, and data mining. The first step in developing AI is selecting the appropriate programming language.

Why Should You Employ AI for Your Upcoming Project?

AI aims to simplify everyday tasks like scheduling appointments, managing a home or workplace, or even driving a vehicle. About 51% of online retailers rely on AI to deliver a smooth customer experience. Therefore, picture a scenario where your tech is smart enough to anticipate and provide for your requirements. Doing this would make your every day more enjoyable and freer of worry and provide additional time to spend on yourself. 

In What Ways Does Artificial Intelligence Operate?

The information its users provide to an AI system is crucial to its success. There is an abundance of tech that uses AI. Around 77% of devices employ some AI system. The size of its error range is proportional to the reliability of these numbers. Regularly providing your AI system with sufficient and reliable data can increase its efficacy, dependability, and precision. The three cognitive abilities that AI acquires to improve its efficiency are:

best language for AI development
  • Procedures for Learning: It’s a kind of AI software that gathers pertinent information to create rules for turning raw data into valuable insights. Algorithms are the rules that tell computers what to do and how to do it systematically.
  • Mechanisms for Reasoning: The appropriate AI algorithm for accomplishing a task is identified throughout this programming procedure.
  • Procedures for Self-Correction: This branch of AI programming constantly adjusts algorithms to improve accuracy, resulting in reliable outcomes.

Top 10 Languages for Artificial Intelligence Development

AI programming computer image

Several languages are available for use in the creation of AI. The top 10 programming languages for creating AI and machine learning systems are the following:

Python

Python is the most often used language for AI development because of its accessibility and widespread use. It has several uses in networking, desktop software, the internet, science, data science, AI, and ML. It’s ready for AI development because of its extensive collection of libraries like  PyTorch, MXNet, Keras, Pybrain, TensorFlow, and Scikit-learn.

Python’s easy syntax is ideal for AI and NPL (Natural Language Processing) applications, and it also provides enhanced text processing tools, programming with modular layouts, and more. Python’s conciseness and clarity make it easy to pick up and master. In addition, there is a sizable community of dedicated users behind it.

Haskell

The winning features of Haskell are its speed and security. Haskell is a cutting-edge, completely functioning programming language with many practical applications in AI. Its more sophisticated features include type classes, which make type-safe operator overloading possible.

Lambda expressions, pattern matching, type classes, type polymorphism, and list comprehension are more characteristics. Haskell’s rich features make it well-suited for educational and professional use. Haskell is one of the most secure AI programming languages due to its adaptability and mistake-handling capability.

Lisp

From its inception in the 1960s, Lisp has seen extensive application in academia, particularly for studying natural languages, verifying theorems, and solving AI issues. Lisp was developed as a practical mathematical notation for programming, but AI programmers now widely use it.

Lisp is great for solving problems, iterating quickly, or creating dynamic software. The popular tools like Grammarly, Routinic, and DART were all developed using Lisp. Despite its flaws, Lisp remains a promising programming language for advancements in artificial intelligence.

R

The R Foundation for Statistical Computing maintains R, an open software platform with a programming language for statistical computation and graphic elements. Although not ideal for AI applications, this language excels in number-crunching. 

Complex procedures for expressing and analyzing numerical data are fundamental to the development of AI. R outperforms Python in this scenario as it is more adept at handling complicated mathematical equations. 

Java

Another language that is popular among AI developers because of its adaptability, friendliness, and wealth of resources. Java is not as quick as other programming languages but is robust and may be used in AI projects.

Importantly, it works on several platforms without constantly changing your code. Java can also create high-quality images. It is not necessary for you to be very concerned with the clarity of the AI graphics.

Prolog

Program in Logic, or Prolog for short, is another computer programming language. In 1972, a rule-based framework for the language was created. It finds most of its usage in computational linguistics and artificial intelligence projects.

Regarding jobs that need a database, natural language processing, and symbolic reasoning, Prolog is the preferred language! It’s the top pick for language support in artificial intelligence exploration.

Scala

Scala improves the efficiency, simplicity, and effectiveness of the coding process. Developers may find useful tools and libraries for working with Scala in the index called Scaladex. It’s compatible with the Java Virtual Machine (JVM) and facilitates the creation of intelligent applications.

Scala is a powerful programming language that is cross-platform with Java and JS and has many valuable features such as pattern matching, browser extensions, fast functions, and adaptable user interfaces. Scala has pleased experts in AI and is considered one of the top solutions for AI development.

Julia

This dynamic language was developed to provide superior performance in numerical analysis and computational research. Since MIT first released the language in 2012, Julia has gained popularity because of its high computing capability, rapid execution, and script-like syntax.

Scikitlearn.Jl, TensorFlow. Jl, Flux, Mocha. Jl and many more are just a few examples of machine learning components that have arisen in recent years to support this language.

C#

Another long-standing language that can still hold its own in artificial intelligence is C#. The language’s extreme adaptability is a significant factor, making it a good fit for demanding programs that need plenty of memory and CPU time. The AI model is best handled in production when written in C#, a low-level language.

C# is considered to be one of the best .NET frameworks. Many developers tends to use libraries like accord.NET and TenserFlow.NET to develop and integrate machine learning frameworks in C#. Therefore companies prefer to hire  .NET development company to leverage the best functionality of the .Net framework.

While it’s true that numerous profound machine learning frameworks are developed in C#, this fact is often overlooked by AI developers. In addition, C#’s efficiency and performance are top-notch since it translates user code into machine-readable code.

JavaScript

Most programmers nowadays utilize JavaScript to build more interactive and secure online applications. It is also an excellent language for creating AI. Since JavaScript provides developers unrestricted access to server-side and client-side processes, it simplifies the process of building AI software. This language ensures a brisk pace in creating AI, higher performance, and more safety.

JavaScript enables parallel processing and interaction with several source codes, including HTML and CSS. That’s an essential quality for advancing AI. Also, this programming language has a sizable community that may assist programmers. React.js, Underscore.js, and jQuery are a few JavaScript frameworks that make creating AI easier.

Conclusion

Incorporating AI into anything that impacts daily life marks the arrival of the technological future. AI has increased in popularity to enhance professional and personal endeavors. A surprising truth about AI is that just 34% of customers know they are encountering AI in some form or another.

Many languages are available to programmers, a boon for developers looking to improve AI software. The ideal language for oneself is the one in which you can express yourself effectively. If you are starting, choosing a language that makes the development process easier is essential since this will help you the most.