[-\w]+)/$',
16 | views.post_list, name='post_list_by_tag'
17 | ),
18 | url(r'^feed/$', LatestPostsFeed(), name='post_feed'),
19 | ]
20 |
--------------------------------------------------------------------------------
/interview_questions/general/occurs_once.py:
--------------------------------------------------------------------------------
1 | # Find the only element in an array that only occurs once.
2 | from operator import itemgetter
3 |
4 |
5 | def count_occurrences(array):
6 | # dict with {item: times}
7 | d = {}
8 | for item in array:
9 | if not d.get(item):
10 | d.update({item: 1})
11 | else:
12 | d[item] += 1
13 | return d
14 |
15 |
16 | def occurs_once(array):
17 | dic = count_occurrences(array)
18 | s = sorted(dic.items(), key=itemgetter(1))
19 | return [i for i in s if i[1] == 1]
20 |
21 |
22 | assert occurs_once([1, 2, 1, 2, 3, 5, 5]) == [(3, 1)]
23 | assert occurs_once([1, 2, 1, 1, 3, 5, 5]) == [(2, 1), (3, 1)]
24 | assert occurs_once([1, 2, 2, 1, 3, 5, 5, 3]) == []
25 |
--------------------------------------------------------------------------------
/python/django/django_by_example/mysite/blog/migrations/0003_post_tags.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | # Generated by Django 1.9.6 on 2016-06-03 12:44
3 | from __future__ import unicode_literals
4 |
5 | from django.db import migrations
6 | import taggit.managers
7 |
8 |
9 | class Migration(migrations.Migration):
10 |
11 | dependencies = [
12 | ('taggit', '0002_auto_20150616_2121'),
13 | ('blog', '0002_comment'),
14 | ]
15 |
16 | operations = [
17 | migrations.AddField(
18 | model_name='post',
19 | name='tags',
20 | field=taggit.managers.TaggableManager(help_text='A comma-separated list of tags.', through='taggit.TaggedItem', to='taggit.Tag', verbose_name='Tags'),
21 | ),
22 | ]
23 |
--------------------------------------------------------------------------------
/python/django/tutorials/django-channels/channels/README.md:
--------------------------------------------------------------------------------
1 | # Django Channels example
2 |
3 | [Tutorial here](https://blog.heroku.com/archives/2016/3/17/in_deep_with_django_channels_the_future_of_real_time_apps_in_django)
4 |
5 | [Oficial repo here](https://github.com/jacobian/channels-example)
6 |
7 | ## Installation
8 |
9 | Install the requirements:
10 |
11 | ```sh
12 | $ pip install -r requirements.txt
13 | ```
14 |
15 | ## Usage example
16 |
17 | A Redis server is needed, a Docker container can be used.
18 |
19 | ```sh
20 | $ docker run -it -p 6379:6379 redis
21 | ```
22 |
23 | To run locally:
24 |
25 | ```sh
26 | $ python manage.py makemigrations
27 | $ python manage.py migrate
28 | $ python manage.py collectstatic
29 | $ python manage.py runserver
30 | ```
31 |
--------------------------------------------------------------------------------
/python/django/django_by_example/mysite/blog/admin.py:
--------------------------------------------------------------------------------
1 | from django.contrib import admin
2 | from .models import Post, Comment
3 |
4 |
5 | class PostAdmin(admin.ModelAdmin):
6 | list_display = ('title', 'slug', 'author', 'publish', 'status')
7 | list_filter = ('status', 'created', 'publish', 'author')
8 | search_fields = ('title', 'body')
9 | prepopulated_fields = {'slug': ('title',)}
10 | raw_id_fields = ('author',)
11 | date_hierarchy = 'publish'
12 | ordering = ['status', 'publish']
13 |
14 | admin.site.register(Post, PostAdmin)
15 |
16 |
17 | class CommentAdmin(admin.ModelAdmin):
18 | list_display = ('name', 'email', 'post', 'created', 'active')
19 | list_filter = ('active', 'created', 'updated')
20 | search_fields = ('name', 'email', 'body')
21 |
22 | admin.site.register(Comment, CommentAdmin)
23 |
--------------------------------------------------------------------------------
/python/django/tutorials/django-channels/channels/dj_channels/chat/templates/about.html:
--------------------------------------------------------------------------------
1 | {% extends "base.html" %}
2 |
3 | {% block content %}
4 | Django Channels Example
5 |
6 | This is a demo using
7 | Django Channels to implement a simple WebSocket-based chat server.
8 | You can see the
9 | code on GitHub, or try the app:
10 |
11 |
12 | Create new chat room
13 |
14 |
15 | Or, you can visit {{ request.scheme }}://{{ request.get_host }}/any-path-you-want
16 | to create a arbitrary room or join one whose name you know.
17 |
18 | {% endblock content %}
--------------------------------------------------------------------------------
/python/django/django_by_example/bookmarks/actions/models.py:
--------------------------------------------------------------------------------
1 | from django.db import models
2 | from django.contrib.auth.models import User
3 | from django.contrib.contenttypes.models import ContentType
4 | from django.contrib.contenttypes.fields import GenericForeignKey
5 |
6 |
7 | class Action(models.Model):
8 | user = models.ForeignKey(User, related_name='actions', db_index=True)
9 | verb = models.CharField(max_length=255)
10 | target_ct = models.ForeignKey(
11 | ContentType, blank=True, null=True, related_name='target_obj'
12 | )
13 | target_id = models.PositiveIntegerField(
14 | blank=True, null=True, db_index=True
15 | )
16 | target = GenericForeignKey('target_ct', 'target_id')
17 | created = models.DateTimeField(auto_now_add=True, db_index=True)
18 |
19 | class Meta:
20 | ordering = ('-created', )
21 |
--------------------------------------------------------------------------------
/python/django/django_by_example/myshop/shop/admin.py:
--------------------------------------------------------------------------------
1 | from django.contrib import admin
2 |
3 | from parler.admin import TranslatableAdmin
4 |
5 | from .models import Category, Product
6 |
7 |
8 | class CategoryAdmin(TranslatableAdmin):
9 | list_display = ['name', 'slug']
10 |
11 | def get_prepopulated_fields(self, request, obj=None):
12 | return {'slug': ('name', )}
13 |
14 | admin.site.register(Category, CategoryAdmin)
15 |
16 |
17 | class ProductAdmin(TranslatableAdmin):
18 | list_display = [
19 | 'name', 'slug', 'price', 'stock', 'avaiable', 'created', 'updated'
20 | ]
21 | list_filter = ['avaiable', 'created', 'updated']
22 | list_editable = ['price', 'stock', 'avaiable']
23 |
24 | def get_prepopulated_fields(self, request, obj=None):
25 | return {'slug': ('name', )}
26 |
27 | admin.site.register(Product, ProductAdmin)
28 |
--------------------------------------------------------------------------------
/python/django/django_by_example/bookmarks/account/templates/account/user/list.html:
--------------------------------------------------------------------------------
1 | {% extends "base.html" %}
2 | {% load thumbnail %}
3 | {% block title %}People{% endblock %}
4 | {% block content %}
5 | People
6 |
7 | {% for user in users %}
8 |
20 | {% endfor %}
21 |
22 | {% endblock %}
--------------------------------------------------------------------------------
/python/django/django_by_example/myshop/coupons/views.py:
--------------------------------------------------------------------------------
1 | from django.shortcuts import render, redirect
2 | from django.utils import timezone
3 | from django.views.decorators.http import require_POST
4 |
5 | from .models import Coupon
6 | from .forms import CouponApplyForm
7 |
8 |
9 | @require_POST
10 | def coupon_apply(request):
11 | now = timezone.now()
12 |
13 | form = CouponApplyForm(request.POST)
14 | if form.is_valid():
15 | code = form.cleaned_data['code']
16 | try:
17 | coupon = Coupon.objects.get(
18 | code__iexact=code,
19 | valid_from__lte=now,
20 | valid_to__gte=now,
21 | active=True
22 | )
23 | request.session['coupon_id'] = coupon.id
24 | except Coupon.DoesNotExist:
25 | request.session['coupon_id'] = None
26 |
27 | return redirect('cart:cart_detail')
28 |
--------------------------------------------------------------------------------
/interview_questions/general/most_frequent.py:
--------------------------------------------------------------------------------
1 | # Find the most frequent integer in an array
2 | from operator import itemgetter
3 |
4 |
5 | def count_occurrences(array):
6 | # dict with {item: times}
7 | d = {}
8 | for item in array:
9 | if not d.get(item):
10 | d.update({item: 1})
11 | else:
12 | d[item] += 1
13 | return d
14 |
15 |
16 | def monst_frequent(array):
17 | if not array:
18 | return None
19 | dic = count_occurrences(array)
20 | s = sorted(dic.items(), key=itemgetter(1))
21 | # return everybody that has value equals the last one
22 | return [i for i in s if i[1] == s[-1][1]]
23 |
24 |
25 | assert monst_frequent([1, 2, 1, 2, 3, 5, 5, 5, 7]) == [(5, 3)]
26 | assert monst_frequent([1, 2, 1, 1, 3, 5, 5]) == [(1, 3)]
27 | assert monst_frequent([1, 2, 3, 4]) == [(1, 1), (2, 1), (3, 1), (4, 1)]
28 | assert monst_frequent([]) is None
29 |
--------------------------------------------------------------------------------
/python/django/django_by_example/bookmarks/account/migrations/0001_initial.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import unicode_literals
3 |
4 | from django.db import migrations, models
5 | from django.conf import settings
6 |
7 |
8 | class Migration(migrations.Migration):
9 |
10 | dependencies = [
11 | migrations.swappable_dependency(settings.AUTH_USER_MODEL),
12 | ]
13 |
14 | operations = [
15 | migrations.CreateModel(
16 | name='Profile',
17 | fields=[
18 | ('id', models.AutoField(primary_key=True, auto_created=True, serialize=False, verbose_name='ID')),
19 | ('data_of_birth', models.DateField(null=True, blank=True)),
20 | ('photo', models.ImageField(upload_to='users/%Y/%m/%d', blank=True)),
21 | ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL)),
22 | ],
23 | ),
24 | ]
25 |
--------------------------------------------------------------------------------
/python/tdd_by_example/three.py:
--------------------------------------------------------------------------------
1 | # Log string in WasRun
2 |
3 |
4 | class TestCase:
5 | def __init__(self, name):
6 | self.name = name
7 |
8 | def setUp(self):
9 | pass
10 |
11 | def run(self):
12 | self.setUp()
13 | method = getattr(self, self.name)
14 | method()
15 |
16 |
17 | class WasRun(TestCase):
18 | def __init__(self, name):
19 | self.wasRun = None
20 | TestCase.__init__(self, name)
21 |
22 | def setUp(self):
23 | self.wasRun = None
24 | self.log = "setUp "
25 |
26 | def testMethod(self):
27 | self.wasRun = 1
28 | self.log = self.log + "testMethod "
29 |
30 |
31 | class TestCaseTest(TestCase):
32 | def testTemplateMethod(self):
33 | self.test = WasRun("testMethod")
34 | self.test.run()
35 | assert("setUp testMethod " == self.test.log)
36 |
37 | TestCaseTest("testTemplateMethod").run()
38 |
--------------------------------------------------------------------------------
/python/django/django_by_example/myshop/orders/migrations/0002_auto_20160623_1328.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import unicode_literals
3 |
4 | from django.db import migrations, models
5 | import django.core.validators
6 |
7 |
8 | class Migration(migrations.Migration):
9 |
10 | dependencies = [
11 | ('coupons', '0001_initial'),
12 | ('orders', '0001_initial'),
13 | ]
14 |
15 | operations = [
16 | migrations.AddField(
17 | model_name='order',
18 | name='coupon',
19 | field=models.ForeignKey(blank=True, related_name='orders', null=True, to='coupons.Coupon'),
20 | ),
21 | migrations.AddField(
22 | model_name='order',
23 | name='discount',
24 | field=models.IntegerField(validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100)], default=0),
25 | ),
26 | ]
27 |
--------------------------------------------------------------------------------
/python/django/django_by_example/bookmarks/account/templates/registration/login.html:
--------------------------------------------------------------------------------
1 | {% extends "base.html" %}
2 | {% block title %}Log-in{% endblock %}
3 | {% block content %}
4 | Log-in
5 | {% if form.errors %}
6 |
7 | Your username and password didn't match.
8 | Please try again.
9 |
10 | {% else %}
11 |
12 | Please, use the following form to log-in. If you don't have an account register here
13 |
14 | {% endif %}
15 |
24 | {% endblock %}
--------------------------------------------------------------------------------
/python/django/django_by_example/bookmarks/actions/utils.py:
--------------------------------------------------------------------------------
1 | import datetime
2 |
3 | from django.utils import timezone
4 | from django.contrib.contenttypes.models import ContentType
5 |
6 | from .models import Action
7 |
8 |
9 | def create_action(user, verb, target=None):
10 | # check for any similar action made in the last minute
11 | now = timezone.now()
12 | last_minute = now - datetime.timedelta(seconds=60)
13 | similar_actions = Action.objects.filter(
14 | user_id=user.id, verb=verb, created__gte=last_minute
15 | )
16 |
17 | if target:
18 | target_ct = ContentType.objects.get_for_model(target)
19 | similar_actions = similar_actions.filter(
20 | target_ct=target_ct, target_id=target.id
21 | )
22 |
23 | if not similar_actions:
24 | # no existing actions found
25 | action = Action(user=user, verb=verb, target=target)
26 | action.save()
27 | return True
28 |
29 | return False
30 |
--------------------------------------------------------------------------------
/python/django/tutorials/django-channels/channels/dj_channels/urls.py:
--------------------------------------------------------------------------------
1 | """dj_channels URL Configuration
2 |
3 | The `urlpatterns` list routes URLs to views. For more information please see:
4 | https://docs.djangoproject.com/en/1.9/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, include
17 | from django.contrib import admin
18 |
19 | urlpatterns = [
20 | url(r'^admin/', admin.site.urls),
21 | url(r'^', include('dj_channels.chat.urls', namespace='chat')),
22 | ]
23 |
--------------------------------------------------------------------------------
/javascript/nodejs/tutorials/nodeauth/views/index.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Node Authentication
6 |
7 |
8 |
11 |
12 |
13 |
14 |
15 |
16 |
Node Authentication
17 |
18 |
Login or Register with:
19 |
20 |
Local Login
21 |
Local Signup
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/python/django/django_by_example/myshop/coupons/migrations/0001_initial.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import unicode_literals
3 |
4 | from django.db import migrations, models
5 | import django.core.validators
6 |
7 |
8 | class Migration(migrations.Migration):
9 |
10 | dependencies = [
11 | ]
12 |
13 | operations = [
14 | migrations.CreateModel(
15 | name='Coupon',
16 | fields=[
17 | ('id', models.AutoField(verbose_name='ID', serialize=False, primary_key=True, auto_created=True)),
18 | ('code', models.CharField(unique=True, max_length=50)),
19 | ('valid_from', models.DateTimeField()),
20 | ('valid_to', models.DateTimeField()),
21 | ('discount', models.IntegerField(validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100)])),
22 | ('active', models.BooleanField()),
23 | ],
24 | ),
25 | ]
26 |
--------------------------------------------------------------------------------
/python/django/django_by_example/mysite/blog/templates/blog/post/list.html:
--------------------------------------------------------------------------------
1 | {% extends "blog/base.html" %}
2 | {% load blog_tags %}
3 | {% block title %}My Blog{% endblock %}
4 | {% block content %}
5 | My blog
6 | {% if tag %}
7 | Posts tagget with "{{ tag.name }}"
8 | {% endif %}
9 | {% for post in posts %}
10 |
15 |
16 | Tags:
17 | {% for tag in post.tags.all %}
18 |
19 | {{ tag.name }}
20 |
21 | {% if not forloop.last %}, {% endif %}
22 | {% endfor %}
23 |
24 |
25 | Published {{ post.publish }} by {{ post.author }}
26 |
27 | {{ post.body|markdown|truncatewords_html:30 }}
28 | {% endfor %}
29 | {% include "blog/paginator.html" with page=posts%}
30 | {% endblock %}
--------------------------------------------------------------------------------
/python/tdd_by_example/two.py:
--------------------------------------------------------------------------------
1 | # Invoke setUp first
2 |
3 |
4 | class TestCase:
5 | def __init__(self, name):
6 | self.name = name
7 |
8 | def setUp(self):
9 | pass
10 |
11 | def run(self):
12 | self.setUp()
13 | method = getattr(self, self.name)
14 | method()
15 |
16 |
17 | class WasRun(TestCase):
18 | def __init__(self, name):
19 | self.wasRun = None
20 | TestCase.__init__(self, name)
21 |
22 | def setUp(self):
23 | self.wasRun = None
24 | self.wasSetUp = 1
25 |
26 | def testMethod(self):
27 | self.wasRun = 1
28 |
29 |
30 |
31 |
32 | class TestCaseTest(TestCase):
33 | def setUp(self):
34 | self.test = WasRun("testMethod")
35 |
36 | def testRunning(self):
37 | self.test.run()
38 | assert(self.test.wasRun)
39 |
40 | def testSetUp(self):
41 | self.test.run()
42 | assert(self.test.wasSetUp)
43 |
44 | TestCaseTest("testRunning").run()
45 | TestCaseTest("testSetUp").run()
46 |
--------------------------------------------------------------------------------
/javascript/rock_paper_scissors/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
Computer
13 |
14 |
15 |

16 |
17 |
18 |
19 |
20 |
You
21 |
22 |
23 |

24 |
25 |
26 |
27 |
28 |
29 |
Choose your option!
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
--------------------------------------------------------------------------------
/python/django/django_by_example/bookmarks/account/models.py:
--------------------------------------------------------------------------------
1 | from django.db import models
2 | from django.conf import settings
3 | from django.contrib.auth.models import User
4 |
5 |
6 | # add following field to User dynamically
7 | User.add_to_class(
8 | 'following',
9 | models.ManyToManyField('self', related_name='followers', symmetrical=False)
10 | )
11 |
12 |
13 | class Profile(models.Model):
14 | user = models.OneToOneField(settings.AUTH_USER_MODEL)
15 | date_of_birth = models.DateField(blank=True, null=True)
16 | photo = models.ImageField(upload_to='users/%Y/%m/%d', blank=True)
17 |
18 |
19 | class Contact(models.Model):
20 | user_from = models.ForeignKey(User, related_name='rel_from_set')
21 | user_to = models.ForeignKey(User, related_name='rel_to_set')
22 | created = models.DateTimeField(auto_now_add=True, db_index=True)
23 |
24 | class Meta:
25 | ordering = ('-created', )
26 |
27 | def __str__(self):
28 | return '{} follows {}'.format(self.user_from, self.user_to)
29 |
--------------------------------------------------------------------------------
/python/tdd_by_example/four.py:
--------------------------------------------------------------------------------
1 | # Invoke tearDown afterward
2 |
3 |
4 | class TestCase:
5 | def __init__(self, name):
6 | self.name = name
7 |
8 | def setUp(self):
9 | pass
10 |
11 | def tearDown(self):
12 | pass
13 |
14 | def run(self):
15 | self.setUp()
16 | method = getattr(self, self.name)
17 | method()
18 | self.tearDown()
19 |
20 |
21 | class WasRun(TestCase):
22 | def __init__(self, name):
23 | self.wasRun = None
24 | TestCase.__init__(self, name)
25 |
26 | def setUp(self):
27 | self.log = "setUp "
28 |
29 | def testMethod(self):
30 | self.log = self.log + "testMethod "
31 |
32 | def tearDown(self):
33 | self.log = self.log + "tearDown "
34 |
35 |
36 | class TestCaseTest(TestCase):
37 | def testTemplateMethod(self):
38 | test = WasRun("testMethod")
39 | test.run()
40 | assert("setUp testMethod tearDown " == test.log)
41 |
42 | TestCaseTest("testTemplateMethod").run()
43 |
--------------------------------------------------------------------------------
/python/django/django_by_example/bookmarks/account/templates/account/dashboard.html:
--------------------------------------------------------------------------------
1 | {% extends "base.html" %}
2 | {% block title %}Dashboard{% endblock %}
3 | {% block content %}
4 | Dashboard
5 | {% with total_images_created=request.user.images_created.count %}
6 | Welcome to your dashboard. You have bookmarked {{ total_images_created }} image{{ total_images_created|pluralize }}.
7 | {% endwith %}
8 |
9 | Drag the following button to your bookmarks toolbar to bookmark
10 | images from other websites → Bookmark it
11 |
12 |
13 | You can edit your profile or change your password.
14 |
15 | What's happening
16 |
17 | {% for action in actions %}
18 | {% include "actions/action/detail.html" %}
19 | {% endfor %}
20 |
21 | {% endblock %}
--------------------------------------------------------------------------------
/python/django/django_by_example/mysite/blog/templatetags/blog_tags.py:
--------------------------------------------------------------------------------
1 | from django import template
2 | from django.db.models import Count
3 | from django.utils.safestring import mark_safe
4 |
5 | import markdown
6 |
7 | from ..models import Post
8 |
9 |
10 | register = template.Library()
11 |
12 |
13 | @register.simple_tag
14 | def total_posts():
15 | return Post.published.count()
16 |
17 |
18 | @register.inclusion_tag('blog/post/latest_posts.html')
19 | def show_latest_posts(count=5):
20 | latest_posts = Post.published.order_by('-publish')[:count]
21 | return {'latest_posts': latest_posts}
22 |
23 |
24 | @register.assignment_tag
25 | def get_most_commented_posts(count=5):
26 | return Post.published.annotate(
27 | total_comments=Count('comments')).order_by('-total_comments')[:count]
28 |
29 |
30 | # Use mark_safe to tell Django to not escape the HTML,
31 | # because it is not dangerous!
32 | @register.filter(name='markdown')
33 | def markdown_format(text):
34 | return mark_safe(markdown.markdown(text))
35 |
--------------------------------------------------------------------------------
/python/simple_irc_bot.py:
--------------------------------------------------------------------------------
1 | import socket
2 |
3 | SERVER = ''
4 | CHANNEL = ''
5 | BOTNICK = 'Bot_'
6 | PORT = 6667
7 | PASS = ''
8 |
9 |
10 | def sendmsg(msg):
11 | ircsock.send("PRIVMSG "+ CHANNEL +" :"+ msg +"\r\n")
12 |
13 | def joinchannel():
14 | ircsock.send("JOIN %s %s\r\n" % (CHANNEL, PASS))
15 |
16 | def identifying():
17 | ircsock.send("NICK %s\r\n" % BOTNICK)
18 | ircsock.send("USER %s %s any :%s\r\n" % (BOTNICK, SERVER, BOTNICK))
19 |
20 | def quit():
21 | ircsock.send("QUIT :%s\r\n" %('T+'))
22 | ircsock.close()
23 |
24 | ircsock = socket.socket()
25 | ircsock.connect((SERVER, PORT))
26 | identifying()
27 | joinchannel()
28 |
29 | while True:
30 | ircmsg = ircsock.recv(2048)
31 | ircmsg = ircmsg.strip('\n\r')
32 |
33 | if '!ping' in ircmsg:
34 | sendmsg('Pong!')
35 |
36 | if '!quit' in ircmsg:
37 | quit()
38 | break
39 |
40 | if ircmsg.find('PING') != -1:
41 | n = ircmsg.split(':')[1]
42 | ircsock.send('PONG :' + n)
43 |
44 | if '!commands' in ircmsg:
45 | sendmsg('Commads: !ping, !quit')
46 |
--------------------------------------------------------------------------------
/python/django/django_by_example/mysite/blog/templates/blog/base.html:
--------------------------------------------------------------------------------
1 | {% load blog_tags %}
2 | {% load staticfiles %}
3 |
4 |
5 |
6 | {% block title %}{% endblock %}
7 |
8 |
9 |
10 |
11 | {% block content %}
12 | {% endblock %}
13 |
14 |
30 |
31 |
--------------------------------------------------------------------------------
/python/django/django_by_example/README.md:
--------------------------------------------------------------------------------
1 | # Django By Example
2 |
3 | This folder has the codes examples from the book.
4 |
5 | * [Codes from chapter 1](https://github.com/delete/lab/tree/chapter1/python/django/django_by_example)
6 | * [Codes from chapter 2](https://github.com/delete/lab/tree/chapter2/python/django/django_by_example)
7 | * [Codes from chapter 3](https://github.com/delete/lab/tree/chapter3/python/django/django_by_example)
8 | * [Codes from chapter 4](https://github.com/delete/lab/tree/chapter4/python/django/django_by_example)
9 | * [Codes from chapter 5](https://github.com/delete/lab/tree/chapter5/python/django/django_by_example)
10 | * [Codes from chapter 6](https://github.com/delete/lab/tree/chapter6/python/django/django_by_example)
11 | * [Codes from chapter 7](https://github.com/delete/lab/tree/chapter7/python/django/django_by_example)
12 | * [Codes from chapter 8](https://github.com/delete/lab/tree/chapter8/python/django/django_by_example)
13 | * [Codes from chapter 9](https://github.com/delete/lab/tree/chapter9/python/django/django_by_example)
14 |
--------------------------------------------------------------------------------
/javascript/nodejs/http-request-post.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const http = require('http');
4 | const querystring = require('querystring');
5 | const postData = querystring.stringify({
6 | name: 'Fellipe Pinheiro'
7 | , type: 'aluno'
8 | });
9 | const options = {
10 | host: 'webschool-io.herokuapp.com'
11 | , method: 'POST'
12 | , path: '/api/pokemons'
13 | , headers: {
14 | 'Content-Type': 'application/x-www-form-urlenconded'
15 | , 'Content-Length': postData.length
16 | }
17 | };
18 |
19 | function callback (res) {
20 | console.log('STATUS: ' + res.statusCode);
21 | console.log('HEADERS: '+ JSON.stringify(res.headers));
22 |
23 | let data = '';
24 |
25 | res.setEncoding('utf8');
26 | res.on('data', (chunk) => {
27 | data += chunk;
28 | });
29 |
30 | res.on('end', () => {
31 | console.log('Dados finalizados: ', data);
32 | });
33 | }
34 |
35 | const req = http.request(options, callback);
36 |
37 | req.on('error', (e) => {
38 | console.log('ERROR: ' + e.message);
39 | });
40 |
41 | req.write(postData);
42 | req.end();
43 |
--------------------------------------------------------------------------------
/python/django/tutorials/django-channels/channels/dj_channels/chat/models.py:
--------------------------------------------------------------------------------
1 | from __future__ import unicode_literals
2 |
3 | from django.db import models
4 | from django.utils import timezone
5 |
6 |
7 | class Room(models.Model):
8 | name = models.TextField()
9 | label = models.SlugField(unique=True)
10 |
11 | def __unicode__(self):
12 | return self.label
13 |
14 |
15 | class Message(models.Model):
16 | room = models.ForeignKey(Room, related_name='messages')
17 | handle = models.TextField()
18 | message = models.TextField()
19 | timestamp = models.DateTimeField(default=timezone.now, db_index=True)
20 |
21 | def __unicode__(self):
22 | return '[{timestamp}] {handle}: {message}'.format(**self.as_dict())
23 |
24 | @property
25 | def formatted_timestamp(self):
26 | return self.timestamp.strftime('%b %-d %-I:%M %p')
27 |
28 | def as_dict(self):
29 | return {
30 | 'handle': self.handle,
31 | 'message': self.message,
32 | 'timestamp': self.formatted_timestamp
33 | }
34 |
--------------------------------------------------------------------------------
/javascript/nodejs/tutorials/nodeauth/app/models/user.js:
--------------------------------------------------------------------------------
1 | var mongoose = require('mongoose');
2 | var bcrypt = require('bcrypt-nodejs');
3 |
4 | var userSchema = mongoose.Schema({
5 |
6 | local: {
7 | email: String,
8 | password: String
9 | },
10 |
11 | facebook: {
12 | id: String,
13 | token: String,
14 | email: String,
15 | name: String
16 | },
17 |
18 | twitter: {
19 | id: String,
20 | token: String,
21 | displayName: String,
22 | username: String
23 | },
24 |
25 | google: {
26 | id: String,
27 | token: String,
28 | email: String,
29 | name: String
30 | }
31 | });
32 |
33 | // generating a hash
34 | userSchema.methods.generateHash = function(password) {
35 | return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
36 | };
37 |
38 | // checking if password is valid
39 | userSchema.methods.validPassword = function(password) {
40 | return bcrypt.compareSync(password, this.local.password);
41 | };
42 |
43 | // create the model for users and expose it to our app
44 | module.exports = mongoose.model('User', userSchema);
45 |
--------------------------------------------------------------------------------
/python/django/django_by_example/bookmarks/images/templates/images/image/list.html:
--------------------------------------------------------------------------------
1 | {% extends "base.html" %}
2 | {% block title %}Images bookmarked{% endblock %}
3 | {% block content %}
4 | Images bookmarked
5 |
6 | {% include "images/image/list_ajax.html" %}
7 |
8 | {% endblock %}
9 |
10 | {% block domready %}
11 | var page = 1;
12 | var empty_page = false;
13 | var block_request = false;
14 | $(window).scroll(function() {
15 | var margin = $(document).height() - $(window).height() - 200;
16 | if ($(window).scrollTop() > margin && empty_page == false && block_request == false) {
17 | block_request = true;
18 | page += 1;
19 | $.get('?page=' + page, function(data) {
20 | if(data == '') {
21 | empty_page = true;
22 | }
23 | else {
24 | block_request = false;
25 | $('#image-list').append(data);
26 | }
27 | });
28 | }
29 | });
30 | {% endblock %}
--------------------------------------------------------------------------------
/python/django/django_by_example/bookmarks/account/migrations/0003_contact.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import unicode_literals
3 |
4 | from django.db import migrations, models
5 | from django.conf import settings
6 |
7 |
8 | class Migration(migrations.Migration):
9 |
10 | dependencies = [
11 | migrations.swappable_dependency(settings.AUTH_USER_MODEL),
12 | ('account', '0002_auto_20160606_1317'),
13 | ]
14 |
15 | operations = [
16 | migrations.CreateModel(
17 | name='Contact',
18 | fields=[
19 | ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),
20 | ('created', models.DateTimeField(db_index=True, auto_now_add=True)),
21 | ('user_from', models.ForeignKey(related_name='rel_from_set', to=settings.AUTH_USER_MODEL)),
22 | ('user_to', models.ForeignKey(related_name='rel_to_set', to=settings.AUTH_USER_MODEL)),
23 | ],
24 | options={
25 | 'ordering': ('-created',),
26 | },
27 | ),
28 | ]
29 |
--------------------------------------------------------------------------------
/python/django/django_by_example/myshop/orders/templates/orders/order/create.html:
--------------------------------------------------------------------------------
1 | {% extends "shop/base.html" %}
2 | {% load i18n %}
3 | {% block title %}
4 | {% trans "Checkout" %}
5 | {% endblock %}
6 | {% block content %}
7 | {% trans "Checkout" %}
8 |
9 |
{% trans "Your order" %}
10 |
11 | {% for item in cart %}
12 | -
13 | {{ item.quantity }}x {{ item.product.name }}
14 | ${{ item.total_price }}
15 |
16 | {% endfor %}
17 | {% if cart.coupon %}
18 | -
19 | {% blocktrans with code=cart.coupon.code discount=cart.coupon.discount %}
20 | "{{ code }}" ({{ discount }}% off)
21 | {% endblocktrans %}
22 | - ${{ cart.get_discount|floatformat:"2" }}
23 |
24 | {% endif %}
25 |
26 |
27 | {% trans "Total" %}: ${{ cart.get_total_price_after_discount|floatformat:"2" }}
28 |
29 |
30 |
35 | {% endblock %}
--------------------------------------------------------------------------------
/python/django/django_by_example/myshop/shop/migrations/0006_remove_untranslated_fields.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import unicode_literals
3 |
4 | from django.db import migrations, models
5 |
6 |
7 | class Migration(migrations.Migration):
8 |
9 | dependencies = [
10 | ('shop', '0005_migrate_translatable_fields'),
11 | ]
12 |
13 | operations = [
14 | migrations.AlterModelOptions(
15 | name='product',
16 | options={'ordering': ('-created',)},
17 | ),
18 | migrations.RemoveField(
19 | model_name='category',
20 | name='name',
21 | ),
22 | migrations.RemoveField(
23 | model_name='category',
24 | name='slug',
25 | ),
26 | migrations.RemoveField(
27 | model_name='product',
28 | name='description',
29 | ),
30 | migrations.RemoveField(
31 | model_name='product',
32 | name='name',
33 | ),
34 | migrations.RemoveField(
35 | model_name='product',
36 | name='slug',
37 | ),
38 | ]
39 |
--------------------------------------------------------------------------------
/python/django/django_by_example/myshop/orders/static/css/pdf.css:
--------------------------------------------------------------------------------
1 | body {
2 | font-family:Helvetica, sans-serif;
3 | color:#222;
4 | line-height:1.5;
5 | }
6 |
7 | table {
8 | width:100%;
9 | border-spacing:0;
10 | border-collapse: collapse;
11 | margin:20px 0;
12 | }
13 |
14 | table th, table td {
15 | text-align:left;
16 | font-size:14px;
17 | padding:10px;
18 | margin:0;
19 | }
20 |
21 | tbody tr:nth-child(odd) {
22 | background:#efefef;
23 | }
24 |
25 | thead th, tbody tr.total {
26 | background:#5993bb;
27 | color:#fff;
28 | font-weight:bold;
29 | }
30 |
31 | h1 {
32 | margin:0;
33 | }
34 |
35 |
36 | .secondary {
37 | color:#bbb;
38 | margin-bottom:20px;
39 | }
40 |
41 | .num {
42 | text-align:right;
43 | }
44 |
45 | .paid, .pending {
46 | color:#1bae37;
47 | border:4px solid #1bae37;
48 | text-transform:uppercase;
49 | font-weight:bold;
50 | font-size:22px;
51 | padding:12px;
52 | float:right;
53 | transform: rotate(-15deg);
54 | margin-right:40px;
55 | }
56 |
57 | .pending {
58 | color:#a82d2d;
59 | border:4px solid #a82d2d;
60 | }
--------------------------------------------------------------------------------
/python/django/django_by_example/mysite/blog/migrations/0002_comment.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import unicode_literals
3 |
4 | from django.db import migrations, models
5 |
6 |
7 | class Migration(migrations.Migration):
8 |
9 | dependencies = [
10 | ('blog', '0001_initial'),
11 | ]
12 |
13 | operations = [
14 | migrations.CreateModel(
15 | name='Comment',
16 | fields=[
17 | ('id', models.AutoField(serialize=False, primary_key=True, verbose_name='ID', auto_created=True)),
18 | ('name', models.CharField(max_length=80)),
19 | ('email', models.EmailField(max_length=254)),
20 | ('body', models.TextField()),
21 | ('created', models.DateTimeField(auto_now_add=True)),
22 | ('updated', models.DateTimeField(auto_now=True)),
23 | ('active', models.BooleanField(default=True)),
24 | ('post', models.ForeignKey(to='blog.Post', related_name='comments')),
25 | ],
26 | options={
27 | 'ordering': ('created',),
28 | },
29 | ),
30 | ]
31 |
--------------------------------------------------------------------------------
/python/django/tutorials/django-channels/channels/dj_channels/chat/static/chat.js:
--------------------------------------------------------------------------------
1 | $(function() {
2 | // When we're using HTTPS, use WSS too.
3 | var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
4 | var chatsock = new ReconnectingWebSocket(ws_scheme + '://' + window.location.host + "/chat" + window.location.pathname);
5 |
6 | chatsock.onmessage = function(message) {
7 | var data = JSON.parse(message.data);
8 | var chat = $("#chat")
9 | var ele = $('
')
10 |
11 | ele.append(
12 | $(" | ").text(data.timestamp)
13 | )
14 | ele.append(
15 | $(" | ").text(data.handle)
16 | )
17 | ele.append(
18 | $(" | ").text(data.message)
19 | )
20 |
21 | chat.append(ele)
22 | };
23 |
24 | $("#chatform").on("submit", function(event) {
25 | var message = {
26 | handle: $('#handle').val(),
27 | message: $('#message').val(),
28 | }
29 | chatsock.send(JSON.stringify(message));
30 | $("#message").val('').focus();
31 | return false;
32 | });
33 | });
--------------------------------------------------------------------------------
/python/django/django_by_example/bookmarks/account/forms.py:
--------------------------------------------------------------------------------
1 | from django import forms
2 | from django.contrib.auth.models import User
3 |
4 | from .models import Profile
5 |
6 |
7 | class LoginForm(forms.Form):
8 | username = forms.CharField()
9 | password = forms.CharField(widget=forms.PasswordInput)
10 |
11 |
12 | class UserRegistrationForm(forms.ModelForm):
13 | password = forms.CharField(label='Password', widget=forms.PasswordInput)
14 | password2 = forms.CharField(
15 | label='Repeat Password', widget=forms.PasswordInput
16 | )
17 |
18 | class Meta:
19 | model = User
20 | fields = ('username', 'first_name', 'email')
21 |
22 | def clean_password2(self):
23 | cd = self.cleaned_data
24 | if cd['password'] != cd['password2']:
25 | raise forms.ValidationError('Passwords dont\'t match.')
26 | return cd['password2']
27 |
28 |
29 | class UserEditForm(forms.ModelForm):
30 | class Meta:
31 | model = User
32 | fields = ('first_name', 'last_name', 'email')
33 |
34 |
35 | class ProfileEditForm(forms.ModelForm):
36 | class Meta:
37 | model = Profile
38 | fields = ('date_of_birth', 'photo')
39 |
--------------------------------------------------------------------------------
/python/django/django_by_example/bookmarks/bookmarks/urls.py:
--------------------------------------------------------------------------------
1 | """bookmarks URL Configuration
2 |
3 | The `urlpatterns` list routes URLs to views. For more information please see:
4 | https://docs.djangoproject.com/en/1.8/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. Add an import: from blog import urls as blog_urls
14 | 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
15 | """
16 | from django.conf.urls import include, url
17 | from django.contrib import admin
18 | from django.conf import settings
19 | from django.conf.urls.static import static
20 |
21 |
22 | urlpatterns = [
23 | url(r'^admin/', include(admin.site.urls)),
24 | url(r'^account/', include('account.urls')),
25 | url(r'^images/', include('images.urls', namespace='images')),
26 | ]
27 |
28 | if settings.DEBUG:
29 | urlpatterns += static(
30 | settings.MEDIA_URL, document_root=settings.MEDIA_ROOT
31 | )
32 |
--------------------------------------------------------------------------------
/python/django/django_by_example/bookmarks/images/models.py:
--------------------------------------------------------------------------------
1 | from django.db import models
2 | from django.conf import settings
3 | from django.utils.text import slugify
4 | from django.core.urlresolvers import reverse
5 |
6 |
7 | class Image(models.Model):
8 | user = models.ForeignKey(
9 | settings.AUTH_USER_MODEL, related_name='images_created'
10 | )
11 |
12 | title = models.CharField(max_length=200)
13 | slug = models.SlugField(max_length=200, blank=True)
14 | url = models.URLField()
15 | image = models.ImageField(upload_to='images/%Y/%m/%d')
16 | description = models.TextField(blank=True)
17 | created = models.DateField(auto_now_add=True, db_index=True)
18 |
19 | users_like = models.ManyToManyField(
20 | settings.AUTH_USER_MODEL, related_name='images_liked', blank=True
21 | )
22 | total_likes = models.PositiveIntegerField(db_index=True, default=0)
23 |
24 | def __str__(self):
25 | return self.title
26 |
27 | def save(self, *args, **kwargs):
28 | if not self.slug:
29 | self.slug = slugify(self.title)
30 | super(Image, self).save(*args, **kwargs)
31 |
32 | def get_absolute_url(self):
33 | return reverse('images:detail', args=[self.id, self.slug])
34 |
--------------------------------------------------------------------------------
/python/django/django_by_example/mysite/mysite/urls.py:
--------------------------------------------------------------------------------
1 | """mysite URL Configuration
2 |
3 | The `urlpatterns` list routes URLs to views. For more information please see:
4 | https://docs.djangoproject.com/en/1.8/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. Add an import: from blog import urls as blog_urls
14 | 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
15 | """
16 | from django.conf.urls import include, url
17 | from django.contrib import admin
18 | from django.contrib.sitemaps.views import sitemap
19 |
20 | from blog.sitemaps import PostSitemap
21 |
22 | sitemaps = {
23 | 'posts': PostSitemap,
24 | }
25 |
26 | urlpatterns = [
27 | url(r'^admin/', include(admin.site.urls)),
28 | url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')),
29 | url(
30 | r'^sitemap\.xml$', sitemap,
31 | {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'
32 | ),
33 | ]
34 |
--------------------------------------------------------------------------------
/python/django/django_by_example/bookmarks/images/static/css/bookmarklet.css:
--------------------------------------------------------------------------------
1 | #bookmarklet {
2 | background:#fff;
3 | border-bottom:8px solid #12c064;
4 | font-family:"Helvetica Neue", helvetica, arial, sans-serif !important;
5 | padding:10px; overflow:auto;
6 | box-shadow:0px 0px 8px 0 #666;
7 | position:fixed;
8 | width:400px;
9 | min-height:200px;
10 | top:10px;
11 | right:10px;
12 | z-index:1000000000000;
13 | }
14 |
15 | #bookmarklet h1{
16 | font-family:"Helvetica Neue", helvetica, arial, sans-serif;
17 | font-weight:normal;
18 | color:#333;
19 | font-size:18px;
20 | padding:4px 0 20px 0;
21 | }
22 |
23 | #bookmarklet #close {
24 | float:right;
25 | font-size:18px;
26 | text-decoration:none;
27 | color:#666;
28 | margin-top:-6px;
29 | }
30 |
31 | #bookmarklet #close:hover {
32 | color:#000;
33 | }
34 |
35 | #bookmarklet .images {
36 | margin-bottom:20px;
37 | overflow:auto;
38 | }
39 |
40 | #bookmarklet .images img {
41 | border:1px solid #ccc;
42 | padding:2px;
43 | margin:2px;
44 | opacity:0.8;
45 | width:90px;
46 | float:left;
47 | }
48 |
49 | #bookmarklet .images img.selected,
50 | #bookmarklet .images img:hover {
51 | border:1px solid #12c064;
52 | opacity:1;
53 | }
54 |
--------------------------------------------------------------------------------
/python/django/django_by_example/bookmarks/actions/migrations/0001_initial.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import unicode_literals
3 |
4 | from django.db import migrations, models
5 | from django.conf import settings
6 |
7 |
8 | class Migration(migrations.Migration):
9 |
10 | dependencies = [
11 | migrations.swappable_dependency(settings.AUTH_USER_MODEL),
12 | ('contenttypes', '0002_remove_content_type_name'),
13 | ]
14 |
15 | operations = [
16 | migrations.CreateModel(
17 | name='Action',
18 | fields=[
19 | ('id', models.AutoField(serialize=False, primary_key=True, verbose_name='ID', auto_created=True)),
20 | ('verb', models.CharField(max_length=255)),
21 | ('target_id', models.PositiveIntegerField(blank=True, null=True, db_index=True)),
22 | ('created', models.DateTimeField(auto_now_add=True, db_index=True)),
23 | ('target_ct', models.ForeignKey(null=True, to='contenttypes.ContentType', blank=True, related_name='target_obj')),
24 | ('user', models.ForeignKey(related_name='actions', to=settings.AUTH_USER_MODEL)),
25 | ],
26 | options={
27 | 'ordering': ('-created',),
28 | },
29 | ),
30 | ]
31 |
--------------------------------------------------------------------------------
/python/django/tutorials/django-channels/channels/dj_channels/chat/templates/base.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | {% block title %}Django Channels Example{% endblock %}
6 |
7 |
8 | {% load staticfiles %}
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 | {% block content %}{% endblock content %}
17 |
18 |
19 | {% block afterbody %}{% endblock afterbody %}
20 |
21 |
22 |
--------------------------------------------------------------------------------
/python/django/django_by_example/bookmarks/images/migrations/0001_initial.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import unicode_literals
3 |
4 | from django.db import migrations, models
5 | from django.conf import settings
6 |
7 |
8 | class Migration(migrations.Migration):
9 |
10 | dependencies = [
11 | migrations.swappable_dependency(settings.AUTH_USER_MODEL),
12 | ]
13 |
14 | operations = [
15 | migrations.CreateModel(
16 | name='Image',
17 | fields=[
18 | ('id', models.AutoField(verbose_name='ID', auto_created=True, serialize=False, primary_key=True)),
19 | ('title', models.CharField(max_length=200)),
20 | ('slug', models.SlugField(blank=True, max_length=200)),
21 | ('url', models.URLField()),
22 | ('image', models.ImageField(upload_to='images/%Y/%m/%d')),
23 | ('description', models.TextField(blank=True)),
24 | ('created', models.DateField(db_index=True, auto_now_add=True)),
25 | ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL, related_name='images_created')),
26 | ('users_like', models.ManyToManyField(blank=True, related_name='images_liked', to=settings.AUTH_USER_MODEL)),
27 | ],
28 | ),
29 | ]
30 |
--------------------------------------------------------------------------------
/python/django/django_by_example/bookmarks/account/static/js/jquery.cookie.min.js:
--------------------------------------------------------------------------------
1 | /*! jquery.cookie v1.4.1 | MIT */
2 | !function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof exports?a(require("jquery")):a(jQuery)}(function(a){function b(a){return h.raw?a:encodeURIComponent(a)}function c(a){return h.raw?a:decodeURIComponent(a)}function d(a){return b(h.json?JSON.stringify(a):String(a))}function e(a){0===a.indexOf('"')&&(a=a.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\"));try{return a=decodeURIComponent(a.replace(g," ")),h.json?JSON.parse(a):a}catch(b){}}function f(b,c){var d=h.raw?b:e(b);return a.isFunction(c)?c(d):d}var g=/\+/g,h=a.cookie=function(e,g,i){if(void 0!==g&&!a.isFunction(g)){if(i=a.extend({},h.defaults,i),"number"==typeof i.expires){var j=i.expires,k=i.expires=new Date;k.setTime(+k+864e5*j)}return document.cookie=[b(e),"=",d(g),i.expires?"; expires="+i.expires.toUTCString():"",i.path?"; path="+i.path:"",i.domain?"; domain="+i.domain:"",i.secure?"; secure":""].join("")}for(var l=e?void 0:{},m=document.cookie?document.cookie.split("; "):[],n=0,o=m.length;o>n;n++){var p=m[n].split("="),q=c(p.shift()),r=p.join("=");if(e&&e===q){l=f(r,g);break}e||void 0===(r=f(r))||(l[q]=r)}return l};h.defaults={},a.removeCookie=function(b,c){return void 0===a.cookie(b)?!1:(a.cookie(b,"",a.extend({},c,{expires:-1})),!a.cookie(b))}});
--------------------------------------------------------------------------------
/python/django/django_by_example/myshop/orders/templates/orders/order/pdf.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | My Shop
4 |
5 | Invoice no. {{ order.id }}
6 |
7 | {{ order.created|date:"M d, Y" }}
8 |
9 |
10 | Bill to
11 |
12 | {{ order.first_name }} {{ order.last_name }}
13 | {{ order.email }}
14 | {{ order.address }}
15 | {{ order.postal_code }}, {{ order.city }}
16 |
17 | Items bought
18 |
19 |
20 |
21 | | Product |
22 | Price |
23 | Quantity |
24 | Cost |
25 |
26 |
27 |
28 | {% for item in order.items.all %}
29 |
30 | | {{ item.product.name }} |
31 | ${{ item.price }} |
32 | {{ item.quantity }} |
33 | ${{ item.get_cost }} |
34 |
35 | {% endfor %}
36 |
37 | | Total |
38 | ${{ order.get_total_cost }} |
39 |
40 |
41 |
42 |
43 | {% if order.paid %}Paid{% else %}Pending payment{% endif %}
44 |
45 |
46 |
--------------------------------------------------------------------------------
/javascript/nodejs/tutorials/nodeauth/views/profile.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Node Authentication
6 |
7 |
8 |
11 |
12 |
13 |
14 |
15 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
Local
26 |
27 |
28 | id: <%= user._id %>
29 | email: <%= user.local.email %>
30 | password: <%= user.local.password %>
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/python/django/django_by_example/myshop/shop/templates/shop/product/list.html:
--------------------------------------------------------------------------------
1 | {% extends "shop/base.html" %}
2 | {% load static %}
3 | {% block title %}
4 | {% if category %}{{ category.name }}{% else %}Products{% endif %}
5 | {% endblock %}
6 | {% block content %}
7 |
20 |
21 |
{% if category %}{{ category.name }}{% else %}Products{% endif %}
22 | {% for product in products %}
23 |
30 | {% endfor %}
31 |
32 | {% endblock %}
--------------------------------------------------------------------------------
/front-end/livros/domine_a_web_do_futuro/site_sao_paulo/style.css:
--------------------------------------------------------------------------------
1 | body {
2 | font-family: "Lucida Grande", "Lucida Sans Unicode", Verdana, sans-serif;
3 | line-height: 1.6;
4 | background: #FFF1D6;
5 | }
6 |
7 | .container {
8 | margin: 0 auto;
9 | width: 960px;
10 | }
11 |
12 | .places {
13 | float: left;
14 | width: 660px;
15 | }
16 |
17 | .place {
18 | background-color: #FFF;
19 | border-color: #CCC #999 #CCC;
20 | border: 1px solid #CCC;
21 | margin-bottom: 20px;
22 | padding: 10px;
23 | }
24 |
25 | .place h2 {
26 | border-bottom: 1px dashed #7E9F19;
27 | margin: 0px;
28 | }
29 |
30 | .place a {
31 | color: #2C88A7;
32 | font-weight: bold;
33 | }
34 |
35 | h1 a {
36 | color: #7E9F19;
37 | text-decoration: none;
38 | }
39 |
40 | h1 a:hover {
41 | background-color: #7E9F19;
42 | color: #FFF;
43 | }
44 |
45 | .place img {
46 | border: 1px solid #7E9F19;
47 | float: left;
48 | margin: 10px 10px 0 0;
49 | padding: 2px;
50 | }
51 |
52 | .clear {
53 | clear: both;
54 | }
55 |
56 | .sidenote {
57 | background-color: #FFFBE4;
58 | border: 1px solid #C9BC8F;
59 | padding: 10px;
60 | float: right;
61 | width: 260px;
62 | }
63 |
64 | .sidenote h3 {
65 | font-size: 14px;
66 | margin-top: 0;
67 | }
68 |
69 | .sidenote ol {
70 | font-size: 12px;
71 | }
72 |
73 | .footer {
74 | font-size: 12px;
75 | text-align: center;
76 | }
77 |
--------------------------------------------------------------------------------
/python/django/django_by_example/mysite/blog/migrations/0001_initial.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import unicode_literals
3 |
4 | from django.db import migrations, models
5 | from django.conf import settings
6 | import django.utils.timezone
7 |
8 |
9 | class Migration(migrations.Migration):
10 |
11 | dependencies = [
12 | migrations.swappable_dependency(settings.AUTH_USER_MODEL),
13 | ]
14 |
15 | operations = [
16 | migrations.CreateModel(
17 | name='Post',
18 | fields=[
19 | ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),
20 | ('title', models.CharField(max_length=250)),
21 | ('slug', models.SlugField(max_length=250, unique_for_date='publish')),
22 | ('body', models.TextField()),
23 | ('publish', models.DateTimeField(default=django.utils.timezone.now)),
24 | ('created', models.DateTimeField(auto_now_add=True)),
25 | ('updated', models.DateTimeField(auto_now=True)),
26 | ('status', models.CharField(max_length=10, choices=[('draft', 'Draft'), ('published', 'Published')], default='draft')),
27 | ('author', models.ForeignKey(related_name='blog_posts', to=settings.AUTH_USER_MODEL)),
28 | ],
29 | options={
30 | 'ordering': ('-publish',),
31 | },
32 | ),
33 | ]
34 |
--------------------------------------------------------------------------------
/python/django/tutorials/django-channels/channels/dj_channels/chat/templates/chat/room.html:
--------------------------------------------------------------------------------
1 | {% extends "base.html" %}
2 |
3 | {% block content %}
4 | {% load staticfiles %}
5 | {{ room.label }}
6 |
7 | Anyone with this URL can join the room and chat:
8 | {{ request.scheme }}://{{ request.get_host }}/{{ room.label }}
9 |
10 |
11 |
12 |
13 |
14 |
35 | {% endblock content %}
36 |
37 | {% block afterbody %}
38 |
39 |
40 |
41 | {% endblock afterbody %}
--------------------------------------------------------------------------------
/python/django/django_by_example/bookmarks/images/forms.py:
--------------------------------------------------------------------------------
1 | from urllib import request
2 |
3 | from django import forms
4 | from django.core.files.base import ContentFile
5 | from django.utils.text import slugify
6 |
7 | from .models import Image
8 |
9 |
10 | class ImageCreateForm(forms.ModelForm):
11 | class Meta:
12 | model = Image
13 | fields = ('title', 'url', 'description')
14 | widgets = {
15 | 'url': forms.HiddenInput,
16 | }
17 |
18 | def clean_url(self):
19 | url = self.cleaned_data['url']
20 | valid_extensions = ['jpg', 'jpeg']
21 | extensions = url.rsplit('.', 1)[1].lower()
22 |
23 | if extensions not in valid_extensions:
24 | raise forms.ValidationError(
25 | 'The given URL does not match valid image extensions.'
26 | )
27 |
28 | return self.cleaned_data['url']
29 |
30 | def save(self, force_insert=False, force_update=False, commit=True):
31 | image = super(ImageCreateForm, self).save(commit=False)
32 | image_url = self.cleaned_data['url']
33 | image_name = '{}.{}'.format(
34 | slugify(image.title), image_url.rsplit('.', 1)[1].lower()
35 | )
36 |
37 | # download image from the given url
38 | respose = request.urlopen(image_url)
39 | image.image.save(image_name, ContentFile(respose.read()), save=False)
40 |
41 | if commit:
42 | image.save()
43 |
44 | return image
45 |
--------------------------------------------------------------------------------
/javascript/nodejs/tutorials/nodeauth/server.js:
--------------------------------------------------------------------------------
1 | var express = require('express');
2 | var app = express();
3 | var port = process.env.PORT || 8080;
4 | var mongoose = require('mongoose');
5 | var passport = require('passport');
6 | var flash = require('connect-flash');
7 |
8 | var morgan = require('morgan');
9 | var cookieParser = require('cookie-parser');
10 | var bodyParser = require('body-parser');
11 | var session = require('express-session');
12 |
13 | var configDB = require('./config/database.js');
14 |
15 | // configurations =====================================
16 |
17 | // Connect to our database
18 | mongoose.connect(configDB.url);
19 |
20 | require('./config/passport')(passport);
21 |
22 | // Set up or express application
23 |
24 | // Log every request to the console - dev mode
25 | app.use(morgan('dev'));
26 |
27 | // Read cookies(need for auth)
28 | app.use(cookieParser());
29 |
30 | // Get information from html forms
31 | app.use(bodyParser());
32 |
33 | // Required for passport
34 | app.use(session( { secret:'huehuebrhuehue' } ));
35 | app.use(passport.initialize());
36 | // Persistent login sessions
37 | app.use(passport.session());
38 |
39 | app.use(flash());
40 |
41 | // routes =============================================
42 |
43 | // Load our routes and pass in our app and fully configured passport
44 | require('./app/routes.js')(app, passport);
45 |
46 |
47 | // launch ==============================================
48 |
49 | app.listen(port);
50 | console.log('The magic happens on port' + port);
51 |
--------------------------------------------------------------------------------
/python/django/tutorials/django-channels/channels/dj_channels/chat/migrations/0001_initial.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | # Generated by Django 1.9.4 on 2016-03-25 17:29
3 | from __future__ import unicode_literals
4 |
5 | from django.db import migrations, models
6 | import django.db.models.deletion
7 | import django.utils.timezone
8 |
9 |
10 | class Migration(migrations.Migration):
11 |
12 | initial = True
13 |
14 | dependencies = [
15 | ]
16 |
17 | operations = [
18 | migrations.CreateModel(
19 | name='Message',
20 | fields=[
21 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
22 | ('handle', models.TextField()),
23 | ('message', models.TextField()),
24 | ('timestamp', models.DateTimeField(db_index=True, default=django.utils.timezone.now)),
25 | ],
26 | ),
27 | migrations.CreateModel(
28 | name='Room',
29 | fields=[
30 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
31 | ('name', models.TextField()),
32 | ('label', models.SlugField(unique=True)),
33 | ],
34 | ),
35 | migrations.AddField(
36 | model_name='message',
37 | name='room',
38 | field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='messages', to='chat.Room'),
39 | ),
40 | ]
41 |
--------------------------------------------------------------------------------
/python/django/django_by_example/myshop/myshop/urls.py:
--------------------------------------------------------------------------------
1 | """myshop URL Configuration
2 |
3 | The `urlpatterns` list routes URLs to views. For more information please see:
4 | https://docs.djangoproject.com/en/1.8/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. Add an import: from blog import urls as blog_urls
14 | 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
15 | """
16 | from django.conf.urls import include, url
17 | from django.contrib import admin
18 | from django.conf import settings
19 | from django.conf.urls.static import static
20 | from django.conf.urls.i18n import i18n_patterns
21 | from django.utils.translation import gettext_lazy as _
22 |
23 |
24 | urlpatterns = i18n_patterns(
25 | url(r'^admin/', include(admin.site.urls)),
26 | url(_(r'^cart/'), include('cart.urls', namespace='cart')),
27 | url(_(r'^orders/'), include('orders.urls', namespace='orders')),
28 | url(_(r'^coupons/'), include('coupons.urls', namespace='coupons')),
29 | url(r'^rosetta/', include('rosetta.urls')),
30 | url(r'^', include('shop.urls', namespace='shop')),
31 | )
32 |
33 | if settings.DEBUG:
34 | urlpatterns += static(
35 | settings.MEDIA_URL, document_root=settings.MEDIA_ROOT
36 | )
37 |
--------------------------------------------------------------------------------
/python/django/django_by_example/mysite/blog/templates/blog/post/detail.html:
--------------------------------------------------------------------------------
1 | {% load blog_tags %}
2 | {% extends "blog/base.html" %}
3 | {% block title %}{{ post.title }}{% endblock %}
4 | {% block content %}
5 | {{ post.title }}
6 |
7 | Published {{ post.publish }} by {{ post.author }}
8 |
9 | {{ post.body|markdown }}
10 |
11 |
12 | Share this post
13 |
14 |
15 | {% with comments.count as total_comments %}
16 |
17 | {{ total_comments}} comment{{ total_comments|pluralize }}
18 |
19 | {% endwith %}
20 |
21 | Similar posts
22 | {% for post in similar_posts %}
23 | {{ post.title }}
24 | {% empty %}
25 | There are no similar posts yet.
26 | {% endfor %}
27 |
28 | {% for comment in comments %}
29 |
36 | {% empty %}
37 | There are no comments yet.
38 | {% endfor %}
39 |
40 | {% if new_comment %}
41 | Your comment has been added.
42 | {% else %}
43 | Add a new comment
44 |
49 | {% endif %}
50 | {% endblock %}
--------------------------------------------------------------------------------
/javascript/nodejs/tutorials/nodeauth/views/login.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Node Authentication
6 |
7 |
8 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
Login
18 |
19 |
20 | <% if (message.length > 0) { %>
21 |
<%= message %>
22 | <% } %>
23 |
24 |
25 |
37 |
38 |
39 |
40 |
Need an account? Signup
41 |
Or go home.
42 |
43 |
44 |
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/python/django/tutorials/django-channels/channels/dj_channels/chat/views.py:
--------------------------------------------------------------------------------
1 | import haikunator
2 |
3 | from django.db import transaction
4 | from django.shortcuts import render, redirect
5 | from django.core.urlresolvers import reverse
6 |
7 | from .models import Room
8 |
9 |
10 | def about(request):
11 | return render(request, "about.html")
12 |
13 |
14 | def new_room(request):
15 | """
16 | Randomly create a new room, and redirect to it.
17 | """
18 | new_room = None
19 | while not new_room:
20 | with transaction.atomic():
21 | label = haikunator.haikunate()
22 | if Room.objects.filter(label=label).exists():
23 | continue
24 | new_room = Room.objects.create(label=label)
25 | return redirect(reverse('chat:chat_room', args=[label]))
26 |
27 |
28 | def chat_room(request, label):
29 | """
30 | Room view - show the room, with latest messages.
31 |
32 | The template for this view has the WebSocket business to send and stream
33 | messages, so see the template for where the magic happens.
34 | """
35 | # If the room with the given label doesn't exist, automatically create it
36 | # upon first visit (a la etherpad).
37 | room, created = Room.objects.get_or_create(label=label)
38 |
39 | # We want to show the last 50 messages, ordered most-recent-last
40 | messages = reversed(room.messages.order_by("-timestamp")[:50])
41 |
42 | return render(request, "chat/room.html", {
43 | "room": room,
44 | "messages": messages
45 | })
46 |
--------------------------------------------------------------------------------
/javascript/nodejs/tutorials/nodeauth/views/signup.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Node Authentication
6 |
7 |
8 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
Signup
18 |
19 |
20 | <% if (message.length > 0) { %>
21 |
<%= message %>
22 | <% } %>
23 |
24 |
25 |
37 |
38 |
39 |
40 |
Already have an account? Login
41 |
Or go home.
42 |
43 |
44 |
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/python/django/django_by_example/myshop/shop/templates/shop/product/detail.html:
--------------------------------------------------------------------------------
1 | {% extends "shop/base.html" %}
2 | {% load i18n %}
3 | {% load static %}
4 |
5 | {% block title %}
6 | {{ product.name }}
7 | {% endblock %}
8 |
9 | {% block content %}
10 |
11 |

12 |
{{ product.name }}
13 |
14 |
${{ product.price }}
15 |
20 | {{ product.description|linebreaks }}
21 | {% if recommended_products %}
22 |
23 |
{% trans "People who bought this also bought" %}
24 | {% for p in recommended_products %}
25 |
31 | {% endfor %}
32 |
33 | {% endif %}
34 |
35 | {% endblock %}
--------------------------------------------------------------------------------
/javascript/nodejs/tutorials/nodeauth/app/routes.js:
--------------------------------------------------------------------------------
1 | module.exports = function(app, passport) {
2 | //
3 | // HOME page with login links
4 | //
5 | app.get('/', function(req, res) {
6 | res.render('index.ejs');
7 | });
8 |
9 | //
10 | // LOGIN
11 | //
12 | app.get('/login', function(req, res){
13 | res.render('login.ejs', {message: req.flash('loginMessage')});
14 | });
15 |
16 | // process the login form
17 | app.post('/login', passport.authenticate('local-login', {
18 | successRedirect : '/profile',
19 | failureRedirect : '/login',
20 | failureFlash : true
21 | }));
22 |
23 | //
24 | // SIGNUP
25 | //
26 | app.get('/signup', function(req, res){
27 | res.render('signup.ejs', { message: req.flash('signupMessage') });
28 | });
29 |
30 | //process the signup form
31 | app.post('/signup', passport.authenticate('local-signup', {
32 | successRedirect: '/profile',
33 | failureRedirect: '/signup',
34 | failureFlash: true
35 | }));
36 |
37 |
38 | //
39 | // PROFILE SECTION
40 | //
41 | app.get('/profile', isLoggedIn, function(req, res){
42 | res.render('profile.ejs', {
43 | // get the user out of session and pass to template
44 | user: req.user
45 | })
46 | });
47 |
48 | //
49 | // LOGOUT
50 | //
51 | app.get('/logout', function(req, res){
52 | req.logout();
53 | res.redirect('/');
54 | });
55 | };
56 |
57 | // route middleware to make sure a user is logged in
58 | function isLoggedIn(req, res, next) {
59 |
60 | if ( req.isAuthenticated() ) {
61 | return next();
62 | }
63 |
64 | res.redirect('/');
65 | }
66 |
--------------------------------------------------------------------------------
/python/django/django_by_example/myshop/shop/views.py:
--------------------------------------------------------------------------------
1 | from django.shortcuts import render, get_object_or_404
2 |
3 | from cart.forms import CartAddProductForm
4 |
5 | from .models import Category, Product
6 | from .recommender import Recommender
7 |
8 |
9 | def product_list(request, category_slug=None):
10 | category = None
11 | categories = Category.objects.all()
12 | products = Product.objects.filter(avaiable=True)
13 |
14 | if category_slug:
15 | language = request.LANGUAGE_CODE
16 | category = get_object_or_404(
17 | Category,
18 | translations__language_code=language,
19 | translations__slug=category_slug
20 | )
21 | products = products.filter(category=category)
22 |
23 | return render(
24 | request, 'shop/product/list.html',
25 | {'category': category, 'categories': categories, 'products': products}
26 | )
27 |
28 |
29 | def product_detail(request, id, slug):
30 | language = request.LANGUAGE_CODE
31 | product = get_object_or_404(
32 | Product,
33 | id=id,
34 | translations__language_code=language,
35 | translations__slug=slug,
36 | avaiable=True
37 | )
38 |
39 | cart_product_form = CartAddProductForm()
40 |
41 | r = Recommender()
42 | recommended_products = r.suggest_products_for([product], 4)
43 |
44 | return render(
45 | request, 'shop/product/detail.html',
46 | {
47 | 'product': product,
48 | 'cart_product_form': cart_product_form,
49 | 'recommended_products': recommended_products
50 | }
51 | )
52 |
--------------------------------------------------------------------------------
/python/django/django_by_example/myshop/shop/models.py:
--------------------------------------------------------------------------------
1 | from django.db import models
2 | from django.core.urlresolvers import reverse
3 |
4 | from parler.models import TranslatableModel, TranslatedFields
5 |
6 |
7 | class Category(TranslatableModel):
8 | translations = TranslatedFields(
9 | name=models.CharField(max_length=200, db_index=True),
10 | slug=models.SlugField(max_length=200, db_index=True, unique=True)
11 | )
12 |
13 | class Meta:
14 | # ordering = ('name', )
15 | verbose_name = 'category'
16 | verbose_name_plural = 'categories'
17 |
18 | def __str__(self):
19 | return self.name
20 |
21 | def get_absolute_url(self):
22 | return reverse('shop:product_list_by_category', args=[self.slug])
23 |
24 |
25 | class Product(TranslatableModel):
26 | translations = TranslatedFields(
27 | name=models.CharField(max_length=200, db_index=True),
28 | slug=models.SlugField(max_length=200, db_index=True),
29 | description=models.TextField(blank=True)
30 | )
31 | category = models.ForeignKey(Category, related_name='products')
32 | image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
33 | price = models.DecimalField(max_digits=10, decimal_places=2)
34 | stock = models.PositiveIntegerField()
35 | avaiable = models.BooleanField(default=True)
36 | created = models.DateTimeField(auto_now_add=True)
37 | updated = models.DateTimeField(auto_now=True)
38 |
39 | class Meta:
40 | ordering = ('-created', )
41 | # index_together = (('id'), ('slug'))
42 |
43 | def __str__(self):
44 | return self.name
45 |
46 | def get_absolute_url(self):
47 | return reverse('shop:product_detail', args=[self.id, self.slug])
48 |
--------------------------------------------------------------------------------
/python/django/django_by_example/mysite/blog/static/css/blog.css:
--------------------------------------------------------------------------------
1 | body {
2 | margin:0;
3 | padding:0;
4 | font-family:helvetica, sans-serif;
5 | }
6 |
7 | a {
8 | color:#00abff;
9 | text-decoration:none;
10 | }
11 |
12 | h1 {
13 | font-weight:normal;
14 | border-bottom:1px solid #bbb;
15 | padding:0 0 10px 0;
16 | }
17 |
18 | h2 {
19 | font-weight:normal;
20 | margin:30px 0 0;
21 | }
22 |
23 | #content {
24 | float:left;
25 | width:60%;
26 | padding:0 0 0 30px;
27 | }
28 |
29 | #sidebar {
30 | float:right;
31 | width:30%;
32 | padding:10px;
33 | background:#efefef;
34 | height:100%;
35 | }
36 |
37 | p.date {
38 | color:#ccc;
39 | font-family: georgia, serif;
40 | font-size: 12px;
41 | font-style: italic;
42 | }
43 |
44 | /* pagination */
45 | .pagination {
46 | margin:40px 0;
47 | font-weight:bold;
48 | }
49 |
50 | /* forms */
51 | label {
52 | float:left;
53 | clear:both;
54 | color:#333;
55 | margin-bottom:4px;
56 | }
57 | input, textarea {
58 | clear:both;
59 | float:left;
60 | margin:0 0 10px;
61 | background:#ededed;
62 | border:0;
63 | padding:6px 10px;
64 | font-size:12px;
65 | }
66 | input[type=submit] {
67 | font-weight:bold;
68 | background:#00abff;
69 | color:#fff;
70 | padding:10px 20px;
71 | font-size:14px;
72 | text-transform:uppercase;
73 | }
74 | .errorlist {
75 | color:#cc0033;
76 | float:left;
77 | clear:both;
78 | padding-left:10px;
79 | }
80 |
81 | /* comments */
82 | .comment {
83 | padding:10px;
84 | }
85 | .comment:nth-child(even) {
86 | background:#efefef;
87 | }
88 | .comment .info {
89 | font-weight:bold;
90 | font-size:12px;
91 | color:#666;
92 | }
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 |
5 | # C extensions
6 | *.so
7 |
8 | # Distribution / packaging
9 | .Python
10 | env/
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | *.egg-info/
23 | .installed.cfg
24 | *.egg
25 | *.sqlite3
26 | # PyInstaller
27 | # Usually these files are written by a python script from a template
28 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
29 | *.manifest
30 | *.spec
31 |
32 | # Installer logs
33 | pip-log.txt
34 | pip-delete-this-directory.txt
35 |
36 | # Unit test / coverage reports
37 | htmlcov/
38 | .tox/
39 | .coverage
40 | .coverage.*
41 | .cache
42 | nosetests.xml
43 | coverage.xml
44 | *,cover
45 |
46 | # Translations
47 | *.mo
48 | *.pot
49 |
50 | # Django stuff:
51 | *.log
52 | media/
53 | staticfiles/
54 |
55 | # Sphinx documentation
56 | docs/_build/
57 |
58 | # PyBuilder
59 | target/
60 |
61 |
62 | ### Node ###
63 | # Logs
64 | logs
65 | *.log
66 | npm-debug.log*
67 |
68 | # Runtime data
69 | pids
70 | *.pid
71 | *.seed
72 |
73 | # Directory for instrumented libs generated by jscoverage/JSCover
74 | lib-cov
75 |
76 | # Coverage directory used by tools like istanbul
77 | coverage
78 |
79 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
80 | .grunt
81 |
82 | # node-waf configuration
83 | .lock-wscript
84 |
85 | # Compiled binary addons (http://nodejs.org/api/addons.html)
86 | build/Release
87 |
88 | # Dependency directory
89 | # https://docs.npmjs.com/misc/faq#should-i-check-my-node-modules-folder-into-git
90 | node_modules
91 |
92 | # Optional npm cache directory
93 | .npm
94 |
95 | # Optional REPL history
96 | .node_repl_history
97 |
--------------------------------------------------------------------------------
/python/django/django_by_example/myshop/cart/views.py:
--------------------------------------------------------------------------------
1 | from django.shortcuts import render, redirect, get_object_or_404
2 | from django.views.decorators.http import require_POST
3 |
4 | from shop.models import Product
5 | from coupons.forms import CouponApplyForm
6 | from shop.recommender import Recommender
7 |
8 | from .cart import Cart
9 | from .forms import CartAddProductForm
10 |
11 |
12 | @require_POST
13 | def cart_add(request, product_id):
14 | cart = Cart(request)
15 | product = get_object_or_404(Product, id=product_id)
16 |
17 | form = CartAddProductForm(request.POST)
18 | if form.is_valid():
19 | cd = form.cleaned_data
20 | cart.add(
21 | product=product,
22 | quantity=cd['quantity'],
23 | update_quantity=cd['update']
24 | )
25 |
26 | return redirect('cart:cart_detail')
27 |
28 |
29 | def cart_remove(request, product_id):
30 | cart = Cart(request)
31 | product = get_object_or_404(Product, id=product_id)
32 | cart.remove(product)
33 | return redirect('cart:cart_detail')
34 |
35 |
36 | def cart_detail(request):
37 | cart = Cart(request)
38 | for item in cart:
39 | item['update_quantity_form'] = CartAddProductForm(
40 | initial={'quantity': item['quantity'], 'update': True}
41 | )
42 | coupon_apply_form = CouponApplyForm()
43 |
44 | r = Recommender()
45 |
46 | cart_products = [item['product'] for item in cart]
47 | recommended_products = r.suggest_products_for(cart_products, max_results=4)
48 |
49 | return render(
50 | request, 'cart/detail.html',
51 | {
52 | 'cart': cart,
53 | 'coupon_apply_form': coupon_apply_form,
54 | 'recommended_products': recommended_products
55 | }
56 | )
57 |
--------------------------------------------------------------------------------
/python/django/django_by_example/myshop/orders/locale/en/LC_MESSAGES/django.po:
--------------------------------------------------------------------------------
1 | # SOME DESCRIPTIVE TITLE.
2 | # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
3 | # This file is distributed under the same license as the PACKAGE package.
4 | # FIRST AUTHOR , YEAR.
5 | #
6 | #, fuzzy
7 | msgid ""
8 | msgstr ""
9 | "Project-Id-Version: PACKAGE VERSION\n"
10 | "Report-Msgid-Bugs-To: \n"
11 | "POT-Creation-Date: 2016-06-24 08:40-0300\n"
12 | "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
13 | "Last-Translator: FULL NAME \n"
14 | "Language-Team: LANGUAGE \n"
15 | "Language: \n"
16 | "MIME-Version: 1.0\n"
17 | "Content-Type: text/plain; charset=UTF-8\n"
18 | "Content-Transfer-Encoding: 8bit\n"
19 |
20 | #: orders/models.py:12
21 | msgid "first_name"
22 | msgstr ""
23 |
24 | #: orders/models.py:13
25 | msgid "last_name"
26 | msgstr ""
27 |
28 | #: orders/models.py:14
29 | msgid "e-mail"
30 | msgstr ""
31 |
32 | #: orders/models.py:15
33 | msgid "address"
34 | msgstr ""
35 |
36 | #: orders/models.py:16
37 | msgid "postal_code"
38 | msgstr ""
39 |
40 | #: orders/models.py:17
41 | msgid "city"
42 | msgstr ""
43 |
44 | #: orders/templates/orders/order/create.html:4
45 | #: orders/templates/orders/order/create.html:7
46 | msgid "Checkout"
47 | msgstr ""
48 |
49 | #: orders/templates/orders/order/create.html:9
50 | msgid "Your order"
51 | msgstr ""
52 |
53 | #: orders/templates/orders/order/create.html:19
54 | #, python-format
55 | msgid ""
56 | "\n"
57 | "\t\t\t\t\t\"%(code)s\" (%(discount)s%% off)\n"
58 | "\t\t\t\t"
59 | msgstr ""
60 |
61 | #: orders/templates/orders/order/create.html:27
62 | msgid "Total"
63 | msgstr ""
64 |
65 | #: orders/templates/orders/order/create.html:32
66 | msgid "Place order"
67 | msgstr ""
68 |
69 | #: orders/urls.py:8
70 | msgid "^create/$"
71 | msgstr ""
72 |
--------------------------------------------------------------------------------
/python/django/django_by_example/bookmarks/actions/templates/actions/action/detail.html:
--------------------------------------------------------------------------------
1 | {% load thumbnail %}
2 | {% with user=action.user profile=action.user.profile %}
3 |
4 |
5 | {% if profile.photo %}
6 | {% thumbnail user.profile.photo "80x80" crop="100%" as im %}
7 |
8 |
10 |
11 | {% endthumbnail %}
12 | {% endif %}
13 | {% if action.target %}
14 | {% with target=action.target %}
15 | {% if target.image %}
16 | {% thumbnail target.image "80x80" crop="100%" as im %}
17 |
18 |
19 |
20 | {% endthumbnail %}
21 | {% endif %}
22 | {% endwith %}
23 | {% endif %}
24 |
25 |
26 |
27 | {{ action.created|timesince }} ago
28 |
29 |
30 | {{ user.first_name }}
31 |
32 | {{ action.verb }}
33 | {% if action.target %}
34 | {% with target=action.target %}
35 | {{ target }}
36 | {% endwith %}
37 | {% endif %}
38 |
39 |
40 |
41 | {% endwith %}
--------------------------------------------------------------------------------
/git/README.md:
--------------------------------------------------------------------------------
1 | # Git snippets
2 |
3 |
4 | ## Rollback to a previous commit
5 |
6 | ```sh
7 | $ git reset --hard 8719a98b...
8 |
9 | $ git push --force origin master
10 | ```
11 |
12 | ## Move last commit no another branch
13 |
14 | ```sh
15 | git checkout existingbranch
16 | git merge master
17 | git checkout master
18 | git reset --hard HEAD~1 # Go back 1 commits. You *will* lose uncommitted work.
19 | git checkout existingbranch
20 | ```
21 |
22 | ## Change branch after of edited some files
23 | ```sh
24 | $ git stash
25 |
26 | $ git checkout foo
27 |
28 | $ git stash pop
29 | ```
30 |
31 | ## Amend changing
32 | ```sh
33 | $ git add file1.py
34 | $ git commit -m "First commit"
35 | ```
36 |
37 | Then you forgot some files
38 | ```sh
39 | $ git add file2.py
40 | $ git commit --amend --no-edit
41 | ```
42 | > "--no-edit" parameter fixes the file without change the commit message
43 |
44 | ## Force pull request overwrite local files
45 |
46 | ```sh
47 | $ git fetch --all
48 | $ git reset --hard origin/
49 | ```
50 |
51 | ## Simple deploy with GIT
52 | Access the server using SSH and follow the commands:
53 |
54 | ### Server side
55 |
56 | Create a directory to the app:
57 | `cd /myapps && mkdir app.git && cd app.git`
58 |
59 | Initiate git bare repository:
60 | `git init --bare`
61 |
62 | Set hooks up:
63 | `nano hooks/post-receive`
64 |
65 | Paste the content(must be the path to your app directory):
66 | ```
67 | #!/bin/sh
68 | GIT_WORK_TREE=/myapps git checkout -f
69 | ```
70 |
71 | Give to it an execution permission:
72 | `sudo chmod +x hooks/post-receive`
73 |
74 | ### Client side
75 |
76 | Add remote repository (change USER and DOMAIN to yours):
77 |
78 | `git remote add deploy USER@DOMAIN:/myapps/app.git`
79 |
80 | Now:
81 | ```
82 | git add .
83 | git commit -m “To server”
84 | git push deploy master
85 | ```
86 |
--------------------------------------------------------------------------------
/python/django/django_by_example/myshop/locale/en/LC_MESSAGES/django.po:
--------------------------------------------------------------------------------
1 | # SOME DESCRIPTIVE TITLE.
2 | # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
3 | # This file is distributed under the same license as the PACKAGE package.
4 | # FIRST AUTHOR , YEAR.
5 | #
6 | #, fuzzy
7 | msgid ""
8 | msgstr ""
9 | "Project-Id-Version: PACKAGE VERSION\n"
10 | "Report-Msgid-Bugs-To: \n"
11 | "POT-Creation-Date: 2016-06-24 08:40-0300\n"
12 | "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
13 | "Last-Translator: FULL NAME \n"
14 | "Language-Team: LANGUAGE \n"
15 | "Language: \n"
16 | "MIME-Version: 1.0\n"
17 | "Content-Type: text/plain; charset=UTF-8\n"
18 | "Content-Transfer-Encoding: 8bit\n"
19 |
20 | #: cart/forms.py:10
21 | msgid "Quantity"
22 | msgstr ""
23 |
24 | #: coupons/forms.py:6
25 | msgid "Coupon"
26 | msgstr ""
27 |
28 | #: myshop/settings.py:102
29 | msgid "English"
30 | msgstr ""
31 |
32 | #: myshop/settings.py:103
33 | msgid "Spanish"
34 | msgstr ""
35 |
36 | #: myshop/urls.py:26
37 | msgid "^cart/"
38 | msgstr ""
39 |
40 | #: myshop/urls.py:27
41 | msgid "^orders/"
42 | msgstr ""
43 |
44 | #: myshop/urls.py:28
45 | msgid "^coupons/"
46 | msgstr ""
47 |
48 | #: shop/templates/shop/base.html:7 shop/templates/shop/base.html.py:12
49 | msgid "My shop"
50 | msgstr ""
51 |
52 | #: shop/templates/shop/base.html:18
53 | msgid "Your cart"
54 | msgstr ""
55 |
56 | #: shop/templates/shop/base.html:20
57 | #, python-format
58 | msgid ""
59 | "\n"
60 | " %(total_items)s item%(total_items_plural)s,\n"
61 | " $%(total_price)s\n"
62 | " "
63 | msgstr ""
64 |
65 | #: shop/templates/shop/base.html:26
66 | msgid "Your cart is empty."
67 | msgstr ""
68 |
69 | #: shop/templates/shop/product/detail.html:17
70 | msgid "Add to cart"
71 | msgstr ""
72 |
--------------------------------------------------------------------------------
/python/tdd_by_example/five.py:
--------------------------------------------------------------------------------
1 | # Report collected results
2 |
3 |
4 | class TestCase:
5 | def __init__(self, name):
6 | self.name = name
7 |
8 | def setUp(self):
9 | pass
10 |
11 | def tearDown(self):
12 | pass
13 |
14 | def run(self):
15 | result = TestResult()
16 | result.testStarted()
17 | self.setUp()
18 | method = getattr(self, self.name)
19 | method()
20 | self.tearDown()
21 | return result
22 |
23 |
24 | class WasRun(TestCase):
25 | def __init__(self, name):
26 | self.wasRun = None
27 | TestCase.__init__(self, name)
28 |
29 | def setUp(self):
30 | self.log = "setUp "
31 |
32 | def testMethod(self):
33 | self.log = self.log + "testMethod "
34 |
35 | def testBrokenMethod(self):
36 | raise Exception
37 |
38 | def tearDown(self):
39 | self.log = self.log + "tearDown "
40 |
41 |
42 | class TestResult:
43 | def __init__(self):
44 | self.runCount = 0
45 |
46 | def testStarted(self):
47 | self.runCount += 1
48 |
49 | def summary(self):
50 | return "%d run, 0 failed" % self.runCount
51 |
52 |
53 | class TestCaseTest(TestCase):
54 | def testTemplateMethod(self):
55 | test = WasRun("testMethod")
56 | test.run()
57 | assert("setUp testMethod tearDown " == test.log)
58 |
59 | def testResult(self):
60 | test = WasRun("testMethod")
61 | result = test.run()
62 | assert("1 run, 0 failed" == result.summary())
63 |
64 | def testFailedResult(self):
65 | test = WasRun("testBrokenMethod")
66 | result = test.run()
67 | assert("1, run, 1 failed" == result.summary())
68 |
69 | TestCaseTest("testTemplateMethod").run()
70 | TestCaseTest("testResult").run()
71 | #TestCaseTest("testFailedResult").run()
72 |
--------------------------------------------------------------------------------
/python/django/django_by_example/myshop/orders/migrations/0001_initial.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import unicode_literals
3 |
4 | from django.db import migrations, models
5 |
6 |
7 | class Migration(migrations.Migration):
8 |
9 | dependencies = [
10 | ('shop', '0003_auto_20160613_1408'),
11 | ]
12 |
13 | operations = [
14 | migrations.CreateModel(
15 | name='Order',
16 | fields=[
17 | ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),
18 | ('first_name', models.CharField(max_length=50)),
19 | ('last_name', models.CharField(max_length=50)),
20 | ('email', models.EmailField(max_length=254)),
21 | ('address', models.CharField(max_length=250)),
22 | ('postal_code', models.CharField(max_length=20)),
23 | ('city', models.CharField(max_length=100)),
24 | ('created', models.DateTimeField(auto_now_add=True)),
25 | ('updated', models.DateTimeField(auto_now=True)),
26 | ('paid', models.BooleanField(default=False)),
27 | ],
28 | options={
29 | 'ordering': ('-created',),
30 | },
31 | ),
32 | migrations.CreateModel(
33 | name='OrderItem',
34 | fields=[
35 | ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),
36 | ('price', models.DecimalField(max_digits=10, decimal_places=2)),
37 | ('quantity', models.PositiveIntegerField(default=1)),
38 | ('order', models.ForeignKey(related_name='items', to='orders.Order')),
39 | ('product', models.ForeignKey(related_name='order_items', to='shop.Product')),
40 | ],
41 | ),
42 | ]
43 |
--------------------------------------------------------------------------------
/python/django/django_by_example/bookmarks/account/urls.py:
--------------------------------------------------------------------------------
1 | from django.conf.urls import url
2 |
3 | from . import views
4 |
5 | urlpatterns = [
6 | # url(r'^login/$', views.user_login, name='login'),
7 | url(r'^login/$', 'django.contrib.auth.views.login', name='login'),
8 | url(r'^logout/$', 'django.contrib.auth.views.logout', name='logout'),
9 | url(
10 | r'^logout-then-login/$', 'django.contrib.auth.views.logout_then_login',
11 | name='logout_then_login'
12 | ),
13 | url(r'^$', views.dashboard, name='dashboard'),
14 | url(
15 | r'^password-change/$', 'django.contrib.auth.views.password_change',
16 | name='password_change'
17 | ),
18 | url(
19 | r'^password-change/done/$',
20 | 'django.contrib.auth.views.password_change_done',
21 | name='password_change_done'
22 | ),
23 | url(
24 | r'^password-reset/$',
25 | 'django.contrib.auth.views.password_reset',
26 | name='password_reset'
27 | ),
28 | url(
29 | r'^password-reset/done/$',
30 | 'django.contrib.auth.views.password_reset_done',
31 | name='password_reset_done'
32 | ),
33 | url(
34 | r'^password-reset/confirm/(?P[-\w]+)/(?P[-\w]+)/$',
35 | 'django.contrib.auth.views.password_reset_confirm',
36 | name='password_reset_confirm'),
37 | url(
38 | r'^password-reset/complete/$',
39 | 'django.contrib.auth.views.password_reset_complete',
40 | name='password_reset_complete'
41 | ),
42 | url(r'^register/$', views.register, name='register'),
43 | url(r'^edit/$', views.edit, name='edit'),
44 | url(r'^users/$', views.user_list, name='user_list'),
45 | url(r'^users/follow/$', views.user_follow, name='user_follow'),
46 | url(
47 | r'^users/(?P[-\w]+)/$',
48 | views.user_detail, name='user_detail'
49 | ),
50 | ]
51 |
--------------------------------------------------------------------------------
/docker/README.md:
--------------------------------------------------------------------------------
1 | # Here will be stored "how to"s and some Dockerfiles/docker-compose examples.
2 |
3 | For more details, access the [Docker docs](https://docs.docker.com/):
4 |
5 | - About volumes and mounting data: [https://docs.docker.com/engine/userguide/dockervolumes/](https://docs.docker.com/engine/userguide/dockervolumes/)
6 |
7 | - About Dockerfile: [https://docs.docker.com/engine/reference/builder/](https://docs.docker.com/engine/reference/builder/)
8 |
9 | - About build images: [https://docs.docker.com/engine/reference/commandline/build/](https://docs.docker.com/engine/reference/commandline/build/)
10 |
11 | ## Run MongoDb server and client with Docker in different containers.
12 |
13 | **Server**
14 |
15 | `docker volume create --name mongodata`
16 |
17 | `docker run -d -p 27017:27017 --name mongod -v mongodata:/data mongo mongod`
18 |
19 | > Then just need to run `docker start mongod`, the line above does not need be repeated.
20 |
21 | **Client**
22 |
23 | `docker run -it mongo mongo IP:27017/data`
24 |
25 | ## Share node_modules with various projects(generic Dockerfile).
26 |
27 | > OBS: Use this tip for dev environment, only.
28 |
29 | First create a generic Dockerfile with:
30 |
31 | ```
32 | from node:argon
33 |
34 | RUN mkdir -p /install
35 |
36 | ENV NODE_PATH=/install/node_modules
37 |
38 | RUN mkdir /app
39 |
40 | WORKDIR /app/
41 | ```
42 |
43 | Then build an image running `docker build -t node-app .`
44 |
45 | Create a volume to store all node modules(to all projects):
46 |
47 | `docker volume create --name nodemodules`
48 |
49 | From the root of your project, access the shell to copy the package file and install the modules:
50 |
51 | `docker run -it -v nodemodules:/install -v $(pwd):/app node-app /bin/bash`
52 |
53 | `cp package.json /install && cd /install && npm install && exit`
54 |
55 | Now you can run your app, using something like this:
56 |
57 | `docker run -it -v nodemodules:/install -v $(pwd):/app node-app node index.js`
58 |
--------------------------------------------------------------------------------
/python/django/django_by_example/myshop/orders/models.py:
--------------------------------------------------------------------------------
1 | from decimal import Decimal
2 |
3 | from django.db import models
4 | from django.core.validators import MinValueValidator, MaxValueValidator
5 | from django.utils.translation import gettext_lazy as _
6 |
7 | from shop.models import Product
8 | from coupons.models import Coupon
9 |
10 |
11 | class Order(models.Model):
12 | first_name = models.CharField(_('first_name'), max_length=50)
13 | last_name = models.CharField(_('last_name'), max_length=50)
14 | email = models.EmailField(_('e-mail'), )
15 | address = models.CharField(_('address'), max_length=250)
16 | postal_code = models.CharField(_('postal_code'), max_length=20)
17 | city = models.CharField(_('city'), max_length=100)
18 | created = models.DateTimeField(auto_now_add=True)
19 | updated = models.DateTimeField(auto_now=True)
20 | paid = models.BooleanField(default=False)
21 |
22 | # Coupon fields
23 | coupon = models.ForeignKey(
24 | Coupon, related_name='orders', null=True, blank=True
25 | )
26 | # Preserve the value if the coupon is changed or deleted
27 | discount = models.IntegerField(
28 | default=0, validators=[MinValueValidator(0), MaxValueValidator(100)]
29 | )
30 |
31 | class Meta:
32 | ordering = ('-created', )
33 |
34 | def __str__(self):
35 | return 'Order {}'.format(self.id)
36 |
37 | def get_total_cost(self):
38 | total_cost = sum(item.get_cost() for item in self.items.all())
39 | return total_cost - total_cost * (self.discount / Decimal('100'))
40 |
41 |
42 | class OrderItem(models.Model):
43 | order = models.ForeignKey(Order, related_name='items')
44 | product = models.ForeignKey(Product, related_name='order_items')
45 | price = models.DecimalField(max_digits=10, decimal_places=2)
46 | quantity = models.PositiveIntegerField(default=1)
47 |
48 | def __str__(self):
49 | return '{}'.format(self.id)
50 |
51 | def get_cost(self):
52 | return self.price * self.quantity
53 |
--------------------------------------------------------------------------------
/python/django/django_by_example/myshop/shop/migrations/0001_initial.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import unicode_literals
3 |
4 | from django.db import migrations, models
5 |
6 |
7 | class Migration(migrations.Migration):
8 |
9 | dependencies = [
10 | ]
11 |
12 | operations = [
13 | migrations.CreateModel(
14 | name='Category',
15 | fields=[
16 | ('id', models.AutoField(primary_key=True, serialize=False, auto_created=True, verbose_name='ID')),
17 | ('name', models.CharField(db_index=True, max_length=200)),
18 | ('slug', models.SlugField(unique=True, max_length=200)),
19 | ],
20 | options={
21 | 'ordering': ('name',),
22 | 'verbose_name_plural': 'categories',
23 | 'verbose_name': 'category',
24 | },
25 | ),
26 | migrations.CreateModel(
27 | name='Product',
28 | fields=[
29 | ('id', models.AutoField(primary_key=True, serialize=False, auto_created=True, verbose_name='ID')),
30 | ('name', models.CharField(db_index=True, max_length=200)),
31 | ('slug', models.SlugField(max_length=200)),
32 | ('image', models.ImageField(upload_to='products/%Y/%m/%d', blank=True)),
33 | ('description', models.TextField(blank=True)),
34 | ('price', models.DecimalField(decimal_places=2, max_digits=10)),
35 | ('sotck', models.PositiveIntegerField()),
36 | ('avaiable', models.BooleanField(default=True)),
37 | ('created', models.DateTimeField(auto_now_add=True)),
38 | ('updated', models.DateTimeField(auto_now=True)),
39 | ('Category', models.ForeignKey(related_name='products', to='shop.Category')),
40 | ],
41 | options={
42 | 'ordering': ('name',),
43 | },
44 | ),
45 | migrations.AlterIndexTogether(
46 | name='product',
47 | index_together=set([('id', 'slug')]),
48 | ),
49 | ]
50 |
--------------------------------------------------------------------------------
/python/django/django_by_example/myshop/shop/migrations/0005_migrate_translatable_fields.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import unicode_literals
3 |
4 | from django.db import models, migrations
5 | from django.apps import apps
6 | from django.conf import settings
7 | from django.core.exceptions import ObjectDoesNotExist
8 |
9 |
10 | translatable_models = {
11 | 'Category': ['name', 'slug'],
12 | 'Product': ['name', 'slug', 'description'],
13 | }
14 |
15 |
16 | def forwards_func(apps, schema_editor):
17 | for model, fields in translatable_models.items():
18 | Model = apps.get_model('shop', model)
19 | ModelTranslation = apps.get_model('shop', '{}Translation'.format(model))
20 |
21 | for obj in Model.objects.all():
22 | translation_fields = {field: getattr(obj, field) for field in fields}
23 | translation = ModelTranslation.objects.create(
24 | master_id=obj.pk,
25 | language_code=settings.LANGUAGE_CODE,
26 | **translation_fields
27 | )
28 |
29 |
30 | def backwards_func(apps, schema_editor):
31 | for model, fields in translatable_models.items():
32 | Model = apps.get_model('shop', model)
33 | ModelTranslation = apps.get_model('shop', '{}Translation'.format(model))
34 |
35 | for obj in Model.objects.all():
36 | translation = _get_translation(obj, ModelTranslation)
37 | for field in fields:
38 | setattr(obj, field, getattr(translation, field))
39 | obj.save()
40 |
41 |
42 | def _get_translation(obj, MyModelTranslation):
43 | translations = MyModelTranslation.objects.filter(master_id=obj.pk)
44 | try:
45 | # Try default translation
46 | return translations.get(language_code=settings.LANGUAGE_CODE)
47 | except ObjectDoesNotExist:
48 | return translations.get()
49 |
50 |
51 | class Migration(migrations.Migration):
52 |
53 | dependencies = [
54 | ('shop', '0004_add_translation_model'),
55 | ]
56 |
57 | operations = [
58 | migrations.RunPython(forwards_func, backwards_func),
59 | ]
60 |
--------------------------------------------------------------------------------
/python/django/django_by_example/myshop/shop/templates/shop/base.html:
--------------------------------------------------------------------------------
1 | {% load i18n %}
2 | {% load static %}
3 |
4 |
5 |
6 |
7 | {% block title %}{% trans "My shop" %}{% endblock %}
8 |
9 |
10 |
11 |
29 |
30 |
47 |
48 | {% block content %}
49 | {% endblock %}
50 |
51 |
52 |
--------------------------------------------------------------------------------
/python/django/django_by_example/mysite/blog/models.py:
--------------------------------------------------------------------------------
1 | from django.db import models
2 | from django.utils import timezone
3 | from django.contrib.auth.models import User
4 | from django.core.urlresolvers import reverse
5 |
6 | from taggit.managers import TaggableManager
7 |
8 |
9 | class PublishedManager(models.Manager):
10 | def get_queryset(self):
11 | return super(
12 | PublishedManager, self
13 | ).get_queryset().filter(status='published')
14 |
15 |
16 | class Post(models.Model):
17 | STATUS_CHOICES = (
18 | ('draft', 'Draft'),
19 | ('published', 'Published')
20 | )
21 | title = models.CharField(max_length=250)
22 | slug = models.SlugField(max_length=250, unique_for_date='publish')
23 | author = models.ForeignKey(User, related_name='blog_posts')
24 | body = models.TextField()
25 | publish = models.DateTimeField(default=timezone.now)
26 | created = models.DateTimeField(auto_now_add=True)
27 | updated = models.DateTimeField(auto_now=True)
28 | status = models.CharField(
29 | max_length=10, choices=STATUS_CHOICES, default='draft'
30 | )
31 |
32 | objects = models.Manager()
33 | published = PublishedManager()
34 | tags = TaggableManager()
35 |
36 | class Meta:
37 | ordering = ('-publish',)
38 |
39 | def __str__(self):
40 | return self.title
41 |
42 | def get_absolute_url(self):
43 | return reverse(
44 | 'blog:post_detail',
45 | args=[
46 | self.publish.year,
47 | self.publish.strftime('%m'),
48 | self.publish.strftime('%d'),
49 | self.slug
50 | ]
51 | )
52 |
53 |
54 | class Comment(models.Model):
55 | post = models.ForeignKey(Post, related_name='comments')
56 | name = models.CharField(max_length=80)
57 | email = models.EmailField()
58 | body = models.TextField()
59 | created = models.DateTimeField(auto_now_add=True)
60 | updated = models.DateTimeField(auto_now=True)
61 | active = models.BooleanField(default=True)
62 |
63 | class Meta:
64 | ordering = ('created',)
65 |
66 | def __str__(self):
67 | return 'Comment by {} on {}'.format(self.name, self.post)
68 |
--------------------------------------------------------------------------------
/python/django/django_by_example/myshop/orders/admin.py:
--------------------------------------------------------------------------------
1 | import csv
2 | import datetime
3 |
4 | from django.http import HttpResponse
5 | from django.contrib import admin
6 | from django.core.urlresolvers import reverse
7 |
8 | from .models import Order, OrderItem
9 |
10 |
11 | def export_to_csv(modeladmin, request, queryset):
12 | opts = modeladmin.model._meta
13 | response = HttpResponse(content_type='text/csv')
14 | response['Content-Disposition'] = 'attachment; filename={}.csv'.format(
15 | opts.verbose_name
16 | )
17 | writer = csv.writer(response)
18 |
19 | fields = [
20 | field
21 | for field in opts.get_fields()
22 | if not field.many_to_many and not field.one_to_many
23 | ]
24 |
25 | # write a first row with header information
26 | writer.writerow([field.verbose_name for field in fields])
27 | # write data rows
28 | for obj in queryset:
29 | data_row = []
30 | for field in fields:
31 | value = getattr(obj, field.name)
32 | if isinstance(value, datetime.datetime):
33 | value = value.strftime('%d/%m/%Y')
34 | data_row.append(value)
35 | writer.writerow(data_row)
36 | return response
37 |
38 | export_to_csv.short_description = 'Export to CSV'
39 |
40 |
41 | class OrderItemInline(admin.TabularInline):
42 | model = OrderItem
43 | raw_id_fields = ['product']
44 |
45 |
46 | def order_detail(obj):
47 | return 'View'.format(
48 | reverse('orders:admin_order_detail', args=[obj.id])
49 | )
50 | order_detail.allow_tags = True
51 |
52 |
53 | def order_pdf(obj):
54 | return 'PDF'.format(
55 | reverse('orders:admin_order_pdf', args=[obj.id])
56 | )
57 | order_pdf.allow_tags = True
58 | order_pdf.short_description = 'PDF bill'
59 |
60 |
61 | class OrderAdmin(admin.ModelAdmin):
62 | list_display = [
63 | 'id', 'first_name', 'last_name', 'email', 'address', 'postal_code',
64 | 'city', 'paid', 'created', 'updated', order_detail, order_pdf
65 | ]
66 | list_filter = ['paid', 'created', 'updated']
67 | inlines = [OrderItemInline]
68 | actions = [export_to_csv]
69 |
70 |
71 | admin.site.register(Order, OrderAdmin)
72 |
--------------------------------------------------------------------------------
/python/django/django_by_example/bookmarks/account/templates/account/user/detail.html:
--------------------------------------------------------------------------------
1 | {% extends "base.html" %}
2 | {% load thumbnail %}
3 | {% block title %}{{ user.get_full_name }}{% endblock %}
4 | {% block content %}
5 | {{ user.get_full_name }}
6 |
7 | {% thumbnail user.profile.photo "180x180" crop="100%" as im %}
8 |

9 | {% endthumbnail %}
10 |
11 | {% with total_followers=user.followers.count %}
12 |
13 | {{ total_followers }}
14 | follower{{ total_followers|pluralize }}
15 |
16 | {% if request.user.id != user.id %}
17 |
18 | {% if request.user not in user.followers.all %}
19 | Follow
20 | {% else %}
21 | Unfollow
22 | {% endif %}
23 |
24 | {% endif %}
25 |
26 | {% include "images/image/list_ajax.html" with images=user.images_created.all %}
27 |
28 | {% endwith %}
29 | {% endblock %}
30 |
31 | {% block domready %}
32 | $('a.follow').click(function(e){
33 | e.preventDefault();
34 | $.post('{% url "user_follow" %}',
35 | {
36 | id: $(this).data('id'),
37 | action: $(this).data('action')
38 | },
39 | function(data){
40 | if (data['status'] == 'ok') {
41 | var previous_action = $('a.follow').data('action');
42 | // toggle data-action
43 | $('a.follow').data('action', previous_action == 'follow' ? 'unfollow' : 'follow');
44 | // toggle link text
45 | $('a.follow').text(previous_action == 'follow' ? 'Unfollow' : 'Follow');
46 | // update total followers
47 | var previous_followers = parseInt($('span.count .total').text());
48 | $('span.count .total').text(previous_action == 'follow' ? previous_followers + 1 : previous_followers - 1);
49 | }
50 | }
51 | );
52 | });
53 | {% endblock %}
--------------------------------------------------------------------------------
/python/tdd_by_example/six.py:
--------------------------------------------------------------------------------
1 | # Report failed tests
2 |
3 |
4 | class TestCase:
5 | def __init__(self, name):
6 | self.name = name
7 |
8 | def setUp(self):
9 | pass
10 |
11 | def tearDown(self):
12 | pass
13 |
14 | def run(self):
15 | result = TestResult()
16 | result.testStarted()
17 | self.setUp()
18 | try:
19 | method = getattr(self, self.name)
20 | method()
21 | except:
22 | result.testFailed()
23 | self.tearDown()
24 | return result
25 |
26 |
27 | class WasRun(TestCase):
28 | def __init__(self, name):
29 | self.wasRun = None
30 | TestCase.__init__(self, name)
31 |
32 | def setUp(self):
33 | self.log = "setUp "
34 |
35 | def testMethod(self):
36 | self.log = self.log + "testMethod "
37 |
38 | def testBrokenMethod(self):
39 | raise Exception
40 |
41 | def tearDown(self):
42 | self.log = self.log + "tearDown "
43 |
44 |
45 | class TestResult:
46 | def __init__(self):
47 | self.runCount = 0
48 | self.failureCount = 0
49 |
50 | def testStarted(self):
51 | self.runCount += 1
52 |
53 | def testFailed(self):
54 | self.failureCount += 1
55 |
56 | def summary(self):
57 | return "%d run, %d failed" % (self.runCount, self.failureCount)
58 |
59 |
60 | class TestCaseTest(TestCase):
61 | def testTemplateMethod(self):
62 | test = WasRun("testMethod")
63 | test.run()
64 | assert("setUp testMethod tearDown " == test.log)
65 |
66 | def testResult(self):
67 | test = WasRun("testMethod")
68 | result = test.run()
69 | assert("1 run, 0 failed" == result.summary())
70 |
71 | def testFailedResult(self):
72 | test = WasRun("testBrokenMethod")
73 | result = test.run()
74 | assert("1 run, 1 failed" == result.summary())
75 |
76 | def testFailedResultFormatting(self):
77 | result = TestResult()
78 | result.testStarted()
79 | result.testFailed()
80 | assert("1 run, 1 failed" == result.summary())
81 |
82 | print TestCaseTest("testTemplateMethod").run().summary()
83 | print TestCaseTest("testResult").run().summary()
84 | print TestCaseTest("testFailedResult").run().summary()
85 | print TestCaseTest("testFailedResultFormatting").run().summary()
86 |
--------------------------------------------------------------------------------
/python/django/django_by_example/myshop/orders/templates/admin/orders/order/detail.html:
--------------------------------------------------------------------------------
1 | {% extends "admin/base_site.html" %}
2 | {% load static %}
3 | {% block extrastyle %}
4 |
5 | {% endblock %}
6 | {% block title %}
7 | Order {{ order.id }} {{ block.super }}
8 | {% endblock %}
9 | {% block breadcrumbs %}
10 |
17 | {% endblock %}
18 | {% block content %}
19 | Order {{ order.id }}
20 |
25 |
26 |
27 | | Created |
28 | {{ order.created }} |
29 |
30 |
31 | | Customer |
32 | {{ order.first_name }} {{ order.last_name }} |
33 |
34 |
35 | | E-mail |
36 | {{ order.email }} |
37 |
38 |
39 | | Address |
40 | {{ order.address }}, {{ order.postal_code }} {{ order.city }} |
41 |
42 |
43 | | Total amount |
44 | ${{ order.get_total_cost }} |
45 |
46 |
47 | | Status |
48 | {% if order.paid %}Paid{% else %}Pending payment{% endif %} |
49 |
50 |
51 |
80 | {% endblock %}
--------------------------------------------------------------------------------
/python/django/django_by_example/bookmarks/account/templates/base.html:
--------------------------------------------------------------------------------
1 | {% load staticfiles %}
2 |
3 |
4 |
5 | {% block title %}{% endblock %}
6 |
7 |
8 |
9 |
33 | {% if messages %}
34 |
35 | {% for message in messages %}
36 | -
37 | {{ message|safe }}
38 | ✖
39 |
40 | {% endfor %}
41 |
42 | {% endif %}
43 |
44 | {% block content %}
45 | {% endblock %}
46 |
47 |
48 |
49 |
50 |
68 |
69 |
--------------------------------------------------------------------------------
/python/django/django_by_example/myshop/orders/locale/es/LC_MESSAGES/django.po:
--------------------------------------------------------------------------------
1 | # SOME DESCRIPTIVE TITLE.
2 | # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
3 | # This file is distributed under the same license as the PACKAGE package.
4 | # FIRST AUTHOR , YEAR.
5 | #
6 | #, fuzzy
7 | msgid ""
8 | msgstr ""
9 | "Project-Id-Version: PACKAGE VERSION\n"
10 | "Report-Msgid-Bugs-To: \n"
11 | "POT-Creation-Date: 2016-06-24 08:40-0300\n"
12 | "PO-Revision-Date: 2015-06-14 08:38+0000\n"
13 | "Last-Translator: b' '\n"
14 | "Language-Team: LANGUAGE \n"
15 | "Language: \n"
16 | "MIME-Version: 1.0\n"
17 | "Content-Type: text/plain; charset=UTF-8\n"
18 | "Content-Transfer-Encoding: 8bit\n"
19 | "Plural-Forms: nplurals=2; plural=(n != 1);\n"
20 | "X-Translated-Using: django-rosetta 0.7.6\n"
21 |
22 | #: orders/models.py:12
23 | #, fuzzy
24 | #| msgid "first name"
25 | msgid "first_name"
26 | msgstr "nombre"
27 |
28 | #: orders/models.py:13
29 | #, fuzzy
30 | #| msgid "last name"
31 | msgid "last_name"
32 | msgstr "apellidos"
33 |
34 | #: orders/models.py:14
35 | msgid "e-mail"
36 | msgstr "e-mail"
37 |
38 | #: orders/models.py:15
39 | msgid "address"
40 | msgstr "dirección"
41 |
42 | #: orders/models.py:16
43 | #, fuzzy
44 | #| msgid "postal code"
45 | msgid "postal_code"
46 | msgstr "código postal"
47 |
48 | #: orders/models.py:17
49 | msgid "city"
50 | msgstr "ciudad"
51 |
52 | #: orders/templates/orders/order/create.html:4
53 | #: orders/templates/orders/order/create.html:7
54 | msgid "Checkout"
55 | msgstr "Compra"
56 |
57 | #: orders/templates/orders/order/create.html:9
58 | msgid "Your order"
59 | msgstr "Tu compra"
60 |
61 | #: orders/templates/orders/order/create.html:19
62 | #, python-format
63 | msgid ""
64 | "\n"
65 | "\t\t\t\t\t\"%(code)s\" (%(discount)s%% off)\n"
66 | "\t\t\t\t"
67 | msgstr ""
68 |
69 | #: orders/templates/orders/order/create.html:27
70 | msgid "Total"
71 | msgstr "Total"
72 |
73 | #: orders/templates/orders/order/create.html:32
74 | msgid "Place order"
75 | msgstr "Comprar"
76 |
77 | #: orders/urls.py:8
78 | msgid "^create/$"
79 | msgstr "^crear/$"
80 |
81 | #~ msgid "Thank you"
82 | #~ msgstr "Gracias"
83 |
84 | #~ msgid ""
85 | #~ "\n"
86 | #~ " Your order has been successfully completed. Your order number "
87 | #~ "is %(order_id)s.
\n"
88 | #~ " "
89 | #~ msgstr ""
90 | #~ "\n"
91 | #~ "Tu pedido se ha completado correctamente. El número de tu pedido es "
92 | #~ "%(order_id)s.
"
93 |
--------------------------------------------------------------------------------
/python/django/django_by_example/myshop/orders/views.py:
--------------------------------------------------------------------------------
1 | from django.shortcuts import render, get_object_or_404
2 | from django.contrib.admin.views.decorators import staff_member_required
3 | from django.conf import settings
4 | from django.http import HttpResponse
5 | from django.template.loader import render_to_string
6 | import weasyprint
7 |
8 | from cart.cart import Cart
9 |
10 | from .models import OrderItem, Order
11 | from .forms import OrderCreateForm
12 | from .tasks import order_created
13 |
14 |
15 | # checks that both is_active and is_staff are True
16 | @staff_member_required
17 | def admin_order_detail(request, order_id):
18 | order = get_object_or_404(Order, id=order_id)
19 | return render(request, 'admin/orders/order/detail.html', {'order': order})
20 |
21 |
22 | @staff_member_required
23 | def admin_order_pdf(request, order_id):
24 | order = get_object_or_404(Order, id=order_id)
25 |
26 | html = render_to_string('orders/order/pdf.html', {'order': order})
27 |
28 | response = HttpResponse(content_type='application/pdf')
29 | response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(
30 | order.id
31 | )
32 |
33 | weasyprint.HTML(string=html).write_pdf(
34 | response,
35 | stylesheets=[
36 | weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')
37 | ]
38 | )
39 |
40 | return response
41 |
42 |
43 | def order_create(request):
44 | cart = Cart(request)
45 |
46 | if request.method == 'POST':
47 | form = OrderCreateForm(request.POST)
48 | if form.is_valid():
49 | order = form.save(commit=False)
50 |
51 | if cart.coupon:
52 | order.coupon = cart.coupon
53 | order.discount = cart.coupon.discount
54 | order.save()
55 |
56 | for item in cart:
57 | OrderItem.objects.create(
58 | order=order,
59 | product=item['product'],
60 | price=item['price'],
61 | quantity=item['quantity']
62 | )
63 | # clear the cart
64 | cart.clear()
65 | # launch asynchronous task
66 | # order_created.delay(order.id)
67 | return render(
68 | request, 'orders/order/created.html', {'order': order}
69 | )
70 | else:
71 | form = OrderCreateForm()
72 |
73 | return render(
74 | request, 'orders/order/create.html', {'cart': cart, 'form': form}
75 | )
76 |
--------------------------------------------------------------------------------
/python/django/django_by_example/myshop/shop/recommender.py:
--------------------------------------------------------------------------------
1 | import redis
2 | from django.conf import settings
3 |
4 | from .models import Product
5 |
6 |
7 | # connect to redis
8 | r = redis.StrictRedis(
9 | host=settings.REDIS_HOST,
10 | port=settings.REDIS_PORT,
11 | db=settings.REDIS_DB
12 | )
13 |
14 |
15 | class Recommender(object):
16 |
17 | def get_product_key(self, id):
18 | return 'product:{}:purchased_with'.format(id)
19 |
20 | def products_bought(self, products):
21 | product_ids = [p.id for p in products]
22 | for product_id in product_ids:
23 | for with_id in product_ids:
24 | # get the other products bought with each product
25 | if product_id != with_id:
26 | # increment score for product porchased together
27 | r.zincrby(
28 | self.get_product_key(product_id), with_id, amount=1
29 | )
30 |
31 | def suggest_products_for(self, products, max_results=6):
32 | product_ids = [p.id for p in products]
33 | if len(products) == 1:
34 | # only 1 product
35 | suggestions = r.zrange(
36 | self.get_product_key(product_ids[0]), 0, -1, desc=True
37 | )[: max_results]
38 | else:
39 | # generate a temporary key
40 | flat_ids = ''.join([str(id) for id in product_ids])
41 | tmp_key = 'tmp_{}'.format(flat_ids)
42 | # multiple products, combine scores of all products
43 | # store the resulting sorted set in a temporary key
44 | keys = [self.get_product_key(id) for id in product_ids]
45 | r.zunionstore(tmp_key, keys)
46 | # remove ids for the products the recommendation is for
47 | r.zrem(tmp_key, *product_ids)
48 | # get the product ids by their score, descendant sort
49 | suggestions = r.zrange(tmp_key, 0, -1, desc=True)[:max_results]
50 | # remove the remporary key
51 | r.delete(tmp_key)
52 |
53 | suggested_products_ids = [int(id) for id in suggestions]
54 | # get suggested products and sort by order of appearance
55 | suggested_products = list(
56 | Product.objects.filter(id__in=suggested_products_ids)
57 | )
58 | suggested_products.sort(
59 | key=lambda x: suggested_products_ids.index(x.id)
60 | )
61 |
62 | return suggested_products
63 |
64 | def clear_purchases(self):
65 | for id in Product.objects.values_list('id', flat=True):
66 | r.delete(self.get_product_key(id))
67 |
--------------------------------------------------------------------------------
/javascript/add_rm_li_from_ul.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Add and remove item from list
5 |
6 |
7 |
8 |
9 | -
10 | Item 1
11 |
12 |
13 | -
14 | Item 2
15 |
16 |
17 | -
18 | Item 3
19 |
20 |
21 |
22 |
23 |
24 |
88 |
89 |
--------------------------------------------------------------------------------
/python/django/django_by_example/bookmarks/images/templates/images/image/detail.html:
--------------------------------------------------------------------------------
1 | {% extends "base.html" %}
2 | {% block title %}{{ image.title }}{% endblock %}
3 | {% block content %}
4 | {{ image.title }}
5 | {% load thumbnail %}
6 | {% thumbnail image.image "300" as im %}
7 |
8 |
9 |
10 | {% endthumbnail %}
11 | {% with total_likes=image.users_like.count users_like=image.users_like.all %}
12 |
13 |
29 | {{ image.description|linebreaks }}
30 |
31 |
32 | {% for user in image.users_like.all %}
33 |
34 |

35 |
{{ user.first_name }}
36 |
37 | {% empty %}
38 | Nobody likes this image yet.
39 | {% endfor %}
40 |
41 | {% endwith %}
42 | {% endblock %}
43 |
44 | {% block domready %}
45 | $('a.like').click(function(e){
46 | e.preventDefault();
47 | $.post('{% url "images:like" %}',
48 | {
49 | id: $(this).data('id'),
50 | action: $(this).data('action')
51 | },
52 | function(data){
53 | if (data['status'] == 'ok')
54 | {
55 | var previous_action = $('a.like').data('action');
56 | // toggle data-action
57 | $('a.like').data('action', previous_action == 'like' ?'unlike' : 'like');
58 | // toggle link text
59 | $('a.like').text(previous_action == 'like' ? 'Unlike' :'Like');
60 | // update total likes
61 | var previous_likes = parseInt($('span.count .total').text());
62 | $('span.count .total').text(previous_action == 'like' ?previous_likes + 1 : previous_likes - 1);
63 | }
64 | }
65 | );
66 | });
67 | {% endblock %}
--------------------------------------------------------------------------------
/python/django/django_by_example/bookmarks/images/static/js/bookmarklet.js:
--------------------------------------------------------------------------------
1 | (function(){
2 | var jquery_version = '2.1.4';
3 | var site_url = 'http://127.0.0.1:8000/';
4 | var static_url = site_url + 'static/';
5 | var min_width = 100;
6 | var min_height = 100;
7 |
8 | function bookmarklet(msg) {
9 | // load CSS
10 | var css = jQuery('');
11 | css.attr({
12 | rel: 'stylesheet',
13 | type: 'text/css',
14 | href: static_url + 'css/bookmarklet.css?r=' + Math.floor(Math.random()*99999999999999999999)
15 | });
16 | jQuery('head').append(css);
17 |
18 | // load HTML
19 | box_html = '×Select an image to bookmark:
';
20 | jQuery('body').append(box_html);
21 |
22 | // close event
23 | jQuery('#bookmarklet #close').click(function(){
24 | jQuery('#bookmarklet').remove();
25 | });
26 |
27 | // find images and display them
28 | jQuery.each(jQuery('img[src$="jpg"]'), function(index, image) {
29 | if (jQuery(image).width() >= min_width && jQuery(image).height() >= min_height)
30 | {
31 | image_url = jQuery(image).attr('src');
32 | jQuery('#bookmarklet .images').append('
');
33 | }
34 | });
35 |
36 | // when an image is selected open URL with it
37 | jQuery('#bookmarklet .images a').click(function(e){
38 | selected_image = jQuery(this).children('img').attr('src');
39 | // hide bookmarklet
40 | jQuery('#bookmarklet').hide();
41 | // open new window to submit the image
42 | window.open(site_url +'images/create/?url='
43 | + encodeURIComponent(selected_image)
44 | + '&title=' + encodeURIComponent(jQuery('title').text()),
45 | '_blank');
46 | });
47 |
48 | };
49 | // Check if jQuery is loaded
50 | if(typeof window.jQuery != 'undefined') {
51 | bookmarklet();
52 | } else {
53 | // Check for conflicts
54 | var conflict = typeof window.$ != 'undefined';
55 | // Create the script and point to Google API
56 | var script = document.createElement('script');
57 | script.setAttribute('src','http://ajax.googleapis.com/ajax/libs/jquery/' + jquery_version + '/jquery.min.js');
58 | // Add the script to the 'head' for processing
59 | document.getElementsByTagName('head')[0].appendChild(script);
60 | // Create a way to wait until script loading
61 | var attempts = 15;
62 | (function(){
63 | // Check again if jQuery is undefined
64 | if(typeof window.jQuery == 'undefined') {
65 | if(--attempts > 0) {
66 | // Calls himself in a few milliseconds
67 | window.setTimeout(arguments.callee, 250)
68 | } else {
69 | // Too much attempts to load, send error
70 | alert('An error ocurred while loading jQuery')
71 | }
72 | } else {
73 | bookmarklet();
74 | }
75 | })();
76 | }
77 |
78 | })()
79 |
--------------------------------------------------------------------------------
/python/django/django_by_example/myshop/cart/templates/cart/detail.html:
--------------------------------------------------------------------------------
1 | {% extends "shop/base.html" %}
2 | {% load i18n %}
3 | {% load static %}
4 | {% block title %}
5 | Your shopping cart
6 | {% endblock %}
7 | {% block content %}
8 | Your shopping cart
9 |
10 |
11 |
12 | | Image |
13 | Product |
14 | Quantity |
15 | Remove |
16 | Unit price |
17 | Price |
18 |
19 |
20 |
21 | {% for item in cart %}
22 | {% with product=item.product %}
23 |
24 |
25 |
26 |
27 |
28 | |
29 | {{ product.name }} |
30 |
31 |
37 | |
38 | Remove |
39 | ${{ item.price }} |
40 | ${{ item.total_price }} |
41 |
42 | {% endwith %}
43 | {% endfor %}
44 | {% if cart.coupon %}
45 |
46 | | Subtotal |
47 | |
48 | ${{ cart.get_total_price }} |
49 |
50 |
51 | |
52 | "{{ cart.coupon.code }}" coupon
53 | ({{ cart.coupon.discount }}% off)
54 | |
55 | |
56 |
57 | - ${{ cart.get_discount|floatformat:"2" }}
58 | |
59 |
60 | {% endif %}
61 |
62 | | Total |
63 | |
64 |
65 | ${{ cart.get_total_price_after_discount|floatformat:"2" }}
66 | |
67 |
68 |
69 |
70 | {% if recommended_products %}
71 |
72 |
{% trans 'People who bought this also bought' %}
73 | {% for p in recommended_products %}
74 |
80 | {% endfor %}
81 |
82 | {% endif %}
83 | Apply a coupon:
84 |
89 |
90 | Continue shopping
91 | Checkout
92 |
93 | {% endblock %}
--------------------------------------------------------------------------------
/javascript/rock_paper_scissors/rock_paper_scissors.js:
--------------------------------------------------------------------------------
1 | var CHOICES = {
2 | 'rock': 'images/rock.png',
3 | 'paper': 'images/paper.jpg',
4 | 'scissors': 'images/scissors.png'
5 | };
6 |
7 | (function () {
8 | var chooseOptions = document.getElementById('options');
9 |
10 | chooseOptions.addEventListener('click', function (event) {
11 | var target = event.toElement || event.srcTarget || event.target || event.srcElement;
12 |
13 | var playerChoice = target.id;
14 | var computerChoice = getComputerChoice();
15 |
16 | displayResults(playerChoice, computerChoice);
17 |
18 | setTimeout(function(){
19 | defaultEnv()
20 | }, 1500);
21 | });
22 | }());
23 |
24 | function getComputerChoice () {
25 | var options = ['rock', 'paper', 'scissors'];
26 | return options[Math.floor(Math.random()*3)];
27 | };
28 |
29 | function displayResults (playerChoice, compChoice) {
30 |
31 | changeImages(playerChoice, compChoice);
32 |
33 | if ( playerChoice == compChoice ) {
34 | setResultMessage('Tie!', 'tie');
35 |
36 | } else if ( (isRock(playerChoice) && isScissors(compChoice)) ||
37 | (isPaper(playerChoice) && isRock(compChoice)) ||
38 | (isScissors(playerChoice) && isPaper(compChoice)) ) {
39 | setResultMessage('You Win!', 'win');
40 |
41 | } else {
42 | setResultMessage('You Lose!', 'lose');
43 | }
44 |
45 | function isRock(choice) {
46 | return choice === 'rock'
47 | }
48 | function isScissors(choice){
49 | return choice === 'scissors'
50 | }
51 | function isPaper(choice) {
52 | return choice === 'paper'
53 | }
54 |
55 | };
56 |
57 | function changeImages (playerChoice, compChoice) {
58 | var playerHand = document.getElementById('right_hand');
59 | playerHand.setAttribute('src', CHOICES[playerChoice]);
60 |
61 | var compHand = document.getElementById('left_hand');
62 | compHand.setAttribute('src', CHOICES[compChoice]);
63 | };
64 |
65 | function setResultMessage (text, result) {
66 | var message = document.getElementById('message');
67 |
68 | switch (result) {
69 | case 'tie':
70 | message.setAttribute('class', 'tie');
71 | message.innerHTML = text;
72 | break;
73 |
74 | case 'win':
75 | message.setAttribute('class', 'win');
76 | message.innerHTML = text;
77 | break;
78 |
79 | case 'lose':
80 | message.setAttribute('class', 'lose');
81 | message.innerHTML = text;
82 | break;
83 |
84 | default:
85 | message.setAttribute('class', '');
86 | }
87 | };
88 |
89 | function defaultEnv () {
90 | var playerHand = document.getElementById('right_hand');
91 | playerHand.setAttribute('src', 'images/right_fist.png');
92 |
93 | var compHand = document.getElementById('left_hand');
94 | compHand.setAttribute('src', 'images/left_fist.png');
95 |
96 | var message = document.getElementById('message');
97 | message.innerHTML = 'Choose you option!';
98 | message.setAttribute('class', '');
99 | };
100 |
101 |
--------------------------------------------------------------------------------
/python/django/tutorials/django-channels/channels/dj_channels/chat/static/reconnecting-websocket.min.js:
--------------------------------------------------------------------------------
1 | !function(a,b){"function"==typeof define&&define.amd?define([],b):"undefined"!=typeof module&&module.exports?module.exports=b():a.ReconnectingWebSocket=b()}(this,function(){function a(b,c,d){function l(a,b){var c=document.createEvent("CustomEvent");return c.initCustomEvent(a,!1,!1,b),c}var e={debug:!1,automaticOpen:!0,reconnectInterval:1e3,maxReconnectInterval:3e4,reconnectDecay:1.5,timeoutInterval:2e3};d||(d={});for(var f in e)this[f]="undefined"!=typeof d[f]?d[f]:e[f];this.url=b,this.reconnectAttempts=0,this.readyState=WebSocket.CONNECTING,this.protocol=null;var h,g=this,i=!1,j=!1,k=document.createElement("div");k.addEventListener("open",function(a){g.onopen(a)}),k.addEventListener("close",function(a){g.onclose(a)}),k.addEventListener("connecting",function(a){g.onconnecting(a)}),k.addEventListener("message",function(a){g.onmessage(a)}),k.addEventListener("error",function(a){g.onerror(a)}),this.addEventListener=k.addEventListener.bind(k),this.removeEventListener=k.removeEventListener.bind(k),this.dispatchEvent=k.dispatchEvent.bind(k),this.open=function(b){h=new WebSocket(g.url,c||[]),b||k.dispatchEvent(l("connecting")),(g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","attempt-connect",g.url);var d=h,e=setTimeout(function(){(g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","connection-timeout",g.url),j=!0,d.close(),j=!1},g.timeoutInterval);h.onopen=function(){clearTimeout(e),(g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","onopen",g.url),g.protocol=h.protocol,g.readyState=WebSocket.OPEN,g.reconnectAttempts=0;var d=l("open");d.isReconnect=b,b=!1,k.dispatchEvent(d)},h.onclose=function(c){if(clearTimeout(e),h=null,i)g.readyState=WebSocket.CLOSED,k.dispatchEvent(l("close"));else{g.readyState=WebSocket.CONNECTING;var d=l("connecting");d.code=c.code,d.reason=c.reason,d.wasClean=c.wasClean,k.dispatchEvent(d),b||j||((g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","onclose",g.url),k.dispatchEvent(l("close")));var e=g.reconnectInterval*Math.pow(g.reconnectDecay,g.reconnectAttempts);setTimeout(function(){g.reconnectAttempts++,g.open(!0)},e>g.maxReconnectInterval?g.maxReconnectInterval:e)}},h.onmessage=function(b){(g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","onmessage",g.url,b.data);var c=l("message");c.data=b.data,k.dispatchEvent(c)},h.onerror=function(b){(g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","onerror",g.url,b),k.dispatchEvent(l("error"))}},1==this.automaticOpen&&this.open(!1),this.send=function(b){if(h)return(g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","send",g.url,b),h.send(b);throw"INVALID_STATE_ERR : Pausing to reconnect websocket"},this.close=function(a,b){"undefined"==typeof a&&(a=1e3),i=!0,h&&h.close(a,b)},this.refresh=function(){h&&h.close()}}return a.prototype.onopen=function(){},a.prototype.onclose=function(){},a.prototype.onconnecting=function(){},a.prototype.onmessage=function(){},a.prototype.onerror=function(){},a.debugAll=!1,a.CONNECTING=WebSocket.CONNECTING,a.OPEN=WebSocket.OPEN,a.CLOSING=WebSocket.CLOSING,a.CLOSED=WebSocket.CLOSED,a});
--------------------------------------------------------------------------------
/python/tdd_by_example/seven.py:
--------------------------------------------------------------------------------
1 | # Run multiple tests
2 |
3 |
4 | class TestCase:
5 | def __init__(self, name):
6 | self.name = name
7 |
8 | def setUp(self):
9 | pass
10 |
11 | def tearDown(self):
12 | pass
13 |
14 | def run(self, result):
15 | result.testStarted()
16 | self.setUp()
17 | try:
18 | method = getattr(self, self.name)
19 | method()
20 | except:
21 | result.testFailed()
22 | self.tearDown()
23 |
24 |
25 | class WasRun(TestCase):
26 | def __init__(self, name):
27 | self.wasRun = None
28 | TestCase.__init__(self, name)
29 |
30 | def setUp(self):
31 | self.log = "setUp "
32 |
33 | def testMethod(self):
34 | self.log = self.log + "testMethod "
35 |
36 | def testBrokenMethod(self):
37 | raise Exception
38 |
39 | def tearDown(self):
40 | self.log = self.log + "tearDown "
41 |
42 |
43 | class TestResult:
44 | def __init__(self):
45 | self.runCount = 0
46 | self.failureCount = 0
47 |
48 | def testStarted(self):
49 | self.runCount += 1
50 |
51 | def testFailed(self):
52 | self.failureCount += 1
53 |
54 | def summary(self):
55 | return "%d run, %d failed" % (self.runCount, self.failureCount)
56 |
57 |
58 | class TestSuite:
59 | def __init__(self):
60 | self.tests = []
61 |
62 | def add(self, test):
63 | self.tests.append(test)
64 |
65 | def run(self, result):
66 | for test in self.tests:
67 | test.run(result)
68 |
69 |
70 | class TestCaseTest(TestCase):
71 | def setUp(self):
72 | self.result = TestResult()
73 |
74 | def testTemplateMethod(self):
75 | test = WasRun("testMethod")
76 | test.run(self.result)
77 | assert("setUp testMethod tearDown " == test.log)
78 |
79 | def testResult(self):
80 | test = WasRun("testMethod")
81 | test.run(self.result)
82 | assert("1 run, 0 failed" == self.result.summary())
83 |
84 | def testFailedResult(self):
85 | test = WasRun("testBrokenMethod")
86 | test.run(self.result)
87 | assert("1 run, 1 failed" == self.result.summary())
88 |
89 | def testFailedResultFormatting(self):
90 | self.result.testStarted()
91 | self.result.testFailed()
92 | assert("1 run, 1 failed" == self.result.summary())
93 |
94 | def testSuite(self):
95 | suite = TestSuite()
96 | suite.add(WasRun("testMethod"))
97 | suite.add(WasRun("testBrokenMethod"))
98 | suite.run(self.result)
99 | assert("2 run, 1 failed" == self.result.summary())
100 |
101 | suite = TestSuite()
102 | suite.add(TestCaseTest("testTemplateMethod"))
103 | suite.add(TestCaseTest("testResult"))
104 | suite.add(TestCaseTest("testFailedResultFormatting"))
105 | suite.add(TestCaseTest("testFailedResult"))
106 | suite.add(TestCaseTest("testSuite"))
107 |
108 | result = TestResult()
109 | suite.run(result)
110 | print(result.summary())
111 |
--------------------------------------------------------------------------------