import tensorflow as tf
from sklearn.metrics import accuracy_score, precision_score, recall_score
from sklearn.metrics import confusion_matrix
import sklearn
from sklearn.metrics import recall_score, classification_report, auc, roc_curve
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve
from sklearn.metrics import roc_auc_score
# tf.keras.losses.MeanSquaredError(
#     reduction=losses_utils.ReductionV2.AUTO, name='mean_squared_error'
# )
import warnings

# import data_picker
import seaborn as sns
sns.set()

warnings.filterwarnings('ignore')

def evaluate_ann(history):
    # print("Cosine Proximity  :   ", history.history['cosine'])
    print("Train Loss : ", history.history["loss"])
    print("Validation Loss : ", history.history["val_loss"])
    print("Mean Squared Erro : ", history.history['mean_squared_error'])
    print("Mean Absolute Error : ", history.history['mean_absolute_error'])
    print("Mean Absolute Percentage Error : ", history.history['mean_absolute_percentage_error'])
    print("Val Mean Squared Erro : ", history.history['val_mean_squared_error'])
    print("Val Mean Absolute Error : ", history.history['val_mean_absolute_error'])
    print("Val Mean Absolute Percentage Error : ", history.history['val_mean_absolute_percentage_error'])
    print("Train Loss : ", history.history["loss"][0])
    print("Validation Loss : ", history.history["val_loss"][0])
    # plot metrics

def predict(model, data, thresholds):
    reconstruction = model(data)
    loss = tf.keras.losses.mae(reconstruction, data)
    # print("loss :", loss)
    # return tf.math.less(loss, threshold)
    return tf.math.less(thresholds, loss)

def print_stats(predictions, labels):
    print("Accuracy = {}".format(accuracy_score(labels, predictions)))
    print("Precision = {}".format(precision_score(labels, predictions)))
    print("Recall = {}".format(recall_score(labels, predictions)))

def prediction(autoencoder, x_test, y_test, threshold):
    preds = predict(autoencoder, x_test, threshold)
    # print("y_test : ", y_test)
    # print("preds : ", preds)
    print_stats(preds, y_test)
    print(preds)
    confusion_matrix_value = confusion_matrix(y_test, preds)
    print("Confusion Matrix : \n ", confusion_matrix_value)
    print("roc_auc_score : ", roc_auc_score(y_test, preds))
    fpr, tpr, thresholds = roc_curve(y_test, preds)
    # plt.plot(fpr, tpr, color="orange", label="ROC")
    # plt.plot([0, 1], [0, 1], color="darkblue", linestyle="--", label="Guessing")
    plt.plot(fpr, tpr, color="orange", label='AUC = %0.3f' % roc_auc_score(y_test, preds))
    plt.plot([0, 1], [0, 1], color="darkblue", linestyle="--", label='Guessing')
    plt.xlabel("False positive rate (fpr)")
    plt.ylabel("True positive rate (tpr)")
    plt.title("Receiver Operating Characteristic (ROC) Curve")
    plt.legend()
    plt.show()


n = int(input())
st = [0]
for i in range(n):
    q = [int(i) for i in input().split()]
    if len(q) > 1:
        st.append(max(q[1], st[-1]))
    elif q[0] == 2:
        st.pop()
    else:
        print(st[-1])


from ..abstract import ParserInterface
from ..exceptions import *
from ..commons import *
from typing import Mapping, List, Any

import configparser
from configparser import ConfigParser

class IniParser(ParserInterface):
    format = 'ini'
    config:Union[ConfigParser, None]

    def __init__(self):
        super().__init__()

    def parse_input(self) -> Mapping:
        check_is_not_null(self.raw_content)
        check_is_str(self.raw_content)

        self.config = ConfigParser()
        self.config.read_string(self.raw_content)

        out: Mapping = IniParser.__cfg_to_dict(self.config)
        del self.config

        return out

    def parse_output(self, output_path:str, parsed_content, **kwargs):
        raise NotImplementedError()

    @classmethod
    def __cfg_to_dict(self, cfg:ConfigParser)->Mapping:
        sections:List[str] = cfg.sections()
        out:Mapping = dict()
        for s in sections:
            d:Mapping = dict()
            for k, v in cfg[s].items():
                d[k] = v
            out[s] = d
        return out


def get_value_1(key):
    half_len = int(len(key)/2)
    tmp_str_1 = key[:half_len]
    tmp_str_2 = key[-half_len:]
    for x in tmp_str_1:
        if x in tmp_str_2:
            return x

def get_point_1(key):
    if ord(key) >= 97:
        return ord(key) - 96
    else:
        return ord(key) - 38

def day_3_1(main_list):
    sum_point_1 = 0
    for key in main_list:
        value = get_value_1(key)
        sum_point_1 = sum_point_1 + get_point_1(value)
    return sum_point_1

def get_value_2(key):
    for x in key[0]:
        if x in key[1] and x in key[2]:
            return x

def day_3_2(main_list):
    sum_point_1 = 0
    for key in main_list:
        if len(key) == 3:
            value = get_value_2(key)
            sum_point_1 = sum_point_1 + get_point_1(value)
    return sum_point_1


import configparser
import json
import os

import pkg_resources
import requests

from . import paths

def checkLocal():
    cli_version, patches_version, integrations_version = None, None, None
    config = configparser.ConfigParser()
    try:
        config.read(paths.PATH_VERSION)
        cli_version = config['Versions']['CLI']
        patches_version = config['Versions']['Patches']
        integrations_version = config['Versions']['Integration']
    except:
        pass
    return cli_version, patches_version, integrations_version

def checkRemote():
    # CLI
    cli = [
        version
        for version in json.loads(requests.get(paths.API_V_CLI).text)
        if version['prerelease'] == False
    ][0]
    cli_version = cli['tag_name']
    cli_download = [file for file in cli['assets'] if file['content_type'] == 'application/java-archive'][0]['browser_download_url']

    # Patches
    patches = [
        version
        for version in json.loads(requests.get(paths.API_V_PATCHES).text)
        if version['prerelease'] == False
    ][0]
    patches_version = patches['tag_name']
    patches_download = [file for file in patches['assets'] if file['content_type'] == 'application/java-archive'][0]['browser_download_url']
    patches_info_version = patches_version
    patches_info_download = [file for file in patches['assets'] if file['content_type'] == 'application/json'][0]['browser_download_url']

    # Integration
    integrations = [
        version
        for version in json.loads(requests.get(paths.API_V_INTEGRATIONS).text)
        if version['prerelease'] == False
    ][0]
    integrations_version = integrations['tag_name']
    integrations_download = [file for file in integrations['assets'] if file['content_type'] == 'application/vnd.android.package-archive'][0]['browser_download_url']

    return (
        (cli_version, cli_download),
        (patches_version, patches_download),
        (patches_info_version, patches_info_download),
        (integrations_version, integrations_download)
    )

def downloadFile(url, targetPath):
    file = requests.get(url)
    if file.ok:
        if os.path.isfile(targetPath):
            os.remove(targetPath)
        with open(targetPath, 'wb') as f:
            f.write(file.content)
    else:
        return RuntimeError(f'Failed to download file: {url} -> {targetPath}')

def checkAndDownloadUpdate():
    # Helper
    parse_version = lambda v: pkg_resources.packaging.version.parse(v)
    rewrite_version_file = False

    # Check for local version
    cli_v_local, patches_v_local, integrations_v_local = checkLocal()
    print('\n'.join([
        'Local version:',
        f"CLI: {cli_v_local}",
        f"Patches: {patches_v_local}",
        f"Integrations: {integrations_v_local}"
    ]))

    # In case the versions are empty,
    # assign an empty string so that they can be parsed by parse_version()
    if (cli_v_local == None): cli_v_local = ''
    if (patches_v_local == None): patches_v_local = ''
    if (integrations_v_local == None): integrations_v_local = ''

    # Check for remote version
    (cli_v_remote, cli_url_remote), (patches_v_remote, patches_url_remote), (patches_info_v_remote, patches_info_url_remote), (integrations_v_remote, integrations_url_remote) = checkRemote()
    if (parse_version(cli_v_remote) > parse_version(cli_v_local)):
        rewrite_version_file = True
        print(f"Downloading new version for CLI: {cli_v_remote}")
        downloadFile(cli_url_remote, paths.PATH_CLI)
    if (parse_version(patches_v_remote) > parse_version(patches_v_local)):
        rewrite_version_file = True
        print(f"Downloading new version for Patches: {patches_v_remote}")
        downloadFile(patches_url_remote, paths.PATH_PATCHES)
        print(f"Downloading new version for Patch Info: {patches_v_remote}")
        downloadFile(patches_info_url_remote, paths.PATH_PATCHES_INFO)
    if (parse_version(integrations_v_remote) > parse_version(integrations_v_local)):
        rewrite_version_file = True
        print(f"Downloading new version for Integrations: {integrations_v_remote}")
        downloadFile(integrations_url_remote, paths.PATH_INTEGRATIONS)

    # If there were new versions, update the file
    if rewrite_version_file:
        config = configparser.ConfigParser()
        config.add_section('Versions')
        config['Versions']['CLI'] = cli_v_remote
        config['Versions']['Patches'] = patches_v_remote
        config['Versions']['Integration'] = integrations_v_remote
        with open(paths.PATH_VERSION, 'w') as f:
            config.write(f)

    print('Everything up-to-date.')


#- importar copy para hacer deepcopy

import copy

#- Definir el stock de un producto en una variable.
stock = [[1, 100], [2, 100], [3, 100], [4, 100], [5, 100], [6, 100], [7, 100], [8, 100], [9, 100], [10, 100]]

#- Definir una forma de solicitar el stock disponible del producto por consola.
def mostrar_stock(codigo):
    print(f"El producto {codigo} tiene un stock de {stock[codigo-1][1]} unidades")

#- Definir una forma de solicitar unidades del producto por consola. Este número de productos se
#almacenarán en una nueva variable llamada ‘Productos seleccionados’.
productos_seleccionados_plantilla = [[1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0], [10, 0]]
productos_seleccionados = copy.deepcopy[productos_seleccionados_plantilla]

def pedir(codigo, cantidad):# corregir: agregar verificación de stock
    global productos_seleccionados #para usar el scope global de la variable
    productos_seleccionados[(codigo-1)][1] = cantidad #corregir: lista de sólo los itemes seleccionados

   ###

#- Los productos reubicados serán descontados del stock inicial.

for item in productos_seleccionados:
    if ((stock[item[0]-1][1]) - (productos_seleccionados[item[0]-1][1])) < 0: ##- El programa debe verificar que existan unidades disponibles.
        print(f"No hay suficiente stock del producto código N° {item[0]}")
    else:
        stock[item[0]-1][1] = (stock[item[0]-1][1]) - (productos_seleccionados[item[0]-1][1]) #si hay stock, descuenta

#borrar carrito
productos_seleccionados = copy.deepcopy[productos_seleccionados_plantilla]

#- Al verificar las unidades disponibles, el programa entregará una unidad extra cuando se seleccionen
#más de 12 unidades. Verificar que el stock posibilite entregar una unidad extra. Sino se entregan las
#unidades justas. Cada una de las posibles acciones debe imprimir un mensaje explicando lo realizado.

#- No se pueden solicitar más de 20 unidades en un mismo pedido.

#- Si el valor ingresado es superior al stock disponible, este debe entregar un mensaje indicando que no
#es posible realizar esta acción debido a que no hay stock suficiente.


from sys import stdin
N = int(stdin.readline())
cnt = 0
for _ in range(N):
    s = stdin.readline().rstrip()
    lst = []
    flag = 0
    for i in range(len(s)):
        if not lst:
            lst.append(s[i])
        if s[i] in lst:
            if s[i] == lst[-1]:
                continue
            else:
                flag = 1
                break
        else:
            lst.append(s[i])

    if flag == 0:
        cnt += 1
print(cnt)

백준/Silver/1316. 그룹 단어 체커/그룹 단어 체커.py


#!/usr/bin/env python
# coding: utf-8

# In[16]:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import requests
import time
from scipy.stats import linregress
import citipy
from citipy import citipy
from config import api_key
import json
import os

output_data_file = "output/cities.csv"

# In[2]:

#Set ranges
lat_range = (-90, 90)
lng_range = (-180, 180)

# In[ ]:

#Create lists for latitudes/longitudes and cities
lat_lngs = []
cities = []

# In[3]:

# Use .random to select random latitudes/longitudes
lats = np.random.uniform(low=-90.000, high=90.000, size=1500)
lngs = np.random.uniform(low=-180.000, high=180.000, size=1500)

#Use zip to combine latitudes/longitudes and put in list
lat_lngs = zip(lats, lngs)

# In[ ]:

# Using the list made, identify nearest city for latitudes/longitudes combinations
for lat_lng in lat_lngs:
    near_city = citipy.nearest_city(lat_lng[0], lat_lng[1]).city_name

    # If the city is unique, then add it to a our cities list
    if near_city not in cities:
        cities.append(near_city)

# In[4]:

#Set up lists to append data into
city_list = []
max_temp_list = []
humidity_list = []
cloud_list = []
wind_speed_list = []
country_code_list = []
date_list = []
lat_list = []
lng_list = []

# In[24]:

index = 0
set_count = 1
print("Begin")

base_url = "http://api.openweathermap.org/data/2.5/weather?"
imperial = "imperial"

#Use f string to set up query url
query_url = f"{base_url}appid={api_key}&units={imperial}&q="

# For each city name in cities list, do below things...
for city in (cities):
    try:
        response_json = requests.get(query_url + city).json()
        city_list.append(response_json["name"])
        cloud_list.append(response_json["clouds"]["all"])
        country_code_list.append(response_json["sys"]["country"])
        date_list.append(response_json["dt"])
        humidity_list.append(response_json["main"]["humidity"])
        lat_list.append(response_json["coord"]["lat"])
        lng_list.append(response_json["coord"]["lon"])
        max_temp_list.append(response_json['main']['temp_max'])
        wind_speed_list.append(response_json["wind"]["speed"])

        if index > 49:
            index = 1
            set_count += 1
        else:
            index += 1
        print(f"Processing Record #{index}, city name: {city}, set #{set_count}")
    except KeyError:
        print("Oops, that key doesn't exist.")

print("-----------------------------")
print("All Finished!")
print("-----------------------------")

# In[25]:

print(f"The first response is {json.dumps(response, indent=2)}.")

# In[26]:

print(len(city_list))
print(len(cloud_list))
print(len(country_code_list))
print(len(date_list))
print(len(humidity_list))
print(len(lat_list))
print(len(lng_list))
print(len(max_temp_list))
print(len(date_list))
print(len(wind_speed_list))

# In[57]:

# In[59]:

# Create a pandas dataframe using data retrieved
weather_df = pd.DataFrame({
                "City" : city_list,
                "Cloudiness" : cloud_list,
                "Country" : country_code_list,
                "Date" : date_list,
                "Humidity" : humidity_list,
                "Lat" : lat_list,
                "Lng" : lng_list,
                "Max Temp" : max_temp_list,
                "Wind Speed" : wind_speed_list
})

# In[58]:

weather_df.to_csv("output/cities_final.csv", index = False)

# In[60]:

weather_df

# In[61]:

weather_df.describe()

# In[64]:

# Create scatter plot
plt.scatter(weather_df["Lat"], weather_df["Max Temp"], facecolor = "red", edgecolor = "black")

# Set title, label and grid
plt.title("City Latitude vs. Maximum Temperature")
plt.xlabel("Laitude")
plt.ylabel("Maximum Temperature")
plt.grid(linewidth=.5, alpha = 1)

# Save as .pngs
plt.savefig("images/City Latitude vs Maximum Temperature.png")
print("The lower the latitude the more likely temperature is to drop")

# In[65]:

# Create scatter plot
plt.scatter(weather_df["Lat"], weather_df["Humidity"], facecolor = "yellow", edgecolor = "black")

# Set title, label and grid
plt.title("City Latitude vs. Humidity")
plt.xlabel("Laitude")
plt.ylabel("Humidity")
plt.grid(linewidth=.5, alpha = 1)

# Save as .pngs
plt.savefig("images/City Latitude vs. Humidity.png")
print("The higher latitude the higher the likelyhood of there being high humidity")

# In[42]:

# Create scatter plot
plt.scatter(weather_df["Lat"], weather_df["Cloudiness"], facecolor = "skyblue", edgecolor = "black")

# Set title, label and grid
plt.title("City Latitude vs. Cloudiness")
plt.xlabel("Laitude")
plt.ylabel("Cloudiness")
plt.grid(linewidth=.5, alpha = 1)

# Save as .pngs
plt.savefig("images/City Latitude vs. Cloudiness.png")
print("There doesn't appear to be much of a correlation betweent the two")

# In[43]:

# Create scatter plot
plt.scatter(weather_df["Lat"], weather_df["Wind Speed"], facecolor = "purple", edgecolor = "black")

# Set title, label and grid
plt.title("City Latitude vs. Wind Speed")
plt.xlabel("Laitude")
plt.ylabel("Wind Speed")
plt.grid(linewidth=.5, alpha = 1)

# Save as .pngs
plt.savefig("images/City Latitude vs. Wind Speed.png")
print("There are slightly higher wind speeds at higher latitudes")

# In[44]:

from datetime import datetime
ts = int("1611860897")
print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d'))

# In[45]:

weather_df['date'] = pd.to_datetime(weather_df['Date'],unit='s')

# In[46]:

weather_df

# In[47]:

#Sepperate northern and southern by latitude
Northern_Hem = weather_df[weather_df.Lat >= 0]
Southern_Hem = weather_df[weather_df.Lat <= 0]

# In[48]:

from sklearn.linear_model import LinearRegression

# In[77]:

#Create variables for northern and southern , temperature,humidity,coudiness and wind speed.
Lat_N = Northern_Hem.iloc[:, 5].values.reshape(-1, 1)
Lat_S = Southern_Hem.iloc[:, 5].values.reshape(-1, 1)

Temp_N = Northern_Hem.iloc[:, 7].values.reshape(-1, 1)
Temp_S = Southern_Hem.iloc[:, 7].values.reshape(-1, 1)

Humidity_N = Northern_Hem.iloc[:, 4].values.reshape(-1, 1)
Humidity_S = Southern_Hem.iloc[:, 4].values.reshape(-1, 1)

Cloudiness_N = Northern_Hem.iloc[:, 1].values.reshape(-1, 1)
Cloudiness_S = Southern_Hem.iloc[:, 1].values.reshape(-1, 1)

Wind_Speed_N = Northern_Hem.iloc[:, 8].values.reshape(-1, 1)
Wind_Speed_S = Southern_Hem.iloc[:, 8].values.reshape(-1, 1)

#Create predictor line
linear_regressor = LinearRegression()
linear_regressor.fit(Lat_N, Temp_N)
Temp_N_Predict = linear_regressor.predict(Lat_N)

#Create plot and set labels, title and grid
plt.scatter(Lat_N, Temp_N, facecolor = "red", edgecolor = "black")
plt.title("Northern Hemisphere - Max Temp vs. Latitude Linear Regression")
plt.xlabel("Latitude")
plt.ylabel("Max Temp (F)")
plt.plot(Lat_N, Temp_N_Predict, color='blue')
plt.grid(linewidth=.5, alpha = 1)
plt.show()

plt.savefig("images/Northern Hemisphere - Max Temp vs. Latitude Linear Regression.png")

# In[78]:

#Create predictor line
linear_regressor = LinearRegression()
linear_regressor.fit(Lat_S, Temp_S)
Temp_S_Predict = linear_regressor.predict(Lat_S)

#Create plot and set labels, title and grid
plt.scatter(Lat_S, Temp_S, facecolor = "red", edgecolor = "black")
plt.title("Southern Hemisphere - Max Temp vs. Latitude Linear Regression")
plt.xlabel("Latitude")
plt.ylabel("Max Temp (F)")
plt.plot(Lat_S, Temp_S_Predict, color='red')
plt.grid(linewidth=.5, alpha = 1)
plt.show()

plt.savefig("images/Southern Hemisphere - Max Temp vs. Latitude Linear Regression.png")

# In[79]:

#Create predictor line
linear_regressor = LinearRegression()
linear_regressor.fit(Lat_S, Humidity_S)
Humidity_S_Predict = linear_regressor.predict(Lat_S)

#Create plot and set labels, title and grid
plt.scatter(Lat_S, Humidity_S, facecolor = "yellow", edgecolor = "black")
plt.title("Southern Hemisphere - Humidity vs. Latitude Linear Regression")
plt.xlabel("Latitude")
plt.ylabel("Humidity")
plt.plot(Lat_S, Humidity_S_Predict, color='red')
plt.grid(linewidth=.5, alpha = 1)
plt.show()

plt.savefig("images/Southern Hemisphere - Humidity vs. Latitude Linear Regression.png")

# In[80]:

#Create predictor line
linear_regressor = LinearRegression()
linear_regressor.fit(Lat_N, Humidity_N)
Humidity_N_Predict = linear_regressor.predict(Lat_N)

#Create plot and set labels, title and grid
plt.scatter(Lat_N, Humidity_N, facecolor = "yellow", edgecolor = "black")
plt.title("Northern Hemisphere - Humidity vs. Latitude Linear Regression")
plt.xlabel("Latitude")
plt.ylabel("Humidity")
plt.plot(Lat_N, Humidity_N_Predict, color='blue')
plt.grid(linewidth=.5, alpha = 1)
plt.show()

plt.savefig("images/Northern Hemisphere - Humidity vs. Latitude Linear Regression.png")

# In[81]:

#Create predictor line
linear_regressor = LinearRegression()
linear_regressor.fit(Lat_S, Cloudiness_S)
Cloudiness_S_Predict = linear_regressor.predict(Lat_S)

#Create plot and set labels, title and grid
plt.scatter(Lat_S, Cloudiness_S, facecolor = "skyblue", edgecolor = "black")
plt.title("Southern Hemisphere - Cloudiness vs. Latitude Linear Regression")
plt.xlabel("Latitude")
plt.ylabel("Cloudiness")
plt.plot(Lat_S, Cloudiness_S_Predict, color='red')
plt.grid(linewidth=.5, alpha = 1)
plt.show()

plt.savefig("images/Southern Hemisphere - Cloudiness vs. Latitude Linear Regression.png")

# In[82]:

#Create predictor line
linear_regressor = LinearRegression()
linear_regressor.fit(Lat_N, Cloudiness_N)
Cloudiness_N_Predict = linear_regressor.predict(Lat_N)

#Create plot and set labels, title and grid
plt.scatter(Lat_N, Cloudiness_N, facecolor = "skyblue", edgecolor = "black")
plt.title("Northern Hemisphere - Cloudiness vs. Latitude Linear Regression")
plt.xlabel("Latitude")
plt.ylabel("Cloudiness")
plt.plot(Lat_N, Cloudiness_N_Predict, color='blue')
plt.grid(linewidth=.5, alpha = 1)
plt.show()

plt.savefig("Northern Hemisphere - Cloudiness vs. Latitude Linear Regression.png")

# In[83]:

#Create predictor line
linear_regressor = LinearRegression()
linear_regressor.fit(Lat_N, Wind_Speed_N)
Wind_Speed_N_Predict = linear_regressor.predict(Lat_N)

#Create plot and set labels, title and grid
plt.scatter(Lat_N, Wind_Speed_N, facecolor = "purple", edgecolor = "black")
plt.title("Northern Hemisphere - Wind_Speed vs. Latitude Linear Regression")
plt.xlabel("Latitude")
plt.ylabel("Wind_Speed")
plt.plot(Lat_N, Wind_Speed_N_Predict, color='blue')
plt.grid(linewidth=.5, alpha = 1)
plt.show()

plt.savefig("Northern Hemisphere - Wind_Speed vs. Latitude Linear Regression.png")

# In[84]:

#Create predictor line
linear_regressor = LinearRegression()
linear_regressor.fit(Lat_S, Wind_Speed_S)
Wind_Speed_S_Predict = linear_regressor.predict(Lat_S)

#Create plot and set labels, title and grid
plt.scatter(Lat_S, Wind_Speed_S, facecolor = "purple", edgecolor = "black")
plt.title("Southern Hemisphere - Wind_Speed vs. Latitude Linear Regression")
plt.xlabel("Latitude")
plt.ylabel("Wind_Speed")
plt.plot(Lat_S, Wind_Speed_S_Predict, color='red')
plt.grid(linewidth=.5, alpha = 1)
plt.show()

plt.savefig("Southern Hemisphere - Wind_Speed vs. Latitude Linear Regression.png")

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:


import subprocess
import argparse
import os

parser = argparse.ArgumentParser()
parser.add_argument('-p', '--path') # path to exe folder
parser.add_argument('-ls', '--logserver') # path to exe folder
parser.add_argument('-lc', '--logclient') # path to exe folder
parser.add_argument('-d', '--dumpfile') # path to exe folder
parser.add_argument('-mn', '--maxnumber') # path to exe folder

args = parser.parse_args()
FNULL = open(os.devnull, 'w')

host = "localhost"
port = "1234"
server = args.path + "tcp-mean-server.exe "
client = args.path + "tcp-mean-client.exe "
logfolder = "log/"

isExist = os.path.exists(logfolder)
if not isExist:
   # Create a new directory because it does not exist
   os.makedirs(logfolder)

# Run the server
#subprocess.Popen(args = [server, port, logfolder + args.logserver, logfolder + args.dumpfile, args.maxnumber])
subprocess.Popen(args = ["start", "cmd", "/k", server, port, logfolder + args.logserver, logfolder + args.dumpfile, args.maxnumber], shell=True)

#os.system("start /wait cmd /c {server} {port} {logfolder + args.logserver} {logfolder + args.dumpfile} {args.maxnumber}")

for i in range(9):
    # Run some clients
    subprocess.Popen(args = [client, host, port, logfolder + str(i) + args.logclient, args.maxnumber])

# Let's add a client who sends incorrect values
subprocess.Popen(args = [client, host, port, logfolder + 'wrong' + args.logclient, str(int(args.maxnumber)+10)])


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 15 17:35:48 2018
@author: Lucas Liu

Implementing Deep Q Network (DQN)
On my designed task.
"""

import torch.nn.functional as F
import torch.optim as optim
import torch.nn as nn
import torch

import pybullet as p
import pybullet_data

from collections import namedtuple
import matplotlib.pyplot as plt
from math import exp
import numpy as np
import random
import copy

class Net(nn.Module):

    def __init__(self):

        super(Net, self).__init__()

        self.bn0 = nn.BatchNorm1d(ob_size)
        self.fc1 = nn.Linear(ob_size, 400)
        self.bn1 = nn.BatchNorm1d(400)
        self.fc2 = nn.Linear(400, 300)
        self.bn2 = nn.BatchNorm1d(300)
        self.fc3 = nn.Linear(300, ac_size)

    def forward(self, x):

        x = self.bn0(x)
        x = F.relu( self.bn1(self.fc1(x)) )
        x = F.relu( self.bn2(self.fc2(x)) )
        x = self.fc3(x)

        return x

class Env():

    def __init__(self):

        self.physicsClient = p.connect(p.DIRECT)   # p.DIRECT or p.GUI
        p.setAdditionalSearchPath(pybullet_data.getDataPath())
        p.configureDebugVisualizer(p.COV_ENABLE_GUI, 0)
        p.resetDebugVisualizerCamera(cameraDistance=3, cameraYaw=90, cameraPitch=-30, cameraTargetPosition=[0,1,0])
        self.base_pos = []

        self.angle1 = np.deg2rad(20)
        self.length1 = 2
        self.angle2 = np.deg2rad(10)
        self.length2 = 1
        self.radius = 15
        self.plane_urdf = '/home/lucas/modules/summer_project/bullet3-master/pybullet/gym/pybullet_data/plane.urdf'

        self.action_delta = 2 * action_bound / (ac_size-1)
        self.action_range = [-action_bound+self.action_delta*i for i in range(ac_size)]

    def reset(self):

        self.vt = 0

        p.resetSimulation()
        p.setGravity(0,0,-9.8)
        #self.planeId = p.loadURDF("plane.urdf")
        self.plane1 = p.loadURDF(self.plane_urdf,
                                 [0, -13, 0],
                                 p.getQuaternionFromEuler([0, 0, 0]))

        self.plane2 = p.loadURDF(self.plane_urdf,
                                 [0, 2+self.radius*np.cos(self.angle1), -self.radius*np.sin(self.angle1)],
                                 p.getQuaternionFromEuler([-self.angle1, 0, 0]))

        self.plane3 = p.loadURDF(self.plane_urdf,
                                 [0, 3+self.length1*np.cos(self.angle1), -self.length1*np.sin(self.angle1)],
                                 p.getQuaternionFromEuler([0, 0, 0]))
        '''
        self.plane4 = p.loadURDF(self.plane_urdf,
                                 [0, 4+self.length1*np.cos(self.angle1)+self.length2*np.cos(self.angle2)-self.radius*np.cos(self.angle2),
                                  self.length2*np.sin(self.angle2)-self.length1*np.sin(self.angle1)-self.radius*np.sin(self.angle2)],
                                 p.getQuaternionFromEuler([self.angle2, 0, 0]))

        self.plane5 = p.loadURDF(self.plane_urdf,
                                 [0, 4+self.length1*np.cos(self.angle1)+self.length2*np.cos(self.angle2)+self.radius,
                                  self.length2*np.sin(self.angle2)-self.length1*np.sin(self.angle1)],
                                 p.getQuaternionFromEuler([0, 0, 0]))
        '''
        self.botId = p.loadURDF("/home/lucas/modules/summer_project/my_models/bot_origin2.urdf", StartPos, StartOrien)

        p.stepSimulation()

        observation = self.step_observation()

        return observation

    def step(self, action, ob):

        self.step_action(action)

        p.stepSimulation()

        ob2 = self.step_observation()

        reward = self.step_reward(ob2)

        done = self.step_done(ob2)

        return (ob2, reward, done, ob2[0][4])

    def step_action(self, action):

        acceleration = self.action_range[action]
        self.vt += acceleration
        self.vt = max(-25, min(self.vt, 25))
        # execute the action
        p.setJointMotorControl2(bodyUniqueId = self.botId,
                                jointIndex = 0,
                                controlMode = p.VELOCITY_CONTROL,
                                targetVelocity = self.vt)
        p.setJointMotorControl2(bodyUniqueId = self.botId,
                                jointIndex = 1,
                                controlMode = p.VELOCITY_CONTROL,
                                targetVelocity = -self.vt)

    def step_observation(self):

        base_pos, base_orn = p.getBasePositionAndOrientation(self.botId)
        base_orn = p.getEulerFromQuaternion(base_orn)
        base_linV, bas_anguV = p.getBaseVelocity(self.botId)
        _, joint_V, _, _ = p.getJointState(self.botId, 0)

        observation = torch.tensor([base_orn[0], bas_anguV[0], base_linV[1], joint_V, base_pos[1]], dtype=torch.float)
        observation = torch.unsqueeze(observation, 0)
        #print(observation)

        return observation

    def step_reward(self, ob2):
        #-exp(2*(x+0.2)^2)+1
        reward = -exp(2*(ob2[0][0]+0.05)**2)+1 + 2*ob2[0][4] + 4*ob2[0][2]
        reward = torch.tensor([reward], dtype=torch.float)
        reward = torch.unsqueeze(reward, 0)

        return reward

    def step_done(self, ob2):

        done = abs(ob2[0][0]) > 1.2

        return done

class DQN():

    def __init__(self):

        self.greedy_end = 0.05
        self.memory_size = memory_size
        self.anneal = 0.05 / self.memory_size # check!!!!

        self.memory = []
        self.Transition = namedtuple('Transition', ('state', 'action', 'reward', 'next_state'))

        self.dqnNet = Net()
        self.dqnNet.zero_grad()
        self.optimizor = optim.RMSprop(self.dqnNet.parameters(), lr=0.001)
        #Surprisingly, RMSprop+smooth_l1_loss is much better than SGD+MSELoss, especially the optimizor.

        self.targetNet = copy.deepcopy(self.dqnNet)
        self.targetNet.zero_grad()

    def store_transitions(self, ob, action, reward, ob2):

        if(step_count < self.memory_size):
            self.memory.append(None)
            self.memory[step_count] = self.Transition(ob, action, reward, ob2)
        else:
            position = step_count % self.memory_size
            self.memory[position] = self.Transition(ob, action, reward, ob2)

    def step_action(self, ob, steps):

        a = random.random()

        # annealing greedy (0.9 - 0.1)
        if(steps > self.memory_size):
            greedy = self.greedy_end
        else:
            greedy = 0.9 - self.anneal * steps

        if(a < greedy):
            action = random.randint(0, ac_size - 1)
        else:
            self.dqnNet = self.dqnNet.eval()
            output = self.dqnNet(ob)
            _, index = torch.max(output, dim=1)
            action = index.item()
            self.dqnNet = self.dqnNet.train()

        return action

    def learn(self):

        input_state = torch.zeros(batch_size, ob_size)
        input_nextState = torch.zeros(batch_size, ob_size)
        reward = torch.zeros(batch_size, 1)
        target_Q = torch.zeros(batch_size, 1)
        current_Q = torch.zeros(batch_size, 1)
        nextState_max = torch.zeros(batch_size, 1)

        # randomly sampled from experience
        drawn = random.sample(range(self.memory_size), batch_size)

        for i in range(batch_size):
            input_state[i] = self.memory[drawn[i]][0]
            input_nextState[i] = self.memory[drawn[i]][3]

        # calculate current/target q (action) values
        output_state = self.dqnNet(input_state)
        output_nextState = self.targetNet(input_nextState)
        output_nextState = output_nextState.detach()

        # get current state-action value and maximum target q_value
        for i in range(batch_size):
            a = self.memory[drawn[i]][1]
            current_Q[i] = output_state[i][a]

            reward[i] = self.memory[drawn[i]][2]
            _, index = torch.max(output_nextState[i], 0)
            nextState_max[i] = output_nextState[i][index]

        target_Q = reward + gamma * nextState_max

        # update neural network
        loss = F.smooth_l1_loss(current_Q, target_Q)
        self.optimizor.zero_grad()
        loss.backward()
        self.optimizor.step()

def main():

    global targetNet_step, step_count, train_flag

    env1 = Env()

    dqn = DQN()

    for episode in range(episode_count):#episode_count

        ob = env1.reset()

        survival = 0

        while True:

            action = dqn.step_action(ob, step_count)

            ob2, reward, done, base_pos = env1.step(action, ob)

            # store memory
            dqn.store_transitions(ob, action, reward, ob2)

            # train
            if(step_count>memory_size and train_flag):
                if(step_count == memory_size + 1):
                    print('-------------learning_start-------------')
                dqn.learn()
                targetNet_step += 1
                if(targetNet_step>target_update):
                    dqn.targetNet = copy.deepcopy(dqn.dqnNet)
                    targetNet_step = 0

            ob = ob2
            survival += 1
            step_count += 1
            if(done or survival>1999 or base_pos>9):
                print('Episode:', episode, ' survival:', survival, ' position: %.2f' % base_pos, 'action: %.2f' % action,
                      'base_linV: %.2f' % ob2[0][2], 'joint_V: %.2f' % ob2[0][3],)
                record_survival.append(survival)
                record_position.append(base_pos)
                if(base_pos>7):
                   train_flag = False
                   print('--------------Training STOP--------------')
                break

if __name__ == '__main__':

    random.seed(1) #2 # 1
    torch.manual_seed(1) # 2 # 1

    ob_size = 5
    ac_size = 21

    # for bullet environment
    StartOrien = p.getQuaternionFromEuler([0, 0, 0])
    StartPos = [0, 0, 0]
    action_bound = torch.tensor([[4]], dtype=torch.float)

    # for deep Q network
    episode_count = 1000 # 2000 # 1000
    memory_size = 10000 # 100000 # 10000
    step_count = 0
    batch_size = 32 # 64 # 32
    gamma = 0.99
    target_update = 100
    targetNet_step = 0

    train_flag = True
    record_survival = []
    record_position = []

    main()


from django import forms
from schedule.models import Enrolled
from django.utils.translation import ugettext_lazy as _

class DateInput(forms.DateInput):
    input_type = 'date'

class CompleteProfile(forms.ModelForm):
    class Meta:
        model = Enrolled
        exclude = ['user']
        labels = {
            'name': _('Nombre(s)'),
            'lastname': _('Apellidos'),
            'birth_date': _('Fecha de nacimiento'),
            'gender': _('Género'),
            'phone': _('Teléfono'),
            'address': _('Dirección'),
            'city': _('Ciudad'),
            'country': _('País'),
            'zip_code': _('Código Postal'),
            'academy': _('Academia'),
            'disease': _('Enfermedades'),
            'blood_type': _('Tipo de sangre'),
        }
        widgets = {
            'birth_date': DateInput(),
        }

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)


# support for tooltip showing original text ----------------------------
import sphinx

from os import path
from typing import Any, Text

from docutils.nodes import (
    Element,
    Node,
    NodeVisitor,
    TextElement,
    image,
    literal_block,
    raw,
)
from docutils.utils import relative_path
from docutils.writers._html_base import HTMLTranslator
from sphinx.addnodes import toctree
from sphinx.application import Sphinx
from sphinx.builders.html import StandaloneHTMLBuilder
from sphinx.locale import init as init_locale
from sphinx.transforms import SphinxTransform
from sphinx.util import logging
from sphinx.util.fileutil import copy_asset
if sphinx.version_info[0] >= 2:
    from sphinx.util.i18n import docname_to_domain
else:
    from sphinx.util.i18n import find_catalog as docname_to_domain
from sphinx.util.nodes import extract_messages

logger = logging.getLogger(__name__)

class LocaleOriginalText(TextElement):
    pass

def visit_locale_original_text(self: NodeVisitor, node: TextElement) -> None:
    if isinstance(self, HTMLTranslator):
        self.body.append(self.starttag(node, "span"))
    else:
        logger.warning(
            "self '{}' is not an instance of HTMLTranslator".format(self)
        )

def depart_locale_original_text(self: NodeVisitor, node: TextElement) -> None:
    if isinstance(self, HTMLTranslator):
        self.body.append("</span>")
        # logger.info(node)
    else:
        logger.warning(
            "self '{}' is not an instance of HTMLTranslator".format(self)
        )

ORIGINAL_TEXT_ATTR = "data-trans-original-text"
ORIGINAL_TEXT_CSS = "trans-original-text"
TRANSLATED_TEXT_CSS = "trans-translated-text"

# custom transform for keep left original text translated, implemented
# based on (mostly copied from) sphinx.transforms.i18n.Locale
class PreserveLocaleOriginalMessage(SphinxTransform):
    """
    Add locale original text to translated nodes as %s attribute.
    """ % ORIGINAL_TEXT_ATTR

    # 20 is the priority of sphinx.transforms.i18n.Locale
    default_priority = 15
    # default_priority = 20

    logger = logging.getLogger(__name__)

    def apply(self, **kwargs: Any) -> None:
        source = self.document["source"]
        msgstr = ""

        # XXX check if this is reliable
        assert source.startswith(self.env.srcdir)
        docname = path.splitext(
            relative_path(path.join(self.env.srcdir, "dummy"), source)
        )[0]
        textdomain = docname_to_domain(docname, self.config.gettext_compact)

        # fetch translations
        dirs = [
            path.join(self.env.srcdir, directory)
            for directory in self.config.locale_dirs
        ]
        # sphinx.locale.init changes its args type by version
        # so, ignore mypy check for the following call
        catalog, has_catalog = init_locale(
            dirs, self.config.language, textdomain  # type: ignore
        )
        if not has_catalog:
            return

        # for translated text keep original as ORIGINAL_TEXT_ATTR attribute
        for node, msg in extract_messages(self.document):
            msgstr = catalog.gettext(msg)
            if not msgstr or msgstr == msg or not msgstr.strip():
                # as-of-yet untranslated
                continue
            # self.logger.info("add %s attr to node." % ORIGINAL_TEXT_ATTR)
            node[ORIGINAL_TEXT_ATTR] = msg

def is_translated_node(node: Node) -> bool:
    if not isinstance(node, Element):
        return False
    return ORIGINAL_TEXT_ATTR in node.attributes

def append_css_class(node: Element, class_: Text) -> None:
    node.coerce_append_attr_list("classes", class_)

def is_gettext_additional_targets(node: Node) -> bool:
    # This func judges if passed `node` is one of the following, which can be
    # tranlated by `gettext_addtional_targets` setting and is not supported by
    # this sphinx extension:
    # - toctree (with hidden attribute as True)
    # - literal-block
    # - raw
    # - image

    # hidden toc element
    if isinstance(node, toctree) and node.get("hidden", None) is True:
        return True

    # literal_block / raw / image nodes are not supported since they are not
    # supported due to implementation issue, e.g. compatibility with code-block
    # highlight HTML writing
    elif (
        isinstance(node, literal_block)
        or isinstance(node, raw)
        or isinstance(node, image)
    ):
        return True
    else:
        return False

class PostProcessTranslatedNode(SphinxTransform):
    """
    Add %s class attribute to translated text node.
    Append locale original text node with %s class to translated text node.
    """ % (
        TRANSLATED_TEXT_CSS,
        ORIGINAL_TEXT_CSS,
    )

    # 20 is the priority of sphinx.transforms.i18n.Locale
    # 80 is the priority of sphinx.transforms.i18n.RemoveTranslatableInline
    default_priority = 999
    # default_priority = 20

    logger = logging.getLogger(__name__)

    def apply(self, **kwargs: Any) -> None:
        # XXX check if this is reliable
        source = self.document["source"]
        assert source.startswith(self.env.srcdir)

        for node in self.document.traverse(is_translated_node):
            # some tranlated node for gettext_additional_targets setting is
            # not supported by this sphinx extension. The target may be the
            # followings:
            # - toctree (with hidden attribute as True)
            # - literal-block
            # - raw
            # - image
            if is_gettext_additional_targets(node):
                continue

            # add TRANSLATED_TEXT_CSS to classes
            append_css_class(node, TRANSLATED_TEXT_CSS)

            # append original msg node as LocaleOriginalText node
            orig_text_node = LocaleOriginalText(text=node[ORIGINAL_TEXT_ATTR])
            append_css_class(orig_text_node, ORIGINAL_TEXT_CSS)
            node.append(orig_text_node)

def setup(app: Sphinx) -> None:
    # display builder info to check what builder is used
    # e.g. to check the builder in external env such as readthedocs
    def show_builder_name(event_app: Sphinx) -> None:
        logger.info("builder name: %s" % event_app.builder.name)
        logger.info(event_app.builder)

    app.connect("builder-inited", show_builder_name)

    # for original text tooltip support
    def setup_html_builder_extras(event_app: Sphinx) -> None:
        lang = event_app.config.language  # type: ignore
        if lang is None:
            return
        if not isinstance(event_app.builder, StandaloneHTMLBuilder):
            return
        event_app.add_transform(PreserveLocaleOriginalMessage)
        event_app.add_transform(PostProcessTranslatedNode)
        event_app.add_css_file("trans-tooltip.css")
        # register new Node type with vistor methods
        event_app.add_node(
            LocaleOriginalText,
            html=(visit_locale_original_text, depart_locale_original_text),
        )

    app.connect("builder-inited", setup_html_builder_extras)

    def copy_asset_files(event_app: Sphinx, exception: Exception) -> None:
        if not exception:
            src_static_dir = path.join(path.dirname(__file__), "_static")
            dst_static_dir = path.join(event_app.outdir, "_static")
            # logger.info("__file__: %s" % __file__)
            # logger.info("src_static_dir: %s" % src_static_dir)
            # logger.info("dst_static_dir: %s" % dst_static_dir)
            copy_asset(src_static_dir, dst_static_dir, context={})

    app.connect("build-finished", copy_asset_files)


import os
import glob
from collections import Counter

basedir = "/devdata/home/pishichan/code/asr/data/mandarin/supervised"
all_lines = []

search_path = os.path.join(basedir, '*/*/' + "trans.txt")
for fname in glob.iglob(search_path, recursive=True):
    cur_trans_path = os.path.realpath(fname)
    cur_dir = os.path.dirname(cur_trans_path)
    print("cur process trans_file: %s" % cur_trans_path)
    save_line_list = []
    rm_cnt = 0
    audio_handle_list = []
    with open(cur_trans_path, "r") as fr:
        for cur_line in fr:
            audio_handle, cur_trans = cur_line.strip().split("<--->")
            audio_handle_list.append(audio_handle)
            audio_path = os.path.join(cur_dir, "wav", audio_handle + ".wav")
            if os.path.exists(audio_path):
                save_line_list.append(cur_line)
            else:
                rm_cnt += 1
                print("cur audio: %s do not exist. " % audio_path)

    print("len(audio_handle_list) = %d " % len(audio_handle_list))
    b = dict(Counter(audio_handle_list))
    print([key for key, value in b.items() if value > 1])  # 只展示重复元素
    audio_handle_list = list(set(audio_handle_list))
    print("len(audio_handle_list) = %d " % len(audio_handle_list))

    if rm_cnt > 0:
        new_file_path = cur_trans_path.replace(".txt", "_new.txt")
        with open(new_file_path, "w") as fw:
            for cur_line in save_line_list:
                fw.write(cur_line)
print("all done!")


n = int(input())
s = []
for _ in range(n):
    L, H = map(int,input().split())
    s.append([-H, L])
s.sort()
result = -s[0][0]
l_s, r_s = 0, 0

mid = s[0][1]
l, r = mid, mid
for i in range(1, n):
    H, L = s[i]
    if L > r:
        r_s = abs(L - r)
        result += -H * r_s
        r = L
    elif L < l:
        l_s = abs(L - l)
        result += -H * l_s
        l = L
print(result)


import unittest

from src.vidsegment.utils.seconds_to_time import seconds_to_time

class SecondsToTimeTests(unittest.TestCase):
    def test_seconds_to_time(self):
        entries = {
            1: '00:01',
            23: '00:23',
            60: '01:00',
            47.23: '00:47.23',
            12.0: '00:12',
            60 + 23: '01:23',
            19 * 60 + 27: '19:27',
            2 * 3600 + 5 * 60 + 22: '02:05:22',
            1 * 3600 + 2 * 60 + 3: '01:02:03',
        }

        for key, val in entries.items():
            with self.subTest(seconds=key):
                if val is not None:
                    self.assertEqual(val, seconds_to_time(key))
                else:
                    with self.assertRaises(ValueError):
                        seconds_to_time(key)


import sys
import pefile
import binascii
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QTextEdit, QVBoxLayout, QWidget, QPushButton

class StaticMalwareAnalyzerApp(QMainWindow):
    def __init__(self):
        super(StaticMalwareAnalyzerApp, self).__init__()

        self.setWindowTitle("Static Malware Analyzer")
        self.setGeometry(100, 100, 800, 600)

        self.central_widget = QWidget(self)
        self.setCentralWidget(self.central_widget)

        self.layout = QVBoxLayout(self.central_widget)

        self.txt_file_content = QTextEdit(self.central_widget)
        self.layout.addWidget(self.txt_file_content)

        self.btn_analyze = QPushButton("Analyze File", self.central_widget)
        self.btn_analyze.clicked.connect(self.analyze_file)
        self.layout.addWidget(self.btn_analyze)

        self.txt_report = QTextEdit(self.central_widget)
        self.layout.addWidget(self.txt_report)

    def analyze_file(self):
        file_dialog = QFileDialog()
        file_path, _ = file_dialog.getOpenFileName(self, "Select a file", "", "Executable Files (*.exe);;All Files (*)")
        if file_path:
            self.clear_results()
            self.display_file_content(file_path)
            self.analyze_pe_header(file_path)
            self.analyze_strings(file_path)

    def clear_results(self):
        self.txt_file_content.clear()
        self.txt_report.clear()

    def display_file_content(self, file_path):
        try:
            with open(file_path, 'rb') as file:
                content_hex = binascii.hexlify(file.read()).decode('utf-8')
                self.txt_file_content.setPlainText(content_hex)
        except Exception as e:
            self.txt_report.append(f"Error reading file: {str(e)}")

    def analyze_pe_header(self, file_path):
        try:
            pe = pefile.PE(file_path)
            self.txt_report.append(f"\nPE Header Analysis:\n")
            self.txt_report.append(f"Image Base: 0x{pe.OPTIONAL_HEADER.ImageBase:08X}")
            self.txt_report.append(f"Entry Point: 0x{pe.OPTIONAL_HEADER.AddressOfEntryPoint:08X}")
            self.txt_report.append(f"Sections:")
            #for section in pe.sections:
                #self.txt_report.append(f"  - {section.Name.decode(errors='ignore').rstrip('\\x00')}")

        except pefile.PEFormatError as e:
            self.txt_report.append(f"\nError analyzing PE header: {str(e)}")

    def analyze_strings(self, file_path):
        try:
            with open(file_path, 'rb') as file:
                content = file.read().decode(errors='ignore')
                strings = [s for s in content.split('\x00') if s]
                self.txt_report.append(f"\nString Analysis:\n")
                for string in strings:
                    self.txt_report.append(f"  - {string}")

        except Exception as e:
            self.txt_report.append(f"\nError analyzing strings: {str(e)}")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    mainWindow = StaticMalwareAnalyzerApp()
    mainWindow.show()
    sys.exit(app.exec_())


#!/usr/bin/env python
# coding: utf-8

# In[1]:

n = 5
coin = [3, 2, 1, 1, 9]

# In[13]:

from itertools import combinations
can_made = list({sum(j) for i in range(1, n+1) for j in combinations(coin, i)}) #만들 수 있는 금액 합계
can_made

# In[16]:

max(can_made)

# In[18]:

for idx in range(max(can_made)):
    if can_made[idx+1] == can_made[idx] + 1: #연속적인 숫자 나열 중 빠진 부분, 즉 만들 수 없는 최솟값
        pass
    else:
        result = can_made[idx] + 1
        break
result

# In[ ]:

#시간 복잡도가 조금.. 비싸긴 하다. 그러나 이런 방법도 있다는 차원.

# In[19]:

#답지 복습:
#Key-Idea: target 보다 작거나 같은 수가 있다면 만들 수 있고, target에 그 수를 더한 값 -1 까지 만들 수 있다.

target =1 #동전의 최솟값은 1

coin.sort() #오름차순 정렬해서, 작은 수부터 차례대로 뽑기만 하면 되도록 하자.

for i in coin:
    if i <= target:
        target += i #target보다 작은 값만큼 만들 수 있는 범위 확장, 이 값부터 다시 확인.
    else:
        result = target
        break
result


from compas.geometry import Point, Line, Polyline, Bezier, Box
from compas.geometry import Frame, Transformation
from compas.utilities import window

from compas_view2.app import App

curve = Bezier([Point(0, 0, 0), Point(3, 6, 0), Point(6, -3, 3), Point(10, 0, 0)])

points = curve.locus(resolution=50)

T = []
N = []
for a, b, c in window(points, 3):
    if a and c:
        t = c - a
        n = (c - b).cross(a - b).cross(t)
        T.append(t)
        N.append(n)

frames = []
for p, t, n in zip(points[1:-1], T, N):
    frames.append(Frame(p, t, n))

viewer = App(width=1200, height=750)
viewer.view.camera.rz = 90
viewer.view.camera.rx = -75
viewer.view.camera.tx = 0
viewer.view.camera.ty = -1
viewer.view.camera.distance = 6

viewer.add(Polyline(curve.locus()), linewidth=3)
viewer.add(Polyline(curve.points), show_points=True, linewidth=0.5)

for frame in frames:
    viewer.add(frame, linewidth=3)

viewer.show()


import sqlite3
from sqlite3 import Error

# ponizsze funckje odpalone tylko raz - zeby utworzyc db
"""
def create_gamedata(conn, game_data):
    sql = ''' INSERT INTO GAME_DATA(high_score, coins, car0_unlocked, car1_unlocked, car2_unlocked, games_played, total_time_ig)
            VALUES(?,?,?, ?,?,?, ?) '''
    cur = conn.cursor()
    cur.execute(sql, game_data)
    conn.commit()
    return cur.lastrowid

def create_table(conn, create_table_sql):
    try:
        c = conn.cursor()
        c.execute(create_table_sql)
    except Error as e:
        print(e)

def run_once():
    db = 'baza2.db'
    sql_create_gamedata_table = ''' CREATE TABLE IF NOT EXISTS GAME_DATA (
                                        high_score integer,
                                        coins integer,
                                        car0_unlocked integer,
                                        car1_unlocked integer,
                                        car2_unlocked integer,
                                        games_played integer,
                                        total_time_ig integer
                                    ); '''

    conn = create_connection(db)

    with conn:
        create_table(conn, sql_create_gamedata_table)

        game_data = (0, 0, 1, 0, 0, 0, 0)
        gamedata_id = create_gamedata(conn, game_data)

"""

db_file = 'baza2.db'

def create_connection(db_file):
    '''create a database connection to a SQLite database'''
    # obiekt połączenia - póki co None
    conn = None
    try:
        # fcja connect zwraca obiekt Connection
        # na którym można wykonać operacje
        conn = sqlite3.connect(db_file)
        print(sqlite3.version)
    except Error as e:
        print(e)

    return conn

def get_coins(cur):
    return cur.execute("SELECT coins FROM game_data").fetchone()[0]

def update_coins(conn, coins):
    cur = conn.cursor()
    current_coins = get_coins(cur)

    sql = ''' UPDATE GAME_DATA
            SET coins = ?'''

    cur.execute(sql, (current_coins + coins, ))
    conn.commit()

def get_highscore(cur):
    # dostaje kursor i zwraca high score
    return cur.execute("SELECT high_score FROM game_data").fetchone()[0]

def update_highscore(conn, score):

    cur = conn.cursor()
    current_hs = get_highscore(cur)
    print(current_hs)
    if score > current_hs:
        sql = ''' UPDATE GAME_DATA
                SET high_score = ?'''
        cur.execute(sql, (score, ))
        conn.commit()

def update_games_played(conn):
    cur = conn.cursor()
    games_played = cur.execute("SELECT games_played FROM game_data").fetchone()[0]
    sql = ''' UPDATE GAME_DATA
            SET games_played = ?'''
    cur.execute(sql, (games_played + 1, ))
    conn.commit()

def update_total_time_ig(conn, time):
    '''dostaje czas w ms, przelicza na sekundy i dodaje do calkowitego
    no i wpisuje to do bazy'''
    cur = conn.cursor()
    ttig = cur.execute("SELECT total_time_ig FROM game_data").fetchone()[0]
    time_updated = ttig + round(time, -3)/1000
    sql = ''' UPDATE GAME_DATA
            SET total_time_ig = ?'''
    cur.execute(sql, (time_updated, ))
    conn.commit()

def unlock_car(conn, car_id):
    '''dostaje id auta do odblokowania 1 lub 2
    sprawdza czy auto nie jest juz odblokowane
    no i wpisuje to do bazy. odblokowane auto oznaczone jest jako 1'''
    cur = conn.cursor()
    is_unlocked = cur.execute(f"SELECT car{car_id}_unlocked FROM game_data").fetchone()[0]
    if not is_unlocked:
        sql = f''' UPDATE GAME_DATA
                SET car{car_id}_unlocked = ?'''
        cur.execute(sql, (1, ))
        conn.commit()

def main():
    database = 'baza2.db'

    # create a database connection
    conn = create_connection(database)
    with conn:
        update_coins(conn, 5)
        update_highscore(conn, 2000)
        update_games_played(conn)
        update_total_time_ig(conn, 4769)
        unlock_car(conn, 1)

if __name__ == '__main__':
    main()


import pytest
from mockito import mock, spy, verify

from ...src.logic.DataProcessingEntity import DataProcessingEntity

@pytest.mark.usefixtures('unstub')
class TestDataProcessingEntity:
    def setup_class(self):
        self.__depth_estimation = mock()
        self.__object_detection = mock()
        self.__database_handler = mock()
        self.__position_reconstruction = mock()
        self.__data_processing_entity = DataProcessingEntity(0, 0, 0, 0, 0, self.__depth_estimation, self.__object_detection, self.__database_handler, self.__position_reconstruction, False)

    def test_when_ProcessData_then_ProcessingEntitiesCalledExactlyOnce(self):
        spy(self.__depth_estimation)
        spy(self.__object_detection)

        self.__data_processing_entity.process_frame([[[]]])

        verify(self.__depth_estimation).process_frame(...)
        verify(self.__object_detection).process_frame(...)


def stringPermutations(strr):
    perms = []
    perms.append(strr)

    # processing every char of the string one by one
    for i in range(len(strr)):
        # do following only if char is alpha
        if strr[i].isalpha():
            # recording len before, since ele will be added to perms
            n = len(perms)
            # using all previous perms to create new perms for ith char
            for j in range(n):
                # converting to list cause str is immutable
                newPerm = list(perms[j])
                # for ith char
                newPerm[i] = newPerm[i].swapcase()
                # back to str and append finally to perms
                perms.append(''.join(newPerm))

    return perms

print(stringPermutations("ab7c"))

10. Subsets/4_Letter case permutations (medium).py


import pandas as pd
from db_read_write import select_distinct_from_db
from db_read_write import select_with_condition_from_db

# Setting values
db_name='Gazprom_Energy_db'
validity = 'not valid'

while validity == 'not valid':
    # Gets input from the user via the commandline/console
    user_input= input('Please choose which requirement you would like to fulfill by typing the number followed by enter.\n\n1 - Get number of meters in the db \n2 - Get all data for given meter \n3 - Get the amount of files in the db \n4 - Get the latest uploaded filename \n')

    if user_input == '1':
        # Setting relivant values
        table_name='Meter_Information'
        value='Meter_Number'
        rows = select_distinct_from_db(db_name,table_name,value)
        count = 0

        for row in rows:
            count = count + 1 # Counts number of rows returned

        print('There is {number_of_meters} meter(s) in the database'.format(number_of_meters=count))
        print(rows)
        validity = 'valid' # Sets validity to valid meaning that the loop will complete

    elif user_input == '2':
        # Setting relivant values
        table_name='Meter_Information'
        value='Meter_Number'
        columns='Meter_Number,Measurement_Date,Measurement_Time,Consumption,File_generation_number'

        # Gets the user to input the specific meter nuber that is to be queried
        user_defined_number = input('\nPlease type the exact meter number followed by enter to find the data held on that meter\n')
        rows = select_with_condition_from_db(db_name,table_name,value,columns,user_defined_number)
        df = pd.DataFrame(rows,columns=['Meter_Number','Measurement_Date','Measurement_Time','Consumption','File_generation_number'])
        if df.empty == True:
            print('The file {user_file} could not be found in the db'.format(user_file = user_defined_number))
            validity = 'not valid' # Sets validity to invalid meaning that the loop will not complete
        else:
            print(df)
            validity = 'valid' # Sets validity to valid meaning that the loop will complete

    elif user_input == '3':
        # Setting relivant values
        table_name='Files'
        values='File_generation_number'
        rows = select_distinct_from_db(db_name,table_name,value)
        count = 0

        for row in rows:
            count = count + 1 # Counts number of rows returned

        print('There is {number_of_files} file(s) that has been recieved and is in the database'.format(number_of_files=count))
        print(rows)
        validity = 'valid' # Sets validity to valid meaning that the loop will complete

    elif user_input == '4':
        # Setting relivant values
        table_name='Files'
        values='File_generation_number,Received_datetime'

        rows = select_distinct_from_db(db_name,table_name,values)
        df = pd.DataFrame(rows,columns=['File_generation_number','Received_datetime'])
        df['Received_datetime'] = df['Received_datetime'].astype('datetime64[ns]')

        # Gets the latest time from the retrieved results
        latest_datetime = df.Received_datetime.max()
        latest_file = df.loc[df['Received_datetime'] == latest_datetime, 'File_generation_number']
        latest_file = latest_file.values[0]

        print('The latest file is {file} which was recived at {datetime}'.format(
            file = latest_file,
            datetime = latest_datetime))
        validity = 'valid' # Sets validity to valid meaning that the loop will complete

    else:
        print ('Please select either 1,2,3 or 4 followed by the enter key')
        validity = 'not valid' # Sets validity to invalid meaning that the loop will not complete


from django.core.management.base import BaseCommand, CommandError
from city.models import City
cities = ['Kherson', 'Kiev', 'Nikolaev']

'''
for i in range(1,60)
    pass

'''

class Command(BaseCommand):

    def handle(self, *args, **options):

        print('Load cities')
        City.objects.all().delete()
        for item in cities:
            c = City()
            c.name = item
            c.save()
            print('Saving...%s' % item)


#Problem statement at: https://www.hackerrank.com/challenges/30-2d-arrays/

#!/bin/python3

import math
import os
import random
import re
import sys

def hourglassSum(arr):
    sum_list=[]
    for i in range(0,4):
        for j in range(0,4):
            sum_list.append(arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2])
    return max(sum_list)

if __name__ == '__main__':
    arr = []

    for _ in range(6):
        arr.append(list(map(int, input().rstrip().split())))
    result = hourglassSum(arr)
    print((str(result) + '\n'))


from tabulate import tabulate
from ipykernel.kernelbase import Kernel

from pytezos.repl.helpers import helpers_prim
from pytezos.michelson.macros import primitives
from pytezos.repl.interpreter import Interpreter

from michelson_kernel import __version__
from michelson_kernel.docs import docs

static_macros = [
    'CMPEQ', 'CMPNEQ', 'CMPLT', 'CMPGT', 'CMPLE', 'CMPGE',
    'IFEQ', 'IFNEQ', 'IFLT', 'IFGT', 'IFLE', 'IFGE',
    'IFCMPEQ', 'IFCMPNEQ', 'IFCMPLT', 'IFCMPGT', 'IFCMPLE', 'IFCMPGE',
    'FAIL',
    'ASSERT_EQ', 'ASSERT_NEQ', 'ASSERT_LT', 'ASSERT_GT', 'ASSERT_LE', 'ASSERT_GE',
    'ASSERT_CMPEQ', 'ASSERT_CMPNEQ', 'ASSERT_CMPLT', 'ASSERT_CMPGT', 'ASSERT_CMPLE', 'ASSERT_CMPGE',
    'ASSERT_NONE', 'ASSERT_SOME', 'ASSERT_LEFT', 'ASSERT_RIGHT',
    'UNPAIR',
    'IF_SOME',
    'SET_CAR', 'SET_CDR',
    'MAP_CAR', 'MAP_CDR'
]

def parse_token(line, cursor_pos):
    begin_pos = next((i + 1 for i in range(cursor_pos - 1, 0, -1) if line[i] in ' ;({\n'), 0)
    end_pos = next((i for i in range(cursor_pos, len(line)) if line[i] in ' ;){\n'), len(line))
    return line[begin_pos:end_pos], begin_pos, end_pos

def html_table(items):
    def pre(s):
        return f'
{s}
'

    def pre_dict(d):
        return {k: pre(v) for k, v in d.items()}

    res = tabulate(list(map(pre_dict, items)), tablefmt='html', headers="keys")
    res = res.replace('<', '<').replace('>', '>')  # tabulate escapes our
 tags
    return res

def plain_table(items):
    return tabulate(items, tablefmt='simple', headers="keys")

def format_result(result, execution_count):
    kind = result['kind']
    if kind in ['message', 'code']:
        plain, html = result['value'], result['value']
    elif kind in ['stack', 'big_map_diff']:
        plain = plain_table(result['value'])
        html = html_table(result['value'])
    elif kind == 'output':
        ops, storage, bmd = result['value']
        data = list(filter(lambda x: len(x) > 0, [storage, bmd, ops]))
        plain = '\n'.join(map(plain_table, data))
        html = '
'.join(map(html_table, data))
    else:
        assert False, kind
    return {'data': {'text/plain': plain,
                     'text/html': html},
            'metadata': {},
            'execution_count': execution_count}

class MichelsonKernel(Kernel):
    implementation = 'IMichelson'
    implementation_version = __version__
    language_info = {
        'name': 'Michelson',
        'mimetype': 'text/x-michelson',
        'file_extension': '.tz',
        'codemirror_mode': 'michelson'
    }
    banner = 'Michelson (Tezos VM language)'
    help_links = [
        'https://michelson.nomadic-labs.com/',
        'https://tezos.gitlab.io/whitedoc/michelson.html'
    ]

    def __init__(self, **kwargs):
        super(MichelsonKernel, self).__init__(**kwargs)
        self.interpreter = Interpreter(debug=False)

    def do_execute(self, code, silent, store_history=True, user_expressions=None, allow_stdin=False):
        int_res = self.interpreter.execute(code)
        if not silent and int_res.get('stdout'):
            self.send_response(
                self.iopub_socket, 'stream', {'name': 'stdout',
                                              'text': int_res['stdout']})

        if int_res.get('success'):
            res = {'status': 'ok'}
            if not silent and int_res.get('result'):
                self.send_response(
                    self.iopub_socket, 'execute_result', format_result(int_res['result'], self.execution_count))
        else:
            res = {'status': 'error'}
            if int_res.get('stderr'):
                traceback = [f'{int_res["stderr"]["name"]}: {int_res["stderr"]["value"]}',
                             int_res["stderr"]["trace"]]
                res = {'ename': int_res['stderr']['name'],
                       'evalue': int_res['stderr']['value'],
                       'traceback': traceback}
                self.send_response(
                    self.iopub_socket, 'stream', {'name': 'stderr',
                                                  'text': '\n'.join(traceback)})

        res['execution_count'] = self.execution_count
        return res

    def do_complete(self, code, cursor_pos):
        token, begin_pos, end_pos = parse_token(code, cursor_pos)

        suggests = []
        for word_set in [primitives, static_macros, helpers_prim]:
            for word in word_set:
                if word.startswith(token):
                    suggests.append(word)

        if suggests:
            res = {
                'matches': suggests,
                'cursor_start': begin_pos,
                'cursor_end': end_pos}
        else:
            res = {
                'matches': [],
                'cursor_start': cursor_pos,
                'cursor_end': cursor_pos}

        res['status'] = 'ok'
        return res

    def do_inspect(self, code, cursor_pos, detail_level=0):
        token, _, _ = parse_token(code, cursor_pos)
        docstring = docs.get(token)
        if docstring:
            res = {
                'found': True,
                'data': {'text/plain': docstring}}
        else:
            res = {'found': False}

        res['status'] = 'ok'
        return res


import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.optim as optim
from CNNModel import CNNModel
from MyDataset import MyDataset
from torch.utils.data import DataLoader
import argparse
import yaml
from easydict import EasyDict

parser = argparse.ArgumentParser(description='Classifier Task With CNN')
parser.add_argument("--config_path", type=str, default="config.yaml")
args = parser.parse_args()
config_path =args.config_path
config = yaml.load(open(config_path, 'r'), Loader=yaml.Loader)
config = EasyDict(config)
config = config["CNN"]

train_path = config["Train"]["train_path"]
val_path = config["Val"]["val_path"]
class_num = config["General"]["class_num"]
batch_size = config["Train"]["batch_size"]
epochs = config["Train"]["epochs"]
lr = config["Train"]["lr"]
is_load = config["Train"]["is_load"]
load_path = config["Train"]["load_path"]
save_path = config["Train"]["save_path"]

def eval(model):
    eval_dataset = MyDataset(data_path = val_path,
                              class_num = class_num, )
    eval_loader = DataLoader(dataset = eval_dataset,
                              shuffle = True,
                              batch_size = batch_size,
                              drop_last = False)
    acc_num = 0
    for i, batch in enumerate(eval_loader):
        img_tensor, label_tensor = batch # torch.tensor
        with torch.no_grad():
            pred_tensor = model(img_tensor.to(device))
            for j in range(pred_tensor.size(0)):
                pred = torch.argmax(pred_tensor[j]).item()
                if pred==label_tensor[j]:
                    acc_num+=1

    acc_rate = acc_num / len(eval_dataset)
    print("Acc_rate %.2f%% \n" % (acc_rate*100))
    return acc_rate

if __name__ == "__main__":

    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    model = CNNModel()
    model.to(device)

    if is_load:
        print(" -------< Loading parameters from {} >------- \n".format(load_path))
        params = torch.load(load_path, map_location=device)
        model.load_state_dict(params, strict=True)

    # softmax
    loss_function = nn.CrossEntropyLoss()
    optimizer = optim.Adam(model.parameters(), lr=lr)

    train_dataset = MyDataset(data_path=train_path,
                              class_num=class_num, )
    train_loader = DataLoader(dataset = train_dataset,
                              shuffle = True,
                              batch_size = batch_size,
                              drop_last = True)
    best_acc = 0
    epoch_record_x = []
    acc_rate_record_y = []
    epoch_record_x.append(0)
    acc_rate_y = eval(model)
    acc_rate_record_y.append(acc_rate_y)

    for epoch in range(0, epochs+1):
        for i, batch in enumerate(train_loader):
            img_tensor, label_tensor = batch
            pred_tensor = model(img_tensor.to(device))
            loss = loss_function(pred_tensor, label_tensor.to(device))
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()

        if epoch % 5 == 0:
            print("Epoch" , epoch)
            epoch_record_x.append(epoch)
            acc_rate_y = eval(model)

            if best_acc < acc_rate_y:
                print(" -------< Saved Best Model >------- \n")
                torch.save(model.state_dict(), save_path)
                best_acc = acc_rate_y

            acc_rate_record_y.append(acc_rate_y)

    plt.plot(epoch_record_x, acc_rate_record_y,
                color="green", label="acc_rate_record")
    plt.title("Loss with epoch")
    plt.legend()
    plt.show()


from flow.petri_net.color import ColorDescriptor
from flow.petri_net.transitions.basic import BasicTransition
from test_helpers import NetTest
from unittest import main

import flow.redisom as rom

class TestBasic(NetTest):
    def setUp(self):
        NetTest.setUp(self)

    def test_consume_tokens_with_empty_marking(self):
        color_group = self.net.add_color_group(size=5)
        color = color_group.begin
        color_descriptor = ColorDescriptor(color, color_group)

        enabler = 2
        trans = self.setup_transition(BasicTransition, 10, 0)

        rv = trans.consume_tokens(enabler, color_descriptor,
                self.net.color_marking.key, self.net.group_marking.key)

        self.assertNotEqual(0, rv)

        self.assertEqual(0, len(trans.enablers))
        self.assertEqual(0,
                len(trans.active_tokens(color_descriptor).value))
        self.assertEqual(0, len(self.net.color_marking))
        self.assertEqual(0, len(self.net.group_marking))

        self.assertIn(trans.state_key(color_descriptor),
                trans.transient_keys)

    def test_consume_tokens_partially_ready(self):
        color_group = self.net.add_color_group(size=1)
        trans = self.setup_transition(BasicTransition, 3, 0)

        tokens = self._make_colored_tokens(color_group)

        num_successes = 0
        for i in trans.arcs_in:
            enabler = int(i)
            place_ids = range(enabler+1)
            for j in xrange(len(color_group.colors)):
                colors = color_group.colors[:j+1]

                color_descriptor = ColorDescriptor(j, color_group)

                self._put_tokens(place_ids, colors, color_group.idx, tokens)
                color_marking_copy = self.net.color_marking.value
                group_marking_copy = self.net.group_marking.value

                rv = trans.consume_tokens(enabler, color_descriptor,
                        self.net.color_marking.key, self.net.group_marking.key)

                if rv != 0:
                    self.assertEqual(color_marking_copy,
                            self.net.color_marking.value)
                    self.assertEqual(group_marking_copy,
                            self.net.group_marking.value)
                    self.assertEqual(0, len(trans.enablers))

                    self.assertIn(trans.state_key(color_descriptor),
                            trans.transient_keys)

                else:
                    num_successes += 1
                    self.assertEqual(0, len(self.net.color_marking.value))
                    self.assertEqual(0, len(self.net.group_marking.value))
                    self.assertEqual(enabler,
                            int(trans.enablers[color_group.idx]))
                    expected_token_keys = [str(x.index.value)
                            for x in tokens.values()]

                    self.assertItemsEqual(expected_token_keys,
                            trans.active_tokens(color_descriptor))

                    self.assertNotIn(trans.state_key(color_descriptor),
                            trans.transient_keys)

        self.assertEqual(1, num_successes)

    def test_push_tokens(self):
        color_group = self.net.add_color_group(size=1)
        color_descriptor = ColorDescriptor(color_group.begin, color_group)

        trans = self.setup_transition(BasicTransition, 4, 2)

        tokens = self._make_colored_tokens(color_group)

        self._put_tokens(trans.arcs_in, color_group.colors,
                color_group.idx, tokens)

        rv = trans.consume_tokens(0, color_descriptor,
                self.net.color_marking.key, self.net.group_marking.key)

        self.assertEqual(0, rv)
        self.assertEqual(1,
                len(trans.active_tokens(color_descriptor).value))

        self.assertIn(trans.active_tokens_key(color_descriptor),
                trans.transient_keys)

        rv = trans.push_tokens(self.net, color_descriptor, tokens.values())

        expected_color = {"0:4": 0, "0:5": 0}
        expected_group = {"0:4": 1, "0:5": 1}

        self.assertEqual(0,
                len(trans.active_tokens(color_descriptor).value))
        self.assertEqual(expected_color, self.net.color_marking.value)
        self.assertEqual(expected_group, self.net.group_marking.value)

        self.assertNotIn(trans.active_tokens_key(color_descriptor),
                trans.transient_keys)

if __name__ == "__main__":
    main()


from selenium import webdriver
import time
import math
import submit_web_form

link = "http://suninjuly.github.io/find_link_text"
browser = webdriver.Chrome()
text = str(math.ceil(math.pow(math.pi, math.e)*10000))

def form(url, string, webdriver):
    try:

        webdriver.get(url)
        clink = webdriver.find_element_by_partial_link_text(string)
        clink.click()
        time.sleep(2)
        submit_web_form.form_data(webdriver)

    finally:
        # успеваем скопировать код за 10 секунд
        time.sleep(10)
        # закрываем браузер после всех манипуляций
        webdriver.quit()
    return

form(link, text, browser)


import easyocr
import streamlit as st
import pandas as pd
import re
from pymongo import MongoClient
from PIL import Image

st.markdown(
    """
    <style>
    .main {
    background-color: #FF9DC4;
    }
    </style>
    """,
    unsafe_allow_html=True
    )

# To Display the title for the project
st.title("BizCardX: Extract Business Card Details with OCR")
st.header('(Credit: Mayur)')

#  Input for Collection name in database
name = st.text_input("Enter Your Name")

# upload button
uploaded_file = st.file_uploader("Choose a file")

if uploaded_file is not None:
        bytes_data = uploaded_file.getvalue()
        image = Image.open(uploaded_file)
        new_image = image.resize((500, 333))
        st.write("Image Preview")
        st.image(new_image)

        # showing the details
        show_details = st.button("Show Details")

        reader = easyocr.Reader(['en'])
        result1 = reader.readtext(bytes_data)

        # Creating string to iterate
        df1 = pd.DataFrame(result1, columns=['a', 'b', 'c'])
        name_list= df1['b'].tolist()
        my_string = ', '.join(name_list)

# Creating Patterns
        pattern1 = r"[A-Za-z]+(?:\s+[A-Za-z]+)*(?:\s+(?:&|-)\s+[A-Za-z]+(?:\s+[A-Za-z]+)*)*"
        match1 = re.search(pattern1, my_string)
        if match1:
            card_holder = match1.group()
        else:
            card_holder = 'NA'

        pattern2 = r'\b([A-Z]+[ -&]+[A-Z]+?)+\b'
        match2 = re.search(pattern2, my_string)
        if match2:
            designation = match2.group()
        else:
            designation = 'NA'

        #pattern3 = r"^\+91-\d{10},$"
        #pattern3 = r'[\+\(]?[1-9][0-9 .\-\(\)]{8,}[0-9]'
        pattern3 = r'\d{3}-\d{3}-\d{4}'
        match3 = re.search(pattern3, my_string)
        if match3:
            mobile = match3.group()
        else:
            mobile = 'NA'

        #pattern4 = r"[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+"
        pattern4 = r"\w+@\w+\.\w+"
        match4 = re.search(pattern4, my_string)
        if match4:
            email = match4.group()
        else:
            email = 'NA'

        pattern5 = r"\bglobal\.com\b"
        #pattern6 = r"https?://(?:www\.)?[A-Za-z0-9.-]+(?:\.[A-Za-z]{2,})?/?[A-Za-z0-9_./~#&=+-]*"
        match5 = re.search(pattern5, my_string)
        if match5:
            website = match5.group()
        else:
            website = 'NA'

        pattern6 = r"Andhra Pradesh|Arunachal Pradesh|Assam|Bihar|Chhattisgarh|Goa|Gujarat|Haryana|Himachal Pradesh|Jharkhand|Karnataka|Kerala|Madhya Pradesh|Maharashtra|Manipur|Meghalaya|Mizoram|Nagaland|Odisha|Punjab|Rajasthan|Sikkim|TamilNadu|Telangana|Tripura|Uttar Pradesh|Uttarakhand|West Bengal"
        match6 = re.search(pattern6, my_string)
        if match6:
            state = match6.group()
        else:
            state = 'NA'

        pattern7 = r"\d{6}"
        match7 = re.search(pattern7, my_string)
        if match7:
            pincode = match7.group()
        else:
            pincode = 'NA'

        l = [card_holder, designation, mobile, email, website, state, pincode]
        df = pd.DataFrame(l).T
        df.columns = ['Card_holder', 'Designation', 'Mobile', 'Email', 'Website', 'State', 'Pincode']

        # Showing details in dataframe form
        if show_details:
          st.write(df)

        upload = st.button('Upload to Database')

        # Codes to Store the Datas in to the Data Base
        client = MongoClient(("mongodb://localhost:27017"))
        # Data Base
        db = client["Card_Reader"]

        if upload:
            col1, col2 = st.columns(2)
            with col1:
                mydb = db[name]
                df.reset_index(inplace=True)
                df_dict = df.to_dict("records")
                mydb.insert_one({"index": name + 'data', "data": df_dict})
                st.write("Details uploaded")

        if upload:
            # downloading the data
             data_from_db = mydb.find_one({"index":name+'data'})
             df = pd.DataFrame(data_from_db["data"])
             df.to_csv("card.csv")
             df.to_json("card.json")

             col3, col4 = st.columns(2)
             with col3:
                 st.download_button("Download as CSV",
                                df.to_csv(),
                                mime = 'text/csv')
             with col4:
                 st.download_button("Download as Json",
                                df.to_json(),
                                mime='json')


# -*- coding: utf-8 -*-
# @Time    : 2020/7/12 10:38
# @Author  : sihao
# @File    : 递归-任意进制转换.py

def tostr(n,base):
    converString="0123456789ABCDEF"
    if n<base:
        return converString[n]
    else:
        return tostr(n//base,base)+converString[n%base]

print(tostr(2134,2))

数据结构的学习/递归-任意进制转换.py

递归-任意进制转换.py


import sys
input = sys.stdin.readline

n = int(input().rstrip())
maps = [list(input().rstrip()) for _ in range(n)]
garo = 0
sero = 0

for i in range(n):
    cnt = 0
    for j in range(n):
        if maps[i][j] == '.': cnt += 1
        else:
            if cnt >= 2: garo += 1
            cnt = 0

    if cnt >= 2: garo += 1

for j in range(n):
    cnt = 0
    for i in range(n):
        if maps[i][j] == '.': cnt += 1
        else:
            if cnt >= 2: sero += 1
            cnt = 0

    if cnt >= 2: sero += 1

print(garo, sero)

백준/Silver/1652. 누울 자리를 찾아라/누울 자리를 찾아라.py

누울 자리를 찾아라.py


from odoo_report_helper.report import Report

class EqReport(Report):
    def __init__(self, entry_name, report_name: str, report_type: str, model_name: str, eq_export_type="pdf",
                 print_report_name="Report",attachment="Report.pdf", eq_ignore_images=True, eq_ignore_html=False,
                 eq_export_complete_html=False,eq_export_as_sql=True, multi_print=False, attachment_use=False,
                 eq_print_button=False, dependencies=[], model_fields={}, calculated_fields={}, eq_merge_data_from_multi=False):
        self.entry_name = entry_name
        self.report_name = report_name
        self.report_type = report_type
        self.model_name = model_name
        self.print_report_name = print_report_name
        self.eq_export_type = eq_export_type
        self.attachment = attachment
        self.eq_ignore_images = eq_ignore_images
        self.eq_ignore_html = eq_ignore_html
        self.eq_export_complete_html = eq_export_complete_html
        self.eq_export_as_sql = eq_export_as_sql
        self.multi_print = multi_print
        self.attachment_use = attachment_use
        self.eq_merge_data_from_multi = eq_merge_data_from_multi
        self.eq_print_button = eq_print_button
        self._fields = model_fields
        self._calculated_fields = calculated_fields
        self._dependencies = dependencies
        self._data_dictionary = {}

    def self_ensure(self):
        """
            Before mapping the fields, the value dictionary for Odoo must be set.
        """
        self._data_dictionary = {
            'name': self.entry_name['ger'],
            'report_name': self.report_name,
            'report_type': self.report_type,
            'print_report_name': self.print_report_name,
            'model': self.model_name,
            'eq_export_type': self.eq_export_type,
            'eq_ignore_images': self.eq_ignore_images,
            'eq_ignore_html': self.eq_ignore_html,
            'eq_export_complete_html': self.eq_export_complete_html,
            'eq_export_as_sql': self.eq_export_as_sql,
            'eq_merge_data_from_multi': self.eq_merge_data_from_multi,
            'multi': self.multi_print,
            'attachment': self.attachment,
            'attachment_use': self.attachment_use,
            'eq_print_button': self.eq_print_button
        }

    def ensure_data_for_yaml(self):
        yaml_data = {'name': self.entry_name,
            'report_name': self.report_name,
            'report_type': self.report_type,
            'print_report_name': self.print_report_name,
            'report_model': self.model_name,
            'eq_export_type': self.eq_export_type,
            'eq_ignore_images': self.eq_ignore_images,
            'eq_ignore_html': self.eq_ignore_html,
            'eq_export_complete_html': self.eq_export_complete_html,
            'eq_export_as_sql': self.eq_export_as_sql,
            'eq_merge_data_from_multi': self.eq_merge_data_from_multi,
            'multiprint': self.multi_print,
            'attachment': self.attachment,
            'attachment_use': self.attachment_use,
            'eq_print_button': self.eq_print_button,
            'dependencies': [],
            'report_fields': self._fields,
            'calculated_fields': self._calculated_fields
        }
        return yaml_data


import pcbnew
import wx

class Create_Rectangular_Polygons ( pcbnew.ActionPlugin ):

    def defaults( self ):
        self.name = "Create Rectangular Polygons"
        self.category = "Modify PCB"
        self.description = "Creates Polygons for selectable net on F_Cu and B_Cu"

    def Run(self):
        class displayDialog(wx.Dialog):
            def __init__(self, parent):
                wx.Dialog.__init__(self, parent, id=-1, title="Polygon settings")#

                self.perform_changes = False
                self.netz = 0
                self.layer = 3
                self.clearance = 0.2
                self.distance = 0.5
                self.min_thickness = 0.175
                self.thermal_gap = 0.3

                self.panel = wx.Panel(self)
                vbox = wx.GridSizer(7, 2, 0, 0)

                l1 = wx.StaticText(self.panel, -1, "Connect to net:")
                vbox.Add(l1, 1, wx.ALIGN_RIGHT|wx.ALL,5)
                netList = [str(k) for k in pcbnew.GetBoard().GetNetsByName().keys()]
                self.t1 = wx.ComboBox(self.panel, choices=netList)
                self.t1.SetSelection(0)
                self.t1.Bind(wx.EVT_COMBOBOX, self.OnNet)
                vbox.Add(self.t1,1,wx.EXPAND|wx.ALIGN_LEFT|wx.ALL,5)

                l6 = wx.StaticText(self.panel, -1, "On PCB-Copper-Layer(s):")
                vbox.Add(l6, 1, wx.ALIGN_RIGHT|wx.ALL,5)
                layerList = ['Top and Bottom', 'Top', 'Bottom']
                self.t6 = wx.ComboBox(self.panel, choices=layerList)
                self.t6.SetSelection(0)
                self.t6.Bind(wx.EVT_COMBOBOX, self.OnLayer)
                vbox.Add(self.t6,1,wx.EXPAND|wx.ALIGN_LEFT|wx.ALL,5)

                l2 = wx.StaticText(self.panel, -1, "Clearance (mm):")
                vbox.Add(l2, 1, wx.ALIGN_RIGHT|wx.ALL,5)
                self.t2 = wx.TextCtrl(self.panel)
                vbox.Add(self.t2,1,wx.EXPAND|wx.ALIGN_LEFT|wx.ALL,5)
                self.t2.Bind(wx.EVT_TEXT,self.OnKeyTyped2)
                self.t2.SetValue("0.2")

                l3 = wx.StaticText(self.panel, -1, "Distance to board outline (mm):")
                vbox.Add(l3, 1, wx.ALIGN_RIGHT|wx.ALL,5)
                self.t3 = wx.TextCtrl(self.panel)
                vbox.Add(self.t3,1,wx.EXPAND|wx.ALIGN_LEFT|wx.ALL,5)
                self.t3.Bind(wx.EVT_TEXT,self.OnKeyTyped3)
                self.t3.SetValue("0.5")

                l4 = wx.StaticText(self.panel, -1, "Minimum thickness (mm):")
                vbox.Add(l4, 1, wx.ALIGN_RIGHT|wx.ALL,5)
                self.t4 = wx.TextCtrl(self.panel)
                vbox.Add(self.t4,1,wx.EXPAND|wx.ALIGN_LEFT|wx.ALL,5)
                self.t4.Bind(wx.EVT_TEXT,self.OnKeyTyped4)
                self.t4.SetValue("0.175")

                l5 = wx.StaticText(self.panel, -1, "Thermal relief gap (mm):")
                vbox.Add(l5, 1, wx.ALIGN_RIGHT|wx.ALL,5)
                self.t5 = wx.TextCtrl(self.panel)
                vbox.Add(self.t5,1,wx.EXPAND|wx.ALIGN_LEFT|wx.ALL,5)
                self.t5.Bind(wx.EVT_TEXT,self.OnKeyTyped5)
                self.t5.SetValue("0.3")

                btn_ok = wx.Button(self.panel,-1,"OK")
                btn_ok.Bind(wx.EVT_BUTTON,self.on_ok_clicked)
                vbox.Add(btn_ok,0, wx.EXPAND)

                btn_cancel = wx.Button(self.panel,-1,"Cancel")
                btn_cancel.Bind(wx.EVT_BUTTON,self.on_cancel_clicked)
                vbox.Add(btn_cancel, 0, wx.EXPAND)

                self.panel.SetSizer(vbox)

                self.Centre()
                self.Show()
                self.Fit()

            #----------------------------------------------------------------------
            def OnNet(self, event):
                self.netz = pcbnew.GetBoard().GetNetsByName().find(self.t1.GetValue()).value()[1].GetNetCode()

            def OnLayer(self, event):
                self.layer = 3 - self.t6.GetSelection()

            def OnKeyTyped2(self, event):
                self.clearance = self.retanum(event.GetString(), 0.2)

            def OnKeyTyped3(self, event):
                self.distance = self.retanum(event.GetString(), 0.5)

            def OnKeyTyped4(self, event):
                self.min_thickness = self.retanum(event.GetString(), 0.175)

            def OnKeyTyped5(self, event):
                self.thermal_gap = self.retanum(event.GetString(), 0.3)

            def on_ok_clicked(self, event):
                self.perform_changes = True
                self.Destroy()

            def on_cancel_clicked(self, event):
                self.perform_changes = False
                self.Destroy()

            def retanum(self, n, alternative=0):
                try:
                    float(n)
                except ValueError:
                    return alternative
                return float(n)
        ########################################################
        #
        # Ab hier werden die Polygone erstellt
        #
        ########################################################

        pcb = pcbnew.GetBoard()

        frame = displayDialog(None)
        frame.ShowModal()

        netz = frame.netz
        clearance = frame.clearance
        distance = frame.distance
        min_thickness = frame.min_thickness
        thermal_gap = frame.thermal_gap

        laylst = []
        if (frame.layer & 1):
            laylst.append(pcbnew.B_Cu)
        if (frame.layer & 2):
            laylst.append(pcbnew.F_Cu)

        if frame.perform_changes:
            min_x = None
            min_y = None
            max_x = None
            max_y = None

            # Small board outline
            pcbdrawings = pcb.GetDrawings()
            i = 0
            for f in pcbdrawings:
                if (f.GetLayerName()=="Edge.Cuts"):
                    f.SetWidth(pcbnew.FromMM(0.01))
                    if (i==0):
                        min_x = f.GetStart().x
                        min_y = f.GetStart().y
                        max_x = f.GetStart().x
                        max_y = f.GetStart().y

                    min_x = min(f.GetStart().x, min_x)
                    min_y = min(f.GetStart().y, min_y)
                    max_x = max(f.GetStart().x, max_x)
                    max_y = max(f.GetStart().y, max_y)
                    min_x = min(f.GetEnd().x, min_x)
                    min_y = min(f.GetEnd().y, min_y)
                    max_x = max(f.GetEnd().x, max_x)
                    max_y = max(f.GetEnd().y, max_y)

                    i += 1

            poly_min_x = (min_x + pcbnew.FromMM(distance))
            poly_max_x = (max_x - pcbnew.FromMM(distance))
            poly_min_y = (min_y + pcbnew.FromMM(distance))
            poly_max_y = (max_y - pcbnew.FromMM(distance))

            i = 0
            for layer in laylst:
                # poly = pcb.InsertArea(netz, 0, layer, poly_min_x, poly_min_y, pcbnew.ZONE_CONTAINER.DIAGONAL_EDGE)
                wp = pcbnew.wxPoint(0, 0)
                wp.Set(poly_min_x, poly_min_y)
                poly = pcb.AddArea(None, netz, layer, wp, 2)
                poly.SetLocalClearance(pcbnew.FromMM(clearance))
                poly.SetMinThickness(pcbnew.FromMM(min_thickness))
                poly.SetThermalReliefGap(pcbnew.FromMM(thermal_gap))
                poly.SetThermalReliefSpokeWidth(pcbnew.FromMM(thermal_gap))
                # poly.SetArcSegmentCount(32)
                poly.SetHV45(False)
                poly.Outline().Append(poly_max_x, poly_min_y)
                poly.Outline().Append(poly_max_x, poly_max_y)
                poly.Outline().Append(poly_min_x, poly_max_y)
                poly.HatchBorder()
                i += 1

if __name__ == "__main__":
    Create_Rectangular_Polygons().Run()


import os
import sys
import requests
import time
import random
import yaml
from fake_useragent import UserAgent

current_path = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(current_path)[0]
sys.path.append(rootPath)

from settings import CONF_DIR
from auxiliary.LogRecord import Logger

logger = Logger().logger

class ApiRequest:
    """
    抓取信息基类
    """

    def __init__(self):
        self.time_out = 20  # 访问链接超时设置
        self.num = 0  # 计算访问次数，用于访问次数限制
        self.proxies = {
            'http': 'http://192.168.2.251:1080',
            'https': 'https://192.168.2.251:1080',
        }

    def answer_the_url(self, url):
        """
        :param url: request url
        :return: return response
        """
        use_time = 0  # 计算同一个链接访问限制，当访问同一链接超过10次时就跳过该链接
        response = None
        # 读取source文件,获取headers
        with open(CONF_DIR + '/conf.yaml', 'r') as f:
            config_dict = yaml.load(f, Loader=yaml.FullLoader)
        headers_dict = config_dict["headers"]
        # headers_dict['user-agent'] = UserAgent().random
        while True:
            try:
                if self.num >= 500:
                    # 超过500次，等待10s
                    time.sleep(10)
                    self.num = 0
                response = requests.get(url=url, timeout=self.time_out, headers=headers_dict, proxies=self.proxies)
                self.num += 1
                break
            except Exception as e:
                time.sleep(random.random() * 2.0 + 0.3)
                use_time += 1
                if use_time > 10:
                    logger.error("<answer_the_url>" + str(e) + url)
                    break
                time.sleep(60)
                continue
        return response


import sys
from collections import deque
input = sys.stdin.readline

n = int(input().rstrip())
queue = deque()
for i in range(1, n + 1):
    queue.append(i)

while queue:
    now = queue.popleft()
    print(now, end=' ')

    if queue:
        go = queue.popleft()
        queue.append(go)


# %%

# まだ環境にJupyterがはいっていないのでRun Cellみただけで満足ってことで。
import math
import random

def pdf(x,mu,sigma):
    sigma_pow=sigma*2
    return (
        1
        /math.sqrt(2*math.pi*sigma_pow)
        *math.exp(-(x-mu)**2/2*sigma_pow)
    )

#%%


class Funcionario:
    def __init__(self, nome, tempo_de_casa, salario):
        self.m_nome = nome
        self.m_tempo_de_casa = tempo_de_casa
        self.m_salario = salario

    def aumento_de_salario(self):
        if self.m_tempo_de_casa < 10:
            self.m_salario *= 1.05
        else:
            self.m_salario *= 1.1

    def impressao(self):
        print(f"O funcionário {self.m_nome} tem "
              f"{self.m_tempo_de_casa} anos de casa "
              f"e um sálario de {self.m_salario}")

funcionario_1 = Funcionario("Alberto", 5, 1000)
funcionario_2 = Funcionario("Maria", 15, 5000)
funcionario_1.impressao()
funcionario_1.aumento_de_salario()
funcionario_1.impressao()
funcionario_2.impressao()
funcionario_2.aumento_de_salario()
funcionario_2.impressao()

Desenvolvimento para Dispositivos Móveis/Aula 09-28/funcionario.py


import requests
from nu.modules.config import query_config

queryConfig = query_config()

class WeatherForecastApi:

    def __init__(self, key, location):
        self.key = key
        self.setLocation(location)

    def setLocation(self, location):
        self.location = location

    def current(self):
        response = self._current()
        data = 'unknown'
        if response != None:
            data = str(int(response['main']['temp'])) + ' Celsius with ' + response['weather'][0]['description']
        return data

    def forecastToday(self):
      response = self._forecast()
      data = 'unknown'
      if response != None:
          data = response['list'][0]['weather'][0]['description'] + ' with a minimum of ' + str(int(response['list'][0]['main']['temp_min'])) + ' and a maximum of ' + str(int(response['list'][0]['main']['temp_max'])) + ' Celsius'
      return data

    def forecastTomorrow(self):
      response = self._forecast()
      data = 'unknown'
      if response != None:
          data = response['list'][1]['weather'][0]['description'] + ' with a minimum of ' + str(int(response['list'][1]['main']['temp_min'])) + ' and a maximum of ' + str(int(response['list'][1]['main']['temp_max'])) + ' Celsius'
      return data

    # http://api.openweathermap.org/data/2.5/weather?q=Montreal&units=metric&APPID=f4b293fa455d861843e2afb0acd35852
    def _current(self):
        req = requests.get('http://api.openweathermap.org/data/2.5/weather?q=' + self.location + '&units=metric&APPID=' + self.key)
        if req.status_code == requests.codes.ok:
            return req.json()
        else:
            return None

    # http://api.openweathermap.org/data/2.5/forecast?q=Montreal&units=metric&APPID=f4b293fa455d861843e2afb0acd35852
    def _forecast(self):
        req = requests.get('http://api.openweathermap.org/data/2.5/forecast?q=' + self.location + '&units=metric&APPID=' + self.key)
        if req.status_code == requests.codes.ok:
            return req.json()
        else:
            return None

WeatherForecast = WeatherForecastApi(queryConfig.get('WeatherForecast', 'apiKey'), queryConfig.get('WeatherForecast', 'location'))