Thursday, December 27, 2018

Using Zypper and RPM to install ,uninstall and manage packages ,patches and updates on SUSE Enterprise Linux,Linux Teacher Sourav,Kolkata 08910141720

install something

sudo zypper install packagename

it will install the package with the dependancies

for example to install git-core

sudo zypper install git-core


now to remove the package

sudo zypper remove git-core


as you might seee when installing the git-core package
you have  a dependency called perl-error which was installed
but this is not removed when using sudo zypper remove git-core

so to remove it manually

 sudo zypper remove perl-Error

however let us do the proper way of removing a package with the dependencies

lets install git-core again

 sudo zypper install git-core

after installing we need to use this to remove git-core as well as
the dependency perl-error

sudo zypper rm --clean-deps git-core


to see all our missing dependecies

 sudo zypper verify

this will most likely solve any dependency issue the system is having

to get the necessary patches/updates

sudo zypper patch



to include the optionalpatches

sudo zypper patch --with-optional


to get a summary list of security patches recommended patches

and optional patches


sudo zypper patch-check

the difference between patches and updates is

patches which are mostly associated with kernel are generally
backward compatible

but updates are not always backward compatible

to list all the patches

sudo zypper list-patches

to update the system

sudo zypper update

after update to reflect the changes to some files

sudo zypper ps -s

to see if there is any more update to perform

sudo zypper list-updates

to get information about a package

rpm -q -i wget


to list all the files in the package

 rpm -q -l wget

to see all the documentation files in a package

rpm -q -d wget

to see all the configuration files in a package

rpm -q -c wget

to see the scripts those are used for installing and uninstalling

rpm -q --scripts wget











Managing repositories in SUSE Enterprise Server,Linux Teacher Sourav,Kolkata 08910141720

list repositories
zypper lr

the output will show the current repositories


to get more detailed out about repositories

zypper repos -d

to add your own or any generic repository

sudo zypper addrepo http://example.com/repo myrepo

here myrepo is the alias of this repo


now to see if this new repo is added

zypper lr


now to remove this repo

we can do this

sudo zypper removerepo 7

this number is for myrepo ,we can see this number by the command

zypper lr


to check if the new repo is removed or not

zypper lr

we could have removed the repo by using the alias in place of number

sudo zypper removerepo myrepo

Monday, December 24, 2018

Nice terminal trick if you forget to put sudo before a command,Linux Teacher Sourav,Kolkata 08910141720

Sometimes a command need sudo before it as it requires permissions,we can write 

sudo !!

that will run the last command with sudo appearing in front of it

Find the age of my suse enterprise linux system,Linux Teacher Sourav,Kolkata 08910141720

I have a trial of suse enterprise linux server which gives me two months to play around,I want to know how many days have gone by after installation ,this is the way worked for me

ls -alp /etc/ssh/ssh_host_dsa_key.pub | cut -d " " -f6


Source:https://serverfault.com/questions/221377/how-to-determine-the-age-of-a-linux-system-since-installation

Wednesday, December 5, 2018

Creating Dynamic Reports from Excel Data using VBA,VBA Teacher Sourav,Kolkata 08910141720

Dim sdsheet, ersheet As Worksheet

k = ActiveWorkbook.Sheets.Count

    For i = k To 1 Step -1
        t = Sheets(i).Name
        If t = "Emp_rpt_insurance" Then
            Application.DisplayAlerts = False
                Sheets(i).Delete
            Application.DisplayAlerts = True
          
        End If
    Next i
On Error Resume Next
  ActiveWorkbook.Sheets.Add(After:=ActiveWorkbook.Sheets(ActiveWorkbook.Sheets.Count)).Name = "Emp_rpt_insurance"
Set sdsheet = ThisWorkbook.Sheets("Sortsheet")
Set ersheet = ThisWorkbook.Sheets("Emp_rpt_insurance")
If sdsheet.Cells(Rows.Count, 1).End(xlUp).Row = 1 Then
sdlr = 2
Else
sdlr = sdsheet.Cells(Rows.Count, 1).End(xlUp).Row
End If
y = 2

ersheet.Cells(1, 1) = "Emp ID"
ersheet.Cells(1, 2) = "First Name"
ersheet.Cells(1, 3) = "Last Name"
ersheet.Cells(1, 4) = "Address"
ersheet.Cells(1, 5) = "Zipcode"
ersheet.Cells(1, 6) = "Mail"
ersheet.Cells(1, 7) = "Date Of Birth"
ersheet.Cells(1, 8) = "Phone"








For x = 2 To sdlr
If (UCase(sdsheet.Cells(x, 14)) = "A") And (CInt(sdsheet.Cells(x, 17)) >= 40) Then
ersheet.Cells(y, 1) = sdsheet.Cells(x, 1)

ersheet.Cells(y, 2) = sdsheet.Cells(x, 2)

ersheet.Cells(y, 3) = sdsheet.Cells(x, 3)

ersheet.Cells(y, 4) = sdsheet.Cells(x, 5)

ersheet.Cells(y, 5) = sdsheet.Cells(x, 9)

ersheet.Cells(y, 6) = sdsheet.Cells(x, 12)

ersheet.Cells(y, 7) = sdsheet.Cells(x, 15)

ersheet.Cells(y, 8) = "XXX-XXX-" & Right(sdsheet.Cells(x, 10), 4)

y = y + 1
End If



Next x


ersheet.Cells.Columns.AutoFit

'If ersheet.Cells(Rows.Count, 1).End(xlUp).Row = 1 Then
'erlr = 2
'Else
'erlr = ersheet.Cells(Rows.Count, 1).End(xlUp).Row
'End If
'

Tuesday, December 4, 2018

Determine employee is eligible for insurance using datediff and Iif function in VBA,VBA Teacher Sourav,Kolkata 08910141720

I have an employee list with their date of birth ,I need to calculate whether they are below or above 40 years old  to determine if they are eligible for insurance,here is the vba code for that

If IsDate(Application.WorksheetFunction.VLookup(Me.Label1, [Emplist_dob], 15, 0)) Then

Label6.Caption = IIf(DateDiff("yyyy", Application.WorksheetFunction.VLookup(Me.Label1, [Emplist_dob], 15, 0), Date) >= 40, "Above 40 no insurance", "Below 40 eligible for insurance")

End If

Saturday, December 1, 2018

Get Historical Data from NSE using VBA and Internet Explorer,VBA Teacher Sourav,Kolkata 08910141720


Public Sub downloadData()
'Open an excel sheet and rename one of the sheets as "DailyData". The data will be
'copied to that sheet

Dim frmDate As String, toDate As String, scrip As String
frmDate = DateSerial(2017, 5, 22)
frmDate = Format(frmDate, "dd-mm-yyyy")
toDate = DateSerial(2017, 5, 26)
toDate = Format(toDate, "dd-mm-yyyy")
scrip = "DABUR"
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("DailyData")

'Call subroutine to download the data
getNSE_post frmDate, toDate, 1, 1, scrip, ws

End Sub


Sub getNSE_post(frmDate As String, toDate As String, nRow As Integer, _
nCol As Integer, scrip As String, ws As Worksheet)
Dim str As String
Dim ie As Object
Dim frm As Variant
Dim element, submitInput As Variant
Dim rowCollection, htmlRow As Variant
Dim rowSubContent, rowSubData As Variant
Dim i, j, k, pauseTime As Integer
Dim anchorRange As Range, cellRng As Range
Dim start

Set ie = CreateObject("InternetExplorer.Application")
ie.navigate "https://www.nseindia.com/products/content/equities/equities/eq_security.htm"
While ie.readyState <> 4: DoEvents: Wend

'try to get form by ID
Set frm = ie.document.getElementById("histForm")

ie.Visible = True
ie.document.getElementById("dataType").Value = "priceVolumeDeliverable"
ie.document.getElementById("symbol").Value = scrip
ie.document.getElementById("segmentLink").Value = 3
ie.document.getElementById("symbolCount").Value = 1
ie.document.getElementById("series").Value = "EQ"
'ie.document.getElementById("dateRange").Value = "day"
ie.document.getElementById("rdPeriod").Checked = True
ie.document.getElementById("fromDate").Value = frmDate
ie.document.getElementById("toDate").Value = toDate

'Pause For User To See Entry
pauseTime = 2 ' Set duration in seconds
start = Timer ' Set start time.
Do While Timer < start + pauseTime
DoEvents ' Yield to other processes.
Loop

For Each submitInput In ie.document.getelementsbytagname("INPUT")
If InStr(submitInput.getAttribute("onclick"), "submitData") Then
submitInput.Click
Exit For
End If
Next


 k = ActiveWorkbook.Sheets.Count

    For i = k To 1 Step -1
        t = Sheets(i).Name
        If t = "Full Table" Then
            Application.DisplayAlerts = False
                Sheets(i).Delete
            Application.DisplayAlerts = True
           
        End If
    Next i
On Error Resume Next
  ActiveWorkbook.Sheets.Add(After:=ActiveWorkbook.Sheets(ActiveWorkbook.Sheets.Count)).Name = "Full Table"
  
Set anchorRange = Sheets("Full Table").Cells(1, 1)
i = 0 'The header row needs to be omitted

Set rowCollection = ie.document.getelementsbytagname("tr")
For Each htmlRow In rowCollection
Set rowSubContent = htmlRow.getelementsbytagname("td")
k = 0
For Each rowSubData In rowSubContent

anchorRange.Offset(i, k).Value = rowSubData.innerText
k = k + 1


Next rowSubData

i = i + 1
Next htmlRow

End Sub



Maximize minimize and random size of internet explorer window using VBA,VBA Teacher Sourav,Kolkata 08910141720

 Declare Function apiIEsize Lib "user32" Alias "ShowWindow" _
(ByVal hwnd As Long, ByVal CmdShow As Long) As Long

Global Const SW_MAXIMIZE = 3
 Global Const SW_SHOWNORMAL = 1
Global Const SW_SHOWMINIMIZED = 2

Sub differntIEsize()

Set ie = CreateObject("InternetExplorer.Application")

 ie.Visible = True
apiIEsize ie.hwnd, SW_MAXIMIZE

ie.navigate "https://www.google.com"

 End Sub 



Source:https://www.youtube.com/watch?v=Kiro_vuS6Bo&index=4&list=PLe_F6wC3Fvdrh3aUyLExNcuofDAmb0nGV

Friday, November 30, 2018

Automatic Web Form Fill Up using VBA and Internet Explorer,VBA Teacher Sourav,Kolkata 08910141720

Sub ienavigate()

Dim firstName, lastName, phone, UserName, address1, address2, city, state, postalCode, country, email, password, confirmPassword As Object
'Dim HTMLDoc As HTMLDocument
Dim ie As Object
Set ie = CreateObject("internetexplorer.application")
With ie

    .Visible = True
    .navigate "http://www.newtours.demoaut.com/mercuryregister.php"
    'to make the page load so that it will not close in fraction of second
    'to make the internet explorer wait
    'it should do some events
    Do While .busy
   
    DoEvents
   
    Loop
   
    'now if the internet explorer is not fully loaded it should do some events
   
    Do While .readystate <> 4
       
    DoEvents
   
    Loop
   
   
    'to make this application wait for 5 seconds
    'Application.Wait (Now + TimeValue("00:00:05"))
   
    'to search google for a phrase
    'get the name of the textbox by right click on it and inspect elements
    'it is q
   
   
    'Set searchtext = .document.getelementsbyclassname("gLFyf gsfi")
    Set firstName = .document.getElementsByName("firstName")
    firstName.Item.innerText = "Sourav"
    Set lastName = .document.getElementsByName("lastName")
    lastName.Item.innerText = "Bhattacharya"
    Set phone = .document.getElementsByName("phone")
    phone.Item.innerText = "Bhattacharya"
    Set UserName = .document.getElementsByName("userName")
    UserName.Item.innerText = "allsourav"
    Set address1 = .document.getElementsByName("address1")
    address1.Item.innerText = "123/1/1,Roy Bahadur Road"
    Set address2 = .document.getElementsByName("address2")
    address2.Item.innerText = "123/1/1,Roy Bahadur Road"
    Set city = .document.getElementsByName("city")
    city.Item.innerText = "kolkata"
     Set state = .document.getElementsByName("state")
    state.Item.innerText = "West Bengal"
     Set postalCode = .document.getElementsByName("postalCode")
    postalCode.Item.innerText = "700034"
   
    'this is for the country selection from the drop down values

     Set e = .document.getElementsByName("country")(0)
    For Each o In e.Options
        If StrComp(o.Text, "INDIA", vbTextCompare) = 0 Then
            o.Selected = True
            Exit For
        End If
    Next
    e.FireEvent ("onchange")

  
   

 
  
   
     Set email = .document.getElementsByName("email")
    email.Item.innerText = "allsourav2@gmail.com"
   
    Set password = .document.getElementsByName("password")
   
    password.Item.innerText = "123456"
   
    Set confirmPassword = .document.getElementsByName("confirmPassword")
   
    confirmPassword.Item.innerText = "123456"
   

   
    email.Item.innerText = "allsourav2@gmail.com"
   
    'now to press the search button
   
    .document.forms(0).submit
   
    'now the search results page will load,
    'to ensure the page load completes
    'we need to do perform the same steps
   
     'to make the page load so that it will not close in fraction of second
    'to make the internet explorer wait
    'it should do some events
    Do While .busy
   
    DoEvents
   
    Loop
   
    'now if the internet explorer is not fully loaded it should do some events
   
    Do While .readystate <> 4
       
    DoEvents
   
    Loop
   
   
    'now I need to get the resultset such as howmany pages google find on this phrase
   
    'to get this we need to right click on the result number at the top of the page
    'and go to inspect elements
   
    'there we see this div which shows the result has an id of
    'resultStats
   
    'Set numberofpages = .document.getelementbyid("resultStats")
   
    'to get the resultant text from numberofpages we need to use innertext
   
    'MsgBox ("The number of searches is " & numberofpages.innerText)
   
   
   
    .Quit
   
   
End With


End Sub

Serarch google for a keyword and get the resultstat automatically using vba and internet explorer,VBA Teacher Sourav,Kolkata 08910141720

Sub ienavigateandsearch()

Dim searchtxt As Object
Dim numberofpages As Object
Dim ie As Object
Set ie = CreateObject("internetexplorer.application")
With ie

    .Visible = True
    .navigate "https://www.google.com"
    'to make the page load so that it will not close in fraction of second
    'to make the internet explorer wait
    'it should do some events
    Do While .busy
   
    DoEvents
   
    Loop
   
    'now if the internet explorer is not fully loaded it should do some events
   
    Do While .readystate <> 4
       
    DoEvents
   
    Loop
   
   
    'to make this application wait for 5 seconds
    'Application.Wait (Now + TimeValue("00:00:05"))
   
    'to search google for a phrase
    'get the name of the textbox by right click on it and inspect elements
    'it is q
   
   
    'Set searchtext = .document.getelementsbyclassname("gLFyf gsfi")
    Set searchtext = .document.getElementsByName("q")
    searchtext.Item.innertext = "bbw"
   
    'now to press the search button
   
    .document.forms(0).submit
   
    'now the search results page will load,
    'to ensure the page load completes
    'we need to do perform the same steps
   
     'to make the page load so that it will not close in fraction of second
    'to make the internet explorer wait
    'it should do some events
    Do While .busy
   
    DoEvents
   
    Loop
   
    'now if the internet explorer is not fully loaded it should do some events
   
    Do While .readystate <> 4
       
    DoEvents
   
    Loop
   
   
    'now I need to get the resultset such as howmany pages google find on this phrase
   
    'to get this we need to right click on the result number at the top of the page
    'and go to inspect elements
   
    'there we see this div which shows the result has an id of
    'resultStats
   
    Set numberofpages = .document.getelementbyid("resultStats")
   
    'to get the resultant text from numberofpages we need to use innertext
   
    MsgBox ("The number of searches is " & numberofpages.innertext)
   
   
   
    .Quit
   
   
End With


End Sub

Open Internet explorer and navigate to an url and wait some seonds using VBA ,VBA Teacher Sourav,Kolkata 08910141720

Sub ienavigate()

Dim ie As Object
Set ie = CreateObject("internetexplorer.application")
With ie

    .Visible = True
    .navigate "https://www.google.com"
    'to make the page load so that it will not close in fraction of second
    'to make the internet explorer wait
    'it should do some events
    Do While .busy
   
    DoEvents
   
    Loop
   
    'now if the internet explorer is not fully loaded it should do some events
   
    Do While .readystate <> 4
       
    DoEvents
   
    Loop
   
   
    'to make this application wait for 5 seconds
    Application.Wait (Now + TimeValue("00:00:05"))
   
   
    .Quit
   
   
End With


End Sub

Thursday, November 22, 2018

Extract employee id from text in combobox whenever combobox text is changed in a label,VBA Teacher Sourav,Kolkata 08910141720

Private Sub ComboBox1_Change()

If Me.ComboBox1.Text <> "" Then

If Me.OptionButton1 = True Then
Me.Label1 = Left(Me.ComboBox1.Text, Application.WorksheetFunction.Find(" -", Me.ComboBox1.Text) - 1)

'Me.Label1 = Application.WorksheetFunction.Find(" -", Me.ComboBox1.Text)
Else
'Me.Label1 = Right(Me.ComboBox1.Text, Application.WorksheetFunction.Find(" -", Me.ComboBox1.Text) + 1)
Me.Label1 = Right(Me.ComboBox1.Text, Len(Me.ComboBox1.Text) - (Application.WorksheetFunction.Find(" -", Me.ComboBox1.Text) + 2))


End If


Else

Exit Sub

End If

End Sub

Include or Exclude employee names with their employee id in a dropdown based on a criteria,VBA Teacher Sourav,Kolkata 08910141720

Sub loadcmb()
Dim sdsheet As Worksheet
Set sdsheet = ThisWorkbook.Sheets("Sortsheet")
If sdsheet.Cells(Rows.Count, 1).End(xlUp).Row = 1 Then
lr = 2
Else
lr = sdsheet.Cells(Rows.Count, 1).End(xlUp).Row
End If

SortForm.ComboBox1.Clear

If SortForm.CheckBox1 = True Then


For x = 2 To lr

If SortForm.OptionButton1 = True Then



SortForm.ComboBox1.AddItem Sortsheet.Cells(x, 1) & " - " & Sortsheet.Cells(x, 2)


Else

SortForm.ComboBox1.AddItem Sortsheet.Cells(x, 2) & " - " & Sortsheet.Cells(x, 1)

End If


Next x

Else


For x = 2 To lr

If SortForm.OptionButton1 = True Then

If UCase(Cells(x, 14)) = "A" Then

SortForm.ComboBox1.AddItem Sortsheet.Cells(x, 1) & " - " & Sortsheet.Cells(x, 2)

End If

Else

If UCase(Cells(x, 14)) = "A" Then

SortForm.ComboBox1.AddItem Sortsheet.Cells(x, 2) & " - " & Sortsheet.Cells(x, 1)

End If


End If


Next x


End If


End Sub



Randomly choose between two given characters (for example A and I) and format the row based on that choice using excel,Excel Teacher Sourav,Kolkata 08910141720

=CHAR(CHOOSE(RANDBETWEEN(1,2),65,73))

Or

=CHOOSE(RANDBETWEEN(1,2),"A","I")

Source:https://exceljet.net/formula/random-text-values

Now select the whole section of data ,go to home,conditional formatting ,manage rules,new rule

select use a formula to determine which cells to format

in the formula box write

=$N2="I"

then go to format,under fill tab make sure grey is selected,so that people with
status I (inactive ) have their rows greyed out




Tuesday, November 20, 2018

Load Combobox with Employee ID and Names on initialization of userform ,VBA Teacher Sourav,Kolkata 08910141720

Private Sub UserForm_Initialize()
Call loadcmb
End Sub


Sub loadcmb()
Dim sdsheet As Worksheet
Set sdsheet = ThisWorkbook.Sheets("Sortsheet")
If sdsheet.Cells(Rows.Count, 1).End(xlUp).Row = 1 Then
lr = 2
Else
lr = sdsheet.Cells(Rows.Count, 1).End(xlUp).Row
End If

SortForm.ComboBox1.Clear

For x = 2 To lr

If SortForm.OptionButton1 = True Then

SortForm.ComboBox1.AddItem Sortsheet.Cells(x, 1) & " - " & Sortsheet.Cells(x, 2)


Else

SortForm.ComboBox1.AddItem Sortsheet.Cells(x, 2) & " - " & Sortsheet.Cells(x, 1)

End If


Next x

End Sub

Create random but unique numbers for employee id column in a given range using VBA,VBA Teacher Sourav,Kolkata 08910141720

Sub fillcolumnwithuniquerandomnumbers()

Sheets("Sortsheet").Select
 Dim cell As Range
    Dim rng As Range
    Dim High As Long, Sample As Long
   
  
    'High = Application.InputBox("Enter population total", Type:=1)
    'Sample = Application.InputBox("Enter the Sample Size", Type:=1)
    High = 500
    Low = 1
   
    'Set rng = Application.Range(ActiveCell, ActiveCell.Offset(Sample, 0))
    Set rng = Range("A2:A500")
   
    For Each cell In rng.Cells
        If WorksheetFunction.CountA(rng) = (High - Low + 1) Then Exit For
        Do
            rndNumber = Int((High - Low + 1) * Rnd() + Low)
        Loop Until rng.Cells.Find(rndNumber, LookIn:=xlValues, lookat:=xlWhole) Is Nothing
        cell.Value = rndNumber
    Next
    rng.Select
    Selection.NumberFormat = "@" 'changing the format to text so that cells can contain leading zeros
   
    For Each cell In rng.Cells
    cell.Value = "000" & cell.Value
   
   
   
    Next
   
   
   
End Sub

Thursday, November 15, 2018

Sort excel data from an userform using column names(sort key) in option button using VBA,VBA Teacher Sourav,Kolkata 08910141720





The code behind sort button

Private Sub CommandButton1_Click()

Dim sdsheet As Worksheet
Set sdsheet = ThisWorkbook.Sheets("Sortsheet")
If sdsheet.Cells(Rows.Count, 1).End(xlUp).Row = 1 Then
lr = 2
Else
lr = sdsheet.Cells(Rows.Count, 1).End(xlUp).Row
End If

Set sortarea = Range("A2:L" & lr)
If Me.OptionButton1 = True Then

Set sortcol = Range("A2:A" & lr)
ElseIf Me.OptionButton2 = True Then
Set sortcol = Range("G2:G" & lr)

Else

End If






sdsheet.Sort.SortFields.Clear
sdsheet.Sort.SortFields.Add Key:=sortcol _
    , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With sdsheet.Sort
    .SetRange sortarea
    .Header = xlNo
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With
End Sub


Source:https://www.youtube.com/watch?v=6Ju6B99eleo&index=2&list=PLw8O1w0Hv2zvnLFyiMrihcaOqA0sT0X2U

Tuesday, September 18, 2018

Automatically Filter data and copy the filtered data and merge it in a sheet with a dynamically created name using VBA,VBA Teacher Sourav,Kolkata 08910141720

Sub automatefilter()
'This is to get the todays date and i like this date as part of the name of the new sheet,however this is not necessary

Dim mydate As String
mydate = Format(Now(), "MMM DD YYYY")

'We need to remove all filters first




Workbooks(ActiveWorkbook.Name).Activate
    Sheets("Sheet1").Activate
    Dim str3 As String
Dim fieldname As Integer


Dim InputBoxRangeCancelVariable As Range

  
ActiveSheet.Cells.Select

Selection.ClearFormats

If ActiveSheet.AutoFilterMode Or ActiveSheet.FilterMode Then
    ActiveSheet.ShowAllData
End If

'Now we need to get the data by which we are going to filter



    On Error Resume Next

    Set InputBoxRangeCancelVariable = Application.InputBox(Prompt:="Please select the cell which contains basis of the filter", Type:=8)

    On Error GoTo 0

    If InputBoxRangeCancelVariable Is Nothing Then

       MsgBox ("You have not selected anything")
       GoTo 0
    Else

        str3 = InputBoxRangeCancelVariable.Value
      

    End If
'We need to find the address of the range to be filtered which is expanding horizantally


    Sheets("Sheet1").Activate
ActiveSheet.Range("A1").Select
  
    Dim i As Long
    Dim count As Integer

    Dim str1 As String
    For i = 1 To 500000
    If ActiveCell.Value = "DOA(Month)" Then

    str1 = ActiveCell.Address
    Exit For
    Else
    ActiveCell.Offset(0, 1).Select
End If

  
  
  
  
  
    Next i
   
   
   
   ActiveSheet.Range(str1).Select
    For i = 1 To 500000
    If ActiveCell.Value = "" Then
  
    Exit For
    Else
    str1 = ActiveCell.Address
  
  
    ActiveCell.Offset(1, 0).Select
   
End If

  
  
  
  
  
    Next i
   str1 = Replace(str1, "$", "")
  
 For i = 1 To Len(str1)
If IsNumeric(Mid(str1, i, 1)) = False Then

temp = temp + Mid(str1, i, 1)

End If




 Next i


fieldname = Range(temp & 1).Column

 
    Dim str2 As String
    str2 = "A1:" & str1
 
   Selection.Clear



     ActiveSheet.Range(str2).AutoFilter Field:=fieldname, Criteria1:=str3
  

  
'as you have seen we are able to get the filtered data ,now let's create a sheet and copy paste the filtered data in the new sheet
'or there is a old sheet and we have to append the filtered data inside it,that'sour requirement

'Now let's create another sheet






str3 = str3 + " " + mydate

Dim signal As Boolean
signal = False


For i = 1 To ActiveWorkbook.Sheets.count



If ActiveWorkbook.Sheets(i).Name = str3 Then
signal = True
End If




Next i

If signal = False Then
'create the sheet as it is not present,and copy the filtered data with headers


Worksheets.Add(After:=Worksheets(Worksheets.count)).Name = str3
'copy and paste
Sheets("Sheet1").Select

 Range("A1").Select
    Range(Selection, Selection.End(xlToRight)).Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.Copy
    Sheets(str3).Select
    Range("A1").Select
   
    ActiveSheet.Paste
Else
'here the sheet is already present


Sheets(str3).Activate
If Range("A1").Value <> "" Then



Sheets("Sheet1").Select

 Range("A2").Select
    Range(Selection, Selection.End(xlToRight)).Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.Copy
   
  Else
  Sheets("Sheet1").Select

 Range("A1").Select
    Range(Selection, Selection.End(xlToRight)).Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.Copy

End If

Sheets(str3).Select
Range("A1").Select
While ActiveCell.Value <> ""
ActiveCell.Offset(1, 0).Select




Wend

ActiveSheet.Paste


End If
Application.CutCopyMode = False

  
  
0:
End Sub

Monday, September 3, 2018

Connect to access database ,run query and fetch the result in excel using VBA,VBA Teacher Sourav,Kolkata 09748184075

Sub getDataFromAccess()
' Click on Tools, References and select
' the Microsoft ActiveX Data Objects 2.0 Library

Dim DBFullName As String
Dim Connect As String, Source As String
Dim Connection As ADODB.Connection
Dim Recordset As ADODB.Recordset
Dim Col As Integer

Cells.Clear

' Database path info

' Your path will be different
DBFullName = "C:\Users\sourav\Desktop\Database6.accdb"
' Open the connection
Set Connection = New ADODB.Connection
Connect = "Provider=Microsoft.ACE.OLEDB.12.0;"
Connect = Connect & "Data Source=" & DBFullName & ";"
Connection.Open ConnectionString:=Connect

' Create RecordSet
Set Recordset = New ADODB.Recordset
With Recordset
' Filter Data
Source = "SELECT * FROM QWERTY"
'Source = "SELECT * FROM Customers WHERE [Job Title] = 'Owner' "
.Open Source:=Source, ActiveConnection:=Connection

' MsgBox “The Query:” & vbNewLine & vbNewLine & Source

' Write field names

For Col = 0 To (Recordset.Fields.Count - 1)


Range("A1").Offset(0, Col).Value = Recordset.Fields(Col).Name
Next

' Write recordset
Range("A1").Offset(1, 0).CopyFromRecordset Recordset
End With
ActiveSheet.Columns.AutoFit
Set Recordset = Nothing
Connection.Close
Set Connection = Nothing
End Sub

Wednesday, August 8, 2018

Automatic filtering of excel data and save the filtered data in a pdf using VBA ,VBA Teacher Sourav,Kolkata 09748184075

Sub filter_pdf()

'We need to remove all filters first

Workbooks(ActiveWorkbook.Name).Activate
    Sheets("Sheet1").Activate
    Dim str3 As String



   
ActiveSheet.Cells.Select

Selection.ClearFormats

If ActiveSheet.AutoFilterMode Or ActiveSheet.FilterMode Then
    ActiveSheet.ShowAllData
End If

'Now we need to get the data by which we are going to filter

Dim Message, Title, Default
Message = "Enter a value "    ' Set prompt.
Title = "InputBox Demo"    ' Set title.
Default = "1"    ' Set default.
' Display message, title, and default value.
str3 = InputBox(Message, Title, Default)

'We need to find the address of the range to be filtered which is expanding horizantally


    Sheets("Sheet1").Activate
ActiveSheet.Range("A1").Select
   
    Dim i As Long
    Dim count As Integer

    Dim str1 As String
    For i = 1 To 500000
    If ActiveCell.Value = "Sales" Then
    str1 = ActiveCell.Address
    Exit For
    Else
    ActiveCell.Offset(0, 1).Select
End If

   
   
   
   
   
    Next i
    MsgBox (str1)
   ActiveSheet.Range(str1).Select
    For i = 1 To 500000
    If ActiveCell.Value = "" Then
   
    Exit For
    Else
    str1 = ActiveCell.Address
   
   
    ActiveCell.Offset(1, 0).Select
End If

   
   
   
   
   
    Next i
   
 
   MsgBox (str1)
  
    Dim str2 As String
    str2 = "A1:" & str1
    MsgBox (str2)
   Selection.Clear
   ActiveSheet.Range(str2).AutoFilter Field:=1, Criteria1:=str3, Operator:=xlAnd
  
  
   'Now the filtered data is presented in the sheet.we need to convert this result into a pdf
  
   Dim customer_code As String
Dim pdffolder As FileDialog

customer_code = Range("A2").Text


Set pdffolder = Application.FileDialog(msoFileDialogFolderPicker)
pdffolder.AllowMultiSelect = False
pdffolder.Show

  
   
        Dim dir As String
        dir = pdffolder.SelectedItems(1)
   
        ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=dir & "\" & customer_code & ".pdf", openafterpublish:=False
               
        MsgBox ("PDF Generated")
               
     
       

End Sub

Sort an user defined portion of excel table or range or data using VBA,VBA Teacher Sourav,Kolkata 8910141720


Sub Macro1()
'
' Macro1 Macro
'

'
Dim selectrange As Range
Dim sorton As Range
Set selectrange = Application.InputBox(prompt:="select the cells for the range", Type:=8)

Set sorton = Application.InputBox(prompt:="select the cells for the range to be sorted", Type:=8)
  
    ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add2 Key:=Range(sorton.Address) _
        , sorton:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Sheet1").Sort
        .SetRange Range(selectrange.Address)
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End Sub

Convert a complete or partial worksheet of excel to pdf using VBA ,VBA Teacher Sourav,Kolkata 8910141720

Private Sub CommandButton1_Click()

Dim code As String
Dim mtd As String
Dim pdffolder As FileDialog

code = Range("m3").Text
mtd = Range("u7").Text

Set pdffolder = Application.FileDialog(msoFileDialogFolderPicker)
pdffolder.AllowMultiSelect = False
pdffolder.Show

    If Range("m3") = "" Then
   
        MsgBox ("Please Enter a Stockist Code")
       
    Else
   
        Dim dir As String
        dir = pdffolder.SelectedItems(1)
   
        ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=dir & "\" & code & "_" & mtd & ".pdf", openafterpublish:=False
               
        MsgBox ("PDF Generated")
               
        End If
       
End Sub

Use a variable inside find command in VBA,VBA Teacher Sourav,Kolkata 09748184075

Suppose I have a string variable containing subham$,to get the position of the dollar symbol we can use findcommand in excel ,however in VBA we have to use find like this




s = "subham$"
  x = Application.WorksheetFunction.Find("$", s)

s = Application.WorksheetFunction.Find("$", Range("A1"))



s = WorksheetFunction.Find("$", Range("A1"))

s = Application.Find("$", Range("A1"))

s = InStr(s, "$") 


ActiveCell.Formula = "=FIND(""$""," & """" & s & """" & ")"


 Sheets("Sheet1").Range("B1") = WorksheetFunction.Find("$", s, 1) 




Range("D1").FormulaR1C1 = "=FIND(""$"",""" & s & """)"

Saturday, June 30, 2018

Zip some files and put the zip file in a fixed folder automatically using shell script,Linux Teacher Sourav,Kolkata 09748184075

#!/bin/sh
#
# 01/07/2018
#

FN="/home/sourav/Desktop/shell scripts/work1.zip"
cd /tmp
mkdir work 2>/dev/null # suppress message if directory already exists
cd work
#cp /etc/motd .
cat /var/run/motd.dynamic > motd
cp /etc/issue .
ls -la /tmp > tmp.txt
ls -la /usr > usr.txt
rm "$FN" 2>/dev/null # remove any previous file
zip "$FN" *
echo File "$FN" created. # cp to an external drive, and/or scp to another computer
echo "End of automatic zipping using shell script"
exit 0

Setting an attractive message of the day(MOTD) banner in Ubuntu 16,Linux Teacher Sourav,Kolkata 09748184075

# install lsb-release
apt-get install lsb-release
# install figlet to enable ASCII art
apt-get install figlet
# install update-motd software
apt-get install update-motd
# delete default directory
rm -r /etc/update-motd.d/
# create new directory
mkdir /etc/update-motd.d/
# create dynamic files
touch /etc/update-motd.d/00-header ; touch /etc/update-motd.d/10-sysinfo ; touch /etc/update-motd.d/90-footer
# make files executable
chmod +x /etc/update-motd.d/*
# remove MOTD file
rm /etc/motd.dynamic


The 00-header file should contain

#!/bin/sh
#
#    00-header - create the header of the MOTD
#    Copyright (c) 2013 Nick Charlton
#    Copyright (c) 2009-2010 Canonical Ltd.
#
#    Authors: Nick Charlton
#             Dustin Kirkland
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License along
#    with this program; if not, write to the Free Software Foundation, Inc.,
#    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

[ -r /etc/lsb-release ] && . /etc/lsb-release

if [ -z "$DISTRIB_DESCRIPTION" ] && [ -x /usr/bin/lsb_release ]; then
        # Fall back to using the very slow lsb_release utility
        DISTRIB_DESCRIPTION=$(lsb_release -s -d)
fi

figlet $(hostname)
printf "\n"

printf "Welcome to %s (%s).\n" "$DISTRIB_DESCRIPTION" "$(uname -r)"
printf "\n"


****************************************************************************************
The 10-sysinfo file should contain


#!/bin/sh
TERM=linux
export TERM
upSeconds="$(/usr/bin/cut -d. -f1 /proc/uptime)"
secs=$((${upSeconds}%60))
mins=$((${upSeconds}/60%60))
hours=$((${upSeconds}/3600%24))
days=$((${upSeconds}/86400))
UPTIME=`printf "%d days, %02dh%02dm%02ds" "$days" "$hours" "$mins" "$secs"`

# get the load averages
read one five fifteen rest < /proc/loadavg

echo "$(tput setaf 2)
   .~~.   .~~.    `date +"%A, %e %B %Y, %r"`
  '. \ ' ' / .'   `uname -srmo`$(tput setaf 1)
   .~ .~~~..~.
  : .~.'~'.~. :   Uptime.............: ${UPTIME}
 ~ (   ) (   ) ~  Memory.............: `cat /proc/meminfo | grep MemFree | awk {'print $2'}`kB (Free) / `cat /proc/meminfo | grep MemTotal | awk {'print $2'}`kB (Total)
( : '~'.~.'~' : ) Load Averages......: ${one}, ${five}, ${fifteen} (1, 5, 15 min)
 ~ .~ (   ) ~. ~  Running Processes..: `ps ax | wc -l | tr -d " "`
  (  : '~' :  )   IP Addresses.......: `ip a | grep glo | awk '{print $2}' | head -1 | cut -f1 -d/` and `wget -q -O - http://icanhazip.com/ | tail`
   '~ .~~~. ~'    Weather............: `curl -s "http://rss.accuweather.com/rss/liveweather_rss.asp?metric=1&locCode=EUR|UK|UK001|NAILSEA|" | sed -n '/Currently:/ s/.*: \(.*\): \([0-9]*\)\([CF]\).*/\2°\3, \1/p'`
       '~'
$(tput sgr0)"


***************************************************************************************************
I also have a backup 10-sysinfo file which contains

#!/bin/bash
#
#    10-sysinfo - generate the system information
#    Copyright (c) 2013 Nick Charlton
#
#    Authors: Nick Charlton
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License along
#    with this program; if not, write to the Free Software Foundation, Inc.,
#    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

date=`date`
load=`cat /proc/loadavg | awk '{print $1}'`
root_usage=`df -h / | awk '/\// {print $(NF-1)}'`
memory_usage=`free -m | awk '/Mem:/ { printf("%3.1f%%", $3/$2*100) }'`
swap_usage=`free -m | awk '/Swap:/ { printf("%3.1f%%", $3/$2*100) }'`
users=`users | wc -w`
time=`uptime | grep -ohe 'up .*' | sed 's/,/\ hours/g' | awk '{ printf $2" "$3 }'`
processes=`ps aux | wc -l`
ip=`ifconfig $(route | grep default | awk '{ print $8 }') | grep "inet addr" | awk -F: '{print $2}' | awk '{print $1}'`

echo "System information as of: $date"
echo
printf "System Load:\t%s\tIP Address:\t%s\n" $load $ip
printf "Memory Usage:\t%s\tSystem Uptime:\t%s\n" $memory_usage "$time"
printf "Usage On /:\t%s\tSwap Usage:\t%s\n" $root_usage $swap_usage
printf "Local Users:\t%s\tProcesses:\t%s\n" $users $processes
echo
/usr/lib/update-notifier/update-motd-reboot-required
/usr/lib/update-notifier/apt-check --human-readable
echo

*************************************************************************************************

The 90-footer file contains

#!/bin/sh
#
#    99-footer - write the admin's footer to the MOTD
#    Copyright (c) 2013 Nick Charlton
#    Copyright (c) 2009-2010 Canonical Ltd.
#
#    Authors: Nick Charlton
#             Dustin Kirkland
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License along
#    with this program; if not, write to the Free Software Foundation, Inc.,
#    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

[ -f /etc/motd.tail ] && cat /etc/motd.tail || true

***********************************************************************************************


Now you should see this motd message when you try to login in a different run level

to see this in gui which is run level 7 you have to type

cat /var/run/motd.dynamic



Source:
https://oitibs.com/ubuntu-16-04-dynamic-motd/
https://ownyourbits.com/2017/04/05/customize-your-motd-login-message-in-debian-and-ubuntu/

reference
https://www.resellerspanel.com/articles/cloud-web-hosting-articles/crontab/which-files-can-be-executed-with-crontab/
https://askubuntu.com/questions/319528/how-to-see-the-details-which-ubuntu-shows-at-the-time-of-login-anytime




Thursday, May 31, 2018

Gracefully Exit Firefox using shell script and xdotool,Linux Teacher Sourav,Kolkata 09748184075

sudo apt-get install xdotool

if [[ -n `pidof firefox` ]];then
  WID=`xdotool search "Mozilla Firefox" | head -1`
  xdotool windowactivate --sync $WID
  xdotool key --clearmodifiers ctrl+q
fi



Source:http://how-to.wikia.com/wiki/How_to_gracefully_kill_(close)_programs_and_processes_via_command_line

Sending notifications alert to the User if battery status getting less than a threshold and shutdown the pc using shell script,Linux Teacher Sourav,Kolkata 09748184075

#!/bin/bash
#01/06/2018


while true
do
    battery_level=`acpi -b | acpi -b | cut -f4 -d ' '|tr -d ',%'`
    if [ $battery_level -le 5 ]; then
       notify-send "Battery is less than 5%!" "Charging: ${battery_level}%" " Please connect the charger ,the system will shutdown after 2 minute"
shutdown -P +2 "Shutdown script started"
  
    elif [ $battery_level -le 20 ]; then
       notify-send "Battery is lower than 20%!" "Please connect the charger: ${battery_level}%"
      

 

    fi

    sleep 10 # run this script in every 10 seconds
done


Source:https://askubuntu.com/questions/518928/how-to-write-a-script-to-listen-to-battery-status-and-alert-me-when-its-above?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

Saturday, May 26, 2018

Shell script to play Constant sound until user press a button when a new user logs on,Linux Teacher Sourav,Kolkata 09748184075

#!/bin/sh
#
# 27/05/2018
#
export BEEP=/usr/share/sounds/ubuntu/ringtones/Harmonics.ogg
alias beep='paplay $BEEP'
beepsound()
{
while [ 1 ]
do
beep
 read -t 0.25 -N 1 input
    if [[ $input = "q" ]] || [[ $input = "Q" ]]; then
# The following line is for the prompt to appear on a new line.
        echo
        exit

    fi
done
}

echo "New User Login Alert,Press Q to stop the beep"
numusers=`who | wc -l`
while [ true ]
do
currusers=`who | wc -l`
# get current number of users
if [ $currusers -gt $numusers ] ; then
echo "Someone new has logged on!!!!!!!!!!!"
date
who

beepsound
numusers=$currusers
elif [ $currusers -lt $numusers ] ; then
echo "Someone logged off."
date
numusers=$currusers
fi
sleep 1 # sleep 1 second
done



Friday, May 25, 2018

Do a task if your partition usage is greater than a given percentage using shell script,Linux Teacher Sourav,Kolkata 09748184075

a=$(df -h | grep -E 'root' | awk ' { print $5 " " $1}' | cut -f1 -d " " )
echo $a

b=${a::-1}
echo $b
if [ $b -ge 90 ] ; then
echo "hello"
else
echo "nope"
fi


in terminal you do it like this

df -H | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }' | awk '{ print $1}' | cut -d '%' -f1 

Check a string if it is palindrome in shell script using rev command and without the use of rev command,Linux Teacher Sourav,Kolkata 09748184075

#/bin/sh
#25/05/2018

#in our class there is a very common task to see a string is palindrome or not

#for example aba is a string that will be same when altered from the opposite direction

#another example is 1991
#do you understand the assignment
#yes

#so let us ask the user to give us a string

echo "Please enter a string to be checked whether it is a palindrom"

read answer

echo "the string you entered is stored in the answer variable and it is $answer"

#there is an utility called rev by which we can do it just by a command

reverse=`echo $answer | rev`
#echo $reverse
#if [ $answer == $reverse ] ; then

#echo "the entered string is palindrome"

#else

#echo "the entered string is not palindrome"

#fi


#so it's working,however if we like we can do it without the use of rev command

#this backtick is used for evaluation ,like whatever inside the backtick will be evaluated

#and then be assigned to the left side

#wso to perform the same task without using rev

#we need to find the length of the string(for example the length of hello is 5

lenofword=$(echo -n $answer | wc -m)

echo the length of the word is $lenofword


#i am using shell command wc -m to get the character count,what could the problem
#for character we use -c, right?


#yes my mistake
#for some reason it's not working right now ,let me search a solution and will get back to you
#ok. leave it here. now can we work on the script i shared.


#yes sure

#i will come back to this later
#sometimes in shell script i forget the syntax,will check surely
reverse=""
for(( i=lenofword;i>=0;i--)) ; do
reverse+=${answer:i:1}



done

#echo $reverse

if [ $answer == $reverse ] ; then

echo "the entered string is palindrome"

else

echo "the entered string is not palindrome"

fi

Wednesday, May 23, 2018

Trap in shell script,invoking subroutine using a key combination,Linux Teacher Sourav,Kolkata 09748184075

#!/bin/sh
#
# 23/05/2018
#
echo "Usage of trap in Shell Script,for example a key combination can invoke a subroutine"
trap catchCtrlC INT
# Initialize the trap
# Subroutines
catchCtrlC()
{
echo "Entering catchCtrlC routine."
}
# Code starts here
echo "Press Ctrl-C to trigger the trap, 'Q' to exit."
loop=0
while [ $loop -eq 0 ]
do
read -t 1 -n 1 str
rc=$?
if [ $rc -gt 128 ] ; then
echo "Timeout exceeded."
fi
if [[ "$str" = "q" || "$str" = "Q" ]] ; then
echo "Exiting the script."
# wait 1 sec for input or for 1 char
loop=1
fi
done
exit 0

Tuesday, May 22, 2018

Make your Shell Script interactive using read command,Linux Teacher Sourav,Kolkata 09748184075

#!/bin/sh
#
# 23/05/2018
#
echo "Usage Of Read Command in Linux"
rc=0 # return code
while [ $rc -eq 0 ]
do
read -p "Enter value or q to quit: " var
echo "var: $var"
if [ "$var" = "q" ] ; then
rc=1
fi
done
rc=0 # return code
while [ $rc -eq 0 ]
do
read -p "Password: " -s var
echo ""
# carriage return
echo "var: $var"
if [ "$var" = "q" ] ; then
rc=1
fi
done
echo "Press some keys and q to quit."
rc=0
# return code
while [ $rc -eq 0 ]
do
read -n 1 -s var # wait for 1 char, does not output it
echo $var # output it here
if [ "$var" = "q" ] ; then
rc=1
fi
done
exit $rc

Monday, May 21, 2018

Automatic backing up a file if any changes occur in a regular interval,Linux Teacher Sourav,Kolkata 09748184075



 sh ./autobackup.sh a1.txt usb/ 3

 autobackup.sh=script name

a1.txt=file to be monitored

3=interval of checking in seconds

 autobackup.sh

#!/bin/sh
#
# automatically creating a backup of a file if the any changes to the file occurs
# the script that automatically backs up everytime with an incremented number is needed
# Checks that /back exists
# Copies to specific USB directory# Checks if filename.bak exists on startup, copy if it doesn't
# 22/05/2018
if [ $# -ne 3 ] ; then
echo "Usage: autobackup filename USB-backup-dir delay"
exit 255
fi
# Create back directory if it does not exist
if [ ! -d back ] ; then
mkdir back
fi
FN=$1 # filename to monitor
USBdir=$2 # USB directory to copy to
DELAY=$3 # how often to check
if [ ! -f $FN ] ; then # if no filename abort
echo "File: $FN does not exist."
exit 5
fi
if [ ! -f $FN.bak ] ; then
cp $FN $FN.bak
fi
filechanged=0
while [ 1 ]
do
cmp $FN $FN.bak
rc=$?
if [ $rc -ne 0 ] ; then
cp $FN back
cp $FN $USBdir
cd back
sh ./createnumberedbackup.sh $FN
cd ..
cp $FN $FN.bak
filechanged=1
fi
sleep $DELAY
done
****************************************************
createnumberedbackup.sh


#!/bin/sh
#let me show you this script which is able to back up of files in the same directory and number
#the backup,in devops it is very common the save the project with revision number,this
#script is not that complex though


echo "Create Numbered Backup from files of the current directory given as argument"
if [ $# -eq 0 ] ; then
echo "Usage: sh ./createnumberedbackup.sh filename(s) "
echo " Will make a numbered backup of the files(s) given."
echo " Files must be in the current directory."
exit 255
fi
rc=0 # return code, default is no error
for fn in $*  # for each filename given as arguments

do
if [ ! -f $fn ] ; then # if not found
echo "File $fn not found."
rc=1 # one or more files were not found
else
cnt=1 # file counter
loop1=0 # loop flag
while [ $loop1 -eq 0 ]
do
tmp=bak-$cnt.$fn
if [ ! -f $tmp ] ; then
cp $fn $tmp
echo "File "$tmp" created."
loop1=1
# end the inner loop
else
let cnt++ # try the next one
fi
done
fi
done
exit $rc # exit with return code


#every time you run this script with arguments if it finds backup file created by itself

#it will create the next backup with incrementing numbers so the backup can

#more organized


Using TPUT command to change cursor position in a Shell Script,Linux Teacher Sourav,Kolkata 09748184075

#!/bin/sh
# 21/05/2018
# script4
# Subroutines Example
export LINES=$LINES
export COLUMNS=$COLUMNS
#echo $LINES
cls()
{
tput clear
return 0
}
home()
{
tput cup 0 0
return 0
}

bold()
{
tput smso
# no newline or else will scroll
}
unbold()
{
tput rmso
}
underline()
{
tput smul
}
normalline()
{
tput rmul
}
end()
{
#x="${COLUMNS}"-1
let x=$COLUMNS-1

let y=$LINES
#echo x is $x
#echo y is $y
tput cup $y $x
echo -n ""
}
# Code starts here
rc=0
# return code
if [ $# -ne 1 ] ; then
echo "Usage: script4 parameter"
echo "Where parameter can be: "
echo " home - put an X at the home position"
echo " cls - clear the terminal screen"
echo " end - put an X at the last screen position"
echo " bold - bold the following output"
echo " underline - underline the following output"
exit 255
fi
parm=$1
# main parameter 1
if [ "$parm" = "home" ] ; then
echo "Calling subroutine home."
home
echo -n "X"
elif [ "$parm" = "cls" ] ; then
cls
elif [ "$parm" = "end" ] ; then
echo "Calling subroutine end."
end
elif [ "$parm" = "bold" ] ; then
echo "Calling subroutine bold."
bold
echo "After calling subroutine bold."
unbold
echo "After calling subroutine unbold."
elif [ "$parm" = "underline" ] ; then
echo "Calling subroutine underline."
underline
echo "After subroutine underline."
normalline
echo "After subroutine normalline."
else
echo "Unknown parameter: $parm"
rc=1
fi
exit $rc

Saturday, May 19, 2018

Create Numbered backup files from the current working directory given as arguments,Linux Teacher Sourav,Kolkata 09748184075

#!/bin/sh
#
echo "Create Numbered Backup from files of the current directory given as argument"
if [ $# -eq 0 ] ; then
echo "Usage: sh ./createnumberedbackup.sh filename(s) "
echo " Will make a numbered backup of the files(s) given."
echo " Files must be in the current directory."
exit 255
fi
rc=0 # return code, default is no error
for fn in $*  # for each filename given as arguments

do
if [ ! -f $fn ] ; then # if not found
echo "File $fn not found."
rc=1 # one or more files were not found
else
cnt=1 # file counter
loop1=0 # loop flag
while [ $loop1 -eq 0 ]
do
tmp=bak-$cnt.$fn
if [ ! -f $tmp ] ; then
cp $fn $tmp
echo "File "$tmp" created."
loop1=1
# end the inner loop
else
let cnt++ # try the next one
fi
done
fi
done
exit $rc # exit with return code


Usage:


sh ./createnumberedbackup.sh a1.txt a2.txt

Friday, May 18, 2018

Shell script to watch a process and inform when it ends ,Linux Teacher Sourav,Kolkata 09748184075

#!/bin/sh
#
# 18/5/2018
#
echo "this shell script will watch when a process ends"
if [ $# -ne 1 ] ; then
echo "Usage: processwatcher process-directory"
echo " For example: processwatcher /proc/14856 where 14856 is the PID of the  target process"
exit 255
fi
FN=$1
# process directory i.e. /proc/14856
rc=1
while [ $rc -eq 1 ]
do
if [ ! -d $FN ] ; then
# if directory is not there
echo "Process $FN is not running or has been terminated."
let rc=0
else
sleep 1
fi
done
echo "End of processwatcher script"
exit 0

I have given the name of this script as processwatcher.sh,suppose another job or process is going on simultaneously and i want to know when it ends ,my script will serve that purpose when we run it with the Process ID of the target process or job as an argument to this shell script

For example we created this shell script to show the usage of break and continue in shell scripting ,it will run for a certain amount of time

#!/bin/sh
#
# 18/5/2018
#
echo "Break Continue Example"
FN1=/tmp/break.txt
FN2=/tmp/continue.txt
x=1
while [ $x -le 1000000 ]
do
echo "x:$x"
if [ -f $FN1 ] ; then
echo "Running the break command"
rm -f $FN1
break
fi
if [ -f $FN2 ] ; then
echo "Running the continue command"
rm -f $FN2
continue
fi
let x++
sleep 2
done
echo "x:$x"
echo "End"
exit 0


we first run it from the terminal

sh ./breakandcontunue.sh


Now to see what process ID it has while running we need to use the grep command


ps auxw | grep break* | grep -v grep

the last piped section was to filter the grep search which itself acts as a process

the output is like this

sourav   14856  0.0  0.0  12876  2996 pts/1    S+   20:05   0:00 sh ./breakandcontunue.sh

So the PID as we can see is 14856


so in the /proc/folder we should find a folder named 14856 and it will continue to exist while this script/process/job runs

our shell script processwatcher is basically checking the existence of this folder and thus if the process is running with an interval of 1 second with the help of sleep command



 
      

Usage of break and continue statement in a shell script,Linux Teacher Sourav,Kolkata 09748184075

#!/bin/sh
#
# 18/5/2018
#
echo "Break Continue Example"
FN1=/tmp/break.txt
FN2=/tmp/continue.txt
x=1
while [ $x -le 1000000 ]
do
echo "x:$x"
if [ -f $FN1 ] ; then
echo "Running the break command"
rm -f $FN1
break
fi
if [ -f $FN2 ] ; then
echo "Running the continue command"
rm -f $FN2
continue
fi
let x++
sleep 1
done
echo "x:$x"
echo "End"
exit 0

You can test the script after creating the necessary files such as continue.txt and break.txt in the /tmp folder


touch /tmp/continue.txt

and the script will continue till x gets 1000000

to stop this use the tab feature in terminal and in a different tab use
touch /tmp/break.txt

The shell script will stop using the break statement

Using Let command in shell script error command not found solved,Linux Teacher Sourav,Kolkata 09748184075

If anyone is trying to learn shell script in ubuntu (in my case ubuntu 16.04), he or she might found out that bash built in commands such as let giving you command not found error ,to solve this you need to understand even if you put the line #!/bin/sh at the top of your script /bin/sh on ubuntu is dash not bash

So to solve this you need to reconfigure dash to not be the default shell

The command to accomplish this is

sudo dpkg-reconfigure dash


press no when asked for whether you like dash to be the default

and then everything should work fine


Source:https://ubuntuforums.org/showthread.php?t=1377218

Thursday, May 10, 2018

Send a message in your phone using VBA and TextLocal API.VBA Teacher Sourav,Kolkata 09748184075

Private Sub Command1_Click()
  
        Dim username As String
        Dim password As String
        Dim result As String
        Dim myURL As String
        Dim Sender As String
        Dim numbers As String
        Dim Message As String
        Dim postData As String
        Dim winHttpReq As Object
        apikey = Text1.Text
        Sender = Text2.Text
        numbers = Text3.Text
        Message = Text4.Text
    
        Set winHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1")
    
        myURL = "https://api.textlocal.in/send/?"
        postData = "apikey=" + apikey + "&message=" + Message + "&numbers=" + numbers + "&sender=" + Sender
    
        winHttpReq.Open "POST", myURL, False
        winHttpReq.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
        winHttpReq.Send (postData)
    
        sendsms = winHttpReq.responseText
        MsgBox (sendsms)
       
    End Sub
   

**For promotional account which is mine the sender should be blank

**Due to TRI NCCP regulation after 9 pm and before 9 am you can not send message (error 192)
   


I followed this tutorial

https://www.youtube.com/watch?v=fc5ZNMXb4Fo

Tuesday, May 8, 2018

WI-FI getting disconnected/Networks not showing up on Ubuntu 16.04 solved ,Linux Teacher Sourav,Kolkata 09748184075


Install rfkill

sudo apt-get install rfkill
then run this command

rfkill unblock all
check if the wifi is working. If not do this

sudo nano /var/lib/NetworkManager/NetworkManager.state
then you will see some settings. Set everything to "true" reboot your system

give this command in terminal

rfkill list
you'll see that some are softblocked and hardblocked. All of them should be "no".

If it's not "no" then you need to somehow turn them to "no". I did this and it worked for me

sudo modprobe -r acer-wmi
cd /etc/modprobe.d
sudo nano blacklist.conf
Then add blacklist acer-wmi as a new line at the end of the file.

then save the file by pressing Ctrl+O ,close it and reboot the system. It should work

Source:https://askubuntu.com/questions/769521/wifi-networks-are-not-showing-in-ubuntu-16-04?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

Friday, May 4, 2018

Install PHPMyAdmin after installing Mysql on Ubuntu 16.04

 sudo apt-get update
    sudo apt-get install phpmyadmin php-mbstring php-gettext

After opening PHPMyAdmin if you create a database and open it you may see

CONNECTION FOR CONTROLUSER AS DEFINED IN YOUR CONFIGURATION FAILED

You have to open this file

/etc/phpmyadmin/config-db.php

and see if the configuration is like this

$dbuser='root';
$dbpass='password'; // set current password between quotes ' '
$basepath='';
$dbname='phpmyadmin';
$dbserver='';
$dbport='';
$dbtype='mysql';

save and close the file

restart mysql server by

sudo service mysql stop

sudo service mysql start


Thursday, April 19, 2018

Oracle 11g basics,part 1,Oracle Teacher Sourav,Kolkata 09748184075

set ORACLE_SID=sysdba

echo %ORACLE_SID%

set ORACLE_HOME=E:\app\sourav\product\11.2.0\dbhome_1

echo %ORACLE_HOME%

Now connect to oracle

start sqlplus

sqlplus /nolog

connect as sysdba

connect / as sysdba;

run a sample query and find the name of the databse you are connected to


select name from v$database;

to see the instance name which you are connected with

select * from global_name;


exit

Now we like to use the sql developer



****************************************************


shut down the database


log in as sysdba

shutdown immediate;

exit


start the database

log in as sysdba

startup;



***********************************************************
Data types supported by oracle

char
varchar2
number
date
timestamp
BLOB
CLOB
User Defined data types


*****************************************************************

Find the number of rows in a table

select count(*) from dba_tablespaces;

(dba_tablespaces give information about tablespaces,during the installation oracle create some tablespaces by default,those tablespaces hold all the data)
to find all the tablespaces currently existing in the database


select * from dba_tablespaces;


we can select particular columns using select such as

select TABLESPACE_NAME,STATUS from DBA_TABLESPACES;

we can also change the order by changing the name of columns







****************************************************************


to know the structure of the table use describe

describe dba_tablespaces;

desc dba_tablespaces;


***************************************************************


to find the total number of rows in a table

select count(*) from dba_tablespaces;


***************************************************************


filtering data using where clause


select * from dba_roles where role='CONNECT';


*****************************************************************


To make your pc faster

go to services.msc

and change these services startup from automatic to manual as written below

(My oracle instance name is sysdba instead of orcl)

Oracledbconsolesysdba

oraclemtsrecoveryservice

oracleoradb11g_home1tnslistener

oracleservicesysdba


you have to start these services manually every time you want to use oracle



*********************************************************************

Find the user list for your oracle database;

select username from dba_users;

let's see if the user scott is enabled or disabled

SELECT username, account_status   from dba_users;

if you find the username scott is locked let's try to enable/unlock that user

alter user scott account unlock;

let's logout and try to use scott

exit


sqlplus /nolog

if you use this command to connect connect using scott and the password tiger it
will prompt you to change the password as it is expired


you could also change the user status and password in a same line such as

alter user hr identified by 123456 account unlock;

after loggin in you can verify it by using this sql command

select * from global_name

then go to sql developer and create another connect using hr and password 123456 and see the tables created for the hr schema




*****************************************************************************************

directly login as scott


sqlplus scott/tiger@orcl


show the date

SELECT SYSDATE FROM dual;


login as sysdba and run the storeschema.sql

To end SQL*Plus, you enter EXIT. To reconnect to the store schema
in SQL*Plus, you enter store as the user name with a password
of store_password.


connect using sqlplus like this

sqlplus store@sysdba

enter the password



****************************************************************************************************

creating the database user


CREATE USER sourav IDENTIFIED BY 123456;

If you want the user to be able to work in the database, the user must be granted the
necessary permissions to do that work. In the case of store, this user must be able to log onto
the database (which requires the connect permission) and create items like database tables
(which requires the resource permission). Permissions are granted by a privileged user (for
example, the system user) using the GRANT statement.



GRANT connect, resource TO sourav;


*************************************************************************************************************


Oracle data types explanation


Format Number Supplied Number Stored
NUMBER 1234.567 1234.567
NUMBER(6, 2) 123.4567 123.46
NUMBER(6, 2) 12345.67 Number exceeds the specified precision and
is therefore rejected by the database.


CHAR(length) Stores strings of a fixed length. The length parameter specifies
the length of the string. If a string of a smaller length is stored, it
is padded with spaces at the end. For example, CHAR(2) may
be used to store a fixed-length string of two characters; if 'C' is
stored in a CHAR(2), then a single space is added at the end;
'CA' is stored as is, with no padding.


VARCHAR2(length) Stores strings of a variable length. The length parameter specifies
the maximum length of the string. For example, VARCHAR2(20)
may be used to store a string of up to 20 characters in length. No
padding is used at the end of a smaller string.


DATE Stores dates and times. The DATE type stores the century, all four
digits of a year, the month, the day, the hour (in 24-hour format),
the minute, and the second. The DATE type may be used to store
dates and times between January 1, 4712 B.C. and December 31,
4712 A.D.


INTEGER Stores integers. An integer doesn’t contain a floating point: it is a
whole number, such as 1, 10, and 115.


NUMBER(precision,scale)
Stores floating point numbers, but may also be used to store
integers. The precision is the maximum number of digits
(left and right of a decimal point, if used) that may be used for
the number. The maximum precision supported by the Oracle
database is 38. The scale is the maximum number of digits to
the right of a decimal point (if used). If neither precision nor
scale is specified, any number may be stored up to a precision
of 38 digits. Any attempt to store a number that exceeds the
precision is rejected by the database.


BINARY_FLOAT Introduced in Oracle Database 10g, stores a single precision
32-bit floating point number. You’ll learn more about BINARY_
FLOAT later in the section “The BINARY_FLOAT and BINARY_
DOUBLE Types.”


BINARY_DOUBLE Introduced in Oracle Database 10g, stores a double precision
64-bit floating point number.

using sql developer if you connect using store to enter the store schema you will see

The customers table holds the details of the customers. The
following items are held in this table:
First name
Last name
Date of birth (dob)
Phone number

to create a table like in this schema the sql command is this


CREATE TABLE customers (
customer_id INTEGER CONSTRAINT customers_pk PRIMARY KEY,
first_name VARCHAR2(10) NOT NULL,
last_name VARCHAR2(10) NOT NULL,
dob DATE,
phone VARCHAR2(12)
);



As you can see, the customers table contains five columns,

one for each item in the

previous list, and an extra column named customer_id. The columns are
customer_id Contains a unique integer for each row in the table. Each table should
have one or more columns that uniquely identifies each row; the column(s) are known as
the primary key. The CONSTRAINT clause indicates that the customer_id column is the
primary key. A CONSTRAINT clause restricts the values stored in a column, and, for the
customer_id column, the PRIMARY KEY keywords indicate that the customer_id
column must contain a unique value for each row. You can also attach an optional
name to a constraint, which must immediately follow the CONSTRAINT keyword—for
example, customers_pk. You should always name your primary key constraints, so
that when a constraint error occurs it is easy to spot where it happened.


first_name Contains the first name of the customer. You’ll notice the use of the NOT
NULL constraint for this column—this means that a value must be supplied for first_
name when adding or modifying a row. If a NOT NULL constraint is omitted, a user
doesn’t need to supply a value and the column can remain empty.

last_name Contains the last name of the customer. This column is NOT NULL, and
therefore a value must be supplied when adding or modifying a row.
dob Contains the date of birth for the customer. Notice that no NOT NULL constraint is
specified for this column; therefore, the default NULL is assumed, and a value is optional
when adding or modifying a row.

phone Contains the phone number of the customer. This is an optional value.


You can see the rows in the customers table for yourself by executing the following
SELECT statement using SQL*Plus:
SELECT * FROM customers;

The product_types table holds the names of the product
types sold by the store. This table is created by the store_schema.sql script using the
following CREATE TABLE statement:


CREATE TABLE product_types (
product_type_id INTEGER CONSTRAINT product_types_pk PRIMARY KEY,
name VARCHAR2(10) NOT NULL
);



The product_types table contains the following two columns:

product_type_id uniquely identifies each row in the table; the product_type_id
column is the primary key for this table. Each row in the product_types table must
have a unique integer value for the product_type_id column.

name contains the product type name. It is a NOT NULL column, and therefore a value
must be supplied when adding or modifying a row.

You can see the rows in the product_types table for yourself by executing the following
SELECT statement using SQL*Plus:

SELECT * FROM product_types;


The products Table The products table holds the products sold by the store. The
following pieces of information are held for each product:
Product type
Name
Description
Price

The sql for creating the product table


CREATE TABLE products (
product_id INTEGER CONSTRAINT products_pk PRIMARY KEY,
product_type_id INTEGER
CONSTRAINT products_fk_product_types
REFERENCES product_types(product_type_id),
name VARCHAR2(30) NOT NULL,
description VARCHAR2(50),
price NUMBER(5, 2)
);


The columns in this table are as follows:

product_id uniquely identifies each row in the table. This column is the primary key
of the table.

product_type_id associates each product with a product type. This column is a
reference to the product_type_id column in the product_types table; it is known
as a foreign key because it references a column in another table. The table containing
the foreign key (the products table) is known as the detail or child table, and the table
that is referenced (the product_types table) is known as the master or parent table.

This type of relationship is known as a master-detail or parent-child relationship. When
you add a new product, you associate that product with a type by supplying a matching
product_types.product_type_id value in the products.product_type_id
column .

name contains the product name, which must be specified, as the name column is
NOT NULL.

description contains an optional description of the product.

price contains an optional price for a product. This column is defined as NUMBER(5,
2)—the precision is 5, and therefore a maximum of 5 digits may be supplied for this
number. The scale is 2; therefore 2 of those maximum 5 digits may be to the right of the
decimal point.

***********************************************************************************************************


Adding modifying and removing rows in a table

Adding a Row to a Table
You use the INSERT statement to add new rows to a table. You can specify the following
information in an INSERT statement:

The table into which the row is to be inserted
A list of columns for which you want to specify column values
A list of values to store in the specified columns
When inserting a row, you need to supply a value for the primary key and all other columns
that are defined as NOT NULL. You don’t have to specify values for the other columns if you don’t
want to; those columns will be automatically set to null if you omit values for them.
You can tell which columns are defined as NOT NULL using the SQL*Plus DESCRIBE
command. The following example DESCRIBEs the customers table:

SQL> DESCRIBE customers
Name Null? Type
----------------------------------------- -------- ------------
CUSTOMER_ID NOT NULL NUMBER(38)
FIRST_NAME NOT NULL VARCHAR2(10)
LAST_NAME NOT NULL VARCHAR2(10)
DOB DATE
PHONE VARCHAR2(12)

As you can see, the customer_id, first_name, and last_name columns are NOT NULL,
meaning that you must supply a value for these columns. The dob and phone columns don’t
require a value; you could omit the values if you wanted, and they would be automatically set to null.
Go ahead and run the following INSERT statement, which adds a row to the customers
table; notice that the order of values in the VALUES list matches the order in which the columns
are specified in the column list:

SQL> INSERT INTO customers (
 customer_id, first_name, last_name, dob, phone) VALUES ( 6, 'Fred', 'Brown', '01-JAN-1970', '800-555-1215' );


SELECT *
FROM customers;

will show the added row


Possible error when inserting


When a row is added to the customers table, a unique value for the customer_id column
must be given. The Oracle database will prevent you from adding a row with a primary key value
that already exists in the table; for example, the following INSERT statement causes an error
because a row with a customer_id of 1 already exists:
SQL> INSERT INTO customers (
2 customer_id, first_name, last_name, dob, phone
3 ) VALUES (
4 1, 'Lisa', 'Jones', '02-JAN-1971', '800-555-1225'
5 );
INSERT INTO customers (
*
ERROR at line 1:
ORA-00001: unique constraint (STORE.CUSTOMERS_PK) violated


Modifying an Existing Row in a Table


You use the UPDATE statement to change rows in a table. Normally, when you use the UPDATE
statement, you specify the following information:
The table containing the rows that are to be changed
A WHERE clause that specifies the rows that are to be changed
A list of column names, along with their new values, specified using the SET clause
You can change one or more rows using the same UPDATE statement. If more than one row is
specified, the same change will be made for all the rows. The following example updates customer
#2’s last_name to Orange:

UPDATE customers
SET last_name = 'Orange'
WHERE customer_id = 2;
1 row updated.
SQL*Plus confirms that one row was updated.


SELECT *
FROM customers
WHERE customer_id = 2;


Removing a Row from a Table

You use the DELETE statement to remove rows from a table. You typically use a WHERE clause to
limit the rows you wish to delete; if you don’t, all the rows will be deleted from the table.
The following DELETE statement removes customer #2:
DELETE FROM customers
WHERE customer_id = 2;
1 row deleted.
To undo the changes you’ve made to the rows, you use ROLLBACK:
ROLLBACK;


********************************************************************

show all the tables in your schema

log in as store

conn store@sysdba;

enter password

select TABLE_NAME from user_tables



************************************************************************


To see the post number and the instance name of your oracle database

open this file in notepad

E:\app\sourav\product\11.2.0\dbhome_1\NETWORK\ADMIN\tnsnames.ora

*******************************************************************************