from glob import glob
# import itertools as it
from os.path import basename, splitext, join, abspath
import re
import subprocess
import toolz.curried as z
import argparse
import yaml

fst = z.operator.itemgetter(0)
snd = z.operator.itemgetter(1)

NOTEBOOK_DIR = '_notebooks'
# NOTEBOOK_HTML_DIR = 'ipy_html'
NOTEBOOK_HTML_DIR = '_includes'

base = z.comp(fst, splitext, basename)
htmlname = z.comp(z.curry(join, NOTEBOOK_HTML_DIR), '{}.html'.format, base)

pat = re.compile(r'''^---\n
(.+?)\n
---
''', re.VERBOSE + re.DOTALL)  # # ^---
# print(pat.findall(txt)[0])

def post_todict(posttxt, ret_yaml=False):
    m = pat.findall(posttxt)
    if not m:
        if ret_yaml:
            return (None, None)
        return
    [txt] = m
    dct = yaml.load(txt)
    if ret_yaml:
        return dct, txt
    return dct

def nbconvert(frm, to, template=None):
    template = template or join(NOTEBOOK_DIR, 'output_toggle_html.tpl')
    cmd = ['ipython', 'nbconvert', '--to', 'html', '--template', template,
           '--output', to, frm, ]
    try:
        res = subprocess.check_output(cmd, cwd=abspath('.'), stderr=subprocess.STDOUT)
    except subprocess.CalledProcessError as e:
        # import ipdb; ipdb.set_trace()
        # import traceback
        # traceback.print_exc()
        print(e.output.decode('utf-8'))
        raise e

    print(res)
    return res

def rewrite_post_spec(post_txt, key='ipynb'):
    dct, yamtxt = post_todict(post_txt, ret_yaml=True)
    if (dct is None) or key not in dct:
        return (None, None, None)

    src = dct[key]
    html_fn = htmlname(src)
    new_yaml = """---
{yaml}
---

{{% include {html} %}}
""".format(yaml=yamtxt, html=basename(html_fn))
    return new_yaml, html_fn, src

def convert_and_update(yamlfn, write=True):
    with open(yamlfn, 'rb') as f:
        yamltxt = f.read().decode()
#         print(yamltxt)
    new_yaml, html_out, isrc = rewrite_post_spec(yamltxt)
    if new_yaml is None:
        print('Pattern not found')
        return

    nbconvert(isrc, html_out)
#     print(new_yaml)
    if write:
        with open(yamlfn, 'w') as f:
            f.write(new_yaml)

    return 0

def main(files):
    list(map(z.comp(convert_and_update, z.do(print)), files))

if __name__ == '__main__':
    desc = 'Convert ipython notebooks to blog-friendly htmls.'
    parser = argparse.ArgumentParser(description=desc)
    add = parser.add_argument
    add('--files', '-f', type=str, nargs='+', help='Markdown file specs to convert.')
    add('--all', '-a', action='store_true', help='Convert all .md files in `_posts` directory')

    args = parser.parse_args()
    if args.all:
        files = glob('_posts/*.md')
    else:
        files = args.files
    print(files)
    main(files)


# x = {
#     'a' : 1,
#     'b' : 2,
#     'c' : 3
# }

# print(x['a'])
# print(list(x.keys())[0])

# print(list(x.values()).index(2))

#key berdasarkan value
# print(list(x.keys())[list(x.values()).index(3)])

morse = {
    'a' : '.-',
    'b' : '-...',
    'c' : '-.-.',
    'd' : '-..',
    'e': '.',
    'f' : '..-.',
    'g' : '--.',
    'h' : '....',
    'i' : '..',
    'j' : '.---',
    'k' : '-.-',
    'l' : '.-..',
    'm': '--',
    'n' : '-.',
    'o' : '---',
    'p' : '.--.',
    'q' : '--.-',
    'r' : '.-.',
    's' : '...',
    't' : '-',
    'u' : '..-',
    'v' : '...-',
    'w' : '.--',
    'x' : '-..-',
    'y' : '-.--',
    'z' : '--..',
    # . : '.-.-',
    # , : '--..--',
    # ? : '..--..',
    # / : '--..-.',
    # @ : '.--.-.',
    # 1 : '.----',
    # 2 : '..---',
    # 3 : '...--',
    # 4 : '....-',
    # 5 : '.....',
    # 6 : '-....',
    # 7 : '--...',
    # 8 : '---..',
    # 9 : '----.',
    # 0 : '-----',
}

# def ubahkemorse(teks):
#  kalimat = teks.lower().replace(' ', '')
#  hasil = ''
#  for i in kalimat:
#         hasil+= morse[i] + '/'
#  print(hasil)

# def ubahdarimorse(teks):
#     kalimat = teks.split(' / ')
#     # print(kalimat)
#     hasil = ''
#     for i in kalimat:
#         hasil += list(morse.keys())[list(morse.values()).index(i)]
#     print(hasil)

# ubahkemorse('Raka')
# ubahdarimorse('.... / .- / .-.. / ---')

# satuinput = input('Ketik karakter yang akan diubah =')
#     if satuinput == tekss:
#         ubahdarimorse(tekss)

# def ubah(tekss):
#     # print(tekss.isalpha())
#     if tekss.upper() == tekss.lower():
#         kalimat = tekss.split(' / ')
#         hasil = ''
#         for i in kalimat:
#             hasil += list(morse.keys())[list(morse.values()).index(i)]
#         print(hasil)
#     else :
#         kalimat = tekss.lower().replace(' ', '')
#         hasil = ''
#         for i in kalimat:
#                 hasil+= morse[i] + '/'
#         print(hasil)

# ubah(input('\n ketik karakter yang akan diubah : '))

#package = built-in & 3rd party
#package datetime

# import  datetime

# x = datetime.datetime.now()

# # print(x)
# waktu = str(x).split(' ')
# dateform = waktu[0]
# tahun = dateform.split('-')[0]
# bulan = dateform.split('-')[1]
# tanggal = dateform.split('-')[2]
# print(tanggal,bulan,tahun)
# hourForm = waktu[1]
# jam = hourForm.split(':')[0]
# menit = hourForm.split(':')[1]
# detik = hourForm.split(':')[2]
# print(jam, menit, detik)

# x = datetime.datetime.now()

# print(x.strftime('%A, %d - %m %B - %Y'))

# hari = {
#     'Monday' : 'Senin',
#     'Tuesday' : 'Selasa',
#     'Wednesday' : 'Rabu',
#     'Thursday' : 'Kamis',
#     'Friday' : 'Jum\'at',
#     'Saturday' : 'Sabtu'
# }

# print(hari[x.strftime('%A')])

# bulan = {
#     'January' : 'Januari',
#     'February' : 'Februari',
#     'Maret' : 'April',
#     'May' : 'Mei',
#     'June' : 'Juni',
#     'July' : 'Juli',
#     'August' : 'Agustus',
#     'September' : 'September',
#     'October' : 'Oktober',
#     'November' :'November',
#     'December' : 'Desember'
# }

# print(bulan[x.strftime('%B')])

# print(x.strftime('%H')) #24 jam
# print(x.strftime('%I')) #12 jam
# print(x.strftime('%p'))
# print(x.strftime('%M'))
# print(x.strftime('%S'))

# import threading

# def printtiapdetik():
#     threading.Timer(1.0, printtiapdetik).start()
#     print('Halo Dunia!')

# printtiapdetik()

# import time
# import datetime

# def tes():
#     while True:
#         print('Tes 1 2 3')
#         time.sleep(1)

# tes()

# def tes():
#     while True:
#         x = datetime.datetime.now()
#         print(x.strftime('Sekarang jam %H:%M:%S WIB'))
#         time.sleep(1)

# tes()

# import test1

# print(test1.nama)
# print(test1.Usia)
# print(test1.Jomblo)
# print(test1.job[2])

# # print(test1.halo()) #None
# test1.halo('Ali')

# print(test1.kuadrat(8))

# import morse

# morse.ubah(input('\n ketik karakter yang akan diubah : '))

#lambda

# def namafunction(param)
#     print(param)

# namafunction('Halo gaes!')

# cetak = lambda a : a
# print(cetak('halo'))

# def cetak2(a):
#     return a
# print(cetak2('haha'))

# cetak = lambda a : a + 2
# print(cetak(2))

# cetak = lambda a, b : a + b
# print(cetak(2,3))

# def tes(x):
#     return lambda a : a * x

# duakali = tes(2)
# tigakali = tes(3)
# empatkali  = tes(4)

# print(duakali(4))

#try except

try:
    nilai = int(input('Ketik angka 1:'))
    nilai2 = int(input('Ketik angka 2 : '))
    print(nilai/nilai2)
    # print(int(nilai))
except ValueError:
    print('HAHA BEGO')
except ZeroDivisionError:
    print('ndak bisa di bagi 0 WOI!')


import urllib2
from HTMLParser import HTMLParser

class VerseParser(HTMLParser):
  v = False
  verse = ''
  book = ''
  def handle_starttag(self, tag, attrs):
    if tag == 'b':
      self.v = False
  def handle_endtag(self, tag):
    if tag == 'b':
      self.v = True
  def handle_data(self, data):
    if self.v:
      self.verse = data.decode('utf-8')
    if not self.v:
      self.book = data.decode('utf-8')

def get_verse():
  response = urllib2.urlopen('http://labs.bible.org/api/?passage=random')
  html = response.read()
  parser = VerseParser()
  parser.feed(html)

  v = parser.verse
  if v.startswith('"') and v.endswith('"'):
    v = v[1:-1]

  return (v, parser.book)


# coding=utf-8

import logging
import cv2

logger = logging.getLogger(__name__)

class BoundingBox(object):
    """
    """
    def __init__(self, pid, x, y, w, h, W=-1, H=-1):
        """Constructor

        Args:
            pid :
            x :
            y :
            w :
            h :
            W : image width in which the bounding box is defined
            H : image height in which the bounding box is defined

        """
        self.pid = pid
        self.x = x
        self.y = y
        self.w = w
        self.h = h
        self.W = W
        self.H = H

    def __str__(self):
        return "{} ({},{}) {}x{} on {}x{}".format(
            self.pid, self.x, self.y, self.w, self.h, self.W, self.H)

    def __repr__(self):
        return self.__str__()

    def draw(self, image, color=(0,0,255), thickness=1):
        """Draw the bounding box on the image"""
        ratio = float(image.shape[0])/float(self.H) if self.H > 0 else 1.0
        x0 = int(ratio*self.x)
        y0 = int(ratio*self.y)
        x1 = int(ratio*(self.x + self.w - 1))
        y1 = int(ratio*(self.y + self.h - 1))
        cv2.rectangle(image, (x0, y0), (x1, y1), color=color, thickness=thickness)
        cv2.putText(image, str(self.pid), (x0, y0),
                    fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=1,
                    color=color, thickness=1)

def load_mot_annotations(file_name):
    """Load a MOT challenge .csv file

    From https://motchallenge.net/instructions/

       <frame>, <id>, <bb_left>, <bb_top>, <bb_width>, <bb_height>, <conf>, <x>, <y>, <z>

    is returned as

    {
      frame: [ BoundingBox(...), BoundingBox(...), ...]
      ...
    }

    for instance:

    {
      1: [ BoundingBox(3, ...), BoundingBox(8, ...), BoundingBox(7, ...) ],
      4: [ BoundingBox(3, ...), BoundingBox(7, ...) ],
      ...
    }

    """
    annotations = {}
    with open(file_name) as fid:
        for line in fid:
            line = line.strip()
            tok = line.split(",")
            if len(tok) != 10:
                logger.error("Line '{}' is not valid")
                continue
            frame = int(tok[0])
            pid = int(tok[1])
            bb_left = float(tok[2])
            bb_top = float(tok[3])
            bb_width = float(tok[4])
            bb_height = float(tok[5])
            conf = float(tok[6])
            x = float(tok[7])
            y = float(tok[8])
            z = float(tok[9])

            if frame not in annotations:
                annotations[frame] = []

            annotations[frame].append(
                BoundingBox(pid, bb_left, bb_top, bb_width, bb_height)
            )

    return annotations

def reassign_mot_id(input_mot, output_mot, t2p):
    """Reassign the IDs of the input file to the output file with
    providing map between old and new IDs

    Args:
        input_mot :
        output_mot :
        t2p : tracklet id to person id

    """

    with open(input_mot) as inp, open(output_mot, "w") as out:
        for line in inp:
            line = line.strip()
            tok = line.split(",")
            if len(tok) != 10:
                logger.error("Line '{}' is not valid")
                continue

            tid = int(tok[1])
            assert tid in t2p
            pid = t2p[tid]

            out.write("{},{},{},{},{},{},{},{},{},{}\n"
                      .format(tok[0], pid, tok[2], tok[3], tok[4], tok[5],
                              tok[6], tok[7], tok[8], tok[9]))

def scale_bounding_box(image,
                       h, w, height, width,
                       image_height=-1, image_width=-1):
    """Adapt the coordinates of the input bounding box.

    Args:
        image  : Image in which to project the bounding box.
        h      :
        w      :
        height :
        width  :
        image_height : Height of image in which the bounding box is.
        image_width  :

    Returns:
        x0, x1, y0, y1 : Start and end points of bounding box

    """
    if image_height < 0:
        image_height = image.shape[0]
    if image_width < 0:
        image_width = image.shape[1]
    W = float(image.shape[1])/float(image_width)
    H = float(image.shape[0])/float(image_height)
    x0 = int(w*W)
    y0 = int(h*H)
    x1 = int((w + width)*W)
    y1 = int((h + height)*H)
    return x0, x1, y0, y1


# This page is to check/save/modify data.

import os
import pickle
from conf import settings

# check data
def select_data(cls, username):
    class_name = cls.__name__
    user_dir_path = os.path.join(settings.DB_PATH, class_name)
    if not os.path.exists(user_dir_path):
        os.mkdir(user_dir_path)

    user_path = os.path.join(user_dir_path, username)

    if os.path.exists(user_path):
        with open(user_path, mode='rb') as f:
            obj = pickle.load(f)
            return obj

# save/modify data
def save_data(obj):
    class_name = obj.__class__.__name__
    user_dir_path = os.path.join(settings.DB_PATH, class_name)
    if not os.path.exists(user_dir_path):
        os.mkdir(user_dir_path)

    user_path = os.path.join(user_dir_path, obj.user)

    with open(user_path, mode='wb') as f:
        pickle.dump(obj, f)


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

# In[9]:

#import packages

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# In[10]:

#reading data into the jupyter notebook

data = pd.read_csv("marketing_data.csv")
data.head()

# In[11]:

#general information about data
data.info()

# In[12]:

#from data.info() we found that date column needs to be converted to datetime format

data['Date']= pd.to_datetime(data['Date'])

#similarly Income to be converted into float data type but before that we have to delete
#commas in the income values
data['Income']=data['Income'].str.replace(',','')
data['Income'] = data['Income'].astype(float)

# In[13]:

#check for duplicate records
duplicated_rows = data.duplicated()
duplicated_rows
duplicated_rows.value_counts() #everything is False = no duplicates

# In[14]:

#check for null values
data.isnull().sum()

# In[15]:

#to fill the values of Income with median income values
data['Income'] = data['Income'].fillna(value=data['Income'].median())

# In[16]:

#checking if the null values are filled
data.isnull().sum()

# In[17]:

#getting all unique values of category variables to examine any errors in it
country_var = data.Country.unique()
edu_var = data.Education.unique()
marital_var = data.Marital_Status.unique()

# In[18]:

country_var #all good

# In[19]:

edu_var #2n cycle --> Master

# In[20]:

marital_var #YOLO, Alone, Absurd --> Single

# In[21]:

#transforming 45,43
data['Education']=data['Education'].replace('2n Cycle','Master')
data['Marital_Status']=data['Marital_Status'].replace(['Alone','Master','YOLO'], 'Single')

# In[22]:

#creation of dataframes

num = ['Year_Birth','Income', 'Recency', 'MntWines', 'MntFruits',
       'MntMeatProducts', 'MntFishProducts', 'MntSweetProducts',
       'MntGoldProds', 'NumDealsPurchases', 'NumWebPurchases',
       'NumCatalogPurchases', 'NumStorePurchases', 'NumWebVisitsMonth']

data_num = data[num]

# In[23]:

#checking numerical variables
data_num.describe()

# In[24]:

#creating boxplots for each column
for column in data_num:
    plt.figure()
    data_num.boxplot([column])

# In[25]:

#in birthyear box plots, we can see there are some absurd outliers, for instance, people born before 1900,
#this can be corrected by excluding people born before 1900

data = data[data["Year_Birth"] > 1900]

# In[26]:

data.head()

# In[27]:

sns.distplot(data['Income'])

# In[28]:

#Income range is too long, hence adding log(income) as another column
data["LogIncome"] = np.log(data["Income"])

# In[29]:

#creating aggregated fields

#1 amount spent
data['TotalAmountSpent'] = data['MntWines']+data['MntFruits']+data['MntMeatProducts']+data['MntFishProducts']+data['MntSweetProducts']+data['MntGoldProds']

# In[30]:

#2 products purchased
data['TotalProductsPurchased'] = data['NumWebPurchases'] + data['NumCatalogPurchases'] + data['NumStorePurchases']

# In[31]:

#3 total children
data['TotalChildren'] = data['Kidhome'] + data['Teenhome']

# In[32]:

data['Year_Birth']

# In[33]:

# Creating age bins
data['AgeDemographic']=pd.cut(data['Year_Birth'], bins = [1900,1945,1964,1980,1996,2012], labels = ["Silent Gen", "Baby Boomer", "Gen X","Millennial", "Gen Z"])

# In[34]:

data['AgeDemographic']

# In[35]:

#renaming columns for ease of reading
data = data.rename(columns={"Amount_Spent":"Amount Spent", "Marital_Status":"Marital Status",
                            "Products_Purchased":"Products Purchased", "Total_Children": "Total Children"})

# In[36]:

#customer demographics
cust_dem = ['AgeDemographic', 'Education', 'Marital Status', 'TotalChildren', 'Country']

# In[37]:

# Make a bar chart that visualizes the number of customers for each demographic using a for loop
for i in cust_dem:
    plt.figure()
    sns.countplot(data[i])
    plt.title(f'Number of customers per {i}')

# In[38]:

# Make a table showing amount and average spent grouped by each demographic using a for loop
for i in cust_dem:
    c_table = data[[i, "TotalAmountSpent"]].groupby(i).sum()
    c_table["Average Spent"] = data[[i, "TotalAmountSpent"]].groupby(i).mean()
    # Make a bar graph showing amount and average spent grouped by each demographic using a for loop
    for i in c_table.columns:
        plt.figure()
        sns.barplot(x=c_table.index, y=c_table[i])
        plt.title(f'{i}')

# In[39]:

data.info()

# In[40]:

data = data.rename(columns={'MntWines':'Wines', 'MntFruits':'Fruits', 'MntMeatProducts':'Meat', 'MntFishProducts':'Fish',
                           'MntSweetProducts':'Sweet', 'MntGoldProds':'Gold'})

# In[41]:

data.head()

# In[42]:

# Make table that shows the total amount spent per product category
products = ["Wines", "Fruits", "Meat", "Fish", "Sweet", "Gold"]

# In[43]:

sum=data[products].sum(axis=0)

# In[44]:

plt.figure()
sns.barplot(x=products, y=sum)
plt.title('Total Amount Spent per Category')
plt.xlabel('Product Type')

# In[45]:

for i in cust_dem:
    df = data[[i, "Wines", "Fruits", "Meat", "Fish", "Sweet", "Gold"]].groupby(i).sum()
    df = df.div(df.sum(axis=1), axis=0)*100
    df = df.reset_index()
    df.plot(x=i, kind='barh', stacked = True, mark_right=True)
    plt.title(f"Percentage of sales per product by {i}")

# In[46]:

# Make a table showing the number of purchases accross each sales channel

# In[47]:

data.info()

# In[48]:

data=data.rename(columns={"NumWebPurchases":"Website",
                          "NumCatalogPurchases":"Catalog",
                          "NumStorePurchases":"Store"})
sales_channel = ['Website', 'Catalog', 'Store']

# In[49]:

# Make a table showing the number of purchases accross each sales channels
sales_c = data[sales_channel].sum(axis=0)
sales_c = pd.DataFrame(sales_c, columns=["Number of Purchases"])

sns.barplot(x=sales_c.index, y=sales_c["Number of Purchases"])

# In[50]:

#stacked bar plot for purchases per demographic
for i in cust_dem:
    df = data[[i, 'Website', 'Catalog', 'Store']].groupby(i).sum()
    df = df.div(df.sum(axis=1), axis=0)*100
    df = df.reset_index()
    df.plot(x=i, kind='barh', stacked = True, mark_right=True)
    plt.title(f"Percentage of sales per product by {i}")

# In[51]:

#correlation heatmaps
# Make a list of variables to include in the correlation graph
corr_var = ["Year_Birth", "Kidhome", "Teenhome", "Recency", "Wines",
            "Fruits", "Meat", "Fish", "Sweet", "Gold",
            "NumDealsPurchases", "Website", "Catalog", "Store",
            "NumDealsPurchases", "NumWebVisitsMonth", "LogIncome",
            "TotalAmountSpent", "TotalProductsPurchased", "TotalChildren"]

# In[52]:

corr_var = data[corr_var]

# In[56]:

plt.figure(figsize=(30,20))
sns.heatmap(corr_var.corr(), annot=True)
plt.title("Correlation Heatmap", size=40)

Marketing Analytics Winter Break Project.py


from menace import Menace
import logging

class FailNetwork(Menace):
    """ Openstack implementation of Fail Network.
        Drops a percentage of packets.
    """

    def can_apply(self):
        return (self.instance != None and
                self.client.is_owned_instance(self.instance))

    def apply(self):
        assert self.instance != None
        status = True
        try:
            self.instance.exec_script("fail_network")
        except:
            logging.error("Executing menace %s failed" % "fail_network")
            status = False
        return status

    def undo(self):
        assert self.instance != None
        status = False
        try:
            status = self.instance.exec_script("restore_network")
        except:
            logging.error("Undoing menace %s failed" % "fail_network")

        return status


# Mixins used for unit tests of openwisp_controller

class GetEditFormInlineMixin(object):
    def _get_org_edit_form_inline_params(self, user, org):
        params = super()._get_org_edit_form_inline_params(user, org)
        params.update(
            {
                # config inline
                'config_settings-TOTAL_FORMS': 0,
                'config_settings-INITIAL_FORMS': 0,
                'config_settings-MIN_NUM_FORMS': 0,
                'config_settings-MAX_NUM_FORMS': 0,
                # device limit inline
                'config_limits-TOTAL_FORMS': 0,
                'config_limits-INITIAL_FORMS': 0,
            }
        )
        return params

    def _get_user_edit_form_inline_params(self, user, organization):
        params = super()._get_user_edit_form_inline_params(user, organization)
        params.update(
            {
                'notificationsetting_set-TOTAL_FORMS': 0,
                'notificationsetting_set-INITIAL_FORMS': 0,
                'notificationsetting_set-MIN_NUM_FORMS': 0,
                'notificationsetting_set-MAX_NUM_FORMS': 0,
            }
        )
        return params


# -*- coding: utf-8 -*-
"""
Created on Wed Jul  5 21:22:00 2023

@author: Shubhi Tiwari
"""

from queue import Queue

V=4
adj=[[2],[3],[4],[1]]
def topopath(node,vis,ans,adj):
        vis[node-1]=1
        for i in adj[node-1]:
            topopath(i,vis,ans,adj)
        ans.append(node)
    #Function to return list containing vertices in Topological order.
def topoSort( V, adj):
        # Code here
        vis=[0]*V
        ans=[]
        for i in range(V):
            if (vis[i]==0):
                topopath(i,vis,ans,adj)
        ls=[]
        for i in range(len(ans)-1,-1,-1):
            ls.append(ans[i])
            ans.pop()

        if len(vis)==V:
            return False

        return True
print(topoSort(V, adj))


import requests
import logging
import signal
from loggingpy.log import JsonFormatter
import logging.handlers

from .sender import HttpSender

class SimpleHttpSink(logging.Handler):
    """
    Sends every log message in series one-by-one.
    """

    def __init__(self, endpoint_uri: str):
        logging.Handler.__init__(self)
        self.endpoint_uri = endpoint_uri
        self.setFormatter(JsonFormatter())

    def emit(self, record):
        log_entry = self.format(record)
        try:
            return requests.post(self.endpoint_uri, log_entry, headers={"Content-type": "application/json"}).content
        except Exception as ex:  # after the post retries, all bets are off
            print(ex)

def post_request(info):
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    endpoint_uri, log_entry = info[0], info[1]
    try:
        return requests.post(endpoint_uri, log_entry, headers={"Content-type": "application/json"}).content
    except Exception as ex:  # after the post retries, all bets are off
        print(ex)

class BundlingHttpSink(logging.Handler):
    """
    Sends messages by bundling multiple messages into one request.
    Adjusted version from: https://github.com/logzio/logzio-python-handler/tree/master/logzio
    """
    def __init__(self,
                 app_name: str,
                 environment: str,
                 url: str,
                 logs_drain_timeout=3,
                 debug=False):

        self.app_name = app_name
        self.environment = environment.upper()

        self.http_sender = HttpSender(
            url=url,
            logs_drain_timeout=logs_drain_timeout,
            debug=debug)
        logging.Handler.__init__(self)

    def flush(self):
        self.http_sender.flush()

    def emit(self, record):
        record.app_name = self.app_name
        record.environment = self.environment
        log_entry = self.format(record)
        self.http_sender.append(log_entry)


# GFG problem
# Link: https://practice.geeksforgeeks.org/problems/number-of-distinct-subsequences0909/1

# Solution:

#{
 # Driver Code Starts
#Initial Template for Python 3

if __name__ == '__main__':
	T=int(input())
	for i in range(T):
		s = input()

		ob = Solution()
		answer = ob.distinctSubsequences(s)
		print(answer)

# } Driver Code Ends

class Solution:
    def distinctSubsequences(self, S):
        # code here
        n = len(S)
        dp = [0] * (n + 1)
        dp[0] = 1
        last = {}
        for i in range(1, n + 1):
            dp[i] = 2 * dp[i - 1]
            if S[i - 1] in last:
                dp[i] -= dp[last[S[i - 1]]]
            last[S[i - 1]] = i - 1
        return dp[n] % 1000000007


# -*- coding: utf-8 -*-
"""
Created on Tue May 10 00:22:52 2022

@author: longj
"""

'''
************ 3.4 定义一个 reference DEM limit ************
# ref_dem_limit
# 使用 SRTM 90 m DEM, TBD = 120 m
'''
import sys
import numpy as np
import csv
from osgeo import gdal
from gdalconst import *

'''
 ****** 提取在 DEM 上下 120 m 内的点 *******
'''
# 函数功能：elevation 最邻近插值
def nearest_interp_elev(elev):
    new_elev = []
    for i in range(len(elev)):
        if elev[i] != -100:
            new_elev.append(elev[i])
        else:
            j_left = 0
            j_right = 0
            for j in range(1000):
                if elev[i-j_left] == -100:
                    j_left = j_left + 1
                else:
                    break
                if i<j_left:
                    j_left = -100
                    break
                #print(j_left)
            for j in range(1000):
                if elev[i+j_right] == -100:
                    j_right = j_right + 1
                else:
                    break
                if i + j_right > len(elev)-1:
                    j_right = -100
                    break
            if j_left != -100 and j_right != -100:
                new_elev.append((elev[i-j_left]+elev[i+j_right])/2)
            elif j_left == -100 and j_right != -100:
                #print(i,j_right,len(new_elev))
                new_elev.append(elev[i+j_right])
            elif j_right == -100 and j_left != -100:
                #print(i,j_left,len(new_elev))
                new_elev.append(elev[i-j_left])

        if i % 1000 == 0:
            print(">",end="")

    return new_elev

# 函数功能：point overlay raster， get elevation
def in_DEM_threshold(tif_path, xy_ls):
    #获取注册类
    gdal.AllRegister()

    #打开栅格数据
    ds = gdal.Open(tif_path)#, GA_ReadOnly)
    if ds is None:
        print('Could not open image')
        sys.exit(1)

    #获取仿射变换信息
    transform = ds.GetGeoTransform()
    xOrigin = transform[0]
    yOrigin = transform[3]
    pixelWidth = transform[1]
    pixelHeight = transform[5]
    # 提取(X, Y)处的 pixel_value, 即 DEM 高程
    #DEM_height = []
    #print("xOrigin,xOrigin,pixelWidth,pixelHeight",xOrigin,yOrigin,pixelWidth,pixelHeight)
    #print("range(len(xy_ls)),xy_ls[0][0:2],xy_ls[len(xy_ls)-1][0:2]")
    #print(range(len(xy_ls)),xy_ls[0][0:2],xy_ls[len(xy_ls)-1][0:2])
    elev = []
    for i in range(len(xy_ls)):
        x = xy_ls[i][2]
        y = xy_ls[i][3]
        if x != -100:
            # 获取 (X, Y) 所在的栅格的位置
            xOffset = int((x-xOrigin)/pixelWidth)
            yOffset = int((y-yOrigin)/pixelHeight)
            # 提取 pixel_velue
            data = ds.GetRasterBand(1).ReadAsArray(xOffset, yOffset,1,1)
            pixel_value = data[0,0]
            elev.append(pixel_value)
            '''
            if abs(xy_ls[i][2] - pixel_value)<120:
                pInThreshold.append(xy_ls[i])
            '''
        else:
            elev.append(-100)
    print("已完成从 DEM 的 elevation 提取")
    interped_elev = nearest_interp_elev(elev)
    print("已完成 elevation 最邻近插值")
    pInThreshold = []
    for i in range(len(interped_elev)):
        if abs(xy_ls[i][1] - interped_elev[i])<120:
            pInThreshold.append(xy_ls[i])

    return pInThreshold

# 读取 0_Asmooth 的所有点 X,Y,h 和 along-track_dist
xy_ls = list(np.genfromtxt("./3_Asmooth_0.txt",delimiter = ","))

# 获取 DEM/srtm_61_04_4550
pInThreshold = in_DEM_threshold("../srtm_61_04_4550.tif", xy_ls)
print("xy_ls 长度：",len(xy_ls))
print("pInTreshold 长度：",len(pInThreshold))

# 存储 pInThreshold
with open('./4_Asmooth_1.txt','w') as out:
        csv_out=csv.writer(out)
        # csv_out.writerow(['X','Y'])
        for row in pInThreshold:
            csv_out.writerow(row)


import numpy as np
import matplotlib.pyplot as plt

from games import NormalFormGame
from tools import *
import math

# %% Player cell
class Player:
    def __init__(self, model, playerIndex, verbose=False, strategy='UCB'):
        self.verbose = verbose
        self.strategy = strategy
        self.model = model
        self.nActions = model.nActions[playerIndex]
        self.playerIndex = playerIndex
        self.actions = []
        self.regrets = []
        self.probabilityDistibution = np.random.random(self.nActions)
        self.probabilityDistibution /= np.sum(self.probabilityDistibution)

        # UCB attributes
        self.explorationTime = self.nActions
        self.S = np.zeros(self.nActions)
        self.N = np.zeros(self.nActions)
        self.rho = 0.2

        #Exp3 attributes
        self.gamma = 0.01
        self.eta = self.gamma/self.nActions
        self.beta = 0.01
        self.weights = np.ones(self.nActions)

    def chooseAction(self):
        action = np.random.randint(self.nActions)
        if self.strategy == 'UCB':
            t = len(self.actions)
            action = t if (t < self.nActions) else np.argmax(self.S / self.N + self.rho * np.sqrt(np.log(t) / (2*self.N)))
        elif self.strategy == 'Exp3':
            action = choose(self.probabilityDistibution)
        elif self.strategy == 'Thompson sampling':
            t = len(self.actions)
            action = t if (t < self.nActions) else np.argmax(np.random.beta((self.S+4*self.N)/8+1, self.N - (self.S+4)/8 + 1))
        elif self.strategy == 'Naive':
            t = len(self.actions)
            action = t if (t < self.nActions) else np.argmax(self.S/self.N)
        else :
            print("strategy not implemented : random policy applied -- choose 'UCB', 'Exp3', 'Thompson sampling' or 'Naive'")
        return action

    def step(self):
        action = self.chooseAction()
        self.actions.append(action)
        self.N[action] += 1
        return action

    def analyzeStep(self, playerAction, opponentAction, rewards):
        reward = rewards[self.playerIndex]
        regret = self.model.bestReward(self.playerIndex, opponentAction) - reward
        self.regrets.append(regret)
        self.S[playerAction] += reward

        if self.strategy == 'Exp3':
            maxreward = np.max(self.model.matrix[:,:,self.playerIndex])
            minreward = np.min(self.model.matrix[:,:,self.playerIndex])

            estimatedRewards = self.beta/self.probabilityDistibution
            estimatedRewards[playerAction] += (reward - minreward)/(maxreward-minreward)/self.probabilityDistibution[playerAction]
            self.weights = self.weights * np.exp(self.eta * estimatedRewards)
            self.probabilityDistibution = (1 - self.gamma) * self.weights/ np.sum(self.weights) + self.gamma/self.nActions

    def plotAnalysis(self, player):
        plt.figure(1)
        plt.plot(np.cumsum(self.regrets))
        plt.title("Regrets for %s"%(player))
        plt.show()
        plt.figure(1)
        plt.plot(self.actions)
        plt.title("Actions for %s"%(player))
        plt.show()


#!/usr/bin/env python
''' TODO
add a way to update the shell file instead of overwriting it
'''

from argparse import ArgumentParser
from datetime import datetime
import json
import os
import sys

here = os.path.abspath(os.path.dirname(__file__))
ALIAS_PATH = os.path.join(here, 'aliases.json')
EDITOR_CONFIG_PATH = os.path.join(here, 'editorconfig')
VIM_DIR_PATH = os.path.join(here, 'vim')
VIMRC_PATH = os.path.join(VIM_DIR_PATH, 'vimrc')
TMUX_PATH = os.path.join(here, 'tmux.conf')

PS1 = '\\[\033[1;34m\\]\\u\\[\033[1;36m\\]@\\[\033[1;35m\\]\\W\\[\033[1;32m\\] $ \\[\033[0m\\]'
with open(ALIAS_PATH) as f:
    ALIASES = json.load(f)

VUNDLE_REPO = 'https://github.com/VundleVim/Vundle.vim.git'
PYENV_REPO = 'https://github.com/yyuu/pyenv.git'
PYENV_VIRTUALENV_REPO = 'https://github.com/yyuu/pyenv-virtualenv.git'

def configure_shell_file(install_dir, shell_file):
    with open(shell_file, 'a') as f:
        # set vim keybindings
        f.write('\nset -o vi\n')

        # install terminal prompt (PS1)
        f.write('\nPS1="{}"\n'.format(PS1))

        # install aliases
        for alias_type, aliases in ALIASES.items():
            f.write('\n# {} aliases\n'.format(alias_type))
            for alias in aliases:
                f.write('alias {}\n'.format(alias))

def install_vim(install_dir, shell_file):
    vim_dir_target = os.path.join(install_dir, '.vim')
    os.system('ln -s %s %s' % (VIM_DIR_PATH, vim_dir_target))

    vimrc_target = os.path.join(install_dir, '.vimrc')
    os.system('ln -s %s %s' % (VIMRC_PATH, vimrc_target))

    vundle_target = os.path.join(vim_dir_target, 'bundle', 'Vundle.vim')
    if not os.path.exists(vundle_target):
        os.system('git clone %s %s' % (VUNDLE_REPO, vundle_target))

def install_tmux(install_dir, shell_file):
    tmux_target = os.path.join(install_dir, '.tmux.conf')
    os.system('ln -s %s %s' % (TMUX_PATH, tmux_target))

def install_pyenv(install_dir, shell_file):
    pyenv_target = os.path.join(install_dir, '.pyenv')
    os.system('git clone %s %s' % (PYENV_REPO, pyenv_target))

    pyenv_virtualenv_target = os.path.join(pyenv_target, 'plugins', 'pyenv-virtualenv')
    os.system('git clone %s %s' % (PYENV_VIRTUALENV_REPO, pyenv_virtualenv_target))

    with open(shell_file, 'a') as f:
        f.write('\n# pyenv + pyenv-virtualenv\n')
        f.write('export PYENV_ROOT="%s"\n' % pyenv_target)
        f.write('export PATH="$PYENV_ROOT/bin:$PATH"\n')
        f.write('eval "$(pyenv init -)"\n')
        f.write('eval "$(pyenv virtualenv-init -)"\n')

def install(install_dir, shell_file):
    ''' Install .vim/ + .vimrc
    Install editorconfig
    Install .tmux.conf
    Setup pyenv + pyenv-virtualenv
    '''

    if not os.path.isdir(install_dir):
        print('install directory %s does not exist. exiting' % install_dir)
        sys.exit(1)

    install_dir = os.path.realpath(install_dir)
    shell_file = os.path.join(install_dir, shell_file)
    if not os.path.isfile(shell_file):
        with open(shell_file, 'w+') as f:
            now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            f.write('# file generated by denv at %s\n' % now)

    editor_config_target = os.path.join(install_dir, '.editorconfig')
    os.system('ln -s %s %s' % (EDITOR_CONFIG_PATH, editor_config_target))

    configure_shell_file(install_dir, shell_file)
    install_vim(install_dir, shell_file)
    install_tmux(install_dir, shell_file)
    install_pyenv(install_dir, shell_file)

if __name__ == '__main__':
    arg_parser = ArgumentParser()
    arg_parser.add_argument('-i', '--install-dir', type=str,
        help='specify the install directory')
    arg_parser.add_argument('-s', '--shell-file', type=str,
        help='specify the shell file')
    args = arg_parser.parse_args()

    install_dir = args.install_dir or os.environ['HOME']
    shell_file = args.shell_file or '.bashrc'
    install(install_dir, shell_file)


# -*- coding: utf-8 -*-
"""
@File    : responses.py
@Time    : 2023/3/23 5:53 下午
@Author  : xxlaila
@Software: PyCharm
"""
from django.http import JsonResponse

class BaseResponse(JsonResponse):
    def __init__(self, data, code=None, msg=None, **kwargs):
        data = {
            'code': code if code is not None else 0,
            'msg': msg if msg is not None else 'success',
            'data': data
        }
        super().__init__(data, **kwargs)


# naver/ 파파고 번역 api 사용예제

import os
import sys
import urllib.request
client_id = "클라이언트 ID 값" # 개발자센터에서 발급받은 Client ID 값
client_secret = "클라이언트 PWD 값" # 개발자센터에서 발급받은 Client Secret 값
encText = urllib.parse.quote("반갑습니다 네이버 번역 시스템")
data = "source=ko&target=en&text=" + encText
#source : 원본언어 언어코드 / target : 번역언어 언어코드 /  text : 번역할 문자
url = "https://openapi.naver.com/v1/papago/n2mt"
request = urllib.request.Request(url)
request.add_header("X-Naver-Client-Id",client_id)
request.add_header("X-Naver-Client-Secret",client_secret)
response = urllib.request.urlopen(request, data=data.encode("utf-8"))
rescode = response.getcode()
if(rescode==200):
    response_body = response.read()
    print(response_body.decode('utf-8'))
else:
    print("Error Code:" + rescode)


##|################################################
# | Author: Seth Jaksik
# | ID: 1001541359
# | Email: seth.jaksik@mavs.uta.edu
##|################################################
# | naive_bayes.py
# |
# | Use: Calculate Bayesian Classifiers for data
##|################################################
# | Licence: MIT License
##|################################################

##|################################################
# | Imports
##|################################################
import sys
import csv
import numpy as np
import math

##|################################################
# | Data Prep
##|################################################
if len(sys.argv) < 3:
    print("Not enough arguments")
    exit(0)

inFile = open(sys.argv[1], 'r')
lines = inFile.readlines()
trainData = []
for row in lines:
    trainData.append(row.split())

inFile = open(sys.argv[2], 'r')
lines = inFile.readlines()
testData = []
for row in lines:
    testData.append(row.split())

# Format data into dictionaries and convert to floats
totalTrain = len(trainData)
totalTest = len(testData)

# seperate train based on class
trainClasses = dict()
for i in range(len(trainData)):
    vector = trainData[i]
    class_value = int(vector[-1])
    if (class_value not in trainClasses):
        trainClasses[class_value] = list()
    trainClasses[class_value].append(vector[:-1])

# convert train arrays to floats
for i in trainClasses:
    for j in range(len(trainClasses[i])):
        trainClasses[i][j] = np.array(trainClasses[i][j]).astype(np.float64)

# convert test arrays to floats
for i in range(len(testData)):
    testData[i] = np.array(testData[i]).astype(np.float64)

##|################################################
# | Training
##|################################################
# prep mean and std matrices
numClass = len(trainClasses)
numAttr = len(next(iter(trainClasses.values()))[0])
trainMean = dict()
trainSTD = dict()

# calc mean and std for each class and attr
for i in trainClasses:
    tempMean = tempSTD = [0]*numAttr

    # calc mean
    for j in range(len(trainClasses[i])):
        tempMean += trainClasses[i][j]
    tempMean /= len(trainClasses[i])
    trainMean[i] = tempMean

    # calc std
    for j in range(len(trainClasses[i])):
        tempSTD += ((trainClasses[i][j] - trainMean[i])**2)
    tempSTD = (tempSTD/(len(trainClasses[i])-1))**(1/2)
    trainSTD[i] = tempSTD

# set to 0.01 if smaller
for i in trainSTD:
    for j in range(len(trainSTD[i])):
        if trainSTD[i][j] < 0.01:
            trainSTD[i][j] = 0.01

# calc class probabilities
classProb = dict()
for i in trainClasses:
    classProb[i] = len(trainClasses[i])/totalTrain

# print train stats
for i in sorted(trainMean.keys()):
    for j in range(len(trainMean[i])):
        print("Class {:d}, attribute {:d}, mean = {:0.2f}, std = {:0.2f}".format(
            i, j+1, trainMean[i][j], trainSTD[i][j]))

##|################################################
# | Classification
##|################################################
totalAcc = 0
for i in range(len(testData)):
    gaussian = dict()
    for j in trainMean:
        gaussian[j] = 1
    predict = (0, 0)
    accuracy = 1

    for j in trainMean:
        for k in range(len(testData[i])-1):
            # generate p(x|c) for each attribute
            gaussian[j] *= ((1/(trainSTD[j][k] * math.sqrt(2 * math.pi))) *
                            math.exp(-((testData[i][k] - trainMean[j][k])**2)/(2*trainSTD[j][k]**2)))
        gaussian[j] *= classProb[j]

    # find max prob using bayes rule
    for j in trainMean:
        if (gaussian[j]/sum(gaussian.values())) == predict[1]:
            accuracy += 1
        elif (gaussian[j]/sum(gaussian.values())) > predict[1]:
            predict = (j, gaussian[j]/sum(gaussian.values()))
            accuracy = 1

    # set accuracy of guesses
    accuracy = 1 if (int(predict[0]) == int(testData[i][-1])) else 0
    totalAcc += accuracy

    # print statistics
    print("ID={:5d}, predicted={:3d}, probability = {:0.4f}, true={:3d}, accuracy={:4.2f}".format(
        i+1, predict[0], predict[1], int(testData[i][-1]), accuracy))

print("classification accuracy={:6.4f}".format(totalAcc/len(testData)))


import random
import numpy as np
import matplotlib.pyplot as plt
import math
import time
import os
import collections.abc
container_abcs = collections.abc
import scipy.io as sio
import numpy.linalg as LA
import scipy.spatial.distance as scipy_spatial_dist

def intx(x):
    return(int(x[0]), int(x[1]))

def cos_cdis(x, y, semi_sphere=False):
    # input: x: mxp, y: nxp
    # output: y, mxn
    # https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html#scipy.spatial.distance.cdist
    ### compute cosine distance
    ### scipy: same 0, opposite 2, orthorgonal 1, dist = 1-AB/(|A||B|)
    dist_cos = scipy_spatial_dist.cdist(x, y, 'cosine')  # num_points_ x num_points
    # ### map to: same 1, opposite -1, orthorgonal 0, dist = AB/(|A||B|)
    dist_cos *= -1.0
    dist_cos += 1.0

    if semi_sphere is True: dist_cos = np.abs(dist_cos) #  dist = abs|AB/(|A||B|)|
    dist_cos_arc = np.arccos(dist_cos)
    return dist_cos_arc

def catersian_to_sphere(xyz):
    #  input: xyz, nx3, in the gaussian_catersian coordinate
    #  output: angles, (alpha, beta), nx2, in the gaussian sphere coordinate
    #  beta: elevation; alpha: azimuth.
    ### norm = [sin(alpha)cos(beta), sin(beta), cos(alpha)cos(beta)]
    num_points = len(xyz)
    angle = np.zeros((num_points,2))
    angle[:,1] = np.arcsin(xyz[:,1])
    inner = xyz[:,0] / np.cos(angle[:,1])
    inner = np.clip(inner, a_min=-1.0, a_max=1.0)
    angle[:,0] = np.arcsin(inner)
    return angle

def sphere_to_catesian(angles):
    #  input: angles (alphas, betas), nx2, in the gasussian sphere coordinate
    #  output: xyz (x,y,z), nx3, in the gaussian_catersian coordinate
    #  beta: elevation; alpha: azimuth.
    ### n = [sin(alpha)cos(beta), sin(beta), cos(alpha)cos(beta)]
    num_points = len(angles)
    xyz = np.zeros((num_points,3))
    xyz[:,0] = np.sin(angles[:,0]) * np.cos(angles[:,1])
    xyz[:,1] = np.sin(angles[:,1])
    xyz[:,2] = np.cos(angles[:,0]) * np.cos(angles[:,1])

    return xyz

def gold_spiral_sampling_patch(v, alpha, num_pts):
    v1 = orth(v)
    v2 = np.cross(v, v1)
    v, v1, v2 = v[:, None], v1[:, None], v2[:, None]
    # indices = np.arange(num_pts) + 0.66
    indices = np.arange(num_pts) + 0.5
    phi = np.arccos(1 + (math.cos(alpha) - 1) * indices / num_pts)
    theta = np.pi * (1 + 5 ** 0.5) * indices
    r = np.sin(phi)
    return (v * np.cos(phi) + r * (v1 * np.cos(theta) + v2 * np.sin(theta))).T

def orth(v):
    x, y, z = v
    o = np.array([0.0, -z, y] if abs(x) < abs(y) else [-z, 0.0, x])
    o /= LA.norm(o)
    return o


from collections import deque
from copy import deepcopy
import time
from template import Agent, GameRule
import random
import heapq
from Azul.azul_model import AzulGameRule as GameRule
from Azul.azul_model import AzulState as GameState
from itertools import count

THINKTIME   = 0.95
NUM_PLAYERS = 2

class myAgent(Agent):
    def __init__(self,_id):
        super().__init__(_id)
        self.game_rule = GameRule(NUM_PLAYERS)
        self.game_state = GameState(NUM_PLAYERS)

    def isGoal(self, state, action):
        numRowsCompleted = 0
        numRowsCompletedSucc = 0
        for i in range(state.agents[self.id].GRID_SIZE):
            if (state.agents[self.id].lines_number[i] == i+1):
                numRowsCompleted += 1

        state = self.game_rule.generateSuccessor(state, action, self.id)

        for j in range(state.agents[self.id].GRID_SIZE):
            if (state.agents[self.id].lines_number[j] == j+1):
                numRowsCompletedSucc += 1

        return numRowsCompletedSucc > numRowsCompleted

    def GetActions(self, state):
        return self.game_rule.getLegalActions(state, self.id)

    def heuristic(self, state):
        arrayOnFloor = state.agents[self.id].floor
        numOnFloor = 0
        for val in arrayOnFloor:
            if val == 1:
                numOnFloor += 1
        return -numOnFloor

    def SelectAction(self,actions,root_state):
        unique = count()
        start_time = time.time()
        myPQ = []
        node = (deepcopy(root_state), [])
        hValue = self.heuristic(root_state)
        heapq.heappush(myPQ, (hValue, next(unique),  node))
        ##myPQ = deque([node])
        closedStates = []
        while len(myPQ) and time.time()-start_time < THINKTIME:
            whole = heapq.heappop(myPQ)
            _,_, currNode = whole
            state, path = currNode
            newActions = self.GetActions(state)
            if (state not in closedStates):
                closedStates = closedStates + [state]
                for a in newActions:
                    next_path = path + [a]
                    next_state = deepcopy(state)
                    if(self.isGoal(next_state, a)):
                        return next_path[0]
                    else:
                        hValue = self.heuristic(root_state)
                        newNode = (next_state, next_path)
                        heapq.heappush(myPQ, (hValue, next(unique), newNode))
                        ##myPQ.append(newNode)
        return random.choice(actions)


import nltk # Import all the libraries need to build the seq2seq model
from nltk.stem.lancaster import LancasterStemmer
stemmer = LancasterStemmer()

import numpy as np
import tflearn
import tensorflow as tf
import random

import pickle
import json

ERROR_THRESHOLD = 0.25 # The error should not be greater than this value

def clean_up_sentence(sentence):
    # tokenize the pattern
    sentence_words = nltk.word_tokenize(sentence)
    # stem each word
    sentence_words = [stemmer.stem(word.lower()) for word in sentence_words]
    return sentence_words

# return bag of words array: 0 or 1 for each word in the bag that exists in the sentence
def bow(sentence, words, show_details=False): # and to pass that numpy array to the model.predict
    # tokenize the pattern
    sentence_words = clean_up_sentence(sentence)
    # bag of words
    bag = [0]*len(words)
    for s in sentence_words:
        for i, w in enumerate(words):
            if w == s:
                bag[i] = 1
                if show_details:
                    print("found in bag %s" % w)
    return np.array(bag)

def classify(sentence):
    # generate probabilities from the model
    results = model.predict([bow(sentence, words)])[0]
    # filter out predictions below a threshold
    results = [[i, r] for i, r in enumerate(results) if r > ERROR_THRESHOLD]
    # sort by strength of probability
    results.sort(key = lambda x: x[1], reverse=True)
    return_list = []
    for r in results:
        return_list.append((classes[r[0]], r[1]))
    # return tuple of intent and probability
    return return_list

# ===
data = pickle.load(open("training_data", "rb"))
words = data['words']
classes = data['classes']
train_x = data['train_x']
train_y = data['train_y']

# import our chat-bot intents file
with open('intents.json') as json_data:
    intents = json.load(json_data)

# load saved model
net = tflearn.input_data(shape=[None, len(train_x[0])])
net = tflearn.fully_connected(net, 8)
net = tflearn.fully_connected(net, 8)
net = tflearn.fully_connected(net, len(train_y[0]), activation='softmax')
net = tflearn.regression(net)
model = tflearn.DNN(net, tensorboard_dir='tflearn_logs')
model.load('./model.tflearn')

print (classify('What is the cutoff for computer science in your college?'))
print (classify('What kind of faculty does your college have?'))
print (classify('Can I take this book?'))
print (classify('When was COEP founded ?'))
print (classify('What is your name ?'))


# coding=utf-8

import socket

#socket.AF_INET, socket.SOCK_STREAM，分别代表ipv4地址族和TCP流
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = socket.gethostbyname(socket.getfqdn(socket.gethostname()))
print("host IP",host)
port = 8000

serversocket.bind((host,port))
serversocket.listen(5)  #最多可以可以接受5个连接请求

while True:
    conn,addr = serversocket.accept()
    print("received",addr)
    conn.send('welcome to visit'.encode("UTF-8"))

    while True:
        data = conn.recv(1024).decode("UTF-8")
        if not data:
            pass
        else:
            print(data)

        if data == 'close':
            print("End of this connection")
            conn.close()
            break

        if len(data) == 0:
            print("connect error")
            conn.close()
            break

        #userdata = input("请输入要回复的数据，按回车跳过")
        #if len(userdata) == 0:
            #pass
        #服务器端，根据指令做出不同动作，待改进。。。

#服务器做成可以多客户端连接。。。待完成

conn.close()


users = [
    {"id": 0, "name": "Hero"},
    {"id": 1, "name": "Dunn"},
    {"id": 2, "name": "Sue"},
    {"id": 3, "name": "Chi"},
    {"id": 4, "name": "Thor"},
    {"id": 5, "name": "Clive"},
    {"id": 6, "name": "Hicks"},
    {"id": 7, "name": "Devin"},
    {"id": 8, "name": "Kate"},
    {"id": 9, "name": "Klein"}
]

friendships = [
    (0, 1),
    (0, 2),
    (1, 2),
    (1, 3),
    (2, 3),
    (3, 4),
    (4, 5),
    (5, 6),
    (5, 7),
    (6, 8),
    (7, 8),
    (8, 9)
]

def number_of_friends(user):
    """how many friends does _user_ have?"""
    return len(user["friends"])

for user in users:
    user["friends"] = []

for i, j in friendships:
    # this works because users[i] is the user whose id is i
    users[i]["friends"].append(users[j])  # add j as a friend of i
    users[j]["friends"].append(users[i])  # add i as a friend of j

number_of_friends_by_user = [number_of_friends(user) for user in users]

total_connections = sum(number_of_friends_by_user)

num_users = len(users)

avg_connections = total_connections / num_users

print(avg_connections)

num_friends_by_id = [(user["id"], number_of_friends(user))
                     for user in users]

print (sorted(num_friends_by_id,
       key=(lambda x: x[1]),
       reverse=True))


import os
import sys
import cv2
import time
import numpy as np
import easyocr

image_dir = sys.argv[1]
out_dir = sys.argv[2]

debug_dir = None
if (len(sys.argv) == 4):
    print("Debug out on")
    debug_dir = sys.argv[3]

reader = easyocr.Reader(['en'])

start_time = time.time()

ims = os.listdir(image_dir)
im_num = len(ims)

failed = []

remaining = -1

for i, im in enumerate(ims):
    outpath = os.path.join(out_dir, im + "_mask.npy")
    if (os.path.exists(outpath)) or not("jpg" in im.lower() or "png" in im.lower() or "jpeg" in im.lower()):
        continue

    filename = os.path.join(image_dir, im)

    try:
        results = reader.readtext(filename)
        im = cv2.imread(filename)
        if im is None:
            failed.append("Not found:")
            failed.append(filename)
            continue
        mask = np.zeros_like(im)
        for result in results:
            a, b, c, d = result[0]
            min_x = round(min(a[0], b[0], c[0], d[0]))
            min_y = round(min(a[1], b[1], c[1], d[1]))
            max_x = round(max(a[0], b[0], c[0], d[0]))
            max_y = round(max(a[1], b[1], c[1], d[1]))
            mask[min_y:max_y,min_x:max_x,:] = 1

        if not(debug_dir is None):
            debug_out = os.path.join(debug_dir, filename)
            cv2.imwrite(debug_out + "_masked.png", im*mask)
            cv2.imwrite(debug_out + "_un_masked.png", im*(1-mask))
        np.save(outpath, mask)

        elapsed = time.time() - start_time
        speed = (i+1) / elapsed
        remaining = (im_num - i - 1) / speed
        remaining = int(remaining * 100) / 100.0
    except Exception as e:
        failed.append(e)
        failed.append(filename)

    print(str(i+1) + " / " + str(im_num) + ", about " + str(remaining) + "s left.")
    sys.stdout.write("\033[F") # Cursor up one line

print()
print()
print()
print(failed)
print("~~~~~~~~~~~~~")
print(len(failed))
print(im_num)


import hashlib
import logging
import os

LOG = logging.getLogger(__name__)

SHARDS = int(os.environ.get("SHARDS", 1))
SHARD_ID = int(os.environ.get("SHARD_ID", 0))

def is_in_shard(value):
    if SHARDS == 1:
        return True

    h = hashlib.new("md5", usedforsecurity=False)
    h.update(value.encode())
    value_hex = h.hexdigest()
    value_int = int(value_hex, base=16)

    in_shard = value_int % SHARDS == SHARD_ID

    if in_shard:
        LOG.debug("IN_SHARD TRUE: %s", value)
    else:
        LOG.debug("IN_SHARD FALSE: %s", value)

    return in_shard

def is_in_shard_round_robin(value, index):
    if SHARDS == 1:
        return True

    in_shard = index % SHARDS == SHARD_ID

    if in_shard:
        LOG.debug("IN_SHARD TRUE: %s", value)
    else:
        LOG.debug("IN_SHARD FALSE: %s", value)

    return in_shard


# 11399
n = int(input())
b = list(map(int, input().split()))

orders = []
for i in range(len(b)):
    k = len(b) - i
    for j in range(1, k):
        if b[j-1] >= b[j]:
            temp = b[j-1]
            b[j-1] = b[j]
            b[j] = temp

sum = 0
new_sum = []
for i in b:
    sum +=i
    new_sum.append(sum)
print(sum)
print(new_sum)

total = 0
for i in new_sum:
    total+=i

print(total)

# a = int(input())
# b = list(input())

# c = 0
# for i in range(a):
#     c+=int(b[i])

# print(c)


import torch
import unittest

from torch_blade.version import cuda_available
from tests.disc.testing_base import DiscTestCase

class TestDiscGroupNorm(DiscTestCase):
    def _test_group_norm(self, groupnorm):
        test_data = torch.randn([2, 320, 64, 64], device=self.device)
        annotation = ([-1, -1, -1, -1], torch.float)
        self._test_disc(groupnorm, [annotation], (test_data,), rtol=1e-3)

    def test_groupnorm_module(self):
        groupnorm = torch.nn.GroupNorm(32, 320, affine=False)
        self._test_group_norm(groupnorm)

    def test_groupnorm_module_has_affine(self):
        groupnorm = torch.nn.GroupNorm(32, 320, affine=True)
        self._test_group_norm(groupnorm)

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


from DeepSecuritySDK import DeepSecurityAPI as dsmAPI
from DeepSecuritySDK.DeepSecurityAPI import models

class DeepSecurityRestApi:

    def __init__(self, config):
        self._config = config
        self._url = "https://{0}:{1}/api".format(self._config.hostname, self._config.port)
        self._Conf = dsmAPI.Configuration()
        self._Conf.host = self._url
        self._Conf.verify_ssl = self._config.sslVerify
        self._Conf.debug = self._config.Debug
        self._Conf.api_key = {'api-secret-key': self._config.apiKey}
        self._client = dsmAPI.ApiClient(self._Conf)
        self._computerAPI = dsmAPI.ComputersApi(self._client)
        self._policyAPI = dsmAPI.PoliciesApi(self._client)
        self._groupAPI = dsmAPI.ComputerGroupsApi(self._client)

        self._firewallAPI = dsmAPI.ComputerFirewallRuleAssignmentsApi(self._client)
        self._firewallRulesAPI = dsmAPI.FirewallRulesApi(self._client)
        self._portlistAPI = dsmAPI.PortListsApi(self._client)
        self._computerIPS_API = dsmAPI.ComputerIntrusionPreventionRuleDetailsApi(self._client)

        self._integrityAPI = dsmAPI.IntegrityMonitoringRulesApi(self._client)
        self._IPSAPI = dsmAPI.IntrusionPreventionRulesApi(self._client)
        self._LogInspectionAPI = dsmAPI.LogInspectionRulesApi(self._client)
        self._antiMalwareAPI = dsmAPI.AntiMalwareConfigurationsApi(self._client)
        self._IntegrityMonitorComputerAPI = dsmAPI.ComputerIntegrityMonitoringRuleAssignmentsRecommendationsApi(
            self._client)
        self._computerIPS = dsmAPI.ComputerIntrusionPreventionRuleAssignmentsRecommendationsApi(self._client)
        self._computerLog = dsmAPI.ComputerLogInspectionRuleAssignmentsRecommendationsApi(self._client)

    def GetAllComputersFromGroup(self, groupID):
        groupComputers = []
        DoAgain = True
        ComputerIndex = 0
        Max_items = 500
        while DoAgain:
            try:
                if groupID:
                    search_by_group = models.SearchCriteria(field_name="groupID", numeric_value=groupID,
                                                                           numeric_test="equal")
                else:
                    search_by_group = models.SearchCriteria(field_name="groupID", null_test=True)

                search_by_id = models.SearchCriteria(id_value=ComputerIndex,
                                                                    id_test="greater-than-or-equal")

                searchfilter = models.SearchFilter(max_items=Max_items,
                                                                  search_criteria=[search_by_group, search_by_id],
                                                                  sort_by_object_id=True)

                computersReturn = self._computerAPI.search_computers("v1", search_filter=searchfilter).computers
                DoAgain = False
                if len(computersReturn) > 0:
                    groupComputers += computersReturn
                if len(computersReturn) == Max_items:
                    DoAgain = True
                    ComputerIndex = computersReturn[len(computersReturn) - 1].id
                    ComputerIndex = ComputerIndex + 1

            except Exception as err:
                print("Error obtaining Group {0} with error {1}".format(groupID, err))
                if err.status == 404:
                    DoAgain = False

        return groupComputers

    def AllGroups(self):
        DoAgain = True
        while DoAgain:
            try:
                allGroups = self._groupAPI.list_computer_groups("v1")
                DoAgain = False
            except Exception as err:
                print("Error obtaining Group computers ith error {0}".format(err))
        return allGroups


import csv

def write_to_csv(data):
    with open("database.csv", newline="", mode="a") as csv_database:
        csv_writer = csv.writer(
            csv_database, delimiter=",", quotechar='"', quoting=csv.QUOTE_MINIMAL
        )
        csv_writer.writerow(data)

# makes a log of any component failure
def write_txt(data):
    with open("log.txt", mode="a") as text_file:  # change this to absolute path
        text_file.write(data + "\n")


import asyncio
import grpc
import logging
import time

from payment_pb2 import (
    ProcessPaymentRequest,
    ProcessPaymentReply,
)
from payment_pb2_grpc import (
    PaymentService,
    add_PaymentServiceServicer_to_server,
)
from tasks import process_payment

class PaymentServer(PaymentService):

    async def ProcessPayment(
        self,
        request: ProcessPaymentRequest,
        context: grpc.aio.ServicerContext,
    ) -> ProcessPaymentReply:
        logging.info("[ProcessPayment] Serving request %s", request)
        for payment in request.payments:
            initiated_at = time.strftime('%Y-%m-%d %H:%M:%S')
            task = process_payment.s(
                payment.payment_id,
                payment.card_holder_name,
                payment.card_number,
                payment.price,
                initiated_at,
            ).apply_async()
            task.forget()
        return ProcessPaymentReply(
            message=f"[ProcessPayment] Sent task-process_payment to celery-worker"
        )

SERVER_PORT = 50051

async def serve() -> None:
    server = grpc.aio.server()
    add_PaymentServiceServicer_to_server(PaymentServer(), server)
    listen_addr = f"[::]:{SERVER_PORT}"
    server.add_insecure_port(listen_addr)
    logging.info("Starting server on %s", listen_addr)
    await server.start()
    await server.wait_for_termination()

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    asyncio.run(serve())


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('partner', '0007_auto_20160417_0253'),
    ]

    operations = [
        migrations.AddField(
            model_name='shop',
            name='description',
            field=models.TextField(verbose_name='Description', blank=True),
        ),
        migrations.AddField(
            model_name='shop',
            name='image',
            field=models.ImageField(upload_to=b'images/products/%Y/%m/', max_length=255, verbose_name=b'image', blank=True),
        ),
    ]


# Wydruk polskich świąt z datami - z pliku csv.

import pandas as pd
import numpy as np
from tabulate import tabulate

path = ('holidays_csv.csv')

df = pd.read_csv(path)
# kasuj kolumnę province code
df.__delitem__('Province Code')
#print(df.loc[0:3, lambda x: ['Country Code']])
#print(df.loc[0:3, ['Country Code', 'Holiday Name']])

print('Kolumny w pliku csv:',list(df))
#  tylko PL z kolumny Country Code:
pl = df.loc[df['Country Code'] == 'PL']
# ilosc wierszy w zbiorze PL = ilosc swiat :
print('Ilosc swiat w PL:', pl.shape[0])

# sprawdzamy jakie sa typy swiat:
print('Typy swiat:', ((df['Type of Holiday']).unique()))

# ilosc swiat posortowane:
#print(df['Country Code'].value_counts())
#  ilosc swiat nieposortowane:
#print(df.groupby('Country Code').size())
wydruk = df.groupby('Country Code').size()

# święta - tylko public:
swieta_optional  = df.loc[(df['Country Code'] == 'PL') & (df['Type of Holiday'] == 'public')]

swieta_optional.drop_duplicates('Holiday Name',  keep='last')
polskie_swieta = swieta_optional.loc[:, ['Date','Type of Holiday','Holiday Name']]
sq = pd.DataFrame(polskie_swieta)

rok_2019 = sq['Date']>'2019-00-00 00:00:00'
print(tabulate(sq[rok_2019],headers='keys',tablefmt='psql'))


class programmer:
    company = "Google"

    def __init__(self, Name, Product, salary, post):
        self.Name = Name
        self.product = Product
        self.salary = salary
        self.post = post

    def getInfo(self):
        print(f" The programmer name is {self.Name} and \
                Their product name is {self.product} \
                   and Their salary is {self.salary} \
                  and Their post is {self.post}")

Anon = programmer("Anon", "Youtube", "110K", "Manager")
Alex = programmer("Alex", "Chrome", "90K", "Devloper")

Anon.getInfo()
Alex.getInfo()


from collections import deque

from .task import Future, Task

class AsyncQueue:
    def __init__(self, maxsize: int = None):
        self._queue: deque[Task] = deque()
        self._wait_get: deque[Future] = deque()
        self._wait_put: deque[Future] = deque()
        self._maxsize: int = maxsize if maxsize is not None and maxsize > 0 else None
        from . import _get_event_loop
        self._loop = _get_event_loop()

    def empty(self) -> bool:
        return not self._queue

    def full(self) -> bool:
        if self._maxsize is None:
            return False
        return len(self._queue) >= self._maxsize

    @staticmethod
    def _wakeup_next_waiter(waiters):
        if not waiters:
            return
        waiter = waiters.popleft()
        waiter.set_result(None)

    def _get(self):
        return self._queue.popleft()

    def _put(self, item):
        self._queue.append(item)

    def _put_nowait(self, item):
        if self.full():
            raise Exception("queue is full")
        self._put(item)
        self._wakeup_next_waiter(self._wait_get)

    def _get_nowait(self):
        if self.empty():
            raise Exception("queue is empty")
        item = self._get()
        self._wakeup_next_waiter(self._wait_put)
        return item

    async def put(self, item):
        while self.full():
            fut = Future()
            self._wait_put.append(fut)
            await fut
        self._put_nowait(item)

    async def get(self):
        while self.empty():
            fut = Future()
            self._wait_get.append(fut)
            await fut
        return self._get_nowait()


'''
Name: Matthew Chung
Description: Program to count months over budget for gas and electric

'''
#list of months and variables for budget
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
budget = 0
for each in months:
    inputE = float(raw_input("How much was the eletric bill for " + each + "?"))
    inputG = float(raw_input("How much was the gas bill for " + each +"?"))
    if (inputE > 70.00) or (inputG > 30.00):
        budget += 1

print("Went over budget " + str(budget) + " months this year.")


THREE_NUMBER: int = 3
THIRTY_NUMBER: int = 30
FIFTY_NUMBER: int = 50
ZERO_NUMBER: int = 0
YES_STRING: str = "Yes"
TRUE_VALUE: str = "true"
FALSE_VALUE: str = "false"
CONCAT_SEPARATOR: str = "||"
SHA_KEY: int = 256

COUNT_COLUMN: str = "count"

INNER_TYPE: str = "inner"

CLIENTS_PATH: str = "clients_path"
CLIENTS_SCHEMA: str = "clients_schema"
CONTRACTS_PATH: str = "contracts_path"
CONTRACTS_SCHEMA: str = "contracts_schema"
PRODUCTS_PATH: str = "products_path"
PRODUCTS_SCHEMA: str = "products_schema"
OUTPUT_PATH: str = "output_path"
OUTPUT_SCHEMA: str = "output_schema"
EXTRA_DISCOUNT: str = "extra_discount"

CUSTOMER_PATH = ""
PHONES_PATH = ""

DELIMITER: str = "delimiter"
HEADER: str = "header"
COMMA: str = ","

OVERWRITE = "overwrite"
MODE = "partitionOverwriteMode"
DYNAMIC = "dynamic"

# SEPARO CONSTANTES DE EJERCICIOS DE FORM
START_DATE = "2020-03-01"
END_DATE = "2020-03-04"
DELL = "Dell"
COOLPAD = "Coolpad"
CHEA = "Chea"
BQ = "BQ"
BLU = "BLU"
CH = "CH"
IT = "IT"
CZ = "CZ"
DK = "DK"
DATE1 = "2020-03-01"
DATE2 = "2020-03-04"
CAST_LONG = "long"
PRICE_P: float = 7500.00
YES = "Yes"
NO = "No"
XOLO = "XOLO"
SIEMENS = "Siemens"
PANASONIC = "Panasonic"
BLACKBERRY = "BlackBerry"
THIRTY5_NUMBER: int = 35
ZEROONE: float = 0.1
ZEROZERO: float = 0.00
TOP50ENTRY = "Entre al top 50"
TOP50NOENTRY = "No entre al top 50"
EXTRA_DISCOUNT = "extra_discount"
BRANDS_TOP = "brands_top"
RANK = "rank"
TOP50 = "top_50"
NFC = "nfc"
FINAL_PRICE = "final_price"
AVGFINAL = "average_final_price"
CUSTOMERVIP = "customer_vip"


from odoo import api, fields, models, _
from odoo.exceptions import UserError, ValidationError
from odoo.addons.delivery_ups.models.ups_request import UPSRequest, Package
from odoo.tools import pdf
import logging
_logger = logging.getLogger(__name__)

class ProviderUPS(models.Model):
    _inherit = 'delivery.carrier'

    def _get_ups_signature_required_type(self, order=None, picking=None, package=None):
        # '3' for Adult Sig.
        return '2'

    def _get_ups_signature_required(self, order=None, picking=None, package=None):
        if self.get_signature_required(order=order, picking=picking, package=package):
            return self._get_ups_signature_required_type(order=order, picking=picking, package=package)
        return False

    def _get_ups_is_third_party(self, order=None, picking=None):
        third_party_account = self.get_third_party_account(order=order, picking=picking)
        if third_party_account:
            if not third_party_account.delivery_type == 'ups':
                raise ValidationError('Non-UPS Shipping Account indicated during UPS shipment.')
            return True
        if order and order.ups_bill_my_account and order.ups_carrier_account:
            return True
        return False

    def _get_main_ups_account_number(self, order=None, picking=None):
        wh = None
        if order:
            wh = order.warehouse_id
        if picking:
            wh = picking.picking_type_id.warehouse_id
        if wh and wh.ups_shipper_number:
            return wh.ups_shipper_number
        return self.ups_shipper_number

    def _get_ups_account_number(self, order=None, picking=None):
        """
        Common hook to customize what UPS Account number to use.
        :return: UPS Account Number
        """
        # Provided by Hibou Odoo Suite `delivery_hibou`
        third_party_account = self.get_third_party_account(order=order, picking=picking)
        if third_party_account:
            if not third_party_account.delivery_type == 'ups':
                raise ValidationError('Non-UPS Shipping Account indicated during UPS shipment.')
            return third_party_account.name
        if order and order.ups_carrier_account:
            return order.ups_carrier_account
        if picking and picking.sale_id.ups_carrier_account:
            return picking.sale_id.ups_carrier_account
        if picking and picking.picking_type_id.warehouse_id.ups_shipper_number:
            return picking.picking_type_id.warehouse_id.ups_shipper_number
        return self.ups_shipper_number

    def _get_ups_carrier_account(self, picking):
        # 3rd party billing should return False if not used.
        account = self._get_ups_account_number(picking=picking)
        return account if account not in (self.ups_shipper_number, picking.picking_type_id.warehouse_id.ups_shipper_number) else False

    """
    Overrides to use Hibou Delivery methods to get shipper etc. and to add 'transit_days' to result.
    """
    def ups_rate_shipment(self, order):
        superself = self.sudo()
        # Hibou Shipping
        signature_required = superself._get_ups_signature_required(order=order)
        insurance_value = superself.get_insurance_value(order=order)
        currency = order.currency_id or order.company_id.currency_id
        insurance_currency_code = currency.name

        srm = UPSRequest(self.log_xml, superself.ups_username, superself.ups_passwd, superself._get_main_ups_account_number(order=order), superself.ups_access_number, self.prod_environment)
        ResCurrency = self.env['res.currency']
        max_weight = self.ups_default_packaging_id.max_weight
        packages = []
        total_qty = 0
        total_weight = 0
        for line in order.order_line.filtered(lambda line: not line.is_delivery and not line.display_type):
            total_qty += line.product_uom_qty
            total_weight += line.product_id.weight * line.product_qty

        if max_weight and total_weight > max_weight:
            total_package = int(total_weight / max_weight)
            last_package_weight = total_weight % max_weight

            for seq in range(total_package):
                packages.append(Package(self, max_weight,
                                        insurance_value=insurance_value, insurance_currency_code=insurance_currency_code, signature_required=signature_required))
            if last_package_weight:
                packages.append(Package(self, last_package_weight,
                                        insurance_value=insurance_value, insurance_currency_code=insurance_currency_code, signature_required=signature_required))
        else:
            packages.append(Package(self, total_weight,
                                    insurance_value=insurance_value, insurance_currency_code=insurance_currency_code, signature_required=signature_required))

        shipment_info = {
            'total_qty': total_qty  # required when service type = 'UPS Worldwide Express Freight'
        }

        if self.ups_cod:
            cod_info = {
                'currency': order.partner_id.country_id.currency_id.name,
                'monetary_value': order.amount_total,
                'funds_code': self.ups_cod_funds_code,
            }
        else:
            cod_info = None

        # Hibou Delivery
        shipper_company = self.get_shipper_company(order=order)
        shipper_warehouse = self.get_shipper_warehouse(order=order)
        recipient = self.get_recipient(order=order)
        date_planned = None
        if self.env.context.get('date_planned'):
            date_planned = self.env.context.get('date_planned')

        check_value = srm.check_required_value(shipper_company, shipper_warehouse, recipient, order=order)
        if check_value:
            return {'success': False,
                    'price': 0.0,
                    'error_message': check_value,
                    'warning_message': False}

        ups_service_type = order.ups_service_type or self.ups_default_service_type
        result = srm.get_shipping_price(
            shipment_info=shipment_info, packages=packages, shipper=shipper_company, ship_from=shipper_warehouse,
            ship_to=recipient, packaging_type=self.ups_default_packaging_id.shipper_package_code, service_type=ups_service_type,
            saturday_delivery=self.ups_saturday_delivery, cod_info=cod_info, date_planned=date_planned)

        if result.get('error_message'):
            return {'success': False,
                    'price': 0.0,
                    'error_message': _('Error:\n%s') % result['error_message'],
                    'warning_message': False}

        if order.currency_id.name == result['currency_code']:
            price = float(result['price'])
        else:
            quote_currency = ResCurrency.search([('name', '=', result['currency_code'])], limit=1)
            price = quote_currency._convert(
                float(result['price']), order.currency_id, order.company_id, order.date_order or fields.Date.today())

        # Hibou Delivery
        if self._get_ups_is_third_party(order=order):
            # Don't show delivery amount, if ups bill my account option is true
            price = 0.0

        return {'success': True,
                'price': price,
                'transit_days': result.get('transit_days', 0),
                'error_message': False,
                'warning_message': False}

    def ups_send_shipping(self, pickings):
        res = []
        superself = self.sudo()
        ResCurrency = self.env['res.currency']
        for picking in pickings:
            srm = UPSRequest(self.log_xml, superself.ups_username, superself.ups_passwd, superself._get_main_ups_account_number(picking=picking), superself.ups_access_number, self.prod_environment)
            # Hibou Delivery
            shipper_company = superself.get_shipper_company(picking=picking)
            shipper_warehouse = superself.get_shipper_warehouse(picking=picking)
            recipient = superself.get_recipient(picking=picking)
            currency = picking.sale_id.currency_id if picking.sale_id else picking.company_id.currency_id
            insurance_currency_code = currency.name

            picking_packages = picking.package_ids
            package_carriers = picking_packages.mapped('carrier_id')
            if package_carriers:
                # only ship ours
                picking_packages = picking_packages.filtered(lambda p: p.carrier_id == self and not p.carrier_tracking_ref)

            if not picking_packages:
                continue

            packages = []
            package_names = []
            if picking_packages:
                # Create all packages
                for package in picking_packages:
                    packages.append(Package(self, package.shipping_weight, quant_pack=package.packaging_id, name=package.name,
                                            insurance_value=superself.get_insurance_value(picking=picking, package=package), insurance_currency_code=insurance_currency_code, signature_required=superself._get_ups_signature_required(picking=picking, package=package)))
                    package_names.append(package.name)

            # what is the point of weight_bulk?
            # Create one package with the rest (the content that is not in a package)
            # if picking.weight_bulk:
            #     packages.append(Package(self, picking.weight_bulk))

            invoice_line_total = 0
            for move in picking.move_lines:
                invoice_line_total += picking.company_id.currency_id.round(move.product_id.lst_price * move.product_qty)

            shipment_info = {
                'description': superself.get_order_name(picking=picking),
                'total_qty': sum(sml.qty_done for sml in picking.move_line_ids),
                'ilt_monetary_value': '%d' % invoice_line_total,
                'itl_currency_code': self.env.user.company_id.currency_id.name,
                'phone': recipient.mobile or recipient.phone,
            }
            if picking.sale_id and picking.sale_id.carrier_id != picking.carrier_id:
                ups_service_type = picking.carrier_id.ups_default_service_type or picking.ups_service_type or superself.ups_default_service_type
            else:
                ups_service_type = picking.ups_service_type or superself.ups_default_service_type

            # Hibou Delivery
            ups_carrier_account = superself._get_ups_carrier_account(picking)

            if picking.carrier_id.ups_cod:
                cod_info = {
                    'currency': picking.partner_id.country_id.currency_id.name,
                    'monetary_value': picking.sale_id.amount_total,
                    'funds_code': superself.ups_cod_funds_code,
                }
            else:
                cod_info = None

            check_value = srm.check_required_value(shipper_company, shipper_warehouse, recipient, picking=picking)
            if check_value:
                raise UserError(check_value)

            package_type = picking_packages and picking_packages[0].packaging_id.shipper_package_code or self.ups_default_packaging_id.shipper_package_code
            srm.send_shipping(
                shipment_info=shipment_info, packages=packages, shipper=shipper_company, ship_from=shipper_warehouse,
                ship_to=recipient, packaging_type=package_type, service_type=ups_service_type, duty_payment=picking.carrier_id.ups_duty_payment,
                label_file_type=self.ups_label_file_type, ups_carrier_account=ups_carrier_account, saturday_delivery=picking.carrier_id.ups_saturday_delivery,
                cod_info=cod_info)
            result = srm.process_shipment()
            if result.get('error_message'):
                raise UserError(result['error_message'].__str__())

            order = picking.sale_id
            company = order.company_id or picking.company_id or self.env.company
            currency_order = picking.sale_id.currency_id
            if not currency_order:
                currency_order = picking.company_id.currency_id

            if currency_order.name == result['currency_code']:
                price = float(result['price'])
            else:
                quote_currency = ResCurrency.search([('name', '=', result['currency_code'])], limit=1)
                price = quote_currency._convert(
                    float(result['price']), currency_order, company, order.date_order or fields.Date.today())

            package_labels = []
            for track_number, label_binary_data in result.get('label_binary_data').items():
                package_labels = package_labels + [(track_number, label_binary_data)]

            carrier_tracking_ref = "+".join([pl[0] for pl in package_labels])
            logmessage = _("Shipment created into UPS
"
                           "Tracking Numbers: %s
"
                           "Packages: %s") % (carrier_tracking_ref, ','.join(package_names))
            if superself.ups_label_file_type != 'GIF':
                attachments = [('LabelUPS-%s.%s' % (pl[0], superself.ups_label_file_type), pl[1]) for pl in package_labels]
            if superself.ups_label_file_type == 'GIF':
                attachments = [('LabelUPS.pdf', pdf.merge_pdf([pl[1] for pl in package_labels]))]
            picking.message_post(body=logmessage, attachments=attachments)
            shipping_data = {
                'exact_price': price,
                'tracking_number': carrier_tracking_ref}
            res = res + [shipping_data]
            if self.return_label_on_delivery:
                self.ups_get_return_label(picking)
        return res

    def ups_rate_shipment_multi(self, order=None, picking=None, packages=None):
        if not packages:
            return self._ups_rate_shipment_multi_package(order=order, picking=picking)
        else:
            rates = []
            for package in packages:
                rates += self._ups_rate_shipment_multi_package(order=order, picking=picking, package=package)
            return rates

    def _ups_rate_shipment_multi_package(self, order=None, picking=None, package=None):
        superself = self.sudo()
        srm = UPSRequest(self.log_xml, superself.ups_username, superself.ups_passwd, superself._get_main_ups_account_number(order=order, picking=picking), superself.ups_access_number, self.prod_environment)
        ResCurrency = self.env['res.currency']
        max_weight = self.ups_default_packaging_id.max_weight
        packages = []
        if order:
            insurance_value = superself.get_insurance_value(order=order)
            signature_required = superself._get_ups_signature_required(order=order)
            currency = order.currency_id
            insurance_currency_code = currency.name
            company = order.company_id
            date_order = order.date_order or fields.Date.today()
            total_qty = 0
            total_weight = 0
            for line in order.order_line.filtered(lambda line: not line.is_delivery):
                total_qty += line.product_uom_qty
                total_weight += line.product_id.weight * line.product_qty

            if max_weight and total_weight > max_weight:
                total_package = int(total_weight / max_weight)
                last_package_weight = total_weight % max_weight

                for seq in range(total_package):
                    packages.append(Package(self, max_weight, insurance_value=insurance_value, insurance_currency_code=insurance_currency_code, signature_required=signature_required))
                if last_package_weight:
                    packages.append(Package(self, last_package_weight, insurance_value=insurance_value, insurance_currency_code=insurance_currency_code, signature_required=signature_required))
            else:
                packages.append(Package(self, total_weight, insurance_value=insurance_value, insurance_currency_code=insurance_currency_code, signature_required=signature_required))
        else:
            currency = picking.sale_id.currency_id if picking.sale_id else picking.company_id.currency_id
            insurance_currency_code = currency.name
            company = picking.company_id
            date_order = picking.sale_id.date_order or fields.Date.today() if picking.sale_id else fields.Date.today()
            # Is total quantity the number of packages or the number of items being shipped?
            if package:
                total_qty = 1
                packages = [Package(self, package.shipping_weight, insurance_value=superself.get_insurance_value(picking=picking, package=package), insurance_currency_code=insurance_currency_code, signature_required=superself._get_ups_signature_required(picking=picking, package=package))]
            elif picking.package_ids:
                # all packages....
                total_qty = len(picking.package_ids)
                packages = [Package(self, package.shipping_weight, insurance_value=superself.get_insurance_value(picking=picking, package=package), insurance_currency_code=insurance_currency_code, signature_required=superself._get_ups_signature_required(picking=picking, package=package)) for package in picking.package_ids.filtered(lambda p: not p.carrier_id)]
            else:
                total_qty = 1
                packages.append(Package(self, picking.shipping_weight or picking.weight, insurance_value=superself.get_insurance_value(picking=picking), insurance_currency_code=insurance_currency_code, signature_required=superself._get_ups_signature_required(picking=picking)))

        shipment_info = {
            'total_qty': total_qty  # required when service type = 'UPS Worldwide Express Freight'
        }

        if self.ups_cod:
            cod_info = {
                'currency': currency.name,
                'monetary_value': order.amount_total if order else picking.sale_id.amount_total,
                'funds_code': self.ups_cod_funds_code,
            }
        else:
            cod_info = None

        # Hibou Delivery
        shipper_company = self.get_shipper_company(order=order, picking=picking)
        shipper_warehouse = self.get_shipper_warehouse(order=order, picking=picking)
        recipient = self.get_recipient(order=order, picking=picking)
        date_planned = fields.Datetime.now()
        if self.env.context.get('date_planned'):
            date_planned = self.env.context.get('date_planned')

        check_value = srm.check_required_value(shipper_company, shipper_warehouse, recipient, order=order, picking=picking)
        if check_value:
            return [{'success': False,
                     'price': 0.0,
                     'error_message': check_value,
                     'warning_message': False,
                     }]
        # We now use Shop if we send multi=True
        ups_service_type = (order.ups_service_type or self.ups_default_service_type) if order else self.ups_default_service_type
        result = srm.get_shipping_price(
            shipment_info=shipment_info, packages=packages, shipper=shipper_company, ship_from=shipper_warehouse,
            ship_to=recipient, packaging_type=self.ups_default_packaging_id.shipper_package_code, service_type=ups_service_type,
            saturday_delivery=self.ups_saturday_delivery, cod_info=cod_info, date_planned=date_planned, multi=True)
        # Hibou Delivery
        is_third_party = self._get_ups_is_third_party(order=order, picking=picking)

        response = []
        for rate in result:
            if isinstance(rate, str):
                # assume error
                response.append({
                    'success': False, 'price': 0.0,
                    'error_message': _('Error:\n%s') % rate,
                    'warning_message': False,
                })
            elif rate.get('error_message'):
                _logger.error('UPS error: %s' % rate['error_message'])
                response.append({
                    'success': False, 'price': 0.0,
                    'error_message': _('Error:\n%s') % rate['error_message'],
                    'warning_message': False,
                })
            else:
                if currency.name == rate['currency_code']:
                    price = float(rate['price'])
                else:
                    quote_currency = ResCurrency.search([('name', '=', rate['currency_code'])], limit=1)
                    price = quote_currency._convert(
                        float(rate['price']), currency, company, date_order)

                if is_third_party:
                    # Don't show delivery amount, if ups bill my account option is true
                    price = 0.0

                service_code = rate['service_code']
                carrier = self.ups_find_delivery_carrier_for_service(service_code)
                if carrier:
                    response.append({
                        'carrier': carrier,
                        'package':  package or self.env['stock.quant.package'].browse(),
                        'success': True,
                        'price': price,
                        'error_message': False,
                        'warning_message': False,
                        'date_planned': date_planned,
                        'date_delivered': None,
                        'transit_days': rate.get('transit_days', 0),
                        'service_code': service_code,
                    })
        return response

    def ups_find_delivery_carrier_for_service(self, service_code):
        if self.ups_default_service_type == service_code:
            return self
        # arbitrary decision, lets find the same account number
        carrier = self.search([('ups_shipper_number', '=', self.ups_shipper_number),
                               ('ups_default_service_type', '=', service_code)
                               ], limit=1)
        return carrier


# -*- coding: utf-8 -*-
import Connect2Pi
import threading
import keyboard
import time
import sys
import cv2
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtCore import QTimer, QThread, Qt, QEvent

IP = ''
re_port = '5555'
se_port = '5556'

global Vx
global Vy
global Angz
global AngArm
Vx = 0
Vy = 0
Angz = 0
AngArm=0

global arm_num # 用于选择控制哪个舵机
arm_num = True
global img

re_img = Connect2Pi._RecvImg(IP,re_port)
se_cmd = Connect2Pi._SendCmd(IP,se_port)

exit_event = threading.Event()

def sendNumLimit():
    global Vx, Vy, Angz, AngArm
    if Vx > 5:
        Vx = 0
    elif Vy > 5:
        Vy = 0
    elif Angz > 90:
        Angz = 0
    elif AngArm > 90:
        AngArm = 0

class VideoViewer(QMainWindow):
    def __init__(self):
        super().__init__()
        self.label = QLabel(self)
        self.label.setGeometry(10, 10, 640, 480)
        self.label_vx = QLabel(self)
        self.label_vx.setGeometry(660, 10, 200, 30)
        self.label_vy = QLabel(self)
        self.label_vy.setGeometry(660, 50, 200, 30)
        self.label_angz = QLabel(self)
        self.label_angz.setGeometry(660, 90, 200, 30)
        self.label_angarm = QLabel(self)
        self.label_angarm.setGeometry(660, 130, 200, 30)
        self.label_armNum = QLabel(self)
        self.label_armNum.setGeometry(660, 170, 200, 30)
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update_frame)
        self.timer.start(1)

    def update_frame(self):
        global Vx, Vy, Angz, AngArm
        # temp = re_img.check_connection()
        # if temp:
        #     print('re is ok')
        # temp2 = se_cmd.check_connection()
        # if temp2:
        #     print('se is ok')

        ret, frame = re_img.imgProcessing()
        if ret:
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            height, width, channel = frame.shape
            bytes_per_line = 3 * width
            q_image = QImage(frame.data, width, height, bytes_per_line, QImage.Format_RGB888)
            pixmap = QPixmap.fromImage(q_image)
            self.label.setPixmap(pixmap)
            self.label.setScaledContents(True)
            self.label_vx.setText(f'前后速度: {Vx}')
            self.label_vy.setText(f'左右速度: {Vy}')
            self.label_angz.setText(f'底盘旋转速度: {Angz}')
            self.label_angarm.setText(f'舵机旋转速度:{AngArm}')
            self.label_armNum.setText(f'舵机控制：{arm_num}')

class VideoViewerThread(QThread):
    def run(self):
        app = QApplication([])
        viewer = VideoViewer()
        viewer.show()
        sys.exit(app.exec_())

def key_listener():
    global Vx, Vy, Angz, arm_num, AngArm
    while not exit_event.is_set():
        sendNumLimit()
        if keyboard.is_pressed('q'):
            exit_event.set()
            break
        elif keyboard.is_pressed('w'):
            se_cmd.velocitySet(Vx, 0, 0)
            time.sleep(0.3)
        elif keyboard.is_pressed('a'):
            se_cmd.velocitySet(0, Vy, 0)
            time.sleep(0.3)
        elif keyboard.is_pressed('s'):
            se_cmd.velocitySet(Vx*(-1), 0, 0)
            time.sleep(0.3)
        elif keyboard.is_pressed('d'):
            se_cmd.velocitySet(0, Vy*(-1), 0)
            time.sleep(0.3)
        elif keyboard.is_pressed('left'):
            se_cmd.velocitySet(0, 0, Angz)
            time.sleep(0.3)
        elif keyboard.is_pressed('right'):
            se_cmd.velocitySet(0, 0, Angz*(-1))
            time.sleep(0.3)
        elif keyboard.is_pressed('up'):
            if not arm_num:
                se_cmd.armCamContral(AngArm, 0)
            else:
                se_cmd.armCamContral(0, AngArm)
            time.sleep(0.3)
        elif keyboard.is_pressed('down'):
            if not arm_num:
                se_cmd.armCamContral(-1*AngArm, 0)
            else:
                se_cmd.armCamContral(0, -1*AngArm)
            time.sleep(0.3)
        elif keyboard.is_pressed('right shift'):
            arm_num = not arm_num
            time.sleep(0.5)
        elif keyboard.is_pressed('c'):
            Vx = Vx + 1
            Vy = Vy + 1
            Angz = Angz + 18
            AngArm = AngArm + 18
            time.sleep(0.3)

if __name__ == '__main__':
    viewer_thread = VideoViewerThread()
    keylistener_thread = threading.Thread(target=key_listener)

    keylistener_thread.start()
    viewer_thread.start()

    keylistener_thread.join()