Skip to content
Browse files

[*] pep8

unfinished
  • Loading branch information...
1 parent 24e983d commit 4340e0b62795ab481cb29a5a77bcbd622da51dd8 Serge Travin committed
View
11 setwithme/apps/core/facebook_sdk.py
@@ -54,9 +54,9 @@ def get_app_access_token(application_id, application_secret):
returns the application access_token
"""
# Get an app access token
- args = {'grant_type':'client_credentials',
- 'client_id':application_id,
- 'client_secret':application_secret}
+ args = {'grant_type': 'client_credentials',
+ 'client_id': application_id,
+ 'client_secret': application_secret}
try:
result_io = urllib2.urlopen(
@@ -157,6 +157,7 @@ def process_request(self, request):
request.facebook = DjangoFacebook(fb_user) if fb_user else None
return None
+
class FacebookProfileBackend(ModelBackend):
""" Authenticate a facebook user and autopopulate facebook data into the users profile. """
def authenticate(self, fb_uid=None, fb_graphtoken=None):
@@ -174,7 +175,9 @@ def authenticate(self, fb_uid=None, fb_graphtoken=None):
if me.get('first_name'): user.first_name = me['first_name']
if me.get('last_name'): user.last_name = me['last_name']
if me.get('email'): user.email = me['email']
- pic = GraphAPI().get_connections('%s' % fb_uid, 'picture', type='square')
+ pic = GraphAPI().get_connections('%s' % fb_uid,
+ 'picture',
+ type='square')
profile.user_pic = pic.get('url', '')
profile.save()
user.save()
View
1 setwithme/apps/core/middleware.py
@@ -2,6 +2,7 @@
import datetime
from django.contrib.auth.models import User
+
class CsrfFixMiddleware(object):
def process_view(self, request, view_func, callback_args, callback_kwargs):
request.META["CSRF_COOKIE_USED"] = True
View
3 setwithme/apps/core/templatetags/media.py
@@ -22,7 +22,8 @@ def media(filename, flags=''):
url = urlparse.urljoin(settings.STATIC_URL, filename)
if 'absolute' in flags:
url = _absolute_url(url)
- if (filename.endswith('.css') or filename.endswith('.js')) and 'no-timestamp' not in flags or \
+ if (filename.endswith('.css') or filename.endswith('.js')) and \
+ 'no-timestamp' not in flags or \
'timestamp' in flags:
fullname = os.path.join(settings.MEDIA_ROOT, filename)
if os.path.exists(fullname):
View
1 setwithme/apps/game/__init__.py
@@ -1,2 +1 @@
# -*- coding: utf-8 -*-
-
View
1 setwithme/apps/game/management/__init__.py
@@ -1,2 +1 @@
# -*- coding: utf-8 -*-
-
View
1 setwithme/apps/game/management/commands/__init__.py
@@ -1,2 +1 @@
# -*- coding: utf-8 -*-
-
View
29 setwithme/apps/game/models.py
@@ -11,7 +11,7 @@
from users.models import get_user_json
-get_uid = lambda : unicode(uuid.uuid4().hex)
+get_uid = lambda: unicode(uuid.uuid4().hex)
attributes_order = ('color', 'symbol', 'number', 'shading')
@@ -24,11 +24,13 @@
ids = range(81)
random.shuffle(ids)
+
def get_desk():
return ','.join(
map(str,
ids[:constants.CARDS_ON_DESK]))
+
def get_remaining():
return ','.join(
map(str,
@@ -94,7 +96,6 @@ def replace_cards(self, *cards_to_remove):
self.rem_cards_list = left_cards
self.desk_cards_list = cards
-
def pop_cards(self, quantity=3):
cards = self.rem_cards_list
indexes = []
@@ -111,7 +112,8 @@ def pop_cards(self, quantity=3):
@property
def last_action_time(self):
- last_action = self.gamesession_set.filter(set_pressed_dt__isnull=False)\
+ last_action = self.gamesession_set.\
+ filter(set_pressed_dt__isnull=False)\
.order_by('-set_pressed_dt')
if last_action.count():
return last_action[0].set_pressed_dt
@@ -122,10 +124,12 @@ def cards_to_pop(self):
cards_to_pop = constants.CARDS_ON_DESK
now = datetime.datetime.now()
time_since_last_action = now - self.last_action_time
- if time_since_last_action > datetime.timedelta(seconds=constants.CARD_ADD_INTERVAL):
+ if time_since_last_action > datetime.timedelta(
+ seconds=constants.CARD_ADD_INTERVAL):
cards_to_pop += min(
constants.MAX_ADDITIONAL_CARDS,
- int(time_since_last_action.seconds / float(constants.CARD_ADD_INTERVAL))
+ int(time_since_last_action.seconds /
+ float(constants.CARD_ADD_INTERVAL))
)
return cards_to_pop
@@ -136,8 +140,8 @@ def count_sets(self):
cnt = 0
cards = sorted(self.desk_cards_list)
for ncard1, card1 in enumerate(cards):
- for ncard2, card2 in enumerate(cards[ncard1+1:]):
- for ncard3, card3 in enumerate(cards[ncard2+ncard1+1+1:]):
+ for ncard2, card2 in enumerate(cards[ncard1 + 1:]):
+ for ncard3, card3 in enumerate(cards[ncard2 + ncard1 + 1 + 1:]):
if is_set(Card(id=card1), Card(id=card2), Card(id=card3)):
cnt += 1
return cnt
@@ -156,8 +160,10 @@ def is_finished(self):
@property
def leader(self):
- """Determines leading user, can be user after game end for determining winner"""
- scores = self.gamesession_set.exclude(client_state=ClientConnectionState.LOST)\
+ """Determines leading user,
+ can be user after game end for determining winner"""
+ scores = self.gamesession_set.\
+ exclude(client_state=ClientConnectionState.LOST)\
.exclude(state=GameSessionState.LEFT)\
.values_list('sets_found', 'failures', 'user')
return max([(score[0] - score[1], score[2]) for score in scores])[1]
@@ -182,8 +188,8 @@ class GameSessionState:
class ClientConnectionState:
ACTIVE = "ACTIVE"
- IDLE = "IDLE" #no status requests in 30 sec
- LOST = "LOST" #no status requests in 60 sec
+ IDLE = "IDLE" # no status requests in 30 sec
+ LOST = "LOST" # no status requests in 60 sec
ClientConnectionStateChoices = (
@@ -254,5 +260,6 @@ def name(self):
def score(self):
return self.sets_found - self.failures
+
class Facts(models.Model):
text = models.CharField(max_length=255)
View
25 setwithme/apps/game/tests.py
@@ -45,8 +45,8 @@ def test_has_sets(self):
game = self.test_game_creation()
cards = sorted(game.desk_cards_list)
for ncard1, card1 in enumerate(cards):
- for ncard2, card2 in enumerate(cards[ncard1+1:]):
- for ncard3, card3 in enumerate(cards[ncard2+ncard1+1+1:]):
+ for ncard2, card2 in enumerate(cards[ncard1 + 1:]):
+ for ncard3, card3 in enumerate(cards[ncard2 + ncard1 + 1 + 1:]):
if is_set(Card(id=card1), Card(id=card2), Card(id=card3)):
self.assertEqual(True, game.has_sets())
return
@@ -65,26 +65,29 @@ def test_game_rem_cards(self):
rem_lst = game.rem_cards_list
self.assertEqual(len(rem_lst), 81 - 12 - 12)
-
def _create_user(self):
user_uuid = unicode(uuid.uuid4().hex)[:30]
user, created = User.objects.get_or_create(
- username=user_uuid, defaults={'first_name': 'Anon %s' % (user_uuid[:4],)})
+ username=user_uuid,
+ defaults={'first_name': 'Anon %s' % (user_uuid[:4],)})
return user
-
class UtilsTestCase(TestCase):
def test_ids(self):
for n in range(80):
self.assertEqual(Card(text=Card(id=n).as_text()).as_id(), n)
def test_is_set(self):
- data = [(True, 0,3,6),
- (True, 0,1,2),
- (True, 15,16,17),
- (False, 8,9,10),
- (False, 14,16,17),]
+ data = [(True, 0 ,3 ,6),
+ (True, 0, 1, 2),
+ (True, 15, 16, 17),
+ (False, 8, 9, 10),
+ (False, 14, 16, 17),]
for d in data:
- self.assertEqual(d[0], is_set(Card(id=d[1]), Card(id=d[2]), Card(id=d[3])), '%s: %d, %d, %d' % d)
+ self.assertEqual(d[0],
+ is_set(Card(id=d[1]),
+ Card(id=d[2]),
+ Card(id=d[3])),
+ '%s: %d, %d, %d' % d)
View
4 setwithme/apps/game/urls.py
@@ -4,7 +4,9 @@
urlpatterns = patterns('game.views',
url(r'^create/$', 'start_game'),
- url(r'^game_screen/(?P<game_id>[\w]+)$', 'game_screen', name='game_screen'),
+ url(r'^game_screen/(?P<game_id>[\w]+)$',
+ 'game_screen',
+ name='game_screen'),
url(r'^get_status/(?P<game_id>[\w]+)$', 'get_status'),
url(r'^put_set_mark/(?P<game_id>[\w]+)$', 'put_set_mark'),
url(r'^check_set/(?P<game_id>[\w]+)$', 'check_set'),
View
7 setwithme/apps/game/utils.py
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
from django.utils.datastructures import SortedDict
+
def match(first, second, third):
return (first == second and second == third) or \
(first != second and first != third and second != third)
@@ -32,7 +33,7 @@ def id_to_params(self, id):
result = {}
for n, key in enumerate(Card.attributes.keys()):
power = 3**(len(Card.attributes)-n-1)
- pn = id/power
+ pn = id / power
id -= pn * power
result[key] = Card.attributes[key][pn]
return result
@@ -42,7 +43,7 @@ def params_to_id(self, *kwargs):
for n, key in enumerate(Card.attributes.keys()):
result += 3**(len(Card.attributes)-n-1) * Card.attributes[key].index(getattr(self, key))
return result
-
+
def as_text(self):
return ' '.join([getattr(self, key) for key in Card.attributes.keys()])
@@ -55,5 +56,3 @@ def is_set(first, second, third):
getattr(first, a_name),
getattr(second, a_name),
getattr(third, a_name)) for a_name in Card.attributes.keys())
-
-
View
19 setwithme/apps/game/views.py
@@ -11,7 +11,8 @@
from chat.models import ChatMessage
from game import constants
-from game.models import ClientConnectionState, Game, GameSession, GameSessionState, get_uid
+from game.models import (ClientConnectionState, Game,
+ GameSession, GameSessionState, get_uid)
from game.utils import Card, is_set
from users.models import WaitingUser
@@ -24,7 +25,7 @@ def game_screen(request, game_id):
desc_cards = game.desk_cards_list
rem_cards_cnt = len(game.rem_cards_list)
initial_status = {'users': users,
- 'cards': [{'id': card_id,
+ 'cards': [{'id': card_id,
'class': Card(id=card_id).as_text()} \
for card_id in desc_cards],
'cards_left': rem_cards_cnt,
@@ -33,7 +34,7 @@ def game_screen(request, game_id):
'leader': game.leader},
'chat': []}
return {'game_id': game_id,
- 'initial_status': json.dumps(initial_status, separators=(',',':'))}
+ 'initial_status': json.dumps(initial_status, separators=(',', ':'))}
@ajax_request
@@ -42,7 +43,8 @@ def start_game(request):
qs = GameSession.objects.\
filter(user=user,
left=False,
- game__finished=False).exclude(client_state=ClientConnectionState.LOST)
+ game__finished=False).\
+ exclude(client_state=ClientConnectionState.LOST)
if qs.count():
gs = qs.all()[0]
return {'status': 302,
@@ -203,7 +205,9 @@ def check_set(request, game_id):
gs_other.save()
def add_stat(gs, data):
- data.update({'sets_found': gs.sets_found, 'failures': gs.failures, 'score': gs.score})
+ data.update({'sets_found': gs.sets_found,
+ 'failures': gs.failures,
+ 'score': gs.score})
return data
if gs.set_received_in_time():
@@ -217,6 +221,7 @@ def add_stat(gs, data):
if not all(card_id in desk_cards_lst for card_id in ids_lst):
return {'success': False, 'msg': 'Not all card were on desk'}
cards = [Card(id=card_id) for card_id in ids_lst]
+
def is_set_wrapper(*args):
if constants.CANCEL_SET_CHECK:
return True
@@ -233,7 +238,9 @@ def is_set_wrapper(*args):
gs.save()
# Remove cards from desc list and replace with new, if any
game.replace_cards(*ids_lst)
- result = {'success': True, 'msg': 'SET!', 'sets_found': gs.sets_found}
+ result = {'success': True,
+ 'msg': 'SET!',
+ 'sets_found': gs.sets_found}
return add_stat(gs, result)
else:
gs.state = GameSessionState.SET_PENALTY
View
1 setwithme/apps/users/__init__.py
@@ -1,2 +1 @@
# -*- coding: utf-8 -*-
-
View
4 setwithme/apps/users/models.py
@@ -4,6 +4,7 @@
from django.db import models
from django.contrib.auth.models import User
+
class WaitingUser(models.Model):
user = models.ForeignKey(User)
@@ -32,7 +33,8 @@ def get_user_json(user):
name = u"%s %s" % (user.first_name, user.last_name)
else:
name = user.username
- pic = profile.user_pic if profile.user_pic else settings.DEFAULT_PROFILE_PIC
+ pic = profile.user_pic if profile.user_pic \
+ else settings.DEFAULT_PROFILE_PIC
return {'id': user.id,
'username': user.username,
'name': name,
View
1 setwithme/apps/users/views.py
@@ -1,2 +1 @@
# -*- coding: utf-8 -*-
-

0 comments on commit 4340e0b

Please sign in to comment.
Something went wrong with that request. Please try again.