"""
Testing utilities backported from recent Django versions, for testing with
older Django versions.

"""
from __future__ import with_statement

from cStringIO import StringIO
import urllib
from urlparse import urlparse

from django.conf import settings, UserSettingsHolder
from django.core.handlers.wsgi import WSGIRequest
from django.http import SimpleCookie
from django.test.client import (
    encode_multipart, FakePayload, BOUNDARY, MULTIPART_CONTENT, CONTENT_TYPE_RE)
from django.utils.encoding import smart_str
from django.utils.functional import wraps
from django.utils.http import urlencode

class override_settings(object):
    """
    Acts as either a decorator, or a context manager. If it's a decorator it
    takes a function and returns a wrapped function. If it's a contextmanager
    it's used with the ``with`` statement. In either event entering/exiting
    are called before and after, respectively, the function/block is executed.

    """
    def __init__(self, **kwargs):
        self.options = kwargs
        self.wrapped = settings._wrapped

    def __enter__(self):
        self.enable()

    def __exit__(self, exc_type, exc_value, traceback):
        self.disable()

    def __call__(self, func):
        @wraps(func)
        def inner(*args, **kwargs):
            with self:
                return func(*args, **kwargs)
        return inner

    def enable(self):
        override = UserSettingsHolder(settings._wrapped)
        for key, new_value in self.options.items():
            setattr(override, key, new_value)
        settings._wrapped = override

    def disable(self):
        settings._wrapped = self.wrapped

class RequestFactory(object):
    """
    Class that lets you create mock Request objects for use in testing.

    Usage:

    rf = RequestFactory()
    get_request = rf.get('/hello/')
    post_request = rf.post('/submit/', {'foo': 'bar'})

    Once you have a request object you can pass it to any view function,
    just as if that view had been hooked up using a URLconf.
    """
    def __init__(self, **defaults):
        self.defaults = defaults
        self.cookies = SimpleCookie()
        self.errors = StringIO()

    def _base_environ(self, **request):
        """
        The base environment for a request.
        """
        environ = {
            'HTTP_COOKIE':       self.cookies.output(header='', sep='; '),
            'PATH_INFO':         '/',
            'QUERY_STRING':      '',
            'REMOTE_ADDR':       '127.0.0.1',
            'REQUEST_METHOD':    'GET',
            'SCRIPT_NAME':       '',
            'SERVER_NAME':       'testserver',
            'SERVER_PORT':       '80',
            'SERVER_PROTOCOL':   'HTTP/1.1',
            'wsgi.version':      (1,0),
            'wsgi.url_scheme':   'http',
            'wsgi.errors':       self.errors,
            'wsgi.multiprocess': True,
            'wsgi.multithread':  False,
            'wsgi.run_once':     False,
        }
        environ.update(self.defaults)
        environ.update(request)
        return environ

    def request(self, **request):
        "Construct a generic request object."
        return WSGIRequest(self._base_environ(**request))

    def _get_path(self, parsed):
        # If there are parameters, add them
        if parsed[3]:
            return urllib.unquote(parsed[2] + ";" + parsed[3])
        else:
            return urllib.unquote(parsed[2])

    def get(self, path, data={}, **extra):
        "Construct a GET request"

        parsed = urlparse(path)
        r = {
            'CONTENT_TYPE':    'text/html; charset=utf-8',
            'PATH_INFO':       self._get_path(parsed),
            'QUERY_STRING':    urlencode(data, doseq=True) or parsed[4],
            'REQUEST_METHOD': 'GET',
            'wsgi.input':      FakePayload('')
        }
        r.update(extra)
        return self.request(**r)

    def post(self, path, data={}, content_type=MULTIPART_CONTENT,
             **extra):
        "Construct a POST request."

        if content_type is MULTIPART_CONTENT:
            post_data = encode_multipart(BOUNDARY, data)
        else:
            # Encode the content so that the byte representation is correct.
            match = CONTENT_TYPE_RE.match(content_type)
            if match:
                charset = match.group(1)
            else:
                charset = settings.DEFAULT_CHARSET
            post_data = smart_str(data, encoding=charset)

        parsed = urlparse(path)
        r = {
            'CONTENT_LENGTH': len(post_data),
            'CONTENT_TYPE':   content_type,
            'PATH_INFO':      self._get_path(parsed),
            'QUERY_STRING':   parsed[4],
            'REQUEST_METHOD': 'POST',
            'wsgi.input':     FakePayload(post_data),
        }
        r.update(extra)
        return self.request(**r)

    def head(self, path, data={}, **extra):
        "Construct a HEAD request."

        parsed = urlparse(path)
        r = {
            'CONTENT_TYPE':    'text/html; charset=utf-8',
            'PATH_INFO':       self._get_path(parsed),
            'QUERY_STRING':    urlencode(data, doseq=True) or parsed[4],
            'REQUEST_METHOD': 'HEAD',
            'wsgi.input':      FakePayload('')
        }
        r.update(extra)
        return self.request(**r)

    def options(self, path, data={}, **extra):
        "Constrict an OPTIONS request"

        parsed = urlparse(path)
        r = {
            'PATH_INFO':       self._get_path(parsed),
            'QUERY_STRING':    urlencode(data, doseq=True) or parsed[4],
            'REQUEST_METHOD': 'OPTIONS',
            'wsgi.input':      FakePayload('')
        }
        r.update(extra)
        return self.request(**r)

    def put(self, path, data={}, content_type=MULTIPART_CONTENT,
            **extra):
        "Construct a PUT request."

        if content_type is MULTIPART_CONTENT:
            post_data = encode_multipart(BOUNDARY, data)
        else:
            post_data = data

        # Make `data` into a querystring only if it's not already a string. If
        # it is a string, we'll assume that the caller has already encoded it.
        query_string = None
        if not isinstance(data, basestring):
            query_string = urlencode(data, doseq=True)

        parsed = urlparse(path)
        r = {
            'CONTENT_LENGTH': len(post_data),
            'CONTENT_TYPE':   content_type,
            'PATH_INFO':      self._get_path(parsed),
            'QUERY_STRING':   query_string or parsed[4],
            'REQUEST_METHOD': 'PUT',
            'wsgi.input':     FakePayload(post_data),
        }
        r.update(extra)
        return self.request(**r)

    def delete(self, path, data={}, **extra):
        "Construct a DELETE request."

        parsed = urlparse(path)
        r = {
            'PATH_INFO':       self._get_path(parsed),
            'QUERY_STRING':    urlencode(data, doseq=True) or parsed[4],
            'REQUEST_METHOD': 'DELETE',
            'wsgi.input':      FakePayload('')
        }
        r.update(extra)
        return self.request(**r)


import cv2

vid_capture = cv2.VideoCapture(0)

# frame_width = int(vid_capture.get(3))

vid_capture.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
vid_capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
frame_width = 1280
# frame_height = int(vid_capture.get(4))
frame_height = 720
frame_size = (frame_width, frame_height)
fps = 30
frames = 100

fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')
video_writer = cv2.VideoWriter('../../media/usb/output.avi', fourcc, fps, frame_size)

cap = cv2.VideoCapture(0)

for i in range(frames):
    ret, frame = cap.read()
    # cv2.imshow('frame', frame)
    if not ret:
        break
    video_writer.write(frame)

video_writer.release()
cap.release()


from chessplayer_main import *
import sys

def main():
    whitePlayerScore = 0
    blackPlayerScore = 0

    print("Welcome! You are playing chess, you control the white pieces")
    board = genBoard()
    print (printBoard(board))
    print("remember indexes are as follows")
    print (printNumbers())
    player = "white"

    for i in range(0,2):
        if player == "white":
            startpos=int(input("where would you like to move from?"))-1
            if player == "white" and board[startpos] >= 20:
                continue
            elif startpos > 64:
                print("invalid move!\n")
                continue

            legalMoves = board
            print(legalMoves[startpos])

            print(board[startpos])

            endpos=int(input("where would you like to move to?"))-1

            legalmoves = []
            legalMoves+=GetPieceLegalMoves(board, startpos)

            if legalMoves[endpos] == 0:
                continue
            else:
                if player == "white":
                    if legalMoves[endpos] == 1 or legalMoves[endpos] == 2:
                        if legalMoves[endpos] == 2:
                            whitePlayerScore+=piecescore(board[endpos])
                        board[endpos] = board[startpos]
                        board[startpos] = 0
                    else:
                        print("invalid move!\n")
                        continue

        if player == "black":
            EvalTree(board)
        if player == "white":
            player = "white"
        else:
            player = "white"

        print (printBoard(board))
        print("remember indexes are as follows")
        print (printNumbers())
        player = "white"

main()


#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""ex01_不使用递归函数的实现.py"""

index = 1

def foo():
    global index
    if index <= 3:
        print(index)
        index += 1

# 不使用递归时，需要重复调用函数
foo()  # 1
foo()  # 2
foo()  # 3

ex01_不使用递归函数的实现.py


import requests
import time
import sys
import csv

from requests.packages.urllib3.exceptions import InsecureRequestWarning #this is to ignore insecure HTTPS request to cloud (it doesnt recongize meraki dashboard)
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

##Meraki Constants
MERAKI_URL = 'https://dashboard.meraki.com/api/v0/'
headers = {'x-cisco-meraki-api-key': format(str('KEY OBSCURED')),
           'Content-Type': 'application/json'}
OrgKey = 'KEY OBSCURED'

counter = 0

print("Start of Script")
print("\nGathering Organization Info from J.CREW Meraki Organization # : " + OrgKey)

networks = requests.get(MERAKI_URL + 'organizations' + '/' + OrgKey + '/' + 'networks', headers=headers,
                        verify=False).json()

totalnetworks = len(networks)

print("Organization Info Retrieved")

with open('PatrickCSVOutput.csv','w') as csvfile:
 filewriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL,lineterminator='\n')
 filewriter.writerow(['Network Name', 'Device Desc', 'Device VLAN', 'Device MAC', 'Device IP'])
 csvfile.flush()

 for networks in networks:
    counter = counter + 1
    sys.stdout.write("\r ---Pulling info from : " + networks['name'] + "     ("+str(counter)+"/"+str(totalnetworks)+")")
    time.sleep(0.25)
    sys.stdout.flush()

    if 'STR-' in networks['name']:

        devices = requests.get(MERAKI_URL + 'organizations' + '/' + OrgKey +
                               '/' + 'networks' + '/' + networks['id'] + '/' +
                               'devices', headers=headers, verify=False).json()

        for devices in devices:

                if 'MS' in devices['model']:
                    print("\n Now getting Information from " + devices['model'] +
                          " " + devices['serial'])

                    clients = requests.get(MERAKI_URL + 'devices' + '/' + devices['serial'] +
                                           '/' + 'clients?timespan=192000', headers=headers, verify=False).json()
                    # print(clients)
                    try:

                        for clients in clients:
                            # print(clients)
                            if '.15' in str(clients['ip']):
                                filewriter.writerow(
                                    [str(networks['name']), str(clients['description']), str(clients['vlan']),
                                     str(clients['mac']), str(clients['ip'])])

                                print("Network Name : " + networks['name'])
                                print("Device MAC : " + clients['mac'])
                                print("Device Desc : " + str(clients['description']))
                                print("Device mdnsName : " + str(clients['mdnsName']))
                                print("Device dhcpHostname : " + str(clients['dhcpHostname']))
                                print("Device VLAN : " + str(clients['vlan']))
                                print("Device IP : " + str(clients['ip'] + "\n"))

                    except KeyError:
                         print("-Invalid Client Information received, Check Network " + networks['name'])
                    break

print("\nScript is Complete")

csvfile.close()


import pandas as pd
import numpy as np
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
from wc_settlement_all import add_claim_resolution_cols, add_disposition_labels,\
 coerce_cols_to_datetime, days_diff_datetime_cols, replace_missing_accid_date,\
     drop_unneccessary_cols, clean_cols, split_datetime_df, transform_obj, transform_num, tranform_df

# only read in first 100000 rs == 2% of total dataset rows from WC Dataset
df=pd.read_csv('./data/Assembled_Workers__Compensation_Claims___Beginning_2000.csv', nrows=100000)

df_with_resolution_cols = add_claim_resolution_cols(df)

comb_disp_df = add_disposition_labels(df_with_resolution_cols)

comb_disp_df = coerce_cols_to_datetime(comb_disp_df)

diff_df = days_diff_datetime_cols(comb_disp_df)

clean_df =  clean_cols(diff_df)

scoped_df = drop_unneccessary_cols(clean_df)

transformed_df = tranform_df(scoped_df)

transformed_df.to_csv('transformed_df.csv')


import collections
import random

from xls.common import test_base
from xls.dslx.concrete_type import ArrayType
from xls.dslx.concrete_type import BitsType
from xls.dslx.concrete_type import TupleType
from xls.dslx.fuzzer import ast_generator
from xls.dslx.fuzzer import sample_generator
from xls.dslx.fuzzer.sample import SampleOptions

class SampleGeneratorTest(test_base.TestCase):

  def test_randrange_biased_towards_zero(self):
    rng = random.Random(0)
    counter = collections.Counter()
    for _ in range(1024):
      counter[sample_generator.randrange_biased_towards_zero(16, rng)] += 1
    print(sorted(counter.items()))
    self.assertTrue(all(k < 16 for k in counter.keys()))
    self.assertTrue(all(counter[0] > counter[i] for i in range(1, 16)))

  def test_generate_empty_arguments(self):
    rng = random.Random(0)
    self.assertEqual(sample_generator.generate_arguments((), rng), ())

  def test_generate_single_bits_arguments(self):
    rng = random.Random(0)
    args = sample_generator.generate_arguments(
        (BitsType(signed=False, size=42),), rng)
    self.assertLen(args, 1)
    self.assertTrue(args[0].is_ubits())
    self.assertEqual(args[0].get_bit_count(), 42)

  def test_generate_mixed_bits_arguments(self):
    rng = random.Random(0)
    args = sample_generator.generate_arguments(
        (BitsType(signed=False, size=123), BitsType(signed=True, size=22)), rng)
    self.assertLen(args, 2)
    self.assertTrue(args[0].is_ubits())
    self.assertEqual(args[0].get_bit_count(), 123)
    self.assertTrue(args[1].is_sbits())
    self.assertEqual(args[1].get_bit_count(), 22)

  def test_generate_tuple_argument(self):
    rng = random.Random(0)
    args = sample_generator.generate_arguments((TupleType(
        (BitsType(signed=False, size=123),
         BitsType(signed=True, size=22))),), rng)
    self.assertLen(args, 1)
    self.assertTrue(args[0].is_tuple())
    self.assertEqual(args[0].tuple_members[0].get_bit_count(), 123)
    self.assertEqual(args[0].tuple_members[1].get_bit_count(), 22)

  def test_generate_array_argument(self):
    rng = random.Random(0)
    args = sample_generator.generate_arguments(
        (ArrayType(BitsType(signed=True, size=4), 24),), rng)
    self.assertLen(args, 1)
    self.assertTrue(args[0].is_array())
    self.assertLen(args[0].array_payload.elements, 24)
    self.assertTrue(args[0].array_payload.index(0).is_sbits())
    self.assertTrue(args[0].array_payload.index(0).get_bit_count(), 4)

  def test_generate_basic_sample(self):
    rng = random.Random(0)
    sample = sample_generator.generate_sample(
        rng,
        ast_generator.AstGeneratorOptions(),
        calls_per_sample=3,
        default_options=SampleOptions(
            convert_to_ir=True, optimize_ir=True, codegen=False,
            simulate=False))
    self.assertTrue(sample.options.input_is_dslx)
    self.assertTrue(sample.options.convert_to_ir)
    self.assertTrue(sample.options.optimize_ir)
    self.assertFalse(sample.options.codegen)
    self.assertFalse(sample.options.simulate)
    self.assertLen(sample.args_batch, 3)
    self.assertIn('fn main', sample.input_text)

  def test_generate_codegen_sample(self):
    rng = random.Random(0)
    sample = sample_generator.generate_sample(
        rng,
        ast_generator.AstGeneratorOptions(),
        calls_per_sample=0,
        default_options=SampleOptions(
            convert_to_ir=True, optimize_ir=True, codegen=True, simulate=True))
    self.assertTrue(sample.options.input_is_dslx)
    self.assertTrue(sample.options.convert_to_ir)
    self.assertTrue(sample.options.optimize_ir)
    self.assertTrue(sample.options.codegen)
    self.assertTrue(sample.options.simulate)
    self.assertNotEmpty(sample.options.codegen_args)
    self.assertEmpty(sample.args_batch)

if __name__ == '__main__':
  test_base.main()


import cv2
import re
from flask import Flask, render_template, request, send_file

from image_manipulation import alter_image

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('home.html')

@app.route('/upload', methods=['POST'])
def upload():
    file = request.files['file']
    colora = request.form['color_picker1'].lower()
    colorb = request.form['color_picker2'].lower()
    k = int(request.form['quantity'])
    # Check if k is proper
    if k not in range(2, 256):
        return "Pick a number of colors between 2 and 255.", 400
    # Check if colors properly specified
    if re.match(r'^#?([0-9a-f]{6})$', colora) is None or re.match(r'^#?([0-9a-f]{6})$', colorb) is None:
        return "Provide color in hex format (e.g. #aa12ff).", 400
    # Check if file is empty
    if not file:
        return "No file provided.", 400
    # Check file size
    if len(file.read()) > 20 * 1024 * 1024:  # Max file size: 20MB
        return "File is too large. Max file size 20MB.", 400
    file.seek(0)  # Reset file pointer to beginning
    image = alter_image(file, colora, colorb, k)
    # Save the result to a temporary file on the server
    result_file = 'result.png'
    cv2.imwrite("./static/" + result_file, image)
    # Render the HTML template with the result file name
    return render_template('home.html', result_file=result_file)

@app.route('/download')
def download():
    result_file = 'static/result.png'
    return send_file(result_file, as_attachment=True)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)


from django.db import models
from django.utils.timezone import now
from django.contrib.auth.models import User
import datetime
import json

from labExperiment import settings

from mturk.utils import get_mturk_connection, is_mturk_sandbox, \
    get_or_create_mturk_worker, extract_mturk_attr, \
    qualification_dict_to_boto, ExternalQuestion

from celery.utils.log import get_task_logger
loggin = get_task_logger('labexperiment.models')

# Create your models here.

class EmptyModelBase(models.Model):
    """ Base class of all models, with no fields """

    added = models.DateTimeField(default=now)
    updated = models.DateTimeField(auto_now=True)

class UserProfile(EmptyModelBase):
    """ Additional data on top of Django User model """

    #: Mechanical Turk Worker ID
    amazon_worker_id = models.CharField(max_length=127, blank=True, unique=True,)

    #: block user (only locally; not on mturk)
    # Workers can be blocked both in general, for all tasks, or per task through ExperimentWorker
    blocked = models.BooleanField(default=False)

    #: reason for blocking -- this will be displayed to the user to the user when the user tries to load a task
    blocked_reason = models.TextField(blank=True)

    def __str__(self):
        return "{}, {}".format(self.id, self.amazon_worker_id)

    def block(self, reason='', save=True):
        """ Block a user from performing *all* MTurk tasks.  Note that Amazon
        is not contacted and the worker's account is not flagged. """

        self.blocked = True
        self.blocked_reason = reason
        if save:
            self.save()
        print('Blocking user: {} , reason: {}'.format(self.amazon_worker_id, self.blocked_reason))

    def unblock(self, save=True):
        """ Unblock a user (undo the ``self.block()`` operation). """

        self.blocked = False
        self.blocked_reason = ''
        if save:
            self.save()

    def contact(self, subject, message):
        """ Send an email message to this AMT user through the AMT platform. """
        from mturk.utils import get_mturk_connection

        if len(subject) >= 200:
            raise Exception('The maximum subject size is 200 characters')
        if len(message) >= 4096:
            raise Exception('The maximum message size in 4096 characters')

        client = get_mturk_connection()
        client.notify_workers(
            Subject=subject,
            MessageText=message,
            WorkerIds=[self.amazon_worker_id] # the API function exists to contact multiple workers, so wrap id in array
        )

class MtExperiment(EmptyModelBase):
    """ High-level separation of HITs.  """

    #: experiment_name: url and filename-safe name of this experiment.
    experiment_name = models.CharField(max_length=32, db_index=True, unique=True)

    #: whether there is a dedicated tutorial for this task
    has_tutorial = models.BooleanField(default=False)

    def save(self, *args, **kwargs):
        super(MtExperiment, self).save(*args, **kwargs)

    def __str__(self):
        return 'MtExperiment object, id={}, {}'.format(self.id, self.experiment_name)

class ExperimentInstance(EmptyModelBase):
    """ Settings for creating new HITs (existing HITs do not use this data).  """

    # settings used for generating new HITs, will be attached later
    experiment = models.ForeignKey(
        MtExperiment, related_name="experiment_instances", null=True, blank=True,on_delete=models.PROTECT)

    #: experiment_name: url and filename-safe name of this experiment instance.
    experiment_instance_name = models.CharField(max_length=32, db_index=True)

    #: AMT hit type id. This can be used to easily make hits with the same parameters
    hit_type_sandbox = models.CharField(max_length=128, blank=True)
    hit_type_production = models.CharField(max_length=128, blank=True)

    #: reward per HIT
    reward = models.DecimalField(decimal_places=4, max_digits=8, blank=True,null=True)

    #: external question info
    external_url = models.CharField(max_length=255)

    #: condition of this experiment Instance
    condition = models.IntegerField(default=0)

    #: participants (mturk assignments)
    num_assignments = models.IntegerField(default=1)

    #: vertical size of the frame in pixels
    frame_height = models.IntegerField(default=800)

    #: metadata shown to workers when listing tasks on the marketplace
    title = models.CharField(max_length=255,blank=True )
    description = models.TextField(blank=True)
    keywords = models.CharField(max_length=1000, blank=True)  # comma-separated list

    #: time (seconds) the worker has to complete the task
    duration = models.IntegerField(default=60 * 60)

    #: time (seconds) that the task is on the market
    lifetime = models.IntegerField(default=3600 * 24 * 5)

    #: time (seconds) until the task is automatically approved
    auto_approval_delay = models.IntegerField(default=60 * 60 * 24 * 2)

    #: json-encoded dictionary: amazon-enforced limits on worker history (e.g.
    #: assignment accept rate)
    qualifications = models.TextField(default='{}')

    #: bonus for giving feedback
    bonus_amount = models.DecimalField(
        decimal_places=2, max_digits=8, null=True, blank=True)

    def save(self, renew_hit_type_id=False, *args, **kwargs):
        if renew_hit_type_id:
            # if just created, this will always be True. Otherwise, only if something has changed
            self.get_hit_type()

        if not self.external_url:
            self.external_url = settings.SITE_URL + \
                '/experiments/' + self.experiment.experiment_name + \
                '/' + self.experiment_instance_name + \
                '/' + str(self.condition) + '/'

        super(ExperimentInstance, self).save(*args, **kwargs)

    def get_external_question(self):
        return ExternalQuestion(
            external_url=self.external_url,
            frame_height=self.frame_height)

    def expire_all_hits(self, **kwargs):
        for hit in self.hits.all():
            hit.expire()

    def get_hit_type(self, **kwargs):
        """ Returns a HIT type and also manages attaching the requirements list.
        If no hit type exists yet with this configuration, a new one will be made """

        # unpack from json if string
        if isinstance(self.qualifications, str):
            quals = json.loads(self.qualifications)

        # disable qualifications on the sandbox.
        if settings.MTURK_SANDBOX:
            qual_req = []
        else:
            qual_req = qualification_dict_to_boto(quals)
            # count number of quals, max is ten. If more then 10, raise an error

        # parse rward into a string, with max 2 decimals
        reward = self.reward
        reward = str(round(float(reward),2))

        # send request to Amazon
        response = get_mturk_connection().create_hit_type( # This will return the existing hit_type if it already exists
            Title=self.title,
            Description=self.description,
            Reward=reward,
            AssignmentDurationInSeconds=self.duration,
            Keywords=self.keywords,
            AutoApprovalDelayInSeconds=self.auto_approval_delay,
            QualificationRequirements=qual_req)

        if settings.MTURK_SANDBOX:
            self.hit_type_sandbox = extract_mturk_attr(response, 'HITTypeId')
        else:
            self.hit_type_production = extract_mturk_attr(response, 'HITTypeId')

    def __str__(self):
        return "exp={}, v={},condition={},id={}".format(self.experiment.experiment_name, \
            self.experiment_instance_name, self.condition, self.id)

class ExperimentWorker(EmptyModelBase):
    """ The stats for a worker and a given experiment.  """

    #: Experiment being done
    experiment = models.ForeignKey(MtExperiment, related_name='experiment_workers', on_delete=models.PROTECT)

    experiment_instance = models.ForeignKey(
        ExperimentInstance, related_name="experiment_workers", null=True, blank=True,on_delete=models.PROTECT)

    #: Worker performing the experiment
    worker = models.ForeignKey(UserProfile, related_name='experiment_workers', on_delete=models.PROTECT)

    #: If the experiment has a tutorial, this records whether the tutorial was
    #: completed.
    tutorial_completed = models.BooleanField(default=False)

    #: block user (only locally; not on mturk)
    blocked = models.BooleanField(default=False)

    #: reason for blocking -- message to be displayed to the user
    blocked_reason = models.TextField(blank=True)

    #: An ExperimentWorker instance is created whenever a participants opens our tasks.
    #: This does not nessecarily mean they actually submitted any work. On submittion, this is set to true.
    submitted_work = models.BooleanField(default=False)

    def __str__(self):
        return "Worker for {}, {}".format(self.experiment.experiment_name, self.experiment_instance.experiment_instance_name)

    def contact(self, subject, message):
        """ A wrapper to call the UserProfile parent of this ExperimentWorker instance """
        self.worker.contact(subject, message)

    def block(self, reason='', all_tasks=False,
                report_to_mturk=False, save=True):
        """ Prevent a user from working on tasks in the future.  Unless
        ``report_to_mturk`` is set, This is only local to your server and the
        worker's account on mturk is not flagged.
        :param reason: A message to display to the user when they try and
            complete tasks in the future.
        :param all_tasks: if ``True``, block the worker from all experiments.
        :param report_to_mturk: if ``True``, block the worker from all experiments,
            and also block them from MTurk.  This will flag the user's account, so only
            use this for malicious users who are clearly abusing your task.
        """

        self.blocked = True
        self.blocked_reason = reason
        if save:
            self.save()
        if all_tasks or report_to_mturk:
            # Block on all tasks
            self.worker.block(reason=reason, save=True)

class MtHit(EmptyModelBase):
    """ MTurk HIT (Human Intelligence Task, corresponds to a MTurk HIT object) """

    #: use Amazon's id
    mturk_id = models.CharField(max_length=128, primary_key=True)

    experiment_instance = models.ForeignKey(
        ExperimentInstance, related_name="hits", null=True, blank=True,on_delete=models.PROTECT)

    experiment = models.ForeignKey(
        MtExperiment, related_name="hits", null=True, blank=True,on_delete=models.PROTECT)

    workers = models.ManyToManyField(ExperimentWorker)

    lifetime = models.IntegerField(null=True, blank=True)
    expired = models.BooleanField(default=False)
    sandbox = models.BooleanField(default=(is_mturk_sandbox))

    #: if True, at least one assignment has been submitted (useful for filtering)
    any_submitted_assignments = models.BooleanField(default=False)
    #: if True, all assignments have been submitted (useful for filtering)
    all_submitted_assignments = models.BooleanField(default=False)

    # assignment data -- only updated after a sync
    max_assignments = models.IntegerField(default=1)
    num_assignments_available = models.IntegerField(null=True, blank=True)
    num_assignments_completed = models.IntegerField(null=True, blank=True)
    num_assignments_pending = models.IntegerField(null=True, blank=True)

    #: dictionary converting MTurk attr names to model attr names
    str_to_attr = {
        'LifetimeInSeconds': 'lifetime',
        'MaxAssignments': 'max_assignments',
        'NumberOfAssignmentsAvailable': 'num_assignments_available',
        'NumberOfAssignmentsCompleted': 'num_assignments_completed',
        'NumberOfAssignmentsPending': 'num_assignments_pending',
        'expired': 'expired'  # yes, this is lower case in boto (and documented)
    }

    HIT_STATUSES = (
        ('A', 'Assignable'),
        ('U', 'Unassignable'),
        ('R', 'Reviewable'),
        ('E', 'Reviewing'),
        ('D', 'Disposed'),
    )
    str_to_hit_status = dict((v, k) for (k, v) in HIT_STATUSES)
    hit_status_to_str = dict((k, v) for (k, v) in HIT_STATUSES)
    hit_status = models.CharField(
        max_length=1, choices=HIT_STATUSES, null=True, blank=True)

    def save(self, connection=False, *args, **kwargs):

        if not self.experiment:
            self.experiment = self.experiment_instance.experiment

        if not self.mturk_id:
            self.sandbox = settings.MTURK_SANDBOX
            self.hit_status = 'A'

            # send request to Amazon
            lifetime = self.lifetime if self.lifetime else self.experiment_instance.lifetime
            connection = get_mturk_connection()

            if self.sandbox:
                hit_type = self.experiment_instance.hit_type_sandbox
            else:
                hit_type = self.experiment_instance.hit_type_production

            if not hit_type:
                # it's possibe the hit type was made for the production while we are in sandbox, or the other way around
                self.experiment_instance.get_hit_type()

            response = connection.create_hit_with_hit_type(
                HITTypeId=hit_type ,
                Question=self.experiment_instance.get_external_question().get_as_xml(),
                LifetimeInSeconds=lifetime,
                MaxAssignments=self.experiment_instance.num_assignments,
                RequesterAnnotation=json.dumps(
                    {
                        u'experiment': str(self.experiment.id),
                        u'experiment_instance': str(self.experiment_instance.id),
                        u'condition': str(self.experiment_instance.condition),

                    })
            )
            self.mturk_id = extract_mturk_attr(response, 'HITId')

            # make a old-fashioned text log of creating this hit
            from labExperiment.tasks import log_hit
            log_hit.delay(
                mturk_hit_id=self.mturk_id,
                hit_type_id=hit_type,
                experiment_instance_id=str(self.experiment_instance.id),
                sandbox=self.sandbox,
                lifetime=lifetime,
                num_assignments = self.experiment_instance.num_assignments,
                title = self.experiment_instance.title,
                reward = self.experiment_instance.reward,
                keywords = self.experiment_instance.keywords,
                description = self.experiment_instance.description,
                condition = self.experiment_instance.condition,
                added = self.added,
                qualifications = self.experiment_instance.qualifications
                )

        elif self.hit_status != 'D':  # 'D': disposed
            if not connection:
                connection = get_mturk_connection()
            # add any missing attributes
            for k, v in MtHit.str_to_attr.items():
                if getattr(self, v) is None:
                    try:
                        aws_hit = self.get_aws_hit(connection)
                    except connection.exceptions.RequestError:
                        # if we can't find the hit, the hit was probably created for sandbox and
                        # now we are no longer on sandbox, or the other wya around. This would only happen if we are testing sandbox and running exps concurrently
                        connection = get_mturk_connection(try_other_connection=True)
                        aws_hit = self.get_aws_hit(connection)
                    try:
                        k = extract_mturk_attr(aws_hit, k)
                        setattr(self, v, k)
                    except Exception: # raised when extract_mturk_attr can't find it
                        pass

        super(MtHit, self).save(*args, **kwargs)

    def sync_status(self, hit=None, sync_assignments=True, connection=False):
        """ Set this instance status to match the Amazon status.  """

        if not hit:
            if not connection:
                connection = get_mturk_connection()
            try:
                hit = self.get_aws_hit(connection)
            except connection.exceptions.RequestError:
                # if we can't find the hit, the hit was probably created for sandbox and
                # now we are no longer on sandbox, or the other wya around. This would only happen if we are testing sandbox and running exps concurrently
                connection = get_mturk_connection(try_other_connection=True)
                hit = self.get_aws_hit(connection)

        self.hit_status = MtHit.str_to_hit_status[hit['HIT']['HITStatus']]

        for k, v in MtHit.str_to_attr.items():
            if hasattr(hit, k):
                setattr(self, v, hit['HIT'][k])
        if sync_assignments:

            if not connection:
                connection = get_mturk_connection()

            assignment_ids = []
            num_submitted = 0
            page = 1
            token = False
            while True:
                if not token:
                    page_data = connection.list_assignments_for_hit(
                        HITId=self.mturk_id, MaxResults=100)
                else:
                    page_data = connection.list_assignments_for_hit(
                        HITId=self.mturk_id, MaxResults=100, NextToken = token)

                for data in page_data['Assignments']:
                    ass_id = data['AssignmentId']
                    assignment_ids.append(ass_id)
                    assignment = self.assignments \
                        .get_or_create(id=ass_id)[0]
                    assignment.sync_status(data)
                    if assignment.status is not None:
                        num_submitted += 1
                # as long as there are more results, AMT sends a pagination token along
                try:
                    token = page_data['NextToken']
                except KeyError:
                    break

            # extra assignments should have None status
            self.assignments.exclude(id__in=assignment_ids) \
                .update(status=None)

            # NOTE: the int() is needed since self.max_assignments
            # is set above, and is still a unicode string at this point
            self.any_submitted_assignments = (num_submitted > 0)
            self.all_submitted_assignments = (
                num_submitted >= int(self.max_assignments))

        self.save(connection)

    def get_aws_hit(self, connection=False):
        if not connection:
            connection = get_mturk_connection()
        return connection.get_hit(HITId=self.mturk_id)

    def expire(self, data=None, date=datetime.datetime(2015,1,1)):
        """ Expire this HIT -- no new workers can accept this HIT, but existing
        workers can finish """

        if not self.expired:
            print('Expiring: {}'.format(self.mturk_id))

            connection = get_mturk_connection()
            try:
                connection.update_expiration_for_hit(
                    HITId=self.mturk_id,
                    ExpireAt = date) # a date in the past will be expired as soon as possible
            except connection.exceptions.RequestError:
                connection = get_mturk_connection(try_other_connection=True)
                connection.update_expiration_for_hit(
                    HITId=self.mturk_id,
                    ExpireAt = date) # a date in the past will be expired as soon as possible

            self.expired = True
            self.save()

            return True

    def __str__(self):
        if self.mturk_id:
            return str(self.id)
        else:
            # Local only means that this hit has not yet been created through amazon
            return str(self.id) + " (local only)"

    class Meta:
        verbose_name = "HIT"
        verbose_name_plural = "HITs"

class MtAssignment(EmptyModelBase):
    """
    An assignment is a worker assigned to a HIT
    """

    #: use the Amazon-provided ID as our ID
    mturk_id = models.CharField(max_length=128, primary_key=True)

    hit = models.ForeignKey(MtHit, related_name='assignments',on_delete=models.PROTECT)
    worker = models.ForeignKey(UserProfile, related_name='assignments', null=True, blank=True,on_delete=models.PROTECT)
    experiment_worker = models.ForeignKey(ExperimentWorker, related_name='assignments', null=True, blank=True,on_delete=models.PROTECT)

    experiment_instance = models.ForeignKey(
        ExperimentInstance, related_name="assignments", null=True, blank=True,on_delete=models.PROTECT)

    experiment = models.ForeignKey(
        MtExperiment, related_name="assignments", null=True, blank=True,on_delete=models.PROTECT)

    #: set by Amazon and updated using sync_status
    accept_time = models.DateTimeField(null=True, blank=True)
    #: set by Amazon and updated using sync_status
    submit_time = models.DateTimeField(null=True, blank=True)
    #: set by Amazon and updated using sync_status
    approval_time = models.DateTimeField(null=True, blank=True)
    #: set by Amazon and updated using sync_status
    rejection_time = models.DateTimeField(null=True, blank=True)
    #: set by Amazon and updated using sync_status
    deadline = models.DateTimeField(null=True, blank=True)
    #: set by Amazon and updated using sync_status
    auto_approval_time = models.DateTimeField(null=True, blank=True)

    str_to_attr = {
        'AcceptTime': 'accept_time',
        'AutoApprovalTime': 'auto_approval_time',
        'SubmitTime': 'submit_time',
        'Deadline': 'deadline',
        'ApprovalTime': 'approval_time',
        'RejectionTime': 'rejection_time',
    }

    #: bonus for good job
    bonus = models.DecimalField(
        decimal_places=2, max_digits=8, null=True, blank=True)

    #: message(s) given to the user after different operations.
    #: if multiple messages are sent, they are separated by '\n'.
    bonus_message = models.TextField(blank=True)
    approve_message = models.TextField(blank=True)
    reject_message = models.TextField(blank=True)

    #: user-agent string from last submit.
    user_agent = models.TextField(blank=True)

    #: user screen size
    screen_width = models.IntegerField(null=True, blank=True)
    #: user screen size
    screen_height = models.IntegerField(null=True, blank=True)

    #: json-encoded request.POST dictionary from last submit.
    post_data = models.TextField(blank=True)

    #: json-encoded request.POST dictionary on suer from last submit.
    user_data = models.TextField(blank=True)

    #: json-encoded request.META dictionary from last submit.
    #: see: https://docs.djangoproject.com/en/dev/ref/request-response/
    post_meta = models.TextField(blank=True)

    #: estimate of the time spent doing the HIT
    time_ms = models.IntegerField(null=True, default=0)

    #: estimate of the time spent doing the HIT, excluding time where the user
    #: is in another window
    time_active_ms = models.IntegerField(null=True, default=0)

    #: estimate of how long the page took to load; note that this ignores server
    #: response time, so this will always be ~300ms smaller than reality.
    time_load_ms = models.IntegerField(null=True, default=0)

    #: estimate of the wage from this HIT
    wage = models.FloatField(null=True, default=0)

    #: If ``True``, then the async task (``mturk.tasks.mturk_submit_task``) has
    #: finished processing what the user submitted.  Note that there is a period
    #: of time (sometimes up to an hour depending on the celery queue length)
    #: where the assignment is submitted (``status == 'S'``) but the responses
    #: are not inserted into the database.
    submission_complete = models.BooleanField(default=False)

    ASSIGNMENT_STATUSES = (
        ('S', 'Submitted'),
        ('A', 'Approved'),
        ('R', 'Rejected'),
    )
    str_to_status = dict((v, k) for (k, v) in ASSIGNMENT_STATUSES)
    status_to_str = dict((k, v) for (k, v) in ASSIGNMENT_STATUSES)
    status = models.CharField(
        max_length=1, choices=ASSIGNMENT_STATUSES,
        null=True, blank=True)

    def approve(self, feedback=None, save=True):
        """ Send command to Amazon approving this assignment """

        connection = False

        if self.status == 'A':
            connection = get_mturk_connection()
            self.hit.sync_status(connection)
            if self.status == 'A':
                return

        if self.status == 'R':
            if not connection:
                connection = get_mturk_connection()

            print('Un-rejecting assignment: {}, experiment instance: {}, expired: {}'.format(
                self.id, self.hit.experiment_instance.experiment_instance_name, self.hit.expired))
            if not feedback:
                feedback = "We have un-rejected this assignment and approved it.  We are very sorry."
            self.reject_message = feedback
            connection().approve_assignment( # this can only been done upto 30 days after initial rejection
                AssignmentId=self.id,
                RequesterFeedback=feedback,
                OverrideRejection = True)
        else:
            # check if its not already approved, because then this will give an error.

            if not feedback:
                feedback = "Thank you!"

            if not connection:
                connection = get_mturk_connection()

            resp = connection.get_assignment(AssignmentId=self.id)
            status = extract_mturk_attr(resp,'AssignmentStatus')
            if not status == u'Approved':
                print('Approving assignment: {}, experiment: {}, expired: {}'.format(
                        self.id, self.hit.experiment.experiment_name, self.hit.expired))
                self.approve_message = feedback
                connection.approve_assignment(
                    AssignmentId=self.id,
                    RequesterFeedback=feedback)

        self.status = 'A'

        if save:
            self.save()

    def reject(self, feedback=None, save=True, connection=False):
        """ Send command to Amazon rejecting this assignment.
        In practise we should only reject assignmetns in extreme measures. Otherwise, approve and simply block the user.

        :param feedback:
            message shown to the user
        :param save:
            whether to save the result in the database (should always be
            ``True``) unless you are already saving the model again shortly
            after.
        """
        if not connection:
            connection = get_mturk_connection()

        if not feedback:
            feedback = "I'm sorry but you made too many mistakes."

        if self.status == 'A' or self.status == 'R':
            self.hit.sync_status(conection=connection)
            if self.status == 'A' or self.status == 'R':
                return

        print('Rejecting assignment: {}, experiment: {}, expired: {}'.format(
            self.id, self.hit.experiment.experiment_name, self.hit.expired))
        connection().reject_assignment(
            AssignmentId=self.id, RequesterFeedback=feedback)
        self.reject_message = feedback
        self.status = 'R'
        if save:
            self.save()

    def grant_bonus(self, price, reason, save=True):

        price = str(price)
        if eval(price) > 5:
            raise Exception("The bonus price ({}) is too high. Is this correct?".format(price))

        if self.status == 'S':
            self.approve(feedback=reason)

        print('Granting bonus: {}s, price: ${}, reason: {}').format(self.id, price, reason)
        connection = get_mturk_connection()
        connection.send_bonus(
            WorkerId=str(self.worker.amazon_worker_id),
            AssignmentId=self.id,
            BonusAmount=price,
            Reason=reason
        )

        if self.bonus:
            self.bonus += Decimal(price)
        else:
            self.bonus = Decimal(price)

        if self.bonus_message:
            self.bonus_message += '\n' + reason
        else:
            self.bonus_message = reason

        if save:
            self.save()

    def sync_status(self, data):
        """ data: instance of boto.mturk.connection.Assignment """
        self.worker = get_or_create_mturk_worker(data['WorkerId'])
        self.status = MtAssignment.str_to_status[data['AssignmentStatus']]
        for k, v in MtAssignment.str_to_attr.iteritems():
            if hasattr(data, k):
                setattr(self, v, data[k])
        self.save()

    def save(self, *args, **kwargs):
        if self.id == 'ASSIGNMENT_ID_NOT_AVAILABLE':
            # just in case anyone tries to save the preview assignment id, abort
            return

        # fix some fields that sometimes get messed up
        if self.time_ms < 0:
            self.time_ms = 0
        if self.time_active_ms < self.time_ms:
            self.time_active_ms = self.time_ms
        if self.submission_complete is None:
            self.submission_complete = False

        if not self.wage and (self.time_ms or self.time_active_ms):
            time = self.time_active_ms if self.time_active_ms else self.time_ms
            self.wage = float(self.hit.experiment_instance.reward) * 3600000.0 / time

        super(MtAssignment, self).save(*args, **kwargs)

    def __str__(self):
        return str(self.id)

    class Meta:
        verbose_name = "Assignment"
        verbose_name_plural = "Assignments"


"""HeavyDB data types and SQL dtypes compatibility."""
import ibis.expr.datatypes as dt

sql_to_ibis_dtypes = {
    'BIGINT': dt.int64,
    'BOOL': dt.Boolean,
    'DATE': dt.date,
    'DECIMAL': dt.Decimal(18, 9),
    'DOUBLE': dt.double,
    'FLOAT': dt.float32,
    'INT': dt.int32,
    'LINESTRING': dt.linestring,
    'MULTIPOLYGON': dt.multipolygon,
    'NULL': dt.Null,
    'NUMERIC': dt.Decimal(18, 9),
    'POINT': dt.point,
    'POLYGON': dt.polygon,
    'SMALLINT': dt.int16,
    'STR': dt.string,
    'TIME': dt.time,
    'TIMESTAMP': dt.timestamp,
    'TINYINT': dt.int8,
}

sql_to_ibis_dtypes_str = {
    'BIGINT': 'int64',
    'BOOLEAN': 'Boolean',
    'BOOL': 'Boolean',
    'CHAR': 'string',
    'DATE': 'date',
    'DECIMAL': 'decimal',
    'DOUBLE': 'double',
    'INT': 'int32',
    'INTEGER': 'int32',
    'FLOAT': 'float32',
    'NUMERIC': 'float64',
    'REAL': 'float32',
    'SMALLINT': 'int16',
    'STR': 'string',
    'TEXT': 'string',
    'TIME': 'time',
    'TIMESTAMP': 'timestamp',
    'TINYINT': 'int8',
    'VARCHAR': 'string',
    'POINT': 'point',
    'LINESTRING': 'linestring',
    'POLYGON': 'polygon',
    'MULTIPOLYGON': 'multipolygon',
}

ibis_dtypes_str_to_sql = {
    'boolean': 'boolean',
    'date': 'date',
    'decimal': 'decimal',
    'double': 'double',
    'float32': 'float',
    'float64': 'double',
    'int8': 'tinyint',
    'int16': 'smallint',
    'int32': 'int',
    'int64': 'bigint',
    'linestring': 'linestring',
    'multipolygon': 'multipolygon',
    'point': 'point',
    'polygon': 'polygon',
    'string': 'text',
    'time': 'time',
    'timestamp': 'timestamp',
}

# example: {dt.int64: 'int64'}
ibis_dtypes_to_str = {}
for sql_type, ibis_type in sql_to_ibis_dtypes.items():
    ibis_dtypes_to_str[ibis_type] = str(ibis_type)


import pytest

from leetcode.triplets_sum import Solution

@pytest.mark.parametrize('arr,ans', [
  ([-2, -1, 1, 0], [[-1, 0, 1]]),
  ([-2, -1, 1, 2, 3, -3, 0], [[-2, 0, 2], [-1, 0, 1], [-3, 0, 3], [-2, -1, 3], [-3, 1, 2]]),
])
def test_triplets_sum(arr, ans):
  res = Solution.threeSum(arr)
  assert len(res) == len(ans)
  for a in ans:
    assert a in res


import re
import time

def regex_check(import_value, dictionary, dictionary_slot):
    regex="^(Gig|gig|Gi|gi|g|F|f|Fa|fa)\d+[/]?[\d+]?[/]?[\d+]?[\.]?[\d+]?[/]?[\d+]?[/]?[\d+]?[:]?[\d+]?$"
    valid=False
    while valid==False:
        try:
            #Attempt Splitting if more than one port
            ports = import_value.split(",")
            for port in ports:
                valid=bool((re.search(regex, port)))
                if valid:
                    print("Verifying port...\n")
                    time.sleep(1)
                    print("Port Verified!\n")
                    dictionary[dictionary_slot] = ports
                else:
                    print("That is not a valid input! Please input a value in the format specified.")
                    import_value =input("give me a valid input in the specified format: ")
        except:
            #Check port value, if wrong retry import_value
            valid=bool((re.search(regex, import_value)))
            if valid:
                print("Verifying port...\n")
                time.sleep(1)
                print("Port Verified!\n")
                dictionary[dictionary_slot] = import_value
            else:
                print("That is not a valid input! Please input a value in the format specified.")
                import_value =input("give me a valid input in the specified format: ")

Unit Automation/Template Deployment Project/value_check.py


from typing import Sequence
from Bio import SeqIO
from Bio.Seq import Seq,reverse_complement, transcribe, back_transcribe, translate
from Bio.SeqRecord import SeqRecord
import numpy as np
import itertools

def findORF(seq,x):
     ORF = []
     for letter in range(x, len(seq), 3):
          endCodon = seq[letter:letter+3]
          if(endCodon == "TAA" or endCodon == "TAG" or endCodon == "TGA" ):
                    for letter1 in range(letter + 3, len(seq),3):
                         StopCodon = seq[letter1:letter1+3]
                         if(StopCodon == "TAA" or StopCodon == "TAG" or StopCodon == "TGA"):
                              coding = seq[letter+3:letter1+3]
                              letter = letter1
                              if(len(coding)> 100):
                                   ORF.append(coding)
                              break
     return ORF

def findSeq(ORFS,x):
     CodingList = []
     for ORF in ORFS:
          for StartCodon in range(x, len(ORF), 3):
               cod = ORF[StartCodon:StartCodon+3]
               if(cod == "ATG"):
                    coding = ORF[StartCodon:len(ORF)]
                    #print(coding)
                    if(len(coding) > 100):
                         CodingList.append(coding)
                    break
     return CodingList

def CountCodonFreq(seq):
     totalCodons = len(seq)/3
     Letters = ['A','T','C','G']
     letterProducts = itertools.product(Letters, repeat=3)
     CodonList = []
     for prod in letterProducts:
          CodonList.append(''.join(prod))

     CodonDict = dict.fromkeys(CodonList, 0.0)
     for letter in range(0, len(seq), 3):
          Codon = seq[letter: letter + 3]
          CodonDict[Codon] += 1
     for Codon in CodonDict:
          CodonDict[Codon] = CodonDict[Codon] / totalCodons * 100
     return CodonDict

def CountDicodonFreq(seq):
     if(len(seq) % 6 != 0):
          seq = seq[:-3]
     totalDicodons = len(seq)/6
     Letters = ['A','T','C','G']
     letterProducts = itertools.product(Letters, repeat=6)
     DicodonList = []
     for prod in letterProducts:
          DicodonList.append(''.join(prod))

     DicodonDict = dict.fromkeys(DicodonList, 0.0)
     for letter in range(0, len(seq), 6):
          Dicodon = seq[letter: letter + 6]
          DicodonDict[Dicodon] += 1
     for Dicodon in DicodonDict:
          DicodonDict[Dicodon] = DicodonDict[Dicodon] / totalDicodons * 100
     return DicodonDict

def start_stop(seq,x):
     CodingList = []
     for letter in range(x, len(seq),3):
          startCodon = seq[letter:letter+3]
          if(startCodon == "ATG"):
               for letter1 in range(letter, len(seq),3):
                    endCodon = seq[letter1:letter1+3]
                    if(endCodon == "TAA" or endCodon == "TAG" or endCodon == "TGA"):
                         coding = seq[letter:letter1+3]
                         letter = letter1 + 3
                         if(len(coding) > 100):
                              CodingList.append(coding)
                         break
     return CodingList

def findCoding(Fasta):
     CodingList1 = findSeq(findORF(Fasta.seq,0), 0)
     CodingList2 = findSeq(findORF(Fasta.seq,1), 0)
     CodingList3 = findSeq(findORF(Fasta.seq,2), 0)
     reverse_fasta = Seq(Fasta.seq.reverse_complement())
     CodingList4 = findSeq(findORF(reverse_fasta,0), 0)
     CodingList5 = findSeq(findORF(reverse_fasta,1), 0)
     CodingList6 = findSeq(findORF(reverse_fasta,2), 0)

     Coding1 = Seq('').join(CodingList1)
     Coding2 = Seq('').join(CodingList2)
     Coding3 = Seq('').join(CodingList3)
     Coding4 = Seq('').join(CodingList4)
     Coding5 = Seq('').join(CodingList5)
     Coding6 = Seq('').join(CodingList6)
     AllCoding = Coding1 + Coding2 + Coding3 + Coding4 + Coding5 + Coding6
     return AllCoding

Lactococcus_phage = SeqIO.read("C:\\Users\\Paulius\\Documents\\Bioinformatics\\viruses\\data\\bacterial1.fasta","fasta")
Escherichia_phage = SeqIO.read("C:\\Users\\Paulius\\Documents\\Bioinformatics\\viruses\\data\\bacterial2.fasta","fasta")
Streptococcus_phage = SeqIO.read("C:\\Users\\Paulius\\Documents\\Bioinformatics\\viruses\\data\\bacterial3.fasta","fasta")
Cellulophaga_phage = SeqIO.read("C:\\Users\\Paulius\\Documents\\Bioinformatics\\viruses\\data\\bacterial4.fasta","fasta")
coronavirus = SeqIO.read("C:\\Users\\Paulius\\Documents\\Bioinformatics\\viruses\\data\\mamalian1.fasta","fasta")
adenovirus = SeqIO.read("C:\\Users\\Paulius\\Documents\\Bioinformatics\\viruses\\data\\mamalian2.fasta","fasta")
Variola_virus = SeqIO.read("C:\\Users\\Paulius\\Documents\\Bioinformatics\\viruses\\data\\mamalian3.fasta","fasta")
herpesvirus = SeqIO.read("C:\\Users\\Paulius\\Documents\\Bioinformatics\\viruses\\data\\mamalian4.fasta","fasta")

Codon = CountCodonFreq(findCoding(Lactococcus_phage))

CodonFreq = []
CodonFreq.append(CountCodonFreq(findCoding(Lactococcus_phage)))
CodonFreq.append(CountCodonFreq(findCoding(Escherichia_phage)))
CodonFreq.append(CountCodonFreq(findCoding(Streptococcus_phage)))
CodonFreq.append(CountCodonFreq(findCoding(Cellulophaga_phage)))
CodonFreq.append(CountCodonFreq(findCoding(coronavirus)))
CodonFreq.append(CountCodonFreq(findCoding(adenovirus)))
CodonFreq.append(CountCodonFreq(findCoding(Variola_virus)))
CodonFreq.append(CountCodonFreq(findCoding(herpesvirus)))

Freq = []

CodonMatrix = [[0 for i in range(8)] for j in range (8)]
for i in range(0,8):
     for j in range(0,8):
          for key in Codon:
               Freq.append((CodonFreq[i][key] - CodonFreq[j][key])**2)
          CodonMatrix[i][j] = sum(Freq)
          Freq = []

np.savetxt("CodonFreq.txt", CodonMatrix)

Dicodon = CountDicodonFreq(findCoding(Lactococcus_phage))
DicodonFreq = []
DicodonFreq.append(CountDicodonFreq(findCoding(Lactococcus_phage)))
DicodonFreq.append(CountDicodonFreq(findCoding(Escherichia_phage)))
DicodonFreq.append(CountDicodonFreq(findCoding(Streptococcus_phage)))
DicodonFreq.append(CountDicodonFreq(findCoding(Cellulophaga_phage)))
DicodonFreq.append(CountDicodonFreq(findCoding(coronavirus)))
DicodonFreq.append(CountDicodonFreq(findCoding(adenovirus)))
DicodonFreq.append(CountDicodonFreq(findCoding(Variola_virus)))
DicodonFreq.append(CountDicodonFreq(findCoding(herpesvirus)))

Freq = []

DicodonMatrix = [[0 for i in range(8)] for j in range (8)]
for i in range(0,8):
     for j in range(0,8):
          for key in Dicodon:
               Freq.append((DicodonFreq[i][key] - DicodonFreq[j][key])**2)
          DicodonMatrix[i][j] = sum(Freq)
          Freq = []

np.savetxt("DicodonFreq.txt", DicodonMatrix)


"""
Name: <Olivia Bianco>
<Lab11>.py

Problem: <Creating a three door game>

Certification of Authenticity:
<I certify that this assignment is entirely my own work. Using graphics.>
"""

from lab10.button import Button
from lab10.door import Door
from random import randint
from graphics import GraphWin, Text, Rectangle, Point

def three_door_game():
    win = GraphWin("Three Door Game", 700, 700)
    win.setBackground("white")
    door_1 = Door(Rectangle(Point(150, 200), Point(250, 600)), "Door 1")  # Drawing each door
    door_1.color_door("salmon4")
    door_1.draw(win)
    door_2 = Door(Rectangle(Point(300, 200), Point(400, 600)), "Door 2")
    door_2.color_door("salmon4")
    door_2.draw(win)
    door_3 = Door(Rectangle(Point(450, 200), Point(550, 600)), "Door 3")
    door_3.color_door("salmon4")
    door_3.draw(win)
    quit_button = Button(Rectangle(Point(400, 50), Point(550, 150)), "Quit")  # Drawing the exit button
    quit_button.draw(win)
    score_wins = Rectangle(Point(50, 50), Point(150, 150))  # drawing the scoreboards
    score_wins.draw(win)
    wins_text = Text(Point(100, 40), "Wins")
    wins_text.draw(win)
    score_losses = Rectangle(Point(150, 50), Point(250, 150))
    score_losses.draw(win)
    losses_text = Text(Point(200, 40), "Losses")
    losses_text.draw(win)
    instructions = Text(Point(350, 650), "Click to guess which is the secret door!")
    instructions.draw(win)
    begin_text = Text(Point(325, 175), "I have a secret door")
    begin_text.draw(win)

    play_again = Text(Point(350, 650), "click anywhere to play again.")
    win_msg = Text(Point(325, 175), "you win!")
    loss_msg = Text(Point(325, 175), "you lost.")
    wins_acc = []  # initializing the accumulator
    losses_acc = []
    win_cen = score_wins.getCenter()
    w_x, w_y = win_cen.getX(), win_cen.getY()
    wins_num = Text(Point(w_x, w_y), "")
    wins_num.setText(len(wins_acc))
    wins_num.draw(win)
    loss_cen = score_losses.getCenter()
    l_x, l_y = loss_cen.getX(), loss_cen.getY()
    loss_num = Text(Point(l_x, l_y), "")
    loss_num.setText(len(losses_acc))
    loss_num.draw(win)

    secret_num = randint(1, 3)  # setting the secret door
    if secret_num == 1:
        door_1.set_secret(True)
    if secret_num == 2:
        door_2.set_secret(True)
    if secret_num == 3:
        door_3.set_secret(True)

    pt = win.getMouse()
    while not quit_button.is_clicked(pt):
        instructions.undraw()
        play_again.draw(win)
        begin_text.undraw()
        if door_1.is_clicked(pt) and door_1.is_secret():
            door_1.color_door("green")
            wins_acc.append("w")
            wins_num.setText(len(wins_acc))
            win_msg.draw(win)
        elif door_2.is_clicked(pt) and door_2.is_secret():
            door_2.color_door("green")
            wins_acc.append("w")
            wins_num.setText(len(wins_acc))
            win_msg.draw(win)
        elif door_3.is_clicked(pt) and door_3.is_secret():
            door_3.color_door("green")
            wins_acc.append("w")
            wins_num.setText(len(wins_acc))
            win_msg.draw(win)
        else:
            loss_msg.draw(win)
            if not door_1.is_secret() and door_1.is_clicked(pt):
                if door_2.is_secret():
                    door_2.color_door("green")
                if door_3.is_secret():
                    door_3.color_door("green")
                door_1.color_door("red")
                losses_acc.append("l")
                loss_num.setText(len(losses_acc))
            elif not door_2.is_secret() and door_2.is_clicked(pt):
                if door_1.is_secret():
                    door_1.color_door("green")
                if door_3.is_secret():
                    door_3.color_door("green")
                door_2.color_door("red")
                losses_acc.append("l")
                loss_num.setText(len(losses_acc))
            elif not door_3.is_secret() and door_3.is_clicked(pt):
                if door_1.is_secret():
                    door_1.color_door("green")
                if door_2.is_secret():
                    door_2.color_door("green")
                door_3.color_door("red")
                losses_acc.append("l")
                loss_num.setText(len(losses_acc))
        pt = win.getMouse()
        if quit_button.is_clicked(pt):
            win.close()
        else:
            door_1.color_door("salmon4")
            door_2.color_door("salmon4")
            door_3.color_door("salmon4")
            win_msg.undraw()
            loss_msg.undraw()
            play_again.undraw()
            instructions.draw(win)
            begin_text.draw(win)
            pt = win.getMouse()

    win.close()

three_door_game()


from django.urls import path
from django.contrib.auth.decorators import login_required

from .views import BlogListView, BlogCreateView, BlogPostDeleteView, BlogDetailView, BlogUpdateView

app_name = 'blog'
urlpatterns = [
    path('', login_required(BlogListView.as_view()), name='home'),
    path('create/', login_required(BlogCreateView.as_view()), name='create'),
    path('delete/<int:pk>', login_required(BlogPostDeleteView.as_view()), name='delete'),
    path('details/<slug:slug>', login_required(BlogDetailView.as_view()), name='details'),
    path('update/<slug:slug>', login_required(BlogUpdateView.as_view()), name='update'),
]


from subprocess import Popen, CREATE_NEW_CONSOLE

print('Сокет-сервер запущен!')  # запускаем сервер отдельным процессом
p_list = [Popen('python server.py', creationflags=CREATE_NEW_CONSOLE)]

print('3 Сокет-клиента запущены!')  # запускаем 3 клиента отдельными процессами
p_list = [*p_list, *[Popen('python client.py', creationflags=CREATE_NEW_CONSOLE) for _ in range(3)]]

while input("Закрыть клиентов и выйти (q) ").lower() != 'q':  # Выход: <q><enter>
    ...
[p.kill() for p in p_list]  # удаляем запущенные процессы


"""mysite URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import *
from django.contrib import admin
from django.views.generic import RedirectView
from reading import views
from django.conf.urls.static import static
from django.conf import settings
admin.autodiscover()

urlpatterns = [
    url(r'^$', views.index),
    url(r'^admin/', include(admin.site.urls)),
    # url(r'^blog/', include('blog.urls')),
    url(r'^search/', views.search),
    url(r'^download/', views.download),
    url(r'^register/', views.register),
    url(r'^login/', views.userlogin),
    url(r'^logout/', views.userlogout),
    url(r'^changepassword/', views.changepassword),
    url(r'^uploadfile/', views.uploadfile),
    url(r'^upload/', views.upload),
    url(r'^dotask/', views.dotask),
    url(r'^contact/', views.contact),
    url(r'^createtask/', views.createtask),
    url(r'^task/', views.task),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)


################################
#                               #
#   PSI Battle                  #
#   20201002 -                  #
#   Zed & JHarttech             #
#                               #
################################
#   Back Burner                 #
#                               #
#   Pyrokinesis -poison         #
#   GUI                         #
#                               #
###############################
#   Known Issues                #
#   ************                #
#                               #
#   pType() only collects on    #
#   the second go round         #
#                               #
#

import random
from os import system, name

psiList = ["eshot","bes","tele","abs"]
enemypsi = (psiList[random.randint(0,3)])

helpList = ["Enerny Shot    : ","Beserker       : ","Telekinesis    : ","Absorbtion     : "]
helpinfo = ["Energy Shot Info","Beserker Info","Telekinesis Info","Absoption Info"]

#stats are given a base stat of 5, and the player can put up to 5 extra points into each stat.
pool = 5
stre = 5
awar = 5
fort = 5
char = 5
inte = 5
quic = 5
luck = 5

class Engine():

    def __init__(self,pName,psi):
        self.pName = pName
        self.psi = psi

    def start():
        print("Welcome.\n")
        print("Would you like to create a new game")
        nl = input("or Load a saved one? : ")
        onepass = False
        while(onepass == False):
            while(nl.lower() not in ("load","new")):
                nl = input("(new / load) : ")
            if(nl.lower() == "load"):
                onepass = True
                Engine.clear()
                ###### Load Goes Here ######
                Char.name()
            elif(nl.lower() == "new"):
                onepass = True
                print("\n## New Game ##")
                Engine.clear()
                Char.name()

    def clear():

        # for windows
        if name == 'nt':
            _ = system('cls')

        # for mac and linux
        else:
            _ = system('clear')

class Char():

    def name():
        pName = ""
        while(not pName.strip()):
                pName = input("What is your name? : ")
                Engine.clear()
        pName = str(pName)
        Engine.clear()
        return pName

    def pType():
        psi = None
        print("""What Type of Psychic Power do you Desire?\n
                (1) Energy Shot     (2) Beserker
                (3) Telekinesis     (4) Absorption
                (5) Help\n""")
        psi = input("Please enter a number given : ")
        while(True):
            try:
                psi = int(input("Please enter a number given : "))
            except(ValueError):
                continue
            else:
                if(psi > 5):
                    Engine.clear()
                    Char.pType()
                else:
                    break
        if(psi == 5):
            Engine.clear()
            for x,y in zip(helpList,helpinfo):
                print(x,y)
            input("\nPress Enter to Continue : ")
            Engine.clear()
            Char.pType()

        psi -= 1
        print("#######", psiList[psi])
        print("####### Enemy =", enemypsi)
        input("#######dev pause for info")
        Engine.clear()
        return psi

    def cr():
        global initChoice
        choiceTest = None
        while(choiceTest == None):
            print("Customize (C), Randomize (R)")
            initChoice = input("Would you like to customize a character or have one randomized for you?: ")
            if(initChoice.lower() == "c" or initChoice.lower() == "r"):
                choiceTest = True
            else:
                print("\n###############################################################")
                print("# Please enter either a C to customize, or an R to randomize. #")
                print("###############################################################")
        if(initChoice.lower() == "c"):
            Engine.clear()
            Char.custom()
        else:
            Engine.clear()
            Char.randChar()

    def statTable():
        if(pool > 0):
            print("You have", pool," character points left to spend.")
            print("\nName         : ", pName)
            print("Strength     : ", stre)
            print("Awareness    : ", awar)
            print("Fortitude    : ", fort)
            print("Charisma     : ", char)
            print("Intellect    : ", inte)
            print("Quickness    : ", quic)
            print("Luck         : ", luck)
        else:
            print("Name         : ", pName)
            print("\nStrength     : ", stre)
            print("Awareness    : ", awar)
            print("Fortitude    : ", fort)
            print("Charisma     : ", char)
            print("Intellect    : ", inte)
            print("Quickness    : ", quic)
            print("Luck         : ", luck)

    def custom():
        while(pool > 0):
            netPoints = stre + awar + fort + char + inte + quic + luck
            print("Stats must be between 1 and 10")
            Char.statTable()
            Char.calcStats()
            print("Total        : ",netPoints)
            #player is given the option to add to a stat or subtract from one.
            addsub = input("\nWould you like to add or subtract form a stat? (+/-): ")
            if(addsub == "+"):
                #player is chosing what stat to add to.
                stat = input("\nWhat stat? (First Letter): ")
                if(stat == "s" or stat == "S"):
                    stre += 1
                    pool -= 1
                    if(stre == 11):
                        stre -= 1
                        pool += 1
                elif(stat == "a" or stat == "A"):
                    awar += 1
                    pool -= 1
                    if(awar == 11):
                        perc -= 1
                        pool += 1
                elif(stat == "f" or stat == "F"):
                    fort += 1
                    pool -= 1
                    if(fort == 11):
                        fort -= 1
                        pool += 1
                elif(stat == "c" or stat == "C"):
                    char += 1
                    pool -= 1
                    if(char == 11):
                        char -= 1
                        pool += 1
                elif(stat == "i" or stat == "I"):
                    inte += 1
                    pool -= 1
                    if(inte == 11):
                        inte -= 1
                        pool += 1
                elif(stat == "q" or stat == "Q"):
                    quic += 1
                    pool -= 1
                    if(quic == 11):
                        agil -= 1
                        pool += 1
                elif(stat == "l" or stat == "L"):
                    luck += 1
                    pool -= 1
                    if(luck == 11):
                        luck -= 1
                        pool += 1
                else:
                    print("\n##########################################")
                    print("# Please use the first letter of a stat. #")
                    print("##########################################")
            elif(addsub == "-"):
                #player is chosing what stat to subtract from.
                stat = input("\nWhat stat? (First Letter): ")
                if(stat == "s" or stat == "S"):
                    stre -= 1
                    pool += 1
                    if(stre == 0):
                        stre += 1
                        pool -= 1
                elif(stat == "a" or stat == "A"):
                    awar -= 1
                    pool += 1
                    if(perc == 0):
                        perc += 1
                        pool -= 1
                elif(stat == "f" or stat == "F"):
                    fort -= 1
                    pool += 1
                    if(fort == 0):
                        fort += 1
                        pool -= 1
                elif(stat == "c" or stat == "C"):
                    char -= 1
                    pool += 1
                    if(char == 0):
                        char += 1
                        pool -= 1
                elif(stat == "i" or stat == "I"):
                    inte -= 1
                    pool += 1
                    if(inte == 0):
                        inte += 1
                        pool -= 1
                elif(stat == "q" or stat == "Q"):
                    quic -= 1
                    pool += 1
                    if(quic == 0):
                        agil += 1
                        pool -= 1
                elif(stat == "l" or stat == "L"):
                    luck -= 1
                    pool += 1
                    if(luck == 0):
                        luck += 1
                        pool -= 1
                else:
                    print("\n##########################################")
                    print("# Please use the first letter of a stat. #")
                    print("##########################################")
            else:
                print("\n##############################")
                print("# Please enter either + or - #")
                print("##############################")
        Char.statTable()
        Char.calcStats()
        Char.saveChar()
        print("\nThis is now your character.")
        input("\nPress Enter to exit.")

    def randChar():
        global stre
        global awar
        global fort
        global char
        global inte
        global quic
        global luck
        test = False
        while(test != True):
            stre = random.randint(1,10)
            awar = random.randint(1,10)
            fort = random.randint(1,10)
            char = random.randint(1,10)
            inte = random.randint(1,10)
            quic = random.randint(1,10)
            luck = random.randint(1,10)
            netPoints = stre + awar + fort + char + inte + quic + luck
            if(netPoints >= 30 and netPoints <= 45):
                test = True
            elif(netPoints == 60):
                #That's a 0.00001% chance of rolling max stats
                test = True
        print("Name         : ", pName)
        print("Level        : ", pLevel)
        print("Strength     : ", stre)
        print("Awareness    : ", awar)
        print("Fortitude    : ", fort)
        print("Charisma     : ", char)
        print("Intellect    : ", inte)
        print("Quickness    : ", quic)
        print("Luck         : ", luck)
        print("Total        : ", netPoints)

    def calcStats():
        global maxHP
        global pHP
        global maxEnergy
        global energy
        global critChance
        global critDam
        global meleeDam
        global physDef
        global spDef
        maxHP = fort * 10
        #
        #if class == bes then maxhp = fort * 15
        #
        pHP = maxHP
        maxStam = int((fort * quic) / 2)
        stam = maxStam
        maxMana = int((inte * char) / 2)
        mana = maxMana
        skillRate = int(10 + (inte / 2))
        maxCarry = (150 + (stre * 10))
        critChance = int(luck / 100)
        critDam = 2
        meleeDam = int(stre / 2)
        physDef = 0
        spDef = 0
        print("\nHP           : ", pHP,"/", maxHP)
        print("Stamina      : ", stam,"/", maxStam)
        print("Mana         : ", energy,"/", maxEnergy)
        print("         ____________")
        print("        |TEMP DEV BOX|")
        print("=============================")
        print("Skill Rate   : ", skillRate)
        print("Carry Weight : ", maxCarry)
        print("Crit Chance  : ", critChance, "%")
        print("Crit Damage  : ", critDam)
        print("Melee Damage : ", meleeDam)
        print("Phys. Def.   : ", physDef)
        print("Psi Def.     : ", spDef)
        print("=============================")

    def saveChar():
        save = open(pName + ".txt", "a+")
        save.write(str(pName) + ":")
        save.write(str(stre) + ":")
        save.write(str(awar) + ":")
        save.write(str(fort) + ":")
        save.write(str(char) + ":")
        save.write(str(inte) + ":")
        save.write(str(quic) + ":")
        save.write(str(luck) + ":")
        save.write(str(maxHP) + ":")
        save.write(str(pHP) + ":")
        save.write(str(maxStam) + ":")
        save.write(str(stam) + ":")
        save.write(str(maxMana) + ":")
        save.write(str(mana) + ":")
        save.write(str(critChance) + ":")
        save.write(str(critDam) + ":")
        save.write(str(meleeDam) + ":")
        save.write(str(physDef) + ":")
        save.write(str(spDef) + "\n")
        save.close()

Engine.clear()
Engine.start()
Char.pType()
Char.cr()


from MultisizerReader import MultiSizerReader
import os

#Get all spread sheet files in fodler and create multisizer files for each
folder = "./Data_Organised/Log_Comparison"
allFiles = os.listdir(folder)
multiSizerFiles = [allFiles[i] for i in range(len(allFiles)) if allFiles[i].endswith(".XLS")]
data = []
for files in multiSizerFiles:
    data.append(MultiSizerReader(path=os.path.join(folder,files)))
#Extract ODs from file names
groupList = [(d.name) for d in data]

#************************ PLOT EVERYTHING **********************************
#Plotting all plots as individual traces
labels = ["Linear PE ","Linear ","Log "]
#data = [data[0]]
#labels = [labels[0]]
MultiSizerReader.plotData(data,labels=labels,logAxis=False,smoothing=15 ,spacing=0.025,xLims=(0,10),
        legend=False,title="Log vs Linear Comparison",joymode= False,logNormalFits=True)

#************************* Plot summed hists by OD *************************
#combinedData,combinedODs = MultiSizerReader.sumByGroup(data,ODList)
#MultiSizerReader.plotData(combinedData,combinedODs,labels=["OD: {0} ".format(combinedODs[i]) for i in range(len(combinedODs))],legend=True,alpha = 1.0,title = "MG1655 Summed cell size growth curve",joymode=False)


import subprocess
import optparse
import re

def get_user_input():
    parse_object = optparse.OptionParser()
    parse_object.add_option("-i","--interface",dest="interface",help="change to interface")
    parse_object.add_option("-m","--mac",dest="mac_address",help="new mac address")
    return parse_object.parse_args()

def change_mac_address(p_interface,p_mac_address):
    subprocess.call(["ifconfig",p_interface,"down"])
    subprocess.call(["ifconfig",p_interface,"hw","ether",p_mac_address])
    subprocess.call(["ifconfig",p_interface,"up"])

def control_new_mac(p_interface):
    ifconfig = subprocess.check_output(["ifconfig",p_interface])
    new_mac = re.search(r"\w\w:\w\w:\w\w:\w\w:\w\w:\w\w",str(ifconfig))

    if new_mac:
        return new_mac.group(0)
    else:
        return None

print("mac changer started !")
(user_inputs,arguments) = get_user_input()
change_mac_address(user_inputs.interface,user_inputs.mac_address)
finalized_mac = control_new_mac(str(user_inputs.interface))

if finalized_mac == user_inputs.mac_address:
    print("success\n\n")
    subprocess.call(["ifconfig",user_inputs.interface])
else:
    print("error")


#/usr/bin/env python
# -*- coding: utf-8 -*-
# processing multiple root json as custom json or csv
import json
import csv
from UnicodeWriter import UnicodeWriter

with open('4s_venues.json', 'r') as f, open('output_file.csv', 'w') as fp:

    writer = UnicodeWriter(fp)

    for i, line in enumerate(f):
        response = json.loads(line)

        uid = response['venue']['id']
        name = response['venue']['name']
        address = response['venue']['location']['address']
        city = reponse['venue']['location']

        writer.writerow([uid, text])


import math
import cv2
import numpy as np
import os
import yaml
from yaml.loader import SafeLoader
from math import sqrt
import Jetson.GPIO as GPIO
import time

class YOLO_Pred:
    def __init__(self, onnx_model, data_yaml):
        with open('data.yaml', mode='r') as f:
            data_yaml = yaml.load(f, Loader=SafeLoader)

        self.labels = data_yaml['names']
        self.nc = data_yaml['nc']
        # Rough estimation of lane width on Indian roads in pixels
        lane_width_pixels = 350  # Adjust this value based on your estimation

        # Rough estimation of lane width on Indian roads in centimeters
        lane_width_cm = 350  # Adjust this value based on your estimation

        # Calculate the scale factor for distance estimation
        self.scale_factor = lane_width_pixels / lane_width_cm
        self.yolo = cv2.dnn.readNetFromONNX('./Model/weights/best.onnx')
        self.yolo.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)  # Use CUDA backend for GPU acceleration
        self.yolo.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)
        self.yolo.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA_FP16)  # Use FP16 for even faster inference
        self.confidence_threshold = 0.2  # You can adjust this threshold

    def angle_to_bottom_center(self, x, y, w, h, image_w, image_h):
        # Calculate the center of the bounding box
        center_x = x + w // 2
        center_y = y + h

        # Calculate the angle between the bottom center of the image and the center of the bounding box
        angle = math.atan2(center_x - image_w // 2, image_h - center_y)

        return angle

    def calculate_distance(self, x, y, w, h, image_w, image_h):
        # Calculate the angle between the bottom center of the image and the center of the bounding box
        angle = math.atan2((x + w / 2) - (image_w / 2), self.camera_focal_length)

        # Calculate the distance in meters using the angle and camera focal length
        distance_meters = self.actual_lane_width_meters / (2 * math.tan(angle / 2))

        return distance_meters

    def find_closest_person(self, boxes, distances, angles):
        if distances:
            closest_distance = min(distances)
            closest_index = distances.index(closest_distance)
        else:
            closest_index = -1

        return closest_index

    def generate_colors(self):
        np.random.seed(10)
        colors = np.random.randint(100, 255, size=(self.nc, 3)).tolist()
        return colors

    def predictions(self, image):
        GPIO.setmode(GPIO.BOARD)

        self.red_led = 12
        self.yellow_led = 7
        self.green_led = 11
        self.motor = 31

        GPIO.setup(self.red_led, GPIO.OUT)
        GPIO.setup(self.yellow_led, GPIO.OUT)
        GPIO.setup(self.green_led, GPIO.OUT)
        GPIO.setup(self.motor,GPIO.OUT)

        GPIO.output(self.motor, GPIO.LOW)

        row, col, d = image.shape
        max_rc = max(row, col)
        input_image = np.zeros((max_rc, max_rc, 3), dtype=np.uint8)
        input_image[0:row, 0:col] = image

        input_wh_yolo = 640
        blob = cv2.dnn.blobFromImage(input_image, 1 / 255, (input_wh_yolo, input_wh_yolo), swapRB=True, crop=False)
        self.yolo.setInput(blob)
        preds = self.yolo.forward()

        text_color = (0, 255, 0)
        # Filter detections based on confidence score (0.2) and probability score (0.25)
        detections = preds[0]
        boxes = []
        confidences = []
        classes = []
        image_w, image_h = input_image.shape[:2]
        x_factor = image_w / input_wh_yolo
        y_factor = image_h / input_wh_yolo

        for i in range(len(detections)):
            row = detections[i]
            confidence = row[4]
            if confidence > 0.2:
                class_score = row[5:].max()
                class_id = row[5:].argmax()
                if class_score > 0.25:
                    cx, cy, w, h = row[0:4]
                    # Construct bounding box from four values
                    left = int((cx - 0.5 * w) * x_factor)
                    top = int((cy - 0.5 * h) * y_factor)
                    width = int(w * x_factor)
                    height = int(h * y_factor)
                    box = np.array([left, top, width, height])
                    confidences.append(confidence)
                    boxes.append(box)
                    classes.append(class_id)

        boxes_np = np.array(boxes).tolist()
        confidences_np = np.array(confidences).tolist()

        # Non-maximum suppression
        index = cv2.dnn.NMSBoxes(boxes_np, confidences_np, 0.15, 0.25)

        distances = []
        angles_text = []

        for ind in index:
            x, y, w, h = boxes_np[ind]

            # Calculate the center of the bounding box
            center_x = x + w // 2
            center_y = y + h

            # Calculate the angle to the bottom center and add it to angles_text
            angle = self.angle_to_bottom_center(x, y, w, h, image_w, image_h)

            if angle < 0:
                angle_text = "Left"
            elif angle >= 0:
                angle_text = "Right"
            elif angle< 150 and angle< 90:
                angle_text = "Middle"

            # Calculate the distance in meters using the scale factor
            distance_pixels = sqrt((center_x - image_w // 2) ** 2 + (center_y - image_h) ** 2)
            distance_meters = distance_pixels / (self.scale_factor * 100)  # Convert from centimeters to meters
            distances.append(distance_meters)

            angles_text.append(angle_text)

        closest_warning = ""  # Initialize closest_warning here
        colors = self.generate_colors()

        red_detected = False
        yellow_detected = False
        green_detected = False

        for i, ind in enumerate(index):
            x, y, w, h = boxes_np[ind]
            bb_conf = int(confidences_np[ind] * 100)
            classes_id = classes[ind]
            class_name = self.labels[classes_id]

    # Calculate the angle to the bottom center and add it to angles_text
            angle = self.angle_to_bottom_center(x, y, w, h, image_w, image_h)

            if angle < 0:
                angle_text = "Left"
            elif angle >= 0:
                angle_text = "Right"
            else:
                angle_text = "Middle"

            # Calculate the distance in meters using the scale factor
            distance_pixels = sqrt((center_x - image_w // 2) ** 2 + (center_y - image_h) ** 2)
            distance_meters = distance_pixels / (self.scale_factor * 100)  # Convert from centimeters to meters
            distances.append(distance_meters)
            # Draw the bounding box
            cv2.rectangle(image, (x, y), (x + w, y + h), colors[classes_id], 2)
            cv2.rectangle(image, (x, y - 30), (x + w, y), colors[classes_id], -1)

            # Add text for class, distance, and angle at the top
            # Add text for class, distance, and angle at the top

            # Add text for distance in bold letters on top of the bounding box
            distance_text = f'  {distances[i]:.2f} m'
            text_x = x + w // 2 - len(distance_text) * 6  # Adjust the X-coordinate based on text length
            text_y = y + h + 20  # Adjust the Y-coordinate as needed
            cv2.putText(image, distance_text, (text_x, text_y), cv2.FONT_HERSHEY_COMPLEX, 0.4, (0, 0, 0), 1)

            # Add text for angle at the bottom
            text_x = x
            text_y = y + h + 45  # Adjust this value as needed to control the vertical position of the text
            text_color = (0, 0, 255)
            angle_text = angles_text[i]  # Use angles_text directly
            cv2.putText(image, angle_text, (text_x, text_y), cv2.FONT_HERSHEY_PLAIN, 0.7, (0, 0, 255), 1)

            if i < len(distances):  # Make sure i is within the valid range
                if distances[i] <= 7:
                    # Display a warning message for the closest person within 7 meters
                    closest_warning = f"The person on the {angle_text} is too close!"
                    text_color = (0, 0, 255)  # Set text color to red

                    # Change the color of the bounding box to red
                    cv2.rectangle(image, (x, y), (x + w, y + h), (255, 0, 0), 2)
                    cv2.rectangle(image, (x, y - 30), (x + w, y), (255, 0, 0), -1)
                    red_detected = True
                elif distances[i] > 7 and distances[i] <= 10:
                    # Change the color of the bounding box to yellow
                    cv2.rectangle(image, (x, y), (x + w, y + h), (255, 165, 0), 2)
                    cv2.rectangle(image, (x, y - 30), (x + w, y), (255, 165, 0), -1)
                    closest_warning = f"Careful!"
                    yellow_detected = True
                else:
                    # No warning message for safe distances
                    closest_warning = "Looks safe, keep moving"
                    text_color = (0, 255, 0)  # Set text color to green

                    # Change the color of the bounding box to green
                    cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
                    cv2.rectangle(image, (x, y - 30), (x + w, y), (0, 255, 0), -1)
                    green_detected = True
        # Draw the "Looks safe, keep moving" or other warning text
        text_x = 10  # Adjust the X-coordinate as needed
        text_y = 30  # Adjust the Y-coordinate as needed
        cv2.putText(image, closest_warning, (text_x, text_y), cv2.FONT_HERSHEY_PLAIN, 1, text_color, 2)

        # Convert the image to BGR format for saving
        img_pred = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)

        if red_detected:
            GPIO.output(self.red_led, GPIO.HIGH)
            GPIO.output(self.yellow_led, GPIO.LOW)
            GPIO.output(self.green_led, GPIO.LOW)
            GPIO.output(self.motor, GPIO.LOW)
        elif yellow_detected:
            GPIO.output(self.red_led, GPIO.LOW)
            GPIO.output(self.yellow_led, GPIO.HIGH)
            GPIO.output(self.green_led, GPIO.LOW)
            GPIO.output(self.motor, GPIO.LOW)
        else:
            GPIO.output(self.red_led, GPIO.LOW)
            GPIO.output(self.yellow_led, GPIO.LOW)
            GPIO.output(self.green_led, GPIO.HIGH)
            GPIO.output(self.motor, GPIO.HIGH)
            time.sleep(2)  # Delay for 5 seconds
            GPIO.output(self.motor, GPIO.LOW)

        return img_pred, closest_warning


from typing import Type, Optional

from catboost import CatBoostClassifier
from sklearn.model_selection import train_test_split
import pandas as pd

from instacart.decorators.camel2snake import camel2snake
from instacart.dto.mixed.dto import MixedProductsAndTransactionsDto
from instacart.bridge.bridge import InstaCartBridgeConfigurator
from instacart.abstracts._features.abc import _instaCartFeaturesAbstractFabric, _InstaCartFeaturesAbstractFabric
from instacart.fabrics.features.catboost.fabric import catBoostClassifierFeaturesFabric, CatBoostClassifierFeaturesFabric
from instacart.handlers.features.catboost.main.feature import MainFeature

class InstaCartCatBoostClassifier(CatBoostClassifier):

    @classmethod
    @camel2snake
    def name(cls):
        return __class__.__name__

    @property
    def mix(self) -> MixedProductsAndTransactionsDto:
        return self._mix

    def __init__(self, mix: MixedProductsAndTransactionsDto, *args, **kwargs) -> None:
        CatBoostClassifier.__init__(self, *args, **kwargs)
        self._mix = mix

        self.__recommendations = None
        self.__prepared_df = None

    def _prepare_df(
            self,
            bridge: Type[InstaCartBridgeConfigurator] = InstaCartBridgeConfigurator,
            features_abc: _InstaCartFeaturesAbstractFabric = _instaCartFeaturesAbstractFabric,
            features_fabric: CatBoostClassifierFeaturesFabric = catBoostClassifierFeaturesFabric
    ) -> pd.DataFrame:
        futures = list()
        for feature_name, _ in features_fabric.handlers.items():
            feature_class = bridge(
                abstract=features_abc,
                fabric_name=features_fabric.name(),
                handler_name=feature_name
            ).produce_handler()
            feature = feature_class(mix=self.mix)
            futures.append(feature.prepare_df())
        df = pd.DataFrame()
        for future in futures:
            feature_df: pd.DataFrame = future.result()
            if df.empty:
                df = feature_df
            else:
                df = df.merge(feature_df, how='left', on=[self.mix.USER_ID, self.mix.PRODUCT_ID])
        return df

    def instacart_train(self) -> None:
        self.__prepared_df = self._prepare_df()
        x = self.__prepared_df.drop(columns=MainFeature.name()).values
        y = self.__prepared_df[MainFeature.name()].values
        _x, X, _y, Y = train_test_split(x, y, test_size=.01, stratify=y)
        self.fit(_x, _y)

    def instacart_predict(self, is_save_to_csv: bool = False, csv_path: Optional[str] = None):
        df = self.__prepared_df.drop(columns=MainFeature.name())
        self.__recommendations = self.predict_proba(df.values)
        self.__recommendations = pd.concat(
            [
                df[[self.mix.USER_ID, self.mix.PRODUCT_ID]],
                pd.Series(self.__recommendations[:, 1], name='proba')
            ],
            axis=1
        ).sort_values(by=['user_id', 'proba'], ascending=[True, False])
        if is_save_to_csv:
            df = self.__recommendations.groupby(['user_id'], as_index=False).head(10)
            output = df.groupby(['user_id'], as_index=False).agg(lambda product_ids: ' '.join(str(value) for value in list(product_ids)))[['user_id', 'product_id']]
            output.to_csv(csv_path, index=False)


import imp
from mtcnn import MTCNN
import cv2
import os
import threading
import time

os.chdir('/home/devai01/Me/python-image-processing/')
# os.chdir('/home/devai01/Me/')
cap = cv2.VideoCapture('people_check.mp4')
detector = MTCNN()

def draw(image, face):
    for i in range(len(face)):
        person = face[i]
        x, y, width, height = person['box']
        image = cv2.rectangle(image, (x, y), (x+width, y+height), (0, 155, 255), 2)

    return image

        # for key, value in person['keypoints'].items():
        #     cv2.circle(image, value, 2, (0, 155, 255), 2)
    # cv2.waikey(1)
    # os.chdir('/home/devai01/Me/python-image-processing/results')
    # cv2.imwrite("face-detection-MTCNN.jpg", image)

while True:
    result, img = cap.read()
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    img = cv2.resize(img, (640,480))
    faces = detector.detect_faces(img)
    # t2 = threading.Thread
    # t1 = threading.Thread(target=draw,args=(img,faces))
    # t1.start
    img = draw(img, faces)
    cv2.imshow("image", img)
    if cv2.waitKey(1) == ord('q'):
        break


import unittest

import os
import env
from binance.client import Client as ClientBinance
from coinbase.wallet.client import Client as ClientCoinbase

import importlib

class TestConfig(unittest.TestCase):

    def test_check_presence_of_Binance_API_Key(self):
        key = os.getenv('Binance_API_Key')
        self.assertIsNotNone(key)
        self.assertIsNot(key, "")

    def test_check_presence_of_Binance_API_Secret(self):
        key = os.getenv('Binance_API_Secret')
        self.assertIsNotNone(key)
        self.assertIsNot(key, "")

    def test_check_Binance_valid_credentials(self):
        error_raised = False

        api_key = os.getenv('Binance_API_Key')
        api_secret = os.getenv('Binance_API_Secret')

        try:
            client = ClientBinance(api_key, api_secret, {"verify": True, "timeout": 20})
            client.get_all_orders(symbol='BNBBTC', limit=1)
        except:
            error_raised = True
        self.assertFalse(error_raised, "Invalid Bianance credentials")

    def test_check_presence_of_Coinbase_API_Key(self):
        key = os.getenv('Coinbase_API_Key')
        self.assertIsNotNone(key)
        self.assertIsNot(key, "")

    def test_check_presence_of_Coinbase_API_Secret(self):
        key = os.getenv('Coinbase_API_Secret')
        self.assertIsNotNone(key)
        self.assertIsNot(key, "")

    def test_check_Coinbase_valid_credentials(self):
        error_raised = False

        api_key = os.getenv('Coinbase_API_Key')
        api_secret = os.getenv('Coinbase_API_Secret')

        try:
            client = ClientCoinbase(api_key, api_secret)
            client.get_accounts()
        except:
            error_raised = True
        self.assertFalse(error_raised, "Invalid Coinbase credentials")

if __name__ == '__main__':
    unittest.main()