Змея / Говнокод #6118 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
from django.db import models

# Класс Студент
class Student(models.Model):
    name = models.CharField(max_length=50) # ФИО студента
    group = models.CharField(max_length=10) # Группа студента
    starosta = models.BooleanField(default=False) # Является ли студент старостой группы?

# Класс Пара
class Pair(models.Model):
    name = models.CharField(max_length=30) # Название пары
    auditory = models.CharField(max_length=7) # Аудитория
    lecturer = models.CharField(max_length=50) # ФИО преподавателя

# Класс День
class Day(models.Model):
    pair1 = models.ForeignKey(Pair) # Первая пара
    pair2 = models.ForeignKey(Pair) # Вторая пара
    pair3 = models.ForeignKey(Pair) # Третья пара
    pair4 = models.ForeignKey(Pair) # Четвёртая пара
    pair5 = models.ForeignKey(Pair) # Пятая пара
    pair6 = models.ForeignKey(Pair) # Шестая пара
    pair7 = models.ForeignKey(Pair) # Седьмая пара

# Класс Расписание
class TimeTable(models.Model):
    group = models.CharField(max_length=10) # Группа, к которой относится расписание
    weekcolor = models.BooleanField() # False, 0 - Красная неделя; True, 1 - Синяя неделя
    monday = models.ForeignKey(Day) # Понедельник
    tuesday = models.ForeignKey(Day) # Вторник
    wednesday = models.ForeignKey(Day) # Среда
    thursday = models.ForeignKey(Day) # Четверг
    friday = models.ForeignKey(Day) # Пятница
    saturday = models.ForeignKey(Day) # Суббота

Очередной шедевр от Magister Yoda

Попытка сделать модель расписания для студентов.

cutwater cutwater, (Updated )

Комментарии (8, +8)

Змея / Говнокод #6117 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
if row[0].find('lk_s_du') > -1 or row[0].find('lk_s_su') > -1:
    price = ''
    if row[6] == 'incoming_external':
        if tariff['ie_price_second'] == 0:
            price = row[5] * tariff['ie_price_first'] / 102400
        elif ie_global > tariff['ie_price_switch']:
            price = row[5] * tariff['ie_price_second'] / 102400
        else:
            price = overhead(tariff['ie_price_switch']-ie_global,tariff['ie_price_switch'])*tariff['ie_price_first'] / 102400 + hev((row[5]+ie_global-tariff['ie_price_switch']))*tariff['ie_price_second'] / 102400
        ie_global += row[5]
        unit = 'kb'
        if tariff['price_per_unit'] == 1:
            price = price /1024
            unit = 'mb'
        if tariff['price_per_unit'] == 2:
            price = price /1024/1024
            unit = 'gb'
        if tariff['price_per_unit'] == 3:
            price = price /1024/1024/1024
            unit = 'tb'
    if row[6] == 'internal':
        if tariff['il_price_second'] == 0:
            price = row[5] * tariff['il_price_first'] / 102400
        elif il_global > tariff['il_price_switch']:
            price = row[5] * tariff['il_price_second'] / 102400
        else:
            price = overhead(tariff['il_price_switch']-il_global,tariff['il_price_switch'])*tariff['il_price_first'] / 102400 + hev((row[5]+il_global-tariff['il_price_switch']))*tariff['il_price_second'] / 102400
        il_global += row[5]
        unit = 'kb'
        if tariff['price_per_unit'] == 1:
            price = price /1024
            unit = 'mb'
        if tariff['price_per_unit'] == 2:
            price = price /1024/1024
            unit = 'gb'
        if tariff['price_per_unit'] == 3:
            price = price /1024/1024/1024
            unit = 'tb'
    if row[6] == 'outgoing_any':
        if tariff['oe_price_second'] == 0:
            price = row[5] * tariff['oe_price_first'] / 102400
        elif oe_global > tariff['oe_price_switch']:
            price = row[5] * tariff['oe_price_second'] / 102400
        else:
            price = overhead(tariff['oe_price_switch']-oe_global,tariff['oe_price_switch'])*tariff['oe_price_first'] / 102400 + hev((row[5]+oe_global-tariff['oe_price_switch']))*tariff['oe_price_second'] / 102400
        oe_global += row[5]
        unit = 'kb'
        if tariff['price_per_unit'] == 1:
            price = price /1024
            unit = 'mb'
        if tariff['price_per_unit'] == 2:
            price = price /1024/1024
            unit = 'gb'
        if tariff['price_per_unit'] == 3:
            price = price /1024/1024/1024
            unit = 'tb'
    price = str(price).replace('.',',')

Черная магия непосредственно тарификации интернет-трафика.

spaceoflabview spaceoflabview, (Updated )

Комментарии (7, +7)

Змея / Говнокод #6116 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
for row in rows:
    service = row[0].split('_')
    if row[0].find('lk_s_du') > -1:
        loki_cursor.execute("""select tariff_id from inet_inetsessionlog where id = %s;""", (service[-1],))
        tariff_id = str(loki_cursor.fetchall()[0][0])
    else:
        if row[1] == 'inet_dynamic_ip':
            cursor.execute('select tariff_plan from inet_dynamic_ip_services where id = %s', (service[-1],))
            tariff = str(cursor.fetchall()[0][0])
        elif row[1] == 'inet_fixed_ip':
            if row[0].split('_')[-1].find('.') == -1:
                cursor.execute('select tariff_plan from inet_fixed_ip_services where id = %s', (service[-1],))
            else:
                cursor.execute('select tariff_plan from inet_fixed_ip_services where id = %s', (service[-2],))
            tariff = str(cursor.fetchall()[0][0])
        loki_cursor.execute("select tariff_ptr_id from inet_inettariff where cherry_id = %s", (tariff,))
        tariff_id = str(loki_cursor.fetchall()[0][0])
    loki_cursor.execute("select * from inet_inettariff where tariff_ptr_id = %s", (tariff_id,))
    tariff = loki_cursor.fetchall()[0]
tariff = dict(zip(('tariff_ptr_id', 'price_per_unit', 'is_dynamic', 'cherry_id', 'ie_price_first', 'ie_price_second', 'ie_price_switch', 'oe_price_first', 'oe_price_second', 'oe_price_switch', 'il_price_first', 'il_price_second', 'il_price_switch', 'ol_price_first', 'ol_price_second', 'ol_price_switch'), tariff))
    if login in row[0]:
        print>>o, (str(row[2]) + ';' + row[4] + ';' + str(row[5]).replace('.000000', '').replace('.', ',') + ';' + row[6] + ';' + str(price)).decode('utf-8').replace(u'incoming_external', u'Входящий внешний').replace(u'internal', u'Внутренний').replace(u'outgoing_any',u'Исходящий внешний').encode('utf-8')
    else:
        print>>o, (str(row[2]) + ';' + row[4] + ';' + str(row[5]).replace('.000000', '').replace('.', ',') + ';' + row[6] + ';' + str(price)).decode('utf-8').replace(u'incoming_external', u'Входящий внешний').replace(u'internal', u'Внутренний').replace(u'outgoing_any',u'Исходящий внешний').replace(date_start,u'Суммарно').encode('utf-8')
else:
    price = str(row[7]).replace('.',',')
    if login in row[0]:
        print>>o, (str(row[2]) + ';' + row[4] + ';' + str(row[5]).replace('.000000', '').replace('.', ',') + ';' + row[6] + ';' + str(price)).decode('utf-8').replace(u'incoming_external', u'Входящий внешний').replace(u'internal', u'Внутренний').replace(u'outgoing_any',u'Исходящий внешний').encode('utf-8')
    else:
        print>>o, (str(row[2]) + ';' + row[4] + ';' + str(row[5]).replace('.000000', '').replace('.', ',') + ';' + row[6] + ';' + str(price)).decode('utf-8').replace(u'incoming_external', u'Входящий внешний').replace(u'internal', u'Внутренний').replace(u'outgoing_any',u'Исходящий внешний').replace(date_start,u'Суммарно').encode('utf-8')

Кусочек интернет-тарификатора.

spaceoflabview spaceoflabview, (Updated )

Комментарии (5, +5)

Змея / Говнокод #6005 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
def validate_line(line):
    if len(line) <= 2: return False
    if line[0] == '""': return False
    if line[0] == "''": return False
    if line[0] == '+!': return False
    if line[0] == '-?': return False
    if line[0] == '- (': return False
    if line[0] == '-(': return False
    if line[0] == '-)': return False

    if line[0] == '-6a': return False
    if line[0] == '-6a )': return False
    if line[0] == '-a': return False
    if line[0] == '-aa': return False

    if line[0] == '-:': return False
    if line[0] == ':': return False
    if line[0][0] == '#': return False
    if line[0][0] == "'": return False
    if line[0][0] == '&': return False
    if line[0][0] == '(': return False
    return True

Жил был один маленький портальчик одной немаленькой компании. Портал внутренний, пользовался секретамками, манагерами и прочим планктоном. С задачей своей справлялся, не глючил и вообще проблем не приносил. И вот задумали в него добавить пару "фишек". А писался он давно, программиста уже не найти. Полезли в код, а там ... В общем вот; ВЕСЬ код написан в так вот стиле...

ossa ossa, (Updated )

Комментарии (6, +6)

Змея / Говнокод #5937 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
- application = webapp.WSGIApplication(foo)	
+ if 0==1:	
+     application = webapp.WSGIApplication(foo)
+ application = webapp.WSGIApplication(bar)

пакистанский юноша знает толк в комментариях.

awsum awsum, (Updated )

Комментарии (6, +6)

Змея / Говнокод #5881 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
#coding=utf8
 
#Ввод коэффициентов
def inputVar():
    a=raw_input('Enter a')
    b=raw_input('Enter b')
    c=raw_input('Enter c')
    return a,b,c
#Вывод исходного уравнения в виде ax^2+bx+c=0
def printHeader(a,b,c):
    import math
    ax2=str(a)*bool(a)*bool(a-1)+'x^2'*bool(a)+'+'*bool(b+math.fabs(b))*bool(a)
    bx1=str(b)*bool(b)*bool(b-1)+'x'*bool(b)+'+'*bool(c+math.fabs(c))*bool(bool(a)+bool(b))
    cx0=str(c)*bool(c)+'0'*bool(not(bool(bool(a)+bool(b)+bool(c))))
    print '\n\nУравнение:',ax2+bx1+cx0+' = 0'
#Подсчет и вывод корней уравнения    
def printRoots(a,b,c):
    D=b**2-4*a*c
    import math
    import cmath
    if a:
        if D>0:
            x1=(-b+math.sqrt(D))/(2*a)
            x2=(-b-math.sqrt(D))/(2*a)
            print "Корни уравнения:\n","x1 =",x1,"\nx2 =",x2
        if D==0:
            x1=(-b)/(2*a)
            x2=x1
            print "Корень уравнения:\n","x1 = x2 =",x1
        if D<0:
            print "Корни уравнения:"
            print 'x1 = '+str((-b)/(2*a))*bool(b)+'+'*bool(b)+str(cmath.sqrt(D)/(2*math.fabs(a)))
            print 'x2 = '+str((-b)/(2*a))*bool(b)+'-'*bool(b)+str(cmath.sqrt(D)/(2*math.fabs(a)))
    elif b:
        x1=-c/b
        x2=x1
        print'Корень уравнения:\n','x =',x1
    elif c:
        print'Уравнение неверно'
    else:
        print'Уравнение верно'
#Тело программы             
a,b,c=inputVar()
a=int(a); b=int(b); c=int(c)
printHeader(a,b,c)
printRoots(a,b,c)

Juris_Kabanis Juris_Kabanis, (Updated )

Комментарии (1, +1)

Змея / Говнокод #5750 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
def ispalindrome(string):
	decide=1
	i=0
	while i<=int(len(string)/2) and decide==1:
		if string[i]!=string[-(i+1)]:
			decide=0
		i+=1
	return decide

Функция определяет, является ли число паниндромом =)

SSPkrolik SSPkrolik, (Updated )

Комментарии (6, +6)

Змея / Говнокод #5480 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
import gzip, StringIO
eval (compile (gzip.GzipFile (fileobj = StringIO.StringIO ('\x1f\x8b\x08\x00\xfe\xb9\x0cM\x02\xff\xa5\x93\xdfj\xdb0\x14\xc6\xaf\xeb\xa78\xb9\x8a\xdd\x19\xe1\xac4\x17\x83^\xa4\xa3\x83A\xe8\xc6RV\xc6(\xc2\x7fTWD\x95\x82,/aw\xd9Mo\n\x83\xbd\xc1\xde\xa0\x94\x85m\x8c\xb6\xaf \xbf\xd1\x8e\x1c%\xe9E\xd6\x9b\xd9\xc6\xb2\xbe#\xfd\xce\xd1\'\xb9`\xe7\xa0$\xbd\xe0E\xc1$\xcdjc\xb0\x97\x0b\x9e\x8fY\x01\xe1n\xaa\xcb*z\x11\xecL\xb9\x84\x03(\xcd\x98\x9crY\xa8)\x84Q\xb0\x93y\xe9\xb0\x9d\x05a\xd7~\xb7?\xec\xc2\xfe\xb17\xcd\x97\xe6\x1a\xecm3\xb7\x0b\xb0\x0f\xf6\x97\xfd\x89\x11T\xed=!\xa4\xeb\xe6\x92\xea\xc2c\x84\xc7\x0c\xd3\x8c\x89\xa5B\xb0\x1e\xe6?+f\xa8a3\xe3\xf8\xdf\xb6\x00;\x9d\xce\x12\x98+)Y\xee\xc6\xf9\xfa\xbb1P\xaa\x04\xde1\x84"\x86,\xc2q\x9f25\xf3\t\xdf\x1f\xe2g\xf8\xdc\x8bd\x92\xe6cZ\x99T#"\xdb&\x8a\x95\xb8.\x1dm!i\x81F9\xd9\xf7]\xbd\x13Uq\xc3\x9d\'\xade\xaf\x8f\xe9\xdb7#\xfa\xf2\xe8\xf8\xe4\xe8\x1d\x1d\x0cO\x07\x1fF\xab\xd1+\xd4Dsi\xc0Y\xb8\xb0\xbf\x9b+\\\xdb\x1c\xec\x1d6W\xf8^\xa0\x9f\xf3\xe6\xab\xf3.\x08\n\xdc2\xbf.\x08\xa71\xd4\x15\xd3\xb4HM\xea6j\xdd\x81\x8f\xc9\xd9\x86\xfeH\xee\x9dm\xdc-\x05\xcf\x88\xe1\x97L\xd5\x86\xb6\x0b\xe9%\x89s\r\xe1\x8f\xc0\x8e\x85\xa3}f\x8c9/0Yj\x8c\xae\xd0\xccI*KE\x06\xd8\x1b\xf2\xca\xb4\xe4s\xa5\x81\x03\x9e\x9a\x99\xc6 f\x13\x0c\xdd\x10\xa4\\\xeff\x149\xc4\x92A\xb8\xc4\\(nH\xaf\x94f\xa5V\xb5\xc4\xa2\x9c3!r\nuI\x96\rN\x87]\xe8\xef\xef\xef\xf5\xa3\x18\xfe;\x8e\x0f<\x83\x9e;\x1f\xff\xaag\xc4?\xb3\'*I\xf0B\x12\x9a\xb7m\xa1\xeb\x83\xec\xe8\x1c\xff2VA\xd8f\xdaDd)\x9eH\xb0\xd7O\x1cE3Sk\t\'\xbaf\xc1_\xf0\xb6d\xa4\xbb\x03\x00\x00')).read (), '', 'exec'))
del gzip, StringIO

"Хитрая" пасхалка из моего курсача :)

byss byss, (Updated )

Комментарии (7, +7)

Змея / Говнокод #5354 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 62
  63. 63
  64. 64
  65. 65
  66. 66
  67. 67
  68. 68
  69. 69
  70. 70
  71. 71
  72. 72
  73. 73
  74. 74
  75. 75
  76. 76
  77. 77
  78. 78
  79. 79
  80. 80
  81. 81
  82. 82
  83. 83
  84. 84
  85. 85
  86. 86
  87. 87
  88. 88
  89. 89
  90. 90
  91. 91
  92. 92
  93. 93
  94. 94
  95. 95
  96. 96
#! /usr/bin/python2.4
# -*- coding: utf-8 -*-
'''
from Tkinter import *
import subprocess
import Queue
import threading

class ifStatThreadClass(threading.Thread):
    """класс потока с ifstat"""
    def __init__(self,breakCount):
        global listBox
        selectedIface=listBox.curselection()
        if not selectedIface: selectedIface=0
        self.ifaceName=listBox.get(selectedIface);
        self.breakCount=breakCount
        threading.Thread.__init__(self)
        
    def run(self):
        global queue
        global stop_event       
    # рабочий тред, запускает ifstat на вывод 20 строк    
        global listBox
        cmd="ifstat -i %s 1 %s"% (self.ifaceName, self.breakCount,)
        print "Запускаю: %s"%cmd
        PIPE = subprocess.PIPE
        p = subprocess.Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE,
                stderr=subprocess.STDOUT, close_fds=True)
        #пока нет стоп-события ловим строки из стдоута
        if (stop_event.is_set()): print "stop event detected!"
        while not stop_event.is_set():
            s = p.stdout.readline()
            if not s: break
            if self.breakCount==0: break
            self.breakCount-=1
            #кладем очередную строку в очередь
            queue.put(s)
            print s,
        
def startIfStat():
    """ стартуем рабочий тред"""
    global stop_event
    global ifStatThread
    ifStatThread = ifStatThreadClass(10)
    try:
        stop_event.clear() 
        ifStatThread.start() 
    except: 
        print "Не могу запустить поток! Может, он уже запущен?"
        stop_event.set()
    
    #вот тут стартуем
       
            
def stopWorker():
    """создаем стоп-событие"""
    print("Тпырррр!")
    global stop_event
    global ifStatThread
    # установим событие останова
    stop_event.set()
    
def ifStatResultUpdater():
    """обновлялка текстового поля из очереди query"""
    global queue
    global stop_event
    global ifStatResult
    global ifStatThread
    global emptyQueueCounter
#    print("updater")
#    ifStatResult.configure(text=time.strftime('%H:%M:%S'))
    #только если не было стоп-события 

    if not stop_event.is_set():
        if ifStatThread.isAlive(): print "Поток еще жив!"
        else: print "Потока в живых не обнаружено"
        s='' 
        try:
            #берем из очереди строку и выводим на лейбл
            print 'Что у нас в очереди? ',
            s = queue.get_nowait()
            print "а в очереди вот:",s
            ifStatResult.configure(text=s)
        except Queue.Empty:
            print('ничего в очереди нету(')
            if (emptyQueueCounter>2):
                print('аааа.. похоже, все умерли... щас заново запущу!') 
                startIfStat()
                emptyQueueCounter=0                
            emptyQueueCounter+=1
            
        #если стоп-события не было, запускаем эту же функцию через секунду
    root.after(1000,ifStatResultUpdater)

queue = Queue.Queue() #создаем очередь
emptyQueueCounter=0

Мой первый (мало-мальски серьезный) опыт на питоне. Выводит список из 3х интерфейсов, по нажатию Старт запускает тред с ифстатом, выводит в окошко результаты. Кривинько-косо, но работает)
Если есть замечания как криво написано и предложения как лучше, жду комментарии.
P.S. до этого писал на пхÐ%BF, D1‚ак что не пинайте сильно)

hakimovis hakimovis, (Updated )

Комментарии (3, +3)