AWS Lambda to auto start stop Ec2 instance on schedule using python and boto3

AWS EC2 Start Stop with boto3

AI Dashboard is available on the Web, Apple, Google, and Microsoft, PRO version

AWS Lambda to auto start stop Ec2 instance on schedule using python and boto3

Use this lambda function to auto start stop all Ec2 instances based on schedule from tags.

aws ec2 auto start stop lambda


#Auto Shutodown - Start EC2 instances based on tags
import boto3
import os
import json
import croniter
import datetime
# Enter the region your instances are in. Include only the region without specifying Availability Zone; e.g., 'us-east-1'
region = 'us-west-2'

EC2_STATUS_CODE_RUNNING = 16
EC2_STATUS_CODE_STOPPED = 80

Get 20% off Google Google Workspace (Google Meet) Standard Plan with  the following codes: 96DRHDRA9J7GTN6
Get 20% off Google Workspace (Google Meet)  Business Plan (AMERICAS) with  the following codes:  C37HCAQRVR7JTFK Get 20% off Google Workspace (Google Meet) Business Plan (AMERICAS): M9HNXHX3WC9H7YE (Email us for more codes)

Active Anti-Aging Eye Gel, Reduces Dark Circles, Puffy Eyes, Crow's Feet and Fine Lines & Wrinkles, Packed with Hyaluronic Acid & Age Defying Botanicals

def lambda_handler(event, context):
ec2 = boto3.client(‘ec2’, region_name=region)


AI Unraveled: Demystifying Frequently Asked Questions on Artificial Intelligence (OpenAI, ChatGPT, Google Bard, Generative AI, Discriminative AI, xAI, LLMs, GPUs, Machine Learning, NLP, Promp Engineering)

#auto_start_stop_tag = ‘tc:uptime_schedule_gmt’
auto_start_tag = ‘tc:start_time_schedule_gmt_24h_format’
auto_shutdown_tag = ‘tc:shutdown_time_schedule_gmt_24h_format’

instances_to_shutdown = []
instances_to_start = []
# Query ec2 machines for auto_start_stop_tag,
#instances_with_schedules = get_instance_schedules(auto_start_stop_tag)
instances_with_start_schedules = get_instance_schedules(auto_start_tag)
instances_with_shutdown_schedules = get_instance_schedules(auto_shutdown_tag)
print(“instances_with_start_schedules: %s” % instances_with_start_schedules)
print(“instances_with_shutdown_schedules: %s” % instances_with_shutdown_schedules)

If you are looking for an all-in-one solution to help you prepare for the AWS Cloud Practitioner Certification Exam, look no further than this AWS Cloud Practitioner CCP CLF-C02 book

for instance_id, values in instances_with_start_schedules.items():
now = datetime.datetime.now()
print(“now: %s” % now)
iterator = croniter.croniter(values[‘Schedule’], now)
next_run_time = iterator.get_next(datetime.datetime)
print(“next_run_time: %s” % next_run_time)
duration_until_next_run_time = next_run_time – now
print(“duration_until_next_start_time: %s” % duration_until_next_run_time)
duration_of_one_hour = datetime.timedelta(hours=1)

if duration_until_next_run_time <= duration_of_one_hour and values[‘State’][‘Code’] == EC2_STATUS_CODE_STOPPED: print(“true”) print(“instance_to_stop.append(%s)” % instance_id) instances_to_start.append(instance_id) for instance_id, values in instances_with_shutdown_schedules.items(): now = datetime.datetime.now() print(“now: %s” % now) iterator = croniter.croniter(values[‘Schedule’], now) next_run_time = iterator.get_next(datetime.datetime) print(“next_run_time: %s” % next_run_time) duration_until_next_run_time = next_run_time – now print(“duration_until_next_shutdown_time: %s” % duration_until_next_run_time) duration_of_one_hour = datetime.timedelta(hours=1) if duration_until_next_run_time <= duration_of_one_hour and values[‘State’][‘Code’] == EC2_STATUS_CODE_RUNNING: print(“instance_to_shutdown.append(%s)” % instance_id) instances_to_shutdown.append(instance_id) if len(instances_to_shutdown) > 0:
ec2.stop_instances(InstanceIds=instances_to_shutdown)
print(‘stopped your instances: ‘ + str(instances_to_shutdown))
send_shutdown_notification(instances_to_shutdown, “STOPPED”)

if len(instances_to_start) > 0:
ec2.start_instances(InstanceIds=instances_to_start)
print(‘started your instances: ‘ + str(instances_to_start))
send_start_notification(instances_to_start, “STARTED”)

def send_shutdown_notification(instances, event):
instances_json_object = {“instances”:instances, “event”:event}
instances_json_string = json.dumps(instances_json_object)
instances_json_bytes = instances_json_string.encode(‘utf-8’)

lambda_arn = os.environ[‘LAMBDA_NOTIFICATION_SHUTDOWN_ARN’]
lambda_client = boto3.client(“lambda”)
lambda_client.invoke(
FunctionName=lambda_arn,
InvocationType=’Event’,
LogType=’None’,
Payload=instances_json_bytes
)

Djamgatech: Build the skills that’ll drive your career into six figures: Get Djamgatech.

def send_start_notification(instances, event):
instances_json_object = {“instances”:instances, “event”:event}
instances_json_string = json.dumps(instances_json_object)
instances_json_bytes = instances_json_string.encode(‘utf-8’)

lambda_arn = os.environ[‘LAMBDA_NOTIFICATION_START_ARN’]
lambda_client = boto3.client(“lambda”)
lambda_client.invoke(
FunctionName=lambda_arn,
InvocationType=’Event’,
LogType=’None’,
Payload=instances_json_bytes
)

def get_instance_schedules(tag_name):
# When passed a tag key, tag value this will return a list of InstanceIds that were found.

ec2client = boto3.client(‘ec2’)

response = ec2client.describe_instances(
Filters=[
{
‘Name’: ‘tag-key’,
‘Values’: [tag_name]
}
]
)
instancelist = {}
for reservation in (response[“Reservations”]):
for instance in reservation[“Instances”]:
tag_value = ”
for tag in instance[‘Tags’]:
if tag[‘Key’] == tag_name:
tag_value = tag[‘Value’]
break
instancelist[instance[“InstanceId”]] = {‘Schedule’:tag_value,’State’:instance[‘State’]}

Ace the Microsoft Azure Fundamentals AZ-900 Certification Exam: Pass the Azure Fundamentals Exam with Ease


return instancelist

Get all All AWS Ec2 snapshot reports with python and boto3

AWS EC2 Start Stop with boto3

AI Dashboard is available on the Web, Apple, Google, and Microsoft, PRO version

How to Get all All AWS Ec2 snapshot reports with python and boto3?

Use this python script to get all EC2 snapshot report in your AWS account.

AWS EC2 snapshop report


import boto3
def lambda_handler(event, context):
session = boto3.Session(profile_name='saml')
ec2client = session.client('ec2')
instances_with_volumes = get_instance_ids(ec2client, "tc:OpsAutomatorTaskList")

for instance_id, volume_ids in instances_with_volumes.items():
response = ec2client.describe_snapshots(
Filters = [
{'Name':'volume-id', 'Values': volume_ids}
#{'Name':'start-time', 'Values': ['2019-01-01']}
]
#MaxResults = 10
)
#print(response['ResponseMetadata'])
#print("instance_id:%s, number_of_snapshots:%s" % (instance_id, len(response['Snapshots'])))
if len(response['Snapshots']) > 0:
#print(response['Tags'])
#Print Header
print('InstanceId' + ' , ' + 'Description' + ' , ' + 'Encrypted' + ' , ' + 'OwnerId' + ' , ' + 'Progress' + ' , ' + 'SnapshotId' + ' , ' + 'StartTime' + ' , ' + 'State' + ' , ' + 'VolumeId' + ' , ' + 'VolumeSize')
for snapshot in response['Snapshots']:
print(instance_id + ' , ' + snapshot['Description'] + ' , ' + str(snapshot['Encrypted']) + ' , ' + str(snapshot['OwnerId']) + ' , ' + snapshot['Progress'] + ' , ' + snapshot['SnapshotId'] + ' , ' + str(snapshot['StartTime']) + ' , ' + snapshot['State'] + ' , ' + snapshot['VolumeId'] + ' , ' + str(snapshot['VolumeSize']) )

Get 20% off Google Google Workspace (Google Meet) Standard Plan with  the following codes: 96DRHDRA9J7GTN6
Get 20% off Google Workspace (Google Meet)  Business Plan (AMERICAS) with  the following codes:  C37HCAQRVR7JTFK Get 20% off Google Workspace (Google Meet) Business Plan (AMERICAS): M9HNXHX3WC9H7YE (Email us for more codes)

Active Anti-Aging Eye Gel, Reduces Dark Circles, Puffy Eyes, Crow's Feet and Fine Lines & Wrinkles, Packed with Hyaluronic Acid & Age Defying Botanicals

def get_instance_ids(ec2client, tag_name):
# When passed a tag key, tag value this will return a list of InstanceIds that were found.

response = ec2client.describe_instances(
Filters=[
{
‘Name’: ‘tag-key’,
‘Values’: [tag_name]
}
]
)
instancelist = {}
for reservation in (response[“Reservations”]):
for instance in reservation[“Instances”]:


AI Unraveled: Demystifying Frequently Asked Questions on Artificial Intelligence (OpenAI, ChatGPT, Google Bard, Generative AI, Discriminative AI, xAI, LLMs, GPUs, Machine Learning, NLP, Promp Engineering)

ebs_volume_ids = []
for ebs in instance[‘BlockDeviceMappings’]:
ebs_volume_ids.append(ebs[‘Ebs’][‘VolumeId’])

If you are looking for an all-in-one solution to help you prepare for the AWS Cloud Practitioner Certification Exam, look no further than this AWS Cloud Practitioner CCP CLF-C02 book

instancelist[instance[“InstanceId”]] = ebs_volume_ids

return instancelist

lambda_handler(”,”)


How to call a shell script from python code?

AI Dashboard is available on the Web, Apple, Google, and Microsoft, PRO version

This is how to How to call a shell script from python code

To call a shell script from Python code, you can use the subprocess module, which is a part of the Python standard library. The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.

import subprocess

# Call the script using the `call` function
subprocess.call([“/path/to/script.sh”])

# Call the script and pass arguments to it
subprocess.call([“/path/to/script.sh”, “arg1”, “arg2”])

# Call the script and store the output in a variable
output = subprocess.check_output([“/path/to/script.sh”])
print(output)

Get 20% off Google Google Workspace (Google Meet) Standard Plan with  the following codes: 96DRHDRA9J7GTN6
Get 20% off Google Workspace (Google Meet)  Business Plan (AMERICAS) with  the following codes:  C37HCAQRVR7JTFK Get 20% off Google Workspace (Google Meet) Business Plan (AMERICAS): M9HNXHX3WC9H7YE (Email us for more codes)

Active Anti-Aging Eye Gel, Reduces Dark Circles, Puffy Eyes, Crow's Feet and Fine Lines & Wrinkles, Packed with Hyaluronic Acid & Age Defying Botanicals

In this example, the call function is used to execute the shell script and wait for it to complete. The check_output function is used to execute the shell script and store the output in a variable.

You can also use the Popen class from the subprocess module to execute the shell script in a separate process and communicate with it in real-time.


import subprocess
subprocess.call(['sh shell_script.sh arguments'])


AI Unraveled: Demystifying Frequently Asked Questions on Artificial Intelligence (OpenAI, ChatGPT, Google Bard, Generative AI, Discriminative AI, xAI, LLMs, GPUs, Machine Learning, NLP, Promp Engineering)

or





import sys, os
os.system("sh shell_script.sh arguments")

If you are looking for an all-in-one solution to help you prepare for the AWS Cloud Practitioner Certification Exam, look no further than this AWS Cloud Practitioner CCP CLF-C02 book

Output Example

Quicksort Algorithm Implementation with Python

AI Dashboard is available on the Web, Apple, Google, and Microsoft, PRO version

QuickSort is an O(nlogn) efficient sorting algorithm, serving as systematic method for placing elements of an array in order. Quicksort is a comparison sort, meaning that it can sort items of any type for which a “less-than” relation (formally, a total order) is defined. In efficient implementations it is not a stable sort, meaning that the relative order of equal sort items is not preserved. Quicksort can operate in-place on an array, requiring small additional amounts of memory to perform the sorting. It is very similar to selection sort, except that it does not always choose worst-case partition.

Source: https://en.wikipedia.org/wiki/Quicksort
Below are 2 versions of the Quicksort Algorithm Implementation with Python. The first version is easy, but use more memory. The second version use the memory very efficiently.




I- QuickSort Algorithm Implementation with Python (Memory intensive version)

QuickSort Algorithm Implementation with Python method1

Output:

Get 20% off Google Google Workspace (Google Meet) Standard Plan with  the following codes: 96DRHDRA9J7GTN6
Get 20% off Google Workspace (Google Meet)  Business Plan (AMERICAS) with  the following codes:  C37HCAQRVR7JTFK Get 20% off Google Workspace (Google Meet) Business Plan (AMERICAS): M9HNXHX3WC9H7YE (Email us for more codes)

Active Anti-Aging Eye Gel, Reduces Dark Circles, Puffy Eyes, Crow's Feet and Fine Lines & Wrinkles, Packed with Hyaluronic Acid & Age Defying Botanicals

II- Quicksort Algorithm Implementation with Python (with Memory Optimisation)


AI Unraveled: Demystifying Frequently Asked Questions on Artificial Intelligence (OpenAI, ChatGPT, Google Bard, Generative AI, Discriminative AI, xAI, LLMs, GPUs, Machine Learning, NLP, Promp Engineering)

III- QuickSort Algorithm Implementation with Python for Both Methods with duration captured

Output

If you are looking for an all-in-one solution to help you prepare for the AWS Cloud Practitioner Certification Exam, look no further than this AWS Cloud Practitioner CCP CLF-C02 book

III- Most Efficient Quicksort implementation in Python on array of  integer represented as string. Example: array=[“1″,”237373737″,”3″,”1971771717171717″,”0”]

def QuickSort(array):
    return array.sort(key=lambda x: (len(x),x))
input:
6
31415926535897932384626433832795
1
3
10
3
5
Output:
1
3
3
5
10
31415926535897932384626433832795

Just to clarify that lambda part, in case someone else doesn't understand how exactly string comparison works: '2' > '1' is True, but '2' > '10' is also True, as well as '2' > '1000'. That's why the strings are sorted by length first, because len('2') < len('10'). IV- Build up a sorted array, one element at a time. Print the array after each iteration of the insertion sort, i.e., whenever the next element has been inserted at its correct position
build up sorted array
Python build up sorted array
python build up sorted array input output
python build up sorted array input output

Binary Search Algorithm Implementation with Python

binary search algorithm in Python

AI Dashboard is available on the Web, Apple, Google, and Microsoft, PRO version

Binary Search Algorithm Implementation with Python

Binary Search  is an algorithm that finds the position of a target in a sorted array. Binary search compares the target value to the middle element of the array. If they are not equal, the half in which the target cannot lie is eliminated and the search continues on the remaining half, again taking the middle element to compare to the target value, and repeating this until the target value is found. If the search ends with the remaining half being empty, the target is not in the array. Even though the idea is simple, implementing binary search correctly requires attention to some subtleties about its exit conditions and midpoint calculation, particularly if the values in the array are not all of the whole numbers in the range.

Source: https://en.wikipedia.org/wiki/Binary_search_algorithm

Below the binary search algorithm implementation  with python:




Get 20% off Google Google Workspace (Google Meet) Standard Plan with  the following codes: 96DRHDRA9J7GTN6
Get 20% off Google Workspace (Google Meet)  Business Plan (AMERICAS) with  the following codes:  C37HCAQRVR7JTFK Get 20% off Google Workspace (Google Meet) Business Plan (AMERICAS): M9HNXHX3WC9H7YE (Email us for more codes)

Active Anti-Aging Eye Gel, Reduces Dark Circles, Puffy Eyes, Crow's Feet and Fine Lines & Wrinkles, Packed with Hyaluronic Acid & Age Defying Botanicals


#Test_Binary_Search.py
Array=[-2,1,0,4,7,8,10,13,16,17, 21,30,45,100,150,160,191,200]
Target=201
n=len(Array)
def binarySearch(A,T):
L=0
R=n-1
while (L <= R):
m=int((L + R)/2)
if ( A[m] < T ):
L = m +1
elif (A[m] > T):
R = m-1
else:
print("Target is at %s:" % m)
return m
print("Target not found")
return "unsuccessful"


binarySearch(Array, Target)


AI Unraveled: Demystifying Frequently Asked Questions on Artificial Intelligence (OpenAI, ChatGPT, Google Bard, Generative AI, Discriminative AI, xAI, LLMs, GPUs, Machine Learning, NLP, Promp Engineering)
Binary Search Algorithm implementation with python
binary search algorithm in Python
binary search algorithm in Python

In this example, the binary_search function takes a sorted list arr and an element x as input, and returns the index of the element if it is found, or -1 if it is not found. The function uses a binary search algorithm to search for the element in the list, by dividing the list into halves and comparing the element with the middle element of the list. If the element is greater than the middle element, it searches the right half of the list, and if it is less than the middle element, it searches the left half of the list. This process is repeated until the element is found or the list is exhausted.

Script with hash tables on windows and Linux

AI Dashboard is available on the Web, Apple, Google, and Microsoft, PRO version

How to declare and write a script with hash tables on windows and linux

A hash table, also known as a hash map, is a data structure that is used to store key-value pairs. It is an efficient way to store data that can be quickly retrieved using a unique key.

Here is an example of how to declare and write a script with a hash table in Python:

# Declare an empty hash table
hash_table = {}

# Add some key-value pairs to the hash table
hash_table[‘key1’] = ‘value1’
hash_table[‘key2’] = ‘value2’
hash_table[‘key3’] = ‘value3’

# Access a value using its key
print(hash_table[‘key2’]) # Output: “value2”

Get 20% off Google Google Workspace (Google Meet) Standard Plan with  the following codes: 96DRHDRA9J7GTN6
Get 20% off Google Workspace (Google Meet)  Business Plan (AMERICAS) with  the following codes:  C37HCAQRVR7JTFK Get 20% off Google Workspace (Google Meet) Business Plan (AMERICAS): M9HNXHX3WC9H7YE (Email us for more codes)

Active Anti-Aging Eye Gel, Reduces Dark Circles, Puffy Eyes, Crow's Feet and Fine Lines & Wrinkles, Packed with Hyaluronic Acid & Age Defying Botanicals

# Modify a value using its key
hash_table[‘key2’] = ‘new value’
print(hash_table[‘key2’]) # Output: “new value”

# Delete a key-value pair using the `del` statement
del hash_table[‘key1’]

# Check if a key is in the hash table using the `in` operator
print(‘key1’ in hash_table) # Output: False


AI Unraveled: Demystifying Frequently Asked Questions on Artificial Intelligence (OpenAI, ChatGPT, Google Bard, Generative AI, Discriminative AI, xAI, LLMs, GPUs, Machine Learning, NLP, Promp Engineering)

# Output: False

In this example, we declare an empty hash table using the {} syntax. We then add some key-value pairs to the hash table using the [] syntax. We access a value using its key, modify a value using its key, delete a key-value pair using the del statement, and check if a key is in the hash table using the in operator.

I hope this helps! Let me know if you have any questions.

    • Hash tables with powershell on windows

      Declaration:
      $states=@{“Alberta” = “Calgary”; “British Columbia” = “Vancouver”; “Ontario” = “Toronto” ; “Quebec” = “Montreal”}

      Name
      _____
      Value
      _______
      AlbertaCalgary
      British ColumbiaVancouver
      OntarioToronto
      QuebecMontreal

      Add new key-value in hashtable:
      $states.Add(“Manitoba”,”Winnipeg”)

      Remove key-value in hashtable:
      $states.Remove(“Manitoba”,”Winnipeg”)
      Change value in hashtable:
      $states.Set_Item(“Ontario”,”Ottawa”)
      Retrieve value in hashtable:
      $states.Get_Item(“Alberta”)
      Find key in hashtable:
      $states.ContainsKey(“Alberta”)
      Find Value in hashtable:
      $states.ContainsValue(“Calgary”)
      Count items in hashtable:
      $states.Count
      Sort items by Name in hashtable:
      $states.GetEnumerator() | Sort-Object Name -descending
      Sort items by Value in hashtable:
      $states.GetEnumerator() | Sort-Object Value -descending

    • Hash tables with perl on linux or windows

      Declaration:
      my %hash = (); #Initialize a hash
      my $hash_ref = {}; # Initialize a hash reference. ref will return HASH
      Clear (or empty) a hash
      for (keys %hash)
      {
      delete $hash{$_};
      }
      Clear (or empty) a hash reference
      for (keys %$href)
      {
      delete $href->{$_};
      }
      Add a key/value pair to a hash
      $hash{ ‘key’ } = ‘value’; # hash
      $hash{ $key } = $value; # hash, using variables
      Using Hash Reference
      $href->{ ‘key’ } = ‘value’; # hash ref
      $href->{ $key } = $value; # hash ref, using variables
      Add several key/value pairs to a hash
      %hash = ( ‘key1’, ‘value1’, ‘key2’, ‘value2’, ‘key3’, ‘value3’ );
      %hash = (
      key1 => ‘value1’,
      key2 => ‘value2’,
      key3 => ‘value3’,
      );

      Copy a hash
      my %hash_copy = %hash; # copy a hash
      my $href_copy = $href; # copy a hash ref
      Delete a single key/value pair
      delete $hash{$key};
      delete $hash_ref->{$key};

Hash tables with python on linux or windows

Hash tables are called dictionary in python.
Declaration:
dict = {‘Name’: ‘Zara’, ‘Age’: 7, ‘Class’: ‘First’}
Accessing Values
print “dict[‘Name’]: “, dict[‘Name’]
print “dict[‘Age’]: “, dict[‘Age’]
Output:
dict[‘Name’]: Zara
dict[‘Age’]: 7
Updating Dictionary
dict = {‘Name’: ‘Zara’, ‘Age’: 7, ‘Class’: ‘First’}

If you are looking for an all-in-one solution to help you prepare for the AWS Cloud Practitioner Certification Exam, look no further than this AWS Cloud Practitioner CCP CLF-C02 book

dict[‘Age’] = 8; # update existing entry
dict[‘School’] = “DPS School”; # Add new entry
Delete Dictionary Elements
#!/usr/bin/python

dict = {‘Name’: ‘Zara’, ‘Age’: 7, ‘Class’: ‘First’}

del dict[‘Name’]; # remove entry with key ‘Name’
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary

Source:

  1. https://technet.microsoft.com/en-us/library/ee692803.aspx
  2. http://www.cs.mcgill.ca/~abatko/computers/programming/perl/howto/hash/
  3. http://www.tutorialspoint.com/python/python_dictionary.htm

reverse a string on Linux and Windows

AI Dashboard is available on the Web, Apple, Google, and Microsoft, PRO version

How to reverse a string on Linux and Windows

On Linux:

  1. Using the rev command: The rev command is a utility that reverses the lines of a file or the characters in a string. To reverse a string, you can use the echo command to pass the string to rev:
echo "string" | rev
  1. Using the sed command: The sed command is a powerful utility that can perform various text transformations. To reverse a string, you can use the sed command with the -r option and the 's/.*(.)/\1/g' expression:
echo "string" | sed -r 's/.*(.)/\1/g'
  1. Using the awk command: The awk command is a programming language that is used for text processing. To reverse a string, you can use the awk command with the {print} action:
echo "string" | awk '{print $1}'

On Windows:

  1. Using the powershell command: The powershell command is a shell that provides a command-line interface for Windows. To reverse a string, you can use the powershell command with the -C option and the '[System.Text.Encoding]::Unicode.GetString([System.Text.Encoding]::Unicode.GetBytes("string"))' expression:
powershell -C "[System.Text.Encoding]::Unicode.GetString([System.Text.Encoding]::Unicode.GetBytes("string"))"
  1. Using the cmd command: The cmd command is the command-line interpreter for Windows. To reverse a string, you can use the cmd command with the for loop:
cmd /c "for /L %i in (1,1,%len%) do @echo !string:~%len%-%i,1!"

These are some ways to reverse a string on Linux and Windows. There are other ways to achieve this, using different utilities or programming languages.

Via shell script on Linux

reverse a string on Linux and Windows

sh-3.2# vi reverse.sh
#### Start Script #####
#!/bin/bash
input_string=”$1″
reverse_string=””

Get 20% off Google Google Workspace (Google Meet) Standard Plan with  the following codes: 96DRHDRA9J7GTN6
Get 20% off Google Workspace (Google Meet)  Business Plan (AMERICAS) with  the following codes:  C37HCAQRVR7JTFK Get 20% off Google Workspace (Google Meet) Business Plan (AMERICAS): M9HNXHX3WC9H7YE (Email us for more codes)

Active Anti-Aging Eye Gel, Reduces Dark Circles, Puffy Eyes, Crow's Feet and Fine Lines & Wrinkles, Packed with Hyaluronic Acid & Age Defying Botanicals

input_string_length=${#input_string}
for (( i=$input_string_length-1; i>=0; i– ))
do
reverse_string=”$reverse_string${input_string:$i:1}”
done

echo “$reverse_string”
##### End Script #####

Let’s run it:


AI Unraveled: Demystifying Frequently Asked Questions on Artificial Intelligence (OpenAI, ChatGPT, Google Bard, Generative AI, Discriminative AI, xAI, LLMs, GPUs, Machine Learning, NLP, Promp Engineering)

sh-3.2# chmod 775 reverse.sh
sh-3.2# ./reverse.sh Etienne
enneitE

Via powershell script on Windows

#Let’s use the script reverse.ps1 below.
######
$string=”Etienne”
$string_array=$string -split “”
[array]::Reverse($string_array)
$string_array -join ”

#####Output#####
PS C:\Users\etienne_noumen\Documents\Etienne\Scripting> .\reverse.ps1

If you are looking for an all-in-one solution to help you prepare for the AWS Cloud Practitioner Certification Exam, look no further than this AWS Cloud Practitioner CCP CLF-C02 book

E t i e n n e

enneitE

Via powershell script on Windows in one line

([regex]::Matches($String,’.’,’RightToLeft’) | ForEach {$_.value}) -join ”

Via batch script on Windows

::Note: ReverseStr also calls StrLen
::and string length is not greater than 80 chars
:: but can be changed.

@echo off
SetLocal EnableDelayedExpansion
cls
set Str=Etienne
call :StrLen %Str%
echo Length=%Len%
call :ReverseStr %Str%
echo String=%Str%
echo Reverse Str=%Reverse%
exit /b

::—————-
:: Calc Var Length
::—————-
:: %*=Str to Check
:: Returns %Len%
:: —————
:StrLen %*
set Data=%*
for /L %%a in (0,1,80) do (
set Char=!Data:~%%a,1!
if not “!Char!”==”” (
set /a Len=%%a+1
) else (exit /b)
)
exit /b

::—————
:: Reverse String
::—————
:: %* Str to Reverse
:: Returns %Reverse%
::——————
:ReverseStr %*
set Data=%*
call :StrLen %Data%
for /L %%a in (!Len!,-1,0) do (
set Char=!Data:~%%a,1!
set Reverse=!Reverse!!Char!
)
exit /b

Via perl script on Windows or Linux

Via python script on Windows or Linux

def reverse_string(a_string)
return a_string[::-1]
reverse_string(“etienne”) returns “enneite”
Source:

  1. http://www.computing.net/answers/programming/reverse-a-string-in-dos/26004.html

prompt and read input variables from keyboard

AI Dashboard is available on the Web, Apple, Google, and Microsoft, PRO version

Let’s find how to prompt and read input variables from keyboard while executing a script using shell, perl, python, batch and powershell (windows and Linux)

  • On Linux via shell

    read -p “Enter your name: ” name
    echo “Hi, $name. Let’s be friend!”

  • On Windows via powershell

    $name=read-host “Enter your name:”
    write-host “Hi $name, Let’s be friend!”

  • On Windows via batch

    Set /p Name=”Enter your name:”
    echo “Hi %name%, Let’s be friend!”

  • On Windows or Linux via perl

    print “Enter your name “;
    my $name = ;
    chomp $name; # Get rid of newline character at the end
    print “Hello $name, let’s be friend”;

  • On Windows or Linux via python

    name=input(“Enter your name: “)
    print (“Hello ” + name + ” let’s be friend”)

Pass the 2023 AWS Cloud Practitioner CCP CLF-C02 Certification with flying colors Ace the 2023 AWS Solutions Architect Associate SAA-C03 Exam with Confidence Pass the 2023 AWS Certified Machine Learning Specialty MLS-C01 Exam with Flying Colors

List of Freely available programming books - What is the single most influential book every Programmers should read



#BlackOwned #BlackEntrepreneurs #BlackBuniness #AWSCertified #AWSCloudPractitioner #AWSCertification #AWSCLFC02 #CloudComputing #AWSStudyGuide #AWSTraining #AWSCareer #AWSExamPrep #AWSCommunity #AWSEducation #AWSBasics #AWSCertified #AWSMachineLearning #AWSCertification #AWSSpecialty #MachineLearning #AWSStudyGuide #CloudComputing #DataScience #AWSCertified #AWSSolutionsArchitect #AWSArchitectAssociate #AWSCertification #AWSStudyGuide #CloudComputing #AWSArchitecture #AWSTraining #AWSCareer #AWSExamPrep #AWSCommunity #AWSEducation #AzureFundamentals #AZ900 #MicrosoftAzure #ITCertification #CertificationPrep #StudyMaterials #TechLearning #MicrosoftCertified #AzureCertification #TechBooks

Top 1000 Canada Quiz and trivia: CANADA CITIZENSHIP TEST- HISTORY - GEOGRAPHY - GOVERNMENT- CULTURE - PEOPLE - LANGUAGES - TRAVEL - WILDLIFE - HOCKEY - TOURISM - SCENERIES - ARTS - DATA VISUALIZATION
zCanadian Quiz and Trivia, Canadian History, Citizenship Test, Geography, Wildlife, Secenries, Banff, Tourism

Top 1000 Africa Quiz and trivia: HISTORY - GEOGRAPHY - WILDLIFE - CULTURE - PEOPLE - LANGUAGES - TRAVEL - TOURISM - SCENERIES - ARTS - DATA VISUALIZATION
Africa Quiz, Africa Trivia, Quiz, African History, Geography, Wildlife, Culture

Exploring the Pros and Cons of Visiting All Provinces and Territories in Canada.
Exploring the Pros and Cons of Visiting All Provinces and Territories in Canada

Exploring the Advantages and Disadvantages of Visiting All 50 States in the USA
Exploring the Advantages and Disadvantages of Visiting All 50 States in the USA


Health Health, a science-based community to discuss health news and the coronavirus (COVID-19) pandemic

Today I Learned (TIL) You learn something new every day; what did you learn today? Submit interesting and specific facts about something that you just found out here.

Reddit Science This community is a place to share and discuss new scientific research. Read about the latest advances in astronomy, biology, medicine, physics, social science, and more. Find and submit new publications and popular science coverage of current research.

Reddit Sports Sports News and Highlights from the NFL, NBA, NHL, MLB, MLS, and leagues around the world.

Turn your dream into reality with Google Workspace: It’s free for the first 14 days.
Get 20% off Google Google Workspace (Google Meet) Standard Plan with  the following codes:
Get 20% off Google Google Workspace (Google Meet) Standard Plan with  the following codes: 96DRHDRA9J7GTN6 96DRHDRA9J7GTN6
63F733CLLY7R7MM
63F7D7CPD9XXUVT
63FLKQHWV3AEEE6
63JGLWWK36CP7WM
63KKR9EULQRR7VE
63KNY4N7VHCUA9R
63LDXXFYU6VXDG9
63MGNRCKXURAYWC
63NGNDVVXJP4N99
63P4G3ELRPADKQU
With Google Workspace, Get custom email @yourcompany, Work from anywhere; Easily scale up or down
Google gives you the tools you need to run your business like a pro. Set up custom email, share files securely online, video chat from any device, and more.
Google Workspace provides a platform, a common ground, for all our internal teams and operations to collaboratively support our primary business goal, which is to deliver quality information to our readers quickly.
Get 20% off Google Workspace (Google Meet) Business Plan (AMERICAS): M9HNXHX3WC9H7YE
C37HCAQRVR7JTFK
C3AE76E7WATCTL9
C3C3RGUF9VW6LXE
C3D9LD4L736CALC
C3EQXV674DQ6PXP
C3G9M3JEHXM3XC7
C3GGR3H4TRHUD7L
C3LVUVC3LHKUEQK
C3PVGM4CHHPMWLE
C3QHQ763LWGTW4C
Even if you’re small, you want people to see you as a professional business. If you’re still growing, you need the building blocks to get you where you want to be. I’ve learned so much about business through Google Workspace—I can’t imagine working without it.
(Email us for more codes)

error: Content is protected !!