├── .gitattributes ├── django ├── forms.py ├── models.py ├── utils.py └── views.py ├── flask ├── utils.py ├── forms │ ├── city_select_field.py │ └── new_project_wizard.py └── views │ └── custom_questions.py ├── python ├── check_ip.py ├── generate_pid.py ├── create_objects.py ├── generate_report.py ├── akinator.py ├── send_email.py ├── sql_bids.py ├── genpassword.py ├── AI-battlship_game.py ├── PhyRe.py └── player.py ├── obfuscation └── __init__.py ├── README.md └── .gitignore /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto -------------------------------------------------------------------------------- /django/forms.py: -------------------------------------------------------------------------------- 1 | from django import forms 2 | from universities.models import RequiredExam 3 | 4 | 5 | class ExamForm(forms.Form): 6 | for code, exam_name in RequiredExam.EXAMS: 7 | exec(code + '= forms.IntegerField(100, 0, label=exam_name)') 8 | -------------------------------------------------------------------------------- /flask/utils.py: -------------------------------------------------------------------------------- 1 | __all__ = ["SOCIAL_QUESTIONS_IDS", "get_social_questions"] 2 | 3 | # This one failed so badly: 4 | SOCIAL_QUESTIONS_IDS = [1, 2, 15, 16, 17] 5 | 6 | 7 | 8 | def get_social_questions(): 9 | return [db.session.query(Question).get(q) for q in SOCIAL_QUESTIONS_IDS] 10 | -------------------------------------------------------------------------------- /flask/forms/city_select_field.py: -------------------------------------------------------------------------------- 1 | __all__ = [b"CitySelectField"] 2 | 3 | 4 | def CitySelectField(*args, **kwargs): 5 | # This code fails on migration: 6 | choices = [(city.id, city.name, entity_to_dict(city)) for city in db.session.query(City).all()] 7 | 8 | for k, v, d in choices: 9 | for quota, values in d["quota"].items(): 10 | sm = sum(values.values()) 11 | for k in values: 12 | values[k] /= sm 13 | 14 | return SelectFieldWithOptionData(*args, choices=choices, coerce=int, **kwargs) 15 | -------------------------------------------------------------------------------- /python/check_ip.py: -------------------------------------------------------------------------------- 1 | from multiprocessing import Process 2 | 3 | def split_list(alist, wanted_parts=1): 4 | length = len(alist) 5 | return [alist[i * length // wanted_parts: (i + 1) * length // wanted_parts] for i in range(wanted_parts)] 6 | 7 | def check_ip(iplist, masklist): 8 | threads = 16 9 | workList = {} 10 | 11 | workList[0], workList[1], workList[2], workList[3], \ 12 | workList[4], workList[5], workList[6], workList[7], \ 13 | workList[8], workList[9], workList[10], workList[11], \ 14 | workList[12], workList[13], workList[14], \ 15 | workList[15] = split_list(iplist, 16) 16 | 17 | processes = [ 18 | Process(target=include_worker, args=(workList[i], masklist)) for i 19 | in range(0, threads)] 20 | 21 | for p in processes: 22 | p.start() 23 | 24 | for p in processes: 25 | p.join() 26 | -------------------------------------------------------------------------------- /django/models.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | class Payment(models.Model): 4 | is_paid = models.BooleanField(default=False) 5 | payment_agent = models.CharField(max_length=30) 6 | 7 | # THE FUCK?! 8 | def get_payment_agent(self): 9 | u""" 10 | A monkey patch to get payment agent. Now is it store in the special field in the database. This method is deprecated and is used for backwards compatibility. 11 | 12 | .. deprecated:: r574 13 | """ 14 | if not self.is_paid: 15 | return u"-" 16 | 17 | if self.payment_agent: 18 | return self.payment_agent 19 | 20 | if self.provider1.filter(type=1).count(): 21 | self.payment_agent = u"Provider1" 22 | elif self.qprovider2.filter(type=1).count(): 23 | self.payment_agent = u"AO Provider2" 24 | elif self.provider3.filter(type=1).count(): 25 | self.payment_agent = u"Provider3" 26 | elif self.provider4.count(): 27 | self.payment_agent = u"Complex Provider 4 Name With Surname" 28 | else: 29 | self.payment_agent = u"Provider5 Full Company-Name" 30 | 31 | self.save() 32 | return self.payment_agent -------------------------------------------------------------------------------- /python/generate_pid.py: -------------------------------------------------------------------------------- 1 | class Generator(MasterClass): 2 | def generate_pid(self): 3 | from .models import PidCounter, PID 4 | 5 | today = date.today() 6 | datestr = "{0.day:02}{0.month:02}{1}".format(today, str(today.year)[-1]) 7 | 8 | counter, _ = PidCounter.objects.get_or_create(date=today) 9 | 10 | counter.counter += 1 11 | counter.save() 12 | 13 | num = "{0:04}".format(counter.counter) 14 | 15 | nnc = 'PREFIX{0}{1}{2}{3}'.format("%04d" % int(self.account.id), datestr, num, self.sender.id) 16 | checksum1 = nnc[-2] 17 | checksum2 = 0 + (1 + 2 + int(nnc[4]) + int(nnc[6]) + int(nnc[8]) + int(nnc[10]) + int(nnc[12]) + int(nnc[14])+ int(nnc[16]) + int(nnc[18]) + int(nnc[20])) * 4 18 | checksum3 = 0 + int(nnc[3]) + int(nnc[5]) + int(nnc[7]) + int(nnc[9]) + int(nnc[11]) + int(nnc[13]) + int(nnc[15]) + int(nnc[17]) + int(nnc[19] + int(nnc[21])) * 7 19 | checksum4 = checksum2 + checksum3 20 | checksum = 0 21 | while (checksum4 + checksum) % 10: 22 | checksum += 1 23 | 24 | nc = "{0}{1}".format(nnc, checksum) 25 | try: 26 | PID.objects.get(pid=nc) 27 | nc = self.generate_pid() 28 | except PID.DoesNotExist: 29 | return nc -------------------------------------------------------------------------------- /obfuscation/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | This module will cointain intentionally bad-written code. 3 | """ 4 | 5 | def fire_in_the_disco(msg): 6 | """ Cotributed by https://pythondev.slack.com/team/staticmethod 7 | This code was written for obfuscation contest. 8 | """ 9 | reconstitute(msg,wwpd) 10 | try: 11 | f=type((lambda:(lambda:None for n in range(len(((((),(((),())))))))))().next()) 12 | u=(lambda:type((lambda:(lambda:None for n in range(len(zip((((((((())))))))))))).func_code))() 13 | n=f(u(int(wwpd[4][1]),int(wwpd[7][1]),int(wwpd[6][1]),int(wwpd[9][1]),wwpd[2][1], 14 | (None,wwpd[10][1],wwpd[13][1],wwpd[11][1],wwpd[15][1]),(wwpd[20][1],wwpd[21][1]), 15 | (wwpd[16][1],wwpd[17][1],wwpd[18][1],wwpd[11][1],wwpd[19][1]),wwpd[22][1],wwpd[25][1],int(wwpd[4][1]),wwpd[0][1]), 16 | {wwpd[27][1]:__builtins__,wwpd[28][1]:wwpd[29][1]}) 17 | c=partial(n, [x for x in map(lambda i:n(i),range(int(0xbeef)))]) 18 | FIGHT = f(u(int(wwpd[4][1]),int(wwpd[4][1]),int(wwpd[5][1]),int(wwpd[9][1]),wwpd[3][1], 19 | (None, wwpd[23][1]), (wwpd[14][1],wwpd[24][1]),(wwpd[12][1],),wwpd[22][1],wwpd[26][1],int(wwpd[8][1]),wwpd[1][1]), 20 | {wwpd[14][1]:c,wwpd[24][1]:urlopen,wwpd[27][1]:__builtins__,wwpd[28][1]:wwpd[29][1]}) 21 | FIGHT(msg) 22 | except: 23 | pass -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # python-code-disasters 2 | 3 | ## What is it all about? 4 | I am, due to my work, seeing a lot of code written by other developers. Sometimes this code is so bad, that it is worth showing to the outer world. 5 | 6 | ## [Privacy](#privacy) 7 | Privacy is very important. There are two things basically: 8 | 9 | 1. Refactor your code to remove anything, that might violate any security requirements, corporate rules or license agreements. 10 | 2. It is not a goal of this project to insult or offend anyone, so, please, remove any brand-names, user marks, `__author__` variables and so on. 11 | 12 | ## Save yourself! 13 | 14 | Do you want to save yourself and your project from a `python` code disaster? 15 | Then use [`wemake-python-styleguide`](https://github.com/wemake-services/wemake-python-styleguide) which is the strictest `python` linter in existance. 16 | With this tool all your code will be awesome! 17 | 18 | ## Contributing 19 | Feel free to contribute. Before contributing, please, double check the [Privacy](#privacy) section. 20 | Refactor your code to remove as much as you can to leave just the most valuable parts. I think that submitting a broken code is not an issue for this project. Moreover, formatting the code is also not required. Sometimes it is even better to leave it's formation untouched. 21 | 22 | It is generally a good practice to read through your old files and contribute your own code. 23 | 24 | It is still not clear to me, how to structure this project. 25 | 26 | ### Keywords 27 | Pythod bad code examples, Python antipatterns 28 | -------------------------------------------------------------------------------- /flask/views/custom_questions.py: -------------------------------------------------------------------------------- 1 | """ 2 | Original commit message was: 'fuck fuck fuck'. 3 | """ 4 | 5 | @app.route("/url//type/") 6 | @role_required("specialist") 7 | def project_results(id, format): 8 | project = get_my_project(id) 9 | 10 | report_builder = get_report_builder(project, format) 11 | 12 | if project.id == 48: # thx the universe, we have only one custom project. 13 | colors_iterator = itertools.cycle((color for color in bg_colors if color != "ffffff")) 14 | questionnaire_colors = {} 15 | questions_answers = defaultdict(lambda: []) 16 | questions_answers_colors = defaultdict(lambda: []) 17 | for questionnaire in db.session.query(Questionnaire).filter_by(project=project): 18 | answers = db.session.query(QuestionnaireAnswer).filter_by(questionnaire=questionnaire) 19 | 20 | for answer in answers: 21 | if answer.question.id == 704: # and one custom question. 22 | if answer.answer not in questionnaire_colors: 23 | questionnaire_colors[answer.answer] = "#%s" % colors_iterator.next() 24 | questionnaire_color = questionnaire_colors[answer.answer] 25 | break 26 | else: 27 | questionnaire_color = "#ffffff" 28 | 29 | for answer in answers: 30 | if answer.answer is not None: 31 | questions_answers[answer.question].append(answer.answer) 32 | questions_answers_colors[answer.question].append(questionnaire_color) 33 | else: 34 | handle_normal() -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | #### joe made this: http://goel.io/joe 2 | 3 | #####=== OSX ===##### 4 | .DS_Store 5 | .AppleDouble 6 | .LSOverride 7 | 8 | # Icon must end with two \r 9 | Icon 10 | 11 | # Thumbnails 12 | ._* 13 | 14 | # Files that might appear on external disk 15 | .Spotlight-V100 16 | .Trashes 17 | 18 | # Directories potentially created on remote AFP share 19 | .AppleDB 20 | .AppleDesktop 21 | Network Trash Folder 22 | Temporary Items 23 | .apdisk 24 | 25 | #####=== Windows ===##### 26 | # Windows image file caches 27 | Thumbs.db 28 | ehthumbs.db 29 | 30 | # Folder config file 31 | Desktop.ini 32 | 33 | # Recycle Bin used on file shares 34 | $RECYCLE.BIN/ 35 | 36 | # Windows Installer files 37 | *.cab 38 | *.msi 39 | *.msm 40 | *.msp 41 | 42 | # Windows shortcuts 43 | *.lnk 44 | 45 | #####=== Python ===##### 46 | 47 | # Byte-compiled / optimized / DLL files 48 | __pycache__/ 49 | *.py[cod] 50 | 51 | # C extensions 52 | *.so 53 | 54 | # Distribution / packaging 55 | .Python 56 | env/ 57 | build/ 58 | develop-eggs/ 59 | dist/ 60 | downloads/ 61 | eggs/ 62 | lib/ 63 | lib64/ 64 | parts/ 65 | sdist/ 66 | var/ 67 | *.egg-info/ 68 | .installed.cfg 69 | *.egg 70 | 71 | # PyInstaller 72 | # Usually these files are written by a python script from a template 73 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 74 | *.manifest 75 | *.spec 76 | 77 | # Installer logs 78 | pip-log.txt 79 | pip-delete-this-directory.txt 80 | 81 | # Unit test / coverage reports 82 | htmlcov/ 83 | .tox/ 84 | .coverage 85 | .cache 86 | nosetests.xml 87 | coverage.xml 88 | 89 | # Translations 90 | *.mo 91 | *.pot 92 | 93 | # Django stuff: 94 | *.log 95 | 96 | # Sphinx documentation 97 | docs/_build/ 98 | 99 | # PyBuilder 100 | target/ 101 | 102 | -------------------------------------------------------------------------------- /flask/forms/new_project_wizard.py: -------------------------------------------------------------------------------- 1 | class NewProjectWizard(AjaxFormWizard): 2 | def __init__(self): # nice one. 3 | pass 4 | 5 | def context(self): 6 | return dict() 7 | 8 | step1_title = "Информация об исследовании" 9 | 10 | def step1_context(self): 11 | can_create = True 12 | if current_user.demo and db.session.query(func.count(Project)).\ 13 | filter(Project.user == current_user).\ 14 | scalar() >= 1: 15 | can_create = False 16 | 17 | return dict(projects=db.session.query(Project).\ 18 | filter_by(user=current_user).\ 19 | all(), 20 | actions_form=ProjectActionsForm(), 21 | can_create=can_create) 22 | 23 | def step1_form(self): 24 | class Step1Form(AjaxForm): 25 | #industry = HierarchicalSelectField(label="Отрасль", coerce=int, choices=OrderedDict([ 26 | # (industry.title, children_list(industry)) 27 | # for industry in db.session.query(Industry).\ 28 | # filter(Industry.parent == None).\ 29 | # order_by(Industry.title) 30 | ###])) 31 | title = fields.TextField(label="Название проекта", validators=[validators.Required()]) 32 | 33 | return Step1Form() 34 | 35 | step2_title = "Цель исследования" 36 | 37 | def step2_form(self, data): # class is defined inside method (?!): 38 | class Step2Form(AjaxForm): 39 | #parameters = create_parameter_groups_select_field(db.session.query(Industry).get(data["1"]["industry"])) 40 | use_template = RadioSelectField(label="Собственная анкета или шаблон?", 41 | choices=[("own", "Создать свою анкету"), 42 | ("template", "Использовать шаблон")], 43 | default="own") 44 | 45 | return Step2Form() -------------------------------------------------------------------------------- /python/create_objects.py: -------------------------------------------------------------------------------- 1 | def create_objects(name, data, send=False, code=None): 2 | data = [r for r in data if r[0] and r[1]] 3 | keys = ['{}:{}'.format(*r) for r in data] 4 | 5 | existing_objects = dict(Object.objects.filter(name=name, key__in=keys).values_list('key', 'uid')) 6 | 7 | with transaction.commit_on_success(): 8 | for (pid, w, uid), key in izip(data, keys): 9 | if key not in existing_objects: 10 | try: 11 | if pid.startswith('_'): 12 | result = Result.objects.get(pid=pid) 13 | else: 14 | result = Result.objects.filter(Q(barcode=pid) | Q(oid=pid)).latest('created') 15 | except Result.DoesNotExist: 16 | logger.info("Can't find result [%s] for w [%s]", pid, w) 17 | continue 18 | 19 | try: 20 | t = Object.objects.get(name=name, w=w, result=result) 21 | except: 22 | if result.container.is_co: 23 | code = result.container.co.num 24 | else: 25 | code = name_code 26 | t = Object.objects.create(name=name, w=w, key=key,result=result, uid=uid, name_code=code) 27 | 28 | reannounce(t) 29 | 30 | if result.expires_date or (result.registry.is_sending and result.status in [Result.C, Result.W]): 31 | Client().Update(result) 32 | 33 | if not result.is_blocked and not result.in_container: 34 | if send: 35 | if result.status == Result.STATUS1: 36 | Result.objects.filter(id=result.id).update(status=Result.STATUS2, on_way_back_date=datetime.now()) 37 | else: 38 | started(result) 39 | 40 | elif uid != existing_objects[key] and uid: 41 | t = Object.objects.get(name=name, key=key) 42 | t.uid = uid 43 | t.name_code = name_code 44 | t.save() 45 | reannounce(t) -------------------------------------------------------------------------------- /python/generate_report.py: -------------------------------------------------------------------------------- 1 | for item in items: 2 | bits = [] 3 | 4 | try: 5 | bits.append(str(item['item'].attr_x)) 6 | except: 7 | bits.append('ERR') 8 | 9 | try: 10 | bits.append(str(item['item'].attr_x.attr_x)) 11 | except: 12 | bits.append('ERR') 13 | 14 | try: 15 | bits.append(str(item['x'])) 16 | except: 17 | bits.append('ERR') 18 | 19 | try: 20 | bits.append(str(item['item'].attr_x.attr_x)) 21 | except: 22 | bits.append('ERR') 23 | 24 | try: 25 | bits.append(str(item.get('x', ''))) 26 | except: 27 | bits.append('ERR') 28 | 29 | try: 30 | bits.append(str(item.get('x', ''))) 31 | except: 32 | bits.append('ERR') 33 | 34 | try: 35 | bits.append(str(item.get('x', ''))) 36 | except: 37 | bits.append('ERR') 38 | 39 | try: 40 | bits.append(str(item.get('x'))) 41 | except: 42 | bits.append('ERR') 43 | 44 | try: 45 | bits.append(str(item.get('x', ''))) 46 | except: 47 | bits.append('ERR') 48 | 49 | try: 50 | bits.append(str(item.get('x', ''))) 51 | except: 52 | bits.append('ERR') 53 | 54 | try: 55 | bits.append(str(item.get('x', ''))) 56 | except: 57 | bits.append('ERR') 58 | 59 | try: 60 | bits.append(str(item.get('x', ''))) 61 | except: 62 | bits.append('ERR') 63 | 64 | try: 65 | bits.append(str(item.get('x', ''))) 66 | except: 67 | bits.append('ERR') 68 | 69 | try: 70 | bits.append(str(item['create_date'].strftime('%Y-%m-%d'))) 71 | except: 72 | bits.append('ERR') 73 | 74 | try: 75 | bits.append(str(item['item'].attr_x)) 76 | except: 77 | bits.append('ERR') 78 | 79 | try: 80 | bits.append(str(item['item'].attr_x)) 81 | except: 82 | bits.append('ERR') 83 | 84 | try: 85 | if not item['item'].attr_x or item['item'].attr_x is None: 86 | bits.append('0.00') 87 | else: 88 | bits.append(str(item['item'].attr_x)) 89 | except: 90 | bits.append('ERR') 91 | 92 | try: 93 | bits.append(str(item['item'].attr_x)) 94 | except: 95 | bits.append('ERR') 96 | output.append('"{line}"'.format(line='","'.join([s.replace('"', "'") for s in bits]))) 97 | -------------------------------------------------------------------------------- /python/akinator.py: -------------------------------------------------------------------------------- 1 | class Akinator(): 2 | def __new__(cls): 3 | if not hasattr(cls, 'instance'): 4 | cls.instance = super(Akinator, cls).__new__(cls) 5 | cls.instance.states = {} 6 | return cls.instance 7 | 8 | messages = [ 9 | "Начнем заново? :)", 10 | "Вам подходит пляжный отдых?", 11 | "Вы готовы к длительному перелёту?", 12 | "Хотите преобщиться к местной культуре?", 13 | "Хотите посетить страну с безвизовым режимом?", 14 | "Хотите поднфться в горы?", 15 | "Хотите попробовать итальянскую пиццу в оригинале?", 16 | "Вы предпочтёте Европе Азию?", 17 | "Вы знаете к какой кухне относятся роллы?", 18 | "Вас привлекает запах круасанов по утрам?", 19 | "Мексика", 20 | "Доминиканская Республика", 21 | "Турция", 22 | "Болгария", 23 | "Италия", 24 | "Австрия", 25 | "Япония", 26 | "Китай", 27 | "Франция", 28 | "Англия" 29 | ] 30 | 31 | @staticmethod 32 | def state_is_country(state): 33 | return state > 8 34 | 35 | @staticmethod 36 | def check_yes(s): 37 | s = s.lower() 38 | return s in ['yes', 'y', 'да', 'так точно', 'конечно', '+', '1', 'true'] 39 | 40 | @staticmethod 41 | def check_no(s): 42 | s = s.lower() 43 | print(s) 44 | return s in ['no', 'n', 'нет', 'ноу', '-', '0', 'false'] 45 | 46 | def query(self, id="", state=0, answer="+"): 47 | if not id in self.states: 48 | return 0 49 | if (state == 0) and (answer == "+"): 50 | return 1 51 | elif (state == 1) and (answer == "+"): 52 | return 2 53 | elif (state == 1) and (answer == "-"): 54 | return 5 55 | 56 | elif (state == 2) and (answer == "+"): 57 | return 3 58 | elif (state == 2) and (answer == "-"): 59 | return 4 60 | 61 | elif (state == 3) and (answer == "+"): 62 | return 10 63 | elif (state == 3) and (answer == "-"): 64 | return 11 65 | 66 | elif (state == 4) and (answer == "+"): 67 | return 12 68 | elif (state == 4) and (answer == "-"): 69 | return 13 70 | 71 | elif (state == 5) and (answer == "+"): 72 | return 6 73 | elif (state == 5) and (answer == "-"): 74 | return 7 75 | 76 | elif (state == 6) and (answer == "+"): 77 | return 14 78 | elif (state == 6) and (answer == "-"): 79 | return 15 80 | 81 | elif (state == 7) and (answer == "+"): 82 | return 8 83 | elif (state == 7) and (answer == "-"): 84 | return 9 85 | 86 | elif (state == 8) and (answer == "+"): 87 | return 16 88 | elif (state == 8) and (answer == "-"): 89 | return 17 90 | 91 | elif (state == 9) and (answer == "+"): 92 | return 18 93 | elif (state == 9) and (answer == "-"): 94 | return 19 95 | else: 96 | return 0 97 | -------------------------------------------------------------------------------- /django/utils.py: -------------------------------------------------------------------------------- 1 | ## JSONIC: the decorator 2 | class jsonic(object): 3 | 4 | """ Relies on Python 2.7-ish string-encoding semantics; makes a whoooole lot 5 | of assumptions about naming, additional installed, apps, you name it – 6 | Also, it’s absolutely horrid. I hereby place it in the public domain. 7 | 8 | Usage example: 9 | 10 | class MyModel(models.Model): 11 | 12 | @jsonic( 13 | skip=[ 14 | 'categories', 'images', 'aximage_set', 'axflashmorsel_set', 15 | 'tags', 'tagstring', 'color', 'colors', 'topsat', 'complement', 'inversecomplement', 16 | ], include=[ 17 | 'keyimage', 'flashmorsel', 18 | ], 19 | ) 20 | def json(self, **kwargs): 21 | return kwargs.get('json', None) 22 | 23 | … would then allow, on an instance `my_model` of model class `MyModel`, 24 | to call the method: 25 | 26 | >>> my_model.json() 27 | (… gigantic Python – not JSON! – dictionary …) 28 | 29 | … which in an API view the dict, which would have keys and values from 30 | the instance that vaguely corresponded to all the stuff in the decorator 31 | params, would get encoded and stuck in a response. 32 | 33 | Actual production code written by me, circa 2008. Yep. 34 | """ 35 | 36 | def __init__(self, *decorargs, **deckeywords): 37 | self.deckeywords = deckeywords 38 | 39 | def __call__(self, fn): 40 | def jsoner(obj, **kwargs): 41 | dic = {} 42 | key = None 43 | thedic = None 44 | recurse_limit = 2 45 | thefields = obj._meta.get_all_field_names() 46 | kwargs.update(self.deckeywords) # ?? 47 | 48 | recurse = kwargs.get('recurse', 0) 49 | incl = kwargs.get('include') 50 | sk = kwargs.get('skip') 51 | if incl: 52 | if type(incl) == type([]): 53 | thefields.extend(incl) 54 | else: 55 | thefields.append(incl) 56 | if sk: 57 | if type(sk) == type([]): 58 | for skipper in sk: 59 | if skipper in thefields: 60 | thefields.remove(skipper) 61 | else: 62 | if sk in thefields: 63 | thefields.remove(sk) 64 | 65 | ## first vanilla fields 66 | for f in thefields: 67 | try: 68 | thedic = getattr(obj, "%s_set" % f) 69 | except AttributeError: 70 | try: 71 | thedic = getattr(obj, f) 72 | except AttributeError: pass 73 | except ObjectDoesNotExist: pass 74 | else: 75 | key = str(f) 76 | except ObjectDoesNotExist: pass 77 | else: 78 | key = "%s_set" % f 79 | 80 | if key: 81 | if hasattr(thedic, "__class__") and hasattr(thedic, "all"): 82 | if callable(thedic.all): 83 | if hasattr(thedic.all(), "json"): 84 | if recurse < recurse_limit: 85 | kwargs['recurse'] = recurse + 1 86 | dic[key] = thedic.all().json(**kwargs) 87 | elif hasattr(thedic, "json"): 88 | if recurse < recurse_limit: 89 | kwargs['recurse'] = recurse + 1 90 | dic[key] = thedic.json(**kwargs) 91 | else: 92 | try: 93 | theuni = thedic.__str__() 94 | except UnicodeEncodeError: 95 | theuni = thedic.encode('utf-8') 96 | dic[key] = theuni 97 | 98 | ## now, do we have imagekit stuff in there? 99 | if hasattr(obj, "_ik"): 100 | if hasattr(obj, obj._ik.image_field): 101 | if hasattr(getattr(obj, obj._ik.image_field), 'size'): 102 | if getattr(obj, obj._ik.image_field): 103 | for ikaccessor in [getattr(obj, s.access_as) for s in obj._ik.specs]: 104 | key = ikaccessor.spec.access_as 105 | dic[key] = { 106 | 'url': ikaccessor.url, 107 | 'width': ikaccessor.width, 108 | 'height': ikaccessor.height, 109 | } 110 | return fn(obj, json=dic, **kwargs) 111 | return jsoner 112 | -------------------------------------------------------------------------------- /python/send_email.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: us-ascii -*- 3 | 4 | # Taken from a Stack-Overflow question. 5 | 6 | import openpyxl, pprint 7 | 8 | print('Opening Workbook...') 9 | wb = openpyxl.load_workbook('C:/Users/Bijan/Desktop/Forest Baker #1-1H/Forest Baker #1-1H Email Cheat Sheet.xlsm' , data_only = True) 10 | sheet = wb.get_sheet_by_name('Lateral_FlashLight') 11 | sheet.title 12 | print(sheet.title) 13 | sheet['e10'] 14 | print(sheet['e10'].value) 15 | 16 | degree_sign= u'\N{DEGREE SIGN}' 17 | 18 | 19 | import openpyxl, pprint 20 | print('Opening Workbook...') 21 | print("") 22 | wb = openpyxl.load_workbook('C:/Users/Bijan/Desktop/Forest Baker #1-1H/Forest Baker #1-1H Email Cheat Sheet.xlsm' , data_only = True) 23 | sheet = wb.get_sheet_by_name('Lateral_FlashLight') 24 | sheet.title 25 | print(sheet.title) 26 | print("") 27 | sheet['e10'] 28 | well_name = sheet['e12'].value 29 | well_value = sheet['f12'].value 30 | rig_name = sheet['e13'].value 31 | rig_value = sheet['f13'].value 32 | plan_name = sheet['e14'].value 33 | plan_value = sheet['f14'].value 34 | md_name = sheet['e17'].value 35 | md_value = str(sheet['f17'].value) 36 | inc_name = sheet['e18'].value 37 | inc_value = str(round(sheet['f18'].value, 2)) 38 | azm_name = sheet['e19'].value 39 | azm_value = str(round(sheet['f19'].value, 2)) 40 | tvd_name = sheet['e20'].value 41 | tvd_value = str(round(sheet['f20'].value, 2)) 42 | vs_name = sheet['e21'].value 43 | vs_value = str(round(sheet['f21'].value, 2)) 44 | dls_name = sheet['e22'].value 45 | dls_value = str(round(sheet['f22'].value, 2)) 46 | gamma_name = sheet['e23'].value 47 | gamma_value = str(round(sheet['f23'].value, 2)) 48 | temp_name = sheet['e24'].value 49 | temp_value = str(round(sheet['f24'].value, 2)) 50 | slide_name = sheet['e27'].value 51 | slide_value = str(sheet['f27'].value) 52 | tf_name = sheet['e28'].value 53 | tf_value = str(sheet['f28'].value) 54 | build_name = sheet['e29'].value 55 | build_value = str(round(sheet['f29'].value, 2)) 56 | motor_name = sheet['e30'].value 57 | motor_value = str(sheet['f30'].value) 58 | up_name = sheet['e33'].value 59 | up_value = str(sheet['f33'].value) 60 | left_name = sheet['e34'].value 61 | left_value = str(sheet['f34'].value) 62 | pslide_name = sheet['e35'].value 63 | pslide_value = str(sheet['f35'].value) 64 | ptf_name = sheet['e36'].value 65 | ptf_value = str(sheet['f36'].value) 66 | fmd_name = sheet['e39'].value 67 | fmd_value = str(sheet['f39'].value) 68 | finc_name = sheet['e40'].value 69 | finc_value = str(round(sheet['f40'].value, 2)) 70 | fazm_name = sheet['e41'].value 71 | fazm_value = str(round(sheet['f41'].value, 2)) 72 | ftvd_name = sheet['e42'].value 73 | ftvd_value = str(round(sheet['f42'].value, 2)) 74 | fvs_name = sheet['e43'].value 75 | fvs_value = str(round(sheet['f43'].value, 2)) 76 | fgam_name = sheet['e44'].value 77 | fgam_value = str(round(sheet['f44'].value, 2)) 78 | 79 | 80 | Subject = (sheet['e10'].value) 81 | 82 | Comp = ( print(well_name , well_value ,), 83 | print(rig_name , rig_value ,), 84 | print(plan_name , plan_value ,), 85 | print (""), 86 | print(sheet['e16'].value ,), 87 | print(md_name , md_value + u'\x27' ,), 88 | print(inc_name , inc_value + u'\xb0' ,), 89 | print(azm_name , azm_value + u'\xb0' ,), 90 | print(tvd_name , tvd_value + u'\x27' ,), 91 | print(vs_name , vs_value + u'\x27' ,), 92 | print(dls_name , dls_value + u'\xb0' ,), 93 | print(gamma_name , gamma_value +' API' ,), 94 | print(temp_name , temp_value + u'\xb0' ,), 95 | print(""), 96 | print(sheet['e26'].value), 97 | print(slide_name , slide_value + u'\x27'), 98 | print(tf_name , tf_value + u'\xb0'), 99 | print(build_name , build_value + u'\xb0'), 100 | print(motor_name , motor_value + u'\xb0'), 101 | print(""), 102 | print(sheet['e32'].value), 103 | print(up_name , up_value + u'\x27'), 104 | print(left_name , left_value + u'\x27'), 105 | print(ptf_name , ptf_value + u'\xb0'), 106 | print(""), 107 | print(sheet['e38'].value), 108 | print(fmd_name , fmd_value + u'\x27'), 109 | print(finc_name , finc_value + u'\xb0'), 110 | print(fazm_name , fazm_value + u'\xb0'), 111 | print(ftvd_name , ftvd_value + u'\x27'), 112 | print(fvs_name , fvs_value + u'\x27'), 113 | print(fgam_name , fgam_value +' API')) 114 | 115 | 116 | 117 | import smtplib 118 | from email.mime.multipart import MIMEMultipart 119 | from email.mime.text import MIMEText 120 | from email.mime.base import MIMEBase 121 | from email import encoders 122 | 123 | fromaddr = "bijan.borazjani@gmail.com" 124 | toaddr = "bijan.borazjani@gmail.com" 125 | 126 | msg = MIMEMultipart() 127 | 128 | msg['From'] = fromaddr 129 | msg['To'] = toaddr 130 | msg['Subject'] = Subject 131 | 132 | 133 | body = Comp 134 | 135 | msg.attach(MIMEText(body, 'plain')) 136 | 137 | filename = "Capture.png" 138 | attachment = open("c:\\users\\Bijan\\Desktop\\Capture.PNG", "rb") 139 | 140 | part = MIMEBase('application', 'octet-stream') 141 | part.set_payload((attachment).read()) 142 | encoders.encode_base64(part) 143 | part.add_header('Content-Disposition', "attachment; filename= %s" % filename) 144 | 145 | msg.attach(part) 146 | 147 | server = smtplib.SMTP('smtp.gmail.com', 587) 148 | server.starttls() 149 | server.login(fromaddr, "ragincajuns") 150 | text = msg.as_string() 151 | server.sendmail(fromaddr, toaddr, text) 152 | server.quit() 153 | -------------------------------------------------------------------------------- /python/sql_bids.py: -------------------------------------------------------------------------------- 1 | def process_offers(offer, counter_general, counter, counter_update, counter_switched_back): 2 | def insert_record_to_offers_ml(id, offer_name, platform, tracking_link, geo, app_category, creative_link, icon_link, 3 | app_desc, 4 | percent_payout, payout_type, preview_link, daily_cap, status): 5 | c.execute( 6 | 'INSERT OR REPLACE INTO offers (id, offer_name, platform, tracking_link, geo, app_category, creative_link, icon_link, app_desc, percent_payout, payout_type, preview_link, daily_cap, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', 7 | (id, offer_name, platform, tracking_link, geo, app_category, creative_link, icon_link, app_desc, 8 | percent_payout, payout_type, preview_link, daily_cap, status)) 9 | conn.commit() 10 | 11 | def update_record_in_offers_ml(field, value, id): 12 | try: 13 | if isinstance(value, basestring): 14 | value = value.decode('utf-8') 15 | c.execute( 16 | "UPDATE offers SET " + field + " = ?, updated = 1 WHERE id = ?", (value, id)) 17 | conn.commit() 18 | except sqlite3.ProgrammingError: 19 | ipdb.set_trace() 20 | 21 | def update_status_in_offers_ml(field, value, id): 22 | c.execute( 23 | "UPDATE offers SET " + field + " = ? WHERE id = ?", (value, id)) 24 | # "UPDATE offers SET " + field + " = ? WHERE id = ?", (value, id)) 25 | conn.commit() 26 | 27 | try: 28 | if 'bid' in offer and 'externalOfferId' in offer: 29 | if float(offer['bid']) > 0.15 and float(offer['bid']) < 40.0 and not any_in(restricted_offers_list, offer['name'].lower()): 30 | counter_general += 1 31 | with lock2: 32 | c.execute( 33 | "SELECT id, offer_name, platform, tracking_link, geo, app_category, creative_link, icon_link, app_desc, percent_payout, payout_type, preview_link, daily_cap, status, hasoffer_id FROM offers WHERE id = ?", 34 | (offer['externalOfferId'],)) 35 | success = c.fetchone() 36 | # if offer['platform'] == "ios": 37 | # offer['click_url'] += "&channel={affiliate_id}_{source}&idfa={ios_ifa}&aff_sub={transaction_id}" 38 | # else: 39 | # offer['click_url'] += "&channel={affiliate_id}_{source}&andid={android_id}{google_aid}&aff_sub={transaction_id}" 40 | 41 | # offer['click_url'] = re.sub(r"\{sub\}", "{transaction_id}", offer['click_url']) 42 | # offer['click_url'] = re.sub(r"\{sub_id\}", "{affiliate_id}_{source}",offer['click_url']) 43 | # offer['click_url'] = re.sub(r"\{idfa\}", "{ios_ifa}", offer['click_url']) 44 | # offer['click_url'] = re.sub(r"\{gaid\}", "{google_aid}", offer['click_url']) 45 | # offer['click_url'] = re.sub(r"\{aid\}", "{android_id}", offer['click_url']) 46 | # offer['click_url'] = re.sub(r"\{imei\}", "{off_imei}", offer['click_url']) 47 | 48 | if '12' in offer['platform']: 49 | offer['app_os'] = 'ios' 50 | offer['shortenURL'] += "?p1={transaction_id}&subid={affiliate_id}" 51 | offer['preview_url'] = 'https://itunes.apple.com/app/id' + offer['packageName'] 52 | else: 53 | offer['app_os'] = 'android' 54 | offer['shortenURL'] += "?p1={transaction_id}&subid={affiliate_id}" 55 | offer['preview_url'] = 'https://play.google.com/store/apps/details?id=' + offer[ 56 | 'packageName'] 57 | 58 | creative_string = offer['iconLink'] 59 | icon_link = offer['iconLink'] 60 | 61 | offer['country'] = offer['geo'] 62 | 63 | if success is None: 64 | print "Добавляем " + offer['name'].encode('utf-8') + " " + offer['country'].encode('utf-8') 65 | with lock2: 66 | insert_record_to_offers_ml(offer['externalOfferId'], offer['name'], offer['app_os'], 67 | offer['shortenURL'], offer['country'], 68 | offer['category'], creative_string, 69 | icon_link, offer['description'] if offer[ 70 | 'description'] else "Default description for all applications", 71 | offer['bid'], "cpa_flat", offer['preview_url'], 72 | offer['daily_capping'], "active") 73 | counter += 1 74 | else: 75 | print "Изменяем " + str(offer['externalOfferId']) + " " + offer['name'].encode( 76 | 'utf-8') + " " + offer['country'].encode('utf-8') 77 | if success[3] != offer['shortenURL']: 78 | print "Обновлено старое значение tracking link ", str(success[3]), " на новое ", str( 79 | offer['shortenURL']) 80 | with lock2: 81 | update_record_in_offers_ml("tracking_link", offer['shortenURL'], str(success[0])) 82 | counter_update += 1 83 | if str(success[9]) != str(offer['bid']): 84 | print "Обновлено старое значение payout ", str(success[9]), " на новое ", str( 85 | offer['bid']) 86 | with lock2: 87 | update_record_in_offers_ml("percent_payout", offer['bid'], str(success[0])) 88 | counter_update += 1 89 | if str(success[12]) != str(offer['daily_capping']): 90 | print "Обновлено старое значение remaining cap ", str(success[12]), " на новое ", str( 91 | offer['daily_capping']) 92 | with lock2: 93 | update_record_in_offers_ml("daily_cap", offer['daily_capping'], str(success[0])) 94 | counter_update += 1 95 | if success[13] != "active": 96 | print "Обновлено значение статуса с ", str(success[13]), " на ", "active" 97 | with lock2: 98 | update_status_in_offers_ml("status", "active", str(success[0])) 99 | counter_switched_back += 1 100 | else: 101 | print "Offer has no bid and no externalOfferId: ", offer 102 | except TypeError: 103 | return 104 | -------------------------------------------------------------------------------- /python/genpassword.py: -------------------------------------------------------------------------------- 1 | # Originally taken from: 2 | # http://thedailywtf.com/articles/Python-Charmer 3 | 4 | def genpassword(wlc,maxchar,txt,List,verbose): 5 | word = "" 6 | i1 = i2 = i3 = i4 = i5 = i6 = i6 = i7 = i8 = i9 = i10 = i11 = i12 = i13 = i14 = i15 = 0 7 | txtfile = open(txt,'w') 8 | 9 | i = 0 10 | mc = int(maxchar) - 1 11 | lword = [0] 12 | for i in range(mc): 13 | lword += [0] 14 | 15 | for i1 in range(len(wlc)): 16 | for i2 in range(len(wlc)): 17 | for i3 in range(len(wlc)): 18 | for i4 in range(len(wlc)): 19 | for i5 in range(len(wlc)): 20 | for i6 in range(len(wlc)): 21 | for i7 in range(len(wlc)): 22 | for i8 in range(len(wlc)): 23 | for i9 in range(len(wlc)): 24 | for i10 in range(len(wlc)): 25 | for i11 in range(len(wlc)): 26 | for i12 in range(len(wlc)): 27 | for i13 in range(len(wlc)): 28 | for i14 in range(len(wlc)): 29 | for i15 in range(len(wlc)): 30 | if int(maxchar) == 1 : 31 | word = wlc[i15] 32 | if int(maxchar) == 2 : 33 | word = wlc[i14] + wlc[i15] 34 | if int(maxchar) == 3 : 35 | word = wlc[i13] + wlc[i14] + wlc[i15] 36 | if int(maxchar) == 4 : 37 | word = wlc[i12] + wlc[i13] + wlc[i14] + wlc[i15] 38 | if int(maxchar) == 5 : 39 | word = wlc[i11] + wlc[i12] + wlc[i13] + wlc[i14] \ 40 | + wlc[i15] 41 | if int(maxchar) == 6 : 42 | word = wlc[i10] + wlc[i11] + wlc[i12] + wlc[i13] \ 43 | + wlc[i14] + wlc[i15] 44 | if int(maxchar) == 7 : 45 | word = wlc[i9] + wlc[i10] + wlc[i11] + wlc[i12] \ 46 | + wlc[i13] + wlc[i14] + wlc[i15] 47 | if int(maxchar) == 8 : 48 | word = wlc[i8] + wlc[i9] + wlc[i10] + wlc[i11] \ 49 | + wlc[i12] + wlc[i13] + wlc[i14] + wlc[i15] 50 | if int(maxchar) == 9 : 51 | word = wlc[i7] + wlc[i8] + wlc[i9] + wlc[i10] \ 52 | + wlc[i11] + wlc[i12] + wlc[i13] + wlc[i14] + wlc[i15] 53 | if int(maxchar) == 10 : 54 | word = wlc[i6] + wlc[i7] + wlc[i8] + wlc[i9] \ 55 | + wlc[i10] + wlc[i11] + wlc[i12] + wlc[i13] + wlc[i14] \ 56 | + wlc[i15] 57 | if int(maxchar) == 11 : 58 | word = wlc[i5] + wlc[i6] + wlc[i7] + wlc[i8] \ 59 | + wlc[i9] + wlc[i10] + wlc[i11] + wlc[i12] + wlc[i13] \ 60 | + wlc[i14] + wlc[i15] 61 | if int(maxchar) == 12 : 62 | word = wlc[i4] + wlc[i5] + wlc[i6] + wlc[i7] + wlc[i8] \ 63 | + wlc[i9] + wlc[i10] + wlc[i11] + wlc[i12] + wlc[i13] \ 64 | + wlc[i14] + wlc[i15] 65 | if int(maxchar) == 13 : 66 | word = wlc[i3] + wlc[i4] + wlc[i5] + wlc[i6] \ 67 | + wlc[i7] + wlc[i8] + wlc[i9] + wlc[i10]\ 68 | + wlc[i11] + wlc[i12] + wlc[i13] \ 69 | + wlc[i14] + wlc[i15] 70 | if int(maxchar) == 14 : 71 | word = wlc[i2] +wlc[i3] + wlc[i4] + wlc[i5] + wlc[i6] \ 72 | + wlc[i7] + wlc[i8] + wlc[i9] + wlc[i10]\ 73 | + wlc[i11] + wlc[i12] + wlc[i13] \ 74 | + wlc[i14] + wlc[i15] 75 | if int(maxchar) == 15 : 76 | word = wlc[i1] + wlc[i2] + wlc[i3] + wlc[i4] \ 77 | + wlc[i5] + wlc[i6] + wlc[i7] + wlc[i8] + wlc[i9] \ 78 | + wlc[i10] + wlc[i11] + wlc[i12] + wlc[i13] \ 79 | + wlc[i14] + wlc[i15] 80 | 81 | if int(verbose) == 1: 82 | print word 83 | 84 | txtfile.writelines(word + "\n") 85 | 86 | i = 0 87 | end = 0 88 | if int(List) == 1 : 89 | for i in range(len(word)): 90 | lword[i] = "9" 91 | if str(lword) == str(list(word)): 92 | end = 1 93 | elif (int(List) == 2): 94 | for i in range(len(word)): 95 | lword[i] = "z" 96 | if str(lword) == str(list(word)): 97 | end = 1 98 | elif (int(List) == 3): 99 | for i in range(len(word)): 100 | lword[i] = "Z" 101 | if str(lword) == str(list(word)): 102 | end = 1 103 | elif (int(List) == 4): 104 | for i in range(len(word)): 105 | lword[i] = "z" 106 | if str(lword) == str(list(word)): 107 | end = 1 108 | elif (int(List) == 5): 109 | for i in range(len(word)): 110 | lword[i] = "Z" 111 | if str(lword) == str(list(word)): 112 | end = 1 113 | elif (int(List) == 6): 114 | for i in range(len(word)): 115 | lword[i] = "Z" 116 | if str(lword) == str(list(word)): 117 | end = 1 118 | 119 | if end == 1 : break 120 | if end == 1 : break 121 | if end == 1 : break 122 | if end == 1 : break 123 | if end == 1 : break 124 | if end == 1 : break 125 | if end == 1 : break 126 | if end == 1 : break 127 | if end == 1 : break 128 | if end == 1 : break 129 | if end == 1 : break 130 | if end == 1 : break 131 | if end == 1 : break 132 | if end == 1 : break 133 | if end == 1 : break 134 | 135 | txtfile.close() 136 | -------------------------------------------------------------------------------- /python/AI-battlship_game.py: -------------------------------------------------------------------------------- 1 | import random 2 | from models import Player, Field, Ship 3 | from restrictions import CheckSurround, BorderRestriction 4 | 5 | 6 | class AI(Player): 7 | def __init__(self, turn): 8 | super(AI, self).__init__(turn) 9 | self.name = 'A.I.' 10 | 11 | def placing_ships_on_the_field(self, size): 12 | """ 13 | With this method computer places ships on the game field 14 | :param size: size of the ship 15 | """ 16 | old_field = list(self.field) 17 | upd_field = list(self.field) 18 | 19 | def place_ship(fld, cur_fld, trn): 20 | current_ship_position = set([place for place in range( 21 | len(fld)) if fld[place] == '&']) 22 | forb_places = CheckSurround(fld).forbid_placement() 23 | forb_places_upd = [place for place in forb_places 24 | if cur_fld[place] == trn] 25 | if len(forb_places_upd) == 0: 26 | for position in current_ship_position: 27 | cur_fld[position] = trn 28 | self.ships_alive.append(list(current_ship_position)) 29 | return True 30 | 31 | commands = {'w': Ship(size).move_up, 32 | 'd': Ship(size).move_right, 33 | 's': Ship(size).move_down, 34 | 'a': Ship(size).move_left, 35 | 'r': Ship(size).rotate_ship, 36 | 'p': place_ship} 37 | while True: 38 | Ship(size).place_ship(old_field, upd_field) 39 | upd_field, old_field = list(self.field), upd_field 40 | attempts = 0 41 | randoms = random.randint(1, 50) 42 | try: 43 | while attempts != randoms: 44 | commands[random.choice(('w', 'd', 's', 45 | 'a', 'r'))](old_field, upd_field) 46 | if BorderRestriction(upd_field).forbid_of_cross_border(): 47 | upd_field = list(self.field) 48 | continue 49 | upd_field, old_field = list(self.field), upd_field 50 | attempts += 1 51 | if commands['p'](old_field, self.field, self.turn): 52 | break 53 | else: 54 | continue 55 | except IndexError: 56 | upd_field = list(self.field) 57 | continue 58 | 59 | def shooting(self): 60 | """ 61 | Method marks the field: 62 | 'o' - miss 63 | 'x' - hit the target 64 | """ 65 | wounded_ships = [deck for deck in range(len( 66 | self.opponent.field)) if self.opponent.field[deck] == 'x' and 67 | self.opponent.field[deck] not in self.ships_hit] 68 | if len(wounded_ships) == 1: 69 | while True: 70 | shot = random.choice(list( 71 | AI.shooting_area(wounded_ships))) 72 | if self.opponent.field[shot] == self.opponent.turn: 73 | self.opponent.field[shot] = 'x' 74 | break 75 | elif self.opponent.field[shot] is None: 76 | self.opponent.field[shot] = 'o' 77 | break 78 | else: 79 | continue 80 | elif len(wounded_ships) > 1: 81 | if self.opponent.field[wounded_ships[-1] - 1] == 'x': 82 | while True: 83 | shot = random.choice(list( 84 | AI.horizontal_shooting_area(wounded_ships))) 85 | if self.opponent.field[shot] == self.opponent.turn: 86 | self.opponent.field[shot] = 'x' 87 | break 88 | elif self.opponent.field[shot] is None: 89 | self.opponent.field[shot] = 'o' 90 | break 91 | else: 92 | continue 93 | else: 94 | while True: 95 | shot = random.choice(list( 96 | AI.upright_shooting_area(wounded_ships))) 97 | if self.opponent.field[shot] == self.opponent.turn: 98 | self.opponent.field[shot] = 'x' 99 | break 100 | elif self.opponent.field[shot] is None: 101 | self.opponent.field[shot] = 'o' 102 | break 103 | else: 104 | continue 105 | else: 106 | available_to_shoot = random.choice([pos for pos in range( 107 | len(self.opponent.field)) if self.opponent.field[pos] != 'o']) 108 | if self.opponent.field[available_to_shoot] == self.opponent.turn: 109 | self.opponent.field[available_to_shoot] = 'x' 110 | else: 111 | self.opponent.field[available_to_shoot] = 'o' 112 | 113 | @staticmethod 114 | def shooting_area(ship_position): 115 | """ 116 | If computer hit the target this method defies the area there it will 117 | tries to hit the next target 118 | :param ship_position: current hit ship position in the list 119 | """ 120 | set_of_pos = set() 121 | for place in ship_position: 122 | if place in Field.r_upper_corner: 123 | set_of_pos.update({place - 1}, 124 | {place + Field.num_of_lines} 125 | ) 126 | elif place in Field.r_bottom_corner: 127 | set_of_pos.update({place - 1}, 128 | {place - Field.num_of_lines} 129 | ) 130 | elif place in Field.l_upper_corner: 131 | set_of_pos.update({place + 1}, 132 | {place + Field.num_of_lines} 133 | ) 134 | elif place in Field.l_bottom_corner: 135 | set_of_pos.update({place + 1}, 136 | {place - Field.num_of_lines} 137 | ) 138 | elif place in Field.right_border: 139 | set_of_pos.update({place - 1}, 140 | {place - Field.num_of_lines}, 141 | {place + Field.num_of_lines} 142 | ) 143 | elif place in Field.left_border: 144 | set_of_pos.update({place + 1}, 145 | {place - Field.num_of_lines}, 146 | {place + Field.num_of_lines} 147 | ) 148 | elif place in Field.upper_border: 149 | set_of_pos.update({place + 1}, 150 | {place - 1}, 151 | {place + Field.num_of_lines} 152 | ) 153 | elif place in Field.bottom_border: 154 | set_of_pos.update({place + 1}, 155 | {place - 1}, 156 | {place - Field.num_of_lines} 157 | ) 158 | else: 159 | set_of_pos.update({place + 1}, 160 | {place - 1}, 161 | {place - Field.num_of_lines}, 162 | {place + Field.num_of_lines} 163 | ) 164 | return set_of_pos 165 | 166 | @staticmethod 167 | def horizontal_shooting_area(ship_position): 168 | """ 169 | If computer hit the target this method defies the area there it will 170 | tries to hit the next target (horizontally) 171 | :param ship_position: current hit ship position in the list 172 | """ 173 | set_of_pos = set() 174 | for place in ship_position: 175 | if place in Field.r_upper_corner: 176 | set_of_pos.update({place - 1}) 177 | elif place in Field.r_bottom_corner: 178 | set_of_pos.update({place - 1}) 179 | elif place in Field.l_upper_corner: 180 | set_of_pos.update({place + 1}) 181 | elif place in Field.l_bottom_corner: 182 | set_of_pos.update({place + 1}) 183 | elif place in Field.right_border: 184 | set_of_pos.update({place - 1}) 185 | elif place in Field.left_border: 186 | set_of_pos.update({place + 1}) 187 | elif place in Field.upper_border: 188 | set_of_pos.update({place + 1}, 189 | {place - 1}) 190 | elif place in Field.bottom_border: 191 | set_of_pos.update({place + 1}, 192 | {place - 1}) 193 | else: 194 | set_of_pos.update({place + 1}, 195 | {place - 1}) 196 | return set_of_pos 197 | 198 | @staticmethod 199 | def upright_shooting_area(ship_position): 200 | """ 201 | If computer hit the target this method defies the area there it will 202 | tries to hit the next target (upright) 203 | :param ship_position: current hit ship position in the list 204 | """ 205 | set_of_pos = set() 206 | for place in ship_position: 207 | if place in Field.r_upper_corner: 208 | set_of_pos.update( 209 | {place + Field.num_of_lines} 210 | ) 211 | elif place in Field.r_bottom_corner: 212 | set_of_pos.update( 213 | {place - Field.num_of_lines} 214 | ) 215 | elif place in Field.l_upper_corner: 216 | set_of_pos.update( 217 | {place + Field.num_of_lines} 218 | ) 219 | elif place in Field.l_bottom_corner: 220 | set_of_pos.update( 221 | {place - Field.num_of_lines} 222 | ) 223 | elif place in Field.right_border: 224 | set_of_pos.update( 225 | {place - Field.num_of_lines}, 226 | {place + Field.num_of_lines} 227 | ) 228 | elif place in Field.left_border: 229 | set_of_pos.update( 230 | {place + Field.num_of_lines}, 231 | {place - Field.num_of_lines} 232 | ) 233 | elif place in Field.upper_border: 234 | set_of_pos.update( 235 | {place + Field.num_of_lines} 236 | ) 237 | elif place in Field.bottom_border: 238 | set_of_pos.update( 239 | {place - Field.num_of_lines} 240 | ) 241 | else: 242 | set_of_pos.update( 243 | {place - Field.num_of_lines}, 244 | {place + Field.num_of_lines} 245 | ) 246 | return set_of_pos 247 | -------------------------------------------------------------------------------- /python/PhyRe.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | """ 4 | CODENAME: PhyRe 5 | DESCRIPTION: 6 | 7 | Copyright (c) 2009 Ronald R. Ferrucci, Federico Plazzi, and Marco Passamonti.. 8 | 9 | 10 | 11 | Permission is hereby granted, free of charge, to any person 12 | obtaining a copy of this software and associated documentation 13 | files (the "Software"), to deal in the Software without 14 | restriction, including without limitation the rights to use, 15 | copy, modify, merge, publish, distribute, sublicense, and/or sell 16 | copies of the Software, and to permit persons to whom the 17 | Software is furnished to do so, subject to the following 18 | conditions: 19 | 20 | The above copyright notice and this permission notice shall be 21 | included in all copies or substantial portions of the Software. 22 | 23 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 24 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 25 | OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 26 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 27 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 28 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 29 | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 30 | OTHER DEALINGS IN THE SOFTWARE. 31 | 32 | """ 33 | 34 | import sys 35 | 36 | samplefile = sys.argv[1]; del sys.argv[1] 37 | popfile = sys.argv[1]; del sys.argv[1] 38 | #outfile= sys.argv[1]; del sys.argv[1] 39 | 40 | #outfile = samplefile 41 | #output = open(outfile, 'w') 42 | 43 | #efile = open('error.log','w') 44 | #sys.stderr = efile 45 | 46 | #output = open('output','w') 47 | #out.write(allelesfile) 48 | #out.close() 49 | ###-----------------options-------------------------### 50 | 51 | """p = permutations for confidence intervals, d1 and d2 are range for number of 52 | species for funnel plot. parameter: m = AvTD, v = VarTD, e = euler, b = AvTD and VarTd. 53 | ci = confidence intervals b = batch file. l = user-defined path lengths 54 | """ 55 | 56 | p = 1000; d1 = 10; d2 = 70; ci = 'y'; b = 'n'; l = 'n' 57 | batch = b; pathlengths = l; missing = 'n' 58 | #parameter = 'm'; 59 | 60 | from optparse import OptionParser 61 | parser = OptionParser() 62 | 63 | d1= int(sys.argv[1]); del sys.argv[1] 64 | d2= int(sys.argv[1]); del sys.argv[1] 65 | 66 | parser.add_option('-o') 67 | parser.add_option('-p',type = 'int') 68 | parser.add_option('-c') 69 | parser.add_option('-b') 70 | parser.add_option('-l') 71 | parser.add_option('-m') 72 | 73 | 74 | (options,args) = parser.parse_args() 75 | 76 | if options.m: missing = options.m 77 | else: missing = 'n' 78 | 79 | if options.o: 80 | out = options.o 81 | else: 82 | out = samplefile.split('.')[0] 83 | 84 | 85 | if options.p: p = options.p 86 | else: p = 1000 87 | 88 | if options.c: ci = options.c 89 | else: ci = 'y' 90 | 91 | if options.b: batch = options.b 92 | else: batch = 'n' 93 | 94 | if options.l: pathlengths = options.l 95 | else: pathlengths = 'n' 96 | 97 | 98 | 99 | sample = {}; population = {} 100 | 101 | 102 | 103 | output = out + '.out' 104 | 105 | 106 | 107 | o = open(output,'a') 108 | 109 | saveout = sys.stdout 110 | sys.stdout = open(output, 'w') 111 | 112 | from re import * 113 | 114 | #def Taxon(): 115 | if batch == 'y': 116 | Files = [] 117 | else: 118 | Files = [samplefile] 119 | 120 | Index = {}; Taxon = {}; coef = {}; Taxon = {}; taxon = [] 121 | 122 | pathLengths= {} 123 | 124 | for i in open(samplefile): 125 | """ 126 | if match('Taxon:', i): 127 | x = i.split() 128 | x.remove('Taxon:') 129 | #x = [string.lower() for string in x] 130 | 131 | for i in x: 132 | taxon.append(i) 133 | j = x.index(i) 134 | Index[i] = j + 1 135 | continue 136 | 137 | elif match('Coefficients:', i): 138 | x = i.split() 139 | x.remove('Coefficients:') 140 | x = map(eval, x) 141 | 142 | for t in taxon: 143 | i = taxon.index(t) 144 | coef[t] = sum(x[i:]) 145 | pathLengths[t] = x[i] 146 | 147 | continue 148 | """ 149 | 150 | if batch == 'y': 151 | j = i.strip() 152 | Files.append(j) 153 | else: 154 | break 155 | 156 | duplicates = [] 157 | 158 | for i in open(popfile): 159 | if match('Taxon:', i): 160 | x = i.split() 161 | x.remove('Taxon:') 162 | #x = [string.lower() for string in x] 163 | 164 | for i in x: 165 | taxon.append(i) 166 | j = x.index(i) 167 | Index[i] = j + 1 168 | continue 169 | 170 | elif match('Coefficients:', i): 171 | x = i.split() 172 | x.remove('Coefficients:') 173 | x = map(eval, x) 174 | 175 | for t in taxon: 176 | i = taxon.index(t) 177 | coef[t] = sum(x[i:]) 178 | pathLengths[t] = x[i] 179 | 180 | continue 181 | 182 | i.strip() 183 | x = i.split() 184 | 185 | #if match('Taxon:', i): continue 186 | #if match('Coefficients:', i): continue 187 | 188 | species = x[0]; population[species] = {} 189 | 190 | if species in sample.keys(): 191 | duplicates.append(species) 192 | else: 193 | sample[species] = {} 194 | population[species] = {} 195 | 196 | 197 | if missing == 'y': 198 | mtax = '' 199 | for t in taxon: 200 | if x[Index[t]] == '/': 201 | #sample[species][t] = sample[species][t] 202 | sample[species][t] = mtax 203 | else: 204 | sample[species][t] = x[Index[t]] 205 | mtax = x[Index[t]] 206 | 207 | population[species][t] = sample[species][t] 208 | 209 | else: 210 | for t in taxon: 211 | #y = Taxon[t] 212 | sample[species][t] = x[Index[t]] 213 | population[species][t] = sample[species][t] 214 | 215 | #for t in taxon: 216 | #y = Taxon[t] 217 | # population[species][t] = x[Index[t]] 218 | 219 | 220 | if len(duplicates) > 0: 221 | print "Population master list contains duplicates:" 222 | for i in duplicates: print i,'\n' 223 | 224 | def PathLength(population): 225 | taxonN = {} 226 | 227 | X = {} 228 | for t in taxon: 229 | Taxon[t] = {} 230 | X[t] = [population[i][t] for i in sample] 231 | 232 | if taxon.index(t) == 0: 233 | for i in set(X[t]): 234 | Taxon[t][i] = X[t].count(i) 235 | else: 236 | for i in set(X[t]): 237 | if i not in X[taxon[taxon.index(t)-1]]: 238 | Taxon[t][i] = X[t].count(i) 239 | 240 | taxonN[t] = len(Taxon[t]) 241 | 242 | n = [float(len(Taxon[t])) for t in taxon] 243 | 244 | n.insert(0,1.0) 245 | 246 | #s = 100/float(N) 247 | raw = [] 248 | for i in range((len(n)-1)): 249 | j = i + 1 250 | 251 | if n[i] > n[j]: 252 | c = 1 253 | else: 254 | c = (1 - n[i]/n[j]) 255 | 256 | raw.append(c) 257 | 258 | s = sum(raw) 259 | adjco = [i*100/s for i in raw] 260 | 261 | coef = {}; pathLengths = {} 262 | for i in range(len(taxon)): 263 | t = taxon[i] 264 | coef[t] = sum(adjco[i:]) 265 | pathLengths[t] = adjco[i] 266 | 267 | return coef, taxonN, pathLengths 268 | 269 | if pathlengths == 'n': 270 | coef, popN, pathLengths = PathLength(population) 271 | if pathlengths == 'y': 272 | XXX, popN, YYY = PathLength(population) 273 | del XXX, YYY 274 | 275 | #N = len(sample.keys()) 276 | def ATDmean(data,sample): 277 | #[sample = data.keys() 278 | N = len(sample) 279 | 280 | Taxon = {}; taxonN = {}; AvTD = 0; n = 0 281 | #Taxon are counts of taxa at each level, taxonN are numbers of pairwise differences 282 | #at each level, with n being the accumlation of pairwise differences at that level. the difference 283 | #between n and TaxonN is the number of species that are in different taxa in that level 284 | #but not in upper levels 285 | 286 | for t in taxon: 287 | Taxon[t] = {} 288 | x = [data[i][t] for i in sample] 289 | for i in set(x): 290 | Taxon[t][i] = x.count(i) 291 | 292 | for t in taxon: 293 | taxonN[t] = sum([Taxon[t][i] * Taxon[t][j] for i in Taxon[t] for j in Taxon[t] if i != j]) 294 | n = taxonN[t] - n 295 | AvTD = AvTD + (n * coef[t]) 296 | n = taxonN[t] 297 | 298 | #print sample 299 | AvTD /= (N * (N - 1)) 300 | 301 | return AvTD,taxonN, Taxon 302 | 303 | def ATDvariance(taxonN, sample, atd): 304 | vtd = [] 305 | 306 | #N = sum(taxon) 307 | 308 | vtd = 0; N = 0; n = 0 309 | 310 | for t in taxon: 311 | n = taxonN[t] - n 312 | vtd = vtd + n * coef[t]**2 313 | n = taxonN[t] 314 | 315 | N = len(sample) 316 | n = N * (N - 1) 317 | 318 | vtd = (vtd - ((atd*n)**2)/n)/n 319 | 320 | #vtd = (sum([tax1,tax2,tax3,tax4]) - (((atd * n)**2)/n))/n 321 | 322 | return vtd 323 | 324 | def euler(data, atd, TaxonN): 325 | sample = data.keys() 326 | 327 | n = len(sample) 328 | TDmin = 0 329 | N = 0 330 | for t in taxon: 331 | k = len(Taxon[t]) 332 | TDmin += coef[t] * (((k-1)*(n-k +1)* 2+ (k-1)*(k-2))-N) 333 | N += ((k-1)*(n-k +1)* 2 + (k-1)*(k-2))-N 334 | 335 | TDmin /= (n * (n-1)) 336 | 337 | #Taxon = {} 338 | 339 | #tax = [] 340 | 341 | #taxon.append('sample') 342 | #Taxon['sample'] = sample 343 | taxon.reverse() 344 | TaxMax = {} 345 | 346 | taxonN = {} 347 | import random 348 | for t in taxon: 349 | TaxMax[t] = [] 350 | if taxon.index(t) == 0: 351 | TaxMax[t] = [] 352 | for i in range(len(Taxon[t])): 353 | TaxMax[t].append([]) 354 | for i in range(len(Taxon[t])): 355 | TaxMax[t][i] = [sample[j] for j in range(i,n,len(Taxon[t]))] 356 | else: 357 | TaxMax[t] = [] 358 | for i in range(len(Taxon[t])): 359 | TaxMax[t].append([]) 360 | s = taxon[taxon.index(t)-1] 361 | 362 | Tax = [TaxMax[s][j] for j in range(i,len(Taxon[s]),len(Taxon[t]))] 363 | 364 | for j in Tax: 365 | TaxMax[t][i] += j 366 | TaxMax[t].reverse() 367 | 368 | taxon.reverse(); TDmax = 0; n = 0; N = len(sample) 369 | for t in taxon: 370 | taxonN[t] = sum([len(TaxMax[t][i]) * len(TaxMax[t][j]) for i in range(len(TaxMax[t])) for j in range(len(TaxMax[t])) if i != j]) 371 | n = taxonN[t] - n 372 | TDmax += n * coef[t] 373 | n = taxonN[t] 374 | #for i in TaxMax[t]: 375 | # print t, len(i) 376 | 377 | TDmax /= (N * (N-1)) 378 | 379 | EI = (TDmax-atd)/(TDmax-TDmin) 380 | 381 | Eresults = {'EI':EI, 'TDmin':TDmin,'TDmax':TDmax} 382 | return Eresults 383 | #print TDmax 384 | 385 | print "Output from Average Taxonomic Distinctness\n" 386 | def Sample(samplefile): 387 | sample = {} 388 | print samplefile 389 | for i in open(samplefile): 390 | if match('Taxon:', i): continue 391 | elif match('Coefficients:', i): continue 392 | 393 | x = i.split() 394 | 395 | species = x[0] 396 | #sample[species] = {} 397 | 398 | sample[species] = population[species] 399 | 400 | return sample 401 | 402 | 403 | results = {} 404 | 405 | for f in Files: 406 | sample = Sample(f) 407 | f = f.split('.') 408 | f = f[0] 409 | 410 | results[f] = {} 411 | 412 | samp = sample.keys() 413 | 414 | atd,taxonN, Taxon = ATDmean(sample,samp) 415 | vtd = ATDvariance(taxonN,samp,atd) 416 | Eresults = euler(sample,atd, taxonN) 417 | 418 | results[f]['atd'] = atd 419 | results[f]['vtd'] = vtd 420 | results[f]['euler'] = Eresults 421 | results[f]['N'] = taxonN 422 | results[f]['n'] = len(sample) 423 | results[f]['taxon'] = Taxon 424 | 425 | N = len(sample.keys()) 426 | 427 | def printResults(): 428 | #if parameter == 'm': 429 | #if parameter == 'm': 430 | # print "parameter is Average Taxonomic Distinctness\n" 431 | #elif parameter == 'v': 432 | # print "parameter is Variation in Taxonomic Distinctness\n" 433 | #elif parameter == 'e': 434 | # print "parameter is Euler's Index of Imbalance\n" 435 | 436 | print "Number of taxa and path lengths for each taxonomic level:" 437 | 438 | for t in taxon: 439 | print '%-10s\t%d\t%.4f' %(t,popN[t],pathLengths[t]) 440 | n = taxonN[t] 441 | 442 | print "\n", 443 | 444 | for f in results: 445 | print "---------------------------------------------------" 446 | print "Results for sample: ", f,'\n' 447 | print "Dimension for this sample is", results[f]['n'], '\n\n', 448 | print "Number of taxa and pairwise comparisons at each taxon level:" 449 | 450 | n = 0 451 | for t in taxon: 452 | 453 | N = results[f]['N'][t] - n 454 | print '%-10s\t%i\t%i' %(t,len(results[f]['taxon'][t]),N) 455 | n = results[f]['N'][t] 456 | 457 | print """\nNumber of pairwise comparisons is for pairs that differ \ 458 | at each level excluding comparisons that differ at upper levels""" 459 | print "\n", 460 | 461 | print "Average taxonomic distinctness = %.4f" % results[f]['atd'] 462 | print "Variation in taxonomic distinctness = %.4f" % results[f]['vtd'] 463 | print "Minimum taxonomic distinctness = %.4f" % results[f]['euler']['TDmin'] 464 | print "Maximum taxonomic distinctness = %.4f" % results[f]['euler']['TDmax'] 465 | print "von Euler's index of imbalance = %.4f" % results[f]['euler']['EI'] 466 | print '\n', 467 | 468 | 469 | printResults() 470 | print "---------------------------------------------------" 471 | 472 | #sys.stdout = saveout 473 | 474 | #sys.stdout=sys.__stdout__ 475 | 476 | 477 | sys.stdout = saveout 478 | 479 | sys.stdout=sys.__stdout__ 480 | 481 | if ci == 'y': 482 | 483 | output = out.split('_')[0] + '_funnel.out' 484 | 485 | o = open(output,'a') 486 | 487 | saveout = sys.stdout 488 | sys.stdout = open(output, 'w') 489 | print """Confidence limits for average taxonomic distinctness and variation in taxonomic distinctness 490 | limits are lower 95% limit for AvTD and upper 95% limit for VarTD 491 | """ 492 | print "Number of permutations for confidence limits =", p, '\n' 493 | 494 | #if paramter == 'm': 495 | # print "Confidence limits for Average Taxonomic Distinctiveness are in file ", output 496 | #if paramter == 'v': 497 | # print "Confidence limits for Variation in Taxonomic Distinctiveness are in file ", output 498 | 499 | 500 | #o = open('sample2.txt','w') 501 | 502 | #saveout = sys.stdout 503 | #sys.stdout = open(output, 'w') 504 | 505 | ciarray = []; x = [];carray = [] 506 | def Funnel(p,d1,d2): 507 | from random import sample 508 | pop = population.keys() 509 | 510 | dims = []; up = []; lo = []; means = [] 511 | 512 | print "dimension AvTD05% AvTDmean AvTD95% AvTDup VarTDlow VarTD05% VarTDmean VarTD95%" 513 | for d in range(d1, d2 + 1): 514 | #for i in range(10): 515 | #d = N 516 | #if d != N: continue 517 | #from math import max, min 518 | x.append(d) 519 | AvTDci = []; VarTDci = [] 520 | for j in range(p): 521 | rsamp = sample(pop,d) 522 | 523 | atd,taxonN, Taxon = ATDmean(population,rsamp); AvTDci.append(atd) 524 | vtd = ATDvariance(taxonN,rsamp,atd); VarTDci.append(vtd) 525 | 526 | AvTDci.sort() 527 | VarTDci.sort() 528 | 529 | AvTD = AvTDci[int(.05 * p)], sum(AvTDci)/p, AvTDci[int(.95 * p)], max(AvTDci) 530 | VarTD = min(VarTDci), VarTDci[int(.05 * p)],sum(VarTDci)/p,VarTDci[int(.95 * p)] 531 | 532 | dims.append(d) 533 | ciarray.append(AvTD[0]) 534 | carray.append(AvTD[1]) 535 | 536 | #up.append(ci95[1]) 537 | #lo.append(ci95[0]) 538 | #means.append(mean) 539 | print '%i %6.4f %6.4f %6.4f %6.4f %6.4f %6.4f %6.4f %6.4f' \ 540 | %(d, AvTD[0], AvTD[1], AvTD[2], AvTD[3], VarTD[0], VarTD[1], VarTD[2], VarTD[3]) 541 | 542 | #if d == N: 543 | # Ie = (max(cache)-atd)/(max(cache)-min(cache)) 544 | # print d, Ie, ci95, mean 545 | 546 | #return dims, up, lo, means 547 | #print d,ci95 548 | 549 | Funnel(p,d1,d2) 550 | #dims, up, lo, means = Funnel(p,d1,d2) 551 | 552 | sys.stdout = saveout 553 | 554 | sys.stdout=sys.__stdout__ 555 | 556 | #from QUASImage import *; from numpy import * 557 | #ciarray = array(ciarray) 558 | #from pgen import * 559 | 560 | #ciarray += carray 561 | 562 | #x *= 1 563 | #charplot(x,ciarray) 564 | 565 | #plot(ciarray) 566 | """ 567 | from matplotlib.pylab import * 568 | 569 | if parameter == 'm': 570 | param = 'Average Taxonomic Distinctiveness' 571 | elif parameter == 'v': 572 | param = 'Variation in Taxnomic Distinctiveness' 573 | elif parameter == 'e': 574 | param = 'Imbalance' 575 | 576 | #N = len(sample) 577 | #print N, atd 578 | #figure(1) 579 | plot(dims,up,dims, lo, dims, means) 580 | title('ATD',fontstyle='italic') 581 | xlabel('Number of Species') 582 | ylabel(param,fontstyle='italic') 583 | #savefig(figureOutput+".png") 584 | 585 | show() 586 | 587 | #sys.stdout = saveout 588 | 589 | #sys.stdout=sys.__stdout__ 590 | """ 591 | 592 | -------------------------------------------------------------------------------- /python/player.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | ####################################################### 4 | # Python Music Player 5 | # By Benjamin Urquhart 6 | # VERSION: 2.4.3 7 | 8 | This player is designed to play music on a Raspberry Pi, 9 | but can be used on Windows and OSX. 10 | OSX support is limited. 11 | 12 | Don't expect good documentation for a little while. 13 | ####################################################### 14 | """ 15 | version = '2.4' 16 | revision = '3' 17 | ###################################################### 18 | import datetime 19 | import urllib 20 | import urllib2 21 | import os 22 | import sys 23 | import string 24 | import tarfile 25 | from threading import Thread as Process 26 | #from multiprocessing import Process 27 | from time import sleep 28 | from random import randint 29 | try: 30 | import traceback 31 | import requests 32 | except ImportError: 33 | pass 34 | ##################################################### 35 | #connUser = False 36 | threadUse = False 37 | stop = False 38 | skip = False 39 | pause = False 40 | play = False 41 | debug = False 42 | option = "n" 43 | select = 0 44 | current = "" 45 | amount = 0 46 | played = [] 47 | playlist = [] 48 | check = "" 49 | width = 800 50 | height = 600 51 | console = False 52 | text = '' 53 | songNum = 1 54 | kill = False 55 | ###################################################### 56 | # ############ 57 | print "Starting Python Music Player " + version + "." + revision # 58 | # ############ 59 | ###################################################### 60 | def mkdir(directory): 61 | if not os.path.exists(directory): 62 | os.makedirs(directory) 63 | ###################################################### 64 | def touch(path): 65 | with open(path, 'a'): 66 | os.utime(path, None) 67 | ###################################################### 68 | # The shutdown process 69 | def shutdown(): 70 | try: 71 | bcast("\n") 72 | bcast("Stopping...") 73 | pygame.mixer.music.stop() 74 | """ 75 | try: 76 | conn.close() 77 | s.close() 78 | except: 79 | LogErr() 80 | pass 81 | """ 82 | log("Shutdown success") 83 | log_file.close() 84 | pygame.quit() 85 | quit() 86 | except: 87 | log("An error occoured") 88 | LogErr() 89 | log_file.close() 90 | pygame.quit() 91 | quit() 92 | ###################################################### 93 | # Custom logging function 94 | def log(string): 95 | try: 96 | if debug: 97 | print "[Debug]: " + string 98 | log_file.write("[Logger]: ") 99 | log_file.write(string) 100 | log_file.write("\n") 101 | except: 102 | pass 103 | ###################################################### 104 | def LogErr(): 105 | try: 106 | exc_type, exc_value, exc_traceback = sys.exc_info() 107 | lines = traceback.format_exception(exc_type, exc_value, exc_traceback) 108 | log('') 109 | log(''.join(line for line in lines)) 110 | if debug: 111 | bcast("[Error]: " + ''.join(line for line in lines), True) 112 | except: 113 | pass 114 | ###################################################### 115 | def bcast(string, err=False): 116 | try: 117 | if err: 118 | print string 119 | else: 120 | print "[Player]: " + string 121 | #conn.send(string) 122 | text = string 123 | #display(string, background, screen) 124 | except: 125 | pass 126 | ###################################################### 127 | def updater(): 128 | log('Update requested; attempting...') 129 | if update == 0: 130 | bcast('No update found.') 131 | log('No update found') 132 | else: 133 | bcast('Attempting to retrive tarball...') 134 | try: 135 | log('Connecting to ' + url +'...') 136 | try: 137 | r = requests.get('http://' + url) 138 | status = r.status_code 139 | except: 140 | status = 200 141 | LogErr() 142 | if status == int(200): 143 | try: 144 | filename = urllib.urlretrieve('http://' + url + '/python/downloads/player/music-player-' + str(ver) + '.tar.gz', 'music-player-' + str(ver) + '.tar.gz') 145 | except: 146 | LogErr() 147 | raise IOError 148 | bcast('Installing...') 149 | log('Download success') 150 | log('Will now attempt to install update') 151 | try: 152 | mkdir('update') 153 | os.rename("music-player-" + str(ver) + ".tar.gz", 'update/update.tar.gz') 154 | os.chdir('update') 155 | tar = tarfile.open("update.tar.gz") 156 | tar.extractall() 157 | tar.close() 158 | os.remove('update.tar.gz') 159 | os.chdir('..') 160 | log('Success!') 161 | bcast('Done!') 162 | bcast("Move 'player.py' from the folder 'update' to: " + os.path.dirname(os.getcwd())) 163 | except: 164 | LogErr() 165 | bcast('Installation failed') 166 | else: 167 | bcast('Server is down') 168 | raise IOError 169 | except: 170 | LogErr() 171 | bcast('Download failed') 172 | ###################################################### 173 | 174 | # To control the player remotely (non-functional) 175 | 176 | def server(): 177 | try: 178 | import socket 179 | HOST = socket.gethostname() 180 | PORT = 9000 181 | try: 182 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 183 | s.bind((HOST, PORT)) 184 | except socket.error as msg: 185 | print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] 186 | LogErr() 187 | try: 188 | s.close() 189 | except: 190 | LogErr() 191 | pass 192 | s.listen(2) 193 | print 'Started control server on ' + HOST + ':' + str(PORT) 194 | except: 195 | print "Couldn't create control server" 196 | LogErr() 197 | ###################################################### 198 | # Get news updates 199 | def news(): 200 | log("Getting news") 201 | try: 202 | news = urllib2.urlopen("http://" + url + "/news.txt") 203 | news = news.read() 204 | if news == '': 205 | bcast("No News") 206 | log("No News") 207 | else: 208 | bcast(news) 209 | log(news) 210 | except: 211 | LogErr() 212 | bcast("Couldn't get news updates", True) 213 | ###################################################### 214 | def control(): 215 | threadUse = True 216 | option = '' 217 | option = raw_input('> ') 218 | try: 219 | option = option.replace("\n", '') 220 | option = option.lower() 221 | if option == 'quit' or option == 'stop': 222 | print "Use Control-C to quit" 223 | #stop = True 224 | #shutdown() 225 | elif option == 'skip': 226 | #skip = True 227 | pygame.mixer.music.stop() 228 | elif option == 'update': 229 | #update = True 230 | updater() 231 | # Play/Pause indev 232 | elif option == 'pause': 233 | #pause = True 234 | pygame.mixer.music.pause() 235 | bcast('Paused') 236 | elif option == 'play': 237 | #play = True 238 | pygame.mixer.music.play() 239 | elif option == '': 240 | option = '' 241 | elif option == 'debug': 242 | if debug == True: 243 | print "Debug mode disabled" 244 | debug = False 245 | elif debug == False: 246 | print "Debug mode enabled" 247 | debug = True 248 | elif option == "news": 249 | news() 250 | else: 251 | bcast("Invalid command: " + option) 252 | except: 253 | LogErr() 254 | sleep(0.1) 255 | threadUse = False 256 | ################################################### 257 | def control2(): 258 | try: 259 | for event in pygame.event.get(): 260 | if event.type == pygame.KEYDOWN: 261 | if event == pygame.K_d: 262 | print "Debug" 263 | if debug: 264 | debug = False 265 | else: 266 | debug = True 267 | if event.key == pygame.K_SPACE or event.key == pygame.K_F11: 268 | bcast("Pause") 269 | if pause == True: 270 | pygame.mixer.music.play() 271 | pause = False 272 | elif pause == False: 273 | pygame.mixer.music.pause() 274 | pause = True 275 | if event.key == pygame.K_u: 276 | bcast("Update") 277 | updater() 278 | if event.key == pygame.K_F12: 279 | bcast("Skip") 280 | pygame.mixer.music.stop() 281 | if event.key == pygame.K_F10 or event.key == pygame.K_q: 282 | bcast("Quit") 283 | shutdown() 284 | except: 285 | LogErr() 286 | sleep(0.2) 287 | ###################################################### 288 | mkdir('logs') 289 | time = datetime.datetime.now() 290 | try: 291 | log_file = open("./logs/" + str(time), "w+") 292 | except: 293 | LogErr() 294 | bcast("Failed to create log") 295 | ###################################################### 296 | """ 297 | def text_objects(text, font): 298 | textSurface = font.render(text, True, black) 299 | return textSurface, textSurface.get_rect() 300 | ###################################################### 301 | def display(text): 302 | screen.fill((225, 225, 225)) 303 | largeText = pygame.font.Font('freesansbold.ttf',115) 304 | TextSurf, TextRect = text_objects(text, largeText) 305 | TextRect.center = ((width/2),(height/2)) 306 | screen.blit(TextSurf, TextRect) 307 | pygame.display.update() 308 | pygame.display.flip() 309 | """ 310 | def display(text, background, screen): 311 | font = pygame.font.Font("freesansbold", 36) 312 | out = font.render(text, 1, (10, 10, 10)) 313 | textpos = out.get_rect() 314 | textpos.centerx = background.get_rect().centerx 315 | background.blit(out, textpos) 316 | # Blit everything to the screen 317 | screen.blit(background, (0, 0)) 318 | pygame.display.flip() 319 | ###################################################### 320 | #server() 321 | ###################################################### 322 | # Looking for pygame... 323 | try: 324 | import pygame 325 | from pygame.locals import * 326 | #import Screen 327 | except ImportError: 328 | LogErr() 329 | try: 330 | print "Downloading assets" 331 | log('Pygame missing; getting installer') 332 | osv = sys.platform 333 | if osv == 'win32': 334 | urllib.urlretrieve('https://pygame.org/ftp/pygame-1.9.1.win32-py2.7.msi', 'pygame-1.9.1.msi') 335 | elif osv == 'darwin': 336 | urllib.urlretrieve('https://pygame.org/ftp/pygame-1.9.1release-python.org-32bit-py2.7-macosx10.3.dmg', 'pygame-mac.dmg') 337 | log('Success!') 338 | elif osv == 'linux2' or 'cygwin': 339 | print 'You are using linux or cygwin' 340 | print "Use the command 'sudo pip install pygame' to download\nthe nessasary modules" 341 | log(osv + ' detected; pip installer recommended') 342 | else: 343 | print 'Unrecognized os: ' + osv 344 | try: 345 | urllib.urlretrieve('http://' + url + '/pygame.tar.gz', 'pygame.tar.gz') 346 | tar = tarfile.open("pygame.tar.gz") 347 | tar.extractall() 348 | tar.close() 349 | os.remove('pygame.tar.gz') 350 | except: 351 | LogErr() 352 | print "Failed to get assets" 353 | exit() 354 | print 'Please run the installer that has been dropped into the ' + os.path.dirname(os.getcwd()) + ' folder' 355 | except: 356 | print 'Failed to get assets' 357 | print "Please install the 'pygame' module manually at pygame.org" 358 | LogErr() 359 | shutdown() 360 | exit() 361 | ####################################################### 362 | # Load pygame module 363 | try: 364 | pygame.init() 365 | pygame.mixer.init() 366 | #pygame.font.init() 367 | log('Pygame initialized') 368 | except: 369 | bcast("Couldn't run pygame.init()", True) 370 | log("pygame.init() failed") 371 | LogErr() 372 | ####################################################### 373 | try: 374 | if len(sys.argv) > 1: 375 | i = 1 376 | while i < len(sys.argv): 377 | arg = sys.argv[i] 378 | if arg == "--console" or arg == "-c": 379 | console = True 380 | elif arg == "--verbose" or arg == "-v": 381 | debug = True 382 | elif arg == "-f" or arg == "--file": 383 | pygame.init() 384 | try: 385 | pygame.mixer.music.load(sys.argv[i+1]) 386 | print "Now Playing: " + sys.argv[i+1] 387 | pygame.mixer.music.play() 388 | while pygame.mixer.music.get_busy(): 389 | continue 390 | kill = True 391 | except: 392 | LogErr() 393 | print "There was an error playing the file" 394 | kill = True 395 | elif arg == "-h" or arg == "--help": 396 | print 'Plays music in the "Music" folder within the current directory\n' 397 | print "Usage: " + sys.argv[0] + " [-hvc] [-f ]" 398 | print "Options: " 399 | print "\t -h, --help\t Displays this help text" 400 | print "\t -v, --verbose\t Displays extra information" 401 | print "\t -c, --console\t Disables Pygame screen (text-only mode)" 402 | print "\t -f, --file\t Plays the file at the filepath specified" 403 | print "\nExamples: \n\t " + sys.argv[0] + " -v -c -f /sample/file/path/foo.bar" 404 | print "\t " + sys.argv[0] + " -f foo.bar" 405 | kill = True 406 | i = i + 1 407 | except: 408 | pass 409 | if kill: 410 | exit() 411 | ###################################################### 412 | # Checking for updates... 413 | url = "benjaminurquhart.me" # This wasn't the original URL - replaced for privacy 414 | update = 0 415 | try: 416 | log('Checking for updates...') 417 | log('Getting info from ' + url) 418 | ver = urllib2.urlopen('http://' + url + '/version.txt') 419 | rev = urllib2.urlopen('http://' + url + '/rev.txt') 420 | ver = ver.read() 421 | rev = rev.read() 422 | if float(ver) > float(version): 423 | log('Update found!') 424 | bcast("Python Music Player " + ver + " is availible") 425 | bcast("Type update at the prompt to download") 426 | update = 1 427 | elif float(ver) < float(version): 428 | log('Indev vesion in use') 429 | bcast('Indev version in use') 430 | elif int(rev) > int(revision) and float(ver) == float(version): 431 | log('New revision found!') 432 | bcast('Revision ' + str(rev) + ' is availible') 433 | bcast('Type update at the prompt to download') 434 | update = 1 435 | elif float(ver) == float(version): 436 | log('No update found') 437 | bcast('No update found') 438 | except: 439 | bcast('Failed to check for updates', True) 440 | LogErr() 441 | log('Update check failed') 442 | ###################################################### 443 | mkdir('Music') 444 | log("Player starting...") 445 | news() 446 | ###################################################### 447 | try: 448 | if console == False: 449 | screen = pygame.display.set_mode((1000, 200)) 450 | pygame.display.set_caption("Music Player") 451 | background = pygame.Surface(screen.get_size()) 452 | background = background.convert() 453 | background.fill((250, 250, 250)) 454 | except: 455 | bcast("Display error, console mode active", True) 456 | log("Display error") 457 | LogErr() 458 | console = True 459 | log("Player started") 460 | # Check the Music folder for tracks 461 | sound_data = os.listdir('./Music') 462 | try: 463 | for i in sound_data: 464 | playlist.append(i) 465 | i = 0 466 | amount = len(playlist) 467 | log(str(amount) + " Songs found") 468 | if amount == 0: 469 | bcast('No music found!') 470 | shutdown() 471 | bcast("Number of songs: " + str(amount)) 472 | ####################################################### 473 | # Play the music 474 | while i != amount: 475 | select = randint(0, amount - 1) 476 | if option.lower() == "y": 477 | for i in song: 478 | current = i 479 | option = "n" 480 | else: 481 | current = playlist[select] 482 | #current = current.replace("\n", "") 483 | if current not in played: 484 | # Try to load the track 485 | bcast("Now Playing: " + current + " (" + str(songNum) + " out of " + str(amount) + ")") 486 | log("Song " + str(songNum) + " out of " + str(amount)) 487 | try: 488 | log("Loading '" + current + "'") 489 | pygame.mixer.music.load("./Music/" + current) 490 | log('Now Playing: ' + current) 491 | except: 492 | bcast("Couldn't play " + current) 493 | ####################################################### 494 | # Play loaded track 495 | pygame.mixer.music.play() 496 | # Take user input for controlling player 497 | while pygame.mixer.music.get_busy(): 498 | if console == False: 499 | #font = pygame.font.Font(None, 36) 500 | #out = font.render(text, 1, (10, 10, 10)) 501 | #textpos = out.get_rect() 502 | ##textpos.centerx = background.get_rect().centerx 503 | screen.blit(background, (0, 0)) 504 | #pygame.display.flip() 505 | control2() 506 | else: 507 | t = Process(None, control()) 508 | t.daemon = False 509 | t.start() 510 | ####################################################### 511 | if not current in played: 512 | played.append(current) 513 | i = i + 1 514 | sleep(0.2) 515 | songNum = songNum + 1 516 | bcast("All songs have been played!") 517 | log('All songs have been played') 518 | shutdown() 519 | ####################################################### 520 | except: 521 | LogErr() 522 | shutdown() 523 | -------------------------------------------------------------------------------- /django/views.py: -------------------------------------------------------------------------------- 1 | @login_required 2 | @transaction.commit_on_success 3 | def create_w(request, id): 4 | if Register.objects.filter(id=id).exists() and Register.objects.get(id=id).sender == request.sender: 5 | return create_response([id], user_friendly=True) 6 | else: 7 | return HttpResponseRedirect("/") 8 | 9 | 10 | def map_reduce_task(request, ids): 11 | registers = get_registers(request) 12 | ids = get_ids(ids) 13 | if not registers: 14 | return HttpResponseRedirect("/") 15 | else: 16 | for register in registers: 17 | if ids: # Using optimized queries: 18 | objects = register.objects.filter(id__in=ids).values_list("id", flat=True) 19 | else: 20 | objects = register.objects.all().values_list("id", flat=True) 21 | 22 | t = 0 23 | task_map = [] 24 | 25 | def chunks(objects, length): # Defining method with a generator in a loop. 26 | for i in xrange(0, len(objects), length): 27 | yield objects[i:i+length] 28 | 29 | for chunk in chunks(objects, 20): 30 | countdown = 5*t 31 | t += 1 32 | tasks_map.append(request_by_mapper(register, chunk, countdown, datetime.now())) 33 | g = group(*tasks_map) 34 | reduce_task = chain(g, create_request_by_reduce_async.s(tasks_map))() 35 | 36 | 37 | @login_required 38 | def create_payment(request): 39 | # currency=BTC&version=1&cmd=get_callback_address&key=your_api_public_key&format=json 40 | public_key = os.environ.get('PUBLIC_KEY') 41 | private_key = os.environ.get('PRIVATE_KEY') 42 | # get payment info 43 | if request.method == "POST": 44 | policy_id = request.POST.get('policy_id', '') 45 | currency = request.POST.get('currency') 46 | logger.debug(currency) 47 | policy = InsurancePolicy.objects.get(id=policy_id) 48 | try: 49 | payment = policy.payment_id 50 | # if payment is NULL then exeption 51 | payment.id 52 | except Exception as e: 53 | # everything is ok, new user 54 | # create payment with coinpayment 55 | post_params = { 56 | 'amount': policy.fee, 57 | 'currency1': 'BTC', 58 | 'currency2': currency, 59 | 'buyer_email': 60 | request.user.email, # TODO set request.user.mail, 61 | 'item_name': 'Policy for ' + policy.exchange.name, 62 | 'item_number': policy.id 63 | } 64 | try: 65 | client = CryptoPayments(public_key, private_key) 66 | transaction = client.createTransaction(post_params) 67 | logger.debug(transaction) # FOR DEBUG 68 | if len(transaction) == 0: 69 | raise Exception 70 | except Exception as e: 71 | logger.error(e) 72 | message = 'Payment gateway is down' 73 | responseData = {'error': True, 'message': message} 74 | return JsonResponse(responseData) 75 | 76 | try: 77 | try: 78 | payment = UserPayments( 79 | status=0, 80 | update_date=datetime.datetime.now(), 81 | amount=transaction.amount, 82 | address=transaction.address, 83 | payment=transaction.txn_id, 84 | confirms_needed=transaction.confirms_needed, 85 | timeout=transaction.timeout, 86 | status_url=transaction.status_url, 87 | qrcode_url=transaction.qrcode_url, 88 | currency=currency) 89 | 90 | try: 91 | default_email = os.environ.get('DJANGO_EMAIL_DEFAULT_EMAIL') 92 | subject = "Website: You’re one step away from being secured" 93 | message = render_to_string('first_email.html', {'user': policy.user, 'payment': payment}) 94 | send_mail(subject, message, default_email, [policy.user.email]) 95 | except Exception as e: 96 | logger.error('Error on sending first email: ', e) 97 | 98 | except Exception as e: 99 | logger.error(e) 100 | responseData = { 101 | 'error': True, 102 | 'message': 'Payment Gateway Error' 103 | } 104 | return JsonResponse(responseData) 105 | else: 106 | payment.save() 107 | policy.payment_id = payment 108 | policy.save() 109 | 110 | except Exception as e: 111 | message = "Error contacting with the Gateway" 112 | response = JsonResponse({ 113 | 'status': 'false', 114 | 'message': message 115 | }) 116 | response.status_code = 418 117 | logger.error(e) 118 | return response 119 | else: 120 | post_params = { 121 | "payment_amount": 122 | decimal.Decimal(transaction.amount).quantize( 123 | decimal.Decimal('0.00000001'), 124 | rounding=decimal.ROUND_DOWN).normalize(), 125 | "payment_address": 126 | transaction.address, 127 | "payment_qr": 128 | transaction.qrcode_url, 129 | "gateway_status": 130 | transaction.status_url, 131 | "policy_cover": 132 | policy.cover, 133 | "exchange_name": 134 | policy.exchange.name, 135 | "date_of_formating": 136 | policy.request_date.date(), 137 | "currency": 138 | currency 139 | } 140 | 141 | response = JsonResponse(post_params) 142 | return response 143 | else: 144 | # payment already exist 145 | if payment.status == PaymentStatus.ERROR: 146 | logger.info('status Error, should create new') 147 | post_params = { 148 | 'amount': policy.fee, 149 | 'currency1': 'BTC', 150 | 'currency2': currency, 151 | 'buyer_email': 152 | request.user.email, # TODO set request.user.mail, 153 | 'item_name': 'Policy for ' + policy.exchange.name, 154 | 'item_number': policy.id 155 | } 156 | 157 | try: 158 | client = CryptoPayments(public_key, private_key) 159 | transaction = client.createTransaction(post_params) 160 | except Exception as e: 161 | logger.error(e) 162 | message = 'Payment gateway is down' 163 | responseData = {'error': True, 'message': message} 164 | return JsonResponse(responseData) 165 | 166 | try: 167 | payment = UserPayments( 168 | status=0, 169 | update_date=datetime.datetime.now(), 170 | amount=transaction.amount, 171 | address=transaction.address, 172 | payment=transaction.txn_id, 173 | confirms_needed=transaction.confirms_needed, 174 | timeout=transaction.timeout, 175 | status_url=transaction.status_url, 176 | qrcode_url=transaction.qrcode_url, 177 | currency=currency) 178 | payment.save() 179 | policy.payment_id = payment 180 | policy.save() 181 | 182 | try: 183 | default_email = os.environ.get('DJANGO_EMAIL_DEFAULT_EMAIL') 184 | subject = "Website: You’re one step away from being secured" 185 | message = render_to_string('first_email.html', {'user': policy.user, 'payment': payment}) 186 | send_mail(subject, message, default_email, [policy.user.email]) 187 | except Exception: 188 | logger.error('Error on sending first email') 189 | 190 | 191 | except Exception as e: 192 | message = "Error contacting with the Gateway" 193 | response = JsonResponse({ 194 | 'status': 'false', 195 | 'message': message 196 | }) 197 | response.status_code = 418 198 | logger.error(e) 199 | return response 200 | else: 201 | post_params = { 202 | "payment_amount": 203 | decimal.Decimal(transaction.amount).quantize( 204 | decimal.Decimal('0.00000001'), 205 | rounding=decimal.ROUND_DOWN).normalize(), 206 | "payment_address": 207 | transaction.address, 208 | "payment_qr": 209 | transaction.qrcode_url, 210 | "gateway_status": 211 | transaction.status_url, 212 | "policy_cover": 213 | policy.cover, 214 | "exchange_name": 215 | policy.exchange.name, 216 | "date_of_formating": 217 | policy.request_date.date(), 218 | "currency": 219 | currency 220 | } 221 | 222 | response = JsonResponse(post_params) 223 | return response 224 | 225 | message = "Payment Exist" 226 | response = JsonResponse({ 227 | 'status': 'false', 228 | 'message': message 229 | }) 230 | return response 231 | elif payment.status == PaymentStatus.PENDING: 232 | logger.info('status Pending, do nothing') 233 | transaction = policy.payment_id 234 | elif payment.status == PaymentStatus.SUCCESS: 235 | logger.info('status Success') 236 | transaction = policy.payment_id 237 | post_params = { 238 | "payment_amount": 239 | decimal.Decimal(transaction.amount).quantize( 240 | decimal.Decimal('0.00000001'), 241 | rounding=decimal.ROUND_DOWN).normalize(), 242 | "payment_address": 243 | transaction.address, 244 | "payment_qr": 245 | transaction.qrcode_url, 246 | "gateway_status": 247 | transaction.status_url, 248 | "policy_cover": 249 | policy.cover, 250 | "exchange_name": 251 | policy.exchange.name, 252 | "date_of_formating": 253 | policy.request_date.date(), 254 | "currency": 255 | currency 256 | } 257 | 258 | response = JsonResponse(post_params) 259 | return response 260 | 261 | 262 | @staff_member_required 263 | def backup_to_csv(request): 264 | data = {} 265 | data['referral'] = ReferralPartner 266 | data['user'] = UserProfile 267 | data['exchange'] = CryptoExchange 268 | data['payments'] = UserPayments 269 | data['policy'] = InsurancePolicy 270 | data['case'] = InsuranceCase 271 | data['additional'] = AdditionalData 272 | cursor = connection.cursor() 273 | cursor.execute('''SELECT insurance_policy.id AS Policy_number, 274 | insurance_policy.request_date AS Policy_date, 275 | user_profile.first_name AS First_name, 276 | user_profile.last_name AS Last_name, 277 | user_profile.email AS Email, 278 | insurance_policy.start_date AS Start_date, 279 | insurance_policy.expiration_date AS Expiration_date, 280 | insurance_policy.expiration_date - \ 281 | insurance_policy.start_date AS Number_of_days, 282 | crypto_exchange.name AS Crypto_exchange_name, 283 | crypto_exchange.coverage_limit AS Limit_BTC, 284 | insurance_policy.cover AS Insured_Limit, 285 | insurance_policy.fee AS Premium_paid, 286 | user_payments.amount AS User_paid, 287 | user_payments.currency AS User_currency, 288 | crypto_exchange.rate AS Premium_rate, 289 | user_payments.update_date AS Premium_payment_date, 290 | insurance_case.loss_value AS Outstanding_claim_BTC, 291 | insurance_case.incident_date AS Date_of_claim, 292 | insurance_case.refund_paid AS Paid_claim_BTC, 293 | insurance_case.request_date AS Date_of_claim_payment, 294 | insurance_policy.status AS Insurance_policy_status, 295 | user_payments.status AS User_payments_status, 296 | insurance_case.status AS Insurance_case_status 297 | FROM insurance_policy 298 | LEFT JOIN user_profile ON user_profile.id = \ 299 | insurance_policy.user 300 | LEFT JOIN crypto_exchange ON crypto_exchange.id = \ 301 | insurance_policy.exchange 302 | LEFT JOIN user_payments ON user_payments.id = \ 303 | insurance_policy.payment_id 304 | LEFT JOIN insurance_case ON \ 305 | insurance_case.insurance = insurance_policy.id 306 | ''') 307 | insurance_report = cursor.fetchall() 308 | 309 | if request.method == 'GET': 310 | datasets = {} 311 | datasets['referral'] = not bool(request.GET.get('referral')) 312 | datasets['user'] = not bool(request.GET.get('user')) 313 | datasets['exchange'] = not bool(request.GET.get('exchange')) 314 | datasets['payments'] = not bool(request.GET.get('payments')) 315 | datasets['policy'] = not bool(request.GET.get('policy')) 316 | datasets['case'] = not bool(request.GET.get('case')) 317 | datasets['additional'] = not bool(request.GET.get('additional')) 318 | response = HttpResponse(content_type='application/zip') 319 | response['Content-Disposition'] = 'attachment; filename=backup.csv.zip' 320 | z = zipfile.ZipFile(response, 'w') 321 | for key in datasets: 322 | if datasets[key] is True: 323 | output = StringIO() 324 | writer = csv.writer(output, dialect='excel') 325 | query = data[key].objects.all().values() 326 | if query.count() > 0: 327 | keys = list(query[0]) 328 | writer.writerow(sorted(keys)) 329 | for row in query: 330 | writer.writerow([row[k] for k in sorted(keys)]) 331 | else: 332 | writer.writerow(['NULL TABLE']) 333 | z.writestr("%s.csv" % key, output.getvalue()) 334 | 335 | out = StringIO() 336 | writer = csv.writer(out) 337 | header = [ 338 | 'Policy_number', 'Policy_date', 'Name', 'Surname', 'E-mail', 339 | 'Policy_start_date', 'Policy_expiry_date', 'Number_of_days', 340 | 'Crypto_exchange_name', 'Limit_BTC', 'Insured_Limit', 'Premium_paid_BTC', 341 | 'User_paid', 'User_currency', 'Premium_rate_%', 342 | 'Premium_payment_date', 'Outstanding_claim_BTC', 'Date_of_claim', 343 | 'Paid_claim_BTC', 'Date_of_claim_payment', 344 | 'Insurance_policy_status', 'User_payments_status', 345 | 'Insurance_case_status' 346 | ] 347 | 348 | writer.writerow(header) 349 | for row in insurance_report: 350 | writer.writerow(row) 351 | z.writestr("insurance_report.csv", out.getvalue()) 352 | try: 353 | if not z.testzip(): 354 | responseData = {'error': True, 'message': 'Nothing to backup'} 355 | return JsonResponse(responseData) 356 | except Exception: 357 | return response 358 | 359 | @csrf_protect 360 | @login_required 361 | def dashboard(request): 362 | user = get_object_or_404( 363 | UserProfile, django_user_id=request.user.id 364 | ) # django_user because we're searching in the registred users 365 | 366 | # check for referral user 367 | try: 368 | userPartner = Partner.objects.get( 369 | django_user=request.user.id) 370 | logger.info( 371 | "Partner: %s logged into system" % (userPartner)) 372 | return account(request) 373 | except ObjectDoesNotExist: 374 | # handle case for regular user 375 | pass 376 | 377 | insurancy_policy_info = Policy.objects.order_by('-id').filter( 378 | user=user.id).exclude(status=PolicyStatus.DELETED) 379 | DEFAULT_VALUE = "NOT FOUND" 380 | PERIOD_NOT_IDENTIFIED = "NOT SET UNTIL PAYMENT DONE" 381 | PAYMENT_ERROR = "REPEAT PAYMENT" 382 | # NOTE: Getting every {'fee':value} pair so we could use it 383 | # while filling the form 384 | try: 385 | found_fee_values = insurancy_policy_info.values('fee') 386 | except Exception: 387 | logger.error("Fee values hasn't been found for user with ID: " + 388 | str(user.id)) 389 | found_fee_values = [] 390 | 391 | fee_values = [] 392 | for current_fee_json in found_fee_values: 393 | fee_values.append(current_fee_json) 394 | 395 | # NOTE: Getting every policy's numbers 396 | policy_numbers = [] 397 | try: 398 | found_policy_numbers = insurancy_policy_info.values('id') 399 | except KeyError as error: 400 | logger.error("Policy number hasn't been found for user with ID: " + 401 | str(user.id)) 402 | found_policy_numbers = [] 403 | 404 | for current_policy_number_json in found_policy_numbers: 405 | policy_numbers.append(current_policy_number_json) 406 | 407 | # NOTE: filling 'insurance period' form 408 | 409 | try: 410 | found_start_dates = insurancy_policy_info.values('start_date') 411 | except KeyError as error: 412 | logger.error("Couldn't find start dates for user with ID: " + 413 | str(user.id)) 414 | found_start_dates = [] 415 | 416 | start_dates = [] 417 | for current_date in found_start_dates: 418 | start_dates.append(current_date) 419 | 420 | try: 421 | found_expiration_dates = insurancy_policy_info.values( 422 | 'expiration_date') 423 | except KeyError as error: 424 | logger.error("Couldn't find expirations dates for user with ID: " + 425 | str(user.id)) 426 | found_expiration_dates = [] 427 | 428 | expiration_dates = [] 429 | for current_date in found_expiration_dates: 430 | expiration_dates.append(current_date) 431 | 432 | # NOTE: filling 'Limit of liability' form 433 | try: 434 | found_limits_of_liability = insurancy_policy_info.values('cover_btc') 435 | except KeyError as error: 436 | logger.error("Couldn't find limits of liability for user with ID: " + 437 | str(user.id)) 438 | found_limits_of_liability = [] 439 | 440 | limits_of_liability = [] 441 | for current_limit in found_limits_of_liability: 442 | limits_of_liability.append(current_limit) 443 | 444 | # NOTE: filling 'date of formatting' form 445 | try: 446 | found_dates_of_formatting = insurancy_policy_info.values( 447 | 'request_date') 448 | except KeyError as error: 449 | logger.error("Couldn't find dates of formatting for user with ID: " + 450 | str(user.id)) 451 | found_dates_of_formatting = [] 452 | 453 | dates_of_formatting = [] 454 | for current_date_of_formatting in found_dates_of_formatting: 455 | dates_of_formatting.append(current_date_of_formatting) 456 | 457 | # NOTE: filling "Crypto exchange" form 458 | try: 459 | found_stock_exchanges = insurancy_policy_info.values('exchange') 460 | except KeyError as error: 461 | logger.error("Couldn't find stock exchanges for user with ID: " + 462 | str(user.id)) 463 | found_stock_exchanges = [] 464 | 465 | stock_exchange_ids = [] 466 | for current_stock_exchange_id in found_stock_exchanges: 467 | stock_exchange_ids.append(current_stock_exchange_id) 468 | 469 | # NOTE: Filling "Status" form 470 | try: 471 | found_policy_statuses = insurancy_policy_info.values('status') 472 | except KeyError as error: 473 | logger.error("Couldn't find policy statuses for user with ID: " + 474 | str(user.id)) 475 | found_policy_statuses = [] 476 | 477 | policy_statuses = [] 478 | for policy_status in found_policy_statuses: 479 | policy_statuses.append(policy_status) 480 | 481 | contextPolicy = [] 482 | for current_id, policy_id in enumerate(insurancy_policy_info): 483 | 484 | context_policy_number = DEFAULT_VALUE 485 | context_limit = DEFAULT_VALUE 486 | context_date_of_formatting = DEFAULT_VALUE 487 | context_insurance_period = PERIOD_NOT_IDENTIFIED 488 | context_fee = DEFAULT_VALUE 489 | context_stock_exchange = DEFAULT_VALUE 490 | 491 | # NOTE: filling policy number 492 | policy_number_tag = "Crypto" 493 | try: 494 | context_policy_number = policy_number_tag + \ 495 | str((policy_numbers[current_id])['id']) 496 | except (IndexError, KeyError) as error: 497 | logger.error( 498 | "An error has occured while trying to get policy number.\ 499 | Reason: " + str(error)) 500 | 501 | # NOTE: filling 'Amount of premium' form 502 | try: 503 | context_fee = fee_values[current_id]['fee'] 504 | except (IndexError, KeyError) as error: 505 | logger.error( 506 | "An error has occured while trying to get fee. Reason: " + 507 | str(error)) 508 | 509 | # NOTE: filling 'insurane period' form 510 | try: 511 | s_date = start_dates[current_id]['start_date'] 512 | e_date = expiration_dates[current_id]['expiration_date'] 513 | context_insurance_period = '%s %s\'%s - %s %s\'%s' % ( 514 | s_date.day, s_date.strftime("%B")[0:3], s_date.year - 2000, 515 | e_date.day, e_date.strftime("%B")[0:3], e_date.year - 2000) 516 | except (IndexError, KeyError, AttributeError) as error: 517 | if policy_id.payment_id and policy_id.payment_id.status < 0: 518 | context_insurance_period = PAYMENT_ERROR 519 | logger.error( 520 | "An error has occured while trying to get insurane period.\ 521 | Reason: " + str(error)) 522 | 523 | # NOTE: filling 'Limit of liability' form 524 | try: 525 | context_limit = limits_of_liability[current_id]['cover_btc'] 526 | except (IndexError, KeyError) as error: 527 | logger.error( 528 | "An error has occured while trying to get limit . Reason: " + 529 | str(error)) 530 | 531 | # NOTE: filling 'date of formatting' form 532 | try: 533 | context_date_of_formatting = str( 534 | dates_of_formatting[current_id]['request_date'].date()) 535 | except (IndexError, KeyError, AttributeError) as error: 536 | logger.error( 537 | "An error has occured while trying to get date of formatting.\ 538 | Reason: " + str(error)) 539 | 540 | # NOTE: filling "Crypto exchange" form 541 | try: 542 | exchange_tag = CryptoExchange.objects.filter(id=stock_exchange_ids[ 543 | current_id]['exchange']).values('name')[0] 544 | context_stock_exchange = exchange_tag['name'] 545 | except (IndexError, KeyError) as error: 546 | logger.error( 547 | "An error has occured while trying to get exchange tag.\ 548 | Reason: " + str(error)) 549 | 550 | # NOTE: filling "policy status" form 551 | 552 | try: 553 | policy_status_numerical_value = policy_statuses[current_id][ 554 | 'status'] 555 | policy_status_tag = get_policy_status_tag( 556 | policy_status_numerical_value) 557 | except (IndexError, KeyError) as error: 558 | logger.error( 559 | "An error has occured while trying to get policy status.\ 560 | Reason: " + str(error)) 561 | 562 | sos = False 563 | try: 564 | sosexists = InsuranceCase.objects.filter( 565 | insurance=(policy_numbers[current_id])['id']) 566 | logger.debug(sosexists.count()) 567 | if sosexists.count() > 0: 568 | sos = True 569 | except (IndexError, KeyError) as error: 570 | logger.error( 571 | "An error has occured while trying to get InsuranceCase.\ 572 | Reason: " + str(error)) 573 | if start_dates[current_id]['start_date']: 574 | days = expiration_dates[current_id]['expiration_date'] -\ 575 | timezone.make_aware( 576 | datetime.datetime.now()) 577 | if policy_status_numerical_value == 2 and ( 578 | days < datetime.timedelta(days=10)): 579 | expired_soon = True 580 | days_left = int( 581 | (expiration_dates[current_id]['expiration_date'] - 582 | timezone.make_aware(datetime.datetime.now())).days) + 1 583 | else: 584 | expired_soon = False 585 | days_left = None 586 | else: 587 | expired_soon = False 588 | days_left = None 589 | 590 | context_policies = { 591 | 'id': (policy_numbers[current_id])['id'], 592 | 'policy_number': 593 | context_policy_number, 594 | 'insurance_period': 595 | context_insurance_period, 596 | 'limit': 597 | context_limit, 598 | 'stock': 599 | context_stock_exchange, 600 | 'formatting_date': 601 | context_date_of_formatting, 602 | 'amount_of_premium': 603 | decimal.Decimal(context_fee).quantize( 604 | decimal.Decimal('0.00000001'), 605 | rounding=decimal.ROUND_DOWN).normalize(), 606 | 'status': 607 | policy_status_tag, 608 | 'numstatus': 609 | policy_status_numerical_value, 610 | 'sosexists': 611 | sos, 612 | 'expired_soon': 613 | expired_soon, 614 | 'days_left': 615 | days_left 616 | } 617 | logger.debug(context_policies) 618 | contextPolicy.append(context_policies) 619 | 620 | # Check User 621 | # .......... 622 | # If user 623 | # Get User policies and notifications 624 | # Policies model: 625 | # - Id - unique. Need to identify a policy(to get info page). 626 | # Mb we can use another field("Policy number"?) 627 | # - Policy number 628 | # - Insurance period 629 | # - Limits of liability 630 | # - Crypto exchange 631 | # - Date of formation 632 | # - Amount of premium paid 633 | # Notification model: 634 | # - Text 635 | # - Date 636 | 637 | 638 | # POLICY_STATUS_ACTIVE = 2 639 | # POLICY_STATUS_WAITING_FOR_PAYMENT = 4 640 | stock_exchange_tags = set() 641 | for stock_exchange in stock_exchange_ids: 642 | current_stock_exchange = (CryptoExchange.objects.select_related( 643 | ).filter(id=stock_exchange['exchange']).values('name')[0])['name'] 644 | stock_exchange_tags.add(current_stock_exchange) 645 | 646 | user_limit_information_context = [] 647 | for stock_exchange in stock_exchange_tags: 648 | coverage_limit = (CryptoExchange.objects.select_related().filter( 649 | name=stock_exchange).values('coverage_limit')[0])['coverage_limit'] 650 | # current_stock_exchange = (CryptoExchange.objects.select_related( 651 | # ).filter(id=stock_exchange['exchange']).values('name')[0])['name'] 652 | current_stock_exchange = stock_exchange 653 | amount_of_holdings = 0 654 | for policy in contextPolicy: 655 | if policy['stock'] == current_stock_exchange and ( 656 | policy['numstatus'] == 1 657 | or policy['numstatus'] == 2): # BEFORE 2 658 | amount_of_holdings += float(policy['limit']) 659 | user_limit_information = { 660 | 'stock_exchange': current_stock_exchange, 661 | 'summary_of_holdings': amount_of_holdings, 662 | 'coverage_limit': float(coverage_limit), 663 | 'rate': int(amount_of_holdings / float(coverage_limit) * 100) 664 | } 665 | user_limit_information_context.append(user_limit_information) 666 | logger.debug(contextPolicy) 667 | # user_limit_information_context = set(user_limit_information_context) 668 | context = { 669 | 'USER_LIMIT_INFO': user_limit_information_context, 670 | 'POLICIES': contextPolicy, 671 | # ToDo: 672 | # Check if user already referral partern 673 | 'is_referral': False 674 | } 675 | return render(request, 'website/dashboard/dashboard.html', context) 676 | --------------------------------------------------------------------------------