63 |
64 | {% endblock content %}
65 |
66 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | #### joe made this: http://goel.io/joe
2 |
3 | #####=== Python ===#####
4 |
5 | # Byte-compiled / optimized / DLL files
6 | __pycache__/
7 | *.py[cod]
8 | *$py.class
9 |
10 | # C extensions
11 | *.so
12 |
13 | # Distribution / packaging
14 | .Python
15 | env/
16 | build/
17 | develop-eggs/
18 | dist/
19 | downloads/
20 | eggs/
21 | .eggs/
22 | lib/
23 | lib64/
24 | parts/
25 | sdist/
26 | var/
27 | *.egg-info/
28 | .installed.cfg
29 | *.egg
30 |
31 | # PyInstaller
32 | # Usually these files are written by a python script from a template
33 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
34 | *.manifest
35 | *.spec
36 |
37 | # Installer logs
38 | pip-log.txt
39 | pip-delete-this-directory.txt
40 |
41 | # Unit test / coverage reports
42 | htmlcov/
43 | .tox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *,cover
50 |
51 | # Translations
52 | *.mo
53 | *.pot
54 |
55 | # Django stuff:
56 | *.log
57 |
58 | # Sphinx documentation
59 | docs/_build/
60 |
61 | # PyBuilder
62 | target/
63 |
64 | #####=== Vim ===#####
65 | [._]*.s[a-w][a-z]
66 | [._]s[a-w][a-z]
67 | *.un~
68 | Session.vim
69 | .netrwhist
70 | *~
71 |
72 | #
73 | .ipynb_checkpoints/
74 | .venv
75 | *.txt
76 | #### joe made this: http://goel.io/joe
77 |
78 | #####=== OSX ===#####
79 | .DS_Store
80 | .AppleDouble
81 | .LSOverride
82 |
83 | # Icon must end with two \r
84 | Icon
85 |
86 |
87 | # Thumbnails
88 | ._*
89 |
90 | # Files that might appear in the root of a volume
91 | .DocumentRevisions-V100
92 | .fseventsd
93 | .Spotlight-V100
94 | .TemporaryItems
95 | .Trashes
96 | .VolumeIcon.icns
97 |
98 | # Directories potentially created on remote AFP share
99 | .AppleDB
100 | .AppleDesktop
101 | Network Trash Folder
102 | Temporary Items
103 | .apdisk
104 |
105 | # django folders
106 | media/
107 | db.sqlite*
108 |
--------------------------------------------------------------------------------
/03-django/ecommerce/ecom/templates/base.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
33 | {% block content %}
34 | {% endblock content %}
35 |
36 |
37 | {% block footer %}
38 | {% endblock footer %}
39 |
40 |
41 |
43 | {% block js %}
44 | {% endblock js %}
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/02-python-oo/aula-02/exemplos/cao.py:
--------------------------------------------------------------------------------
1 | class Cão:
2 | qtd_patas = 4
3 | carnívoro = True
4 | nervoso = False
5 |
6 | def __init__(self, nome, data_nascimento=None):
7 | self.nome = nome
8 | self.data_nascimento = data_nascimento
9 |
10 | def latir(self, vezes=1):
11 | """ Latir do cão. Quanto mais nervoso mais late. """
12 |
13 | vezes += self.nervoso * vezes
14 | latido = 'Au! ' * vezes
15 | print('{}: {}'.format(self.nome, latido))
16 |
17 |
18 | class GoldenRetriever(Cão):
19 | def __init__(self, *args, **kwargs):
20 | super().__init__(*args, **kwargs)
21 | self.itens = []
22 |
23 | def pega(self, item):
24 | """ busca/pega um item quando ordenado """
25 | self.itens.append(item)
26 | print('{} pegou {}'.format(self.nome, item))
27 |
28 | def devolve(self, item):
29 | """ devolve um item, caso o item não seja especificado retorna o último que pegou """
30 | if not self.itens:
31 | raise ValueError('{} não está segurando item algum!'.format(self.nome))
32 |
33 | if item not in self.itens:
34 | raise ValueError('{} não está segurando {}!'.format(self.nome, item))
35 |
36 | self.itens.remove(item)
37 | print('{} devolve {}'.format(self.nome, item))
38 | return item
39 |
40 | def devolve_ultimo(self):
41 | if not self.itens:
42 | raise ValueError('{} não está segurando item algum!'.format(self.nome))
43 |
44 | return self.itens.pop()
45 |
46 |
47 | class Pinscher(Cão):
48 | nervoso = True
49 |
50 | def latir(self, vezes=1):
51 | vezes *= 2
52 | super().latir(vezes)
53 |
54 |
55 | class SãoBernardo(Cão):
56 | def __init__(self, *args, **kwargs):
57 | super().__init__(*args, **kwargs)
58 | self.doses = 10
59 |
60 | def servir(self):
61 | if self.doses == 0:
62 | raise ValueError('Cabô a cachaça!')
63 |
64 | self.doses -= 1
65 | print('Alguém está começando a ficar bebado (restam {} doses)'.format(self.doses))
66 |
--------------------------------------------------------------------------------
/04-python-prat/data_science/build/split.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python2.7
2 |
3 | import glob
4 | import json
5 | import os
6 | import re
7 |
8 | def blank_code_cell():
9 | return {
10 | "cell_type": "code",
11 | "execution_count": None,
12 | "metadata": {
13 | "collapsed": True
14 | },
15 | "outputs": [],
16 | "source": [],
17 | }
18 |
19 | def question_cell(text):
20 | return {
21 | "cell_type": "markdown",
22 | "metadata": {
23 | "collapsed": True
24 | },
25 | "source": '### ' + text.strip(),
26 | }
27 |
28 | def main():
29 | session_cells = {n: [] for n in range(1, 6+1)}
30 | f = open(os.path.dirname(os.path.abspath(__file__)) + '/../All.ipynb')
31 | j = json.load(f)
32 | cells = j['cells']
33 | for cell in cells:
34 | source = u''.join(cell['source'])
35 | m = re.search(r'# +(\d+)\. ', source.strip())
36 | if not m:
37 | continue
38 | n = int(m.group(1))
39 | session_cells[n].append(cell)
40 | for n, cells in sorted(session_cells.items()):
41 | print 'Session {}: {} cells'.format(n, len(cells))
42 |
43 | def convert(filename):
44 | f = open(filename)
45 | j = json.load(f)
46 | j['cells'] = list(filter_cells(filename, j['cells']))
47 | assert 'Solutions' in filename
48 | with open(filename.replace('Solutions', 'Exercises'), 'w') as f:
49 | f.write(json.dumps(j, indent=2))
50 |
51 | def filter_cells(filename, cells):
52 | n = 0
53 | starting = True
54 | for cell in cells:
55 | if cell['cell_type'] != 'code':
56 | continue
57 | source = u''.join(cell['source'])
58 |
59 | if starting:
60 | if not source.startswith('# '):
61 | yield cell
62 | else:
63 | starting = False
64 |
65 | if not source.startswith('# '):
66 | continue
67 |
68 | question = []
69 |
70 | for line in cell['source']:
71 | if not line.startswith('# '):
72 | break
73 | question.append(line[2:].strip())
74 |
75 | question = ' '.join(question)
76 |
77 | yield question_cell(question)
78 |
79 | yield blank_code_cell()
80 | yield blank_code_cell()
81 |
82 | n += 1
83 | print '{:6} {}'.format(n, filename)
84 |
85 | def main2():
86 | for filename in sorted(glob.glob('Solutions-*.ipynb')):
87 | convert(filename)
88 |
89 | if __name__ == '__main__':
90 | main2()
91 |
--------------------------------------------------------------------------------
/01-python-intro/aula-04/conta_palavras.py:
--------------------------------------------------------------------------------
1 | """
2 | Este arquivo apresenta diferentes formas de contar as palavras de uma frase
3 | usando dicts e o módulo collections (https://docs.python.org/2/library/collections.html)
4 | """
5 |
6 | from collections import Counter, defaultdict
7 |
8 |
9 | def conta_palavras(frase):
10 | """
11 | Recebe uma palavra e retorna um dicionário em que a chave é uma palavra
12 | e seu valor a quantidade de vezes que essa palavra está presente na frase
13 | """
14 |
15 | d = {}
16 | for palavra in frase.lower().split():
17 | if palavra in d:
18 | d[palavra] += 1
19 | else:
20 | d[palavra] = 1
21 | return d
22 |
23 |
24 | def conta_palavras(frase):
25 | d = defaultdict(int)
26 | for palavra in frase.lower().split():
27 | d[palavra] += 1
28 | return d
29 |
30 |
31 | def conta_palavras(frase):
32 | return Counter(frase.lower().split())
33 |
34 |
35 | # seu código estará correto se nenhuma das linhas abaixo levantar exceção
36 | assert conta_palavras("quod dolore dolore dolore modi sapiente quod ullam nostrum ullam") == {'ullam': 2, 'sapiente': 1, 'quod': 2, 'nostrum': 1, 'dolore': 3, 'modi': 1}
37 | assert conta_palavras("soluta Soluta sapiente sapiente nostrum Sapiente dolore nostrum modi ullam") == {'ullam': 1, 'sapiente': 3, 'nostrum': 2, 'dolore': 1, 'soluta': 2, 'modi': 1}
38 | assert conta_palavras("quod dolore dolore soluta sapiente sapiente dolore quod sapiente modi") == {'dolore': 3, 'quod': 2, 'soluta': 1, 'modi': 1, 'sapiente': 3}
39 | assert conta_palavras("dolore Dolore quis quod dolore nostrum quod Nostrum sapiente soluta") == {'sapiente': 1, 'quod': 2, 'nostrum': 2, 'soluta': 1, 'dolore': 3, 'quis': 1}
40 | assert conta_palavras("sapiente sapiente quod soluta quis ullam nostrum soluta ullam ullam") == {'ullam': 3, 'sapiente': 2, 'quod': 1, 'nostrum': 1, 'soluta': 2, 'quis': 1}
41 | assert conta_palavras("modi Sapiente dolore Soluta sapiente quis soluta modi dolore ullam") == {'ullam': 1, 'sapiente': 2, 'quis': 1, 'dolore': 2, 'soluta': 2, 'modi': 2}
42 | assert conta_palavras("quis quis nostrum nostrum sapiente quis nostrum quod quis dolore") == {'sapiente': 1, 'quod': 1, 'quis': 4, 'nostrum': 3, 'dolore': 1}
43 | assert conta_palavras("nostrum sapiente quis ullam ullam quod ullam nostrum ullam soluta") == {'ullam': 4, 'sapiente': 1, 'quod': 1, 'nostrum': 2, 'soluta': 1, 'quis': 1}
44 | assert conta_palavras("sapiente ullam quod quis dolore modi Quis quod dolore nostrum") == {'ullam': 1, 'sapiente': 1, 'quod': 2, 'quis': 2, 'nostrum': 1, 'dolore': 2, 'modi': 1}
45 | assert conta_palavras("modi nostrum ullam Quis Soluta modi quis ullam modi ullam") == {'ullam': 3, 'soluta': 1, 'modi': 3, 'nostrum': 1, 'quis': 2}
46 |
--------------------------------------------------------------------------------
/ementa.md:
--------------------------------------------------------------------------------
1 | ## Ementa - Trilha Python | Opensanca Developer
2 |
3 | #### Módulo 1 - Introdução à linguagem (6 aulas / 18h)
4 |
5 | Neste curso será ensinado tudo o que você precisa saber para começar a programar em Python.
6 | Conteúdo: expressões, atribuição, estruturas básicas de controle (if, while, for), funções, tipos de dados básicos (números, str, sequências e dicionários), arquivos, virtualenv e pip.
7 |
8 | * Aula 1: instalação do python, ambiente virtual, instalação e uso de bibliotecas e introdução a estruturas de dados do Python
9 | * Aula 2: tipos básicos: números, string, sequências (strings, listas e tuplas) e estruturas de controle de fluxo
10 | * Aula 3: conjuntos e mapeamento
11 | * Aula 4: funções e arquivos
12 | * Aula 5: módulos e testes automáticos
13 |
14 | #### Módulo 2 - Orientação a objetos e frameworks (6 aulas / 18h)
15 |
16 | Neste curso serão abordados os conceitos de orientação a objetos no Python usando exemplos práticos da biblioteca padrão e do framework web Django. Conteúdo deste móduo aborda sobre a terminologia de orientação a objetos em Python, duck typing, herança, herança múltipla, sobrecarga de métodos e operadores, encapsulamento, polimorfismo, classes abstratas e protocolos (interfaces informais), testes automáticos.
17 |
18 | * Aula 1: conceito de objetos, tipagem, mutabilidade, como funciona variáveis e atribuição, classes
19 | * Aula 2: herança, herança múltipla no Django e mixins
20 | * Aula 3: encapsulamento e polimorfismo
21 | * Aula 4: python data model: sobrecarga de operadores, sequências, iteráveis, geradores
22 | * Aula 5: gerenciadores de contexto, geradores, módulo functools e operator, decoradores
23 | * Aula 6: testes automáticos: conceito, tipos de testes, asserções, mock
24 |
25 | #### Módulo 3 - Desenvolvimento web com Django (6 aulas / 18h)
26 |
27 | Neste curso será ensinado como criar aplicações web utilizando o framework full-stack Django e como fazer deploy no Heroku.
28 |
29 | * Aula 1: Instalação do python e django, explicação do funcionamento do framework e hello world
30 | * Aula 2: herança, herança múltipla no Django e mixins
31 | * Aula 3: encapsulamento e polimorfismo
32 | * Aula 4: python data model: sobrecarga de operadores, sequências, iteráveis, geradores
33 | * Aula 5: gerenciadores de contexto, geradores, módulo functools e operator, decoradores
34 | * Aula 6: testes automáticos: conceito, tipos de testes, asserções, mock
35 | * Aula 7: deploy no heroku, requirements
36 |
37 | #### Módulo 4 - Python na prática (4 aulas / 12h)
38 |
39 | Neste curso será ensinado como criar aplicações web utilizando o framework full-stack Django e como fazer deploy no Heroku.
40 |
41 | * Aula 1: introdução à aprendizado de máquina com Python
42 | * Aula 2: NoSQL com MongoDB e Python
43 | * Aula 3: Webscraping com scrapy
44 | * Aula 4: Programação para desktop com tkinter
45 |
--------------------------------------------------------------------------------
/02-python-oo/aula-03/exemplos/vetor2.py:
--------------------------------------------------------------------------------
1 | """
2 | Implementa um vetor bidimensional (versão 2 - mais completa)
3 | """
4 | from numbers import Real
5 | import math
6 |
7 |
8 | class Vetor:
9 | """
10 | Vetor bidimensional que implementa soma, subtração, multiplicação por escalar etc.
11 |
12 | >>> v1 = Vetor(3, -2)
13 | >>> v1
14 | Vetor(3, -2)
15 | >>> v2 = Vetor(1, 1)
16 | >>> v2
17 | Vetor(1, 1)
18 | >>> v1 + v2
19 | Vetor(4, 1)
20 | >>> v1 - v2
21 | Vetor(2, -3)
22 | >>> v1 * 3
23 | Vetor(9, -6)
24 | >>> 5 * v2
25 | Vetor(5, 5)
26 | """
27 |
28 | def __init__(self, x=0, y=0):
29 | self.x = x
30 | self.y = y
31 |
32 | def __repr__(self): return 'Vetor({!r}, {!r})'.format(self.x, self.y)
33 |
34 | def __abs__(self):
35 | return math.hypot(self.x, self.y)
36 |
37 | def __add__(self, outro):
38 | if isinstance(outro, Vetor):
39 | return Vetor(self.x + outro.x, self.y + outro.y)
40 | else:
41 | return NotImplemented
42 |
43 | def __bool__(self):
44 | return bool(self.x or self.y)
45 |
46 | def __eq__(self, outro):
47 | if isinstance(outro, Vetor):
48 | return self.x == outro.x and self.y == outro.y
49 | else:
50 | return NotImplemented
51 |
52 | def __iter__(self):
53 | yield self.x
54 | yield self.y
55 |
56 | def __matmul__(self, outro):
57 | return self.x * outro.x + self.y * outro.y
58 |
59 | def __mul__(self, escalar):
60 | if isinstance(escalar, Real):
61 | return Vetor(self.x * escalar, self.y * escalar)
62 | else:
63 | return NotImplemented
64 |
65 | def __rmul__(self, outro):
66 | return self * outro
67 |
68 | def __neg__(self):
69 | return self * -1
70 |
71 | def __pos__(self):
72 | return self
73 |
74 | def __sub__(self, outro):
75 | return Vetor(self.x - outro.x, self.y - outro.y)
76 |
77 |
78 | class VetorMutavel(Vetor):
79 | """
80 | Versão mutável do Vetor bidimensional. Não tem muita utilidade no mundo real, serve
81 | mais para demonstrar como funciona `__iadd__` e `__imul__`
82 | """
83 |
84 | def __repr__(self):
85 | return 'VetorMutavel({!r}, {!r})'.format(self.x, self.y)
86 |
87 | def __iadd__(self, outro):
88 | if isinstance(outro, Vetor):
89 | self.x += outro.x
90 | self.y += outro.y
91 | return self
92 | return NotImplemented
93 |
94 | def __imul__(self, outro):
95 | if isinstance(outro, Real):
96 | self.x *= outro
97 | self.y *= outro
98 | return self
99 | return NotImplemented
100 |
--------------------------------------------------------------------------------
/04-python-prat/data_science/README.md:
--------------------------------------------------------------------------------
1 |
2 | # Welcome to Brandon’s Pandas Tutorial
3 |
4 | The first instance of this tutorial was delivered at PyCon 2015 in
5 | Montréal, but I hope that many other people will be able to benefit from
6 | it over the next few years — both on occasions on which I myself get to
7 | deliver it, and also when other instructors are able to do so.
8 |
9 | If you want to follow along with the tutorial at home, here is the
10 | YouTube recording of the 3-hour tutorial at PyCon itself:
11 |
12 | [](http://www.youtube.com/watch?v=5JnMutdy6Fw "Pandas From The Ground Up - PyCon 2015")
13 |
14 | https://www.youtube.com/watch?v=5JnMutdy6Fw
15 |
16 | To make it useful to as many people as possible, I hereby release it
17 | under the MIT license (see the accompanying `LICENSE.txt` file) and I
18 | have tried to make sure that this repository contains all of the scripts
19 | needed to download and set up the data set that we used.
20 |
21 | ## Quick Start
22 |
23 | If you have both `conda` and `git` on your system (otherwise, read the
24 | next section for more detailed instructions):
25 |
26 | $ conda install --yes ipython-notebook matplotlib pandas
27 | $ git clone https://github.com/brandon-rhodes/pycon-pandas-tutorial.git
28 | $ cd pycon-pandas-tutorial
29 | $ build/BUILD.sh
30 | $ ipython notebook
31 |
32 | ## Detailed Instructions
33 |
34 | You will need Pandas, the IPython Notebook, and Matplotlib installed
35 | before you can successfully run the tutorial notebooks. The [Anaconda
36 | Distribution](http://continuum.io/downloads) is a great way to get up
37 | and running quickly without having to install them each separately —
38 | running the `conda` command shown above will install all three.
39 |
40 | Note that having `git` is not necessary for getting the materials.
41 | Simply click the “Download ZIP” button over on the right-hand side of
42 | this repository’s front page at the following link, and its files will
43 | be delivered to you as a ZIP archive:
44 |
45 | https://github.com/brandon-rhodes/pycon-pandas-tutorial
46 |
47 | Once you have unpacked the ZIP file, download the following four
48 | [IMDB](https://www.imdb.com/) data files and place them in the
49 | tutorial’s `build` directory:
50 |
51 | * ftp://ftp.fu-berlin.de/pub/misc/movies/database/actors.list.gz
52 | * ftp://ftp.fu-berlin.de/pub/misc/movies/database/actresses.list.gz
53 | * ftp://ftp.fu-berlin.de/pub/misc/movies/database/genres.list.gz
54 | * ftp://ftp.fu-berlin.de/pub/misc/movies/database/release-dates.list.gz
55 |
56 | To convert these into the CSV files that the tutorial needs, run the
57 | `BUILD.py` script with either Python 2 or Python 3. It will create the
58 | three CSV files in the `data` directory that you need to run all of the
59 | tutorial examples. It should take about 5 minutes to run on a fast
60 | modern machine:
61 |
62 | $ python build/BUILD.py
63 |
64 | You can then start up the IPython Notebook and start looking at the
65 | notebooks:
66 |
67 | $ ipython notebook
68 |
69 | I hope that the recording and the exercises in this repository prove
70 | useful if you are interested in learning more about Python and its data
71 | analysis capabilities!
72 |
73 | — [Brandon Rhodes](http://rhodesmill.org/brandon/)
74 |
--------------------------------------------------------------------------------
/01-python-intro/aula-04/img/uniao.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |