Skip to content

Instantly share code, notes, and snippets.

View bdelate's full-sized avatar

Brendon Delate bdelate

  • South Africa
View GitHub Profile
@bdelate
bdelate / reduxDeleteCard.js
Created July 3, 2018 06:42
Kanban delete card action
// if last card was deleted, only that card is removed from server and Redux store
// If non last card was deleted, remaining cards are updated to reflect their
// updated position_ids received from the server
export const deleteCard = (column_id, id) => {
return dispatch => {
dispatch(toggleSpinner(id, true));
axios
.delete(`/api/cards/${id}/`)
.then(res => {
dispatch(cardDeleted(column_id, id));
@bdelate
bdelate / drf_multi_card_update.py
Created July 2, 2018 14:55
Kanban multi card update
class CardListSerializer(serializers.ListSerializer):
def update(self, instance, validated_data):
"""
Update multiple existing cards
"""
card_mapping = {card.id: card for card in instance}
data_mapping = {item['id']: item for item in validated_data}
cards = []
@bdelate
bdelate / delete_card_view.py
Created July 2, 2018 14:18
Kanban delete card view
def delete(self, request, pk):
"""
If last column card is deleted, return response without extra data,
else update remaining card position_ids and return them in
the response.
"""
try:
card = Card.objects.get(pk=pk)
except Card.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
@bdelate
bdelate / calc_correlation.py
Last active July 2, 2018 09:20
Diversify Portfolio correlation calculation
def calc_correlation(self, months, data, time_span):
"""
Calculate pair wise correlations for stocks in 'data' over
specified 'time_span'.
Remove duplicates from resulting matrix.
Stack the data to create columns: symbol_01, symbol_02, time_span
"""
df.reset_index(inplace=True)
df.set_index(['date', 'symbol'], inplace=True)
df.sortlevel(inplace=True)
@bdelate
bdelate / signals.py
Last active May 23, 2018 10:00
PayPal payment received
from django.contrib.auth.models import User
from django.core.cache import cache
from paypal.standard.ipn.signals import valid_ipn_received
import redis
def paypal_notification(sender, **kwargs):
"""
sender contains all the transaction information received from paypal.
Determine the nature of the paypal transaction by accessing sender
@bdelate
bdelate / portfolio_utils.py
Last active July 2, 2018 09:39
Diversify Portfolio Cache
def get_portfolio_analysis(user, portfolio_id):
cache_key = '{}:{}:portfolio'.format(user, portfolio_id)
analysis_results = None
try:
analysis_results = cache.get(cache_key)
except redis.exceptions.ConnectionError:
logger.warn('relevant info is logged here')
# perform analysis on a cache miss or redis connection error
if analysis_results is None:
@bdelate
bdelate / high-volume-stocks.sql
Created April 6, 2018 09:29
Selecting the highest volume stocks
-- select 1 year worth of daily data for the top 1500 symbols
-- with the highest average volume over the last 3 months
SELECT core_daily.date, core_daily.close, core_daily.symbol
WHERE (
core_daily.symbol_id IN (
SELECT symbol_id FROM core_daily
WHERE date > current_date - INTERVAL'3' month
GROUP BY symbol_id ORDER BY AVG(volume) DESC
LIMIT 1500
@bdelate
bdelate / test_views.py
Last active April 5, 2018 15:01
Django - Using a mixin for setting up test data
from tests.mixins import BaseTestMixins
class QuestionCreateAndDetailTest(TestCase, BaseTestMixins):
@classmethod
def setUpTestData(cls):
# create_test_data is made available through the BaseTestMixins mixin
# it is only run once at the beginning of QuestionCreateAndDetailTest
cls.create_test_data()
@bdelate
bdelate / views.py
Last active April 5, 2018 05:51
Combing Django OuterRef and Exists
user = self.request.user
voted_flag = (Question.objects
.filter(votes__voter=user,
votes__object_id=OuterRef('pk')))
query = (Question.objects
.select_related('user')
.annotate(voted=Exists(voted_for_question)))
question = get_object_or_404(question_query, slug=kwargs['slug'])
@bdelate
bdelate / models.py
Created April 3, 2018 09:55
Answer Model
from django.db import models
from django.conf import settings
from django.contrib.contenttypes.fields import GenericRelation
from votes.models import Vote
from comments.models import Comment
from questions.models import Question
class Answer(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,