├── django_framework
├── blog
│ ├── blog
│ │ ├── __init__.py
│ │ ├── asgi.py
│ │ ├── wsgi.py
│ │ ├── urls.py
│ │ └── settings.py
│ ├── weblog
│ │ ├── __init__.py
│ │ ├── migrations
│ │ │ ├── __init__.py
│ │ │ └── 0001_initial.py
│ │ ├── tests.py
│ │ ├── apps.py
│ │ ├── admin.py
│ │ ├── forms.py
│ │ ├── models.py
│ │ └── views.py
│ ├── templates
│ │ └── weblog
│ │ │ ├── index.html
│ │ │ ├── base.html
│ │ │ ├── post.html
│ │ │ └── search.html
│ ├── manage.py
│ └── static
│ │ └── weblog
│ │ └── livesearch.js
└── points
│ ├── points
│ ├── __init__.py
│ ├── wsgi.py
│ ├── urls.py
│ └── settings.py
│ ├── webpoints
│ ├── __init__.py
│ ├── migrations
│ │ ├── __init__.py
│ │ └── 0001_initial.py
│ ├── tests.py
│ ├── apps.py
│ ├── admin.py
│ ├── models.py
│ └── views.py
│ ├── manage.py
│ ├── templates
│ └── webpoints
│ │ └── index.html
│ └── static
│ └── webpoints
│ └── map.js
├── labs
├── ex_04_atoms.zip
├── cities.txt
├── ex_04_atoms
│ ├── atoms.py
│ └── playground.py
├── ex_02.py
├── ex_06_xml_examples.py
├── ex_04.py
├── ex_01.py
├── ex_01_solution.py
├── ex_02_files.py
├── ex_01_extended.py
└── ex_01_extended_solution.py
├── raptor_game
├── images
│ ├── bomb.gif
│ ├── dock.gif
│ ├── pod.gif
│ ├── bullet.gif
│ ├── enemy1.gif
│ ├── enemy2.gif
│ ├── enemy3.gif
│ ├── enemy4.gif
│ ├── enemy5.gif
│ ├── plane.gif
│ ├── oilholder.gif
│ ├── megabomb_icon.gif
│ ├── energymodule_icon.gif
│ ├── ionscanner_icon.gif
│ ├── micromissile_icon.gif
│ ├── missilepod_icon.gif
│ ├── phaseshield_icon.gif
│ ├── plasmacannon_icon.gif
│ ├── pulsecannon_icon.gif
│ ├── airtoairmissile_icon.gif
│ ├── autotrackminigun_icon.gif
│ ├── dumbfiremissile_icon.gif
│ ├── plane_turning_left_1.gif
│ ├── plane_turning_left_2.gif
│ ├── plane_turning_right_1.gif
│ ├── plane_turning_right_2.gif
│ └── airtogroundmissile_icon.gif
├── raptor_template.py
└── raptor.py
├── xml_rpc
├── calc_client.py
├── calc_service2.py
└── calc_service.py
├── notebooks
├── canteen.xml
├── menza.xml
├── lecture_05_xml_parsing.ipynb
├── lecture_05_xml_to_object.ipynb
├── lecture_04_context_manager.ipynb
├── lecture_03_oop.ipynb
├── lecture_04_decorators.ipynb
├── lecture_04_modules.ipynb
├── lecture_02.ipynb
└── lecture_01.ipynb
├── twitter_client
├── tc_auth.py
├── twitter_basic.py
└── twitter_full.py
├── LICENSE
├── lectures.md
├── exercises_en.md
├── exercises.md
├── README_en.md
└── README.md
/django_framework/blog/blog/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/django_framework/blog/weblog/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/django_framework/points/points/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/django_framework/points/webpoints/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/django_framework/blog/weblog/migrations/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/django_framework/points/webpoints/migrations/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/labs/ex_04_atoms.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/geordi/skj-course/HEAD/labs/ex_04_atoms.zip
--------------------------------------------------------------------------------
/raptor_game/images/bomb.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/geordi/skj-course/HEAD/raptor_game/images/bomb.gif
--------------------------------------------------------------------------------
/raptor_game/images/dock.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/geordi/skj-course/HEAD/raptor_game/images/dock.gif
--------------------------------------------------------------------------------
/raptor_game/images/pod.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/geordi/skj-course/HEAD/raptor_game/images/pod.gif
--------------------------------------------------------------------------------
/django_framework/blog/weblog/tests.py:
--------------------------------------------------------------------------------
1 | from django.test import TestCase
2 |
3 | # Create your tests here.
4 |
--------------------------------------------------------------------------------
/raptor_game/images/bullet.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/geordi/skj-course/HEAD/raptor_game/images/bullet.gif
--------------------------------------------------------------------------------
/raptor_game/images/enemy1.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/geordi/skj-course/HEAD/raptor_game/images/enemy1.gif
--------------------------------------------------------------------------------
/raptor_game/images/enemy2.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/geordi/skj-course/HEAD/raptor_game/images/enemy2.gif
--------------------------------------------------------------------------------
/raptor_game/images/enemy3.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/geordi/skj-course/HEAD/raptor_game/images/enemy3.gif
--------------------------------------------------------------------------------
/raptor_game/images/enemy4.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/geordi/skj-course/HEAD/raptor_game/images/enemy4.gif
--------------------------------------------------------------------------------
/raptor_game/images/enemy5.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/geordi/skj-course/HEAD/raptor_game/images/enemy5.gif
--------------------------------------------------------------------------------
/raptor_game/images/plane.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/geordi/skj-course/HEAD/raptor_game/images/plane.gif
--------------------------------------------------------------------------------
/django_framework/points/webpoints/tests.py:
--------------------------------------------------------------------------------
1 | from django.test import TestCase
2 |
3 | # Create your tests here.
4 |
--------------------------------------------------------------------------------
/raptor_game/images/oilholder.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/geordi/skj-course/HEAD/raptor_game/images/oilholder.gif
--------------------------------------------------------------------------------
/labs/cities.txt:
--------------------------------------------------------------------------------
1 | Ostrava:336000
2 | Praha:1249000
3 | Brno:405000
4 | Olomouc:101000
5 | Karvina:63000
6 | Havirov:82000
7 |
--------------------------------------------------------------------------------
/raptor_game/images/megabomb_icon.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/geordi/skj-course/HEAD/raptor_game/images/megabomb_icon.gif
--------------------------------------------------------------------------------
/raptor_game/images/energymodule_icon.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/geordi/skj-course/HEAD/raptor_game/images/energymodule_icon.gif
--------------------------------------------------------------------------------
/raptor_game/images/ionscanner_icon.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/geordi/skj-course/HEAD/raptor_game/images/ionscanner_icon.gif
--------------------------------------------------------------------------------
/raptor_game/images/micromissile_icon.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/geordi/skj-course/HEAD/raptor_game/images/micromissile_icon.gif
--------------------------------------------------------------------------------
/raptor_game/images/missilepod_icon.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/geordi/skj-course/HEAD/raptor_game/images/missilepod_icon.gif
--------------------------------------------------------------------------------
/raptor_game/images/phaseshield_icon.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/geordi/skj-course/HEAD/raptor_game/images/phaseshield_icon.gif
--------------------------------------------------------------------------------
/raptor_game/images/plasmacannon_icon.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/geordi/skj-course/HEAD/raptor_game/images/plasmacannon_icon.gif
--------------------------------------------------------------------------------
/raptor_game/images/pulsecannon_icon.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/geordi/skj-course/HEAD/raptor_game/images/pulsecannon_icon.gif
--------------------------------------------------------------------------------
/django_framework/blog/weblog/apps.py:
--------------------------------------------------------------------------------
1 | from django.apps import AppConfig
2 |
3 |
4 | class WeblogConfig(AppConfig):
5 | name = 'weblog'
6 |
--------------------------------------------------------------------------------
/raptor_game/images/airtoairmissile_icon.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/geordi/skj-course/HEAD/raptor_game/images/airtoairmissile_icon.gif
--------------------------------------------------------------------------------
/raptor_game/images/autotrackminigun_icon.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/geordi/skj-course/HEAD/raptor_game/images/autotrackminigun_icon.gif
--------------------------------------------------------------------------------
/raptor_game/images/dumbfiremissile_icon.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/geordi/skj-course/HEAD/raptor_game/images/dumbfiremissile_icon.gif
--------------------------------------------------------------------------------
/raptor_game/images/plane_turning_left_1.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/geordi/skj-course/HEAD/raptor_game/images/plane_turning_left_1.gif
--------------------------------------------------------------------------------
/raptor_game/images/plane_turning_left_2.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/geordi/skj-course/HEAD/raptor_game/images/plane_turning_left_2.gif
--------------------------------------------------------------------------------
/raptor_game/images/plane_turning_right_1.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/geordi/skj-course/HEAD/raptor_game/images/plane_turning_right_1.gif
--------------------------------------------------------------------------------
/raptor_game/images/plane_turning_right_2.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/geordi/skj-course/HEAD/raptor_game/images/plane_turning_right_2.gif
--------------------------------------------------------------------------------
/raptor_game/images/airtogroundmissile_icon.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/geordi/skj-course/HEAD/raptor_game/images/airtogroundmissile_icon.gif
--------------------------------------------------------------------------------
/django_framework/points/webpoints/apps.py:
--------------------------------------------------------------------------------
1 | from django.apps import AppConfig
2 |
3 |
4 | class WebpointsConfig(AppConfig):
5 | name = 'webpoints'
6 |
--------------------------------------------------------------------------------
/django_framework/blog/weblog/admin.py:
--------------------------------------------------------------------------------
1 | from django.contrib import admin
2 | from .models import Post, Comment
3 |
4 | admin.site.register(Post)
5 | admin.site.register(Comment)
6 |
--------------------------------------------------------------------------------
/django_framework/blog/weblog/forms.py:
--------------------------------------------------------------------------------
1 | from django import forms
2 | from .models import Comment
3 |
4 | class CommentForm(forms.ModelForm):
5 | class Meta:
6 | model = Comment
7 | exclude = ['post']
8 |
9 |
--------------------------------------------------------------------------------
/django_framework/points/webpoints/admin.py:
--------------------------------------------------------------------------------
1 | from django.contrib.gis import admin
2 | #from django.contrib import admin
3 | from .models import Point
4 |
5 | admin.site.register(Point, admin.OSMGeoAdmin)
6 | #admin.site.register(Point)
7 |
--------------------------------------------------------------------------------
/django_framework/blog/templates/weblog/index.html:
--------------------------------------------------------------------------------
1 | {% extends "weblog/base.html" %}
2 |
3 | {% block body %}
4 |
5 | {% for post in posts %}
6 |
7 | {% endfor %}
8 |
9 | {% endblock %}
10 |
--------------------------------------------------------------------------------
/xml_rpc/calc_client.py:
--------------------------------------------------------------------------------
1 | from xmlrpc.client import ServerProxy
2 |
3 | s = ServerProxy('http://localhost:10000')
4 |
5 | a = 5
6 | b = 6
7 |
8 | print(s.add(a, b))
9 |
10 | a = [1, 2, 3]
11 | b = [4, 5, 6, 7]
12 |
13 | print(s.add(a, b))
14 | print(s.system.listMethods())
15 | print(s.system.methodHelp('add'))
16 |
--------------------------------------------------------------------------------
/django_framework/blog/templates/weblog/base.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | {% block head %}{% endblock %}
4 |
5 |
6 |
7 |
8 |
9 | {% block body %}{% endblock %}
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/django_framework/points/webpoints/models.py:
--------------------------------------------------------------------------------
1 | from django.contrib.gis.db import models
2 |
3 | class Point(models.Model):
4 | title = models.CharField(max_length=100)
5 | info = models.TextField()
6 |
7 | point = models.PointField()
8 |
9 | def __str__(self):
10 | return self.title
11 |
12 | def to_json(self):
13 | return {'lat': self.point.y, 'lng': self.point.x}
14 |
--------------------------------------------------------------------------------
/django_framework/points/webpoints/views.py:
--------------------------------------------------------------------------------
1 | from django.http import HttpResponse
2 | from django.shortcuts import render
3 | import json
4 |
5 | from .models import Point
6 |
7 | def index(request):
8 | return render(request, 'webpoints/index.html', {})
9 |
10 | def points(request):
11 | points = Point.objects.all()
12 |
13 | points_json = [ p.to_json() for p in points ]
14 | return HttpResponse(json.dumps(points_json))
15 |
--------------------------------------------------------------------------------
/django_framework/blog/blog/asgi.py:
--------------------------------------------------------------------------------
1 | """
2 | ASGI config for blog project.
3 |
4 | It exposes the ASGI callable as a module-level variable named ``application``.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
8 | """
9 |
10 | import os
11 |
12 | from django.core.asgi import get_asgi_application
13 |
14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'blog.settings')
15 |
16 | application = get_asgi_application()
17 |
--------------------------------------------------------------------------------
/django_framework/blog/blog/wsgi.py:
--------------------------------------------------------------------------------
1 | """
2 | WSGI config for blog project.
3 |
4 | It exposes the WSGI callable as a module-level variable named ``application``.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
8 | """
9 |
10 | import os
11 |
12 | from django.core.wsgi import get_wsgi_application
13 |
14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'blog.settings')
15 |
16 | application = get_wsgi_application()
17 |
--------------------------------------------------------------------------------
/django_framework/points/points/wsgi.py:
--------------------------------------------------------------------------------
1 | """
2 | WSGI config for points project.
3 |
4 | It exposes the WSGI callable as a module-level variable named ``application``.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
8 | """
9 |
10 | import os
11 |
12 | from django.core.wsgi import get_wsgi_application
13 |
14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "points.settings")
15 |
16 | application = get_wsgi_application()
17 |
--------------------------------------------------------------------------------
/xml_rpc/calc_service2.py:
--------------------------------------------------------------------------------
1 | from xmlrpc.server import SimpleXMLRPCServer
2 |
3 | def add(a, b):
4 | """
5 | Adds two things.
6 | """
7 | return a + b
8 |
9 | def main():
10 | server_address = ('localhost', 10000)
11 | server = SimpleXMLRPCServer(server_address)
12 | server.register_function(add)
13 | server.register_introspection_functions()
14 |
15 | print('CTRL-C to stop')
16 | server.serve_forever()
17 |
18 | if __name__ == '__main__':
19 | main()
20 |
--------------------------------------------------------------------------------
/notebooks/canteen.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/notebooks/menza.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/twitter_client/tc_auth.py:
--------------------------------------------------------------------------------
1 | import oauth2 as oauth
2 | import urllib
3 |
4 | # Register on Twitter to obtain your keys
5 | CONSUMER_KEY=''
6 | CONSUMER_SECRET=''
7 | ACCESS_KEY='136577499-Iw71gSAtAXA0NdltH8EGb9wj0GeHtU6eQL920N0k'
8 | ACCESS_SECRET='tdzTRgoudJ9w6W6Vt8a2p9mUwEp2X0olELF9o6DmBw'
9 |
10 | def twitter_auth():
11 | consumer = oauth.Consumer(key=CONSUMER_KEY, secret=CONSUMER_SECRET)
12 | access_token = oauth.Token(key=ACCESS_KEY, secret=ACCESS_SECRET)
13 | client = oauth.Client(consumer, access_token)
14 |
15 | return client
16 |
17 |
--------------------------------------------------------------------------------
/twitter_client/twitter_basic.py:
--------------------------------------------------------------------------------
1 | import json
2 | import urllib
3 |
4 | import tc_auth
5 |
6 | # https://dev.twitter.com/docs/api/1.1/get/search/tweets
7 |
8 | client = tc_auth.twitter_auth()
9 |
10 | searchURL = 'https://api.twitter.com/1.1/search/tweets.json?q=python&count=5&tresult_type=popular'
11 |
12 | response, data = client.request(searchURL)
13 |
14 | print(data)
15 |
16 | decoded_json = json.loads(data.decode('utf-8'))
17 |
18 | statuses = decoded_json['statuses']
19 |
20 | for status in statuses:
21 | print('{}: {}'.format(status['user']['name'], status['text']))
22 |
23 |
--------------------------------------------------------------------------------
/xml_rpc/calc_service.py:
--------------------------------------------------------------------------------
1 | from xmlrpc.server import SimpleXMLRPCServer
2 |
3 | class CalcService:
4 |
5 | def add(self, a, b):
6 | """
7 | Adds two things.
8 | """
9 | return a + b
10 |
11 | def main():
12 | server_address = ('localhost', 10000)
13 | server = SimpleXMLRPCServer(server_address)
14 | xmlrpc_service = CalcService()
15 | server.register_instance(xmlrpc_service)
16 | server.register_introspection_functions()
17 |
18 | print('CTRL-C to stop')
19 | server.serve_forever()
20 |
21 | if __name__ == '__main__':
22 | main()
23 |
--------------------------------------------------------------------------------
/django_framework/blog/weblog/models.py:
--------------------------------------------------------------------------------
1 | from django.db import models
2 |
3 | class Post(models.Model):
4 | title = models.CharField(max_length=100)
5 | body = models.TextField()
6 | pub_date = models.DateTimeField('date published', auto_now_add=True)
7 |
8 | def __str__(self):
9 | return self.title
10 |
11 |
12 | class Comment(models.Model):
13 | post = models.ForeignKey(Post, on_delete=models.CASCADE)
14 | body = models.TextField()
15 | date = models.DateTimeField('date commented', auto_now_add=True)
16 |
17 | def __str__(self):
18 | return f'{self.id}, {self.post.title}'
19 |
--------------------------------------------------------------------------------
/django_framework/blog/templates/weblog/post.html:
--------------------------------------------------------------------------------
1 | {% extends "weblog/base.html" %}
2 |
3 | {% block body %}
4 | {{ post.title }}
5 |
6 |
7 | {{ post.body }}
8 |
9 |
10 | Comments
11 | {% for comment in comments %}
12 | {{ comment.date|date:"d. m. Y H:i" }}: {{ comment.body }}
13 | {% endfor %}
14 |
15 | Add comment
16 |
17 |
21 | {% endblock %}
22 |
23 |
--------------------------------------------------------------------------------
/labs/ex_04_atoms/atoms.py:
--------------------------------------------------------------------------------
1 | import playground
2 |
3 | class ExampleWorld(object):
4 |
5 | def __init__(self, size_x, size_y):
6 | self.width = size_x
7 | self.height = size_y
8 |
9 | def tick(self):
10 | """This method is called by playground. Sends a tuple of atoms to rendering engine.
11 |
12 | :param size_x: world size x dimension
13 | :param size_y: world size y dimension
14 | :return: tuple of atom objects, each containing (x, y, radius) coordinates
15 | """
16 | return ((80, 50, 10), (150, 200, 20))
17 |
18 |
19 | if __name__ == '__main__':
20 | size_x, size_y = 400, 300
21 |
22 | world = ExampleWorld(size_x, size_y)
23 | playground.run((size_x, size_y), world)
--------------------------------------------------------------------------------
/django_framework/blog/templates/weblog/search.html:
--------------------------------------------------------------------------------
1 | {% extends "weblog/base.html" %}
2 | {% load static %}
3 |
4 | {% block head %}
5 |
6 |
17 | {% endblock %}
18 |
19 | {% block body %}
20 |
21 |
26 |
27 | {% endblock %}
28 |
--------------------------------------------------------------------------------
/django_framework/blog/manage.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """Django's command-line utility for administrative tasks."""
3 | import os
4 | import sys
5 |
6 |
7 | def main():
8 | """Run administrative tasks."""
9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'blog.settings')
10 | try:
11 | from django.core.management import execute_from_command_line
12 | except ImportError as exc:
13 | raise ImportError(
14 | "Couldn't import Django. Are you sure it's installed and "
15 | "available on your PYTHONPATH environment variable? Did you "
16 | "forget to activate a virtual environment?"
17 | ) from exc
18 | execute_from_command_line(sys.argv)
19 |
20 |
21 | if __name__ == '__main__':
22 | main()
23 |
--------------------------------------------------------------------------------
/django_framework/blog/static/weblog/livesearch.js:
--------------------------------------------------------------------------------
1 | var xmlhttp;
2 |
3 | function showResult( str ) {
4 | if ( str.length == 0 ) {
5 | document.getElementById( "livesearch" ).innerHTML = "";
6 | document.getElementById( "livesearch" ).style.border = "0px";
7 | return;
8 | }
9 |
10 | xmlhttp = new XMLHttpRequest();
11 |
12 | let url = "/livesearch";
13 | url += "/" + str;
14 | url += "/" + Math.random();
15 |
16 | xmlhttp.onreadystatechange = stateChange;
17 | xmlhttp.open( "GET", url, true );
18 | xmlhttp.send( null );
19 | }
20 |
21 | function stateChange() {
22 | if ( xmlhttp.readyState == 4 ) {
23 | document.getElementById( "livesearch" ).innerHTML = xmlhttp.responseText;
24 | document.getElementById( "livesearch" ).style.border = "1px solid #A5ACB2";
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/labs/ex_02.py:
--------------------------------------------------------------------------------
1 | def envelope(string):
2 | """
3 | Returns input string with added leading and closing '!' character.
4 |
5 | Example:
6 | "Hello" -> "!Hello!"
7 | """
8 | pass
9 |
10 |
11 | def use_envelope(lst):
12 | """
13 | Returns a list that contains strings that are enveloped using '!' character.
14 | Use envelope function to decouple the problem.
15 | """
16 | pass
17 |
18 |
19 | def super_print(*arg):
20 | """
21 | Prints string of joined strings from *arg separated by whitespace.
22 | On the top and bottom of the string, `-` character is print in the same length
23 | as the output string.
24 |
25 | Example:
26 | super_print("Hello", "World!")
27 |
28 | ------------
29 | Hello World!
30 | ------------
31 | """
32 | pass
33 |
34 |
35 |
--------------------------------------------------------------------------------
/django_framework/points/webpoints/migrations/0001_initial.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | # Generated by Django 1.10.7 on 2017-11-27 08:39
3 | from __future__ import unicode_literals
4 |
5 | import django.contrib.gis.db.models.fields
6 | from django.db import migrations, models
7 |
8 |
9 | class Migration(migrations.Migration):
10 |
11 | initial = True
12 |
13 | dependencies = [
14 | ]
15 |
16 | operations = [
17 | migrations.CreateModel(
18 | name='Point',
19 | fields=[
20 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
21 | ('title', models.CharField(max_length=100)),
22 | ('info', models.TextField()),
23 | ('point', django.contrib.gis.db.models.fields.PointField(srid=4326)),
24 | ],
25 | ),
26 | ]
27 |
--------------------------------------------------------------------------------
/django_framework/points/manage.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | import os
3 | import sys
4 |
5 | if __name__ == "__main__":
6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "points.settings")
7 | try:
8 | from django.core.management import execute_from_command_line
9 | except ImportError:
10 | # The above import may fail for some other reason. Ensure that the
11 | # issue is really that Django is missing to avoid masking other
12 | # exceptions on Python 2.
13 | try:
14 | import django
15 | except ImportError:
16 | raise ImportError(
17 | "Couldn't import Django. Are you sure it's installed and "
18 | "available on your PYTHONPATH environment variable? Did you "
19 | "forget to activate a virtual environment?"
20 | )
21 | raise
22 | execute_from_command_line(sys.argv)
23 |
--------------------------------------------------------------------------------
/django_framework/points/points/urls.py:
--------------------------------------------------------------------------------
1 | """points URL Configuration
2 |
3 | The `urlpatterns` list routes URLs to views. For more information please see:
4 | https://docs.djangoproject.com/en/1.10/topics/http/urls/
5 | Examples:
6 | Function views
7 | 1. Add an import: from my_app import views
8 | 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
9 | Class-based views
10 | 1. Add an import: from other_app.views import Home
11 | 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
12 | Including another URLconf
13 | 1. Import the include() function: from django.conf.urls import url, include
14 | 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
15 | """
16 | from django.conf.urls import url
17 | from django.contrib import admin
18 |
19 | import webpoints.views
20 |
21 | urlpatterns = [
22 | url(r'^admin/', admin.site.urls),
23 | url(r'^$', webpoints.views.index, name='index'),
24 | url(r'^points$', webpoints.views.points, name='points'),
25 | ]
26 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2021 Jan Gaura
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/django_framework/blog/blog/urls.py:
--------------------------------------------------------------------------------
1 | """blog URL Configuration
2 |
3 | The `urlpatterns` list routes URLs to views. For more information please see:
4 | https://docs.djangoproject.com/en/3.1/topics/http/urls/
5 | Examples:
6 | Function views
7 | 1. Add an import: from my_app import views
8 | 2. Add a URL to urlpatterns: path('', views.home, name='home')
9 | Class-based views
10 | 1. Add an import: from other_app.views import Home
11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
12 | Including another URLconf
13 | 1. Import the include() function: from django.urls import include, path
14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
15 | """
16 | from django.contrib import admin
17 | from django.urls import path
18 | from weblog import views
19 |
20 | urlpatterns = [
21 | path('admin/', admin.site.urls),
22 | path('', views.index, name='index'),
23 | path('post//', views.post, name='post'),
24 | path('post//addcomment', views.addcomment, name='addcomment'),
25 | path('search', views.search, name='search'),
26 | path('livesearch//.', views.livesearch, name='livesearch'),
27 | ]
28 |
--------------------------------------------------------------------------------
/django_framework/points/templates/webpoints/index.html:
--------------------------------------------------------------------------------
1 | {% load static %}
2 |
3 |
4 |
5 |
11 |
12 |
13 |
14 | My Google Maps Demo
15 |
16 |
39 |
40 |
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/django_framework/points/static/webpoints/map.js:
--------------------------------------------------------------------------------
1 | var xmlhttp;
2 |
3 | function showResult( ) {
4 | xmlhttp = GetXmlHttpObject();
5 | if ( xmlhttp == null ) {
6 | alert( "Your browser does not support XML HTTP Request" );
7 | return;
8 | }
9 | var url = "/points";
10 | xmlhttp.onreadystatechange = stateChanged;
11 | xmlhttp.open( "GET", url, true );
12 | xmlhttp.send( null );
13 | }
14 |
15 | function stateChanged() {
16 | console.log('rt:', xmlhttp.responseText);
17 | console.log('len:', xmlhttp.responseText.length);
18 | if ( xmlhttp.responseText.length > 0 ) {
19 | var points_in_json = JSON.parse(xmlhttp.responseText);
20 | console.log('points_in_js:', points_in_json);
21 | for ( var p in points_in_json ) {
22 | console.log( 'point:', points_in_json[ p ] );
23 | addPoint( points_in_json[ p ] );
24 | }
25 | }
26 | }
27 |
28 | function GetXmlHttpObject() {
29 | if ( window.XMLHttpRequest ) {
30 | // code for IE7+, Firefox, Chrome, Opera, Safari
31 | return new XMLHttpRequest();
32 | }
33 | if ( window.ActiveXObject ) {
34 | // code for IE6, IE5
35 | return new ActiveXObject( "Microsoft.XMLHTTP" );
36 | }
37 | return null;
38 | }
39 |
--------------------------------------------------------------------------------
/django_framework/blog/weblog/migrations/0001_initial.py:
--------------------------------------------------------------------------------
1 | # Generated by Django 3.1.7 on 2021-03-24 15:01
2 |
3 | from django.db import migrations, models
4 | import django.db.models.deletion
5 |
6 |
7 | class Migration(migrations.Migration):
8 |
9 | initial = True
10 |
11 | dependencies = [
12 | ]
13 |
14 | operations = [
15 | migrations.CreateModel(
16 | name='Post',
17 | fields=[
18 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
19 | ('title', models.CharField(max_length=100)),
20 | ('body', models.TextField()),
21 | ('pub_date', models.DateTimeField(auto_now_add=True, verbose_name='date published')),
22 | ],
23 | ),
24 | migrations.CreateModel(
25 | name='Comment',
26 | fields=[
27 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
28 | ('body', models.TextField()),
29 | ('date', models.DateTimeField(auto_now_add=True, verbose_name='date commented')),
30 | ('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='weblog.post')),
31 | ],
32 | ),
33 | ]
34 |
--------------------------------------------------------------------------------
/labs/ex_06_xml_examples.py:
--------------------------------------------------------------------------------
1 | import xml.etree.ElementTree as ET
2 |
3 | root = ET.parse('canteen.xml') #ElementTree instance
4 |
5 | datums = root.findall('date') #list of Elements
6 |
7 | for date in dates:
8 | print(datum.attrib['day'])
9 | meals = datum.iter('meal')
10 | for meal in meals:
11 | print('\t' + meal.attrib['name'])
12 | for ingredience in meal.iter('ingredience'):
13 | print('\t\t' + ingredience.attrib['name'])
14 |
15 |
16 | def xml2py(node):
17 | name = node.tag
18 |
19 | pytype = type(name, (object, ), {})
20 | pyobj = pytype()
21 |
22 | for attr in node.attrib.keys():
23 | setattr(pyobj, attr, node.get(attr))
24 |
25 | if node.text and node.text != '' and node.text != ' ' \
26 | and node.text != '\n':
27 | setattr(pyobj, 'text', node.text)
28 |
29 | for cn in node:
30 | if not hasattr(pyobj, cn.tag):
31 | setattr(pyobj, cn.tag, [])
32 | getattr(pyobj, cn.tag).append(xml2py(cn))
33 |
34 | return pyobj
35 |
36 | xml_string = ''
37 | with open('canteen.xml', 'rt') as f:
38 | xml_string = f.read()
39 |
40 | menza_xml_tree = ET.fromstring(xml_string)
41 |
42 | obj = xml2py(menza_xml_tree)
43 |
44 | for date in obj.date:
45 | print(datum.day)
46 | for meal in date.meal:
47 | print('\t' + meal.name)
48 | for ingredience in meal.ingredience:
49 | print('\t\t' + ingredience.name)
50 |
--------------------------------------------------------------------------------
/labs/ex_04.py:
--------------------------------------------------------------------------------
1 | class Battlestar:
2 | """
3 | Represents a battlestar
4 | (its name and commander).
5 | """
6 |
7 | def __init__(self, name, commander): # initializer
8 | self.name = name # instance variable
9 | self.commander = commander
10 |
11 | def identify(self): # method
12 | return 'This is Battlestar {}, commanded by {}.'.format(self.name, self.commander)
13 |
14 | galactica = Battlestar('Galactica', 'Bill Adama')
15 | pegasus = Battlestar('Pegasus', 'Helena Cain')
16 |
17 | print(galactica.identify())
18 |
19 | print(pegasus.identify())
20 |
21 |
22 |
23 | """
24 | Task:
25 |
26 | Create Dog and Cat classes. Both classes will have the same
27 | constructor that will take one argument and name the animal.
28 |
29 | Next, implement the "make_sound" method, which prints a string:
30 | "Name: MNAU!"
31 | or
32 | "Name: HAF!"
33 | depending on whether you are implementing a cat or a dog.
34 |
35 | Finally, create a list in which you put several instances of classes
36 | Dog and Cat. Using the for loop call the make_sound method.
37 | In this way we find out that in dynamically typed languages it is not necessary to
38 | implement a common ancestor or a common interface to obtain a polymorphism.
39 | """
40 |
41 | class Cat:
42 | pass
43 |
44 |
45 | #animals = [ Pes("Lassie"), Kocka("Mikes"), Pes("Zeryk") ]
46 |
47 | #for animal in animals:
48 | # animal.make_sound()
49 |
--------------------------------------------------------------------------------
/lectures.md:
--------------------------------------------------------------------------------
1 | # Přednášky
2 |
3 | Většina témat je k dispozici online na [YT](https://www.youtube.com/@jgatvsb2919).
4 | [Zdrojové kódy z přednášek](notebooks) jsou k dispozici ve formě Jupyter notebooků.
5 |
6 |
7 | ## Přednáška 1
8 |
9 | - [YouTube](https://www.youtube.com/watch?v=Fpebl5z0cWQ&list=PL6QCBtgT0B94gbUONguB72-xfgWP_EWNr)
10 | - [Jupyter notebook](https://github.com/geordi/skj-course/blob/master/notebooks/lecture_01.ipynb)
11 |
12 |
13 | ## Přednáška 2
14 |
15 | - [YouTube](https://www.youtube.com/playlist?list=PL6QCBtgT0B95n2ZXcPt2JsNdcJzPpMM7b)
16 | - [Jupyter notebook](https://github.com/geordi/skj-course/blob/master/notebooks/lecture_02.ipynb)
17 | - [Jupyter notebook](https://github.com/geordi/skj-course/blob/master/notebooks/lecture_03_oop.ipynb)
18 |
19 |
20 | ## Přednáška 4
21 | - [YouTube](https://www.youtube.com/watch?v=mNCnN5gKhFI&list=PL6QCBtgT0B97xA8-A70X6HUkoU9R-5Jjw)
22 | - [YouTube](https://www.youtube.com/watch?v=ZcRHZcVIFuc&list=PL6QCBtgT0B97f3DOV9KUylDurVDxT0Qvt)
23 | - [Jupyter notebook](https://github.com/geordi/skj-course/blob/master/notebooks/lecture_05_xml_parsing.ipynb)
24 | - [Jupyter notebook](https://github.com/geordi/skj-course/blob/master/notebooks/lecture_05_xml_to_object.ipynb)
25 |
26 |
27 | ## Přednáška 5
28 |
29 | - [YouTube](https://www.youtube.com/watch?v=k_NiT4ghQr4&list=PL6QCBtgT0B95ji4HeTNkVYSUAga73Onx3)
30 |
31 |
32 | ## Přednáška 6
33 |
34 | - [Zrdojové kódy](django_framework/blog)
35 | - [YouTube](https://www.youtube.com/watch?v=_rka931pePE&list=PL6QCBtgT0B97xJIV4khohm2jb3innxf1J)
36 |
37 |
--------------------------------------------------------------------------------
/labs/ex_04_atoms/playground.py:
--------------------------------------------------------------------------------
1 | import time
2 | import tkinter
3 |
4 |
5 | class Colors:
6 | BLUE = 'blue'
7 | RED = 'red'
8 | GREEN = 'green'
9 | BLACK = 'black'
10 | YELLOW = 'yellow'
11 |
12 |
13 | class PlaygroundWindow:
14 |
15 | def __init__(self, window_size):
16 | self.window_size = window_size
17 |
18 | self.master = tkinter.Tk()
19 | self.master.title('Playground')
20 | self.master.protocol("WM_DELETE_WINDOW", lambda: self.master.destroy())
21 | self.master.bind('', lambda e: self.master.destroy())
22 |
23 | self.canvas = tkinter.Canvas(self.master, width=window_size[0], height=window_size[1], background=Colors.BLACK)
24 | self.canvas.pack()
25 |
26 | def put_oval_to_canvas(self, atom):
27 | pos_x, pos_y, rad = atom
28 | o = self.canvas.create_oval(pos_x - rad, pos_y - rad, pos_x + rad, pos_y + rad, fill=Colors.GREEN)
29 |
30 | return o
31 |
32 | def update(self):
33 | self.master.update()
34 |
35 | def delete_item_from_canvas(self, item):
36 | self.canvas.delete(item)
37 |
38 |
39 | def run(size, world):
40 | playground_window = PlaygroundWindow(size)
41 |
42 | while True:
43 | coords = world.tick()
44 |
45 | ovals = []
46 | for coord in coords:
47 | oval = playground_window.put_oval_to_canvas(coord)
48 | ovals.append(oval)
49 |
50 | playground_window.update()
51 |
52 | time.sleep(0.1)
53 |
54 | for oval in ovals:
55 | playground_window.delete_item_from_canvas(oval)
56 |
--------------------------------------------------------------------------------
/django_framework/blog/weblog/views.py:
--------------------------------------------------------------------------------
1 | from django.shortcuts import render, get_object_or_404, redirect
2 | from django.http import HttpResponse
3 | from django.urls import reverse
4 | from .models import Post, Comment
5 | from .forms import CommentForm
6 |
7 |
8 | def index(request):
9 | posts = Post.objects.all()
10 |
11 | return render(request, 'weblog/index.html', {'posts': posts})
12 |
13 |
14 | def post(request, post_id):
15 | post = get_object_or_404(Post, pk=post_id)
16 | comments = Comment.objects.filter(post=post)
17 | comment_form = CommentForm()
18 |
19 | return render(request, 'weblog/post.html', {'post': post, 'comments': comments, 'comment_form': comment_form})
20 |
21 | def addcomment(request, post_id):
22 | post = get_object_or_404(Post, pk=post_id)
23 | if request.method == 'POST':
24 | #print(request.POST)
25 | comment_form = CommentForm(request.POST)
26 | if comment_form.is_valid():
27 | comment_body = comment_form.cleaned_data['body']
28 | comment = Comment(post=post, body=comment_body)
29 | comment.save()
30 |
31 | return redirect('post', post_id=post.id)
32 |
33 | def search(request):
34 | return render(request, 'weblog/search.html', {})
35 |
36 | def livesearch(request, word, sid1, sid2):
37 | posts = Post.objects.filter(title__icontains=word)
38 |
39 | if len(posts) > 0:
40 | response = ''
41 | for p in posts:
42 | response += '{p.title}
'
43 | else:
44 | response = 'no suggestion'
45 |
46 | return HttpResponse(response)
47 |
--------------------------------------------------------------------------------
/twitter_client/twitter_full.py:
--------------------------------------------------------------------------------
1 | import json
2 | import re
3 | import urllib.request, urllib.error, urllib.parse
4 | import tc_auth
5 | from dataclasses import dataclass
6 |
7 | PINK = '\033[95m'
8 | RESET = '\033[0m'
9 | BLUE = '\033[94m'
10 | GREEN = '\033[92m'
11 | WARNING = '\033[93m'
12 | RED = '\033[91m'
13 |
14 | @dataclass
15 | class Tweet:
16 |
17 | from_user : str
18 | text : str
19 |
20 | def __repr__(self):
21 | tags = re.findall(r'\#\w+', self.text)
22 | text = self.text
23 | for tag in tags:
24 | text = text.replace(tag, GREEN+tag+RESET)
25 | return f'{PINK}{self.from_user}:{RESET} {text}'
26 |
27 | class Twitter:
28 |
29 | base_search_url = 'https://api.twitter.com/1.1/search/tweets.json?q={}&count=5&tresult_type=popular'
30 |
31 | def __init__(self, *search):
32 | self.client = tc_auth.twitter_auth()
33 | self.search = search
34 |
35 | def create_search_url(self):
36 | escaped_search = []
37 | for word in self.search:
38 | escaped_search.append(word.replace('#', '%23'))
39 | search_str = '%20'.join(escaped_search)
40 | return Twitter.base_search_url.format(search_str)
41 |
42 | def download(self):
43 | url = self.create_search_url()
44 | self.response, self.data = self.client.request(url)
45 |
46 | def decode_json(self):
47 | self.decoded_json = json.loads(self.data.decode('utf-8'))
48 |
49 | def get_tweets(self):
50 | self.download()
51 | self.decode_json()
52 |
53 | statuses = self.decoded_json['statuses']
54 |
55 | for status in statuses:
56 | from_user = status['user']['name']
57 | text = status['text']
58 |
59 | yield Tweet(from_user, text)
60 |
61 | t = Twitter('#django', '#python')
62 | tweets = t.get_tweets()
63 |
64 | for tweet in tweets:
65 | print(tweet)
66 |
--------------------------------------------------------------------------------
/labs/ex_01.py:
--------------------------------------------------------------------------------
1 | """
2 | Script for the first laboratory.
3 | Add code by following instructions of the teacher.
4 | """
5 |
6 | def add(a, b):
7 | """Adds parameters."""
8 | return a + b
9 |
10 | def what_number(number):
11 | """Returns string positive/zero/negative specifying
12 | value of the number."""
13 | # if :
14 | # elif :
15 | # else:
16 | pass
17 |
18 | def sum_of_numbers(numbers):
19 | """Returns sum of the numbers in the list."""
20 | pass
21 |
22 | def ship_name(fleet, designated_no):
23 | """Return ship's name for specified designated number
24 | from the fleet."""
25 | # has dictionary a key? Use syntax: key in dictionary
26 | pass
27 |
28 | def how_many_5(numbers):
29 | """Returns number of numbers greater than 5."""
30 | # Modify example to take argument that specifies threshold
31 | pass
32 |
33 | def gen_list_gt(lst, no):
34 | """Returns list with numbers greater than no."""
35 | #syntax: [ item for item in lst if_condition ]
36 | pass
37 |
38 | print(add(1, 3))
39 | #print(add([1, 2, 3], [4, 5, 6]))
40 | # Try addition of strings or different data type and see what happens
41 |
42 | #if statement example
43 | #n = 5
44 | #print("Number", n, "is:", what_number(n))
45 |
46 | #for example: sum of the list example
47 | #lst = [1, 2, 3, 6, 7, 8]
48 | #print("Sum is:", sum_of_numbers(lst))
49 |
50 | #dictionary example
51 | #fleet = {'BS62': 'Pegasus', "BS75": "Galactica", 36: 'Valkirie'}
52 | #designated_no = "BS62"
53 | #print("We've got {} in the fleet".format(ship_name(fleet, designated_no)))
54 |
55 | #function to count how many numbers > 5 are in the list
56 | #lst = [1, 2, 5, 6, 7, 10, 12, 40, 3]
57 | #print("There are {} numbers greater than 5".format(how_many_5(lst)))
58 |
59 | #generating list example
60 | #lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
61 | #no = 5
62 | #print("List with numbers > {}: {}".format(no, gen_list_gt(lst, no)))
63 |
--------------------------------------------------------------------------------
/labs/ex_01_solution.py:
--------------------------------------------------------------------------------
1 | """
2 | Script for the first laboratory.
3 | Add code by following instructions of the teacher.
4 | """
5 |
6 | def add(a, b):
7 | """Adds parameters."""
8 | return a + b
9 |
10 | def what_number(number):
11 | """Returns string positive/zero/negative specifying
12 | value of the number."""
13 | # if :
14 | # elif :
15 | # else:
16 | if number > 0:
17 | return "positive"
18 | elif number == 0:
19 | return "zero"
20 | else:
21 | return "negative"
22 |
23 | def sum_of_numbers(numbers):
24 | """Returns sum of the numbers in the list."""
25 | return sum(numbers)
26 |
27 | def ship_name(fleet, designated_no):
28 | """Return ship's name for specified designated number
29 | from the fleet."""
30 | # has dictionary a key? Use syntax: key in dictionary
31 | if designated_no in fleet:
32 | return fleet[designated_no]
33 |
34 | def how_many_5(numbers):
35 | """Returns number of numbers greater than 5."""
36 | # Modify example to take argument that specifies threshold
37 | return sum( 1 for number in numbers if number > 5 )
38 |
39 | def gen_list_gt(lst, no):
40 | """Returns list with numbers greater than no."""
41 | #syntax: [ item for item in lst if_condition ]
42 | return [ item for item in lst if item > no ]
43 |
44 | print(add(1, 3))
45 | #print(add([1, 2, 3], [4, 5, 6]))
46 | # Try addition of strings or different data type and see what happens
47 |
48 | #if statement example
49 | #n = 5
50 | #print("Number", n, "is:", what_number(n))
51 |
52 | #for example: sum of the list example
53 | #lst = [1, 2, 3, 6, 7, 8]
54 | #print("Sum is:", sum_of_numbers(lst))
55 |
56 | #dictionary example
57 | #fleet = {'BS62': 'Pegasus', "BS75": "Galactica", 36: 'Valkirie'}
58 | #designated_no = "BS62"
59 | #print("We've got {} in the fleet".format(ship_name(fleet, designated_no)))
60 |
61 | #function to count how many numbers > 5 are in the list
62 | #lst = [1, 2, 5, 6, 7, 10, 12, 40, 3]
63 | #print("There are {} numbers greater than 5".format(how_many_5(lst)))
64 |
65 | #generating list example
66 | #lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
67 | #no = 5
68 | #print("List with numbers > {}: {}".format(no, gen_list_gt(lst, no)))
69 |
--------------------------------------------------------------------------------
/labs/ex_02_files.py:
--------------------------------------------------------------------------------
1 | def read_file(filename):
2 | """
3 | Returns content of a file as a string.
4 |
5 | Uses classic file access.
6 | """
7 |
8 | f = None
9 | lines = 'Unable to open a file: {0}'.format(filename)
10 | try:
11 | pass
12 | except FileNotFoundError:
13 | pass
14 | finally:
15 | return lines
16 |
17 |
18 | def read_file_using_with(filename):
19 | """
20 | Returns content of a file as a string.
21 |
22 | Uses with statement to open a file.
23 | """
24 |
25 | lines = 'Unable to open a file: {0}'.format(filename)
26 | try:
27 | pass
28 | except FileNotFoundError:
29 | pass
30 | finally:
31 | return lines
32 |
33 |
34 | def filter_cities(filename, **kw):
35 | """
36 | Returns a list of cities that match their population specified by restrictions.
37 | In **kw it will be possible to set an argument:
38 | 'gt': only cities with a population greater than the value of the argument
39 | 'lt': only cities with a population less than the value of the argument
40 | It is possible to enter none, one or both parameters at once.
41 | If no parameter is specified, an empty list is returned.
42 | Use list comprehension for filtering.
43 | Use so-called "unpacking" to load data.
44 |
45 | Reimplement the function to return a generator.
46 | """
47 |
48 | cities = read_file(filename)
49 | filtered = []
50 | if 'gt' in kw:
51 | pass
52 |
53 | return filtered
54 |
55 |
56 | def main():
57 | """
58 | Main function.
59 | This function is run at the startup of a script thanks to the cryptic if statement below.
60 | """
61 |
62 | # file reading
63 | #filename = 'cities.txt'
64 | #content = read_file(filename)
65 | #print('{} file content is: {}'.format(filename, content))
66 |
67 | #content = read_file_using_with(filename)
68 | #print('{} file content using with statement is: {}'.format(filename, content))
69 |
70 | # filtering
71 | #print(filter_cities(filename, gt=500000))
72 | #print(filter_cities(filename, lt=300000))
73 | #print(filter_cities(filename, lt=300000, gt=500000))
74 |
75 | if __name__ == '__main__':
76 | main()
77 |
--------------------------------------------------------------------------------
/notebooks/lecture_05_xml_parsing.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 1,
6 | "metadata": {
7 | "collapsed": true
8 | },
9 | "outputs": [],
10 | "source": [
11 | "import xml.etree.ElementTree as ET"
12 | ]
13 | },
14 | {
15 | "cell_type": "code",
16 | "execution_count": 2,
17 | "metadata": {
18 | "collapsed": true
19 | },
20 | "outputs": [],
21 | "source": [
22 | "root = ET.parse('menza.xml') # ElementTree instance"
23 | ]
24 | },
25 | {
26 | "cell_type": "code",
27 | "execution_count": 3,
28 | "metadata": {
29 | "collapsed": true
30 | },
31 | "outputs": [],
32 | "source": [
33 | "dates = root.findall('date') # list of elements"
34 | ]
35 | },
36 | {
37 | "cell_type": "code",
38 | "execution_count": 16,
39 | "metadata": {},
40 | "outputs": [
41 | {
42 | "name": "stdout",
43 | "output_type": "stream",
44 | "text": [
45 | "Monday\n",
46 | "\tPotato flat cakes\n",
47 | "\t\tpotatoes\n",
48 | "\t\tflour\n",
49 | "\t\teggs\n",
50 | "\tPancakes\n",
51 | "\t\tmilk\n",
52 | "\t\tflour\n",
53 | "\t\teggs\n"
54 | ]
55 | }
56 | ],
57 | "source": [
58 | "for date in dates:\n",
59 | " print(date.attrib['day'])\n",
60 | " meals = iter(date)\n",
61 | " for meal in meals:\n",
62 | " print('\\t' + meal.attrib['name'])\n",
63 | " for ingredient in meal.iterfind('ingredient'):\n",
64 | " print('\\t\\t' + ingredient.attrib['name'])"
65 | ]
66 | },
67 | {
68 | "cell_type": "code",
69 | "execution_count": null,
70 | "metadata": {
71 | "collapsed": true
72 | },
73 | "outputs": [],
74 | "source": []
75 | }
76 | ],
77 | "metadata": {
78 | "kernelspec": {
79 | "display_name": "Python 3",
80 | "language": "python",
81 | "name": "python3"
82 | },
83 | "language_info": {
84 | "codemirror_mode": {
85 | "name": "ipython",
86 | "version": 3
87 | },
88 | "file_extension": ".py",
89 | "mimetype": "text/x-python",
90 | "name": "python",
91 | "nbconvert_exporter": "python",
92 | "pygments_lexer": "ipython3",
93 | "version": "3.5.3"
94 | }
95 | },
96 | "nbformat": 4,
97 | "nbformat_minor": 2
98 | }
99 |
--------------------------------------------------------------------------------
/labs/ex_01_extended.py:
--------------------------------------------------------------------------------
1 | """
2 | Script for the first laboratory.
3 | Add code by following instructions of the teacher.
4 | """
5 |
6 | def add(a, b):
7 | """Adds parameters."""
8 | return a + b
9 |
10 | def what_number(number):
11 | """Returns string positive/zero/negative specifying
12 | value of the number."""
13 | # if :
14 | # elif :
15 | # else:
16 | pass
17 |
18 | def fact(n):
19 | """Returns factorial of the n using recursion."""
20 | pass
21 |
22 | def sum_of_numbers(list_of_numbers):
23 | """Returns sum of the numbers in the list."""
24 | pass
25 |
26 | def ship_name(fleet, designated_no):
27 | """Return ship's name for specified designated number
28 | from the fleet."""
29 | # has dictionary a key? Use syntax: key in dictionary
30 | pass
31 |
32 | def dividable_by(lst, divisor):
33 | """Prints first integer in the lst that is
34 | dividable by specified divisor."""
35 | # types: int, float, str, list, tuble, dict
36 | # get type of a variable: type(variable_name)
37 | pass
38 |
39 | def how_many_5(numbers):
40 | """Returns number of numbers greater than 5."""
41 | # Modify example to take argument that specifies threshold
42 | pass
43 |
44 | def gen_list_gt(lst, no):
45 | """Returns list with numbers greater than no."""
46 | #syntax: [ item for item in lst if_condition ]
47 | pass
48 |
49 | def fact_while(n):
50 | """Returns factorial of the n using while loop."""
51 | pass
52 |
53 | print(add(1, 3))
54 | #print add([1, 2, 3], [4, 5, 6])
55 | # Try addition of strings or different data type and see what happens
56 |
57 | #if statement example
58 | #n = 5
59 | #print("Number", n, "is:", what_number(n))
60 |
61 | #recursion example
62 | #print("Factorial of number", n, "is:", fact(n))
63 |
64 | #for example: sum of the list example
65 | #lst = [1, 2, 3, 6, 7, 8]
66 | #print("Sum is:", sum_of_numbers(lst))
67 |
68 | #dictionary example
69 | #fleet = {'BS62': 'Pegasus', "BS75": "Galactica", 36: 'Valkirie'}
70 | #designated_no = "BS62"
71 | #print("We've got {} in the fleet".format(ship_name(fleet, designated_no)))
72 |
73 | #for example: find first number dividable by ...
74 | #lst = [3, 'string1', 23, 14.0, "string2", 49, 64, 70 ]
75 | #divisor = 8
76 | #dividable_by(lst, divisor)
77 |
78 | #function to count how many numbers > 5 are in the list
79 | #lst = [1, 2, 5, 6, 7, 10, 12, 40, 3]
80 | #print("There are {} numbers greater than 5".format(how_many_5(lst))
81 |
82 | #generating list example
83 | #lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
84 | #no = 5
85 | #print("List with numbers > {}: {}".format(no, gen_list_gt(lst, no))
86 |
87 | #while loop example
88 | #print("Factorial of number", n, "is:", fact_while(n))
89 |
--------------------------------------------------------------------------------
/raptor_game/raptor_template.py:
--------------------------------------------------------------------------------
1 | import os
2 | import sys
3 | import pygame
4 | from pygame.locals import *
5 |
6 | if not pygame.font: print('Warning, fonts disabled')
7 | if not pygame.mixer: print('Warning, sound disabled')
8 |
9 |
10 | def load_image(name, colorkey=None):
11 | fullname = name # os.path.join('data', name)
12 | try:
13 | image = pygame.image.load(fullname)
14 | except pygame.error as message:
15 | print('Cannot load image:', name)
16 | raise SystemExit(message)
17 | image = image.convert()
18 | if colorkey is not None:
19 | if colorkey is -1:
20 | colorkey = image.get_at((0, 0))
21 | image.set_colorkey(colorkey, RLEACCEL)
22 | return image, image.get_rect()
23 |
24 |
25 | class Enemy(pygame.sprite.Sprite):
26 |
27 | def __init__(self):
28 | pygame.sprite.Sprite.__init__(self)
29 | self.image, self.rect = load_image('images/enemy1.gif', -1)
30 | self.x_dist, self.y_dist = 0, 5
31 | self.pos = (10.0, 10.0)
32 | self.rect.center = self.pos
33 | self.health = 100
34 |
35 | def update(self):
36 | pass
37 |
38 |
39 | class Raptor(pygame.sprite.Sprite):
40 |
41 | images = {'left': 'images/plane_turning_right_1.gif',
42 | 'right': 'images/plane_turning_left_1.gif',
43 | 'straight': 'images/plane.gif'}
44 |
45 | def __init__(self):
46 | pygame.sprite.Sprite.__init__(self)
47 | self.image, self.rect = load_image(self.images['straight'], -1)
48 | self.rect.center = 55, 100
49 | self.x_dist, self.y_dist = 5, 5
50 |
51 | def update(self, event):
52 | x_move = 0
53 | y_move = 0
54 |
55 |
56 | class RaptorMain:
57 |
58 | def __init__(self, width=440, height=480):
59 | pygame.init()
60 | self.width = width
61 | self.height = height
62 | self.screen = pygame.display.set_mode((self.width, self.height))
63 | self.score = 0
64 | self.running = True
65 |
66 | def draw(self):
67 | self.screen.blit(self.background, (0, 0))
68 | self.raptor_sprites.draw(self.screen)
69 |
70 | if pygame.font:
71 | font = pygame.font.Font(None, 36)
72 | text = font.render("Score: %d" % self.score, 1, (255, 0, 0))
73 | textpos = text.get_rect(centerx=self.width/2)
74 | self.screen.blit(text, textpos)
75 |
76 | pygame.display.flip()
77 |
78 | def update_scene(self):
79 | pass
80 |
81 | def handle_keys(self):
82 | for event in pygame.event.get():
83 | if event.type == pygame.QUIT:
84 | sys.exit()
85 | elif event.type == KEYDOWN:
86 | self.raptor.update(event)
87 | if event.key == K_q:
88 | self.running = False
89 |
90 | def main_loop(self):
91 | pygame.key.set_repeat(500, 30)
92 |
93 | self.background = pygame.Surface(self.screen.get_size())
94 | self.background = self.background.convert()
95 | self.background.fill((0, 0, 0))
96 |
97 | self.load_sprites()
98 |
99 | while self.running:
100 | self.handle_keys()
101 | self.update_scene()
102 | self.draw()
103 |
104 | def load_sprites(self):
105 | self.raptor = Raptor()
106 | self.raptor_sprites = pygame.sprite.RenderPlain((self.raptor))
107 |
108 |
109 | if __name__ == "__main__":
110 | main_window = RaptorMain()
111 | main_window.main_loop()
112 |
--------------------------------------------------------------------------------
/labs/ex_01_extended_solution.py:
--------------------------------------------------------------------------------
1 | """
2 | Toto je skript pro 1. cviceni.
3 | Doplnte kod dle pokynu cviciciho.
4 | """
5 |
6 | def add(a, b):
7 | """Adds parameters."""
8 | return a + b
9 |
10 | def what_number(number):
11 | """Returns string positive/zero/negative specifying
12 | value of the number."""
13 | # if :
14 | # elif :
15 | # else:
16 | if number > 0:
17 | return "positive"
18 | elif number == 0:
19 | return "zero"
20 | else:
21 | return "negative"
22 |
23 | def fact(n):
24 | """Returns factorial of the n using recursion."""
25 | if n == 0 or n == 1:
26 | return 1
27 | else: return n*fact(n-1)
28 |
29 | def sum_of_numbers(list_of_numbers):
30 | """Returns sum of the numbers in the list."""
31 | return sum(list_of_numbers)
32 |
33 | def ship_name(fleet, designated_no):
34 | """Return ship's name for specified designated number
35 | from the fleet."""
36 | # has dictionary a key? Use syntax: key in dictionary
37 | if designated_no in fleet:
38 | return fleet[designated_no]
39 |
40 | def dividable_by(lst, divisor):
41 | """Prints first integer in the lst that is
42 | dividable by specified divisor."""
43 | # types: int, float, str, list, tuble, dict
44 | # get type of a variable: type(variable_name)
45 | """
46 | for x in lst:
47 | if type(x) != int:
48 | continue
49 | if not x % divisor:
50 | print 'Integer dividable by %d is: %d' % (divisor, x)
51 | break
52 | """
53 | dividable_integer = [ x for x in lst if type(x) is int and not x % divisor ][0]
54 | print 'Integer dividable by %d is: %d' % (divisor, dividable_integer)
55 |
56 | def how_many_5(numbers):
57 | """Returns number of numbers greater than 5."""
58 | # Modify example to take argument that specifies threshold
59 | return sum( 1 for number in numbers if number > 5 )
60 |
61 | def gen_list_gt(lst, no):
62 | """Returns list with numbers greater than no."""
63 | #syntax: [ item for item in lst if_condition ]
64 | return [ item for item in lst if item > no ]
65 |
66 | def fact_while(n):
67 | """Returns factorial of the n using while loop."""
68 | s = 1
69 | while n > 1:
70 | s *= n
71 | n -= 1
72 | return s
73 |
74 | print(add(1, 3))
75 | #print(add([1, 2, 3], [4, 5, 6]))
76 | # Try addition of strings or different data type and see what happens
77 |
78 | #if statement example
79 | #n = 5
80 | #print("Number", n, "is:", what_number(n))
81 |
82 | #recursion example
83 | #print("Factorial of number", n, "is:", fact(n))
84 |
85 | #for example: sum of the list example
86 | #lst = [1, 2, 3, 6, 7, 8]
87 | #print("Sum is:", sum_of_numbers(lst))
88 |
89 | #dictionary example
90 | #fleet = {'BS62': 'Pegasus', "BS75": "Galactica", 36: 'Valkirie'}
91 | #designated_no = "BS62"
92 | #print("We've got {} in the fleet".format(ship_name(fleet, designated_no)))
93 |
94 | #for example: find first number dividable by ...
95 | #lst = [3, 'string1', 23, 14.0, "string2", 49, 64, 70 ]
96 | #divisor = 8
97 | #dividable_by(lst, divisor)
98 |
99 | #function to count how many numbers > 5 are in the list
100 | #lst = [1, 2, 5, 6, 7, 10, 12, 40, 3]
101 | #print("There are {} numbers greater than 5".format(how_many_5(lst)))
102 |
103 | #generating list example
104 | #lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
105 | #no = 5
106 | #print("List with numbers > {}: {}".format(no, gen_list_gt(lst, no)))
107 |
108 | #while loop example
109 | #print("Factorial of number", n, "is:", fact_while(n))
--------------------------------------------------------------------------------
/django_framework/blog/blog/settings.py:
--------------------------------------------------------------------------------
1 | """
2 | Django settings for blog project.
3 |
4 | Generated by 'django-admin startproject' using Django 3.1.7.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/3.1/topics/settings/
8 |
9 | For the full list of settings and their values, see
10 | https://docs.djangoproject.com/en/3.1/ref/settings/
11 | """
12 |
13 | import os
14 |
15 | from pathlib import Path
16 |
17 | # Build paths inside the project like this: BASE_DIR / 'subdir'.
18 | BASE_DIR = Path(__file__).resolve().parent.parent
19 |
20 |
21 | # Quick-start development settings - unsuitable for production
22 | # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
23 |
24 | # SECURITY WARNING: keep the secret key used in production secret!
25 | SECRET_KEY = 'z=3=209qtnz%x5ks3##-dy63s7hu#+3mjw-onk##hfovcc=s!q'
26 |
27 | # SECURITY WARNING: don't run with debug turned on in production!
28 | DEBUG = True
29 |
30 | ALLOWED_HOSTS = []
31 |
32 |
33 | # Application definition
34 |
35 | INSTALLED_APPS = [
36 | 'django.contrib.admin',
37 | 'django.contrib.auth',
38 | 'django.contrib.contenttypes',
39 | 'django.contrib.sessions',
40 | 'django.contrib.messages',
41 | 'django.contrib.staticfiles',
42 | 'weblog.apps.WeblogConfig',
43 | ]
44 |
45 | MIDDLEWARE = [
46 | 'django.middleware.security.SecurityMiddleware',
47 | 'django.contrib.sessions.middleware.SessionMiddleware',
48 | 'django.middleware.common.CommonMiddleware',
49 | 'django.middleware.csrf.CsrfViewMiddleware',
50 | 'django.contrib.auth.middleware.AuthenticationMiddleware',
51 | 'django.contrib.messages.middleware.MessageMiddleware',
52 | 'django.middleware.clickjacking.XFrameOptionsMiddleware',
53 | ]
54 |
55 | ROOT_URLCONF = 'blog.urls'
56 |
57 | TEMPLATES = [
58 | {
59 | 'BACKEND': 'django.template.backends.django.DjangoTemplates',
60 | 'DIRS': ['templates',],
61 | 'APP_DIRS': True,
62 | 'OPTIONS': {
63 | 'context_processors': [
64 | 'django.template.context_processors.debug',
65 | 'django.template.context_processors.request',
66 | 'django.contrib.auth.context_processors.auth',
67 | 'django.contrib.messages.context_processors.messages',
68 | ],
69 | },
70 | },
71 | ]
72 |
73 | WSGI_APPLICATION = 'blog.wsgi.application'
74 |
75 |
76 | # Database
77 | # https://docs.djangoproject.com/en/3.1/ref/settings/#databases
78 |
79 | DATABASES = {
80 | 'default': {
81 | 'ENGINE': 'django.db.backends.sqlite3',
82 | 'NAME': BASE_DIR / 'db.sqlite3',
83 | }
84 | }
85 |
86 |
87 | # Password validation
88 | # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
89 |
90 | AUTH_PASSWORD_VALIDATORS = [
91 | {
92 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
93 | },
94 | {
95 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
96 | },
97 | {
98 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
99 | },
100 | {
101 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
102 | },
103 | ]
104 |
105 |
106 | # Internationalization
107 | # https://docs.djangoproject.com/en/3.1/topics/i18n/
108 |
109 | LANGUAGE_CODE = 'en-us'
110 |
111 | TIME_ZONE = 'UTC'
112 |
113 | USE_I18N = True
114 |
115 | USE_L10N = True
116 |
117 | USE_TZ = True
118 |
119 |
120 | # Static files (CSS, JavaScript, Images)
121 | # https://docs.djangoproject.com/en/3.1/howto/static-files/
122 |
123 | STATIC_URL = '/static/'
124 | STATICFILES_DIRS = (os.path.join('static'),)
125 |
--------------------------------------------------------------------------------
/exercises_en.md:
--------------------------------------------------------------------------------
1 | # Labs
2 |
3 | ## Lab 1
4 |
5 | The script to which you can gradually add the code is available here: [ex_01.py](labs/ex_01.py). The solution is available in: [ex_01_solution.py](labs/ex_01_solution.py).
6 |
7 | We will discuss the following topics in the exercise:
8 | * Dynamic typing
9 | * Garbage collector
10 |
11 | * Working environment:
12 | * ipython
13 | * Magic command,% hist
14 |
15 | * Basic data types:
16 | * numbers (int, long, float, complex)
17 | * string:
18 | * immutable
19 | * literal for long string
20 | * encoding (prefix u)
21 | * list, tuple
22 | * dict
23 |
24 | * Singletons: `None`, `True`, `False`
25 |
26 | * Syntax basics:
27 | * Comments (+ docstring)
28 | * Assignment to a variable
29 | * Calling functions
30 | * print (basic `{}` substitution)
31 | * Conditions (possibility to bypass the absence of the switch)
32 | * Cycles:
33 | * for
34 | * while
35 | * Function definition
36 |
37 | Recommended for practice:
38 |
39 | A script from the 2011/2012 academic year that also includes recursion: [ex_01_extended.py](labs/ex_01_extended.py).
40 | (solution: [cv1_labs_extended_full.py](cv1_labs_extended_full.py)).
41 |
42 |
43 | ### Exercise 2
44 |
45 |
48 |
49 |
50 |
51 | ### Exercise 3
52 |
53 |
56 |
57 |
58 |
59 |
60 | ### Exercise 4
61 |
62 |
65 |
66 |
71 |
72 | ### Exercise 5
73 |
74 |
77 |
78 |
82 |
83 |
84 | ### Exercise 6
85 |
86 |
89 |
90 |
94 |
95 |
96 | ### Exercise 7
97 |
98 |
107 |
108 |
111 |
112 |
113 | ### Exercise 8
114 |
115 |
125 |
126 | ### Exercise 9
127 |
128 |
131 |
--------------------------------------------------------------------------------
/django_framework/points/points/settings.py:
--------------------------------------------------------------------------------
1 | """
2 | Django settings for points project.
3 |
4 | Generated by 'django-admin startproject' using Django 1.10.7.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/1.10/topics/settings/
8 |
9 | For the full list of settings and their values, see
10 | https://docs.djangoproject.com/en/1.10/ref/settings/
11 | """
12 |
13 | import os
14 |
15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
17 |
18 |
19 | # Quick-start development settings - unsuitable for production
20 | # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
21 |
22 | # SECURITY WARNING: keep the secret key used in production secret!
23 | SECRET_KEY = 'g_4d*av$7a+kdwy1d+q^rslim^*rs7dbe1mz2b8@@&+9upimn&'
24 |
25 | # SECURITY WARNING: don't run with debug turned on in production!
26 | DEBUG = True
27 |
28 | ALLOWED_HOSTS = []
29 |
30 |
31 | # Application definition
32 |
33 | INSTALLED_APPS = [
34 | 'django.contrib.admin',
35 | 'django.contrib.auth',
36 | 'django.contrib.contenttypes',
37 | 'django.contrib.sessions',
38 | 'django.contrib.messages',
39 | 'django.contrib.staticfiles',
40 | 'django.contrib.gis',
41 | 'webpoints.apps.WebpointsConfig',
42 | ]
43 |
44 | MIDDLEWARE = [
45 | 'django.middleware.security.SecurityMiddleware',
46 | 'django.contrib.sessions.middleware.SessionMiddleware',
47 | 'django.middleware.common.CommonMiddleware',
48 | 'django.middleware.csrf.CsrfViewMiddleware',
49 | 'django.contrib.auth.middleware.AuthenticationMiddleware',
50 | 'django.contrib.messages.middleware.MessageMiddleware',
51 | 'django.middleware.clickjacking.XFrameOptionsMiddleware',
52 | ]
53 |
54 | ROOT_URLCONF = 'points.urls'
55 |
56 | TEMPLATES = [
57 | {
58 | 'BACKEND': 'django.template.backends.django.DjangoTemplates',
59 | 'DIRS': ['templates'],
60 | 'APP_DIRS': True,
61 | 'OPTIONS': {
62 | 'context_processors': [
63 | 'django.template.context_processors.debug',
64 | 'django.template.context_processors.request',
65 | 'django.contrib.auth.context_processors.auth',
66 | 'django.contrib.messages.context_processors.messages',
67 | ],
68 | },
69 | },
70 | ]
71 |
72 | WSGI_APPLICATION = 'points.wsgi.application'
73 |
74 |
75 | # Database
76 | # https://docs.djangoproject.com/en/1.10/ref/settings/#databases
77 |
78 | DATABASES = {
79 | 'default': {
80 | 'ENGINE': 'django.contrib.gis.db.backends.spatialite',
81 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
82 | }
83 | }
84 |
85 |
86 | # Password validation
87 | # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
88 |
89 | AUTH_PASSWORD_VALIDATORS = [
90 | {
91 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
92 | },
93 | {
94 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
95 | },
96 | {
97 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
98 | },
99 | {
100 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
101 | },
102 | ]
103 |
104 |
105 | # Internationalization
106 | # https://docs.djangoproject.com/en/1.10/topics/i18n/
107 |
108 | LANGUAGE_CODE = 'en-us'
109 |
110 | TIME_ZONE = 'UTC'
111 |
112 | USE_I18N = True
113 |
114 | USE_L10N = True
115 |
116 | USE_TZ = True
117 |
118 |
119 | # Static files (CSS, JavaScript, Images)
120 | # https://docs.djangoproject.com/en/1.10/howto/static-files/
121 |
122 | STATIC_URL = '/static/'
123 | STATICFILES_DIRS = ( os.path.join('static'), )
124 |
125 | SPATIALITE_LIBRARY_PATH = 'mod_spatialite'
126 |
--------------------------------------------------------------------------------
/notebooks/lecture_05_xml_to_object.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 2,
6 | "metadata": {},
7 | "outputs": [],
8 | "source": [
9 | "xml_str = '''\n",
10 | "\n",
11 | " \n",
12 | " \n",
13 | " \n",
14 | " \n",
15 | " \n",
16 | " \n",
17 | " \n",
18 | " \n",
19 | " \n",
20 | " \n",
21 | " \n",
22 | " \n",
23 | "'''"
24 | ]
25 | },
26 | {
27 | "cell_type": "code",
28 | "execution_count": 3,
29 | "metadata": {
30 | "collapsed": true
31 | },
32 | "outputs": [],
33 | "source": [
34 | "import xml.etree.ElementTree as ET"
35 | ]
36 | },
37 | {
38 | "cell_type": "code",
39 | "execution_count": 5,
40 | "metadata": {
41 | "collapsed": true
42 | },
43 | "outputs": [],
44 | "source": [
45 | "def xml2py(node):\n",
46 | " name = node.tag\n",
47 | "\n",
48 | " pytype = type(name, (object, ), {})\n",
49 | " pyobj = pytype()\n",
50 | "\n",
51 | " for attr in node.attrib.keys():\n",
52 | " setattr(pyobj, attr, node.get(attr))\n",
53 | "\n",
54 | " if node.text and node.text != '' and node.text != ' ' and node.text != '\\n':\n",
55 | " setattr(pyobj, 'text', node.text)\n",
56 | "\n",
57 | " for cn in node:\n",
58 | " if not hasattr(pyobj, cn.tag):\n",
59 | " setattr(pyobj, cn.tag, [])\n",
60 | " getattr(pyobj, cn.tag).append(xml2py(cn))\n",
61 | "\n",
62 | " return pyobj"
63 | ]
64 | },
65 | {
66 | "cell_type": "code",
67 | "execution_count": 7,
68 | "metadata": {},
69 | "outputs": [],
70 | "source": [
71 | "menza_xml_tree = ET.fromstring(xml_str)"
72 | ]
73 | },
74 | {
75 | "cell_type": "code",
76 | "execution_count": 8,
77 | "metadata": {
78 | "collapsed": true
79 | },
80 | "outputs": [],
81 | "source": [
82 | "obj = xml2py(menza_xml_tree)"
83 | ]
84 | },
85 | {
86 | "cell_type": "code",
87 | "execution_count": 10,
88 | "metadata": {},
89 | "outputs": [
90 | {
91 | "name": "stdout",
92 | "output_type": "stream",
93 | "text": [
94 | "Monday\n",
95 | "\t Potato flat cakes\n",
96 | "\t\t potatoes\n",
97 | "\t\t flour\n",
98 | "\t\t eggs\n",
99 | "\t Pancakes\n",
100 | "\t\t milk\n",
101 | "\t\t flour\n",
102 | "\t\t eggs\n"
103 | ]
104 | }
105 | ],
106 | "source": [
107 | "for date in obj.date:\n",
108 | " print(date.day)\n",
109 | " for meal in date.meal:\n",
110 | " print('\\t', meal.name)\n",
111 | " for ingredient in meal.ingredient:\n",
112 | " print('\\t\\t', ingredient.name)"
113 | ]
114 | },
115 | {
116 | "cell_type": "code",
117 | "execution_count": null,
118 | "metadata": {
119 | "collapsed": true
120 | },
121 | "outputs": [],
122 | "source": []
123 | }
124 | ],
125 | "metadata": {
126 | "kernelspec": {
127 | "display_name": "Python 3",
128 | "language": "python",
129 | "name": "python3"
130 | },
131 | "language_info": {
132 | "codemirror_mode": {
133 | "name": "ipython",
134 | "version": 3
135 | },
136 | "file_extension": ".py",
137 | "mimetype": "text/x-python",
138 | "name": "python",
139 | "nbconvert_exporter": "python",
140 | "pygments_lexer": "ipython3",
141 | "version": "3.5.3"
142 | }
143 | },
144 | "nbformat": 4,
145 | "nbformat_minor": 2
146 | }
147 |
--------------------------------------------------------------------------------
/notebooks/lecture_04_context_manager.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "id": "stunning-bunch",
6 | "metadata": {},
7 | "source": [
8 | "## Context Managers"
9 | ]
10 | },
11 | {
12 | "cell_type": "code",
13 | "execution_count": 1,
14 | "id": "entitled-peter",
15 | "metadata": {},
16 | "outputs": [
17 | {
18 | "name": "stdout",
19 | "output_type": "stream",
20 | "text": [
21 | "Ostrava:336000\n",
22 | "\n",
23 | "Praha:1249000\n",
24 | "\n",
25 | "Brno:405000\n",
26 | "\n",
27 | "Olomouc:101000\n",
28 | "\n",
29 | "Karvina:63000\n",
30 | "\n",
31 | "Havirov:82000\n",
32 | "\n"
33 | ]
34 | }
35 | ],
36 | "source": [
37 | "with open('cities.txt', 'rt') as f:\n",
38 | " for line in f:\n",
39 | " print(line)"
40 | ]
41 | },
42 | {
43 | "cell_type": "code",
44 | "execution_count": 2,
45 | "id": "classical-passing",
46 | "metadata": {},
47 | "outputs": [],
48 | "source": [
49 | "class MCM:\n",
50 | " def __init__(self, filename, mode):\n",
51 | " self.filename = filename\n",
52 | " self.mode = mode\n",
53 | " \n",
54 | " def __enter__(self):\n",
55 | " self.f = open(self.filename, self.mode)\n",
56 | " return self.f\n",
57 | " \n",
58 | " def __exit__(self, exc_type, exc_value, traceback):\n",
59 | " self.f.close()"
60 | ]
61 | },
62 | {
63 | "cell_type": "code",
64 | "execution_count": 3,
65 | "id": "interracial-miniature",
66 | "metadata": {},
67 | "outputs": [
68 | {
69 | "name": "stdout",
70 | "output_type": "stream",
71 | "text": [
72 | "Ostrava:336000\n",
73 | "\n",
74 | "Praha:1249000\n",
75 | "\n",
76 | "Brno:405000\n",
77 | "\n",
78 | "Olomouc:101000\n",
79 | "\n",
80 | "Karvina:63000\n",
81 | "\n",
82 | "Havirov:82000\n",
83 | "\n"
84 | ]
85 | }
86 | ],
87 | "source": [
88 | "with MCM('cities.txt', 'rt') as f:\n",
89 | " for line in f:\n",
90 | " print(line)"
91 | ]
92 | },
93 | {
94 | "cell_type": "code",
95 | "execution_count": 8,
96 | "id": "indirect-drilling",
97 | "metadata": {},
98 | "outputs": [],
99 | "source": [
100 | "from contextlib import contextmanager\n",
101 | "\n",
102 | "@contextmanager\n",
103 | "def opened(filename, mode='rt'):\n",
104 | " f = open(filename, mode)\n",
105 | " try:\n",
106 | " yield f\n",
107 | " finally:\n",
108 | " f.close()"
109 | ]
110 | },
111 | {
112 | "cell_type": "code",
113 | "execution_count": 9,
114 | "id": "utility-flower",
115 | "metadata": {},
116 | "outputs": [
117 | {
118 | "name": "stdout",
119 | "output_type": "stream",
120 | "text": [
121 | "Ostrava:336000\n",
122 | "\n",
123 | "Praha:1249000\n",
124 | "\n",
125 | "Brno:405000\n",
126 | "\n",
127 | "Olomouc:101000\n",
128 | "\n",
129 | "Karvina:63000\n",
130 | "\n",
131 | "Havirov:82000\n",
132 | "\n"
133 | ]
134 | }
135 | ],
136 | "source": [
137 | "with opened('cities.txt', 'rt') as f:\n",
138 | " for line in f:\n",
139 | " print(line)"
140 | ]
141 | },
142 | {
143 | "cell_type": "code",
144 | "execution_count": null,
145 | "id": "strategic-trade",
146 | "metadata": {},
147 | "outputs": [],
148 | "source": []
149 | }
150 | ],
151 | "metadata": {
152 | "kernelspec": {
153 | "display_name": "Python 3.6.9 64-bit ('skj': venv)",
154 | "language": "python",
155 | "name": "python36964bitskjvenv37e9edb2b84c40b4aecebea1eb80b141"
156 | },
157 | "language_info": {
158 | "codemirror_mode": {
159 | "name": "ipython",
160 | "version": 3
161 | },
162 | "file_extension": ".py",
163 | "mimetype": "text/x-python",
164 | "name": "python",
165 | "nbconvert_exporter": "python",
166 | "pygments_lexer": "ipython3",
167 | "version": "3.6.9"
168 | }
169 | },
170 | "nbformat": 4,
171 | "nbformat_minor": 5
172 | }
173 |
--------------------------------------------------------------------------------
/exercises.md:
--------------------------------------------------------------------------------
1 | # Cvičení
2 |
3 | Pro editaci zdrojového kódu doporučuji [VisualStudio Code](https://code.visualstudio.com/) s nainstalovaným rozšířením [ms-python.python](https://marketplace.visualstudio.com/items?itemName=ms-python.python). Pokud chcete používat jiný editor, tak můžete využít, např. [PyCharm](https://www.jetbrains.com/pycharm/), kde můžete získat plnou verzi jako studenti (BTW: IntelliJ IDEA má pěkný [Rust plugin](https://plugins.jetbrains.com/plugin/8182-rust), do kterého příspívá i jeden ze cvičících tohoto předmětu a to [Jakub Beránek](https://github.com/Kobzol)), [Doom Emacs](https://github.com/hlissner/doom-emacs), [SpaceVim](https://spacevim.org/), aj.
4 |
5 | Osobně jsem si vždy vystačil s obyčejným textovým editorem, příkazovou řádkou [iPython](https://ipython.org/) a [Jupyter Notebooky](https://jupyter.org/) (v předmětu je k dispozici i [pár vlastních noteboků](notebooks)).
6 |
7 |
8 | ## Cvičení 1
9 |
10 | Skript, do kterého můžete postupně doplňovat kód, je k dispozici zde: [ex_01.py](labs/ex_01.py). (řešení: [ex_01_solution.py](labs/ex_01_solution.py)).
11 |
12 | Na cvičení budeme probírat níže uvedená témata:
13 | * Dynamická typovost
14 | * Garbage collector
15 |
16 | *Pracovní prostředí:
17 | * ipython
18 | * Magic command `%run`, `%hist`
19 |
20 | * Základní datové typy:
21 | * čísla (`int`, `long`, `float`, `complex`)
22 | * `string`:
23 | * immutable
24 | * literal pro long string
25 | * kódováni, encoding (bytes)
26 | * `list`, `tuple`
27 | * `dict`
28 |
29 | * Singletony: `None`, `True`, `False`
30 |
31 | * Základy syntaxe:
32 | * Komentáře (+ docstring)
33 | * Přiřazení do proměnné
34 | * Volání funkcí
35 | * funkce `print` (základní `{}` substituce)
36 | * Podmínky (možnost obejití absence switche)
37 | * Cykly:
38 | * `for`
39 | * `while`
40 | * Definice funkce
41 |
42 | Doporučeno k procvičení:
43 |
44 | Skript z akademického roku 2011/2012, který navíc obsahuje rekurzi: [ex_01_extended.py](labs/ex_01_extended.py) (řešení: [cv1_labs_extended_full.py](cv1_labs_extended_full.py)).
45 |
46 |
47 |
48 | ## Cvičení 2
49 |
50 | Procvičíme si kolekce, práci se soubory, použití různých parametrů funkcí, generátory, apod.
51 |
52 | Skript, do kterého můžete postupně doplňovat kód, je k dispozici zde: [ex_02.py](labs/ex_02.py).
53 |
54 | Skript pro práci se soubory, je k dispozici zde: [ex_02_files.py](labs/ex_02_files.py).
55 | K němu je ještě třeba doplňkový sobor [cities.txt](labs/cities.txt).
56 |
57 |
60 |
61 |
62 |
63 |
70 |
71 |
72 |
76 |
77 |
78 |
83 |
84 |
89 |
90 |
95 |
96 |
100 |
101 |
106 |
107 |
111 |
112 |
123 |
126 |
127 |
146 |
147 | ## Cvičení 13
148 |
149 | + Závěrečný test
150 |
151 |
152 | ## Cvičení 14
153 |
154 | Odevzdávání projektů + oprava závěrečného testu.
155 |
--------------------------------------------------------------------------------
/raptor_game/raptor.py:
--------------------------------------------------------------------------------
1 | import os
2 | import sys
3 | import pygame
4 | from pygame.time import Clock
5 | from pygame.locals import *
6 |
7 | DIR_UP = 1
8 | DIR_DOWN = -1
9 |
10 | if not pygame.font: print('Warning, fonts disabled')
11 | if not pygame.mixer: print('Warning, sound disabled')
12 |
13 | def load_image(name, colorkey=None):
14 | fullname = name # os.path.join('data', name)
15 | try:
16 | image = pygame.image.load(fullname)
17 | except pygame.error as message:
18 | print('Cannot load image:', name)
19 | raise SystemExit(message)
20 | image = image.convert()
21 | if colorkey is not None:
22 | if colorkey is -1:
23 | colorkey = image.get_at((0, 0))
24 | image.set_colorkey(colorkey, RLEACCEL)
25 | return image, image.get_rect()
26 |
27 |
28 | class Bullet(pygame.sprite.Sprite):
29 |
30 | def __init__(self, pos, direction):
31 | pygame.sprite.Sprite.__init__(self)
32 | self.image, self.rect = load_image('images/bullet.gif', -1)
33 | self.direction = direction
34 | self.rect.center = pos
35 | self.damage = 10
36 |
37 | def update(self):
38 | if self.direction == DIR_DOWN:
39 | move_y = 1
40 | elif self.direction == DIR_UP:
41 | move_y = -1
42 |
43 | self.rect.move_ip(0, move_y)
44 |
45 | _, b_y = self.rect.center
46 | if b_y <= 0:
47 | self.kill()
48 |
49 |
50 | class Enemy(pygame.sprite.Sprite):
51 |
52 | def __init__(self, pos):
53 | pygame.sprite.Sprite.__init__(self)
54 | self.image, self.rect = load_image('images/enemy1.gif', -1)
55 | self.x_dist, self.y_dist = 0, 0.5
56 | self.pos = pos
57 | self.rect.center = self.pos
58 | self.health = 100
59 | self.score_for_kill = 10
60 |
61 | def update(self):
62 | pos_x, pos_y = self.pos
63 | pos_y += self.y_dist
64 | self.pos = (pos_x, pos_y)
65 | self.rect.center = (round(pos_x), round(pos_y))
66 |
67 |
68 | class Raptor(pygame.sprite.Sprite):
69 |
70 | images = {'left': 'images/plane_turning_right_1.gif',
71 | 'right': 'images/plane_turning_left_1.gif',
72 | 'straight': 'images/plane.gif'}
73 |
74 | def __init__(self, pos):
75 | pygame.sprite.Sprite.__init__(self)
76 | self.image, self.rect = load_image(self.images['straight'], -1)
77 | self.rect.center = pos
78 | self.x_dist, self.y_dist = 5, 5
79 |
80 | def update(self, event):
81 | x_move = 0
82 | y_move = 0
83 |
84 | if event.type == KEYDOWN:
85 | if event.key == K_RIGHT:
86 | x_move = self.x_dist
87 | center = self.rect.center
88 | self.image, self.rect = load_image(self.images['right'], -1)
89 | self.rect.center = center
90 | elif event.key == K_LEFT:
91 | x_move = -self.x_dist
92 | center = self.rect.center
93 | self.image, self.rect = load_image(self.images['left'], -1)
94 | self.rect.center = center
95 | elif event.key == K_UP:
96 | y_move = -self.y_dist
97 | elif event.key == K_DOWN:
98 | y_move = self.y_dist
99 | elif event.type == KEYUP:
100 | center = self.rect.center
101 | self.image, self.rect = load_image(self.images['straight'], -1)
102 | self.rect.center = center
103 |
104 | self.rect.move_ip(x_move, y_move)
105 |
106 | def create_bullet(self):
107 | bullet = Bullet(self.rect.center, DIR_UP)
108 | return bullet
109 |
110 |
111 | class RaptorMain:
112 |
113 | def __init__(self, width=440, height=480):
114 | pygame.init()
115 | self.width = width
116 | self.height = height
117 | self.screen = pygame.display.set_mode((self.width, self.height))
118 | self.score = 0
119 | self.running = True
120 | self.clock = Clock()
121 |
122 | def draw(self):
123 | self.screen.blit(self.background, (0, 0))
124 | self.raptor_sprites.draw(self.screen)
125 | self.enemy_sprites.draw(self.screen)
126 | self.bullet_sprites.draw(self.screen)
127 |
128 | if pygame.font:
129 | font = pygame.font.Font(None, 36)
130 | text = font.render('Score: {}'.format(self.score), 1, (255, 0, 0))
131 | textpos = text.get_rect(centerx=self.width/2)
132 | self.screen.blit(text, textpos)
133 |
134 | self.clock.tick(60)
135 |
136 | pygame.display.flip()
137 |
138 | def update_scene(self):
139 | self.enemy.update()
140 | self.bullet_sprites.update()
141 |
142 | for bullet in self.bullet_sprites:
143 | lst_cols = pygame.sprite.spritecollide(bullet, self.enemy_sprites, False)
144 |
145 | for col_obj in lst_cols:
146 | col_obj.health -= bullet.damage
147 | if col_obj.health <= 0:
148 | col_obj.kill()
149 | self.score += col_obj.score_for_kill
150 |
151 | if lst_cols != []:
152 | bullet.kill()
153 |
154 |
155 | def handle_keys(self):
156 | for event in pygame.event.get():
157 | if event.type == pygame.QUIT:
158 | sys.exit()
159 | elif event.type == KEYDOWN or event.type == KEYUP:
160 | self.raptor.update(event)
161 |
162 | if event.key == K_SPACE:
163 | self.bullet_sprites.add(self.raptor.create_bullet())
164 | if event.key == K_q:
165 | self.running = False
166 |
167 | def main_loop(self):
168 | pygame.key.set_repeat(500, 30)
169 |
170 | self.background = pygame.Surface(self.screen.get_size())
171 | self.background = self.background.convert()
172 | self.background.fill((0, 0, 0))
173 |
174 | self.load_sprites()
175 |
176 | while self.running:
177 | self.handle_keys()
178 | self.update_scene()
179 | self.draw()
180 |
181 | def load_sprites(self):
182 | self.raptor = Raptor((self.width/2, self.height - 20,))
183 | self.raptor_sprites = pygame.sprite.RenderPlain((self.raptor))
184 | self.enemy = Enemy((20.0, 10.0,))
185 | self.enemy_sprites = pygame.sprite.RenderPlain((self.enemy))
186 | self.bullet_sprites = pygame.sprite.RenderPlain()
187 |
188 |
189 | if __name__ == '__main__':
190 | main_window = RaptorMain()
191 | main_window.main_loop()
192 |
--------------------------------------------------------------------------------
/notebooks/lecture_03_oop.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 1,
6 | "metadata": {},
7 | "outputs": [],
8 | "source": [
9 | "class Document:\n",
10 | " \n",
11 | " no_of_documents = 0\n",
12 | " total_length = 0\n",
13 | "\n",
14 | " def __init__(self, content):\n",
15 | " self._content = content\n",
16 | " Document.no_of_documents += 1\n",
17 | " Document.total_length += len(self._content)\n",
18 | "\n",
19 | " @property\n",
20 | " def content(self):\n",
21 | " return self._content\n",
22 | " \n",
23 | " @content.setter\n",
24 | " def content(self, content):\n",
25 | " Document.total_length -= len(self._content)\n",
26 | " self._content = content\n",
27 | " Document.total_length += len(self._content)\n",
28 | " \n",
29 | " @staticmethod\n",
30 | " def average_length():\n",
31 | " return Document.total_length / Document.no_of_documents\n",
32 | " \n",
33 | " def __str__(self):\n",
34 | " return f'Document: {self._content[:10]}'\n",
35 | " \n",
36 | " def __repr__(self):\n",
37 | " return str(self)"
38 | ]
39 | },
40 | {
41 | "cell_type": "code",
42 | "execution_count": 2,
43 | "metadata": {},
44 | "outputs": [],
45 | "source": [
46 | "class SearchEngine:\n",
47 | "\n",
48 | " def __init__(self):\n",
49 | " self.documents = []\n",
50 | "\n",
51 | " def add_document(self, document):\n",
52 | " self.documents.append(document)\n",
53 | "\n",
54 | " def search(self, **query):\n",
55 | " documents = []\n",
56 | "\n",
57 | " for document in self.documents:\n",
58 | " if 'contains' in query:\n",
59 | " if document.content.find(query['contains']) >= 0:\n",
60 | " documents.append(document)\n",
61 | " if 'icontains' in query:\n",
62 | " if document.content.lower().find(query['icontains'].lower()) >= 0:\n",
63 | " documents.append(document)\n",
64 | "\n",
65 | " return documents\n",
66 | "\n",
67 | " def __iter__(self):\n",
68 | " for doc in self.documents:\n",
69 | " yield doc\n"
70 | ]
71 | },
72 | {
73 | "cell_type": "code",
74 | "execution_count": 3,
75 | "metadata": {},
76 | "outputs": [],
77 | "source": [
78 | "d1 = Document('Text')"
79 | ]
80 | },
81 | {
82 | "cell_type": "code",
83 | "execution_count": 4,
84 | "metadata": {},
85 | "outputs": [
86 | {
87 | "name": "stdout",
88 | "output_type": "stream",
89 | "text": [
90 | "Text\n"
91 | ]
92 | }
93 | ],
94 | "source": [
95 | "print(d1.content)"
96 | ]
97 | },
98 | {
99 | "cell_type": "code",
100 | "execution_count": 5,
101 | "metadata": {},
102 | "outputs": [
103 | {
104 | "name": "stdout",
105 | "output_type": "stream",
106 | "text": [
107 | "1\n"
108 | ]
109 | }
110 | ],
111 | "source": [
112 | "print(d1.no_of_documents)"
113 | ]
114 | },
115 | {
116 | "cell_type": "code",
117 | "execution_count": 6,
118 | "metadata": {},
119 | "outputs": [],
120 | "source": [
121 | "d2 = Document('Another text')"
122 | ]
123 | },
124 | {
125 | "cell_type": "code",
126 | "execution_count": 7,
127 | "metadata": {},
128 | "outputs": [
129 | {
130 | "name": "stdout",
131 | "output_type": "stream",
132 | "text": [
133 | "2\n"
134 | ]
135 | }
136 | ],
137 | "source": [
138 | "print(Document.no_of_documents)"
139 | ]
140 | },
141 | {
142 | "cell_type": "code",
143 | "execution_count": 8,
144 | "metadata": {},
145 | "outputs": [
146 | {
147 | "name": "stdout",
148 | "output_type": "stream",
149 | "text": [
150 | "8.0\n"
151 | ]
152 | }
153 | ],
154 | "source": [
155 | "print(Document.average_length())"
156 | ]
157 | },
158 | {
159 | "cell_type": "code",
160 | "execution_count": 9,
161 | "metadata": {},
162 | "outputs": [
163 | {
164 | "name": "stdout",
165 | "output_type": "stream",
166 | "text": [
167 | "14.0\n"
168 | ]
169 | }
170 | ],
171 | "source": [
172 | "d2.content = 'Another text second time'\n",
173 | "print(Document.average_length())"
174 | ]
175 | },
176 | {
177 | "cell_type": "code",
178 | "execution_count": 10,
179 | "metadata": {},
180 | "outputs": [],
181 | "source": [
182 | "se = SearchEngine()\n",
183 | "se.add_document(d1)\n",
184 | "se.add_document(d2)"
185 | ]
186 | },
187 | {
188 | "cell_type": "code",
189 | "execution_count": 11,
190 | "metadata": {},
191 | "outputs": [
192 | {
193 | "name": "stdout",
194 | "output_type": "stream",
195 | "text": [
196 | "Case sensitive: [Document: Another te]\n",
197 | "Case insensitive: [Document: Text, Document: Another te]\n"
198 | ]
199 | }
200 | ],
201 | "source": [
202 | "print('Case sensitive:', se.search(contains='text'))\n",
203 | "print('Case insensitive:', se.search(icontains='text'))"
204 | ]
205 | },
206 | {
207 | "cell_type": "code",
208 | "execution_count": 12,
209 | "metadata": {},
210 | "outputs": [
211 | {
212 | "name": "stdout",
213 | "output_type": "stream",
214 | "text": [
215 | "Iterator:\n",
216 | "Document: Text\n",
217 | "Document: Another te\n"
218 | ]
219 | }
220 | ],
221 | "source": [
222 | "print('Iterator:')\n",
223 | "for doc in se:\n",
224 | " print(doc)"
225 | ]
226 | },
227 | {
228 | "cell_type": "markdown",
229 | "metadata": {},
230 | "source": [
231 | "### Generator"
232 | ]
233 | },
234 | {
235 | "cell_type": "code",
236 | "execution_count": 13,
237 | "metadata": {},
238 | "outputs": [],
239 | "source": [
240 | "se_it = iter(se)"
241 | ]
242 | },
243 | {
244 | "cell_type": "code",
245 | "execution_count": 14,
246 | "metadata": {},
247 | "outputs": [
248 | {
249 | "name": "stdout",
250 | "output_type": "stream",
251 | "text": [
252 | "Document: Text\n"
253 | ]
254 | }
255 | ],
256 | "source": [
257 | "elem = next(se_it)\n",
258 | "print(elem)"
259 | ]
260 | },
261 | {
262 | "cell_type": "code",
263 | "execution_count": 15,
264 | "metadata": {},
265 | "outputs": [
266 | {
267 | "name": "stdout",
268 | "output_type": "stream",
269 | "text": [
270 | "Document: Another te\n"
271 | ]
272 | }
273 | ],
274 | "source": [
275 | "elem = next(se_it)\n",
276 | "print(elem)"
277 | ]
278 | },
279 | {
280 | "cell_type": "code",
281 | "execution_count": 16,
282 | "metadata": {},
283 | "outputs": [
284 | {
285 | "ename": "StopIteration",
286 | "evalue": "",
287 | "output_type": "error",
288 | "traceback": [
289 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
290 | "\u001b[0;31mStopIteration\u001b[0m Traceback (most recent call last)",
291 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0melem\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mnext\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mse_it\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 2\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0melem\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
292 | "\u001b[0;31mStopIteration\u001b[0m: "
293 | ]
294 | }
295 | ],
296 | "source": [
297 | "elem = next(se_it)\n",
298 | "print(elem)"
299 | ]
300 | },
301 | {
302 | "cell_type": "code",
303 | "execution_count": null,
304 | "metadata": {},
305 | "outputs": [],
306 | "source": []
307 | }
308 | ],
309 | "metadata": {
310 | "kernelspec": {
311 | "display_name": "Python 3.6.9 64-bit ('skj': venv)",
312 | "language": "python",
313 | "name": "python36964bitskjvenv37e9edb2b84c40b4aecebea1eb80b141"
314 | },
315 | "language_info": {
316 | "codemirror_mode": {
317 | "name": "ipython",
318 | "version": 3
319 | },
320 | "file_extension": ".py",
321 | "mimetype": "text/x-python",
322 | "name": "python",
323 | "nbconvert_exporter": "python",
324 | "pygments_lexer": "ipython3",
325 | "version": "3.6.9"
326 | }
327 | },
328 | "nbformat": 4,
329 | "nbformat_minor": 2
330 | }
331 |
--------------------------------------------------------------------------------
/notebooks/lecture_04_decorators.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "id": "elegant-parallel",
6 | "metadata": {},
7 | "source": [
8 | "## Decorators"
9 | ]
10 | },
11 | {
12 | "cell_type": "code",
13 | "execution_count": 1,
14 | "id": "skilled-handling",
15 | "metadata": {},
16 | "outputs": [],
17 | "source": [
18 | "import datetime\n",
19 | "import functools"
20 | ]
21 | },
22 | {
23 | "cell_type": "code",
24 | "execution_count": 2,
25 | "id": "guided-veteran",
26 | "metadata": {},
27 | "outputs": [],
28 | "source": [
29 | "def test_fun():\n",
30 | " print('This is a long operation...')"
31 | ]
32 | },
33 | {
34 | "cell_type": "code",
35 | "execution_count": 3,
36 | "id": "diverse-functionality",
37 | "metadata": {},
38 | "outputs": [
39 | {
40 | "name": "stdout",
41 | "output_type": "stream",
42 | "text": [
43 | "This is a long operation...\n"
44 | ]
45 | }
46 | ],
47 | "source": [
48 | "test_fun()"
49 | ]
50 | },
51 | {
52 | "cell_type": "code",
53 | "execution_count": 4,
54 | "id": "according-penetration",
55 | "metadata": {},
56 | "outputs": [],
57 | "source": [
58 | "def test_fun():\n",
59 | " print(datetime.datetime.now())\n",
60 | " print('This is a long operation...')\n",
61 | " print(datetime.datetime.now())"
62 | ]
63 | },
64 | {
65 | "cell_type": "code",
66 | "execution_count": 5,
67 | "id": "transsexual-blast",
68 | "metadata": {},
69 | "outputs": [
70 | {
71 | "name": "stdout",
72 | "output_type": "stream",
73 | "text": [
74 | "2021-03-03 16:13:50.083756\n",
75 | "This is a long operation...\n",
76 | "2021-03-03 16:13:50.084091\n"
77 | ]
78 | }
79 | ],
80 | "source": [
81 | "test_fun()"
82 | ]
83 | },
84 | {
85 | "cell_type": "code",
86 | "execution_count": 6,
87 | "id": "middle-pipeline",
88 | "metadata": {},
89 | "outputs": [],
90 | "source": [
91 | "def logger(f):\n",
92 | " def wrapped():\n",
93 | " print(datetime.datetime.now())\n",
94 | " f()\n",
95 | " print(datetime.datetime.now())\n",
96 | " return wrapped"
97 | ]
98 | },
99 | {
100 | "cell_type": "code",
101 | "execution_count": 7,
102 | "id": "balanced-guyana",
103 | "metadata": {},
104 | "outputs": [],
105 | "source": [
106 | "def test_fun():\n",
107 | " print('This is a long operation...')"
108 | ]
109 | },
110 | {
111 | "cell_type": "code",
112 | "execution_count": 8,
113 | "id": "affiliated-holly",
114 | "metadata": {},
115 | "outputs": [],
116 | "source": [
117 | "test_fun = logger(test_fun)"
118 | ]
119 | },
120 | {
121 | "cell_type": "code",
122 | "execution_count": 9,
123 | "id": "cleared-nurse",
124 | "metadata": {},
125 | "outputs": [
126 | {
127 | "name": "stdout",
128 | "output_type": "stream",
129 | "text": [
130 | "2021-03-03 16:16:51.817324\n",
131 | "This is a long operation...\n",
132 | "2021-03-03 16:16:51.817500\n"
133 | ]
134 | }
135 | ],
136 | "source": [
137 | "test_fun()"
138 | ]
139 | },
140 | {
141 | "cell_type": "code",
142 | "execution_count": 10,
143 | "id": "polyphonic-dover",
144 | "metadata": {},
145 | "outputs": [],
146 | "source": [
147 | "@logger\n",
148 | "def test_fun():\n",
149 | " print('This is a long operation...')"
150 | ]
151 | },
152 | {
153 | "cell_type": "code",
154 | "execution_count": 11,
155 | "id": "attempted-wallet",
156 | "metadata": {},
157 | "outputs": [
158 | {
159 | "name": "stdout",
160 | "output_type": "stream",
161 | "text": [
162 | "2021-03-03 16:18:29.905967\n",
163 | "This is a long operation...\n",
164 | "2021-03-03 16:18:29.906524\n"
165 | ]
166 | }
167 | ],
168 | "source": [
169 | "test_fun()"
170 | ]
171 | },
172 | {
173 | "cell_type": "code",
174 | "execution_count": 12,
175 | "id": "surprising-decline",
176 | "metadata": {},
177 | "outputs": [],
178 | "source": [
179 | "def logger(f):\n",
180 | " def wrapped(*args, **kw):\n",
181 | " print(datetime.datetime.now())\n",
182 | " f(*args, **kw)\n",
183 | " print(datetime.datetime.now())\n",
184 | " return wrapped"
185 | ]
186 | },
187 | {
188 | "cell_type": "code",
189 | "execution_count": 13,
190 | "id": "latter-creativity",
191 | "metadata": {},
192 | "outputs": [],
193 | "source": [
194 | "@logger\n",
195 | "def test_fun(greetings):\n",
196 | " print(f'This is a long operation... {greetings}')"
197 | ]
198 | },
199 | {
200 | "cell_type": "code",
201 | "execution_count": 14,
202 | "id": "intensive-slave",
203 | "metadata": {},
204 | "outputs": [
205 | {
206 | "name": "stdout",
207 | "output_type": "stream",
208 | "text": [
209 | "2021-03-03 16:22:12.027140\n",
210 | "This is a long operation... SKJ Class\n",
211 | "2021-03-03 16:22:12.027440\n"
212 | ]
213 | }
214 | ],
215 | "source": [
216 | "test_fun('SKJ Class')"
217 | ]
218 | },
219 | {
220 | "cell_type": "code",
221 | "execution_count": 16,
222 | "id": "stainless-volleyball",
223 | "metadata": {},
224 | "outputs": [
225 | {
226 | "data": {
227 | "text/plain": [
228 | "'print'"
229 | ]
230 | },
231 | "execution_count": 16,
232 | "metadata": {},
233 | "output_type": "execute_result"
234 | }
235 | ],
236 | "source": [
237 | "print.__name__"
238 | ]
239 | },
240 | {
241 | "cell_type": "code",
242 | "execution_count": 17,
243 | "id": "asian-article",
244 | "metadata": {},
245 | "outputs": [
246 | {
247 | "data": {
248 | "text/plain": [
249 | "'wrapped'"
250 | ]
251 | },
252 | "execution_count": 17,
253 | "metadata": {},
254 | "output_type": "execute_result"
255 | }
256 | ],
257 | "source": [
258 | "test_fun.__name__"
259 | ]
260 | },
261 | {
262 | "cell_type": "code",
263 | "execution_count": 18,
264 | "id": "soviet-mixer",
265 | "metadata": {},
266 | "outputs": [],
267 | "source": [
268 | "def logger(f):\n",
269 | " @functools.wraps(f)\n",
270 | " def wrapped(*args, **kw):\n",
271 | " print(datetime.datetime.now())\n",
272 | " f(*args, **kw)\n",
273 | " print(datetime.datetime.now())\n",
274 | " return wrapped"
275 | ]
276 | },
277 | {
278 | "cell_type": "code",
279 | "execution_count": 19,
280 | "id": "painted-henry",
281 | "metadata": {},
282 | "outputs": [],
283 | "source": [
284 | "@logger\n",
285 | "def test_fun(greetings):\n",
286 | " print(f'This is a long operation... {greetings}')"
287 | ]
288 | },
289 | {
290 | "cell_type": "code",
291 | "execution_count": 20,
292 | "id": "fixed-wisconsin",
293 | "metadata": {},
294 | "outputs": [
295 | {
296 | "data": {
297 | "text/plain": [
298 | "'test_fun'"
299 | ]
300 | },
301 | "execution_count": 20,
302 | "metadata": {},
303 | "output_type": "execute_result"
304 | }
305 | ],
306 | "source": [
307 | "test_fun.__name__"
308 | ]
309 | },
310 | {
311 | "cell_type": "code",
312 | "execution_count": 21,
313 | "id": "impossible-karaoke",
314 | "metadata": {},
315 | "outputs": [],
316 | "source": [
317 | "def logger(prefix):\n",
318 | " def read_decorator(f):\n",
319 | " @functools.wraps(f)\n",
320 | " def wrapped(*args, **kw):\n",
321 | " print(prefix, datetime.datetime.now())\n",
322 | " retval = f(*args, **kw)\n",
323 | " print(prefix, datetime.datetime.now())\n",
324 | " return retval\n",
325 | " return wrapped\n",
326 | " return read_decorator"
327 | ]
328 | },
329 | {
330 | "cell_type": "code",
331 | "execution_count": 22,
332 | "id": "suitable-edwards",
333 | "metadata": {},
334 | "outputs": [],
335 | "source": [
336 | "@logger('My logger prefix:')\n",
337 | "def test_fun(greetings):\n",
338 | " print(f'This is a long operation... {greetings}')"
339 | ]
340 | },
341 | {
342 | "cell_type": "code",
343 | "execution_count": 23,
344 | "id": "understood-tension",
345 | "metadata": {},
346 | "outputs": [
347 | {
348 | "name": "stdout",
349 | "output_type": "stream",
350 | "text": [
351 | "My logger prefix: 2021-03-03 16:28:20.415308\n",
352 | "This is a long operation... SKJ Class\n",
353 | "My logger prefix: 2021-03-03 16:28:20.415740\n"
354 | ]
355 | }
356 | ],
357 | "source": [
358 | "test_fun('SKJ Class')"
359 | ]
360 | },
361 | {
362 | "cell_type": "code",
363 | "execution_count": null,
364 | "id": "material-coast",
365 | "metadata": {},
366 | "outputs": [],
367 | "source": []
368 | }
369 | ],
370 | "metadata": {
371 | "kernelspec": {
372 | "display_name": "Python 3.6.9 64-bit ('skj': venv)",
373 | "language": "python",
374 | "name": "python36964bitskjvenv37e9edb2b84c40b4aecebea1eb80b141"
375 | },
376 | "language_info": {
377 | "codemirror_mode": {
378 | "name": "ipython",
379 | "version": 3
380 | },
381 | "file_extension": ".py",
382 | "mimetype": "text/x-python",
383 | "name": "python",
384 | "nbconvert_exporter": "python",
385 | "pygments_lexer": "ipython3",
386 | "version": "3.6.9"
387 | }
388 | },
389 | "nbformat": 4,
390 | "nbformat_minor": 5
391 | }
392 |
--------------------------------------------------------------------------------
/README_en.md:
--------------------------------------------------------------------------------
1 | # Scripting Languages Course
2 |
3 | Here, you can find all necessary information about Scripting Languages course.
4 |
5 |
6 | ## Labs
7 |
8 | Information about labs is available in a [separate page](exercises_en.md).
9 |
10 |
11 | ## Source Codes
12 |
13 | You can find source codes from lectures in the [Jupyter notebooks](notebooks) section.
14 |
15 | See also [labs](labs) section for codes for Labs.
16 |
17 |
18 | ## Grading
19 |
20 | In the course of the semester, you will be assigned 8 exercises, which you will elaborate independently. Tasks will appear in the [Kelvin](https://kelvin.cs.vsb.cz) system.
21 |
22 | You will be also assigned one project.
23 | The assignment will be posted on this page and you will be informed about it.
24 | Your task is to elaborate this task individually and present it to your teacher by the given deadline, who will evaluate the functionality of the solution and also the way the task is programmed.
25 | The project is worth 30 points.
26 | If you do not submit the assignment within the deadline, 3 points will be subtracted from the maximum ammount of points for each commenced week after the due deadline.
27 | The task is mandatory!
28 | You must delived it!
29 | You must earn at least 10 points from this task.
30 |
31 |
32 |
33 |
34 | ### Final test
35 |
36 | The final test will take place in the examination period and you schedule will be announced in [EdISon](https://edison.vsb.cz).
37 |
38 |
39 | ### Summary
40 |
41 |
42 | | Task type | MAX points | MIN points | Note |
43 | | Elaboration of tasks | 30 (40) | 10 | Scoring mentioned above. |
44 | | Submission of the project in Django | 30 | 10 | |
45 | | Final test | 40 | 15 |
46 |
47 |
48 |
49 | ## Delivering Tasks
50 |
51 | To handout task, use [Kelvin](https://kelvin.cs.vsb.cz) system.
52 |
53 |
54 | ## Books
55 |
56 | I recommend [Dive Into Python 3](https://diveintopython3.problemsolving.io/) book for reading.
57 |
58 |
59 | Text from [MIT 6.01](https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-01sc-introduction-to-electrical-engineering-and-computer-science-i-spring-2011/syllabus/MIT6_01SCS11_textbook.pdf) course is also recommend.
60 |
61 |
62 | ## Additional resources
63 |
64 | * [Python documentation](http://docs.python.org/index.html)
65 |
66 |
67 |
68 | * For the basics of programming, you can use the [Think Python](http://www.greenteapress.com/thinkpython/) book, which you can download for free.
69 |
70 | * You can use the official [Python Tutorial](https://docs.python.org/3/tutorial/) as additional literature.
71 |
72 | * A set of [lectures from MIT ](https://www.youtube.com/watch?v=bX3jvD7XFPs&list=PLB2BE3D6CA77BB8F7) that explain the use of Python on various tasks.
73 |
74 |
75 | ## Django
76 |
77 | Part of our tutorials focus on developing web applications using the [Django framework](http://www.djangoproject.com/).
78 |
79 | For those interested in using Django, I recommend [The Django Book](https://djangobook.com/).
80 |
81 |
82 |
83 |
106 |
107 |
108 | ## Project assignment for full-time students
109 | Deadline for submitting: at seminars in the week from 9.5.2022 to 13.5.2022.
110 |
111 | Using the Django framework, program a simple web application that meets the following criteria:
112 |
113 | - Your application will contain at least 6 models, which will be connected using foreign keys.
114 | - Create adequate administrative interfaces for models.
115 | - Your application will contain at least 12 view and the associated URLs that will work with the models.
116 | - Your application will pass content to templates (you will implement 12 templates).
117 | - Your application will contain at least 6 forms (either model-bound or your own).
118 | - Resulting application should form a logical concept, i.e. individual pages will be linked to each other.
119 | - Blogging and forum apps are not allowed as we did them in lectures.
120 | - A gas station project is not acceptable as we did it at the exercises.
121 | - Your application does not have to contain graphic elements and CSS styles.
122 | - Your app doesn't have contain spatial data (GeoDjango), but you can, of course, use it if you want to.
123 | - Your application must not contain generic views.
124 | - The application can be e.g. your very simple implementation of Twitter service, part of the school information system (granting credit to students), some part of the blue page (Facebook), etc.
125 |
126 |
359 |
--------------------------------------------------------------------------------
/notebooks/lecture_04_modules.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "id": "straight-affect",
6 | "metadata": {},
7 | "source": [
8 | "## Modules"
9 | ]
10 | },
11 | {
12 | "cell_type": "code",
13 | "execution_count": 1,
14 | "id": "psychological-privacy",
15 | "metadata": {},
16 | "outputs": [
17 | {
18 | "data": {
19 | "text/plain": [
20 | "4"
21 | ]
22 | },
23 | "execution_count": 1,
24 | "metadata": {},
25 | "output_type": "execute_result"
26 | }
27 | ],
28 | "source": [
29 | "len('ahoj')"
30 | ]
31 | },
32 | {
33 | "cell_type": "code",
34 | "execution_count": 2,
35 | "id": "superior-artist",
36 | "metadata": {},
37 | "outputs": [
38 | {
39 | "data": {
40 | "text/plain": [
41 | "{'__name__': '__main__',\n",
42 | " '__doc__': 'Automatically created module for IPython interactive environment',\n",
43 | " '__package__': None,\n",
44 | " '__loader__': None,\n",
45 | " '__spec__': None,\n",
46 | " '__builtin__': ,\n",
47 | " '__builtins__': ,\n",
48 | " '_ih': ['', \"len('ahoj')\", 'globals()'],\n",
49 | " '_oh': {1: 4},\n",
50 | " '_dh': ['/home/geordi/skj21/notebooks'],\n",
51 | " 'In': ['', \"len('ahoj')\", 'globals()'],\n",
52 | " 'Out': {1: 4},\n",
53 | " 'get_ipython': >,\n",
54 | " 'exit': ,\n",
55 | " 'quit': ,\n",
56 | " '_': 4,\n",
57 | " '__': '',\n",
58 | " '___': '',\n",
59 | " '_i': \"len('ahoj')\",\n",
60 | " '_ii': '',\n",
61 | " '_iii': '',\n",
62 | " '_i1': \"len('ahoj')\",\n",
63 | " '_1': 4,\n",
64 | " '_i2': 'globals()'}"
65 | ]
66 | },
67 | "execution_count": 2,
68 | "metadata": {},
69 | "output_type": "execute_result"
70 | }
71 | ],
72 | "source": [
73 | "globals()"
74 | ]
75 | },
76 | {
77 | "cell_type": "code",
78 | "execution_count": 3,
79 | "id": "confirmed-humor",
80 | "metadata": {
81 | "scrolled": false
82 | },
83 | "outputs": [
84 | {
85 | "data": {
86 | "text/plain": [
87 | "['ArithmeticError',\n",
88 | " 'AssertionError',\n",
89 | " 'AttributeError',\n",
90 | " 'BaseException',\n",
91 | " 'BlockingIOError',\n",
92 | " 'BrokenPipeError',\n",
93 | " 'BufferError',\n",
94 | " 'BytesWarning',\n",
95 | " 'ChildProcessError',\n",
96 | " 'ConnectionAbortedError',\n",
97 | " 'ConnectionError',\n",
98 | " 'ConnectionRefusedError',\n",
99 | " 'ConnectionResetError',\n",
100 | " 'DeprecationWarning',\n",
101 | " 'EOFError',\n",
102 | " 'Ellipsis',\n",
103 | " 'EnvironmentError',\n",
104 | " 'Exception',\n",
105 | " 'False',\n",
106 | " 'FileExistsError',\n",
107 | " 'FileNotFoundError',\n",
108 | " 'FloatingPointError',\n",
109 | " 'FutureWarning',\n",
110 | " 'GeneratorExit',\n",
111 | " 'IOError',\n",
112 | " 'ImportError',\n",
113 | " 'ImportWarning',\n",
114 | " 'IndentationError',\n",
115 | " 'IndexError',\n",
116 | " 'InterruptedError',\n",
117 | " 'IsADirectoryError',\n",
118 | " 'KeyError',\n",
119 | " 'KeyboardInterrupt',\n",
120 | " 'LookupError',\n",
121 | " 'MemoryError',\n",
122 | " 'ModuleNotFoundError',\n",
123 | " 'NameError',\n",
124 | " 'None',\n",
125 | " 'NotADirectoryError',\n",
126 | " 'NotImplemented',\n",
127 | " 'NotImplementedError',\n",
128 | " 'OSError',\n",
129 | " 'OverflowError',\n",
130 | " 'PendingDeprecationWarning',\n",
131 | " 'PermissionError',\n",
132 | " 'ProcessLookupError',\n",
133 | " 'RecursionError',\n",
134 | " 'ReferenceError',\n",
135 | " 'ResourceWarning',\n",
136 | " 'RuntimeError',\n",
137 | " 'RuntimeWarning',\n",
138 | " 'StopAsyncIteration',\n",
139 | " 'StopIteration',\n",
140 | " 'SyntaxError',\n",
141 | " 'SyntaxWarning',\n",
142 | " 'SystemError',\n",
143 | " 'SystemExit',\n",
144 | " 'TabError',\n",
145 | " 'TimeoutError',\n",
146 | " 'True',\n",
147 | " 'TypeError',\n",
148 | " 'UnboundLocalError',\n",
149 | " 'UnicodeDecodeError',\n",
150 | " 'UnicodeEncodeError',\n",
151 | " 'UnicodeError',\n",
152 | " 'UnicodeTranslateError',\n",
153 | " 'UnicodeWarning',\n",
154 | " 'UserWarning',\n",
155 | " 'ValueError',\n",
156 | " 'Warning',\n",
157 | " 'ZeroDivisionError',\n",
158 | " '__IPYTHON__',\n",
159 | " '__build_class__',\n",
160 | " '__debug__',\n",
161 | " '__doc__',\n",
162 | " '__import__',\n",
163 | " '__loader__',\n",
164 | " '__name__',\n",
165 | " '__package__',\n",
166 | " '__spec__',\n",
167 | " 'abs',\n",
168 | " 'all',\n",
169 | " 'any',\n",
170 | " 'ascii',\n",
171 | " 'bin',\n",
172 | " 'bool',\n",
173 | " 'bytearray',\n",
174 | " 'bytes',\n",
175 | " 'callable',\n",
176 | " 'chr',\n",
177 | " 'classmethod',\n",
178 | " 'compile',\n",
179 | " 'complex',\n",
180 | " 'copyright',\n",
181 | " 'credits',\n",
182 | " 'delattr',\n",
183 | " 'dict',\n",
184 | " 'dir',\n",
185 | " 'display',\n",
186 | " 'divmod',\n",
187 | " 'enumerate',\n",
188 | " 'eval',\n",
189 | " 'exec',\n",
190 | " 'filter',\n",
191 | " 'float',\n",
192 | " 'format',\n",
193 | " 'frozenset',\n",
194 | " 'get_ipython',\n",
195 | " 'getattr',\n",
196 | " 'globals',\n",
197 | " 'hasattr',\n",
198 | " 'hash',\n",
199 | " 'help',\n",
200 | " 'hex',\n",
201 | " 'id',\n",
202 | " 'input',\n",
203 | " 'int',\n",
204 | " 'isinstance',\n",
205 | " 'issubclass',\n",
206 | " 'iter',\n",
207 | " 'len',\n",
208 | " 'license',\n",
209 | " 'list',\n",
210 | " 'locals',\n",
211 | " 'map',\n",
212 | " 'max',\n",
213 | " 'memoryview',\n",
214 | " 'min',\n",
215 | " 'next',\n",
216 | " 'object',\n",
217 | " 'oct',\n",
218 | " 'open',\n",
219 | " 'ord',\n",
220 | " 'pow',\n",
221 | " 'print',\n",
222 | " 'property',\n",
223 | " 'range',\n",
224 | " 'repr',\n",
225 | " 'reversed',\n",
226 | " 'round',\n",
227 | " 'set',\n",
228 | " 'setattr',\n",
229 | " 'slice',\n",
230 | " 'sorted',\n",
231 | " 'staticmethod',\n",
232 | " 'str',\n",
233 | " 'sum',\n",
234 | " 'super',\n",
235 | " 'tuple',\n",
236 | " 'type',\n",
237 | " 'vars',\n",
238 | " 'zip']"
239 | ]
240 | },
241 | "execution_count": 3,
242 | "metadata": {},
243 | "output_type": "execute_result"
244 | }
245 | ],
246 | "source": [
247 | "dir(__builtins__)"
248 | ]
249 | },
250 | {
251 | "cell_type": "code",
252 | "execution_count": 4,
253 | "id": "rotary-wildlife",
254 | "metadata": {},
255 | "outputs": [],
256 | "source": [
257 | "import math"
258 | ]
259 | },
260 | {
261 | "cell_type": "code",
262 | "execution_count": 5,
263 | "id": "northern-mercury",
264 | "metadata": {},
265 | "outputs": [
266 | {
267 | "data": {
268 | "text/plain": [
269 | "['__doc__',\n",
270 | " '__loader__',\n",
271 | " '__name__',\n",
272 | " '__package__',\n",
273 | " '__spec__',\n",
274 | " 'acos',\n",
275 | " 'acosh',\n",
276 | " 'asin',\n",
277 | " 'asinh',\n",
278 | " 'atan',\n",
279 | " 'atan2',\n",
280 | " 'atanh',\n",
281 | " 'ceil',\n",
282 | " 'copysign',\n",
283 | " 'cos',\n",
284 | " 'cosh',\n",
285 | " 'degrees',\n",
286 | " 'e',\n",
287 | " 'erf',\n",
288 | " 'erfc',\n",
289 | " 'exp',\n",
290 | " 'expm1',\n",
291 | " 'fabs',\n",
292 | " 'factorial',\n",
293 | " 'floor',\n",
294 | " 'fmod',\n",
295 | " 'frexp',\n",
296 | " 'fsum',\n",
297 | " 'gamma',\n",
298 | " 'gcd',\n",
299 | " 'hypot',\n",
300 | " 'inf',\n",
301 | " 'isclose',\n",
302 | " 'isfinite',\n",
303 | " 'isinf',\n",
304 | " 'isnan',\n",
305 | " 'ldexp',\n",
306 | " 'lgamma',\n",
307 | " 'log',\n",
308 | " 'log10',\n",
309 | " 'log1p',\n",
310 | " 'log2',\n",
311 | " 'modf',\n",
312 | " 'nan',\n",
313 | " 'pi',\n",
314 | " 'pow',\n",
315 | " 'radians',\n",
316 | " 'sin',\n",
317 | " 'sinh',\n",
318 | " 'sqrt',\n",
319 | " 'tan',\n",
320 | " 'tanh',\n",
321 | " 'tau',\n",
322 | " 'trunc']"
323 | ]
324 | },
325 | "execution_count": 5,
326 | "metadata": {},
327 | "output_type": "execute_result"
328 | }
329 | ],
330 | "source": [
331 | "dir(math)"
332 | ]
333 | },
334 | {
335 | "cell_type": "code",
336 | "execution_count": 6,
337 | "id": "convinced-mainland",
338 | "metadata": {},
339 | "outputs": [
340 | {
341 | "data": {
342 | "text/plain": [
343 | "3.141592653589793"
344 | ]
345 | },
346 | "execution_count": 6,
347 | "metadata": {},
348 | "output_type": "execute_result"
349 | }
350 | ],
351 | "source": [
352 | "math.pi"
353 | ]
354 | },
355 | {
356 | "cell_type": "code",
357 | "execution_count": 7,
358 | "id": "interior-trader",
359 | "metadata": {},
360 | "outputs": [
361 | {
362 | "data": {
363 | "text/plain": [
364 | "['In',\n",
365 | " 'Out',\n",
366 | " '_',\n",
367 | " '_1',\n",
368 | " '_2',\n",
369 | " '_3',\n",
370 | " '_5',\n",
371 | " '_6',\n",
372 | " '__',\n",
373 | " '___',\n",
374 | " '__builtin__',\n",
375 | " '__builtins__',\n",
376 | " '__doc__',\n",
377 | " '__loader__',\n",
378 | " '__name__',\n",
379 | " '__package__',\n",
380 | " '__spec__',\n",
381 | " '_dh',\n",
382 | " '_i',\n",
383 | " '_i1',\n",
384 | " '_i2',\n",
385 | " '_i3',\n",
386 | " '_i4',\n",
387 | " '_i5',\n",
388 | " '_i6',\n",
389 | " '_i7',\n",
390 | " '_ih',\n",
391 | " '_ii',\n",
392 | " '_iii',\n",
393 | " '_oh',\n",
394 | " 'exit',\n",
395 | " 'get_ipython',\n",
396 | " 'math',\n",
397 | " 'quit']"
398 | ]
399 | },
400 | "execution_count": 7,
401 | "metadata": {},
402 | "output_type": "execute_result"
403 | }
404 | ],
405 | "source": [
406 | "dir()"
407 | ]
408 | },
409 | {
410 | "cell_type": "code",
411 | "execution_count": 8,
412 | "id": "smoking-shoot",
413 | "metadata": {},
414 | "outputs": [],
415 | "source": [
416 | "from math import *"
417 | ]
418 | },
419 | {
420 | "cell_type": "code",
421 | "execution_count": 9,
422 | "id": "renewable-tradition",
423 | "metadata": {},
424 | "outputs": [
425 | {
426 | "data": {
427 | "text/plain": [
428 | "['In',\n",
429 | " 'Out',\n",
430 | " '_',\n",
431 | " '_1',\n",
432 | " '_2',\n",
433 | " '_3',\n",
434 | " '_5',\n",
435 | " '_6',\n",
436 | " '_7',\n",
437 | " '__',\n",
438 | " '___',\n",
439 | " '__builtin__',\n",
440 | " '__builtins__',\n",
441 | " '__doc__',\n",
442 | " '__loader__',\n",
443 | " '__name__',\n",
444 | " '__package__',\n",
445 | " '__spec__',\n",
446 | " '_dh',\n",
447 | " '_i',\n",
448 | " '_i1',\n",
449 | " '_i2',\n",
450 | " '_i3',\n",
451 | " '_i4',\n",
452 | " '_i5',\n",
453 | " '_i6',\n",
454 | " '_i7',\n",
455 | " '_i8',\n",
456 | " '_i9',\n",
457 | " '_ih',\n",
458 | " '_ii',\n",
459 | " '_iii',\n",
460 | " '_oh',\n",
461 | " 'acos',\n",
462 | " 'acosh',\n",
463 | " 'asin',\n",
464 | " 'asinh',\n",
465 | " 'atan',\n",
466 | " 'atan2',\n",
467 | " 'atanh',\n",
468 | " 'ceil',\n",
469 | " 'copysign',\n",
470 | " 'cos',\n",
471 | " 'cosh',\n",
472 | " 'degrees',\n",
473 | " 'e',\n",
474 | " 'erf',\n",
475 | " 'erfc',\n",
476 | " 'exit',\n",
477 | " 'exp',\n",
478 | " 'expm1',\n",
479 | " 'fabs',\n",
480 | " 'factorial',\n",
481 | " 'floor',\n",
482 | " 'fmod',\n",
483 | " 'frexp',\n",
484 | " 'fsum',\n",
485 | " 'gamma',\n",
486 | " 'gcd',\n",
487 | " 'get_ipython',\n",
488 | " 'hypot',\n",
489 | " 'inf',\n",
490 | " 'isclose',\n",
491 | " 'isfinite',\n",
492 | " 'isinf',\n",
493 | " 'isnan',\n",
494 | " 'ldexp',\n",
495 | " 'lgamma',\n",
496 | " 'log',\n",
497 | " 'log10',\n",
498 | " 'log1p',\n",
499 | " 'log2',\n",
500 | " 'math',\n",
501 | " 'modf',\n",
502 | " 'nan',\n",
503 | " 'pi',\n",
504 | " 'pow',\n",
505 | " 'quit',\n",
506 | " 'radians',\n",
507 | " 'sin',\n",
508 | " 'sinh',\n",
509 | " 'sqrt',\n",
510 | " 'tan',\n",
511 | " 'tanh',\n",
512 | " 'tau',\n",
513 | " 'trunc']"
514 | ]
515 | },
516 | "execution_count": 9,
517 | "metadata": {},
518 | "output_type": "execute_result"
519 | }
520 | ],
521 | "source": [
522 | "dir()"
523 | ]
524 | },
525 | {
526 | "cell_type": "code",
527 | "execution_count": 10,
528 | "id": "mental-general",
529 | "metadata": {},
530 | "outputs": [
531 | {
532 | "data": {
533 | "text/plain": [
534 | "6"
535 | ]
536 | },
537 | "execution_count": 10,
538 | "metadata": {},
539 | "output_type": "execute_result"
540 | }
541 | ],
542 | "source": [
543 | "sum([1, 2, 3])"
544 | ]
545 | },
546 | {
547 | "cell_type": "code",
548 | "execution_count": 11,
549 | "id": "martial-boston",
550 | "metadata": {},
551 | "outputs": [],
552 | "source": [
553 | "sum = sum([1,2 , 3])"
554 | ]
555 | },
556 | {
557 | "cell_type": "code",
558 | "execution_count": 12,
559 | "id": "genuine-offense",
560 | "metadata": {},
561 | "outputs": [
562 | {
563 | "ename": "TypeError",
564 | "evalue": "'int' object is not callable",
565 | "output_type": "error",
566 | "traceback": [
567 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
568 | "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
569 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0msum\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m3\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
570 | "\u001b[0;31mTypeError\u001b[0m: 'int' object is not callable"
571 | ]
572 | }
573 | ],
574 | "source": [
575 | "sum([1, 2, 3])"
576 | ]
577 | },
578 | {
579 | "cell_type": "code",
580 | "execution_count": 13,
581 | "id": "later-lemon",
582 | "metadata": {},
583 | "outputs": [],
584 | "source": [
585 | "from math import pi, sin, cos"
586 | ]
587 | },
588 | {
589 | "cell_type": "code",
590 | "execution_count": 14,
591 | "id": "brutal-hartford",
592 | "metadata": {},
593 | "outputs": [
594 | {
595 | "data": {
596 | "text/plain": [
597 | "3.141592653589793"
598 | ]
599 | },
600 | "execution_count": 14,
601 | "metadata": {},
602 | "output_type": "execute_result"
603 | }
604 | ],
605 | "source": [
606 | "pi"
607 | ]
608 | },
609 | {
610 | "cell_type": "code",
611 | "execution_count": 15,
612 | "id": "unlike-opportunity",
613 | "metadata": {},
614 | "outputs": [
615 | {
616 | "data": {
617 | "text/plain": [
618 | "'__main__'"
619 | ]
620 | },
621 | "execution_count": 15,
622 | "metadata": {},
623 | "output_type": "execute_result"
624 | }
625 | ],
626 | "source": [
627 | "__name__"
628 | ]
629 | },
630 | {
631 | "cell_type": "code",
632 | "execution_count": 16,
633 | "id": "beautiful-manual",
634 | "metadata": {},
635 | "outputs": [],
636 | "source": [
637 | "import numpy as np"
638 | ]
639 | },
640 | {
641 | "cell_type": "code",
642 | "execution_count": 17,
643 | "id": "cardiac-plain",
644 | "metadata": {},
645 | "outputs": [
646 | {
647 | "data": {
648 | "text/plain": [
649 | ""
650 | ]
651 | },
652 | "execution_count": 17,
653 | "metadata": {},
654 | "output_type": "execute_result"
655 | }
656 | ],
657 | "source": [
658 | "np.zeros"
659 | ]
660 | },
661 | {
662 | "cell_type": "code",
663 | "execution_count": null,
664 | "id": "occasional-sweden",
665 | "metadata": {},
666 | "outputs": [],
667 | "source": []
668 | }
669 | ],
670 | "metadata": {
671 | "kernelspec": {
672 | "display_name": "Python 3.6.9 64-bit ('skj': venv)",
673 | "language": "python",
674 | "name": "python36964bitskjvenv37e9edb2b84c40b4aecebea1eb80b141"
675 | },
676 | "language_info": {
677 | "codemirror_mode": {
678 | "name": "ipython",
679 | "version": 3
680 | },
681 | "file_extension": ".py",
682 | "mimetype": "text/x-python",
683 | "name": "python",
684 | "nbconvert_exporter": "python",
685 | "pygments_lexer": "ipython3",
686 | "version": "3.6.9"
687 | }
688 | },
689 | "nbformat": 4,
690 | "nbformat_minor": 5
691 | }
692 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Skriptovací jazyky ([Scripting Languages Course](README_en.md))
2 |
3 | Na této stránce naleznete informace pro přednášky a cvičení předmětu Skriptovací jazyky.
4 |
5 |
6 | ## Přednášky
7 |
8 | Informace ohledně přednášek naleznete na [samostatné stránce](lectures.md).
9 |
10 |
11 | ## Cvičení
12 |
13 | Informace ohledně cvičení naleznete na [samostatné stránce](exercises.md) nebo stránce Vašeho cvičícího.
14 |
15 |
16 | ## Zdrojové kódy
17 |
18 | Zdrojové kódy z úvodních lekcí můžete najít v adresáři s [Jupyter notebooky](notebooks).
19 |
20 | Jsou též k dispozici [zdrojové kódy ke cvičením](labs).
21 |
22 |
23 | ## Hodnocení
24 |
25 | V průběhu semestru dostanete zadáno 8 úloh na cvičeních nebo jako domácí ukoly, které **samostatně** vypracujete.
26 | Samozřejmě se budete moci cvičícího doptat na případné nejasnosti.
27 | Tyto úlohy se budou týkat témat probraných na přednáškách.
28 | K jednotlivým cvičením budete též mít k dispozici krátký text vysvětlující danou problematiku.
29 | Za každé cvičení nebo úkol budete moci získat až 5 bodů.
30 | Celkové bodové ohodnocení se Vám bude počítat ze 6ti nejlepších výsledků, kterých na cvičeních dosáhnete (maximálně tedy 30 bodů).
31 | Toto je nastaveno z důvodů, že můžete onemocnět a tudíž se nebudete moci dostavit na cvičení apod.
32 |
33 | Dále budete mít zadán projekt.
34 | Specifikace projektu bude vystaveno na této stránce a budete ní informováni na přednášce a cvičeních.
35 | Vašim úkolem je tuto úlohu samostatně vypracovat a v zadaném termínu předvést na cvičení svému cvičícímu, který ohodnotí funkčnost řešení a také způsob, jakým je úloha naprogramována.
36 | Úloha je za 30 bodů. Na pozdější odevzdání nebude brán zřetel. Projekt se odevzdává do systému [Kelvin](https://kelvin.cs.vsb.cz).
37 | le
38 | Projekt je povinný a musíte jej odevzdat!
39 | Z tohoto úkolu musíte získat alespoň 10 bodů.
40 |
41 | Proběhne také závěrečný test, který musíte absolvovat.
42 | Za tento test můžete získat až 40 bodů.
43 | Minimálně musíte získat 15 bodů.
44 |
45 |
46 | ### Závěrečný test
47 |
48 | Závěrečný test proběhne na ve zkouškovém období.
49 |
50 | Termíny budou vypsány v [EdISonu](https://edison.vsb.cz).
51 | Ve zkouškovém období také proběhne oprava (můžete přijít i vícekrát).
52 |
53 | Test bude sestávat z programovacích úloh, které se budou odevzdávat do systému [Kelvin](https://kelvin.cs.vsb.cz).
54 | Nebude se požadovat znalost Django frameworku nebo jiných speciálních knihoven.
55 | Povolený zdroj informací je [dokumentace k jazyku Python](https://docs.python.org/3.8/) a [studijní opora](http://mrl.cs.vsb.cz/people/gaura/skj/skripta.pdf).
56 |
57 |
58 | ### Shrnutí
59 |
60 |
61 |
62 | | MAX bodů | MIN bodů | Poznámka |
63 |
64 |
65 | | Vypracování úloh na cvičeních a DÚ | 30 (40) | 10 | Bodování uvedeno v textu výše. |
66 |
67 |
68 | | Projekt | 30 | 10 | Samostatná práce. |
69 |
70 |
71 | | Závěrečný test | 40 | 15 |
72 |
73 |
74 |
75 |
76 |
82 |
83 | ## Odevzdávání úloh
84 |
85 | Pro odevzdávání úloh bude sloužit systém [Kelvin](https://kelvin.cs.vsb.cz) (pokud cvičící neurčí jinak).
86 |
87 |
88 | ## Literatura
89 |
90 | Studijní opora je k dispozici v samostatném repozitáři [skj-skripta](http://github.com/geordi/spja-skripta) [[PDF](http://mrl.cs.vsb.cz/people/gaura/skj/skripta.pdf)].
91 |
92 | Velmi pěkný totoriál o Pythonu je v kurzu [PyLadies](https://naucse.python.cz/course/pyladies/).
93 |
94 |
95 | ### Knihy
96 |
97 | Doporučuji knihu [Dive Into Python 3](https://diveintopython3.problemsolving.io/) pro přečtení.
98 |
99 | Velice pěkný text je také z kurzu [MIT 6.01](https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-01sc-introduction-to-electrical-engineering-and-computer-science-i-spring-2011/syllabus/MIT6_01SCS11_textbook.pdf).
100 |
101 |
102 | ### Další zdroje
103 |
104 | * [Python documentation](http://docs.python.org/index.html)
105 |
106 |
107 |
108 | * Začátečnické informace o jazyce můžete nalézt v [kurzu PyLadies](https://pyladies.cz/course.html).
109 |
110 | * Pro základy programování můžete využít knihu [Think Python](http://www.greenteapress.com/thinkpython/), kterou si můžete stáhnout zdarma.
111 |
112 | * Jako doplňkovou literaturu můžete použít oficiální [Python Tutorial](https://docs.python.org/3/tutorial/).
113 |
114 | * Sada [přednášek z MIT](https://www.youtube.com/watch?v=bX3jvD7XFPs&list=PLB2BE3D6CA77BB8F7), které vysvětlují použití Pythonu na různých úlohách.
115 |
116 | * Svůj programovací skill si můžete vyzkoušet např. na [CodinGame](https://www.codingame.com/start).
117 |
118 |
119 | ## Django Framework
120 |
121 | Část našich cvičení se zabývá vývojem webových aplikací pomocí [Django frameworku](http://www.djangoproject.com/).
122 |
123 | Pro zájemce o další informace z oblasti použití Django, doporučuji knihu [The Django Book](https://djangobook.com/).
124 |
125 |
126 |
127 |
128 | ## Kombinované studium
129 |
130 | Pro studenty kombinované formy studia jsou úlohy dostupné v systému [Kelvin](https://kelvin.cs.vsb.cz).
131 |
133 |
134 | ## Projekt
135 |
136 | Termín odevzdávání: na cvičeních v zápočtovém týdnu od 13.5.2024 do 17.5.2024.
137 |
138 | Pomocí Django frameworku naprogramujte webovou aplikaci, která bude splňovat následující kritéria
139 | (můžete využít již hotového projektu do předmětu DS II s tím, že jeho návrh použijete jako základ Vaší Django aplikace):
140 |
141 | * aplikace bude obsahovat alespoň 6 modelů, které budou vzájemně provázány vazbou
142 | * k modelům vytvořte adekvátní administrativní rozhraní
143 | * aplikace bude obsahovat alespoň 12 view a s tím spojené URL, které budou s modely pracovat
144 | * view Vaší aplikace budou obsah předávat templatům (budete tedy implementovat 12 templatů)
145 | * aplikace bude obsahovat alespoň 6 formulářů (ať už formulář vázaný na model nebo Váš vlastní)
146 | * REST API k datům aplikace s použitím např. [Django Ninja](https://django-ninja.dev/) nebo view, která vracejí [JsonResponse](https://docs.djangoproject.com/en/5.1/ref/request-response/#jsonresponse-objects)
147 | * výsledná aplikace by měla tvořit nějaký logický celek, tj. jednotlivé stránky na sebe budou odkazoval pomocí linků
148 | * blogovací a fórum aplikace nejsou přípustné, neboť jsme je dělali na přednášce
149 | * projekt na téma benzínové stanice není přípustný, neboť jsme jej dělali na cvičeních
150 | * aplikace by měla obsahovat grafické prvky a CSS styly (pro jednoduchout využijte např. knihovnu [Bootstrap](https://getbootstrap.com/))
151 | * aplikace nemusí obsahovat geografickou složku
152 | * aplikace nesmí obsahovat generické view
153 |
154 | Aplikace může být např. Vaše velmi jednoduchá implementace služby Twitter, část školního informačního systému, základní GitHub, apod.
155 |
156 |
157 |
180 |
181 |
182 |
415 |
--------------------------------------------------------------------------------
/notebooks/lecture_02.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 1,
6 | "id": "clear-gates",
7 | "metadata": {},
8 | "outputs": [],
9 | "source": [
10 | "def sqr(x):\n",
11 | " return x**2"
12 | ]
13 | },
14 | {
15 | "cell_type": "code",
16 | "execution_count": 2,
17 | "id": "fixed-treasure",
18 | "metadata": {},
19 | "outputs": [
20 | {
21 | "data": {
22 | "text/plain": [
23 | "4"
24 | ]
25 | },
26 | "execution_count": 2,
27 | "metadata": {},
28 | "output_type": "execute_result"
29 | }
30 | ],
31 | "source": [
32 | "sqr(2)"
33 | ]
34 | },
35 | {
36 | "cell_type": "code",
37 | "execution_count": 3,
38 | "id": "champion-development",
39 | "metadata": {},
40 | "outputs": [],
41 | "source": [
42 | "def pow(x, y):\n",
43 | " return x**y"
44 | ]
45 | },
46 | {
47 | "cell_type": "code",
48 | "execution_count": 4,
49 | "id": "engaged-subscriber",
50 | "metadata": {},
51 | "outputs": [
52 | {
53 | "data": {
54 | "text/plain": [
55 | "4"
56 | ]
57 | },
58 | "execution_count": 4,
59 | "metadata": {},
60 | "output_type": "execute_result"
61 | }
62 | ],
63 | "source": [
64 | "pow(2, 2)"
65 | ]
66 | },
67 | {
68 | "cell_type": "code",
69 | "execution_count": 5,
70 | "id": "disciplinary-colors",
71 | "metadata": {},
72 | "outputs": [
73 | {
74 | "data": {
75 | "text/plain": [
76 | "8"
77 | ]
78 | },
79 | "execution_count": 5,
80 | "metadata": {},
81 | "output_type": "execute_result"
82 | }
83 | ],
84 | "source": [
85 | "pow(2, 3)"
86 | ]
87 | },
88 | {
89 | "cell_type": "code",
90 | "execution_count": 6,
91 | "id": "distributed-margin",
92 | "metadata": {},
93 | "outputs": [],
94 | "source": [
95 | "def pow(x, y=2):\n",
96 | " return x**y"
97 | ]
98 | },
99 | {
100 | "cell_type": "code",
101 | "execution_count": 7,
102 | "id": "unsigned-jungle",
103 | "metadata": {},
104 | "outputs": [
105 | {
106 | "data": {
107 | "text/plain": [
108 | "4"
109 | ]
110 | },
111 | "execution_count": 7,
112 | "metadata": {},
113 | "output_type": "execute_result"
114 | }
115 | ],
116 | "source": [
117 | "pow(2)"
118 | ]
119 | },
120 | {
121 | "cell_type": "code",
122 | "execution_count": 8,
123 | "id": "further-nickname",
124 | "metadata": {},
125 | "outputs": [
126 | {
127 | "data": {
128 | "text/plain": [
129 | "9"
130 | ]
131 | },
132 | "execution_count": 8,
133 | "metadata": {},
134 | "output_type": "execute_result"
135 | }
136 | ],
137 | "source": [
138 | "pow(3)"
139 | ]
140 | },
141 | {
142 | "cell_type": "code",
143 | "execution_count": 9,
144 | "id": "smoking-glasgow",
145 | "metadata": {},
146 | "outputs": [
147 | {
148 | "data": {
149 | "text/plain": [
150 | "8"
151 | ]
152 | },
153 | "execution_count": 9,
154 | "metadata": {},
155 | "output_type": "execute_result"
156 | }
157 | ],
158 | "source": [
159 | "pow(x=2, y=3)"
160 | ]
161 | },
162 | {
163 | "cell_type": "code",
164 | "execution_count": 10,
165 | "id": "awful-world",
166 | "metadata": {},
167 | "outputs": [
168 | {
169 | "data": {
170 | "text/plain": [
171 | "8"
172 | ]
173 | },
174 | "execution_count": 10,
175 | "metadata": {},
176 | "output_type": "execute_result"
177 | }
178 | ],
179 | "source": [
180 | "pow(y=3, x=2)"
181 | ]
182 | },
183 | {
184 | "cell_type": "code",
185 | "execution_count": 11,
186 | "id": "covered-humor",
187 | "metadata": {},
188 | "outputs": [],
189 | "source": [
190 | "def my_sum(*args):\n",
191 | " print(args, type(args))"
192 | ]
193 | },
194 | {
195 | "cell_type": "code",
196 | "execution_count": 12,
197 | "id": "imperial-permit",
198 | "metadata": {},
199 | "outputs": [
200 | {
201 | "name": "stdout",
202 | "output_type": "stream",
203 | "text": [
204 | "(1, 2, 3) \n"
205 | ]
206 | }
207 | ],
208 | "source": [
209 | "my_sum(1, 2, 3)"
210 | ]
211 | },
212 | {
213 | "cell_type": "code",
214 | "execution_count": 14,
215 | "id": "fewer-return",
216 | "metadata": {},
217 | "outputs": [
218 | {
219 | "data": {
220 | "text/plain": [
221 | "6"
222 | ]
223 | },
224 | "execution_count": 14,
225 | "metadata": {},
226 | "output_type": "execute_result"
227 | }
228 | ],
229 | "source": [
230 | "sum([1, 2, 3])"
231 | ]
232 | },
233 | {
234 | "cell_type": "code",
235 | "execution_count": 15,
236 | "id": "adjusted-diving",
237 | "metadata": {},
238 | "outputs": [],
239 | "source": [
240 | "def my_sum(*args):\n",
241 | " res = 0\n",
242 | " for i in args:\n",
243 | " res += i\n",
244 | " return res"
245 | ]
246 | },
247 | {
248 | "cell_type": "code",
249 | "execution_count": 16,
250 | "id": "following-democracy",
251 | "metadata": {},
252 | "outputs": [
253 | {
254 | "data": {
255 | "text/plain": [
256 | "6"
257 | ]
258 | },
259 | "execution_count": 16,
260 | "metadata": {},
261 | "output_type": "execute_result"
262 | }
263 | ],
264 | "source": [
265 | "my_sum(1, 2, 3)"
266 | ]
267 | },
268 | {
269 | "cell_type": "code",
270 | "execution_count": 17,
271 | "id": "casual-prime",
272 | "metadata": {},
273 | "outputs": [],
274 | "source": [
275 | "def f(a, b, *args):\n",
276 | " print(f'a: {a}')\n",
277 | " print(f'b: {b}')\n",
278 | " print(f'args: {args}')"
279 | ]
280 | },
281 | {
282 | "cell_type": "code",
283 | "execution_count": 19,
284 | "id": "dominant-thompson",
285 | "metadata": {},
286 | "outputs": [
287 | {
288 | "name": "stdout",
289 | "output_type": "stream",
290 | "text": [
291 | "a: 1\n",
292 | "b: 2\n",
293 | "args: (3, 4, 5, 6)\n"
294 | ]
295 | }
296 | ],
297 | "source": [
298 | "f(1, 2, 3, 4, 5, 6)"
299 | ]
300 | },
301 | {
302 | "cell_type": "code",
303 | "execution_count": 20,
304 | "id": "fourth-correction",
305 | "metadata": {},
306 | "outputs": [],
307 | "source": [
308 | "def f(**kwargs):\n",
309 | " print(kwargs)"
310 | ]
311 | },
312 | {
313 | "cell_type": "code",
314 | "execution_count": 21,
315 | "id": "integral-breed",
316 | "metadata": {},
317 | "outputs": [
318 | {
319 | "name": "stdout",
320 | "output_type": "stream",
321 | "text": [
322 | "{}\n"
323 | ]
324 | }
325 | ],
326 | "source": [
327 | "f()"
328 | ]
329 | },
330 | {
331 | "cell_type": "code",
332 | "execution_count": 22,
333 | "id": "afraid-contamination",
334 | "metadata": {},
335 | "outputs": [
336 | {
337 | "name": "stdout",
338 | "output_type": "stream",
339 | "text": [
340 | "{'arg1': 1, 'arg2': 'Ahoj'}\n"
341 | ]
342 | }
343 | ],
344 | "source": [
345 | "f(arg1=1, arg2='Ahoj')"
346 | ]
347 | },
348 | {
349 | "cell_type": "code",
350 | "execution_count": 23,
351 | "id": "speaking-personality",
352 | "metadata": {},
353 | "outputs": [],
354 | "source": [
355 | "g = lambda x: x**2"
356 | ]
357 | },
358 | {
359 | "cell_type": "code",
360 | "execution_count": 24,
361 | "id": "alike-college",
362 | "metadata": {},
363 | "outputs": [
364 | {
365 | "data": {
366 | "text/plain": [
367 | "(x)>"
368 | ]
369 | },
370 | "execution_count": 24,
371 | "metadata": {},
372 | "output_type": "execute_result"
373 | }
374 | ],
375 | "source": [
376 | "g"
377 | ]
378 | },
379 | {
380 | "cell_type": "code",
381 | "execution_count": 25,
382 | "id": "charged-buyer",
383 | "metadata": {},
384 | "outputs": [
385 | {
386 | "data": {
387 | "text/plain": [
388 | "4"
389 | ]
390 | },
391 | "execution_count": 25,
392 | "metadata": {},
393 | "output_type": "execute_result"
394 | }
395 | ],
396 | "source": [
397 | "g(2)"
398 | ]
399 | },
400 | {
401 | "cell_type": "code",
402 | "execution_count": 26,
403 | "id": "bronze-currency",
404 | "metadata": {},
405 | "outputs": [
406 | {
407 | "data": {
408 | "text/plain": [
409 | "9"
410 | ]
411 | },
412 | "execution_count": 26,
413 | "metadata": {},
414 | "output_type": "execute_result"
415 | }
416 | ],
417 | "source": [
418 | "g(3)"
419 | ]
420 | },
421 | {
422 | "cell_type": "code",
423 | "execution_count": 27,
424 | "id": "seeing-relation",
425 | "metadata": {},
426 | "outputs": [],
427 | "source": [
428 | "h = lambda x, y: x**y"
429 | ]
430 | },
431 | {
432 | "cell_type": "code",
433 | "execution_count": 28,
434 | "id": "green-identity",
435 | "metadata": {},
436 | "outputs": [
437 | {
438 | "data": {
439 | "text/plain": [
440 | "8"
441 | ]
442 | },
443 | "execution_count": 28,
444 | "metadata": {},
445 | "output_type": "execute_result"
446 | }
447 | ],
448 | "source": [
449 | "h(2, 3)"
450 | ]
451 | },
452 | {
453 | "cell_type": "code",
454 | "execution_count": 29,
455 | "id": "perceived-impression",
456 | "metadata": {},
457 | "outputs": [
458 | {
459 | "data": {
460 | "text/plain": [
461 | "9"
462 | ]
463 | },
464 | "execution_count": 29,
465 | "metadata": {},
466 | "output_type": "execute_result"
467 | }
468 | ],
469 | "source": [
470 | "(lambda x: x*3)(3)"
471 | ]
472 | },
473 | {
474 | "cell_type": "code",
475 | "execution_count": 30,
476 | "id": "danish-message",
477 | "metadata": {},
478 | "outputs": [],
479 | "source": [
480 | "def make_incrementator(n):\n",
481 | " return lambda x: x + n"
482 | ]
483 | },
484 | {
485 | "cell_type": "code",
486 | "execution_count": 31,
487 | "id": "hungarian-satisfaction",
488 | "metadata": {},
489 | "outputs": [],
490 | "source": [
491 | "inc_by_2 = make_incrementator(2)"
492 | ]
493 | },
494 | {
495 | "cell_type": "code",
496 | "execution_count": 32,
497 | "id": "awful-diagram",
498 | "metadata": {},
499 | "outputs": [
500 | {
501 | "data": {
502 | "text/plain": [
503 | "12"
504 | ]
505 | },
506 | "execution_count": 32,
507 | "metadata": {},
508 | "output_type": "execute_result"
509 | }
510 | ],
511 | "source": [
512 | "inc_by_2(10)"
513 | ]
514 | },
515 | {
516 | "cell_type": "code",
517 | "execution_count": 33,
518 | "id": "tested-stable",
519 | "metadata": {},
520 | "outputs": [
521 | {
522 | "data": {
523 | "text/plain": [
524 | "158"
525 | ]
526 | },
527 | "execution_count": 33,
528 | "metadata": {},
529 | "output_type": "execute_result"
530 | }
531 | ],
532 | "source": [
533 | "inc_by_2(156)"
534 | ]
535 | },
536 | {
537 | "cell_type": "code",
538 | "execution_count": 34,
539 | "id": "embedded-fireplace",
540 | "metadata": {},
541 | "outputs": [],
542 | "source": [
543 | "lst = [1, 2, 3, 4]"
544 | ]
545 | },
546 | {
547 | "cell_type": "code",
548 | "execution_count": 36,
549 | "id": "stainless-snapshot",
550 | "metadata": {},
551 | "outputs": [
552 | {
553 | "data": {
554 | "text/plain": [
555 | "[1, 4, 9, 16]"
556 | ]
557 | },
558 | "execution_count": 36,
559 | "metadata": {},
560 | "output_type": "execute_result"
561 | }
562 | ],
563 | "source": [
564 | "list(map(sqr, lst))"
565 | ]
566 | },
567 | {
568 | "cell_type": "code",
569 | "execution_count": 37,
570 | "id": "spatial-winner",
571 | "metadata": {},
572 | "outputs": [
573 | {
574 | "data": {
575 | "text/plain": [
576 | "[1, 4, 9, 16]"
577 | ]
578 | },
579 | "execution_count": 37,
580 | "metadata": {},
581 | "output_type": "execute_result"
582 | }
583 | ],
584 | "source": [
585 | "list(map(lambda x: x**2, lst))"
586 | ]
587 | },
588 | {
589 | "cell_type": "code",
590 | "execution_count": 38,
591 | "id": "virtual-convention",
592 | "metadata": {},
593 | "outputs": [],
594 | "source": [
595 | "def my_map(func, seq):\n",
596 | " ret = []\n",
597 | " for item in seq:\n",
598 | " ret.append(func(item))\n",
599 | " return ret"
600 | ]
601 | },
602 | {
603 | "cell_type": "code",
604 | "execution_count": 40,
605 | "id": "massive-hebrew",
606 | "metadata": {},
607 | "outputs": [
608 | {
609 | "data": {
610 | "text/plain": [
611 | "[1, 4, 9, 16]"
612 | ]
613 | },
614 | "execution_count": 40,
615 | "metadata": {},
616 | "output_type": "execute_result"
617 | }
618 | ],
619 | "source": [
620 | "my_map(lambda x: x**2, lst)"
621 | ]
622 | },
623 | {
624 | "cell_type": "code",
625 | "execution_count": 41,
626 | "id": "adjustable-visibility",
627 | "metadata": {},
628 | "outputs": [],
629 | "source": [
630 | "lst2 = ['Hello', 'World!']"
631 | ]
632 | },
633 | {
634 | "cell_type": "code",
635 | "execution_count": 42,
636 | "id": "contrary-raising",
637 | "metadata": {},
638 | "outputs": [
639 | {
640 | "data": {
641 | "text/plain": [
642 | "['HELLO', 'WORLD!']"
643 | ]
644 | },
645 | "execution_count": 42,
646 | "metadata": {},
647 | "output_type": "execute_result"
648 | }
649 | ],
650 | "source": [
651 | "list(map(lambda s: s.upper(), lst2))"
652 | ]
653 | },
654 | {
655 | "cell_type": "code",
656 | "execution_count": 43,
657 | "id": "suited-specification",
658 | "metadata": {},
659 | "outputs": [],
660 | "source": [
661 | "lst3 = [-3, -2, -1, 1, 2, 3]"
662 | ]
663 | },
664 | {
665 | "cell_type": "code",
666 | "execution_count": 44,
667 | "id": "elegant-collect",
668 | "metadata": {},
669 | "outputs": [
670 | {
671 | "data": {
672 | "text/plain": [
673 | "[2, 3]"
674 | ]
675 | },
676 | "execution_count": 44,
677 | "metadata": {},
678 | "output_type": "execute_result"
679 | }
680 | ],
681 | "source": [
682 | "list(filter(lambda x: x > 1, lst3))"
683 | ]
684 | },
685 | {
686 | "cell_type": "code",
687 | "execution_count": 45,
688 | "id": "marked-spirit",
689 | "metadata": {},
690 | "outputs": [
691 | {
692 | "data": {
693 | "text/plain": [
694 | "[4, 9]"
695 | ]
696 | },
697 | "execution_count": 45,
698 | "metadata": {},
699 | "output_type": "execute_result"
700 | }
701 | ],
702 | "source": [
703 | "list(map(sqr, filter(lambda x: x > 1, lst3)))"
704 | ]
705 | },
706 | {
707 | "cell_type": "code",
708 | "execution_count": 46,
709 | "id": "opposite-vehicle",
710 | "metadata": {},
711 | "outputs": [
712 | {
713 | "data": {
714 | "text/plain": [
715 | "[-3, -2, -1, 1, 2, 3]"
716 | ]
717 | },
718 | "execution_count": 46,
719 | "metadata": {},
720 | "output_type": "execute_result"
721 | }
722 | ],
723 | "source": [
724 | "[ item for item in lst3 ]"
725 | ]
726 | },
727 | {
728 | "cell_type": "code",
729 | "execution_count": 49,
730 | "id": "least-lecture",
731 | "metadata": {},
732 | "outputs": [
733 | {
734 | "data": {
735 | "text/plain": [
736 | "[4, 9]"
737 | ]
738 | },
739 | "execution_count": 49,
740 | "metadata": {},
741 | "output_type": "execute_result"
742 | }
743 | ],
744 | "source": [
745 | "[ sqr(item) for item in lst3 if item > 1 ]"
746 | ]
747 | },
748 | {
749 | "cell_type": "code",
750 | "execution_count": 50,
751 | "id": "silver-allergy",
752 | "metadata": {},
753 | "outputs": [],
754 | "source": [
755 | "it = iter(lst3)"
756 | ]
757 | },
758 | {
759 | "cell_type": "code",
760 | "execution_count": 51,
761 | "id": "textile-reflection",
762 | "metadata": {},
763 | "outputs": [
764 | {
765 | "data": {
766 | "text/plain": [
767 | ""
768 | ]
769 | },
770 | "execution_count": 51,
771 | "metadata": {},
772 | "output_type": "execute_result"
773 | }
774 | ],
775 | "source": [
776 | "it"
777 | ]
778 | },
779 | {
780 | "cell_type": "code",
781 | "execution_count": 53,
782 | "id": "incorporated-somewhere",
783 | "metadata": {},
784 | "outputs": [
785 | {
786 | "data": {
787 | "text/plain": [
788 | "-3"
789 | ]
790 | },
791 | "execution_count": 53,
792 | "metadata": {},
793 | "output_type": "execute_result"
794 | }
795 | ],
796 | "source": [
797 | "next(it)"
798 | ]
799 | },
800 | {
801 | "cell_type": "code",
802 | "execution_count": 59,
803 | "id": "ahead-segment",
804 | "metadata": {},
805 | "outputs": [
806 | {
807 | "ename": "StopIteration",
808 | "evalue": "",
809 | "output_type": "error",
810 | "traceback": [
811 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
812 | "\u001b[0;31mStopIteration\u001b[0m Traceback (most recent call last)",
813 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mnext\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mit\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
814 | "\u001b[0;31mStopIteration\u001b[0m: "
815 | ]
816 | }
817 | ],
818 | "source": [
819 | "next(it)"
820 | ]
821 | },
822 | {
823 | "cell_type": "code",
824 | "execution_count": 60,
825 | "id": "emerging-tract",
826 | "metadata": {},
827 | "outputs": [],
828 | "source": [
829 | "def my_map(func, seq):\n",
830 | " ret = []\n",
831 | " for item in seq:\n",
832 | " ret.append(func(item))\n",
833 | " return ret"
834 | ]
835 | },
836 | {
837 | "cell_type": "code",
838 | "execution_count": 61,
839 | "id": "colonial-nature",
840 | "metadata": {},
841 | "outputs": [
842 | {
843 | "data": {
844 | "text/plain": [
845 | "[1, 4, 9, 16]"
846 | ]
847 | },
848 | "execution_count": 61,
849 | "metadata": {},
850 | "output_type": "execute_result"
851 | }
852 | ],
853 | "source": [
854 | "my_map(lambda x: x**2, lst)"
855 | ]
856 | },
857 | {
858 | "cell_type": "code",
859 | "execution_count": 62,
860 | "id": "mediterranean-tsunami",
861 | "metadata": {},
862 | "outputs": [],
863 | "source": [
864 | "def my_map(func, seq):\n",
865 | " for item in seq:\n",
866 | " yield func(item)"
867 | ]
868 | },
869 | {
870 | "cell_type": "code",
871 | "execution_count": 63,
872 | "id": "specific-flower",
873 | "metadata": {},
874 | "outputs": [
875 | {
876 | "data": {
877 | "text/plain": [
878 | ""
879 | ]
880 | },
881 | "execution_count": 63,
882 | "metadata": {},
883 | "output_type": "execute_result"
884 | }
885 | ],
886 | "source": [
887 | "my_map(lambda x: x**2, lst)"
888 | ]
889 | },
890 | {
891 | "cell_type": "code",
892 | "execution_count": 64,
893 | "id": "public-pharmacy",
894 | "metadata": {},
895 | "outputs": [
896 | {
897 | "data": {
898 | "text/plain": [
899 | "[1, 4, 9, 16]"
900 | ]
901 | },
902 | "execution_count": 64,
903 | "metadata": {},
904 | "output_type": "execute_result"
905 | }
906 | ],
907 | "source": [
908 | "list(my_map(lambda x: x**2, lst))"
909 | ]
910 | },
911 | {
912 | "cell_type": "code",
913 | "execution_count": 65,
914 | "id": "lesbian-crash",
915 | "metadata": {},
916 | "outputs": [
917 | {
918 | "name": "stdout",
919 | "output_type": "stream",
920 | "text": [
921 | "1\n",
922 | "4\n",
923 | "9\n",
924 | "16\n"
925 | ]
926 | }
927 | ],
928 | "source": [
929 | "for i in my_map(lambda x: x**2, lst):\n",
930 | " print(i)"
931 | ]
932 | },
933 | {
934 | "cell_type": "code",
935 | "execution_count": 66,
936 | "id": "joined-chuck",
937 | "metadata": {},
938 | "outputs": [
939 | {
940 | "data": {
941 | "text/plain": [
942 | " at 0x7f0470399bf8>"
943 | ]
944 | },
945 | "execution_count": 66,
946 | "metadata": {},
947 | "output_type": "execute_result"
948 | }
949 | ],
950 | "source": [
951 | "( sqr(item) for item in lst3 if item > 1 )"
952 | ]
953 | },
954 | {
955 | "cell_type": "code",
956 | "execution_count": 67,
957 | "id": "induced-doctrine",
958 | "metadata": {},
959 | "outputs": [
960 | {
961 | "data": {
962 | "text/plain": [
963 | "[4, 9]"
964 | ]
965 | },
966 | "execution_count": 67,
967 | "metadata": {},
968 | "output_type": "execute_result"
969 | }
970 | ],
971 | "source": [
972 | "list( sqr(item) for item in lst3 if item > 1 )"
973 | ]
974 | },
975 | {
976 | "cell_type": "code",
977 | "execution_count": 68,
978 | "id": "pressing-relationship",
979 | "metadata": {},
980 | "outputs": [],
981 | "source": [
982 | "gen1 = ( sqr(item) for item in lst3 if item > 1 )"
983 | ]
984 | },
985 | {
986 | "cell_type": "code",
987 | "execution_count": 69,
988 | "id": "ignored-boulder",
989 | "metadata": {},
990 | "outputs": [
991 | {
992 | "data": {
993 | "text/plain": [
994 | "4"
995 | ]
996 | },
997 | "execution_count": 69,
998 | "metadata": {},
999 | "output_type": "execute_result"
1000 | }
1001 | ],
1002 | "source": [
1003 | "next(gen1)"
1004 | ]
1005 | },
1006 | {
1007 | "cell_type": "code",
1008 | "execution_count": 70,
1009 | "id": "future-bleeding",
1010 | "metadata": {},
1011 | "outputs": [
1012 | {
1013 | "data": {
1014 | "text/plain": [
1015 | "9"
1016 | ]
1017 | },
1018 | "execution_count": 70,
1019 | "metadata": {},
1020 | "output_type": "execute_result"
1021 | }
1022 | ],
1023 | "source": [
1024 | "next(gen1)"
1025 | ]
1026 | },
1027 | {
1028 | "cell_type": "code",
1029 | "execution_count": 71,
1030 | "id": "stock-tension",
1031 | "metadata": {},
1032 | "outputs": [
1033 | {
1034 | "ename": "StopIteration",
1035 | "evalue": "",
1036 | "output_type": "error",
1037 | "traceback": [
1038 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
1039 | "\u001b[0;31mStopIteration\u001b[0m Traceback (most recent call last)",
1040 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mnext\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mgen1\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
1041 | "\u001b[0;31mStopIteration\u001b[0m: "
1042 | ]
1043 | }
1044 | ],
1045 | "source": [
1046 | "next(gen1)"
1047 | ]
1048 | },
1049 | {
1050 | "cell_type": "code",
1051 | "execution_count": 73,
1052 | "id": "partial-retirement",
1053 | "metadata": {},
1054 | "outputs": [
1055 | {
1056 | "name": "stdout",
1057 | "output_type": "stream",
1058 | "text": [
1059 | "0 -3\n",
1060 | "1 -2\n",
1061 | "2 -1\n",
1062 | "3 1\n",
1063 | "4 2\n",
1064 | "5 3\n"
1065 | ]
1066 | }
1067 | ],
1068 | "source": [
1069 | "for no, i in enumerate(lst3):\n",
1070 | " print(no, i)"
1071 | ]
1072 | },
1073 | {
1074 | "cell_type": "code",
1075 | "execution_count": 74,
1076 | "id": "happy-hampshire",
1077 | "metadata": {},
1078 | "outputs": [],
1079 | "source": [
1080 | "def my_enumerate(seq):\n",
1081 | " n = 0\n",
1082 | " for item in seq:\n",
1083 | " yield n, item\n",
1084 | " n += 1"
1085 | ]
1086 | },
1087 | {
1088 | "cell_type": "code",
1089 | "execution_count": 75,
1090 | "id": "discrete-albert",
1091 | "metadata": {},
1092 | "outputs": [
1093 | {
1094 | "name": "stdout",
1095 | "output_type": "stream",
1096 | "text": [
1097 | "0 -3\n",
1098 | "1 -2\n",
1099 | "2 -1\n",
1100 | "3 1\n",
1101 | "4 2\n",
1102 | "5 3\n"
1103 | ]
1104 | }
1105 | ],
1106 | "source": [
1107 | "for no, i in my_enumerate(lst3):\n",
1108 | " print(no, i)"
1109 | ]
1110 | },
1111 | {
1112 | "cell_type": "code",
1113 | "execution_count": 76,
1114 | "id": "rural-apache",
1115 | "metadata": {},
1116 | "outputs": [
1117 | {
1118 | "name": "stdout",
1119 | "output_type": "stream",
1120 | "text": [
1121 | "No way!\n",
1122 | "must be str, not int\n"
1123 | ]
1124 | }
1125 | ],
1126 | "source": [
1127 | "try:\n",
1128 | " 'str' + 1\n",
1129 | "except TypeError as e:\n",
1130 | " print('No way!')\n",
1131 | " print(e)"
1132 | ]
1133 | },
1134 | {
1135 | "cell_type": "code",
1136 | "execution_count": 77,
1137 | "id": "balanced-keyboard",
1138 | "metadata": {},
1139 | "outputs": [
1140 | {
1141 | "ename": "TypeError",
1142 | "evalue": "My TypeError message",
1143 | "output_type": "error",
1144 | "traceback": [
1145 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
1146 | "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
1147 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mTypeError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'My TypeError message'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
1148 | "\u001b[0;31mTypeError\u001b[0m: My TypeError message"
1149 | ]
1150 | }
1151 | ],
1152 | "source": [
1153 | "raise TypeError('My TypeError message')"
1154 | ]
1155 | },
1156 | {
1157 | "cell_type": "code",
1158 | "execution_count": null,
1159 | "id": "velvet-great",
1160 | "metadata": {},
1161 | "outputs": [],
1162 | "source": []
1163 | }
1164 | ],
1165 | "metadata": {
1166 | "kernelspec": {
1167 | "display_name": "Python 3.6.9 64-bit ('skj': venv)",
1168 | "language": "python",
1169 | "name": "python36964bitskjvenv37e9edb2b84c40b4aecebea1eb80b141"
1170 | },
1171 | "language_info": {
1172 | "codemirror_mode": {
1173 | "name": "ipython",
1174 | "version": 3
1175 | },
1176 | "file_extension": ".py",
1177 | "mimetype": "text/x-python",
1178 | "name": "python",
1179 | "nbconvert_exporter": "python",
1180 | "pygments_lexer": "ipython3",
1181 | "version": "3.6.9"
1182 | }
1183 | },
1184 | "nbformat": 4,
1185 | "nbformat_minor": 5
1186 | }
1187 |
--------------------------------------------------------------------------------
/notebooks/lecture_01.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Introduction to the Scripting Programming Languages and Their Applications (SPJA) Course"
8 | ]
9 | },
10 | {
11 | "cell_type": "markdown",
12 | "metadata": {},
13 | "source": [
14 | "In this Jupyter Notebook, we'll cover basics of Python programming language as is coverd during the first lecture."
15 | ]
16 | },
17 | {
18 | "cell_type": "markdown",
19 | "metadata": {},
20 | "source": [
21 | "As it's usual in any programming language tutorial, we'll start with the famous 'Hello, World!'"
22 | ]
23 | },
24 | {
25 | "cell_type": "code",
26 | "execution_count": 1,
27 | "metadata": {},
28 | "outputs": [
29 | {
30 | "name": "stdout",
31 | "output_type": "stream",
32 | "text": [
33 | "Hello, World!\n"
34 | ]
35 | }
36 | ],
37 | "source": [
38 | "print('Hello, World!')"
39 | ]
40 | },
41 | {
42 | "cell_type": "markdown",
43 | "metadata": {},
44 | "source": [
45 | "### Let's play with numbers"
46 | ]
47 | },
48 | {
49 | "cell_type": "code",
50 | "execution_count": 2,
51 | "metadata": {},
52 | "outputs": [
53 | {
54 | "data": {
55 | "text/plain": [
56 | "3"
57 | ]
58 | },
59 | "execution_count": 2,
60 | "metadata": {},
61 | "output_type": "execute_result"
62 | }
63 | ],
64 | "source": [
65 | "1 + 2"
66 | ]
67 | },
68 | {
69 | "cell_type": "code",
70 | "execution_count": 3,
71 | "metadata": {},
72 | "outputs": [
73 | {
74 | "data": {
75 | "text/plain": [
76 | "12"
77 | ]
78 | },
79 | "execution_count": 3,
80 | "metadata": {},
81 | "output_type": "execute_result"
82 | }
83 | ],
84 | "source": [
85 | "3 * 4"
86 | ]
87 | },
88 | {
89 | "cell_type": "code",
90 | "execution_count": 4,
91 | "metadata": {},
92 | "outputs": [
93 | {
94 | "data": {
95 | "text/plain": [
96 | "0.75"
97 | ]
98 | },
99 | "execution_count": 4,
100 | "metadata": {},
101 | "output_type": "execute_result"
102 | }
103 | ],
104 | "source": [
105 | "3 / 4"
106 | ]
107 | },
108 | {
109 | "cell_type": "code",
110 | "execution_count": 5,
111 | "metadata": {},
112 | "outputs": [
113 | {
114 | "data": {
115 | "text/plain": [
116 | "3"
117 | ]
118 | },
119 | "execution_count": 5,
120 | "metadata": {},
121 | "output_type": "execute_result"
122 | }
123 | ],
124 | "source": [
125 | "3 % 4"
126 | ]
127 | },
128 | {
129 | "cell_type": "code",
130 | "execution_count": 6,
131 | "metadata": {},
132 | "outputs": [
133 | {
134 | "data": {
135 | "text/plain": [
136 | "0"
137 | ]
138 | },
139 | "execution_count": 6,
140 | "metadata": {},
141 | "output_type": "execute_result"
142 | }
143 | ],
144 | "source": [
145 | "3 // 4"
146 | ]
147 | },
148 | {
149 | "cell_type": "code",
150 | "execution_count": 7,
151 | "metadata": {},
152 | "outputs": [
153 | {
154 | "data": {
155 | "text/plain": [
156 | "8"
157 | ]
158 | },
159 | "execution_count": 7,
160 | "metadata": {},
161 | "output_type": "execute_result"
162 | }
163 | ],
164 | "source": [
165 | "2 ** 3"
166 | ]
167 | },
168 | {
169 | "cell_type": "markdown",
170 | "metadata": {},
171 | "source": [
172 | "#### Big integets are for free :-)"
173 | ]
174 | },
175 | {
176 | "cell_type": "code",
177 | "execution_count": 8,
178 | "metadata": {},
179 | "outputs": [
180 | {
181 | "data": {
182 | "text/plain": [
183 | "1524157869227296232586103878620885370592631183396989512763506883943081346741239028441332953091425973418270460159528674514565994178959355909517622796067319546096882122520651426"
184 | ]
185 | },
186 | "execution_count": 8,
187 | "metadata": {},
188 | "output_type": "execute_result"
189 | }
190 | ],
191 | "source": [
192 | "1234567898765432123456789098765432456787654323456789878909876543432345678987654323456789876543231234567 \\\n",
193 | "* \\\n",
194 | "1234567876543245676789878989089098765432345678976543212345678987654345678"
195 | ]
196 | },
197 | {
198 | "cell_type": "code",
199 | "execution_count": 9,
200 | "metadata": {},
201 | "outputs": [],
202 | "source": [
203 | "a = 1"
204 | ]
205 | },
206 | {
207 | "cell_type": "markdown",
208 | "metadata": {},
209 | "source": [
210 | "#### All variables have a corresponding type!"
211 | ]
212 | },
213 | {
214 | "cell_type": "code",
215 | "execution_count": 10,
216 | "metadata": {},
217 | "outputs": [
218 | {
219 | "data": {
220 | "text/plain": [
221 | "int"
222 | ]
223 | },
224 | "execution_count": 10,
225 | "metadata": {},
226 | "output_type": "execute_result"
227 | }
228 | ],
229 | "source": [
230 | "type(a)"
231 | ]
232 | },
233 | {
234 | "cell_type": "markdown",
235 | "metadata": {},
236 | "source": [
237 | "#### Create a new `float` variable from an `int`"
238 | ]
239 | },
240 | {
241 | "cell_type": "code",
242 | "execution_count": 11,
243 | "metadata": {},
244 | "outputs": [],
245 | "source": [
246 | "a = float(a)"
247 | ]
248 | },
249 | {
250 | "cell_type": "code",
251 | "execution_count": 12,
252 | "metadata": {},
253 | "outputs": [
254 | {
255 | "data": {
256 | "text/plain": [
257 | "float"
258 | ]
259 | },
260 | "execution_count": 12,
261 | "metadata": {},
262 | "output_type": "execute_result"
263 | }
264 | ],
265 | "source": [
266 | "type(a)"
267 | ]
268 | },
269 | {
270 | "cell_type": "code",
271 | "execution_count": 13,
272 | "metadata": {},
273 | "outputs": [],
274 | "source": [
275 | "b = 1.5"
276 | ]
277 | },
278 | {
279 | "cell_type": "code",
280 | "execution_count": 14,
281 | "metadata": {},
282 | "outputs": [],
283 | "source": [
284 | "a = int(b)"
285 | ]
286 | },
287 | {
288 | "cell_type": "markdown",
289 | "metadata": {},
290 | "source": [
291 | "We can also simply convert string containing a numer to an integer or float datatype."
292 | ]
293 | },
294 | {
295 | "cell_type": "code",
296 | "execution_count": 15,
297 | "metadata": {},
298 | "outputs": [],
299 | "source": [
300 | "c = int('123')"
301 | ]
302 | },
303 | {
304 | "cell_type": "code",
305 | "execution_count": 16,
306 | "metadata": {},
307 | "outputs": [
308 | {
309 | "data": {
310 | "text/plain": [
311 | "int"
312 | ]
313 | },
314 | "execution_count": 16,
315 | "metadata": {},
316 | "output_type": "execute_result"
317 | }
318 | ],
319 | "source": [
320 | "type(c)"
321 | ]
322 | },
323 | {
324 | "cell_type": "code",
325 | "execution_count": 17,
326 | "metadata": {},
327 | "outputs": [],
328 | "source": [
329 | "d = float('123.456')"
330 | ]
331 | },
332 | {
333 | "cell_type": "code",
334 | "execution_count": 18,
335 | "metadata": {},
336 | "outputs": [
337 | {
338 | "data": {
339 | "text/plain": [
340 | "float"
341 | ]
342 | },
343 | "execution_count": 18,
344 | "metadata": {},
345 | "output_type": "execute_result"
346 | }
347 | ],
348 | "source": [
349 | "type(d)"
350 | ]
351 | },
352 | {
353 | "cell_type": "markdown",
354 | "metadata": {},
355 | "source": [
356 | "### Strings"
357 | ]
358 | },
359 | {
360 | "cell_type": "markdown",
361 | "metadata": {},
362 | "source": [
363 | "We can create strings in two ways: (i) single line strings, (ii) multiline strings. Each string can be enclosed using \" or ' specifier."
364 | ]
365 | },
366 | {
367 | "cell_type": "markdown",
368 | "metadata": {},
369 | "source": [
370 | "#### Single Line Strings"
371 | ]
372 | },
373 | {
374 | "cell_type": "code",
375 | "execution_count": 19,
376 | "metadata": {},
377 | "outputs": [],
378 | "source": [
379 | "s = 'Google'"
380 | ]
381 | },
382 | {
383 | "cell_type": "code",
384 | "execution_count": 20,
385 | "metadata": {},
386 | "outputs": [
387 | {
388 | "data": {
389 | "text/plain": [
390 | "'Google'"
391 | ]
392 | },
393 | "execution_count": 20,
394 | "metadata": {},
395 | "output_type": "execute_result"
396 | }
397 | ],
398 | "source": [
399 | "s"
400 | ]
401 | },
402 | {
403 | "cell_type": "code",
404 | "execution_count": 21,
405 | "metadata": {},
406 | "outputs": [],
407 | "source": [
408 | "s = \"Google\""
409 | ]
410 | },
411 | {
412 | "cell_type": "code",
413 | "execution_count": 22,
414 | "metadata": {},
415 | "outputs": [
416 | {
417 | "data": {
418 | "text/plain": [
419 | "'Google'"
420 | ]
421 | },
422 | "execution_count": 22,
423 | "metadata": {},
424 | "output_type": "execute_result"
425 | }
426 | ],
427 | "source": [
428 | "s"
429 | ]
430 | },
431 | {
432 | "cell_type": "markdown",
433 | "metadata": {},
434 | "source": [
435 | "As you can see, if you use \" and want do describe, for example, HTML then you need to escape inner \" characters. However, if you use ' character to enclose strings, you can embed HTML very easily without escaping."
436 | ]
437 | },
438 | {
439 | "cell_type": "markdown",
440 | "metadata": {},
441 | "source": [
442 | "Let's use len function fo get length of the string"
443 | ]
444 | },
445 | {
446 | "cell_type": "code",
447 | "execution_count": 23,
448 | "metadata": {},
449 | "outputs": [
450 | {
451 | "data": {
452 | "text/plain": [
453 | "35"
454 | ]
455 | },
456 | "execution_count": 23,
457 | "metadata": {},
458 | "output_type": "execute_result"
459 | }
460 | ],
461 | "source": [
462 | "len(s)"
463 | ]
464 | },
465 | {
466 | "cell_type": "markdown",
467 | "metadata": {},
468 | "source": [
469 | "#### Get a substring using slicing (works also on `list` and `tuple` collections)"
470 | ]
471 | },
472 | {
473 | "cell_type": "code",
474 | "execution_count": 24,
475 | "metadata": {},
476 | "outputs": [],
477 | "source": [
478 | "s = 'Hello, World!'"
479 | ]
480 | },
481 | {
482 | "cell_type": "code",
483 | "execution_count": 25,
484 | "metadata": {},
485 | "outputs": [
486 | {
487 | "data": {
488 | "text/plain": [
489 | "' Wor'"
490 | ]
491 | },
492 | "execution_count": 25,
493 | "metadata": {},
494 | "output_type": "execute_result"
495 | }
496 | ],
497 | "source": [
498 | "s[6:10]"
499 | ]
500 | },
501 | {
502 | "cell_type": "code",
503 | "execution_count": 26,
504 | "metadata": {},
505 | "outputs": [
506 | {
507 | "data": {
508 | "text/plain": [
509 | "'Hello'"
510 | ]
511 | },
512 | "execution_count": 26,
513 | "metadata": {},
514 | "output_type": "execute_result"
515 | }
516 | ],
517 | "source": [
518 | "s[:5]"
519 | ]
520 | },
521 | {
522 | "cell_type": "markdown",
523 | "metadata": {},
524 | "source": [
525 | "We can split a string"
526 | ]
527 | },
528 | {
529 | "cell_type": "code",
530 | "execution_count": 27,
531 | "metadata": {},
532 | "outputs": [
533 | {
534 | "data": {
535 | "text/plain": [
536 | "['Hello,', 'World!']"
537 | ]
538 | },
539 | "execution_count": 27,
540 | "metadata": {},
541 | "output_type": "execute_result"
542 | }
543 | ],
544 | "source": [
545 | "s.split(' ')"
546 | ]
547 | },
548 | {
549 | "cell_type": "markdown",
550 | "metadata": {},
551 | "source": [
552 | "### Lists"
553 | ]
554 | },
555 | {
556 | "cell_type": "code",
557 | "execution_count": 28,
558 | "metadata": {},
559 | "outputs": [],
560 | "source": [
561 | "l = [1, 2, 3.14, 'Hello']"
562 | ]
563 | },
564 | {
565 | "cell_type": "markdown",
566 | "metadata": {},
567 | "source": [
568 | "#### Get length of the list"
569 | ]
570 | },
571 | {
572 | "cell_type": "code",
573 | "execution_count": 29,
574 | "metadata": {},
575 | "outputs": [
576 | {
577 | "data": {
578 | "text/plain": [
579 | "4"
580 | ]
581 | },
582 | "execution_count": 29,
583 | "metadata": {},
584 | "output_type": "execute_result"
585 | }
586 | ],
587 | "source": [
588 | "len(l)"
589 | ]
590 | },
591 | {
592 | "cell_type": "markdown",
593 | "metadata": {},
594 | "source": [
595 | "Append new items"
596 | ]
597 | },
598 | {
599 | "cell_type": "code",
600 | "execution_count": 30,
601 | "metadata": {},
602 | "outputs": [],
603 | "source": [
604 | "l.append(-10)"
605 | ]
606 | },
607 | {
608 | "cell_type": "code",
609 | "execution_count": 31,
610 | "metadata": {},
611 | "outputs": [
612 | {
613 | "data": {
614 | "text/plain": [
615 | "5"
616 | ]
617 | },
618 | "execution_count": 31,
619 | "metadata": {},
620 | "output_type": "execute_result"
621 | }
622 | ],
623 | "source": [
624 | "len(l)"
625 | ]
626 | },
627 | {
628 | "cell_type": "markdown",
629 | "metadata": {},
630 | "source": [
631 | "#### Let's modify an element of a list"
632 | ]
633 | },
634 | {
635 | "cell_type": "code",
636 | "execution_count": 32,
637 | "metadata": {},
638 | "outputs": [
639 | {
640 | "data": {
641 | "text/plain": [
642 | "[1, 2, 3.14, 'Hello', -10]"
643 | ]
644 | },
645 | "execution_count": 32,
646 | "metadata": {},
647 | "output_type": "execute_result"
648 | }
649 | ],
650 | "source": [
651 | "l"
652 | ]
653 | },
654 | {
655 | "cell_type": "code",
656 | "execution_count": 33,
657 | "metadata": {},
658 | "outputs": [],
659 | "source": [
660 | "l[0] = 6"
661 | ]
662 | },
663 | {
664 | "cell_type": "code",
665 | "execution_count": 34,
666 | "metadata": {},
667 | "outputs": [
668 | {
669 | "data": {
670 | "text/plain": [
671 | "[6, 2, 3.14, 'Hello', -10]"
672 | ]
673 | },
674 | "execution_count": 34,
675 | "metadata": {},
676 | "output_type": "execute_result"
677 | }
678 | ],
679 | "source": [
680 | "l"
681 | ]
682 | },
683 | {
684 | "cell_type": "markdown",
685 | "metadata": {},
686 | "source": [
687 | "#### Slicing a list"
688 | ]
689 | },
690 | {
691 | "cell_type": "code",
692 | "execution_count": 35,
693 | "metadata": {},
694 | "outputs": [
695 | {
696 | "data": {
697 | "text/plain": [
698 | "[2, 3.14]"
699 | ]
700 | },
701 | "execution_count": 35,
702 | "metadata": {},
703 | "output_type": "execute_result"
704 | }
705 | ],
706 | "source": [
707 | "l[1:3]"
708 | ]
709 | },
710 | {
711 | "cell_type": "code",
712 | "execution_count": 36,
713 | "metadata": {},
714 | "outputs": [
715 | {
716 | "data": {
717 | "text/plain": [
718 | "[6, 2, 3.14]"
719 | ]
720 | },
721 | "execution_count": 36,
722 | "metadata": {},
723 | "output_type": "execute_result"
724 | }
725 | ],
726 | "source": [
727 | "l[:3]"
728 | ]
729 | },
730 | {
731 | "cell_type": "code",
732 | "execution_count": 37,
733 | "metadata": {},
734 | "outputs": [
735 | {
736 | "data": {
737 | "text/plain": [
738 | "[2, 3.14, 'Hello', -10]"
739 | ]
740 | },
741 | "execution_count": 37,
742 | "metadata": {},
743 | "output_type": "execute_result"
744 | }
745 | ],
746 | "source": [
747 | "l[1:]"
748 | ]
749 | },
750 | {
751 | "cell_type": "code",
752 | "execution_count": 38,
753 | "metadata": {},
754 | "outputs": [
755 | {
756 | "data": {
757 | "text/plain": [
758 | "[-10, 'Hello']"
759 | ]
760 | },
761 | "execution_count": 38,
762 | "metadata": {},
763 | "output_type": "execute_result"
764 | }
765 | ],
766 | "source": [
767 | "l[4:2:-1]"
768 | ]
769 | },
770 | {
771 | "cell_type": "markdown",
772 | "metadata": {},
773 | "source": [
774 | "### Tuples"
775 | ]
776 | },
777 | {
778 | "cell_type": "markdown",
779 | "metadata": {},
780 | "source": [
781 | "Tuples are immutable"
782 | ]
783 | },
784 | {
785 | "cell_type": "code",
786 | "execution_count": 39,
787 | "metadata": {},
788 | "outputs": [],
789 | "source": [
790 | "t = (1, 2, 3.14)"
791 | ]
792 | },
793 | {
794 | "cell_type": "code",
795 | "execution_count": 40,
796 | "metadata": {},
797 | "outputs": [
798 | {
799 | "data": {
800 | "text/plain": [
801 | "3"
802 | ]
803 | },
804 | "execution_count": 40,
805 | "metadata": {},
806 | "output_type": "execute_result"
807 | }
808 | ],
809 | "source": [
810 | "len(t)"
811 | ]
812 | },
813 | {
814 | "cell_type": "markdown",
815 | "metadata": {},
816 | "source": [
817 | "We can't modify a tuple"
818 | ]
819 | },
820 | {
821 | "cell_type": "code",
822 | "execution_count": 41,
823 | "metadata": {},
824 | "outputs": [
825 | {
826 | "ename": "TypeError",
827 | "evalue": "'tuple' object does not support item assignment",
828 | "output_type": "error",
829 | "traceback": [
830 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
831 | "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
832 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mt\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m6\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
833 | "\u001b[0;31mTypeError\u001b[0m: 'tuple' object does not support item assignment"
834 | ]
835 | }
836 | ],
837 | "source": [
838 | "t[0] = 6"
839 | ]
840 | },
841 | {
842 | "cell_type": "markdown",
843 | "metadata": {},
844 | "source": [
845 | "We obtained and exception that says we cannot assign a new value to the tuple"
846 | ]
847 | },
848 | {
849 | "cell_type": "markdown",
850 | "metadata": {},
851 | "source": [
852 | "**We can get a new list from tuple**"
853 | ]
854 | },
855 | {
856 | "cell_type": "code",
857 | "execution_count": 42,
858 | "metadata": {},
859 | "outputs": [
860 | {
861 | "data": {
862 | "text/plain": [
863 | "[1, 2, 3.14]"
864 | ]
865 | },
866 | "execution_count": 42,
867 | "metadata": {},
868 | "output_type": "execute_result"
869 | }
870 | ],
871 | "source": [
872 | "list(t)"
873 | ]
874 | },
875 | {
876 | "cell_type": "markdown",
877 | "metadata": {},
878 | "source": [
879 | "Slicing may be used in the same way as in lists or strings"
880 | ]
881 | },
882 | {
883 | "cell_type": "code",
884 | "execution_count": 43,
885 | "metadata": {},
886 | "outputs": [
887 | {
888 | "data": {
889 | "text/plain": [
890 | "(2, 3.14)"
891 | ]
892 | },
893 | "execution_count": 43,
894 | "metadata": {},
895 | "output_type": "execute_result"
896 | }
897 | ],
898 | "source": [
899 | "t[1:3]"
900 | ]
901 | },
902 | {
903 | "cell_type": "markdown",
904 | "metadata": {},
905 | "source": [
906 | "### For Loop"
907 | ]
908 | },
909 | {
910 | "cell_type": "markdown",
911 | "metadata": {},
912 | "source": [
913 | "For loops are essentialy for each loops."
914 | ]
915 | },
916 | {
917 | "cell_type": "code",
918 | "execution_count": 44,
919 | "metadata": {},
920 | "outputs": [
921 | {
922 | "name": "stdout",
923 | "output_type": "stream",
924 | "text": [
925 | "6\n",
926 | "2\n",
927 | "3.14\n",
928 | "Hello\n",
929 | "-10\n"
930 | ]
931 | }
932 | ],
933 | "source": [
934 | "for item in l:\n",
935 | " print(item)"
936 | ]
937 | },
938 | {
939 | "cell_type": "markdown",
940 | "metadata": {},
941 | "source": [
942 | "**Let's square each item in a list**"
943 | ]
944 | },
945 | {
946 | "cell_type": "code",
947 | "execution_count": 45,
948 | "metadata": {},
949 | "outputs": [
950 | {
951 | "name": "stdout",
952 | "output_type": "stream",
953 | "text": [
954 | "1\n",
955 | "4\n",
956 | "9\n",
957 | "16\n"
958 | ]
959 | }
960 | ],
961 | "source": [
962 | "for item in [1, 2, 3, 4]:\n",
963 | " print(item**2)"
964 | ]
965 | },
966 | {
967 | "cell_type": "markdown",
968 | "metadata": {},
969 | "source": [
970 | "### While Loop"
971 | ]
972 | },
973 | {
974 | "cell_type": "code",
975 | "execution_count": 46,
976 | "metadata": {},
977 | "outputs": [
978 | {
979 | "name": "stdout",
980 | "output_type": "stream",
981 | "text": [
982 | "10\n",
983 | "9\n",
984 | "8\n",
985 | "7\n",
986 | "6\n",
987 | "5\n",
988 | "4\n",
989 | "3\n",
990 | "2\n",
991 | "1\n"
992 | ]
993 | }
994 | ],
995 | "source": [
996 | "n = 10\n",
997 | "while n > 0:\n",
998 | " print(n)\n",
999 | " n -= 1"
1000 | ]
1001 | },
1002 | {
1003 | "cell_type": "markdown",
1004 | "metadata": {},
1005 | "source": [
1006 | "### Functions\n",
1007 | "\n",
1008 | "Functions don't have return types and parameters also don't have types specified.\n",
1009 | "Function that doesn't return anything returns `None`."
1010 | ]
1011 | },
1012 | {
1013 | "cell_type": "code",
1014 | "execution_count": 47,
1015 | "metadata": {},
1016 | "outputs": [],
1017 | "source": [
1018 | "def f(a, b):\n",
1019 | " return a + b"
1020 | ]
1021 | },
1022 | {
1023 | "cell_type": "code",
1024 | "execution_count": 48,
1025 | "metadata": {},
1026 | "outputs": [
1027 | {
1028 | "data": {
1029 | "text/plain": [
1030 | "3"
1031 | ]
1032 | },
1033 | "execution_count": 48,
1034 | "metadata": {},
1035 | "output_type": "execute_result"
1036 | }
1037 | ],
1038 | "source": [
1039 | "f(1, 2)"
1040 | ]
1041 | },
1042 | {
1043 | "cell_type": "code",
1044 | "execution_count": 49,
1045 | "metadata": {},
1046 | "outputs": [
1047 | {
1048 | "data": {
1049 | "text/plain": [
1050 | "[1, 2, 3, 4, 5]"
1051 | ]
1052 | },
1053 | "execution_count": 49,
1054 | "metadata": {},
1055 | "output_type": "execute_result"
1056 | }
1057 | ],
1058 | "source": [
1059 | "f([1, 2], [3, 4, 5])"
1060 | ]
1061 | },
1062 | {
1063 | "cell_type": "markdown",
1064 | "metadata": {},
1065 | "source": [
1066 | "We cannot add incompatible types"
1067 | ]
1068 | },
1069 | {
1070 | "cell_type": "code",
1071 | "execution_count": 50,
1072 | "metadata": {},
1073 | "outputs": [
1074 | {
1075 | "ename": "TypeError",
1076 | "evalue": "unsupported operand type(s) for +: 'int' and 'str'",
1077 | "output_type": "error",
1078 | "traceback": [
1079 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
1080 | "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
1081 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mf\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'My string'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
1082 | "\u001b[0;32m\u001b[0m in \u001b[0;36mf\u001b[0;34m(a, b)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mf\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mb\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0ma\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0mb\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
1083 | "\u001b[0;31mTypeError\u001b[0m: unsupported operand type(s) for +: 'int' and 'str'"
1084 | ]
1085 | }
1086 | ],
1087 | "source": [
1088 | "f(1, 'My string')"
1089 | ]
1090 | },
1091 | {
1092 | "cell_type": "markdown",
1093 | "metadata": {},
1094 | "source": [
1095 | "### Build in functions\n",
1096 | "\n",
1097 | "Python has a large set of build in functions. Here's just a few of them."
1098 | ]
1099 | },
1100 | {
1101 | "cell_type": "markdown",
1102 | "metadata": {},
1103 | "source": [
1104 | "**Is any element in a sequence logical true (does not have to contain boolean values only)?**"
1105 | ]
1106 | },
1107 | {
1108 | "cell_type": "code",
1109 | "execution_count": 51,
1110 | "metadata": {},
1111 | "outputs": [],
1112 | "source": [
1113 | "l2 = [True, True, False]"
1114 | ]
1115 | },
1116 | {
1117 | "cell_type": "code",
1118 | "execution_count": 52,
1119 | "metadata": {},
1120 | "outputs": [
1121 | {
1122 | "data": {
1123 | "text/plain": [
1124 | "True"
1125 | ]
1126 | },
1127 | "execution_count": 52,
1128 | "metadata": {},
1129 | "output_type": "execute_result"
1130 | }
1131 | ],
1132 | "source": [
1133 | "any(l2)"
1134 | ]
1135 | },
1136 | {
1137 | "cell_type": "markdown",
1138 | "metadata": {},
1139 | "source": [
1140 | "**Are all elements of the sequence logicaly true (again does not have to contain boolean values only)?**"
1141 | ]
1142 | },
1143 | {
1144 | "cell_type": "code",
1145 | "execution_count": 53,
1146 | "metadata": {},
1147 | "outputs": [
1148 | {
1149 | "data": {
1150 | "text/plain": [
1151 | "False"
1152 | ]
1153 | },
1154 | "execution_count": 53,
1155 | "metadata": {},
1156 | "output_type": "execute_result"
1157 | }
1158 | ],
1159 | "source": [
1160 | "all(l2)"
1161 | ]
1162 | },
1163 | {
1164 | "cell_type": "markdown",
1165 | "metadata": {},
1166 | "source": [
1167 | "**Summing elements of a sequence (items have to be \"countable\")**"
1168 | ]
1169 | },
1170 | {
1171 | "cell_type": "code",
1172 | "execution_count": 54,
1173 | "metadata": {},
1174 | "outputs": [],
1175 | "source": [
1176 | "l3 = [1, 4, 7, 10]"
1177 | ]
1178 | },
1179 | {
1180 | "cell_type": "code",
1181 | "execution_count": 55,
1182 | "metadata": {},
1183 | "outputs": [
1184 | {
1185 | "data": {
1186 | "text/plain": [
1187 | "22"
1188 | ]
1189 | },
1190 | "execution_count": 55,
1191 | "metadata": {},
1192 | "output_type": "execute_result"
1193 | }
1194 | ],
1195 | "source": [
1196 | "sum(l3)"
1197 | ]
1198 | },
1199 | {
1200 | "cell_type": "code",
1201 | "execution_count": null,
1202 | "metadata": {},
1203 | "outputs": [],
1204 | "source": []
1205 | }
1206 | ],
1207 | "metadata": {
1208 | "kernelspec": {
1209 | "display_name": "Python 3",
1210 | "language": "python",
1211 | "name": "python3"
1212 | },
1213 | "language_info": {
1214 | "codemirror_mode": {
1215 | "name": "ipython",
1216 | "version": 3
1217 | },
1218 | "file_extension": ".py",
1219 | "mimetype": "text/x-python",
1220 | "name": "python",
1221 | "nbconvert_exporter": "python",
1222 | "pygments_lexer": "ipython3",
1223 | "version": "3.6.9"
1224 | }
1225 | },
1226 | "nbformat": 4,
1227 | "nbformat_minor": 2
1228 | }
1229 |
--------------------------------------------------------------------------------