import _io
from io import BytesIO

import numpy as np
import streamlit as st
import plyfile as ply
from numpy.lib import recfunctions as rfn

def parse_npz(byte_obj: _io.BytesIO) -> np.ndarray:
    """
    Parse point cloud saved as a compressed numpy array.

    :param byte_obj: input object to be parsed.
    :type byte_obj: _io.BytesIO
    :returns: point cloud
    :rtype: np.ndarray
    """
    blob_container = np.load(byte_obj, encoding="bytes")
    blob_name = blob_container.__dict__["files"][-1]
    return blob_container[blob_name]

def parse_npy(byte_obj: _io.BytesIO) -> np.ndarray:
    """
    Parse point cloud saved as a numpy array.

    :param byte_obj: input object to be parsed.
    :type byte_obj: _io.BytesIO
    :returns: point cloud
    :rtype: np.ndarray
    """
    blob = np.load(byte_obj, encoding="bytes")
    return blob

def _construct_blob(points: np.ndarray) -> np.ndarray:
    x, y, z = points[:, 0][:, np.newaxis], points[:, 1][:, np.newaxis], points[:, 2][:, np.newaxis]
    features = points[:, 3][:, np.newaxis]
    x_range = int(np.max(x)) + 1
    y_range = int(np.max(y)) + 1
    z_range = int(np.max(z)) + 1

    blob = np.zeros((x_range, y_range, z_range))
    blob[(x.astype(int), y.astype(int), z.astype(int))] = features
    return blob

def parse_ply(byte_obj: _io.BytesIO) -> np.ndarray:
    """
    Parse ply files
    ply file structure:
    x y z feature
    where x, y, z are coordinates and feature is a feature value at point with the given x, y, z coordinates

    :param byte_obj: input object to be parsed.
    :type byte_obj: _io.BytesIO
    :returns: point cloud
    :rtype: np.ndarray
    """
    plydata = ply.PlyData.read(byte_obj)

    points = np.array(plydata.elements[0].data)
    points = rfn.structured_to_unstructured(points)

    return _construct_blob(points)

def parse_xyz_pts_txt(byte_obj: _io.BytesIO, ext: str) -> np.ndarray:
    """
    Parse xyz, pts and txt files
    - xyz and txt file structure: should contain only numerical data (without any header), each line should have
        the following format:
        x y z feature
        where x, y, z are coordinates and feature is a feature value at point with the given x, y, z coordinates;
        lines should be separated with \n character
    - pts file structure: in the first line there should be information about the number of points in the given
        point cloud, later the structure follows the xyz format structure

    :param byte_obj: input object to be parsed.
    :type byte_obj: _io.BytesIO
    :param ext: file extension
    :type ext: str
    :returns: point cloud
    :rtype: np.ndarray
    """
    if ext == 'pts':
        _ = byte_obj.readline()
    points = np.loadtxt(byte_obj, encoding="bytes")
    return _construct_blob(points)

def parse_csv(byte_obj: _io.BytesIO) -> np.ndarray:
    """
    Parse csv files
    - csv file structure: should contain only numerical data (without any header), each line should have
        the following format:
        x, y, z, feature
        where x, y, z are coordinates and feature is a feature value at point with the given x, y, z coordinates;
        lines should be separated with \n character

    :param byte_obj: input object to be parsed.
    :type byte_obj: _io.BytesIO
    :returns: point cloud
    :rtype: np.ndarray
    """
    try:
        points = np.loadtxt(byte_obj, delimiter=',', encoding="bytes")
    except ValueError:
        _ = byte_obj.readline()
        points = np.loadtxt(byte_obj, delimiter=',', encoding="bytes")
    return _construct_blob(points)

def parse(file: st.runtime.uploaded_file_manager.UploadedFile) -> np.ndarray:
    """
    Parse point cloud.

    :param byte_obj: input object to be parsed.
    :type byte_obj: _io.BytesIO
    :returns: point cloud
    :rtype: np.ndarray
    """
    byte_object = BytesIO(file.getvalue())

    ext = file.__dict__["name"].split(".")[-1]
    if ext == "npz":
        return parse_npz(byte_object)
    elif ext == "npy":
        return parse_npy(byte_object)
    elif ext == "ply":
        return parse_ply(byte_object)
    elif ext == "xyz" or ext == "pts" or ext == "txt":
        return parse_xyz_pts_txt(byte_object, ext)
    elif ext == "csv":
        return parse_csv(byte_object)


#!/usr/bin/env python

import fileinput

from heapq import heappop, heappush
import heapq

expand = 1  # part 1
expand = 5  # part 2

O = list()
G = list()

for line in fileinput.input():
    O.append([int(i) for i in line.strip()])

# expand
for i in range(expand):
    for x in range(len(O)):
        r = list()
        for j in range(expand):
            for y in range(len(O[0])):
                v = O[x][y] + j + i
                if v > 9:
                    v -= 9
                r.append(v)
        G.append(r)

def solve(G):
    h = len(G)
    w = len(G[0])

    # initial costs
    W = [[1e6 for x in range(w)] for y in range(h)]
    W[0][0] = G[0][0]

    changed = True
    while changed:
        changed = False
        for x in range(w):
            for y in range(h):
                for (dx, dy) in [(-1, 0), (0, -1), (1, 0), (0, 1)]:
                    xx = x + dx
                    yy = y + dy
                    if 0 <= xx < w and 0 <= yy < h:
                        if W[xx][yy] + G[x][y] < W[x][y]:
                            W[x][y] = W[xx][yy] + G[x][y]
                            changed = True
    return W[-1][-1] - W[0][0]

def dijkstra(start, end, G):
    queue = [(0, start)]
    seen = set()

    h = len(G)
    w = len(G[0])

    while queue:
        c, state = heappop(queue)
        if state in seen:
            continue
        seen.add(state)

        if state == end:
            return c

        x, y = state
        for (dx, dy) in [(-1, 0), (0, -1), (1, 0), (0, 1)]:
            xx = x + dx
            yy = y + dy
            if 0 <= xx < w and 0 <= yy < h:
                heappush(queue, (c+G[xx][yy], (xx, yy)))

    raise ValueError("end not found")

start = (0, 0)
end = (len(G)-1, len(G[0])-1)
# print(f"Shortest path (expand:{expand}) ", solve(G))
print(f"Shortest path (expand:{expand}) ", dijkstra(start, end, G))


import bpy
from bpy.props import BoolProperty, IntProperty

#法線をアクティブにする、既にチェック済み場合は無視。
def oSm(b):
    for o in bpy.context.selected_objects:
        if o.type == 'MESH':
            bpy.ops.object.shade_smooth()
            if o.data.use_auto_smooth == False:
                o.data.use_auto_smooth = True
                o.data.auto_smooth_angle = b
        elif o.type == 'CURVE':
            o.data.splines[0].use_smooth = True

def si_active_normal():
    oCM = bpy.context.object.mode
    if oCM == 'OBJECT':
        oSm(1.0472)
    else:
        bpy.ops.object.mode_set(mode='OBJECT')
        oSm(1.0472)
        bpy.ops.object.mode_set ( mode = oCM )

#サブディビジョンモデファイア削除、法線設定もデフォルトに戻す
def oDeln():
    for o in bpy.context.selected_objects:
        if o.type == 'MESH':
            bpy.ops.object.shade_flat()
            o.data.use_auto_smooth = False
            o.data.auto_smooth_angle = 0.523599
        elif o.type == 'CURVE':
            o.data.splines[0].use_smooth = False

def si_noactive_normal():
    oCM = bpy.context.object.mode
    if oCM == 'OBJECT':
        oDeln()
    else:
        bpy.ops.object.mode_set(mode='OBJECT')
        oDeln()
        bpy.ops.object.mode_set ( mode = oCM )

#サブディビジョン適応。法線適応コマンドのために、
#一々オブジェクトモードに切り替えて実行後、もとに戻す。
def oDel():
    for o in bpy.context.selected_objects:
        for m in o.modifiers:
            if(m.type == "SUBSURF"):
                o.modifiers.remove(m)
    return

def delete_subdiv():
    oCM = bpy.context.object.mode
    if oCM == 'OBJECT':
        oDel()
    else:
        bpy.ops.object.mode_set(mode='OBJECT')
        oDel()
        bpy.ops.object.mode_set ( mode = oCM )

def GetModifires():
    for i in bpy.context.selected_objects:
        #モディファイアの適応数
        num = len(i.modifiers)
        return num

def xsisubdiv(oL, oAdd, maxSubdivCount=3):
    #サブディビモデファイアの名前が一致したらプレビューの数値を増やす
    for o in bpy.context.selected_objects:
        #メッシュかカーブ判定
        if o.type == 'MESH' or o.type == 'CURVE':
            #名称規則でSI_subdivが存在しなければ新規でモデファイア生成
            if o.modifiers.get("SI_subdiv") == None:
                #すでに知らん名前のサブディビモデファイアがあれば全てさよならグッバイ
                for m in o.modifiers:
                    if(m.type == "SUBSURF"):
                        o.modifiers.remove(m)
                oLevel =o.modifiers.new("SI_subdiv",type = "SUBSURF")
                oLevel.render_levels = oL
                oLevel.levels = oL
                #ケージモードON
                o.modifiers["SI_subdiv"].show_on_cage = True
                print(o.name + " add SI_subdiv,Set CageMode")

            #名称規則でSI_subdivが存在していれば、サブディビジョンレベルを＋１
            #ただし、知らん名前のSUBSURFがあれば放置
            else:
                for m in o.modifiers:
                    if(m.type == "SUBSURF" or m.name == "SI_subdiv"):
                        #上限設定
                        if m.render_levels < maxSubdivCount:
                            m.render_levels = m.render_levels+ oAdd
                            m.levels = m.levels+ oAdd
                            print(o.name + " subdiv level " + str(m.levels))
    #ビューのリフレッシュ
    bpy.context.scene.frame_current = bpy.context.scene.frame_current
    return

class si_del_subdiv_OT_object(bpy.types.Operator):
    bl_idname = "object.si_del_sudiv"
    bl_label = "Delete Subdivision"
    bl_description = "Subdivisions like Softimage"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):
        delete_subdiv()
        si_noactive_normal()
        return {'FINISHED'}

class si_add_subdiv_OT_object(bpy.types.Operator):
    bl_idname = "object.si_add_sudiv"
    bl_label = "Add Subdivision"
    bl_description = "Subdivisions like Softimage"
    bl_options = {'REGISTER', 'UNDO'}

    #モデファイアを最後に移動するオプション
    si_moveindex : BoolProperty(default = True, name = "Move Modifire", description = "Move Modifire")
    maxSubdivCountInt : IntProperty(default = 3, name = "Max Subdivisions", description = "Max Subdivisions")

    def execute(self,context):
        si_active_normal()
        xsisubdiv(1, 1, maxSubdivCount= self.maxSubdivCountInt)

        if self.si_moveindex:
            #選択オブジェクトからモデファイア数を戻す
            num = GetModifires()
            bpy.ops.object.modifier_move_to_index(modifier="SI_subdiv",index= num - 1)
        return {'FINISHED'}

class si_minus_subdiv_OT_object(bpy.types.Operator):
    bl_idname = "object.si_minus_sudiv"
    bl_label = "Subtract subdivision"
    bl_description = "Subdivisions like Softimage"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self,context):
        xsisubdiv(1, -1, maxSubdivCount= 99)
        return {'FINISHED'}


import os
import sys
import argparse

def gotox(offset, time):
	os.system("gotox -d " + str(offset) + " -t " + str(time) + " && gotox -d " + str(offset) + " -t " + str(time))

parser = argparse.ArgumentParser(description='Searches for satellites.')
parser.add_argument("satellite")
parser.add_argument("-s", "--start", help="Where to start looking.", default=0, type=float)
parser.add_argument("-e", "--end", help="Where to stop looking.", default=20, type=float)
parser.add_argument("-d", "--direction", help="Which direction (E or W).", default="W")
parser.add_argument("-i", "--increment", help="How much to move each time by.", default=0.1, type=float)

args = parser.parse_args()

if args.direction == "W":
	args.start = args.start * -1
	args.end = args.end * -1

offset=args.start
gotox(offset, 30)
while (offset != args.end):
	print ("Offset ", offset)
	gotox(offset, 5)
	exit = os.system("w_scan -s " + args.satellite + " -f s")

	if exit == 0:
		print(offset)
		sys.exit(0)

	if args.direction == "W":
		offset = round(offset - args.increment, 2)
	else:
		offset = round(offset + args.increment, 2)


import cartopy
import cartopy.crs as ccrs
import matplotlib
import pandas

def plot_patches(ax,obs,**kwargs):
    """Plot observations as points.

    Args:
        ax (:obj:`cartopy.mpl.geoaxes.GeoAxes`): Axes on which to draw.
        obs (:obj:`pandas.DataFrame`): Data frame containing obs positions.

    Keyword Args:
        obs_projection (:obj:`cartopy.crs.CRS`): Projection in which observations latitudes and longitudes are defined. Default is :class:`cartopy.crs.PlateCarree`.
        lat_label (:obj:`str`): Key, in the obs dataframe, of the latitude data. Defaults to 'Latitude'.
        lon_label (:obj:`str`): Key, in the obs dataframe, of the longitude data. Defaults to 'Longitude'.
        radius (:obj:`float`): Radius of circle marking each ob. (degrees). Defaults to 1.
        facecolor (see :mod:`matplotlib.colors`): Main colour of the circle to be plotted for each ob. Defaults to 'yellow'.
        edgecolor (see :mod:`matplotlib.colors`): Border colour of the circle to be plotted for each ob. Defaults to 'black'.
        alpha (:obj:`float`): Alpha value for facecolor and edgecolor. Defaults to 0.85. Will be multiplied by the observation weight if present.
        zorder (:obj:`float`): Standard matplotlib parameter determining which things are plotted on top (high zorder), and which underneath (low zorder), Defaults to 25.

    Returns:
        Nothing - adds the obs. points to the plot.

    |
    """

    kwargs.setdefault('obs_projection',ccrs.PlateCarree())
    kwargs.setdefault('lat_label'     ,        'Latitude')
    kwargs.setdefault('lon_label'     ,       'Longitude')
    kwargs.setdefault('radius'        ,                 1)
    kwargs.setdefault('facecolor'     ,          'yellow')
    kwargs.setdefault('edgecolor'     ,           'black')
    kwargs.setdefault('alpha'         ,              0.85)
    kwargs.setdefault('zorder'        ,                25)

    rp=ax.projection.transform_points(kwargs.get('obs_projection'),
                                   obs[kwargs.get('lon_label')].values,
                                   obs[kwargs.get('lat_label')].values)
    new_longitude=rp[:,0]
    new_latitude=rp[:,1]

    # Plot each ob as a circle
    for i in range(0,len(new_longitude)):
        weight=1.0
        if 'weight' in obs.columns: weight=obs['weight'].values[i]
        ax.add_patch(matplotlib.patches.Circle((new_longitude[i],
                                                new_latitude[i]),
                                                radius=kwargs.get('radius'),
                                                facecolor=kwargs.get('facecolor'),
                                                edgecolor=kwargs.get('edgecolor'),
                                                alpha=kwargs.get('alpha')*weight,
                                                zorder=kwargs.get('zorder')))

# Plot observations
def plot(ax,obs,**kwargs):
    """Plot observations.

    Generic function for plotting observations. Use the 'type' argument to choose the plot style.

    Args:
        ax (:obj:`cartopy.mpl.geoaxes.GeoAxes`): Axes on which to draw.
        obs (:obj:`pandas.DataFrame`): Dataframe containing obs positions.

    Kwargs:
        type (:obj:`str`, optional): Style to plot. Only option is: 'patches', (default) which delegates plotting to :meth:`plot_patches`.

        Other keyword arguments are passed to the style-specific plotting function.

    Returns:
        Nothing - adds the obs. points to the plot.
    |
    """

    kwargs.setdefault('type','patches')

    if kwargs.get('type')=='patches':
        return plot_patches(ax,obs,**kwargs)

    raise Exception('Unsupported observations plot type %s' %
                         kwargs.get('type'))


from maya import cmds
from ngSkinTools import selectionState
from ngSkinTools.doclink import SkinToolsDocs
from ngSkinTools.influenceMapping import InfluenceMapping
from ngSkinTools.log import getLogger
from ngSkinTools.mllInterface import MllInterface
from ngSkinTools.ui.basetab import CommandLayout
from ngSkinTools.ui.basetoolwindow import BaseToolWindow
from ngSkinTools.ui.components import uiGroup
from ngSkinTools.ui.components.influencesManualMapping import InfluencesManualMapping
from ngSkinTools.ui.components.influencesMappingPreview import InfluencesMappingPreview

log = getLogger('editMirrorInfluencesWindow')

class EditMirrorInfluencesWindow(BaseToolWindow):
    def __init__(self, windowName):
        BaseToolWindow.__init__(self, windowName)
        self.useUserPrefSize = False
        self.windowTitle = 'Edit Mirror Influences'
        self.sizeable = True
        self.defaultHeight = 400
        self.defaultWidth = 450

        self.influenceMappingPreview = InfluencesMappingPreview()
        self.influencesManualMapping = InfluencesManualMapping()

        self.buildMapper = None

        self.mapper = InfluenceMapping()

    @staticmethod
    def getInstance():
        return BaseToolWindow.getWindowInstance('EditMirrorInfluencesWindow', EditMirrorInfluencesWindow)

    def setMapperBuilder(self,buildMapper):
        self.buildMapper = buildMapper
        self.previewInfluenceMapping()

    def createWindow(self):
        BaseToolWindow.createWindow(self)

        buttons = [
            ('Close', self.closeWindow, '')
        ]

        self.cmdLayout = CommandLayout(SkinToolsDocs.MIRRORWEIGHTS_INTERFACE, buttons)

        contentRoot = self.cmdLayout.innerLayout

        self.influenceMappingPreview.mirrorMode = True
        self.influenceMappingPreview.createUI(contentRoot)
        self.influenceMappingPreview.onDelete.addHandler(self.influencesManualMapping.removeSelectedManualMappings, contentRoot)

        manualGroup = uiGroup.create(contentRoot, 'Manual influence mapping')
        self.influencesManualMapping.mirrorMode = True
        self.influencesManualMapping.createUI(manualGroup)
        self.influencesManualMapping.getSelectedInfluences = lambda: self.influenceMappingPreview.currentInfluencesSelection

        def onManualOverridesChanged():
            mll = MllInterface()
            mll.setManualMirrorInfluences(self.influencesManualMapping.manualOverrides)
            self.previewInfluenceMapping()
        self.influencesManualMapping.manualOverridesChanged.addHandler(onManualOverridesChanged, contentRoot)

        def updateForSelectionInfoChange():
            log.info("updating for selection change")
            layersAvailable = selectionState.getLayersAvailable()
            cmds.layout(contentRoot,e=True,enable=layersAvailable)
            if not layersAvailable:
                log.info("layers unavailable")
                return

            self.previewInfluenceMapping()

        selectionState.selectionInfo.changed.addHandler(updateForSelectionInfoChange,contentRoot)
        selectionState.mirrorInfo.changed.addHandler(self.previewInfluenceMapping,contentRoot)
        updateForSelectionInfoChange()

    def previewInfluenceMapping(self):
        log.info("preview influence mapping")
        if self.buildMapper is None:
            log.info("mapper not available")
            return

        if not selectionState.getLayersAvailable():
            log.info("layers not available")
            return

        self.influencesManualMapping.manualOverrides = selectionState.mll.getManualMirrorInfluences()

        self.mapper.sourceInfluences = selectionState.mll.listInfluenceInfo()
        self.mapper = self.buildMapper()

        self.mapper.manualOverrides = self.influencesManualMapping.manualOverrides
        self.mapper.calculate()

        self.influenceMappingPreview.mapper = self.mapper
        self.influenceMappingPreview.constructInfluenceList()


#-*- coding: UTF-8 -*-
import os
import json
import time
from core.keyboardinterceptor import KeyboardInterceptor
from queue import Queue
from core.keyhandler import KeyHandler

DEFAULT_CONFIG = {
    "buffCoef1": 0.3,
    "buffCoef2": 0.6,
    "buffCoef3": 4.0,
    "buffCoef4": 8.0,
    "buffCoef5": 12.0,
    "shiftBuff": 2,
    "spaceBuff": 3
}

class AppController:
    queue = None
    interceptor = None
    keyHandler = None
    engaged = False
    ui = None

    def __init__(self):
        pass

    def start(self):
        self.queue = Queue()
        self.interceptor = KeyboardInterceptor(self.queue)
        self.interceptor.controller = self
        self.keyHandler = KeyHandler(self.interceptor,self.queue,self.getConfig())
        self.interceptor.start()
        self.keyHandler.start()
        self.engaged = True
        self.updateUIStatus()
        print('controller start')

    def stop(self):
        print('controller stop')
        self.keyHandler.stop()
        self.interceptor.stop()
        self.engaged = False
        self.updateUIStatus()

    def startFilter(self):
        self.interceptor.enable = True

    def stopFilter(self):
        self.interceptor.enable = False

    def getConfig(self):
        configData = None
        if not os.path.exists('config.json'):
            return DEFAULT_CONFIG
        with open('config.json','r',encoding='utf8')as f:
            configData = json.load(f)
        return configData

    def submitConfig(self,configData):
        self.stop()
        with open("config.json", 'w') as f:
            json.dump(configData, f, indent=4, ensure_ascii=False)
        self.start()

    def updateUIStatus(self):
        self.ui.updateStatus(self.engaged,self.interceptor.enable)

if __name__ == '__main__':
    app = AppController()
    app.submitConfig({'buffCoef1': 0.1, 'buffCoef2': 0.6, 'buffCoef3': 99, 'buffCoef4': 8, 'buffCoef5': 12, 'shiftBuff': 2, 'spaceBuff': 3})
    time.sleep(1)
    print(app.getConfig())


def get123Sum(n):
    global memo
    if memo[n] != 0:
        print(memo[n])
        return

    for i in range(1, n+1):
        if memo[i] != 0:
            continue

        if i <= 3:
            memo[i] = i
            continue

        k = i - 3
        if k % 2 == 0:  # k가 짝수일 때
            memo[i] = memo[k] + k//2 + 2
        else:           # k가 홀수일 때
            memo[i] = memo[k] + k // 2 + 3

    print(memo[n])

if __name__ == '__main__':
    TC = int(input())
    memo = [0] * 10001
    for T in range(TC):
        get123Sum(int(input()))


import requests
from bs4 import BeautifulSoup
import json
import re
import collections

HOST = "https://www.cfcunderwriting.com"

def get_privacy_policy_location(all_urls):
    for _, url in enumerate(all_urls):
        if "privacy-policy" in url:
            return url

def get_external_resources(all_urls):
    external_resources = []
    for url in all_urls:
        if is_external(url):
            external_resources.append(url)

    return external_resources

def is_external(url):
    return (url.startswith("http") or url.startswith("//")) and "cfcunderwriting" not in url

def get_url(tag, attr):
    return tag[attr]

def has_url(tag):
    return tag.has_attr("href") or tag.has_attr("src")

def write_to_json_file(filename, content):
    with open(filename, "w") as outfile:
        json.dump(content, outfile)
    outfile.close()

def scrape_page(url):
    r = requests.get(url)
    return BeautifulSoup(r.content, "html.parser")

def main():
    # scrape index page
    index_page = scrape_page(HOST)
    all_resources = index_page.find_all(has_url)  # full tags
    all_urls = [get_url(r, "href") if r.has_attr("href") else get_url(r, "src") for r in all_resources]  # urls

    # list of external resources
    external_resources = get_external_resources(all_urls)
    write_to_json_file("external_resources.json", external_resources)

    privacy_page_location = get_privacy_policy_location(all_urls)

    # scrape privacy policy page
    privacy_page = scrape_page(HOST + privacy_page_location)
    text = privacy_page.get_text(separator=" ", strip=True)
    # use regex to strip the text of special characters and numbers
    stripped_text = re.sub("[^a-zA-Z\s]", "", text)
    text_list = stripped_text.lower().split()
    # create a Counter object to calculate word frequencies
    frequencies = collections.Counter(text_list)
    write_to_json_file("word_count.json", dict(frequencies))

if __name__ == "__main__":
    main()


"""Creates an interactive website displaying characteristics of electric vehicles"""

# Import Libraries
import pandas as pd
import numpy as np
import streamlit as st
import plotly_express as px
import plotly.figure_factory as ff

## READ AND CLEAN DATA
# Set Application Name
st.set_page_config(page_title='Electric Vehicle Data Visualizations')

# Read in dataset
url = 'https://raw.githubusercontent.com/kellyshreeve/Web-App-Project/main/ElectricCarData_Clean.csv'
ev = pd.read_csv(url)

# Rename columns with snake case
ev = ev.rename(
    columns={'Brand':'brand',
             'Model':'model',
             'AccelSec':'accel_sec',
             'TopSpeed_KmH':'top_speed_kmh',
             'Range_Km':'range_km',
             'Efficiency_WhKm':'efficiency_whkm',
             'FastCharge_KmH':'fast_charge_kmh',
             'RapidCharge':'rapid_charge',
             'PowerTrain':'power_train',
             'PlugType':'plug_type',
             'BodyStyle':'body_style',
             'Segment':'segment',
             'Seats':'seats',
             'PriceEuro':'price_euro'
             }
)

# Clean duplicates and missing values
ev['fast_charge_kmh'] = ev['fast_charge_kmh'].replace('-', np.NaN) # Change '-' to NaN

ev['fast_charge_kmh'] = pd.to_numeric(ev['fast_charge_kmh']) # Change fast_charge_kmh to int type data

ev = ev.drop_duplicates(subset=['brand', 'model']).reset_index(drop=True)

# Create top brands data frame
top_brands = ev[(ev['brand']=='Tesla ') | (ev['brand']=='Audi ') | (ev['brand']=='Nissan ')
                | (ev['brand']=='Volkswagen ') | (ev['brand']=='Skoda ') | (ev['brand']=='Renault ')
                | (ev['brand']=='Porsche ') | (ev['brand']=='BMW ') | (ev['brand']=='Ford ')
                | (ev['brand']=='Kia ') | (ev['brand']=='Smart ') | (ev['brand']=='Byton ')
                | (ev['brand']=='Mercedes ') | (ev['brand']=='Hyundai ') | (ev['brand']=='Opel ')]

## CREATE HEADER
st.header('Electric Vehicle Market Visualizations')

# Create Text
st.markdown('Welcome to the electric vehicle data visualization page! Click the buttons \nand toggle the colors to see how price, efficiency, and range of electric vehicles compare across the market.')

## CREATE BAR CHARTS
# Create a bar chart of average price by brand
price_bar = px.histogram(top_brands, x='brand', y='price_euro', histfunc='avg',
                          title='Average Price by Brand', text_auto='.2s',
                          labels={'price_euro':'Price (Euros)', 'brand':'Brand Name'},
                          color_discrete_sequence=[px.colors.qualitative.Plotly[7]],
                          width=800, height=500)

price_bar.update_layout({
    'plot_bgcolor':'rgba(0, 0, 0, 0)',
    'paper_bgcolor':'rgba(0, 0, 0, 0)'
})

price_bar.update_traces(textfont_size=11, textposition='outside') # Add labels above bars

price_bar.update_layout(xaxis={'categoryorder':'total descending'}) # Arrange in order from expensive to inexpensive

price_bar.update_xaxes(showgrid=False) # Turn off x grid
price_bar.update_yaxes(showgrid=False) # Turn off y grid

# Create bar chart of average efficiency by brand
eff_bar = px.histogram(top_brands, x='brand', y='efficiency_whkm', histfunc='avg',
                        title='Average efficiency by Brand', text_auto='.2s',
                        labels={'efficiency_whkm':'Efficiency (WhKm)', 'brand':'Brand Name'},
                        color_discrete_sequence=[px.colors.qualitative.Plotly[7]],
                        width=800, height=500)

eff_bar.update_layout({
    'plot_bgcolor':'rgba(0, 0, 0, 0)',
    'paper_bgcolor':'rgba(0, 0, 0, 0)'
})

eff_bar.update_traces(textfont_size=11, textposition='outside')

eff_bar.update_layout(xaxis={'categoryorder':'array', 'categoryarray':
    ['Porsche ', 'Audi ', 'Tesla ', 'Mercedes ', 'Byton ', 'Ford ', 'BMW ',
     'Nissan ', 'Skoda ', 'Hyundai ', 'Kia ', 'Opel ', 'Volkswagen ', 'Renault ', 'Smart ']})

eff_bar.update_xaxes(showgrid=False)
eff_bar.update_yaxes(range=[0,250], showgrid=False) # Set y axis range

# Bar chart of average range by brand
range_bar = px.histogram(top_brands, x='brand', y='range_km', histfunc='avg',
                         title='Average Range by Brand', text_auto='.2s',
                         labels={'range_km':'Range (Km)', 'brand':'Brand Name'},
                         color_discrete_sequence=[px.colors.qualitative.Plotly[7]],
                         width=800, height=500)

range_bar.update_layout({
    'plot_bgcolor':'rgba(0, 0, 0, 0)',
    'paper_bgcolor':'rgba(0, 0, 0, 0)'
})

range_bar.update_traces(textfont_size=11, textposition='outside')

range_bar.update_layout(xaxis={'categoryorder':'array', 'categoryarray':
    ['Porsche ', 'Audi ', 'Tesla ', 'Mercedes ', 'Byton ', 'Ford ', 'BMW ',
     'Nissan ', 'Skoda ', 'Hyundai ', 'Kia ', 'Opel ', 'Volkswagen ', 'Renault ', 'Smart ']})

range_bar.update_xaxes(showgrid=False)
range_bar.update_yaxes(showgrid=False)

# Create Header
st.subheader('By Brand')

# Radio Buttons
option = st.radio(label='Choose characteristic:', options=['Price', 'Efficiency', 'Range'])
st.write('<style>div.row-widget.stRadio > div{flex-direction:row;}</style>', unsafe_allow_html=True) # Make buttons horizontal

# Displays for radio button options
if option == 'Price':
    st.plotly_chart(price_bar)
elif option == 'Efficiency':
    st.plotly_chart(eff_bar)
elif option == 'Range':
    st.plotly_chart(range_bar)

# DENSITY PLOTS
# Header for body style
st.subheader('By Body Style')

# Drop down menu
option_2 = st.selectbox('Choose characteristic:', ('Price', 'Efficiency', 'Range'))

x_value_dens = (option_2=='Price' and 'price_euro') or (option_2=='Efficiency' and 'efficiency_whkm') or (option_2=='Range' and 'range_km')
x_label_dens = (option_2=='Price' and 'Price (Euros)') or (option_2=='Efficiency' and 'Efficiency (WhKm)') or (option_2=='Range' and 'Range (Km)')

# Create histograms by drop down selection
suv_hatch_sed = ev[(ev['body_style']=='SUV') | (ev['body_style']=='Hatchback') | (ev['body_style']=='Sedan')]

suv = suv_hatch_sed[suv_hatch_sed['body_style']=='SUV'][x_value_dens]
hatch = suv_hatch_sed[suv_hatch_sed['body_style']=='Hatchback'][x_value_dens]
sedan = suv_hatch_sed[suv_hatch_sed['body_style']=='Sedan'][x_value_dens]

hist_data = [sedan, suv, hatch]
group_labels = ['Sedan', 'SUV', 'Hatchback']

density = ff.create_distplot(hist_data, group_labels, show_hist=False, show_rug=False,
                                colors=[px.colors.qualitative.Plotly[0],
                                        px.colors.qualitative.Plotly[7],
                                        px.colors.qualitative.Plotly[9]])

density.update_layout({
    'plot_bgcolor':'rgba(0, 0, 0, 0)',
    'paper_bgcolor':'rgba(0, 0, 0, 0)'
})

density.update_layout(title=f'{option_2} by Body Style', xaxis_title=x_label_dens, yaxis_title='Percent of Body Type')
density.update_xaxes(showgrid=False)
density.update_yaxes(showgrid=False)

st.plotly_chart(density)

# CREATE SCATTER PLOTS
# Header for scatter plot
st.subheader('By Price')

# Drop down nenu for scatter plot
y_axis = st.selectbox('Y Axis:', ('Efficiency', 'Range'))

# Create scatter plot from drop down selection
y_value_scat = (y_axis=='Efficiency' and 'efficiency_whkm') or (y_axis=='Range' and 'range_km')

y_label_scat = (y_axis=='Price' and 'Price (Euros)') or (y_axis=='Efficiency' and 'Efficiency (WhKm)') or (y_axis=='Range' and 'Range (Km)')

price_efficiency = px.scatter(data_frame=ev, title=f'{y_axis} vs Price', x='price_euro', y=y_value_scat,
           labels={'price_euros':'Price (Euros)', y_value_scat:y_label_scat},
           color='brand', width=900, height=500, hover_data=['model'])

price_efficiency.update_layout({
    'plot_bgcolor':'rgba(0, 0, 0, 0)',
    'paper_bgcolor':'rgba(0, 0, 0, 0)'
})

price_efficiency.update_xaxes(showgrid=False)
price_efficiency.update_yaxes(showgrid=False)

# Display scatter plot on website
st.plotly_chart(price_efficiency)

st.markdown('Graphics on this site were created from data on the 103 top electric vehicles on the market today.')


import requests
from bs4 import BeautifulSoup
import re
import sys
sys.path.append('/home/nandagopal/eagle')
from data_collection.config import *

f_ratios_list = list(open(f_ratios_file, 'r').readlines())

def find_data_for_all_stock(sector=None):
    """
    method to be called from airflow

    loops through all urls and get their financial ratios

    :return:
    """
    for url in open(money_control_urls_file, 'r').readlines():
        if sector in url :
            find_data(url)

def find_data(url):
    """

    :param url: finace ration url of money control for single stock
    :return:

    INE428A01015,Basic EPS,-65.34,  -59.63,  -4.36,  -12.68,  11.39
    INE428A01015,Diluted Eps,-65.34,  -59.63,  -4.36,  -12.68,  11.39
    INE428A01015,Cash EPS,-39.09,  -53.69,  -2.11,  -10.21,  12.61

    """
    ofile = open(finance_csv, 'a')
    isin, sector, f_ratios, pl_ratios, q_ratios = url.split(delimiter)
    url = f_ratios
    print(isin, url)
    res = requests.get(url).text
    soup = BeautifulSoup(res, 'lxml')
    td_list = list(soup.find_all('td'))
    idx = 0
    for ele in td_list:
        ele = str(ele)
        try:
            for f_ratio in f_ratios_list:
                f_ratio = f_ratio.rstrip('\n')
                if f_ratio in ele :
                    print(f_ratio)
                    ratios = []
                    for i in range(1, 6):
                        data = td_list[idx+i]
                        # print(data)
                        ratios.append(re.findall(r'-?\d+.\d+',str(data))[0])
                    print(ratios)
                    ofile.write(isin + ',' + f_ratio +"," +",  ".join(ratios) + '\n')
            idx += 1
        except Exception as err:
            print(err)

find_data_for_all_stock('Banks - Public Sector')


import requests,bs4
from twilio.rest import Client

accountSID='**********************************'      #I have obtained the accountsid,authtoken and twilio no but will not be showing as it can be misused
authToken='********************************'

twilioCli=Client(accountSID,authToken)
mytwiliono='************'
myno='*************'
res=requests.get('https://weather.com/en-GB/weather/tenday/l/81cc0aa50e5a2f8287fd6848b8a6940233a43352ee461cf19c0dbd775515a51d')
res.raise_for_status()
parse=bs4.BeautifulSoup(res.text,'html.parser')
rain=parse.select('#detailIndex0 > div:nth-child(2) > div:nth-child(1) > div:nth-child(2) > div:nth-child(3) > div:nth-child(1) > span:nth-child(2)')
#getting the rain chance percentage
rainper=str(rain[0].getText())
rainperno=rainper[:-1]
# print(rainperno)
if int(rainperno)>70:
    twilioCli.messages.create(body='Akshaya it might rain today,make sure to take an umbrlla',from_=mytwiliono,to=myno)


import collections

#FUNCTIONS THAT INVOLVE BUILDING AND MODIFYING BASIC GRAPHS

#takes an int specifying the number of vertices or an iterable containing the vertex names, and
#a list of the edges [(0, 1), (1, 2), (0, 2), (2, 4, 1)] (the third parameter, if given, is the order of a directed edge)
#with that, it clears and reconstructs the graph.
#TODO: make a directed version of this
def buildGraph(g, vertices, edges=None, vdata={}, edata={}):
    """
    @param g: The graph to write to.
    @type g: L{GraphEngine.BaseObjects.BaseGraph}
    @param vertices: A list of edges

    """
    g.clearGraph()

    if isinstance(vertices, collections.Iterable):
        uvertices = vertices
    else:
        uvertices = range(vertices)

    for x in uvertices:
        g.addVertex(x)

    if edges is not None:
        for x in edges:
            l = 0
            if len(x) >= 3:
                l = x[2]
            e = g.addEdge(x[0], x[1], l)
            if len(x) == 4:
                for i in x[3]:
                    g.setEdgeData(e, i[0], i[1])

    #print(vdata)
    for vd in vdata:
        for i in vdata[vd]:
            #print(str(vd) + " " + str(i[0]) + " " + str(i[1]))
            g.setVertexData(vd, i[0], i[1])

    for ed in edata:
        for i in edata[ed]:
            g.setEdgeData(ed, i[0], i[1])
    return

#Builds the graphs from dictionaries
#vertices should be either a number or a dictionary.
#If it is a number, then that many vertices will simply be added with
#integer ids.
#If it is a dictionary, then each entry is a vertex. There are 2 entries that are important:
#"data" and "name". "data" should be a dictionary of data entries attached to that vertex. "name" is
#the name of the vertex. if this is not present, then the dictionary key in vertices of that entry will
#be used.
#edges should be None or a dictionary. If None, then there will be no edges. If a dictionary.
#then each entry will be an edge. #There are 4 important entries to each edge. "name", "vertices", "directed", and "data".
#"data" and "name" work the same as with vertices. "vertices" is a tuple containing the 2 vertices connected by
#the edge. "directed" should be True or False. If True, then it is directed from the first vertex in the "vertices" tuple
#to the second. You could also set "directed" to -1 to have it be directed from the second to the first.
def buildGraphD(g, vertices, edges=None):
    g.clearGraph()
    if not isinstance(vertices, collections.Iterable):
        o = {}
        for v in range(vertices):
            o[v] = {"name":v}
        vertices = o

    for key in vertices:
        name = vertices[key]["name"] if "name" in vertices[key] else key
        datadic = vertices[key]["data"] if "data" in vertices[key] else None
        g.addVertex(name)
        if datadic is not None:
            for k in datadic:
                g.setVertexData(name, k, datadic[k])

    if edges is not None:
        for key in edges:
            name = edges[key]["name"] if "name" in edges[key] else key
            vertices = edges[key]["vertices"]
            directed = edges[key]["directed"] if "directed" in edges[key] else 0
            datadic = edges[key]["data"] if "data" in edges[key] else None
            g.addEdge(vertices[0], vertices[1], directed, name)
            if datadic is not None:
                for k in datadic:
                    g.setEdgeData(name, k, datadic[k])
    return

#appends g2 and all of its properties to g. Returns the first vertex id and the first edge id
def appendGraph(g, g2):
   #get and sort the vertex lists
   vl = [x for x in g2.getVertexList()]
   vl.sort()
   el = [x for x in g2.getEdgeList()]
   el.sort()

   vstart = g.getOrder()
   estart = g.getSize()

   #setup the new vertices
   for i in vl:
      n = g.addVertex()
      for di in g2.getVertexDataKeys(i):
         g.setVertexData(n, di, g2.getVertexData(i, di))

   v2ne = {}
   for i in range(len(el)):
      v2ne[el[i]] = i
   #set up the new edges
   for i in el:
      edgeinfo = g2.getEdgeInfo(i)
      n = g.addEdge(v2ne[edgeinfo[0]]+vstart, v2ne[edgeinfo[1]]+vstart, edgeinfo[2])
      for di in g2.getEdgeDataKeys(i):
         g.setEdgeData(n, di, g2.getEdgeData(i, di))
   return (vstart, estart)


import itertools

amt = int(input().rstrip())
for i in range(amt):
	line = input().rstrip().split(" ")
	ooga = list(line[1])
	ooga.sort()
	all_perms = list(itertools.permutations(ooga))
	#print(all_perms)
	print("{} {}".format(''.join(all_perms[ int(line[0]) ]) , ''.join(all_perms[len(all_perms)-int(line[0]) -1 ])))

#print(''.join(test[2]))


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# test-train-shakeel/format_data.py
#
# format time series data for training
#

import os
import re
import pandas as pd
import datetime as dt
import pandas as pd
import numpy as np
import scipy
#import matlab.engine

from sklearn.preprocessing import minmax_scale

#linux内のmatlabを起動する
#mat = matlab.engine.start_matlab()
#mat.cd(r'matlab', nargout=0)

class preprocess_for_Siamese_Net():
    """
    siamese network用のデータ前処理クラス
    """

    def __init__(self):
        super()

    @classmethod
    def convert_csv_to_mergedcsv(self, climo_csv_path:str, gauss_csv_path:str) -> pd:
        """
        2つのセンサーの時系列csvデータを同時刻部のみを切り出しmergeする

        arg:
            - climo_csv_path:climomasterデータのcsvパス
            - gauss_csv_path:milli gauss meterデータのcsvパス
        return:
            - merged_df:二つのセンサーの時系列csvデータを同時刻部のみを切り出しmergeしたデータフレーム
        """

        def climo_momenttime(x_linespace:int,beginning_time:str,sampling_interval:int)-> dt:
            """
            climomaster.dfの各データ行の日付型を生成

            args:
                - x_linespace: 等間隔の数列
                - beginning_time: 開始時刻
                - sampleing_interval: サンプリング間隔

            return:
                - moment_time: 日付型
            """

            #開始時刻の文字列からデータの日付型を取得
            beginning_time = beginning_time.replace('#','')
            beginning_time_list = re.split('[/: ]',beginning_time)
            beginning_year = int(beginning_time_list[2])
            beginning_month = int(beginning_time_list[1])
            beginning_day = int(beginning_time_list[0])
            beginning_hour = int(beginning_time_list[3])
            beginning_minite = int(beginning_time_list[4])
            beginning_second = int(beginning_time_list[5])
            beginning_time = dt.datetime(beginning_year,beginning_month,beginning_day,beginning_hour,beginning_minite,beginning_second)

            #サンプリング間隔
            elapsed_time = x_linespace * sampling_interval
            moment_time = beginning_time + dt.timedelta(seconds = elapsed_time)
            return moment_time

        def gauss_momenttime(time:str)-> dt:
            """
            milli gauss meter.dfの各データ行の日付型を生成

            arg:
                -time:時刻

            return:
                - moment_time: 日付型
            """
            moment_time_list = re.split('[/: ]',time)
            year = int(moment_time_list[0])
            month = int(moment_time_list[1])
            day = int(moment_time_list[2])
            hour = int(moment_time_list[3])
            minute = int(moment_time_list[4])
            second = int(moment_time_list[5])
            moment_time = dt.datetime(year,month,day,hour,minute,second)
            return moment_time

        #パスからデータフレームを取得
        climo_csv_df = pd.read_csv(climo_csv_path,names = ["No.","V(m/s)","T(C)","H(%RH)","A(hPa)","Atom.F"])

        #climomaster.csvの先頭部のinfo情報のみをclimo_info_dictに抽出
        climo_info_df = climo_csv_df[:13]
        climo_info_df =  climo_info_df.rename(columns={'No.': 'info','V(m/s)':'data'})
        climo_info_df = climo_info_df.drop(["T(C)","H(%RH)","A(hPa)","Atom.F"],axis=1)
        climo_info_dict = dict(zip(climo_info_df['info'], climo_info_df['data']))

        #開始時間とサンプリング間隔を抽出
        beginning_time = climo_info_dict['[Measurement beginning time]']
        sampling_interval = int(climo_info_dict['[S-TIME(S) -- Sampling interval(s)]'])

        #climomaster.csvのデータ部の情報を加工し、climo_dfに抽出
        climo_df = climo_csv_df[19:]
        climo_df =  climo_df.rename(columns={'No.': 'Time'})
        climo_df = climo_df.drop(["A(hPa)","Atom.F"],axis=1)
        climo_df = climo_df.astype({'Time':int, 'V(m/s)':float, "T(C)":float ,"H(%RH)":float})

        #一行ずつ時間を更新
        for i in range(len(climo_df)):
            number = sampling_interval * (i+1)
            climo_df.loc[i+19,"Time"] = climo_momenttime(number,beginning_time,sampling_interval)
        #行の部分に時間をセットする
        climo_df = climo_df.set_index('Time')

        #milli gauss meterのデータフレームを取得
        gauss_df = pd.read_csv(gauss_csv_path, encoding = 'shift_jis')

        #gauss.csvのデータ部の情報を加工し、gauss_dfを取得
        gauss_df['Time'] = gauss_df['年月日'].str.cat(gauss_df['時刻'], sep = ' ')
        gauss_df = gauss_df.drop(columns = {'年月日','時刻'})
        gauss_df = gauss_df.rename(columns = {'データ01(mG)':'φ(mG)'})
        #全ての"Time"行にgauss_momenttime関数を適用
        gauss_df['Time'] = gauss_df['Time'].map(gauss_momenttime)
        #行の部分に時間をセットする
        gauss_df = gauss_df.set_index('Time')

        #両方のcsvをmergeし、時刻の共通部のみを切り出す
        merged_df = pd.merge(climo_df,gauss_df,left_index=True,right_index = True)
        merged_df = merged_df.dropna()
        merged_df.plot(subplots = True)

        return merged_df

    @classmethod
    def normalization(data_array:np)->np:
        """
        時系列データ(numpy配列)を配列内で最大値最小値を取り、正規化する

        args:
            - data_array(np): データのnumpy配列
        return:
            - rms_data(np):正規化処理を加えた後のデータのnumpy配列
        """
        normalizated_data = minmax_scale(data_array)
        return normalizated_data

    @classmethod
    def rms(data_array:np)->np:
        """
        時系列データ(numpy配列)に実効値処理を加える

        args:
            - data_array(np): データのnumpy配列
        return:
            - rms_data(np):実効値処理を加えた後のデータのnumpy配列
        """
        square_data_array = data_array**2
        abs_square_data_array = np.abs(square_data_array)
        sum_abs_square_data = np.sum(abs_square_data_array)
        sum_mean_square_data = sum_abs_square_data / len(data_array)
        rms_data = np.sqrt(data_array / sum_mean_square_data)
        return rms_data

    @classmethod
    def convert_mergedcsv_to_matfile(self,csv_path:str,
                                        is_wind_vel_converted: bool = True,
                                        is_temp_converted: bool = False,
                                        is_humid_converted: bool = False,
                                        is_gauss_converted: bool = True):
        """
        メルスペクトログラム変換する関数
        """

        #データの取り込み
        merged_data_df = pd.read_csv(csv_path,names = ["Time","V(m/s)","T(C)","H(%RH)","φ(mG)"],skiprows=1)

        #風速をmatファイルに変換
        if is_wind_vel_converted:
            wind_vel_df = merged_data_df['V(m/s)']
            wind_vel_array = np.array(wind_vel_df.values[1:], dtype = 'float')
            mel_spect_wind_vel_data = mat.mel_spectrogram_bad(matlab.double(wind_vel_array),matlab.double(2900))
            scipy.io.savemat('data/mat/wind_vel/wind'+ csv_path.replace('.csv','') + '.mat', {'wind_feat':mel_spect_wind_vel_data})
            print("convert wind velocity data to mat file.")

        #温度をmatファイルに変換
        if is_temp_converted:
            temp_df = merged_data_df['T(C)']
            temp_array = np.array(temp_df.values[1:], dtype = 'float')
            mel_spect_temp_data = mat.mel_spectrogram_bad(matlab.double(temp_array),matlab.double(2900))
            scipy.io.savemat('data/mat/temp/temp'+ csv_path.replace('.csv','') + '.mat', {'temp_feat':mel_spect_temp_data})
            print("convert temperature data to mat file.")

        #湿度をmatファイルに変換
        if is_humid_converted:
            humid_df = merged_data_df['H(%RH)']
            humid_array = np.array(humid_df.values[1:], dtype = 'float')
            mel_spect_humid_data = mat.mel_spectrogram_bad(matlab.double(humid_array),matlab.double(2900))
            scipy.io.savemat('data/mat/humid/humid'+ csv_path.replace('.csv','') + '.mat', {'humid_feat':mel_spect_humid_data})
            print("convert humidity data to mat file.")

        #磁束密度をmatファイルに変換
        if is_gauss_converted:
            gauss_df = merged_data_df['H(%RH)']
            gauss_array = np.array(gauss_df.values[1:], dtype = 'float')
            mel_spect_gauss_data = mat.mel_spectrogram_bad(matlab.double(gauss_array),matlab.double(2900))
            scipy.io.savemat('data/mat/gauss/gauss'+ csv_path.replace('.csv','') + '.mat', {'gauss_feat':mel_spect_gauss_data})
            print("convert milli Gauss data to mat file.")

    def generate_npy_for_siamese(mat1_dir,mat1_feat,mat2_dir,mat2_feat):
        """
        siamese networks用に2対のデータセットとラベルのnpyファイルを生成
        args:
            - mat1_dir(str): matファイルが格納されているディレクトリ
            - mat1_feat: ['wind_feat','temp_feat','humid_feat','gauss_feat']のどれか、mat1_dirの種類による
            - mat2_dir(str): matファイルが格納されているディレクトリ(もう一組)
            - mat2_feat: ['wind_feat','temp_feat','humid_feat','gauss_feat']のどれか、mat1_dirの種類による
        """

        def convert_mat_to_list(mat_dir:str,feature_type:str):
            """
            ディレクトリ内のmatファイルの組み合わせを全てlistに変換する関数
            args:
                - mat_dir(str): matファイルが格納されているディレクトリ名
                - feature_type(str): ['wind_feat','temp_feat','humid_feat','gauss_feat']のどれか、mat_dirの種類による
            """

            mat_files = os.listdir(mat_dir)
            mat2_a = []
            mat2_b = []
            mat2_y = []
            for i in range(len(mat_files)):
                    a_path = mat_files[i]
                    temp1 = scipy.io.loadmat(mat_dir + a_path)
                    feat1 = np.array(temp1[feature_type]).reshape(999,50)
                    for j in range(len(mat_files)):
                        b_path = mat_files[j]
                        temp2 = scipy.io.loadmat(mat_dir + b_path)
                        feat2 = np.array(temp2[feature_type]).reshape(999,50)
                        mat2_a.append(feat1)
                        mat2_b.append(feat2)
                        if(a_path[0]==b_path[0]):
                            mat2_y.append(ord(a_path[0])-48)
                        else:
                            mat2_y.append(-1)

            return mat2_a,mat2_b,mat2_y

        mat1_a,mat1_b,mat1_y = convert_mat_to_list(mat1_dir,mat1_feat)
        mat2_a,mat2_b,mat2_y = convert_mat_to_list(mat2_dir,mat2_feat)
        label=[]

        #ラベリング
        for i in range(len(mat2_a)):
            if(mat1_y[i] == -1 or mat2_y[i] == -1):
                label.append(0)
            elif(mat1_y[i] == mat2_y[i]):
                label.append(1)
            else:
                label.append(0)

        #npyファイルに変換s
        datadir = "data/train-npy/"
        np.save(datadir + mat1_feat + '_a_set', mat1_a)
        np.save(datadir + mat1_feat + '_b_set', mat1_b)
        np.save(datadir + mat2_feat + '_a_set', mat2_a)
        np.save(datadir + mat2_feat + '_b_set', mat2_b)
        np.save(datadir + 'labels', label)
        return


# https://app.codesignal.com/interview-practice/task/uX5iLwhc6L5ckSyNC

def firstNotRepeatingCharacter(s):
    cache = {}

    for c in s:
        temp = cache.get(c, 0)
        temp += 1
        cache[c] = temp

    for key in cache.keys():
        if cache[key] == 1:
            return key

    return '_'

print(firstNotRepeatingCharacter("abacabad"))

Interview Questions/First Non Repeating Character.py


"""
Plot helpers

"""

import matplotlib.pyplot as plt
import numpy as np

__all__ = ['plot_pressure', 'plot_filltime', 'show_flowfront', 'show_kmaps']

def plot_pressure(pr, showlegend=True):
    """
    Plot pressure for all the rows

    Parameters
    ----------
    pr : np.ndarray
        Pressure values
    showlegend : bool
        Show legend on the plot

    Returns
    -------
    None

    """
    plt.plot(np.transpose(pr))

    plt.title('Pressure values for all nodes')
    plt.xlabel('x nodes')
    plt.ylabel('pressure level')
    #if showlegend:
    #    plt.legend(['row' + str(i+1) for i in range(self.ynodes)])

    plt.show()

def plot_filltime(ft, showlegend=True):
    """
    Plot filltime for all the rows

    Parameters
    ----------
    ft : np.ndarray
        Filltime for all nodes
    showlegend : bool
        Show legend on the plot

    Returns
    -------
    None

    """

    plt.plot(np.transpose(ft))

    plt.title('filltime for all nodes')
    plt.xlabel('x nodes')
    plt.ylabel('filltime')
    #if showlegend:
    #    plt.legend(['row' + str(i+1) for i in range(self.ynodes)])

    plt.show()

def show_flowfront(ft):
    """
    Show flowfront

    Parameters
    ----------
    ft: np.ndarray
        flowtime

    Returns
    -------
    None

    """

    from copy import copy

    #cmap = copy(plt.cm.get_cmap("tab20b"))
    cmap = copy(plt.cm.get_cmap("jet"))
    cmap.set_under(color='white')

    plt.title('flowfront')
    #plt.imshow(ft, cmap=cmap, interpolation="bilinear", origin="lower", vmin=1e-12)
    plt.imshow(ft, cmap=cmap, origin="lower", vmin=1e-12)
    plt.xlim(0.5, ft.shape[1]-.5)
    plt.ylim(0.5, ft.shape[0]-.5)
    plt.colorbar()
    plt.show()

def show_kmaps(m):
    """
    Show K maps

    Parameters
    ----------
    m: Mesh
        Mesh data to be shown

    Returns
    -------
    None

    """

    from copy import copy

    cmap = copy(plt.cm.get_cmap("tab20b"))
    cmap.set_under(color='black')

    kxx = m.get_cell_kxx()
    kyy = m.get_cell_kyy()
    kxy = m.get_cell_kxy()

    fig, (ax1, ax2, ax3) = plt.subplots(3)
    fig.suptitle('K maps for the mesh')

    #im = ax1.imshow(kxx, cmap=cmap, interpolation="bilinear", origin="lower")
    im = ax1.imshow(kxx, cmap=cmap, origin="lower")
    ax1.set_xlim(0, kxx.shape[1]-1)
    ax1.set_ylim(0, kxx.shape[0]-1)
    ax1.set_title('Kxx')
    fig.colorbar(im, ax=ax1)

    ax2.imshow(kyy, cmap=cmap, origin="lower")
    ax2.set_xlim(0, kyy.shape[1]-1)
    ax2.set_ylim(0, kyy.shape[0]-1)
    ax2.set_title('Kyy')
    fig.colorbar(im, ax=ax2)

    ax3.imshow(kxy, cmap=cmap, origin="lower")
    ax3.set_xlim(0, kxy.shape[1]-1)
    ax3.set_ylim(0, kxy.shape[0]-1)
    ax3.set_title('Kxy')
    fig.colorbar(im, ax=ax3)

    plt.show()


class ExtroversionQuiz:

    def __init__(self):
        self.valid = True
        self.score = 0
        self.output = ''
        self.prediction_statement = 'You are about to take a quiz on whether you are an introvert or an extrovert.\nBut first, lets see how well you know yourself.\nEnter 1 if you think you are an introvert, 2 if you think you are a extrovert, and 3 if you think you have qualities of both.'
        self.prediction_answers = ['1', '2', '3']
        self.prediction_output = ''
        self.compare_prediction = ''
        self.intro_statement = 'For each statement given, how well does this statement represent you?\nAnswer on a scale of 1-5 : 1 being very inaccurate to you, and 5 being very accurate to you.\n'
        self.statement_list = ['I never avoid contact with others. ',
                                'I find it very easy to make new friends. ',
                                'I am very good at cheering others up. ',
                                'I easily captivate people. ',
                                'I am a very talkative person. ',
                                'My overall experiences are exciting. ',
                                'If I am at a party I talk to many different people. ',
                                'I am good at handeling social situations. ',
                                'I am easy to get to know. ',
                                'I do not mind being the center of attention. ',
                                'I feel comfortable around new people. ',
                                'I have a lot to say when I am around others in a social setting. ',
                                'I am the life of the party. ',
                                'I warm up to others easily. ',
                                'I easily start new conversations. ']
        self.possible_answers = ['1', '2', '3', '4', '5']

    def run_extroversion_quiz(self):

        """ Prints out quiz statements for user. Changes input to an integer and adds the total score together. Catches if the
        user inputs an incorrect value and sets the variable self.valid to false.

        Parameters
        ----------
        none

        Returns
        -------
        self.valid : boolean
            If self.valid is false this means the user inputed an incorrect value. They are then prompted to rerun the code and
            only input integer values between 1-5. If true, the quiz continues as normal.

       self.score : int
           The sum of all user inputs to the statement questions. Score is used to determined whether the user is an introvert,
           extrovert, or has qualities of both.

       """

        print(self.prediction_statement)
        self.user_prediction = input()

        if self.user_prediction in self.prediction_answers:
            print(self.intro_statement)

            for statement in self.statement_list:
                user_input = input(statement)
                print('')

                if user_input in self.possible_answers:
                    user_input = int(user_input)  # In order to add user inputs together, str must be changed to int
                    self.score = self.score + user_input

                else:
                    self.valid = False
                    return self.valid

        return self.score

    def score_analysis(self):

        """ Compares user score to fixed ranges to determine whether or not the user is more extroverted, introverted, or has
        qualities of both. Sets a value for self.compare_prediction depending on what the quiz results are.

        Parameters
        ----------
        none

        Returns
        -------
        self.compare_prediction : str
            Assigns a value to the users quiz results to see if it matched the users prediction.

        self.output : str
            Attributes a string output to the users total quiz score indicating their quiz results.

        self.valid : boolean
            If self.valid is false this means the user inputed an incorrect value. They are then prompted to rerun the code and
            only input integer values between 1-5. If true, the quiz continues as normal.

        """

        if type(self.score) == int and self.valid == True: #  extra checks to make sure inputs are correct

            if 15 <= self.score <= 35:
                self.output = ' are an introvert. '
                self.compare_prediction = '1'

            elif 36 <= self.score <= 55:
                self.output = ' have a mix of both introverted and extroverted qualities. '
                self.compare_prediction = '3'

            elif 56 <= self.score <= 75:
                self.output = ' are an extrovert. '
                self.compare_prediction = '2'

            return self.compare_prediction, self.output

        else:
            print('Oops, looks like you entered an invalid input. Please re-run the quiz and make sure you only enter integers between 1 and 5.')

            self.valid = False  # When self.valid = False the rest of the methods will not execute (or print anything).
            return self.valid

    def extroversion_prediction(self):

        """ Checks the users prediction vs. their actual quiz results, and attributes print statements to whether the user
        correctly or incorrectly predicted their quiz results.

        Parameters
        ----------
        none

        Returns
        -------
        self.valid : boolean
            If self.valid is false this means the user inputed an incorrect value. They are then prompted to rerun the code and
            only input integer values between 1-5. If true, the quiz continues as normal.

        """

        if self.user_prediction in self.prediction_answers:

            if self.user_prediction == self.compare_prediction:
                self.prediction_output = 'You guessed correctly!\nYour initial prediction matches your test results.'

            elif self.user_prediction != self.compare_prediction:
                self.prediction_output = 'Your initial prediction does not match your test results.'

        else:
            print ('Oops, looks like you entered an invalid input. Please re-run and enter a 1, 2, or 3.')

            self.valid = False  # When self.valid = False the rest of the methods will not execute (or print anything).
            return self.valid

    def quiz_results(self):

        #Makes sure self.valid = True and then prints out quiz results. This is the final print statement that the user sees.

        if self.valid == True:
            print('Your score is ' + str(self.score) + ' meaning you' + self.output + self.prediction_output)


cost = 4356
persons = int(input('aantal pesons'))
try:
    result = cost/persons
    if result < 0:
        print('Dit is een negatief getal dit is niet mogelijk')
    else:
        print(result)

except ZeroDivisionError:
    print('Je kan het niet delen door 0')
except ValueError:
    print('')
except:
    print('Fout ingevuld')