def num_safe_paths_to_castle(scouted):
    """
    Returns the number of different ways Mario can reach the castle safely. The
    answer should be zero if the castle cannot be reached safely.

    scouted:   A list of strings. Represents the tiles leading to and around the
               castle. The first element is always "start".
    """
    cst = find_castle(scouted)

    if scouted == ["start", "castle"]:
        return 1
    if len(scouted) > 2:
        if scouted[1] in ["turtle shell", "spike", "hole", "bush"] and scouted[2] in ["turtle shell", "spike", "hole","bush"] and scouted[0] != "mushroom":
            return 0
        elif scouted[1] in ["turtle shell", "spike", "hole", "bush"]:
            return 1 * num_safe_paths_to_castle(scouted[2:cst + 1])
        elif scouted[2] in ["turtle shell", "spike", "hole", "bush"]:
            return 1 * num_safe_paths_to_castle(scouted[1:cst + 1])
        elif scouted[0] == "mushroom":
            if not scouted[3] in ["turtle shell", "spike", "hole", "bush"]:
                return 1 * num_safe_paths_to_castle(scouted[1:cst + 1]) + 1 * num_safe_paths_to_castle(
                    scouted[2:cst + 1]) + 1 * num_safe_paths_to_castle(scouted[3:cst + 1])
            else:
                return 1 * num_safe_paths_to_castle(scouted[1:cst + 1]) + 1 * num_safe_paths_to_castle(
                    scouted[2:cst + 1])
        else:
            return 1 * num_safe_paths_to_castle(scouted[1:cst + 1]) + 1 * num_safe_paths_to_castle(scouted[2:cst + 1])
    return 1

def find_castle(way):
    for i in way:
        if i == "castle":
            return way.index(i)


###
#-------------------------------------------------------------------------------
# problem2.py
#-------------------------------------------------------------------------------
#
# Author:       Alwin Tareen
# Created:      Feb 04, 2022
# Execution:    python3 problem2.py
#
# This program determines the fixed monthly payment needed to pay off a debt.
#
##

def fixedPayoff(balance, annualInterestRate):
    monthlyInterestRate = annualInterestRate / 12.0
    initialBalance = balance
    fixedMonthlyPayment = 0
    while balance >= 0.0:
        balance = initialBalance
        fixedMonthlyPayment += 10
        for month in range(1, 13):
            monthlyUnpaidBalance = balance - fixedMonthlyPayment
            balance = monthlyUnpaidBalance + (monthlyInterestRate * monthlyUnpaidBalance)
    return f'Lowest payment: {fixedMonthlyPayment}'


import enum
import math
from dataclasses import dataclass
from typing import List

from sklearn.tree import DecisionTreeClassifier

from ..bagging_pu import BaggingClassifierPU
from ..transforms import CandidateTransform
from ..types import Candidate, LabelValue, PULabelType
from .transductive import TransductiveModel

@dataclass(frozen=True)
class ProbLabel:
    label: PULabelType
    p: float

@dataclass
class NodeExtractionModel(
    TransductiveModel[List[Candidate], List[PULabelType], List[ProbLabel]]
):
    n_estimators: int = 256
    max_features: float = 1.0
    max_samples: int = 100
    pos_thr: float = 0.5

    def learn(
        self, data: List[Candidate], labels: List[PULabelType]
    ) -> List[ProbLabel]:
        tf = CandidateTransform()
        # First of all we need to predict if it is a node.
        # Then we need to predict the relationship between them

        X = [tf.encode(c) for c in data]
        y = [1 if l == PULabelType.POS else 0 for l in labels]

        clf = DecisionTreeClassifier(max_features="auto")

        model = BaggingClassifierPU(
            base_estimator=clf,
            n_estimators=self.n_estimators,
            max_features=self.max_features,
            max_samples=self.max_samples,
        )
        model.fit(X, y)

        out = []
        for i, d in enumerate(model.oob_decision_function_[:, 1]):
            if labels[i] != PULabelType.UNK:
                out.append(ProbLabel(labels[i], d))
            else:
                lbl = PULabelType.POS if d > self.pos_thr else PULabelType.NEG
                out.append(ProbLabel(lbl, d))

        return out


# coding: utf-8
# pylint: disable=invalid-name

"Conse messages"

# start game
new_game = """新游戏开始！正在生成题目...正在上传音乐片段...15s之后发布选项..."""
guess_start = """听过这首歌吗？现在可以根据键盘的选项作答了!"""

game_already_running = """当前游戏正在进行，不能开启新的游戏。"""

# guess
game_not_running = """目前没有游戏正在进行，使用 /start 开启一个新游戏!"""
answer_wrong = """{0}猜错了！游戏继续进行。{0}不能继续再猜了"""
you_are_tried = """{}已经猜过了，没有机会再猜了"""

# over
game_over_lose = """游戏结束，正确答案是{}, 歌手{}"""
game_over_win = """{}猜对了！游戏结束, 正确答案是{}, 歌手是{}"""


import fitz
from . import *
from utils.filestoring import FileStore

@hr_app.route('/docops/<uid>',methods=["GET","POST","DELETE"])
@roles_xor('superuser','Hr Admin')
def documents(uid):
    doc_form=AddDocumentsForm()
    if request.method == "GET":
        user=db.session.execute(select(User).where(User.uid == uid)).scalars().unique().first()
        user_id=user.id
        employee=db.session.execute(select(Employee).where(Employee.user_id == int(user_id)).options(joinedload(Employee.user_files))).scalars().unique().first()
        documents=[EmployeeModelAll.from_orm(employee).dict()]
        return render_template('hrm/managedocuments.html', doc_form=doc_form,uid=uid,user_id=user_id,documents=documents,\
        name=user.name[0].name, delete_form=DeleteDocumentsForm())
    elif request.method == "POST":

        data=dict(doc_form.data)
        data.pop('csrf_token')
        data=[data]
        user_id=db.session.execute(select(User).where(User.uid == uid)).scalars().unique().first().id
        employee=db.session.execute(select(Employee).where(Employee.user_id == user_id)).scalars().unique().first()
        docsdir=current_app.config['UPLOAD_FOLDER']+'/'+employee.name+'/'
        fs=FileStore()
        try:

            check_exists=db.session.execute(select(HrDocuments).where(HrDocuments.employee_id == employee.id).where(HrDocuments.document_type == int(data[0]['document_type'].id) )).scalars().unique().all()
            if len(check_exists) > 0:
                db.session.execute(delete(HrDocuments).where(HrDocuments.employee_id == employee.id).where(HrDocuments.document_type == int(data[0]['document_type'].id) ))

            datapic=[ (docsdir+val['document_type'].name+'/',val['document_file'],val['document_type'],\
                secure_filename(f"{val['document_type']}_+{str(current_user.serialized['uid'])+'_'+str(randint(1,1000000))}")) \
                for val in data if val['document_file'].filename.rsplit('.', 1)[1].lower() != "pdf"]
            dbdatapic=[HrDocuments(file_name=docsdir+x[2].name+"/"+x[3]+".jpg",employee_id=employee.id,document_type=x[2].id) for x in datapic]

            #pdf data
            datapdf=[ (docsdir+val['document_type'].name+'/',val['document_file'],val['document_type'],\
                secure_filename(f"{val['document_type']}_+{str(current_user.serialized['uid'])+'_'+str(randint(1,1000000))}")) \
                for val in data if val['document_file'].filename.rsplit('.', 1)[1].lower() == "pdf"]

            dbdatapdf=[]
            for x in datapdf:
                if not os.path.exists(x[0]):
                    os.makedirs(x[0])
                x[1].save(x[0]+x[3])
                for i in range(len(fitz.open(x[0]+x[3]))):
                    dbdatapdf.append(HrDocuments(file_name=docsdir+x[2].name+"/"+x[3]+f'-{i}.jpg',employee_id=employee.id,document_type=x[2].id))

            db.session.add_all(dbdatapic+dbdatapdf)
            db.session.commit()
            for x in datapic:
                fs.store_pic(x[0],x[1],x[3])
            for x in datapdf:
                fs.store_file(x[0],x[3])

            flash("succesfull file update")
            return redirect(url_for('hrapp.documents',uid=uid))
        except Exception as e:
            fs.clean_pdf()
            fs.clean_pic()
            current_app.logger.error(str(e),exc_info=True)
            db.session.rollback()
            flash("Documents Update didnot complete successfully, please try again")
            return redirect(url_for('hrapp.documents',uid=uid))
        finally:
            db.session.close()
    elif request.method == "DELETE":
        try:
            data=loads(request.data)
            document_type=db.session.execute(select(HrFileType).where(HrFileType.name == data['document_type'])).scalars().unique().first().id
            dt=db.session.execute(delete(HrDocuments).where(HrDocuments.employee_id ==int(data['employee_id'])).where(HrDocuments.document_type == document_type))
            db.session.commit()
            return { "Message" : "Deleting Object Sucessful"},status.HTTP_202_ACCEPTED
        except Exception as e:
            current_app.logger.error(str(e),exc_info=True)
            db.session.rollback()
            return { "Message" : "Something Unexpected happened"},status.HTTP_500_INTERNAL_SERVER_ERROR
        finally:
            db.session.close()
    else:

        return { "Message" : "Method is not allowed"},status.HTTP_405_METHOD_NOT_ALLOWED


from turtle import Screen
from player import Player
from scoreboard import Scoreboard
from cars import Car
from random import randint
import time
screen = Screen()
screen.tracer(0)
screen.setup(width=600, height=600)
screen.title("Crossing Turtle")

player1 = Player()
scoreboard = Scoreboard()

screen.listen()
screen.onkey(fun=player1.move, key="w")

movement_increment = 0.5
time_sleep = 0.1
game_on = True
car_list = []

while game_on:
    chance = randint(1, 6)
    time.sleep(time_sleep)
    screen.update()
    if chance == 1:
        car = Car()
        car_list.append(car)
    for car in car_list:
        if player1.distance(car) <= 22:
            scoreboard.game_over()
            game_on = False

    if player1.is_at_finish_line():
        scoreboard.increase_level()
        time_sleep *= movement_increment

    for car in car_list:
        if car.xcor() > -350:
            car.move_car()

screen.exitonclick()


# This program gives naive life advice.

print('Answer "yes" or "no".')
happy_status = input('Are you happy?')
if happy_status == 'yes':
    happy = True
elif happy_status == 'no':
    happy = False
else:
    print('I do not understand!')

rich_status = input('Are you rich?')
if rich_status == 'yes':
    rich = True
elif rich_status == 'no':
    rich = False
else:
    print('I do not understand!')

if rich and happy:
    # rich and at the same time.
    print('Congratulations!')
elif rich:
    # rich but not "rich and happy",
    #so must be only rich.
    print('Try to smile more.')
elif happy:
    # must be only happy.
    print('Try to spend less.')
else:
    # neither happy nor rich.
    print("I'm sorry for you.")


import numpy as np
import pandas as pd

from utils.read_data import read_data
from utils.plot import plot_var
from utils.var import var

transform = ["RGDP", "RGOV", "RCONS", "RINV"]
to = ["Y", "G", "CONS", "INV"]

name_map = dict(zip(transform, to))

def parse_data(df: pd.DataFrame)->pd.DataFrame:

    new_df = df.copy()
    pop = new_df["POP"]

    for transf_var in transform:
        trans_data = np.log(new_df[transf_var] / pop)
        new_df[name_map[transf_var]] = trans_data

    return new_df.drop(transform, axis = 1)

if __name__ == "__main__":
    df = read_data("data/ramey.xls")
    parsed_df = parse_data(df)["1960Q1":]

    restr_var = ["G", "T", "Y"]
    restr_df = parsed_df[restr_var]
    res = var(restr_df, trend="ctt", lags = 4)
    plot_var(res, impulse="G", folder="ramey/base")

    aug_var = restr_var + ["CONS", "INV"]
    aug_df = parsed_df[aug_var]
    res = var(aug_df, trend="ctt", lags = 4)
    plot_var(res, impulse="G", folder="ramey/aug")

    war_var = ["WAR"] + aug_var
    war_df = parsed_df[war_var]
    res = var(war_df, trend="ctt", lags = 4)
    plot_var(res, impulse="WAR", folder="ramey/war")

    mil_var = ["MIL"] + aug_var
    mil_df = parsed_df[mil_var]
    res = var(mil_df, trend="ctt", lags = 4)
    plot_var(res, impulse="MIL", folder="ramey/mil")


""" Utilities used in building example surfaces. """

from itertools import count as naturals
from math import inf
from typing import Any, Callable, Iterable, Optional, Tuple
import re

def integers(start: Optional[int] = None, stop: Optional[int] = None) -> Iterable[int]:
    """Return an iterable that yields all of the integers."""

    if start is not None and stop is not None:
        return range(start, stop)
    elif start is None and stop is not None:
        return naturals(stop, -1)
    elif start is not None and stop is None:
        return naturals(start)

    return (z for n in naturals() for z in (n, ~n))

def extract_curve_and_test(curve_names: str, name: str) -> Tuple[str, Callable[[Any], bool]]:
    """Return a curve and a test to apply for which of it's components to twist."""

    twist_match = re.match(rf"(?P<curve>[{curve_names}])_(?P<n>-?\d+)$", name)
    twist_index_match = re.match(rf"(?P<curve>[{curve_names}])\[ *(?P<n>-?\d+) *\]$", name)
    twist_slice_match = re.match(rf"(?P<curve>[{curve_names}])(\[ *(?P<start>-?\d*) *: *(?P<stop>-?\d*) *(: *(?P<step>-?\d*) *)?\])?$", name)
    twist_expr_match = re.match(rf"(?P<curve>[{curve_names}])\{{(?P<expr>.*)\}}$", name)

    if twist_match is not None:
        parameters = twist_match.groupdict()
        curve = parameters["curve"]
        n = int(parameters["n"])
        test = lambda edge: edge == n
    elif twist_index_match is not None:
        parameters = twist_index_match.groupdict()
        curve = parameters["curve"]
        n = int(parameters["n"])
        test = lambda edge: edge == n
    elif twist_slice_match is not None:
        parameters = twist_slice_match.groupdict()
        curve = parameters["curve"]
        start = int(parameters["start"]) if parameters["start"] else -inf
        stop = int(parameters["stop"]) if parameters["stop"] else inf
        step = int(parameters["step"]) if parameters["step"] else 1
        test = lambda edge: start <= edge < stop and (edge % step == (0 if start == -inf else start % step))
    elif twist_expr_match is not None:
        parameters = twist_expr_match.groupdict()
        curve = parameters["curve"]
        test = lambda n: eval(parameters["expr"], {"n": n, **globals()})  # pylint: disable=eval-used
    else:
        raise ValueError(f"Unknown mapping class {name}")

    return curve, test


# coding: utf-8

import os
import pandas as pd

from graph_tool import load_graph
from glob import glob
from tqdm import tqdm
from joblib import Parallel, delayed
from itertools import product

from eval_helpers import eval_map
from experiment import one_run
from helpers import is_processed, makedir_if_not_there

n_jobs = 4
n_sample = 1000

methods = ['our', 'pagerank', 'min-steiner-tree']

cascade_models = ['si', 'ic']

graphs = ['fb-messages', 'email-univ', 'infectious', 'lattice-1024', 'grqc']

# a batch of settings to iterate through
settings = [
    {'graphs': graphs,
     'obs_fractions': ["0.1", "0.2", "0.3", "0.4", "0.5", "0.6", "0.7", "0.8", "0.9"],
     'cascade_fractions': ["0.1"]},
    {'graphs': graphs,
     'obs_fractions': ["0.5"],
     'cascade_fractions': ["0.1", "0.2", "0.3", "0.4", "0.5"]}
]

for setting in settings:
    graphs, obs_fractions, cascade_fractions = setting['graphs'], \
                                               setting['obs_fractions'], \
                                               setting['cascade_fractions']
    for graph, cascade_model, obs_fraction, cascade_fraction, method \
            in product(
                graphs, cascade_models, obs_fractions, cascade_fractions, methods
            ):

        if cascade_model == 'ic':
            # use reversed graph
            suffix = "uniform"
            graph_path = 'data/{}/graph_weighted_{}.gt'.format(graph, suffix + '_rev')
        else:
            suffix = "0.1"
            graph_path = 'data/{}/graph_weighted_{}.gt'.format(graph, suffix)

        g = load_graph(graph_path)
        edge_weights = g.edge_properties['weights']

        dataset_id = "{}-m{}-s{}-o{}-omuniform".format(graph, cascade_model, cascade_fraction, obs_fraction)
        print('method', method)
        print('dataset_id', dataset_id)

        input_dir = 'cascade/{}/'.format(dataset_id)
        output_dir = 'output/{}/{}/'.format(method, dataset_id)
        eval_result_path = 'eval/{}/{}.pkl'.format(method, dataset_id)

        makedir_if_not_there(output_dir)
        makedir_if_not_there(os.path.dirname(eval_result_path))

        rows = Parallel(n_jobs=n_jobs)(

            delayed(one_run)(
                g, edge_weights, input_path, output_dir, method,
                n_sample=n_sample)

            for input_path in tqdm(glob(input_dir + '*.pkl'))
            if not is_processed(input_path, output_dir))

        # assert len(rows) > 0, 'nothing calculated'

        scores = eval_map(input_dir, output_dir)

        summ = pd.Series(scores).describe()
        print(summ)
        summ.to_pickle(eval_result_path)


from django.conf.urls import include, url

from rest_framework import routers

from teams import views

app_name = 'teams'

router = routers.DefaultRouter()
router.register(r'teams', views.TeamListViewSet)

urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^invites/$', views.UserInviteListView.as_view(), name='invite-list'),
    url(r'^invites/(?P<pk>[0-9]+)/$', views.UserInviteDetailView.as_view(), name='invite-detail'),      # noqa
    url(r'^members/(?P<pk>[0-9]+)/$', views.TeamMemberDetailView.as_view(), name='member-detail'),      # noqa
    url(r'^teams/(?P<pk>[0-9]+)/invites/$', views.TeamInviteListView.as_view(), name='team-invites'),   # noqa
]


from db.database import execute_query, fetch_data
from model.round import Round, SeatWind

def create_round(game_id: int,
                 round_number: int,
                 round_wind: str,
                 dealer_id: int,
                 wall_id: int) -> Round:
    query = (
        "INSERT INTO round (game_id, round_number, round_wind, dealer_id, "
        "wall_id, end_time) "
        "VALUES (%s, %s, %s, %s, %s, %s) "
        "RETURNING id, game_id, round_number, round_wind, dealer_id"
    )
    result = execute_query(query,
                           (game_id, round_number, round_wind, dealer_id,
                            wall_id, None),
                           ("id", "game_id", "round_number", "round_wind",
                            "dealer_id"))

    if result:
        id = result["id"]
        game_id = result["game_id"]
        round_number = result["round_number"]
        round_wind = result["round_wind"]
        dealer_id = result["dealer_id"]

        round = Round(id, game_id, round_number,
                      round_wind, dealer_id, wall_id)
        return round
    else:
        return None

def set_seat_wind(round_id: int,
                  player_id: int,
                  wind: str) -> SeatWind:
    query = (
        "INSERT INTO seat_wind (round_id, player_id, wind) "
        "VALUES (%s, %s, %s) "
        "RETURNING id, round_id, player_id, wind "
    )
    result = execute_query(query,
                           (round_id, player_id, wind),
                           ("id", "round_id", "player_id", "wind"))

    if result:
        id = result["id"]
        round_id = result["round_id"]
        player_id = result["player_id"]
        wind = result["wind"]

        seat_wind = SeatWind(id, round_id, player_id, wind)
        return seat_wind
    else:
        return None

def fetch_wind_by_player_id(round_id: int, player_id: int) -> str:
    query = (
        "SELECT sw.wind "
        "FROM seat_wind sw "
        "WHERE sw.round_id = %s AND sw.player_id = %s"
    )
    result = fetch_data(query, (round_id, player_id))

    if result:
        wind = result[0][0]
        return wind
    else:
        return None

def fetch_player_id_by_wind(round_id: int, wind: str) -> int:
    query = (
        "SELECT sw.player_id "
        "FROM seat_wind sw "
        "WHERE sw.round_id = %s AND sw.wind = %s"
    )
    result = fetch_data(query, (round_id, wind))

    if result:
        player_id = result[0][0]
        return player_id
    else:
        return None

def fetch_round_count(game_id: int) -> int:
    query = (
        "SELECT COUNT(*) "
        "FROM round "
        "WHERE game_id = %s"
    )
    result = fetch_data(query, (game_id,))

    if result:
        return result[0][0]
    else:
        return None

def fetch_round(round_id: int) -> Round:
    query = (
        "SELECT id, game_id, round_number, round_wind, dealer_id, wall_id "
        "FROM round "
        "WHERE id = %s "
        "LIMIT 1"
    )
    result = fetch_data(query, (round_id,))

    if result:
        id, game_id, round_number, round_wind, dealer_id, wall_id = result[0]
        round = Round(id, game_id, round_number,
                      round_wind, dealer_id, wall_id)
        return round
    else:
        return None

def fetch_previous_round_id(game_id: int) -> int:
    query = (
        "SELECT id "
        "FROM round "
        "WHERE game_id = %s "
        "ORDER BY start_time DESC "
        "LIMIT 2"
    )

    result = fetch_data(query, (game_id,))

    if len(result) >= 2:
        return result[1][0]
    else:
        return None

def fetch_round_id_by_room_id(room_id: int) -> int:
    query = (
        "SELECT id "
        "FROM round "
        "WHERE game_id = (SELECT id FROM game WHERE room_id = %s) "
        "ORDER BY id DESC "
        "LIMIT 1"
    )
    result = fetch_data(query, (room_id, ))

    if result:
        round_id = result[0][0]
        return round_id
    else:
        return None

def fetch_current_player_id(round_id: int) -> int:
    query = (
        "SELECT player_id "
        "FROM ("
        "   SELECT call_player_id AS player_id, MAX(call_time) AS action_time "
        "   FROM call "
        "   WHERE round_id = %s "
        "   GROUP BY call_player_id "
        "   UNION ALL "
        "   SELECT player_id, MAX(draw_time) AS action_time "
        "   FROM draw "
        "   WHERE round_id = %s "
        "   GROUP BY player_id "
        "   UNION ALL "
        "   SELECT player_id, MAX(discard_time) AS action_time "
        "   FROM discard "
        "   WHERE round_id = %s "
        "   GROUP BY player_id "
        "   UNION ALL "
        "   SELECT player_id, MAX(agari_time) AS action_time "
        "   FROM agari "
        "   WHERE round_id = %s "
        "   GROUP BY player_id "
        ") AS all_actions "
        "ORDER BY action_time DESC "
        "LIMIT 1"
    )

    result = fetch_data(query, (round_id, round_id, round_id, round_id))

    if result:
        return result[0][0]
    else:
        return None


import statistics

import discord
from discord.ext import commands, menus
from discord.ext.commands.cooldowns import BucketType
from samp_client.client import SampClient

from atom.utils import executor

@executor()
def get_samp_data(ip: str, port: int):
    with SampClient(address=ip, port=port) as client:
        players = client.get_server_clients_detailed()
        server_info = client.get_server_info()
        return players, server_info

class SampPlayers(menus.ListPageSource):
    def __init__(self, data):
        super().__init__(data, per_page=15)

    async def format_page(self, menu, entries):
        offset = menu.current_page * self.per_page
        embed = discord.Embed(
            title="Samp Players",
            description="\n".join(f"{i}. {v.name}  `ping {v.ping}ms` " for i, v in enumerate(entries, start=offset)),
            color=0x2F3136,
        )
        return embed

class SampUtils(
    commands.Cog,
    name="Samp",
    description="Module for getting player info from samp servers",
):
    def __init__(self, bot):
        self.bot = bot
        self.emoji = 837198453431074846

    @commands.group(invoke_without_command=True)
    async def samp(self, ctx):
        if not ctx.invoked_subcommand:
            await ctx.reply(
                embed=self.bot.embed(
                    description=f"Use `{ctx.prefix}samp players` for player info \n Use `{ctx.prefix}samp info` for general info",
                    colorful=False,
                )
            )

    async def get_samp_ip_port(self, id):
        if await self.bot.cache.exists(id):
            gdata = await self.bot.cache.get(id)
            if not gdata.samp["samp_ip"]:
                async with self.bot.db.acquire() as conn:
                    async with conn.transaction():
                        gdata = await conn.fetchrow(
                            "SELECT samp_ip,samp_port FROM guilds INNER JOIN samp ON guilds.id = samp.id WHERE gid = $1;",
                            id,
                        )
                        gdata = gdata._replace(samp_port=gdata["samp_port"], samp_ip=gdata["samp_ip"])
                        await self.bot.cache.set(id, gdata)
        return gdata.samp

    @commands.cooldown(1, 3, BucketType.guild)
    @samp.command()
    async def info(self, ctx):
        async with ctx.typing():
            gdata = await self.get_samp_ip_port(ctx.guild.id)
            if not gdata:
                return await ctx.reply(
                    embed=self.bot.embed(
                        description=f"Samp module is not configured.. Pls do `{ctx.prefix}samp set ip port`",
                        colorful=False,
                    )
                )
            try:
                results = await get_samp_data(gdata["samp_ip"], gdata["samp_port"])
            except Exception as e:
                await ctx.send(e)
                return await ctx.reply(embed=self.bot.embed(description="Seems like the server is down!", colorful=False))
            embed = self.bot.embed(
                title="Samp Status",
                description=f"```{results[1].hostname}```",
                colorful=False,
            )
            embed.add_field(name="Players", value=f"{len(results[0])} Players Online")
            embed.add_field(
                name="Average Ping",
                value=f"{int(statistics.mean([a.ping for a in results[0]]))} ms",
            )
            embed.set_footer(text="Shahad Uyir")
            await ctx.reply(embed=embed)

    @commands.cooldown(1, 3, BucketType.guild)
    @samp.command()
    async def players(self, ctx):
        async with ctx.typing():
            gdata = await self.get_samp_ip_port(ctx.guild.id)
            if not gdata:
                return await ctx.reply(
                    embed=self.bot.embed(
                        description=f"Samp module is not configured.. Pls do `{ctx.prefix}samp set ip port`",
                        colorful=False,
                    )
                )
            try:
                results = await get_samp_data(gdata["samp_ip"], gdata["samp_port"])
            except Exception as e:
                return await ctx.reply(embed=self.bot.embed(description="Seems like the server is down!", colorful=False))
            players = [a for a in results[0]]
            smenus = menus.MenuPages(source=SampPlayers(players), clear_reactions_after=True)
            await smenus.start(ctx)

def setup(bot):
    bot.add_cog(SampUtils(bot))


from enum import Enum
from typing import Union, List, Optional, Tuple

from rich.color import Color, blend_rgb
from rich.console import ConsoleOptions, RenderResult, Console
from rich.measure import Measurement
from rich.segment import Segment
from rich.style import Style

from .cell import PlotCellStyle, PlotCellRenderer

class OneLinePlotStyle(Enum):
    """Styles for one-line plots.

    Args:
        cell_style (PlotCellStyle): One of the plot styles defined in PlotCellStyle.
    """

    LINE = PlotCellStyle.LINE_V
    """Style for line plots."""
    AREA = PlotCellStyle.BLOCK_V
    """Style for area plots"""
    HORIZON = PlotCellStyle.BLOCK_V
    """Style for horizon plots."""
    SHADE = PlotCellStyle.SHADE
    """Style for shaded plots."""

    def __new__(cls, *args, **kwargs):
        value = len(cls.__members__) + 1
        obj = object.__new__(cls)
        obj._value_ = value
        return obj

    def __init__(self, cell_style: PlotCellStyle):
        self.cell_style = cell_style

class Sparkline:
    """A console renderable to draw a Sparkline.

    Args:
        values (List[float]): Values displayed in the Sparkline.
        value_range (Tuple[float, float], optional): Range of values displayed in the Sparkline.
        color (Union[Color, str]): Color of the Sparkline.
        bgcolor (Union[Color, str]): Background color of the Sparkline.
        plot_style (OneLinePlotStyle): One of the plot styles defined in OneLinePlotStyle.
        end (str): End character. Defaults to "\n".
    """

    def __init__(
        self,
        values: List[float],
        value_range: Optional[Tuple[float, float]] = None,
        color: Union[Color, str] = "default",
        bgcolor: Union[Color, str] = "default",
        plot_style: OneLinePlotStyle = OneLinePlotStyle.AREA,
        end: str = "\n",
    ):
        self.values = values
        self.value_range = value_range
        self.style = Style(color=color, bgcolor=bgcolor)
        self.plot_style = plot_style
        self.end = end

    def __rich_console__(
        self, console: Console, options: ConsoleOptions
    ) -> RenderResult:
        value_range = self.value_range or (min(self.values), max(self.values))
        cell_style = self.plot_style.cell_style

        if self.plot_style == OneLinePlotStyle.HORIZON:
            lower, upper = value_range
            mid = lower + (upper - lower) / 2
            mid_shade = Color.from_triplet(
                blend_rgb(
                    self.style.bgcolor.get_truecolor(),
                    self.style.color.get_truecolor(),
                    0.5,
                )
            )
            lower_style = Style(bgcolor=self.style.bgcolor, color=mid_shade)
            upper_style = Style(bgcolor=mid_shade, color=self.style.color)
            for value in self.values:
                cell = PlotCellRenderer.render(
                    value=value,
                    value_range=(lower, mid) if value < mid else (mid, upper),
                    cell_style=cell_style,
                )
                yield Segment(cell, style=lower_style if value < mid else upper_style)
        else:
            cells = ""
            for value in self.values:
                cells += PlotCellRenderer.render(
                    value=value, value_range=value_range, cell_style=cell_style
                )
            yield Segment(cells, self.style)
        yield Segment(self.end)

    def __rich_measure__(
        self, console: Console, options: ConsoleOptions
    ) -> Measurement:
        width = len(self.values)
        return Measurement(width, width)

if __name__ == "__main__":
    from math import sin, pi
    from rich.table import Table

    WIDTH_CONSOLE = 120

    def wave(
        num: int, offset: int = 0, seed: int = 0, scale: float = 1.0
    ) -> List[float]:
        result = [sin(2 * pi * (d + offset) / 10) for d in range(num)]
        if seed > 0:  # overlay second wave
            result = [
                val * sin(2 * pi * d / (40 + seed * 5)) * scale
                for d, val in enumerate(result)
            ]
        return result

    # Sparkline Table Example

    data = wave(22, 0)

    table = Table()
    table.add_column("Plot Style")
    for style in OneLinePlotStyle:
        table.add_column(style.name)
    lines = [
        Sparkline(
            values=data,
            color="purple",
            value_range=(-1.5, 1.5),
            plot_style=style,
        )
        for style in OneLinePlotStyle
    ]
    table.add_row("Sparkline", *lines)

    console = Console(record=True, width=WIDTH_CONSOLE)
    console.print()
    console.print(table, justify="center")
    console.print()


"""
    SpectraVue: a Python Dash application used to visualize and analyze wearable spectroscopic data.

    Tarek Hamid, hamidtarek3@gmail.com
"""

import dash
from dash import dcc, html
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
import dash_player as dp
from dash import callback_context

import pandas as pd

import matplotlib
matplotlib.use('agg')
import plotly.graph_objects as go
import plotly.io as pio

import base64

import io
import tools

# Imports and Title
app = dash.Dash(
    external_stylesheets=[
       dbc.themes.BOOTSTRAP,
       dbc.icons.BOOTSTRAP,
       'https://fonts.googleapis.com/css?family=Open+Sans&display=swap'],
    suppress_callback_exceptions=True,
)

app.title = "SpectraVue"

# Header
header = html.Header(
    dbc.Container(
        dbc.Row(
            [
                dbc.Col(
                    html.Img(src=app.get_asset_url("logo.png"), height="100px", className="me-3"),
                    width=9,
                    align="center",
                ),
                dbc.Col(
                    html.Div(
                        [
                           dbc.Button(
                              "Tutorial",
                              href="",
                              color="dark",
                              className="me-2 header-button",
                              external_link=True,
                              outline=True
                           ),
                            dbc.Button(
                              "GitHub",
                              href="https://github.com/tarek-hamid/SpectraVue",
                              target="_blank",
                              color="dark",
                              className="me-2 header-button",
                              external_link=True,
                              outline=True
                           ),
                           dbc.Button(
                              "Contact",
                              href="mailto:hamidtarek3@gmail.com",
                              color="dark",
                              className="header-button",
                              external_link=True,
                              outline=True
                           )
                        ],
                        className="d-flex justify-content-end",
                    ),
                    width=3,
                    align="center",
                ),
            ],
            align="center",
            className="py-3",
        ),
        fluid=True,
        className="bg-light",
    )
)

# User Inputs and Buttons
inputs = dbc.Tabs(
    [
        dbc.Tab(
            [
               html.P('The spectrometer mode is used to visualize raw spectrometer data in a static or animated graph.', className='tab-text'),
                dbc.Row([
                    dbc.Col(
                        dcc.Upload(
                            id="upload-data-spectrometer-spec-mode",
                            children=html.Div(
                                dbc.Button(
                                    "Upload Spectrometer Data",
                                    id="upload-button-spectrometer",
                                    color="light",
                                    className="tab-button",
                                ),
                            ),
                            multiple=False,
                            style={"width": "100%"},
                        ),
                        className="mb-3",
                    ),
                    html.Div(id='output-data-upload-spectrometer-spec-mode'),
            ]),
                html.Br(),
                dbc.Row(
                    [
                        dbc.Col(
                            html.Div("Output:", className="label-text"),
                            className="d-flex justify-content-center align-items-center",
                            width=3
                        ),
                        dbc.Col(
                            dcc.Dropdown(
                                id='dropdown',
                                options=[
                                    {'label': 'Static', 'value': 'static'},
                                    {'label': 'Animation', 'value': 'animation'}
                                ],
                                value='static',
                                clearable=False,
                                style={'width': '100%'}
                            ),
                            width=7,
                            className="d-flex justify-content-center align-items-center"
                        ),
                    ],
                    className="d-flex justify-content-center align-items-center"
                ),
                html.Br(),
                html.Br(),
                dbc.Row(
                    dbc.Col(
                        dbc.Button(
                            "Generate",
                            color="light",
                            id="generate-button-spectrometer",
                            className="tab-button generate-button",
                        ),
                    ),
                )
            ],
            label="Spectrometer",
        ),
        dbc.Tab(
            [
                html.P('The biomarker mode is used to visualize spectrometer data in comparison with a clinical biomarker.', className='tab-text'),
                dbc.Row([
                    dbc.Col(
                        dcc.Upload(
                            id="upload-data-spectrometer-bio-mode",
                            children=html.Div(
                                dbc.Button(
                                    "Upload Spectrometer + Biomarker Data",
                                    id="upload-button-spectrometer-bio",
                                    color="light",
                                    className="tab-button",
                                ),
                            ),
                            multiple=False,
                            style={"width": "100%"},
                        )
                    ),
                    html.Div(id='output-data-upload-spectrometer-bio-mode'),
                ]),
                html.Br(),
                html.Br(),
                dbc.Row(
                    dbc.Col(
                        dbc.Button(
                            "Generate",
                            id="generate-button-biomarker",
                            color="light",
                            className="tab-button generate-button",
                        ),
                    ),
                )
            ],
            label="Spectro + Biomarker",
        ),
    ],
    className="mb-3",
)

# Graph
graph = dbc.Row([
    dbc.Col(
        dcc.Graph(
            id="graph",
            figure={},
            style={
                "height": "600px",
                "width": "100%",
            }
        ),
        align="center",
    )
], justify="center")

# Layout
app.layout = dbc.Container(
    [
        header,
        html.Br(),
        dbc.Row(
            [
                dbc.Col(inputs, width=3),
                dbc.Col(
                    html.Div(id="graph-container", style={"height": "600px", "width": "100%"}),
                    width=9,
                ),
            ],
        ),
        # Store user uploaded data
        dcc.Store(id="data-store-spectrometer", storage_type="session"),
        dcc.Store(id="data-store-combined", storage_type="session"),
        dcc.Store(id="filename-spectrometer", storage_type="session"),
        dcc.Store(id="filename-combined", storage_type="session"),
    ],
    fluid=True,
)

# Callbacks

# Display the uploaded file name (Spectrometer Mode)
@app.callback(
    Output('output-data-upload-spectrometer-spec-mode', 'children'),
    Input('upload-data-spectrometer-spec-mode', 'filename'),
)
def update_output_spec_mode(filename):
    if filename is not None:
        return html.Div([
            html.B('Uploaded file: '), html.P(filename)
        ], className='file-name')
    else:
        return dash.no_update

# Display the uploaded file name (Biomarker Mode)
@app.callback(
    Output('output-data-upload-spectrometer-bio-mode', 'children'),
    Input('upload-data-spectrometer-bio-mode', 'filename'),
)
def update_output_bio_mode(filename_bio):
    if filename_bio is not None:
        return [html.Div(),
            html.Div([ html.B('Uploaded biomarker file: '), html.P(filename_bio)], className='file-name')]
    else:
        raise PreventUpdate

# Callback to store the uploaded file for spectrometer and biomarker data in both modes
@app.callback(
    [
        Output('filename-spectrometer', 'data'),
        Output('data-store-spectrometer', 'data'),
        Output('filename-combined', 'data'),
        Output('data-store-combined', 'data'),
    ],
    [
        Input('upload-data-spectrometer-spec-mode', 'filename'),
        Input('upload-data-spectrometer-spec-mode', 'contents'),
        Input('upload-data-spectrometer-bio-mode', 'filename'),
        Input('upload-data-spectrometer-bio-mode', 'contents'),
    ]
)
def update_output_spectrometer_and_biomarker(filename_spec, contents_spec, filename_combined, contents_combined):
    outputs = [dash.no_update]*4
    if filename_spec is not None and contents_spec is not None:
        outputs[0], outputs[1] = decode_content_and_store(filename_spec, contents_spec)
    if filename_combined is not None and contents_combined is not None:
        outputs[2], outputs[3] = decode_content_and_store(filename_combined, contents_combined)

    return outputs

def decode_content_and_store(filename, contents):
    '''
        Helper method used to decode uploaded file content and store contents in data store.
    '''
    content_type, content_string = contents.split(',')
    decoded = base64.b64decode(content_string)

    if content_type == 'data:text/plain;base64':
        data = decoded.decode('utf-8')
        return filename, data
    elif content_type == 'data:text/csv;base64':
        df = pd.read_csv(io.StringIO(decoded.decode('utf-8')))
        return filename, df.to_json()
    else:
        raise PreventUpdate

# Callback to update graph container based on user input
@app.callback(
    Output('graph-container', 'children'),
    Input('generate-button-spectrometer', 'n_clicks'),
    Input('generate-button-biomarker', 'n_clicks'),
    State('filename-spectrometer', 'data'),
    State('data-store-spectrometer', 'data'),
    State('data-store-combined', 'data'),
    State('dropdown', 'value'),
)
def generate_graph_spec(spec_clicks, biomarker_clicks, filename, spec_data, combined_data, output):

    ctx = callback_context
    prop_id = ctx.triggered[0]['prop_id']

    if 'generate-button-spectrometer' not in prop_id and 'generate-button-biomarker' not in prop_id:
        # Return a blank 3D plot with axis planes
        fig = go.Figure(
            data=[go.Scatter3d(x=[0], y=[0], z=[0], mode='markers', marker=dict(size=0))],
            layout=go.Layout(scene=dict(xaxis=dict(showgrid=False, zeroline=False),
                                        yaxis=dict(showgrid=False, zeroline=False),
                                        zaxis=dict(showgrid=False, zeroline=False)))
        )
        return dcc.Graph(figure=fig, style={"height": "600px", "width": "100%"})
    elif 'generate-button-spectrometer' in prop_id:
        if filename.endswith('.csv'):
            processed_df = tools.process_spec_csv(spec_data)
        elif filename.endswith('.txt'):
            processed_df = tools.process_spec_txt(spec_data)

        if output == 'static':
            fig = tools.static_graph_output(processed_df)
            return dcc.Graph(figure=fig, style={"height": "600px", "width": "100%"})

        elif output == 'animation':
            video_filename = tools.animation_graph_output(processed_df)
            return dp.DashPlayer(
                id="player",
                url=f"/{video_filename}",
                controls=True,
                width="100%",
                height="600px",
            )
    else:
        processed_df = tools.process_spec_csv(combined_data)
        video_filename = tools.animation_graph_biomarker(processed_df)
        return dp.DashPlayer(
                id="player",
                url=f"/{video_filename}",
                controls=True,
                width="100%",
                height="600px",
            )

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


import time

from appium import webdriver
from selenium.webdriver.support.wait import WebDriverWait

desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = '5.1'
desired_caps['deviceName'] = '192.168.56.101:5555'
desired_caps['appPackage'] = 'com.cyanogenmod.filemanager'
desired_caps['appActivity'] = '.activities.NavigationActivity'
desired_caps['automationName'] = 'Uiautomator2'
# desired_caps['noReset'] = True

driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)

time.sleep(2)

driver.press_keycode(4)
time.sleep(1)
driver.press_keycode(4)
time.sleep(1)
driver.press_keycode(4)

# print(WebDriverWait(driver, 10, 1).until(lambda x: x.find_element_by_xpath("//*[contains(@text,'再次点击')]")).text)

print(driver.find_element_by_xpath("//*[@text='再次点击即可退出.']").text)

time.sleep(5)


import math
class maths:
	def add(x, y):
		return x + y
	def subtract(x, y):
		return x - y
	def multiply(x, y):
		return x * y
	def divide(x, y):
		return x / y
	def mod(x,y):
                return x % y
	def pow(x,y):
		return x**2
		return y**2
	def floor(x,y):
		return x // y
	def sqr(x,y):
		return math.sqrt(x)
		return math.sqrt(y)
	def fact(x,y):
		return math.factorial(x)
		return math.factorial(y)
	def log(x,y):
		return math.log(x)
		return math.log(y)
	print("Select operation.")
	print("1.Add")
	print("2.Subtract")
	print("3.Multiply")
	print("4.Divide")
	print("5.modules")
	print("6.power")
	print("7.floor division")
	print("8.square root")
	print("9.factorial")
	print("10.logs")
	while True:
		choice = input("Enter choice(1/2/3/4/5/6/7/8/9/10): ")
		if choice in ('1', '2', '3', '4','5','6','7','8','9','10'):
			num1 = int(input("Enter first number: "))
			num2 = int(input("Enter second number: "))
		if choice == '1':
			print("addition of",num1,"and",num2,"is", add(num1, num2))
		elif choice == '2':
			print("subtraction of",num1,"and",num2,"is", subtract(num1, num2))
		elif choice == '3':
			print("multiplication of",num1,"and",num2,"is", multiply(num1, num2))
		elif choice == '4':
			print("division of",num1,"and",num2,"is", divide(num1, num2))
		elif choice == '5':
			print("modulus of ",num1,"and",num2,"is", mod(num1, num2))
		elif choice == '6':
			print("power of",num1,"and",num2,"is", pow(num1, num2))
		elif choice == '7':
			print("floor division of",num1,"and",num2,"is", floor(num1, num2))
		elif choice == '8':
                        print("square root of",num1,"and",num2,"is", sqr(num1,num2))
		elif choice == '9':
                        print("factorial of",num1, "and",num2,"is", fact(num1, num2))
		elif choice == '10':
                        print("logs of ",num1,"and",num2,"is", log(num1,num2))
		else:
                        print("Invalid choice")

		check = input("Do you want to continue  ? (yes/no): ")
		if check == "no":
			break
		else:
			print("Invalid Input")


import fragmenter
from openeye import oechem
import pandas as pd
import json
import socket
import getpass

validation_set_input = pd.read_csv('../filter/validation_set/drugbank_filtered.csv')

# Clean up names = remove space because it causes bash scripts to crash
for name in validation_set_input['name']:
    if ' ' in name:
        name_split = name.split(' ')
        new_name = ''
        for n in name_split[:-1]:
            new_name += n
            new_name += '_'
        new_name += name_split[-1]
        validation_set_input.replace(to_replace=name, value=new_name, inplace=True)
    if name[0].isdigit():
        new_name = 'four' + name[1:]
        name = new_name
        validation_set_input.replace(to_replace=name, value=new_name, inplace=True)
# save csv with fixed names
validation_set_input.to_csv('../filter/validation_set/drugbank_filtered_fixed_names.csv')

provenance = {}
provenance['creator'] = "fragmenter"
provenance['hostname'] = socket.gethostname()
provenance['username'] = getpass.getuser()
provenance['routine'] = {'enumerate_states' : {'version': fragmenter.__version__,
                        'options': {'stereoisomers': False, 'explicit_h': False, 'filter_nitro': True}}}

all_states =[]
all_names = []
for smiles, name in zip(validation_set_input.smiles, validation_set_input.name):
    mol = oechem.OEMol()
    oechem.OESmilesToMol(mol, smiles)
    mol.SetTitle(name)

    states, names = fragmenter.fragment.enumerate_states(mol,stereoisomers=False, explicit_h=False, return_names=True,
                                                   filter_nitro=True)

    states_dict = {'provenance': provenance, 'states': states}
    states_dict['provenance']['routine']['enumerate_states']['parent_molecule_name'] = name
    states_dict['provenance']['routine']['enumerate_states']['parent_molecule'] = smiles
    with open('validation_set/{}_states.json'.format(name), 'w') as f:
        json.dump(states_dict, f, indent=2, sort_keys=True)
    all_states.extend(states)
    all_names.extend(names)

fragmenter.chemi.to_pdf(molecules=all_states, names=all_names, fname='enumerated_states.pdf')
print('Number of molelcules to fragment: {}'.format(len(all_states)))


import json
import os
import sys
import time

import requests

class OSVDataMiner:
    def __init__(self):
        if not os.path.isfile('github_access_token.txt'):
            print("please place a Github access token in 'github_access_token.txt' directory.")
            sys.exit()

        with open('github_access_token.txt', 'r') as access_token:
            self.access = access_token.readline().replace("\n", "")

        self.headers = {'Accept': 'application/vnd.github+json', 'Authorization': f'token {self.access}'}

    def getting_data(self):
        commits = {}
        if os.path.isfile('all_commits.json'):
            with open('all_commits.json', 'r') as infile:
                commits = json.load(infile)

        parameters = [
            "buffer overflow", "denial of service", "dos", "XXE", "vuln", "CVE", "XSS", "NVD", "malicious",
            "cross site", "exploit", "directory traversal", "rce", "remote code execution", "XSRF",
            "cross site request forgery", "click jack", "clickjack", "session fixation", "cross origin",
            "infinite loop", "brute force", "buffer overflow", "cache overflow", "command injection",
            "cross frame scripting", "csv injection", "eval injection", "execution after redirect",
            "format string", "path disclosure", "function injection", "replay attack", "session hijacking", "smurf",
            "sql injection", "flooding", "tampering", "sanitize", "sanitise", "unauthorized", "unauthorised"
        ]

        prefixes = [
            "prevent", "fix", "attack", "protect", "issue", "correct", "update", "improve", "change", "check",
            "malicious", "insecure", "vulnerable", "vulnerability"
        ]

        for k in parameters:
            for pre in prefixes:
                self.find_commits(k + " " + pre, commits)

    def find_commits(self, key, commits):
        maximum = 3000
        new = 0

        params = (
            ('q', key), ('per_page', 100)
        )
        next_link = "https://api.github.com/search/commits"

        for i in range(0, maximum):
            print(str(len(commits)) + " commits so far.")

            limit = 0
            while limit == 0:
                response = requests.get(next_link, headers=self.headers, params=params)
                h = response.headers
                if 'X-RateLimit-Remaining' in h:
                    limit = int(h['X-RateLimit-Remaining'])
                    if limit == 0:
                        print("Rate limit. Sleep.")
                        time.sleep(35)
            if 'Link' not in h:
                break

            content = response.json()
            for k in range(0, len(content["items"])):
                repo = content["items"][k]["repository"]["html_url"]
                if repo not in commits:
                    c = {
                        "url": content["items"][k]["url"],
                        "html_url": content["items"][k]["html_url"],
                        "message": content["items"][k]["commit"]["message"],
                        "sha": content["items"][k]["sha"],
                        "keyword": key
                    }
                    commits[repo] = {}
                    commits[repo][content["items"][k]["sha"]] = c
                else:
                    if not content["items"][k]["sha"] in commits[repo]:
                        new = new + 1
                        c = {
                            "url": content["items"][k]["url"],
                            "html_url": content["items"][k]["html_url"],
                            "sha": content["items"][k]["sha"],
                            "keyword": key
                        }
                        commits[repo][content["items"][k]["sha"]] = c

            link = h['Link']
            ref_links = self.analyze_links(link)
            if "last" in ref_links:
                last_number = ref_links["last"].split("&page=")[1]
                maximum = int(last_number) - 1
            if not "next" in ref_links:
                break
            else:
                next_link = ref_links["next"]

        with open('all_commits.json', 'w') as outfile:
            json.dump(commits, outfile)

    def find_pypi_commits(self):
        osv_pypi_packages = "https://api.github.com/repos/pypa/advisory-database/contents/vulns"
        osv_vulnerability_url = 'https://api.osv.dev/v1/vulns'
        progress_time_start = time.time()

        response = requests.get(osv_pypi_packages, headers=self.headers)
        folders: list = response.json() if response and response.status_code == 200 else []
        osv_data = {}

        if os.path.isfile('osv_packages.json'):
            with open('osv_packages.json', 'r') as infile:
                osv_data = json.load(infile)

        progress = 0
        for content in folders:
            folder = content['name']
            file_type = content['type']
            progress += 1
            if progress % 10 == 0:
                print(f"Progress: {progress}/{len(folders)} ({(progress / len(folders)) * 100}%)")

            if file_type == 'dir' and folder not in osv_data:
                dir_files = requests.get(f'{osv_pypi_packages}/{folder}', headers=self.headers)
                if 'X-RateLimit-Remaining' in response.headers:
                    limit = int(response.headers['X-RateLimit-Remaining'])
                    if limit == 0:
                        print("Rate limit. Sleep.")
                        time.sleep(60)

                for dir_file in dir_files.json():
                    if dir_file['type'] == 'file':
                        if folder not in osv_data:
                            osv_package = {
                                "osv_id": dir_file['name'][:-5],
                                "package": content['path'].split('/')[1]
                            }
                            osv_data[folder] = {}
                            osv_data[folder][dir_file['name'][:-5]] = osv_package
                        elif dir_file['name'][:-5] not in osv_data[folder]:
                            osv_package = {
                                "osv_id": dir_file['name'][:-5],
                                "package": content['path'].split('/')[1]
                            }
                            osv_data[folder][dir_file['name'][:-5]] = osv_package

                with open('osv_packages.json', 'w') as outfile:
                    json.dump(osv_data, outfile)

        progress_time_middle = time.time()
        print("Number of packages:", len(osv_data))
        print("Number of documented vulnerabilities:", len(osv_data.values()))
        print(f'Time to process PyPI osv data: {progress_time_middle - progress_time_start}')

        osv_vulnerability_details = {}
        for osv_vulnerability_package in osv_data.keys():
            for osv_vulnerability_id in osv_data[osv_vulnerability_package].keys():
                osv_vulnerability_data = requests.get(f'{osv_vulnerability_url}/{osv_vulnerability_id}')
                osv_vulnerability_details[f'{osv_vulnerability_package}|{osv_vulnerability_id}'] = osv_vulnerability_data.json()

        with open('osv_vulnerability_details.json', 'w') as outfile:
            json.dump(osv_vulnerability_details, outfile)

        progress_time_end = time.time()
        print('processing end.')
        print(f'Time to process details: {progress_time_end - progress_time_middle}')
        print(f'Time to process all: {progress_time_end - progress_time_start}')

    def analyze_links(self, link):
        link = link + ","
        ref_links = {}
        while "," in link:
            pos = link.find(",")
            text = link[:pos]
            rest = link[pos + 1:]
            try:
                if "\"next\"" in text:
                    text = text.split("<")[1]
                    text = text.split(">;")[0]
                    ref_links["next"] = text
                if "\"prev\"" in text:
                    text = text.split("<")[1]
                    text = text.split(">;")[0]
                    ref_links["prev"] = text
                if "\"first\"" in text:
                    text = text.split("<")[1]
                    text = text.split(">;")[0]
                    ref_links["first"] = text
                if "\"last\"" in text:
                    text = text.split("<")[1]
                    text = text.split(">;")[0]
                    ref_links["last"] = text
            except IndexError as e:
                print(e)
                print("\n")
                print(text)
                print("\n\n")
                sys.exit()
            link = rest
        return ref_links

miner = OSVDataMiner()
miner.find_pypi_commits()


#!/usr/bin/env python
import sys, gym, time
import numpy as np
import env.wrappers as wrappers
import matplotlib.pyplot as plt
from argparse import ArgumentParser
import buffer as bf
import cv2

#
# Test yourself as a learning agent! Pass environment name as a command-line argument, for example:
#
# python keyboard_agent.py SpaceInvadersNoFrameskip-v4
#

#env = gym.make('BreakoutDeterministic-v4' if len(sys.argv)<2 else sys.argv[1])

""" configuration """
parser = ArgumentParser(description='configuration switches')

parser.add_argument('--save_buffer', type=str, default='buffer.pkl')

""" environment """
parser.add_argument('--env_name', type=str, default='BreakoutDeterministic-v4')
parser.add_argument('--env_render', action='store_true', default=False)
parser.add_argument('--env_reward_scale', type=float, default=1.0)
parser.add_argument('--env_reward_bias', type=float, default=0.0)
parser.add_argument('--env_timelimit', type=int, default=3000)
config = parser.parse_args()

def rescale_reward(reward):
    return reward * config.env_reward_scale - config.env_reward_bias

def make_env():
    env = gym.make('SpaceInvadersDeterministic-v4')
    env = wrappers.TimeLimit(env.unwrapped, max_episode_steps=config.env_timelimit)
    env = wrappers.EpisodicLifeEnv(env)
    env = wrappers.NoopResetEnv(env)
    if 'FIRE' in env.unwrapped.get_action_meanings():
        env = wrappers.FireResetEnv(env)
    env = wrappers.ClipState2D(env, 0, 24, 210 - 24, 160)
    env = wrappers.WarpFrame(env)
    env = wrappers.Gradient(env)
    env = wrappers.ClipRewardEnv(env)
    env = wrappers.PenalizeOneIfDone(env)
    env = gym.wrappers.TransformReward(env, rescale_reward)
    return env

# plt.ion()
# fig = plt.figure()
# spec = plt.GridSpec(nrows=1, ncols=2, figure=fig)
#
# ax_state = fig.add_subplot(fig.add_subplot(spec[0, 0]))
# ax_grad = fig.add_subplot(fig.add_subplot(spec[0, 1]))

env = make_env()
env, buffer = bf.wrap(env)

if not hasattr(env.action_space, 'n'):
    raise Exception('Keyboard agent only supports discrete action spaces')
ACTIONS = env.action_space.n
SKIP_CONTROL = 0    # Use previous control decision SKIP_CONTROL times, that's how you
                    # can test what skip is still usable.

human_agent_action = 0
human_wants_restart = False
human_sets_pause = False

_keymap = {ord(' '): 1,
       ord('a'): 3,
       ord('d'): 2 }

def keymap(key):
    if key in _keymap:
        return _keymap[key]
    else:
        return 0

def key_press(key, mod):
    global human_agent_action, human_wants_restart, human_sets_pause
    if key==0xff0d: human_wants_restart = True
    #if key==32: human_sets_pause = not human_sets_pause
    a = keymap(key)
    if a <= 0 or a >= ACTIONS: return
    human_agent_action = a

def key_release(key, mod):
    global human_agent_action
    a = keymap(key)
    if a <= 0 or a >= ACTIONS: return
    if human_agent_action == a:
        human_agent_action = 0

env.render()
env.unwrapped.viewer.window.on_key_press = key_press
env.unwrapped.viewer.window.on_key_release = key_release

# `def plot(obser):
#     ax_state.clear()
#     ax_grad.clear()
#     ax_state.imshow(obser[:, :, 0])
#     ax_grad.imshow(obser[:, :, 1])
#     fig.canvas.draw()`

def rollout(env):
    global human_agent_action, human_wants_restart, human_sets_pause
    human_wants_restart = False
    obser = env.reset()
    print('RESET')
    total_reward = 0
    total_timesteps = 0
    while 1:
        a = human_agent_action

        obser, r, done, info = env.step(a)
        total_timesteps += 1
        if r != 0:
            print("reward %0.3f" % r)
        total_reward += r
        window_still_open = env.render()
        if window_still_open==False: return False
        if done: print('DONE'); break
        if human_wants_restart: break
        time.sleep(0.1)
    print("timesteps %i reward %0.2f" % (total_timesteps, total_reward))

print("ACTIONS={}".format(ACTIONS))
print("Press keys 1 2 3 ... to take actions 1 2 3 ...")
print("No keys pressed is taking action 0")

for i in range(40):
    window_still_open = rollout(env)
    if window_still_open==False: break
d
print(f'buffer length {len(buffer)}')

bf.save(buffer, 'space_invaders.pkl')


from django.db import models
from django.conf import settings

# Create your models here.
class Genre(models.Model):
    name = models.CharField(max_length=20)

class Movie(models.Model):
    title = models.CharField(max_length=50)
    audience = models.IntegerField()
    poster_url = models.CharField(max_length=200)
    description = models.TextField()
    # related_name을 해야 장르가 영화에 대한 정보를 가지고올 수 있다.
    # related_name을 쓰지않고 genre.movie를 가지고오려면 movie_set하면 된다
    # Movie.genre는 가지고올 수 있음 why? 모델안에 존재하기 때문!
    genre = models.ForeignKey(Genre, on_delete=models.CASCADE, related_name='movies')

class Review(models.Model):
    content = models.CharField(max_length=80)
    score = models.IntegerField()
    #  알아서 db에 movie_id로 저장시킨다.
    movie = models.ForeignKey(Movie, on_delete=models.CASCADE, related_name='movies')
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='movies')


import foggie.utils.foggie_load as fog
import yt
from yt import YTQuantity,YTArray
from yt.data_objects.particle_filters import add_particle_filter
import numpy as np
import h5py

halo = 'Tempest'
hnum = '008508'

#Mogget
snap_name = '/Users/bnguyen/Downloads/DD2427/DD2427'
halo_c_v_name = '/Users/bnguyen/FOGGIE/foggie/halo_infos/'+hnum+'/nref11c_nref9f/halo_c_v'
trackname = '/Users/bnguyen/FOGGIE/foggie/halo_tracks/'+hnum+'/nref11n_selfshield_15/halo_track_200kpc_nref9'
masses_dir = '/Users/bnguyen/FOGGIE/foggie/halo_infos/'+hnum+'/nref11c_nref9f/'
hsfile = '/Users/bnguyen/Downloads/'+halo+'_RD0042_allhalostardata.h5'

f = h5py.File(hsfile,'r')
pids = f['particle_IDs'][:]
hids = f['host_IDs'].asstr()[:]
f.close()

def StarParts(pfilter, data):
    return data[("all", "particle_type")] == 2

add_particle_filter("stars", function=StarParts, filtered_type='all', requires=["particle_type"])

ds, region = fog.foggie_load(snap_name, trackname, find_halo_center=True, halo_c_v_name=halo_c_v_name, disk_relative=True, \
                            particle_type_for_angmom='young_stars', do_filter_particles=True, gravity=False,\
                            region='refine_box',masses_dir=masses_dir)

ds.add_particle_filter('stars')
ads = ds.all_data()

allstarmasses = ads['stars','particle_mass']

# Create version of star allstarmasses that contains only halo stars and
# lists the masses in the same order as the halostardata file
allstarinds = ads['stars','particle_index']
index = np.argsort(allstarinds) # put particle IDs for all stars in numerical order
sorted_allstars = allstarinds[index]
sorted_index = np.searchsorted(sorted_allstars,pids)
# Create a mask that will reorder an array so that it's in the same order as the halostardata
# file and will include only halo stars
pindex = np.take(index,sorted_index,mode="clip")
mask = allstarinds[pindex] != pids
res = np.ma.array(pindex,mask=mask)
massarr = allstarmasses[np.ma.compressed(res)].in_units('Msun')
# masarr now lists the masses of the stars in the same order that the halostardata file lists their
# particle IDs, host IDs, creation times, etc


### Module imports ###
import time
import argparse
from utils import VnAnnotator, read_txt

### Global Variables ###
text_path = 'vi_text.txt'

### Class declarations ###

### Function declarations ###
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--lib', type=str, default='', required=True)
    parser.add_argument('--mode', type=str, default='', required=True)
    args = parser.parse_args()

    annotator = VnAnnotator()
    text_list = read_txt(text_path)
    output = f'{args.lib}/{args.mode}_{args.lib}_output.txt'
    t = time.time()
    annotator.annotate(args.lib, text_list, args.mode, output)
    print(time.time() - t)


import re

# A collection of validation functions used through the app
def check_unique(coll, data, field, results=False):
    query = coll.find({field: data})

    if query.count() == 0:
        return {"unique": True}

    if results:
        return {"unique": False, "query_results": [x for x in query]}

    return False

def set_key_number(coll, key_value):
    query = coll.find({'_key': key_value})

    if query.count() == 0:
        return key_value

    key_search = re.search(r"\d+$", key_value)
    try:
        next_val = int(key_search.group()) + 1
        key_value = key_value[:key_search.start()] + str(next_val)
    except AttributeError:
        key_value = key_value + '1'

    return set_key_number(coll, key_value)


#!coding=utf8

class DomainListModel(object):
	def __init__(self, ipcis):
		self.ipcis = ipcis

	async def get_known_domains(self):
		ret = []
		rs = await self.ipcis.query(
			"SELECT domain_name FROM domain2ip;")
		for item in rs:
			ret.append(item[0])

		return ret


import io
import picamera
import logging
import socketserver
from threading import Condition
from http import server

PAGE="""\
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Random</title>

        <button class="btn-group btn-fwd">Forward</button>
        <button class="btn-group btn-left">Left</button>
        <button class="btn-group btn-play">Play</button>
        <button class="btn-group btn-right">Right</button>
        <button class="btn-group btn-rev">Backwards</button>

"""

class StreamingOutput(object):
    def __init__(self):
        self.frame = None
        self.buffer = io.BytesIO()
        self.condition = Condition()

    def write(self, buf):
        if buf.startswith(b'\xff\xd8'):
            self.buffer.truncate()
            with self.condition:
                self.frame = self.buffer.getvalue()
                self.condition.notify_all()
            self.buffer.seek(0)
        return self.buffer.write(buf)

class StreamingHandler(server.BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/':
            self.send_response(301)
            self.send_header('Location', '/index.html')
            self.end_headers()
        elif self.path == '/index.html':
            content = PAGE.encode('utf-8')
            self.send_response(200)
            self.send_header('Content-Type', 'text/html')
            self.send_header('Content-Length', len(content))
            self.end_headers()
            self.wfile.write(content)
        elif self.path == '/stream.mjpg':
            self.send_response(200)
            self.send_header('Age', 0)
            self.send_header('Cache-Control', 'no-cache, private')
            self.send_header('Pragma', 'no-cache')
            self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=FRAME')
            self.end_headers()
            try:
                while True:
                    with output.condition:
                        output.condition.wait()
                        frame = output.frame
                    self.wfile.write(b'--FRAME\r\n')
                    self.send_header('Content-Type', 'image/jpeg')
                    self.send_header('Content-Length', len(frame))
                    self.end_headers()
                    self.wfile.write(frame)
                    self.wfile.write(b'\r\n')
            except Exception as e:
                logging.warning(
                    'Removed streaming client %s: %s',
                    self.client_address, str(e))
        else:
            self.send_error(404)
            self.end_headers()

class StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer):
    allow_reuse_address = True
    daemon_threads = True

with picamera.PiCamera(resolution='1280x720', framerate=60) as camera:
    output = StreamingOutput()
    camera.rotation = 180
    camera.start_recording(output, format='mjpeg')
    try:
        address = ('192.168.1.116', 8080)
        server = StreamingServer(address, StreamingHandler)
        server.serve_forever()
    finally:
        camera.stop_recording()


#!/usr/bin/env python
"""
    goal_sub_pub_beta_4.1.py
    2020.08.25
    Zhanyu Guo
"""
"""
    imports
"""
import math
import random
import rospy
import tf
from std_msgs.msg import Bool, String, Int8
from geometry_msgs.msg import PoseStamped, PoseWithCovarianceStamped
from tf.transformations import quaternion_from_euler

# all conditon for publishing next goal
begin_flag = Bool()
reach_flag = Bool()
receive_flag = Bool()

begin_flag.data = False    # default: False
reach_flag.data = True     # default: True: to begin the 1st publishment
receive_flag.data = False  # default: Fasle

# times(counts) limitation of calculating shortest route
cal_times = 30

# the list to store Goals for publishing
Goals = []

# set current goal
# default to (100, 100) to avoid the initial pose too close to current_goal
current_goal = PoseStamped()
current_goal.pose.position.x = 100
current_goal.pose.position.y = 100

# current point, that is also the starting point
cur = 0

# next point, to which the initial pose direct
nxt = 0

# the condition of reaching current goal
goal_dis = 2.5  # param

# choices of each point
choices = [[2, 9],
           [1, 10, 4],
           [4, 11],
           [2, 3, 5],
           [4, 6, 11],
           [5, 7],
           [6, 8, 10],
           [7, 9, 10],
           [1, 8],
           [2, 7, 8, 11],
           [3, 5, 10]]

# distance from each point to where it can reach
dis = [[0, 5, -1, -1, -1, -1, -1, -1, 9, -1, -1],
       [5, 0, 6.24, 10, -1, -1, -1, -1, -1, 4.96, -1],
       [-1, 6.24, 0, 6.24, -1, -1, -1, -1, -1, -1, 1.78],
       [-1, 10, 6.24, 0, 5.1, -1, -1, -1, -1, -1, -1],
       [-1, -1, -1, 5.1, 0, 3.9, -1, -1, -1, -1, 6.98],
       [-1, -1, -1, -1, 3.9, 0, 7, -1, -1, -1, -1],
       [-1, -1, -1, -1, -1, 7, 0, 4.5, -1, 4.53, -1],
       [-1, -1, -1, -1, -1, -1, 4.5, 0, 3.5, 5.29, -1],
       [9, -1, -1, -1, -1, -1, -1, 3.5, 0, -1, -1],
       [-1, 4.96, -1, -1, -1, -1, 4.53, 5.29, -1, 0, 3],
       [-1, -1, 1.78, -1, 6.98, -1, -1, -1, -1, 3, 0]]

# open and read the pose file
# totally 11 points, 22 rows
with open('/home/gzy/pose_.txt', 'r') as file_handle:
    pos_1 = PoseStamped()
    pos_2 = PoseStamped()
    pos_3 = PoseStamped()
    pos_4 = PoseStamped()
    pos_5 = PoseStamped()
    pos_6 = PoseStamped()
    pos_7 = PoseStamped()
    pos_8 = PoseStamped()
    pos_9 = PoseStamped()
    pos_10 = PoseStamped()
    pos_11 = PoseStamped()

    # point position list
    point_pos = [pos_1, pos_2, pos_3, pos_4, pos_5, pos_6, pos_7, pos_8, pos_9, pos_10, pos_11]

    # read file
    for pos in point_pos:
        pos.pose.position.x = float(file_handle.readline().replace('\n', ''))
        pos.pose.position.y = float(file_handle.readline().replace('\n', ''))

def cur_sub_cb(data):
    """
    This function is the callback of /cur, gets the cur.
    :param data: Int8(), number of current point
    :return: None
    """
    global cur
    cur = data.data
    rospy.loginfo("current:%d" % cur)

def nxt_sub_cb(data):
    """
    This function is the callback of /nxt, gets the cur.
    :param data: Int8(), number of next point
    :return: None
    """
    global nxt
    nxt = data.data
    rospy.loginfo("next:%d" % nxt)

def get_distance(x1, y1, x2, y2):
    """
    This function gets distance between two points using x and y.
    :param x1: float
    :param y1: float
    :param x2: float
    :param y2: float
    :return: dis: float
    """
    # calculate distance between (x1, y1) and (x2, y2)
    dis = math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
    return dis

def get_quaternion(angle):
    """
    This function is used to get quaternion from yaw:angle
    :param angle: yaw
    :return: q: quaternion
    """
    # From degrees to radians
    rad = math.radians(angle)

    # Get q(uaternion)
    q = quaternion_from_euler(0, 0, rad)
    return q

def set_xyzw(i, angle):
    """
    This function is used to set x, y, z, w in quaternion
    :param point: point to be set
    :param angle: angle
    :return: None
    """
    # Set x, y, z, w
    Goals[i].pose.orientation.x = get_quaternion(angle)[0]
    Goals[i].pose.orientation.y = get_quaternion(angle)[1]
    Goals[i].pose.orientation.z = get_quaternion(angle)[2]
    Goals[i].pose.orientation.w = get_quaternion(angle)[3]

def begin_sub_cb(data):
    """
    This is the callback of begin_flag_subscriber.
    :param data: Bool, no mater what it is, it will begin the racecar
    :return: None
    """
    # Get begin flag
    begin_flag.data = True

    # Info
    rospy.loginfo("Begin flag received!...")

def goal_sub_cb(data):
    """
    This is the callback of goal number subscriber
    :param data: String, the point list in string split by space
    :return: None
    """
    global cur
    global nxt
    global cal_times
    # The list to store points
    # point_list = [ending_point, point_1, point_2, point_3, ...]
    point_list = list(map(int, data.data.split(' ')))

    # The ending point(destination)
    ending_point = point_list.pop(0)

    # Minimum distance default to infinite
    min_dis = float('inf')

    # Store shortest way
    shortest_way = []

    # Yaw defaults to 0
    yaw = 0
    q = get_quaternion(yaw)
    for pos in point_pos:
        pos.header.frame_id = 'map'
        pos.pose.position.z = 0.0
        pos.pose.orientation.x = q[0]
        pos.pose.orientation.y = q[1]
        pos.pose.orientation.z = q[2]
        pos.pose.orientation.w = q[3]

    # find way flag
    find_way = False

    # error flag
    error = False

    # times of find way
    find_way_time = 0

    # main while, searching for a route
    while find_way_time < cal_times:
        # init before searching
        pre = cur
        now = nxt
        way = [pre, now]

        # tempoary distance
        tmp_dis = 0
        for i in range(20):
            count = len(choices[now - 1])
            p = choices[now - 1][random.randint(0, count - 1)]

            # p can't be previous point, beacause the racecar is hard to reverse
            if p == pre:
                continue

            # change status
            pre = now
            now = p

            # distance from now to p
            tmp_dis += dis[now - 1][p - 1]

            # add p in way
            way.append(p)

            # reach destination
            if p == ending_point:
                for j in point_list:
                    # for all points in point_list, if not all in way, continue to search
                    if j not in way:
                        break

                # if all in way
                else:
                    # counts of elements in way
                    length = len(way)

                    # special cases
                    for k in range(1, length - 1):
                        if way[k] == 2 and way[k - 1] in [3, 4] and way[k + 1] in [3, 4]:
                            error = True
                            break
                        if way[k] == 3 and way[k - 1] in [2, 4] and way[k + 1] in [2, 4]:
                            error = True
                            break
                        if way[k] == 4 and way[k - 1] in [2, 3] and way[k + 1] in [2, 3]:
                            error = True
                            break
                        if way[k] == 2 and way[k - 1] in [4, 10] and way[k + 1] in [4, 10]:
                            error = True
                            break
                        if way[k] == 2 and way[k - 1] in [3, 10] and way[k + 1] in [3, 10]:
                            error = True
                            break
                        if way[k] == 3 and way[k - 1] in [2, 11] and way[k + 1] in [2, 11]:
                            error = True
                            break
                        if way[k] == 10 and way[k - 1] in [2, 11] and way[k + 1] in [2, 11]:
                            error = True
                            break
                        if way[k] == 3 and way[k - 1] in [5, 11] and way[k + 1] in [5, 11]:
                            error = True
                            break
                        if way[k] == 5 and way[k - 1] in [4, 11] and way[k + 1] in [4, 11]:
                            error = True
                            break
                        if way[k] == 7 and way[k - 1] in [8, 10] and way[k + 1] in [8, 10]:
                            error = True
                            break
                        if way[k] == 8 and way[k - 1] in [7, 10] and way[k + 1] in [7, 10]:
                            error = True
                            break
                        if way[k] == 10 and way[k - 1] in [7, 8] and way[k + 1] in [7, 8]:
                            error = True
                            break
                        if way[k] == 11 and way[k - 1] in [3, 5] and way[k + 1] in [3, 5]:
                            error = True
                            break

                    # not in special cases
                    if not error:
                        find_way = True
                        find_way_time += 1

                        # judge whether the shortest way for now
                        if tmp_dis < min_dis:
                            min_dis = tmp_dis
                            shortest_way = way[:]

            # if find a correct way break out of the while
            if find_way:
                find_way = False
                break

            # if special cases, also break out, but it doesn't add in shortest_way
            # and also, the find_way_time dosen't increase
            if error:
                error = False
                break

    # pop out the first point, which is the starting_point, don't need to publish it
    shortest_way.pop(0)

    # info the way before improving the yaw
    for j in shortest_way:
        rospy.loginfo('%d ' % j)

    # append the goals to Goals[] in order
    for k in shortest_way:
        Goals.append(point_pos[k - 1])

    # counts of the Goals
    l = len(Goals)

    # for every point(except ending_point), its set yaw is determined by next goal
    for i in range(l - 1):
        if shortest_way[i] == 1:
            if shortest_way[i + 1] == 2:
                set_xyzw(i, 10)
            else:
                set_xyzw(i, -100)

        if shortest_way[i] == 2:
            if shortest_way[i + 1] == 1:
                set_xyzw(i, 180)
            elif shortest_way[i + 1] == 10:
                set_xyzw(i, -68)
            else:
                set_xyzw(i, 0)

        if shortest_way[i] == 3:
            if shortest_way[i + 1] == 4:
                set_xyzw(i, 49)
            else:
                set_xyzw(i, -131)

        if shortest_way[i] == 4:
            if shortest_way[i + 1] == 5:
                set_xyzw(i, -70)
            else:
                set_xyzw(i, 170)

        if shortest_way[i] == 5:
            if shortest_way[i + 1] == 4:
                set_xyzw(i, 90)
            elif shortest_way[i + 1] == 6:
                set_xyzw(i, -80)
            else:
                set_xyzw(i, 135)

        if shortest_way[i] == 6:
            if shortest_way[i + 1] == 5:
                set_xyzw(i, 80)
            else:
                set_xyzw(i, -170)

        if shortest_way[i] == 7:
            if shortest_way[i + 1] == 6:
                set_xyzw(i, 0)
            elif shortest_way[i + 1] == 10:
                set_xyzw(i, 112)
            else:
                set_xyzw(i, 180)

        if shortest_way[i] == 8:
            if shortest_way[i + 1] == 7:
                set_xyzw(i, 0)
            elif shortest_way[i + 1] == 10:
                set_xyzw(i, 49)
            else:
                set_xyzw(i, -170)

        if shortest_way[i] == 9:
            if shortest_way[i + 1] == 1:
                set_xyzw(i, 100)
            else:
                set_xyzw(i, -10)

        if shortest_way[i] == 10:
            if shortest_way[i + 1] == 8:
                set_xyzw(i, -168)
            elif shortest_way[i + 1] == 2:
                set_xyzw(i, 110)
            elif shortest_way[i + 1] == 7:
                set_xyzw(i, -72)
            else:
                set_xyzw(i, 49)

        if shortest_way[i] == 11:
            if shortest_way[i + 1] == 3:
                set_xyzw(i, 49)
            elif shortest_way[i + 1] == 5:
                set_xyzw(i, -30)
            else:
                set_xyzw(i, -160)

    if shortest_way[-1] == 1:
        if shortest_way[-2] == 9:
            set_xyzw(-1, 90)
        else:
            set_xyzw(-1, 180)

    if shortest_way[-1] == 2:
        if shortest_way[-2] == 1:
            set_xyzw(-1, 0)
        elif shortest_way[-2] == 4:
            set_xyzw(-1, 180)
        else:
            set_xyzw(-1, 120)

    if shortest_way[-1] == 3:
        if shortest_way[-2] == 4:
            set_xyzw(-1, -131)
        else:
            set_xyzw(-1, 49)

    if shortest_way[-1] == 4:
        if shortest_way[-2] == 5:
            set_xyzw(-1, 90)
        else:
            set_xyzw(-1, 0)

    if shortest_way[-1] == 5:
        if shortest_way[-2] == 4:
            set_xyzw(-1, -90)
        elif shortest_way[-2] == 6:
            set_xyzw(-1, 90)
        else:
            set_xyzw(-1, -30)

    if shortest_way[-1] == 6:
        if shortest_way[-2] == 5:
            set_xyzw(-1, -90)
        else:
            set_xyzw(-1, 0)

    if shortest_way[-1] == 7:
        if shortest_way[-2] == 6:
            set_xyzw(-1, 180)
        if shortest_way[-2] == 10:
            set_xyzw(-1, -49)
        else:
            set_xyzw(-1, 180)

    if shortest_way[-1] == 8:
        if shortest_way[-2] == 9:
            set_xyzw(-1, 0)
        elif shortest_way[-2] == 7:
            set_xyzw(-1, 180)
        else:
            set_xyzw(-1, 49)

    if shortest_way[-1] == 9:
        if shortest_way[-2] == 1:
            set_xyzw(-1, -90)
        else:
            set_xyzw(-1, 180)

    if shortest_way[-1] == 10:
        if shortest_way[-2] == 11:
            set_xyzw(i, -168)
        elif shortest_way[-2] == 7:
            set_xyzw(i, 110)
        elif shortest_way[-2] == 2:
            set_xyzw(i, -72)
        else:
            set_xyzw(i, 49)

    if shortest_way[-1] == 11:
        if shortest_way[-2] == 3:
            set_xyzw(-1, -120)
        elif shortest_way[-2] == 10:
            set_xyzw(-1, 49)
        else:
            set_xyzw(-1, 150)

    # finish receiving
    receive_flag.data = True

def listener_cb(_):
    """
    This is the callback of reach_flag_subscriber.
    :param data: None
    :return: None
    """
    global current_goal
    global goal_dis

    # get TF from map to base_link
    if not rospy.is_shutdown():
        listener.waitForTransform('map', 'base_link', rospy.Time(0), rospy.Duration(4.0))
        (trans, rot) = listener.lookupTransform('map', 'base_link', rospy.Time(0))

        # x and y of odometry, pose of the racecar
        odom_x = trans[0]
        odom_y = trans[1]

        # the distance between current goal and odom
        distance = get_distance(odom_x, odom_y,
                                current_goal.pose.position.x, current_goal.pose.position.y)

        # info
        rospy.loginfo("distance to current goal:%.2f" % distance)
        if distance < goal_dis:
            # info
            rospy.loginfo("Goal reached!...")

            # already reached previous goal
            reach_flag.data = True

        # all condition need to be satisfied
        if begin_flag.data and reach_flag.data and receive_flag.data:
            if not Goals:
                # info
                rospy.loginfo('Final Goal Reach!...')
                rospy.signal_shutdown('Race over')
            else:
                # get current goal
                current_goal = Goals.pop(0)

                # publish current goal
                goal_pub.publish(current_goal)
                goal_pub.publish(current_goal)

                # info
                rospy.loginfo('Pub next...')

            # reach flag reset
            reach_flag.data = False

def main():
    """
        Main function starts
    """
    # global
    global goal_pub
    global listener

    # Init node
    rospy.init_node("goal_sub_pub_node")

    # TF listener
    listener = tf.TransformListener()

    # Subscribers
    rospy.Subscriber('/begin_flag', Bool, begin_sub_cb, queue_size=1)
    rospy.Subscriber('/points_num', String, goal_sub_cb, queue_size=1)
    rospy.Subscriber('/cur', Int8, cur_sub_cb, queue_size=1)
    rospy.Subscriber('/nxt', Int8, nxt_sub_cb, queue_size=1)

    # Publisher
    goal_pub = rospy.Publisher('/move_base_simple/goal', PoseStamped, queue_size=1)

    # timer
    rospy.Timer(rospy.Duration(0.2), listener_cb)

    # spin
    rospy.spin()
    """
        Main function ends
    """

if __name__ == "__main__":
    try:
        main()
    except rospy.ROSInterruptException:
        pass


import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
import time
import numpy as np
from tqdm import tnrange, tqdm
import optuna
import os
import random
from os.path import join
from scipy.io import wavfile
import pickle
from glob import glob
from models import Rnn, BinaryFileSource, LBG
from loss_func import calc_lf0_rmse, vqvae_loss, rmse
from util import create_loader, train_rnn, test_rnn, parse, create_loader_duration
from synthesize import gen_waveform

device = "cuda" if torch.cuda.is_available() else "cpu"

w_accent = False

def train_vqvae(args, trial=None):
    """
    """
    model = Rnn(
        num_layers=args["num_layers"], input_linguistic_dim = 531+2 if w_accent else 442+2, output_dim=199
    ).to(device)

    train_loader, test_loader = create_loader()# 285 ~ 334, 488 ~ 530
    train_loader_tokyo, _ = create_loader(tokyo=True, appendix='_with_acc')
    train_loader_tokyo = train_loader_tokyo[:3000]

    length_osaka = len(train_loader)

    #np.random.seed(0)
    #np.random.shuffle(train_loader)
    #train_num = 1000#int(args["train_ratio"] * len(train_loader))  # 1
    #train_loader = train_loader[:train_num]

    train_loader = np.concatenate([train_loader, train_loader_tokyo])

    train_num = int(args["train_ratio"] * len(train_loader))  # 1
    train_loader = train_loader[:train_num]

    for i in range(len(train_loader)):
        if w_accent:
            train_loader[i][0] = np.concatenate((train_loader[i][0], np.ones((train_loader[i][0].shape[0], 1)), np.zeros((train_loader[i][0].shape[0], 1))), axis=1).astype('float64') if i < 3696 else np.concatenate((train_loader[i][0], np.zeros((train_loader[i][0].shape[0], 1)), np.ones((train_loader[i][0].shape[0], 1))), axis=1).astype('float64')
        else:
            train_loader[i][0] = np.concatenate((train_loader[i][0][:, :285], train_loader[i][0][:, 335:488], train_loader[i][0][:, -4:], np.ones((train_loader[i][0].shape[0], 1)), np.zeros((train_loader[i][0].shape[0], 1))), axis=1).astype('float64')

    for i in range(len(test_loader)):
        if w_accent:
            test_loader[i][0] = np.concatenate((test_loader[i][0], np.ones((test_loader[i][0].shape[0], 1)), np.zeros((test_loader[i][0].shape[0], 1))), axis=1).astype('float64')
        else:
            test_loader[i][0] = np.concatenate((test_loader[i][0][:, :285], test_loader[i][0][:, 335:488], test_loader[i][0][:, -4:], np.ones((test_loader[i][0].shape[0], 1)), np.zeros((test_loader[i][0].shape[0], 1))), axis=1).astype('float64')

    np.random.shuffle(train_loader)
    if args["model_path"] != "":
        model.load_state_dict(torch.load(args["model_path"]))

    optimizer = optim.Adam(model.parameters(), lr=2e-5)# 1e-3
    loss_list = []
    train_f0loss_list = []
    test_loss_list = []
    f0_loss_list = []
    start = time.time()
    for epoch in range(1, args["num_epoch"] + 1):
        loss, train_f0_loss = train_rnn(
            epoch, model, train_loader, optimizer, duration=True
        )
        test_loss, f0_loss = test_rnn(epoch, model, test_loader, duration=True)
        print(f0_loss)

        print(
            "epoch [{}/{}], loss: {:.4f} test_loss: {:.4f}".format(
                epoch + 1, args["num_epoch"], loss, test_loss
            )
        )
        # scheduler.step()
        # logging
        loss_list.append(loss)
        test_loss_list.append(test_loss)

        if trial is not None:
            trial.report(test_loss, epoch - 1)

        if trial is not None:
            if trial.should_prune():
                return optuna.TrialPruned()

        print(time.time() - start)

        if epoch % 5 == 0:
            torch.save(
                model.state_dict(),
                args["output_dir"] + "/rnn_model_{}.pth".format(epoch),
            )
        np.savetxt(args["output_dir"] + "/loss_list.csv", np.array(loss_list))
        np.savetxt(args["output_dir"] + "/f0loss_list.csv", np.array(train_f0loss_list))
        np.savetxt(args["output_dir"] + "/test_loss_list.csv", np.array(test_loss_list))
        np.savetxt(args["output_dir"] + "/test_f0loss_list.csv", np.array(f0_loss_list))

    if args["num_epoch"] == 0:
        model.load_state_dict(torch.load(args["model_path"]))
        #loss, train_f0_loss = train_rnn(
        #    0, model, train_loader, optimizer
        #)
        #torch.save(
        #        model.state_dict(),
        #        args["output_dir"] + "/rnn_model_80.pth",
        #    )
        test_z = []
        train_loader, test_loader = create_loader(valid=False)
        files = sorted(glob('models/duration_rnn/predicted_X_acoustic/*.npy'))
        test_loader = [[np.loadtxt(x)] for x in files]

        for i in range(len(test_loader)):
            if w_accent:
                test_loader[i][0] = np.concatenate((test_loader[i][0], np.ones((test_loader[i][0].shape[0], 1)), np.zeros((test_loader[i][0].shape[0], 1))), axis=1).astype('float64')
            else:
                test_loader[i][0] = np.concatenate((test_loader[i][0][:, :285], test_loader[i][0][:, 335:488], test_loader[i][0][:, -4:], np.ones((test_loader[i][0].shape[0], 1)), np.zeros((test_loader[i][0].shape[0], 1))), axis=1).astype('float64')

        model.eval()
        f0_loss = 0
        f0_losses = []
        for i, data in tqdm(enumerate(test_loader)):
            tmp = []
            for j in range(1):
                tmp.append(torch.tensor(data[j]).float().to(device))

            recon_batch = model(tmp[0])
            recon_batch = recon_batch.detach().cpu().numpy().reshape(-1, 199)
            np.savetxt(join(args['output_dir'], 'predicted_Y_acoustic', 'OSAKA_PHRASES3696_{}{}.csv'.format('0'*(4-len(str(i*13+2))), i*13+2)), recon_batch)
            #waveform = gen_waveform(recon_batch, True, verbose=False)
            #ratio = 28000 / max(waveform.max(), abs(waveform.min()))
            #wavfile.write(join(args['output_dir'], 'generated/OSAKA3696_{}{}.wav'.format('0'*(4-len(str(i*13+2))), i*13+2)), rate=48000, data=(waveform*ratio).astype(np.int16))

            del tmp

        f0_loss /= len(test_loader)
        np.savetxt(join(args['output_dir'], 'test_f0_loss.csv'), f0_losses)
        print(f0_loss*1200/np.log(2))

    return f0_loss

if __name__ == "__main__":
    args = parse()
    os.makedirs(args.output_dir, exist_ok=True)
    train_vqvae(vars(args))


"""
Taiga Asanuma
7-19-2019
Version 1.0
https://github.com/tasanuma714/Raspberry-Pi-Security-Camera-using-Google-Coral-USB-Accelerator

***Big Credit to Adrian at PyImageSearch for the base code on detectVideoMod.py
    python file.
        https://www.pyimagesearch.com/2019/04/22/getting-started-with-google-corals-tpu-usb-accelerator/
        https://www.pyimagesearch.com/2019/05/13/object-detection-and-image-classification-with-google-coral-usb-accelerator/

File Description: This is the python file which records video after a
    pre-set object is detected by the detectVideoTest.py. A 15-second
    video is taken and uploded to Google Drive. This python file will
	be called from	detectVideoMod.py. You need to be signed into a Google
    Account for the program to work.

"""

# imports
import time
import datetime
import picamera

from subprocess import call

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

# function for naming video with timestamp
def get_file_name():
    return time.ctime() + ".h264"

# record video
fileName = get_file_name()
cam = picamera.PiCamera()
cam.start_preview()
cam.start_recording(fileName)
time.sleep(15)
cam.stop_preview()
cam.stop_recording()

# uploads to Google Drive
gauth = GoogleAuth()
drive = GoogleDrive(gauth)
file1 = drive.CreateFile()
file1.SetContentFile(fileName)
file1.Upload()


# Дано натуральное число n. Выведите все числа от 1 до n.

def sum_n(n):
    if n <= 0:
        return n
    else:
        return n + sum_n(n - 1)

if __name__ == '__main__':
    n = 10
    print(sum_n(n))
    print((1 + n) * n / 2)
    assert sum_n(n) == (1 + n) * n / 2, "Error!"


import ctypes
from multiprocessing import BoundedSemaphore
import socket
import struct
import threading
import pickle

from Logic.Chat.Frame import Frame, FrameType
from Logic.Crypto.AESLogic import AESLogic
from Logic.Crypto.SessionKey import SessionKey

class Client:

    def __init__(self,chatWindow):
        self.chatWindow = chatWindow
        self.sessionKeySemaphore = BoundedSemaphore(value=1)
        self.sendAccessSemaphore = BoundedSemaphore(value=1)

    def CreateClient(self,addr, port):

        connected = False
        while not connected:
            try:
                self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                self.socket.connect((addr,port))
                connected = True
            except Exception as e:
                self.socket.close()
                pass #Do nothing, just try again

    def Set_Stranger_RSA(self,RSAKey):
        with self.sessionKeySemaphore:
            self.strangerRSA = RSAKey

    def Send(self,frame):
        with self.sendAccessSemaphore:
            if frame.frame_type == FrameType.TEXT and frame.data == '':
                return

            if frame.frame_type == FrameType.TEXT:
                self.chatWindow.UpdateOutput("Me: " + frame.data)

            if frame.frame_type != FrameType.PUBLIC_KEY:

                session_key = SessionKey.Generate(32)
                with self.sessionKeySemaphore:
                    sessionKeyFrame = SessionKey.PrepareSessionKeyFrame(self.strangerRSA,session_key)
                session_string = pickle.dumps(sessionKeyFrame)
                self.SendSizeFrame(len(session_string))
                frame.data = AESLogic.Encrypt(frame.data,session_key[0:16],session_key[16:32],frame.encrypt_type)
                self.socket.sendall(session_string)

            data_string = pickle.dumps(frame)
            self.SendSizeFrame(len(data_string))
            self.socket.sendall(data_string)

    def SendSizeFrame(self, size):
        size_in_4_bytes = struct.pack('I', size)
        self.socket.sendall(pickle.dumps(Frame(size_in_4_bytes,FrameType.SIZE)))