# data[].attributes.attachment_link.readable_text
the_world_is_flat = True
if the_world_is_flat:
    print("Be Careful not to fall off!")

# data[].attributes.attachment_link.readable_text
print('spam eggs')
print('doesn\'t')
print("doesn't")
print('"Yes," they said.')
print("\"Yes,\" they said.")
print('"Isn\'t" they said.')
print('First Line \nSecond Line')
print(r'C:\some\name')
print("""\

Usage: thingy [OPTIONS]

     -h                        Display this usage message

     -H hostname               Hostname to connect to

""")
print(3*'un'+'ium')
print('Py''thon')
word = "Nasief"
print(word[0])
print(word[-1])
print(word[:3])
print(word[3:])
print(word[:3]+word[3:])
print('"Isn\'t," they said.')

# data[].attributes.attachment_link.readable_text
print("FOR")
words = ['cat', 'window', 'defenestrate']
for w in words:
  print(w, len(w))
  
for w in words[:]:  # Loop over a slice copy of the entire list.
  if len(w) > 6:
    words.insert(0, w)
print(words)

print("")
print("IF ELSE ELIF")
x = int(input("Enter your data here..."))
if x < 0:
    x = 0
    print('Negative Changed to zero')
elif x == 0:
    print("Zero")
elif x == 1:
    print("Single")
else:
    print("More")

print("")
print("RANGE")
for i in range(5):
  print(i)

print()
a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
    print(i, a[i])

print()
for n in range(2, 10):
  for x in range(2, n):
    if n % x == 0:
          print(n, 'equals', x, '*', n//x)
          break
    else:
# loop fell through without finding a factor
      print(n, 'is a prime number')

print()
for num in range(2, 10):
  if num % 2 == 0:
    print("Found an even number", num)
    continue
  print("Found a number", num)

print()
print("FIBANACCI")
def fib(n):    # write Fibonacci series up to n
  
  """Print a Fibonacci series up to n."""
a, b = 0, 1
while a < n:
  print(a, end=' ')
a, b = b, a+b
print()

# data[].attributes.attachment_link.readable_text
#While FUnction

def ask_ok(prompt, retries=4, reminder='Please try again!'):

    while True:

        ok = str(input(prompt))

        if ok in ('y', 'ye', 'yes'):

            return True

        if ok in ('n', 'no', 'nop', 'nope'):

            return False

        retries = retries - 1

        if retries < 0:

            raise ValueError('invalid user response')

    print(reminder)

print()
#Next
i = 5

def f(arg=i):

 print(arg)

i = 6

f()

print (5.)

print()
#Continuing
def f(a, L=[]):
    
 L.append(a)

 return L

print(f(1))

print(f(2))

print(f(3))

print()
#Extended
def f(a, L=None):
    
 if L is None:

     L = []

 L.append(a)

 return L

print(f(1))

print(f(2))

print(f(3))

print()
#Calling functions using arguments
def parrot(voltage='kilowatts', state='a stiff', action='voom', type='Norwegian Blue'):  
    
    print("-- This parrot wouldn't", action, end=' ')

    print("if you put", voltage, "volts through it.")

    print("-- Lovely plumage, the", type)

    print("-- It's", state, "!")

parrot(1000)                                       # 1 positional argument
print()
parrot(voltage=1000)                               # 1 keyword argument
print() 
parrot(voltage=1000000, action='VOOOOOM')          # 2 keyword arguments
print()
parrot(action='VOOOOOM', voltage=1000000)          # 2 keyword arguments
print()
parrot('a million', 'bereft of life', 'jump')      # 3 positional arguments

print()
#Formal Parameter definition + function
def cheeseshop(kind, *arguments, **keywords):
    
    print("-- Do you have any", kind, "?")

    print("-- I'm sorry, we're all out of", kind)

    for arg in arguments:

        print(arg)

    print("-" * 40)

    for kw in keywords:

        print(kw, ":", keywords[kw])

cheeseshop(1000)

print()
#Continued
cheeseshop("Limburger", "It's very runny, sir.",

        "It's really very, VERY runny, sir.",

           shopkeeper="Michael Palin",

           client="John Cleese",

           sketch="Cheese Shop Sketch")

cheeseshop(1000)

print()
#Tuple & Sequences
def my_function(*kids):
      print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

print()
#Basic Lambda Expressions
x = lambda a, b, c: a + b + c
print(x(10, 10, 10))

print()
#Unpacking Argument Lists
list(range(3, 6))         # normal call with separate arguments

[3, 4, 5]

args = [3, 6]

list(range(*args))         # call with arguments unpacked from a list

def parrot(voltage, state='a stiff', action='voom'):

    print("-- This parrot wouldn't", action, end=' ')

    print("if you put", voltage, "volts through it.", end=' ')

    print("E's", state, "!")



d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}

parrot(**d)

parrot(1000)

print()
#Lambda Expressions Continued
def make_incrementor(n):
    return lambda x: x + n
f = make_incrementor(42)
print(f(0))
print(f(1))

print()
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]

pairs.sort(key=lambda pair: pair[1])

print(pairs)

print()
#Documentation Of Strings
def my_function():
    """Do nothing, but document it.
No, really, it doesn't do anything.
    """
pass
print(my_function.__doc__)

print()
#Function Annotation
def f(ham: str, eggs: str = 'eggs') -> str:
    print("Annotations:", f.__annotations__)
    print("Arguments:", ham, eggs)
    return ham + ' and ' + eggs

f('spam')

# data[].attributes.attachment_link.readable_text
def fib(n):
    a, b = 0, 1
    while a < n:
        a, b = b, a + 1
        print(a, end = " ")
    print()

if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1]))

# data[].attributes.attachment_link.readable_text
class Person:
    def __init__(self, fname, lname):
        self.firstname = fname
        self.lastname = lname

    def printname(self):
        print(self.firstname, self.lastname)

x = Person("Nasief", "Khan")
x.printname()

class Student(Person):
    def __init__(self, fname, lname, year):
        super().__init__(fname, lname)
        self.graduationyear = year

    def Welcome(self):
        print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)

x = Student("Nasief", "Khaan", 2016)
x.Welcome()

# data[].attributes.attachment_link.readable_text
class Map:
    def __init__(self, iterate):
        self.list = []
        self.__geek(iterate)
    def geek(self, iterate):
        for item in iterate:
            self.list.append(item)
    __geek = geek

class MapSubClass(Map):
    def geek(self, key, value):
        for i in zip(keys, values):
            self.list.append(1)

# data[].attributes.attachment_link.readable_text
mytuple = ("Apple", "Samsung", "Nokia")
myit = iter(mytuple)

print(next(myit))
print(next(myit))
print(next(myit))
print()

mystr = "Nasief"
myite = iter(mystr)

print(next(myite))
print(next(myite))
print(next(myite))
print(next(myite))
print(next(myite))
print(next(myite))
print()

mytuples = ("Apple", "Samsung", "Nokia")
for x in mytuples:
    print(x)
print()

mystring = "Nasief"
for x in mystring:
    print(x)
print()


class MyNumbers:
    def __iter__(self):
        self.a = 1
        return self
    
    def __next__(self):
        x = self.a
        self.a += 1
        return x

myClass  = MyNumbers()
myiter = iter(myClass)

print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))

class myNumbers:
    def __iter__(self):
        self.a = 1
        return self
    def __next__(self):
        if self.a <= 20:
            x = self.a
            self.a += 1
            return x
        else:
            raise StopIteration
myclass = myNumbers()
myiter = iter(myclass)

for x in myiter:
    print(x)

# data[].attributes.attachment_link.readable_text
print(sum(i*i for i in range(10)))

xvec = [10,20,30]
yvec = [7,5,3]
print(sum(x*y for x,y in zip(xvec,yvec)))

#from math import pi,sin
#sine_table = {x:sin(x*pi/180) for x in range(0,91)}
#unique_words = set(word for line in page for word in line.split())
#valedictorian = max((student.gpa,student.name)for student in graduates)
#data ="golf"
#list(data[i] for i in range(len(data)-1,-1,-1))

import os
print(os.getcwd())
print(os.system('mkdir today'))
print()

print(dir(os))
#print(help(os)) TOO MUCH CODE!!!!
print()


# data[].attributes.attachment_link.readable_text
from datetime import date
now = date.today()
print(now)
print()

print(now.strftime("%m-%d-%y.%d %b %Y is a %A on the %d day of %B."))
print()

birthday = date(1964,7,31)
age = now - birthday
print(age.days)
print()

import zlib
s = b'witch whcih has which witches wrist watch'
print(len(s))
print()

t = zlib.compress(s)
print(len(t))
print()

zlib.decompress(t)
print(zlib.crc32(s))
print()

from timeit import Timer
print(Timer('t=a;a=b;b=t','a=1;b=2').timeit())
print()

def average(values):
    print(average([20,30,70]))

import doctest
doctest.testmod()

import unittest
class testStatisticalFunctions(unittest.TestCase):
    def test_average(self):
        self.assertEqual(average([20,30,70]),40.0)
        self.assertEqual(round(average([1,5,7]),1),4.3)
    with self.assertRaises(ZeroDivisionError):
        average([])
    with self.assertRaises(TypeError):
        average(20,30,70)
Print(unittest.main())

# data[].attributes.attachment_link.readable_text
import reprlib

print(reprlib.repr(set('supercalifragilisticexpialidocious')))

import pprint
t = [[[['black','cyan'],'white',['green','red']],[['magenta','yellow'],'blue']]]
print(pprint.pprint(t,width=30))
print()

import textwrap
doc = """The wrap()metohd is just like fill() except that it returns a list of strings instead of one big stringwith newlines to separate the wrapped lines."""
print(textwrap.fill(doc, width=40))
print()

import locale
print(locale.setlocale(locale.LC_ALL, "English_United States.1252"))
conv = locale.localeconv()
x = 1234567.8
print(locale.format("%d",x,grouping=True))
print(locale.format_string("%s%.*f",(conv['currency_symbol'],conv['frac_digits'],x),grouping=True))
print()

from string import Template
t = Template('${village}folk send $$10 to $cause.')
t.substitute(village='Nottingham',cause='the ditch fund')

#t = Template('Return the $item to $owner.')
#d = dict(item='unladen swallow')
#t.substitute(d)
#print(d)

import time, os.path
photofiles = ['img_1074.jpg','img_1076.jpg','img_1077.jpg']
class BatchRename(Template):
    fmt = input("Enter rename style(%d-date  %n-seqnum %f-format):")
    t = BatchRename(fmt)
    date = time.strftime('%d%b%y')
    for i,filename in enumerate(photofiles):
        base, ext = os.path.splitext(filename)
        newname = t.substitute(d=date,n=i,f=ext)
        print('{0} --> {1}'.format(filename, newname))

# data[].attributes.attachment_link.readable_text
import logging

logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical message')

# data[].attributes.attachment_link.readable_text
import os, random, string

passwordlenth = 10
chars = string.ascii_letters + string.digits + '*&$#^@%'
random.seed = (os.urandom(1024))

print(''.join(random.choice(chars) for i in range(passwordlenth)))

# data[].attributes.attachment_link.readable_text
import pandas as pd
import numpy as np

rng = pd.date_range('5/1/2020', periods=30,freq='H')
print(rng)
print()

rng = pd.date_range('5/1/2020', periods=10,freq='D')
print(rng)
print()

ts = pd.DataFrame(np.random.randn(len(rng),4),index=rng,columns=['A','B','C','D'])
print(ts)
print()

ts = pd.Series(np.random.randn(len(rng)),index=rng)
print(ts)
print()

#PANDAS TIME SERIES

pd.date_range('12/1/2020',periods=30,freq='H')
ts = pd.DataFrame(np.random.randn(len(rng),4),index=rng,columns=['A','B','C','D'])
print(ts)
print("Unknown Army")

ts = ts.resample('1D').mean()
print(ts)
print()

#MANIPLUATING TIMESERIES

rng = pd.date_range('12/1/2020',periods=30,freq='D')
ts = pd.DataFrame(np.random.randn(len(rng),4),index=rng,columns=['A','B','C','D'])
print(ts)
print()


# data[].attributes.attachment_link.readable_text
import matplotlib.pyplot as plt 
plt.subplots()
plt.title('My First matplotlib')
plt.xlabel('A-Axis Label')
plt.ylabel('Y-Axis Label')


fig,axes = plt.subplots(nrows=2,ncols=2)
plt.show()

fig, axes = plt.subplots(nrows=2, ncols=2, sharex=True,sharey=True)
axes[0, 0].set(title='Upper Left')
axes[0, 1].set(title='Upper Right')
axes[1, 0].set(title='Lower Left')
axes[1, 1].set(title='Lower Right')
plt.show()

# data[].attributes.attachment_link.readable_text
import matplotlib.pyplot as plt

#PLOTTING

x = [1.3, 2.9, 3.1, 4.7, 5.6, 6.5, 7.4, 8.8, 9.2, 10]
y = [95, 42, 69, 11, 49, 32, 74, 62, 25, 32]
plt.plot(x, y)
plt.xlabel('X-axis Label')
plt.ylabel('Y-axis Label')
plt.show()


y = [95, 42, 69, 11, 49, 32, 74, 62, 25, 32]
plt.plot(y)
plt.xlabel('Index Values')
plt.ylabel('Elements in List Y')
plt.show()

fmt = '[color][marker][line]'

plt.plot(y,'g')
plt.xlabel('Index Values')
plt.ylabel('Elements in List Y')
plt.show()

plt.plot(y,'go-')
plt.xlabel('index Values')
plt.ylabel('Elements in List y')
plt.show()

plt.plot(y,'g*-')
plt.xlabel('index Values')
plt.ylabel('Elements in List Y')
plt.show()

plt.plot(y,'ro')
plt.xlabel('Index Values')
plt.ylabel('Elements in List Y')
plt.show()

y = [95, 42, 69, 11, 49, 32, 74, 62, 25, 32]
y2 = [35, 52, 96, 77, 36, 66, 50, 12, 35, 63]
plt.plot(y,'go-')

plt.plot(y2,'b*--')
plt.xlabel('Index Values')
plt.ylabel('Elements in List ')
plt.show()

plt.plot(y,'go-',y2,'b*--')
plt.xlabel('Index Values')
plt.ylabel('Elements in List')
plt.show()

# data[].attributes.attachment_link.readable_text
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
x = mycol.find_one()
print(x)
print()

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
for x in mycol.find():
    print(x)
print()

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
for x in mycol.find({},{"_id":0,"name":1,"address":1}):
    print(x)