import urllib2
import simplejson

from django.core.management.base import BaseCommand, CommandError
from django.conf import settings

from accounts.models import Account
from accounts.models import Referral
from accounts.models import MailingList

class Command(BaseCommand):
    help = 'Update database with server data'

    def handle(self, *args, **options):
        """
        Get JSON response from server, parse it and save to the database
        """
        #create url with headers and get response from request
        req = urllib2.Request(
            "%s?username=%s&api_key=%s" %
            (settings.NL_SETTINGS['url'], settings.NL_SETTINGS['username'],
             settings.NL_SETTINGS['api_key'])
            )

        req.add_header('Accept','application/json')
        req.add_header('Content-Type','application/json')

        opener = urllib2.build_opener()
        f = opener.open(req)
        server_data = simplejson.load(f)

        #data from server contents meta information and objects
        for object_data in server_data['objects']:
            referral = Referral()
            referral.name = object_data['tr_referral']['name']
            referral.resource_uri = object_data['tr_referral']['resource_uri']
            referral.save()

            account = Account()
            account.birth_date = object_data['birth_date']
            account.city = object_data['city']
            account.email = object_data['email']
            account.first_name = object_data['first_name']
            account.gender = object_data['gender']
            account.last_name = object_data['last_name']
            account.lead = object_data['lead']
            account.last_name = object_data['last_name']
            account.phone = object_data['phone']
            account.resource_uri = object_data['resource_uri']
            account.street_number = object_data['street_number']
            account.tr_input_method = object_data['tr_input_method']
            account.ip_address = object_data['ip_address']
            account.tr_language = object_data['tr_language']
            account.utm_campaign = object_data['utm_campaign']
            account.utm_medium = object_data['utm_medium']
            account.utm_medium = object_data['utm_source']
            account.utm_medium = object_data['zipcode']
            account.tr_referral = referral
            account.save_from_server()

            for mailing_list_data in object_data['mailing_lists']:
                mailing_list = MailingList()
                mailing_list.name = mailing_list_data['name']
                mailing_list.resource_uri = mailing_list_data['resource_uri']
                mailing_list.save()
                account.mailing_lists.add(mailing_list)

            account.save_from_server()


# @Time    : 4/25/23 9:33 AM
# @Author  : Zhou-Lin-yong
# @File    : Image_transform.py
# @SoftWare: PyCharm
from imutils import paths
import read_caltech101
from collections import Counter
from sklearn.model_selection import train_test_split
from torchvision.transforms import transforms
from torch.utils.data import DataLoader, Dataset

image_paths = list(paths.list_images('./caltech101_data/101_ObjectCategories'))
data, name2label, labels = read_caltech101.data_processor(image_paths, size=65)
print(Counter(labels))
# Counter({44: 800, 89: 798, 29: 435, 82: 435, 30: 239, 49: 200, 69: 128, 4: 123, 17: 114, 83: 107, 26: 100…………})

train_transform = transforms.Compose(
    [transforms.ToPILImage(),
     transforms.ToTensor(),
     transforms.Normalize(mean=[0.485, 0.456, 0.406],
                          std=[0.229, 0.224, 0.225])])
val_transform = transforms.Compose(
    [transforms.ToPILImage(),
     transforms.ToTensor(),
     transforms.Normalize(mean=[0.485, 0.456, 0.406],
                          std=[0.229, 0.224, 0.225])])

(X, x_val, Y, y_val) = train_test_split(data, labels,
                                        test_size=0.2,
                                        stratify=labels,
                                        random_state=42)
(x_train, x_test, y_train, y_test) = train_test_split(X, Y,
                                                      test_size=0.25,
                                                      random_state=42)
print(f"x_train examples: {x_train.shape}\nx_test examples: {x_test.shape}\nx_val examples: {x_val.shape}")

class ImageDataset(Dataset):
    def __init__(self, images, labels=None, transforms=None):
        self.X = images
        self.y = labels
        self.transforms = transforms

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

    def __getitem__(self, i):
        data = self.X[i][:]

        if self.transforms:
            data = self.transforms(data)

        if self.y is not None:
            return (data, self.y[i])
        else:
            return data

def data_loader(batch_size=64):
    train_data = ImageDataset(x_train, y_train, train_transform)
    val_data = ImageDataset(x_val, y_val, val_transform)
    test_data = ImageDataset(x_test, y_test, val_transform)

    train_loader = DataLoader(train_data, batch_size=batch_size, shuffle=True)
    val_loader = DataLoader(val_data, batch_size=batch_size, shuffle=True)
    test_loader = DataLoader(test_data, batch_size=batch_size, shuffle=False)

    return train_loader, val_loader, test_loader


import requests
from bs4 import BeautifulSoup

def time_temperature(location, leave_time, home_time):
    url = f"https://search.naver.com/search.naver?where=nexearch&sm=top_hty&fbm=0&ie=utf8&query={location}+날씨정보"
    html = requests.get(url)
    soup = BeautifulSoup(html.text, 'html.parser')

    data1 = soup.find('div', {'class':'graph_inner _hourly_weather'})
    data2 = data1.find_all('dt', attrs={'class': 'time'})
    data3 = data1.find_all('span', attrs={'class': 'num'})

    a = []
    b = []

    for d in data2: # 시간 정보
        try:
            t = d.get_text()[:2]
            a.append(int(t))
        except:
            a.append(24)

    for d in data3: # 기온 정보
            t = list(d.get_text())
            t = t[:len(t)-1]
            b.append(int(''.join(t)))

    temp = [0] * len(a) # index: 시간, value: 기온

    for i in range(len(a)):
        temp[a[i]] = b[i]
        if a[i] == home_time: break

    return temp[leave_time:home_time+1] # 출발 시간에서 귀가 시간까지 기온 return


from django.shortcuts import render,get_object_or_404,redirect,reverse
from django.views.generic import View
from comments.forms import CommentForm
from article.models import Article
from comments.models import Comment
# Create your views here.

class add_comment(View):
    def post(self,request,id):
        cf = CommentForm(request.POST)
        if cf.is_valid():
            article=get_object_or_404(Article, pk=id)
            username=cf.cleaned_data['name']
            # email=cf.changed_data['email']
            email=request.POST.get('email')
            url=request.POST.get('url')
            # url=cf.changed_data['url']
            # comment=cf.changed_data['comment']
            comment = request.POST.get('comment')
            c=Comment()
            c.username=username
            c.url=url
            c.article=article
            c.email=email
            c.content=comment
            c.save()
            return redirect(reverse('article:detail',args=(id,)))
        else:
            return redirect(reverse('article:detail',args=(id,)))


import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()

# Import data (Make sure to parse dates. Consider setting index column to 'date'.)
df = pd.read_csv('fcc-forum-pageviews.csv', index_col = 'date')

df.index = pd.to_datetime(df.index)

# Clean data
df = df.loc[(df['value'] >= df['value'].quantile(0.025)) & (df['value'] <= df['value'].quantile(0.975))]

def draw_line_plot():
    # Draw line plot
    fig, ax1 = plt.subplots()

    df.plot.line(ax=ax1, legend = False)
    ax1.set_title('Daily freeCodeCamp Forum Page Views 5/2016-12/2019')
    ax1.set(xlabel = 'Date', ylabel = 'Page Views')

    # Save image and return fig (don't change this part)
    fig.savefig('line_plot.png')
    return fig

def draw_bar_plot():
    # Copy and modify data for monthly bar plot
    df_bar = df.copy()
    df_bar.reset_index(inplace=True)
    df_bar['Years'] = [d.year for d in df_bar.date]
    #df_bar['Months'] = [d.strftime('%B') for d in df_bar.date]
    df_bar['Months'] = [d.strftime('%m') for d in df_bar.date]

    #df_bar = df_bar.groupby(['Months', 'Years'], as_index = False).mean()

    df_bar = df_bar.groupby(['Years', 'Months']).mean()

    df_bar = df_bar.unstack()

    months = ['January', 'February', 'March', 'April','May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']

    # Draw bar plot

    '''fig = sns.catplot(x = 'Years', y = 'value', hue = 'Months', data= df_bar, kind = 'bar', hue_order = ['January', 'February', 'March', 'April','May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'])
    fig.set_axis_labels("Years", "Average Page Views")'''

    fig, ax = plt.subplots()

    df_bar.plot.bar(ax=ax)

    ax.set(xlabel = 'Years', ylabel = 'Average Page Views')
    ax.legend(labels=months, title = 'Months')

    # Save image and return fig (don't change this part)
    fig.savefig('bar_plot.png')
    return fig

def draw_box_plot():
    # Prepare data for box plots (this part is done!)
    df_box = df.copy()
    df_box.reset_index(inplace=True)
    df_box['Year'] = [d.year for d in df_box.date]
    df_box['Month'] = [d.strftime('%b') for d in df_box.date]

    # Draw box plots (using Seaborn)

    fig, (ax1, ax2) = plt.subplots(1, 2)

    sns.boxplot(x=df_box['Year'], y=df_box['value'], ax=ax1)

    sns.boxplot(x=df_box['Month'], y=df_box['value'], order = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], ax=ax2)

    ax1.set(ylabel = 'Page Views', title = 'Year-wise Box Plot (Trend)')
    ax2.set(ylabel = 'Page Views', title= 'Month-wise Box Plot (Seasonality)')

    # Save image and return fig (don't change this part)
    fig.savefig('box_plot.png')
    return fig


from src.core.youtube.youtube_video import YouTubeVideo
from youtubesearchpython import VideosSearch

def search_for_videos(search_string):
    try:
        result = VideosSearch(search_string, limit=10).result().get('result')
    except Exception as e:
        print(e)
        raise Exception(e)

    return [
        YouTubeVideo(
            id=data['id'],
            url=data['link'],
            thumbnail_url=data['thumbnails'][0]['url'],
            title=data['title'],
            views=int((data['viewCount']['text']).replace(' views', '').replace(',', '')),
            views_extense=data['viewCount']['short'],
            duration=data['duration']
        ) for data in result]


from os import path
from git import Repo
import subprocess
import git
import sys

repo_path = "C:/Users/lava/lavadocker"
repository = Repo.init(repo_path)
AUTH="auth_creds for accesing nugget/packages/artifactory/libraries"
REGISTRY="Library/nugget/package management tool url"
branch = "test3"

repo = git.Repo(repo_path)
print("GIT init completed")

print("clone started")
#git.Git(repo_path).clone("https://github.com/xxxxxx.git")
print("clone completed")

print("checkout started")
repo.git.checkout(branch)
print("checkout completed")

print("pull started")
repo = git.Repo('C:/Users/lava/lavadocker')
origin = repo.remote(name='origin')
origin.pull()
print("pull completed")

#git.cmd.Git().pull('https://github.com/xxxxx.git','main')
########## Clonning teh github repo ##########
# repo = git.Repo('/Users/lava/lavadocker')
# repo.remotes.upstream.pull('master')
#git.Repo.clone_from('https://github.com/xxxxxx.git', '/Users/lava/lavadocker')

#print("Clonned the repo from GitHub")
# Git Pull #

# repo = git.Repo('reactauth')
# origin = repo.remote(name='origin')
# origin.pull()

############## Docker image creation ####################
branch = "cd /Users/lava/lavadocker && git branch"
subprocess.call(branch, shell=True)

############## To Pass auth and registry as arguments ex: python3 gitclone.py <authtoken> <registry>/ ####################

# docker_build = "docker build --no-cache --build-arg ARTIFACTORY_AUTH="+sys.argv[1]+" --build-arg REGISTRY="+sys.argv[2]+" C:/Users/lava/lavadocker"

############## To build normal ################################
# docker_build = "docker build --no-cache C:/Users/lava/lavadocker"
# subprocess.call(docker_build, shell=True)

############## To Pass auth and registry as variables in python script ################################

docker_build = "docker build -t v1 --no-cache --build-arg ARTIFACTORY_AUTH="+AUTH+" --build-arg REGISTRY="+REGISTRY+" C:/Users/lava/lavadocker"
subprocess.call(docker_build, shell=True)

docker_images = "docker images"
subprocess.call(docker_images, shell=True)

docker_push = "docker push myregistry.azurecr.io/myimage:v1"
subprocess.call(docker_push, shell=True)


import os
import requests
import sys
from send_email_pb2 import SendEmail
from dotenv import load_dotenv

load_dotenv()

DOMAIN: str = os.getenv('MAILGUN_DOMAIN')
API_KEY: str = os.getenv('MAILGUN_API_KEY')
GSUITE_ADMIN_USER = os.getenv('GSUITE_ADMIN_USER')

def send_email(send_email_proto: SendEmail) -> None:
    """Sends a message to mailgun"""

    # Sending to MailGun API
    resp = requests.post(
        f"https://api.mailgun.net/v3/{DOMAIN}/messages",
        auth=("api", API_KEY),
        data={
            "from": send_email_proto.from_address,
            "to": send_email_proto.to_address,
            "subject": send_email_proto.subject,
            "text": send_email_proto.text
        }
    )
    print(f"response from Mailgun: {resp}")

if __name__ == '__main__':
    to_address: str = sys.argv[1]
    send_email_proto: SendEmail = SendEmail(
        from_address=GSUITE_ADMIN_USER,
        to_address=[to_address],
        subject='Test mg send from local script',
        text='Hello...'
    )
    send_email(send_email_proto=send_email_proto)


import argparse, os
import numpy as np
import pandas as pd

import tensorflow as tf
import tensorflow.keras as keras
from tensorflow.keras.layers import Input, Dense, Dropout
from tensorflow.keras.models import Model
from tensorflow.keras import regularizers
from tensorflow.keras.utils import multi_gpu_model

if __name__ == '__main__':

    parser = argparse.ArgumentParser()

    parser.add_argument('--epochs', type=int, default=20)
    parser.add_argument('--learning-rate', type=float, default=0.001)
    parser.add_argument('--batch-size', type=int, default=128)
    parser.add_argument('--activation', type=str, default="relu")
    parser.add_argument('--dropout', type=float, default=0.0)
    parser.add_argument('--gpu-count', type=int, default=os.environ['SM_NUM_GPUS'])
    parser.add_argument('--model-dir', type=str, default=os.environ['SM_MODEL_DIR'])
    parser.add_argument('--training', type=str, default=os.environ['SM_CHANNEL_TRAINING'])
    parser.add_argument('--validation', type=str, default=os.environ['SM_CHANNEL_VALIDATION'])
    args, _ = parser.parse_known_args()

    # read in data
    x_train = np.load(os.path.join(args.training, 'training.npz'))['train']
    x_val = np.load(os.path.join(args.validation, 'validation.npz'))['validation']

    # build network
    input_dim = x_train.shape[1]

    input_layer = Input(shape=(input_dim, ))

    #encoder = Dense(200, activation=args.activation,activity_regularizer=regularizers.l1(args.learning_rate))(input_layer)
    encoder = Dense(200, activation=args.activation)(input_layer)
    encoder = Dense(50, activation=args.activation)(encoder)
    encoder = Dense(50, activation=args.activation)(encoder)
    encoder = Dropout(args.dropout)(encoder)
    encoder = Dense(10, activation=args.activation)(encoder)
    encoder = Dropout(args.dropout)(encoder)
    decoder = Dense(50, activation=args.activation)(encoder)
    decoder = Dense(50, activation=args.activation)(decoder)
    decoder = Dense(200, activation=args.activation)(decoder)
    decoder = Dense(input_dim, activation=None)(decoder)

    autoencoder = Model(inputs=input_layer, outputs=decoder)
    print(autoencoder.summary())

    if args.gpu_count > 1:
        autoencoder = multi_gpu_model(autoencoder, gpus=args.gpu_count)

    # compile and fit
    autoencoder.compile(optimizer='adam', loss='mean_squared_error')

    autoencoder.fit(x_train, x_train,
                    epochs=args.epochs,
                    batch_size=args.batch_size,
                    shuffle=True,
                    verbose=2,
                    validation_data=(x_val, x_val))

    score = autoencoder.evaluate(x_val, x_val,verbose=0)
    print('Validation loss    :', score)

    # Save the trained model:
    os.makedirs(os.path.join(args.model_dir, 'model/1'), exist_ok=True)
    autoencoder.save(os.path.join(args.model_dir, 'model/1'))


'''model.py'''
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import os

class Linear_QNet(nn.Module):
    '''Linear Q Network'''
    def __init__(self, input_size, hidden_size1, output_size):
        '''Initializes the network'''
        super().__init__() # super class
        self.linear1 = nn.Linear(input_size, hidden_size1) # input layer
        self.linear2 = nn.Linear(hidden_size1, output_size)

    def forward(self, x):
        '''Does the forward pass'''
        x = F.relu(self.linear1(x))
        x = self.linear2(x)
        return x

    def save(self, file_name='model.pth'):
        '''Saves the model'''
        model_folder_path = './model'
        if not os.path.exists(model_folder_path):
            os.makedirs(model_folder_path)
        # check if file exists rename it if it does
        file_name = os.path.join(model_folder_path, file_name)
        # print(file_name)
        # while os.path.isfile(file_name):
        #     file_name = file_name.split('.')[0] + '_new.' + file_name.split('.')[1]

        torch.save(self.state_dict(), file_name) # save model

class QTrainer:
    '''QTrainer'''
    def __init__(self, model, lr, gamma):
        '''Initializes the QTrainer'''
        self.lr = lr # learning rate
        self.gamma = gamma # discount rate
        self.model = model # model
        self.optimizer = optim.Adam(model.parameters(), lr=self.lr) # optimizer
        self.criterion = nn.MSELoss() # loss function

    def train_step(self, state, action, reward, next_state, done): # train model
        '''Trains the model using the Q-learning algorithm (Bellman Equation)'''
        state = torch.tensor(state, dtype=torch.float) # convert to tensor
        next_state = torch.tensor(next_state, dtype=torch.float)
        action = torch.tensor(action, dtype=torch.long)
        reward = torch.tensor(reward, dtype=torch.float)

        if len(state.shape) == 1: # if state is 1D, convert to 2D
            # unsqueeze(0) adds a dimension of size 1 at the specified position
            state = torch.unsqueeze(state, 0)
            next_state = torch.unsqueeze(next_state, 0)
            action = torch.unsqueeze(action, 0)
            reward = torch.unsqueeze(reward, 0)
            done = (done, ) # convert to tuple

        # predicted Q values with current state (Q(s, a, w))
        pred = self.model(state)

        target = pred.clone() # clone the predicted Q values
        for i in range(len(done)):
            Q_new = reward[i]
            if not done[i]:
                Q_new = reward[i] + self.gamma * torch.max(self.model(next_state[i]))
            target[i][torch.argmax(action).item()] = Q_new

        # Q_new = r + y * max(next_predicted Q value) -> only do this if not done
        # pred.clone() -> clone the predicted Q values
        # preds[argmax(action)] = Q_new -> update the predicted Q values
        self.optimizer.zero_grad() # reset the optimizer
        loss = self.criterion(target, pred) # calculate the loss
        loss.backward() # back propagation
        self.optimizer.step() # update the weights


import numpy as np
from scipy.integrate import tplquad
from quantumworldX.helium import phi1
zeta = 2

def H11_vpm(t, u, s, zeta=1.6875, Z=2):
    return np.exp(-2*s*zeta)*(s*s - t*t - 4.0*s*u*Z + (s - t)*(s + t)*u*zeta*zeta)
def S11_vpm(t, u, s, zeta=1.6875, Z=2):
    return u*(s*s - t*t)*phi1(s, t, u, zeta)*phi1(s, t, u, zeta)

def expected_phi1(zeta):
    # this is how we 3-d integrate
    S11_int, error = tplquad( S11_vpm  ,
                                0.0, np.inf,
                                lambda x: 0.0, lambda x: x,
                                lambda x, y: 0.0, lambda x, y: y,
                                args=(zeta, 2.0))
    H11_int, error = tplquad(  H11_vpm    ,
                                0.0, 50.0,
                                lambda x: 0.0, lambda x: x,
                                lambda x, y: 0.0, lambda x, y: y,
                                args=(zeta, 2.0))
    return H11_int/S11_int

e = expected_phi1(zeta)
print(e)

15.Variational Principle/Optimizing Very Poor Man's Wave-Function.py


from discord import Embed

from chitanda.config import config
from chitanda.listeners import DiscordListener
from chitanda.util import args, register

@register('aliases')
@args(r'$')
async def call(*, bot, listener, target, author, args, private):
    """Sends a private message detailing the command aliases."""
    if isinstance(listener, DiscordListener):
        embed = Embed(title='Aliases')
        for alias, command in sorted(config['aliases'].items()):
            embed.add_field(
                name=f'{config["trigger_character"]}{alias}',
                value=f'{config["trigger_character"]}{command}',
                inline=False,
            )

        yield {
            'target': author,
            'message': embed,
            'private': True,
            'embed': True,
        }
    else:
        yield {'target': author, 'message': 'Aliases:'}
        for alias, command in sorted(config['aliases'].items()):
            yield {
                'target': author,
                'message': (
                    f'{config["trigger_character"]}{alias} --> '
                    f'{config["trigger_character"]}{command}'
                ),
            }


from fastapi import FastAPI
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
import uvicorn

from db.base import database
from endpoints import users, secretdata

def create_application(title):
    application = FastAPI(title=title)
    return application

app = create_application(title="ForQummy")
app.mount("/static", StaticFiles(directory="static"), name="static")
app.include_router(users.router, prefix="/users", tags=["users"])
app.include_router(secretdata.router, prefix="/secretdata", tags=["secretdata"])

templates = Jinja2Templates(directory="templates")

@app.on_event('startup')
async def startup():
    await database.connect()

@app.get('/', response_class=HTMLResponse)
async def root(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})

@app.on_event("shutdown")
async def shutdown():
    await database.disconnect()

if __name__ == "__main__":
    uvicorn.run("main:app")


#!/usr/bin/python3
#coding: utf-8

'''
#
# Does things
#
'''

import re, io, os, sys, time
import datetime
import sqlite3
import random
from importlib import import_module
from random import seed
from random import randint

#import_module("FullAutoConstants")
import_module("CommonAnalysis")
import_module("TeamConstants")

from CommonAnalysis import *
from BundesLAAlgorithmConstants import *

####--####--####--####--####--####
####  CONSTANTS
####--####--####--####--####--####

AUTO_MODE = "auto"
ALLOWED_MODES = [AUTO_MODE]
LAUNCH_MODE = "NONE"

OUTPUT_FILE = "varOptimalOutput.txt"

ALL_LEAGUES = [{'name': BUNDESLIGA_NAME, 'teams': BUNDESLIGA_TEAMS},
  {'name': LIGUE_ONE_NAME, 'teams': LIGUEONE_TEAMS},
  {'name': LIGUE_TWO_NAME, 'teams': LIGUETWO_TEAMS},
  {'name': PREMIER_LEAGUE_NAME, 'teams': PREMIERLEAGUE_TEAMS},
  {'name': SPANISH_LIGA_NAME, 'teams': SPANISH_LIGA_TEAMS},
  {'name': ITA_SERIE_A_NAME, 'teams': ITA_SERIE_A_TEAMS},
  {'name': PORTUGAL_LIGA_NAME, 'teams': PORTUGAL_LIGA_TEAMS},
]

####--####--####--####--####--####
####  SCRIPT EXECUTION
####--####--####--####--####--####

matchDate = ""
if len(sys.argv) > 2 :
  matchDate = sys.argv[1]
  modeText = sys.argv[2]
  if modeText in ALLOWED_MODES :
    LAUNCH_MODE = modeText
  else:
    LAUNCH_MODE = "NONE"
else :
  print("Need. More. Arguments. Eat.")
  print("Usage : python3 <file.py> initial_date(dd/mm/yyyy) <mode>")
  print("Replace <mode> with " + TRYOUT_MODE + " for algorithm tryout, and with " + PRONO_MODE + " for this week's pronostics.")
  sys.exit()

cursor = initCursor()

if LAUNCH_MODE == AUTO_MODE :
  with open(OUTPUT_FILE, 'w') as outputFile :
    for teamDict in ALL_LEAGUES :
      print("Processing league " + teamDict['name'] + " ...")
      bestVars = monteCarloMode(cursor, matchDate, teamDict['name'], teamDict['teams'], MUTABLE_VARS, 0)
      finalVars = discMode(cursor, matchDate, teamDict['name'], teamDict['teams'], bestVars, 0)

      outputFile.write("## ## RESULTS FOR LEAGUE " + teamDict['name'] + " ## ##\n")
      outputFile.write("## ## WIN RATE: " + str(round(finalVars['WIN_RATE'], 2)) + "%\n")
      for key in finalVars.keys() :
        if key == 'WIN_RATE' :
          continue
        outputFile.write("MUTABLE_VARS[\"" + str(key) + "\"] = " + str(round(finalVars[key], 5)) + "\n")
      outputFile.write("\n\n")
      print(teamDict['name'] + " done ! We keep going !")
else :
  print ("No known actions were asked. Exiting...")


from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

#PATH = "C:\\Users\\214012\\Downloads\\chromedriver_win32\\chromedriver.exe"
PATH = "\\chromedriver_win32\\chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get("http://192.168.1.254/K_1")
data = driver.page_source
Start_pre=data.find("<pre>")
End_pre=data.find("</pre>")
print(data[Start_pre+5:End_pre])

##data=driver.page_source.find("script")
##print(data)
##search=driver.find_element_by_name("script")
##print(search.text)

driver.quit()


from django import forms
from django.contrib.admin import widgets
from html5.forms.widgets import DateInput

from .models import (
    Vaccine, Mother, Child, Appointment
)

class ChildForm(forms.ModelForm):
    class Meta:
        model = Child
        fields = [
            'first_name', 'middle_name', 'last_name',  'national_id',
            'MRN', 'file_no', 'nationality', 'gender', 'birth_date',
            'status', 'mother',
        ]
        widgets = {
            'birth_date' : DateInput
        }

class MotherForm(forms.ModelForm):
    class Meta:
        model = Mother
        fields = [
             'first_name', 'middle_name', 'last_name',  'national_id',
            'mobile'
        ]


from dataclasses import dataclass
from math import sqrt
from statistics import mean
from typing import Callable, List, Sequence, Union

import numpy as np

from .minimization_result import MinimizationExitCondition, MinimizationResult

def _initialize_error_values(
    vertices: List[np.ndarray], objective_function: Callable[[np.ndarray, int], float]
) -> List[float]:
    """Evaluate the objective function at each vertex to create a corresponding list of error values for each vertex"""

    return [objective_function(v, -1) for v in vertices]

@dataclass
class _ErrorProfile:
    highest_index: int = 0
    next_highest_index: int = 0
    lowest_index: int = 0

def _evaluate_simplex(error_values: List[float]) -> _ErrorProfile:
    """Examine all error values to determine the error profile"""

    error_profile = _ErrorProfile()
    if error_values[0] > error_values[1]:
        error_profile.highest_index = 0
        error_profile.next_highest_index = 1
    else:
        error_profile.highest_index = 1
        error_profile.next_highest_index = 0

    for index in range(len(error_values)):
        error_value = error_values[index]
        if error_value <= error_values[error_profile.lowest_index]:
            error_profile.lowest_index = index
        if error_value > error_values[error_profile.highest_index]:
            error_profile.next_highest_index = error_profile.highest_index
            error_profile.highest_index = index
        elif error_value > error_values[error_profile.next_highest_index] and index != error_profile.highest_index:
            error_profile.next_highest_index = index
    return error_profile

def _compute_centroid(vertices: List[np.ndarray], error_profile: _ErrorProfile) -> np.ndarray:
    """Compute the centroid of all points except the worst"""

    num_vertices = len(vertices)
    centroid = np.zeros(num_vertices - 1)
    for i in range(num_vertices):
        if i != error_profile.highest_index:
            centroid = np.add(centroid, vertices[i])
    return centroid * (1.0 / (num_vertices - 1))

def _try_to_scale_simplex(
    scale_factor: float,
    error_profile: _ErrorProfile,
    vertices: List[np.ndarray],
    error_values: List[float],
    objective_function: Callable[[np.ndarray, int], float],
    evaluation_count: int,
) -> float:
    """Test a scaling operation of the high point, and replace it if it is an improvement"""

    # find the centroid through which we will reflect
    centroid = _compute_centroid(vertices, error_profile)

    # define the vector from the centroid to the high point
    centroid_to_high_point = np.subtract(vertices[error_profile.highest_index], centroid)

    # scale and position the vector to determine the new trial point
    new_point = np.add(centroid_to_high_point * scale_factor, centroid)

    # evaluate the new point
    new_error_value = objective_function(new_point, evaluation_count)

    # if it's better, replace the old high point
    if new_error_value < error_values[error_profile.highest_index]:
        vertices[error_profile.highest_index] = new_point
        error_values[error_profile.highest_index] = new_error_value

    return new_error_value

def _shrink_simplex(
    error_profile: _ErrorProfile,
    vertices: List[np.ndarray],
    error_values: List[float],
    objective_function: Callable[[np.ndarray, int], float],
    evaluation_count: int,
) -> None:
    """Contract the simplex uniformly around the lowest point"""

    lowest_vertex = vertices[error_profile.lowest_index]
    for i in range(len(vertices)):
        if i != error_profile.lowest_index:
            vertices[i] = np.add(vertices[i], lowest_vertex) * 0.5
            error_values[i] = objective_function(vertices[i], evaluation_count)
            evaluation_count += 1

class NelderMeadSimplex:
    """Class implementing the Nelder-Mead simplex algorithm, used to find a minima when no gradient is available.

    Called fminsearch() in Matlab. A description of the algorithm can be found at
    http://se.mathworks.com/help/matlab/math/optimizing-nonlinear-functions.html#bsgpq6p-11
    or
    https://en.wikipedia.org/wiki/Nelder%E2%80%93Mead_method
    """

    def __init__(self, convergence_tolerance: float, max_function_evaluations: int, scale: float) -> None:
        self.convergence_tolerance = convergence_tolerance
        self.max_function_evaluations = max_function_evaluations
        self.scale = scale

    def find_minimum(
        self, objective_function: Callable[[np.ndarray, int], float], initial_guess: Union[np.ndarray, Sequence[float]]
    ) -> MinimizationResult:
        """Finds the minimum of the objective function with an intial pertubation"""

        # create the initial simplex
        if not isinstance(initial_guess, np.ndarray):
            initial_guess = np.array(initial_guess)
        vertices = self._initialize_vertices(initial_guess)

        evaluation_count = 0
        exit_condition = MinimizationExitCondition.NONE

        error_values = _initialize_error_values(vertices, objective_function)

        # iterate until we converge, or complete our permitted number of iterations
        while True:
            error_profile = _evaluate_simplex(error_values)

            # see if the range in point heights is small enough to exit
            if self._has_converged(error_values):
                exit_condition = MinimizationExitCondition.CONVERGED
                break

            # attempt a reflection of the simplex
            reflection_point_value = _try_to_scale_simplex(
                -1.0, error_profile, vertices, error_values, objective_function, evaluation_count
            )
            evaluation_count += 1
            if reflection_point_value <= error_values[error_profile.lowest_index]:
                # it's better than the best point, so attempt an expansion of the simplex
                _try_to_scale_simplex(2.0, error_profile, vertices, error_values, objective_function, evaluation_count)
                evaluation_count += 1
            elif reflection_point_value >= error_values[error_profile.next_highest_index]:
                # it would be worse than the second best point, so attempt a contraction to look
                # for an intermediate point
                current_worst = error_values[error_profile.highest_index]
                contraction_point_value = _try_to_scale_simplex(
                    0.5, error_profile, vertices, error_values, objective_function, evaluation_count
                )
                evaluation_count += 1
                if contraction_point_value >= current_worst:
                    # that would be even worse, so let's try to contract uniformly towards the low point;
                    # don't bother to update the error profile, we'll do it at the start of the
                    # next iteration
                    _shrink_simplex(error_profile, vertices, error_values, objective_function, evaluation_count)
                    # that required one function evaluation for each vertex; keep track
                    evaluation_count += len(vertices) - 1
            # check to see if we have exceeded our alloted number of evaluations
            if evaluation_count >= self.max_function_evaluations:
                exit_condition = MinimizationExitCondition.MAX_FUNCTION_EVALUATIONS
                break

        return MinimizationResult(
            exit_condition,
            vertices[error_profile.lowest_index],
            error_values[error_profile.lowest_index],
            evaluation_count,
        )

    def _initialize_vertices(self, initial_guess: np.ndarray) -> List[np.ndarray]:
        """Construct an initial simplex, given starting guesses for the constants,
        and initial step sizes for each dimension"""

        num_dimensions = initial_guess.shape[0]

        pn = self.scale * (sqrt(num_dimensions + 1) - 1 + num_dimensions) / (num_dimensions * sqrt(2))
        qn = self.scale * (sqrt(num_dimensions + 1) - 1) / (num_dimensions * sqrt(2))

        vertices: List[np.ndarray] = []
        p0 = initial_guess
        vertices.append(p0)
        for i in range(num_dimensions):
            v: List[float] = []
            for j in range(num_dimensions):
                v.append(pn if i == j else qn)
            vertices.append(np.add(p0, v))
        return vertices

    def _has_converged(self, error_values: List[float]) -> bool:
        """Check whether the points in the error profile have so little range that we
        consider ourselves to have converged"""

        avg = mean(error_values)
        r = 0
        for ev in error_values:
            r += pow(ev - avg, 2) / (len(error_values) - 1)
        r = sqrt(r)
        return r < self.convergence_tolerance


import logging
from time import sleep

from pyrogram import Client

from .. import glovar
from .channel import share_data, share_regex_count
from .etc import code, general_link, lang, thread
from .file import save
from .group import leave_group
from .telegram import get_admins, get_group_info, send_message

# Enable logging
logger = logging.getLogger(__name__)

def backup_files(client: Client) -> bool:
    # Backup data files to BACKUP
    try:
        for file in glovar.file_list:
            # Check
            if not eval(f"glovar.{file}"):
                continue

            # Share
            share_data(
                client=client,
                receivers=["BACKUP"],
                action="backup",
                action_type="data",
                data=file,
                file=f"data/{file}"
            )
            sleep(5)

        return True
    except Exception as e:
        logger.warning(f"Backup error: {e}", exc_info=True)

    return False

def interval_min_10() -> bool:
    # Execute every 10 minutes
    glovar.locks["message"].acquire()
    try:
        # Clear recorded users
        for gid in list(glovar.recorded_ids):
            glovar.recorded_ids[gid] = set()

        return True
    except Exception as e:
        logger.warning(f"Interval min 10 error: {e}", exc_info=True)
    finally:
        glovar.locks["message"].release()

    return False

def reset_data(client: Client) -> bool:
    # Reset user data every month
    try:
        glovar.bad_ids["users"] = set()
        save("bad_ids")

        glovar.except_ids["temp"] = set()
        save("except_ids")

        glovar.user_ids = {}
        save("user_ids")

        glovar.watch_ids = {
            "ban": {},
            "delete": {}
        }
        save("watch_ids")

        # Send debug message
        text = (f"{lang('project')}{lang('colon')}{general_link(glovar.project_name, glovar.project_link)}\n"
                f"{lang('action')}{lang('colon')}{code(lang('reset'))}\n")
        thread(send_message, (client, glovar.debug_channel_id, text))

        return True
    except Exception as e:
        logger.warning(f"Reset data error: {e}", exc_info=True)

    return False

def send_count(client: Client) -> bool:
    # Send regex count to REGEX
    glovar.locks["regex"].acquire()
    try:
        for word_type in glovar.regex:
            share_regex_count(client, word_type)
            word_list = list(eval(f"glovar.{word_type}_words"))

            for word in word_list:
                eval(f"glovar.{word_type}_words")[word] = 0

            save(f"{word_type}_words")

        return True
    except Exception as e:
        logger.warning(f"Send count error: {e}", exc_info=True)
    finally:
        glovar.locks["regex"].release()

    return False

def update_admins(client: Client) -> bool:
    # Update admin list every day
    glovar.locks["admin"].acquire()
    try:
        group_list = list(glovar.admin_ids)

        for gid in group_list:
            should_leave = True
            reason = "permissions"
            admin_members = get_admins(client, gid)

            if admin_members and any([admin.user.is_self for admin in admin_members]):
                # Admin list
                glovar.admin_ids[gid] = {admin.user.id for admin in admin_members
                                         if (((not admin.user.is_bot and not admin.user.is_deleted)
                                              and admin.can_delete_messages
                                              and admin.can_restrict_members)
                                             or admin.status == "creator"
                                             or admin.user.id in glovar.bot_ids)}
                save("admin_ids")

                # Trust list
                glovar.trust_ids[gid] = {admin.user.id for admin in admin_members
                                         if ((not admin.user.is_bot and not admin.user.is_deleted)
                                             or admin.user.id in glovar.bot_ids)}
                save("trust_ids")

                if glovar.user_id not in glovar.admin_ids[gid]:
                    reason = "user"
                else:
                    for admin in admin_members:
                        if (admin.user.is_self
                                and admin.can_delete_messages
                                and admin.can_restrict_members):
                            should_leave = False

                if not should_leave:
                    continue

                group_name, group_link = get_group_info(client, gid)
                share_data(
                    client=client,
                    receivers=["MANAGE"],
                    action="leave",
                    action_type="request",
                    data={
                        "group_id": gid,
                        "group_name": group_name,
                        "group_link": group_link,
                        "reason": reason
                    }
                )
                reason = lang(f"reason_{reason}")
                project_link = general_link(glovar.project_name, glovar.project_link)
                debug_text = (f"{lang('project')}{lang('colon')}{project_link}\n"
                              f"{lang('group_name')}{lang('colon')}{general_link(group_name, group_link)}\n"
                              f"{lang('group_id')}{lang('colon')}{code(gid)}\n"
                              f"{lang('status')}{lang('colon')}{code(reason)}\n")
                thread(send_message, (client, glovar.debug_channel_id, debug_text))
            elif admin_members is False or any([admin.user.is_self for admin in admin_members]) is False:
                # Bot is not in the chat, leave automatically without approve
                group_name, group_link = get_group_info(client, gid)
                leave_group(client, gid)
                share_data(
                    client=client,
                    receivers=["MANAGE"],
                    action="leave",
                    action_type="info",
                    data={
                        "group_id": gid,
                        "group_name": group_name,
                        "group_link": group_link
                    }
                )
                project_text = general_link(glovar.project_name, glovar.project_link)
                debug_text = (f"{lang('project')}{lang('colon')}{project_text}\n"
                              f"{lang('group_name')}{lang('colon')}{general_link(group_name, group_link)}\n"
                              f"{lang('group_id')}{lang('colon')}{code(gid)}\n"
                              f"{lang('status')}{lang('colon')}{code(lang('leave_auto'))}\n"
                              f"{lang('reason')}{lang('colon')}{code(lang('reason_leave'))}\n")
                thread(send_message, (client, glovar.debug_channel_id, debug_text))

        return True
    except Exception as e:
        logger.warning(f"Update admin error: {e}", exc_info=True)
    finally:
        glovar.locks["admin"].release()

    return False

def update_status(client: Client, the_type: str) -> bool:
    # Update running status to BACKUP
    try:
        share_data(
            client=client,
            receivers=["BACKUP"],
            action="backup",
            action_type="status",
            data={
                "type": the_type,
                "backup": glovar.backup
            }
        )

        return True
    except Exception as e:
        logger.warning(f"Update status error: {e}", exc_info=True)

    return False


from lexi_info import LexiInfo
import json
from session import DF
from collections import defaultdict, OrderedDict
from lexi import sleep

""" Handy to have eyes on json format ...
{
  "lexi": "/hub/device/getRegisteredByType",
  "lighttypes": [
    {
      "106": {
        "deviceCount": 5,
        "devices": [
          {
            "brand": "Lexi",
            "com": "mesh",
            "family": "luminaire",
            "guid": "98535258-a712-11ea-b0f9-b827eb6ed5d9",
            "hub": "46b59a84-1dd2-11b2-bceb-410665d07897",
            "id": 32,
            "ipaddr": "8023",
            "last_value": "255,255,255;15;3",
            "macaddress": "70B3D5AC50A0",
            "model": "BRC-GU10-HTA-001",
            "name": "K2",
            "status": 0,
            "swversion": "1",
            "taxonomyID": 12,
            "type": "124"
          },
          {
            "brand": "Lexi",
            "com": "mesh",

"""

class LexiFun(LexiInfo):

    def _array(self):
        return []
    def _dict(self):
        return {}   # OrderedDict didn't work here

    def _get_info(self):
        reg_info = self.registeredByType(False)

        # lights2 is a dict with every key => {"Tea 7" => {device data } } already set to append
        lights2 = defaultdict(self._dict)

        lighttypes_array = json.loads(reg_info.text)["lighttypes"]
        for lt in lighttypes_array:
            # print (f"lt => {lt}")
            for dtype, devices in lt.items():
                # print (f"{dtype} {type(dtype) } {type(devices) } {devices.keys() }")
                # 106 <class 'str'> <class 'dict'> dict_keys(['deviceCount', 'devices', 'name'])
                d2 = devices["devices"]
                for d in d2:

                    dtype = d['type']
                    dname = d['name']

                    # lights[dtype].append(d)
                    lights2[dtype][dname] = d

        return lights2

    def rotate_group(self, brightness):
        """ Make motion! """
        # type or group
        # get regByType ... list each light: name|id|status

        reg_info = self._get_info()
        self.pp (reg_info, "reg_info")

        for reg_id, reg_hash1 in reg_info.items():
            print (f"reg_id:{reg_id} devices:{len(reg_hash1)} ")

            dev_names = sorted(reg_hash1.keys())

            if len(dev_names) <= 1:
                continue

            dname_last = dev_names[-1]
            dev_last   = reg_hash1[dname_last]

            for dname in dev_names:

                dev = reg_hash1[dname]
                id  = dev['id']
                name= dev['name']
                color , b, cx   = dev_last["last_value"].split(";")

                print (f"{id} {name} {color} {b}")

                lf.on(id, color, b)

                dname_last = dev['name']
                dev_last   = reg_hash1[dname_last]

    def old_ref(self):

        for i in [0]:
            offset = -1 -i
            if abs(i) >= len(teas):
                offset = -1
            last_name = names[offset]
            last = teas[last_name]

            for device_name in sorted(teas):
                ddata = teas[device_name]

                color0, b0, cx0 = ddata["last_value"].split(";")

                color , b, cx   = last["last_value"].split(";")
                id = ddata["id"]
                name = ddata["name"]

                print (f"{id} {name} => color:{color} was: {color0} => b:{b}")
                lf.on(id, color, brightness)

                last = ddata
                last_name = name

    def set_tea(self, brightness = "100"):
        lf.on("23", "48,255,197" , brightness)
        lf.on("24", "123,240,255", brightness)
        lf.on("26", "193,122,255", brightness)
        lf.on("25", "255,158,216", brightness)
        lf.on("27", "255,106,186", brightness)
        lf.on("28", "255,63,70"  , brightness)

    def set_tea2(self, brightness = "100"):
        lf.on("28", "48,255,197" , brightness)
        lf.on("27", "123,240,255", brightness)
        lf.on("25", "193,122,255", brightness)
        lf.on("26", "255,158,216", brightness)
        lf.on("24", "255,106,186", brightness)
        lf.on("23", "255,63,70"  , brightness)

lf = LexiFun()
# lf.set_debug_development()
lf.set_tea()
# lf.set_tea2()

for i in range(500000):
    b = "100" if i % 2 == 0 else "50"
    lf.rotate_group(b)

    print (f"Rotating lights by type ... {i} ")
    sleep(2000)

# lf.set_debug_state(DF.TruncateReponse, False)
# lf.rotate_group(0)

# lf.set_tea("25")
#for brightness in ("100", "50", "25", "100"):
#    lf.set_tea(brightness)
#     lf.rotate_group(7)

"""
    -- Hub had this saved.  Turned on group ... all to 1 color?
Tea Lights only ...
    28 - Tea 6 - 255,63,70;100;0 - type:136 - status: 0
    26 - Tea 3 - 193,122,255;100;0 - type:136 - status: 0
    25 - Tea 4 - 255,158,216;100;0 - type:136 - status: 0
    24 - Tea 2 - 123,240,255;100;0 - type:136 - status: 0
    23 - Tea 1 - 48,255,197;100;0 - type:136 - status: 0
    27 - Tea 5 - 255,106,186;100;0 - type:136 - status: 0
"""


import pygame as pg
from player import Player

pg.init() # Inicializa o pygame
screen = pg.display.set_mode([840, 480]) # Cria a tela para exibição do jogo
pg.display.set_caption("Spacedown") # Defini o nome na barra de titulo da pagina

objectGroup = pg.sprite.Group() # Cria um grupo para adição de sprites

player = Player(objectGroup) # Insere o sprite ao grupo

pg.mixer.music.load("GameTutorial/sounds/space.wav")
pg.mixer.music.play(-1)

shoot = pg.mixer.Sound("GameTutorial/sounds/shoot1.mp3")

def draw(): # Função para desenhar objetos na tela
  screen.fill((19,173,235)) # Defini a cor de fundo da tela
  objectGroup.draw(screen) # Desenha os sprites na tela
  objectGroup.update()

gameloop = True
if __name__ == "__main__":
  while gameloop:
    for event in pg.event.get():
      if event.type == pg.QUIT:
        gameloop = False
      elif event.type == pg.KEYDOWN:
        if event.key == pg.K_SPACE:
          shoot.play()

    draw()
    pg.display.update()


"""

import xml.etree.cElementTree as ET

root = ET.Element("root")
doc = ET.SubElement(root, "url")

ET.SubElement(doc, "field1", name="blah").text = "some value1"
links = ET.SubElement(doc, "External-links")
link = ET.SubElement(links, "link")
ET.SubElement(link, "SRC").text = "link1"
ET.SubElement(link, "Status").text = "Status"
ET.SubElement(link, "Redirect").text = ""

tree = ET.ElementTree(root)
tree.write("test.xml")

"""
import requests
import xml.etree.cElementTree as ETX

urls = ["http://www.ford.com", "http://www.google.com"]

xml_root = ETX.Element("root") # Start XML Element
for url in urls: # Loop through list of urls
    doc = ETX.SubElement(xml_root, "Page", url=url)
    ETX.SubElement(doc, "field1", name="blah").text = "some value1"
    response = requests.get(url) # Perform Get Request of url to gather info

tree = ETX.tostring(xml_root)  # Form XML
# tree = ETX.fromstring(xml_root)
text_file = open("test.xml", "wb")
text_file.write(tree)
text_file.close()


from django.conf.urls import patterns, url, include
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns(
    '',
    url(r"^$", "oauth.views.index", name="evernote_index"),
    url(r"^callback/$", "oauth.views.callback", name="evernote_callback"),
    url(r"^login/$", "oauth.views.login", name="evernote_login"),
    url(r"^logout/$", "oauth.views.logout", name="evernote_logout"),
    url(r"^info/$", "oauth.views.get_info", name="evernote_info"),
    url(r"^import/$", "oauth.views.import_note", name="evernote_import"),
    url(r"^content/$", "oauth.views.import_note_content", name="evernote_import_content"),
    url(r"^reset/$", "oauth.views.reset", name="evernote_auth_reset"),
    url(r"^note/$", "oauth.views.note", name="evernote_note"),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^cms/', include('cms.urls', namespace='cms')),
)


'''
使用mmdetection作为pose net模型的前处理
'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import os
import pprint
import ipdb;pdb=ipdb.set_trace
import numpy as np
from tqdm import tqdm
from utilitys import plot_keypoint, PreProcess
import time

import torch
import _init_paths
from config import cfg
import config
from config import update_config

from utils.transforms import *
from lib.core.inference import get_final_preds
import cv2
import models
#  from lib.detector.yolo.human_detector import human_bbox_get as yolo_det
from lib.detector.mmdetection.high_api import human_boxes_get as mm_det
from collections import OrderedDict
import matplotlib.pyplot as plt

def parse_args():
    parser = argparse.ArgumentParser(description='Train keypoints network')
    # general
    parser.add_argument('--cfg',
                        help='experiment configure file name',
                        default='experiments/coco/hrnet/w32_256x192_adam_lr1e-3.yaml',
                        #  default='experiments/coco/hrnet/w48_256x192_adam_lr1e-3.yaml',
                        #  default='experiments/coco/hrnet/w32_384x288_adam_lr1e-3.yaml',
                        type=str)

    parser.add_argument('opts',
                        help="Modify config options using the command-line",
                        default=None,
                        nargs=argparse.REMAINDER)

    # philly
    parser.add_argument('--modelDir',
                        help='model directory',
                        type=str,
                        default='')
    parser.add_argument('--logDir',
                        help='log directory',
                        type=str,
                        default='')
    parser.add_argument('--dataDir',
                        help='data directory',
                        type=str,
                        default='')
    parser.add_argument('--prevModelDir',
                        help='prev Model directory',
                        type=str,
                        default='')

    parser.add_argument("-i", "--video_input", help="input video file name", default="/home/xyliu/Videos/sports/dance.mp4")
    parser.add_argument("-o", "--video_output", help="output video file name", default="output/output.mp4")

    parser.add_argument('--camera', action='store_true')
    parser.add_argument('--display', action='store_true')

    args = parser.parse_args()
    return args

##### load model
def model_load(config):
    model = eval('models.'+config.MODEL.NAME+'.get_pose_net')(
        config, is_train=False
    )
    model_file_name  = 'models/pytorch/pose_coco/pose_hrnet_w32_256x192.pth'
    #  model_file_name  = 'models/pytorch/pose_coco/pose_hrnet_w48_256x192.pth'
    #  model_file_name  = 'models/pytorch/pose_coco/pose_hrnet_w32_384x288.pth'
    state_dict = torch.load(model_file_name)
    new_state_dict = OrderedDict()
    for k, v in state_dict.items():
        name = k # remove module.
        #  print(name,'\t')
        new_state_dict[name] = v
    model.load_state_dict(new_state_dict)
    model.eval()
    return model

def ckpt_time(t0=None, display=None):
    if not t0:
        return time.time()
    else:
        t1 = time.time()
        if display:
            print('consume {:2f} second'.format(t1-t0))
        return t1-t0, t1

###### 加载human detecotor model
#  from lib.detector.yolo.human_detector import load_model as yolo_model
#  human_model = yolo_model()

from lib.detector.mmdetection.high_api import load_model as mm_model
human_model = mm_model()

def main():
    args = parse_args()
    update_config(cfg, args)

    #### load pose-hrnet MODEL
    pose_model = model_load(cfg)
    #  pose_model = torch.nn.DataParallel(pose_model, device_ids=[0,1]).cuda()
    pose_model.cuda()

    from pycocotools.coco import COCO
    annFile = '/ssd/xyliu/data/coco/annotations/instances_val2017.json'
    im_root = '/ssd/xyliu/data/coco/images/val2017/'
    coco = COCO(annFile)
    catIds = coco.getCatIds(catNms=['person'])
    # 所有人体图片的id
    imgIds = coco.getImgIds(catIds=catIds )
    kpts_result = []
    detected_image_num = 0
    box_num = 0
    for imgId in tqdm(imgIds[:]):
        img = coco.loadImgs(imgId)[0]
        im_name = img['file_name']
        img = im_root + im_name
        img_input = plt.imread(img)

        try:
            bboxs, scores = mm_det(human_model, img_input, 0.3)
            inputs, origin_img, center, scale = PreProcess(img_input, bboxs, scores, cfg)

        except Exception as e:
            print(e)
            continue

        detected_image_num += 1
        with torch.no_grad():
            output = pose_model(inputs.cuda())
            preds, maxvals = get_final_preds(
                cfg, output.clone().cpu().numpy(), np.asarray(center), np.asarray(scale))

            #  vis = np.ones(shape=maxvals.shape,)
            vis = maxvals
            preds = preds.astype(np.float16)
            keypoints = np.concatenate((preds, vis), -1)
            for k, s in zip(keypoints, scores.tolist()):
                box_num += 1
                k = k.flatten().tolist()
                item = {"image_id": imgId, "category_id": 1, "keypoints": k, "score":s}
                kpts_result.append(item)

    num_joints = 17
    in_vis_thre = 0.2
    oks_thre = 0.5
    oks_nmsed_kpts = []
    for i in range(len(kpts_result)):
        img_kpts = kpts_result[i]['keypoints']
        kpt = np.array(img_kpts).reshape(17,3)
        box_score = kpts_result[i]['score']
        kpt_score = 0
        valid_num = 0
        # each joint for bbox
        for n_jt in range(0, num_joints):
            # score
            t_s = kpt[n_jt][2]
            if t_s > in_vis_thre:
                kpt_score = kpt_score + t_s
                valid_num = valid_num + 1
        if valid_num != 0:
            kpt_score = kpt_score / valid_num

        # rescoring 关节点的置信度 与 box的置信度的乘积
        kpts_result[i]['score'] = kpt_score * box_score

    import json
    data = json.dumps(kpts_result)
    print('image num is {} \tdetected_image num is {}\t person num is {}'.format(len(imgIds), detected_image_num, box_num)),
    #  data = json.dumps(str(kpts_result))
    with open('person_keypoints.json', 'wt') as f:
        #  pass
        f.write(data)

if __name__ == '__main__':
    main()


import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)
import time
from functions_channel import channels_create, channel_join
from functions_standup import *
from data_structure import *
import pytest

def reset_data_standup():
    data = getData()
    data['users'] = []
    user1 = auth_register('user1@gmail.com', 'password', 'Sally', 'name')
    user2 = auth_register('user2@gmail.com', 'password', 'Bob', 'name')
    user3 = auth_register('user3@gmail.com', 'password', 'Bob2', 'name')
    global channel_id
    data['channel'] = []
    for user in data['users']:
        user['joined_channels'] = []
    channel_id = 0
    ch_id = channels_create(user1['token'], 'ch1', True)['channel_id']
    channel_join(user2['token'], ch_id)
    return user1, user2,user3, ch_id

def test_standup_start_valid():
    user1, *_, ch = reset_data_standup()
    standup_start(user1['token'], ch, 2)
    assert getChannelDetails(ch)["standup_active"] == True
    assert getChannelDetails(ch)["standup_started_by"] == user1['u_id']

def test_standup_start_invalid_channel():
    user1, *_, ch = reset_data_standup()
    with pytest.raises(ValueError_http):
        standup_start(user1['token'], ch+2 , 2)

def test_standup_start_already_started():
    user1, *_, ch = reset_data_standup()
    standup_start(user1['token'], ch, 2)
    with pytest.raises(ValueError_http):
        standup_start(user1['token'], ch, 2)

def test_standup_send_vaid():
    user1, *_, ch = reset_data_standup()
    standup_start(user1['token'], ch, 2)
    standup_send(user1['token'], ch, 'message')

def test_standup_send_message_too_long():
    user1, *_, ch = reset_data_standup()
    standup_start(user1['token'], ch, 2)
    with pytest.raises(ValueError_http):
        standup_send(user1['token'], ch, 'a'*1001)

def test_standup_send_not_active_standup():
    user1, *_, ch = reset_data_standup()
    with pytest.raises(ValueError_http):
        standup_send(user1['token'], ch, 'a')

def test_standup_send_invalid_channel():
    user1, *_, ch = reset_data_standup()
    standup_start(user1['token'], ch, 2)
    with pytest.raises(ValueError_http):
        standup_send(user1['token'], ch+2, 'a')

def test_standup_active_not_active():
    user1, *_, ch = reset_data_standup()
    assert standup_active(user1['token'], ch)['is_active'] == False

def test_standup_active_active():
    user1, *_, ch = reset_data_standup()
    standup_start(user1['token'], ch, 2)
    assert standup_active(user1['token'], ch)['is_active'] == True

def test_standup_just_ended():
    user1, user2, _, ch = reset_data_standup()
    standup_start(user1['token'], ch, 1)
    standup_send(user1['token'], ch, 'msg1')
    standup_send(user2['token'], ch, 'msg2')
    assert getChannelDetails(ch)["standup_active"] == True
    time.sleep(2)
    standup_active(user1['token'], ch)
    assert getChannelDetails(ch)["standup_active"] == False


from setuptools import setup, find_packages

with open('./README.rst') as readme:
    long_description = readme.read()

setup(
    name='changelog-suggest',
    url='https://github.com/kirankoduru/changelog',
    version='0.1.0',
    license='MIT',
    description='Create a suggested CHANGELOG from your git repos logs',
    author='Kiran Koduru',
    author_email='kiranrkoduru@gmail.com',
    keywords="git log changelog python",
    packages=find_packages(),
    test_suite='changelog.tests',
    include_package_data=True,
    zip_safe=False,
    entry_points={
        'console_scripts': [
            'changelog=changelog.command_line:main'
        ]
    },
    classifiers=[
        'Environment :: Console',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
    ],
    long_description=long_description
)


import gurobipy
import easygui

from tools import edge, pairs

class Instance:
    env = gurobipy.Env(empty=True)
    env.setParam('LogToConsole', 0)
    env.start()

    def __init__(self, vertices=None, edges=None, faces=None):
        self.vertices = set(vertices or [])
        self.edges = set(edges or [])
        self.faces = faces or [(), ]
        if faces is not None and edges is None:
            for face in faces:
                for e in pairs(face):
                    self.edges.add(edge(e))

        self.f_obj = 0
        self.x_vec = {}
        self.solvedQ = False
        self.message = ""
        self.title = ""

        self.input_parameter_edges = {e: False for e in self.edges}
        self.input_parameter_vertices = {v: None for v in self.vertices}

    def add_vertex(self, v):
        if v not in self.vertices:
            self.vertices.add(v)
            self.input_parameter_vertices[v] = None

    def add_edge(self, u, v):
        e = edge([u, v])
        if e not in self.edges:
            self.vertices.add(u)
            self.vertices.add(v)
            self.edges.add(e)
            self.input_parameter_edges[e] = False
            self.update()

    def set_input_parameter_edge_dialog(self, e):
        text_gui = easygui.enterbox("", f"Set input for edge {e}")
        c = None if text_gui in ['', '0', None] else int(text_gui)
        self.input_parameter_edges[e] = c

    def set_other_parameter_dialog(self):
        pass

    def color_of_edge(self, u, v, textQ=False):
        return '' if textQ else 'k'

    def width_of_edge(self, u, v):
        return 1

    def update(self):
        self.f_obj = 0
        self.x_vec = {}
        self.solvedQ = False
        self.title = ""

    def delete_vertex(self, v):
        self.vertices.remove(v)
        del self.input_parameter_vertices[v]
        self.edges = set(e for e in self.edges if v not in e)
        self.faces = [face for face in self.faces if v not in face]
        self.update()

    def delete_edge(self, e):
        e = edge(e)
        self.edges.remove(e)
        del self.input_parameter_edges[e]
        self.faces = [face for face in self.faces if e not in pairs(face)]
        self.update()

    def solve(self, option='x'):
        pass

    def print_debug_info(self):
        print(f"x_vec = {self.x_vec}")


import os
import pytest
import shutil

from tests.lib.testing_classes import (
    HostFixtures,
    PublishTest,
    DeadlinePublishTest
)

class MayaHostFixtures(HostFixtures):
    @pytest.fixture(scope="module")
    def last_workfile_path(self, download_test_data, output_folder_url):
        """Get last_workfile_path from source data.

            Maya expects workfile in proper folder, so copy is done first.
        """
        src_path = os.path.join(download_test_data,
                                "input",
                                "workfile",
                                "test_project_test_asset_test_task_v001.mb")
        dest_folder = os.path.join(output_folder_url,
                                   self.PROJECT,
                                   self.ASSET,
                                   "work",
                                   self.TASK)
        os.makedirs(dest_folder)
        dest_path = os.path.join(dest_folder,
                                 "test_project_test_asset_test_task_v001.mb")
        shutil.copy(src_path, dest_path)

        yield dest_path

    @pytest.fixture(scope="module")
    def startup_scripts(self, monkeypatch_session):
        """Points Maya to userSetup file from input data"""
        startup_path = os.path.join(
            os.path.dirname(__file__), "input", "startup"
        )
        original_pythonpath = os.environ.get("PYTHONPATH")
        monkeypatch_session.setenv(
            "PYTHONPATH",
            "{}{}{}".format(startup_path, os.pathsep, original_pythonpath)
        )

    @pytest.fixture(scope="module")
    def skip_compare_folders(self):
        yield []

class MayaLocalPublishTestClass(MayaHostFixtures, PublishTest):
    """Testing class for local publishes."""

class MayaDeadlinePublishTestClass(MayaHostFixtures, DeadlinePublishTest):
    """Testing class for Deadline publishes."""


# This is to test the difference between operator T and N
import numpy as np
from collections import namedtuple
from UCRL.evi.scevi import SpanConstrainedEVI
from UCRL.evi.evi import EVI
import pytest

MDP = namedtuple('MDP', 'S,A,P,R,gamma')

@pytest.mark.parametrize("params", [[1,0.5,0.1], [10,4,3.9], [7,3,1], [1.1,1.,0.9]])
def test_srevi(params):

    alpha, delta, beta = params
    print(alpha, delta, beta)

    S = 3

    A = [[0], [0, 1], [0]]
    maxa = max(map(len, A))

    P = -np.inf * np.ones((S, maxa, S), dtype=np.float)
    R = -np.inf * np.ones((S, maxa), dtype=np.float)

    P[0, 0, 1] = 1.
    P[0, 0, 0] = 0
    P[0, 0, 2] = 0

    P[1, 0, 0] = 0.
    P[1, 0, 1] = 0.
    P[1, 0, 2] = 1.
    P[1, 1, 0] = 0.
    P[1, 1, 1] = 0.
    P[1, 1, 2] = 1.
    P[2, 0, 0] = 0.
    P[2, 0, 1] = 0.
    P[2, 0, 2] = 1.

    R[0, 0] = alpha
    R[1, 0] = beta
    R[1, 1] = delta
    R[2, 0] = 0

    r_max = np.max(R)

    gamma = 1.

    mdp = MDP(S, A, P, R, gamma)

    policy_indices = np.zeros((mdp.S, 2), dtype=np.int)
    policy = np.zeros((mdp.S, 2), dtype=np.float)

    rs = np.random.randint(1, 2131243)
    print(rs)
    evi = SpanConstrainedEVI(nb_states=mdp.S,
                             actions_per_state=mdp.A,
                             bound_type="chernoff",
                             span_constraint=np.inf,
                             augmented_reward=0,
                             relative_vi=0,
                             random_state=rs,
                             gamma=mdp.gamma)

    epsi = 0.000001
    c = alpha + beta
    u0 = np.zeros((mdp.S,))

    for oper in ['T', 'N']:
        evi.reset_u(u0)
        span_value_new = evi.run(policy_indices=policy_indices,
                                 policy=policy,
                                 estimated_probabilities=mdp.P,
                                 estimated_rewards=mdp.R,
                                 estimated_holding_times=np.ones((mdp.S, maxa)),
                                 beta_r=np.zeros((mdp.S, maxa)),
                                 beta_p=np.zeros((mdp.S, maxa, mdp.S)),
                                 beta_tau=np.zeros((mdp.S, maxa)),
                                 tau_max=1.,
                                 r_max=r_max,
                                 tau=1.,
                                 tau_min=1.,
                                 epsilon=epsi,
                                 span_constraint=c,
                                 initial_recenter=1,
                                 relative_vi=0,
                                 operator_type=oper)
        # estimate gain
        u1, u2 = evi.get_uvectors()
        print('{}: {}'.format(oper, u1 - u1[2]))
        if oper == 'T':
            assert np.isclose(span_value_new, -21), span_value_new
            assert np.allclose(u1 - u1[2], [alpha + beta, delta, 0])
            assert np.isclose(np.max(u1) - np.min(u1), c)

            assert np.allclose(policy_indices, [[-1, -1], [0, 1], [0, 0]]) or \
                   np.allclose(policy_indices, [[-1, -1], [1, 1], [0, 0]])
            assert np.allclose(policy, [[-1, -1], [0, 1.], [1., 0]], atol=1e-5)\
                   or np.allclose(policy, [[-1, -1], [0, 1.], [0, 1.]], atol=1e-5), policy
        else:
            assert np.allclose(u1 - u1[2], [alpha + delta, delta, 0])
            assert np.isclose(np.max(u1) - np.min(u1), alpha + delta)

            print(policy_indices)
            print(policy)
            assert np.allclose(policy_indices, [[0, 0], [0, 1], [0, 0]]) or \
                   np.allclose(policy_indices, [[0, 0], [1, 1], [0, 0]])
            assert np.allclose(policy, [[1., 0], [0, 1], [1., 0]], atol=1e-5)\
                   or np.allclose(policy, [[1., 0], [0, 1], [0, 1.]], atol=1e-5), policy

if __name__ == '__main__':
    test_srevi([1.1,1,0.9])


import yfinance
import pandas as pd
import GrahamRules

class Stock:
    '''Class for stocks, with methods for calculating some variables and checking against Grahams rules'''

    def __init__(self, ticker) -> None:
        self.ticker = yfinance.Ticker(ticker)
        self.score = 0

    def check_current_ratio(self):
        ''' Checking rule nr 2'''
        bs = self.ticker.get_balance_sheet()
        latestyear = max(bs.columns)
        currentasset = bs[latestyear]['CurrentAssets']
        current_liabilities = bs[latestyear]['CurrentLiabilities']
        current_ratio = currentasset / current_liabilities

        if current_ratio > GrahamRules.CURRENT_RATIO_CEILING:
            print(f"The Current Ratio is {current_ratio} to high")
        elif current_ratio < GrahamRules.CURRENT_RATIO_FLOOR:
            print(f"The Current Ratio is {current_ratio} to low")
        else:
            print(f"The current ratio is within the bounds: {current_ratio}")
            self.score += 1

    def div_years_check(self):
        '''Checking rule nr 4 for years of divindends'''

        divident_data = self.ticker.dividends
        divident_df = pd.DataFrame(divident_data.index)
        divident_df['Years'] = divident_df['Date'].dt.year

        if len(divident_df['Years'].unique()) >= GrahamRules.DIVIDENT_PAYMENT_YEARS:
            print(f"dividends history ok, years = {len(divident_df['Years'].unique())}, last year = {divident_df['Years'].max()}")
            self.score += 1
        else:
            print('dividens history too short')

    def market_cap_check(self):
        ''' check nr 1
        need to add basecurrency, for now just use SEK(?)'''

        if self.ticker.fast_info.market_cap > GrahamRules.MARKETCAP_FLOOR:
            print('Sufficient Market Cap')
            self.score += 1
        else:
            print('Too small')

    def check_price_earnings(self):
        '''Checking rule no 6 - using trailing PE'''
        statistics = self.ticker.stats()
        pe = statistics['summaryDetail']['trailingPE']

        if pe < GrahamRules.PE_CEILING:
            print(f'PE is {pe} and below the PE Ceiling')
            self.score += 1
        else:
            print(f'PE is {pe} and above the PE Ceiling')

    def check_price_to_asset(self):
        ''' Checking rule no 7 but using price to book instead'''

        statistics = self.ticker.stats()

        if statistics['defaultKeyStatistics']['priceToBook'] < GrahamRules.PRICE_ASSET_CEILING:
            print(f"Price to Book is {statistics['defaultKeyStatistics']['priceToBook']} which is below the ceiling")
            self.score += 1
        else:
            print(f"Price to Book is {statistics['defaultKeyStatistics']['priceToBook']} which is above the ceiling")


import pygame
import glob
pygame.init()

win = pygame.display.set_mode((2200,672))

pygame.display.set_caption("First Game")

def loadImages(folderName,flip,x_size,y_size):
  fileList=glob.glob(folderName+"/*")
  output=[]
  for i in range(len(fileList)):
    output.append(pygame.image.load(fileList[i]))
    output[i]=pygame.transform.scale(output[i],(x_size, y_size))

  if flip==1:
    for i in range(len(output)):
      output[i]=pygame.transform.flip(output[i],True,False)

  return output

bgX=0
bg=pygame.image.load('Star_Night.png')
char=pygame.image.load('Pygame-Images/Game/standing.png')

clock=pygame.time.Clock()

bulletSound = pygame.mixer.Sound('Game_bullet.mp3')
hitSound = pygame.mixer.Sound('Game_hit.mp3')

music = pygame.mixer.music.load('music.mp3')
pygame.mixer.music.play(-1)

score = 0
xpos=0

class player(object):

  walkRight=loadImages('hero',0,100,100)
  walkLeft=loadImages('hero',1,100,100)

  def __init__(self,x,y,width,height):
    self.initialx=x
    self.initialy=y
    self.x=x
    self.y=y
    self.width=width
    self.height=height
    self.vel=5
    self.isJump=False
    self.left=False
    self.right=False
    self.walkCount=0
    self.jumpCount =10
    self.standing = True
    self.hitbox = (self.x + 17, self.y + 11, 29, 52)

  def draw(self,win):
    if self.walkCount + 1 >= 28:
      self.walkCount=0

    if not(self.standing):
      if self.left:
        win.blit(self.walkLeft[self.walkCount//7], (self.x,self.y))
        self.walkCount +=1
      elif self.right:
        win.blit(self.walkRight[self.walkCount//7], (self.x,self.y))
        self.walkCount +=1
    else:
      if self.right:
        win.blit(self.walkRight[0], (self.x, self.y))
      else:
        win.blit(self.walkLeft[0], (self.x, self.y))
    self.hitbox = (self.x + 17, self.y + 11, 29, 52)
    #pygame.draw.rect(win, (255, 0, 0), self.hitbox,2)

  def hit(self):
    self.isJump = False
    self.JumpCount = 10
    self.x = self.initialx
    self.y = self.initialy
    self.walkCount = 0
    font1 = pygame.font.SysFont('comicsans', 100)
    text = font1.render('-5', 1, (255, 0, 0))
    win.blit(text, (250 - (text.get_width()/2),200))
    pygame.display.update()
    i = 0
    while i < 200:
      pygame.time.delay(10)
      i += 1
      for event in pygame.event.get():
        if event.type == pygame.QUIT:
          i = 201
          pygame.quit()

class projectile(object):
  def __init__(self,x,y,radius,color,facing):
    self.x = x
    self.y = y
    self.radius = radius
    self.color = color
    self.facing = facing
    self.vel = 8 * facing

  def draw(self,win):
    pygame.draw.circle(win, self.color, (self.x, self.y), self.radius)

class enemy(object):
  walkLeft=loadImages('dino',1,100,100)
  walkRight=loadImages('dino',0,100,100)

  def __init__(self, x, y, width, height, end):
    self.initialx=x
    self.initialy=y
    self.x = x
    self.y = y
    self.width = width
    self.height = height
    self.end = end
    self.path = [self.x, self.end]
    self.walkCount = 0
    self.vel = 3
    self.hitbox = (self.x + 17, self.y + 2, 31, 57)
    self.health = 10
    self.visible = True

  def draw(self,win):
    self.move()
    if self.visible:
      if self.walkCount + 1 >= 28:
        self.walkCount = 0

      if self.vel > 0:
        win.blit(self.walkRight[self.walkCount//7], (self.x, self.y))
        self.walkCount += 1
      else:
        win.blit(self.walkLeft[self.walkCount//7], (self.x, self.y))
        self.walkCount += 1

      pygame.draw.rect(win,(255, 0, 0), (self.hitbox[0], self.hitbox[1] - 20, 50, 10))
      pygame.draw.rect(win,(0,128, 0), (self.hitbox[0], self.hitbox[1] - 20, 50 - (5 * (10 - self.health)), 10))
      self.hitbox = (self.x + 17, self.y + 2, 31, 57)
      #pygame.draw.rect(win, (255, 0, 0), self.hitbox,2)

  def move(self):
    if self.vel > 0:
      if self.x  + self.vel < self.path [1]:
        self.x += self.vel
      else:
        self.vel = self.vel * -1
        self.walkCount = 0
    else:
      if self.x - self.vel > self.path[0]:
        self.x += self.vel
      else:
        self.vel = self.vel * -1
        self.walkCount = 0

  def hit(self):
    if self.health > 0:
      self.health -= 1
    else:
      self.visible = False
    print('hit')

def redrawGameWindow():
  win.blit(bg,(bgX,0))
  text = font.render('Score: ' + str(score), 1, (0,0,0))
  text2 = font.render('xpos: ' + str(xpos), 1, (0,0,0))
  win.blit(text, (390,10))
  win.blit(text2, (390,30))
  hero.draw(win)
  dino.draw(win)
  for bullet in bullets:
    bullet.draw(win)

  pygame.display.update()

scrolling = True
#main loop
font = pygame.font.SysFont('comicsans', 30, True)
hero=player(50,382,64,64)
dino = enemy(100,386,64,64,300)
shootLoop = 0
bullets = []
run=True
while run:
  clock.tick(27)
  """
  if dino.visible == True:
    if hero.hitbox[1] < dino.hitbox[1] + dino.hitbox[3] and hero.hitbox[1] + hero.hitbox[3] > dino.hitbox[1]:
      if hero.hitbox[0] + hero.hitbox[2] > dino.hitbox[0] and hero.hitbox[0] < dino.hitbox[0] + dino.hitbox[2]:
        hero.hit()
        score -= 5
  """

  if shootLoop > 0:
    shootLoop += 1
  if shootLoop > 3:
    shootLoop =0

  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      run=False

  for bullet in bullets:
    if bullet.y - bullet.radius < dino.hitbox[1] + dino.hitbox[3] and bullet.y + bullet.radius > dino.hitbox[1]:
      if bullet.x + bullet.radius > dino.hitbox[0] and bullet.x - bullet.radius < dino.hitbox[0] + dino.hitbox[2]:
        hitSound.play()
        dino.hit()
        score += 1
        bullets.pop(bullets.index(bullet))

    if bullet.x < 500 and bullet.x > 0:
      bullet.x += bullet.vel
    else:
      bullets.pop(bullets.index(bullet))

  keys = pygame.key.get_pressed()

  if keys[pygame.K_SPACE] and shootLoop ==0:
    bulletSound.play()
    if hero.left:
      facing = -1
    else:
      facing = 1

    if len(bullets) < 5:
      bullets.append(projectile(round(hero.x + hero.width //2), round(hero.y + hero.height//2), 6, (0,0,0), facing))

    shootLoop = 1

  if keys[pygame.K_LEFT] and xpos>0:
    if scrolling:
      bgX += hero.vel
      xpos -= hero.vel
      dino.x += hero.vel
    else:
      hero.x -= hero.vel
    hero.left = True
    hero.right = False
    hero.standing = False
  elif keys[pygame.K_RIGHT] and xpos<1400:
    if scrolling:
      bgX -= hero.vel
      xpos += hero.vel
      dino.x -= hero.vel
    else:
      hero.x += hero.vel

    hero.right = True
    hero.left = False
    hero.standing = False
  else:
    hero.standing = True
    hero.walkCount = 0

  if not(hero.isJump):
    if keys[pygame.K_UP]:
      hero.isJump = True
      hero.right = False
      hero.left = False
      hero.walkCount = 0
  else:
    if hero.jumpCount >= -10:
      neg = 1
      if hero.jumpCount < 0:
        neg = -1
      hero.y -= (hero.jumpCount ** 2) * 0.5 * neg
      hero.jumpCount -= 1
    else:
      hero.isJump = False
      hero.jumpCount = 10
  redrawGameWindow()
pygame.quit()


#!/usr/bin/env python

import sys
import operator
import os
from os.path import join
import glob
import numpy as np
import datetime
import matplotlib.pyplot as plt
from matplotlib import dates
from matplotlib import rc
from matplotlib.ticker import (MultipleLocator, FormatStrFormatter, AutoMinorLocator)

rc('font',**{'family':'serif','serif':['Times']})
rc('text', usetex=True)

current_deficit_north_values = [] # initializing lists for loop
norm_deficit_north_values = []
current_deficit_south_values = []
norm_deficit_south_values = []
times = []
directory = os.getcwd()
file_location = os.path.join(directory, '*.dat') # reading all the files in the directory
filenames = sorted(glob.glob(file_location))
first_file = filenames[0] # for naming the plots later
file_date = first_file[:-4]
last_file = filenames[-1]
for f in filenames:
    with open(f,'r') as data_in:
        lines = data_in.readlines() # making the contents a list of strings
        end_of_data = len(lines) # skipping last three lines of file
        data_range = range(1,end_of_data) # actual data in file
        for i in data_range: # looping over only data
            current_linei = lines[i] # picking out one line at a time
            if float(current_linei[21:29])==9999.00: # checking for bad data
                I_total_up_north = np.nan
            else:
                I_total_up_north = float(current_linei[23:29])
            if float(current_linei[29:37])==9999.00:
                I_total_down_north = np.nan
            else:
                I_total_down_north = float(current_linei[30:37])
            if float(current_linei[69:77])==9999.00:
                I_total_up_south = np.nan
            else:
                I_total_up_south = float(current_linei[71:77])
            if float(current_linei[77:86])==9999.00:
                I_total_down_south = np.nan
            else:
                I_total_down_south = float(current_linei[78:85])
            I_deficit_north = I_total_up_north + I_total_down_north
            I_deficit_south = I_total_up_south + I_total_down_south
            current_deficit_north_values.append(I_deficit_north) # list to be plotted
            current_deficit_south_values.append(I_deficit_south)
            I_total_current_north = (I_total_up_north + abs(I_total_down_north))/2
            I_total_current_south = (I_total_up_south + abs(I_total_down_south))/2
            I_norm_deficit_north = I_deficit_north/I_total_current_north
            I_norm_deficit_south = I_deficit_south/I_total_current_south
            norm_deficit_north_values.append(I_norm_deficit_north)
            norm_deficit_south_values.append(I_norm_deficit_south)
            year = int(current_linei[0:4])
            month = int(current_linei[5:7])
            day = int(current_linei[8:10])
            hour = int(current_linei[11:13])
            minute = int(current_linei[14:16])
            second = int(current_linei[17:19])
            timei_formatted = datetime.datetime(year,month,day,hour,minute,second)
            times.append(timei_formatted)

NvsS = plt.figure()
axa = NvsS.add_subplot(111)
axa.set_aspect('equal')
axa.tick_params(which='both',direction='inout')
axa.tick_params(which='major',length=8,right=True)
axa.tick_params(which='minor',length=4,right=True)
axa.xaxis.set_major_locator(MultipleLocator(0.5))
axa.yaxis.set_major_locator(MultipleLocator(0.5))
axa.scatter(current_deficit_south_values,current_deficit_north_values,s=2,c='k')
axa.set_xlabel('South Difference (MA)')
axa.set_ylabel('North Difference (MA)')
plt.tight_layout()
plt.savefig('northdiff_vs_southdiff_' + first_file[-12:-4] + '-' + last_file[-12:-4]+ '.png')

NvsS_norm = plt.figure()
axb = NvsS_norm.add_subplot(111)
axb.set_aspect('equal')
axb.tick_params(which='both',direction='inout')
axb.tick_params(which='major',length=8,right=True)
axb.tick_params(which='minor',length=4,right=True)
# axb.xaxis.set_major_locator(MultipleLocator(0.5))
# axb.yaxis.set_major_locator(MultipleLocator(0.5))
axb.scatter(norm_deficit_south_values,norm_deficit_north_values,s=2,c='k')
axb.set_xlabel('South Difference (MA)')
axb.set_ylabel('North Difference (MA)')
plt.tight_layout()
plt.savefig('norm_northdiff_vs_southdiff_' + first_file[-12:-4] + '-' + last_file[-12:-4]+ '.png')

fig1,axs = plt.subplots(2,1,tight_layout=True)

# ax1.xaxis.tick_top()
# ax1.xaxis.set_label_position('top')
axs[0].tick_params(which='both',direction='inout')
axs[0].tick_params(which='major',length=8,right=True)
axs[0].tick_params(which='minor',length=4,right=True)
axs[0].xaxis.set_major_locator(dates.HourLocator(interval=4))
axs[0].xaxis.set_minor_locator(AutoMinorLocator())
axs[0].yaxis.set_minor_locator(AutoMinorLocator())
axs[0].xaxis.set_major_formatter(dates.DateFormatter('%H:%M\n%m/%d'))

# ax1.text(-10,-20, 'B$_y$ vs B$_z$',fontsize=18,bbox={'facecolor':'white', 'alpha':0.5,'pad':10})
axs[0].plot(times, norm_deficit_north_values, c='k',linewidth=0.25)
axs[0].set_title('North Difference')
axs[0].autoscale(axis='x',tight=True)
axs[0].set_ylabel(R'Normalized Current Difference \textit{(MA)}',fontsize=10)

axs[1].tick_params(which='both',direction='inout')
axs[1].tick_params(which='major',length=8,right=True)
axs[1].tick_params(which='minor',length=4,right=True)
axs[1].xaxis.set_major_locator(dates.HourLocator(interval=4))
axs[1].xaxis.set_minor_locator(AutoMinorLocator())
axs[1].yaxis.set_minor_locator(AutoMinorLocator())
axs[1].xaxis.set_major_formatter(dates.DateFormatter('%H:%M\n%m/%d'))
axs[1].plot(times, norm_deficit_south_values, c='r',linewidth=0.25)
axs[1].set_title('South Difference')

axs[1].set_ylabel(R'Normalized Current Difference \textit{(MA)}',fontsize=10)
axs[1].autoscale(axis='x',tight=True)
plt.savefig(file_date + '_norm_difference.pdf')
# plt.show()
'''
# plotting the histograms

fig2, (ax21,ax22) = plt.subplots(1,2,sharey=True,tight_layout=True)
ax21.set_xlim(-2.0,2.0)
ax21.hist(current_deficit_north_values,16)
ax21.set_title(R'North Difference \textit{(MA)}')
ax22.set_xlim(-2.0,2.0)
ax22.hist(current_deficit_south_values,16)
ax22.set_title(R'South Difference \textit{(MA)}')
plt.tight_layout()
plt.savefig(file_date + '_histograms.pdf')
'''


graph =  {
          "tala"   : ["shebin"],
          "shebin" : ["tala","elsb3","quesna","minouf"],
          "elsb3"  : ["quesna","shebin"],
          "quesna" : ["elsb3","shebin"],
          "minouf" : ["shohda","shebin","sirs","sadat"],
          "shohda" : ["minouf"],
          "sirs"   : ["minouf","bagour"],
          "bagour" : ["sirs"],
          "sadat"  : ["minouf","ashmon"],
          "ashmon" : ["sadat"]
         }

dist =   {
          "tala"   : [0 , 16.3 , 19.7 , 32.8 , 32 , 13.7 , 31.5 , 31.9 , 77.5 , 56.6],
          "shebin" : [16.3 , 0 , 15.2 , 18.3 , 17.9 , 14.3 , 16.2 , 16.2 , 67.5 , 39.1],
          "elsb3"  : [19.7 , 14.3 , 0 , 17.1 , 31.6 , 28.9 , 30.1 , 29.2 , 82 , 51.5],
          "quesna" : [32.8 , 18.3 , 17.1 , 0 , 33.7 , 30.8 , 32.5 , 33.7 , 87.7 , 50.1],
          "minouf" : [32 , 17.9 , 31.6 , 33.7 , 0 , 22.8 , 7.2 , 17.1 , 57.6 , 24.1],
          "shohda" : [13.7 , 14.3 , 28.9 , 30.8 , 22.8 , 0 , 27.1 , 30.7 , 78.9 , 41.6],
          "sirs"   : [31.5 , 16.2 , 30.1 , 32.5 , 7.5 , 27.1 , 0 , 8.3 , 62.6 , 22.2],
          "bagour" : [31.9 , 16.2 , 29.2 , 33.7 , 17.1 , 30.7 , 8.3 , 0 , 70.6 , 21],
          "sadat"  : [77.5 , 67.5 , 82 , 87.7 , 57.7 , 78.9 , 62.6 , 70.6 , 0 , 75],
          "ashmon" : [56.5 , 39.1 , 51.5 , 50.1 , 24.1 , 41.6 , 22.2 , 21 , 75 , 0]
         }

nodes = ["tala","shebin","elsb3","quesna","minouf","shohda","sirs","bagour","sadat","ashmon"]

#=============================
from collections import deque
visited = []
queue = deque([])

newpath = []
path = list ( 20 * ' ' )
n = 0
flag = 0

H_Dist = {}
child_dist = {}
sorted_child_dist = {}

opened = []
closed = []
path1 = []

#==============================
def BFS(start,end):
    if (start == end):
        visited.append(end)
        return

    if ((not start in visited)and(not start in queue)):
        queue.append(start)
    for node in graph[start]:
        if( (not node in queue) and (not node in visited) ):
            queue.append(node)
    visited.append(queue.popleft())
    BFS(queue[0],end)

#==============================
def DFS(start,end):
    global flag
    global n
    if(flag == 0):
        path[n]=start
        if(start == end):
            flag=1
        n+=1
        visited.append(start)
        for cnt in graph[start]:
            if(not cnt in visited):
                DFS(cnt,end)
        n -= 1

#=================================
def Find_H_Dist(end):
    for i in range(10):
        H_Dist[nodes[i]] = dist[end][i]

#=================================
def Greedy_Search(start,end):

    global flag
    global n
    if(flag == 0):
        if(start == end):
            flag=1

        visited.append(start)
        for cnt in graph[start]:
            child_dist[cnt] = H_Dist[cnt]

        sorted_child_dist = sorted(child_dist.items(),key=lambda t:t[1])
        list8 = []
        for i in  sorted_child_dist:
            list8.append(i)
        for cnt in list8:
            if(not cnt[0] in visited):
                Greedy_Search(cnt[0],end)

#=================================
def get_distance(city1,city2):
    return dist[city1][nodes.index(city2)]
#=================================
def add(start,list1):
    global opened
    global closed
    global path1
    list3 =[]
    for c in list1:
        list3.append(c)
    list3.append(start)
    cost = 0
    list2 = []
    for i in range(len(list1)-1):
        cost += get_distance(list1[i],list1[i+1])

    list2.append(list3)
    list2.append(start)
    list2.append(cost)
    opened.append(list2)

#=================================
def Asearch(start,end):
    global opened
    global closed
    global path1

    add(start,[])
    A_search(end)

#=================================
def A_search(goal):
    global opened
    global closed
    global path1
    min1 = opened[0]
    index = 0

    for i in range(1,len(opened),1):
        if ((min1[2]+get_distance(min1[1],goal))> ( opened[i][2]+get_distance(opened[i][1],goal) )):
            min1 = opened[i]
            index=i
    path1 = []
    for c in min1[0]:
        path1.append(c)
    closed.append(min1[1])
    opened.pop(index)
    for c in graph[min1[1]]:
        if( (not c in closed)and ( (c == goal) or (hasopenedchild(c)) ) ):
            add(c,path1)
        if( path1[-1] == goal ):
            return
    A_search(goal)

#================================
def hasopenedchild(c1):
    global opened
    global closed
    global path1
    global graph
    for i in graph[c1]:
        if(not i in closed):
            return True
    return False

#=================================
def Take_In():
    while True:
        try:
            choice = input("Please Enter Your Choice : \n--------------------------\n(1) Breadth First Search Algorthim.\n(2) Depth First Search Algorthim.\n(3) Greedy Search Algorthim.\n(4) A* Search Algorthim.\n")
            if (choice != '1' and choice!= '2' and choice!= '3' and choice!= '4'):
                print("Error choice !! Try again\n")
                continue
        except(NameError):
            print("Error choice !! Try again\n")
            continue
        return choice

#================================

print ("                 ^_^ *** AI SEARCH ALGORTHIMS TASK *** ^_^ ")
print ("                 ----------------------------------------- \n")

input1 = Take_In()
if(input1 == '1'):
    start = input("Enter your Start City :")
    end = input("Enter Your End City :")
    BFS(start,end)
    print (visited)

elif(input1 == '2'):
    start = input("Enter your Start City :")
    end = input("Enter Your End City :")
    DFS(start,end)
    print (visited)

elif(input1 == '3'):
    start = input("Enter your Start City :")
    end = input("Enter Your End City :")
    Find_H_Dist(end)
    Greedy_Search(start,end)
    print (visited)

elif(input1 == '4'):
    start = input("Enter your Start City :")
    end = input("Enter Your End City :")
    Asearch(start,end)
    print (path1)


import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
from sklearn.model_selection import learning_curve

def plot_benchmark(cv_res: pd.DataFrame, xlabel="Mean error"):
    plt.figure()
    g = sns.barplot("Mean", "Algorithm", data=cv_res, palette="Set3", orient="h", **{'xerr': cv_res.Std})
    g.set_xlabel(xlabel)
    g = g.set_title("Cross validation scores")

def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None,
                        n_jobs=-1, train_sizes=np.linspace(.1, 1.0, 5), scoring='neg_log_loss'):
    """Generate a simple plot of the test and training learning curve"""
    plt.figure()
    plt.title(title)
    if ylim is not None:
        plt.ylim(*ylim)
    plt.xlabel("Training examples")
    plt.ylabel("Score")
    train_sizes, train_scores, test_scores = learning_curve(
        estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes, scoring=scoring)
    train_scores_mean = np.mean(train_scores, axis=1)
    train_scores_std = np.std(train_scores, axis=1)
    test_scores_mean = np.mean(test_scores, axis=1)
    test_scores_std = np.std(test_scores, axis=1)
    plt.grid()

    plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.1,
                     color="r")
    plt.fill_between(train_sizes, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std, alpha=0.1,
                     color="g")
    plt.plot(train_sizes, train_scores_mean, 'o-', color="r", label="Training score")
    plt.plot(train_sizes, test_scores_mean, 'o-', color="g", label="Cross-validation score")

    plt.legend(loc="best")
    return plt


import argparse
import os

from geotools.gpdtools import load_excel_points

def excel2geojson(excel_file, out_geojson=None,
                  lat_col='Latitude',
                  lon_col='Longitude'):
    print(f'Loading points: {excel_file}')
    gdf = load_excel_points(excel_file=excel_file,
                            lat_col=lat_col,
                            lon_col=lon_col)
    print(f'{len(gdf):,} points loaded.')
    if out_geojson:
        print(f'Writing to file: {out_geojson}')
        gdf.to_file(out_geojson, driver='GeoJSON')

if __name__ == '__main__':
    parser = argparse.ArgumentParser()

    parser.add_argument('-i', '--input_excel', type=os.path.abspath)
    parser.add_argument('-og', '--out_geojson', type=os.path.abspath)

    parser.add_argument('--lat_col', default='Latitude',
                        help='Name of column with latitude.')
    parser.add_argument('--lon_col', default='Longitude',
                        help='Name of column with longitude.')

    args = parser.parse_args()

    excel2geojson(excel_file=args.input_excel,
                  out_geojson=args.out_geojson,
                  lat_col=args.lat_col,
                  lon_col=args.lon_col)


'''
Created on Mar 26, 2019

@author: barnwaldo
'''

import time
from core.kbuilder import KStreamBuilder, KStream
from core.kutils import KeyValuePair, KWindow
from kafka import KafkaProducer
from random import randint
from multiprocessing import Process

# config info for Kafka broker
config = {'bootstrap.servers': '192.168.21.3:9092', 'group.id': 'barnwaldo', 'session.timeout.ms': 6000}
names = ['bob', 'alice', 'ted', 'samantha', 'vyra', 'frosty', 'abe']
topics = 'clicks'

def peek(kv):
    print("key: {} -- value: {}".format(kv.key, kv.val))
    return kv

def make_clicks():
    producer = KafkaProducer(bootstrap_servers=config['bootstrap.servers'])
    print('make_clicks')
    while True:
        name = names[randint(0, 6)]
        producer.send(topics, key='0'.encode('utf-8'), value=name.encode('utf-8'))
        # print(name,'sent...')
        # sleep for random interval
        interval = randint(2, 15) * 0.5
        # print('interval', interval)
        time.sleep(interval)

if __name__ == '__main__':
    p = Process(target=make_clicks)
    p.start()
    # define builder for streams/table
    builder = KStreamBuilder(topics, config, keyserde='str', valserde='str')
    # initialize Kstream with builder
    views = KStream(builder.builder)

    views.map(lambda kv: KeyValuePair(kv.val, kv.val, time=kv.time))

    anamolous_users = views.count(materialized='usercounts', kwindow=KWindow(60)).filter(lambda kv: kv.val >= 3)

    # change table back to stream and then send output to Kafka topic
    anamolous_users.toStream().peeker(peek).to('anomalous', config, keyserde='str', valserde='str')

    # Note that KStream can either be initialized with a KStreambuilder or a stream (generator) with a Kafka Producer


from django.contrib import admin
from .models import Metar, SkyCondition

class SkyConditionAdmin(admin.TabularInline):
    model = SkyCondition
    extra = 0

class MetarAdmin(admin.ModelAdmin):
    list_display = ("station_id", "observation_time")
    inlines = [
        SkyConditionAdmin,
    ]

admin.site.register(Metar, MetarAdmin)


import numpy as np
import math
from utils import euclidean_dist_squared

class Kmeans:

    def __init__(self, k):
        self.k = k

    def fit(self, X):
        N, D = X.shape
        y = np.ones(N)

        # Getting 500 random samples to be the mean
        means = np.zeros((self.k, D))
        for kk in range(self.k):
            i = np.random.randint(N)
            means[kk] = X[i]

            #self.means = means
            #print(self.error(X))

        while True:
            y_old = y

            # Compute euclidean distance to each mean
            dist2 = euclidean_dist_squared(X, means)
            dist2[np.isnan(dist2)] = np.inf
            y = np.argmin(dist2, axis=1)

            # Update means
            for kk in range(self.k):
                means[kk] = X[y==kk].mean(axis=0)
                self.means = means

                #self.means = means
                #print(self.error(X))

            changes = np.sum(y != y_old)
            #print('Running K-means, changes in cluster assignment = {}'.format(changes))

            # Stop if no point changed cluster
            if changes == 0:
                break

        self.means = means

    def predict(self, X):
        means = self.means
        dist2 = euclidean_dist_squared(X, means)
        dist2[np.isnan(dist2)] = np.inf
        return np.argmin(dist2, axis=1)

    def error(self, X):
        # get closest indices from predict()
        indices = self.predict(X)

        total = 0
        for i in range(self.means.shape[0]):
            total += np.sum(euclidean_dist_squared(X[indices == i], self.means[[i]]))
        return total