from __future__ import print_function, division, absolute_import, unicode_literals

import numpy as np
import pandas as pd
import pickle as pkl
import cupy as cp
import os

from cupy.cuda import Device

import argparse
import tqdm

import utils as wb

parser = argparse.ArgumentParser(description='Evaluate ranks and MAP on hypernym reconstruction')

parser.add_argument('--data', '-d', type=str, help='csv file containing the relations')
parser.add_argument('--embeddings', '-e', type=str,
                    help='folder containing the embeddings')
parser.add_argument('--max_n', type=int, default=None, help = 'number of items to evaluate')
parser.add_argument('--metric', type=str, default="bures_product")
parser.add_argument('--device', type=int, default=7)
parser.add_argument('--verbose', action='store_true')
args = parser.parse_args()

def get_positive_relation_ranks_and_avg_prec(all_distances, positive_relations):
    """
    Given a numpy array of all distances from an item and indices of its positive relations,
    compute ranks and Average Precision of positive relations.
    Parameters
    ----------
    all_distances : numpy.array (float)
        Array of all distances (floats) for a specific item.
    positive_relations : list
        List of indices of positive relations for the item.
    Returns
    -------
    tuple (list, float)
        The list contains ranks (int) of positive relations in the same order as `positive_relations`.
        The float is the Average Precision of the ranking.
        e.g. ([1, 2, 3, 20], 0.610).
    """
    positive_relation_distances = all_distances[positive_relations]
    negative_relation_distances = np.ma.array(all_distances, mask=False)
    negative_relation_distances.mask[positive_relations] = True
    # Compute how many negative relation distances are less than each positive relation distance, plus 1 for rank
    ranks = (negative_relation_distances < positive_relation_distances[:, np.newaxis]).sum(axis=1) + 1
    map_ranks = np.sort(ranks) + np.arange(len(ranks))
    avg_precision = ((np.arange(1, len(map_ranks) + 1) / np.sort(map_ranks).astype(float)).mean())
    return list(ranks), avg_precision

def evaluate_mean_rank_and_map(hypernym_df, max_n=None):
    """Evaluate mean rank and MAP for reconstruction.
    Parameters
    ----------
    max_n : int or None
        Maximum number of positive relations to evaluate, all if `max_n` is None.
    Returns
    -------
    tuple (float, float)
        Contains (mean_rank, MAP).
        e.g (50.3, 0.31)
    """
    pass

def main(embedding_file=args.embeddings, hypernym_file=args.data, device=args.device, max_n = args.max_n):

    Device(device).use()

    print("Reading embedding file:", embedding_file)

    with open(embedding_file, 'rb') as embed_file:
        embeddings = pkl.load(embed_file)

    means = embeddings['means']
    vars = embeddings["vars"]

    words_to_idx = embeddings['word_to_idx']

    hypernym_df = pd.read_csv(hypernym_file, header=None, sep='\t')
    hypernym_df[2] = hypernym_df[0].apply(lambda x: words_to_idx[x])
    hypernym_df[3] = hypernym_df[1].apply(lambda x: words_to_idx[x])
    hypernym_couples = []

    print("Ranking distances")

    idxs1 = hypernym_df[2].values
    idxs2 = hypernym_df[3].values

    n = np.max(idxs1) + 1
    m = np.max(idxs2) + 1

    idxs = np.arange(m)

    ranks = []
    avg_precision_scores = []

    idxs1 = list(set(idxs1))
    np.random.shuffle(idxs1)

    for i, idx in tqdm.tqdm(enumerate(idxs1)):
        x = [idx] * m
        if args.metric == "bures_distance":
            dists_ = wb.batch_W2(cp.array(means[x]), cp.array(means[idxs]), cp.array(vars[x]), cp.array(vars[idxs]))[0]
            item_distances = cp.asnumpy(dists_)
        elif args.metric == "bures_cosine":
            scores_ = wb.bures_cosine(cp.array(means[x]), cp.array(means[idxs]), cp.array(vars[x]), cp.array(vars[idxs]))
            item_distances = -cp.asnumpy(scores_)
        elif args.metric == "bures_product":
            scores_ = wb.batch_W2(cp.array(means[x]), cp.array(means[idxs]), cp.array(vars[x]), cp.array(vars[idxs]), prod=True)[0]
            item_distances = -cp.asnumpy(scores_)

        assert(not (np.isnan(item_distances.any()) or np.isinf(item_distances).any()))

        item_relations = list(set(hypernym_df[hypernym_df[2] == idx][3]).union(set(hypernym_df[hypernym_df[3] == idx][2])))
        positive_relation_ranks, avg_precision = \
            get_positive_relation_ranks_and_avg_prec(item_distances, item_relations)
        ranks += positive_relation_ranks
        avg_precision_scores.append(avg_precision)
        if max_n is not None and i > max_n:
            break
        if args.verbose:
            print('Positive relation distances: ', item_distances[item_relations])
            print('Ranks: ', positive_relation_ranks)
            print('AP:', avg_precision)

        if (i+1) % 10000 == 0:
            print("Rank moving average: %f" % (np.mean(ranks)))
            print("MAP moving average: %f" % (np.mean(avg_precision_scores)))

    print('Mean rank: %f\t MAP: %f\t Rank std: %f\t AP std: %f' % (np.mean(ranks), np.mean(avg_precision_scores), np.std(ranks), np.std(avg_precision_scores)))

    with open(os.path.join(os.path.dirname(embedding_file), "rank_summary"), "a") as result_file:
        result_file.write("File: %s \t Sample size %u\t Metric: %s\t Full Mean rank: %f\t MAP: %f\t Rank std: %f\t AP std: %f\n" % (
        embedding_file.split('/')[-1], len(avg_precision_scores), args.metric, np.mean(ranks), np.mean(avg_precision_scores), np.std(ranks), np.std(avg_precision_scores)))

    if args.max_n is None:
        with open(embedding_file + "_ranks.pkl", "wb") as ranks_file:
            pkl.dump(ranks, ranks_file)
        with open(embedding_file + "_precisons.pkl", "wb") as precision_file:
            pkl.dump(avg_precision_scores, precision_file)

if __name__ == '__main__':
    main()


from turtle import color, right
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
from dash_bootstrap_components._components.Navbar import Navbar

# Connect to main app.py file
from app import app
from app import server

# Connect to your app pages
from apps import vendas, produto, home, notfound

import montaGraficoVendas
import montaGraficoPedidos

nav_link1 = {
    "color": "white",
    "textAlign": "right",
    "fontSize": 15,
    "marginLeft": "600",
    "backgroundColor": "black",
}

nav_link2 = {
    "color": "white",
    "textAlign": "right",
    "fontSize": 15,
    "marginRight": "50",
    "backgroundColor": "black",
}

nav_name = {
    "color": "white",
    "textAlign": "left",
    "fontSize": 18,
    "margin": "auto",
    "fontFamily": "cursive",
    #"backgroundColor": "red",
}

nav_item_01 = dbc.NavLink('Vendas', href='/apps/vendas')
nav_item_02 = dbc.NavLink('Produtos', href='/apps/produto')

navbar = dbc.Navbar(dbc.Container(
         [
             html.A(
                 # Use row and col to control vertical alignment of logo / brand
                 dbc.Row(
                     [
                         dbc.Col(html.Img(src='/assets/EasyDash.png', height="20px")),
                         dbc.Col(dbc.NavbarBrand("2JR Multimarcas", className="ms-2", style=nav_name)),

                     ],
                     align="center",
                     className="g-0",

                 ),
                 href="/",
                 style={"textDecoration": "none"},
             ),
             dbc.Nav([
                                               nav_item_01,nav_item_02
                                             ],

                                             className="ms-auto",
                                             navbar=True,
                                            ),

         ]
     ),
     color="primary",
     dark=True

)

app.layout = html.Div([navbar,
     dcc.Location(id='url', refresh=False),
    #  html.Div([

    #      dbc.NavLink('Video Games|', href='/apps/vendas'),

    #      dbc.NavLink('Other', href='/apps/produto'),

    # ], className="row"),
     html.Div(id='page-content', children=[])

 ])

@app.callback(Output('page-content', 'children'),
              [Input('url', 'pathname')])
def display_page(pathname):
    if pathname == '/apps/vendas':
        return vendas.layout
    if pathname == '/apps/produto':
        return produto.layout
    if pathname == '/':
        return home.layout
    else:
        return notfound.layout

if __name__ == '__main__':
    app.run_server(debug=False)


from note import Note
from datetime import date
import json

path = 'notes/notes.json'
notes = list()

def importListFromFile():
    l = list()
    with open(path, 'r', encoding='utf-8') as f:
        l = json.load(f)
    for item in l:
        notes.append(Note().from_dict(item))

def exportListToFile():
    to_json = list()
    for item in notes:
        item: Note
        to_json.append(item.to_dict())
    with open(path, 'w') as f:
        json.dump(to_json, f, ensure_ascii=False, indent=2)

def getAllNotes():
    return notes

def getNoteByTitle(inputTitle) -> Note:
    result = Note()
    for item in notes:
        item: Note
        if item.title == inputTitle:
            result = item
    return result

def addNote(id, title, body, date: date):
    notes.append(Note(id, title, body, date))

def deleteByTitle(inputTitle: str):
    if isContainsByTitle(inputTitle):
        for item in notes:
            item: Note
            if item.title == inputTitle:
                notes.remove(item)
        return True
    return False

def changeByTitle(inputTitle, newBody):
    if isContainsByTitle(inputTitle):
        for item in notes:
            item: Note
            if item.title == inputTitle:
                item.body = newBody
                item.date = date.today()
        return True
    return False

def isContainsByTitle(inputTitle: str):
    for item in notes:
        item: Note
        if item.title == inputTitle:
            return True
    return False


import xml.etree.ElementTree as ET
from collections import Counter

fieldList = ['Class', 'AL', 'AR', 'AZ', 'CA', 'CO', 'CT', 'DC', 'DE', 'FL', 'GA', 'IA', 'ID', 'IL', 'IN', 'KS', 'KY', 'LA', 'MA', 'MD', 'ME', 'MI', 'MN', 'MO', 'MS', 'MT', 'NC', 'ND', 'NE', 'NH', 'NJ', 'NM', 'NV', 'NY', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VA', 'VT', 'WA', 'WI', 'WV', 'WY']
inputPath = r'C:\Users\danie\Desktop\GEOG 575\GEOG-575-Lab-2\data'
files = ['AllClasses.txt', 'BodyAttack.txt', 'BodyCombat.txt', 'BodyPump.txt', 'BodyStep.txt', 'Sprint.txt']
outputPath = r'C:\Users\danie\Desktop\GEOG 575\GEOG-575-Lab-2\data'
outputFileName = 'classes.csv'

def get_state_from_address(text):
    input = text.split(",")
    cityStateZip = input[-2]
    state = cityStateZip.split(" ")[-2]
    return state

def get_count(path, filename):

    file = open(r'{}\{}'.format(path, filename), 'r')
    data = file.read()
    file.close()

    root = ET.fromstring(data)

    states = []
    addressList = [] # To check for duplicate addresses

    for li in root:
        for item in li:
            if item.tag == "address" and item.text.endswith("United States"):
                address = item.text
                if address not in addressList:
                    addressList.append(address)
                    state = get_state_from_address(item.text)
                    states.append(str.upper(str(state)))

    c = Counter(states)

    countDict = dict(c)
    print(countDict)
    return countDict

def create_output_line(countDict, filename):
    className = filename.split('.')[0]
    output = className + ','
    countValues = []
    for state in fieldList[1:]:
        if state in countDict.keys():
            curValue = countDict[state]
            output += str(curValue) + ','
        else:
            output += '0,'
    output += '\n'
    return output

output = ''
for field in fieldList:
    output += field + ','
output = output[:-1] + '\n'

for file in files:
    countDict = get_count(inputPath, file)
    record = create_output_line(countDict, file)
    output += record

with open('{}\{}'.format(outputPath, outputFileName), 'w') as file:
          file.write(output)


# https://www.acmicpc.net/problem/20040

import sys
sys.setrecursionlimit(10**6)

inp = sys.stdin.readline

def get_parent(u):
    if parent[u] == u:
        return u
    parent[u] = get_parent(parent[u])
    return parent[u]

N, M = map(int, inp().split())
parent = list(range(N))
finished = False
finished_time = None

for i in range(1, M + 1):
    u, v = map(int, inp().split())
    if finished:
        continue
    pu = get_parent(u)
    pv = get_parent(v)
    if pu != pv:
        parent[pv] = pu
    else:
        finished = True
        finished_time = i

if finished:
    print(finished_time)
else:
    print(0)

25 사이클 게임.py


#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals

AUTHOR = u'tpnha'
AUTHORS = u'tpnha'
SITENAME = u'The Thomas Paine National Historical Association'
SITEURL = 'http://thomaspaine.org'

PATH = 'content'

TIMEZONE = 'Europe/Paris'

MENUITEMS = [
    ('Search', 'thomaspaine.org'),
    ]

DIRECT_TEMPLATES = ('index', 'archives', 'events', 'works')

DEFAULT_LANG = u'en'

EXTRA_PATH_METADATA = {
    'images/favicon.ico': {'path': 'favicon.ico'},
    }

# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None

THEME = 'theme'

# Blogroll
LINKS = (('Iona College', 'http://www.iona.edu/About/Iona-in-Community/Institute-for-Thomas-Paine-Studies/'),)

# Social widget
SOCIAL = ()

DEFAULT_PAGINATION = False

# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True


"""Service for engagement settings management."""
from met_api.constants.engagement_status import Status
from met_api.constants.membership_type import MembershipType
from met_api.models.engagement import Engagement as EngagementModel
from met_api.models.engagement_settings import EngagementSettingsModel
from met_api.schemas.engagement_settings import EngagementSettingsSchema
from met_api.services import authorization
from met_api.utils.roles import Role

class EngagementSettingsService:
    """Engagement settings management service."""

    @staticmethod
    def get(engagement_id) -> EngagementSettingsSchema:
        """Get Engagement settings by the id."""
        engagement_model: EngagementModel = EngagementModel.find_by_id(engagement_id)
        if engagement_model.status_id in (Status.Draft.value, Status.Scheduled.value):
            one_of_roles = (
                MembershipType.TEAM_MEMBER.name,
                Role.VIEW_ALL_ENGAGEMENTS.value
            )
            authorization.check_auth(one_of_roles=one_of_roles, engagement_id=engagement_id)

        settings_model: EngagementSettingsModel = EngagementSettingsModel.find_by_id(engagement_id)
        settings = EngagementSettingsSchema().dump(settings_model)
        return settings

    @staticmethod
    def create_settings(data: dict):
        """Create engagement settings."""
        settings_model = EngagementSettingsService._create_settings_model(data)
        settings_model.commit()
        return settings_model.find_by_id(settings_model.engagement_id)

    @staticmethod
    def create_default_settings(engagement_id: int):
        """Create default engagement settings."""
        data = {
            'engagement_id': engagement_id,
            'send_report': True
        }
        return EngagementSettingsService.create_settings(data)

    @staticmethod
    def _create_settings_model(settings: dict) -> EngagementSettingsModel:
        """Save engagement settings."""
        new_settings_model = EngagementSettingsModel(
            engagement_id=settings.get('engagement_id', None),
            send_report=settings.get('send_report', False),
        )
        new_settings_model.save()
        return new_settings_model

    @staticmethod
    def update_settings(data: dict):
        """Update engagement settings partially."""
        engagement_id = data.get('engagement_id', None)
        if not engagement_id:
            raise KeyError('Engagement id is required.')

        authorization.check_auth(
            one_of_roles=(MembershipType.TEAM_MEMBER.name, Role.EDIT_ENGAGEMENT.value),
            engagement_id=engagement_id
        )

        saved_settings = EngagementSettingsModel.find_by_id(engagement_id)

        if saved_settings:
            updated_settings = EngagementSettingsModel.update(engagement_id, data)
        else:
            updated_settings = EngagementSettingsService._create_settings_model(data)

        return updated_settings


import os
import win32process
import win32con
import win32api
import win32event

from .. import cypyonate as cypy

class Shellcode(cypy.Module):
	def __init__(self):
		super().__init__("Shellcode", ("shellcode", "shell"), "Shellcode injection")

	def inject(self, handler: cypy.Cypyonate, target: str, payload: str, verbose: bool):
		proc = cypy.get_process(target)
		if not proc:
			cypy.printe(f"Could not find process {target}")
			return

		b = payload
		if not handler.reflective:
			if not os.path.exists(payload):
				cypy.printe("Shellcode injection requires a valid path to a shellcode file")
				return

			with open(payload, "rb") as f:
				b = f.read()
				cypy.printv(f"Reading shellcode file {payload} ({len(b)} bytes)")

		mem = win32process.VirtualAllocEx(proc, 0, len(
			b), win32con.MEM_COMMIT | win32con.MEM_RESERVE, win32con.PAGE_EXECUTE_READWRITE)

		if not mem:
			cypy.printe("Could not allocate memory")
			return

		cypy.printv(f"Allocated {len(b)} bytes at {mem:X}")

		written = win32process.WriteProcessMemory(proc, mem, b)
		if not written:
			cypy.printe("Could not write to memory")
			return

		cypy.printv(f"Wrote {written} bytes to {mem:X}")

		# Create a thread
		cypy.printv(f"Creating thread at address {mem:X}")
		threadhandle, _ = win32process.CreateRemoteThread(
			proc, None, 0, mem, 0, 0)

		if not threadhandle:
			cypy.printe("Could not create thread")
			return

		cypy.printv("Closing handles")
		# Close handles
		win32api.CloseHandle(threadhandle)
		win32api.CloseHandle(proc)

		cypy.printc(f"Injected into {target} at {mem:X}")

Shellcode()


class Solution:
    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
        result = []

        for i in nums1:
            n2 = nums2.index(i)
            for j in range(n2, len(nums2)):
                if nums2[j] > i:
                    result.append(nums2[j])
                    break
            else:
                    result.append(-1)

        return result


import pyspark
from pyspark.context import SparkContext
from pyspark.sql.session import SparkSession
import os
import sys
sc = SparkContext.getOrCreate()
spark = SparkSession(sc)

df = spark.read.csv("airports.csv", inferSchema = True, header = True )

c=str(sys.argv[1])
outp=str(sys.argv[2])

os.environ["SPARK_WORKER_CORES"]=c
os.system("echo $SPARK_WORKER_CORES")

orig_stdout = sys.stdout
f = open(outp, 'w')
sys.stdout = f

df.filter(df["LATITUDE"] >= '10').filter(df["LATITUDE"] <= '90').filter(df["LONGITUDE"] <= '-10').filter(df["LONGITUDE"] >= '-90').select('NAME').show(20000)
sys.stdout = orig_stdout
f.close()

print("number of CPUs used:",c)
print("output written to:",outp)


# -*- coding: utf-8 -*-
"""
@author     Alexander Rüedlinger <a.rueedlinger@gmail.com>
@date       31.07.2015

"""

from pi_switch import RCSwitchReceiver
import time
import RPi.GPIO as GPIO

LED = 16
GPIO.setmode(GPIO.BOARD)
GPIO.setup(LED, GPIO.OUT)
GPIO.output(LED, GPIO.LOW)

receiver = RCSwitchReceiver()

receiver.enableReceive(2)

receiver.resetAvailable()
num = 0
led_state = False

while True:
    if receiver.available():
        received_value = receiver.getReceivedValue()
        if received_value:
            num += 1
            print("Received[%s]:" % num)
            print(received_value)
            print("%s / %s bit" % (received_value, receiver.getReceivedBitlength()))
            print("Protocol: %s" % receiver.getReceivedProtocol())
            print("")
            led_state = not led_state
            GPIO.output(LED, led_state)
            time.sleep(1.0)
        receiver.resetAvailable()


from django.conf.urls import url

from cms.apphook_pool import apphook_pool
from cms.cms_menus import SoftRootCutter
from menus.menu_pool import menu_pool

from shop.cms_apphooks import CatalogListCMSApp, OrderApp, PasswordResetApp
from dshop.views import DshopProductListView, OrderView

class CatalogListApp(CatalogListCMSApp):
    """
    Create a useable list of urls with Product's slug.
    """
    def get_urls(self, page=None, language=None, **kwargs):
        from dshop.catalog import AddToCartView
        from dshop.catalog import ProductRetrieveView
        from dshop.serializers import AddProductVariableToCartSerializer

        return [
            # Product loading page
            url(
                r'^category/(?P<category_id>[0-9]+)-(?P<category_slug>.+)$',
                DshopProductListView.as_view(),
            ),
            url(
                r'^brand/(?P<brand_id>[0-9]+)-(?P<brand_slug>.+)$',
                DshopProductListView.as_view(),
            ),
            url(
                r'^(?P<slug>[\w-]+)/add-to-cart',
                AddToCartView.as_view(), name="add_to_cart"
            ),
            url(
                r'^(?P<slug>[\w-]+)/add-productvariable-to-cart',
                AddToCartView.as_view(
                    serializer_class=AddProductVariableToCartSerializer,
                ), name="add_productvariable_to_cart"
            ),
            url(
                r'^(?P<slug>[\w-]+)',
                ProductRetrieveView.as_view(use_modal_dialog=False)
            ),
            url(
                r'^',
                DshopProductListView.as_view(),
                name='produits'
            ),
        ]

class OrderApp(OrderApp):

    def get_urls(self, page=None, language=None, **kwargs):
        from django.conf.urls import url

        return [
            url(r'^(?P<slug>[\w-]+)/(?P<secret>[\w-]+)',
                OrderView.as_view(many=False)),  # publicly accessible
            url(r'^(?P<slug>[\w-]+)',
                OrderView.as_view(many=False)),  # requires authentication
            url(r'^',
                OrderView.as_view()),  # requires authentication
        ]

apphook_pool.register(CatalogListApp)

apphook_pool.register(OrderApp)
apphook_pool.register(PasswordResetApp)

def _deregister_menu_pool_modifier(Modifier):
    index = None
    for k, modifier_class in enumerate(menu_pool.modifiers):
        if issubclass(modifier_class, Modifier):
            index = k
    if index is not None:
        menu_pool.modifiers.pop(index)

_deregister_menu_pool_modifier(SoftRootCutter)


from django.urls import path
from django.shortcuts import render
from . import views
from django.contrib.auth.views import LoginView,LogoutView

urlpatterns = [
    # customer view
    path('',views.indexView,name="index"),
    path('home/',views.homeView.as_view(),name="home"),
    path('dashboard/',views.dashboardView,name="dashboard"),
    path('product_display/<pk>',views.productView,name="product_display"),
    path('buy_product/<pk>',views.buyProductView,name="buy_item"),
    path('add_balance/',views.addBalanceView.as_view(),name="add_balance"),
    path('customer_orders/',views.customerOrdersView,name='customer_orders'),
    path('vendor_profile/<pk>',views.vendorProfileView,name='vendor_profile'),
    path('customer_profile/',views.customerProfileView,name='customer_profile'),
    path('add_review/<pk>',views.addReview,name='add_review'),
    path('add_to_cart/<pk>/<is_wished>',views.addToCartView,name='add_to_cart'),
    path('show_cart_items/<is_wished>',views.showCartItemView,name='show_cart_items'),
    path('remove_cart_item/<pk>',views.removeCartItem,name='remove_cart_item'),
    path('buy_multiple_item/',views.buyMultiItemView,name='buy_multiple_item'),
    path('order_detail/<pk>',views.orderDetailView,name='order_detail'),
    path('switch_cart/<pk>',views.switchCartView,name='switch_carts'),

    # seller view
    path('seller/order_list/',views.listOrdersView,name="order_list"),
    path('seller/item_list/',views.listItemView,name="item_list"),
    path('seller/add_item/',views.addItemView.as_view(),name="add_item"),
    path('seller/delete_item/<pk>',views.deleteItemView,name = "delete_item"),
    path('seller/edit_item/<pk>',views.editItemView.as_view(),name = "edit_item"),
    path('seller/get_sales_report/',views.salesReportView,name = "get_sales_report"),

]


import pyecharts.options as opts
from pyecharts.charts import Line, Timeline
from pyecharts.options import LabelOpts
import pickle
import numpy as np
import matplotlib.pyplot as plt

expert_info = np.genfromtxt('../tcdata/sic_semi_process_time_matrix.csv', delimiter=',', encoding='utf-8', dtype='int64')
expert_info = np.delete(expert_info, [0], axis=0)
expert_info = np.delete(expert_info, [0], axis=1)

task_info = np.genfromtxt('../tcdata/sic_semi_work_order.csv', encoding='utf-8', dtype=np.int, delimiter=',')
task_info[0, 0] = 1
task_info[:, [0, 2]] -= 1  # 从0开始

with open('data_280.pkl', 'rb') as file:
    new_arrival_seq_3, waiting_seq_3, processing_seq_3, expert_load_seq_3, expert_work_time_seq_3 = pickle.load(file)
with open('data_272.pkl', 'rb') as file:
    new_arrival_seq_1, waiting_seq_1, processing_seq_1, expert_load_seq_1, expert_work_time_seq_1 = pickle.load(file)

time_1 = np.array(list(new_arrival_seq_1.keys()))
n_new_arrival_1 = np.array([len(new_arrival_seq_1[key]) for key in time_1])
n_waiting_1 = np.array([len(waiting_seq_1[key]) for key in time_1])
n_processing_1 = np.array([len(processing_seq_1[key]) for key in time_1])

time_3 = np.array(list(new_arrival_seq_3.keys()))
n_new_arrival_3 = np.array([len(new_arrival_seq_3[key]) for key in time_3])
n_waiting_3 = np.array([len(waiting_seq_3[key]) for key in time_3])
n_processing_3 = np.array([len(processing_seq_3[key]) for key in time_3])

tl = Timeline(init_opts=opts.InitOpts(width="1600px", height="800px"))
tl.add_schema(play_interval=100, is_loop_play=False, is_timeline_show=False, is_auto_play=True)
this_time = []
this_new_arrival = []
this_waiting = []
this_processing_1 = []
this_processing_3 = []
time_start = 600
time_end = 800
t_start = time_start - 481
t_end = time_end - 481
for i in range(t_end - t_start):
    # this_time.append([j for j in range(i+1)])
    # this_new_arrival.append([0 for j in range(i+1)])
    # this_waiting.append([1 for j in range(i+1)])
    # this_processing.append([-1 for j in range(i+1)])
    this_time.append(list(range(i+1)))
    # this_new_arrival.append(n_new_arrival[t_start:t_start+i+1].tolist())
    # this_waiting.append(n_waiting[t_start:t_start+i+1].tolist())
    this_processing_1.append(n_processing_1[t_start:t_start + i + 1].tolist())
    this_processing_3.append(n_processing_3[t_start:t_start + i + 1].tolist())
for i in range(t_end - t_start):
    line = (
        Line()
        .add_xaxis(xaxis_data=this_time[i])
        # .add_yaxis(
        #     series_name="new arrival",
        #     y_axis=this_new_arrival[i],
        # )
        .add_yaxis(
            series_name="有预测",
            y_axis=this_processing_3[i],
        )
        .add_yaxis(
            series_name='无预测',
            y_axis=this_processing_1[i],
        )
        .set_global_opts(
            title_opts=opts.TitleOpts(title="任务数量变化"),
            # tooltip_opts=opts.TooltipOpts(trigger="axis"),
            # toolbox_opts=opts.ToolboxOpts(is_show=True),
            # xaxis_opts=opts.AxisOpts(type_="category", boundary_gap=False),
        )
        .set_series_opts(LabelOpts(is_show=False))
    )
    tl.add(line, 't={}'.format(i))
# tl.render("num_task_change.html")

plt.figure(figsize=(30, 20), dpi=100, facecolor='w', edgecolor='k')
plt.plot(np.arange(time_start, time_end + 1), n_processing_1[t_start:t_end + 1], marker='o', label='no prediction')
plt.plot(np.arange(time_start, time_end + 1), n_processing_3[t_start:t_end + 1], marker='o', label='with prediction')
plt.yticks(fontsize=36)
plt.xticks(fontsize=36)
plt.grid()
plt.legend(fontsize=36)
plt.savefig('processing_comparison.png', dpi=300)
plt.show()

x_1 = time_1
x_3 = time_3
y_1 = np.zeros(len(time_1), dtype=np.int)
y_3 = np.zeros(len(time_3), dtype=np.int)
for i in range(len(time_1)-1):
    t = time_1[i]
    y_1[i] = np.sum((expert_load_seq_1[t + 1] - expert_load_seq_1[t])[:, 5])
for i in range(len(time_3) - 1):
    t = time_3[i]
    y_3[i] = np.sum((expert_load_seq_3[t + 1] - expert_load_seq_3[t])[:, 5])
plt.figure(figsize=(30, 20), dpi=100, facecolor='w', edgecolor='k')
plt.plot(x_1, y_1, marker='o', label='no prediction')
plt.plot(x_3, y_3, marker='o', label='with prediction')
plt.yticks(fontsize=36)
plt.xticks(fontsize=36)
plt.grid()
plt.legend(fontsize=36)
plt.savefig('la_comparison.png', dpi=300)
plt.show()

x_1 = time_1
x_3 = time_3
# zuihuigan = np.argmin(expert_info, axis=1)
zuixiaoshijian = np.min(expert_info, axis=0)
zuihuigan = [np.where(expert_info[i] == zuixiaoshijian)[0] for i in range(len(expert_info))]
y_1 = np.zeros(len(time_1), dtype=np.int)
y_3 = np.zeros(len(time_3), dtype=np.int)
for i in range(len(time_1)):
    t = time_1[i]
    expert_load_seq_1_copy_t = expert_load_seq_1[t].copy()
    expert_load_seq_1_copy_t[expert_load_seq_1[t] == -1] = 0
    expert_load_seq_1_copy_t[:, 0] = task_info[expert_load_seq_1_copy_t[:, 0], 2]
    expert_load_seq_1_copy_t[:, 1] = task_info[expert_load_seq_1_copy_t[:, 1], 2]
    expert_load_seq_1_copy_t[:, 2] = task_info[expert_load_seq_1_copy_t[:, 2], 2]
    expert_load_seq_1_copy_t[expert_load_seq_1[t] == -1] = -1
    for j in range(133):
        y_1[i] += np.sum(np.isin(expert_load_seq_1_copy_t[j, [0, 1, 2]], zuihuigan[j]))
for i in range(len(time_3)):
    t = time_3[i]
    expert_load_seq_3_copy_t = expert_load_seq_3[t].copy()
    expert_load_seq_3_copy_t[expert_load_seq_3[t] == -1] = 0
    expert_load_seq_3_copy_t[:, 0] = task_info[expert_load_seq_3_copy_t[:, 0], 2]
    expert_load_seq_3_copy_t[:, 1] = task_info[expert_load_seq_3_copy_t[:, 1], 2]
    expert_load_seq_3_copy_t[:, 2] = task_info[expert_load_seq_3_copy_t[:, 2], 2]
    expert_load_seq_3_copy_t[expert_load_seq_3[t] == -1] = -1
    for j in range(133):
        y_3[i] += np.sum(np.isin(expert_load_seq_3_copy_t[j, [0, 1, 2]], zuihuigan[j]))
plt.figure(figsize=(30, 20), dpi=100, facecolor='w', edgecolor='k')
plt.plot(x_1, y_1, marker='o', label='no prediction')
plt.plot(x_3, y_3, marker='o', label='with prediction')
plt.yticks(fontsize=36)
plt.xticks(fontsize=36)
plt.grid()
plt.legend(fontsize=36)
plt.savefig('zuihuigan_comparison.png', dpi=300)
plt.show()


import numpy as np
import random as rd
from Scene import Scene
from Snake import Snake
import pygame, random
from pygame.locals import *
from feedfoward import feedfoward
from normalize import preparateInputData

def ConvertDirection(vector):
    if vector == [-1,-1,-1,1]:
        my_direction = 'UP'
    elif vector == [-1,-1,1,-1]:
        my_direction = 'DOWN'
    elif vector == [-1,1,-1,-1]:
        my_direction = 'LEFT'
    #elif vector == [1,-1,-1,-1]:
    else:
        my_direction = 'RIGHT'
    return my_direction

def ChooseBest(population,offspring,fitness,fitness_offspring):
    fitness_sorted = np.argsort(np.array(fitness+fitness_offspring))[-1:-int(len(population)+1):-1]
    population_merge = population + offspring
    fitness_merge = fitness+fitness_offspring
    #ziped = zip(population + offspring, fitness+fitness_offspring)
    new_population = [population_merge[i] for i in fitness_sorted]
    new_fitness = [fitness_merge[i] for i in fitness_sorted]
    return new_population,new_fitness

def SaveBestSelection(population,offspring,fitness,fitness_offspring):
    new_population = []
    new_fitness = []

    best_index = np.argsort(np.array(fitness))[-1]

    new_population.append(population[best_index])
    new_fitness.append(fitness[best_index])

    for i in range(len(population) - 1):
        pop,fit = Roulette(offspring,fitness_offspring)
        new_population.append(pop)
        new_fitness.append(fit)

    return new_population,new_fitness

def Roulette(population,fitness):

    ## Criar roleta
    roulette = fitness/np.sum(fitness) # ver a questão da quantidade de casas numérica
    # Sortear número
    num = rd.random()

    acc = 0
    for index in range(len(fitness)):
        acc += roulette[index]
        if num < acc:
            return population[index],fitness[index]

'''
def Roulette(population,fitness):

    newParents = []
    ## Criar roleta

    roulette = fitness/np.sum(fitness) # ver a questão da quantidade de casas numérica
    for i in range(2):

        # Sortear número
        num = rd.random()

        acc = 0
        for index in range(len(fitness)):
            acc += roulette[index]
            if num < acc:
                newParents.append(population[index])
                break
    return newParents
'''
def crossoverBlx(parents,tax):
    ##Verificar se deve haver cruzamento
    num = rd.random()

    if num <= tax:
        offspring = []
        ##Gerar dois novos novos filhos
        for index in range(2):
            child = []
            for layer in range(len(parents[0])):
                ## b variando entre -0,5 e 1,5
                b = 2*rd.random() -0.5
                if index == 0:
                    weigth = parents[0][layer] + b*(parents[1][layer] - parents[0][layer])
                else:
                    weigth = parents[1][layer] + b*(parents[0][layer] - parents[1][layer])
                child.append(weigth)
            offspring.append(child)

        return offspring
    else:
        return parents

def GaussMatation(offspring,tax,mean,std):
    #print(offspring)

    for son in offspring:
        r = rd.random()
        if r<tax:
            #print("mutação:")
            #print("Antes:")
            #print(offspring)
            for layer in range(len(son)):
                #print(son)
                #print(son[layer])
                ##Quantidade de elementos da matriz de pesos para todas as linhas e colunas
                for line in range(np.shape(son[layer])[0]):
                    for column in range(np.shape(son[layer])[1]):
                        ##Verificar se vai haver mutação
                        #r = rd.random()
                        #if r<tax:
                            #print("mutacao")
                        ##Etapa de mutação utilizando distribuição gaussiana
                            son[layer][line][column] += std*rd.random() + mean
            #print("Depois:")
            #print(offspring)

    return offspring

def PlayGame(scene,snake,population,topology,fps):

    clock = pygame.time.Clock()
    while True:
        clock.tick(fps)

        coord = preparateInputData(scene.CalculateMetrics(snake),60)

        dir = feedfoward(population,topology,coord,4)

        direction = ConvertDirection(dir)

        snake.UpdateDirection(direction)

        scene.CheckCatchApple(snake)

        snake.UpdateSnake()

        ret = scene.CheckColisson(snake)
        if ret == False and scene.CheckFinalStep() == False:
            scene.UpdateScreen(snake)
        else:
            fit,score = scene.GameOver()
            return fit,score

def Main(topology,mutation_tax,crossover_tax,qtd_population,qtd_offspring,generations,std):
    x_train_length = 26
    d_train_length = 4
    screen_length = 600
    x_screen = 600
    y_screen = 600

    fps = 2

    population = []
    fitness = []
    offspring_population = []
    offspring_fitness = []

    max_score = 0

    for i in range(qtd_population):
        population.append(init_weigth(topology,x_train_length,d_train_length))
        offspring_population.append(init_weigth(topology,x_train_length,d_train_length))
        fitness.append(0)
        offspring_fitness.append(0)
    '''
    for i in range(qtd_offspring):
        offspring_population.append(init_weigth(topology,x_train_length,d_train_length))
        offspring_fitness.append(0)
    '''
    ##Repetir o sistema pela quantidade de gerações especificadas

    ## Calcular fitness
    for index in range(qtd_population):
        scene = Scene(x_screen,y_screen)
        snake = Snake()

        fit,score = PlayGame(scene,snake,population[index],topology,fps)

        fitness[index] = fit
        if (score>max_score):
            max_score = score
        break

    for gen in range(generations):
        print("Começou a geração " + str(gen+1))

        score_gen = 0
        ctrMortesPassos = 0

        ##Gerar novos filhos
        for index in range(int(qtd_population/2)):

            ##Roleta
            offspring=[]
            for i in range(2):
                pop,fit = Roulette(population,fitness)
                offspring.append(pop)

            ##Crossover
            offspring = crossoverBlx(offspring,crossover_tax)

            ##Mutação
            offspring = GaussMatation(offspring,mutation_tax,0,std)

            for i in range(2):
                offspring_population[2*index + i] = offspring[i]
                #population[2*index + i] = offspring[i]

        ## Calcular fitness dos novos filhos
        for index in range(qtd_population):
            scene = Scene(x_screen,y_screen)
            snake = Snake()

        fit,score = PlayGame(scene,snake,offspring_population[index],topology,fps)

        fitness[index] = fit
        if (score>max_score):
            max_score = score
        break

        ## Escolher os melhores entre pais e filhos
        population,fitness  = SaveBestSelection(population,offspring_population,fitness,offspring_fitness)
        print("Média: " + str(sum(fitness)/len(fitness)))
        print("Máximo: " + str(max(fitness)))
        print("Score Máximo: " + str(max_score))
        print("Score Geracao: " + str(score_gen))
        print("Mortes por excesso: " + str(ctrMortesPassos))

def init_weigth(topology,x_train_length,d_train_length):
    weights = []
    # Inicializar as matrizes de pesos e o acumulador
    for index in range(len(topology)+1):
        if index == 0:
            weight = np.random.rand(topology[index], x_train_length+1)-0.5
        elif index == len(topology):
            weight = np.random.rand(d_train_length,topology[index-1] + 1)-0.5
        else:
            weight = np.random.rand(topology[index], topology[index-1]+1)-0.5

        weights.append(weight)

    return weights

Main([15,15],0.05,0.9,2000,20,30,0.2)


from motor.motor_asyncio import AsyncIOMotorClient

client = AsyncIOMotorClient('localhost', 27017)
db = client['test-database']
collection = db['citizen_mongo']

class MongoClient:

    async def do_insert(self, doc):
        result = await collection.insert_one(doc)
        return result.inserted_id

    async def do_count(self):
        res = await collection.estimated_document_count()
        # print(res)
        return res

    async def find(self, r={}, limit=0):
        cursor = collection.find(r).limit(limit)
        docs = await cursor.to_list(length=100)
        res = []
        while docs:
            for doc in docs:
                # print(doc)
                res.append(doc)
            docs = await cursor.to_list(length=100)
        return res

if __name__ == '__main__':
    import asyncio

    loop = asyncio.get_event_loop()
    loop.run_until_complete(MongoClient().do_count())
    loop.run_until_complete(MongoClient().do_insert({'name': 'barrrr', 'coordinates': {'lon': 55, 'lat': 55}}))


import json
import unittest

from app import app, db
from apps.downloads.models import DownloadsReleases
from apps.releases.models import Releases
from apps.utils.time import get_datetime

class TestDownloadsReleasesViews(unittest.TestCase):
    def setUp(self):
        self.app = app.test_client()
        # Add 2 releases
        release1 = Releases(
            Title="UnitTest 1",
            Date=get_datetime(),
            Artist="UnitTest Arts 1",
            Credits="UnitTest is a good and fun activity",
            Created=get_datetime(),
            ReleaseCode="TEST001"
        )
        release2 = Releases(
            Title="UnitTest 2",
            Date=get_datetime(),
            Artist="UnitTest 2 Arts",
            Credits="UnitTest too is good for testing",
            Created=get_datetime(),
            ReleaseCode="TEST002"
        )
        db.session.add(release1)
        db.session.add(release2)
        db.session.commit()
        self.release_ids = [release1.ReleaseID, release2.ReleaseID]

        # Add downloads for them
        rel1_dl1 = DownloadsReleases(
            ReleaseID=self.release_ids[0],
            DownloadDate="2017-01-01 12:00:15"
        )
        rel1_dl2 = DownloadsReleases(
            ReleaseID=self.release_ids[0],
            DownloadDate="2017-01-02 12:00:15"
        )
        rel1_dl3 = DownloadsReleases(
            ReleaseID=self.release_ids[0],
            DownloadDate="2017-01-03 12:00:15"
        )
        rel2_dl1 = DownloadsReleases(
            ReleaseID=self.release_ids[1],
            DownloadDate="2017-03-02 01:00:15"
        )
        rel2_dl2 = DownloadsReleases(
            ReleaseID=self.release_ids[1],
            DownloadDate="2017-04-02 12:00:15"
        )
        db.session.add(rel1_dl1)
        db.session.add(rel1_dl2)
        db.session.add(rel1_dl3)
        db.session.add(rel2_dl1)
        db.session.add(rel2_dl2)
        db.session.commit()

    def tearDown(self):
        # Will also delete the downloads
        for release in Releases.query.filter(Releases.Title.like("UnitTest%")).all():
            db.session.delete(release)
        db.session.commit()

    def test_getting_all_download_counts(self):
        """Should return the download counts for all releases."""
        response = self.app.get("/api/1.0/downloads/releases/")
        data = json.loads(response.data.decode())

        self.assertEqual(200, response.status_code)
        self.assertNotEqual(None, data)
        self.assertEqual(2, len(data["downloads"]))

        self.assertEqual(self.release_ids[0], data["downloads"][0]["releaseID"])
        self.assertEqual(3, data["downloads"][0]["count"])
        self.assertEqual("2017-01-01 12:00:15", data["downloads"][0]["since"])

        self.assertEqual(self.release_ids[1], data["downloads"][1]["releaseID"])
        self.assertEqual(2, data["downloads"][1]["count"])
        self.assertEqual("2017-03-02 01:00:15", data["downloads"][1]["since"])

    def test_getting_download_count_for_specific_release(self):
        """Should return the download count for the specified release."""
        response = self.app.get("/api/1.0/downloads/releases/{}".format(self.release_ids[1]))
        data = json.loads(response.data.decode())

        self.assertEqual(200, response.status_code)
        self.assertNotEqual(None, data)
        self.assertEqual(1, len(data["downloads"]))

        self.assertEqual(self.release_ids[1], data["downloads"][0]["releaseID"])
        self.assertEqual(2, data["downloads"][0]["count"])
        self.assertEqual("2017-03-02 01:00:15", data["downloads"][0]["since"])

    def test_adding_a_download(self):
        """Should add the entry to DB using the release ID specified in the JSON."""
        response = self.app.post(
            "/api/1.0/downloads/releases/",
            data=json.dumps(
                dict(
                    releaseID=self.release_ids[0],
                )
            ),
            content_type="application/json"
        )

        downloads = DownloadsReleases.query.filter_by(ReleaseID=self.release_ids[0]).all()

        self.assertEqual(201, response.status_code)
        self.assertTrue("Location" in response.data.decode())
        self.assertEqual(4, len(downloads))


import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
from PIL import Image
from numpy import array

# Read in the image and print out some stats
# image = mpimg.imread('ColorSelectionTest.png')
image_P = Image.open('ColorSelectionTest.jpg')
print('This image is: ',type(image_P),
         'with dimensions:', image_P.size)

image=array(image_P)

# Pull out the x and y sizes and make a copy of the image
ysize = image.shape[0]
xsize = image.shape[1]
region_select = np.copy(image)

left_bottom = [70,540]
right_bottom = [860,540]
apex = [480, 280]

# Fit lines (y=Ax+B) to identify the  3 sided region of interest
# np.polyfit() returns the coefficients [A, B] of the fit
fit_left = np.polyfit((left_bottom[0], apex[0]), (left_bottom[1], apex[1]), 1)
fit_right = np.polyfit((right_bottom[0], apex[0]), (right_bottom[1], apex[1]), 1)
fit_bottom = np.polyfit((left_bottom[0], right_bottom[0]), (left_bottom[1], right_bottom[1]), 1)

# Find the region inside the lines
XX, YY = np.meshgrid(np.arange(0, xsize), np.arange(0, ysize))
region_thresholds = (YY > (XX*fit_left[0] + fit_left[1])) & \
                    (YY > (XX*fit_right[0] + fit_right[1])) & \
                    (YY < (XX*fit_bottom[0] + fit_bottom[1]))

# Color pixels red which are inside the region of interest
region_select[region_thresholds] = [255, 0, 0]
# print(region_thresholds)

# Display the image
plt.imshow(region_select)
plt.show()


import random
sort = []
for j in range(0,30):
    sort.append(random.randrange(100,200))
print(sort)

def s():
    swap = 0
    for j in range(len(sort)):
        smol = sort[j]
        for i in range(len(sort)-j):
            if sort[i+j] < smol:
                smol = sort[i+j]
                swap = i+j

        temp = sort[j]
        sort[j] = smol
        sort[swap] = temp

    print(sort)

s()


import unittest

import os
import subprocess

class TestGenericClient(unittest.TestCase):

    JSON_PATH = 'etc/'

    def setUp(self):
        None

    def test_json_lint(self):
        """
        Lint all the JSON files under the services directory
        """
        files = []
        for r, d, fs in os.walk(self.JSON_PATH):
            for f in fs:
                files.append(os.path.join(r, f))

        for f in files:
            return_code = subprocess.call('jsonlint %s' % f,
                                          shell=True)

            self.assertEqual(return_code, 0, 'File %s did not validate' % f)

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


import numpy as np
from scipy.spatial.transform import Rotation as Rotation

class SE3Control(object):
    """

    """
    def __init__(self, quad_params, k_p, k_d, k_r, k_w):
        """
        This is the constructor for the SE3Control object. You may instead
        initialize any parameters, control gain values, or private state here.

        For grading purposes the controller is always initialized with one input
        argument: the quadrotor's physical parameters. If you add any additional
        input arguments for testing purposes, you must provide good default
        values!

        Parameters:
            quad_params, dict with keys specified by crazyflie_params.py

        """

        # Quadrotor physical parameters.
        self.mass            = quad_params['mass'] # kg
        self.Ixx             = quad_params['Ixx']  # kg*m^2
        self.Iyy             = quad_params['Iyy']  # kg*m^2
        self.Izz             = quad_params['Izz']  # kg*m^2
        self.arm_length      = quad_params['arm_length'] # meters
        self.rotor_speed_min = quad_params['rotor_speed_min'] # rad/s
        self.rotor_speed_max = quad_params['rotor_speed_max'] # rad/s
        self.k_thrust        = quad_params['k_thrust'] # N/(rad/s)**2
        self.k_drag          = quad_params['k_drag']   # Nm/(rad/s)**2

        # You may define any additional constants you like including control gains.
        self.inertia = np.diag(np.array([self.Ixx, self.Iyy, self.Izz])) # kg*m^2
        self.g = 9.81 # m/s^2

        # STUDENT CODE HERE

        #k_p = 20
        #k_d = 900
        k_p = k_p
        k_d = k_d #bro what the fuck
        k_w = k_w
        k_r = k_r
        self.K_p = np.array([[k_p, 0, 0],
                             [0, k_p, 0],
                             [0, 0, k_p]])

        self.K_d = np.array([[k_d, 0, 0],
                             [0, k_d, 0],
                             [0, 0, k_d]])

        self.K_w = np.array([[60, 0, 0],
                             [0, 60, 0],
                             [0, 0, 60]])

        self.K_r = np.array([[2430, 0, 0],
                             [0, 2430, 0],
                             [0, 0, 400]])

    def vee_map(self, R):
        #R -3 3x3  skew symmetric matrix
        c = R[1][0]
        b = R[0][2]
        a = R[2][1]

        #print('input R: ', R)
        #print('vee output: ', [a, b, c])

        return np.array([a, b, c])

    def update(self, t, state, flat_output):
        """
        This function receives the current time, true state, and desired flat
        outputs. It returns the command inputs.

        Inputs:
            t, present time in seconds
            state, a dict describing the present state with keys
                x, position, m
                v, linear velocity, m/s
                q, quaternion [i,j,k,w]
                w, angular velocity, rad/s
            flat_output, a dict describing the present desired flat outputs with keys
                x,        position, m
                x_dot,    velocity, m/s
                x_ddot,   acceleration, m/s**2
                x_dddot,  jerk, m/s**3
                x_ddddot, snap, m/s**4
                yaw,      yaw angle, rad
                yaw_dot,  yaw rate, rad/s

        Outputs:
            control_input, a dict describing the present computed control inputs with keys
                cmd_motor_speeds, rad/s
                cmd_thrust, N (for debugging and laboratory; not used by simulator)
                cmd_moment, N*m (for debugging; not used by simulator)
                cmd_q, quaternion [i,j,k,w] (for laboratory; not used by simulator)
        """
        cmd_motor_speeds = np.zeros((4,))
        cmd_thrust = 0
        cmd_moment = np.zeros((3,))
        cmd_q = np.zeros((4,))

        #exit()

        # STUDENT CODE HERE
        #print('time: ', t)
        #print('current location: ', state["x"])
        #print('desired location: ', flat_output["x"])
        #print('desired velocity: ', flat_output["x_dot"])
        r_dott_des = flat_output["x_ddot"] - np.matmul(self.K_d, (state["v"]-flat_output["x_dot"])) - np.matmul(self.K_p, (state["x"] - flat_output["x"])) #desired acceleration
        #print('r dotdot des: ', r_dott_des)
        F_des = self.mass*r_dott_des + np.array([0, 0, self.mass*self.g]) #desired force
        #print('F des: ', F_des)

        #calculate rotaiton matrix from input quaternion
        q0 = state["q"][3] #w
        q1 = state["q"][0] #i
        q2 = state["q"][1] #j
        q3 = state["q"][2] #k

        #https://automaticaddison.com/wp-content/uploads/2020/09/quaternion-to-rotation-matrix.jpg
        R = np.array([[2*(q0**2+q1**2)-1, 2*(q1*q2-q0*q3), 2*(q1*q3+q0*q2)],
                      [2*(q1*q2+q0*q3), 2*(q0**2+q2**2)-1, 2*(q2*q3-q0*q1)],
                      [2*(q1*q3-q0*q2), 2*(q2*q3+q0*q1), 2*(q0**2+q3**2)-1]])

        R = Rotation.from_quat(state["q"]).as_matrix()

        #print('R: ', R)

        a_yaw = np.array([np.cos(flat_output["yaw"]),
                          np.sin(flat_output["yaw"]),
                          0])

        #print('a yaw: ', a_yaw)

        b3_des = F_des / np.linalg.norm(F_des)
        b2_des = np.cross(b3_des, a_yaw) / np.linalg.norm(np.cross(b3_des, a_yaw))
        b1_des = np.cross(b2_des, b3_des)

        #print('b3 des: ', b3_des)
        #print('b2 des: ', b2_des)
        #print('b1 des: ', b1_des)

        R_des = np.array([b1_des, b2_des, b3_des]).T

        #print('R des: ', R_des)

        e_R = 0.5*self.vee_map(np.matmul(R_des.T, R) - np.matmul(R.T, R_des))
        #print('error R: ', e_R)
        e_W = state["w"] - 0 #setting desired angular velocity to 0
        #print('error W:', e_W)

        #desired inputs
        b3 = R@np.array([[0],[0],[1]])
        #print('b3', b3)
        u1 = np.matmul(b3.T, F_des)
        u2 = np.matmul(self.inertia, (-np.matmul(self.K_r, e_R) - np.matmul(self.K_w, e_W)))

        #print('u1: ', u1)
        #print('u2: ', u2)

        #calculate corresponding forces
        u = np.array([u1[0], u2[0], u2[1], u2[2]]) #input matrix

        #print('u: ', u)
        #follows the mellinger paper
        K = np.array([[self.k_thrust, self.k_thrust, self.k_thrust, self.k_thrust],
                      [0, self.k_thrust*self.arm_length, 0, -self.k_thrust*self.arm_length],
                      [-self.k_thrust*self.arm_length, 0, self.k_thrust*self.arm_length, 0],
                      [self.k_drag, -self.k_drag, self.k_drag, -self.k_drag]])

        #gamma = self.k_drag/self.k_thrust
        #K = np.array([[1, 1, 1, 1],
        #              [0, self.arm_length, 0, -self.arm_length],
        #              [-self.arm_length, 0, self.arm_length, 0],
        #              [gamma, -gamma, gamma, -gamma]])

        #print('K: ', K)

        cmd_motor_speeds = np.matmul(np.linalg.inv(K),u) #motor speeds^2
        #make sure motor speeds are physically feasible:
        for i in range(len(cmd_motor_speeds)):
            if cmd_motor_speeds[i] > self.rotor_speed_max**2:
                cmd_motor_speeds[i] = self.rotor_speed_max**2
            elif cmd_motor_speeds[i] < self.rotor_speed_min:
                cmd_motor_speeds[i] = self.rotor_speed_min
        cmd_thrust = self.k_thrust*cmd_motor_speeds #motor thrusts
        cmd_moment = self.k_drag*cmd_motor_speeds #motor moments
        cmd_motor_speeds = np.sqrt(cmd_motor_speeds)

        #print('cmd motor speeds: ', cmd_motor_speeds)
        #print('cmd thrust: ', cmd_thrust)
        #print('cmd moment: ', cmd_moment)

        #calculate desired quaternion
        #https://danceswithcode.net/engineeringnotes/quaternions/quaternions.html
        a = (1+R_des[0][0]+R_des[1][1]+R_des[2][2])/4
        if abs(a) < 0.0001:
            a = 0
        mag_q0 = np.sqrt(a)
        b = (1+R_des[0][0]-R_des[1][1]-R_des[2][2])/4
        if abs(b) < 0.0001:
            b = 0
        mag_q1 = np.sqrt(b)
        c = (1-R_des[0][0]+R_des[1][1]-R_des[2][2])/4
        if abs(c) < 0.0001:
            c = 0
        mag_q2 = np.sqrt(c)
        d = (1-R_des[0][0]-R_des[1][1]+R_des[2][2])/4
        if abs(d) < 0.0001:
            d = 0
        mag_q3 = np.sqrt(d)

        #print('mag q0: ', mag_q0)
        #print('mag q1: ', mag_q1)
        #print('mag q2: ', mag_q2)
        #print('mag q3: ', mag_q3)

        q0 = None
        q1 = None
        q2 = None
        q3 = None

        if max([mag_q0, mag_q1, mag_q2, mag_q3]) == mag_q0:
            q0 = mag_q0
            q1 = (R[2][1] - R[1][2])/(4*q0)
            q2 = (R[0][2] - R[2][0])/(4*q0)
            q3 = (R[1][0] - R[0][1])/(4*q0)

        elif max([mag_q0, mag_q1, mag_q2, mag_q3]) == mag_q1:
            q1 = mag_q1
            q0 = (R[2][1] - R[1][2])/(4*q1)
            q2 = (R[0][1] + R[1][0])/(4*q1)
            q3 = (R[0][2] + R[2][0])/(4*q1)

        elif max([mag_q0, mag_q1, mag_q2, mag_q3]) == mag_q2:
            q2 = mag_q2
            q0 = (R[0][2] - R[2][0])/(4*q2)
            q1 = (R[0][1] + R[1][0])/(4*q2)
            q3 = (R[1][2] + R[2][1])/(4*q2)
        else:
            q3 = mag_q3
            q0 = (R[1][0] - R[0][1])/(4*q3)
            q1 = (R[0][2] + R[2][0])/(4*q3)
            q2 = (R[1][2] + R[2][1])/(4*q3)

        cmd_q = [q1, q2, q3, q0]

        #print('cmd q: ', cmd_q)

        control_input = {'cmd_motor_speeds':cmd_motor_speeds,
                         'cmd_thrust':cmd_thrust,
                         'cmd_moment':cmd_moment,
                         'cmd_q':cmd_q}

        #exit()

        return control_input


# -*- coding: utf-8 -*-
"""
Created on Tue May 14 17:44:56 2019

@author: Narayan Devpura
"""

# Create a new Code Challenge to POST data

# Research the below wesbite and post some data on it

# https://requestbin.com

import requests

Host = "http://httpbin.org"

data = {"firstname":"abx","language":"Urdu"}

headers = {"Content-Type":"application/json","Content-Length":len(data)}

def post_method():
    response = requests.post(Host+"/post",json=data)
    return response

print ( post_method().text )

def get_method():
    response = requests.get("http://httpbin.org/get?q=firstname=dev023")
    return response

print (get_method().json())


# coding: utf-8
import sys
import os

DEBUG = True
os.environ['DEBUG'] = str(DEBUG)

app_name = 'Decision tree model visualization'
base_dir = os.path.abspath(os.path.dirname(__file__))
home_dir = os.path.expanduser('~')
app_config_fp = os.path.join(home_dir, 'qt.{}'.format(app_name))

log_file = os.path.join(base_dir, 'log.log')
image_width = 1024
image_height = 768

time_format = '%Y-%m-%d %H:%M:%S'


from crible_eratosthene import eratosthene
import numpy as np
import matplotlib.pyplot as plt

def pi(n):
    """La fonciton qui compte les nombres premiers"""
    L = eratosthene(n)
    return len(L)

th_nb_prem = lambda n : n/np.log(n)  # x-> x/(log x), l'approximation fournie par le théorème des nomrbes premiers

def Li(x, n = 10**4):

    """On utilise la méthode des rectangles à gauche pour approximer l'intégrale
    de 2 à x de dt/ln(t) """

    f = lambda t : 1/np.log(t)
    h = (x-2)/n
    s = 0
    t = 2
    for k in range(n):
        s+=f(t)
        t+=h
    return h*s

N = np.array(list(range(2,1000)))
P = np.array([pi(n) for n in N ])
A = th_nb_prem(N)
L= np.array([Li(n) for n in N])
plt.plot(N,P, label='pi(x)')
plt.plot(N,A, label = 'x/log(x)')
plt.plot(N,L,label= 'Li(x)')
plt.legend()
plt.title("Comparaison des approximations de pi(x)")

plt.show()


# -*- coding: utf-8 -*-
from core import cmd_patterns, cmd

command_patterns = cmd_patterns('jabber_daemon.commands',
        cmd(r'^HELP$', 'help_command', doc='HELP - show this help'),
        cmd(r'^PING$', 'ping_command', doc='PING - pong'),

        cmd(r'^NICK$', 'nick_command', doc='NICK - show nick'),
        cmd(r'^NICK\s+(?P<new_nick>[\w]+)$', 'nick_command',
            doc='NICK <new username> - set new username'),
        #
        cmd(r'^#(?P<post_pk>\d+)$', 'show_message_command',
            doc='#1234 - Show message'),
        cmd(r'^#(?P<post_pk>\d+)/(?P<comment_number>\d+)$',
            'show_message_command', doc='#1234/1 - Show reply'),
        cmd(r'^#(?P<post_pk>\d+)\+$', 'show_message_command',
            extra_kwargs={'show_comments':True},
            doc='#1234+ - Show message with replies'),
        cmd(r'^#(?P<post_pk>\d+)[\s]+[\*](?P<tag>[\S]+)$', 'add_tag_command',
            doc='#1234 *tag - add or remove tag on message'),
        #
        cmd(r'^#(?P<post_pk>\d+)\s+(?P<message>.*)$', 'comment_add_command',
            doc='#1234 Blah-blah-blah - Answer to message #1234'),
        cmd(r'^#(?P<post_pk>\d+)/(?P<comment_number>\d+)\s+(?P<message>.*)$',
            'comment_add_command',
            doc='#1234/5 Blah - Answer to reply #1234/5'),
        #
        cmd(r'^\![\s]+#(?P<post_pk>[\d]+)$',
            'recommend_post_command',
            doc='! #1234 - Recommend post'),

        # delete
        cmd(r'^D[\s]+#(?P<post_pk>\d+)$', 'delete_command' ,
            doc='D #123 - Delete message'),
        cmd(r'^D[\s]+#(?P<post_pk>\d+)/(?P<comment_number>\d+)$',
            'delete_command', doc='D #123/1 - Delete reply'),
        cmd(r'^D[\s]+L$', 'delete_command',
            doc='D L - Delete last message', extra_kwargs={'last':True}),
        #
        cmd( r'^S$', 'subscribe_show_command',
            doc='S - Show your subscriptions'),
        #S
        cmd(r'^S[\s]+#(?P<post_pk>\d+)$' ,'subscribe_toggle_command',
            doc='S #123 - Subscribe to message replies'),
        cmd(r'^S[\s]+@(?P<username>[\w]+)$','subscribe_toggle_command',
            doc='S @username - Subscribe to user\'s blog'),
        cmd(r'^S[\s]+\*(?P<tagname>[\S]+)$','subscribe_toggle_command',
            doc='S *tag - Subscribe to tag'),
        cmd(r'^U[\s]+#(?P<post_pk>\d+)$', 'subscribe_toggle_command',
            extra_kwargs={'delete':True},
            doc='U #123 - Unsubscribe from comments'),
        cmd(r'^U[\s]+@(?P<username>[\w]+)$' ,'subscribe_toggle_command',
            extra_kwargs={'delete':True},
            doc='U @username - Unsubscribe from user\'s blog'),
        cmd(r'^U[\s]+\*(?P<tagname>[\S]+)$' ,'subscribe_toggle_command',
                extra_kwargs={'delete':True},
            doc='U *tag - Unsubscribe from tag'),
        #BL
        cmd(r'^BL$', 'blacklist_toggle_command', doc='BL - Show your blacklist'),
        cmd(r'^BL[\s]+@(?P<username>[\w]+)$','blacklist_toggle_command',
                doc='BL @username - Add/delete user to/from your blacklist'),
        cmd(r'^BL[\s]+\*(?P<tagname>[\S]+)$','blacklist_toggle_command',
                doc='BL *tag - Add/delete tag to/from your blacklist'),

        cmd(r'^\*$', 'show_tags_command', doc='* - Show your tags'),
        cmd(r'^#\+$', 'last_messages', doc='#+ - Show last messages from public timeline'),
        cmd(r'^(?P<numpage>#+)$', 'user_feed_messages',
                doc='# - Show last messages from your feed (## - second page, ...)'),
        cmd(r'^\*(?P<tag>[\S]+)$', 'last_messages_by_tag',
                doc='*tag - Show last messages by tag'),
        cmd(r'^@(?P<username>[\w]+)\+$', 'last_messages_by_user',
                doc='@username+ - Show user\'s info and last 10 messages'),
        cmd(r'^@(?P<username>[\w]+) \*(?P<tag>[\S]+)$', 'last_messages_by_user',
                doc='@username *tag - User\'s messages with this tag'),
        cmd(r'^@(?P<username>[\w]+)$', 'user_info',
                doc='@username - User info'),
        #INFO
        cmd(r'^I @(?P<username>[\w]+)$', 'user_info', doc='I @username - User info'),
        #cmd(r'^I #(?P<post_pk>[\d]+)$', 'info_command', doc='I #1234 - Info for post'),
#cmd(r'^I *(?P<tagname>[\S]+)$', 'info_command', doc='I *tagname - Info for tag'),

        cmd(r'^VCARD$', 'vcard_command', doc='VCARD - Update "About" info from Jabber vCard'),
        cmd(r'^LOGIN$', 'login_command', doc='LOGIN - login in web ui'),

        cmd(r'^PM @(?P<username>[\w]+)(?P<message>.*)$',
                'personal_message_command', doc='Send personal message'),

        cmd(r'^OFF$', 'off_on_command',
                doc='OFF - Disable subscriptions delivery'),
        cmd(r'^ON$', 'off_on_command',
                doc='ON - Enable subscriptions delivery', extra_kwargs={'off':False}),

)


# 3. Longest Substring Without Repeating Characters
# Medium
# Given a string, find the length of the longest substring without repeating characters.

# Example 1:

# Input: "abcabcbb"
# Output: 3
# Explanation: The answer is "abc", with the length of 3.
# Example 2:

# Input: "bbbbb"
# Output: 1
# Explanation: The answer is "b", with the length of 1.
# Example 3:

# Input: "pwwkew"
# Output: 3
# Explanation: The answer is "wke", with the length of 3.
#              Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        start = 0
        index_map = collections.defaultdict(int)
        maxlen = float('-inf')
        for end in range(len(s)):
            end_char = s[end]
            if end_char in index_map: # Repeated Character
                start = max(start, index_map[end_char]+1) # Key!

            index_map[end_char] = end
            maxlen = max(maxlen, end-start+1)

        return maxlen if maxlen != float('-inf') else 0

# Time Complexity #
# The time complexity of the above algorithm will be O(N) where ‘N’ is the number of characters in the input string.

# Space Complexity #
# The space complexity of the algorithm will be O(K) where K is the number of distinct characters in the input string.
# This also means K<=N, because in the worst case, the whole string might not have any repeating character
# so the entire string will be added to the HashMap.
# Having said that, since we can expect a fixed set of characters in the input string (e.g., 26 for English letters),
# we can say that the algorithm runs in fixed space O(1)O(1); in this case, we can use a fixed-size array instead of the HashMap.


import argparse
import os

def parse_common_args(parser):
    parser.add_argument('--model_type', type=str, default='resnet50',
                        help='used in model_entry.py')  # default='base_model'
    parser.add_argument('--data_type', type=str, default='base_dataset', help='used in data_entry.py')
    parser.add_argument('--save_prefix', type=str, default='no_squeeze',
                        help='some comment for model or test result dir')
    parser.add_argument('--load_model_path', type=str,
                        default='checkpoints/amazon2dslr_a_1.0_b_1.0_c_1.0_d_1.0/best_checkpoint.pth',
                        help='model path for pretrain or test')  # checkpoints/base_model_pref/0.pth
    parser.add_argument('--load_not_strict', action='store_true', help='allow to load only common state dicts')

    parser.add_argument('--gpus', default=[0, ], nargs='+', type=int)
    parser.add_argument('--seed', type=int, default=3407)

    # datasets
    parser.add_argument('--data_path_source', type=str, default='./data/office31/',
                        help='root of the source dataset')
    parser.add_argument('--data_path_target_tr', type=str, default='./data/office31/',
                        help='root of the target dataset (for training)')
    parser.add_argument('--data_path_target_te', type=str, default='./data/office31/',
                        help='root of the target dataset (for test)')
    parser.add_argument('--src', type=str, default='amazon', help='source domain')
    parser.add_argument('--tar_tr', type=str, default='dslr', help='target domain (for training)')
    parser.add_argument('--tar_te', type=str, default='dslr', help='target domain (for test)')
    parser.add_argument('--num_classes', type=int, default=31, help='class number')

    parser.add_argument('--eps', type=float, default=1e-6, help='a small value to prevent underflow')
    parser.add_argument('--no_da', action='store_true', help='whether using data augmentation')
    parser.add_argument('--gray_tar_agree', action='store_true',
                        help='whether to enforce the consistency between RGB and gray images on the target domain')
    parser.add_argument('--aug_tar_agree', action='store_true',
                        help='whether to enforce the consistency between RGB and augmented images on the target domain')
    parser.add_argument('--workers', default=0, type=int, metavar='N',
                        help='number of data loading workers (default: 4)')
    parser.add_argument('--remain', default=0.7, type=float,
                        help='the remaining weight of centroid of last epoch at this epoch (a number in [0, 1))')
    parser.add_argument('--print_freq', default=20, type=int,
                        metavar='N', help='print frequency (default: 10)')
    # architecture
    parser.add_argument('--arch', type=str, default='resnet50', help='model name')
    parser.add_argument('--resume', type=str, default='', help='checkpoint path to resume (default: '')')
    parser.add_argument('--pretrained', default=True, action='store_true', help='whether using pretrained model')
    parser.add_argument('--num_neurons', type=int, default=128, help='number of neurons in the fc1 of a new model')
    return parser

def parse_train_args(parser):
    parser = parse_common_args(parser)
    parser.add_argument('--lr', type=float, default=1e-3, help='learning rate')
    parser.add_argument('--momentum', default=0.9, type=float, metavar='M',
                        help='momentum for sgd, alpha parameter for adam')
    parser.add_argument('--beta', default=0.999, type=float, metavar='M',
                        help='beta parameters for adam')
    parser.add_argument('--weight-decay', '--wd', default=0, type=float,
                        metavar='W', help='weight decay')
    parser.add_argument('--model_dir', type=str, default='', help='leave blank, auto generated')
    parser.add_argument('--train_list', type=str, default='/data/dataset1/list/base/train.txt')
    parser.add_argument('--batch_size', type=int, default=64)
    parser.add_argument('--epochs', type=int, default=3)

    # loss coefficient
    parser.add_argument('--alpha1', type=float, default=1.0)
    parser.add_argument('--alpha2', type=float, default=1.0)
    parser.add_argument('--alpha3', type=float, default=1.0)
    parser.add_argument('--alpha4', type=float, default=1.0)
    return parser

def parse_test_args(parser):
    parser = parse_common_args(parser)
    parser.add_argument('--save_viz', action='store_true', help='save viz result in eval or not')
    parser.add_argument('--result_dir', type=str, default='', help='leave blank, auto generated')

    parser.add_argument('--batch_size', type=int, default=64)
    return parser

def get_train_args():
    parser = argparse.ArgumentParser()
    parser = parse_train_args(parser)
    args = parser.parse_args()
    return args

def get_test_args():
    parser = argparse.ArgumentParser()
    parser = parse_test_args(parser)
    args = parser.parse_args()
    return args

def get_train_model_dir(args):
    model_dir = os.path.join('checkpoints', args.src + '2' + args.tar_tr + '_a_' + str(args.alpha1) + '_b_' + str(
        args.alpha2) + '_c_' + str(args.alpha3) + '_d_' + str(args.alpha4))
    if not os.path.exists(model_dir):
        os.system('mkdir -p ' + model_dir)
    args.model_dir = model_dir

def get_test_result_dir(args):
    # ext = os.path.basename(args.load_model_path).split('.')[-1]  # 返回path最后的文件名
    model_dir = args.load_model_path.replace('.pth', '')
    # os.path.dirname 去掉文件名，返回目录 val_info = val

    # val_info = os.path.basename(os.path.dirname(args.val_list)) + '_' \
    #            + os.path.basename(args.val_list.replace('.txt', ''))
    val_info = args.src + '2' + args.tar_te
    # result_dir = os.path.join(model_dir, val_info + '_' + args.save_prefix)
    result_dir = model_dir
    if not os.path.exists(result_dir):
        os.system('mkdir -p ' + result_dir)
    args.result_dir = result_dir

def save_args(args, save_dir):
    args_path = os.path.join(save_dir, 'args.txt')
    with open(args_path, 'w') as fd:
        fd.write(str(args).replace(', ', ',\n'))

def prepare_train_args():
    args = get_train_args()
    get_train_model_dir(args)
    save_args(args, args.model_dir)
    return args

def prepare_test_args():
    args = get_test_args()
    get_test_result_dir(args)
    save_args(args, args.result_dir)
    return args

if __name__ == '__main__':
    args = get_test_args()
    get_test_result_dir(args)
    print(args.result_dir)
    exit()

    args = prepare_test_args()
    # train_args = get_train_args()
    test_args = get_test_args()

    parser = argparse.ArgumentParser()
    parser = parse_common_args(parser)

    args = parser.parse_args()
    print(args.gpus)


import socket

def portscan(ip, maxport, quiet,terminal=None):

    if terminal == None:
        print('-'*40)
        print("[*] WARNING! This method of portscanning is NOT ANNONYMOUS and your ip WILL BE LOGGED on the victim machine.")
        print("-"*40)
        inp = input("Are you SURE you want to continue? y/n\n> ")
        if inp in ("n",'N','no','NO','nO','No'):
            print("[-] Portscan Stopped")
            exit(0)
    else:
        terminal.configure(text=terminal.cget("text")+'\n[*] WARNING: This method of portscanning is NOT ANNONYMOUS and yout ip WILL BE LOGGED on the victim machine.')

    openports = []

    s = socket.socket(2,1)
    s.settimeout(0.5)

    if terminal == None:
        print("\n")
        print("// Results For "+ip+" // ")
    else:
        terminal.configure(text=terminal.cget("text")+'\n\n//Results For '+ip+' // ')

    if not maxport:
        maxport = 100

    for i in range(int(maxport)+1):
        if quiet:
            try:
                if not s.connect_ex((ip,i)):
                    openports.append(i)
                    if terminal == None:
                        print("[+] Open port found: "+str(i))
                    else:
                        terminal.configure(text=terminal.cget("text")+'\n[+] Open port found: '+str(i))
            except:
                pass
        else:
            try:
                if not s.connect_ex((ip,i)):
                    openports.append(i)
                    if terminal == None:
                        print("[+] Open port found: "+str(i))
                    else:
                        terminal.configure(text=terminal.cget("text")+'\n[+] Open port found '+str(i))
                else:
                    if terminal == None:
                        print("[-] Port "+str(i)+" is closed")
                    else:
                        terminal.configure(text=terminal.cget("text")+'\n[-] Port '+str(i)+' is closed ')

            except:
                pass

    if not openports:
        if terminal == None:
            print("[-] No open ports found")
        else:
            terminal.configure(text=terminal.cget("text")+'\n[-] No open ports found')

    s.close()


from flask import Flask, render_template, url_for, request

# load library
import pandas as pd
import pickle
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.model_selection import train_test_split

app = Flask(__name__)

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

@app.route('/predict', methods=['POST','GET'])
def predict():

    data = pd.read_csv("data/Youtube01-Psy.csv")

    # drop columns
    data.drop(['COMMENT_ID', 'DATE','AUTHOR'], axis=1, inplace=True)

    # divide data
    x = data['CONTENT']
    y = data['CLASS']

    # load Countvectorize
    corpus = x

    cv = CountVectorizer()

    x = cv.fit_transform(corpus)

    # TRAIN TEST SPLIT
    x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=42, test_size=0.33)

    # MODEL
    model = MultinomialNB()

    # fit model
    model.fit(x_train, y_train)
    model.score(x_test, y_test)

    # save_model = pickle.dumps(model)

    # load_model = pickle.load(save_model)

    if request.method == 'POST':
        comment = request.form['comment']
        data = [comment]
        vect = cv.transform(data).toarray()
        prediction = model.predict(vect)

    return render_template('prediction.html', prediction=prediction)

if __name__=="__main__":
    app.run(debug=True)


import tkinter
from tkinter import ttk

class Banner:
    def __init__(self, root, banner_text):
        banner_frame = tkinter.Frame(root, bg="#468B97", padx=10, pady=10)
        banner_frame.pack(side="top", fill="both", expand=False)

        separator_above = ttk.Separator(banner_frame, orient="horizontal")
        separator_above.pack(side="top", fill="x", padx=5, pady=5)

        self.banner_label = ttk.Label(banner_frame, text=banner_text,
                                      font=("Helvetica", 16, "bold"), foreground="#f0f0f0",
                                      background="#468B97")
        self.banner_label.pack(side="top", padx=10, pady=5)

        separator_below = ttk.Separator(banner_frame, orient="horizontal")
        separator_below.pack(side="bottom", fill="x", padx=5, pady=5)

    def update_banner(self, banner_text):
        self.banner_label.configure(text=banner_text)


from __future__ import unicode_literals

from django.utils.six import text_type
from django_webtest import WebTest

from usersettings.shortcuts import get_current_usersettings

from .auth import TestUserMixin
from .dates import date_in_near_future
from .factories import (
    AreaExtraFactory, CandidacyExtraFactory, MembershipFactory,
    PersonExtraFactory, PostExtraFactory,
)
from .settings import SettingsMixin
from .uk_examples import UK2015ExamplesMixin

from compat import BufferDictReader

from ..models import MembershipExtra, PersonExtra

class TestConstituencyDetailView(TestUserMixin, SettingsMixin, UK2015ExamplesMixin, WebTest):

    def setUp(self):
        super(TestConstituencyDetailView, self).setUp()
        person_extra = PersonExtraFactory.create(
            base__id='2009',
            base__name='Tessa Jowell'
        )
        dulwich_not_stand = PersonExtraFactory.create(
            base__id='4322',
            base__name='Helen Hayes'
        )
        CandidacyExtraFactory.create(
            election=self.election,
            base__person=person_extra.base,
            base__post=self.dulwich_post_extra.base,
            base__on_behalf_of=self.labour_party_extra.base
            )
        MembershipFactory.create(
            person=person_extra.base,
            organization=self.labour_party_extra.base
        )

        winner_post_extra = self.edinburgh_east_post_extra

        edinburgh_candidate = PersonExtraFactory.create(
            base__id='818',
            base__name='Sheila Gilmore'
        )
        edinburgh_winner = PersonExtraFactory.create(
            base__id='5795',
            base__name='Tommy Sheppard'
        )
        edinburgh_may_stand = PersonExtraFactory.create(
            base__id='5163',
            base__name='Peter McColl'
        )

        CandidacyExtraFactory.create(
            election=self.earlier_election,
            base__person=dulwich_not_stand.base,
            base__post=self.dulwich_post_extra.base,
            base__on_behalf_of=self.labour_party_extra.base,
            )
        dulwich_not_stand.not_standing.add(self.election)

        CandidacyExtraFactory.create(
            election=self.election,
            base__person=edinburgh_winner.base,
            base__post=winner_post_extra.base,
            base__on_behalf_of=self.labour_party_extra.base,
            elected=True,
            )

        CandidacyExtraFactory.create(
            election=self.election,
            base__person=edinburgh_candidate.base,
            base__post=winner_post_extra.base,
            base__on_behalf_of=self.labour_party_extra.base
            )
        MembershipFactory.create(
            person=edinburgh_candidate.base,
            organization=self.labour_party_extra.base
        )
        MembershipFactory.create(
            person=edinburgh_winner.base,
            organization=self.labour_party_extra.base
        )
        CandidacyExtraFactory.create(
            election=self.earlier_election,
            base__person=edinburgh_may_stand.base,
            base__post=winner_post_extra.base,
            base__on_behalf_of=self.labour_party_extra.base
            )

    def test_any_constituency_page_without_login(self):
        # Just a smoke test for the moment:
        response = self.app.get('/election/2015/post/65808/dulwich-and-west-norwood')
        response.mustcontain('Tessa Jowell Labour Party')
        # There should be only one form ( person search ) on the page if you're not logged in:

        # even though there are only two forms on the page the list has
        # two entries per form - one for the numeric identifier and one
        # for the id
        self.assertEqual(4, len(response.forms))
        self.assertEqual(response.forms[1].id, 'person_search_header')

    def test_any_constituency_page(self):
        # Just a smoke test for the moment:
        response = self.app.get(
            '/election/2015/post/65808/dulwich-and-west-norwood',
            user=self.user
        )
        response.mustcontain('Tessa Jowell Labour Party')
        form = response.forms['new-candidate-form']
        self.assertTrue(form)
        response.mustcontain(no='Unset the current winners')

    def test_constituency_with_no_winner_record_results_user(self):
        response = self.app.get(
            '/election/2015/post/65808/dulwich-and-west-norwood',
            user=self.user_who_can_record_results
        )
        response.mustcontain(no='Unset the current winners')

    def test_any_constituency_csv(self):
        response = self.app.get(
            '/election/2015/post/65808/dulwich-and-west-norwood.csv',
        )
        row_dicts = [row for row in BufferDictReader(response.content)]
        self.assertEqual(1, len(row_dicts))
        self.assertEqual(
            row_dicts[0],
            {
                'facebook_page_url': '',
                'honorific_suffix': '',
                'party_ppc_page_url': '',
                'facebook_personal_url': '',
                'elected': '',
                'election': '2015',
                'election_current': 'True',
                'election_date': text_type(date_in_near_future),
                'image_uploading_user_notes': '',
                'id': '2009',
                'post_label': 'Dulwich and West Norwood',
                'honorific_prefix': '',
                'wikipedia_url': '',
                'email': '',
                'mapit_url': '',
                'proxy_image_url_template': '',
                'twitter_username': '',
                'twitter_user_id': '',
                'post_id': '65808',
                'party_id': 'party:53',
                'party_lists_in_use': 'False',
                'party_list_position': '',
                'image_copyright': '',
                'name': 'Tessa Jowell',
                'gender': '',
                'linkedin_url': '',
                'image_uploading_user': '',
                'homepage_url': '',
                'image_url': '',
                'birth_date': '',
                'party_name': 'Labour Party'
            }
        )

    def test_constituency_with_winner(self):
        response = self.app.get('/election/2015/post/14419/edinburgh-east')
        response.mustcontain('
')
        response.mustcontain('
')

        response.mustcontain(no='Unset the current winners')

        response.mustcontain('Unelected candidates for')
        response.mustcontain(no='Known candidates for')

        settings = get_current_usersettings()
        settings.HOIST_ELECTED_CANDIDATES = False
        settings.save()
        response = self.app.get('/election/2015/post/14419/edinburgh-east')
        response.mustcontain(no='Unelected candidates for')
        response.mustcontain('Known candidates for')

    def test_constituency_with_winner_record_results_user(self):
        response = self.app.get(
            '/election/2015/post/14419/edinburgh-east',
            user=self.user_who_can_record_results
        )
        response.mustcontain('Unset the current winners')

    def test_constituency_with_may_be_standing(self):
        response = self.app.get('/election/2015/post/14419/edinburgh-east')
        response.mustcontain('if these candidates from earlier elections are standing')
        response.mustcontain(no='These candidates from earlier elections are known not to be standing again')

    def test_constituency_with_not_standing(self):
        response = self.app.get('/election/2015/post/65808/dulwich-and-west-norwood')
        response.mustcontain('These candidates from earlier elections are known not to be standing again')
        response.mustcontain(no='if these candidates from earlier elections are standing')

    def test_mark_not_standing_no_candidate(self):
        response = self.app.get(
            '/election/2015/post/14419/edinburgh-east',
            user=self.user,
        )

        csrftoken = self.app.cookies['csrftoken']
        response = self.app.post(
            '/election/2015/candidacy/delete',
            {
                'person_id': '9999',
                'post_id': '14419',
                'source': 'test data',
                'csrfmiddlewaretoken': csrftoken,
            },
            expect_errors=True,
        )

        self.assertEqual(response.status_code, 404)

    def test_mark_not_standing_no_post(self):
        response = self.app.get(
            '/election/2015/post/14419/edinburgh-east',
            user=self.user,
        )

        csrftoken = self.app.cookies['csrftoken']
        response = self.app.post(
            '/election/2015/candidacy/delete',
            {
                'person_id': '181',
                'post_id': '9999',
                'source': 'test data',
                'csrfmiddlewaretoken': csrftoken,
            },
            expect_errors=True,
        )

        self.assertEqual(response.status_code, 404)

    def test_mark_standing_no_candidate(self):
        response = self.app.get(
            '/election/2015/post/14419/edinburgh-east',
            user=self.user,
        )

        csrftoken = self.app.cookies['csrftoken']
        response = self.app.post(
            '/election/2015/candidacy',
            {
                'person_id': '9999',
                'post_id': '14419',
                'source': 'test data',
                'csrfmiddlewaretoken': csrftoken,
            },
            expect_errors=True,
        )

        self.assertEqual(response.status_code, 404)

    def test_mark_standing_no_post(self):
        response = self.app.get(
            '/election/2015/post/14419/edinburgh-east',
            user=self.user,
        )

        csrftoken = self.app.cookies['csrftoken']
        response = self.app.post(
            '/election/2015/candidacy',
            {
                'person_id': '5163',
                'post_id': '9999',
                'source': 'test data',
                'csrfmiddlewaretoken': csrftoken,
            },
            expect_errors=True,
        )

        self.assertEqual(response.status_code, 404)

    def test_mark_candidate_not_standing(self):
        response = self.app.get(
            '/election/2015/post/14419/edinburgh-east',
            user=self.user,
        )

        csrftoken = self.app.cookies['csrftoken']
        response = self.app.post(
            '/election/2015/candidacy/delete',
            {
                'person_id': '818',
                'post_id': '14419',
                'source': 'test data',
                'csrfmiddlewaretoken': csrftoken,
            },
            expect_errors=True,
        )

        membership = MembershipExtra.objects.filter(
            base__person_id=818,
            base__post__extra__slug='14419',
            election__slug='2015'
        )
        self.assertFalse(membership.exists())

        person_extra = PersonExtra.objects.get(
            base__id=818
        )
        not_standing = person_extra.not_standing.all()
        self.assertTrue(self.election in not_standing)

        self.assertEqual(response.status_code, 302)
        self.assertEqual(
            response.location,
            "http://localhost:80/election/2015/post/14419/edinburgh-east"
        )

    def test_mark_may_stand_actually_standing(self):
        response = self.app.get(
            '/election/2015/post/14419/edinburgh-east',
            user=self.user,
        )

        csrftoken = self.app.cookies['csrftoken']
        response = self.app.post(
            '/election/2015/candidacy',
            {
                'person_id': '5163',
                'post_id': '14419',
                'source': 'test data',
                'csrfmiddlewaretoken': csrftoken,
            },
            expect_errors=True,
        )

        membership = MembershipExtra.objects.filter(
            base__person_id=5163,
            base__post__extra__slug='14419',
            election__slug='2015'
        )

        self.assertTrue(membership.exists())

        self.assertEqual(response.status_code, 302)
        self.assertEqual(
            response.location,
            "http://localhost:80/election/2015/post/14419/edinburgh-east"
        )

    def test_mark_may_stand_not_standing_again(self):
        response = self.app.get(
            '/election/2015/post/14419/edinburgh-east',
            user=self.user,
        )

        csrftoken = self.app.cookies['csrftoken']
        response = self.app.post(
            '/election/2015/candidacy/delete',
            {
                'person_id': '5163',
                'post_id': '14419',
                'source': 'test data',
                'csrfmiddlewaretoken': csrftoken,
            },
            expect_errors=True,
        )

        membership = MembershipExtra.objects.filter(
            base__person_id=5163,
            base__post__extra__slug='14419',
            election__slug='2015'
        )
        self.assertFalse(membership.exists())

        person_extra = PersonExtra.objects.get(
            base__id=5163
        )
        not_standing = person_extra.not_standing.all()
        self.assertTrue(self.election in not_standing)

        self.assertEqual(response.status_code, 302)
        self.assertEqual(
            response.location,
            "http://localhost:80/election/2015/post/14419/edinburgh-east"
        )

    def test_mark_not_standing_standing_again(self):
        response = self.app.get(
            '/election/2015/post/65808/dulwich-and-west-norwood',
            user=self.user,
        )

        csrftoken = self.app.cookies['csrftoken']
        response = self.app.post(
            '/election/2015/candidacy',
            {
                'person_id': '4322',
                'post_id': '65808',
                'source': 'test data',
                'csrfmiddlewaretoken': csrftoken,
            },
            expect_errors=True,
        )

        membership = MembershipExtra.objects.filter(
            base__person_id=4322,
            base__post__extra__slug='65808',
            election__slug='2015'
        )

        self.assertTrue(membership.exists())

        person_extra = PersonExtra.objects.get(
            base__id=4322
        )
        not_standing = person_extra.not_standing.all()
        self.assertFalse(self.election in not_standing)

        self.assertEqual(response.status_code, 302)
        self.assertEqual(
            response.location,
            "http://localhost:80/election/2015/post/65808/dulwich-and-west-norwood"
        )


# Import Library
import numpy as np
from numpy import loadtxt
import matplotlib.pyplot as plt

## DATA SET
dataset = np.loadtxt('./mnist_train.csv', delimiter=',', dtype=np.float32)

input_data  = dataset[:,1:]
target_data  = dataset[:,0]
print("input_data.shape = ", input_data.shape)
print("target_data.shape = ", target_data.shape)

label = np.zeros((60000,2))
for i in range(60000):
    if target_data[i]== 1.:
        label[i,1]=1
    if target_data[i]== 0.:
        label[i,0]=1

## Activate Fuction Sigmoid
def sigmoid(x):
    return 1 / (1+np.exp(-x))

## Basic Deep Learning Network
class BasicDeepLearning:

    def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate):
        self.input_nodes = input_nodes
        self.hidden_nodes = hidden_nodes
        self.output_nodes = output_nodes

        # hidden layer weight init
        self.W2 = np.random.random((self.input_nodes, self.hidden_nodes))
        # output layer weight init
        self.W3 = np.random.random((self.hidden_nodes, self.output_nodes))

        # output layer
        self.Z3 = np.zeros([1, output_nodes])
        self.A3 = np.zeros([1, output_nodes])

        # hidden layer
        self.Z2 = np.zeros([1, hidden_nodes])
        self.A2 = np.zeros([1, hidden_nodes])

        # input layer
        self.Z1 = np.zeros([1, input_nodes])
        self.A1 = np.zeros([1, input_nodes])

        # learning rate
        self.learning_rate = learning_rate
        print("self.Z1.shape = ",self.Z1.shape)
        print("self.A1.shape = ",self.A1.shape)
        print("self.Z2.shape = ",self.Z2.shape)
        print("self.A2.shape = ",self.A2.shape)
        print("self.Z3.shape = ",self.Z3.shape)
        print("self.A3.shape = ",self.A3.shape)
        print("self.W2.shape = ",self.W2.shape)
        print("self.W3.shape = ",self.W3.shape)
        '''
self.A1.shape =  (1, 784)
self.Z2.shape =  (1, 100)
self.A2.shape =  (1, 100)
self.Z3.shape =  (1, 10)
self.A3.shape =  (1, 10)
self.W2.shape =  (784, 100)
self.W3.shape =  (100, 10)
        '''
    ## Feed Forward
    def feed_forward(self):
        # input layer
        self.Z1 = self.input_data
        self.A1 = self.input_data

        # hidden layer
        self.Z2 = np.dot(self.A1, self.W2)
        self.A2 = sigmoid(self.Z2)

        # output layser
        self.Z3 = np.dot(self.A2, self.W3)
        self.A3 = sigmoid(self.Z3)

        return self.A3

    ## loss
    def loss_val(self):
        loss = ((self.A3 - self.target_data) ** 2)
        loss = np.mean(loss)

        return loss

    ## Train(Backwoard, Weight Update)
    def train(self, input_data, target_data):
        self.target_data = target_data
        self.input_data = input_data

        # feedforward
        self.feed_forward()

        # stage1 (output → hidden weight update)
        loss_3 = (self.A3 - self.target_data) * self.A3 * (1 - self.A3)
        self.W3 = self.W3 - self.learning_rate * np.dot(self.A2.T, loss_3)

        # stage2 (hidden → input weight update)
        loss_2 = np.dot(loss_3, self.W3.T) * self.A2 * (1 - self.A2)
        self.W2 = self.W2 - self.learning_rate * np.dot(self.A1.T, loss_2)

## Parameter Settinga
input_nodes = 784
hidden_nodes = 100
output_nodes = 10
learning_rate = 0.01
epochs=1

## Training for optimization
loss = []
bdl = BasicDeepLearning(input_nodes, hidden_nodes, output_nodes, learning_rate)

for i in range(epochs):
    bdl.train( input_data, target_data)
    loss.append(bdl.loss_val())
    print(bdl.loss_val())


import csv
import sys
from os import replace

# _inputfile = sys.argv[1]
_inputfile = 'sbi.csv'
# _outputfile = sys.argv[2]
_outputfile = 'hb_sbi.csv'
# _assigmments = sys.argv[3]
_assigmments = 'assignments.csv'
# _bank = sys.argv[4]
_bank = 'sbi'
asnmntdata = []

# print('Number of arguments:', len(sys.argv), 'arguments.')
# print('Argument List:', str(sys.argv))
# print('Input File', _inputfile)
# print('Output File', _outputfile)
# print('Assignment File', _assigmments)
# print('Bank is ', _bank)

def savefinalfmt(rowdata):
    finalstr = ""
    delimiter = ","
    finallist = []
    # write finallist to csv
    # massage rowdata to homebank format

def findCategory(trx_memo):
    memostr = trx_memo
    asnmntdata = loadAssignments()
    rtndata_cat = "No Category"
    rtndata_payee = "No Payee"
    rownum=0
    flag=0

    print('Trx_memo is:', memostr, 'count of assignments are: ', len(asnmntdata))
    for _asnmntdata in asnmntdata:

        if(memostr.find(_asnmntdata[4])):
            print("Found",_asnmntdata[4])
            rownum=_asnmntdata
            #print("memostr is ",memostr[rownum])
            flag=1
            break
    if flag==0:
        print("not found")

    return 0

def loadTrx():
    trxData = []
    with open(_inputfile, 'r') as csv_trx:
        csv_trx_reader = csv.reader(csv_trx)
        trxData = list(csv_trx_reader)
    csv_trx.close()
    trxData.pop(0)
    return trxData

def writeTrx(trxlist):
    with open(_outputfile, 'w', newline='') as csvfile:
        csv_trx_writer = csv.writer(csvfile, delimiter=' ',
                                    quotechar='|', quoting=csv.QUOTE_MINIMAL)
        csv_trx_writer.writerows(trxlist)
    csvfile.close()

def loadAssignments():
    asnmntdata = []
    # print('Reading file and loading')
    with open(_assigmments, 'r') as csv_assignments:
        csv_assignment_reader = csv.reader(csv_assignments)
        asnmntdata = list(csv_assignment_reader)
    csv_assignments.close()
    asnmntdata.pop(0)
    print('No of assignments are: ', len(asnmntdata))
    return asnmntdata

# asnmntdata has all the assignments
# in the form of list
asnmntdata = loadAssignments()
# for i in asnmntdata:
#    print(i)
cate = []
trxdata = loadTrx()
_fstring = []
_str = ""
_date = ""
_payment = "0"
_info = ""
_payee = ""
_memo = ""
_amount = 0.00
_category = ""
_tags = ""
for j in trxdata:
    #print("Before calling findCategory(j) ",j[2])
    cate = findCategory(j[2])

    # homebank format
    # date, payment(0), info, payee, memo, amount, category, tags
    # SBI
    _date = j[0]
    _payment = "0"
    _info = j[3]

    #index_pos = asnmntdata.index(j[2]) if j[2] in asnmntdata else -1

    print ("cate is ",cate)
    if cate > 0:
        _payee = cate[6]
        _category = cate[7]
    else:
        _payee = "No Payee"
        _category = "No Category"

    _memo = j[2]
    _dramout = j[4]
    _cramount = j[5]

    _tags = "SBI"
    _str = _date + "," + _payment + "," + _info + "," + _payee + "," + _memo + "," + _dramout + "," + _cramount + "," + _category + "," + _tags
    print("Final String is :", _str)


# -*- coding: utf-8 -*-
"""
Author:
    mumuychen@tencent.com

"""
import sys
from pathlib import Path

import torch

from ..utils.base_model import BaseModel

disk_path = Path(__file__).parent / '../../models/'
sys.path.append(str(disk_path))

from disk.model.disk import DISK

class DiskDesc(BaseModel):
    default_conf = {
        'weights': 'depth-save.pth',
        'window': 8,
        'descriptors_dim': 128,
        'kind': 'nms',
        'topk': 1024
    }
    required_inputs = ['image']

    def _init(self, conf, model_path, device='cuda'):
        self.conf = {**self.default_conf, **conf}

        model_file = str(model_path /Path('disk')/ Path(self.conf['weights']))
        self.net = DISK(window = self.conf['window'], desc_dim = self.conf['descriptors_dim'],
                        with_swin = 'swin' in self.conf['weights'])
        if 'swin' in self.conf['weights']:
            self.net.load_state_dict(torch.load(model_file, map_location=device)['disk'])
        else:
            self.net.load_state_dict(torch.load(model_file, map_location=device)['extractor'])

    def _forward(self, data):
        image = data['image']
        if self.conf['kind'] == 'nms':
            features = self.net.features(image, kind = 'nms', window_size = 5,
                                    cutoff=None, n = self.conf['topk'])
        else:
            features = self.net.features(image, kind = 'rng')

        return {
            'keypoints': [features[0].kp],
            'scores': [features[0].kp_logp],
            'descriptors': [features[0].desc.T],
        }