from argparse import ArgumentParser
from collections import Counter, namedtuple
import curses
import time
import random
import sys
import threading

class Point(namedtuple('P', 'y x')):
    __slots__ = ()
    def adjoint(self, other):
        return not(other == self) \
            and -1 <= other.x - self.x <= 1 \
            and -1 <= other.y -self.y <= 1
    def left(self, i=1):
        return Point(self.y, self.x-i)
    def right(self, i=1):
        return Point(self.y, self.x+i)
    def up(self, i=1):
        return Point(self.y-i, self.x)
    def down(self, i=1):
        return Point(self.y+i, self.x)
    def getNeighbors(self):
        left = self.left()
        right = self.right()
        up = self.up()
        down = self.down()
        result = [left.up(), left, left.down(), up, down, right.up(), right, right.down()]
        return result

class World:
    lifeSignal = 'o'
    emptySignal = '_'
    def __init__(self):
        self.__alives = set()
    def isAlive(self, point):
        return point in self.__alives
    def putLifeAt(self, point):
        self.__alives.add(point)
    def nextGen(self):
        newWorld = World()
        for point, count in self.countNeighbors():
            if self.willBeAlive(point, count):
                newWorld.putLifeAt(point)
        return newWorld
    def countNeighbors(self):
        counts = Counter()
        for cell in self.__alives:
            for neighbor in cell.getNeighbors():
                counts[neighbor] += 1
        return counts.items()
    def willBeAlive(self, point, neighborsCount):
        if neighborsCount == 2: return self.isAlive(point)
        return neighborsCount == 3
    def output(self, topLeft, bottomRight):
        result = ''
        for y in range(topLeft.y, bottomRight.y+1):
            for x in range(topLeft.x, bottomRight.x+1):
                result += self.lifeSignal if self.isAlive(Point(y,x)) else self.emptySignal
            if y < bottomRight.y: result += '\n'
        return result

class Screen:
    def __init__(self, world, waitFun):
        self.world = world
        self.waitFun = waitFun
    def runInContext(self, fun):
        self.fun = fun
        curses.wrapper(self.__run)
    def __run(self, stdscr):
        self.leftTop = Point(0,0)
        self.__initScr(stdscr)
        self.thread = InputThread(self)
        self.thread.start()
        time.sleep(0.1)
        try:
            self.fun(self)
        except (KeyboardInterrupt):
            pass
        self.closeKeyListener(self.thread)
    def closeKeyListener(self, thread):
        while thread.isAlive():
            try:
                curses.ungetch('q')
                if thread.isAlive(): time.sleep(0.1)
            finally:
                pass

    def __initScr(self, stdscr):
        #stdscr.nodelay(not(self.waitFun.stepMode))
        stdscr.timeout(0)
        stdscr.notimeout(1)
        curses.curs_set(False)
        curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
        stdscr.clear()
        self.stdscr = stdscr
    def updateViewSize(self):
        curses.update_lines_cols()
        bottom = curses.LINES-2 + self.leftTop.y
        right = curses.COLS-2 + self.leftTop.x
        self.bottomRight = Point(bottom, right)
    def trigger(self):
        #self.reactInput()
        self.waitFun()
        self.world = self.world.nextGen()
    def reactInput(self):
        updated = True
        c = self.stdscr.getch()
        if c == ord('q'): sys.exit()
        elif c == ord('R'): self.__show()
        elif c in [curses.KEY_LEFT, ord('h')]: self.leftTop = self.leftTop.left(10)
        elif c in [curses.KEY_RIGHT, ord('l')]: self.leftTop = self.leftTop.right(10)
        elif c in [curses.KEY_UP, ord('k')]: self.leftTop = self.leftTop.up(10)
        elif c in [curses.KEY_DOWN, ord('j')]: self.leftTop = self.leftTop.down(10)
        elif c == ord('H'): self.leftTop = self.leftTop.left(50)
        elif c == ord('L'): self.leftTop = self.leftTop.right(50)
        elif c == ord('K'): self.leftTop = self.leftTop.up(50)
        elif c == ord('J'): self.leftTop = self.leftTop.down(50)
        elif c == ord('0'): self.leftTop = Point(0,0)
        else: updated = False
        #if updated: curses.flushinp()
        return updated
    def show(self):
        curses.ungetch('R')
    def __show(self):
        self.updateViewSize()
        self.stdscr.addstr(0, 0, self.world.output(self.leftTop, self.bottomRight), curses.color_pair(1) |curses.A_DIM)
        self.stdscr.refresh()

class InputThread(threading.Thread):
    def __init__(self, screen):
        threading.Thread.__init__(self)
        self.screen = screen
    def run(self):
        while self.isAlive():
            updated = self.screen.reactInput()
            if not(self.isAlive()): return

class Print:
    def __init__(self, world, waitFun):
        self.world = world
        self.waitFun = waitFun
    def runInContext(self, fun):
        fun(self)
    def trigger(self):
        if self.waitFun.stepMode:
            a = input('press enter to next generation...')
            if a == 'q': sys.exit()
        else:
            self.waitFun()
        self.world = self.world.nextGen()
    def show(self):
        print('='*(size+1),'\n'+self.world.output(Point(0,0), Point(size,size)))

def initWorld():
    World.lifeSignal = args.lifeSignal
    World.emptySignal = args.emptySignal
    world = World()
    for initLife in range(int(size * size * args.density / 100)):
        y = random.randint(0,size)
        x = random.randint(0,size)
        world.putLifeAt(Point(y,x))
    return world

def run(runner):
    runner.show()
    i = 0
    while i != args.times:
        i += 1
        runner.trigger()
        runner.show()

def defineArgs():
    parser = ArgumentParser()
    parser.add_argument('-s', dest='size', help='output window size', type=int, default=30)
    parser.add_argument('-i', dest='interval', help='refresh interval, negative to run in step mode', type=float, default=1)
    parser.add_argument('-t', dest='times', help='generation time, -1 run forever', type=int, default=30)
    parser.add_argument('-d', dest='density', help='initial life numbers, size relative', type=int, default=10)
    parser.add_argument('-ls', dest='lifeSignal', help='char to present a life', type=str, default='o')
    parser.add_argument('-es', dest='emptySignal', help='char to present an empty cell', type=str, default=' ')
    parser.add_argument('--print', dest='runner', help='output mode', const=Print, action='store_const', default=Screen)
    return parser.parse_args()

if __name__ == '__main__':
    args = defineArgs()
    size = args.size
    if args.interval < 0:
        waitFun = lambda : None
        waitFun.stepMode = True
    else:
        waitFun = lambda : time.sleep(args.interval)
        waitFun.stepMode = False
    runner = args.runner(initWorld(), waitFun)
    runner.runInContext(run)


#!/usr/bin/env python3

import json
import csv
from operator import itemgetter

def read_data(filename):
    data = []
    with open(filename, 'r') as f:
        for line in f:
            l = json.loads(line)
            if 'status' in l and l['status'] == 'ERROR':
                continue
            galeid = l['docid']
            title = l['metadata']['title']
            d = {'galeid': galeid, 'title': title}
            data.append(d)
    return data

def dump_json(dump_filename, data):
    with open(f'{dump_filename}.json', 'w') as f:
        json.dump(data, f)

def normalize(text):
    remove = '()"\''
    text = ''.join(c for c in text if c not in remove)
    return text

def dump_text(dump_filename, data):
    with open(f'{dump_filename}.txt', 'w') as f:
        # normalize
        triples = []
        for d in data:
            triple = (d['galeid'], d['title'], normalize(d['title']))
            triples.append(triple)
        sort_data = sorted(triples, key=itemgetter(2))
        for triple in sort_data:
            text = f'{triple[0]}\t{triple[1]}\n'
            f.write(text)

def dump_csv(dump_filename, data):
    with open(f'{dump_filename}.csv', 'w') as f:
        fieldnames = ['galeid', 'title']
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()
        for row in data:
            writer.writerow(row)

def main(infile, dump_filename_without_extension):
    data = read_data(infile)
    dump_json(dump_filename_without_extension, data)
    dump_text(dump_filename_without_extension, data)
    dump_csv(dump_filename_without_extension, data)

if __name__ == '__main__':
    # these could be made into cli-parameters.
    infile = 'gale-log.json'
    dump_filename_without_extension = 'gale_list'

    main(infile, dump_filename_without_extension)


"""
@project = BaseToolAPI
@file = statistics_tools
@author = jianwei_hu@aliyun.cm
@create_time = 2020/2/19
"""

import numpy as np
import pandas as pd
import statsmodels.api as sm
from datetime import timedelta

def ar_ma(data):
    """
    AR自相关分析
    :param data: 时间序列数据，类型：list
    :return:
    {
        'x': [],
        'y': []
    }
    """
    data = np.array(data)
    data = data.astype(np.float64)
    data = pd.Series(data)
    data.index = pd.Index(sm.tsa.datetools.dates_from_range('2000m1', length=len(data)))
    ar_ma_qp70 = sm.tsa.ARMA(data, (7, 1)).fit()
    data_pred_start = pd.date_range(data.index[-1], data.index[-1] + timedelta(weeks=20), freq='1m')[0]
    data_pred_end = pd.date_range(data.index[-1], data.index[-1] + timedelta(weeks=20), freq='1m')[-1]
    data_predict = ar_ma_qp70.predict(start=data_pred_start, end=data_pred_end, dynamic=True)
    print(type(data_predict), data_predict)
    return {'x': data_predict.index.tolist(), 'y': data_predict.values.tolist()}

def outlier(data):
    """
    野点剔除
    :param data: 原始数据
    :return: 剔除野点之后的数据
    """
    data = np.array(data)
    data_mean = np.mean(data)
    data_std = np.std(data)
    data_median = np.median(data)
    data_3 = np.percentile(data, 75)
    data_1 = np.percentile(data, 25)
    iqr = data_3 - data_1
    # 用相邻的两个数的均值替换原数据
    for i in np.arange(1, len(data) - 1):
        # i = 1
        if (data[i]>(data_3 + 3 * iqr)) | (data[i] < (data_1 - 3 * iqr)):
            data[i] = (data[i - 1] + data[i + 1]) / 2
    return data.tolist()


import sys
import lab5_ui
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtCore import QObject, QThread, pyqtSignal
from lab5_ui import Ui_MainWindow
import socket
from time import sleep

addr = socket.getaddrinfo("192.168.184.141", 1242)[0][-1]
ServerSideSocket = socket.socket()
ServerSideSocket.bind(addr)
ServerSideSocket.listen(5)
conn, address = ServerSideSocket.accept()  # accept new connection

# Step 1: Create a worker class
class Worker(QObject):
    progress = pyqtSignal(int)

    def run(self):

        while True:
            data = conn.recv(1024).decode()
            #sleep(0.2)
            self.progress.emit(0)

class Lab5():
    def __init__(self) -> None:

        """
        Format of the data:
        b'is_active, pwm'
        """

        self.MainWindow = QtWidgets.QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self.MainWindow)
        self.button_initiator()
        self.is_active = 0
        self.pwm = 0
        self.ui.PWMslider.setMaximum(180)
        self.runLongTask()

    def button_initiator(self):
        self.ui.rb_0.clicked.connect(lambda  a: self.PWM_signal(0))
        self.ui.rb_45.clicked.connect(lambda  a: self.PWM_signal(45))
        self.ui.rb_90.clicked.connect(lambda  a: self.PWM_signal(90))
        self.ui.rb_135.clicked.connect(lambda  a: self.PWM_signal(135))
        self.ui.rb_180.clicked.connect(lambda  a: self.PWM_signal(180))
        self.ui.Releasebutton.clicked.connect(self.release)
        self.ui.PWMslider.sliderReleased.connect(self.PWM_changed)

    def PWM_signal(self, num):
        self.pwm = num
        self.is_active = 1
        self.ui.PWMslider.setValue(num)

    def PWM_changed(self):
        self.PWM_signal(self.ui.PWMslider.value())
        self.ui.SignalText.setText(f"PWM signal changed to {self.ui.PWMslider.value()}")

    def release(self):
        self.is_active = 0
        self.ui.SignalText.setText(f"Button is released")

    def runLongTask(self):
        self.thread = QThread()
        self.worker = Worker()
        self.worker.moveToThread(self.thread)
        self.thread.started.connect(self.worker.run)
        self.worker.progress.connect(self.reportProgress)
        self.thread.start()

    def reportProgress(self,num):
        conn.sendall(f"{self.is_active},{self.pwm}".encode())  # send data to the client
        self.ui.SignalText.setText(f"{self.is_active},{self.pwm}")

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    lab5 = Lab5()
    lab5.MainWindow.show()
    sys.exit(app.exec_())


#!/usr/bin/python
import sys
from datetime import datetime

for line in sys.stdin:
    line = line.strip().split(',')
    if line[0] == 'VendorID' or line[0] == 'WBAN' or line[0]=='"Date/Time"' or line[0]=="Dispatching_base_num" or line[0] == 'vendor_id':
        continue
    if len(line) == 18 or len(line) == 19:
        tpep_pickup_datetime = line[1]
        year_month_day = datetime.strptime(tpep_pickup_datetime, '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d')
        #total_amount = line[18]
        print(("%s\t%d,y") % (year_month_day, 1))
    elif len(line)== 4:
        if line[0].isalnum():
            pickup_datetime = line[1]
            pickup_date = datetime.strptime(pickup_datetime, '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d')
            print(("%s\t%d,u") % (pickup_date, 1))
        else:
            pickup_datetime = line[0]
            pickup_datetime = pickup_datetime[1:-1]
            pickup_date = datetime.strptime(pickup_datetime, '%m/%d/%Y %H:%M:%S').strftime('%Y-%m-%d')
            print(("%s\t%d,u") % (pickup_date, 1))

    elif len(line) == 21 or len(line) == 22 or len(line) == 23:
        lpep_pickup_datetime = line[1]
        year_month_day = datetime.strptime(lpep_pickup_datetime, '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d')
        #total_amount = line[18]
        print(("%s\t%d,g") % (year_month_day, 1))
    elif len(line) == 50:
        year_month_day = datetime.strptime(line[1], '%Y%m%d').strftime('%Y-%m-%d')
        t_max = line[2]
        t_min = line[4]
        t_avg = line[6]
        weather_type = line[22]
        depth = line[24]
        water1 = line[26]
        snowfall = line[28]
        precip_total = line[30]
        avg_speed = line[40]
        print(("%s\t%s,%s,%s,%s,%s,%s,%s,%s,%s") % (year_month_day, t_max, t_min, t_avg, weather_type, depth, water1, snowfall, precip_total, avg_speed))


from datetime import date, timedelta

import pytest
from example import print_owing

from invoice import Invoice
from order import Order

@pytest.fixture
def invoice():
    _invoice = Invoice("Minwoo Jeong")
    for amount in range(10, 60, 10):
        _invoice.add_order(Order(amount))
    due_date = date.today() + timedelta(days=30)
    _invoice.due_date = due_date

    return _invoice

def test_print_owing(capsys, invoice):
    print_owing(invoice)
    expected = (
        "**** Customer Outstanding Debt ****\n"
        f"Customer: {invoice.customer}\n"
        "Outstanding Debt: 150\n"
        f"Due Date: {invoice.due_date.strftime('%d/%m/%y')}\n"
    )
    captured = capsys.readouterr()
    assert captured.out == expected


import pygame
pygame.display.set_mode()
sprite_sheet = pygame.image.load('./textures/mario/mario_sprites.png').convert_alpha()
sprite_width = sprite_sheet.get_width()//14
sprite_height = sprite_sheet.get_height()//12
sprites_per_row = sprite_sheet.get_width() // sprite_width
sprites_per_col = sprite_sheet.get_height() // sprite_height
frames = []
count = 0
for row in range(sprites_per_col):
    for col in range(sprites_per_row):
        x = col * sprite_width
        y = row * sprite_height
        sprite = sprite_sheet.subsurface((x, y, sprite_width, sprite_height))
        pygame.image.save(sprite,f"./textures/mario/{count}.png")
        count += 1


"""
Resource normalizer
"""
from collections import namedtuple

from prjname.common import exceptions
import collections

RULE_NT = namedtuple('Rule', ['execute', 'args', 'default'])

def Rule(args, execute=None, default=None):                             # pylint: disable=C0103
    """
    Returns a named tuple that represent a transformation rule
    @param args set of arguments to be used by the rule
    @param execute transformation function who receive the args
    @param default value used when the attribute defined by path is not in the resource
    """

    return RULE_NT(execute, args, default)

def normalize_resources(resources, normalization_rules, is_ordered=False):
    """
    Normalize a list of resources based on a set of rules
    @param resources list of resources to be normalized
    @param normalization_rules set of rules to normalize the resources
    @param is_ordered mantain the order specified in the schema
    """

    normalized_resources = []
    for resource in resources:
        normalized_resource = normalize_resource(resource,
                                                 normalization_rules,
                                                 is_ordered)
        normalized_resources.append(normalized_resource)

    return normalized_resources

def normalize_resource(resource, normalization_rules, is_ordered=False):
    """
    Normalize a resource based on a set of rules
    @param resources list of resources to be normalized
    @param normalization_rules set of rules to normalize the resources
    @param is_ordered mantain the order specified in the schema
    """

    normalized_resource = {}

    for resource_path, rule in normalization_rules.iteritems():
        if isinstance(rule, dict):
            normalized_value = normalize_resource(resource,
                                                  rule,
                                                  is_ordered)
        else:
            normalized_value = _normalize(rule, resource)

        _set_resource_value_based_on_dotted_path(resource_path,
                                                 normalized_value,
                                                 normalized_resource)

    return normalized_resource

def normalize_response(response, normalization_rules=None):
    """
    Normalize the external service response using the normalization rules
    """
    # pylint: disable=R0201
    normalizer_mapping = {
        dict: normalize_resource,
        list: normalize_resources,
        collections.OrderedDict: normalize_resource
    }

    if normalization_rules is None:
        return response

    try:
        normalized_response = normalizer_mapping[type(response)](
            response, normalization_rules)
    except KeyError as ex:
        raise ValueError('Normalization error: %s' % ex)

    return normalized_response

# Helper method

def _normalize(rule, resource):
    """
    Apply a transformation rule to the resource
    @param rule transformation rule to be applied to the resource
    @param resource resource to transform
    """

    execute = rule.execute
    args = rule.args
    default = rule.default

    kwargs = {}
    for arg in args:
        kwargs[arg.split('.')[-1]] = _get_resource_value_based_on_dotted_path(
            arg, resource, default if not execute else None)

    if execute:
        try:
            normalized_value = execute(**kwargs)
        except Exception:  # pylint: disable=W0703
            normalized_value = default
    elif len(kwargs) > 1:
        raise exceptions.InvalidArgument(
            'too many args for a rule with no "execute"')
    else:
        normalized_key, normalized_value = kwargs.popitem()  # pylint: disable=W0612

    return normalized_value

def _set_resource_value_based_on_dotted_path(path, value, resource):  # pylint: disable=C0103
    """
    Set a resource value based on a dotted path
    @param path string containing a dotted path to an attribute
    @param value value to be set to the attribute specified by path
    @param resource resource who contains the attribute to be changed
    """

    splitted_path = path.split('.')

    for index, path_key in enumerate(splitted_path):
        if index == len(splitted_path) - 1:
            resource[path_key] = value
        else:
            resource = resource[path_key]

def _get_resource_value_based_on_dotted_path(path, resource, default):  # pylint: disable=C0103
    """
    Get a resource value based on a dotted path
    @param path string containing a dotted path to an attribute
    @param resource resource who contains the attribute to be returned
    @param default value used when the attribute defined by path is not in the resource
    """

    splitted_path = path.split('.')

    try:
        for path_key in splitted_path:
            resource = resource.get(path_key, default)
    except AttributeError:
        pass

    return resource


import pickle
import streamlit as st
import pandas as pd
from PIL import Image
model_file = (r"https://raw.githubusercontent.com/JohnTan38/Telco-Customer-Churn-Prediction/blob/main/model_C_1.bin")

with open(model_file, 'rb') as f_in:
    dv, model = pickle.load(f_in)

NB = st.select_slider('', options = [100,150,200,250,300,350,400,500,600,700,750,800,900,1000,1250,1500,1750,2000,2500,3000,3500,4000,4500,5000,5500,6000 ], value = 100)

ColorMinMax = st.markdown(''' <style> div.stSlider > div[data-baseweb = "slider"] > div[data-testid="stTickBar"] > div {
    background: rgb(1 1 1 / 0%); } </style>''', unsafe_allow_html = True)

Slider_Cursor = st.markdown(''' <style> div.stSlider > div[data-baseweb="slider"] > div > div > div[role="slider"]{
    background-color: rgb(14, 38, 74); box-shadow: rgb(14 38 74 / 20%) 0px 0px 0px 0.2rem;} </style>''', unsafe_allow_html = True)

Slider_Number = st.markdown(''' <style> div.stSlider > div[data-baseweb="slider"] > div > div > div > div
                                { color: rgb(14, 38, 74); } </style>''', unsafe_allow_html = True)

col = f''' <style> div.stSlider > div[data-baseweb = "slider"] > div > div {{
    background: linear-gradient(to right, rgb(1, 183, 158) 0%,
                                rgb(1, 183, 158) {NB}%,
                                rgba(151, 166, 195, 0.25) {NB}%,
                                rgba(151, 166, 195, 0.25) 100%); }} </style>'''

#ColorSlider = st.markdown(col, unsafe_allow_html = True)

def main():

	#image = Image.open('images/icone.png')
	#image2 = Image.open('images/image.png')
	#st.image(image,use_column_width=False)
	add_selectbox = st.sidebar.selectbox(
	"How would you like to predict?",
	("Online", "Batch"))
	st.sidebar.info('Input data for customer')
	#st.sidebar.image(image2)
	st.title("Predicting Telco Customer Churn")
	if add_selectbox == 'Online':

		#MonthlyRevenue= st.number_input('Monthly Revenue', min_value=0, max_value=900, value=0)
		MonthlyRevenue = st.select_slider('Monthly Revenue', options = [100,150,200,250,300,350,400,500,600,700,750,800,900,1000,1250,1500,1750,2000,2500,3000,3500,4000,4500,5000,5500,6000 ], value = 100)
		ColorSlider = st.markdown(col, unsafe_allow_html = True)
		#MonthlyMinutes= st.number_input('Monthly Minutes', min_value=0, max_value=6000, value=0)
		MonthlyMinutes= st.select_slider('Monthly Minutes', options = [100,250,500,750,1000,1250,1500,1750,2000,2500,3000,3500,4000,4500,5000,5500,6000 ], value = 100)
		TotalRecurringCharge = st.number_input('Total Recurring Charge', min_value=0, max_value=400, value=0)
		DirectorAssistedCalls = st.number_input('Director Assisted Calls', min_value=0, max_value=75, value=0)
		CustomerCareCalls = st.number_input('Customer Care Calls', min_value=0, max_value=200, value=0)
		ReceivedCalls = st.number_input('Received Calls', min_value=0, max_value=2500, value=0)
		OutboundCalls = st.number_input('Outbound Calls', min_value=0, max_value=600, value=0)
		InboundCalls = st.number_input('Inbound Calls', min_value=0, max_value=600, value=0)
		MonthsInService= st.number_input(' Months In Service', min_value=6, max_value=61, value=6)
		UniqueSubs= st.number_input(' Unique Subs', min_value=1, max_value=18, value=1)
		ActiveSubs = st.number_input('Active Subs', min_value=0, max_value=11, value=0)

		#RetentionCalls = st.number_input('Retention Calls', min_value=0, max_value=5, value=0)
		RetentionCalls = st.select_slider('Retention Calls', options = [1,2,3,4,5], value = 1)
		RetentionOffersAccepted = st.number_input('Retention Offers Accepted', min_value=0, max_value=3, value=0)
		IncomeGroup = st.number_input('Income Group', min_value=0, max_value=9, value=0)
		AdjustmentsToCreditRating = st.number_input('Adjustments To Credit Rating', min_value=0, max_value=25, value=0)
		CreditRating1 = st.selectbox(' Credit Rating', ['Highest', 'High', 'Good', 'Medium', 'Low', 'VeryLow', 'Lowest'])
		CreditRating = st.selectbox(' Credit Rating', [1, 2, 3, 4, 5, 6, 7])
		PrizmCode1= st.selectbox(' Customer Residence', ['Town', 'Sunurban', 'Rural', 'Other'])
		PrizmCode = st.selectbox(' Customer Residence', [1, 2, 3, 4])
		Occupation1 = st.selectbox(' Customer Occupation', ['Clerical', 'Crafts', 'Homemaker', 'Other', 'Professional', 'Retired', 'Self', 'Student'])
		Occupation = st.selectbox(' Customer Occupation', [1, 2, 3, 4, 5, 6, 7, 8])

		output= ""
		output_prob = ""
		input_dict={

				"MonthlyRevenue": MonthlyRevenue,
				"MonthlyMinutes": MonthlyMinutes,
				"TotalRecurringCharge": TotalRecurringCharge,
				"DirectorAssistedCalls": DirectorAssistedCalls,
				"CustomerCareCalls": CustomerCareCalls,
				"ReceivedCalls": ReceivedCalls,
				"OutboundCalls": OutboundCalls,
				"InboundCalls": InboundCalls,
                                "MonthsInService":MonthsInService,
                                "UniqueSubs": UniqueSubs,
                                "ActiveSubs": ActiveSubs,
				"RetentionCalls": RetentionCalls,
				"RetentionOffersAccepted": RetentionOffersAccepted,
                                "IncomeGroup": IncomeGroup,
				"AdjustmentsToCreditRating": AdjustmentsToCreditRating,
				"CreditRating": CreditRating,
                                "PrizmCode": PrizmCode,
				"Occupation": Occupation

			}

		if st.button("Predict"):
			X = dv.transform([input_dict])
			y_pred = model.predict_proba(X)[0, 1]
			churn = y_pred >= 0.5
			output_prob = float(y_pred)
			output = bool(churn)
		st.success('Churn: {0}, Risk Score: {1}'.format(output, output_prob))
	if add_selectbox == 'Batch':
		file_upload = st.file_uploader("Upload csv file for predictions", type=["csv"])
		if file_upload is not None:
			data = pd.read_csv(file_upload)
			X = dv.transform([data])
			y_pred = model.predict_proba(X)[0, 1]
			churn = y_pred >= 0.5
			churn = bool(churn)
			st.write(churn)

if __name__ == '__main__':
	main()


from typing import Mapping

import pandas as pd

from cin_validator.rule_engine import CINTable, RuleContext, rule_definition
from cin_validator.test_engine import run_rule

CINdetails = CINTable.CINdetails
LAchildID = CINdetails.LAchildID
ReferralNFA = CINdetails.ReferralNFA
PrimaryNeedCode = CINdetails.PrimaryNeedCode
CINdetailsID = CINdetails.CINdetailsID

@rule_definition(
    code="8610",
    module=CINTable.CINdetails,
    message="Primary Need code is missing for a referral which led to further action.",
    affected_fields=[ReferralNFA, PrimaryNeedCode],
)
def validate(
    data_container: Mapping[CINTable, pd.DataFrame], rule_context: RuleContext
):
    df = data_container[CINdetails]
    df.index.name = "ROW_ID"
    df.reset_index(inplace=True)

    # If <ReferralNFA> (N00112) = false or 0
    # then
    # <PrimaryNeedCode> (N00101) must be present

    condition = (df[ReferralNFA].isin(["false", "0"])) & (df[PrimaryNeedCode].isna())
    df_issues = df[condition].reset_index()

    link_id = tuple(zip(df_issues[LAchildID], df_issues[CINdetailsID]))
    df_issues["ERROR_ID"] = link_id
    df_issues = (
        df_issues.groupby("ERROR_ID", group_keys=False)["ROW_ID"]
        .apply(list)
        .reset_index()
    )
    rule_context.push_type_1(
        table=CINdetails, columns=[ReferralNFA, PrimaryNeedCode], row_df=df_issues
    )

def test_validate():
    #  Fails rows 0, 1, and 3
    sample_cin = pd.DataFrame(
        {
            "LAchildID": ["child1", "child2", "child3", "child4", "child5"],
            "ReferralNFA": [
                "false",
                "0",
                "1",
                pd.NA,
                "true",
            ],
            "PrimaryNeedCode": [
                pd.NA,  # fail
                pd.NA,  # fail
                "12/09/2022",
                "05/12/1997",
                pd.NA,  # ignore: ReferralNFA is true
            ],
            "CINdetailsID": [
                "ID1",
                "ID2",
                "ID3",
                "ID4",
                "ID5",
            ],
        }
    )

    result = run_rule(validate, {CINdetails: sample_cin})

    issues = result.type1_issues

    issue_table = issues.table
    assert issue_table == CINdetails
    issue_columns = issues.columns
    assert issue_columns == [ReferralNFA, PrimaryNeedCode]

    issue_rows = issues.row_df

    assert len(issue_rows) == 2
    assert isinstance(issue_rows, pd.DataFrame)
    assert issue_rows.columns.to_list() == ["ERROR_ID", "ROW_ID"]

    expected_df = pd.DataFrame(
        [
            {
                "ERROR_ID": (
                    "child1",
                    "ID1",
                ),
                "ROW_ID": [0],
            },
            {
                "ERROR_ID": ("child2", "ID2"),
                "ROW_ID": [1],
            },
        ]
    )
    assert issue_rows.equals(expected_df)

    assert result.definition.code == "8610"
    assert (
        result.definition.message
        == "Primary Need code is missing for a referral which led to further action."
    )


import numpy as np
import matplotlib.pyplot as plt

if __name__ == '__main__':

    x = np.linspace(0, 1, 100)

    plt.plot(x, x, 'r-', label=r'$n_{eff}$')
    plt.plot(x, 8*x, 'b-', label=r'$Waveguide$')

    plt.legend(fontsize = 20)
    plt.show()


import pickle
import random
from Prediction.RobModel import RobModel
import numpy as np
import db_config
from matplotlib import pyplot
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.optimizers import Adam
from sklearn.feature_selection import RFE
from sklearn.linear_model import LogisticRegression
from math import sqrt
from numpy import concatenate
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt
import numpy

np.seterr(divide='ignore', invalid='ignore')

def loadData(riverId):
    cursor = db_config.cnx.cursor()
    sql = 'SELECT data FROM training_data WHERE river_id = %s'
    cursor.execute(sql, (riverId))
    return pickle.loads(cursor.fetchone()['data'])

def train(riverId, configId=1, data=None):
    config = getConfig(configId)

    if data == None:
        data = loadData(riverId)
    print(len(data[0]))
    data_X = data[0]
    data_y = data[1]
    print(np.array(data_X).shape)
    rng_state = np.random.get_state()
    np.random.shuffle(data_X)
    np.random.set_state(rng_state)
    np.random.shuffle(data_y)

    split = int(len(data_X) * 0.8)
    train_X = np.array(data_X[:split])
    train_y = np.array(data_y[:split])

    test_X = np.array(data_X[split:])
    test_y = np.array(data_y[split:])

    # design network
    model = Sequential()
    print(train_X.shape)
    model.add(LSTM(200, input_shape=(train_X.shape[1], train_X.shape[2])))
    model.add(Dense(1))
    model.compile(loss='mae', optimizer='adam', metrics=['mae', 'acc'])

    # fit network
    history = model.fit(train_X, train_y, epochs=500, batch_size=72, validation_data=(test_X, test_y), verbose=1, shuffle=True)
    # plot history
    # plot history
    pyplot.plot(history.history['loss'], label='train')
    pyplot.plot(history.history['val_loss'], label='test')
    pyplot.legend()
    pyplot.show()
    # make a prediction
    yhat = model.predict(test_X)

    robModel = RobModel(riverId, configId).set_model(model).save()
    return robModel

def getConfig(id):
    cursor = db_config.cnx.cursor()
    sql = 'SELECT * FROM model_configs WHERE id = %s'
    cursor.execute(sql, (id))
    return cursor.fetchone()

def getModel(riverId, configId=1):
    return RobModel(riverId, configId).load()


# -*- coding: utf-8 -*-
# @Time : 2022/5/25 16:25
# @Author : AMan

import requests

url = 'https://www.pearvideo.com/video_1763224'
videoId = url.split('_')[1]
# print(videoId)
v_url = 'https://www.pearvideo.com/videoStatus.jsp?contId=' + videoId + '&mrd=0.33864484737666944'
# print(v_url)

hds = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36",
    # 防盗链：溯源上一个页面
    "Referer": url
}

resp = requests.get(v_url, headers=hds)
# print(resp.text)
# print(resp.json().get("videoInfo").get("videos").get("srcUrl"))
# print(resp.json()["videoInfo"]["videos"]["srcUrl"])

video_get_srcUrl = resp.json()["videoInfo"]["videos"]["srcUrl"]
systemTime = resp.json()["systemTime"]

download_url = video_get_srcUrl.replace(systemTime, 'cont-' + videoId)
print(download_url)

with open('video/' + videoId + ".mp4", mode='wb') as f:
    f.write(requests.get(download_url).content)

print('over')

爬虫/第三章/2.梨视频.py


from . import views
from django.urls import path

app_name = 'entries'
urlpatterns = [
    path('', views.entry_view, name='entries'),

    path('create/', views.log_create_view, name='create'),
    path('<int:id>/', views.update_view, name='update'),
    path('<int:id>/delete/', views.delete_view, name='delete')

]


# -*- coding: utf-8 -*-
"""
Created on Sat Mar 27 16:47:49 2021

@author: abish
"""
import streamlit as st
import pickle
import pandas as pd
model=pickle.load(open('diamodel.pkl','rb'))

def main():
    html_temp="""

Diabetes check

"""
    safe="""
You Are Safe!!

    """
    danger="""
You Are Unsafe !!
"""
    nnn="""
Please enter some values , all fields can't be 0 !!
"""
    st.markdown(html_temp,unsafe_allow_html=True)
    BMI = st.text_input('Enter your BMI here (kg/m^2)')
    Gl=st.text_input('Enter your Glucose here (mg/dL)')
    Bp=st.text_input('Enter your Diastolic BloodPressure here (mm Hg)')
    Age=st.text_input('Enter your Age here (years)')
    ST=st.text_input('Enter your Skin Thickness here (mm)')
    preg=st.text_input('Enter your No. of pregnancies here')
    dpf=st.text_input('Enter your Diabetes Pedigree Function  here')
    insulin=st.text_input('Enter your insulin here (mu U/ml)')
    if st.button("predict"):
        a=pd.DataFrame({'Pregnancies':preg, 'Glucose':Gl, 'BloodPressure':Bp, 'SkinThickness':ST, 'Insulin':insulin,
       'BMI':BMI, 'DiabetesPedigreeFunction':dpf, 'Age':Age},index=[0])
        output=model.predict(a)

        if(output==0):
            st.markdown(safe,unsafe_allow_html=True)
        else:
            st.markdown(danger,unsafe_allow_html=True)

if __name__=='__main__':
    main()


from typing import List

from fastapi import Depends, FastAPI, HTTPException
from sqlalchemy.orm import Session

from . import crud, models, schemas
from .database import SessionLocal, engine

models.Base.metadata.create_all(bind=engine)

app = FastAPI()

# Dependency
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@app.post("/karyawan/", response_model=schemas.Karyawan)
def create_karyawan(karyawan: schemas.KaryawanCreate, db: Session = Depends(get_db)):
    # db_karyawan = crud.get_karyawan_by_email(db, email=karyawan.email)
    # if db_karyawan:
    #     raise HTTPException(status_code=400, detail="Email already registered")
    return crud.create_karyawan(db=db, karyawan=karyawan)

@app.get("/karyawan/", response_model=List[schemas.Karyawan])
def read_karyawan(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    karyawan = crud.get_karyawans(db, skip=skip, limit=limit)
    return karyawan

@app.get("/karyawan/{karyawan_id}", response_model=schemas.Karyawan)
def read_karyawan(karyawan_id: int, db: Session = Depends(get_db)):
    db_karyawan = crud.get_karyawan(db, karyawan_id=karyawan_id)
    if db_karyawan is None:
        raise HTTPException(status_code=404, detail="Karyawan not found")
    return db_karyawan

@app.put("/karyawan/{karyawan_id}", response_model=schemas.Karyawan)
def read_karyawan(karyawan_id: int, karyawan: schemas.KaryawanCreate, db: Session = Depends(get_db)):
    db_karyawan = crud.edit_karyawan(db, karyawan_id=karyawan_id, karyawan=karyawan)
    if db_karyawan is None:
        raise HTTPException(status_code=404, detail="Karyawan not found")
    return db_karyawan

@app.delete("/karyawan/{karyawan_id}", response_model=schemas.Karyawan)
def read_karyawan(karyawan_id: int, db: Session = Depends(get_db)):
    db_karyawan = crud.delete_karyawan(db, karyawan_id=karyawan_id)
    if db_karyawan is None:
        raise HTTPException(status_code=404, detail="Karyawan not found")
    return db_karyawan


from django.core.management.base import BaseCommand
from mixer.backend.django import mixer

from situation_report_app.models import Post
from users_app.models import AppUser

class Command(BaseCommand):

    def handle(self, *args, **options):
        AppUser.objects.filter(is_superuser=False).delete()

        count = 500
        for i in range(count):
            p = (i/count)*100
            print(f'{i}) {p} %')
            new_post = mixer.blend(Post)
            print(new_post)
            mixer.blend(Post)

        print('end')


from datetime import datetime, timedelta
import gedcom

def US12():
    for k, v in gedcom.FAMs.items():
        if gedcom.INDIs[v.husbandid].birthday != 'N/A' and gedcom.INDIs[v.wifeid] != 'N/A':
            bd_father = datetime.strptime(gedcom.INDIs[v.husbandid].birthday, '%d %b %Y')
            bd_mother = datetime.strptime(gedcom.INDIs[v.wifeid].birthday, '%d %b %Y')
            for c in v.children:
                if gedcom.INDIs[c].birthday != 'N/A':
                    bd_child = datetime.strptime(gedcom.INDIs[c].birthday, '%d %b %Y')
                    diff_father = (abs((bd_father - bd_child).days))/365
                    diff_mother = (abs((bd_mother - bd_child).days))/365
                    if diff_father > 80:
                        print('ERROR: INDIVIDUAL: US12: ' + c + ': Has over 80 years than his father [ ' + str(diff_father) + 'years ].')
                    if diff_mother > 60:
                        print('ERROR: INDIVIDUAL: US12: ' + c + ': Has over 60 years than his mother [ ' + str(diff_mother) + 'years ].')

def US36():
    for k, v in gedcom.INDIs.items():
        if v.death != 'N/A':
            _date = datetime.strptime(v.death, '%d %b %Y')
            death = abs((_date  - datetime.today()).days)
            if death < 30:
                print('ERROR: INDIVIDUAL: US36: ' + v.indiid + ': died in the last 30 days [ ' + str(death) + 'days ].')


from django.shortcuts import render
import operator

def homepage(request):
    return render(request, "home.html")

def count(request):
    fulltext = request.GET["fulltext"]

    number_of_words = fulltext.split()
    # = ['a', 'b', 'c']

    words_dictionary = {}

    for word in number_of_words:
        if word in words_dictionary:
            words_dictionary[word] += 1
        else:
            words_dictionary[word] = 1

    # sorted_words = sorted(words_dictionary.items(), key=lambda k: k[1], reverse=True)
    # what i found the way

    sorted_words = sorted(
        words_dictionary.items(), key=operator.itemgetter(1), reverse=True
    )

    return render(
        request,
        "count.html",
        {
            "fulltext": fulltext,
            "number_of_words": len(number_of_words),
            "sorted_words": sorted_words,
        },
    )

def about(request):
    return render(request, "about.html")