# Copyright 2022 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================

import numpy as np
import pytest
import mindspore.context as context
from mindspore import Tensor
from mindspore.ops import functional as F

def test_batch_norm_forward_functional(nptype):
    """
    Feature: test batch_norm forward for given input dtype.
    Description: test inputs for given input dtype.
    Expectation: the result match with expected result.
    """
    input_x = Tensor(np.ones([2, 2]).astype(nptype))
    running_mean = Tensor(np.ones([2]).astype(nptype))
    running_var = Tensor(np.ones([2]).astype(nptype))
    weight = Tensor(np.ones([2]).astype(nptype))
    bias = Tensor(np.ones([2]).astype(nptype))
    output = F.batch_norm(input_x, running_mean, running_var, weight, bias)
    expected = np.array([[1., 1.], [1., 1.]]).astype(nptype)
    np.testing.assert_array_almost_equal(output.asnumpy(), expected)

@pytest.mark.level0
@pytest.mark.platform_arm_ascend_training
@pytest.mark.platform_x86_ascend_training
@pytest.mark.env_onecard
def test_batch_norm_forward_float32_functional():
    """
    Feature: test batch_norm forward.
    Description: test float32 inputs.
    Expectation: the result match with expected result.
    """
    context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
    test_batch_norm_forward_functional(np.float32)
    context.set_context(mode=context.PYNATIVE_MODE, device_target="Ascend")
    test_batch_norm_forward_functional(np.float32)


import sys
import math
import torch
import random
import threading
import logging
from torch.utils.data import Dataset, DataLoader
from feature import get_librosa_mfcc, get_librosa_melspectrogram, get_melspectrogram_feature

logger = logging.getLogger('root')
FORMAT = "[%(asctime)s %(filename)s:%(lineno)s - %(funcName)s()] %(message)s"
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG, format=FORMAT)
logger.setLevel(logging.INFO)

PAD = 0
N_FFT = 512
SAMPLE_RATE = 16000

target_dict = dict()

def load_targets(path):
    with open(path, 'r') as f:
        for no, line in enumerate(f):
            key, target = line.strip().split(',')
            target_dict[key] = target

# 정답을 리스트 형식으로 담아주는 함수
def get_script(filepath, bos_id, eos_id):
    # key : 41_0508_171_0_08412_03.script 중 41_0508_171_0_08412_03 -> label
    key = filepath.split('/')[-1].split('.')[0]
    # 41_0508_171_0_08412_03 에 해당하는 label 텍스트일 듯
    script = target_dict[key]
    # 텍스트를 ' ' 기준으로 나눈다 -> 10 268 10207 와 같이 레이블 되어 있으니까!!
    tokens = script.split(' ')

    # result를 담을 리스트 초기화
    result = list()

    # result에 bos_id로 시작을 표시하는 듯
    # Begin Of Script 일 듯
    result.append(bos_id)

    # 나눈 token들을 result에 추가하는 듯
    for i in range(len(tokens)):
        if len(tokens[i]) > 0:
            result.append(int(tokens[i]))
    # 마지막 End Of Script 표시를 해주는 듯
    result.append(eos_id)
    return result

class BaseDataset(Dataset):
    # wav_paths : wav_path가 모여있는 리스트
    # script_paths : script_path가 모여있는 리스트 script == label
    # bos_id : Begin Of Script -> script의 시작을 표시하는 Number
    # eos_id : End Of Script -> script의 끝을 표시하는 Number
    def __init__(self, wav_paths, script_paths, bos_id = 1307, eos_id = 1308):
        self.wav_paths = wav_paths
        self.script_paths = script_paths
        self.bos_id, self.eos_id = bos_id, eos_id

    def __len__(self):
        return len(self.wav_paths)

    def count(self):
        return len(self.wav_paths)

    def getitem(self, idx):
        # 음성데이터에 대한 feature를 feat에 저장 -> tensor 형식
        feat = get_librosa_mfcc(self.wav_paths[idx], n_mfcc = 40)
        # 리스트 형식으로 label을 저장
        script = get_script(self.script_paths[idx], self.bos_id, self.eos_id)
        return feat, script

def _collate_fn(batch):
    def seq_length_(p):
        return len(p[0])

    def target_length_(p):
        return len(p[1])

    seq_lengths = [len(s[0]) for s in batch]
    target_lengths = [len(s[1]) for s in batch]

    max_seq_sample = max(batch, key=seq_length_)[0]
    max_target_sample = max(batch, key=target_length_)[1]

    max_seq_size = max_seq_sample.size(0)
    max_target_size = len(max_target_sample)

    feat_size = max_seq_sample.size(1)
    batch_size = len(batch)

    seqs = torch.zeros(batch_size, max_seq_size, feat_size)

    targets = torch.zeros(batch_size, max_target_size).to(torch.long)
    targets.fill_(PAD)

    for x in range(batch_size):
        sample = batch[x]
        tensor = sample[0]
        target = sample[1]
        seq_length = tensor.size(0)
        seqs[x].narrow(0, 0, seq_length).copy_(tensor)
        targets[x].narrow(0, 0, len(target)).copy_(torch.LongTensor(target))
    return seqs, targets, seq_lengths, target_lengths

class BaseDataLoader(threading.Thread):
    def __init__(self, dataset, queue, batch_size, thread_id):
        threading.Thread.__init__(self)
        self.collate_fn = _collate_fn
        self.dataset = dataset
        self.queue = queue
        self.index = 0
        self.batch_size = batch_size
        self.dataset_count = dataset.count()
        self.thread_id = thread_id

    def count(self):
        return math.ceil(self.dataset_count / self.batch_size)

    # 큐에 들어가는 batch를 만드는 함수
    def create_empty_batch(self):
        seqs = torch.zeros(0, 0, 0)  #  3차원의 0 벡터
        targets = torch.zeros(0, 0).to(torch.long)
        seq_lengths = list()
        target_lengths = list()
        return seqs, targets, seq_lengths, target_lengths

    def run(self):
        logger.debug('loader %d start' % (self.thread_id))
        while True:
            items = list()

            for i in range(self.batch_size):
                if self.index >= self.dataset_count:
                    break
                #logger.info('BaseDataLoader 들어옴')
                items.append(self.dataset.getitem(self.index))
                self.index += 1

            if len(items) == 0:
                batch = self.create_empty_batch()
                # 큐에 batch 삽입
                self.queue.put(batch)
                break

            random.shuffle(items)

            batch = self.collate_fn(items)
            # 큐에 batch 삽입
            self.queue.put(batch)
        logger.debug('loader %d stop' % (self.thread_id))

# BaseLoader()를 여러 개 호출하는 클래스
class MultiLoader():
    def __init__(self, dataset_list, queue, batch_size, worker_size):
        self.dataset_list = dataset_list
        self.queue = queue
        self.batch_size = batch_size
        self.worker_size = worker_size
        self.loader = list()

        for i in range(self.worker_size):
            self.loader.append(BaseDataLoader(self.dataset_list[i], self.queue, self.batch_size, i))

    def start(self):
        # BaseDataLoader run()을 실행!!
        for i in range(self.worker_size):
            self.loader[i].start()

    def join(self):
        for i in range(self.worker_size):
            self.loader[i].join()


from . import serieslink as sl
from . import seriesdetails as sd

#scraping links
sublinks = ["/list/ls021409819/","/list/ls051600015/?st_dt=&mode=detail&sort=release_date,desc&page=1","/search/title?languages=hi&title_type=tv_series&page=1&sort=release_date,desc&view=advanced&ref_=adv_nxt"]
baselink = "https://www.imdb.com"

def link(seriesname):
    temp=""
    message=""
    for links in sublinks:
        serieslink = sl.getserieslink(baselink,links,seriesname)
        #print(serieslink)
        if(len(serieslink)>0):
            serieslink = baselink+serieslink
            print(serieslink)
            seriesdetails = sd.getseriesdetails(serieslink)
            temp=seriesdetails
            break
    if(len(temp)==0):
        message+= "Status: "
        temp="No Details Available"
        message+=temp
    else:
        message+= "Status: "
        message+=temp
    return message


from datetime import date
from datetime import timedelta
from opengever.dossier.behaviors.dossier import IDossier
from opengever.ogds.base.utils import get_current_org_unit
from opengever.task import TASK_STATE_PLANNED
from opengever.task.activities import TaskAddedActivity
from opengever.task.interfaces import ITaskSettings
from opengever.tasktemplates import INTERACTIVE_USERS
from opengever.tasktemplates.content.templatefoldersschema import sequence_type_vocabulary
from opengever.tasktemplates.interfaces import IDuringTaskTemplateFolderTriggering
from opengever.tasktemplates.interfaces import IFromParallelTasktemplate
from opengever.tasktemplates.interfaces import IFromSequentialTasktemplate
from plone import api
from plone.dexterity.content import Container
from plone.dexterity.utils import addContentToContainer
from plone.dexterity.utils import createContent
from zope.event import notify
from zope.globalrequest import getRequest
from zope.interface import alsoProvides
from zope.interface import noLongerProvides
from zope.lifecycleevent import ObjectCreatedEvent

class TaskTemplateFolder(Container):

    @property
    def sequence_type_label(self):
        return sequence_type_vocabulary.by_value[self.sequence_type].title

    @property
    def is_sequential(self):
        return self.sequence_type == u'sequential'

    def trigger(self, dossier, templates, related_documents,
                values, start_immediately):

        trigger = TaskTemplateFolderTrigger(
            self, dossier, templates, related_documents,
            values, start_immediately)
        trigger.generate()

class TaskTemplateFolderTrigger(object):

    def __init__(self, context, dossier, templates,
                 related_documents, values, start_immediately):
        self.context = context
        self.dossier = dossier
        self.selected_templates = templates
        self.related_documents = related_documents
        self.values = values
        self.start_immediately = start_immediately
        self.request = getRequest()

    def generate(self):
        alsoProvides(self.request, IDuringTaskTemplateFolderTriggering)
        main_task = self.create_main_task()
        self.create_subtasks(main_task)
        noLongerProvides(self.request, IDuringTaskTemplateFolderTriggering)

    def add_task(self, container, data):
        task = createContent('opengever.task.task', **data)
        notify(ObjectCreatedEvent(task))
        task = addContentToContainer(container, task, checkConstraints=True)
        self.mark_as_generated_from_tasktemplate(task)
        return task

    def create_main_task(self):
        data = dict(
            title=self.context.title,
            issuer=api.user.get_current().getId(),
            responsible=api.user.get_current().getId(),
            responsible_client=get_current_org_unit().id(),
            task_type='direct-execution',
            deadline=self.get_main_task_deadline())

        main_task = self.add_task(self.dossier, data)

        # set the main_task in to the in progress state
        api.content.transition(obj=main_task,
                               transition='task-transition-open-in-progress')

        return main_task

    def create_subtasks(self, main_task):
        predecessor = None

        subtasks = []
        for template in self.selected_templates:
            subtask = self.create_subtask(
                main_task, template, self.values.get(template.id))
            subtasks.append(subtask)

        main_task.set_tasktemplate_order(subtasks)

    def set_initial_state(self, task, template):
        """Set the initial states to planned for tasks of a sequential
        tasktemplatefolder except for the first if start_immediately is True.
        Tasks of a parallel tasktemplatefolder are skipped.
        """
        if not self.context.is_sequential:
            return

        if not self.start_immediately \
           or template != self.selected_templates[0]:
            task.set_to_planned_state()

    def create_subtask(self, main_task, template, values):
        data = dict(
            title=template.title,
            issuer=template.issuer,
            responsible=template.responsible,
            responsible_client=template.responsible_client,
            task_type=template.task_type,
            text=template.text,
            relatedItems=self.related_documents,
            deadline=date.today() + timedelta(template.deadline),
        )

        data.update(values)
        self.replace_interactive_actors(data)

        task = self.add_task(main_task, data)
        self.set_initial_state(task, template)
        task.reindexObject()
        task.get_sql_object().sync_with(task)

        # add activity record for subtask
        if api.content.get_state(task) != TASK_STATE_PLANNED:
            activity = TaskAddedActivity(task, getRequest(), main_task)
            activity.record()

        return task

    def get_main_task_deadline(self):
        highest_deadline = max(
            [template.deadline for template in self.selected_templates])
        deadline_timedelta = api.portal.get_registry_record(
            'deadline_timedelta', interface=ITaskSettings)
        return date.today() + timedelta(highest_deadline + deadline_timedelta)

    def mark_as_generated_from_tasktemplate(self, task):
        if self.context.is_sequential:
            alsoProvides(task, IFromSequentialTasktemplate)
        else:
            alsoProvides(task, IFromParallelTasktemplate)

    def replace_interactive_actors(self, data):
        data['issuer'] = self.get_interactive_representative(data['issuer'])
        if data['responsible_client'] == INTERACTIVE_USERS:
            data['responsible_client'] = get_current_org_unit().id()
            data['responsible'] = self.get_interactive_representative(
                data['responsible'])

    def get_interactive_representative(self, principal):
        """The current systems knows two interactive users:

        `responsible`: the reponsible of the main dossier.
        `current_user`: the currently logged in user.
        """

        if principal == 'responsible':
            return IDossier(self.dossier.get_main_dossier()).responsible

        elif principal == 'current_user':
            return api.user.get_current().getId()

        else:
            return principal

    def set_tasktemplate_predecessor(self, task, predecessor):
        if not self.context.is_sequential:
            return

        if predecessor:
            task.set_tasktemplate_predecessor(predecessor)


#uncoding: UTF-8
#Autor: Ana María López Soto
#Descripción: Este programa calcúla el rendimiento de la gasolina de un auto.

#Cálculo del rendimiento de km/l
def litrosKilometro(litrosConsumidos,kilometrosRecorridos):
    rendimientoKilometro =  kilometrosRecorridos / litrosConsumidos
    return rendimientoKilometro

#Cálculo del redimiento de Milla/Gálon
def galonesMillas(litrosConsumidos,kilometrosRecorridos):
    rendimientoMillas = (kilometrosRecorridos / 1.609344) / (litrosConsumidos * 0.264172051)
    return rendimientoMillas

#Cálculo de Litros consumidos por cierto kilometraje por recorrer
def calculoLitros(litrosConsumidos, kilometrosRecorridos, kilometrosParaRecorrer):
    litrosPorConsumir = (litrosConsumidos / kilometrosRecorridos) * kilometrosParaRecorrer
    return litrosPorConsumir

def main():
    kilometrosRecorridos = float(input("Teclea el número de km recorridos: "))
    litrosConsumidos = float(input("Teclea el número de litros de gasolina usados: "))
    rendimientoKilometros = litrosKilometro(litrosConsumidos, kilometrosRecorridos)
    rendimientoMillas = galonesMillas(litrosConsumidos, kilometrosRecorridos)
    print(  )
    print("Si recorres", kilometrosRecorridos,"kms con",litrosConsumidos,"litros de gasolina, elrendimiento es:")
    print("{:.2f}".format(rendimientoKilometros), "km/l")
    print("{:.2f}".format(rendimientoMillas), "mi/gal")
    print(       )
    kilometrosParaRecorrer = int(input("¿Cuántos kilómetros vas a recorrer? "))
    print(      )
    print("Para recorrer",kilometrosParaRecorrer, "km. necesitas", ("{:.2f}".format(calculoLitros(litrosConsumidos,kilometrosRecorridos,kilometrosParaRecorrer))),"litros de gasolina")

main()


from __future__ import print_function
import torch

#def my_triplet_margin_loss(anchor,positive, negative, margin=1.0, p=2, eps=1e-6, swap=False):
def my_triplet_margin_loss(x1, x2, margin=1.0, p=2, eps=1e-6):#, swap=False):
    # copy from triplet_marign_loss and modify something

    d1 = x1.size()[-1]
    d2 = x2.size()[-1]

    assert d1 == d2, 'input dimension should be matched'

    if x1.dim() > 2 and x2.dim() >2:
        x1=x1.view(-1,d1)
        x2=x2.view(-1,d2)

    scores = x1.mm(x2.t())
    #print(scores.size())
    diagonal = torch.diag(scores)
    #print(diagonal.size())

    # compare every diagonal score to scores in its column (i.e, all contrastive images for each sentence)
    cost_x2 = torch.clamp(margin - diagonal.view(1,-1) + scores, min=0.0)
    # compare every diagonal score to scores in its row (i.e, all contrastive sentences for each image)
    cost_x1 = torch.clamp(margin - diagonal.view(-1, 1) + scores, min=0.0)

    #print(diagonal.view(-1, 1).size())
    #print(cost_x2.size(), cost_x1.size())

    #print(scores[:6,:6])
    #print(diagonal[:6])
    #print(cost_x2[:6,:6])
    #print(cost_x1[:6,:6])

    # clear diagonals
    for i in range(0,scores.size()[0]):
        cost_x2[i,i] = 0
        cost_x1[i,i] = 0

    return cost_x2.sum() + cost_x1.sum()

    #assert anchor.size() == positive.size(), "Input sizes between positive and negative must be equal."
    #assert anchor.size() == negative.size(), "Input sizes between anchor and negative must be equal."
    #assert positive.size() == negative.size(), "Input sizes between positive and negative must be equal."
    #assert anchor.dim() == 2, "Inputd must be a 2D matrix."
    ##d_p = F.pairwise_distance(anchor, positive, p, eps)
    ##d_n = F.pairwise_distance(anchor, negative, p, eps)
    #d_p = F.cosine_similarity(anchor, positive, dim=1, eps=eps)
    #d_n = F.cosine_similarity(anchor, negative, dim=1, eps=eps)
    #if swap:
    #    d_s = F.cosine_similarity(positive, negative, dim=1, eps=eps)
    #    d_n = torch.min(d_n, d_s)

    #dist_hinge = torch.clamp(margin + d_p - d_n, min=0.0)
    #loss = torch.mean(dist_hinge)
    #return loss


# Figure out how far from gene every motif is placed
# open file and take distance of motif from exact gene
# then sum it, want to get some kind of plot
# its only for upstream part of gene, for downstream you need to make some changes

def splitout(handle):
    #
    # line = handle.readline().strip()
    # if line.rstrip() != ('Name\tMotif'+'\t'+'Coordinate'+'\t'+'Strand'+'\t'+'Name'+'\t'+'Upstream'+'\t' +
    #                      'Upstream dist'+'\t'+'Downstream'+'\t'+'Downstream dist'):
    #     raise SyntaxError("Third line not recognised as OUT")
    # NAME=0
    # MOTIF=1
    # COORDINATE=2
    # STRAND=3
    # NAME of gene, if motif in = 4
    # UPSTREAM=5
    # UPSTREAMD=6
    # DOWNSTREAM=7
    # DOWNSTREAMD=8
    for line in handle:
        parts = line.rstrip().split('\t')
        yield parts

file = open('C:\моё\универ\прогаем\Bio6A6T\Bio\AnalysisUpstream.txt')
for nParts in splitout(file):
    import matplotlib.pyplot as plt

    rangen = 300  # change here
    Gene = nParts[0]  # and here

    handle = open('C:\моё\универ\прогаем\Bio6A6T\Bio\motif_out.txt')
    result = [0]*rangen
    for parts in (splitout(handle)):
        up = parts[5].split('/')
        up.append('hypothetical protein')
        updist = parts[6].split('/')
        updist.append('100')
        if up[0] == Gene and int(updist[0]) < rangen:  # first - name, second - range of distance
            result[int(updist[0])] += 1
        if up[1] == Gene and int(updist[1]) < rangen:
            result[int(updist[1])] += 1
    handle.close()

    summ = 0
    for i in range(rangen):
        result[i] /= int(nParts[1])  # change here, full numbers of 'transcriptional regulator' (take from analysis)
        result[i] *= 100
        summ += result[i]
    print(str(summ) + '% is in first ' + str(rangen) + ' of ' + Gene)

    if summ > 25 and int(nParts[1]) > 50:
        plt.plot(result)
        # plt.savefig(str(summ) + '% is in first ' + str(rangen) + ' of ' + Gene + '.png', format='png')
        plt.show()


from django.db import models
from django.urls import reverse
from django.utils.translation import gettext_lazy as _

from rdmo.core.plugins import get_plugin

from ..managers import IntegrationManager

class Integration(models.Model):

    objects = IntegrationManager()

    project = models.ForeignKey(
        'Project', on_delete=models.CASCADE, related_name='integrations',
        verbose_name=_('Project'),
        help_text=_('The project for this integration.')
    )
    provider_key = models.TextField(
        verbose_name=_('Provider key'),
        help_text=_('The key of the provider for this integration.')
    )

    class Meta:
        ordering = ('project__title', )
        verbose_name = _('Integration')
        verbose_name_plural = _('Integrations')

    def __str__(self):
        return '%s / %s' % (self.project.title, self.provider_key)

    @property
    def provider(self):
        return get_plugin('PROJECT_ISSUE_PROVIDERS', self.provider_key)

    def get_absolute_url(self):
        return reverse('project', kwargs={'pk': self.project.pk})

    def save_options(self, options):
        for field in self.provider.fields:
            try:
                integration_option = IntegrationOption.objects.get(integration=self, key=field.get('key'))
            except IntegrationOption.DoesNotExist:
                integration_option = IntegrationOption(integration=self, key=field.get('key'))

            integration_option.value = options.get(field.get('key')) or ''  # required was (hopefully) checked before
            integration_option.secret = field.get('secret', False)
            integration_option.save()

class IntegrationOption(models.Model):

    integration = models.ForeignKey(
        'Integration', on_delete=models.CASCADE, related_name='options',
        verbose_name=_('Integration'),
        help_text=_('The integration for this integration option.')
    )
    key = models.SlugField(
        max_length=128,
        verbose_name=_('Key'),
        help_text=_('The key for this integration option.')
    )
    value = models.TextField(
        verbose_name=_('Value'),
        help_text=_('The value for this integration option.')
    )
    secret = models.BooleanField(
        default=False,
        verbose_name=_('Secret'),
        help_text=_('Designates whether this integration option is hidden from regular users.')
    )

    class Meta:
        ordering = ('integration__project__title', )
        verbose_name = _('Integration option')
        verbose_name_plural = _('Integration options')

    def __str__(self):
        return '%s / %s / %s = %s' % (self.integration.project.title, self.integration.provider_key, self.key, self.value)


#! usr/bin/python3
# resizeAndAddLogo.py - Resizes all images in current working directory to fit
# in a 300x300 square, and adds catlogo.png to the lower-right corner.

import os
from PIL import Image

SQUARE_FIT_SIZE = 300
LOGO_FILENAME = 'catlogo.png'
logoIm = Image.open(LOGO_FILENAME)
logoWidth, logoHeight = logoIm.size

os.makedirs('withLogo', exist_ok=True)
# Loop over all files in the working directory.
for filename in os.listdir('.'):
    if not (filename.lower().endswith('.png') or filename.lower().endswith('.jpg') or filename.lower().endswith('.gif')
            or filename.lower().endswith('.bmp')) or filename == LOGO_FILENAME:
        continue  # skip non-image files and the logo file itself
    im = Image.open(filename)
    width, height = im.size

    # Check if image needs to be resized.
    if width > SQUARE_FIT_SIZE and height > SQUARE_FIT_SIZE:
        # Calculate the new width and height to resize to.
        if width > height:
            height = int((SQUARE_FIT_SIZE / width) * height)
            width = SQUARE_FIT_SIZE
        else:
            width = int((SQUARE_FIT_SIZE / height) * width)
            height = SQUARE_FIT_SIZE

    # Check if the height or width of the image is at least twice
    # the height and width of the logo image before adding the logo.
    # Otherwise, skip adding the logo.
    if (height <= 2*logoHeight) or (width <= 2*logoWidth):
        print('The image dimensions are too small for pasting the logo. Skipping.')

    # Resize the image.
    print('Resizing %s...' % (filename))
    im = im.resize((width, height))
    # Add the logo.
    print('Adding logo to %s...' % (filename))
    im.paste(logoIm, (width - logoWidth, height - logoHeight), logoIm)

    # Save changes.
    im.save(os.path.join('withLogo', filename))


# Laser Effect

from turtle import *
from random import randint
from colorsys import hls_to_rgb
from saveimg import save
from math import sin

width = 800
height = 600
quality = 250

scr = Screen()
scr.setup(width,height)
delay(0)
t = Turtle()
t.speed(0)

for i in range(1,quality):
    t.penup()
    t.goto(-width,0)
    t.color(hls_to_rgb(0.8,min(i/(quality*0.2),1),0.9))
    t.width((height/i)*2)
    t.pendown()
    for j in range(width):
        t.goto((j)-(width/2),sin(j/30)*10)
"""
x0 = -width

t.color("white")

for x in range(randint(5,10)):
    t.penup()
    t.goto(x0,0)
    t.pendown()
    t.width(randint(1,3))
    while(x0 <= (width/2)):
        x0 += randint(5,30)
        t.pendown()
        t.goto(x0, min(max(t.ycor()+randint(-10,10),-40),40))
    x0 = -width

"""


"""		EE2703 ASSIGNMENT 1
NAME: VINAYAKA SRIDHAR K V V
ROLL NO.: EE19B058
"""
# PYTHON PROGRAM FOR READING A NETLIST AND PRINTING IN THE REVERSE ORDER

from sys import argv, exit	#importing module sys
pycode = argv[0]

CIRCUIT = '.circuit' # defining the constants
END = '.end'
""" Sanity Check whether there is a input file given or not"""
if len(argv) != 2:
	#if the there is no input file mentioned and print the usage method
	print("\nPlease give a input file: Usage: %s <input file name>" % pycode)
	exit()

filename = argv[1]		# Calling the argument after the python file in the commandline as the filename
try:
	with open(filename) as f:		#Taking the input file as f
	#Initialising values of start and end
		start=1
		end=0
		lines = f.readlines()		#reading the input file line by line and storing them in the list "lines"
		for line in lines:
			word = line.split()	# Checking if there is line starting with .circuit
			if word[0]==CIRCUIT:	# if there is a line starting with .circuit then make its index as start
				start = lines.index(line)

			if word[0]==END:	# Checking if there is line starting with .end
				end = lines.index(line)	# if yes then make its index as end

		""" Sanity check: whether input file has valid circuit defintion
			that is whether its starts with .circuit and ends with .end"""
		if start >= end:
			print("Invalid Circuit Definition")	#if the file fails to comply with the circuit defintion then print out error statement
			exit(0)

#printing the lines in the reverse order
	for i in range(end-1,start,-1):
		tokens = lines[i].split("#")[0].split()     #removing the comments and splitting the lines into words and calling them tokens
		print(" ".join(reversed(tokens)))           #printing the tokens in reverse order

# if no file exists with the name given by the user
#then issue an IOError saying invalid file
except IOError:
	print("Invalid File")
	exit(0)


import discord
import asyncio
client = discord.Client()
from commands import STATICS

@asyncio.coroutine
def ex(args, message, client, invoke):
      embed = discord.Embed(
          title=STATICS.BOTNAME,
          color=0xe67e22,
          description="version: "+STATICS.description
      )
      embed.set_author(
          name=STATICS.authorname,
          icon_url="https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Crown_of_Savoy.svg/1280px-Crown_of_Savoy.svg.png",
          url="https://discordapp.com/developers/applications "
      )
      embed.add_field(
          name="ID",
          value="327779958250405889",
      )
      embed.add_field(
          name="Help",
          value="?help",
          inline=False
      )
      embed.set_footer(
          text="Ein bot von Brainkackwitz"
      )
      embed.set_thumbnail(
          url="https://www.welt.de/img/kultur/mobile160730744/9152508057-ci102l-w1024/Die-Wunderbare-Reise-Des-Kleinen-Nils-Holgersson.jpg"
      )
      yield from client.send_message(message.channel, embed=embed)


"""
HW04a test
Author: Xinyi Ye
Date: 02/18/2020
"""
from HW04a_Xinyi_Ye import find_re
import unittest

class TestRE(unittest.TestCase):
    """ test class """
    def test_find_re(self):
        id1 = 'richkempinski'

        result_1 = [['hellogitworld', 30], ['helloworld', 6],
                    ['Mocks', 10], ['Project1', 2], ['threads-of-life', 1]]
        self.assertTrue(find_re(id1) == result_1)

if __name__ == "__main__":
    unittest.main(exit=False, verbosity=2)


__author__ = 'GSA'
import ckan.plugins as p

try:
    p.toolkit.requires_ckan_version("2.9")
except p.toolkit.CkanVersionException:
    from ckanext.googleanalyticsbasic.plugin.pylons_plugin import MixinPlugin
else:
    from ckanext.googleanalyticsbasic.plugin.flask_plugin import MixinPlugin

class GoogleAnalyticsBasicException(Exception):
    pass

class GoogleAnalyticsBasicPlugin(MixinPlugin, p.SingletonPlugin):
    p.implements(p.IConfigurable, inherit=True)
    p.implements(p.IRoutes, inherit=True)
    p.implements(p.IConfigurer, inherit=True)
    p.implements(p.ITemplateHelpers)

    def get_helpers(self):
        '''Return the CKAN 2.0 template helper functions this plugin provides.

        See ITemplateHelpers.

        '''
        return {'googleanalyticsbasic_header': self.googleanalyticsbasic_header}

    def googleanalyticsbasic_header(self):
        '''Render the googleanalytics_header snippet for CKAN 2.0 templates.

        This is a template helper function that renders the
        googleanalytics_header jinja snippet. To be called from the jinja
        templates in this extension, see ITemplateHelpers.

        Using enumerate() to implement multiple trackers support
        https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced#multipletrackers

        '''
        data = {
            'googleanalytics_ids': enumerate(self.googleanalytics_ids, start=1)
        }

        return p.toolkit.render_snippet(
            'snippets/googleanalyticsbasic_header.html', data)


from GoL.gol import GameOfLife
from GoL.rules import LifeRule
from time import sleep

if __name__ == "__main__":

    A = LifeRule.ALIVE
    D = LifeRule.DEAD

    toad = [
        [D for x in range(4)],
        [D, A, A, A],
        [A, A, A, D],
        [D for x in range(4)],
    ]
    gol = GameOfLife(universe=toad)
    while True:
        print(gol)
        gol.turn()
        if gol.heat_death:
            print(gol)
            print(":GAME OVER:\n")
            break
        sleep(2)


#!/usr/bin/python
import ConfigParser
import logging
import subprocess
import sys

import requests
from argo_poem_tools.config import Config
from argo_poem_tools.packages import Packages
from argo_poem_tools.repos import build_api_url, create_yum_repo_file, \
    get_repo_data

def main():
    logger = logging.getLogger('argo-poem-packages')
    logger.setLevel(logging.INFO)

    # setting up logging to file
    logfile = logging.FileHandler('/var/log/messages')
    logfile.setLevel(logging.INFO)
    logfile.setFormatter(logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    ))

    # add the handler to the root logger
    logger.addHandler(logfile)

    try:
        subprocess.call(['yum', 'clean', 'all'])

        config = Config()
        token = config.get_token()
        hostname = config.get_hostname()
        profiles = config.get_profiles()

        logger.info(
            'Sending request for profile(s): ' + ', '.join(profiles)
        )
        data = get_repo_data(
            build_api_url(hostname),
            token,
            profiles
        )

        if not data:
            logger.warning(
                'No data for given metric profile(s): ' +
                ', '.join(profiles)
            )
            sys.exit(2)

        else:
            logger.info('Creating YUM repo files...')
            create_yum_repo_file(data)

            pkg = Packages(data)

            installed, not_installed, downgraded, not_downgraded = \
                pkg.install_packages()

            warn_msg = []
            info_msg = []
            if pkg.get_packages_not_found():
                warn_msg.append(
                    'Packages not found: ' +
                    ', '.join(pkg.get_packages_not_found())
                )

            if installed:
                new_installed = \
                    pkg.get_packages_installed_with_versions_as_requested(
                        installed
                    )

                if new_installed:
                    info_msg.append(
                        'Packages installed: ' + ', '.join(new_installed)
                    )

                installed_diff = \
                    pkg.get_packages_installed_with_different_version()

                if installed_diff:
                    info_msg.append(
                        'Packages installed with different version: ' +
                        ', '.join(installed_diff)
                    )

            if not_installed:
                warn_msg.append(
                    'Packages not installed: ' + ', '.join(not_installed)
                )

            if downgraded:
                info_msg.append(
                    'Packages downgraded: ' + ', '.join(downgraded)
                )

            if not_downgraded:
                warn_msg.append(
                    'Packages not downgraded: ' + ', '.join(not_downgraded)
                )

            if info_msg:
                logger.info('; '.join(info_msg))

            if warn_msg:
                logger.warning('; '.join(warn_msg))
                sys.exit(1)

            else:
                logger.info('ok!')
                sys.exit(0)

    except requests.exceptions.ConnectionError as err:
        logger.error(err)
        sys.exit(2)

    except requests.exceptions.RequestException as err:
        logger.error(err)
        sys.exit(2)

    except ConfigParser.ParsingError as err:
        logger.error(err)
        sys.exit(2)

    except ConfigParser.NoSectionError as err:
        logger.error(err)
        sys.exit(2)

    except ConfigParser.NoOptionError as err:
        logger.error(err)
        sys.exit(2)

if __name__ == '__main__':
    main()


from random import randint

player_score = 0
computer_score = 0
target_score = 3

'''
ERROR: LOOP ENDS WHEN TIE
-FIND WHERE BREAK IS
    -DOUBLE CHECK
'''
while player_score < target_score and computer_score < target_score:

    print(f"Player Score: {player_score} Computer Score: {computer_score}")
    #random decoration
    print("rock...")
    print("paper...")
    print("scissors...")

    #ask for user input
    p1 = input("Please select a move: ").lower()
    print(p1)

    #genrate rock paper or scissors computer move
    random_Num = randint(0,2)
    if random_Num == 0:
        computer = "rock"
    elif random_Num == 1:
        computer = "paper"
    else:
        computer = "scissors"
    print(f"Comupter chose: {computer}")
    print(computer)

    #tie handler
    if p1 == computer:
        print("It's a tie")
        player_score += 1
        computer_score += 1

    #outcome if player chooses rock
    elif p1 == "rock":
        if computer == "paper":
            print("Computer wins")
            computer_score += 1
        elif computer == "scissors":
            print("Player wins")
            player_score += 1

    #outcome if player chooses paper
    elif p1 == "paper":
        if computer == "rock":
            print("Player wins")
            player_score += 1
        elif computer == "scissors":
            print("Computer wins")
            computer_score += 1

    #outcome if player chooses scissors
    elif p1 == "scissors":
        if computer == "rock":
            print("Computer wins")
            computer_score += 1
        elif computer == "paper":
            print("Player wins")
            player_score += 1

    else:
        print("something went wrong")

    #exit game option
    if p1 == "quit" or p1 == "q":
        break

if player_score > computer_score:
    print("Game Over: You win!!!")
elif player_score == computer_score:
    print("Game Over: Its a tie!!")
else:
    print("Game Over: Oh nooo computer wins!")


import collections
import os
import sys
import shutil
import re

dirs = {}
handlers = []

HandlerPattern = collections.namedtuple(
    'HandlerPattern', ['handler', 'input_pattern', 'output_pattern'])

def clean_dir(path):
    if os.path.exists(path):
        shutil.rmtree(path)
    os.makedirs(path)

def create_dir_if_not_exist(directory):
    directory = os.path.dirname(directory)
    if not os.path.exists(directory):
        os.makedirs(directory)

def read_dirs():
    with open("config/dirs.conf") as f:
        for line in f:
            [dir_name, dir_path] = line.split("=")
            dir_path = dir_path.strip()
            dirs[dir_name] = dir_path
    print(dirs)

def read_config():
    with open("config/moex_fx.conf") as f:
        for line in f:
            values = line.split(' ')
            values = [value.strip() for value in values]
            if len(values) > 2:
                [handler, input_file_pattern, output_file_pattern] = values
                handlers.append(HandlerPattern(
                    handler, input_file_pattern, output_file_pattern))
    pass

def find_matching():  # should be only one
    pass

def find_handlers(input_file, handlers, matched_handlers=[], level=0):
    for handler in handlers:
        input_pattern = handler.input_pattern
        if input_pattern == input_file:
            matched_handlers.append((level, handler))
            matched_handlers = find_handlers(
                handler.output_pattern, handlers, matched_handlers, level+1)
    return matched_handlers

def print_matched_handlers(matched_handlers):
    for handler_row in matched_handlers:
        level = handler_row[0]
        handler = handler_row[1]
        print(" "*4*level, handler)

'''
 def get_char_type(type_name):
        pattern = re.compile("^c(\d+)")
        match = pattern.match(type_name)
        return f"char __name__[{match.group(1)}]"

    def get_decimal_type(type_name):
        pattern = re.compile("d(\d+)\.(\d+)")
        match = pattern.match(type_name)
        return f"struct cgate_decimal_{match.group(1)}_{match.group(2)}"
'''
read_dirs()
read_config()
dd = {}
dd[r"^fast.(.+).raw.7z$"] = dirs["SX_ARCHIVE_DIR"]
dd[r"(.+).extr$"] = dirs["SX_EXTRACTED_PATH"]
dd[r"(.+).def.raw.(.+)"] = dirs["SX_RAW_DIR"]
dd[r"(.+).trades.raw.(.+)"] = dirs["SX_RAW_DIR"]
dd[r"(.+).stat.raw.(.+)"] = dirs["SX_RAW_DIR"]
dd[r"(.+).def.clean.(.+)"] = dirs["SX_CLEAN_DIR"]
dd[r"(.+).trades.clean.(.+)"] = dirs["SX_CLEAN_DIR"]
dd[r"(.+).stat.clean.(.+)"] = dirs["SX_CLEAN_DIR"]

def get_full_file_name(date, file_name):
    print("get_full_file_name------------------------")
    # fast.moex_fx.def.app.itubuntu.raw.7z
    #pattern = re.compile("^fast.*.raw.7z$")
    #match = pattern.match(file_name)
    matched_dirs = []
    for key, value in dd.items():
        print(key)
        pattern = re.compile(key)

        match = pattern.match(file_name)

        if match:
            if not dd[key]:
                raise Exception("can't find dir for pattern")
            print("mathced    >>>>>>>>>>>>>>>>>>", file_name, key)
            matched_dirs.append(dd[key])
        else:
            print("not matching :::::::::::::::::", file_name, key)

    if len(matched_dirs) != 1:
        print("KKKKKKKKKKKKKKKKKKKKKKK", matched_dirs)
        raise Exception(
            "should be only one matching pattern for get_full_file_name")

    file_dir = matched_dirs[0]
    full_file_name = os.path.join(file_dir, date, file_name)
    return full_file_name

def generate_pipeline(date, input_file, matched_handlers):
    if len(matched_handlers) == 0:
        return []

    pipeline = []

    tmp_file_to_real = {}
    current_input_file = get_full_file_name(date, input_file)
    for enumerated_handler in enumerate(matched_handlers):
        index = enumerated_handler[0]
        handler_row = enumerated_handler[1]
        handler = handler_row[1]
        tmp_outputfile = str(index)+".tmp"
        tmp_outputfile = os.path.join(dirs["SX_TMP_DIR"], tmp_outputfile)
        tmp_file_to_real[tmp_outputfile] = get_full_file_name(
            date, handler.output_pattern)
        #print("tmp_file ", tmp_outputfile)
        #print(input_file, " to ", tmp_outputfile)
        full_handler_path = os.path.join(dirs["SX_EXE_PATH"], handler.handler)
        cmd = f"python {full_handler_path} {current_input_file} {tmp_outputfile}"
        # print(cmd)
        pipeline.append(cmd)
        current_input_file = tmp_outputfile
    return (pipeline, tmp_file_to_real)
    # print(tmp_file_to_real)

# file_dict tmp_file_names to real_file_names

def apply_pipeline(pipeline, file_dict):
    tmp_directory = dirs["SX_TMP_DIR"]
    clean_dir(tmp_directory)
    for cmd in pipeline:
        print(cmd)
        res = os.system(cmd)
        if (res < 0):
            clean_dir(tmp_directory)
            print("pipeline was broken")
            break
        print("result = ", res)

    for d in os.listdir(tmp_directory):
        full_tmp_file_name = os.path.join(tmp_directory, d)

        if not file_dict[full_tmp_file_name]:
            clean_dir(tmp_directory)
            print("pipeline was broken")
            raise Exception("can't find tmp_file in file_dict")

    for d in os.listdir(tmp_directory):
        full_tmp_file_name = os.path.join(tmp_directory, d)
        print(full_tmp_file_name, " => ", file_dict[full_tmp_file_name])
        create_dir_if_not_exist(file_dict[full_tmp_file_name])
        mv_cmd = f"mv {full_tmp_file_name} {file_dict[full_tmp_file_name]}"
        os.system(mv_cmd)

def check_matching(date, input_file):
    matched_handlers = find_handlers(input_file, handlers)
    print_matched_handlers(matched_handlers)
    [pipeline, file_dict] = generate_pipeline(
        date, input_file, matched_handlers)
    apply_pipeline(pipeline, file_dict)

def resolve_dir_for_input_file(input_file):
    return "/home/data/archive/"

def cli():
    while True:
        try:
            cli_input = input()
            print(cli_input)
            values = cli_input.split(' ')
            values = [value.strip() for value in values]
            [command, date, file_name] = values
            input_dir = resolve_dir_for_input_file(file_name)
            if input_dir == None:
                print("can't resolve input_dir")
                raise Exception("can't resolve dir for input file")
            print("input_dir ", input_dir)
            if command == "add":
                print(command, " -> ", file_name)
                print("---- start adding file ----")
            elif command == "check":
                print("-------- ", command, date, file_name)
                check_matching(date, file_name)
            else:
                print("unknown command")
        except Exception as ex:
            print("exception ", ex)
            break

cli()


import requests
import os

INIT_DATE = "2016-06-06"
END_DATE = "2018-12-31"
PRODUCT = "firefox"
QUERY_FORMAT = "advanced"
QUERY_BASED_ON = ""
J_TOP = "OR"
LIMIT = 50

BASE_URL = "https://bugzilla.mozilla.org/rest/bug?chfieldfrom={}&chfieldto={}&product={}&query_format={}&limit={}&query_based_on={}&j_top={}&offset={}"
BASE_URL_COMMENT = "https://bugzilla.mozilla.org/rest/bug/"
BUGS_FILE_PATH = '/home/guilherme/anaconda3/envs/trace-link-recovery-study/data/mozilla_firefox/firefoxDataset/docs_english/BR_2/all_bugs_p3.csv'

header = "Bug_Number|Summary|Platform|Component|Version|Creation_Time|Whiteboard|QA_Whiteboard|First_Comment_Text|First_Comment_Creation_Time\n"
line = "{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|{8}|{9}\n"

args = [INIT_DATE, END_DATE, PRODUCT, QUERY_FORMAT, LIMIT, QUERY_BASED_ON, J_TOP]

if not os.path.exists(BUGS_FILE_PATH):
    f = open(BUGS_FILE_PATH, 'w+')
    f.write(header)
    f.close()

for offset_ in range(37000, 37750, LIMIT): # 0, 7000, 1000
    if len(args) < 8:
        args = args + [offset_]
    else:
        args[7] = offset_

    bugs = requests.get(BASE_URL.format(*args))
    bugs_json = bugs.json()

    print('OFFSET: {}'.format(offset_))

    for bug in bugs_json['bugs']:
        bug_id = bug['id']

        bug_first_comment = requests.get(BASE_URL_COMMENT + str(bug_id) + '/comment')
        bug_fcomment = bug_first_comment.json()

        print("Bug Id: " + str(bug_id))

        with open(BUGS_FILE_PATH, 'a+') as bug_file:
            bug_file.write(line.format(
                bug['id'],
                bug['summary'],
                bug['platform'],
                bug['component'],
                bug['version'],
                bug['creation_time'],
                bug['whiteboard'],
                bug['cf_qa_whiteboard'],
                bug_fcomment['bugs'][str(bug_id)]['comments'][0]['text'].replace("\n"," "),
                bug_fcomment['bugs'][str(bug_id)]['comments'][0]['creation_time']
            )
        )


"""
Manage AWS Step Functions state machines and executions.
"""

from __future__ import absolute_import, division, print_function, unicode_literals

import os, sys, argparse, json, time, concurrent.futures

from botocore.exceptions import ClientError

from . import batch, logger
from .ls import register_parser, register_listing_parser
from .ecr import ecr_image_name_completer
from .util import Timestamp, paginate, get_mkfs_command
from .util.aws import clients, ARN
from .util.printing import page_output, tabulate, YELLOW, RED, GREEN, BOLD, ENDC

def complete_state_machine_name(**kwargs):
    return [c["name"] for c in paginate(clients.stepfunctions.get_paginator("list_state_machines"))]

def sfn(args):
    sfn_parser.print_help()

sfn_parser = register_parser(sfn, help="Manage AWS Step Functions", description=__doc__)

def state_machines(args):
    page_output(tabulate(paginate(clients.stepfunctions.get_paginator("list_state_machines")), args))

state_machines_parser = register_listing_parser(state_machines, parent=sfn_parser, help="List state machines")

def ls(args):
    if args.state_machine:
        sm_arn = ARN(service="states", resource="stateMachine:" + args.state_machine)
        state_machines = [dict(stateMachineArn=str(sm_arn))]
    else:
        state_machines = paginate(clients.stepfunctions.get_paginator("list_state_machines"))

    def list_executions(state_machine):
        list_executions_paginator = clients.stepfunctions.get_paginator("list_executions")
        return list(paginate(list_executions_paginator, stateMachineArn=state_machine["stateMachineArn"]))

    with concurrent.futures.ThreadPoolExecutor() as executor:
        executions = sum(executor.map(list_executions, state_machines), [])

    page_output(tabulate(executions, args))

ls_parser = register_listing_parser(ls, parent=sfn_parser, help="List executions for state machines in this account")
ls_parser.add_argument("--state-machine").completer = complete_state_machine_name

def describe(args):
    if ARN(args.resource_arn).resource.startswith("execution"):
        desc = clients.stepfunctions.describe_execution(executionArn=args.resource_arn)
        desc["input"] = json.loads(desc.get("input", "null"))
        desc["output"] = json.loads(desc.get("output", "null"))
    else:
        desc = clients.stepfunctions.describe_state_machine(stateMachineArn=args.resource_arn)
        desc["definition"] = json.loads(desc.get("definition", "null"))
    return desc

describe_parser = register_parser(describe, parent=sfn_parser, help="Describe a state machine or execution")
describe_parser.add_argument("resource_arn")

sfn_status_colors = dict(RUNNING=GREEN(), SUCCEEDED=BOLD() + GREEN(),
                         FAILED=BOLD() + RED(), TIMED_OUT=BOLD() + RED(), ABORTED=BOLD() + RED())

def watch(args):
    seen_events = set()
    previous_status = None
    while True:
        exec_desc = clients.stepfunctions.describe_execution(executionArn=str(args.execution_arn))
        if exec_desc["status"] == previous_status:
            sys.stderr.write(".")
            sys.stderr.flush()
        else:
            logger.info("%s %s", exec_desc["executionArn"],
                        sfn_status_colors[exec_desc["status"]] + exec_desc["status"] + ENDC())
            previous_status = exec_desc["status"]
        history = clients.stepfunctions.get_execution_history(executionArn=str(args.execution_arn))
        for event in sorted(history["events"], key=lambda x: x["id"]):
            if event["id"] not in seen_events:
                details = {}
                for key in event.keys():
                    if key.endswith("EventDetails") and event[key]:
                        details = event[key]
                logger.info("%s %s %s %s %s %s", event["timestamp"], event["type"],
                            details.get("resourceType", ""), details.get("resource", ""), details.get("name", ""),
                            json.loads(details.get("parameters", "{}")).get("FunctionName", ""))
                if "taskSubmittedEventDetails" in event:
                    if event.get("taskSubmittedEventDetails", {}).get("resourceType") == "batch":
                        job_id = json.loads(event["taskSubmittedEventDetails"]["output"])["JobId"]
                        logger.info("Batch job ID %s", job_id)
                        batch.watch(batch.watch_parser.parse_args([job_id]))
                seen_events.add(event["id"])
        if exec_desc["status"] in {"SUCCEEDED", "FAILED", "TIMED_OUT", "ABORTED"}:
            break
        time.sleep(1)

    if exec_desc["status"] == "SUCCEEDED":
        return exec_desc["output"]
    else:
        history = clients.stepfunctions.get_execution_history(executionArn=str(args.execution_arn))
        last_event = sorted(history["events"], key=lambda x: x["id"])[-1]
        logger.error("%s %s", args.execution_arn, sfn_status_colors[exec_desc["status"]] + exec_desc["status"] + ENDC())
        return SystemExit(json.dumps(last_event, indent=4, default=str))

watch_parser = register_parser(watch, parent=sfn_parser,
                               help="Monitor a state machine execution and stream its execution history")
watch_parser.add_argument("execution_arn")


from tkinter import Tk, Label, Button, Listbox, END, EXTENDED, Frame, SUNKEN

from bowserScraper import BOARDS_4PLEBS

def greet():
	print("Greetings!")

def nothing():
	print("I do nothing!")

class BowserOptionsPane:
	def __init__(self, parent):

		self.parent = parent

		self.frame_options = Frame(self.parent, width=200, height=200, relief=SUNKEN)
		self.frame_options.pack()

		self.listbox_boards = Listbox(self.frame_options, selectmode=EXTENDED)
		'''List of boards the user wants to save to a CSV file'''
		self.listbox_boards.pack()

		# add all boards
		for item in BOARDS_4PLEBS:
			self.listbox_boards.insert(END, item)

class BowserMainGUI:
	def __init__(self, master):
		self.master = master
		master.title("A simple GUI")

		self.label_hello_world = Label(master, text="This is our first GUI!")
		self.label_hello_world.pack()

		self.button_greet = Button(master, text="Greet", command=greet)
		self.button_greet.pack()

		self.BowserOptionsPane = BowserOptionsPane(master)

		self.button_generate = Button(master, text="Generate CSV", command=nothing)
		'''When clicked, generate a CSV file.'''
		self.button_generate.pack()

		self.button_close = Button(master, text="Close", command=master.quit)
		'''Quits when clicked.'''
		self.button_close.pack()

if __name__ == '__main__':
	root = Tk()
	my_gui = BowserMainGUI(root)
	root.mainloop()


import tensorflow as tf
import numpy as np
import gann.tflowtools as TFT

class GannModule:
    """ For setup of single gann module = layer of neurons (the output) plus incoming weights and biases """

    def __init__(self, ann, index, input_variables, input_size, output_size, weight_range, activation_function):
        self.ann = ann
        self.index = index
        self.input = input_variables  # Both the gann's input variable or the upstream module's output
        self.input_size = input_size  # Number of neurons feeding into this module
        self.output_size = output_size  # Number of neurons in this module
        self.weight_range = weight_range  # Lower and upper bound for random weight initializing
        self.activation_function = activation_function
        self.name = "Module-" + str(self.index)

        # Build module
        self.build()

    def build(self):
        name = self.name
        lower_weight_bound = self.weight_range[0]
        upper_weight_bound = self.weight_range[1]

        # Setup weights
        self.weights = tf.Variable(np.random.uniform(lower_weight_bound, upper_weight_bound,
                                                     size=(self.input_size, self.output_size)),
                                   name=name + '-wgt', trainable=True)  # True = default for trainable anyway

        # Setup biases
        self.biases = tf.Variable(np.random.uniform(lower_weight_bound, upper_weight_bound,
                                                    size=(1, self.output_size)),
                                  name=name + '-bias', trainable=True)

        # Setup outputs
        self.output = self.activation_function(tf.matmul(self.input, self.weights) + self.biases, name=name + '-out')

        # Add to list of modules in ann
        self.ann.add_module(self)

    def get_variable(self, type):  # type = (in,out,wgt,bias)
        return {'in': self.input, 'out': self.output, 'wgt': self.weights, 'bias': self.biases}[type]

    # spec, a list, can contain one or more of (avg,max,min,hist); type = (in, out, wgt, bias)
    def generate_probe(self, type, spec):
        var = self.get_variable(type)
        base = self.name + '_' + type

        with tf.name_scope('probe_'):
            if ('avg' in spec) or ('stdev' in spec):
                avg = tf.reduce_mean(var)
            if 'avg' in spec:
                tf.summary.scalar(base + '/avg/', avg)
            if 'max' in spec:
                tf.summary.scalar(base + '/max/', tf.reduce_max(var))
            if 'min' in spec:
                tf.summary.scalar(base + '/min/', tf.reduce_min(var))
            if 'hist' in spec:
                    tf.summary.histogram(base + '/hist/', var)


import csv
import json
from collections import defaultdict

def abbreviate_team_name(name):
    '''making abbreviation names'''
    split_name = name.split(' ')
    short_name = [each[0] for each in split_name]
    return ''.join(short_name)

def plot():
    '''Creating Json file for total
       runs scored by each team'''

    # creating a dictionary of team and their score
    total_run = defaultdict(int)
    with open('deliveries.csv', 'r') as file:
        deliveries = csv.DictReader(file)
        for row in deliveries:
            total_run[abbreviate_team_name
                      (row['batting_team'])] += int(row['total_runs'])

    data = {'total_run': []}
    for item in total_run.items():
        data['total_run'].append([item[0], item[1]])

    with open('total_runs.json', 'w') as file:
        json.dump(data, file, indent=4)

if __name__ == "__main__":
    plot()


import json

from .errors import EsportsCacheKeyError
from .site import Site
from .cargo_client import CargoClient

class EsportsLookupCache(object):
    def __init__(self, site: Site, cargo_client: CargoClient = None):
        self.cache = {}
        self.event_cache = {}
        self.site = site
        self.cargo_client = cargo_client

    def _get_json_lookup(self, filename):
        """
        Returns a json representation of the requested file, queriying the site to retrieve it if needed
        :param filename: The name of the file to return, e.g. "Champion" or "Role"
        :return: A json object representing the lookup file
        """
        if filename in self.cache:
            return self.cache[filename]
        result = self.site.api(
            'expandtemplates',
            prop='wikitext',
            text='{{JsonEncode|%s}}' % filename
        )
        self.cache[filename] = json.loads(result['expandtemplates']['wikitext'])
        return self.cache[filename]

    def get(self, filename, key, length):
        """
        Returrns the length of the lookup of a key requested from the filename requested. Assumes the file has
        the same structure as the -names modules on Leaguepedia.
        :param filename: "Champion", "Role", etc. - the name of the file
        :param key: The lookup key, e.g. "Morde"
        :param length: The length of value to return, e.g. "long" or "link"
        :return: Correct lookup value provided, or None if it's not found
        """
        file = self._get_json_lookup(filename)
        key = key.lower()
        if key not in file:
            return None
        value_table = file[key]
        if isinstance(value_table, str):
            key = value_table
            value_table = file[value_table]
        if length not in value_table:
            raise EsportsCacheKeyError(filename, key, length, value_table)
        return value_table[length]

    def get_team_from_event_tricode(self, event, tricode):
        event = event.replace('_', ' ')
        tricode = tricode.lower()
        result = self._get_team_from_event_tricode_raw(event, tricode)
        if result:
            return result
        event = self.site.pages[event].resolve_redirect().name
        result = self._get_team_from_event_tricode_raw(event, tricode)
        if result:
            return result
        self._populate_event_tricodes(event)
        return self._get_team_from_event_tricode_raw(event, tricode)

    def _get_team_from_event_tricode_raw(self, event, tricode):
        if event in self.event_cache:
            if tricode in self.event_cache[event]:
                return self.event_cache[event][tricode]
            return None

    def _populate_event_tricodes(self, event):
        result = self.cargo_client.query(
            tables="TournamentRosters=Ros",
            where='Ros.OverviewPage="{}"'.format(event),
            fields="Ros.Team=Team"
        )
        d = {}
        for item in result:
            team = item['Team']
            short = self.get('Team', team, 'short')
            if short is not None:
                d[short.lower()] = self.get('Team', team, 'link')
        self.event_cache[event] = d


from django.conf.urls import url
from . import views

urlpatterns = [
	url(r'^post/(?P<pk>[0-9]+)/$',views.post_detail, name='post_detail'),
	url(r'^blog/(?P<year>\d{4})/(?P<month>\d{2})/(?P<post>[-\w]+)/$',
	views.post_detail_date,name='post_detail_date'),
    url(r'^$', views.home, name='home'),
    url(r'^blog/$', views.post_list, name='post_list'),
    url(r'^blog/gallery/$', views.gallery, name='gallery'),
    url(r'^contact/$', views.contact, name='contact'),
	url(r'^about/$', views.about, name='about'),
	url(r'^blog/post/new/$', views.post_new, name='post_new'),
	url(r'^blog/post/(?P<pk>\d+)/publish/$', views.post_publish, name='post_publish'),
	url(r'^blog/post/(?P<pk>\d+)/draft/$', views.post_draft, name='post_draft'),
    url(r'^blog/post/(?P<pk>[0-9]+)/edit/$', views.post_edit, name='post_edit'),
	url(r'^blog/drafts/$',views.post_draft_list,name='post_draft_list'),
	url(r'^blog/archive/$',views.archive,name='archive'),
]


#!/usr/env/bin python32

"""
Declaration: Copyright (c), by i_dovelemon, 2017. All right reserved.
Author: i_dovelemon[1322600812@qq.com]
Date: 2017/05/26
Brief: Test level laser weapon AI
"""

from config import *
from host_api import *

def main(id):
    bullet_num = EntityGetWeaponBulletNum(id)
    if bullet_num >= 1:
        return

    enemy = EntityFindCloestEnemy(id)
    if enemy != -1:
        dist = EntityCalcDistBetweenEntities(id, enemy)
        if dist < LASER_ATTACK_DIST:
            btlaser = EntityCreate()
            px = EntityGetPosX(id)
            py = EntityGetPosY(id)
            pz = EntityGetPosZ(id)
            EntityAddTransformCom(btlaser, px, py, pz, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0)
            EntityAddRenderCom(btlaser, "res\model\Bullet\TD_Bullet_Laser.obj", px, py, pz, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0)
            EntityAddRoleCom(btlaser, RMT_PLAYER, RST_BULLET_LASER)
            EntityAddScriptCom(btlaser, "btlaser")
            EntityAddDataCom(btlaser)
            EntityAddIntData(btlaser, "attacker", id)
            EntityAddRefCount(id)
            EntityAddIntData(btlaser, "target", enemy)
            EntityAddRefCount(enemy)
            EntityAddFloatData(btlaser, "damage", LASER_DAMAGE)
            EntitySetWeaponBulletNum(id, bullet_num + 1)


#!/usr/bin/env python

__author__ = 'thaus'

import rospy, math
from pid import PID
from geometry_msgs.msg import Vector3, PoseWithCovarianceStamped, PoseStamped, TwistStamped
from nav_msgs.msg import Odometry
from std_msgs.msg import Float64
from dynamic_reconfigure.server import Server
from mmuav_control.cfg import VpcTtcuavZCtlParamsConfig
from mmuav_msgs.msg import PIDController
from mmuav_msgs.msg import MotorSpeed
from mav_msgs.msg import Actuators

class HeightControl:
    '''
    Class implements ROS node for cascade (z, vz) PID control for MAV height.
    Subscribes to:
        /morus/pose       - used to extract z-position of the vehicle
        /morus/velocity   - used to extract vz of the vehicle
        /morus/pos_ref    - used to set the reference for z-position
        /morus/vel_ref    - used to set the reference for vz-position (useful for testing velocity controller)

    Publishes:
        /morus/mot_vel_ref  - referent value for thrust in terms of motor velocity (rad/s)
        /morus/pid_z        - publishes PID-z data - referent value, measured value, P, I, D and total component (useful for tuning params)
        /morus/pid_vz        - publishes PID-vz data - referent value, measured value, P, I, D and total component (useful for tuning params)

    Dynamic reconfigure is used to set controller params online.
    '''

    def __init__(self):
        '''
        Initialization of the class.
        '''

        self.start_flag = False         # indicates if we received the first measurement
        self.config_start = False       # flag indicates if the config callback is called for the first time

        self.z_sp = 1.0                 # z-position set point
        self.z_ref_filt = 0             # z ref filtered
        self.z_mv = 0                   # z-position measured value
        self.pid_z = PID()              # pid instance for z control

        self.vz_sp = 0                  # vz velocity set_point
        self.vz_mv = 0                   # vz velocity measured value
        self.pid_vz = PID()             # pid instance for z-velocity control

        #########################################################
        #########################################################
        # Add parameters for z controller
        self.pid_z.set_kp(100)
        self.pid_z.set_ki(1)
        self.pid_z.set_kd(100)

        # Add parameters for vz controller
        self.pid_vz.set_kp(1)#87.2)
        self.pid_vz.set_ki(0.0)
        self.pid_vz.set_kd(0)#10.89)
        #########################################################
        #########################################################

        self.pid_z.set_lim_high(500)      # max vertical ascent speed
        self.pid_z.set_lim_low(-500)      # max vertical descent speed

        self.pid_vz.set_lim_high(500)   # max velocity of a motor
        self.pid_vz.set_lim_low(-500)   # min velocity of a motor

        self.mot_speed = 0              # referent motors velocity, computed by PID cascade

        self.t_old = 0

        rospy.Subscriber('pose', PoseStamped, self.pose_cb)
        rospy.Subscriber('velocity', Odometry, self.vel_cb)
        rospy.Subscriber('vel_ref', Vector3, self.vel_ref_cb)
        rospy.Subscriber('pos_ref', Vector3, self.pos_ref_cb)
        self.pub_pid_z = rospy.Publisher('pid_z', PIDController, queue_size=1)
        self.pub_pid_vz = rospy.Publisher('pid_vz', PIDController, queue_size=1)
        self.mot_ref_pub = rospy.Publisher('mot_vel_ref', Float64, queue_size=1)
        self.pub_mot = rospy.Publisher('/gazebo/command/motor_speed', Actuators, queue_size=1)
        #self.pub_gm_mot = rospy.Publisher('collectiveThrust', GmStatus, queue_size=1)
        self.cfg_server = Server(VpcTtcuavZCtlParamsConfig, self.cfg_callback)
        self.rate = rospy.get_param('~rate', 100)
        self.ros_rate = rospy.Rate(self.rate)                 # attitude control at 100 Hz
        self.t_start = rospy.Time.now()

    def run(self):
        '''
        Runs ROS node - computes PID algorithms for z and vz control.
        '''

        while not self.start_flag and not rospy.is_shutdown():
            print('Waiting for pose measurements.')
            rospy.sleep(0.5)
        print("Starting height control.")

        self.t_old = rospy.Time.now()
        #self.t_old = datetime.now()

        while not rospy.is_shutdown():
            rospy.sleep(1.0/float(self.rate))

            ########################################################
            ########################################################
            # Implement cascade PID control here.
            # Reference for z is stored in self.z_sp.
            # Measured z-position is stored in self.z_mv.
            # If you want to test only vz - controller, the corresponding reference is stored in self.vz_sp.
            # Measured vz-velocity is stored in self.vz_mv
            # Resultant referent value for motor velocity should be stored in variable mot_speed.
            # When you implement attitude control set the flag self.attitude_ctl to 1

            #self.gm_attitude_ctl = 1  # don't forget to set me to 1 when you implement attitude ctl
            t = rospy.Time.now()
            dt = (t - self.t_old).to_sec()
            #t = datetime.now()
            #dt = (t - self.t_old).total_seconds()
            if dt > 1.05/float(self.rate) or dt < 0.95/float(self.rate):
                #print(dt)
                pass

            self.t_old = t
            #                              (m_uav + m_arms)/(C*4)
            self.mot_speed_hover = math.sqrt(9.81*(2.083+0.208*4)/(8.54858e-06*4.0))
            # prefilter for reference
            #a = 0.1
            #self.z_ref_filt = (1-a) * self.z_ref_filt  + a * self.z_sp
            vz_ref = self.pid_z.compute(self.z_sp, self.z_mv, dt)
            #print("vz_ref", vz_ref)
            self.mot_speed = self.mot_speed_hover + \
                        self.pid_vz.compute(vz_ref, self.vz_mv, dt)
            #print("mot_speed", self.mot_speed)

            ########################################################
            ########################################################

            # gas motors are used to control attitude
            # publish referent motor velocity to attitude controller
            mot_speed_msg = Float64(self.mot_speed)
            self.mot_ref_pub.publish(mot_speed_msg)

            # Publish PID data - could be useful for tuning
            self.pub_pid_z.publish(self.pid_z.create_msg())
            self.pub_pid_vz.publish(self.pid_vz.create_msg())

    def pose_cb(self, msg):
        '''
        Pose (6DOF - position and orientation) callback.
        :param msg: Type PoseWithCovarianceStamped
        '''
        if not self.start_flag:
            self.start_flag = True
        self.z_mv = msg.pose.position.z

    def vel_cb(self, msg):
        '''
        Velocity callback (linear velocity - x,y,z)
        :param msg: Type Vector3Stamped
        '''
        #if not self.start_flag:
        #    self.start_flag = True
        self.vz_mv = msg.twist.twist.linear.z

    def vel_ref_cb(self, msg):
        '''
        Referent velocity callback. Use received velocity values when during initial tuning
        velocity controller (i.e. when position controller still not implemented).
        :param msg: Type Vector3
        '''
        self.vz_sp = msg.z

    def pos_ref_cb(self, msg):
        '''
        Referent position callback. Received value (z-component) is used as a referent height.
        :param msg: Type Vector3
        '''
        self.z_sp = msg.z

    def cfg_callback(self, config, level):
        """
        Callback for dynamically reconfigurable parameters (P,I,D gains for height and velocity controller)
        """
        #print("CFG callback")

        if not self.config_start:
            # callback is called for the first time. Use this to set the new params to the config server
            config.z_kp = self.pid_z.get_kp()
            config.z_ki = self.pid_z.get_ki()
            config.z_kd = self.pid_z.get_kd()

            config.vz_kp = self.pid_vz.get_kp()
            config.vz_ki = self.pid_vz.get_ki()
            config.vz_kd = self.pid_vz.get_kd()

            self.config_start = True
        else:
            # The following code just sets up the P,I,D gains for all controllers
            self.pid_z.set_kp(config.z_kp)
            self.pid_z.set_ki(config.z_ki)
            self.pid_z.set_kd(config.z_kd)

            self.pid_vz.set_kp(config.vz_kp)
            self.pid_vz.set_ki(config.vz_ki)
            self.pid_vz.set_kd(config.vz_kd)

        # this callback should return config data back to server
        return config

if __name__ == '__main__':

    rospy.init_node('vpc_ttcuav_z_controller')
    height_ctl = HeightControl()
    height_ctl.run()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Offer',
            fields=[
                ('id', models.AutoField(primary_key=True, auto_created=True, serialize=False, verbose_name='ID')),
                ('offer_name', models.CharField(max_length=100)),
                ('for_free', models.BooleanField(default=False, verbose_name='Free?')),
                ('pub_date', models.DateTimeField(verbose_name='Date')),
                ('options', models.CharField(max_length=200)),
                ('text', models.TextField(max_length=2000)),
                ('responses', models.IntegerField(default=0)),
            ],
        ),
        migrations.CreateModel(
            name='OfferCategory',
            fields=[
                ('id', models.AutoField(primary_key=True, auto_created=True, serialize=False, verbose_name='ID')),
                ('category', models.CharField(max_length=50)),
            ],
        ),
        migrations.AddField(
            model_name='offer',
            name='offer_category',
            field=models.ForeignKey(to='swap.OfferCategory'),
        ),
    ]


#motor driver pins

MotorAEn=32
MotorA=13
MotorA1=15

MotorBEn=12
MotorB=16
MotorB1=18

GROUND=6

#ultrasonic sensor
TRIG=27
ECHO=29
VCC=4
GND=25

#Camera Servo Motor
VCC_S1=4
GND_S1=34
SERVO_PIN_1=33

VSS_S2=2
GND_S2=39
SERVO_PIN_2=40

#Distance Servo Motor

### NOT USED
#te3mperature_sensor
###TEMP_PIN=37
###VSS_T=1


import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt
import seaborn as sns
import json
import csv
from pandas import DataFrame

with open("input/train.json") as datafile1: #first check if it's a valid json file or not
    data1 = json.load(datafile1)
with open("input/test.json") as datafile2: #first check if it's a valid json file or not
    data2 = json.load(datafile2)
with open("input/validation.json") as datafile3: #first check if it's a valid json file or not
    data3 = json.load(datafile3)
#test = pd.DataFrame(data2)
#test.shape

my_dic_data = data1
keys= my_dic_data.keys()
dict_you_want1={'my_items1':my_dic_data['annotations']for key in keys}
dict_you_want2={'my_items2':my_dic_data['images']for key in keys}
df=pd.DataFrame(dict_you_want1)
fd = pd.DataFrame(dict_you_want2)
df2=df['my_items1'].apply(pd.Series)
#print ("df2",df2.head())
fd2=fd['my_items2'].apply(pd.Series)
#print ("fd2",fd2.head())
train_data = pd.merge(df2, fd2, on='image_id', how='outer')

# for validation data
my_dic_data = data3
keys= my_dic_data.keys()
dict_you_want1={'my_items1':my_dic_data['annotations']for key in keys}
dict_you_want2={'my_items2':my_dic_data['images']for key in keys}
df=pd.DataFrame(dict_you_want1)
fd = pd.DataFrame(dict_you_want2)
df2=df['my_items1'].apply(pd.Series)
#print ("df2",df2.head())
fd2=fd['my_items2'].apply(pd.Series)
#print ("fd2",fd2.head())
validation_data = pd.merge(df2, fd2, on='image_id', how='outer')

# for test data
my_dic_data = data2
keys= my_dic_data.keys()
dict_you_want2={'my_items2':my_dic_data['images']for key in keys}
fd = pd.DataFrame(dict_you_want2)
test_data=fd['my_items2'].apply(pd.Series)

train_data['url'] = train_data['url'].apply(lambda x:str(x[0]))
test_data['url'] = test_data['url'].apply(lambda x:str(x[0]))
validation_data['url'] = validation_data['url'].apply(lambda x:str(x[0]))

train_data.head()
validation_data.head()
test_data.head()

print("size of training data", train_data.shape)
print("size of validation data", validation_data.shape)
print("size of test data", test_data.shape)

# missing data in training data set
total = train_data.isnull().sum().sort_values(ascending = False)
percent = (train_data.isnull().sum()/train_data.isnull().count()).sort_values(ascending = False)
missing_train_data = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])
missing_train_data.head()

# missing data in validation data set
total = validation_data.isnull().sum().sort_values(ascending = False)
percent = (validation_data.isnull().sum()/validation_data.isnull().count()).sort_values(ascending = False)
missing_validation_data = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])
missing_validation_data.head()

# missing data in test data
total = test_data.isnull().sum().sort_values(ascending = False)
percent = (test_data.isnull().sum()/test_data.isnull().count()).sort_values(ascending = False)
missing_test_data = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])
missing_test_data.head()

# now open the URL
temp = 4
print('image_id', train_data['image_id'][temp])
print('url:', train_data['url'][temp])

from IPython.display import Image
from IPython.core.display import HTML

def display_category(urls, category_name):
    img_style = "width: 180px; margin: 0px; float: left; border: 1px solid black;"
    images_list = ''.join([f"<img style='{img_style}' src='{u}' />" for _, u in urls.head(12).iteritems()])
    display(HTML(images_list))

urls = train_data['url'][15:30]
display_category(urls, "")

urls = test_data['url'][15:30]
display_category(urls, "")

urls = validation_data['url'][15:30]
display_category(urls, "")

# Unique URL's
train_data.nunique()

#Class distribution
plt.figure(figsize = (10, 8))
plt.title('Category Distribuition')
sns.distplot(train_data['label_id'])

plt.show()

# Occurance of label_id in decreasing order(Top categories)
temp = pd.DataFrame(train_data.label_id.value_counts().head(8))
temp.reset_index(inplace=True)
temp.columns = ['label_id','count']
temp

plt.figure(figsize=(15,8))
count = train_data['label_id'].value_counts().head(30)
sns.barplot(count.index,  count.values,)
plt.xlabel('label id', fontsize=12)
plt.ylabel('Cou', fontsize=12)
plt.title("Distribution of label ids", fontsize=16)

# Extract website_name for train data
temp_list = list()
for path in train_data['url']:
    temp_list.append((path.split('//', 1)[1]).split('/', 1)[0])
train_data['website_name'] = temp_list
# Extract website_name for test data
temp_list = list()
for path in test_data['url']:
    temp_list.append((path.split('//', 1)[1]).split('/', 1)[0])
test_data['website_name'] = temp_list
# Extract website_name for validation data
temp_list = list()
for path in validation_data['url']:
    temp_list.append((path.split('//', 1)[1]).split('/', 1)[0])
validation_data['website_name'] = temp_list

print("Training data size",train_data.shape)
print("test data size",test_data.shape)
print("validation data size",validation_data.shape)

train_data.head()
test_data.head()
validation_data.head()

print("Total unique websites : ",len(train_data.website_name.value_counts()))
plt.figure(figsize=(15,8))
count = train_data.website_name.value_counts().head(10)
sns.barplot(count.values, count.index)
for i, v in enumerate(count.values):
    plt.text(0.8,i,v,color='k',fontsize=12)
plt.xlabel('Count', fontsize=12)
plt.ylabel('websites name', fontsize=12)
plt.title("websites names with their occurances", fontsize=16)

print("Total unique websites : ",len(test_data.website_name.value_counts()))
plt.figure(figsize=(15,8))
count = test_data.website_name.value_counts().head(10)
sns.barplot(count.values, count.index)
for i, v in enumerate(count.values):
    plt.text(0.8,i,v,color='k',fontsize=12)
plt.xlabel('Count', fontsize=12)
plt.ylabel('Website name', fontsize=12)
plt.title("Website names with their occurances", fontsize=16)

print("Total unique websites : ",len(validation_data.website_name.value_counts()))
plt.figure(figsize=(15,8))
count = validation_data.website_name.value_counts().head(10)
sns.barplot(count.values, count.index)
for i, v in enumerate(count.values):
    plt.text(0.8,i,v,color='k',fontsize=12)
plt.xlabel('Count', fontsize=12)
plt.ylabel('Website name', fontsize=12)
plt.title("Website names with their occurances", fontsize=16)


"""Parsing engine"""

import re
try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO

from .engine import Engine

def s_float(scanner, token):
    """return token as a float"""
    return float(token)

def s_int(scanner, token):
    """return token as an integer"""
    return int(token)

def s_operator(scanner, token):
    """return token as an operation name"""
    return token

_scanner = re.Scanner([
    (r'(\+|-)?\d*\.\d*', s_float),
    (r'(\+|-)?\d+', s_int),
    (r'\S+', s_operator),
    (r'\s+', None),
])

class Parser(object):
    """Input stream parser/tokenizer and processor"""

    def scan(self, stream):
        """scan input stream and return token generator"""
        if isinstance(stream, str):
            stream = StringIO(stream)
        for line in stream:
            tokens, remainder = _scanner.scan(line)
            for t in tokens:
                yield t

    def process(self, stream, engine=None):
        """process all tokens on input stream against calculator engine"""
        if not engine:
            engine = Engine()
        result = None
        for token in self.scan(stream):
            if isinstance(token, float) or isinstance(token, int):
                result = engine.push(token)
            else:
                result = engine.execute(token)
        return result


import tensorflow as tf
import numpy as np
x = [[[1, 2, 3],
     [1, 2, 3]],
     [[3, 4, 5],
      [6, 7, 8]],
     [[3, 4, 5],
      [6, 7, 8]]]

xx = tf.cast(x, tf.float32)
a = tf.nn.moments(xx,axes=[-1],keep_dims=True)
print(a)
# tf.layers.batch_normalization()
# mean_all = tf.reduce_mean(xx, keep_dims=False)
# mean_0 = tf.reduce_mean(xx, axis=0, keep_dims=False)
# mean_1 = tf.reduce_mean(xx, axis=1, keep_dims=False)
# print(xx)
# print(mean_all)
# print(mean_0)
# print(mean_1)
# b = [1,2,3,4]
# a = list(range(len(b)))
# del a[1]
# print(a)


import sqlite3

con = sqlite3.connect(r'/home/dad/Documents/db/chinook.db')
cursorObj = con.cursor()
'''
command = "SELECT albumid, COUNT(trackid)\
        FROM tracks\
        GROUP BY albumid;"

doesnt work
command = "SELECT albumid, COUNT(trackid) \
FROM tracks \
WHERE COUNT(albumid) BETWEEN 18 AND 20;"
# GROUP BY albumid \
# HAVING albumid = 1;"
'''
command = '''\
SELECT
    tracks.AlbumId,
    title,
    SUM(Milliseconds) AS length
FROM
    tracks
INNER JOIN albums ON albums.AlbumId = tracks.AlbumId
GROUP BY
    tracks.AlbumId
HAVING
    length > 60000000;'''

# SELECT
#    albumid,
#    COUNT(trackid)
# FROM
#    tracks
# GROUP BY
#    albumid
# HAVING
#    COUNT(albumid) BETWEEN 18 AND 20
# ORDER BY albumid;'''

cursorObj.execute(command)
rows = cursorObj.fetchall()

for row in rows:
    print(row)

con.commit()


import tensorflow as tf
import numpy as np
from PIL import Image

from model.resnet import ResNet
from model.losses import euclidean_dist
from configs.config import args

def main(argv=None):  # pylint: disable=unused-argument
    net = ResNet(depth=50, training=False, weight_decay=args.weight_decay)
    # if the network is trained as in train_net.py, otherwise reset
    args.ckpt = 10000
    images = np.array([np.array(Image.open(p)) for p in args.img_paths]) / 255.0
    with tf.Session(config=tf.ConfigProto(allow_soft_placement=True,
                                          log_device_placement=False)) as sess:
        # defining the graph
        image_ph = tf.placeholder(tf.float32, shape=[2, 256, 128, 3])
        features = net.build_net(image_ph, 10, False)['pooled']
        features = tf.math.l2_normalize(features, axis=-1)
        distance = euclidean_dist(features[0:1], features[1:])
        similarity = 1 - tf.squeeze(distance) / 2.0    # to be in [0, 1]

        saver = tf.train.Saver(tf.global_variables(), max_to_keep=1000,
                               keep_checkpoint_every_n_hours=1)
        sess.run(tf.global_variables_initializer())
        net.restore_ckpt(sess, saver)
        tf.get_default_graph().finalize()

        sim = sess.run(similarity, feed_dict={image_ph: images})

    print("similarity is:", sim)

if __name__ == '__main__':
    tf.app.run()


#!/usr/bin/env python3

"""Problem 39: Integer right triangles"""

from utils import pythagorean_triplets

def main():
    s = p = 0

    for perimeter in range(12, 1001, 4): # the perimeter is always divisible by 4
        solutions = len(list(pythagorean_triplets(perimeter)))
        if solutions > s:
            s = solutions
            p = perimeter
    return p

if __name__ == "__main__":
    print(main())


# -*- coding: utf-8 -*-
"""
Created on Wed Apr 22 05:22:37 2020

@author: devan
"""

#importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
dataset = pd.read_csv('Position_Salaries (1).csv')
X = dataset.iloc[:, 1].values
y = dataset.iloc[:, 2].values
#reshaping the vallues
X= X.reshape(-1, 1)
y= y.reshape(-1, 1)

#feature scaling
from sklearn.preprocessing  import StandardScaler
sc_X= StandardScaler()
sc_y= StandardScaler()
X= sc_X.fit_transform(X)
y= sc_y.fit_transform(y)
#splitting into training and test set
"""from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)"""

#fitting svr into dataset
from sklearn.svm import SVR
regressor= SVR(kernel= 'rbf')
regressor.fit(X, y)
#predicting the values
Y_pred = sc_y.inverse_transform(regressor.predict(sc_X.transform(np.array([[6.5]]))))
#visualising the polynomial regression results
plt.scatter(X, y, color= 'red')
plt.plot(X, regressor.predict(X), color= 'blue')
plt.title('truth or bluff SVR regression')
plt.xlabel('position level')
plt.ylabel('Salary')
plt.show()

Part 2 - Regression/Section 7 - Support Vector Regression (SVR)/svr.py