From f2dbf5a14544b413502bc5a2b29e2c19829ccc6b Mon Sep 17 00:00:00 2001 From: Svetorus Date: Mon, 8 Oct 2018 16:29:20 +0300 Subject: [PATCH 01/19] =?UTF-8?q?=D0=9D=D0=B0=D0=BF=D0=B8=D1=81=D0=B0?= =?UTF-8?q?=D0=BB=20Hello=20world=20=D0=BD=D0=B0=20=D0=BF=D0=B8=D1=82?= =?UTF-8?q?=D0=BE=D0=BD=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Hello world.html | 1 + 1 file changed, 1 insertion(+) create mode 100644 Hello world.html diff --git a/Hello world.html b/Hello world.html new file mode 100644 index 0000000..e551f1b --- /dev/null +++ b/Hello world.html @@ -0,0 +1 @@ +print("Hello world") \ No newline at end of file From 08f20a127f885126da5f26f97f3deb1d5503571b Mon Sep 17 00:00:00 2001 From: Svetorus Date: Mon, 15 Oct 2018 15:00:26 +0300 Subject: [PATCH 02/19] =?UTF-8?q?=D0=92=D1=8B=D0=BF=D0=BE=D0=BB=D0=BD?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=B4=D0=BE=D0=BC=D0=B0=D1=88=D0=BD=D0=B5=D0=B5?= =?UTF-8?q?=20=D0=B7=D0=B0=D0=B4=D0=B0=D0=BD=D0=B8=D0=B5.=20=D0=BD=D0=B5?= =?UTF-8?q?=20=D1=81=D0=BE=D0=B2=D1=81=D0=B5=D0=BC=20=D0=BF=D0=BE=D0=BD?= =?UTF-8?q?=D1=8F=D0=BB=20=D0=B5=D0=B3=D0=BE.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hard.txt | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 hard.txt diff --git a/hard.txt b/hard.txt new file mode 100644 index 0000000..b860901 --- /dev/null +++ b/hard.txt @@ -0,0 +1,20 @@ +# -1: +# : +# : a == a**2 +# : True +# : a == a*2 +# : True +# : a > 999999 +# : True + +# : a, +# , ? + +# : ;) + +a = math.inf + +if __name__ == "__main__": + print(a == a ** 2) + print(a == a * 2) + print(a > 999999) \ No newline at end of file From 459d1d24ae946156f28d69de73f0b6d1a68fe6a4 Mon Sep 17 00:00:00 2001 From: Svetorus Date: Mon, 15 Oct 2018 15:06:05 +0300 Subject: [PATCH 03/19] =?UTF-8?q?=D0=94=D1=83=D0=BC=D0=B0=D1=8E,=20=D1=82?= =?UTF-8?q?=D1=83=D1=82=20=D0=B3=D0=BB=D0=B0=D0=B2=D0=BD=D0=BE=D0=B5=20?= =?UTF-8?q?=D0=BF=D0=BE=D0=BD=D1=8F=D1=82=D1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- easy.txt | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 easy.txt diff --git a/easy.txt b/easy.txt new file mode 100644 index 0000000..eab5ea2 --- /dev/null +++ b/easy.txt @@ -0,0 +1,40 @@ +# -1: , +# # ... + +name = input(' ') +i = 0 +while i < len(name): + print(name[i]) + i += 1 + + + +# -2: . +# . . +# : +# * +# +# : +# print("a = ", b, "b = ", a) - ! + +a = input(" : ") +b = input(" : ") +a, b = b, a +print(" : ", a) +print(" : ", b) + + + + + +# -3: . +# 18 , : " ", +# ", 18 " + +print(", !") +answer = input(" : ") + +if answer >= '18': + print(" !") +elif answer < "18": + print(" 18 !") From 726d56e6ba13bf95f9f98aefb88d9b990f87201e Mon Sep 17 00:00:00 2001 From: Svetorus Date: Mon, 15 Oct 2018 15:06:18 +0300 Subject: [PATCH 04/19] =?UTF-8?q?=D0=A1=D0=B4=D0=B5=D0=BB=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- normal.txt | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 normal.txt diff --git a/normal.txt b/normal.txt new file mode 100644 index 0000000..7cbf4cb --- /dev/null +++ b/normal.txt @@ -0,0 +1,64 @@ +# -1: , . +# , x = 58375. +# , .. 8. +# , . +# . +# : +# * while; +# * for. + +number = input(' ') +print(max(number)) + + + +# -2: . +# . . +# , . +# : +# * ; +# * Python. + +a = input(" : ") +b = input(" : ") +a, b = b, a +print(" : ", a) +print(" : ", b) + + +# -3: , +# ax2 + + = 0. +# . +# sqrt() math: +# +# .sqrt(4) - 4 + +while True: + a = int(input(" a: ")) + if a == 0: + print(" , \ + , a.") + continue + else: + break +b = int(input(" b: ")) +c = int(input(" c: ")) + +# calculating discriminant +d = (b ** 2) - (4 * a * c) + +# calculating roots +if d < 0: + print(" .") + +elif d == 0: + x = (-b + math.sqrt(d)) / (2 * a) + print(" : ", x) + +else: + x1 = (-b + math.sqrt(d)) / (2 * a) + x2 = (-b - math.sqrt(d)) / (2 * a) + print(" : ", x1, " and", x2) + + + From 6501da959ca12473bea3189fca1d73c539d8453b Mon Sep 17 00:00:00 2001 From: Svetorus Date: Thu, 18 Oct 2018 13:38:10 +0300 Subject: [PATCH 05/19] =?UTF-8?q?=D1=83=D0=B4=D0=B0=D0=BB=D0=B8=D0=BB=20?= =?UTF-8?q?=D1=81=D1=82=D0=B0=D1=80=D0=BE=D0=B5=20=D1=80=D0=B0=D1=81=D1=88?= =?UTF-8?q?=D0=B8=D1=80=D0=B5=D0=BD=D0=B8=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- easy.txt | 40 ---------------------------------- hard.txt | 20 ----------------- normal.txt | 64 ------------------------------------------------------ 3 files changed, 124 deletions(-) delete mode 100644 easy.txt delete mode 100644 hard.txt delete mode 100644 normal.txt diff --git a/easy.txt b/easy.txt deleted file mode 100644 index eab5ea2..0000000 --- a/easy.txt +++ /dev/null @@ -1,40 +0,0 @@ -# -1: , -# # ... - -name = input(' ') -i = 0 -while i < len(name): - print(name[i]) - i += 1 - - - -# -2: . -# . . -# : -# * -# -# : -# print("a = ", b, "b = ", a) - ! - -a = input(" : ") -b = input(" : ") -a, b = b, a -print(" : ", a) -print(" : ", b) - - - - - -# -3: . -# 18 , : " ", -# ", 18 " - -print(", !") -answer = input(" : ") - -if answer >= '18': - print(" !") -elif answer < "18": - print(" 18 !") diff --git a/hard.txt b/hard.txt deleted file mode 100644 index b860901..0000000 --- a/hard.txt +++ /dev/null @@ -1,20 +0,0 @@ -# -1: -# : -# : a == a**2 -# : True -# : a == a*2 -# : True -# : a > 999999 -# : True - -# : a, -# , ? - -# : ;) - -a = math.inf - -if __name__ == "__main__": - print(a == a ** 2) - print(a == a * 2) - print(a > 999999) \ No newline at end of file diff --git a/normal.txt b/normal.txt deleted file mode 100644 index 7cbf4cb..0000000 --- a/normal.txt +++ /dev/null @@ -1,64 +0,0 @@ -# -1: , . -# , x = 58375. -# , .. 8. -# , . -# . -# : -# * while; -# * for. - -number = input(' ') -print(max(number)) - - - -# -2: . -# . . -# , . -# : -# * ; -# * Python. - -a = input(" : ") -b = input(" : ") -a, b = b, a -print(" : ", a) -print(" : ", b) - - -# -3: , -# ax2 + + = 0. -# . -# sqrt() math: -# -# .sqrt(4) - 4 - -while True: - a = int(input(" a: ")) - if a == 0: - print(" , \ - , a.") - continue - else: - break -b = int(input(" b: ")) -c = int(input(" c: ")) - -# calculating discriminant -d = (b ** 2) - (4 * a * c) - -# calculating roots -if d < 0: - print(" .") - -elif d == 0: - x = (-b + math.sqrt(d)) / (2 * a) - print(" : ", x) - -else: - x1 = (-b + math.sqrt(d)) / (2 * a) - x2 = (-b - math.sqrt(d)) / (2 * a) - print(" : ", x1, " and", x2) - - - From bc856d9e5bb782bcf3c98b17b10a8a2a3f0f6709 Mon Sep 17 00:00:00 2001 From: Svetorus Date: Thu, 18 Oct 2018 13:38:35 +0300 Subject: [PATCH 06/19] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D0=BD=D0=BE=D0=B2=D0=BE=D0=B5=20=D1=80=D0=B0=D1=81?= =?UTF-8?q?=D1=88=D0=B8=D1=80=D0=B5=D0=BD=D0=B8=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- "easy.\321\200\321\203.txt" | 40 +++++++++++++++++++++ "hard.\321\200\321\203.txt" | 20 +++++++++++ "normal.\321\200\321\203.txt" | 66 +++++++++++++++++++++++++++++++++++ 3 files changed, 126 insertions(+) create mode 100644 "easy.\321\200\321\203.txt" create mode 100644 "hard.\321\200\321\203.txt" create mode 100644 "normal.\321\200\321\203.txt" diff --git "a/easy.\321\200\321\203.txt" "b/easy.\321\200\321\203.txt" new file mode 100644 index 0000000..57d8e41 --- /dev/null +++ "b/easy.\321\200\321\203.txt" @@ -0,0 +1,40 @@ +# Задача-1: Дано произвольное целое число, вывести поочередно цифры исходного числа +# # код пишем тут... + +name = input('Введите число ') +i = 0 +while i < len(name): + print(name[i]) + i += 1 + + + +# Задача-2: Исходные значения двух переменных запросить у пользователя. +# Поменять значения переменных местами. Вывести новые значения на экран. +# Подсказка: +# * постарайтесь сделать решение через дополнительную переменную +# или через арифметические действия +# Не нужно решать задачу так: +# print("a = ", b, "b = ", a) - это неправильное решение! + +a = input("Введите первое число: ") +b = input("Введите второе число: ") +a, b = b, a +print("Первое число: ", a) +print("Второе число: ", b) + + + + + +# Задача-3: Запросите у пользователя его возраст. +# Если ему есть 18 лет, выведите: "Доступ разрешен", +# иначе "Извините, пользование данным ресурсом только с 18 лет" + +print("Привет, мил человек!") +answer = input("Введите ваш возраст: ") + +if answer >= '18': + print("Добро пожаловать!") +elif answer < "18": + print("Вам нет 18 идите спать!") diff --git "a/hard.\321\200\321\203.txt" "b/hard.\321\200\321\203.txt" new file mode 100644 index 0000000..4ec6c59 --- /dev/null +++ "b/hard.\321\200\321\203.txt" @@ -0,0 +1,20 @@ +# Задание-1: +# Ваня набрал несколько операций в интерпретаторе и получал результаты: +# Код: a == a**2 +# Результат: True +# Код: a == a*2 +# Результат: True +# Код: a > 999999 +# Результат: True + +# Вопрос: Чему была равна переменная a, +# если точно известно, что её значение не изменялось? + +# Подсказка: это значение точно есть ;) + +a = math.inf + +if __name__ == "__main__": + print(a == a ** 2) + print(a == a * 2) + print(a > 999999) \ No newline at end of file diff --git "a/normal.\321\200\321\203.txt" "b/normal.\321\200\321\203.txt" new file mode 100644 index 0000000..55ce0a6 --- /dev/null +++ "b/normal.\321\200\321\203.txt" @@ -0,0 +1,66 @@ +# coping: utf-8 + +# Задача-1: Дано произвольное целое число, вывести самую большую цифру этого числа. +# Например, дается x = 58375. +# Нужно вывести максимальную цифру в данном числе, т.е. 8. +# Подразумевается, что мы не знаем это число заранее. +# Число приходит в виде целого беззнакового. +# Подсказки: +# * постарайтесь решить задачу с применением арифметики и цикла while; +# * при желании и понимании решите задачу с применением цикла for. + +number = input('Введите число ') +print(max(number)) + + + +# Задача-2: Исходные значения двух переменных запросить у пользователя. +# Поменять значения переменных местами. Вывести новые значения на экран. +# Решите задачу, используя только две переменные. +# Подсказки: +# * постарайтесь сделать решение через действия над числами; +# * при желании и понимании воспользуйтесь синтаксисом кортежей Python. + +a = input("Введите первое число: ") +b = input("Введите второе число: ") +a, b = b, a +print("Первое число: ", a) +print("Второе число: ", b) + + +# Задача-3: Напишите программу, вычисляющую корни квадратного уравнения вида +# ax2 + ьх + с = 0. +# Коэффициенты уравнения вводятся пользователем. +# Для вычисления квадратного корня воспользуйтесь функцией sqrt() модуля math: +# импорт математике +# математика.sqrt(4) - вычисляет корень числа 4 + +while True: + a = int(input("Введите коэффициент a: ")) + if a == 0: + print("Это не будет квадратичным уравнением, \ + пожалуйста, введите другое число для коэффициента a.") + continue + else: + break +b = int(input("Введите коэффициент b: ")) +c = int(input("Введите коэффициент c: ")) + +# calculating discriminant +d = (b ** 2) - (4 * a * c) + +# calculating roots +if d < 0: + print("Это уравнение не имеет решения.") + +elif d == 0: + x = (-b + math.sqrt(d)) / (2 * a) + print("Это уравнение имеет два решения: ", x) + +else: + x1 = (-b + math.sqrt(d)) / (2 * a) + x2 = (-b - math.sqrt(d)) / (2 * a) + print("Это уравнение имеет два решения: ", x1, " and", x2) + + + From 51f6c73eca91e998170fcc4881314bdd51dacbf4 Mon Sep 17 00:00:00 2001 From: Svetorus Date: Fri, 2 Nov 2018 14:56:08 +0300 Subject: [PATCH 07/19] =?UTF-8?q?=D0=BD=D0=B5=20=D1=83=D0=B2=D0=B5=D1=80?= =?UTF-8?q?=D0=B5=D0=BD=20=D1=87=D1=82=D0=BE=20=D0=B2=D1=8B=D0=BF=D0=BE?= =?UTF-8?q?=D0=BB=D0=BD=D0=B8=D0=BB=20=D0=B2=D1=81=D0=B5=20=D0=BF=D1=80?= =?UTF-8?q?=D0=B0=D0=B2=D0=B8=D0=BB=D1=8C=D0=BD=D0=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- normal5.py | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 normal5.py diff --git a/normal5.py b/normal5.py new file mode 100644 index 0000000..8c87d84 --- /dev/null +++ b/normal5.py @@ -0,0 +1,44 @@ +# -1: +# , +# . +# , : +# 1. +# 2. +# 3. +# 4. +# 1, 3, 4 +# : " //", +# " //" + +# , +# , +# easy.py + +import os +#import easy + +quitz ='a' +while quitz != '0': + print(' - 1') + print(' - 2') + print(' - 3') + print(' - 4') + print(' - 0') + quitz = input(': ' ) + print(quitz) + if quitz == '1': + dir_name = input (' : ') + easy.change_dir(dir_name) + elif quitz == '2': + dir_name = os.getcwd() + easy.list_dir(dir_name) + elif quitz == '3': + dir_name = input(' : ') + easy.delete_dir(dir_name) + elif quitz == '4': + dir_name = input(' : ') + easy.make_dir(dir_name) + elif quitz == '0': + pass + else: + print(' ') \ No newline at end of file From c2439f21e1b7e3ed101552e7854d96436f919b5e Mon Sep 17 00:00:00 2001 From: Svetorus Date: Fri, 2 Nov 2018 14:56:44 +0300 Subject: [PATCH 08/19] =?UTF-8?q?3=20=D0=B7=D0=B0=D0=B4=D0=B0=D1=87=D0=B0?= =?UTF-8?q?=20=D0=BD=D0=B5=20=D1=80=D0=B0=D0=B7=D0=BE=D0=B1=D1=80=D0=B0?= =?UTF-8?q?=D0=BB=D1=81=D1=8F=20=D0=BF=D0=BE=D0=BB=D0=BD=D0=BE=D1=81=D1=82?= =?UTF-8?q?=D1=8C=D1=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- easy5.py | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 easy5.py diff --git a/easy5.py b/easy5.py new file mode 100644 index 0000000..77d3f9a --- /dev/null +++ b/easy5.py @@ -0,0 +1,65 @@ +# -1: +# , dir_1 - dir_9 , +# . +# , . + +import os + +path = "directory" + +def create_directories(count): + for i in range(1, count+1): + path = f"dir_{i}" + if not os.path.exists(path): + os.mkdir(path) + +def remove_directories(count): + for i in range(1, count+1): + path = f"dir_{i}" + if os.path.exists(path): + os.rmdir(path) + + +# -2: +# , . + +import os + +list = os.listdir() +for i in list: + print(i) + +# -3: +# , , . + +import shutil +import os +import sys + +def copy_file(first_file, backup_file): + shutil.copy(first_file, backup_file) + + +first_file = sys.argv[0] +backup_file = first_file + '.backup' +copy_file(first_file,backup_file) + + +def delete_dir(dir_path): + dir_path = os.path.join(os.getcwd(), dir_path) + try: + 0 + os.rmdir(dir_path) + except: + print(dir_path + ' - ') + + +def change_dir(dir_path): + try: + os.chdir(dir_path) + print(os.getcwd() + ' - ') + except: + print(dir_path + ' - ') + +# dir_path = 'C:\\Users\\ +change_dir(dir_path) \ No newline at end of file From 84f0d3bb083977989ba8e3ea3ddb126cd041a797 Mon Sep 17 00:00:00 2001 From: Svetorus Date: Tue, 6 Nov 2018 14:07:29 +0300 Subject: [PATCH 09/19] ok --- normal6.py | 100 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 normal6.py diff --git a/normal6.py b/normal6.py new file mode 100644 index 0000000..002b923 --- /dev/null +++ b/normal6.py @@ -0,0 +1,100 @@ +# -1: +# , : +# (5, 7 ..), . +# ( ). +# . +# - . +# .. 5 6, +# . + +# : +# 1. +# 2. +# ( " ..") +# 3. +# ( --> --> --> ) +# 4. +# 5. , + +class People: + def __init__(self, name, patronymic, surname): + self.name = name + self.surname = surname + self.patronymic = patronymic + + def get_full_name(self): + return self.name + ' ' + self.patronymic + ' ' + self.surname + + def get_short_name(self): + return '{} {}.{}.'.format(self.surname.title(), self.name[0].upper(), self.patronymic[0].upper()) + + +# if __name__ == '__main__': # . +# people1 = People('', '', '') +# print(people1.get_full_name()) +# print(people1.get_short_name()) + + +class Student(People): + def __init__(self, name, patronymic, surname, mom, dad, school_class): + People.__init__(self, name, patronymic, surname) + self.mom = mom + self.dad = dad + self.school_class = school_class + + +# if __name__ == '__main__': # . +# st_1 = Student('', '', '', ' ', ' ', '7') +# st_2 = Student('', '', '', ' ', ' ', '7') +# st_3 = Student('', '', '', ' ', ' ', '7') +# print(Student.all_classes(st_1)) + + +class Teacher(People): + def __init__(self, name, patronymic, surname, subject): + People.__init__(self, name, patronymic, surname) + self.subject = subject + + +class Class_rooms: + def __init__(self, class_room, teachers): + self.class_room = class_room + self.teachersdict = {t.subject: t for t in teachers} + + + +if __name__ == '__main__': # . + teachers = [Teacher('', '', '', ''), + Teacher('', '', '', ''), + Teacher('', '', '', ''), + Teacher('', '', '', ''), + Teacher('', '', '', '')] + classes = [Class_rooms('11 ', [teachers[0], teachers[1], teachers[2]]), + Class_rooms('11 ', [teachers[1], teachers[3], teachers[4]]), + Class_rooms('10 ', [teachers[3], teachers[1], teachers[0]])] + parents = [People('', '', ''), + People('', '', ''), + People('', '', ''), + People('', '', ''), + People('', '', ''), + People('', '', '')] + students = [Student('', 'C', '', parents[0], parents[1], classes[0]), + Student('', '', '', parents[2], parents[3], classes[1]), + Student('', '', '', parents[4], parents[5], classes[2])] + print(' : ') + for f in classes: + print(f.class_room) + + for f in classes: + print(', {} :'.format(f.class_room)) + for teacher in classes[0].teachersdict.values(): + print(teacher.get_full_name()) + for f in classes: + print(" {}:".format(f.class_room)) + for st in students: + print(st.get_short_name()) + + # for f in students: + # print(' {}'.format(f.school_class)) + # for teacher in classes[0].teachersdict.values(): + # print(teacher.get_full_name()) \ No newline at end of file From 975f01813cc6c6d76b3d9148b78c1656e6084142 Mon Sep 17 00:00:00 2001 From: Svetorus Date: Tue, 6 Nov 2018 14:07:33 +0300 Subject: [PATCH 10/19] ok --- easy6.py | 87 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 easy6.py diff --git a/easy6.py b/easy6.py new file mode 100644 index 0000000..c90bd1a --- /dev/null +++ b/easy6.py @@ -0,0 +1,87 @@ +# -1: -, . +# , : , . +import math + + +class Triangle: + def __init__(self, A, B, C): + # + def sideLen(dot1, dot2): + return math.sqrt((dot1[0] - dot2[0]) ** 2 + + (dot1[1] - dot2[1]) ** 2) + + self.A = A + self.B = B + self.C = C + # AB + self.AB = sideLen(self.A, self.B) + self.BC = sideLen(self.B, self.C) + self.CA = sideLen(self.C, self.A) + + # + def areaTriangle(self): + semi_perimeter = self.perimeterTriangle() / 2 + + return math.sqrt(semi_perimeter + * (semi_perimeter - self.AB) + * (semi_perimeter - self.BC) + * (semi_perimeter - self.CA)) + + # + def perimeterTriangle(self): + return self.AB + self.BC + self.CA + + # + def heightTriangle(self): + return self.areaTriangle() / (self.AB / 2) + + +treugolnik1 = Triangle((3, 2), (6, 7), (0, 12)) + +print(treugolnik1.areaTriangle()) +print(treugolnik1.heightTriangle()) +print(treugolnik1.perimeterTriangle()) + + +# -2: " ", 4- . +# : +# , ; +# : , , . + +class Trapeze: + def __init__(self, A, B, C, D): + # + def sideLen(dot1, dot2): + return math.sqrt((dot1[0] - dot2[0]) ** 2 + + (dot1[1] - dot2[1]) ** 2) + + def areaTriangle(len1, len2, len3): + semi_perimeter = (len1 + len2 + len3) / 2 + + return math.sqrt(semi_perimeter + * (semi_perimeter - len1) + * (semi_perimeter - len2) + * (semi_perimeter - len3)) + + self.A = A + self.B = B + self.C = C + self.D = D + + self.AB = sideLen(self.A, self.B) + self.BC = sideLen(self.B, self.C) + self.CD = sideLen(self.C, self.D) + self.DA = sideLen(self.D, self.A) + self.diagonal_AC = sideLen(self.C, self.A) + self.diagonal_BD = sideLen(self.B, self.D) + self.perimeter = self.AB + self.BC + self.CD + self.DA + + # 2 2 + # + self.area = areaTriangle(self.AB, self.diagonal_BD, self.DA) \ + + areaTriangle(self.diagonal_BD, self.BC, self.CD) + + def isTrapezeEqu(self): + if self.diagonal_AC == self.diagonal_BD: + return True + return False \ No newline at end of file From 31fc952a2508708cadf56573a500a7cb93052894 Mon Sep 17 00:00:00 2001 From: Svetorus Date: Fri, 9 Nov 2018 14:35:29 +0300 Subject: [PATCH 11/19] it is normal or hard) --- normal7.py | 168 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 168 insertions(+) create mode 100644 normal7.py diff --git a/normal7.py b/normal7.py new file mode 100644 index 0000000..1ffa5dd --- /dev/null +++ b/normal7.py @@ -0,0 +1,168 @@ +#!/usr/bin/python3 + +""" + + + . + + , , + () . + + 90 ( 1 90). + + 3 9 . 5 , + . . : + +-------------------------- + 9 43 62 74 90 +2 27 75 78 82 + 41 56 63 76 86 +-------------------------- +""" + +import random +import sys + + +#SETUP + +ballsleft = 90 +p1 = 15 +p2 = 15 +balls = random.sample(range(90), 90) +game_set = random.sample(range(90), 30) +p1_set = random.sample(game_set, 15) +p2_set = [e for e in game_set if not e in p1_set] +p1_field = [p1_set[:5], p1_set[5:10], p1_set[10:]] +p2_field = [p2_set[:5], p2_set[5:10], p2_set[10:]] +for p1line in p1_field: + p1line.sort() + p1line.insert(random.randint(0, 4), ' ') + p1line.insert(random.randint(0, 5), ' ') + p1line.insert(random.randint(0, 6), ' ') + p1line.insert(random.randint(0, 7), ' ') +for p2line in p2_field: + p2line.sort() + p2line.insert(random.randint(0, 4), ' ') + p2line.insert(random.randint(0, 5), ' ') + p2line.insert(random.randint(0, 6), ' ') + p2line.insert(random.randint(0, 7), ' ') + + +#FUNCTIONS + +def field(p): + + if p == 0: + print('{:-^26}'.format(' ')) + for line1 in p1_field: + for n1 in line1: + print('{0:>2}'.format(n1), end=' ') + print() + print('{:-^26}\n'.format('-')) + if p == 1: + print('{:-^26}'.format(' ')) + for line2 in p2_field: + for n2 in line2: + print('{0:>2}'.format(n2), end=' ') + print() + print('{:-^26}\n'.format('-')) + + +def you_move(): + + a = input(' ? (y/n): ') + if a == 'y': + if ball in p1_set: + for l in p1_field: + try: + l.insert(l.index(ball), '><') + l.pop(l.index(ball)) + except ValueError: + continue + print('\nOK') + return 1 + else: + print('\nGAME OVER') + sys.exit() + if a == 'n': + if ball in p1_set: + print('\nGAME OVER') + sys.exit() + else: + print('\nOK') + + +def com_move(): + + if ball in p2_set: + for i in p2_field: + try: + i.insert(i.index(ball), '><') + i.pop(i.index(ball)) + except ValueError: + continue + return 1 + + +#GAME + +for ball in balls: + ballsleft -= 1 + print('\n : {} (: {})\n'.format(ball, ballsleft)) + field(0) + field(1) + if you_move() == 1: + p1 -= 1 + if com_move() == 1: + p2 -= 1 + if p1 == 0: + print('\nYOU WON') + sys.exit() + if p2 == 0: + print('\nYOU LOST') + sys.exit() + if ballsleft == 0: + print('\nGAME OVER') + sys.exit() + + +""" + 2 : . + . + + . + . + + . + "": + - . + - . + "": + - . + - . + + , . + + : + + : 70 ( 76) +------ ----- +6 7 49 57 58 + 14 26 - 78 85 +23 33 38 48 71 +-------------------------- +-- --- +7 87 - 14 11 + 16 49 55 88 77 + 15 20 - 76 - +-------------------------- + ? (y/n) + +: + -. + +: + random: http://docs.python.org/3/library/random.html + +""" \ No newline at end of file From 1aa350780f9cd3bfbfe32d0bfe9cb6c789248793 Mon Sep 17 00:00:00 2001 From: Svetorus Date: Mon, 12 Nov 2018 18:21:24 +0300 Subject: [PATCH 12/19] what --- 8les.py | 96 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 8les.py diff --git a/8les.py b/8les.py new file mode 100644 index 0000000..4f24026 --- /dev/null +++ b/8les.py @@ -0,0 +1,96 @@ +""" +== OpenWeatherMap == +OpenWeatherMap -, API + , , web- + . . + + , . + : +== APPID == + APPID. + + 2 ( ): + - APPID + - APPID, + GRAB (pip install grab) + openweathermap.org: + https://home.openweathermap.org/users/sign_up + : + https://home.openweathermap.org/users/sign_in + "" : + https://home.openweathermap.org/api_keys + + , , "app.id" + +== == + : + http://bulk.openweathermap.org/sample/city.list.json.gz + + ( ): + - + - (ulrlib) + ( gzip + , subprocess) + + . JSON-: +{"_id":707860,"name":"Hurzuf","country":"UA","coord":{"lon":34.283333,"lat":44.549999}} +{"_id":519188,"name":"Novinki","country":"RU","coord":{"lon":37.666668,"lat":55.683334}} + + +== == + id . APPID. + By city ID + Examples of API calls: + http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=b1b15e88fa797225412429c1c50c122a + : + http://api.openweathermap.org/data/2.5/weather?id=520068&units=metric&appid=b1b15e88fa797225412429c1c50c122a + : + http://api.openweathermap.org/data/2.5/group?id=524901,703448,2643743&units=metric&appid=b1b15e88fa797225412429c1c50c122a + JSON- + {"coord":{"lon":38.44,"lat":55.87}, + "weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04n"}], + "base":"cmc stations","main":{"temp":280.03,"pressure":1006,"humidity":83, + "temp_min":273.15,"temp_max":284.55},"wind":{"speed":3.08,"deg":265,"gust":7.2}, + "rain":{"3h":0.015},"clouds":{"all":76},"dt":1465156452, + "sys":{"type":3,"id":57233,"message":0.0024,"country":"RU","sunrise":1465087473, + "sunset":1465149961},"id":520068,"name":"Noginsk","cod":200} +== == + : +1. SQLite + ( ): + + id_ INTEGER PRIMARY KEY + VARCHAR(255) + DATE + INTEGER + id_ INTEGER # weather.id JSON- +2. +( , + + / ()) +3. JSON (XML) +4. + . - + . + : +- ; +- , . + XML-: + XML- : + Date: Fri, 30 Nov 2018 22:32:08 +0300 Subject: [PATCH 13/19] =?UTF-8?q?=D0=9F=D1=80=D0=BE=D0=BF=D1=83=D1=81?= =?UTF-8?q?=D0=BA=D0=B0=D0=B5=D1=82=20=D1=84=D1=83=D0=BD=D0=BA=D1=86=D0=B8?= =?UTF-8?q?=D1=8E=20=D0=BC=D0=B5=D0=BD=D1=8E=20=D0=B8=20=D0=B2=D0=B8=D0=B4?= =?UTF-8?q?=D0=B8=D1=82=20=D1=82=D0=BE=D0=BB=D1=8C=D0=BA=D0=BE=20=D1=84?= =?UTF-8?q?=D1=83=D0=BD=D0=BA=D1=86=D0=B8=D1=8E=20=D0=B4=D0=BE=D0=B1=D0=B0?= =?UTF-8?q?=D0=B2=D0=B8=D1=82=D1=8C=20=D0=BA=D0=BB=D0=B8=D0=B5=D0=BD=D1=82?= =?UTF-8?q?=D0=B0.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 3 | 127 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 127 insertions(+) create mode 100644 3 diff --git a/3 b/3 new file mode 100644 index 0000000..af8d828 --- /dev/null +++ b/3 @@ -0,0 +1,127 @@ +# # 1. создать нового клиента +# # 2. удалить старого клиента +# # 3. просмотреть список клиентов +# # 4. добавить определенному клиенту услугу +# # 5. удалить у определеного клиента услугу +# # 6. посмотреть у определенного клиента список услуг +# # фамилия имя отчество +# # возраст +# # пол +# # телефон +# # адрес +# # услуги(кредитная карта,дебетовая карта, вклад, кредит, пос кредит) +# +# # кредитная карта(грейс период(есть или нет),сумма карты, бонусная программа) +# # дебетовая карта(бонусная программа, проценты на остаток) +# # вклад(срок, сумма, процент,капитализация процентов) +# # кредит(сумма, процент, срок) +# # POS кредит(сумма, срок, процент) + +def print_menu(menu): + print('Добрый день!Выберите желаемый вариант:') + for i, key in enumerate(menu, start=1): + print(f"{i}. {key}") + + +def get_command(limit): + command = int(input("Введите команду: ")) + if 1 <= command <= limit: + return command + + +def add_client(base_customers): + name_client = input('Введите ФИО клиента: ') + if name_client not in base_customers: + base_customers[name_client] = [] + print("Клиент добавлен в базу!") + else: + print("Клиент с таким именем уже существует!") + + +def delete_client(base_customers): + name_client = input('Введите ФИО клиента: ') + if name_client in base_customers: + base_customers.pop(name_client) + print("Клиент удален из базы!") + else: + print("Клиента с таким именем не существует!") + + +def print_clients(base_customers): + print(base_customers) + + +def add_product(base_customers): + name_client = input('Введите ФИО клиента: ') + if name_client in base_customers: + print_product() + product = int(input("Выберите желаемый продукт: ")) + if product == 1: + base_customers[name_client].append("кредитная карта") + elif product == 2: + base_customers[name_client].append("дебетовая карта") + elif product == 3: + base_customers[name_client].append("вклад") + elif product == 4: + base_customers[name_client].append("кредит") + elif product == 5: + base_customers[name_client].append("POS кредит") + print("Продукт добавлен клиенту!") + else: + print("Клиента с таким именем не существует!") + + +def delete_product(base_customers): + name_client = input('Введите ФИО клиента: ') + + if name_client in base_customers: + print_product() + product = int(input("Выберите желаемый продукт: ")) + if product == 1: + product = "кредитная карта" + elif product == 2: + product = "дебетовая карта" + elif product == 3: + product = "вклад" + elif product == 4: + product = "кредит" + elif product == 5: + product = "POS кредит" + + if product in base_customers[name_client]: + base_customers[name_client].remove(product) + else: + print("У клиента не существует такого продукта!") + print("Продукт удален из списка клиента!") + else: + print("Клиента с таким именем не существует!") + + +def show_product_of_client(base_customers): + name_client = input('Введите ФИО клиента: ') + if name_client in base_customers: + client = base_customers.get(name_client, '') + print(client) + else: + print("Клиента с таким именем не существует!") + + +base_customers = dict() + +menu = { + 'Создать нового клиента': add_client(base_customers), + 'Удалить старого клиента': delete_client(base_customers), + 'Просмотреть список клиентов': print_clients(base_customers), + 'Добавить определенному клиенту услугу': add_product(base_customers), + 'Удалить у определеного клиента услугу': delete_product(base_customers), + 'Посмотреть у определенного клиента список услуг': show_product_of_client(base_customers), +} + +while True: + print_menu(menu) + command = get_command(len(menu)) + if command is not None: + key = list(menu.keys())[command - 1] + menu[key]() + else: + print("Ошибка!Такой команды нет!") From a1b56df8eb9cb0fce781714c6fded41cf37e869d Mon Sep 17 00:00:00 2001 From: Svetorus Date: Mon, 29 Jul 2019 12:27:03 +0300 Subject: [PATCH 14/19] I not sure with 5 task. --- 1hw.ipynb | 545 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 545 insertions(+) create mode 100644 1hw.ipynb diff --git a/1hw.ipynb b/1hw.ipynb new file mode 100644 index 0000000..ec5aed2 --- /dev/null +++ b/1hw.ipynb @@ -0,0 +1,545 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 162, + "metadata": {}, + "outputs": [], + "source": [ + "import pickle\n", + "import chardet\n", + "import urllib\n", + "import requests\n", + "import os" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 1. \n", + "Каждое из слов «разработка», «сокет», «декоратор» представить в строковом формате и проверить тип и содержание соответствующих переменных. Затем с помощью онлайн-конвертера преобразовать строковые представление в формат Unicode и также проверить тип и содержимое переменных." + ] + }, + { + "cell_type": "code", + "execution_count": 122, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'разработка'" + ] + }, + "execution_count": 122, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a = 'разработка'\n", + "b = 'сокет'\n", + "c = 'декоратор'\n", + "a" + ] + }, + { + "cell_type": "code", + "execution_count": 123, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(str, str, str)" + ] + }, + "execution_count": 123, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(a),type(b),type(c)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Использовал сайт онлайн-конвектор https://calcsbox.com/post/konverter-teksta-v-unikod.html" + ] + }, + { + "cell_type": "code", + "execution_count": 124, + "metadata": {}, + "outputs": [], + "source": [ + "a1 = '\\u0440\\u0430\\u0437\\u0440\\u0430\\u0431\\u043e\\u0442\\u043a\\u0430' #разработка\n", + "b1 = '\\u0441\\u043e\\u043a\\u0435\\u0442' # сокет\n", + "c1 = '\\u0434\\u0435\\u043a\\u043e\\u0440\\u0430\\u0442\\u043e\\u0440' # декоратор" + ] + }, + { + "cell_type": "code", + "execution_count": 141, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(str, str, str, 'разработка')" + ] + }, + "execution_count": 141, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(a1),type(b1),type(c1),a1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 2. \n", + "Каждое из слов «class», «function», «method» записать в байтовом типе без преобразования в последовательность кодов (не используя методы encode и decode) и определить тип, содержимое и длину соответствующих переменных." + ] + }, + { + "cell_type": "code", + "execution_count": 109, + "metadata": {}, + "outputs": [], + "source": [ + "a2 = b'class'\n", + "b2 = b'function'\n", + "c2 = b'method'" + ] + }, + { + "cell_type": "code", + "execution_count": 110, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(bytes, bytes, bytes)" + ] + }, + "execution_count": 110, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(a2),type(b2),type(c2)" + ] + }, + { + "cell_type": "code", + "execution_count": 134, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(b'class', 5)" + ] + }, + "execution_count": 134, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a2,len(a2)" + ] + }, + { + "cell_type": "code", + "execution_count": 184, + "metadata": {}, + "outputs": [], + "source": [ + "word = 'world'" + ] + }, + { + "cell_type": "code", + "execution_count": 185, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'encoding': 'ascii', 'confidence': 1.0, 'language': ''}" + ] + }, + "execution_count": 185, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "chardet.detect(a2)" + ] + }, + { + "cell_type": "code", + "execution_count": 186, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "b'\\x80\\x03X\\x05\\x00\\x00\\x00worldq\\x00.'" + ] + }, + "execution_count": 186, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "word_b=pickle.dumps(word)\n", + "word_b" + ] + }, + { + "cell_type": "code", + "execution_count": 187, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'world'" + ] + }, + "execution_count": 187, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "pickle.loads(word_b)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 3. \n", + "Определить, какие из слов «attribute», «класс», «функция», «type» невозможно записать в байтовом типе." + ] + }, + { + "cell_type": "code", + "execution_count": 47, + "metadata": {}, + "outputs": [ + { + "ename": "SyntaxError", + "evalue": "bytes can only contain ASCII literal characters. (, line 1)", + "output_type": "error", + "traceback": [ + "\u001b[1;36m File \u001b[1;32m\"\"\u001b[1;36m, line \u001b[1;32m1\u001b[0m\n\u001b[1;33m b3 = b'класс' # выдает ошибку\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m bytes can only contain ASCII literal characters.\n" + ] + } + ], + "source": [ + "b3 = b'класс' # выдает ошибку, т.е. Байтами могут быть только латинские буквы\n", + "c3 = b'функция' # выдает ошибку, т.е. Байтами могут быть только латинские буквы" + ] + }, + { + "cell_type": "code", + "execution_count": 67, + "metadata": {}, + "outputs": [], + "source": [ + "a3 = b'attribute'\n", + "d3 = b'type'" + ] + }, + { + "cell_type": "code", + "execution_count": 68, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "bytes" + ] + }, + "execution_count": 68, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(a3)" + ] + }, + { + "cell_type": "code", + "execution_count": 69, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "b'type'" + ] + }, + "execution_count": 69, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d3" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 4. \n", + "Преобразовать слова «разработка», «администрирование», «protocol», «standard» из строкового представления в байтовое и выполнить обратное преобразование (используя методы encode и decode)." + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [], + "source": [ + "a4 = ('разработка')\n", + "b4 = ('администрирование')\n", + "c4 = ('protocol')\n", + "d4 = ('standart')" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(str, str, str, str)" + ] + }, + "execution_count": 32, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(a4),type(b4),type(c4),type(d4)" + ] + }, + { + "cell_type": "code", + "execution_count": 181, + "metadata": {}, + "outputs": [], + "source": [ + "a4_bytes = a4.encode()\n", + "b4_bytes = b4.encode()\n", + "c4_bytes = c4.encode()\n", + "d4_bytes = d4.encode()" + ] + }, + { + "cell_type": "code", + "execution_count": 182, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "b'\\xd1\\x80\\xd0\\xb0\\xd0\\xb7\\xd1\\x80\\xd0\\xb0\\xd0\\xb1\\xd0\\xbe\\xd1\\x82\\xd0\\xba\\xd0\\xb0'" + ] + }, + "execution_count": 182, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a4_bytes" + ] + }, + { + "cell_type": "code", + "execution_count": 87, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(bytes, bytes, bytes, bytes)" + ] + }, + "execution_count": 87, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(a4_bytes),type(b4_bytes),type(c4_bytes),type(d4_bytes)" + ] + }, + { + "cell_type": "code", + "execution_count": 92, + "metadata": {}, + "outputs": [], + "source": [ + "a41 = a4_bytes.decode()\n", + "b41 = b4_bytes.decode()\n", + "c41 = c4_bytes.decode()\n", + "d41 = d4_bytes.decode()" + ] + }, + { + "cell_type": "code", + "execution_count": 183, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'разработка'" + ] + }, + "execution_count": 183, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a41" + ] + }, + { + "cell_type": "code", + "execution_count": 93, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(str, str, str, str)" + ] + }, + "execution_count": 93, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(a41),type(b41),type(c41),type(d41)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 5. \n", + "Выполнить пинг веб-ресурсов yandex.ru, youtube.com и преобразовать результаты из байтовового в строковый тип на кириллице." + ] + }, + { + "cell_type": "code", + "execution_count": 164, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Яндекс
Завтра похолодание
Лосиноостровский
Хозяева найдитесь.\n", + "Соседи, добрый день! \n", + "Нашли сегодня в кустах у подъезда по Магаданской 3 это чудо. Чудо абсолютно домашнее, ласковое и никого не бо
Богдан С.
5
5
  • Не показывать
  • Закрыть
\"Яндекс.Афиша\"

Концерт певицы
Аиды Гарифулиной

Билеты на Яндекс.Афише12+

Дзен

Публикации на основе ваших интересов
Яндекс.Браузерсо встроенным Дзеном
Не удалось загрузить данные
Богдан С.ЛосиноостровскийХозяева найдитесь.\n", + "Соседи, добрый день! \n", + "Нашли сегодня в кустах у подъезда по Магаданской 3 это чудо. Чудо абсолютно домашнее, ласковое и никого не боОля.БибиревоГде вы? Любители Ларисы, как бы нам достучатся до вашей Ларисы? Да просто потому что под носом у жителей района Бибирево, есть два очень печальных домval-syrovatkinНагатинский ЗатонДостали!!! \n", + "Как же задолбала эта воняющая и шумная моторизованная "забота"!!!\n", + "Всю весну, лучшие майские деньки что-то всё красили. Летом стригли бензоmane4kaf1БратеевоСегодня в парке на Городне случилось чудо! И я была тому свидетелем. В общем, бегаю я себе потихонечку с утра пораньше, ну а тут же и собачники и. ., Наталья С.СвибловоВнимание телефонные мошенники! Сегодня позвонила женщина, с номера +7 (495) 620-57-28. Представилась сотрудником МФЦ. В категоричной форме сказала, чт

Новости

Интересные места в городе

    
Свернуть
{"static":"2.2180","skins":"1.615"}
\n" + ] + } + ], + "source": [ + "r = requests.get('https://yandex.ru/')\n", + "print(r.text)" + ] + }, + { + "cell_type": "code", + "execution_count": 166, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'UTF-8'" + ] + }, + "execution_count": 166, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "r.encoding" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 6. \n", + "Создать текстовый файл test_file.txt, заполнить его тремя строками: «сетевое программирование», «сокет», «декоратор». Проверить кодировку файла по умолчанию. Принудительно открыть файл в формате Unicode и вывести его содержимое." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} From d56e4cd8608fa30da5e38a1c4da433dbb10534f2 Mon Sep 17 00:00:00 2001 From: Svetorus Date: Mon, 29 Jul 2019 12:39:25 +0300 Subject: [PATCH 15/19] Hi! I am not sure with 5 task. --- 1_hw.ipynb | 530 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 530 insertions(+) create mode 100644 1_hw.ipynb diff --git a/1_hw.ipynb b/1_hw.ipynb new file mode 100644 index 0000000..5fae3f8 --- /dev/null +++ b/1_hw.ipynb @@ -0,0 +1,530 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 162, + "metadata": {}, + "outputs": [], + "source": [ + "import pickle\n", + "import chardet\n", + "import urllib\n", + "import requests\n", + "import os" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 1. \n", + "Каждое из слов «разработка», «сокет», «декоратор» представить в строковом формате и проверить тип и содержание соответствующих переменных. Затем с помощью онлайн-конвертера преобразовать строковые представление в формат Unicode и также проверить тип и содержимое переменных." + ] + }, + { + "cell_type": "code", + "execution_count": 122, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'разработка'" + ] + }, + "execution_count": 122, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a = 'разработка'\n", + "b = 'сокет'\n", + "c = 'декоратор'\n", + "a" + ] + }, + { + "cell_type": "code", + "execution_count": 123, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(str, str, str)" + ] + }, + "execution_count": 123, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(a),type(b),type(c)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Использовал сайт онлайн-конвектор https://calcsbox.com/post/konverter-teksta-v-unikod.html" + ] + }, + { + "cell_type": "code", + "execution_count": 124, + "metadata": {}, + "outputs": [], + "source": [ + "a1 = '\\u0440\\u0430\\u0437\\u0440\\u0430\\u0431\\u043e\\u0442\\u043a\\u0430' #разработка\n", + "b1 = '\\u0441\\u043e\\u043a\\u0435\\u0442' # сокет\n", + "c1 = '\\u0434\\u0435\\u043a\\u043e\\u0440\\u0430\\u0442\\u043e\\u0440' # декоратор" + ] + }, + { + "cell_type": "code", + "execution_count": 141, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(str, str, str, 'разработка')" + ] + }, + "execution_count": 141, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(a1),type(b1),type(c1),a1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 2. \n", + "Каждое из слов «class», «function», «method» записать в байтовом типе без преобразования в последовательность кодов (не используя методы encode и decode) и определить тип, содержимое и длину соответствующих переменных." + ] + }, + { + "cell_type": "code", + "execution_count": 109, + "metadata": {}, + "outputs": [], + "source": [ + "a2 = b'class'\n", + "b2 = b'function'\n", + "c2 = b'method'" + ] + }, + { + "cell_type": "code", + "execution_count": 110, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(bytes, bytes, bytes)" + ] + }, + "execution_count": 110, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(a2),type(b2),type(c2)" + ] + }, + { + "cell_type": "code", + "execution_count": 134, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(b'class', 5)" + ] + }, + "execution_count": 134, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a2,len(a2)" + ] + }, + { + "cell_type": "code", + "execution_count": 184, + "metadata": {}, + "outputs": [], + "source": [ + "word = 'world'" + ] + }, + { + "cell_type": "code", + "execution_count": 185, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'encoding': 'ascii', 'confidence': 1.0, 'language': ''}" + ] + }, + "execution_count": 185, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "chardet.detect(a2)" + ] + }, + { + "cell_type": "code", + "execution_count": 186, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "b'\\x80\\x03X\\x05\\x00\\x00\\x00worldq\\x00.'" + ] + }, + "execution_count": 186, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "word_b=pickle.dumps(word)\n", + "word_b" + ] + }, + { + "cell_type": "code", + "execution_count": 187, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'world'" + ] + }, + "execution_count": 187, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "pickle.loads(word_b)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 3. \n", + "Определить, какие из слов «attribute», «класс», «функция», «type» невозможно записать в байтовом типе." + ] + }, + { + "cell_type": "code", + "execution_count": 47, + "metadata": {}, + "outputs": [ + { + "ename": "SyntaxError", + "evalue": "bytes can only contain ASCII literal characters. (, line 1)", + "output_type": "error", + "traceback": [ + "\u001b[1;36m File \u001b[1;32m\"\"\u001b[1;36m, line \u001b[1;32m1\u001b[0m\n\u001b[1;33m b3 = b'класс' # выдает ошибку\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m bytes can only contain ASCII literal characters.\n" + ] + } + ], + "source": [ + "b3 = b'класс' # выдает ошибку, т.е. Байтами могут быть только латинские буквы\n", + "c3 = b'функция' # выдает ошибку, т.е. Байтами могут быть только латинские буквы" + ] + }, + { + "cell_type": "code", + "execution_count": 67, + "metadata": {}, + "outputs": [], + "source": [ + "a3 = b'attribute'\n", + "d3 = b'type'" + ] + }, + { + "cell_type": "code", + "execution_count": 68, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "bytes" + ] + }, + "execution_count": 68, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(a3)" + ] + }, + { + "cell_type": "code", + "execution_count": 69, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "b'type'" + ] + }, + "execution_count": 69, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d3" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 4. \n", + "Преобразовать слова «разработка», «администрирование», «protocol», «standard» из строкового представления в байтовое и выполнить обратное преобразование (используя методы encode и decode)." + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [], + "source": [ + "a4 = ('разработка')\n", + "b4 = ('администрирование')\n", + "c4 = ('protocol')\n", + "d4 = ('standart')" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(str, str, str, str)" + ] + }, + "execution_count": 32, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(a4),type(b4),type(c4),type(d4)" + ] + }, + { + "cell_type": "code", + "execution_count": 181, + "metadata": {}, + "outputs": [], + "source": [ + "a4_bytes = a4.encode()\n", + "b4_bytes = b4.encode()\n", + "c4_bytes = c4.encode()\n", + "d4_bytes = d4.encode()" + ] + }, + { + "cell_type": "code", + "execution_count": 182, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "b'\\xd1\\x80\\xd0\\xb0\\xd0\\xb7\\xd1\\x80\\xd0\\xb0\\xd0\\xb1\\xd0\\xbe\\xd1\\x82\\xd0\\xba\\xd0\\xb0'" + ] + }, + "execution_count": 182, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a4_bytes" + ] + }, + { + "cell_type": "code", + "execution_count": 87, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(bytes, bytes, bytes, bytes)" + ] + }, + "execution_count": 87, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(a4_bytes),type(b4_bytes),type(c4_bytes),type(d4_bytes)" + ] + }, + { + "cell_type": "code", + "execution_count": 92, + "metadata": {}, + "outputs": [], + "source": [ + "a41 = a4_bytes.decode()\n", + "b41 = b4_bytes.decode()\n", + "c41 = c4_bytes.decode()\n", + "d41 = d4_bytes.decode()" + ] + }, + { + "cell_type": "code", + "execution_count": 183, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'разработка'" + ] + }, + "execution_count": 183, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a41" + ] + }, + { + "cell_type": "code", + "execution_count": 93, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(str, str, str, str)" + ] + }, + "execution_count": 93, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(a41),type(b41),type(c41),type(d41)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 5. \n", + "Выполнить пинг веб-ресурсов yandex.ru, youtube.com и преобразовать результаты из байтовового в строковый тип на кириллице." + ] + }, + { + "cell_type": "code", + "execution_count": 164, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Яндекс
Завтра похолодание
Лосиноостровский
Хозяева найдитесь.\n", + "Соседи, добрый день! \n", + "Нашли сегодня в кустах у подъезда по Магаданской 3 это чудо. Чудо абсолютно домашнее, ласковое и никого не бо
Богдан С.
5
5
  • Не показывать
  • Закрыть
\"Яндекс.Афиша\"

Концерт певицы
Аиды Гарифулиной

Билеты на Яндекс.Афише12+

Дзен

Публикации на основе ваших интересов
Яндекс.Браузерсо встроенным Дзеном
Не удалось загрузить данные
Богдан С.ЛосиноостровскийХозяева найдитесь.\n", + "Соседи, добрый день! \n", + "Нашли сегодня в кустах у подъезда по Магаданской 3 это чудо. Чудо абсолютно домашнее, ласковое и никого не боОля.БибиревоГде вы? Любители Ларисы, как бы нам достучатся до вашей Ларисы? Да просто потому что под носом у жителей района Бибирево, есть два очень печальных домval-syrovatkinНагатинский ЗатонДостали!!! \n", + "Как же задолбала эта воняющая и шумная моторизованная "забота"!!!\n", + "Всю весну, лучшие майские деньки что-то всё красили. Летом стригли бензоmane4kaf1БратеевоСегодня в парке на Городне случилось чудо! И я была тому свидетелем. В общем, бегаю я себе потихонечку с утра пораньше, ну а тут же и собачники и. ., Наталья С.СвибловоВнимание телефонные мошенники! Сегодня позвонила женщина, с номера +7 (495) 620-57-28. Представилась сотрудником МФЦ. В категоричной форме сказала, чт

Новости

Интересные места в городе

    
Свернуть
{"static":"2.2180","skins":"1.615"}
\n" + ] + } + ], + "source": [ + "r = requests.get('https://yandex.ru/')\n", + "print(r.text)" + ] + }, + { + "cell_type": "code", + "execution_count": 166, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'UTF-8'" + ] + }, + "execution_count": 166, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "r.encoding" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} From 1ed178a3e5306de52f66b375a8bc13e6f1a08b3f Mon Sep 17 00:00:00 2001 From: Svetorus Date: Thu, 1 Aug 2019 10:04:55 +0300 Subject: [PATCH 16/19] not easy task) --- 2hw.ipynb | 183 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 183 insertions(+) create mode 100644 2hw.ipynb diff --git a/2hw.ipynb b/2hw.ipynb new file mode 100644 index 0000000..68741da --- /dev/null +++ b/2hw.ipynb @@ -0,0 +1,183 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import pickle\n", + "import chardet\n", + "import json\n", + "import csv\n", + "import yaml" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 1. \n", + "Задание на закрепление знаний по модулю CSV. Написать скрипт, осуществляющий выборку определенных данных из файлов info_1.txt, info_2.txt, info_3.txt \n", + "и формирующий новый 'отчетный' файл в формате CSV.\n", + "\n", + "1.1\n", + "Создать функцию get_data(), в которой в цикле осуществляется перебор файлов с данными, их открытие и считывание данных. В этой функции из считанных данных необходимо с помощью регулярных выражений извлечь значения параметров «Изготовитель системы», «Название ОС», «Код продукта», «Тип системы». Значения каждого параметра поместить в соответствующий список. Должно получиться четыре списка — например, os_prod_list, os_name_list, os_code_list, os_type_list. В этой же функции создать главный список для хранения данных отчета — например, main_data — и поместить в него названия столбцов отчета в виде списка: «Изготовитель системы», «Название ОС», «Код продукта», «Тип системы». Значения для этих столбцов также оформить в виде списка и поместить в файл main_data (также для каждого файла);\n", + "\n", + "1.2\n", + "Создать функцию write_to_csv(), в которую передавать ссылку на CSV-файл. В этой функции реализовать получение данных через вызов функции get_data(), а также сохранение подготовленных данных в соответствующий CSV-файл;\n", + "\n", + "1.3\n", + "\n", + "Проверить работу программы через вызов функции write_to_csv()." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import re\n", + "\n", + "def splinter(row):\n", + " row = re.sub(' +', ' ', row)\n", + " return row.split(': ')[1]\n", + "\n", + "\n", + "def get_data(lines, headers):\n", + " res = []\n", + " count = 0\n", + " for header in headers:\n", + " for line in lines:\n", + " if header in line:\n", + " res.append(splinter(line))\n", + " count += 1\n", + " return res\n", + "\n", + "\n", + "def read_file_lines(filename):\n", + " with open(filename) as f:\n", + " return f.read().split('\\n')\n", + "\n", + "\n", + "def write_to_csv(filename, headers, data):\n", + " with open(filename, \"w\") as f:\n", + " f.write(\",\".join(headers) + \"\\n\")\n", + " for line in data:\n", + " f.write(\",\".join(line) + \"\\n\")\n", + "\n", + "\n", + "headers = ['Изготовитель системы', 'Название ОС', 'Код продукта', 'Тип системы']\n", + "# print(headers)\n", + "\n", + "data = []\n", + "for file in [f'info_{number}.txt' for number in range(1, 4)]:\n", + " data.append(get_data(read_file_lines(file), headers))\n", + "\n", + "write_to_csv(\"main_data.csv\", headers, data)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 2. \n", + "Задание на закрепление знаний по модулю json. Есть файл orders в формате JSON с информацией о заказах. Написать скрипт, автоматизирующий его выпонение данными.\n", + "\n", + "2.1\n", + "Создать функцию write_order_to_json(), в которую передается 5 параметров — товар (item), количество (quantity), цена (price), покупатель (buyer), дата (date). Функция должна предусматривать запись данных в виде словаря в файл orders.json. При записи данных указать величину отступа в 4 пробельных символа;\n", + "\n", + "2.2\n", + "Проверить работу программы через вызов функции write_order_to_json() с передачей в нее значений каждого параметра." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def write_order_to_json(filename):\n", + " with open(filename) as f:\n", + " data = json.loads(f.read())\n", + " while True:\n", + "\n", + "\n", + " a = int(input(\"Continue? 1/0\"))\n", + " if a == 0:\n", + " break\n", + "\n", + " d = {}\n", + "\n", + " d['item'] = input(\"Input item: \")\n", + " d['quantity'] = input(\"Input quantity: \")\n", + " d['price'] = input(\"Input price: \")\n", + " d['buyer'] = input(\"Input buyer: \")\n", + " d['date'] = input(\"Input date: \")\n", + "\n", + " data[\"orders\"].append(d)\n", + "\n", + "\n", + " with open(filename, \"w\") as f:\n", + " json.dump(data, f, sort_keys=True, indent=4)\n", + " \n", + "write_order_to_json(\"orders.json\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 3. \n", + "Задание на закрепление знаний по модулю YAML. Написать скрипт, автоматизирующий сохранение данных в файле YAML-формата.\n", + "\n", + "3.1\n", + "Подготовить данные для записи в виде словаря, в котором первому ключу соответствует список, второму — целое число, третьему — вложенный словарь, где значение каждого ключа — это целое число с юникод-символом, отсутствующим в кодировке ASCII (например, €);\n", + "\n", + "3.2\n", + "Реализовать сохранение данных в файл формата YAML — например, в файл file.yaml. При этом обеспечить стилизацию файла с помощью параметра default_flow_style, а также установить возможность работы с юникодом: allow_unicode = True;\n", + "\n", + "3.3\n", + "Реализовать считывание данных из созданного файла и проверить, совпадают ли они с исходными." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "alibra = {\"93к\": [1, 2, 3], \"54в\": 234, \"32ф\": {\"544\":\"4343\"}}\n", + "\n", + "with open('users.yaml', 'w') as f:\n", + " data = yaml.dump(alibra, f, default_flow_style=False, allow_unicode=True)\n", + "\n", + "with open('users.yaml') as f:\n", + " data = yaml.load(f, Loader=yaml.FullLoader)\n", + " print(data)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} From 6a579b39b9a69f09a1ff8d826b3450ca5163e861 Mon Sep 17 00:00:00 2001 From: Svetorus Date: Thu, 29 Aug 2019 21:04:50 +0300 Subject: [PATCH 17/19] file --- .ipynb_checkpoints/2hw-checkpoint.ipynb | 183 ++++++++ 1hw.ipynb | 545 ------------------------ f.py | 74 ++++ 3 files changed, 257 insertions(+), 545 deletions(-) create mode 100644 .ipynb_checkpoints/2hw-checkpoint.ipynb delete mode 100644 1hw.ipynb create mode 100644 f.py diff --git a/.ipynb_checkpoints/2hw-checkpoint.ipynb b/.ipynb_checkpoints/2hw-checkpoint.ipynb new file mode 100644 index 0000000..68741da --- /dev/null +++ b/.ipynb_checkpoints/2hw-checkpoint.ipynb @@ -0,0 +1,183 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import pickle\n", + "import chardet\n", + "import json\n", + "import csv\n", + "import yaml" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 1. \n", + "Задание на закрепление знаний по модулю CSV. Написать скрипт, осуществляющий выборку определенных данных из файлов info_1.txt, info_2.txt, info_3.txt \n", + "и формирующий новый 'отчетный' файл в формате CSV.\n", + "\n", + "1.1\n", + "Создать функцию get_data(), в которой в цикле осуществляется перебор файлов с данными, их открытие и считывание данных. В этой функции из считанных данных необходимо с помощью регулярных выражений извлечь значения параметров «Изготовитель системы», «Название ОС», «Код продукта», «Тип системы». Значения каждого параметра поместить в соответствующий список. Должно получиться четыре списка — например, os_prod_list, os_name_list, os_code_list, os_type_list. В этой же функции создать главный список для хранения данных отчета — например, main_data — и поместить в него названия столбцов отчета в виде списка: «Изготовитель системы», «Название ОС», «Код продукта», «Тип системы». Значения для этих столбцов также оформить в виде списка и поместить в файл main_data (также для каждого файла);\n", + "\n", + "1.2\n", + "Создать функцию write_to_csv(), в которую передавать ссылку на CSV-файл. В этой функции реализовать получение данных через вызов функции get_data(), а также сохранение подготовленных данных в соответствующий CSV-файл;\n", + "\n", + "1.3\n", + "\n", + "Проверить работу программы через вызов функции write_to_csv()." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import re\n", + "\n", + "def splinter(row):\n", + " row = re.sub(' +', ' ', row)\n", + " return row.split(': ')[1]\n", + "\n", + "\n", + "def get_data(lines, headers):\n", + " res = []\n", + " count = 0\n", + " for header in headers:\n", + " for line in lines:\n", + " if header in line:\n", + " res.append(splinter(line))\n", + " count += 1\n", + " return res\n", + "\n", + "\n", + "def read_file_lines(filename):\n", + " with open(filename) as f:\n", + " return f.read().split('\\n')\n", + "\n", + "\n", + "def write_to_csv(filename, headers, data):\n", + " with open(filename, \"w\") as f:\n", + " f.write(\",\".join(headers) + \"\\n\")\n", + " for line in data:\n", + " f.write(\",\".join(line) + \"\\n\")\n", + "\n", + "\n", + "headers = ['Изготовитель системы', 'Название ОС', 'Код продукта', 'Тип системы']\n", + "# print(headers)\n", + "\n", + "data = []\n", + "for file in [f'info_{number}.txt' for number in range(1, 4)]:\n", + " data.append(get_data(read_file_lines(file), headers))\n", + "\n", + "write_to_csv(\"main_data.csv\", headers, data)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 2. \n", + "Задание на закрепление знаний по модулю json. Есть файл orders в формате JSON с информацией о заказах. Написать скрипт, автоматизирующий его выпонение данными.\n", + "\n", + "2.1\n", + "Создать функцию write_order_to_json(), в которую передается 5 параметров — товар (item), количество (quantity), цена (price), покупатель (buyer), дата (date). Функция должна предусматривать запись данных в виде словаря в файл orders.json. При записи данных указать величину отступа в 4 пробельных символа;\n", + "\n", + "2.2\n", + "Проверить работу программы через вызов функции write_order_to_json() с передачей в нее значений каждого параметра." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def write_order_to_json(filename):\n", + " with open(filename) as f:\n", + " data = json.loads(f.read())\n", + " while True:\n", + "\n", + "\n", + " a = int(input(\"Continue? 1/0\"))\n", + " if a == 0:\n", + " break\n", + "\n", + " d = {}\n", + "\n", + " d['item'] = input(\"Input item: \")\n", + " d['quantity'] = input(\"Input quantity: \")\n", + " d['price'] = input(\"Input price: \")\n", + " d['buyer'] = input(\"Input buyer: \")\n", + " d['date'] = input(\"Input date: \")\n", + "\n", + " data[\"orders\"].append(d)\n", + "\n", + "\n", + " with open(filename, \"w\") as f:\n", + " json.dump(data, f, sort_keys=True, indent=4)\n", + " \n", + "write_order_to_json(\"orders.json\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 3. \n", + "Задание на закрепление знаний по модулю YAML. Написать скрипт, автоматизирующий сохранение данных в файле YAML-формата.\n", + "\n", + "3.1\n", + "Подготовить данные для записи в виде словаря, в котором первому ключу соответствует список, второму — целое число, третьему — вложенный словарь, где значение каждого ключа — это целое число с юникод-символом, отсутствующим в кодировке ASCII (например, €);\n", + "\n", + "3.2\n", + "Реализовать сохранение данных в файл формата YAML — например, в файл file.yaml. При этом обеспечить стилизацию файла с помощью параметра default_flow_style, а также установить возможность работы с юникодом: allow_unicode = True;\n", + "\n", + "3.3\n", + "Реализовать считывание данных из созданного файла и проверить, совпадают ли они с исходными." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "alibra = {\"93к\": [1, 2, 3], \"54в\": 234, \"32ф\": {\"544\":\"4343\"}}\n", + "\n", + "with open('users.yaml', 'w') as f:\n", + " data = yaml.dump(alibra, f, default_flow_style=False, allow_unicode=True)\n", + "\n", + "with open('users.yaml') as f:\n", + " data = yaml.load(f, Loader=yaml.FullLoader)\n", + " print(data)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/1hw.ipynb b/1hw.ipynb deleted file mode 100644 index ec5aed2..0000000 --- a/1hw.ipynb +++ /dev/null @@ -1,545 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 162, - "metadata": {}, - "outputs": [], - "source": [ - "import pickle\n", - "import chardet\n", - "import urllib\n", - "import requests\n", - "import os" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### 1. \n", - "Каждое из слов «разработка», «сокет», «декоратор» представить в строковом формате и проверить тип и содержание соответствующих переменных. Затем с помощью онлайн-конвертера преобразовать строковые представление в формат Unicode и также проверить тип и содержимое переменных." - ] - }, - { - "cell_type": "code", - "execution_count": 122, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'разработка'" - ] - }, - "execution_count": 122, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a = 'разработка'\n", - "b = 'сокет'\n", - "c = 'декоратор'\n", - "a" - ] - }, - { - "cell_type": "code", - "execution_count": 123, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(str, str, str)" - ] - }, - "execution_count": 123, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "type(a),type(b),type(c)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Использовал сайт онлайн-конвектор https://calcsbox.com/post/konverter-teksta-v-unikod.html" - ] - }, - { - "cell_type": "code", - "execution_count": 124, - "metadata": {}, - "outputs": [], - "source": [ - "a1 = '\\u0440\\u0430\\u0437\\u0440\\u0430\\u0431\\u043e\\u0442\\u043a\\u0430' #разработка\n", - "b1 = '\\u0441\\u043e\\u043a\\u0435\\u0442' # сокет\n", - "c1 = '\\u0434\\u0435\\u043a\\u043e\\u0440\\u0430\\u0442\\u043e\\u0440' # декоратор" - ] - }, - { - "cell_type": "code", - "execution_count": 141, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(str, str, str, 'разработка')" - ] - }, - "execution_count": 141, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "type(a1),type(b1),type(c1),a1" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### 2. \n", - "Каждое из слов «class», «function», «method» записать в байтовом типе без преобразования в последовательность кодов (не используя методы encode и decode) и определить тип, содержимое и длину соответствующих переменных." - ] - }, - { - "cell_type": "code", - "execution_count": 109, - "metadata": {}, - "outputs": [], - "source": [ - "a2 = b'class'\n", - "b2 = b'function'\n", - "c2 = b'method'" - ] - }, - { - "cell_type": "code", - "execution_count": 110, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(bytes, bytes, bytes)" - ] - }, - "execution_count": 110, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "type(a2),type(b2),type(c2)" - ] - }, - { - "cell_type": "code", - "execution_count": 134, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(b'class', 5)" - ] - }, - "execution_count": 134, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a2,len(a2)" - ] - }, - { - "cell_type": "code", - "execution_count": 184, - "metadata": {}, - "outputs": [], - "source": [ - "word = 'world'" - ] - }, - { - "cell_type": "code", - "execution_count": 185, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'encoding': 'ascii', 'confidence': 1.0, 'language': ''}" - ] - }, - "execution_count": 185, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "chardet.detect(a2)" - ] - }, - { - "cell_type": "code", - "execution_count": 186, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "b'\\x80\\x03X\\x05\\x00\\x00\\x00worldq\\x00.'" - ] - }, - "execution_count": 186, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "word_b=pickle.dumps(word)\n", - "word_b" - ] - }, - { - "cell_type": "code", - "execution_count": 187, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'world'" - ] - }, - "execution_count": 187, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "pickle.loads(word_b)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### 3. \n", - "Определить, какие из слов «attribute», «класс», «функция», «type» невозможно записать в байтовом типе." - ] - }, - { - "cell_type": "code", - "execution_count": 47, - "metadata": {}, - "outputs": [ - { - "ename": "SyntaxError", - "evalue": "bytes can only contain ASCII literal characters. (, line 1)", - "output_type": "error", - "traceback": [ - "\u001b[1;36m File \u001b[1;32m\"\"\u001b[1;36m, line \u001b[1;32m1\u001b[0m\n\u001b[1;33m b3 = b'класс' # выдает ошибку\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m bytes can only contain ASCII literal characters.\n" - ] - } - ], - "source": [ - "b3 = b'класс' # выдает ошибку, т.е. Байтами могут быть только латинские буквы\n", - "c3 = b'функция' # выдает ошибку, т.е. Байтами могут быть только латинские буквы" - ] - }, - { - "cell_type": "code", - "execution_count": 67, - "metadata": {}, - "outputs": [], - "source": [ - "a3 = b'attribute'\n", - "d3 = b'type'" - ] - }, - { - "cell_type": "code", - "execution_count": 68, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "bytes" - ] - }, - "execution_count": 68, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "type(a3)" - ] - }, - { - "cell_type": "code", - "execution_count": 69, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "b'type'" - ] - }, - "execution_count": 69, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "d3" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### 4. \n", - "Преобразовать слова «разработка», «администрирование», «protocol», «standard» из строкового представления в байтовое и выполнить обратное преобразование (используя методы encode и decode)." - ] - }, - { - "cell_type": "code", - "execution_count": 31, - "metadata": {}, - "outputs": [], - "source": [ - "a4 = ('разработка')\n", - "b4 = ('администрирование')\n", - "c4 = ('protocol')\n", - "d4 = ('standart')" - ] - }, - { - "cell_type": "code", - "execution_count": 32, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(str, str, str, str)" - ] - }, - "execution_count": 32, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "type(a4),type(b4),type(c4),type(d4)" - ] - }, - { - "cell_type": "code", - "execution_count": 181, - "metadata": {}, - "outputs": [], - "source": [ - "a4_bytes = a4.encode()\n", - "b4_bytes = b4.encode()\n", - "c4_bytes = c4.encode()\n", - "d4_bytes = d4.encode()" - ] - }, - { - "cell_type": "code", - "execution_count": 182, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "b'\\xd1\\x80\\xd0\\xb0\\xd0\\xb7\\xd1\\x80\\xd0\\xb0\\xd0\\xb1\\xd0\\xbe\\xd1\\x82\\xd0\\xba\\xd0\\xb0'" - ] - }, - "execution_count": 182, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a4_bytes" - ] - }, - { - "cell_type": "code", - "execution_count": 87, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(bytes, bytes, bytes, bytes)" - ] - }, - "execution_count": 87, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "type(a4_bytes),type(b4_bytes),type(c4_bytes),type(d4_bytes)" - ] - }, - { - "cell_type": "code", - "execution_count": 92, - "metadata": {}, - "outputs": [], - "source": [ - "a41 = a4_bytes.decode()\n", - "b41 = b4_bytes.decode()\n", - "c41 = c4_bytes.decode()\n", - "d41 = d4_bytes.decode()" - ] - }, - { - "cell_type": "code", - "execution_count": 183, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'разработка'" - ] - }, - "execution_count": 183, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a41" - ] - }, - { - "cell_type": "code", - "execution_count": 93, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(str, str, str, str)" - ] - }, - "execution_count": 93, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "type(a41),type(b41),type(c41),type(d41)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### 5. \n", - "Выполнить пинг веб-ресурсов yandex.ru, youtube.com и преобразовать результаты из байтовового в строковый тип на кириллице." - ] - }, - { - "cell_type": "code", - "execution_count": 164, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Яндекс
Завтра похолодание
Лосиноостровский
Хозяева найдитесь.\n", - "Соседи, добрый день! \n", - "Нашли сегодня в кустах у подъезда по Магаданской 3 это чудо. Чудо абсолютно домашнее, ласковое и никого не бо
Богдан С.
5
5
  • Не показывать
  • Закрыть
\"Яндекс.Афиша\"

Концерт певицы
Аиды Гарифулиной

Билеты на Яндекс.Афише12+

Дзен

Публикации на основе ваших интересов
Яндекс.Браузерсо встроенным Дзеном
Не удалось загрузить данные
Богдан С.ЛосиноостровскийХозяева найдитесь.\n", - "Соседи, добрый день! \n", - "Нашли сегодня в кустах у подъезда по Магаданской 3 это чудо. Чудо абсолютно домашнее, ласковое и никого не боОля.БибиревоГде вы? Любители Ларисы, как бы нам достучатся до вашей Ларисы? Да просто потому что под носом у жителей района Бибирево, есть два очень печальных домval-syrovatkinНагатинский ЗатонДостали!!! \n", - "Как же задолбала эта воняющая и шумная моторизованная "забота"!!!\n", - "Всю весну, лучшие майские деньки что-то всё красили. Летом стригли бензоmane4kaf1БратеевоСегодня в парке на Городне случилось чудо! И я была тому свидетелем. В общем, бегаю я себе потихонечку с утра пораньше, ну а тут же и собачники и. ., Наталья С.СвибловоВнимание телефонные мошенники! Сегодня позвонила женщина, с номера +7 (495) 620-57-28. Представилась сотрудником МФЦ. В категоричной форме сказала, чт

Новости

Интересные места в городе

    
Свернуть
{"static":"2.2180","skins":"1.615"}
\n" - ] - } - ], - "source": [ - "r = requests.get('https://yandex.ru/')\n", - "print(r.text)" - ] - }, - { - "cell_type": "code", - "execution_count": 166, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'UTF-8'" - ] - }, - "execution_count": 166, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "r.encoding" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### 6. \n", - "Создать текстовый файл test_file.txt, заполнить его тремя строками: «сетевое программирование», «сокет», «декоратор». Проверить кодировку файла по умолчанию. Принудительно открыть файл в формате Unicode и вывести его содержимое." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.7.3" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/f.py b/f.py new file mode 100644 index 0000000..6f16c06 --- /dev/null +++ b/f.py @@ -0,0 +1,74 @@ +# # def f(a,b,*qweqweqe, c): +# # print(a,b,qweqweqe,c ) +# # +# # f(3,4,5,6,7,8,9,0, c=54) +# +# +# # def g(*args, **kwargs): +# # print(args, kwargs) +# # +# # g(1,2,3,4, name="Andrey", surname="Pak", age="26") +# +# +# +# # def f(): +# # pass +# +# +# +# import datetime +# +# week = { +# 0: "пн", +# 1: "вт", +# 2: "ср", +# 3: "чт", +# 4: "пт", +# 5: "сб", +# 6: "вс", +# } +# +# d = datetime.date(2019, 9, 1) +# +# for i in range(100): +# num = f"{d.day}{d.month}{d.year}" +# s = sum(map(int, num)) +# while s >= 12: +# s = sum(map(int, str(s))) +# +# if s in [8, 9, 11] and week[d.weekday()] in ['вс', 'пт']: +# print(d, week[d.weekday()], s) +# d += datetime.timedelta(days=1) +# +# import sys +# +# class A: +# __slots__ = ["name", "id", "surname"] +# pass +# +# +# +# +# a = A() +# +# a.name = "Andrey" +# a.surname = "Pak" +# a.id = 1234 +# # a.qwe = 2143 +# +# # print(a.name, a.surname, a.id) +# # print(a) +# +# +# d = dict() +# +# print(sys.getsizeof(a)) + +a = ["russia", "usa", "france"] +b = ['r', 'u', 'f'] + +d = dict(zip(b,a)) + +print(d["r"]) + +print(d['u']) From 43b82742d07fa296b0a88904dd9d572b41d1740b Mon Sep 17 00:00:00 2001 From: Svetorus Date: Thu, 29 Aug 2019 21:07:38 +0300 Subject: [PATCH 18/19] del f --- .ipynb_checkpoints/1_hw-checkpoint.ipynb | 530 +++++++++++++++++++++++ f.py | 74 ---- 2 files changed, 530 insertions(+), 74 deletions(-) create mode 100644 .ipynb_checkpoints/1_hw-checkpoint.ipynb delete mode 100644 f.py diff --git a/.ipynb_checkpoints/1_hw-checkpoint.ipynb b/.ipynb_checkpoints/1_hw-checkpoint.ipynb new file mode 100644 index 0000000..5fae3f8 --- /dev/null +++ b/.ipynb_checkpoints/1_hw-checkpoint.ipynb @@ -0,0 +1,530 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 162, + "metadata": {}, + "outputs": [], + "source": [ + "import pickle\n", + "import chardet\n", + "import urllib\n", + "import requests\n", + "import os" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 1. \n", + "Каждое из слов «разработка», «сокет», «декоратор» представить в строковом формате и проверить тип и содержание соответствующих переменных. Затем с помощью онлайн-конвертера преобразовать строковые представление в формат Unicode и также проверить тип и содержимое переменных." + ] + }, + { + "cell_type": "code", + "execution_count": 122, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'разработка'" + ] + }, + "execution_count": 122, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a = 'разработка'\n", + "b = 'сокет'\n", + "c = 'декоратор'\n", + "a" + ] + }, + { + "cell_type": "code", + "execution_count": 123, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(str, str, str)" + ] + }, + "execution_count": 123, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(a),type(b),type(c)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Использовал сайт онлайн-конвектор https://calcsbox.com/post/konverter-teksta-v-unikod.html" + ] + }, + { + "cell_type": "code", + "execution_count": 124, + "metadata": {}, + "outputs": [], + "source": [ + "a1 = '\\u0440\\u0430\\u0437\\u0440\\u0430\\u0431\\u043e\\u0442\\u043a\\u0430' #разработка\n", + "b1 = '\\u0441\\u043e\\u043a\\u0435\\u0442' # сокет\n", + "c1 = '\\u0434\\u0435\\u043a\\u043e\\u0440\\u0430\\u0442\\u043e\\u0440' # декоратор" + ] + }, + { + "cell_type": "code", + "execution_count": 141, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(str, str, str, 'разработка')" + ] + }, + "execution_count": 141, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(a1),type(b1),type(c1),a1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 2. \n", + "Каждое из слов «class», «function», «method» записать в байтовом типе без преобразования в последовательность кодов (не используя методы encode и decode) и определить тип, содержимое и длину соответствующих переменных." + ] + }, + { + "cell_type": "code", + "execution_count": 109, + "metadata": {}, + "outputs": [], + "source": [ + "a2 = b'class'\n", + "b2 = b'function'\n", + "c2 = b'method'" + ] + }, + { + "cell_type": "code", + "execution_count": 110, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(bytes, bytes, bytes)" + ] + }, + "execution_count": 110, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(a2),type(b2),type(c2)" + ] + }, + { + "cell_type": "code", + "execution_count": 134, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(b'class', 5)" + ] + }, + "execution_count": 134, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a2,len(a2)" + ] + }, + { + "cell_type": "code", + "execution_count": 184, + "metadata": {}, + "outputs": [], + "source": [ + "word = 'world'" + ] + }, + { + "cell_type": "code", + "execution_count": 185, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'encoding': 'ascii', 'confidence': 1.0, 'language': ''}" + ] + }, + "execution_count": 185, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "chardet.detect(a2)" + ] + }, + { + "cell_type": "code", + "execution_count": 186, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "b'\\x80\\x03X\\x05\\x00\\x00\\x00worldq\\x00.'" + ] + }, + "execution_count": 186, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "word_b=pickle.dumps(word)\n", + "word_b" + ] + }, + { + "cell_type": "code", + "execution_count": 187, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'world'" + ] + }, + "execution_count": 187, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "pickle.loads(word_b)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 3. \n", + "Определить, какие из слов «attribute», «класс», «функция», «type» невозможно записать в байтовом типе." + ] + }, + { + "cell_type": "code", + "execution_count": 47, + "metadata": {}, + "outputs": [ + { + "ename": "SyntaxError", + "evalue": "bytes can only contain ASCII literal characters. (, line 1)", + "output_type": "error", + "traceback": [ + "\u001b[1;36m File \u001b[1;32m\"\"\u001b[1;36m, line \u001b[1;32m1\u001b[0m\n\u001b[1;33m b3 = b'класс' # выдает ошибку\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m bytes can only contain ASCII literal characters.\n" + ] + } + ], + "source": [ + "b3 = b'класс' # выдает ошибку, т.е. Байтами могут быть только латинские буквы\n", + "c3 = b'функция' # выдает ошибку, т.е. Байтами могут быть только латинские буквы" + ] + }, + { + "cell_type": "code", + "execution_count": 67, + "metadata": {}, + "outputs": [], + "source": [ + "a3 = b'attribute'\n", + "d3 = b'type'" + ] + }, + { + "cell_type": "code", + "execution_count": 68, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "bytes" + ] + }, + "execution_count": 68, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(a3)" + ] + }, + { + "cell_type": "code", + "execution_count": 69, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "b'type'" + ] + }, + "execution_count": 69, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d3" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 4. \n", + "Преобразовать слова «разработка», «администрирование», «protocol», «standard» из строкового представления в байтовое и выполнить обратное преобразование (используя методы encode и decode)." + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [], + "source": [ + "a4 = ('разработка')\n", + "b4 = ('администрирование')\n", + "c4 = ('protocol')\n", + "d4 = ('standart')" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(str, str, str, str)" + ] + }, + "execution_count": 32, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(a4),type(b4),type(c4),type(d4)" + ] + }, + { + "cell_type": "code", + "execution_count": 181, + "metadata": {}, + "outputs": [], + "source": [ + "a4_bytes = a4.encode()\n", + "b4_bytes = b4.encode()\n", + "c4_bytes = c4.encode()\n", + "d4_bytes = d4.encode()" + ] + }, + { + "cell_type": "code", + "execution_count": 182, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "b'\\xd1\\x80\\xd0\\xb0\\xd0\\xb7\\xd1\\x80\\xd0\\xb0\\xd0\\xb1\\xd0\\xbe\\xd1\\x82\\xd0\\xba\\xd0\\xb0'" + ] + }, + "execution_count": 182, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a4_bytes" + ] + }, + { + "cell_type": "code", + "execution_count": 87, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(bytes, bytes, bytes, bytes)" + ] + }, + "execution_count": 87, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(a4_bytes),type(b4_bytes),type(c4_bytes),type(d4_bytes)" + ] + }, + { + "cell_type": "code", + "execution_count": 92, + "metadata": {}, + "outputs": [], + "source": [ + "a41 = a4_bytes.decode()\n", + "b41 = b4_bytes.decode()\n", + "c41 = c4_bytes.decode()\n", + "d41 = d4_bytes.decode()" + ] + }, + { + "cell_type": "code", + "execution_count": 183, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'разработка'" + ] + }, + "execution_count": 183, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a41" + ] + }, + { + "cell_type": "code", + "execution_count": 93, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(str, str, str, str)" + ] + }, + "execution_count": 93, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(a41),type(b41),type(c41),type(d41)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### 5. \n", + "Выполнить пинг веб-ресурсов yandex.ru, youtube.com и преобразовать результаты из байтовового в строковый тип на кириллице." + ] + }, + { + "cell_type": "code", + "execution_count": 164, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Яндекс
Завтра похолодание
Лосиноостровский
Хозяева найдитесь.\n", + "Соседи, добрый день! \n", + "Нашли сегодня в кустах у подъезда по Магаданской 3 это чудо. Чудо абсолютно домашнее, ласковое и никого не бо
Богдан С.
5
5
  • Не показывать
  • Закрыть
\"Яндекс.Афиша\"

Концерт певицы
Аиды Гарифулиной

Билеты на Яндекс.Афише12+

Дзен

Публикации на основе ваших интересов
Яндекс.Браузерсо встроенным Дзеном
Не удалось загрузить данные
Богдан С.ЛосиноостровскийХозяева найдитесь.\n", + "Соседи, добрый день! \n", + "Нашли сегодня в кустах у подъезда по Магаданской 3 это чудо. Чудо абсолютно домашнее, ласковое и никого не боОля.БибиревоГде вы? Любители Ларисы, как бы нам достучатся до вашей Ларисы? Да просто потому что под носом у жителей района Бибирево, есть два очень печальных домval-syrovatkinНагатинский ЗатонДостали!!! \n", + "Как же задолбала эта воняющая и шумная моторизованная "забота"!!!\n", + "Всю весну, лучшие майские деньки что-то всё красили. Летом стригли бензоmane4kaf1БратеевоСегодня в парке на Городне случилось чудо! И я была тому свидетелем. В общем, бегаю я себе потихонечку с утра пораньше, ну а тут же и собачники и. ., Наталья С.СвибловоВнимание телефонные мошенники! Сегодня позвонила женщина, с номера +7 (495) 620-57-28. Представилась сотрудником МФЦ. В категоричной форме сказала, чт

Новости

Интересные места в городе

    
Свернуть
{"static":"2.2180","skins":"1.615"}
\n" + ] + } + ], + "source": [ + "r = requests.get('https://yandex.ru/')\n", + "print(r.text)" + ] + }, + { + "cell_type": "code", + "execution_count": 166, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'UTF-8'" + ] + }, + "execution_count": 166, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "r.encoding" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/f.py b/f.py deleted file mode 100644 index 6f16c06..0000000 --- a/f.py +++ /dev/null @@ -1,74 +0,0 @@ -# # def f(a,b,*qweqweqe, c): -# # print(a,b,qweqweqe,c ) -# # -# # f(3,4,5,6,7,8,9,0, c=54) -# -# -# # def g(*args, **kwargs): -# # print(args, kwargs) -# # -# # g(1,2,3,4, name="Andrey", surname="Pak", age="26") -# -# -# -# # def f(): -# # pass -# -# -# -# import datetime -# -# week = { -# 0: "пн", -# 1: "вт", -# 2: "ср", -# 3: "чт", -# 4: "пт", -# 5: "сб", -# 6: "вс", -# } -# -# d = datetime.date(2019, 9, 1) -# -# for i in range(100): -# num = f"{d.day}{d.month}{d.year}" -# s = sum(map(int, num)) -# while s >= 12: -# s = sum(map(int, str(s))) -# -# if s in [8, 9, 11] and week[d.weekday()] in ['вс', 'пт']: -# print(d, week[d.weekday()], s) -# d += datetime.timedelta(days=1) -# -# import sys -# -# class A: -# __slots__ = ["name", "id", "surname"] -# pass -# -# -# -# -# a = A() -# -# a.name = "Andrey" -# a.surname = "Pak" -# a.id = 1234 -# # a.qwe = 2143 -# -# # print(a.name, a.surname, a.id) -# # print(a) -# -# -# d = dict() -# -# print(sys.getsizeof(a)) - -a = ["russia", "usa", "france"] -b = ['r', 'u', 'f'] - -d = dict(zip(b,a)) - -print(d["r"]) - -print(d['u']) From 63eb60ba2c04ab16b982f9ff2dc8bda75bdfdf04 Mon Sep 17 00:00:00 2001 From: Svetorus <43817545+Svetorus@users.noreply.github.com> Date: Thu, 29 Aug 2019 21:08:33 +0300 Subject: [PATCH 19/19] Delete LICENSE --- LICENSE | 674 -------------------------------------------------------- 1 file changed, 674 deletions(-) delete mode 100644 LICENSE diff --git a/LICENSE b/LICENSE deleted file mode 100644 index f288702..0000000 --- a/LICENSE +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -.