Home Blog Page 10

AWS Lambda Function to Stop, Start or Restart AWS Instance

0
Start, Stop or Restart EC2 Instance using Lambda Function
Start, Stop or Restart EC2 Instance using Lambda Function

In this article, Let’s check out What is AWS Lambda Function & How we can use Lambda function to restart the EC2 server server instance.

Video Tutorial

What is AWS Lambda Function?

The AWS Lambda Function is a service provided by Amazon Web Services(AWS) that is basically a server less computing service. Using Lambda function we can run code without managing any servers instance. Here instead of building a overall server infrastructure, you can keep you focus on developing a application’s function code that can we executed when an events occurs or triggers is hit.

Basically AWS Lambda function is a server less computing system, Languages supported are Node.JS, Python, Java, Go, Ruby,C#, PowerShell and custom runtimes.

How to create a Lambda Function in AWS console?

1. SignIn into AWS Console.

2. In search box above search “Lambda”

how to create a lambda function in aws

select it.

3. Click on “Create Function” and fill the form

how to create a lambda function in aws

Here select "Autor from scratch", give a name to function, In Runtime select the language maybe python, nodejs or any other which you prefer to write code on. I select Python 3.11.

The AWS Lambda function get’s created, here is where you need to write your code.

how to create a lambda function in aws

How to change lambda execution time

Usually when you execute a lambda function by default the function execution timeout is 3 sec, suppose your lambda function need more time to execute the whole code then your code will stop execution after 3 sec and you may see an warning “Task timed out after 3.00 seconds”, so you need to change or config lambda function execution timeout below are steps to change timeout.

in lambda function, Goto Configuration -> general configuration, click on Edit

how to change lambda function execution time

Now change AWS lambda function timeout as per your need

AWS lambda function timeout

Note: This is required because sometime the code might require more then 3 sec to fully execute, In our case we are going to write a lambda function that stop our EC2 instance and start it again so for this process our server need at least 3-5 minute to start fully.


Giving permission to lambda function to access EC2 instance

As we are implementing a lambda function that can communicate to EC2 instance and perform event like stop, start or restart the instance server from lambda function itself we need to give permission to access EC2 instance. below are the step:

1. In AWS Console, Top Search Box, search for IAM, Enter the service.

2. Now on side menu goto Roles > select lambda function roles as shown in below image

Next in Permission tab > Permissions policies > click on Add Permission > Attach Policy

Now in Other permissions policies search box, search for “EC2FullAccess”

aws roles add permission for lambda function

Check the Check box and click on Add Permission

AmazonEC2FullAccess add permission to Lambda function

Once you add the roles permission to full access EC2 instance, your lambda function will be able to fully control your EC2 instance.


Lambda Python Code to Stop, Start EC2 Instance

Code – python

import boto3
import time
def lambda_handler(event, context):
    
    ec2 = boto3.client('ec2')
    
    # Specify the instance IDs of the instances you want to start
    instance_ids = ['i-091182e12341c19fd'] // replace with your ec2 instanceID

    
    # Stop the instances
    response = ec2.stop_instances(InstanceIds=instance_ids)
    
    time.sleep(300)

    # Start the instances
    response = ec2.start_instances(InstanceIds=instance_ids)
    print("Started")
    
    return response

To run the code, click on Deploy Button then click on Test Button

how to run lambda function

Structure of Atom – html + css animation

0
structure of atom animation using html and css only
structure of atom animation using html and css only

This article is on creating Structure of Atom with animation effect only using html and css.

via GIPHY

HTML Explaination – Structure of a Atom

We have a division tags that represent the structure of our Atom, This further contain sub-divisions –nucleous and orbits.

The Nucleous class holds protons and neutrons in a form of row.

The Orbits class container multiple electron elements, which simple represent electrons orbiting the nucleus.

The show-info div tag show a icon or button when clicked or hoverd we can show more information on the page using css.

The Info div will show different components on the atom, Including Innder and outer shells, detainls about the nucleus.

Code

<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title> Structure of Atom </title>
  <link rel="stylesheet" href="./style.css">

</head>
<body>

<h1>Carbon</h1>
<div class="atom">
	<div class="nucleous">
		<div class="row">
			<div class="proton"></div>
			<div class="proton"></div>
			<div class="neutron"></div>
			<div class="neutron"></div>
		</div>
		<div class="row">
			<div class="neutron"></div>
			<div class="neutron"></div>
			<div class="proton"></div>
			<div class="proton"></div>
		</div>
	</div>
	<div class="orbits">
		<div class="electron"></div>
		<div class="electron"></div>
		<div class="electron"></div>
		<div class="electron"></div>
		<div class="electron"></div>
		<div class="electron"></div>
	</div>
</div>
<div class="show-info">i</div>
<div class="info">
	<div class="inner-shell">			
		<div class="info-particle">
			<h3>INNER SHELL</h3>
			<p><strong>2</strong> ELECTRONS</p>
		</div>
	</div>
	<div class="outer-shell">
		<div class="info-particle">
			<h3>OUTER SHELL</h3>
			<p><strong>4</strong> ELECTRONS</p>
		</div>
	</div>
	<div class="inner-nucleous">
		<div class="info-particle">
			<h3>NUCLEOUS</h3>
			<p><strong>6</strong> PROTONS</p>
			<p><strong>6</strong> NEUTRONS</p>
		</div>
	</div>
</div>

  <script src='https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.19.0/matter.min.js'></script>
</body>
</html>

CSS Code – Structure of Atom

The body of html is ensured that the atom animation happens at the centered with proper aligment.

The atom structure class defines the properties of the atom, including it’s dimensions and appearance.

Nucleus and Electron

The Nucleus and Electron particulars are core compoments of the atom animation effect, The .nucleus class defines the appearance of the nucleus, while the .electron class sets the properties for the electrons. The animation properties dictate the duration, timing function, and iteration count for the electron animation.

Electron Orbits

The electron orbits are defined using the .orbit1, .orbit2, and .orbit3 classes, each with their respective animation-name properties pointing to the keyframe animations orbit1, orbit2, and orbit3.

The @keyframes rule specifies the animation code for each orbit, detailing the transformation for the electrons around the atom. The rotate and translateX functions play a crucial role in creating the circular motion effect.

code

body {
	margin: 0;
	padding: 0;
	width: 100vw;
	height: 100vh;
	overflow: hidden;
	display: flex;
	align-items: center;
	justify-content: center;
	background: repeating-conic-gradient(#FFF4 0%, transparent .0002%, transparent .075%, transparent .65%), repeating-conic-gradient(#FFF2 0%, transparent .0004%, transparent 0.05%, transparent .495%), radial-gradient(circle at 50% 50%, #121212, #000);
	perspective: 100vmin;
}

body * {
	transform-style: preserve-3d;
}

*::before {
	box-sizing: border-box;
}

h1 {
	position: absolute;
	top: 4vmin;
	color: #fff;
	font-family: Arial, serif;
	font-weight: normal;
	font-size: 3.5vmin;
	margin: 0;
}

.atom {
	width: 50vmin;
	height: 50vmin;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 100%;
	transition: 0.4s ease 0s;
	cursor: zoom-in;
}

.atom:active {
	transform: scale3d(1.5,1.5,1.5);
}

.atom:before {
	content: "";
	width: 50vmin;
	height: 50vmin;
	position: absolute;
	background: radial-gradient(#913ab7 -50%, #fff0 50%);
	transform: translateZ(-6vmin);
	box-shadow: 
		0 0 5vmin -2vmin #cddc3920, 0 0 10vmin 0vmin #cddc3920, 
		0 0 10vmin 0vmin #39dcbe20, 0 0 10vmin 0 #cddc3920 inset, 
		0 0 25vmin 0 #39dcbe20 inset;
	border-radius: 100%;
	animation: orbit-cloud 3s ease 0s infinite alternate;
	opacity: 0.25;
}

@keyframes orbit-cloud {
	0% { filter: hue-rotate(0deg); }
	100% { filter: hue-rotate(50deg);}
}



/*** NUCLEOUS ***/

.nucleous {
	width: 16vmin;
	height: 16vmin;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 100%;
}

.row {
	border-radius: 100%;
	transform: rotateX(80deg);
	position: absolute;
	width: 40%;
	height: 40%;
	margin-top: -8vmin;
	left: 33%;
	display: flex;
	align-items: center;
	justify-content: center;
	transform: rotateX(80deg) rotate(180deg);
	animation: orbit-nucleous 3s linear 0s infinite;
}

.row:nth-child(1) div:before {
	content: "";
	position: absolute;
	width: 100%;
	height: 100%;
	border-radius: 100%;
	margin-top: -11vmin;
	background: red;
	background: radial-gradient(circle at 40% 60%, #fff0, 3vmin, #00000040 calc(3vmin + 1px) 100%), radial-gradient(circle at 28% 57%, #fff, 0.3vmin, #fff0 calc(0.3vmin + 1px) 100%), radial-gradient(circle at 37% 71%, #fff, 0.5vmin, #fff0 calc(0.5vmin + 1px) 100%), radial-gradient(circle at 40% 60%, var(--c2), 1.65vmin, #fff0 calc(1.65vmin + 1px) 100%) var(--c1);
}

.row:nth-child(2) {
	--znt: 1.3,1.3,1.3;
	margin-top: 0vmin;
	animation: orbit-nucleous3 3s linear 0s infinite;
}


@keyframes orbit-nucleous {
	0% { transform: rotateX(80deg) rotate(0deg); }
	100% { transform: rotateX(80deg) rotate(360deg);}
}

@keyframes orbit-nucleous3 {
	0% { transform: rotateX(80deg) rotate(0deg) scale3d(var(--znt)); }
	100% { transform: rotateX(80deg) rotate(360deg) scale3d(var(--znt)); }
}

.row div {
	--c1: #bc0003;
	--c2: #fa0001;
	width: 6vmin;
	height: 6vmin;
	border: 1px solid #0006;
	border-radius: 100%;
	background: 
		radial-gradient(circle at 40% 60%, #fff0, 3vmin, #00000040 calc(3vmin + 1px) 100%), 
		radial-gradient(circle at 28% 57%, #fff, 0.3vmin, #fff0 calc(0.3vmin + 1px) 100%), 
		radial-gradient(circle at 37% 71%, #fff, 0.5vmin, #fff0 calc(0.5vmin + 1px) 100%), 
		radial-gradient(circle at 40% 60%, var(--c2), 1.65vmin, #fff0 calc(1.65vmin + 1px) 100%) 
		var(--c1);
	position: absolute;
	top: -3vmin;
	animation: orbit-nucleous-particle 3s linear 0s infinite;
}

@keyframes orbit-nucleous-particle {
	0% { transform: rotateX(90deg) rotateY(360deg) scale3d(0.75, 0.75, 0.75); }
	100% { transform: rotateX(90deg) rotateY(0deg) scale3d(0.75, 0.75, 0.75);}
}

.row div.neutron {
	--c1: #082976;
	--c2: #124b9c;
}

.row div:nth-child(2) {
	top: calc(100% - 3vmin);
}

.row div:nth-child(3) {
	left: -3vmin;
	top: calc(50% - 3vmin);
}

.row div:nth-child(4) {
	left: calc(100% - 3vmin);
	top: calc(50% - 3vmin);
}



/*** ELECTRONS ***/

.orbits {
	position: absolute;
	width: 100%;
	height: 100%;
	border-radius: 100%;
	animation: orbit-spin 180s linear 0s infinite;
}

@keyframes orbit-spin {
	0% { transform: rotate(0deg); }
	100% { transform: rotate(360deg);}
}

.orbits:before, .orbits:after {
	content: "";
	position: absolute;
	width: 100%;
	height: 100%;
	border-radius: 100%;
	animation: orbit-spin 180s linear 0s infinite;
	border: 0.2vmin dotted #CDDC3980;
	filter: blur(1px);
	opacity: 0.5;
}

.orbits:after {
	width: 60%;
	height: 60%;
	top: 20%;
	left: 20%;
	animation-direction: reverse;
	animation-duration: 90s;
}

.electron {
	--pos: rotateY(0deg);
	--tim: 2s;
	position: absolute;
	width: 100%;
	height: 100%;
	box-shadow: -10px 5px 3px -5px #CDDC3920 inset, 10px 0px 3px -5px #CDDC3920;
	border-radius: 100%;
	transition: all 0.4s ease 0s;
	transform: rotateX(80deg) rotate(180deg);
	animation: orbit-electron var(--tim) linear calc(var(--tim) * -0.5) infinite;
}

@keyframes orbit-electron {
	0% { transform: rotateX(80deg) var(--pos) rotate(0deg); }
	100% { transform: rotateX(80deg) var(--pos) rotate(-360deg);}
}

.electron:before {
	--c1: #8BC34A;
	--c2: #CDDC39;
	width: 1vmin;
	height: 1vmin;
	content: "";
	position: absolute;
	border-radius: 100%;
	box-shadow: 0 0 9px 0px #CDDC39;
	border: 1px solid #fff8;
	left: calc(50% - 0.5vmin);
	top: -0.5vmin;
	background: 
		radial-gradient(circle at 40% 60%, #fff0, 3vmin, #00000040 calc(3vmin + 1px) 100%), 
		radial-gradient(circle at 45% 73%, #fff, 0.3vmin, #fff0 calc(0.3vmin + 1px) 100%), 
		radial-gradient(circle at 27% 58%, #fff, 0.5vmin, #fff0 calc(0.5vmin + 1px) 100%), 
		radial-gradient(circle at 40% 60%, var(--c2), 1vmin, #fff0 calc(1vmin + 1px) 100%), var(--c1);
	transform: rotateX(90deg);
	animation: orbit-electron-particle var(--tim) linear 0s infinite;
}

@keyframes orbit-electron-particle {
	0% { transform: rotateX(90deg) rotateY(-360deg); }
	100% { transform: rotateX(90deg) rotateY(0deg);}
}

.electron:nth-child(2) {
	--pos: rotateY(70deg);
	--tim: 1.535s;
}

.electron:nth-child(3) {
	--pos: rotateY(40deg);
	--tim: 1.875s;
}

.electron:nth-child(4) {
	--pos: rotateY(110deg);
	--tim: 1.275s;
}

.electron:nth-child(n+5) {
	width: 67%;
	height: 67%;
	left: 18%;
	top: 18%;
}

.electron:nth-child(5) {
	--pos: rotateY(140deg);
	--tim: 1.125s;
}

.electron:nth-child(6) {
	--pos: rotateY(25deg);
	--tim: 1s;
}



/*** INFO ***/

.info {
	position: absolute;
	width: 98vw;
	height: 60vmin;
	z-index: -1;
	font-family: Arial, serif;
	display: flex;
	align-items: center;
	justify-content: center;
}

.inner-shell, .outer-shell, .inner-nucleous {
	width: 20.5vmin;
	height: 12vmin;
	position: absolute;
	display: flex;
	align-items: center;
	justify-content: flex-end;
	opacity: 0.05;
	top: 40vmin;
	color: #fff;
	margin-right: 80vmin;
}

.inner-shell {
	margin-top: 0.95vmin;
}

.outer-shell {
	top: 10vmin;
	margin-right: 83.5vmin;
}

.info > div:before {
	content: "";
	position: absolute;
	width: 15vmin;
	height: 15vmin;
	border: 0.25vmin solid #fff0;
	border-left: 0.25vmin dotted #fff;
	border-radius: 100% 0 0 0;
	transform: rotate(-45deg);
	right: -25vmin;
	margin-top: -33vmin;
}

.info > div.outer-shell:before {
	transform: rotate(0deg);
	margin-top: 2vmin;
	right: -30vmin;
	height: 25vmin;
	width: 25vmin;
	clip-path: polygon(0 50%, 100% 100%, 100% 100%, 0% 98%);
}

.inner-nucleous {
	margin-left: 83vmin;
	margin-right: 0 !important;
	top: 19vmin !important;
	height: 17.5vmin !important;
}

.inner-nucleous:before {
	transform: rotate(155deg) !important;
	left: -34.125vmin;
	margin-top: 11vmin !important;
}

.inner-shell:after, .outer-shell:after, .inner-nucleous:after {
	content: "";
	position: absolute;
	width: 15vmin;
	height: 0;
	right: -14.5vmin;
	margin-top: -18vmin;
	z-index: 333;
	border-top: 0.25vmin dotted #fff;
	transform: rotate(-23deg);
}

.outer-shell:after {
	right: -6vmin;
	margin-top: 13.1vmin;
	transform: rotate(14deg);
	width: 6vmin;
}

.inner-nucleous:after {
	transform: rotate(0deg);
	left: -21.5vmin;
	margin-top: 2.75vmin;
	width: 21.5vmin;
}


.info-particle {
	position: absolute;
	width: 20vmin;
	height: 11.5vmin;
	left: 0;
	top: 0;
	border: 0.25vmin dotted #fff;
	border-radius: 0.2vmin;
}

.inner-nucleous .info-particle {
	height: 17.25vmin;
}

.inner-shell:hover,
.outer-shell:hover,
.inner-nucleous:hover{
	opacity: 1;
}



h3 {
	margin: 1vmin 0 1.25vmin;
	font-size: 1.9vmin;
	font-weight: normal;
	text-align: center;
	border-bottom: 0.25vmin dotted #fff;
	padding-bottom: 0.75vmin;
}

p {
	text-align: left;
	font-weight: normal;
	margin: 1vmin 0 3vmin -2.75vmin;
	font-size: 1.5vmin;
	padding-left: 5vmin;
}

p strong {
	font-size: 2.5vmin;
}

p:before {
	--c1: #8BC34A;
	--c2: #CDDC39;
	content: "\2212";
	position: absolute;
	width: 3vmin;
	height: 3vmin;
	border-radius: 100%;
	margin-left: -3.85vmin;
	background: radial-gradient(circle at 45% 45%, var(--c2), 1vmin, #fff0 calc(1vmin + 5px) 100%), var(--c1);
	box-shadow: 0 0 0.5vmin 0 #fff, 0 0 0.1vmin 0.15vmin #fff;
	color: #222;
	text-shadow: 1px 1px 2px #fff, -1px 1px 2px #fff, 1px -1px 2px #fff, -1px -1px 2px #fff;
	font-size: 3vmin;
	line-height: 3.15vmin;
	text-align: center;
}

p:after {
	content: "( NEGATIVE CHARGE )";
	position: absolute;
	bottom: -1.5vmin;
	left: 0;
	font-size: 1vmin;
	width: 100%;
	text-align: center;
}

.inner-nucleous p:before {
	--c1: #bc0003;
	--c2: #fa0001;
	content: "+";
}

.inner-nucleous p + p:before {
	--c1: #082976;
	--c2: #124b9c;
	content: "";
}

.inner-nucleous p:after {
	content: "( POSITIVE CHARGE )";
}
.inner-nucleous p + p:after {
	content: "( NO CHARGE )";
}


body:has(.outer-shell:hover) .atom .orbits .electron:nth-child(n+5),
body:has(.outer-shell:hover) .atom .nucleous {
	opacity: 0.15;
}

body:has(.inner-shell:hover) .atom .orbits .electron:nth-child(-n+4),
body:has(.inner-shell:hover) .atom .nucleous {
	opacity: 0.15;
}

body:has(.inner-nucleous:hover) .atom .orbits .electron {
	opacity: 0.15;
}

.show-info:hover + .info > div {
	opacity: 0.9;
}

.show-info {
	position: absolute;
	bottom: 4vmin;
	font-size: 3.5vmin;
	color: #fff;
	font-weight: bold;
	border: 0.25vmin solid #ffffffc9;
	width: 5vmin;
	height: 5vmin;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 100%;
}

.show-info:hover {
	color: #111;
	background: #fff;
	border-color: #111;
}


/*** PORTRAIT ***/

@media only screen and (orientation: portrait) {

	.info {
		height: 98vh;
	}

	.inner-nucleous {
		margin-left: 0vmin !important;
		margin-right: 0 !important;
		top: calc(50% + 32vmin) !important;
	}

	.inner-nucleous:before {
		transform: rotate(247deg) !important;
		left: -1.125vmin;
		margin-top: -75vmin !important;
	}

	.inner-nucleous:after {
		transform: rotate(90deg);
		left: -1.5vmin;
		margin-top: -41.25vmin;
		width: 23vmin;
	}

	h3 {
		font-size: 2.5vmin;
	}

	p {
		font-size: 2vmin;
	}

	p:after {
		font-size: 1.65vmin;
	}

	.info > div.outer-shell {
		margin-top: calc(50vh - 53.5vmin);
		margin-right: 47.5vmin;
	}

	.outer-shell:after {
		right: -4.5vmin;
		margin-top: 17.75vmin;
		transform: rotate(60deg);
	}

	.info > div.outer-shell:before {
		transform: rotate(52deg);
		margin-top: 33vmin;
		right: -28vmin;
	}

	.info > div.inner-shell {
		margin-right: -36vmin;
		margin-top: calc(50vh - 84vmin);
	}
	
	.inner-shell:after {
		width: 14vmin;
		right: 15.25vmin;
		margin-top: 25vmin;
		transform: rotate(105deg);
	}
	
	.inner-shell:before {
		transform: rotate(80deg) !important;
		right: 14vmin !important;
		margin-top: 51vmin !important;
	}

}

Conclusion

Implementing CSS to simple HTML page will enhance overall visual appearances of the web page. With the CSS snippet code provided above to build a super structure of atom animation, you can experiment and build upon this atom animation by making some changed into the code and add your own login, you can also exploring different properties & keyframe variations to create a more intricate and realistic representation of atomic structures.

Flutter Cupertino Timer Picker example with source code

0
FLUTTER CUPERTINO TIMER PICKER
FLUTTER CUPERTINO TIMER PICKER

Cupertino Timer Picker is IOS style timer picker in flutter, that allows user to search a duration of time or a time interval. In this Flutter Article let’s learn how to implement CupertinoTimerPicker in flutter with complete source code.

If you’re looking for a Cupertino-style timer picker i.e ios style time picker, then flutter provide a Timer Picker widget in Material Design class named CupertinoTimerPicker Here’s a basic example of how you can create a Cupertino-style timer picker:

We can make use of showCupertinoModalPopup widget to show a popup from the bottom of the screen.

Video Tutorial

Creating the Timer Picker Widget:

We have a function _showTimerPicker that open a popup at the bottom of the screen and displays the Timer Picker when a user press on a button to select a time duration user can select time in hours, minutes and seconds, To show type of mode that i.e. hms we can make use of mode property from CupertinoTimerPicker widget.

snippet – CupertinoTimerPacker Widget constructor

CupertinoTimerPicker(
{
 Key? key,
 CupertinoTimerPickerMode mode = CupertinoTimerPickerMode.hms,
 Duration initialTimerDuration = Duration.zero,
 int minuteInterval = 1,
 int secondInterval = 1,
 AlignmentGeometry alignment = Alignment.center,
 Color? backgroundColor, 
 double itemExtent = _kItemExtent, 
 required ValueChanged<Duration> onTimerDurationChanged
}
)

Handling Timer Selection and displaying selected time in Text Widget

The selected duration is stored in the selectedDuration variable initially it will be 0 for hours,minutes and seconds duration, When the user selects a new duration from Cupertino Timer Picker, the onTimerDurationChanged callback is triggered which has callback duration value selected using which we can update the selectedDuration using setState to reflect the user’s selection.

Source Code – CupertinoTimerPicker Flutter

Output

flutter cupertinotimerpicker
import 'package:flutter/cupertino.dart';
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',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(

        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  Duration selectedDuration = Duration(hours: 0,minutes: 0,seconds: 0);

  void _showTimerPicker(BuildContext context){
    showCupertinoModalPopup(
        context: context,
        builder: (BuildContext context){
          return Container(
            height: 200,
            color: CupertinoColors.white,
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [CupertinoButton(child: Text("DONE"), onPressed: (){
                    Navigator.of(context).pop();
                  })],
                ),
                Expanded(
                  child: CupertinoTimerPicker(
                     mode: CupertinoTimerPickerMode.hms,
                      initialTimerDuration: selectedDuration,
                      onTimerDurationChanged:  (Duration duration){
                       setState(() {
                         selectedDuration = duration;
                       });
                      }
                  ),
                )
              ],
            ),
          );
        }
        );
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text('Selected Time ${selectedDuration.inHours} hours, ${selectedDuration.inMinutes % 60} mins, ${selectedDuration.inSeconds % 60} sec,'),
          SizedBox(height: 15,),
          ElevatedButton(onPressed: (){_showTimerPicker(context);}, child: Text("Show Time Picker"))
        ],
      ),),
    );
  }
}

Conclusion: This article introduced you to the Flutter Cupertino Timer Picker and showed you how to implement Time Picker in your flutter app in IOS style UI. You can further customize it to match the style of your app and use it to collect time-related input from your users.

References and Resources:

Related Article

Bottom Popup Cupertino action sheet flutter

easiest way to implement image picker in flutter

Date Time Picker in Flutter

File Picker in flutter

Google apis utilize in flutter

0
FLUTTER GOOGLE API
FLUTTER GOOGLE APIS

Hello guys, Welcome to Proto Coders Point. In this Flutter Article we discuss about Google apis Implement in flutter.

Examples of user-data APIs include Calendar, Gmail, and YouTube. 

Note: The only APIs you should use directly from your Flutter project are those that access user data via Google authentication. APIs that require service accounts should not be used directly from a Flutter application.

Direct use of service account-required APIs from a Flutter application is not advised. This necessitates the use of your application’s insecure shipping service credentials. We advise building an intermediary service in order to leverage these APIs.

Here describe use google api in flutter

Google APIs in flutter

Step 1 : Select the preferred API

The package’s API is listed on googleapis as a distinct Dart library using the name_version format. 

For an example let’s take youtube_v3 as an illustration.

In addition to being the class you must instantiate (see step 3), the Api class also exposes the scopes that stand for the permissions required to utilize the API. You can find the scopes available by looking under the Constants section of the YouTubeApi class. Use the youtubeReadonlyScope when authenticating the user to ask for permission to merely read an end-user’s YouTube data.

Import this library

import 'package:googleapis/youtube/v3.dart';

Step 2 : Turn on the API.

You need a Google project and an account on Google in order to access Google APIs. Additionally, you must turn on the desired API.

Using the console, enable an API for a project:

1) Visit the API Library for the Google Cloud console.

2) Choose the project you want to utilize from the list of projects.

3) Choose the API you want to activate from the API Library. Use the search bar and/or the filters if you need assistance finding the API.

4) Click ENABLE on the API page.


Step 3: Use the necessary scopes to authenticate the user

Users can authenticate with their Google identity by using the google_sign_in package. For each platform you want to support, you must configure sign-in.

Dependencies Within pubspec.yaml

dependencies:
  google_sign_in: 
  googleapis: 
import 'package:google_sign_in/google_sign_in.dart';

The desired permissions are supplied when the GoogleSignIn class is instantiated, as was covered in the previous section.

final _googleSignIn = GoogleSignIn(
  scopes: <String>[YouTubeApi.youtubeReadonlyScope],
);

To enable user authentication , adhere to the directions given by package:google_sign_in.

You must get an authenticated HTTP client after completing your authentication.


Step 4: Obtain an HTTP client that is authorized.

A GoogleSignIn extension method called authenticatedClient is offered by the extension_google_sign_in_as_googleapis_auth package.

import 'package:extension_google_sign_in_as_googleapis_auth/extension_google_sign_in_as_googleapis_auth.dart';

OnCurrentUserChanged can be heard. You can design a client that is authorized if the event value is not null.

var httpClient = (await _googleSignIn.authenticatedClient())!;

When calling Google API classes, this Client instance already has the required credentials.


Step 5: Make the desired API class and use it.

Create the desired API type using the API, then call the methods, like in:

var youTubeApi = YouTubeApi(httpClient);

var favorites = await youTubeApi.playlistItems.list(
  ['snippet'],
  playlistId: 'LL',
);

The principles discussed on this page have a working implementation in the extension_google_sign_in_as_googleapis_auth example. We appreciate you joining us on a flutter journey! I hope you succeeded in finding what you sought.

Working with BLE devices in Flutter, Get List of BLE and Connect it.

0
Bluetooth Low Energy (BLE) In Flutter
Bluetooth Low Energy (BLE) In Flutter

In this flutter article, I’m excited to share an overview/baisc of what I have learnt whileworking with BLE in flutter application will provide you with flutter BLE code example with practical code simple, This flutter article on BLE might be a game changer.

Working with (Bluetooth Low Energy) BLE devices in flutter

Video Tutorial – BLE SCANNER

Flutter Blue Plus

A most popular package to work with Bluetooh Device in flutter is flutter_blue_plus package that provides Bluetooth Low Energy (BLE) functionality by using this package we can scan nearby bluetooth devices, connect with them & communicate with them.

Here is a step by step guide on how to work with BLE devices in flutter using flutter_blue_plus package.

Firstly we need to add BLE package into our flutter project follow below steps

1. Open pubspec.yaml file and under dependence section add

dependencies:
  flutter_blue_plus: ^1.16.2

2. Once package added you need to run below cmd to download the package as external dependencies

flutter pub get

3. To use flutter blue plue you need to import where required

import 'package:flutter_blue_plus/flutter_blue_plus.dart';

Note:- Make sure you ask app users to accept bluetooth usage permission by prompt. Once users accepts the permission, you can start using mobile bluetooth into you flutter application.

Scan from BLE devices

Below is a snippet code to scan nearby BT devices

FlutterBluePlus flutterBlue = FlutterBluePlus.instance;

// Listens to BLE devices
flutterBlue.scanResults.listen((results){

// Hanlde discovered ble devices here

});

Connect to the devices

Once you find the available devices nearby you can connect to that particular devices using below method.

void connectToDevice(BluetoothDevice device) async{
    await device.connect();
}

Discover Services list

Don you know? each BLE devices has list of service that the device can provide, by connecting to in we can discover the list of services it has in it.

To fetch all the list of services that device has use below snippet code.

final services await device.discoverServices();

BLE Characteristics

Each services in BLE devices has list of it own characteristics, which is used to communicate with devices based on how it been manufactured. Fore Example:- Generic Access Services has list of BLS characteristics such as device name, MAC address etc.

Below is snippet code to list out characteristic of a services

for(var service in services){

  List<BlueToothCharacterictic> characteristics = service.characteristics;

}

Read Characteristics in BLE devices

Reading charactericistic retrive data from BT devices.

Create a Bluetooth Charactericistic Object then use read() method to perform read operation make sure to use await as read() is a asynchronous nature.

Snippet

BlueToothCharacterictic characteristics;

List<int> value = await characteristics.read();

//handle the value as needed

print(`Read Value: ${value.toString()}`);

Write Characteristics in BLE devices

Sending data to BLE devices to done by using write characteristics, We make use of write() methods make sure you use await with write() method.

You need to prepare the data to be sent as alist of integers, After the write operation you can listen for notification just to confirm that write was successful.

List<int> dataToSend = [0x01,0x02,0x03];

//write the data to characteristic
await characteristics.write(dataToSend);

Flutter BLE Scanner

Below is a source code, just an example how to implement BLE Scanner into Flutter Application

code

add dependencies in pubspec.yaml file

  flutter_blue:
  get: ^4.6.5
  permission_handler:

ble_controller.dart

The below Code have 2 main methods, One for scanning near by BLE ( Bluetooth Devices ) and another method is used for connecting to BLE devices.

import 'package:flutter_blue/flutter_blue.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';

class BleController extends GetxController{

  FlutterBlue ble = FlutterBlue.instance;
  
// This Function will help users to scan near by BLE devices and get the list of Bluetooth devices.
  Future scanDevices() async{
    if(await Permission.bluetoothScan.request().isGranted){
      if(await Permission.bluetoothConnect.request().isGranted){
        ble.startScan(timeout: Duration(seconds: 15));

        ble.stopScan();
      }
    }
  }

// This function will help user to connect to BLE devices.
 Future<void> connectToDevice(BluetoothDevice device)async {
    await device?.connect(timeout: Duration(seconds: 15));

    device?.state.listen((isConnected) {
      if(isConnected == BluetoothDeviceState.connecting){
        print("Device connecting to: ${device.name}");
      }else if(isConnected == BluetoothDeviceState.connected){
        print("Device connected: ${device.name}");
      }else{
        print("Device Disconnected");
      }
    });

 }

  Stream<List<ScanResult>> get scanResults => ble.scanResults;

}

main.dart

import 'package:ble_scanner_app/ble_controller.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:get/get.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(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text("BLE SCANNER"),),
        body: GetBuilder<BleController>(
          init: BleController(),
          builder: (BleController controller)
          {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  StreamBuilder<List<ScanResult>>(
                      stream: controller.scanResults,
                      builder: (context, snapshot) {
                        if (snapshot.hasData) {
                          return Expanded(
                            child: ListView.builder(
                                shrinkWrap: true,
                                itemCount: snapshot.data!.length,
                                itemBuilder: (context, index) {
                                  final data = snapshot.data![index];
                                  return Card(
                                    elevation: 2,
                                    child: ListTile(
                                      title: Text(data.device.name),
                                      subtitle: Text(data.device.id.id),
                                      trailing: Text(data.rssi.toString()),
                                      onTap: ()=> controller.connectToDevice(data.device),
                                    ),
                                  );
                                }),
                          );
                        }else{
                          return Center(child: Text("No Device Found"),);
                        }
                      }),
                  SizedBox(height: 10,),
                  ElevatedButton(onPressed: ()  async {
                    controller.scanDevices();
                    // await controller.disconnectDevice();
                  }, child: Text("SCAN")),

                ],
              ),
            );
          },
        )
    );
  }
}

building ble bluetooth scanner app in flutter

Conclusion

In this article, we learnt basic of BLE in flutter like how to discover list of BLE devices nearby, connecting to BLE Devices fetching services characteristic , reading & writing to device protocal in flutter application using flutter_blue_plus package.

Build a simple Express server – JS Express

0
build express js server in nodejs
build express js server in nodejs

Express.js in JavaScript. The Express.js is the most popular web framework used for building web applications and APIs in Node.js Project. In this article we will learn how to create express server with nodejs. Before you start, make sure you have Node.js installed on your system. If not, you can download it from the official website: https://nodejs.org/

1. Setup Node Project

Create a folder named express-server open the folder in your favorite code Editor (VSCode), then run below cmd to make it a Node Project.

#initialize a Node Project

npm init -y

This cmd will convert a normal folder into a node project by creating package.json file it holds your project meta-data.


2. Create a server file

In root directory of project, create a file by name index.js.

Now to make a Express Server application we need to download & install Node Express Module into the project.

Run below cmd to install ExpressJS

npm install express

now import it on top on index.js file to create Node Express Application

const express = require('express');

//create express app
const app = express();

3. Add Middleware

In our Node Project, Let’s use 2 middleware

  1. One is to parse incoming request with JSON payloads.
  2. Second is to parse incoming request with URL-encoder payloads
const express = require('express');
const app = express();

// parse incoming request to JSON payloads.
app.use(express.JSON());

//parse incoming request with URL-encoding 
app.use(express.urlencoded({extended:true});

4. Create an API router

Now lets create a root API that will send JSON data response whenever there is a request to root api.

app.get('/',(req,res)=>{

res.status(200).json({message:"API CALLED..!"})

});

5. Creating Express Server & Listen for server

Now let’s make a server to listen to a particular port may be let’s say post 3000 address i.e http://localhost:3000/

const port = 3000;

app.listen(port,()=>{
   console.log("Server listening to port 3000");
});

6. Start a server

To start Node Express Server, Open terminal/cmd prompt & run node index.js be being in root directory of project.

node index.js


7. Make a API request

Visit http://localhost:3000/ in your browser to see the API response.


Related Article

Books Directory Project wirh NodeJS – CRUD operation using Mongoose MongoDB

How does MERN Stack Work