- 1
- 2
if True: #зачем.
....
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
−108
if True: #зачем.
....
На новом проекте. Радуют и код и комментарии)
−113
def normalize_url(url, preserve_fragment=False):
url = url.strip()
if not re.search(r'^\w+:', url):
url = 'http://' + url.lstrip('/')
if not (url.startswith('http:') or url.startswith('https:')):
return url
url = list(urlparse.urlsplit(url))
if url[0] not in ('http', 'https'):
url[0] = 'http'
url[1] = url[1].lower().encode('idna')
if type(url[2]) == unicode:
try:
url[2] = url[2].encode('ascii')
except UnicodeEncodeError:
pass
url[2] = urllib.unquote(url[2])
if type(url[2]) == unicode:
url[2] = url[2].encode('utf-8')
url[2] = urllib.quote(url[2], '/')
if type(url[3]) == unicode:
try:
url[3] = url[3].encode('ascii')
except UnicodeEncodeError:
pass
cut_params = ('utm_source', 'utm_medium', 'utm_term',
'utm_content', 'utm_campaign',
'yclid', 'gclid', 'ref')
new_qsl = []
for tag in url[3].split('&'):
if '=' in tag:
param, value = tag.split('=', 1)
param = urllib.unquote(param)
value = urllib.unquote(value)
if param in cut_params:
continue
if type(value) == unicode:
value = value.encode('utf-8')
new_tag = "%s=%s" % (urllib.quote(param), urllib.quote(value))
else:
new_tag = urllib.unquote(tag)
if type(new_tag) == unicode:
new_tag = new_tag.encode('utf-8')
new_tag = urllib.quote_plus(new_tag)
new_qsl.append(new_tag)
url[3] = '&'.join(new_qsl)
if not preserve_fragment:
url[4] = ''
return urlparse.urlunsplit(url)
Еще немного магии и хватит на сегодня.
−115
now = timezone.now().astimezone(cur_tz)
today = now.replace(hour=0, minute=0, second=0, microsecond=0)
td1day = datetime.timedelta(days=1)
td7days = datetime.timedelta(days=7)
td14days = datetime.timedelta(days=14)
td30days = datetime.timedelta(days=30)
categories = None
if user is not None:
try:
categories = self.categories.restrict_by_acl(
self.acl.by_user(user, can_enter=True), throw_if_all=True)
except CampaignProductCategory.NoAclRestriction:
categories = None
report3_url = reverse('report3', args=[self.pk])
df = lambda d: d.strftime('%d.%m.%Y')
stats = {'to': now}
stats['in_1d'] = get_count(today, categories)
stats['in_1d_from'] = today
stats['in_1d_url'] = (
report3_url +
'#from_date=%s&to_date=%s' % (df(stats['in_1d_from']),
df(stats['to'])))
stats['in_7d'] = get_count(today-td7days+td1day, categories)
stats['in_7d_from'] = today - td7days + td1day
stats['in_7d_url'] = (
report3_url +
'#from_date=%s&to_date=%s' % (df(stats['in_7d_from']),
df(stats['to'])))
stats['in_14d'] = get_count(today-td14days+td1day, categories)
stats['in_14d_from'] = today - td14days + td1day
stats['in_14d_url'] = (
report3_url +
'#from_date=%s&to_date=%s' % (df(stats['in_14d_from']),
df(stats['to'])))
stats['in_30d'] = get_count(today-td30days+td1day, categories)
stats['in_30d_from'] = today - td30days + td1day
stats['in_30d_url'] = (
report3_url +
'#from_date=%s&to_date=%s' % (df(stats['in_30d_from']),
df(stats['to'])))
Пхп и даты, только питон
−106
>>> quit()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'str' object is not callable
>>> quit
'Use Ctrl-D (i.e. EOF) to exit.'
>>> type(quit)
<type 'str'>
>>> type(exit)
<type 'str'>
Первый раз запустил питон 2.4...
−101
self.exclude = list(set(list(self.exclude or []) + ['str1', 'str2']))
−106
qdev_id, iops = _update_device_iops(instance, device_for_change)
try:
qemu.volumes.set_io_throttle(controller.qemu(), qdev_id, iops)
except Exception as e:
# Check if we turn off this instance? just a moment ago.
if "'NoneType' object has no attribute 'connected'" in e:
LOG.warning("kemu process seems to be killed")
else:
raise
Метод set_io_throttle не бросает exception.
Мы так проверяем,есть ли connection к qemu или нет.
−99
@login_required
def datadelivery_stats_report(request, campaign_id):
try:
start_date = extract_date_to_default_timezone(request, 'start_date')
except ValidationError:
return HttpResponseServerError("The %s parameter is invalid." % 'start_date')
except AttributeError:
return HttpResponseServerError("The %s parameter is invalid." % 'start_date')
except KeyError:
return HttpResponseServerError("The %s parameter is missing." % 'start_date')
try:
end_date = extract_date_to_default_timezone(request, 'end_date')
except ValidationError:
return HttpResponseServerError("The %s parameter is invalid." % 'end_date')
except AttributeError:
return HttpResponseServerError("The %s parameter is invalid." % 'end_date')
except KeyError:
return HttpResponseServerError("The %s parameter is missing." % 'end_date')
Джанга такая джанга... Почему же нельзя выбросить ошибку валидации? 404 можно...
−106
import pygame
window = pygame.display.set_mode((600, 600))
pygame.display.set_caption("GAME")
screen = pygame.Surface((600, 600))
class Sprite:
def __init__(self, xpos, ypos, filename):
self.x=xpos
self.y=ypos
self.bitmap=pygame.image.load(filename)
self.bitmap.set_colorkey((0,0,0))
def render(self):
screen.blit(self.bitmap, (self.x,self.y))
laser = Sprite(0, 0, 'laser.png')
done = True
while done:
window.fill((50,50,50))
for e in pygame.event.get():
if e.type == pygame.QUIT:
done = False
screen.fill((50,50,50))
laser.render()
window.blit(screen, (0,0))
pygame.display.flip()
картинка на черном фоне
−96
{% verbatim %}{{ setExpireValue({% endverbatim %}{{ value }}{% verbatim %}) }}{% endverbatim %}
AngularJS + Django, люди доходят до ручки.
−97
def constant_time_compare(val1, val2):
"""
Returns True if the two strings are equal, False otherwise.
The time taken is independent of the number of characters that match.
"""
if len(val1) != len(val2):
return False
result = 0
for x, y in zip(val1, val2):
result |= ord(x) ^ ord(y)
return result == 0
Django.utils.crypto в Django 1.4