Python - auto-mate/CheatSheetWiki GitHub Wiki

Python

Add No To String
Arguments
Array
Calculator
Class
Comment
Curl
Dir Listing
File Read
File Write
For
Functions User
If
Lambda
Notepad
Print
PyTorch
SQL Server Connection
Strings
Substring
WebSite Flask
Flask Website With Plotly and Template
Xml Data Extraction

General

exec(open("filename.py").read()) # run a script in python 3 shell  

Calculator

Run with python3 /..path../pycalc.py

pycalc.py file

#standalone calc  
# Use Tkinter for python 2, tkinter for python 3  

#import tkinter        (access classes A B C by tkinter.A tkinter.B tkinter.C)  
#import tkinter as x   (access classes A B C by x.A x.B x.C)  
#from tkinter import * (access classes A B C by A B C)  

from tkinter import * # one is func  
from tkinter import messagebox as mb  
import tkinter as tk  # one is class    



def mFEq():
    calcStr=StringVar()
    calcStr=mVar.get()
    #remove last 2 characters (print(calcStr[:-2]))
    calcVal=eval(calcStr)
    mVar.set(calcVal)

def mF1():
    mVar.set("A Test String")

def mF2():
    mVar.set(mNewText.get())
    return

def mF3():
    pass

def mF4():
    mVar.set("A Test String")

def mFMn():
    mVar.set("A Test String")

def mFClear():
   mVar.set("")

def mFAdd(No):
    mVal= mVar.get()
    mVar.set(mVal+No)

def fQuit():
    mOk =  mb.askyesno(title="Exit",message="Are you sure?")
    if mOk != 0:
        root.destroy()        
    return

def fAbout():
    mb.showinfo(title="About pyCalc",message="A Simple Calculator Made in Python3\n By auto-mate :-)")

#Make Window
root=tk.Tk()
root.title("PY Calc")

#Menu
root.myMenuBar = tk.Menu()

root.myTopItem = tk.Menu(root.myMenuBar)
root.myTopItem.add_command(label="Quit",command=fQuit,underline=0)
root.myTopItem.add_command(label="About pyCalc",command=fAbout,underline=0)

root.myMenuBar.add_cascade(label="Options",menu=root.myTopItem,underline=0)

root.config(menu=root.myMenuBar)

#Draw and Size
root.grid()
root.geometry('220x300+200+200')

mVar=StringVar()
mVar.set("0")

c1=10
c2=60
c3=110
c4=160

rm1=240
r0=190
r1=140
r2=90
r3=40

#Answer Bar
root.myLabelResult=tk.Label(root,textvariable=mVar,anchor=tk.E,fg="#000000",bg="#ffffff",bd="1",font="-family arial -size 14 -overstrike 0 -underline 0 -slant roman")
root.myLabelResult.place(x=10, y=5, height=30, width=200)

#Row0
root.myButton_00=tk.Button(root,text="0",width=2,command=lambda xNo="0":mFAdd(xNo),fg="black")
root.myButton_00.place(x=c1, y=r0, height=50, width=50)

myButton_Pt=Button(root,text=".",width=2,command=lambda xNo=".":mFAdd(xNo),fg="black")
myButton_Pt.place(x=c2, y=r0, height=50, width=50)

myButton_Eq=Button(root,text="=",width=2,command=mFEq,bg="lightgreen", fg="black")
myButton_Eq.place(x=c3, y=r0, height=50, width=50)

myButton_Pl=Button(root,text="+",width=2,command=lambda xNo="+":mFAdd(xNo),fg="black")
myButton_Pl.place(x=c4, y=r0, height=50, width=50)

#Row1
myButton_01=Button(root,text="1",width=2,command=lambda xNo="1":mFAdd(xNo),fg="black")
myButton_01.place(x=c1, y=r1, height=50, width=50)

myButton_02=Button(root,text="2",width=2,command=lambda xNo="2":mFAdd(xNo),fg="black")
myButton_02.place(x=c2, y=r1, height=50, width=50)

myButton_03=Button(root,text="3",width=2,command=lambda xNo="3":mFAdd(xNo),fg="black")
myButton_03.place(x=c3, y=r1, height=50, width=50)

myButton_Mn=Button(root,text="-",width=2,command=lambda xNo="-":mFAdd(xNo),fg="black")
myButton_Mn.place(x=c4, y=r1, height=50, width=50)

#Row2
myButton_04=Button(root,text="4",width=2,command=lambda xNo="4":mFAdd(xNo),fg="black")
myButton_04.place(x=c1, y=r2, height=50, width=50)

myButton_05=Button(root,text="5",width=2,command=lambda xNo="5":mFAdd(xNo),fg="black")   
myButton_05.place(x=c2, y=r2, height=50, width=50)

myButton_06=Button(root,text="6",width=2,command=lambda xNo="6":mFAdd(xNo),fg="black")
myButton_06.place(x=c3, y=r2, height=50, width=50)

myButton_Tm=Button(root,text="x",width=2,command=lambda xNo="*":mFAdd(xNo),fg="black")
myButton_Tm.place(x=c4, y=r2, height=50, width=50)

#Row3
myButton_07=Button(root,text="7",width=2,command=lambda xNo="7":mFAdd(xNo),fg="black")
myButton_07.place(x=c1, y=r3, height=50, width=50)

myButton_08=Button(root,text="8",width=2,command=lambda xNo="8":mFAdd(xNo),fg="black")
myButton_08.place(x=c2, y=r3, height=50, width=50)

myButton_09=Button(root,text="9",width=2,command=lambda xNo="9":mFAdd(xNo),fg="black")
myButton_09.place(x=c3, y=r3, height=50, width=50)

myButton_Dv=Button(root,text="/",width=2,command=lambda xNo="/":mFAdd(xNo),fg="black")
myButton_Dv.place(x=c4, y=r3, height=50, width=50)

###Row-1
myButton_Cl=Button(root,text="Clear",width=2,command=mFClear,bg="orange",fg="black")
myButton_Cl.place(x=c1, y=rm1, height=40, width=200)

root.mainloop()

if

if 1==2:
    print "1=2"
elif 1==4:
    print "1=4"
else:
    print "1<>2 AND 1<>4"

Print

Print "OK"
x=20
Print x
# COMMENT x Not X

Notepad

# import statements #
import tkinter as tk
import tkinter.filedialog
import tkinter.messagebox as messagebox


# functions #
def about():
    # demo messagebox #    
    messagebox.showinfo(
        "About","Simple Text Editor\n" +
        "in python3/tkinter\n" +
        "by AH")
    pass # pass does nothing

def clear():
    text.delete('1.0','end')  #'1.0' = first char , end = last


def nonCom():
    print("noCom") # test function returns nothing

def openFile():
    # use file dialoge and commented out message box #
    oFl = tkinter.filedialog.askopenfile()
    #messagebox.showinfo("Selection","Selected " +  oFl.name)
    fStr = oFl.read()
    clear() 
    text.insert('1.0', fStr) # insert text at row 1 pos 0
    pass # not required just null

def quitApp():
    root.destroy() # closes app

def saveFile():
    # use file dialoge and message box #
    sFl = tkinter.filedialog.asksaveasfile()
    if sFl:
        sFl.write( text.get('1.0','end') ) # row 1 char 0 to end minus 0 chars
        sFl.close()
        messagebox.showinfo("Selection","Saved as  " +  sFl.name)

# create main window #
root = tk.Tk()

# add window title and python icon edit for your location #
root.title("AH Text Editor")
root.iconbitmap(r'c:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\DLLs\py.ico')

# create menu and submenu objects # 
menu       = tk.Menu( root )  # master menu item
menuFile   = tk.Menu( menu )  # first item for menu
menuClear  = tk.Menu( menu )  # 2nd   item for menu
menuAbout  = tk.Menu( menu )  # 3rd   item for menu

# add sub menus as cascade type #
menu.add_cascade ( menu  = menuFile,  label = "File"  )    # add menus
menu.add_cascade ( menu  = menuClear, label = "Clear"  )   # as cascade
menu.add_cascade ( menu  = menuAbout, label = "About" )    # type

# add options to cascade as list and command #
menuFile.add_command(   label = "Save File",  command = saveFile )  # add item to File  cascade and add command
menuFile.add_command(   label = "Open File",  command = openFile )  # add item to File  cascade   "   "     "
menuFile.add_command(   label = "Quit",       command = quitApp  )  # add item to File  cascade   "   "     "
menuClear.add_command(  label = "Clear",      command = clear    )  # add item to Clear cascade   "   "     "
menuAbout.add_command(  label = "About",      command = about    )  # add item to About cascade   "   "     "

# set the menu #
root['menu'] = menu  # bind the menu to the window

# add a label and text box using pack #
label_1 = tk.Label( root, width = 92  , padx = 0, height = 1, 
                          background = "#333", foreground = "#eee", 
                          text = "S I M P L E   D A R K   T H E M E D   T E X T   E D I T O R")
label_1.pack()

text = tk.Text(root, background = "#444", foreground="#ddd")
text.pack()

# add status bar
status = tk.Label(root, text="status:", bd=1, relief=tk.SUNKEN, anchor=tk.W) 
status.pack(side=tk.BOTTOM, fill=tk.X) 


# start window loop #
root.mainloop()

Curl

In Spyder or VSC use data. to see attributes after line. data = requests.get(url)

#prints HTML of "http://.........."
import requests
url = "http://.........."
data = requests.get(url)
print(data.content)

Dir Listing

import glob
n = glob.glob("c:/....../*.txt")

for x in n:
    print(x) 

File Read

Read 9 Characters

f = open("C:/temp/test.tmp", "r")  
print(f.read(9))  
f.close()  

Read Each Line

f = open("C:/temp/test.tmp", "r")  
for x in f:  
    print(x)  
f.close()  

File Write

#write new or Overwrite    
f = open("C:/temp/pythonTest.txt", "w")    
f.write("Add Data\n")    
f.close()    

#write new or append    
f = open("C:/temp/pythonTest.txt", "a")    
f.write("Add Data\n")    
f.close()    

Add No To String

print("Number Is £" + str(100.40))

SQL Server Connection

import pyodbc  
conn = pyodbc.connect('Driver={SQL Server};'  
                      'Server=<SERVERNAME>;'  
                      'Database=<DATABASENAME>;'  
                      'Trusted_Connection=yes;')  

cursor = conn.cursor()  

cursor.execute("SELECT * FROM dbo.<TABLENAME>")  

for row in cursor:  
  out = ""  
  delim = ""  
  counter = 0  
  for field in row:  
      counter = counter + 1  
      if counter > 1:  
        delim = ","  
      out = out + delim  + field  
  print(out)  

For

range

for i in range(5, 8):
    print(i, i ** 2)

iterate array

x= [1,2,3,4]

for i in x:
  print(i, i ** 2)

Array

x= [1,2,3,4]

Functions User

def printIT(a):  
  print(a)  
  pass  


printIT("OK")  

Lambda

valPlus99 = lambda inVal : inVal + 99
print(valPlus99(1))

Class

class Shopping:
  def __init__(self, item, shop):
    self.item = item
    self.shop = shop

  def shoppingInfo(self):
    print("Get " + self.item + " from " + self.shop)

Shop1 = Shopping("Cheese", "BestShopping Ltd")
Shop1.shoppingInfo()

Comment

# for single line

"""
Multiline
Comment
"""

Strings

x = "a"

PyTorch

# From https://www.analyticsvidhya.com/blog/2019/09/introduction-to-pytorch-from-scratch/
# Using python 3.7.3
# With torch-1.3.1+cpu-cp37-cp37m-win_amd64.whl 
#      torchvision-0.4.2+cpu-cp37-cp37m-win_amd64.whl
#     (converted to .zip and extracted to C:\Users\...\AppData\Local\Continuum\anaconda3\Lib\site-packages )

import numpy as np
import torch
a=np.array(1) 
b=torch.tensor(1)
print(a)
print(b)

print("---------------------------------------")

print(type(a)) 
print(type(b))

print("---------------------------------------")

# initializing two arrays
a = np.array(2)
b = np.array(1)
print(a,b)

print("---------------------------------------")

# addition
print(a+b)

# subtraction
print(b-a)

# multiplication
print(a*b)

# division
print(a/b)

print("---------------------------------------")

# initializing two tensors
a = torch.tensor(2)
b = torch.tensor(1)
print(a,b)

print("---------------------------------------")

# addition
print(a+b)

# subtraction
print(b-a)

# multiplication
print(a*b)

# division
print(a/b)

print("---------------------------------------")

# matrix of zeros
a = np.zeros((3,3))
print(a)
print(a.shape)

print("---------------------------------------")

# matrix of zeros
a = torch.zeros((3,3))
print(a)
print(a.shape)

print("---------------------------------------")

# setting the random seed for numpy
np.random.seed(42)
# matrix of random numbers
a = np.random.randn(3,3)
a

print(a)

print("---------------------------------------")

# setting the random seed for pytorch
torch.manual_seed(42)
# matrix of random numbers
a = torch.randn(3,3)
print(a)

print("---------------------------------------")

# setting the random seed for numpy and initializing two matrices
np.random.seed(42)
a = np.random.randn(3,3)
b = np.random.randn(3,3)

print("---------------------------------------")

# matrix addition
print(np.add(a,b), '\n')

# matrix subtraction
print(np.subtract(a,b), '\n')

# matrix multiplication
print(np.dot(a,b), '\n')

# matrix multiplication
print(np.divide(a,b))

print("---------------------------------------")

# original matrix
print(a, '\n')

# matrix transpose
print(np.transpose(a))

print("---------------------------------------")

# setting the random seed for pytorch and initializing two tensors
torch.manual_seed(42)
a = torch.randn(3,3)
b = torch.randn(3,3)

print("---------------------------------------")

# matrix addition
print(torch.add(a,b), '\n')

# matrix subtraction
print(torch.sub(a,b), '\n')

# matrix multiplication
print(torch.mm(a,b), '\n')

# matrix division
print(torch.div(a,b))

print("---------------------------------------")

# original matrix
print(a, '\n')

# matrix transpose
print(torch.t(a))

print("---------------------------------------")

# initializing two tensors
a = torch.tensor([[1,2],[3,4]])
b = torch.tensor([[5,6],[7,8]])
print(a, '\n')
print(b)

print("---------------------------------------")

# concatenating vertically
print(torch.cat((a,b)))

print("---------------------------------------")

# concatenating horizontally
print(torch.cat((a,b),dim=1))

print("---------------------------------------")

# setting the random seed for pytorch
torch.manual_seed(42)
# initializing tensor
a = torch.randn(2,4)
print(a)
print(a.shape)

print("---------------------------------------")

# reshaping tensor
b = a.reshape(1,8)
print(b)
b.shape

print("---------------------------------------")

# initializing a numpy array
a = np.array([[1,2],[3,4]])
print(a, '\n')

# converting the numpy array to tensor
tensor = torch.from_numpy(a)
print(tensor)

print("---------------------------------------")

# initializing a tensor
a = torch.ones((2,2), requires_grad=True)
print(a)

print("---------------------------------------")

# performing operations on the tensor
b = a + 5
c = b.mean()
print(b,c)

print("---------------------------------------")

# back propagating
c.backward()

# computing gradients
print(a.grad)

print("---------------------------------------")

# importing the optim module
from torch import optim

# adam
## adam = optim.Adam(model.parameters(), lr=learning_rate)

# sgd
## SGD = optim.SGD(model.parameters(), lr=learning_rate)

Image recognition

Using Datatset of clothes images as png of 28*28 pixels, labels as 10 types from 0-9

import torch
import pandas as pnd
from skimage.io import imread
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import numpy as np
import matplotlib.pyplot as plt
#import torchvision
#from torchvision import transforms, datasets

# train,csv of id	label
#               1	9
#               2	0
#               3	0
#               .......
# test,csv of  id	
#               1	
#               2	
#               3	
#               .....

# Load CSV Lists as arrays
train = pnd.read_csv('C:\\Users\\<user.name>\\Documents\\Python Scripts\\TorchTrain\\Train.csv') #60,000 entries
test  = pnd.read_csv('C:\\Users\\<user.name>\\Documents\\Python Scripts\\TorchTest\\Test.csv')   #10,000 entries

# loading training images as Arrays (Adds 60,000 Images)
train_img = []
for img_name in train['id']:
    image_path = 'C:\\Users\\<user.name>\\Documents\\Python Scripts\\TorchTrain\\Train\\' + str(img_name) + '.png'
    img = imread(image_path, as_gray=True)
    img = img.astype('float32')
    train_img.append(img)

# Convert Image Array to NUMPY array
train_x = np.array(train_img)
# Array of Known Results in csv under column Labels
train_y = train['label'].values


# Convert NUMPY Image Array to  1 dimensional array
train_x = train_x.reshape(-1, 28*28).astype('float32')

# Create small set for validating [If test size = 0.05 = 5% = 60000 split as 57000 for train,3000 for test]
# train_x.shape = (57000,784) val_x.shape = (3000,784)  [i.e 60000 images split where the images are 784 long arrays]
# train_y.shape = (57000,) val_y.shape = (3000,)        [i.e 60000 labels split (labels here = 0 - 9 )]
train_x, val_x, train_y, val_y = train_test_split(train_x,train_y, test_size = 0.05, stratify = train_y )


# BUILD MODEL
from torch.autograd import Variable
from torch.nn import Linear, ReLU, CrossEntropyLoss, Sequential
from torch.optim import Adam

# number of neurons in each layer (generaly 3 layers is good)
input_num_units = 28*28 # ( 784 or one per pixel )
hidden_num_units = 500     # A simple method to get a value would be 
                          # input 784 + output 10 = 794/2 = Ave of 397 
                          # picked 500 here as close to that 
output_num_units = 10      # Re classifications 0-9
                          # Machine Mode - returns label / Regression Mode
                          #                                returns value 
                          # Label	Description
                          # 0	T-shirt/top
                          # 1	Trouser
                          # 2	Pullover
                          # 3	Dress
                          # 4	Coat
                          # 5	Sandal
                          # 6	Shirt
                          # 7	Sneaker
                          # 8	Bag
                          # 9	Ankle boot


# set remaining variables
epochs = 20 # cycles though training data can be 100's or 1000's 
learning_rate = 0.0005 # ofter between 0.0...1 and 1
                      # higher value = quicker to drop assumptions
                      # example methods for getting a value for this are 
                      # Trial and Error / "Grid Search" Technique


# define model
model = Sequential(Linear(input_num_units, hidden_num_units),
                  ReLU(),
                  Linear(hidden_num_units, output_num_units))

# Sequential - complete internal parameters in sequence
# Linear     - applies linear transform to input 
# ReLU       - Rectified Linear Unit, an actiiavtion on the output 
#              before passing to next layer     

# loss function
loss_fn = CrossEntropyLoss() # between 1 and zero, 1 is bad 0 is perfect
                            # nn.LogSoftmax() and nn.NLLLoss() in one class.

# define optimization algorithm: Using Adam Model
optimizer = Adam(model.parameters(), lr=learning_rate)


# training
train_losses = []
val_losses = []
for epoch in range(epochs):
    avg_cost = 0
    
    # Variable is a wrapper for the tensor/matrix and operations applied to it, also holds gradient
    # train_x is the 57k images as 1D matrix, train_y the 57k labels for train
    # To be added >>> Notes on "requires_grad"
    x, y = Variable(torch.from_numpy(train_x)), Variable(torch.from_numpy(train_y), requires_grad = False)
    # val_x is the 3k images , val_y the 3k values for validate
    x_val, y_val = Variable(torch.from_numpy(val_x)), Variable(torch.from_numpy(val_y), requires_grad = False)
    #run train items through model
    pred = model(x)
    #run validate items through model
    pred_val = model(x_val)

    # get loss
    loss = loss_fn(pred, y) # train loss
    loss_val = loss_fn(pred_val, y_val) # test/validation loss
    train_losses.append(loss)    # add to array
    val_losses.append(loss_val)  # add to array

    # perform backpropagation
    loss.backward() # call back calc on CrossEntropyLoss() see docs re nn.NLLLoss() example.
    optimizer.step() # single step (small learning rate and steps helps avoid becoming stuck in local minima values)
    avg_cost = avg_cost + loss.data # gather loss data to track through Epochs below

    if (epoch%2 != 0):             #Print Train loss every other cycle
        print(epoch+1, avg_cost)


# plotting the training and validation loss [Commented out Use ]
plt.plot(train_losses, label='Training loss')
plt.plot(val_losses, label='Validation loss')
plt.legend()
plt.show()        

# get training accuracy
x, y = Variable(torch.from_numpy(train_x)), Variable(torch.from_numpy(train_y), requires_grad=False)
pred = model(x) # run data through calculated model

final_pred = np.argmax(pred.data.numpy(), axis=1)  # max value of each array in an array

accuracy_score(train_y, final_pred)  # compare max value of each pred array in an final_pred with actual labels for train

# get validation accuracy
x, y = Variable(torch.from_numpy(val_x)), Variable(torch.from_numpy(val_y), requires_grad=False)
pred = model(x)
final_pred = np.argmax(pred.data.numpy(), axis=1)

accuracy_score(val_y, final_pred) # compare max value of each array in an final_pred with actual labels for test

# loading test images
test_img = []
for img_name in test['id']:
    image_path = 'C:\\Users\\<user.name>\\Documents\\Python Scripts\\TorchTest\\Test\\'  + str(img_name) + '.png'
    img = imread(image_path, as_gray=True)
  img = img.astype('float32')
    test_img.append(img)

test_x = np.array(test_img)
test_x.shape

# converting the images to 1-D
test_x = test_x/train_x.max()
test_x = test_x.reshape(-1, 28*28).astype('float32')
test_x.shape

# getting the prediction for test images
prediction = np.argmax(model(torch.from_numpy(test_x)).data.numpy(), axis=1)

sample_submission = pnd.read_csv('C:\\Users\\<user.name>\\Documents\\Python Scripts\\submission.csv')
# first five rows of sample submission file
sample_submission.head()

# replacing the label with prediction
sample_submission['label'] = prediction
sample_submission.head()

# saving the file
sample_submission.to_csv('C:\\Users\\<user.name>\\Documents\\Python Scripts\\submissionOut.csv', index=False)

WebSite Flask

import pyodbc
from flask import Flask
app = Flask(__name__)


@app.route('/')
def hello():
    return "Hello World!"


@app.route('/first/<Fname>')
def hello_fname(Fname):
    return "Hello {}!".format(Fname)

@app.route('/last/<Lname>')
def hello_lname(Lname):
    return "Hello {}!".format(Lname)

@app.route('/somePage')
def somepge():  
  f = open("C:/temp/someFile.txt", "r")  
  n = f.read()
  f.close()  

  out =   "<HTML>"
  out +=  "<head>"
  out +=  "<link rel=\"stylesheet\" href=\"/static/style/py.css\" type=\"text/css\">" # NOTE need some file here
  out +=  "</head>"
  out +=  "<body>"
  out +=  "<H1>Hello</H1>"+"OK"  
  out +=  "<xmp>"+n+"</xmp>"  
  out +=  "<button onclick=\"window.location.href='/first/Bob'\">Hello Bob</button>"
  out +=  "</body>"
  out +=  "</HTML>"
  return out

@app.route('/sql')
def sqlData():
  conn = pyodbc.connect('Driver={SQL Server};'
                        'Server=SOME_SERVER;'
                        'Database=SOME_DATABASE;'
                        'Trusted_Connection=yes;')

  cursor = conn.cursor()

  rCount = 10

  cursor.execute('SELECT TOP (' + str(rCount) + ') * '
                 'FROM [SOME_DATABASE].[dbo].[SOME_TABLE]')

  out = "<table>"

  for row in cursor:
    out += "<tr>"
    for fld in row:
      out += "<td>" + str(fld) + "</td>"    
    out += "</tr>"  

  out += "</table></div>"

  return out



if __name__ == '__main__':
    app.run()

Flask Website With Plotly and Template

Structure

\web1\static\style\py.css

H1 {color:red;}  

\web1\templates\index.html

<!doctype html>
<html>

<head>
    <style type="text/css">
        .header{
            text-align: center;
            background-color: rgb(136, 185, 229);
            height: 70px;
            line-height: 70px;
        }
        .chart{
            margin-top: 30px;
            text-align: center;
        }
    </style>
</head>

<body>

    <div class="header">
        <h2>
            Plotly Chart Demo
        </h2>
    </div>

    <div id="chart" class="chart">
    </div>

</body>

    <!-- D3.js -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
    <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
    <!-- Plotly.js -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/plotly.js/1.33.1/plotly-basic.min.js"></script>

    <script type="text/javascript">
        
        var graphs = {{graphJSON | safe}};
        
        Plotly.plot('chart',graphs,{});        

    </script>

</html>

\web1\flaskTest.py

import pyodbc
import json
import numpy as np
import plotly
import plotly.graph_objs as go
from flask import Flask,render_template
app = Flask(__name__)


@app.route('/')
def hello():
    return "Hello World!"


@app.route('/first/<Fname>')
def hello_fname(Fname):
    return "Hello {}!".format(Fname)

@app.route('/last/<Lname>')
def hello_lname(Lname):
    return "Hello {}!".format(Lname)

@app.route('/somePage')
def somepge():
  
  f = open("C:/temp/SomeFile.txt", "r")  
  n = f.read()
  f.close()  
  
  out =   "<HTML>"
  out +=  "<head>"
  out +=  "<link rel=\"stylesheet\" href=\"/static/style/py.css\" type=\"text/css\">" 
  out +=  "</head>"
  out +=  "<body>"
  out +=  "<H1>Hello</H1>"+"OK"  
  out +=  "<xmp>"+n+"</xmp>"  
  out +=  "<button onclick=\"window.location.href='/first/Bob'\">Hello Bob</button>"
  out +=  "</body>"
  out +=  "</HTML>"
  return out

@app.route('/sql')
def sqlData():
  conn = pyodbc.connect('Driver={SQL Server};'
                        'Server=SomeServer;'
                        'Database=SomeDatabase;'
                        'Trusted_Connection=yes;')

  cursor = conn.cursor()

  rCount = 10

  cursor.execute('SELECT * FROM [SomeDatabase].[dbo].[SomeTable]')

  out = "<table>"

  for row in cursor:
    out += "<tr>"
    for fld in row:
      out += "<td>" + str(fld) + "</td>"    
    out += "</tr>"  
  
  out += "</table></div>"

  return out

@app.route('/plotlyRender')
def lineRender():
    count = 500
    xScale = np.linspace(0, 100, count)
    yScale = np.random.randn(count)

    # Create a scatter trace
    trace = go.Scatter(
        x = xScale,
        y = yScale
    )

    # Change a scatter trace
    trace = go.Bar(
        x = xScale,
        y = yScale
    )    

    data = [trace]
    graphJSON = json.dumps(data, cls=plotly.utils.PlotlyJSONEncoder)
    return render_template('index.html',
                            graphJSON=graphJSON)


@app.route('/plotly')
def line():
    count = 500
    xScale = np.linspace(0, 100, count)
    yScale = np.random.randn(count)

    # Create a scatter trace
    trace = go.Scatter(
        x = xScale,
        y = yScale
    )

    # Change a scatter trace
    trace = go.Bar(
        x = xScale,
        y = yScale
    )    

    data = [trace]
    graphJSON = json.dumps(data, cls=plotly.utils.PlotlyJSONEncoder)
    gString="""
        <!doctype html>
        <html>
        
        <head>
            <style type="text/css">
                .header{
                    text-align: center;
                    background-color: rgb(136, 185, 229);
                    height: 70px;
                    line-height: 70px;
                }
                .chart{
                    margin-top: 30px;
                    text-align: center;
                }
            </style>
        </head>
        
        <body>
        
            <div class="header">
                <h2>
                    Plotly Chart Demo
                </h2>
            </div>
        
            <div id="chart" class="chart">
            </div>
        
        </body>
        
            <!-- D3.js -->
            <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
            <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
            <!-- Plotly.js -->
            <script src="https://cdnjs.cloudflare.com/ajax/libs/plotly.js/1.33.1/plotly-basic.min.js"></script>
        
            <script type="text/javascript">
                
                Plotly.plot('chart',""" + graphJSON + """,{});        
        
            </script>
        
        </html>
        """
    
    return gString


if __name__ == '__main__':
    app.run()

#Xml Data Extraction

import xml.etree.ElementTree as ET  

# NB r"" for raw string  
# "//*" finds all elements re xquery
# check attributes of element if they contain 'name'
#   see if the value of name is 'ApplicationName'
#   if so print the text inside the tag

for myElement in ET.parse(r"C:/.../.../somefile.xml").findall("//*"):
  elAttrib = myElement.attrib
  if elAttrib.__contains__('name'):
    if elAttrib['name'] == 'ApplicationName':
      print(e.text)

Arguments

Run as c:\python someProg.py "SomeArg" "SomeOtherArg"

# load sys  (needed for sys.argv)  
import sys  
  
x = sys.argv  # Read all into Array
print(x[0]) # Item 1 is Script Name  
print(x[1]) # Arg 1   
print(x[2]) # Arg 2 etc...  

print(len(x)) # use len to see how many arguments 

Substring

tStr = "Hello World"

print(tStr[0:])   # From Beginning To End       >>> "Hello World"  
print(tStr[1:])   # From 2nd Char  To End       >>> "ello World"  
print(tStr[1:2])  # From 2nd Char  To 2nd Char  >>> "e"  
print(tStr[1:4])  # From 2nd Char  To 4th Char  >>> "ell"  
print(tStr[0:4])  # From 1st Char  To 4th Char  >>> "Hell"  
  
# print(tStr[x:y])  # From x (starting at 0)  To y (starting at 1)  

Django

:: make virtual env 
py -m venv "name of env"
:: activate virtual env     
"name of env"\Scripts\activate.bat
:: add django to env
py -m pip install Django
:: create project
django-admin startproject "projectName"
:: create project
django-admin startproject "projectName"
:: create startup app/page
django-admin startapp "startappName"
:: can run at this point with at venv\project folder as
py manage.py runserver

# update views.py in start app folder

from django.shortcuts import render
from django.http import HttpResponse

def <function-name-1>(request):
    return HttpResponse("Some Text")
def <function-name-2>(request):
    return HttpResponse("Some Other Text")



# update/add urls.py in startapp folder

from django.urls import path
from . import views

urlpatterns= [
     path('<startapp>/',views.<function-name-1 or 2>,name='<startapp>')
]

# update/add urls.py in venv\startProject folder
from django.contrib import admin
from django.urls import include,path

urlpatterns = [
    path('',include('<startapp>.urls')),
    path('admin/', admin.site.urls),
]

# reads venv\startProject\urls.py this tells it to include  urls.py in the startapp so when nav to http://localhost:8000/<startapp> 
# it returns a view as defined in <startapp>\urls.py that point to a particular view/def in <startapp>\views.py

# add template
# in <startapp> folder add \templates and an html file "template01.html"
# in <startapp> folder views.py update our rendered def to include

def <function-name-1 or 2>(request):
    template = loader.get_template("template01.html")
    print(template.render())
    return HttpResponse(template.render())

# add <startapp> to INSTALLED_APPS in settings.py and run py manage.py migrate   
⚠️ **GitHub.com Fallback** ⚠️