index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
12,689
yenlt6/learningpython
refs/heads/main
/python4testers_student/code_along/oop/solutions/bank_account.py
class BankAccount: # Magic methods def __init__(self, account_number, account_name, balance=0): self.account_number = account_number self.account_name = account_name self.balance = balance def display(self): print(self.account_number, self.account_name, self.balance, "₫") def withdraw(self, amount): self.balance -= amount def deposite(self, amount): self.balance += amount print("Balance:", self.balance) my_account = BankAccount(1, "Ba") my_account.display() my_account.deposite(1_000_000_000_000_000) # 😊
{"/python4testers_student/code_along/vingroup/payments/vinid.py": ["/python4testers_student/code_along/vingroup/products/vinfast.py"]}
12,690
yenlt6/learningpython
refs/heads/main
/python4testers_student/code_along/vingroup/vinhome.py
def ocean_park(): print('[vinhome] ocean_park()') class VinHome: pass class Database: pass
{"/python4testers_student/code_along/vingroup/payments/vinid.py": ["/python4testers_student/code_along/vingroup/products/vinfast.py"]}
12,691
yenlt6/learningpython
refs/heads/main
/Day16Exam2_TEMP/card_game/game.py
class Game: ''' Class chứa các chức năng chính của game Game chứa danh sách người chơi, và bộ bài ''' def __init__(self): pass def setup(self): '''Khởi tạo trò chơi, nhập số lượng và lưu thông tin người chơi''' pass def guide(self): '''Hiển thị menu chức năng/hướng dẫn chơi''' pass def list_players(self): '''Hiển thị danh sách người chơi''' pass def add_player(self): '''Thêm một người chơi mới''' pass def remove_player(self): ''' Loại một người chơi Mỗi người chơi có một ID (có thể lấy theo index trong list) ''' pass def deal_card(self): '''Chia bài cho người chơi''' pass def flip_card(self): '''Lật bài tất cả người chơi, thông báo người chiến thắng''' pass
{"/python4testers_student/code_along/vingroup/payments/vinid.py": ["/python4testers_student/code_along/vingroup/products/vinfast.py"]}
12,692
yenlt6/learningpython
refs/heads/main
/Date16Exam2Date1610/main.py
import deck as dec import player as pla import card as ca import subprocess as sp import game as ga def main(): # khó game = ga.Game() game.setup() memu=[] memu.append('1.Xem danh sách người chơi') memu.append ('2.Thêm mới người chơi ') memu.append ('4.Chia bài ') memu.append('5.Lật bài: ') memu.append('6.Xem lịch sử chơi') memu.append("7.Tổng số lượt chơi trong ngày") memu.append('8. Thoát game') while True: for i in memu: print(i) luachon=int(input("lựa chọn của bạn:")) if luachon== 1: game.list_players() elif luachon==2: game.add_player() elif luachon==3: id=int(input("Nhập id người dùng muốn xóa:")) game.remove_player(id) elif luachon==4: game.deal_card() elif luachon==5: game.flip_card() elif luachon==8: break else: print("Unknown Option Selected!") main()
{"/python4testers_student/code_along/vingroup/payments/vinid.py": ["/python4testers_student/code_along/vingroup/products/vinfast.py"]}
12,693
yenlt6/learningpython
refs/heads/main
/python4testers_student/code_along/card_game/card.py
class Card: def __init__(self, rank, suit): self._rank = rank self._suit = suit @property def rank(self): return 1 if self._rank == 'A' else self._rank @property def suit(self): points = {'S': 0, 'C': 1, 'D': 2, 'H': 3} return points.get(self._suit) def __str__(self): symbol = {'S': '♠', 'C': '♣', 'D': '♦', 'H': '♥'} return f"{self._rank}{symbol[self._suit]}" def __int__(self): return self.rank def __gt__(self, other): return self.suit > other.suit or (self.suit == other.suit and self.rank > other.rank)
{"/python4testers_student/code_along/vingroup/payments/vinid.py": ["/python4testers_student/code_along/vingroup/products/vinfast.py"]}
12,694
yenlt6/learningpython
refs/heads/main
/Day18UnitTest2310/testing/tests/test_mock_server.py
# Third-party imports... from unittest.mock import patch # Local imports... from services import get_users from tests.mocks import get_free_port, start_mock_server class TestMockServer(object): @classmethod def setup_class(cls): cls.mock_server_port = get_free_port() start_mock_server(cls.mock_server_port) def test_request_response(self): mock_users_url = 'http://localhost:{port}/users'.format(port=self.mock_server_port) # Patch USERS_URL so that the service uses the mock server URL instead of the real URL. with patch.dict('services.__dict__', {'USERS_URL': mock_users_url}): response = get_users() assert 'Content-Type' in response.headers.keys() assert response.headers['Content-Type'] == 'application/json; charset=utf-8' assert response.ok, True assert response.json() == []
{"/python4testers_student/code_along/vingroup/payments/vinid.py": ["/python4testers_student/code_along/vingroup/products/vinfast.py"]}
12,695
yenlt6/learningpython
refs/heads/main
/Day8Test1809/hackathon1_midterm/medium.py
def anagram_number(number): a=str(number)[::-1] if a==str(number): return True else : return False def roman_to_int(s): rom_dict = {'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900,'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000} i = 0 int1 = 0 while i < len(s): if i+1<len(s) and s[i:i+2] in rom_dict: int1+=rom_dict[s[i:i+2]] i+=2 else: #print(i) int1+=rom_dict[s[i]] i+=1 return int1
{"/python4testers_student/code_along/vingroup/payments/vinid.py": ["/python4testers_student/code_along/vingroup/products/vinfast.py"]}
12,696
yenlt6/learningpython
refs/heads/main
/Day8Test1809/hackathon1_midterm/easy.py
# 1 from datetime import datetime import re def day_diff(release_date, code_complete_day): release_date = datetime.strptime(release_date, "%d/%m/%Y") code_complete_day = datetime.strptime(code_complete_day, "%Y-%d-%m") return abs((release_date - code_complete_day).days) # 2 def alpha_num(sentence): return re.findall(r'(?:\d+[a-zA-Z]+|[a-zA-Z]+\d+)', sentence)
{"/python4testers_student/code_along/vingroup/payments/vinid.py": ["/python4testers_student/code_along/vingroup/products/vinfast.py"]}
12,697
yenlt6/learningpython
refs/heads/main
/python4testers_student/code_along/hello.py
print("Hello class") print("The variable __name__ tells me which context this file is running in.") print("The value of __name__ is:", repr(__name__)) class Query(): pass class Database(): pass def main(): print("Hello in main!") if __name__ == "__main__": main()
{"/python4testers_student/code_along/vingroup/payments/vinid.py": ["/python4testers_student/code_along/vingroup/products/vinfast.py"]}
12,698
yenlt6/learningpython
refs/heads/main
/Day20FileHandling0611/file_handling/file_handling/writetodocfile.py
print("Ban muon ghi de hay them noi dung vao file?") mode= input("> ") + "+" contents = [] print("Nhap noi dung cho file") while True: line = input("> ") if len(line) ==0: break contents.append(line + '\n') with open('demo.txt', mode, encoding='utf8') as file: file.writelines(contents) with open('demo.txt') as file: print(file.read())
{"/python4testers_student/code_along/vingroup/payments/vinid.py": ["/python4testers_student/code_along/vingroup/products/vinfast.py"]}
12,699
yenlt6/learningpython
refs/heads/main
/python4testers_student/exercises/sample_debug.py
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% [markdown] # Viết chương trình Python kiểm tra số lớn nhất trong 3 số # # - Khai báo 3 biến `a`, `b`, `c` nhập giá trị số bất kỳ (int) # - Kiểm tra và in ra số lớn nhất trong 3 số đó # %% a, b, c = 12, 16, 19 print(max(a,b,c)) if a >= b: if a >= c: print("Max is: ", a) else: print("Max is: ", c) else: if b >= c: print("Max is: ", b) else: print("Max is: ", c) # %% [markdown] # Viết chương trình kiểm tra một năm có phải năm nhuận hay không # # - Nhập một năm `year` - int # - Kiểm tra và in ra kết quả `year` có phải năm nhuận hay không # # 💡 Năm nhuận là năm: # # - Chia hết cho 400 # - Chia hết cho 4 **nhưng** không chia hết cho 100 # %% # %% [markdown] # Viết chương trình tính chỉ số BMI (Body Mass Index - Chỉ số cơ thể) # # - Nhập chiều cao `h` (đơn vị m) và cân nặng `w` (đơn vị kg) # - Tính chỉ số BMI: `w / (h * h)` # - In chỉ số và thông báo kết quả theo quy ước: # - BMI < 17: Gầy độ II # - 17 <= BMI < 18.5: Gầy độ I # - 18.5 <= BMI < 25: Bình thường # - 25 <= BMI < 30: Thừa cân # - 30 <= BMI < 35: Béo phì độ I # - 35 <= BMI: Béo phì độ II # %% [markdown] #
{"/python4testers_student/code_along/vingroup/payments/vinid.py": ["/python4testers_student/code_along/vingroup/products/vinfast.py"]}
12,700
yenlt6/learningpython
refs/heads/main
/day_8_temp/docfiledic.py
#Bài 3: Bài tập tổng hợp phần Basic - Đếm từ import sys # Đếm từ def print_words(filename): words_count = readfile_count_words(filename) words_count_sorted = sorted(list(words_count), key = lambda k: k[0]) for i in words_count_sorted: print (i, ":", words_count[i]) def print_top(filename): words_count = readfile_count_words(filename) words_count_sorted = sorted(list(words_count), key = words_count.get, reverse = True) inc = 1 for i in words_count_sorted: print (f"{inc}. {i}: {words_count[i]}") inc += 1 if inc > 20: break def readfile_count_words(filename): f = open(filename, encoding='utf-8-sig') content = remove_special_char(f.read()) list_str = content.split(" ") dict_count = {} for i in list_str: if i == '': continue i = i.lower() if i in dict_count: dict_count[i] += 1 else: dict_count[i] = 1 return dict_count def remove_special_char(str): special_char = ['.', ',', '?', '!', '\n', '\r', '(', ')', '[', ']', ':', '--', ';', '`', "' ", '"'] for j in special_char: str = str.replace(j, " ") return str ### # This basic command line argument parsing code is provided and # calls the print_words() and print_top() functions which you must define. def main(): if len(sys.argv) != 3: print('usage: ./wordcount.py {--count | --topcount} file') sys.exit(1) option = sys.argv[1] filename = sys.argv[2] if option == '--count': print_words(filename) elif option == '--topcount': print_top(filename) else: print('unknown option: ' + option) sys.exit(1) if __name__ == '__main__': main()
{"/python4testers_student/code_along/vingroup/payments/vinid.py": ["/python4testers_student/code_along/vingroup/products/vinfast.py"]}
12,701
yenlt6/learningpython
refs/heads/main
/python4testers_student/code_along/vingroup/products/vinfast.py
def lux_sa(): print('[vinfast] lux_sa()') class VinFast: pass from vingroup.payments.vinid import id id()
{"/python4testers_student/code_along/vingroup/payments/vinid.py": ["/python4testers_student/code_along/vingroup/products/vinfast.py"]}
12,702
yenlt6/learningpython
refs/heads/main
/Day102509/bank_account_from_file.py
import os import sys import csv import json import pprint current_dir = os.path.dirname(os.path.abspath(sys.argv[0])) csv_file = os.path.join(current_dir, "bank_accounts.csv") json_file = os.path.join(current_dir, "bank_accounts.json") class BankAccount: minimum_balance = 50000 def __init__(self, account_number, account_name, balance=0): self._account_number = account_number self._account_name = account_name self.balance = balance @property def account_number(self): return self._account_number @property def account_name(self): return self._account_name @property def balance(self): return self._balance @balance.setter def balance(self, balance): if balance >= 0: self._balance = balance else: raise ValueError("Số dư phải lớn hơn 0") def display(self): print( f"| {self.account_number:9} | {self.account_name:15} | {self.balance:>15} |") def withdraw(self, amount): if 0 < amount <= self.balance - BankAccount.minimum_balance: self.balance -= amount else: raise ValueError( f"Số tiền phải lớn hơn 0 và không được vượt quá số dư hiện tại") def deposit(self, amount): if amount > 0: self.balance += amount else: raise ValueError("Số tiền phải lớn hơn 0") @classmethod def from_csv(cls, csv_file): accounts = [] with open(csv_file) as file: reader = csv.reader(file) for account_number, account_name, balance in reader: accounts.append( cls(account_number, account_name, int(balance))) return accounts # @classmethod # def from_json(cls, json_file): # with open(json_file) as file: # return json.load(file, object_hook=lambda d: cls(**d)) @classmethod def from_json(cls, json_file): accounts = [] with open(json_file) as file: data = json.load(file) for item in data: accounts.append(cls(**item)) return accounts csv_accounts = BankAccount.from_csv(csv_file) print(f"| {'Number':9} | {'Account Name':15} | {'Balance':15} |") print(f"|{'-' * 11}|{ '-' * 17 }|{'-' * 17}|") for account in csv_accounts: account.display() print() json_accounts = BankAccount.from_json(json_file) print(f"| {'Number':9} | {'Account Name':15} | {'Balance':15} |") print(f"|{'-' * 11}|{ '-' * 17 }|{'-' * 17}|") for account in json_accounts: account.display() print()
{"/python4testers_student/code_along/vingroup/payments/vinid.py": ["/python4testers_student/code_along/vingroup/products/vinfast.py"]}
12,703
yenlt6/learningpython
refs/heads/main
/python4testers_student/code_along/card_game/deck.py
from card import Card from random import shuffle class Deck: ranks = ['A', 2, 3, 4, 5, 6, 7, 8, 9] suits = ['S', 'C', 'D', 'H'] def build(self): self.cards = [Card(rank, suit) for rank in Deck.ranks for suit in Deck.suits] def shuffle_cards(self): shuffle(self.cards) def deal_card(self): if len(self.cards) > 0: return self.cards.pop()
{"/python4testers_student/code_along/vingroup/payments/vinid.py": ["/python4testers_student/code_along/vingroup/products/vinfast.py"]}
12,707
jUnion44/plastic
refs/heads/master
/core/migrations/0012_auto_20200723_1728.py
# Generated by Django 2.2.4 on 2020-07-23 17:28 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0011_mcpsschool'), ] operations = [ migrations.AddField( model_name='mcpsschool', name='lat', field=models.FloatField(default=1, max_length=200), preserve_default=False, ), migrations.AddField( model_name='mcpsschool', name='long', field=models.FloatField(default=22, max_length=200), preserve_default=False, ), ]
{"/extractionhigh.py": ["/core/models.py"], "/core/views.py": ["/core/models.py"], "/locatem.py": ["/core/models.py"], "/core/migrations/0001_initial.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]}
12,708
jUnion44/plastic
refs/heads/master
/core/migrations/0007_blogpost_compares.py
# Generated by Django 2.2.4 on 2020-07-13 15:06 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0006_auto_20200712_2017'), ] operations = [ migrations.AddField( model_name='blogpost', name='compares', field=models.ManyToManyField(to='core.companyCompare'), ), ]
{"/extractionhigh.py": ["/core/models.py"], "/core/views.py": ["/core/models.py"], "/locatem.py": ["/core/models.py"], "/core/migrations/0001_initial.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]}
12,709
jUnion44/plastic
refs/heads/master
/core/migrations/0024_zipcode_population.py
# Generated by Django 2.2.4 on 2020-08-25 16:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0023_zipcode_area'), ] operations = [ migrations.AddField( model_name='zipcode', name='population', field=models.BigIntegerField(default=0), preserve_default=False, ), ]
{"/extractionhigh.py": ["/core/models.py"], "/core/views.py": ["/core/models.py"], "/locatem.py": ["/core/models.py"], "/core/migrations/0001_initial.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]}
12,710
jUnion44/plastic
refs/heads/master
/extractionhigh.py
from bs4 import BeautifulSoup import camelot import requests import csv from core.models import mcpsSchool ROOT_URL = "https://www.montgomeryschoolsmd.org/" datadump = [["High School","ppp_2014_2015","ppp_2015_2016","ppp_2016_2017","ppp_2017_2018","ppp_2018_2019"]] html = open("high school links.html","r").read() soup = BeautifulSoup(html, 'html.parser') links = soup.find_all('a') for link in links: school = link.contents[0] href = link['href'] pdfdata = requests.get(ROOT_URL+href).content temppdf = open("temp.pdf","wb") temppdf.write(pdfdata) temppdf.close() tables = camelot.read_pdf("temp.pdf") print("Total tables extracted for " + school + ":", tables.n) tables[0].to_csv("temp.csv") datareader = csv.reader(open("temp.csv")) schooltable = ['"'+school+'"',0.0,0.0,0.0,0.0,0.0] for row in datareader: for count in range(len(row)): try: row[count] = row[count].replace("*","") schooltable[count] = schooltable[count] + float(row[count]) except: pass for count in range(1,6): schooltable[count] = str(schooltable[count]/12) datadump.append(schooltable) out = open("outputhigh.csv","w") for row in datadump: rowstring = ",".join(row) out.write(rowstring+"\n") out.close()
{"/extractionhigh.py": ["/core/models.py"], "/core/views.py": ["/core/models.py"], "/locatem.py": ["/core/models.py"], "/core/migrations/0001_initial.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]}
12,711
jUnion44/plastic
refs/heads/master
/core/migrations/0004_auto_20200708_1746.py
# Generated by Django 2.2.4 on 2020-07-08 17:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0003_attachment'), ] operations = [ migrations.AddField( model_name='attachment', name='link', field=models.TextField(blank=True), ), migrations.AddField( model_name='companycompare', name='testField1', field=models.FloatField(default=-1, max_length=200), ), migrations.AddField( model_name='companycompare', name='testField2', field=models.FloatField(default=-1, max_length=200), ), migrations.AddField( model_name='companycompare', name='testField3', field=models.FloatField(default=-1, max_length=200), ), migrations.AddField( model_name='companycompare', name='testField4', field=models.FloatField(default=-1, max_length=200), ), migrations.AddField( model_name='companycompare', name='testField5', field=models.FloatField(default=-1, max_length=200), ), migrations.AddField( model_name='companycompare', name='testField6', field=models.FloatField(default=-1, max_length=200), ), migrations.AddField( model_name='companycompare', name='testField7', field=models.FloatField(default=-1, max_length=200), ), migrations.AddField( model_name='companycompare', name='testField8', field=models.FloatField(default=-1, max_length=200), ), migrations.AddField( model_name='companycompare', name='testField9', field=models.FloatField(default=-1, max_length=200), ), ]
{"/extractionhigh.py": ["/core/models.py"], "/core/views.py": ["/core/models.py"], "/locatem.py": ["/core/models.py"], "/core/migrations/0001_initial.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]}
12,712
jUnion44/plastic
refs/heads/master
/core/migrations/0008_auto_20200716_1415.py
# Generated by Django 2.2.4 on 2020-07-16 14:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0007_blogpost_compares'), ] operations = [ migrations.AddField( model_name='companycompare', name='lat', field=models.FloatField(blank=True, max_length=200, null=True), ), migrations.AddField( model_name='companycompare', name='long', field=models.FloatField(blank=True, max_length=200, null=True), ), migrations.AlterField( model_name='blogpost', name='compares', field=models.ManyToManyField(blank=True, to='core.companyCompare'), ), ]
{"/extractionhigh.py": ["/core/models.py"], "/core/views.py": ["/core/models.py"], "/locatem.py": ["/core/models.py"], "/core/migrations/0001_initial.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]}
12,713
jUnion44/plastic
refs/heads/master
/core/migrations/0011_mcpsschool.py
# Generated by Django 2.2.4 on 2020-07-23 17:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0010_blogpost_script'), ] operations = [ migrations.CreateModel( name='mcpsSchool', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('schooltype', models.CharField(choices=[('elementarty', 'Elementary School'), ('middle', 'Middle School'), ('high', 'High School'), ('special', 'Special Schools')], default='high', max_length=20)), ('name', models.CharField(max_length=500)), ('ppp_2014_2015', models.FloatField(max_length=200)), ('ppp_2018_2019', models.FloatField(max_length=200)), ], ), ]
{"/extractionhigh.py": ["/core/models.py"], "/core/views.py": ["/core/models.py"], "/locatem.py": ["/core/models.py"], "/core/migrations/0001_initial.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]}
12,714
jUnion44/plastic
refs/heads/master
/processAsset/copyFiles.py
import boto3, sys fileName = sys.argv[1] fileAccName = sys.argv[2] session = boto3.session.Session() client = session.client('s3', region_name='sfo2', endpoint_url='https://sfo2.digitaloceanspaces.com', aws_access_key_id="POTR4I5FSNCEF3OUGSV5", aws_secret_access_key="3aJaqDuBbwfBEME41ILK7zJuNxYZH/64I97g2X3xp7M") client.put_object(Bucket='plastic', Key=fileName.split("/")[-1], Body=open(fileName,"rb").read(), ACL='public-read')
{"/extractionhigh.py": ["/core/models.py"], "/core/views.py": ["/core/models.py"], "/locatem.py": ["/core/models.py"], "/core/migrations/0001_initial.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]}
12,715
jUnion44/plastic
refs/heads/master
/core/migrations/0021_zipcode_average_income.py
# Generated by Django 2.2.4 on 2020-08-10 15:52 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0020_auto_20200810_1551'), ] operations = [ migrations.AddField( model_name='zipcode', name='average_income', field=models.FloatField(default=0, max_length=200), preserve_default=False, ), ]
{"/extractionhigh.py": ["/core/models.py"], "/core/views.py": ["/core/models.py"], "/locatem.py": ["/core/models.py"], "/core/migrations/0001_initial.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]}
12,716
jUnion44/plastic
refs/heads/master
/core/migrations/0009_blogpost_desc.py
# Generated by Django 2.2.4 on 2020-07-18 17:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0008_auto_20200716_1415'), ] operations = [ migrations.AddField( model_name='blogpost', name='desc', field=models.TextField(blank=True), ), ]
{"/extractionhigh.py": ["/core/models.py"], "/core/views.py": ["/core/models.py"], "/locatem.py": ["/core/models.py"], "/core/migrations/0001_initial.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]}
12,717
jUnion44/plastic
refs/heads/master
/core/migrations/0018_auto_20200810_0214.py
# Generated by Django 2.2.4 on 2020-08-10 02:14 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0017_zipcode'), ] operations = [ migrations.AlterField( model_name='zipcode', name='code', field=models.CharField(max_length=500), ), ]
{"/extractionhigh.py": ["/core/models.py"], "/core/views.py": ["/core/models.py"], "/locatem.py": ["/core/models.py"], "/core/migrations/0001_initial.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]}
12,718
jUnion44/plastic
refs/heads/master
/core/models.py
from django.db import models from django.contrib.auth import get_user_model from django.conf import settings def get_sentinel_user(): return get_user_model().objects.get_or_create(username='Deleted User')[0] # Create your models here. class companyCompare(models.Model): name = models.CharField(max_length=200) desc = models.TextField(blank=True) longdesc = models.TextField(blank=True) ppp = models.FloatField(null=True) plasticPpp = models.FloatField(null=True) testField1 = models.FloatField(max_length=200,default=-1) testField2 = models.FloatField(max_length=200,default=-1) testField3 = models.FloatField(max_length=200,default=-1) testField4 = models.FloatField(max_length=200,default=-1) testField5 = models.FloatField(max_length=200,default=-1) testField6 = models.FloatField(max_length=200,default=-1) testField7 = models.FloatField(max_length=200,default=-1) testField8 = models.FloatField(max_length=200,default=-1) testField9 = models.FloatField(max_length=200,default=-1) lat = models.FloatField(max_length=200,blank=True,null=True) long = models.FloatField(max_length=200,blank=True,null=True) tags = models.TextField(blank=True) def __str__(self): return self.name class blogpost(models.Model): name = models.CharField(max_length=200) author = models.ForeignKey("auth.user",on_delete=models.SET(get_sentinel_user)) desc = models.TextField(blank=True) content = models.TextField() script = models.TextField(blank=True) compares = models.ManyToManyField(companyCompare,blank=True) def __str__(self): return self.name + " by " + self.author.first_name + " " + self.author.last_name class attachment(models.Model): post = models.ForeignKey(blogpost, on_delete=models.CASCADE) file = models.FileField(upload_to="processAsset/") link = models.TextField(blank=True) def __str__(self): return self.file.filename class mcpsSchool(models.Model): schooltype_choices = [("elementarty","Elementary School"),("middle","Middle School"),("high","High School"),("special","Special Schools")] schooltype = models.CharField(max_length=20,choices=schooltype_choices,default="high") name = models.CharField(max_length=500) ppp_2014_2015 = models.FloatField(max_length=200) ppp_2015_2016 = models.FloatField(max_length=200) ppp_2016_2017 = models.FloatField(max_length=200) ppp_2017_2018 = models.FloatField(max_length=200) ppp_2018_2019 = models.FloatField(max_length=200) ppp_2014_2015_rank = models.FloatField(max_length=200) ppp_2015_2016_rank = models.FloatField(max_length=200) ppp_2016_2017_rank = models.FloatField(max_length=200) ppp_2017_2018_rank = models.FloatField(max_length=200) ppp_2018_2019_rank = models.FloatField(max_length=200) lat = models.FloatField(max_length=200) long = models.FloatField(max_length=200) desc = models.TextField(blank=True,null=True) link = models.TextField(blank=True,null=True) def __str__(self): return self.schooltype + " - " + self.name class pums(models.Model): code = models.CharField(max_length=500) geodata = models.TextField(blank=True,null=True) def __str__(self): return self.code class zipcode(models.Model): code = models.CharField(max_length=10) geodata = models.TextField(blank=True,null=True) area = models.FloatField() population = models.BigIntegerField() average_income = models.FloatField(max_length=200) density = models.FloatField() def __str__(self): return self.code
{"/extractionhigh.py": ["/core/models.py"], "/core/views.py": ["/core/models.py"], "/locatem.py": ["/core/models.py"], "/core/migrations/0001_initial.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]}
12,719
jUnion44/plastic
refs/heads/master
/core/migrations/0022_auto_20200810_1726.py
# Generated by Django 2.2.4 on 2020-08-10 17:26 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0021_zipcode_average_income'), ] operations = [ migrations.AddField( model_name='mcpsschool', name='ppp_2014_2015_rank', field=models.FloatField(default=0, max_length=200), preserve_default=False, ), migrations.AddField( model_name='mcpsschool', name='ppp_2015_2016_rank', field=models.FloatField(default=0, max_length=200), preserve_default=False, ), migrations.AddField( model_name='mcpsschool', name='ppp_2016_2017_rank', field=models.FloatField(default=0, max_length=200), preserve_default=False, ), migrations.AddField( model_name='mcpsschool', name='ppp_2017_2018_rank', field=models.FloatField(default=0, max_length=200), preserve_default=False, ), migrations.AddField( model_name='mcpsschool', name='ppp_2018_2019_rank', field=models.FloatField(default=0, max_length=200), preserve_default=False, ), ]
{"/extractionhigh.py": ["/core/models.py"], "/core/views.py": ["/core/models.py"], "/locatem.py": ["/core/models.py"], "/core/migrations/0001_initial.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]}
12,720
jUnion44/plastic
refs/heads/master
/core/migrations/0014_auto_20200729_2304.py
# Generated by Django 2.2.4 on 2020-07-29 23:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0013_auto_20200724_1722'), ] operations = [ migrations.AddField( model_name='mcpsschool', name='ppp_2015_2016', field=models.FloatField(default=11, max_length=200), preserve_default=False, ), migrations.AddField( model_name='mcpsschool', name='ppp_2016_2017', field=models.FloatField(default=1, max_length=200), preserve_default=False, ), migrations.AddField( model_name='mcpsschool', name='ppp_2017_2018', field=models.FloatField(default=23, max_length=200), preserve_default=False, ), ]
{"/extractionhigh.py": ["/core/models.py"], "/core/views.py": ["/core/models.py"], "/locatem.py": ["/core/models.py"], "/core/migrations/0001_initial.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]}
12,721
jUnion44/plastic
refs/heads/master
/core/views.py
from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse,JsonResponse from .models import * from django.db.models import Model from django.db.models import Field from django.forms.models import model_to_dict from django.core import serializers import json def getName(fieldString): return fieldString.split(".")[-1] # Create your views here. def index(request): return render(request,"core/index.html",{"entities":companyCompare.objects.all()}) def getfield(request,eid,name,index): companies_json = serializers.serialize("json", [get_object_or_404(companyCompare,pk=eid)]) cjl = json.loads(companies_json) return JsonResponse({"index":index,"pk":eid,"val":cjl[0]["fields"][name]}) def getfieldmcps(request,eid,name,index): companies_json = serializers.serialize("json", [get_object_or_404(mcpsSchool,pk=eid)]) cjl = json.loads(companies_json) return JsonResponse({"index":index,"pk":eid,"val":cjl[0]["fields"][name]}) def explore(request): s=False g=False p=False try: objectfilter = request.GET["filter"] if objectfilter=="s": s=True if objectfilter=="g": g=True if objectfilter=="p": p=True except: pass return render(request,"core/explore.html",{"entities":companyCompare.objects.all(),"s":s,"g":g,"p":p}) def plasticmap(request): s=False g=False p=False try: objectfilter = request.GET["filter"] if objectfilter=="s": s=True if objectfilter=="g": g=True if objectfilter=="p": p=True except: pass companies_json = serializers.serialize("json", companyCompare.objects.all()) cjl = json.loads(companies_json) return render(request,"core/plasticmap.html",{"rawjson":companies_json,"entities":cjl,"fields":cjl[0]["fields"].items()}) def plasticmapmcps(request): companies_json = serializers.serialize("json", mcpsSchool.objects.all()) cjl = json.loads(companies_json) zipcodes = zipcode.objects.all() return render(request,"core/plasticmapmcps.html",{"zipcodes":zipcodes,"rawjson":companies_json,"entities":cjl,"fields":cjl[0]["fields"].items()}) def explorespecific(request,eid): e = get_object_or_404(companyCompare,pk=eid) posts = e.blogpost_set.all() return render(request,"core/explorespecific.html",{"e":e,"bps":posts}) def blog(request): return render(request,"core/exploreblog.html",{"bs":blogpost.objects.all()}) def blogspecific(request,eid): e = get_object_or_404(blogpost,pk=eid) return render(request,"core/blogpost.html",{"b":e}) def database(request): fields = companyCompare._meta.fields fields = list(fields) fields = list(map(str,fields)) fields = list(map(getName,fields)) companies = list(companyCompare.objects.all()) companies = list(map(model_to_dict,companies)) companies_json = serializers.serialize("json", companyCompare.objects.all()) cjl = json.loads(companies_json) return render(request,"core/db.html",{"rawjson":companies_json,"entities":cjl,"fields":cjl[0]["fields"].items()})
{"/extractionhigh.py": ["/core/models.py"], "/core/views.py": ["/core/models.py"], "/locatem.py": ["/core/models.py"], "/core/migrations/0001_initial.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]}
12,722
jUnion44/plastic
refs/heads/master
/core/migrations/0002_companycompare.py
# Generated by Django 2.1.3 on 2020-07-03 11:21 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0001_initial'), ] operations = [ migrations.CreateModel( name='companyCompare', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=200)), ('ppp', models.FloatField(null=True)), ('plasticPpp', models.FloatField(null=True)), ], ), ]
{"/extractionhigh.py": ["/core/models.py"], "/core/views.py": ["/core/models.py"], "/locatem.py": ["/core/models.py"], "/core/migrations/0001_initial.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]}
12,723
jUnion44/plastic
refs/heads/master
/core/migrations/0013_auto_20200724_1722.py
# Generated by Django 2.2.4 on 2020-07-24 17:22 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0012_auto_20200723_1728'), ] operations = [ migrations.AddField( model_name='mcpsschool', name='desc', field=models.TextField(blank=True, null=True), ), migrations.AddField( model_name='mcpsschool', name='link', field=models.TextField(blank=True, null=True), ), ]
{"/extractionhigh.py": ["/core/models.py"], "/core/views.py": ["/core/models.py"], "/locatem.py": ["/core/models.py"], "/core/migrations/0001_initial.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]}
12,724
jUnion44/plastic
refs/heads/master
/middle.py
print(models) import csv datareader = csv.reader(open("outputmiddle.csv")) first=False for row in datareader: if not first: first = True continue s = models.mcpsSchool() s.name = row[0] s.schooltype="middle" s.ppp_2014_2015 = row[1] s.ppp_2015_2016 = row[2] s.ppp_2016_2017 = row[3] s.ppp_2017_2018 = row[4] s.ppp_2018_2019 = row[5] s.ppp_2014_2015_rank = row[6] s.ppp_2015_2016_rank = row[7] s.ppp_2016_2017_rank = row[8] s.ppp_2017_2018_rank = row[9] s.ppp_2018_2019_rank = row[10] s.lat=0 s.long=0 s.save()
{"/extractionhigh.py": ["/core/models.py"], "/core/views.py": ["/core/models.py"], "/locatem.py": ["/core/models.py"], "/core/migrations/0001_initial.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]}
12,725
jUnion44/plastic
refs/heads/master
/core/urls.py
from django.urls import path from . import views app_name = "core" urlpatterns = [ #Front Page path('', views.index, name='index'), path('explore/', views.explore, name='explore'), path('explore/<int:eid>/', views.explorespecific, name='explorespecific'), path('blog/', views.blog, name='blog'), path('blog/<int:eid>/', views.blogspecific, name='blogspecific'), path('database/', views.database, name='db'), path('map/', views.plasticmap, name='plasticmap'), path('map/mcps/', views.plasticmapmcps, name='plasticmapmcps'), path('getField/<int:eid>/<str:name>/<int:index>/', views.getfield, name='getfield'), path('getField/mcps/<int:eid>/<str:name>/<int:index>/', views.getfieldmcps, name='getfieldmcps'), ## #Course Signups and Stuff ## path('course/<str:cid>/', views.loadCourse, name='coursePage'), ## path('course/<str:cid>/join/', views.joinCourse, name='joinCourse'), ## path('course/private/join/', views.joinCoursePrivate, name='joinCoursePrivate'), ## path('courseList/', views.courseList, name="courseList"), ## path('courseView/', views.courseView, name="courseView"), ## path('leaveCourse/<str:cid>/', views.leaveCourse, name="courseLeave"), ## ## #Account Management ## path('register/', views.register, name="register"), ## path('login/', views.loginu, name="login"), ## path('logout/', views.logoutu, name="logout"), ## #path('manage/', views.manageAccount, name="manageAccount"), ]
{"/extractionhigh.py": ["/core/models.py"], "/core/views.py": ["/core/models.py"], "/locatem.py": ["/core/models.py"], "/core/migrations/0001_initial.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]}
12,726
jUnion44/plastic
refs/heads/master
/locatem.py
import csv import requests, json from core.models import mcpsSchool from django.shortcuts import get_object_or_404 datareader = csv.reader(open("middleaddr.csv")) BAD = [41,46] for row in datareader: if int(row[0]) in BAD: continue obj = get_object_or_404(mcpsSchool,pk=row[0]) pdfdata = json.loads(requests.get("https://geocoding.geo.census.gov/geocoder/locations/address?street="+row[2]+"&benchmark=9&format=json&zip="+row[3].split(" ")[-1]+"").content) print(pdfdata) obj.long = float(pdfdata["result"]["addressMatches"][0]['coordinates']["x"]) obj.lat = float(pdfdata["result"]["addressMatches"][0]['coordinates']["y"]) obj.save()
{"/extractionhigh.py": ["/core/models.py"], "/core/views.py": ["/core/models.py"], "/locatem.py": ["/core/models.py"], "/core/migrations/0001_initial.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]}
12,727
jUnion44/plastic
refs/heads/master
/core/migrations/0001_initial.py
# Generated by Django 2.1.3 on 2020-07-03 11:13 import core.models from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='blogpost', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=200)), ('content', models.TextField()), ('author', models.ForeignKey(on_delete=models.SET(core.models.get_sentinel_user), to=settings.AUTH_USER_MODEL)), ], ), ]
{"/extractionhigh.py": ["/core/models.py"], "/core/views.py": ["/core/models.py"], "/locatem.py": ["/core/models.py"], "/core/migrations/0001_initial.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]}
12,728
jUnion44/plastic
refs/heads/master
/core/migrations/0020_auto_20200810_1551.py
# Generated by Django 2.2.4 on 2020-08-10 15:51 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0019_auto_20200810_1551'), ] operations = [ migrations.RenameModel( old_name='zipcodeArchive', new_name='zipcode', ), ]
{"/extractionhigh.py": ["/core/models.py"], "/core/views.py": ["/core/models.py"], "/locatem.py": ["/core/models.py"], "/core/migrations/0001_initial.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]}
12,729
jUnion44/plastic
refs/heads/master
/core/admin.py
from django.contrib import admin from .models import * # Register your models here. admin.site.register(blogpost) admin.site.register(companyCompare) admin.site.register(attachment) admin.site.register(mcpsSchool) admin.site.register(zipcode) #admin.site.register(zipcodeArchive)
{"/extractionhigh.py": ["/core/models.py"], "/core/views.py": ["/core/models.py"], "/locatem.py": ["/core/models.py"], "/core/migrations/0001_initial.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]}
12,730
jUnion44/plastic
refs/heads/master
/core/migrations/0010_blogpost_script.py
# Generated by Django 2.2.4 on 2020-07-18 18:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0009_blogpost_desc'), ] operations = [ migrations.AddField( model_name='blogpost', name='script', field=models.TextField(blank=True), ), ]
{"/extractionhigh.py": ["/core/models.py"], "/core/views.py": ["/core/models.py"], "/locatem.py": ["/core/models.py"], "/core/migrations/0001_initial.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]}
12,731
jUnion44/plastic
refs/heads/master
/core/migrations/0006_auto_20200712_2017.py
# Generated by Django 2.2.4 on 2020-07-12 20:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0005_companycompare_tags'), ] operations = [ migrations.AddField( model_name='companycompare', name='desc', field=models.TextField(blank=True), ), migrations.AddField( model_name='companycompare', name='longdesc', field=models.TextField(blank=True), ), ]
{"/extractionhigh.py": ["/core/models.py"], "/core/views.py": ["/core/models.py"], "/locatem.py": ["/core/models.py"], "/core/migrations/0001_initial.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]}
12,732
jUnion44/plastic
refs/heads/master
/core/migrations/0025_zipcode_density.py
# Generated by Django 2.2.4 on 2020-08-25 16:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0024_zipcode_population'), ] operations = [ migrations.AddField( model_name='zipcode', name='density', field=models.FloatField(default=0), preserve_default=False, ), ]
{"/extractionhigh.py": ["/core/models.py"], "/core/views.py": ["/core/models.py"], "/locatem.py": ["/core/models.py"], "/core/migrations/0001_initial.py": ["/core/models.py"], "/core/admin.py": ["/core/models.py"]}
12,769
Merigold89/Testing-trial
refs/heads/main
/calculator.py
class Calculator: def __init__(self, first, second): self.first = first self.second = second def add(self): """ Addition """ return self.first + self.second # przy zamianie na "+" na "-" pojawią się błędy w test_calculator.py def multiply(self): """ Multiplication """ return self.first * self.second def subtract(self): """ Subtraction """ return self.first - self.second def divide(self): """ Division """ if self.second == 0: pass #return ZeroDivisionError return self.first / self.second
{"/calculator_test.py": ["/calculator.py"], "/calculator_GUI.py": ["/calculator.py"]}
12,770
Merigold89/Testing-trial
refs/heads/main
/calculator_test.py
import unittest import calculator # aby uruchomić: linia komend: python -m unittest test_calculator class TestCalculator(unittest.TestCase): def setUp(self): """ Is executed before every test method. """ self.calc = calculator.Calculator(5, 1) print('setUp method') def tearDown(self): """ Is executed after every test method. """ self.calc = calculator.Calculator(1, 0) print('tearDown method') def test_add(self): """ Tests for the add() function. """ self.assertEqual(self.calc.add(), 6) self.calc.first = 8 self.calc.second = 2 self.assertEqual(self.calc.add(), 10) print('test_add method') def test_subtract(self): """ Tests for the subtract() function. """ self.assertEqual(self.calc.subtract(), 4) self.calc.first = 8 self.calc.second = 2 self.assertEqual(self.calc.subtract(), 6) print('test_subtract method') def test_multiply(self): """ Tests for the multiply() function. """ self.assertEqual(self.calc.multiply(), 5) self.calc.first = 8 self.calc.second = 2 self.assertEqual(self.calc.multiply(), 16) print('test_multiply method') def test_divide(self): """ Tests for the divide() function. """ self.assertEqual(self.calc.divide(), 5) self.calc.first = 0 self.calc.second = 5 self.assertEqual(self.calc.divide(), 0) self.calc = calculator.Calculator(1, 0) #self.assertEqual(self.calc.divide(), ZeroDivisionError) print('test_divide method') if __name__ == "__main__": unittest.main()
{"/calculator_test.py": ["/calculator.py"], "/calculator_GUI.py": ["/calculator.py"]}
12,771
Merigold89/Testing-trial
refs/heads/main
/test_calculator_simple.py
import unittest import calculator_simple # aby uruchomić: linia komend: python -m unittest test_calculator lub dodać ostatni fragment kodu # plik test_calclator.py i calculator.py muszą być w jednym folderze class TestCalculator(unittest.TestCase): # a test case for the calculator.py module def test_add(self): """ Tests for the add() function. assertEqual - sprawdza, czy 2 podane argumenty są sobie równe: 2 zmienne ajko argumenty dla funkcji oraz oczekiwany wynik, dodatkowo komentarz w sypadku fail testu """ self.assertEqual(calculator_simple.add(6, 4), 10, 'Error when adding two positive numbers') self.assertEqual(calculator_simple.add(6, -4), 2, 'Error when adding two positive and negative numbers') self.assertEqual(calculator_simple.add(-6, 4), -2, 'Error when adding two negative and positive numbers') self.assertEqual(calculator_simple.add(-6, -4), -10, 'Error when adding two negative numbers') def test_multiply(self): """ Tests for the multiply() function. """ self.assertEqual(calculator_simple.multiply(6, 4), 24) self.assertEqual(calculator_simple.multiply(6, -4), -24) self.assertEqual(calculator_simple.multiply(-6, 4), -24) self.assertEqual(calculator_simple.multiply(-6, -4), 24) def test_subtract(self): """ Tests for the subtract() function. """ self.assertEqual(calculator_simple.subtract(6, 4), 2) self.assertEqual(calculator_simple.subtract(6, -4), 10) self.assertEqual(calculator_simple.subtract(-6, 4), -10) self.assertEqual(calculator_simple.subtract(-6, -4), -2) def test_divide(self): """ Tests for the divide() function. """ self.assertEqual(calculator_simple.divide(10, 2), 5) self.assertEqual(calculator_simple.divide(10, -2), -5) self.assertEqual(calculator_simple.divide(-10, 2), -5) self.assertEqual(calculator_simple.divide(-10, -2), 5) self.assertRaises(ValueError, calculator_simple.divide, 5, 0) # 1 metoda, ValueError jest wartością oczekiwaną, potem argumenty with self.assertRaises(ValueError): # 2 metoda wywołujemy błąd calculator_simple.divide(5, 0) #self.assertEqual(calculator.divide(10, 0), 0) # zamiast litery F zwóci literę E, #test zgłasza wyjątek inny niż błąd AssertionError (ValueError) - nieprawidłowość jest, ale nie uważa się, aby test został oblany if __name__ == "__main__": # jeśli nie chcemy odpalać z linii komend unittest.main()
{"/calculator_test.py": ["/calculator.py"], "/calculator_GUI.py": ["/calculator.py"]}
12,772
Merigold89/Testing-trial
refs/heads/main
/calculator_GUI.py
# from __future__ import unicode_literal # obsługa polskich liter import calculator from PyQt5.QtWidgets import QApplication, QWidget # importujemy klasy z modulu from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QLabel, QGridLayout from PyQt5.QtWidgets import QLineEdit, QPushButton, QHBoxLayout # linia edyccji, przycisk from PyQt5.QtWidgets import QMessageBox # tworzy komunikaty from PyQt5.QtCore import Qt # zawiera stale class calculator_window(QWidget): # klasa dziedziczaca def __init__(self, parent=None): # zwraca nam klase rodzica i wywoluje jego konstruktor super().__init__(parent) self.interfejs() # wywolujemy konstruktor / klasa interfejs def interfejs(self): """ - etykiety - przypisanie widgetow do ukladu tabelarycznego - przypisanie utworzonego ukladu do okna - widzeta - okna do wprowadzenia danych - przyciski działań matematycznych - zwiazanie przyciskow do funkcji operacji """ label1 = QLabel("Number 1:", self) # etykiety label2 = QLabel("Number 2:", self) label3 = QLabel("Result:", self) layoutT = QGridLayout() # QGridLayout - przypisanie umiejscowienia widgetow do ukladu tabelarycznego layoutT.addWidget(label1, 0, 0) # addWidget - przypisanie etykiety do okna aplikacji layoutT.addWidget(label2, 0, 1) layoutT.addWidget(label3, 0, 2) self.setLayout(layoutT) # przypisanie utworzonego układu do okna aplikacji self.number1Edt = QLineEdit() # 1-liniowe pola edycyjne self.number2Edt = QLineEdit() self.resultEdt = QLineEdit() self.resultEdt.readonly = True # mozliwosc odczytu pola tekstowego self.resultEdt.setToolTip("") # ustala odpowiedz layoutT.addWidget(self.number1Edt, 1, 0) layoutT.addWidget(self.number2Edt, 1, 1) layoutT.addWidget(self.resultEdt, 1, 2) addBtn = QPushButton("&Add", self) # przyciski subtractBtn = QPushButton("&Subtract", self) divideBtn = QPushButton("&Divide", self) multiplyBtn = QPushButton("&Multiply", self) exitBtn = QPushButton("&Exit", self) exitBtn.resize(exitBtn.sizeHint()) # sugerowana wielkosc obiektu exitBtn.clicked.connect(self.exit) # zwiazanie przycisku "Exit" z metoda exit addBtn.clicked.connect(self.operation) subtractBtn.clicked.connect(self.operation) multiplyBtn.clicked.connect(self.operation) divideBtn.clicked.connect(self.operation) layoutH = QHBoxLayout() # uklad horyzontalny layoutH.addWidget(addBtn) layoutH.addWidget(subtractBtn) layoutH.addWidget(divideBtn) layoutH.addWidget(multiplyBtn) layoutT.addLayout(layoutH, 2, 0, 1, 3) # uklad tabelaryczny przyciskow: co chcemy wstawic, wiersze i kolumny wstawiania layoutT.addWidget(exitBtn, 3, 0, 1, 3) self.setGeometry(150, 150, 300, 100) # okresla polozenia okna aplikacji self.setWindowIcon(QIcon('calculator_icon.png')) # setWindowIcon - stworzenie widzety - ikony kalkulatora self.setWindowTitle("Simple calculator") # setWindowTitle - opis nagłowka programu self.show() def exit(self): """ Exit the program. """ self.close() def closeEvent(self, event): # nazwa funkcji jest bardzo wazna! - nie zmieniac """ Dialog box "Are you sure you shut up?" when exiting the program. """ answer = QMessageBox.question( # tworze okno dialogowe self, 'message', # naglowek okna "Are you sure you want to close?", # pytanie w oknie QMessageBox.Yes | QMessageBox.No, QMessageBox.No) # komibancja przyciskow "YES' i "NO" oraz przycisku domyslnego if answer == QMessageBox.Yes: event.accept() else: event.ignore() def keyPressEvent(self, e): # nazwa funkcji jest bardzo wazna! - nie zmieniac """ Close the program with the ESC button. """ if e.key() == Qt.Key_Escape: self.close() def operation(self): """ Entered data is sent back to the calculation module (calculator.py) and the result is obtained back. """ user = self.sender() try: # jesli wprowadzone zmienne nie da rady zmienic na float wyswietl blad number1 = float(self.number1Edt.text()) number2 = float(self.number2Edt.text()) result = "" self.calc = calculator.Calculator(number1, number2) if user.text() == "&Add": result = self.calc.add() elif user.text() == "&Subtract": result = self.calc.subtract() elif user.text() == "&Multiply": result = self.calc.multiply() else: # dzielenie try: result = round(self.calc.divide(), 9) except ZeroDivisionError: QMessageBox.critical( self, "Error", "Can not divide by zero!") return self.resultEdt.setText(str(result)) # wyswietlanie wyniku w oknie "Result" except ValueError: QMessageBox.warning(self, "Error", "Incorrect data", QMessageBox.Ok) if __name__ == '__main__': import sys app = QApplication(sys.argv) # reprezentuje aplikacje window = calculator_window() sys.exit(app.exec_()) # głowna petla programu
{"/calculator_test.py": ["/calculator.py"], "/calculator_GUI.py": ["/calculator.py"]}
12,773
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/inheritance.py
class bankAccount: def __init__(self, acct_id, acct_type, cust_id, cust_name, balance, credit_line): self.acct_id = acct_id self.acct_type = acct_type self.cust_id = cust_id self.cust_name = cust_name self.balance = balance self.credit_line = credit_line def deposit(self, amount): print("----------------------") self.displayAccount() print("DEPOSIT TRANSACTION INITIATED FOR AMOUNT : ", amount) print("\n") self.balance = self.balance + amount self.displayAccount() print("----------------------") def withdraw(self, amount): print("----------------------") self.displayAccount() print("WITHDRAWAL TRANSACTION INITIATED FOR AMOUNT: ", amount) print("\n") if (self.balance + self.credit_line >= amount): self.balance = self.balance - amount self.displayAccount() else: print("insufficient funds") print("----------------------") def intRateCalc(self): pass def displayAccount(self): print("current acct id:", self.acct_id) print("current acct type:", self.acct_type) print("current cust id:", self.cust_id) print("current cust name:", self.cust_name) print("current balance:", self.balance) print("current credit line:", self.credit_line) print("\n") # Inheritance ISA relationship # savingAccount inherits bankAccount # savingAccount class can have its own methods extending base class functionality # savingAccount can override parent methods class savingAccount(bankAccount): def __init__(self, acct_id, acct_type, cust_id, cust_name, balance, credit_line): # super key word to call parent class constructor super().__init__(acct_id, acct_type, cust_id, cust_name, balance, credit_line) # method overriding def intRateCalc(self): pass # Inheritance ISA relationship # checkingAccount inherits bankAccount # checkingAccount can have its own methods extending base class functionality # checkingAccount can override parent methods class checkingAccount(bankAccount): def __init__(self, acct_id, acct_type, cust_id, cust_name, balance, credit_line): # super key word to call parent class constructor super().__init__(acct_id, acct_type, cust_id, cust_name, balance, credit_line) # method overriding def intRateCalc(self): pass # create savingAccount object sa = savingAccount(5000124, "SAVING", 1244, "SIRI", 500000, 100000) # create checkingAccount object ca = checkingAccount(5000126, "CHECKING", 1244, "SIRI", 400000, 50000) sa.deposit(20000) ca.deposit(60000) sa.withdraw(600000) ca.withdraw(500000) print(type(sa)) print(type(ca))
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,774
sanneabhilash/python_learning
refs/heads/master
/PracticePrograms/oddEven.py
def is_even(number): if number % 2 == 0: return True return False for i in range(10): print('Is the number:', i, " a even?", is_even(i))
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,775
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/ExceptionHandling/raiseAndThrowExceptions.py
i = input("Enter a number :") j = input("Enter another number :") try: if i == '0' or j == '0': raise ValueError("Input cannot be zero") print(i+j) except ValueError as ve: print(ve) except Exception as e: print(e)
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,776
sanneabhilash/python_learning
refs/heads/master
/PracticePrograms/FileWriteReadDicts.py
performances = {'Ventriloquism': '9:00am', 'Snake Charmer': '12:00pm', 'Amazing Acrobatics': '2:00pm', 'Enchanted Elephants': '5:00pm'} print(performances) print("------------Writing above values into file-----------") schedule_file = open('schedule.txt', 'w') for key, val in performances.items(): schedule_file.write(key + " - " + val) schedule_file.write("\n") schedule_file.close() print('-----------READ FROM FILET---------------') performances_new = {} schedule_file = open('schedule.txt', 'r') for line in schedule_file: (show, time) = line.replace("/n", "").split(" - ") print(show, time) performances_new[show] = time.strip() schedule_file.close() print("------------PRINT LIST--------------") print(performances_new)
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,777
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/dictionaries.py
#!/usr/bin/env python # coding: utf-8 #A dictionary is a collection which is unordered, changeable and indexed. #In Python dictionaries are written with curly brackets, and they have keys and values. # Key Value Pairs mydict = {'a': 'apple', 'b': 'ball', 'c': 'cat', 'd': 'dog'} print(mydict) print(mydict['a']) mydict['a'] = 'Avacado' # update value for key 'a' print(mydict) del mydict['b'] # Delete 'b' key value pair print(mydict) # Below line deletes entire dictionary # del mydict # print(mydict) for i in mydict: print(i, ":", mydict[i]) print("-------Use Items() method-------") for key, value in mydict.items(): print(key, value) # Print length of dictionary print(len(mydict)) # Multi dimensional dictionaries students = {101: {'name': 'John', 'maths': 50, 'chemistry': 56, 'physics': 75}, 102: {'name': 'Steve', 'maths': 66, 'chemistry': 89, 'physics': 59}, 103: {'name': 'Peter', 'maths': 88, 'chemistry': 78, 'physics': 86}, 104: {'name': 'Ben', 'maths': 99, 'chemistry': 76, 'physics': 99} } for student in students: print(students[student]['name'], end=",") print() print('-----------------------------------------') for key, value in students.items(): print(key, end=":") for k, v in value.items(): # print(k, v, end=',') print(v) print("")
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,778
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/Operators/bitwise.py
# Bitwise Operator & | ^ print('Bitwise AND operator') print(0 & 0) print(0 & 1) print(1 & 0) print(1 & 1) print('Bitwise OR operator') print(0 | 0) print(0 | 1) print(1 | 0) print(1 | 1) print('Bitwise ExOR operator') print(0 ^ 0) print(0 ^ 1) print(1 ^ 0) print(1 ^ 1) print('<< Binary Left Shift') a = 240 print(a << 2) print('<< Binary Right Shift') a = 24 print(a << 2) print('~ Binary Ones Complement') a = 60 print(~a)
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,779
sanneabhilash/python_learning
refs/heads/master
/PracticePrograms/swapTwoNumbers.py
print("---------Continue---------") # without temp variable i=10 j=11 print(i,j) i=i+j j=i-j i =i-j print(i,j) print("---------Continue---------") # with temp variable i=10 j=11 print(i,j) temp = j j = i i = temp print(i,j) print("---------Continue---------") # With Python, optimized code i=10 j=11 print(i,j) i,j = j, i print(i, j)
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,780
sanneabhilash/python_learning
refs/heads/master
/PracticePrograms/class_print_student_details.py
import math class Student: # Encapsulation: Binding data and methods together # Also talks about, data access specifiers def __init__(self, name, age, maths, phy, che): self.name = name self.age = age self.maths = maths self.phy = phy self.che = che # End of function constructor def get_average(self): """ Calculate and return the student average scores :return: Average of scores in maths, phy, che """ self.avg = math.floor((self.maths + self.phy + self.che) / 3, ) self.assign_grade() return self.avg # End of method get_average def assign_grade(self): if self.avg >= 75: self.grade = 'A' elif self.avg > 65: self.grade = 'B' else: self.grade = 'C' # End of method getGrade def print_student_details(self): print("---------Student Details for: ", self.name, "---------") print("Name: ", self.name) print("Age: ", self.age) print("Maths: ", self.maths) print("Physics: ", self.phy) print("Chemistry: ", self.che) print("Average: ", self.get_average()) print("Grade: ", self.grade) # End of method printStudentDetails def __del__(self): del self # End of Destructor method # End of class Student stud1 = Student("Abhilash", 28, 55, 65, 88) stud2 = Student("Sneha", 55, 67, 78, 87) stud3 = Student("Mahesh", 33, 45, 65, 45) stud1.print_student_details() stud2.print_student_details() stud3.print_student_details() print("-----------------------------------------------")
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,781
sanneabhilash/python_learning
refs/heads/master
/PracticePrograms/remove_duplicates_lists.py
# [2,2,3,5,5]. Remove duplicate elements and print my_list = [2, 2, 3, 3, 4, 5, 6, 7, 7] new_list: list = [] for i in my_list: if i not in new_list: new_list.append(i) print(new_list)
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,782
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/iterators.py
my_greetings = "helloworld" iter_str = iter(my_greetings) print(next(iter_str), end="") print(next(iter_str), end="") print(next(iter_str), end="") print(next(iter_str), end="") print(next(iter_str), end="") print(next(iter_str), end="") print(next(iter_str), end="") print(next(iter_str), end="") print(next(iter_str), end="") print(next(iter_str), end="") # Printed complete string, next iteration will throw error # print(next(iter_str)) print() for i in my_greetings: # Internally iterator is being called on string __iter__ print(i, end="") # print(my_greetings.__iter__())
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,783
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/classesAndObjects.py
# Class is a collection of objects # Class is a blueprint for creating an object # Class is a logical Entity # An Object is an instance of class class Calculator: def add(self, i, j): # self - (this) pointer pointing to current instance which is invoking # Any method called via object instance should use self self.i = i # Instance variable self.j = j # Instance variable return i + j # End of method add # End of class Calculator calc = Calculator() print(calc.add(1, 2)) print(calc.i, calc.j) print(type(calc)) # <class '__main__.Calculator'> # Type of a class instance is __main__.Calculator, this is beacuse we are running in standalone mode # Python assigns the start of app as __main__ module
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,784
sanneabhilash/python_learning
refs/heads/master
/File_Actions_Automation/copymove.py
# import os # import shutil # import zipfile # import time # # from readwrite import readcfg # # # def mergepaths(path1, path2): # pieces = [] # parts1, tail1 = os.path.splitdrive(path1) # parts2, tail2 = os.path.splitdrive(path2) # result = path2 # parts1 = tail1.split('\\') if '\\' in tail1 else tail1.split('/') # parts2 = tail2.split('\\') if '\\' in tail2 else tail2.split('/') # for pitem in parts1: # if pitem != '': # if not pitem in parts2: # pieces.append(pitem) # for piece in pieces: # result = os.path.join(result, piece) # return result # # # def fileaction(options): # if len(options['type']) == 1: # # for zipping # zipf = startzip(options['dest'], options['type']) # # for exclusions # cmdfolder(zipf, options['origin'], options['dest'], options['type'], options['exclude']) # if options['type'] == 'd': # shutil.rmtree(options['origin']) # endzip(zipf, options['type']) # # # # for exclusions # def cmdfolder(zipf, origin, dest, opt, exc): # for fld, sflds, fnames in os.walk(origin): # # for exclusions # cmdfoldercore(zipf, fld, dest, opt, sflds, fnames, exc) # # # # for exclusions # def cmdfoldercore(zipf, fld, dest, opt, sflds, fnames, exc): # print('Processing folder: ' + fld) # cmdsubfolder(fld, opt, sflds) # # for exclusions # cmdfiles(zipf, fld, dest, opt, fnames, exc) # # # def cmdsubfolder(fld, opt, sflds): # for sf in sflds: # print('Processing subfolder: ' + sf + ' in ' + fld) # # # # for exclusions # def cmdfiles(zipf, fld, dest, opt, fnames, exc): # for fname in fnames: # # for not excluding files with a specific extension # if not isexcluded(fname, exc): # fn = os.path.join(fld, fname) # if opt == 'c': # filecopy(fname, fld, dest) # elif opt == 'm': # filemove(fname, fld, dest) # elif opt == 'd': # filedelete(fname, fld, dest) # # for zipping # elif opt == 'z': # filezip(zipf, fname, fld) # # # def filecopy(fname, fld, dest): # fn = os.path.join(fld, fname) # d = mergepaths(fld, dest) # try: # if not os.path.exists(d): # os.makedirs(d) # shutil.copy(fn, d) # except err: # print('ERROR copying file: ' + fname + ' in ' + fld + ' with exception: ' + str(ioerr)) # finally: # print('Copied file: ' + fname + ' in ' + fld) # # # def filemove(fname, fld, dest): # fn = os.path.join(fld, fname) # d = mergepaths(fld, dest) # try: # # move doesn't check if a file exists # if not os.path.exists(d): # os.makedirs(d) # shutil.move(fn, d) # except ioerr: # print('ERROR moving file: ' + fname + ' in ' + fld + ' with exception: ' + str(ioerr)) # finally: # print('Moved file: ' + fname + ' in ' + fld) # # # def filedelete(fname, fld, dest): # fn = os.path.join(fld, fname) # try: # os.unlink(fn) # except ioerr: # print('ERROR deleting file: ' + fname + ' in ' + fld) # finally: # print('Deleted file: ' + fname + ' in ' + fld) # # # # for zipping # def filezip(zipf, fname, fld): # fn = os.path.join(fld, fname) # try: # zipf.write(fn) # except: # print('ERROR zipping file: ' + fname + ' in ' + fld) # finally: # print('Zipped file: ' + fname + ' in ' + fld) # # # # for zipping # def adddttofilename(fname): # datet = str(time.strftime("%Y%m%d-%H%M%S")) # if '%%' in fname: # fname = fname.replace('%%', datet) # return fname # # # # for zipping # def startzip(dest, opt): # zipf = None # if opt == 'z': # zipf = zipfile.ZipFile(adddttofilename(dest), 'w', allowZip64=True) # return zipf # # # # for zipping # def endzip(zipf, opt): # if not zipf is None and opt == 'z': # zipf.close() # # # # for excluding files with a specific extension # def isexcluded(fname, excl): # res = False # lexc = excl.split(',') # if len(lexc) > 0: # if os.path.splitext(fname)[1] in lexc: # res = True # return res # # # # for ftp... # def ftpaction(opts): # # todo... # return # # # # for cfg script # def runall(): # cfg = os.path.splitext(os.path.basename('readwrite'))[0] + '.ini' # items = readcfg(cfg) # for item in items: # if bool(item) is True: # if item['type'] == 'f': # ftpaction(item) # else: # fileaction(item) # # # # for cfg script # runall()
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,785
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/Operators/comparision.py
# Operators: # Arithmetic # Comparision # Logical # Membership # Identity # Bitwise # Comparision operators print('----------Comparision-------') i = 10 j = 20 print(i > j) print(i < j) print(i >= j) print(i <= j) print(i == j) print(i != j) # Not equal # print(i<>j) # Not equal, not supported in python v3.X
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,786
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/fileHandling_Exceptions.py
# Python file object provides basic methods to manipulate files such as open, read, write, append & close methods # file object = open(file name[, access mode][, buffersize]) # files can be opened in read mode, write mode or append mode # file read methods # read() #return one big string # readline #return one line at a time # readlines #returns a list of lines # file write methods # write () #used to write a fixed sequence of characters to a file # writelines() #writelines to write a list of strings # file close method # close() #release all the system resources # to create a file you have to use open function with any of the mode w, a, w+ and a+ # w write mode (if the file doesn’t exist create it and open it in write mode) # a append mode (if the file doesn’t exist create it and open it in append mode) # w+ create a file – if it doesn’t exist and open it in write mode # a+ create a file – if it doesn’t exist and open it in append mode import os dirName = "C:/temp" # create target directory if don't exist if not os.path.exists(dirName): os.mkdir(dirName) print("directory created:", dirName) else: print("directory exists already :", dirName) fileName = dirName + "/" + "mytext.txt" file_exists = os.path.isfile(fileName) f = None # create file if it does not exist if file_exists: print("file exists already:", fileName) else: # to create a file you have to use open function with any of the mode w, a, w+ and a+ f = open(fileName, 'w') if (f): print("file created :", fileName) # write a fixed sequence of characters to a file f = None try: f = open("C:/TEMP/mytext.txt", 'w') f.write("HELLO WORLD") except (FileNotFoundError, IOError) as e: print(e) finally: if (f): f.close() # to read file as one big string f = None try: f = open("C:/TEMP/mytext.txt", 'r') print(f.read()) except (FileNotFoundError, IOError) as e: print(e) finally: if (f): f.close() # to read one line at a time f = None try: f = open("C:/TEMP/mytext.txt", 'r') print(f.readline()) except (FileNotFoundError, IOError) as e: print(e) finally: if (f): f.close() # to read line from list of lines f = None try: f = open("C:/TEMP/mytext.txt", 'r') for file in f.readlines(): print(file) # print(type(file)) except (FileNotFoundError, IOError) as e: print(e) finally: if (f): f.close() # reading file using for Loop f = None try: f = open("C:/TEMP/mytext.txt", 'r') for line in f: print(line) except (FileNotFoundError, IOError) as e: print(e) finally: if (f): f.close() # write a fixed sequence of characters to a file f = None try: f = open("C:/TEMP/mytext.txt", 'w') f.write("HELLO WORLD, HOW ARE YOU DOING?") except (FileNotFoundError, IOError) as e: print(e) finally: if (f): f.close() # write a fixed sequence of characters to a file f = None try: f = open("C:/TEMP/mytext.txt", 'w') f.write("HELLO\n") f.write("HOW ARE YOU DOING\n") except (FileNotFoundError, IOError) as e: print(e) finally: if (f): f.close() # writelines can write a list of strings # w+ #write to file and read file f = None try: f = open("C:/TEMP/mytext.txt", 'w+') fruits = ['Apples\n', 'Bananas\n', 'Oranges\n'] f.writelines(fruits) f.seek(0) print(f.read()) except (FileNotFoundError, IOError) as e: print(e) finally: if (f): f.close() # append to the file without overwriting it. f = None try: f = open("C:/TEMP/mytext.txt", "a") f.write("Hello World again") except (FileNotFoundError, IOError) as e: print(e) finally: if (f): f.close() # append to the file and then read file f = None try: f = open("C:/TEMP/mytext.txt", 'a+') f.write("\nYou are about to reach in 5 seconds \n") f.write("Please follow the queue to exit door \n") f.write("Collect your luggage here") f.seek(0) print(f.read()) except (FileNotFoundError, IOError) as e: print(e) finally: if (f): f.close() # pattern search for a given string in file f = None try: f = open("C:/TEMP/mytext.txt", 'r') if 'Apple' in f.read(): print('Applle found') except (FileNotFoundError, IOError) as e: print(e) finally: if (f): f.close() # work with file objects using with statement f = None with open(“testfile.txt”) as f: for line in f: print line # binary files ##file wb access mode opens a file for writing only in binary format. f = None try: f = open("C:/TEMP/mytext.txt", "wb") num = [5, 10, 15, 20, 25] arr = bytearray(num) f.write(arr) except (FileNotFoundError, IOError) as e: print(e) finally: if (f): f.close() # binary files # file rb access mode opens a file for reading f = None try: f = open("C:/TEMP/mytext.txt", "rb") num = list(f.read()) print (num) f.close() except (FileNotFoundError, IOError) as e: print(e) finally: if (f): f.close()
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,787
sanneabhilash/python_learning
refs/heads/master
/unit_testing_examples/test_pytestPractice.py
from Concepts_with_examples.modules_and_packages.carsPackage import Audi import pytest @pytest.mark.set1 def test_file1_method1(): x = 5 y = 6 assert x + 1 == y, "test failed" print("Executed Test_file1") @pytest.mark.set2 def test_new_car(): car = Audi.AudiSubDealers() print(car.dealers()) assert 1 == 1, "should be equal" # pytest -m set2 -v filepath
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,788
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/ExceptionHandling/handlingValueError.py
performances = {'Ventriloquism': '9:00am', 'Snake Charmer': '12:00pm', 'Amazing Acrobatics': '2:00pm', 'Enchanted Elephants': '5:00pm'} schedule_file = open('schedule.txt', 'w') for key, val in performances.items(): schedule_file.write(key, "-", val) schedule_file.close() schedule_file = open('schedule.txt', 'r') for line in schedule_file: show, time = line.split(' - ') print(show, time) schedule_file.close() performances_new = {} performances_new = {} try: schedule_file = open('schedule.txt', 'r') except FileNotFoundError as err: print(err) for line in schedule_file: (show, time) = line.split(' - ') performances_new [show] = time schedule_file.close() print(performances_new)
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,789
sanneabhilash/python_learning
refs/heads/master
/PracticePrograms/fibonacci.py
def print_fibonacci(n): if n == 1: print(0, end = " ") elif n == 2: print(0,1, end = "") else: print(0,1, end=" ") a = 0 b = 1 while n > 2: print(a+b, end = " ") a, b = b, a+ b n = n -1 return 0 for i in range(1, 20): print_fibonacci(i) print()
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,790
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/set_operations.py
# These are unordered sets my_empty_dictionary = {} # Creates an empty dictionary my_empty_set = set() # Creates an empty set print(my_empty_set) print(type(my_empty_set)) my_set = {100, 200, 20, 12, 4, 'hello'} print(type(my_set)) print(my_set) my_set.add(200) my_set.add(200) # duplicate values are not added print(my_set) print('---------------------------------------------------') set1 = {1, 2, 3, 4, 5, 12} set2 = {1, 3, 5, 6, 7, 8, 9, 11} print('Union:', set1.union(set2)) print('Operator Union: ', set1 | set2) print('intersection: ', set1.intersection(set2)) print('Operator intersection: ', set1 & set2) print('difference: ', set1.difference(set2)) print('Operator difference: ', set1 - set2) print('symmetric_difference: ', set1.symmetric_difference(set2)) print('Operator symmetric_difference: ', set1^set2) print('isdisjoint: ', set1.isdisjoint(set2)) print('issubset: ', set1.issubset(set2)) print('issuperset: ', set1.issuperset(set2))
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,791
sanneabhilash/python_learning
refs/heads/master
/PracticePrograms/export_excel_data_to_mysql/excel_to_mysql.py
import xlrd import MySQLdb # Open the workbook and define the worksheet book = xlrd.open_workbook("data.xls") sheet = book.sheet_by_name("source") # Establish a MySQL connection connection = MySQLdb.connect(host="localhost", user="root", passwd="root", db="mysqlPython") # Get the cursor, which is used to traverse the database, line by line cursor = connection.cursor() # Drop table if exists cursor.execute("DROP TABLE IF EXISTS orders") # Create Table orders cursor.execute("""CREATE TABLE orders( cus_id INT NOT NULL AUTO_INCREMENT, cus_firstname VARCHAR(100) NOT NULL, cus_product VARCHAR(100) NOT NULL, cus_quantity VARCHAR(100) NOT NULL, PRIMARY KEY ( cus_id ) ); """) # Create the INSERT INTO sql query query = """INSERT INTO orders (cus_firstname, cus_product, cus_quantity) VALUES (%s, %s, %s) """ # Create a For loop to iterate through each row in the XLS file, starting at row 2 to skip the headers for r in range(1, sheet.nrows): name = sheet.cell(r, 0).value product = sheet.cell(r, 1).value quantity = sheet.cell(r, 2).value # Assign values from each row values = (name, product, quantity) # Execute sql Query cursor.execute(query, values) # Commit the transaction connection.commit() # Close the cursor cursor.close() # Close the database connection connection.close() # Print results print("") columns = str(sheet.ncols) rows = str(sheet.nrows - 1) print("Imported", columns, "columns and", rows, "rows to MySQL!") print("Executed Completed!!")
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,792
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/AccessModifiers/public.py
#PUBLIC : All member variables and methods are public by default in Python. class Jar: def __init__(self): self.content = None def fill(self, content): self.content = content def empty(self): print('empty the jar...') self.content = None myJar = Jar() myJar.content = "salt" print(myJar.content) myJar.empty() myJar.fill('sugar') print(myJar.content)
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,793
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/Oops_static_instance_variables.py
# Class or static variables are shared by all objects. Instance or non-static variables are different for different objects (every object has a copy of it). # In C++ and Java, static keyword helps to make a variable as class variable. The variables which don’t have preceding static keyword are instance variables. # The Python doesn’t require a static keyword. All variables which are assigned a value in class declaration are class variables. # And variables which are assigned values inside class methods are instance variables. class BankAccount: # class(static) variable bankName = "ABC INTERNATIONAL BANK" def __init__(self, acct_id, acct_type, cust_id, cust_name, amount, credit_line): # instance variables self.acct_id = acct_id self.acct_type = acct_type self.cust_id = cust_id self.cust_name = cust_name self.amount = amount self.credit_line = credit_line def displayAccount(self): print("----------------------------------------------------------------") print(self.acct_id, self.acct_type, self.cust_id, self.cust_name, self.amount, self.credit_line) def deposit(self, amount): self.amount = self.amount + amount def withdraw(self, amount): if (self.amount + self.credit_line >= amount): self.amount = self.amount - amount self.displayAccount() else: print("insufficient funds") def intRateCalc(self): pass class SavingAccount(BankAccount): def __init__(self, acct_id, acct_type, cust_id, cust_name, amount, credit_line): BankAccount.__init__(self, acct_id, acct_type, cust_id, cust_name, amount, credit_line) def intRateCalc(self): pass class CheckingAccount(BankAccount): def __init__(self, acct_id, acct_type, cust_id, cust_name, amount, credit_line): BankAccount.__init__(self, acct_id, acct_type, cust_id, cust_name, amount, credit_line) def intRateCalc(self): pass sa = SavingAccount(5000124, "SAVING", 1244, "SIRI", 5000000, 100000) ca = CheckingAccount(5000126, "CHECKING", 1244, "SIRI", 4000000, 50000) print("---------------------") print(BankAccount.bankName) print(sa.bankName) print(ca.bankName) # In Python a class(static) variable cannot be changed using an instance # in this case it creates a new instance variable in the saving account object sa.bankName = "XYZ INTERNATIONAL BANK" print("---------------------") print(sa.bankName) print(BankAccount.bankName) # In Python a class(static) variable can be changed only using the class name BankAccount.bankName = "XYZ INTERNATIONAL BANK" print("---------------------") print(BankAccount.bankName) print(ca.bankName) print(sa.bankName) print("---------------------")
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,794
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/regular_expressions.py
# regex is to search for a given pattern in a string # syntax: match = re.search(pat, str) # In Python regular expression supports various things like Modifiers, Identifiers, and White space characters # RegEx Functions # Function Description # findall Returns a list containing all matches # search Returns a Match object if there is a match anywhere in the string # split Returns a list where the string has been split at each match # sub Replaces one or many matches with a string # \d matches decimals [0-9] # \D matches anything other than decimals [0-9] # all regEx in python of form \x (Includes cases) and \X (Not includes cases) are opposite import re my_str = 'Hello world' m = re.search("(world)", my_str) if m: print(m) print(type(m)) print("search:", m.group()) print(m.span()) message = '984799287' match = re.match(r'\d', message) if match: print(match.group()) print(match) match = re.match(r'\d+', message) # Parse more than one digit if match: print(match.group()) print(match) listd = ['dog', 'dog group', 'dog dog', 'dodge'] for element in listd: m = re.match("(d\w+)\s(d\w+)", element) print(m) no_spaces = re.match("(d\w+)\S(d\w+)", element) values ='02873-409-204' for m in re.finditer('\d+', values): print(m.group()) values = "one 22 two-232 56 fffff" result = re.split('\D', values) for element in result: print(element, end=",") #regex or regular expression is to search for a given pattern in a string #import re #syntax: match = re.search(pat, str) #re.search() method returns an match object #regular expression methods? #re.findall() method returns a list containing all matches #re.search() method returns a Match object if there is a match anywhere in the string #re.split() method returns a list where the string has been split at each match #re.sub() method replaces one or many matches with a string #re.search() Vs re.match() #re.search() ⇒ find something anywhere in the string and return a match object. #re.match() ⇒ find something at the beginning of the string and return a match object. #A special sequence is a \ followed by one of the characters in the list below: #A Returns a match if the specified characters are at the beginning of the string "\AThe" #\b Returns a match where the specified characters are at the beginning or at the end of a word r"\bain" #\B Returns a match where the specified characters are present, but NOT at the beginning (or at the end) of a word r"\Bain" #\d Returns a match where the string contains digits (numbers from 0-9) "\d" #\D Returns a match where the string DOES NOT contain digits "\D" #\s Returns a match where the string contains a white space character "\s" #\S Returns a match where the string DOES NOT contain a white space character "\S" #\w Returns a match where the string contains any word characters (characters from a to Z, digits from 0-9, and the underscore _ character) "\w" #\W Returns a match where the string DOES NOT contain any word characters "\W" #\Z Returns a match if the specified characters are at the end of the string "Spain\Z" import re my_str='hello world' #search for "world" in "hello world" m=re.search("(world)",my_str) if m: #print(m) #print(type(m)) print("search:",m.group()) print(m.span()) #search for 'oo' in 'google' match=re.search(r'oo','google') print(match.group()) #search for digits in string match=re.search(r'\d\d\d','p123g') print(match.group()) #search for email address in a given string str='purple aliceinwonderland@google.com ' match=re.search(r'\w+@\w+\.(\w+)',str) if match: print(match.group()) #re.match() ⇒ find something at the beginning of the string and return a match object. m = re.match(r"(?P<int>\w+)\.(\d*)", '3.143') print(m.group()) #re.match() ⇒ find something at the beginning of the string and return a match object. #re.match for "world" in "hello world" my_str='hello world' m=re.match("(world)",my_str) if m: print(m) print(type(m)) print("search:",m.group()) print(m.span()) #re.match() if string starts in digit message='22466678' match=re.match(r'^\d+',message) if match: print(match.group()) # re.match() if two words starting with letter d. list=['dog dot','do dont','dumb-dumb','no match','dumb-kitty'] for element in list: m=re.match("(d\w+)\W(d\w+)",element) if m: print(m.group()) #re.findall() returns a list containing all matches. str='The rain started pouring' x=re.findall('ai',str) print(x) #re.findall() returns a list containing all matches. str='The rain started pouring in india' x=re.findall('india',str) print(x) #re.split() returns a list where the string has been split at each match: value='one 12 two 22 three 333' result=re.split('\D+',value) for element in result: print(element)
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,795
sanneabhilash/python_learning
refs/heads/master
/PracticePrograms/calculate_student_grade_dictionary.py
# Calculate grade using nested dictionaries student_record = {1000: {'name': 'A', 'M': 50, 'P': 60, 'C': 70}, 1001: {'name': 'B', 'M': 55, 'P': 65, 'C': 75}} for key, value in student_record.items(): print('****************************') print('ID: ' + str(key)) total_marks = 0 for k1, v1 in value.items(): if k1.casefold() == 'name': print(k1.capitalize() + ': ' + v1) if (k1 == 'M') or (k1 == 'P') or (k1 == 'C'): total_marks = total_marks + v1 average_scre = total_marks / 3 if average_scre >= 75: print('Grade A') elif average_scre >= 65 and average_scre < 75: print('Grade B') else: print('Grade C') print('****************************')
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,796
sanneabhilash/python_learning
refs/heads/master
/PracticePrograms/sumOfNaturalNumbers.py
def sum_of_natural_numbers(number): total: int = 0 while number > 0: total = total + number number -= 1 return total def recursive_sum(number): total: int = 0 for i in range(number): total = total + i; return total print('While Loop Sum: ', sum_of_natural_numbers(10)) print('For Loop Sum: ', sum_of_natural_numbers(10))
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,797
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/Sqlite3_interactions.py
############################################################ # SQLITE3 DATABASE CONNECTION AND EXCEPTION HANDLING import sqlite3 as lite import sys # create sqlite connection and retrieve the sqlite version con = None try: con = lite.connect('common.db') cur = con.cursor() cur.execute('SELECT SQLITE_VERSIO()') data = cur.fetchone() print ("SQLite version: %s" % data) except lite.Error as e: print("Exception : lite.Error") print ("Error %s:" % e.args[0]) except Exception as e: print("Exception") print(e) sys.exit(1) finally: if con: con.close() ############################################################ # MYSQL DATABASE CONNECTION AND EXCEPTION HANDLING import mysql.connector con = None try: # create MYSQL connection & create commondb by default con = mysql.connector.connect(host='localhost', user='root', passwd='hello123', auth_plugin='mysql_native_password', database='commondb') cur = con.cursor() # fetch MYSQL version print("-----------------------------------------") cur.execute('SELECT VERSION()') data = cur.fetchone() print ("MYSQL version: %s" % data) except mysql.connector.Error as err: print("mysql exception: {}".format(err)) except Exception as e: print ("Error %s:" % e.args[0]) sys.exit(1) finally: if con: con.close() ###########################################################
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,798
sanneabhilash/python_learning
refs/heads/master
/File_Actions_Automation/zip.py
import zipfile zipf = zipfile.ZipFile('./target.zip', 'w', allowZip64=True) zipf.write('./ftp.py') zipf.write('./walkdir.py') zipf.close()
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,799
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/lists.py
my_greetings='Hello world' print(my_greetings) print(my_greetings[0]) print(my_greetings[1]) # Slicing an array print(my_greetings[0:3]) # Start included, end excluded print(my_greetings[4:9]) # Negative indexing print(my_greetings[-1]) print(my_greetings[-2]) # Immutable Strings, Assignment throws error # TypeError: 'str' object does not support item assignment # my_greetings[1] = 'E' print(my_greetings[1]) # Delete # TypeError: 'str' object doesn't support item deletion # del my_greetings[1] # Destroy the entire object del my_greetings # NameError: name 'my_greetings' is not defined # print(my_greetings) my_greetings='Hello world' for i in my_greetings: print(i) # Concatenation print(my_greetings + " " + my_greetings) for i in range(0, len(my_greetings)): print(my_greetings[i], end="") print("") for i in range(1, len(my_greetings)+1): print(my_greetings[-i], end="") print() integer = [1, 2, 3, 4, 5] print(integer * 3) print(integer + integer) #!/usr/bin/env python # coding: utf-8 # List can have different data type values my_list = [1, 2.5, "hello world", [1,2,3,4]] print(type(my_list)) print(id(my_list)) print(my_list) print(my_list[2][1]) print(my_list[3][3]) print(my_list[0:3]) print(my_list[3][1:3]) # Lists are mutable # When its values are changed, new list is not created my_list1 = [1, 2.5, "hello world", [1,2,3,4]] print(type(my_list1)) print(id(my_list1)) my_list1[0] = 12.5 my_list1[1]= "Oranges" print(my_list1) print(type(my_list1)) print(id(my_list1)) # Iterate over sub lists in a list of mixed data types for i in my_list: if type(i)==list: for j in i: print(j) else: print(i) # Concatenate two lists new_list = my_list + my_list1 print(new_list) # Reverse Lists print(new_list[::-1]) revList = list(reversed(new_list)) print(revList) for i in reversed(new_list): print(i, end=", ")
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,800
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/Operators/membership.py
# Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples from typing import List myList: List[str] = ['apple', 'orange', 'banana'] fruit = 'apple' # in operator # Evaluates to true if it finds a variable in the specified sequence and false otherwise. if fruit in myList: print('List holds the fruit: ' + fruit) # not in operator # Evaluates to true if it does not finds a variable in the specified sequence and false otherwise. fruit2 = 'pineapple' if fruit2 not in myList: print('List does not hold the fruit: ' + fruit2)
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,801
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/set_intro.py
#A set is an unordered collection of items. Every element in the set is unique (no duplicates). #Sets can be used to perform mathematical set operations like union, intersection, symmetric difference etc. #Accessing Set : You cannot access items in a set by referring to an index, since sets are unordered and the items have NO INDEX. dataScientist = {'Python', 'R', 'SQL', 'Git', 'Tableau', 'SAS'} dataEngineer = {'Python', 'Java', 'Scala', 'Git', 'SQL', 'Hadoop'} print("------------") print(dataScientist) print(dataEngineer) print("------------") #union of sets dataScientist and dataScientist print(dataScientist.union(dataEngineer)) print(dataScientist|dataEngineer) print("------------") #intersection of sets dataScientist and dataEngineer print(dataScientist.intersection(dataEngineer)) print(dataScientist&dataEngineer) print("------------") #difference of sets dataScientist and dataEngineer print(dataScientist-dataEngineer) print(dataScientist.difference(dataEngineer)) print("------------") #difference of sets dataEngineer and dataScientist print(dataEngineer-dataScientist) print(dataEngineer.difference(dataScientist)) print("------------") #symmetric difference of dataScientist and dataEngineer print(dataScientist.symmetric_difference(dataEngineer)) print(dataScientist^dataEngineer) print("------------") #set is mutable. does it allow adding elements to the set ? my_set = {1,2.5,3,"hello world"} my_set.add(12) print(my_set) #set are unordered collection, indexing has no meaning #You cannot access items in a set by referring to an index, since sets are unordered the items has no index. dataScientist[1]
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,802
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/simpleInheritance.py
class human: def __init__(self, name, gender='female'): self.name = name self.gender = gender def greet(self, message): self.message = message print(self.message, self.name) class man(human): def __init__(self, name, age, message): super().__init__(name, 'male') self.age = age self.greet(message) # self.age = input("Enter Age:") def printDetails(self): print(self.message, self.name, self.age, self.gender) person1 = man("Abhi", 28, "Hello") person1.printDetails()
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,803
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/AccessModifiers/private.py
# By default all member variables and methods are pubic # if you want make a method or variable private, use __ before the name #PRIVATE : By declaring your data member private you mean, that nobody should be able to access it from outside the class #This feature turns every member name prefixed with at least two underscores and suffixed with at most one underscore into _<className><memberName> class Jar: def __init__(self): self.__content = None # private variable def fill(self, content): self.__content = content def empty(self): print('empty the jar...') self.__content = None myJar = Jar() myJar.fill('sugar') # If you try accessing __content from outside, you'll get an error # print(myJar.__content)
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,804
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/ExceptionHandling/customExceptions.py
# CUSTOM Exception design class ErrorInCode(Exception): def __init__(self, data): self.data = data def __str__(self): return repr(self.data) try: a = int(input('Enter a number:')) if a <= 0: raise ErrorInCode(2000) except ErrorInCode as ae: print("Received Error:", ae.data) except Exception as e: print(e) finally: print('Finally')
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,805
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py
class AudiCar: def __init__(self): self.models = ['q7', 'a8', 'a3', '343'] def out_models(self): print("Existing models are: ") for model in self.models: print(model) return "" class AudiSubDealers: def __init__(self): self.dealers = ['1', '2', '3', '4'] def out_dealers(self): print("Existing dealers are: ") for dealer in self.dealers: print("Dealer" + dealer)
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,806
sanneabhilash/python_learning
refs/heads/master
/PracticePrograms/regExForPassword.py
import re pattern = "^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$" password = input("Enter string to test: ") result = re.findall(pattern, password) if result: print("Valid password") else: print("Password not valid")
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,807
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/datatypes.py
# Everything is an object in python i = 5 j = 6.5 greeting = "Hello World" myflag = True print(i, j, greeting, myflag) print('-------------Continue-------------') # Pring Data type of the variables print(type(i)) print(type(j)) print(type(greeting)) print(type(myflag)) print('-------------Continue-------------') # Print address of the variables print(id(i)) print(id(j)) print(id(greeting)) print(id(myflag)) print('-------------Continue-------------') # Analyze address locations for immutable data types k = 10 l = 10 m = 10.5 n = 10.5 print(id(k)) # Prints same address for both integers print(id(l)) print(id(m)) # Prints same address for both floats print(id(n)) l = 15 # Change value to see address change n = 11.9 print(id(k)) print(id(l)) print(id(m)) print(id(n)) print('-------------Continue-------------')
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,808
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/Operators/assignment.py
i = 10 j = 20 k = j + 1 # k is assigned the value of j # c += a is equivalent to c = c + a m = 5 m += j print('Add AND ', m) # c -= a is equivalent to c = c - a m = 5 m -= j print('Subtract AND ', m) # c *= a is equivalent to c = c * a m = 5 m *= j print('Multiply AND ', m) # c /= a is equivalent to c = c / a. c /= a is equivalent to c = c / a m = 5 m /= j print('Divide AND ', m) # c %= a is equivalent to c = c % a m = 5 m %= j print('Modulus AND ', m) # c **= a is equivalent to c = c ** a m = 5 m **= j print('Exponent AND ', m) # c //= a is equivalent to c = c // a m = 5 m //= j print('Floor Division AND ', m)
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,809
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/Singleton_Class.py
# In object-oriented programming, a singleton class is a class that can have only one object (an instance of the #class) at a time. After first time, if we try to instantiate the Singleton class, the class should raise an #exception or the new variable should also point to the first instance created. class Singleton: __single_instance = None def __init__(self): if (Singleton.__single_instance == None): print("creating singleton instance..\n") Singleton.__single_instance = self; else: raise Exception("This class is a singleton! more than one instance cannot be created for singleton class..") # creating singleton instance the very first time s = Singleton() # an exception will be thrown when you try to create more than once instance for an Singleton class s1 = Singleton()
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,810
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/iterators_loops.py
# For loop print('For Loop Execution') for i in range(0, 10): print(i) print('For Loop Execution2') for i in range(10): print(i * 10) # while iteration print('while Loop Execution') j = 10 i = 0 while j > i: print(1 + i) i += 1
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,811
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/Oops_Intro.py
Class: A class is a collection of objects which have common properties.A class is a template or blueprint from which objects are created.It is a logical entity.It can't be physical. A class in Python can contain: Fields, Methods & Constructors Object: object is one of instances of the class . which can perform the functionalities which are defined in the class.An entity that has state and behavior is known as an object e.g.chair, bike, marker, pen, table, car etc.An object can be physical or logical (tangible and intangible). self: self represents the instance of the class . "self" keyword helps to access the attributes and methods of the class in python. __init__: "__init__" is a reserved method in python classes.It is known as a constructor in object oriented concepts.This method called when an object is created from the class . __init__ method allow the class to initialize the attributes of a class.__init__ method receives parameters and assigns fields to the new class instance. class bankAccount: def __init__(self, custId, custName, acctId, balance, acctType, creditLine): self.custName = custName self.custId = custId self.acctId = acctId self.acctType = acctType self.balance = balance self.creditLine = creditLine def deposit(self, depositAmount): self.balance += depositAmount print(self.balance) def withdraw(self, withdrawAmount): print("Amount requested for withdrawal:", withdrawAmount) if (self.balance + self.creditLine >= withdrawAmount): self.balance = self.balance - withdrawAmount print("Total Balance After Withdrawal:", self.balance) else: print( "Insufficient funds in your account and it surpassed the credit line limit,please check your account balance") def accountStatement(self): print("Customer Name:", self.custName) print("Customer Id:", self.custId) print("Account Id:", self.acctId) print("Account Type:", self.acctType) print("Account Balance:", self.balance) # end of class Account # main program. create different types of accounts saving and checking for customer "Vijay" with cust_id=1234 savingAccount = bankAccount(1234, "John", 23423245678, 100000, "SAVING", 50000) savingAccount.accountStatement() savingAccount.withdraw(10000) checkingAccount = bankAccount(1234, "John", 3695287421, 200000, "CHECKING", 50000) checkingAccount.accountStatement() checkingAccount.withdraw(15000) # we have created two different types of account objects with the same class. # while creating the saving account object we passed arguments (1234,"John",23423245678,100000,"SAVING",50000 ) these arguments will pass to #"__init__" method to initialize the object. # while creating the checking account object we passed arguments (1234,"John",3695287421,200000,"CHECKING",50000)these arguments will pass to #"__init__" method to initialize the object. # Keyword "self" represents the instance of the class. It binds the attributes with the given arguments. # Keyword "self" in class is to access the methods and attributes
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,812
sanneabhilash/python_learning
refs/heads/master
/PracticePrograms/modules_import_weather_data/circus.py
import PracticePrograms.modules_import_weather_data.weather as weather def main(): weather.current_weather() main()
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,813
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/Operators/arithmetic.py
i=9; # Declaring and initializing integer variable i, j j=8 print(i+j) # Print addition of two numbers print(i-j) #substraction print(i*j) #multiplication print(i/j) #divivision print(i%j) #Modulus print(i//j) #floor div print(i**j) # power or Exponent
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,814
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/polymorphism_method_overriding.py
class Animal: def whoAmI(self): print("I am Animal") def eat(self): print("Animal is eating") @staticmethod def walk(): print('Animal is walking') class Dog(Animal): def __init__(self): print("Dog created") # Method overriding def whoAmI(self): print("I am Dog") # dog extending base class functionality def bark(self): print("Bow Bow!!") class Cat(Animal): def __init__(self): print("Cat Created") # Method overriding def whoAmI(self): print("I am Cat") # cat extending base class functionality def bark(self): print("Meow Meow!!") # End of class Cat # polymorphism is dynamic binding technique def func(obj): obj.walk() obj.eat() print('-------------------------------------') a = Animal() d = Dog() c = Cat() print('-------------------------------------') a.whoAmI() d.whoAmI() c.whoAmI() print('-------------------------------------') a.eat() d.eat() c.eat() print('-------------------------------------') a.walk() d.walk() c.walk() print('-------------------------------------') func(a) func(d) func(c)
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,815
sanneabhilash/python_learning
refs/heads/master
/PracticePrograms/swapNumbersLambda.py
from copy import copy swapper = lambda l, m: (m, l) x = 10 y = 11 print(x, y) x, y = swapper(x, y) print(x, y)
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,816
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/strings.py
# A string is a list of characters in order # In Python String is immutable # creating a string s1 = "hi," s2 = "how are you doing?" print(s1) print(s2) # accessing a string using index print(s1[0]) print(s2[0]) # slice a string print(s1[0:3]) print(s2[0:3]) # string is immutable, str object does not support item deletion del s1[3] # string is immutable, str object does not support item modification s1[3] = 'a' # concatenate strings s = s1 + ' ' + s2 print(s) # length of a string print(len(s)) # iterate a string for i in s1: print(i) for i in s1 + s2: print(i) # assignment : string palindrome : write a program to check whether a given string is palindrome or not? # program for string reverse s = "hello world" reverse_s = "" for i in s: reverse_s = i + reverse_s print("--------------") print(reverse_s) print("--------------") # reverse a string s = "hello world" for i in reversed(s): print(i) print("--------------") ##reverse of string using pop() method s = "hello world" s_list = list(s) i = len(s_list) while i > 0: print(s_list.pop()) i = i - 1 # convert string to list s = "hello world" print(list(s)) # string comparison s1 = "hello" s2 = "hello" if (s1 == s2): print("s1==s2") else: print("s1!=s2") # sort words in a string s = "hello buddy how are you doing" words = s.split(" ") for word in sorted(words): print(word) # string join() # Create a single string from all the elements in list greetings = ["Hello", "World", "My Name Is John"] print(" ".join(greetings)) # string split() # split() method returns a list of strings after breaking the given string by the specified separator. text = 'hello techie world' # splits at space print(text.split()) word = 'hello,techie,world' # splits at ',' print(word.split(', ')) word = 'hello:techie:world' # splitting at ':' print(word.split(':'))
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,817
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/importing_modules.py
# import math module import math print("Floor of 3.4 :", math.floor(3.4)) print("e value:", math.e) print("inf:", math.inf) print("value of pi:", math.pi) print("Not a number:", math.nan) print("tau value:", math.tau)
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,818
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/modules_and_packages/math_module.py
############################################################# # PYTHON MATH MODULE import math # square root(sqrt) function in math module print(math.sqrt(36)) # pi function contained in math module print(math.pi) # Sine of 2 radians print(math.sin(2)) # Cosine of 0.5 radians print(math.cos(0.5)) # Tangent of 0.23 radians print(math.tan(0.23)) # ceiling value print(math.ceil(5.5667)) # floor value print(math.floor(6.879)) # power function print(math.pow(2, 4)) # factorial(5)=1 * 2 * 3 * 4 *5 = 120 print(math.factorial(5)) # logarithm of a given number print(math.log(10)) # base-10 logarithm of a given number print(math.log10(10)) ############################################################# # PYTHON RANDOM MODULE import random # generate random integer between specified integers print(random.randint(0, 10)) # generate random floating point number between 0.0 and 1.0 print(random.random()) # generate random number between 0 and 5 print(random.random() * 5) num_list = [2, 3.5, "hello world", [12, 36]] # choose random element from the list print(random.choice(num_list)) # randomly shuffle the list random.shuffle(num_list) print(num_list) # randomly selected element from the range created by the start, stop and step arguments. # The value of start is 0 by default. Similarly, the value of step is 1 by default. print(random.randrange(1, 10)) print(random.randrange(1, 10, 2)) ############################################################# # PYTHON DATE AND TIME MODULES import datetime # get current date and time currentTime = datetime.datetime.now() print(currentTime) # get current date in YYYY-MM-DD format today = datetime.date.today() print(today) # get current date in format DD-MM-YYYY today = datetime.date.today().strftime("%d-%m-%Y") print(today) # get current time currentTime = datetime.datetime.now().time() print(currentTime) # get date from timestamp from datetime import date timestamp = date.fromtimestamp(1326244364) print("Date =", timestamp) # get current(today) month, day and year from datetime import date # date object of today's date today = date.today() print("Current year:", today.year) print("Current month:", today.month) # python date time object from datetime import datetime # datetime(year, month, day) a = datetime(2018, 11, 28) print(a) # time object to represent time from datetime import time # time(hour = 0, minute = 0, second = 0) a = time() print("a =", a) # time(hour, minute and second) b = time(11, 34, 56) print("b =", b) # time(hour, minute and second) c = time(hour=11, minute=34, second=56) print("c =", c) # time(hour, minute, second, microsecond) d = time(11, 34, 56, 234566) print("d =", d) # datetime(year, month, day, hour, minute, second, microsecond) b = datetime(2017, 11, 28, 23, 55, 59, 342380) print(b) print("Current day:", today.day) # datetime.timedelta # A timedelta object represents the difference between two dates or times. # Difference between two dates and times from datetime import datetime, date t1 = date(year=2018, month=7, day=12) t2 = date(year=2017, month=12, day=23) t3 = t1 - t2 print("t3 =", t3) t4 = datetime(year=2018, month=7, day=12, hour=7, minute=9, second=33) t5 = datetime(year=2019, month=6, day=10, hour=5, minute=55, second=13) t6 = t4 - t5 print("t6 =", t6) print("type of t3 =", type(t3)) print("type of t6 =", type(t6)) #############################################################
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,819
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/modules_and_packages/importSinglePackage.py
# import Audi module from cars package aliased as car import Concepts_with_examples.modules_and_packages.carsPackage.Audi as Car car1 = Car.AudiCar() print(car1.out_models()) dealer1 = Car.AudiSubDealers() print(dealer1.out_dealers())
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,820
sanneabhilash/python_learning
refs/heads/master
/PracticePrograms/bank_account_without_inheritance.py
# Without inheritance class BankAccount: def __init__(self, custId, custName, custPhone, custEmail, accType, accBal, accNumber): self.id = custId self.name = custName self.phone = custPhone self.email = custEmail self.accType = accType self.bal = accBal self.accNum = accNumber def balanceEnquiry(self): print("Customer Id: ", self.id) print("Customer name: ", self.name) print("Customer phone: ", self.phone) print("Customer email: ", self.email) print("Customer accType: ", self.accType) print("Customer bal: ", self.bal) print("Customer accNum: ", self.accNum) def deposit(self, amount): self.bal = self.bal + amount print("New updated balance is:", self.bal) def withdraw(self, amount): if self.bal > amount: self.bal = self.bal - amount; print("Updated balance amount is: ", self.bal) else: print('Insufficient Balance:', self.bal) def savingsAccount(bankAccount): print("Rate of interest : 6.8%") print("Daily deposit amount limit: 100000/-") print("Daily withdrawal amount limit: 20000/-") print("Minimum balance: 3000/-") def currentAccount(bankAccount): print("Rate of interest : 0.0%") print("Daily deposit amount limit: No Limit") print("Daily withdrawal amount limit: No Limit") print("Minimum balance: 100000/-") # custId, custName, custPhone, custEmail, accType, accBal, accNumber cust1 = BankAccount(1001, 'Abhilash', 920930929, 'abhi@inno,com', 'saving', 10000, 13898298398) cust1 = BankAccount(1002, 'Sanne', 920930928, 'san@inno,com', 'current', 10000, 13898298398) cust1.balanceEnquiry() cust1.currentAccount()
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,821
sanneabhilash/python_learning
refs/heads/master
/PracticePrograms/string_reverse.py
# Without recursion def reverse(greetings): rev = '' for i in greetings: rev = i + rev return rev # end of function reverse # Reverse String using Recursion def rev_string(mystring): if len(mystring) == 0: return mystring else: return rev_string(mystring[1::]) + mystring[0] print('Hello') print(rev_string('Hello')) print(reverse('Hello')) print('---------------------------------------------') string = "Hello" # Print string in normal order for i in range(len(string)): print(string[i], end="") print() # Print string in reverse order using for loop for i in range(1, len(string) + 1): print(string[-i], end="") print() # for loop using index rev = "" for i in string: rev = rev + i print(rev) # Reverse using simple for loop using index and temp var rev = "" for i in string: rev = i + rev print(rev) # Pythonic code to reverse a string print(string[::-1])
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,822
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/tuples.py
# Tuple is an ordered sequence of items same as list.The only difference is that tuples are immutable. # Tuples once created cannot be modified. Tuples are immutable. my_tuple = ("apples", "bananas", "oranges", "kiwis") # accessing tuple using index print(my_tuple[0]) print(my_tuple[3]) # slicing tuple print(my_tuple[1:4]) print(my_tuple[-2:]) print(my_tuple[:-2]) print("--------------") # iterating over tuple for item in my_tuple: print(item) print("--------------") # check if item exists if "apples" in my_tuple: print("Yes") print("--------------") # tuple is immutable hence it will throw an error when you try to modify an element in a tuple or delete an item in a tuple my_tuple[0] = 'ambrosia' # tuple is immutable hence it will throw an error when you try to modify an element in a tuple or delete an item in a tuple del my_tuple[0] # tuple destructor del my_tuple my_tuple = ("apples", "bananas", "oranges", "kiwis") print("--------------") # reverse tuple print(my_tuple[::-1]) print("--------------") # sort tuple print(sorted(my_tuple)) print("--------------") # convert a list into tuple my_list = ['apples', 'bananas', 'kiwis', 'oranges'] my_tuple = tuple(my_list) print(type(my_tuple)) print(my_tuple) print("--------------") # concatenate tuples my_tuple1 = ("apples", "bananas") my_tuple2 = ("oranges", "kiwis") print(my_tuple1 + my_tuple2) print("--------------") # convert tuple to an dictionary my_tuple = (('a', "apple"), ('b', "banana"), ('c', "cat"), ('d', "dog")) dict1 = dict(i for i in my_tuple) print(dict1) print("--------------") # convert a tuple to an string test = ("apple", "banana", "orange", "kiwi") strtest = ','.join(test) print(strtest) print("--------------") # tuple index method test = ("apple", "banana", "orange", "kiwi") print(test.index("orange"))
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,823
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/ExceptionHandling/exceptionHandling.py
""" Python has 60+ types of exceptions. FileNotFoundError - File specified does not exist IndexError - Index out of bound KeyError - Key doesn't exist NameError - Variable name doesn't exist in local or global scope ValueError - Value is wrong type """ # Try and except allows to exscape from crash num1 = 10 num2 = 0 try: # your program goes here a = num1 / num2 print("Try Block: ", a) except ZeroDivisionError as e: print("Error occurred: ", e) print(type(e)) except (FileNotFoundError, ValueError) as e: print("Handling multiple types of exceptions in single statement") except Exception as e: print("General Exception:", e) finally: print("Finally block")
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,824
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/ExceptionHandling/Intro.py
############################################################## # RAISE EXCEPTION try: a = int(input("Enter a?")) b = int(input("Enter b?")) if b is 0: raise ArithmeticError; else: print("a/b = ", a / b) except ArithmeticError: print("The value of b can't be 0") ############################################################## # CUSTOM EXCEPTION DESIGN # Custom exception class ErrorInCode designed below is a subclass of Exception class ErrorInCode(Exception): def __init__(self, data): self.data = data def __str__(self): return repr(self.data) try: a = int(input("Enter a?")) b = int(input("Enter b?")) if b is 0: raise ErrorInCode(2000) except ErrorInCode as ae: print("Received error:", ae.data) ##############################################################
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,825
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/lambdas/Intro.py
#A lambda in Python is a single expression anonymous function often used as inline function. #A lambda form #in python does not have statements as it is used to make new function object and then return them at run time. i=8 j=4 #function to add two variables def add(x,y): return x+y result=add(i,j) print(result) #function to multiply two variables def mult(x,y): return x*y result=mult(i,j) print(result) #function to divide two variables def div(x,y): return x/y result=div(i,j) print(result) #lambda function to add two variables add_l=lambda x,y: y+x result =add_l(i,j) print("lambda function to add ",i,"and", j, "result:",result) #lambda function to multiply two variables mult_l=lambda x,y: x*y result =mult_l(i,j) print("lambda function to multiply ",i,"and",j, "result:",result) #lambda function to concatenate two strings greetings1="hello" greetings2="world" concat_l=lambda x,y: x+" "+y result=concat_l(greetings1,greetings2) print("lambda function to concatenate ",greetings1,"and",greetings2,"result:",result) #function to determine max of two numbers def max(x,y): if x>y: return x else: return y max(10,20) #function to determine min of two numbers def min(x,y): if x<y: return x else: return y min(10,20) #lambda function to determine min of two numbers i=2 j=3 min = lambda x,y: x if x < y else y res=min(i,j) print("lambda function for min of ",i,"and",j, "result:", res) #lambda function to determine max of two numbers max = lambda x,y: x if x > y else y res=max(i,j) print("lambda function for max of ",i,"and",j, "result:", res) #LAMBDA FUNCTIONS : MAP, REDUCE AND FILTER. WHEN TO USE WHAT ? #The rule of thumb you use to determine which method you should use is as follows: #If you already have a list of values and you want to do the exact same operation on each of the elements in the array and return the same amount of #items in the list, in these type of situations it is better to use the map method. If you already have list of values but you only want to have items in the #array that match certain criteria, in these type of situations it is better to use # filter method. If you already have list of values, but you want to use #the values in that list to create something completely new, in these type of situations it is better to use the reduce method. #map() function takes in lambda function and a list. #program with map function : a new list is returned which contains all the lambda modified items my_list=[1,2,3,4,5,6] new_list=list(map(lambda x: (x**2),my_list)) print("lambda map function :",my_list, "square of elements :",new_list) #filter out all the elements of a sequence #Program to filter out only the even items from a list my_list=[1,2,3,4,5,6] new_list=list(filter(lambda x: (x%2==0),my_list)) print("lambda filter function :",my_list,"filter to return even elements :" ,new_list) #reduce() function takes in a function and a list as argument. #new reduced result is returned from functools import reduce my_list=[1,2,3,4] sum=reduce((lambda x,y :x+y),my_list) print("lambda reduce function :",my_list,"sum of elements :",sum) #reduce() function takes in a function and a list as argument. #new reduced result is returned from functools import reduce my_list=[1,2,3,4] mul=reduce((lambda x,y :x*y),my_list) print("lambda reduce function :",my_list,"multiply all elements :",mul)
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,826
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/lambdas/reduce.py
# reduce() function takes in a function and a list as argument # new reduced result is returned from functools import reduce mylist = [1, 3, 5, 6, 7] mul = reduce((lambda x, y: x * y), mylist) # returns product of all elements in mylist print(mul) print(type(mul))
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}
12,827
sanneabhilash/python_learning
refs/heads/master
/Concepts_with_examples/lambdas/filter.py
# Filter out all elements of a sequence mylist = [1, 3, 4] mylist = list(filter(lambda x: (x > 2), mylist)) print(mylist)
{"/PracticePrograms/modules_import_weather_data/circus.py": ["/PracticePrograms/modules_import_weather_data/weather.py"], "/Concepts_with_examples/modules_and_packages/importSinglePackage.py": ["/Concepts_with_examples/modules_and_packages/carsPackage/Audi.py"]}