import psycopg2
import os

def create_table():
    command = """create table wordle(
    username VARCHAR(50),
    score INT NOT NULL,
    played_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    CHECK (score between 0 AND 6),
    constraint pk_wordle PRIMARY KEY (username, played_at));
    """

    conn = None
    try:
        DB_URL = os.environ['DATABASE_URL']
        conn = psycopg2.connect(DB_URL)
        cur = conn.cursor()
        cur.execute(command)
        cur.close()
        conn.commit()
    except Exception as e:
        print(e)
    finally:
        if conn is not None:
            print("done")
            conn.close()


# Python script to detect Faces in an image and Drawing a rectangle around it
import cv2 as cv

# https://github.com/opencv/opencv/tree/master/data/haarcascades Github for haarcascade xml
face_cascade = cv.CascadeClassifier("haarcascades\haarcascade_frontalface_default.xml")

img = cv.imread('images\\face1.jpg')

# Converting image to grayscale for more acurate detection
grey_img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

# Scaling an image multiple time for accurate detection
faces=face_cascade.detectMultiScale(grey_img,scaleFactor = 1.1, minNeighbors = 5)

print(faces) # Prints Start x, Start y, Width, Height as numpy array

for x, y, w, h in faces:

        # rectangle(starting pixel coord, end pix coord, color in BGR, Width of rectangle )
        image = cv.rectangle(img, (x,y),(x+w,y+h),(0,255,255),10)

resize_im = cv.resize(image, (800,600))

cv.imshow("Face Detection",resize_im)
cv.waitKey(0)
cv.destroyAllWindows()


import pygame, math
from sprites import Icon

class Bouncer:
    """ two torps following an orbital ellipse around an invisible mass """
    def __init__(self, ex, ey, cx, cy, n1='torp-me.png', n2='torp-me.png'):
        self.ex = ex
        self.ey = ey
        self.cx = cx
        self.cy = cy
        self.l = Icon(n1, self.cx+50, self.cy)
        self.r = Icon(n2, self.cx-50, self.cy)
        self.position(0, 1)
        self.l.draw()
        self.r.draw()

    def position(self, fuse, fuse_max):
        x = self.ex * math.sin(fuse * math.pi / fuse_max)
        y = self.ey * math.cos(fuse * math.pi / fuse_max)
        self.l.move(self.cx - x, self.cy - y)
        self.r.move(self.cx + x, self.cy + y)

    def update(self, fuse, fuse_max):
        r = []
        r.append(self.l.clear())
        r.append(self.r.clear())
        self.position(fuse, fuse_max)
        r.append(self.l.draw())
        r.append(self.r.draw())
        pygame.display.update(r)


from transformers import BertForPreTraining, BertModel

import torch
from torch import nn
from torch.nn import BCELoss

class BertForClozeQA(BertForPreTraining):
    def __init__(self, config):
        super(BertForClozeQA, self).__init__(config)

        self.bert = BertModel(config)
        self.cloze_qa_outputs = nn.Linear(config.hidden_size, 1)

        self.init_weights()

    def forward(self, input_ids=None, attention_mask=None, token_type_ids=None,
                p_mask=None, candidates=None, start_position=None, train=True):
        batch_dim, segment_dim, token_dim = input_ids.size()
        input_ids_flat, attention_mask_flat, token_type_ids_flat = tuple(
            torch.flatten(tensor, 0, 1)
            for tensor in (input_ids, attention_mask, token_type_ids)
        )

        outputs = self.bert(input_ids_flat,
                            attention_mask=attention_mask_flat,
                            token_type_ids=token_type_ids_flat)

        sequence_output, *_ = outputs

        start_logits = (
            self.cloze_qa_outputs(sequence_output)
                .squeeze(-1)
                .reshape(batch_dim, -1)
        )

        p = torch.softmax(start_logits, dim=1)
        pm = p * p_mask
        pm = pm / torch.sum(pm, dim=1, keepdim=True).expand_as(pm)
        pc = torch.bmm(pm.unsqueeze(1), torch.transpose(candidates, 1, 2).float()).squeeze(1)

        outputs = (pc, ) + outputs[2:]

        if train:
            loss_fct = BCELoss()
            loss = loss_fct(pc, start_position.float())

            outputs = (loss, ) + outputs

        return outputs


from webapp2 import Route

import views
import views_admin

routes = [
]

adminRoutes = [
    Route('/image/upload/', 					views_admin.upload,			'image-upload'),
    Route('/image/upload/url/', 				views_admin.upload_url,		'image-upload-url'),
    Route('/image/delete/', 					views_admin.delete,			'image-delete'),

#    Route('/attachment/upload/', 				views_admin.upload,			'image-upload'),
#    Route('/attachment/upload/url/', 			views_admin.upload_url,		'image-upload-url'),
#    Route('/attachment/delete/', 				views_admin.delete,			'image-delete'),
]


import nuke

class Toggler():

	def __init__(self):
		self.name = 'Toggler GUI'
		self.link_selected_str = 'node.link_nodes(node.get_selected_nodes())'
		self.link_classes_str = 'node.link_nodes(node.get_class_nodes())'
		self.remove_selected_str = 'node.remove_nodes(node.get_selected_nodes())'
		self.remove_classes_str = 'node.remove_nodes(node.get_class_nodes())'
		self.create_node()

	def create_node(self):
		'''
		Builds group nuke node
		'''
		# Create node
		toggler_node = nuke.nodes.Group(tile_color='0x20d34ff')

		# Create knobs
			# Links
		link_selected = nuke.PyScript_Knob('link_selected', 'Link Selected', self.link_selected_str)
		link_classes = nuke.PyScript_Knob('link_classes', 'Link Classes', self.link_classes_str)
		link_classes.setFlag(nuke.STARTLINE)
			# Removal
		remove_selected = nuke.PyScript_Knob('remove_selected', 'Remove Selected', self.remove_selected_str)
		remove_classes = nuke.PyScript_Knob('remove_classes', 'Remove Classes', self.remove_classes_str)
			# Other Knobs
		classes = nuke.String_Knob('classes', 'Classes')
		divider = nuke.Text_Knob('divider', '')

		# Attach knobs to tab
		toggler_node.addKnob(link_selected)
		toggler_node.addKnob(remove_selected)
		toggler_node.addKnob(divider)
		toggler_node.addKnob(classes)
		toggler_node.addKnob(link_classes)
		toggler_node.addKnob(remove_classes)

		# Node Renaming
		toggler_node.knob('User').setName('Toggler')
		toggler_node.setName(self.name)

	def get_selected_nodes(self):
		'''
		Returns a list of nodes based on selection in node graph
		'''
		nodes = nuke.root().selectedNodes()
		return nodes

	def get_class_nodes(self):
		'''
		Returns a list of nodes based on classes input knob
		'''
		this_node = nuke.thisNode()
		classes = this_node['classes'].value().split(',')
		node_list = []

		for node in nuke.allNodes(group=nuke.root()):
			node_class = node.Class()
			for i in classes:
				if node_class.__contains__(i.title()):
					node_list.append(node)

		return node_list

	def link_nodes(self, nodes):
		node_list = nodes
		for node in node_list:
			if node != nuke.thisNode():
				node['disable'].setExpression(nuke.thisNode().name() + '.disable')

	def remove_nodes(self, nodes):
		node_list = nodes
		for node in node_list:
			if node['disable'].hasExpression():
				node['disable'].clearAnimated()

node = Toggler()


import csv
def readRawData(name):
	csv_reader = list(csv.reader(open('./fnc_data/'+name, encoding='utf-8')))
	csv_reader.remove(csv_reader[0])
	return csv_reader

def splitData(data,num):
	dataEdit = []
	for i in range(len(data)):
		dataEdit.append(data[i][num])
	return dataEdit

if __name__=='__main__':
	train_bodies = readRawData('train_bodies.csv')
	trainDocs = splitData(train_bodies,1)
	train_stances = readRawData('train_stances.csv')
	test_bodies = readRawData('test_bodies.csv')
	test_stances_unlabeled = readRawData('test_stances_unlabeled.csv')


import socket

HEADERSIZE = 10
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(), 1241))

while True:
    full_msg = ''
    new_msg = True
    while True:
        msg = s.recv(16)
        if new_msg:
            print("new message len: ", msg[:HEADERSIZE])
            msglen = int(msg[:HEADERSIZE])
            new_msg = False

        print('full message len : {}'.format(msglen))

        full_msg += msg.decode('utf-8')

        print(len(full_msg))

        if len(full_msg) - HEADERSIZE == msglen:
            print('full msg received')
            print(full_msg[HEADERSIZE:])
            new_msg = True
            full_msg = ''


"""
本例中,将传递进去一个可调用类(实例)而不仅仅是一个函数。
相比于 mtsleepC.py,这个实现中提供了更加面向对象的方法。

添加了ThreadFunc类,并在实例化 Thread 对象时,同时实例化了可调用类 ThreadFunc。
实际上,这里完成了两个实例化。
为了ThreadFunc类更加通用,而不是局限于 loop()函数,因此添加了一些新的东西,
比如让这个类保存了函数的参数、函数自身以及函数名的字符串。
而构造函数__init__()用于设定上述这些值。
当创建新线程时,Thread 类的代码将调用 ThreadFunc 对象,此时会调用__call__()这个特殊方法。
由于已经有了要用到的参数,这里就不需要再将其传递给 Thread()的构造函数了,直接调用即可。
"""

import threading
from time import sleep, ctime

loops = [4, 2]

class ThreadFunc(object):
    def __init__(self, func, args, name=''):
        self.name = name
        self.func = func
        self.args = args

    def __call__(self):
        self.func(*self.args)

def loop(nloop, nsec):
    print('start loop', nloop, 'at:', ctime())
    sleep(nsec)
    print('loop', nloop, 'done at:', ctime())

def main():
    print('starting at:', ctime())
    threads = []
    nloops = range(len(loops))

    for i in nloops:
        t = threading.Thread(target=ThreadFunc(loop, (i, loops[i]), loop.__name__))
        threads.append(t)

    for i in nloops:
        threads[i].start()

    for i in nloops:
        threads[i].join()

    print('all DONE at:', ctime())

if __name__ == '__main__':
    main()


from django.contrib import admin

from polls.models import Choice, Question

class ChoiceInline(admin.TabularInline):
    """
    Create a inline representation to be used in QuestionAdmin.
    """
    model = Choice
    extra = 3

@admin.register(Question)
class QuestionAdmin(admin.ModelAdmin):
    """
    Question Admin Customization
    """
    list_display = (
        'question_text',
        'pub_date',
        'was_published_recently'
        )
    fieldsets = [
        (None, {
            'fields': ['question_text']
            }
        ),
        ('Date information', {
            'fields': ['pub_date'],
            'classes': ['collapse']
            }
        )]
    inlines = [ChoiceInline]
    list_filter = ['pub_date']


# coding=utf-8
class UserAgent(object):
    def __init__(self, is_mobile, os):
        self.is_mobile = is_mobile
        self.os = os

class UserAgentDetectMiddleware(object):
    def process_request(self, request):
        """
        检测是否是移动浏览器，然后设置is_mobile、os
        @param request:
        @type request:  django.http.HttpRequest
        @return:
        """
        user_agent = request.META['HTTP_USER_AGENT'].lower()
        is_mobile = False
        os = 'Windows'
        if 'micromessenger' in user_agent:
            is_mobile = True
            os = 'MicroChat'
        elif 'android' in user_agent:
            is_mobile = True
            os = 'Andriod'
        elif 'iphone' in user_agent:
            is_mobile = True
            os = 'iPhone/iOS'
        elif 'ipad' in user_agent:
            is_mobile = True
            os = 'iPad/iOS'
        elif 'windows phone' in user_agent:
            is_mobile = True
            os = 'Windows Phone'
        elif 'ucweb' in user_agent:
            is_mobile = True
            os = 'UCWEB'

        ua = UserAgent(is_mobile, os)
        setattr(request, 'ua', ua)


#!/usr/bin/python
"""
A MatchObject represents the matched pattern, based on a RE specification.
A MatchObject is returned if a match is made against a matched object.

A function, that takes MatchObject as a parameter, can be used to process groups matched by () within the RE.
Difference between 'match' and 'search' is that 'search' tries to match the RE at any location of the string, no only at the beginning, which is what the match does.
"""
import re
print(__doc__)

def normalize_orders(matchobj):
  if matchobj.group(1) == '-':
    return 'A'
  else:
    return 'B'

pattern = re.compile('([-|A-Z])')
list = ["-1234", "A193", "C124"]
for code in list:
  print(pattern.sub(normalize_orders, code))


#!/usr/bin/env python3

import sys

def filter_opcode(f):
    for i, line in enumerate(f):
        line = line.strip()

        if i == 0 and line == HEADERS:
            continue

        addr, op_line = line.split(',', 1)
        ops = [op for op in op_line.split() if op in act_words] # filter

        print('%s,%s' % (addr, ' '.join(ops)))

if __name__ == '__main__':

    if len(sys.argv) != 3:
        print('usage: %s <act-words> <csv>' % sys.argv[0])
        sys.exit(1)

    act_file = sys.argv[1]
    csv_file = sys.argv[2]

    act_words = set(open(act_file).read().splitlines())  # a word per line

    HEADERS = 'Addr,Opcodes'
    print(HEADERS)

    with open(csv_file, 'r', encoding='utf-8') as f:
        filter_opcode(f)


import torch
from torch.utils.data import Dataset
from PIL import Image
import numpy as np
from torchvision.transforms.functional import to_tensor
from pathlib import Path

def NormalizeData(data):
    return (data - np.min(data)) / (np.max(data) - np.min(data))

def img_loader(path):
    return Image.open(path).convert('RGB')

def CropPatches(image, patch_size=32, stride=32):
    w, h = image.size
    #image.show()
    patches = ()
    for i in range(0, h-patch_size, stride):
        for j in range(0, w-patch_size, stride):
            patch = to_tensor(image.crop((j, i, j+patch_size, i+patch_size)))
            patches = patches + (patch,)
    return patches

def Split_left_right(image):
    w, h = image.size
    imL = image.crop((0, 0, w/2, h))
    imR = image.crop((w/2, 0, w, h))
    return imL, imR

class SIQADataset(Dataset):
    def __init__(self, dataset, config, index, status):
        self.img_loader = img_loader
        im_dirR = config[dataset]['im_dirR']
        im_dirL = config[dataset]['im_dirL']
        self.patch_size = config['patch_size']
        self.stride = config['stride']

        test_ratio = config['test_ratio']
        train_ratio = config['train_ratio']
        trainindex = index[:int(train_ratio * len(index))]
        testindex = index[int((1 - test_ratio) * len(index)):]
        train_index, test_index = [], []

        im_names = []
        ref_names = []
        for line1 in open("./data/" + dataset + "/im_names_S.txt", "r"):
            line1 = line1.strip()
            im_names.append(line1)
        im_names = np.array(im_names)
        #print("im_names {}".format (im_names))
        typpe = []
        for line10  in open("./data/" + dataset + "/im_names_S.txt", "r"):
            line10 = line10.strip()
            line10 = line10.split("/")

            typpe.append(line10)
        typpe =[item[0] for item in typpe]
        typpe = np.array(typpe)
        #print("type {}".format (typpe))

        for line2 in open("./data/" + dataset + "/refnames_S.txt", "r"):
            line2 = line2.strip()
            ref_names.append(line2)
        ref_names = np.array(ref_names)
        ref_ids = []
        for line0 in open("./data/" + dataset + "/ref_ids_S.txt", "r"):
            line0 = float(line0[:-1])
            ref_ids.append(line0)
        ref_ids = np.array(ref_ids)

        for i in range(len(ref_ids)):
            if(ref_ids[i] in trainindex):
                train_index.append(i)
            elif(ref_ids[i] in testindex):
                test_index.append(i)

        if status == 'train':
            self.index = train_index
            print("#==> Train Images len: {}".format(len(self.index)))
            print('#==> Training Indexes: ', trainindex)
        if status == 'test':
            self.index = test_index
            print("#==> Test Images len: {}".format(len(self.index)))
            print('#==> Test Indexes: ', testindex)
            print('#==> Test Image names: ', im_names[test_index])

        self.mos_s = []
        self.mos_l = []
        self.mos_r = []

        for line_s in open("./data/" + dataset + "/MOS_S.txt", "r"):
            line_s = float(line_s.strip())
            self.mos_s.append(line_s)
        self.mos_s = np.array(self.mos_s)

        for line_l in open("./data/" + dataset + "/MOS_L.txt", "r"):
            line_l = float(line_l.strip())
            self.mos_l.append(line_l)
        self.mos_l = np.array(self.mos_l)

        for line_r in open("./data/" + dataset + "/MOS_R.txt", "r"):
            line_r = float(line_r.strip())
            self.mos_r.append(line_r)
        self.mos_r = np.array(self.mos_r)

        self.patchesR = ()
        self.patchesL = ()

        self.label = []
        self.label_L = []
        self.label_R = []

        self.im_names = [im_names[i] for i in self.index]
        self.ref_names = [ref_names[i] for i in self.index]
        self.mos_s = [self.mos_s[i] for i in self.index]
        self.mos_l = [self.mos_l[i] for i in self.index]
        self.mos_r = [self.mos_r[i] for i in self.index]

        typpe = [typpe[i] for i in self.index]

        for idx in range(len(self.index)):

            img = self.img_loader(Path(str(im_dirL)+ str(self.im_names[idx]) ))
            imL, imR = Split_left_right(img)

            patchesR = CropPatches(imR, self.patch_size, self.stride)
            patchesL = CropPatches(imL, self.patch_size, self.stride)

            if status == 'train':
                self.patchesL = self.patchesL + patchesL
                self.patchesR = self.patchesR + patchesR

                for i in range(len(patchesL)):
                    self.label.append(self.mos_s[idx])
                    self.label_L.append(self.mos_l[idx])
                    self.label_R.append(self.mos_r[idx])

            elif status == 'test':
                self.patchesL = self.patchesL + (torch.stack(patchesL), )
                self.patchesR = self.patchesR + (torch.stack(patchesR), )
                self.label.append(self.mos_s[idx])
                self.label_L.append(self.mos_l[idx])
                self.label_R.append(self.mos_r[idx])

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

    def __getitem__(self, idx):
        return self.patchesL[idx], self.patchesR[idx], (torch.Tensor([self.label[idx]]), torch.Tensor([self.label_L[idx]]), torch.Tensor([self.label_R[idx]]))


from ..extensions import db

# cria a tabela
class Uc(db.Model):
    __tablename__ = "ucs"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    nome = db.Column(db.String(150))
    tipo = db.Column(db.String(50))
    inicio = db.Column(db.Date)
    fim = db.Column(db.Date)

    # mostar o conteudo do objeto
    def __repr__(self):
        return "<Uc(nome={}, tipo={}, inicio={}, fim={})>".format(self.nome, self.tipo, self.inicio, self.fim)


from tkinter import Tk, filedialog
from datetime import datetime
import json

import os
import subprocess
import webbrowser

def runReport(Folders):
    #create folder for new report
    now = datetime.now()
    current_time = now.strftime("%Y%m%d_%H%M%S")
    f = open ('PyRep.json')
    data = json.load (f)
    f.close()

    driveName = data['appDrive']
    folderName = driveName + data['repFolder'] + data['repPrefix'] + current_time
    os.mkdir(folderName)

    #create report parameters
    repExe = driveName + data['repExe']
    reports = '-reports:"'
    for folder in Folders:
        reports += folder + "\\coverage.xml;"
    reports +='" '
    targetdir = '-targetdir:"{PATH}" '.format(PATH=folderName)
    sourcedirs = '-sourcedirs:"' + driveName + data['sourcedirs'] + '"'

    #run the report
    cmd = repExe + reports + targetdir + sourcedirs
    print (cmd)
    subprocess.call(cmd)

    #show the report
    url = "file://" + folderName + '\\index.html'
    webbrowser.open(url)

# MAIN
root = Tk() # pointing root to Tk() to use it as Tk() in program.
root.withdraw() # Hides small tkinter window.
root.attributes('-topmost', True) # Opened windows will be active. above all windows despite of selection.
folders = []
while True:
    path1 = filedialog.askdirectory(title="Select first folder") # Returns opened path as str
    if not path1:
        break
    folders.append(path1)

runReport(folders)


import os

allow_cors_origins = [
    "http://localhost:3000",
    "http://mystation:3000",
    "http://10.112.210.204:3000",
]

DATASET_UPLOAD_PATH="_data/"

UPLOAD_DATASET_EXTENSIONS = ['.zip', '.tar.gz', '.tar']
UPLOAD_IMAGE_EXTENSIONS = ['.jpg', '.jpeg', '.png']
RECORD_LIMIT = 10
TASK_LIST_IPP = 10
DATASET_LIST_IPP = 6

DIRIGNORE = '__MACOSX'

DATABASE_URI = os.getenv("DATABASE_URI", "localhost")
RABBITMQ_URI = os.getenv("RABBITMQ_URI", "localhost")
REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379/0")


from flask import request, render_template, session, abort
from flask import send_from_directory, url_for, redirect
from models.genero import Genero

class GeneroController():

    def __init__(self):
        pass

    def index(self):
        generos = Genero.all()
        return render_template('generos/index.html', generos=generos)

    def new(self):
        errores = []
        if request.method == 'GET':
            return render_template('generos/new.html')
        elif request.method == 'POST':
            if Genero.existe_genero_con_nombre(request.form["nombre"]):
                errores.append(
                    "Ya existe un genero con el nombre especificado.")
                return render_template('generos/new.html', errores=errores)
            else:
                Genero.crear(request.form["nombre"])
                return self.index()

    def edit(self):
        errores = []
        if request.method == 'GET':
            genero = Genero.encontrar_por_id(request.args.get("genero_id"))
            return render_template('generos/edit.html', genero=genero)
        elif request.method == 'POST':
            if Genero.existe_genero_con_nombre(request.form["nombre"]):
                genero = Genero.encontrar_por_id(request.args.get("genero_id"))
                errores.append(
                    "Ya existe un genero con el nombre especificado.")
                return render_template('generos/edit.html', genero=genero, errores=errores)
            else:
                Genero.edit(request.form["nombre"], request.form["id"])
                return self.index()

    def delete(self, genero_id):
        errores = []
        errores.append("Se elimino el genero correctamente")
        genero = Genero.eliminar(genero_id)
        generos = Genero.all()
        return render_template('generos/index.html', generos=generos, errores=errores)

generoController = GeneroController()


#The complete source code for mplwidget.py is:
# Python Qt5 bindings for GUI objects
from PyQt5 import QtGui, QtWidgets
# import the Qt5Agg FigureCanvas object, that binds Figure to
# Qt5Agg backend. It also inherits from QWidget
import matplotlib as MPL
MPL.use("Qt5Agg")

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
# Matplotlib Figure object
from matplotlib.figure import Figure

class MplCanvas(FigureCanvas):
    """Class to represent the FigureCanvas widget"""
    def __init__(self):
        # setup Matplotlib Figure and Axis after defining standard font properties
        font = {'family' : 'serif',
                'weight' : 'bold',
                'size'   : 8}
        axes = {'labelsize' : 12,
                'labelcolor' : 'green'}

        #MPL.rc('font', **font)  # pass in the font dict as kwargs
        #MPL.rc('axes', **axes)
        MPL.rcParams['figure.facecolor'] = 'white'
        MPL.rcParams['figure.autolayout'] = 'TRUE'
        self.fig = Figure()
        self.ax = self.fig.add_subplot(111)
        # initialization of the canvas
        FigureCanvas.__init__(self, self.fig)
        # we define the widget as expandable
        FigureCanvas.setSizePolicy(self,
        QtWidgets.QSizePolicy.Preferred,
        QtWidgets.QSizePolicy.Preferred)
        # notify the system of updated policy
        FigureCanvas.updateGeometry(self)

class MplWidgetSimple(QtWidgets.QWidget):
    """Widget defined in Qt Designer"""
    def __init__(self, parent = None):
        # initialization of Qt MainWindow widget
        QtWidgets.QWidget.__init__(self, parent)
        # set the canvas to the Matplotlib widget
        self.canvas = MplCanvas()
        ## create a vertical box layout
        self.vbl = QtWidgets.QVBoxLayout()
        # add TabWidget to vertical box
        self.vbl.addWidget(self.canvas)
        self.setLayout(self.vbl)


import sys
from operator import itemgetter

import matplotlib
import matplotlib.pyplot as plt
from pymongo import MongoClient

client = MongoClient('mongodb://147.2.212.204:27017/')
prods = client.bz.prods

prod_all = [  'SUSE Linux Enterprise Desktop 12',
              'SUSE Linux Enterprise Desktop 11 SP3',
              'SUSE Linux Enterprise Desktop 11 SP4 (SLED 11 SP4)']

teamMem = ['xdzhang@suse.com', 'xjin@suse.com','yfjiang@suse.com','ychen@suse.com',
           'ysun@suse.com','wjiang@suse.com','whdu@suse.com','sywang@suse.com',
           'yosun@suse.com','nwang@suse.com','bchou@suse.com']

validreso = ['FIXED','UPSTEAM','NORESPONSE','---','MOVED']
invalidreso = ['INVALID','WONTFIX','DUPLICATE','FEATURE','WORKSFORME']

query_limit = {'product':1, 'component':1, 'creator':1, 'resolution':1,
               'severity':1, '_id':0}
result = prods.find({'product':{'$in':prod_all}}, query_limit)
data = [i for i in result]
print(sys.getsizeof(data))

comps = list(set([i['component'] for i in data]))

def get_count(products=[], comps=[], resolutions=[], creators=[]):
    count = 0
    for d in data:
        if products:
            if d['product'] not in products:
                continue
        if comps:
            if d['component'] not in comps:
                continue
        if resolutions:
            if d['resolution'] not in resolutions:
                continue
        if creators:
            if d['creator'] not in creators:
                continue
        count += 1
    return count

def plt_comp():
    N = len(comps)
    count = 0
    colors = ['r', 'y', 'g']
    fig, ax = plt.subplots()
    for prod in prod_all:
        axis_y = []
        ind = [i*2+count*0.5 for i in range(N)]
        for comp in comps:
            allcomps = get_count([prod,], [comp,])
            if allcomps:
                validcomps = get_count([prod,], [comp,], validreso)
                axis_y.append(validcomps/allcomps)
            else:
                axis_y.append(0)

        rects = ax.bar(ind, axis_y, 0.5, color=colors[count])
        count += 1
    plt.axis([ 2*N+2,0, 0, 1.2])
    plt.savefig('foo.png')

plt_comp()


import pytest

from y2021.day_1.main import InputNotArray, NotEnoughValues, depth_measure_with_window
from y2021.day_2.main import pilot_submarine_with_aim

def test_depth_measure_success():
    input_ = ["forward 5", "down 5", "forward 8", "up 3", "down 8", "forward 2"]

    assert pilot_submarine_with_aim(input_) == 900

def test_depth_measure_input_lower_than_2():
    input_ = [199]

    with pytest.raises(NotEnoughValues):
        depth_measure_with_window(input_)

    assert True

def test_depth_measure_input_is_not_a_list():
    input_ = "[199]"

    with pytest.raises(InputNotArray):
        depth_measure_with_window(input_)

    assert True


class Solution(object):
    def pushDominoes(self, d):
        d = 'L' + d + 'R'
        res = []
        i = 0
        for j in range(1, len(d)):
            if d[j] == '.': continue
            middle = j - i - 1
            if i: res.append(d[i])
            if d[i] == d[j]: res.append(d[i] * middle)
            elif d[i] == 'L' and d[j] == 'R': res.append('.' * middle)
            else: res.append('R' * (middle / 2) + '.' * (middle % 2) + 'L' * (middle / 2))
            i = j
        return ''.join(res)


from pydub import AudioSegment
import glob
import sys
import os

# Glob module is used to find files in a directory.
# Sys module is used to access system parameters and methods.
# Os module is used to access operating system specific functions.

class Audio:
    def __init__(self, infiles, dst):
        self.combined = AudioSegment.empty()
        self.infiles = infiles
        self.outfile = dst

    def process(self):
        for file in self.infiles:
            print(file)
            aud = AudioSegment.from_mp3(file)
            self.combined += aud

        self.combined.export(out_f=self.outfile, format="mp3")

# AudioSegment.from_mp3('D:\\backup\\Tora-Mann-Darpan-Kehlaye-beautiful-krishna-Bhajan-By-Asha-Bhonsle.mp3')

# AudioSegment.ffmpeg = os.getcwd()+"\\ffmpeg\\bin\\ffmpeg.exe"
# print (AudioSegment.ffmpeg)

# from pyffmpeg import FFmpeg
#
# inp = 'path/to/music_folder/f.mp4'
# out = 'path/to/music_folder/f.mp3'
#
# ff = FFmpeg().
# print(ff)
# output_file = "\\ffmpeg\\bin\\ffmpeg.exe"+ff.convert(inp, out)
#
# print(output_file)


import logging
import os
import pathlib
import time

import httpx
import regex
import yarl
from tqdm import tqdm

from ...config import FFMPEG_EXECUTABLE, FFMPEG_HLS, FFMPEG_SUBMERGE
from .content_mt import mimetypes
from .ffmpeg import FFMPEG_EXTENSIONS, ffmpeg_download, has_ffmpeg, merge_subtitles
from .hls import HLS_STREAM_EXTENSIONS, hls_yield

if FFMPEG_EXECUTABLE:
    ffmpeg_executable = FFMPEG_EXECUTABLE

EXEMPT_EXTENSIONS = ["mpd"]
CONTENT_DISP_RE = regex.compile(r'filename=(?:"(.+?)"|([^;]+))')

def sanitize_filename(f):
    return "".join(" - " if _ in '<>:"/\\|?*' else _ for _ in f).strip()

def ext_from_filename(filename):
    position = filename.rfind(".")
    if position == -1:
        return ""
    return filename[position + 1 :]

def get_extension(url):
    url = yarl.URL(url)
    return ext_from_filename(url.name)

def guess_extension(content_type):
    if not content_type:
        return ""

    for _, cd, extension in mimetypes:
        if cd == content_type:
            return (extension or "").lstrip(".")

def ext_from_content_disposition(content_disposition):
    match = CONTENT_DISP_RE.search(content_disposition)

    if not match:
        return ""

    return ext_from_filename(match.group(1) or match.group(2))

def process_url(session, url, headers={}):
    """
    Get the extension, content size and range downloadability forehand.

    Returns:

    `str`, `int`, `bool`
    """
    response = session.head(url, headers=headers)
    response_headers = response.headers

    extension = (
        ext_from_content_disposition(
            response_headers.get("content-disposition", "") or ""
        )
        or guess_extension(response_headers.get("content-type", ""))
        or get_extension(url)
        or get_extension(str(response.url))
    ).lower()

    return (
        extension,
        int(response_headers.get("content-length") or 0),
        "bytes" in response_headers.get("accept-ranges", ""),
    )

def standard_download(
    session: httpx.Client,
    url: str,
    content_dir: pathlib.Path,
    outfile_name: str,
    extension: str,
    content_size: int,
    headers: dict = {},
    ranges=True,
    **opts
):
    file = "{}.{}".format(outfile_name, extension)

    logger = logging.getLogger("downloader/standard[{}]".format(file))
    out_path = content_dir / pathlib.Path(sanitize_filename(file))

    if not ranges:
        logger.critical(
            "Stream does not support ranged downloading; failed downloads cannot be continued."
        )

    with open(out_path, "ab") as outstream:
        downloaded = outstream.tell() if ranges else 0
        progress_bar = tqdm(
            desc="GET / {}".format(file),
            total=content_size,
            disable=opts.get("log_level", 20) > 20,
            initial=downloaded,
            unit="B",
            unit_scale=True,
            unit_divisor=1024,
        )
        while content_size > downloaded:
            temporary_headers = headers.copy()
            if ranges:
                temporary_headers.update({"Ranges": "bytes={}-".format(downloaded)})
            try:
                with session.stream("GET", url, headers=headers) as http_stream:
                    http_stream.raise_for_status()

                    for chunks in http_stream.iter_bytes():
                        size = len(chunks)
                        outstream.write(chunks)
                        progress_bar.update(size)
                        downloaded += size
            except httpx.RequestError as e:
                if not ranges:
                    downloaded = 0
                    outstream.seek(0)
                    progress_bar.clear()
                else:
                    outstream.flush()
                logger.error("Downloading error due to {!r}, retrying.".format(e))
                time.sleep(opts.get("retry_timeout") or 5.0)

    progress_bar.close()

def hls_download(
    session: httpx.Client,
    url: str,
    content_dir: pathlib.Path,
    outfile_name: str,
    headers: dict = {},
    **opts
):

    sanitized = sanitize_filename(outfile_name)
    content_path = content_dir / "{}.ts".format(sanitized)
    index_holder = content_dir / "{}.partialts".format(sanitized)
    index = 1

    if index_holder.exists():
        with open(index_holder, "r") as ih:
            index = int(ih.read() or 1)

    sizes = []
    with open(content_path, "ab") as tsstream, open(index_holder, "w+") as istream:
        downloaded = tsstream.tell()
        if downloaded:
            sizes.extend([downloaded / index] * index)
        progress_bar = tqdm(
            desc="HLS GET / {}.ts".format(outfile_name),
            unit="B",
            unit_scale=True,
            unit_divisor=1024,
            initial=downloaded,
            disable=opts.get("log_level", 20) > 20,
        )

        for content in hls_yield(
            session,
            [{"stream_url": url, "headers": headers}],
            opts.get("preferred_quality") or 1080,
            opts.get("retry_timeout") or 5,
            continuation_index=index,
        ):
            stream = content.get("bytes")
            total = content.get("total")
            current = content.get("current")

            size = len(stream)
            sizes.append(size)

            mean = sum(sizes) / len(sizes)
            stddev = (sum(abs(mean - s) ** 2 for s in sizes) / len(sizes)) ** 0.5

            progress_bar.total = mean * total
            progress_bar.desc = "HLS GET / {}.ts [± {:.3f} MB]".format(
                outfile_name, stddev / (1024**2)
            )
            progress_bar.update(size)

            istream.write(str(current or 0 + 1))
            istream.seek(0)
            istream.flush()

            tsstream.write(stream)

    progress_bar.close()
    os.remove(index_holder)

def idm_download(url, headers, content_dir, outfile_name, extension, **opts):
    file = "{}.{}".format(outfile_name, extension)
    from .idmanlib import wait_until_download as idmdl

    idmdl(url, headers=headers or {}, download_folder=content_dir, filename=file)

def subautomatic(f):
    def __inner__(session, url, headers, content_dir, outfile_name, *args, **kwargs):
        logger = logging.getLogger("ffmpeg/submerge")

        subtitles = kwargs.pop("subtitles", [])

        callback = f(session, url, headers, content_dir, outfile_name, *args, **kwargs)

        if not subtitles:
            return

        if (not has_ffmpeg()) or not FFMPEG_SUBMERGE:
            logger.debug("{!r} will not be merged.".format(subtitles))
            for count, subtitle in enumerate(subtitles, 1):
                handle_download(
                    session,
                    subtitle,
                    headers=headers,
                    content_dir=content_dir,
                    outfile_name="{}_SUB_{}".format(outfile_name, count),
                )
            return callback

        extension, _, _ = process_url(session, url, headers)
        resolved_path = (
            content_dir / "{}.{}".format(outfile_name, extension)
        ).resolve()
        subout_path = (
            content_dir / "{} [CC].{}".format(outfile_name, extension)
        ).resolve()

        ffmpeg_returncode = merge_subtitles(
            resolved_path, subout_path, subtitles, log_level=kwargs.get("log_level", 20)
        )

        if ffmpeg_returncode:
            return (
                logger.warning(
                    "Got a non-zero return code {} from ffmpeg, the original file will not be erased in case of merge failure.".format(
                        ffmpeg_returncode
                    )
                )
                or callback
            )

        try:
            os.remove(resolved_path)
        except FileNotFoundError:
            pass

        try:
            os.rename(subout_path, resolved_path)
        except FileNotFoundError:
            pass

        return callback

    return __inner__

@subautomatic
def handle_download(
    session, url, headers, content_dir, outfile_name, idm=False, **opts
):

    extension, content_size, ranges = process_url(session, url, headers)

    if FFMPEG_HLS and (extension in FFMPEG_EXTENSIONS and has_ffmpeg()):
        return ffmpeg_download(url, headers, outfile_name, content_dir, **opts)

    if extension in EXEMPT_EXTENSIONS:
        raise Exception(
            "Download extension {!r} requires custom downloading which is not supported yet.".format(
                extension
            )
        )

    if extension in HLS_STREAM_EXTENSIONS:
        return hls_download(
            session, url, content_dir, outfile_name, headers or {}, **opts
        )

    if idm:
        return idm_download(
            url, headers or {}, content_dir.resolve(), outfile_name, extension, **opts
        )

    return standard_download(
        session,
        url,
        content_dir,
        outfile_name,
        extension,
        content_size,
        headers or {},
        ranges,
        **opts
    )


import json
import logging

from apiflask import abort, input

from ibm.auth import authenticate
from ibm.middleware import log_restore_activity
from ibm.models import (DisasterRecoveryBackup, IBMCloud, IBMImage, IBMKubernetesCluster, IBMSshKey, WorkflowRoot,
                        WorkflowsWorkspace, IBMSatelliteCluster)
from ibm.tasks.draas_tasks.utils import update_payload_with_new_ids
from ibm.web import db as ibmdb
from ibm.web.common.utils import authorize_and_get_ibm_cloud, verify_and_get_region, create_kubernetes_restore_workflow
from ibm.web.ibm.draas import ibm_draas
from .schemas import ClusterRestoreInSchema, DisasterRecoveryRestoreInSchema, AgentClusterRestoreInSchema
from .utils import create_ibm_draas_restore_workflow, region_to_zones

LOGGER = logging.getLogger(__name__)

@ibm_draas.post('/draas_backups/<backup_id>/restore')
@authenticate
@log_restore_activity
@input(DisasterRecoveryRestoreInSchema)
def restore_backup(backup_id, data, user):
    """
    Restore Disaster Recovery Backup
    This request restores Disaster Recovery Backup for a given backup_id
    """
    backup = ibmdb.session.query(DisasterRecoveryBackup).filter_by(id=backup_id).first()
    if not backup:
        message = f"No Disaster recovery Backup found with ID {backup_id}"
        LOGGER.debug(message)
        abort(404, message)

    if backup.status != DisasterRecoveryBackup.SUCCESS:
        message = f"Disaster recovery Backup with ID {backup_id} not ready"
        LOGGER.debug(message)
        abort(400, message)

    blueprint = backup.disaster_recovery_resource_blueprint

    if data["resource_type"] == "IKS":
        restore_type_existing_iks = data.get("restore_type_existing_iks")
        kubernetes_cluster_target = ibmdb.session.query(IBMKubernetesCluster).filter_by(
            id=restore_type_existing_iks["ibm_cluster_target"]["id"]
        ).first()

        if not kubernetes_cluster_target:
            message = f'IBM Kubernetes Cluster {restore_type_existing_iks["ibm_cluster_target"]["id"]} does not exist'
            LOGGER.debug(message)
            abort(404, message)

        cos_bucket_id = blueprint.resource_metadata["cos_bucket_id"]
        cos_access_keys_id = blueprint.resource_metadata["cos_access_keys_id"]
        namespaces = blueprint.resource_metadata["namespaces"]
        task_metadata = {
            "ibm_cloud": {
                "id": restore_type_existing_iks["ibm_cloud"]["id"]
            },
            "cos_bucket_id": cos_bucket_id,
            "cos_access_keys_id": cos_access_keys_id,
            "backup_name": backup.name,
            "namespaces": namespaces,
            "backup_id": backup_id,
            "workflow_name": f"{DisasterRecoveryBackup.__name__} {kubernetes_cluster_target.name}",
            "email": user.get("email"),
            "resource_type": data["resource_type"],
            "user": user
        }
        backup_provider = backup.backup_metadata['resource_json'].get('provider')
        task_metadata["backup_provider"] = backup_provider
        if backup_provider and backup_provider != "vpc-gen2":  # Classic cluster backup
            kubernetes_cluster = ibmdb.session.query(IBMKubernetesCluster).filter_by(
                id=restore_type_existing_iks["ibm_cluster_source"]["id"]
            ).first()
            if not kubernetes_cluster:
                message = f'IBM Kubernetes Cluster {restore_type_existing_iks["ibm_cluster_source"]["id"]} does not ' \
                          f'exist'
                LOGGER.debug(message)
                abort(404, message)

            resource_json = {
                "name": kubernetes_cluster_target.name,
                "target_resource_id": kubernetes_cluster_target.resource_id,
                "resource_id": kubernetes_cluster.resource_id,
                "target_cluster_hostname": kubernetes_cluster_target.ingress.get("hostname"),
                "classic_cluster_name": kubernetes_cluster.name,
                "classic_cluster_ingress_hostname": kubernetes_cluster.ingress.get("hostname")
            }

        else:
            resource_json = {
                "name": kubernetes_cluster_target.name,
                "resource_id": kubernetes_cluster_target.resource_id
            }

        task_metadata["resource_json"] = resource_json
        workflow_root = create_ibm_draas_restore_workflow(data=task_metadata, user=user)
        return workflow_root.to_json(metadata=True)
    else:
        from ibm.web.ibm.workspaces.utils import create_workspace_workflow
        cloud_id = data["ibm_cloud"]["id"]
        region_id = data["region"]["id"]

        ibm_cloud = authorize_and_get_ibm_cloud(cloud_id=cloud_id, user=user)
        verify_and_get_region(ibm_cloud=ibm_cloud, region_id=region_id)

        workspace_payload = backup.backup_metadata["workspace_payload"]
        updated_workspace_payload = update_payload_with_new_ids(workspace_payload)
        if workspace_payload.get("address_prefixes"):
            old_region_id = updated_workspace_payload["address_prefixes"][0]["region"]["id"]

            zones_old_ids = region_to_zones(old_region_id)
            zones_new_ids = region_to_zones(region_id)

            json_dict_str = json.dumps(updated_workspace_payload)
            json_dict_str = json_dict_str.replace(old_region_id, region_id)

            for old_id, new_id in zip(zones_old_ids, zones_new_ids):
                json_dict_str = json_dict_str.replace(old_id[0], new_id[0])

            updated_workspace_payload = json.loads(json_dict_str)

        for ibm_ssh_key in updated_workspace_payload['ssh_keys']:
            ssh_key = ibmdb.session.query(IBMSshKey).filter_by(name=ibm_ssh_key["resource_json"]['name'],
                                                               public_key=ibm_ssh_key["resource_json"]['public_key'],
                                                               region_id=ibm_ssh_key["region"]["id"]).first()
            if ssh_key:
                for instance in updated_workspace_payload.get("instances"):
                    for key in instance.get("resource_json").get("keys"):
                        if key.get("name") == ssh_key.name:
                            key["id"] = ssh_key.id
                updated_workspace_payload["ssh_keys"].remove(ibm_ssh_key)

        for instance_images in updated_workspace_payload["instances"]:
            image = instance_images["resource_json"].get("image")
            if not image:
                continue
            if image.get("name"):
                instance_images["resource_json"]["image"].pop("id", None)
                continue
            old_image = ibmdb.session.query(IBMImage).filter_by(
                region_id=old_region_id, cloud_id=cloud_id, id=instance_images["resource_json"]["image"]["id"]
            ).first()
            if old_image:
                new_image = ibmdb.session.query(IBMImage).filter_by(region_id=region_id, cloud_id=cloud_id,
                                                                    name=old_image.name).first()
                if new_image:
                    updated_workspace_payload["instances"][0]["resource_json"]["image"]["id"] = new_image.id

        updated_workspace_payload["cloud_id"] = blueprint.cloud_id
        updated_workspace_payload["backup_name"] = backup.name
        updated_workspace_payload['resource_type'] = blueprint.resource_type
        updated_workspace_payload['project_id'] = user.get("project_id")
        updated_workspace_payload["user_id"] = user.get("id")

        workspace_tree = create_workspace_workflow(user, data=updated_workspace_payload, backup_id=backup_id,
                                                   source_cloud=WorkflowsWorkspace.IBM,
                                                   workspace_type=WorkflowsWorkspace.TYPE_RESTORE)
        for workflow_root in workspace_tree.associated_roots.all():
            workflow_root.status = WorkflowRoot.STATUS_READY
            ibmdb.session.commit()

        workspace_tree.status = WorkflowsWorkspace.STATUS_PENDING
        ibmdb.session.commit()

        return workspace_tree.to_json()

@ibm_draas.post('/draas-eks-restores')
@authenticate
@input(ClusterRestoreInSchema)
def restore_eks_backup(data, user):
    """
    Restore Disaster Recovery EKS Backup in IKS cluster
    This request restores Disaster Recovery Backup for a eks backup
    """
    cloud = data["ibm_cloud"]
    cloud["user_id"] = user["id"]
    cloud["project_id"] = user["project_id"]
    ibm_cloud = ibmdb.session.query(IBMCloud).filter_by(
        **cloud
    ).first()
    if not ibm_cloud:
        message = f"IBM Cloud {cloud['id'] if cloud.get('id') else cloud.get('name')} not found"
        LOGGER.debug(message)
        abort(404, message)

    if ibm_cloud.status != IBMCloud.STATUS_VALID:
        message = f"IBM Cloud {ibm_cloud.name} is not in {IBMCloud.STATUS_VALID} status"
        LOGGER.debug(message)
        abort(404, message)

    cluster = data["cluster"]
    cluster["cloud_id"] = ibm_cloud.id
    kubernetes_cluster = ibmdb.session.query(IBMKubernetesCluster).filter_by(
        **cluster
    ).first()
    if not kubernetes_cluster:
        message = f'IBM Kubernetes Cluster {cluster["id"] if data["cluster"].get["id"] else cluster["name"]} does ' \
                  f'not exist'
        LOGGER.debug(message)
        abort(404, message)

    workflow_root = create_kubernetes_restore_workflow(user, IBMKubernetesCluster, data)
    return workflow_root.to_json()

@ibm_draas.post('/draas-satellite-restores')
@authenticate
@input(AgentClusterRestoreInSchema)
def restore_eks_backup_satellite_cluster(data, user):
    """
    Restore Disaster Recovery EKS Backup in Satellite cluster
    This request restores Disaster Recovery Backup for a eks backup
    """
    cloud = data["ibm_cloud"]
    cloud["user_id"] = user["id"]
    cloud["project_id"] = user["project_id"]
    ibm_cloud = ibmdb.session.query(IBMCloud).filter_by(
        **cloud
    ).first()
    if not ibm_cloud:
        message = f"IBM Cloud {cloud['id'] if cloud.get('id') else cloud.get('name')} not found"
        LOGGER.debug(message)
        abort(404, message)

    if ibm_cloud.status != IBMCloud.STATUS_VALID:
        message = f"IBM Cloud {ibm_cloud.name} is not in {IBMCloud.STATUS_VALID} status"
        LOGGER.debug(message)
        abort(404, message)

    cluster = data["cluster"]
    agent_id = data['agent_id']
    cluster["cloud_id"] = ibm_cloud.id
    satellite_cluster = ibmdb.session.query(IBMSatelliteCluster).filter_by(
        **cluster
    ).first()
    if not satellite_cluster:
        message = f'IBM Satellite Cluster {cluster["id"] if data["cluster"].get["id"] else cluster["name"]} does ' \
                  f'not exist'
        LOGGER.debug(message)
        abort(404, message)

    satellite_cluster.agent_id = agent_id
    ibmdb.session.commit()

    workflow_root = create_kubernetes_restore_workflow(user, IBMSatelliteCluster, data)
    return workflow_root.to_json()


#!/usr/bin/env python

PACKAGE = 'usma_remote_interface'
import roslib
roslib.load_manifest(PACKAGE)
import rospy

from geometry_msgs.msg import TwistStamped, Twist
from std_msgs.msg import String
from math import sin, cos, pi, sqrt, asin, atan2, log
from threading import Thread
import time

# actually controls the velocity based on the multiple inputs provided
class cmdDemux:
  def __init__(self):
    rospy.init_node('usma_remote_cmd_demux', anonymous=True)

    self.update_freq = rospy.get_param('/usma_remote/updateFreq', 10.0)
    self.teleopGain = rospy.get_param('/usma_remote/teleopGain', 1.0)

    self.teleopData = None
    self.teleopTime = None
    rospy.Subscriber('/usma_remote/webcmd', TwistStamped, self.teleop)

    self.topics = []
    self.updateTimes = {}
    self.publishers = {}
    self.curCmds = {}

    self.alive=True

  def teleop(self, data):
    if( data.header.frame_id in self.topics ):
        self.updateTimes[data.header.frame_id] = time.time()
        self.curCmds[data.header.frame_id] = data.twist
    else:
        self.topics.append( data.header.frame_id )
        self.updateTimes[data.header.frame_id] = time.time()
        self.curCmds[data.header.frame_id] = data.twist
        self.publishers[data.header.frame_id] = rospy.Publisher( "/usma_remote/"+data.header.frame_id, Twist )

  def cmdDemuxControl(self):
    rate = rospy.Rate(self.update_freq)
    while self.alive == True and not rospy.is_shutdown():
      rate.sleep()
      for t in self.topics:
        outTwist = Twist()
        outTwist.linear.x = 0.0
        outTwist.angular.z = 0.0
        if (time.time()-self.updateTimes[t])<(1/self.update_freq * 10.0): # don't publish if we haven't gotten anything for 10 cycles
           outTwist.linear.x +=  (self.curCmds[t].linear.x*self.teleopGain)
           outTwist.angular.z += (self.curCmds[t].angular.z*self.teleopGain)
        self.publishers[t].publish(outTwist)

if __name__ == '__main__':
	try:
		move = cmdDemux()
		t = Thread(target=move.cmdDemuxControl)
		t.start()
		rospy.spin()
		move.alive = False
		t.join()
	except rospy.ROSInterruptException: pass


from aocutils import get_raw

from collections import defaultdict, Counter
from math import ceil

def problem1():
    return simulate(10)

def problem2():
    return simulate(40)

def simulate(steps):
    mapping, counts = parse_input()
    for _ in range(steps):
        counts = Counter({pair: sum(counts[starter] for starter in starters) for pair, starters in mapping.items()})
    return calc_answer(counts)

def parse_input():
    template, rules = get_raw(14).split('\n\n')
    mapping = defaultdict(list)
    for rule in rules.splitlines():
        pair, insert = rule.split(' -> ')
        mapping[pair[0] + insert].append(pair)
        mapping[insert + pair[1]].append(pair)
    counts = Counter()
    for i in range(len(template) - 1):
        counts[template[i:i + 2]] += 1
    return mapping, counts

def calc_answer(counts):
    elements = Counter()
    for pair, count in counts.items():
        elements[pair[0]] += count
        elements[pair[1]] += count
    return ceil((max(elements.values()) - min(elements.values())) / 2)


import os
from pytube import Playlist, YouTube

def download_video(url, folder, number_videos, skip_existing):
    try:
        if 'playlist' in url:
            playlist = Playlist(url)
            videos = playlist.video_urls
        else:
            videos = [url]

        download_path = os.path.join(os.getcwd(), folder)
        os.makedirs(download_path, exist_ok=True)

        for i, video in enumerate(videos, start=1):
            youtube = YouTube(video)
            stream = youtube.streams.get_highest_resolution()

            if number_videos:
                title = f'{i:02d} - {youtube.title}'
            else:
                title = youtube.title

            filename = f'{title}.{stream.subtype}'.replace(':', '_')

            file_path = os.path.join(download_path, filename)
            if skip_existing and os.path.exists(file_path):
                print(f'Skipping existing file: {filename}')
                continue

            stream.download(output_path=download_path, filename=filename)

            print(f'Downloaded video {i}/{len(videos)}: {filename}')

        print('Beeep boop! Download complete!')
    except Exception as e:
        print('Error:', str(e))

def main():
    print('Beeep boop! Welcome to the YouTube video/playlist downloader app!')

    url = input('Enter the YouTube video or playlist link: ')
    folder = input('Enter the download folder name: ')
    number_videos = input('Should the videos be numbered in the playlist order? (Y/N): ')
    number_videos = number_videos.lower() == 'y'
    skip_existing = input('Should existing files be skipped? (Y/N): ')
    skip_existing = skip_existing.lower() == 'y'

    download_video(url, folder, number_videos, skip_existing)

if __name__ == '__main__':
    main()


from behave import given, then, when, step
import requests
import subprocess
import json
import os

@step('Using "{server}" as endpoint')
def set_endpoint(context, server):
    context.endpoint = server

@step('Working with "{mode}" mode')
def set_server_mode(context, mode):
    context.mode = mode
    context.endpoint = context.endpoint + '/' + mode

@step('Load "{template}" body as template request')
def load_default_json(context, template):
    base_path = os.path.dirname(__file__)
    template_path = os.path.join(base_path, 'utils/bodyTest.json')
    with open(template_path, 'r') as fd:
        context.template = json.loads(fd.read())

@step('Using {method} method to ask {code} as mocked code')
@step('Using {method} method')
def set_request(context, method, code=None):
    context.req_method = method
    if code is not None:
        set_code_to_request(context, code)

@step('Ask {code} as mocked code')
def set_code_to_request(context, code):
    context.req_code = code
    if context.mode == 'mockurl':
        request_mockurl(context)
    else:
        request_mockserver(context)

@step('I get the requested code')
def check_requested_code(context):
    assert int(context.req_code) == int(context.response.status_code),\
        f'Differences between requests [{context.req_code}] and response code [{context.response.status_code}]'

def request_mockurl(context):
    if context.req_method == 'GET':
        context.response = requests.get(f'{context.endpoint}/{context.req_code}')
    elif context.req_method == 'POST':
        context.response = requests.post(f'{context.endpoint}/{context.req_code}')

def content_length(body_to_send):
    str = json.dumps(body_to_send)
    return (len(str.encode('utf-8')))

def request_mockserver(context):
    context.req_body = dict(context.template['content'])
    context.req_body['message']['messages'][0]['text']['body'] = context.req_code
    context.req_headers = context.template['header']
    context.req_headers['Content-Length'] = str(content_length(context.req_body))
    if context.req_method == 'POST':
        context.response = requests.post(context.endpoint, headers=context.req_headers, json=context.req_body)
    else:
        pass


' tuple packing and unpacking '

a=10
b=20
c=30
t=a,b,c

print(t)
print(id(t))

t=(70,80,90)
print(id(t))
d,e,f = t

print('d={},e={},f={}'.format(d,e,f))

t='nanda'
i,j,k,l,m=t
print(i,j,k,l,m)
i,j,k,l,m,n=t #ValueError: not enough values to unpack (expected 6, got 5)


#CALENDAR MODULE

import calendar
calendar.setfirstweekday(calendar.MONDAY)
mm,dd,yyyy = map(int,input().split())
weekdays = ['MONDAY','TUESDAY','WEDNESDAY','THURSDAY','FRIDAY','SATURDAY','SUNDAY']
n = calendar.weekday(yyyy,mm,dd)
print(weekdays[n])


from countryCodeConversion import countryCodeConversion
from database import database
import csv

# Sutter's Initial Query Test
# Region: East Africa

def main():
    # Create database connector using database class
    databaseConnector = database()

    # Converter from conversion class
    converter = countryCodeConversion()

    # Countries to query for
    targetCountries = ["Angola", "Benin", "Burkina Faso", "Cameroon", "Central African Republic", "Congo, the Democratic Republic of the", "Congo", "Equatorial Guinea", "Gabon", "Gambia", "Ghana", "Guinea-Bissau", "Liberia", "Mali", "Mauritania", "Namibia", "Niger", "Nigeria", "Senegal", "Sierra Leone", "Togo"]
    #"Cote d'Ivoire" fails
    # Find counts and avg of numSources using China as Actor1 or Actor2 and target country as ActionGeo
    #getCountAndAvgNumSources(targetCountries, databaseConnector, converter)

    # Compare counts with two techniqes
    #countComparisonByTechniquue(targetCountries, databaseConnector, converter)

    # Get sources for first event in a country
    getSourcesForEvents("Nigeria", databaseConnector, converter)

def getSourcesForEvents(targetCountry, databaseConnector, converter):
    fields = ['Source Name', 'Mention Count']
    with open("sourceCountsWestAfrica.csv", 'w') as csvfile:
        # creating a csv writer object
        csvwriter = csv.writer(csvfile)

        # writing the fields
        csvwriter.writerow(fields)

        shortCountryCode = converter.fipsNameToCode(targetCountry)
        results = databaseConnector.execute("SELECT MentionSourceName, count(*) as sourceMentionCount FROM eventmentions WHERE GLOBALEVENTID in (SELECT GLOBALEVENTID FROM events WHERE (Actor1CountryCode = 'CHN' OR Actor2CountryCode = 'CHN') AND ActionGeo_CountryCode = '" + shortCountryCode + "') group by MentionSourceName ORDER BY sourceMentionCount DESC;")
        print(results)

        for source in results:
            csvwriter.writerow([source[0], source[1]])

def getCountAndAvgNumSources(targetCountries, databaseConnector, converter):
    fields = ['Country Name', 'FIPS-10 Code', 'Event Count', 'Average NumSources']

    with open("countWestAfricas.csv", 'w') as csvfile:
        # creating a csv writer object
        csvwriter = csv.writer(csvfile)

        # writing the fields
        csvwriter.writerow(fields)

        # Convert countries to codes
        for country in targetCountries:
            countryCode = converter.fipsNameToCode(country)
            result = databaseConnector.execute("SELECT count(*), avg(NumSources) FROM events WHERE (Actor1CountryCode = 'CHN' OR Actor2CountryCode = 'CHN') AND ActionGeo_CountryCode = '" + countryCode + "'")
            csvwriter.writerow([country, countryCode, result[0][0], result[0][1]])
            print(country + "(" + countryCode + ")" + ":  " + str(result[0][0]) + " : " + str(result[0][1]))

def countComparisonByTechniquue(targetCountries, databaseConnector, converter):
    fields = ['Country Name', 'FIPS-10 Code', 'Event Count Actor=China and Action=Target', 'Event Count Actor1=China Actor2=Target OR Actor1=Target Actor2=China']

    with open("countsCompareWestAfrica.csv", 'w') as csvfile:
        # creating a csv writer object
        csvwriter = csv.writer(csvfile)

        # writing the fields
        csvwriter.writerow(fields)

        # Convert countries to codes
        for country in targetCountries:
            countryCode = converter.nameToCode(country)
            shortCountryCode = converter.fipsNameToCode(country)
            result1 = databaseConnector.execute("SELECT count(*) FROM events WHERE (Actor1CountryCode = 'CHN' OR Actor2CountryCode = 'CHN') AND ActionGeo_CountryCode = '" + shortCountryCode + "'")
            result2 = databaseConnector.execute("SELECT count(*) FROM events WHERE (Actor1CountryCode = 'CHN' AND Actor2CountryCode = '" + countryCode + "')")
            result3 = databaseConnector.execute("SELECT count(*) FROM events WHERE (Actor2CountryCode = 'CHN' AND Actor1CountryCode = '" + countryCode + "')")
            csvwriter.writerow([country, countryCode, result1[0][0], result2[0][0]+result3[0][0]])
            print(country + " (" + countryCode + ") " + str(result1[0][0]) + " " + str(result2[0][0] + result3[0][0]) )

if __name__== "__main__":
    main()


import numpy as np   # check out how to install numpy
from utils import load, plot_sample
from PIL import Image
import matplotlib.pyplot as plt
from collections import Counter

def KNN_classify(k,X,training_data):
    Xtrain = training_data[0]
    Ytrain = training_data[1]
    #open a dict to store the label of eachdatapoint (by distance)
    d = {}
    # Iterate for each training datapoint:
    # ------

    for i, digit in enumerate(Xtrain):
        # calc auclidien distanse:
        # -then save in a HashTable
        distance = np.linalg.norm(X - digit)
        d[i] = distance

    # get K minimum distance neighbors
    k_nearst_neighbors = sorted(d, key=d.get)[:k]

    arr = []
    # run over each of nearest n's, and count them.
    for index in k_nearst_neighbors:
        neighbor = Ytrain[index]
        arr.append(neighbor[0])

    # return the most common digit among k neighbors
    return Counter(arr).most_common()[0][0]