#!\bin\python3

import pyshark
import matplotlib.pyplot as plt
import matplotlib.dates as md
import json
import argparse
import sys
from datetime import datetime, timedelta, time
import APIForecast
import Dataset
import Utils

# Params
def parse_args():
    parser = argparse.ArgumentParser(description='Simple script that generates a plot based on an input dataset.json')
    data_parser = parser.add_mutually_exclusive_group(required=False)
    data_parser.add_argument('--trset', type=str, required=False, default="NULL",
                             help='dataset from which the script reads the values for training')
    parser.add_argument('--testset', type=str, required=False, default="NULL",
                             help='dataset from which the script reads the values for testing')
    data_parser.add_argument('--pcap', type=str, required=False, default="NULL",
                             help='pcap from which the script reads the packets')
    parser.add_argument('--alpha', type=float, required=False, default=-1,
                        help='alpha parameter for forecasting')
    parser.add_argument('--beta', type=float, required=False, default=-1,
                        help='beta parameter for forecasting')
    parser.add_argument('--gamma', type=float, required=False, default=-1,
                        help='gamma parameter for forecasting')
    iter_parser = parser.add_mutually_exclusive_group(required=False)
    iter_parser.add_argument('--iterative', dest='iter', action='store_true',
                             help='iterates the fitting process 100 times and picks the best result (default)')
    iter_parser.add_argument('--no-iterative', dest='iter', action='store_false',
                             help='execs the fitting process just once')
    parser.set_defaults(iter=True)
    parser.add_argument('--season', type=int, required=False, default=-1,
                        help='points in a season for Holt-Winters forecasting')
    parser.add_argument('--rsi', type=int, required=False, default=2,
                        help='points for RSI calculation')
    parser.add_argument('--interval', type=int, required=False, default=30,
                        help='number of seconds for aggregation')
    return parser.parse_args()

def sse(values, predictions):
    val = 0
    for n, r in zip(values, predictions):
        val = val + ((n - r) ** 2)
    return val

Utils.printgreen("********************************************")
Utils.printgreen("************* DEMO     CAPTURE *************")
Utils.printgreen("********************************************")

# Arguments
args = parse_args()
dataset = args.trset  # Dataset if present
pcap = args.pcap  # PCAP if present

start_time = datetime.now()
nums = []  # Data
dates = []  # Timestamps
count = 0  # Counting (output)
errors = 0  # Errors (output)
if dataset == "NULL" and pcap == "NULL":
    Utils.printgreen("Generating dataset...\n")
    for i in range(14):
        generated = Dataset.createDataset()
        for n in generated:
            nums.append(n)
    n = 0  # Temp (output)
    now = datetime.combine(datetime.today(), time.min)
    for n in nums:
        count = count + 1
        dates.append(now)
        now = now + timedelta(minutes=5)  # Every 5 mins TODO: parameter to specify
        Utils.printyellow("\r\033[F\033[KGenerating\t" + "#" + str(count) + " " + str(n) + "B")
else:
    if dataset != "NULL":
        Utils.printgreen("Loading dataset...\n")
        nums = json.load(open(dataset, "r"))
        n = 0
        now = datetime.combine(datetime.today(), time.min)
        for n in nums:
            count = count + 1
            dates.append(now)
            now = now + timedelta(minutes=5)
            Utils.printyellow("\r\033[F\033[KLoading\t" + "#" + str(count) + " " + str(n) + "B")

    elif pcap != "NULL":
        Utils.printgreen("Loading PCAP...\n")
        cap = pyshark.FileCapture(pcap)  # Reading from PCAP
        for pkt in cap:
            try:
                dates.append(float(pkt.frame_info.time_epoch))
                nums.append(int(pkt.length) / 1000)
                count += 1
                Utils.printyellow("\r\033[F\033[KLoading\t" + "#" + str(count) + " " + str(int(pkt.length)) + "B")
            except AttributeError:
                errors += 1
                continue

        # Aggregation
        interval = args.interval
        intervals = []
        series = []
        start = -1
        sum = 0
        j = 0
        for i in range(len(dates)):
            if start == -1:
                start = i
                sum += nums[i]
            else:
                elapsed = datetime.fromtimestamp(dates[i]) - datetime.fromtimestamp(dates[start])
                sum += nums[i]
                if elapsed.total_seconds() > interval:
                    j += 1
                    series.append(sum)
                    intervals.append(datetime.fromtimestamp(dates[i]))
                    lastdate = datetime.fromtimestamp(dates[i])
                    sum = 0
                    start = -1
        nums = series
        dates = intervals

elapsed = (datetime.now() - start_time)
print("\r\033[F\033[K", end="")
Utils.printyellow("Loaded\t" + str(count) + " data points in " + str(elapsed))  # Output
Utils.printyellow("\t" + str(errors) + " errors")
Utils.printyellow("\tFrom " + dates[0].strftime("%Y-%m-%d %H:%M") + " to " +
                  dates[len(dates) - 1].strftime("%Y-%m-%d %H:%M"))

# Parameters
alpha = args.alpha
beta = args.beta
gamma = args.gamma
lastdate = dates[len(dates) - 1]
count = len(nums)

if alpha != -1 and beta != -1 and gamma != -1:  # All parameters specified, Holt-Winters forecasting
    season = args.season
    if season == -1: season = len(nums) // 2  # TODO ugly
    res, dev, ubound, lbound = APIForecast.triple_exponential_smoothing(nums, season, alpha, beta, gamma, season)  # API
    RSI = APIForecast.rsi(nums, args.rsi)

    for f in res[len(nums):]:
        lastdate = lastdate + timedelta(minutes=5)
        dates.append(lastdate)

    SSE = sse(nums, res)
    MSE = SSE / count

    Utils.printgreen("\n\nHolt-Winters until " + dates[len(dates) - 1].strftime("%Y-%m-%d %H:%M:%S"))

    strSSE = "{:.5f}".format(SSE)
    strMSE = "{:.5f}".format(MSE)
    stralpha = "{:.5f}".format(alpha)
    strbeta = "{:.5f}".format(beta)
    strgamma = "{:.5f}".format(gamma)
    Utils.plot(nums, dates, res, ubound, lbound, RSI, "Holt-Winters forecasting (fitted alpha = " + stralpha +
               ", beta = " + strbeta + ", gamma = " + strgamma + ")\nSSE = " + strSSE + ", MSE = " + strMSE)
    testset = args.testset
    if testset != "NULL":
        Utils.printgreen("\n\nHolt-Winters anomaly detection on " + testset)
#       ubound, lbound = [], []
        nums = json.load(open(testset, "r"))
        datess = []
        now = datetime.combine(datetime.today(), time.min)
        count = 0
        for n in nums:
            datess.append(now)
            now = now + timedelta(minutes=5)
#           ubound.append(res[count % season] + 2.5 * dev[count % season])
#           lbound.append(res[count % season] - 2.5 * dev[count % season])
            count += 1
        RSI = APIForecast.rsi(nums, args.rsi)
        Utils.plot(nums, datess, None, ubound[0:len(nums)], lbound[0:len(nums)], RSI, "Holt-Winters forecasting (fitted alpha = " + stralpha +
               ", beta = " + strbeta + ", gamma = " + strgamma + ")")
elif alpha != -1 and beta != -1:  # Only alpha and beta specified, Double Exponential forecasting
    res = APIForecast.double_exponential_smoothing(nums, alpha, beta)
    RSI = APIForecast.rsi(nums, args.rsi)

    for f in res[len(nums):]:
        lastdate = lastdate + timedelta(minutes=5)
        dates.append(lastdate)

    Utils.printgreen("\n\nDouble Exponential until " + dates[len(dates) - 1].strftime("%Y-%m-%d %H:%M:%S"))

    Utils.plot(nums, dates, res, None, None, RSI, "Double Exponential forecasting (alpha = " +
               str(alpha) + ", beta = " + str(beta) + ")")
elif alpha != -1:  # Only alpha specified, Single Exponential forecasting
    res = APIForecast.exponential_smoothing(nums, alpha)
    RSI = APIForecast.rsi(nums, args.rsi)

    dates.append(lastdate + timedelta(seconds=5))

    Utils.printgreen("\n\nSingle Exponential until " + dates[len(dates) - 1].strftime("%Y-%m-%d %H:%M:%S"))

    Utils.plot(nums, dates, res, None, None, RSI, "Single Exponential forecasting (alpha = " + str(alpha) + ")")
else:  # No parameters specified, auto fitting with Nelder-Mead
    season = args.season
    if season == -1: season = len(nums) // 2  # TODO ugly
    start_time = datetime.now()
    itr = args.iter
    if itr:
        iterations = 100
    else:
        iterations = 1
    Utils.printgreen("\n\nFitting data...\n\n\n")

    bests = []
    for i in range(iterations):
        alpha, beta, gamma, SSE = APIForecast.fit_neldermead(nums, season)
        bests.append([[alpha, beta, gamma], SSE])
        Utils.printyellow("\r\033[F\033[K\r\033[F\033[K\r\033[F\033[KIterations\t" + str(len(bests)))
        Utils.printyellow("Last\talpha\tbeta\tgamma\tSSE")
        Utils.printyellow("\t" + "{:.5f}".format(alpha) + "\t" + "{:.5f}".format(beta) + "\t" + "{:.5f}".format(gamma) + "\t" + "{:.5f}".format(SSE))

    bests.sort(key=lambda x: x[1])
    alpha = bests[0][0][0]
    beta = bests[0][0][1]
    gamma = bests[0][0][2]
    SSE = bests[0][1]
    MSE = SSE / count

    res, dev, ubound, lbound = APIForecast.triple_exponential_smoothing(nums, season, alpha, beta, gamma, season)
    RSI = APIForecast.rsi(nums, args.rsi)

    for f in res[len(nums):]:
        lastdate = lastdate + timedelta(minutes=5)
        dates.append(lastdate)

    # Formatting for better output
    strSSE = "{:.5f}".format(SSE)
    strMSE = "{:.5f}".format(MSE)
    stralpha = "{:.5f}".format(alpha)
    strbeta = "{:.5f}".format(beta)
    strgamma = "{:.5f}".format(gamma)
    elapsed = (datetime.now() - start_time)
    Utils.printyellow("\nFitted in " + str(
        elapsed) + "!\n\talpha = " + stralpha + "\n\tbeta = " + strbeta + "\n\tgamma = " + strgamma)
    Utils.printgreen("\n\nHolt-Winters until " + dates[len(dates) - 1].strftime("%Y-%m-%d %H:%M:%S"))

    Utils.plot(nums, dates, res, ubound, lbound, RSI, "Holt-Winters forecasting (fitted alpha = " + stralpha +
               ", beta = " + strbeta + ", gamma = " + strgamma + ")\nSSE = " + strSSE + ", MSE = " + strMSE)


import json

from didsdk.core.did_key_holder import DidKeyHolder
from didsdk.core.key_provider import KeyProvider
from didsdk.core.property_name import PropertyName
from didsdk.document.encoding import EncodeType
from didsdk.document.publickey_property import PublicKeyProperty
from didsdk.jwt.elements import Header, Payload
from didsdk.jwt.jwt import Jwt

class DidScoreParameter:
    """This class is used to create transaction parameters.

    The transaction parameters that call a score function that can use all the features of the DID document.
    """

    @staticmethod
    def _create_public_key_property(key_provider: KeyProvider, encode_type: EncodeType) -> PublicKeyProperty:
        return PublicKeyProperty(
            id=key_provider.key_id,
            type=[key_provider.type.value.identifier],
            public_key=key_provider.public_key,
            encode_type=encode_type,
        )

    @staticmethod
    def add_key(did_key_holder: DidKeyHolder, key_provider: KeyProvider, encode_type: EncodeType) -> Jwt:
        """Create a parameter for transaction that update the DID Document. (add publicKey)

        It's used for `didsdk.did_service.DidService.add_public_key()`.

        :param did_key_holder: the DidKeyHolder object to use for authentication.
        :param key_provider: the KeyProvider object to add.
        :param encode_type: the encode type
        :return: the Jwt object from parameters.
        """
        header = Header(alg=did_key_holder.type.name, kid=did_key_holder.kid)

        public_key_provider = DidScoreParameter._create_public_key_property(key_provider, encode_type)
        contents = {
            PropertyName.KEY_TX_UPDATE_METHOD: PropertyName.KEY_TX_UPDATE_METHOD_ADDKEY,
            PropertyName.KEY_TX_UPDATE_PARAM: {
                "id": did_key_holder.did,
                PropertyName.KEY_DOCUMENT_PUBLICKEY: public_key_provider.as_dict(),
            },
        }
        payload = Payload(contents=contents)

        return Jwt(header, payload)

    @staticmethod
    def create(key_provider: KeyProvider, encode_type: EncodeType) -> str:
        """Create a parameter set for transaction that creates the DID Document.

        It's used for `didsdk.did_service.DidService.create()`.

        :param key_provider: keyProvider the KeyProvider object
        :param encode_type:
        :return: the json string
        """
        public_key_property = DidScoreParameter._create_public_key_property(key_provider, encode_type)
        return json.dumps(public_key_property.as_dict())

    @staticmethod
    def revoke_key(did_key_holder: DidKeyHolder, revoke_key_id: str) -> Jwt:
        """Create a parameter for transaction that update the DID Document. (revoke publicKey)

        It's used for `didsdk.did_service.DidService.revoke_key()`.

        :param did_key_holder: the DidKeyHolder object to use for authentication.
        :param revoke_key_id: the id of the public key to revoke.
        :return: the Jwt object from parameters.
        """
        header = Header(alg=did_key_holder.type.name, kid=did_key_holder.kid)

        contents = {
            PropertyName.KEY_TX_UPDATE_METHOD: PropertyName.KEY_TX_UPDATE_METHOD_REVOKEKEY,
            PropertyName.KEY_TX_UPDATE_PARAM: {
                PropertyName.KEY_DOCUMENT_ID: did_key_holder.did,
                PropertyName.KEY_DOCUMENT_PUBLICKEY: revoke_key_id,
            },
        }
        payload = Payload(contents=contents)

        return Jwt(header, payload)


class Solution:
    def longestObstacleCourseAtEachPosition(self, obstacles: List[int]) -> List[int]:
        lis = []
        res = []

        for obs in obstacles:
            if len(lis) == 0 or lis[-1] <= obs:
                lis.append(obs)
                res.append(len(lis))
            else:
                index = bisect.bisect(lis, obs)
                lis[index] = obs
                res.append(index + 1)

        return res


#!/usr/bin/env python3

import rospy
from pseudo_vision.msg import Image
from sensor_msgs.msg import LaserScan
from utils import get_occupancy_grid, radial_to_xy

class ImagePublisher:
    def __init__(self):
        self.lidar_sub = rospy.Subscriber(
            "/scan", LaserScan, self.scan_callback, queue_size=1
        )
        self.img_pub = rospy.Publisher("/occupancy_grid", Image, queue_size=1)

        self.occ_grid_config = rospy.get_param("occ_grid")
        self.scan_to_xy_config = rospy.get_param("scan_to_xy")

    def scan_callback(self, data):
        """
        get LiDAR points from /scan, converts it into occupancy grid and publishes to /occupancy_grid
        """

        # get occpancy grid
        pts = radial_to_xy(data.ranges, **self.scan_to_xy_config)
        img = get_occupancy_grid(pts, **self.occ_grid_config)

        # publish to /occupancy_grid
        data = Image()
        data.image = img.flatten().tolist()
        self.img_pub.publish(data)
        rospy.loginfo("Image Published!")

def main():
    rospy.init_node("image_publisher")
    ImagePublisher()
    rospy.spin()

if __name__ == "__main__":
    main()


# -*- coding: utf-8 -*-

import time
import copy, json,sys
import croniter as cron
import datetime as dt
from datetime import datetime, timedelta
import threading

import models
from state import State
from utils import log
# import utils.kafka_utils as kafka_utils
import utils.redis_utils as kafka_utils
import config
import utils.process_utils as process_utils
class TimerInfo(object):
    def __init__(self, task_id, execute_time, etl_day=None):
        self.task_id = task_id
        self.execute_time = execute_time
        self.etl_day = etl_day

    def __repr__(self):
        return "task_id: {}, execute_time: {}, etl_day: {}"\
            .format(self.task_id, self.execute_time, self.etl_day)

class MainScheduler(object):
    """
    the MainScheduler is for crontab, fetch crontab config from mysql
    Keyword Arguments:
        broker: 'host[:port]' string (or list of 'host[:port]'strings)
        fetch_interval (int): scheduler fetch db interval seconds. Default: 30.
        woker_timeout (int): worker timeout milliseconds. Default: 300
        retry_push_times (int): repush cron job to queue times. Default:3
    """
    DEFAULT_CONFIG = {
        'broker': "localhost:9092",
        'fetch_interval': 30,
        'woker_timeout': -1,
        'retry_push_times': 3,
    }
    def __init__(self, **configs):
        self.config = copy.copy(self.DEFAULT_CONFIG)
        for key in self.config:
            if key in configs:
                self.config[key] = configs.pop(key)

        self.crons_conf = {}
        self.timer_list = []
        self.fetch_time = None
        self.depend_scheduler = None
        self.helper_scheduler = None

    def check_sub_threading(self):
        if self.depend_scheduler is None or \
                not self.depend_scheduler.isAlive():
            self.depend_scheduler = DependencyScheduler()
            self.depend_scheduler.setDaemon(True)
            self.depend_scheduler.start()
        else:
            log.logger.info("depend_scheduler is alive")
        if self.helper_scheduler is None or \
                not self.helper_scheduler.isAlive():
            self.helper_scheduler = SchedulerHelper()
            self.helper_scheduler.setDaemon(True)
            self.helper_scheduler.start()
        else:
            log.logger.info("helper_scheduler is alive")

    def run(self):
        log.logger.info("Starting the MainScheduler")
        kafka_utils.setup_kafka(config.G_Conf.Common.Broker)

        exception_count = 0
        exception_begin = datetime.now()
        max_exception_count = 5
        max_exception_seconds = 3 * 60

        while True:
            # try:
            # check_sub_threading
            self.check_sub_threading()

            # get cron 获取定时任务
            execute_timer = self.getMatchedCronTask()
            print('######execute_timer:#####')
            print(execute_timer)
            for timer in execute_timer:
                #根据task_id 执行具体任务
                self.run_timer(timer)
                if timer.task_id in self.crons_conf \
                        and self.crons_conf[timer.task_id].cron_type != State.CRON_SINGLE:
                    #增加更新 self.timer_list
                    self.addTimer(self.crons_conf[timer.task_id])

            # retry timeout worker 重做超时任务
            self.retryZombieInstance()
            waiting = self._next_wait()
            time.sleep(waiting)
            exception_count = 0
            # except Exception as e:
            #     exception_count += 1
            #     if exception_count == 1:
            #         exception_begin = datetime.now()
            #     exception_duration = (datetime.now() - exception_begin).total_seconds()
            #     alert_msg = "if get exception {} times in {} seconds, " \
            #                 "the MainScheduler will exit, current:{} times/{} seconds, exception:{}-{}".\
            #         format(max_exception_count, max_exception_seconds, exception_count, exception_duration, type(e), str(e))
            #     if exception_count >= max_exception_count and exception_duration >= max_exception_seconds:
            #         alert_msg = "scheduler exit, do somthing {}".format(alert_msg)
            #         log.logger.error(alert_msg)
            #         process_utils.Alert(alert_msg)
            #         sys.exit(1)
            #     else:
            #         log.logger.error(alert_msg)
            #         process_utils.Alert(alert_msg)

            #     time.sleep(10)

        log.logger.info("End the scheduler, exit main loop")

    def _next_wait(self):
        """
        main loop sleep scends
        :return: second
        """
        wait_seconds = self.config["fetch_interval"]
        now = datetime.now()
        if len(self.timer_list) > 0:
            timer = self.timer_list[0]
            distance = (timer.execute_time - now).total_seconds()
            if distance > 0 and distance >= wait_seconds:
                pass
            elif distance > 0 and distance < wait_seconds:
                wait_seconds = distance
            elif distance <= 0:
                wait_seconds = 0
        return wait_seconds

    def getMatchedCronTask(self):
        """
        getMatchedCronTask
        :return: matched crontab list
        """
        self._fetchNewCronTask()
        match_timer = []
        now = datetime.now()
        total_size = len(self.timer_list)
        for index, timer in enumerate(self.timer_list):
            if (now - timer.execute_time).total_seconds() >= 0:
                match_timer.append(timer)
            else:
                self.timer_list = self.timer_list[index:]
                break
        if len(match_timer) == total_size:
            self.timer_list = []
        return match_timer

    def _fetchNewCronTask(self):
        """
        update cron info
        :return:
        """
        cron_list = models.CronConf().getCronTask(fetch_time=self.fetch_time)
        for cron in cron_list:
            if (cron.task_id not in self.crons_conf) or (cron.start_time != self.crons_conf[cron.task_id].start_time):
                self.crons_conf[cron.task_id] = cron
                self.addTimer(cron_conf=cron)
        self.fetch_time = datetime.now()

    def calcExecuteTime(self, cron_format):
        """
        calcExecuteTime
        :param cron_format: crontab format time
        :return: next time to run
        """
        return cron.croniter(cron_format, datetime.now()).get_next(datetime)

    def addTimer(self, cron_conf):
        """
        addTimer
        :param cron_conf: cron conf
        :return:
        """
        self.timer_list = list(filter(lambda x: x.task_id != cron_conf.task_id, self.timer_list))
        now = datetime.now()
        execute_time = self.calcExecuteTime(cron_conf.start_time)
        if cron_conf.cron_type == State.CRON_SINGLE \
                and (now - execute_time).total_seconds() > 0:
                return
        self.timer_list.append(TimerInfo(task_id=cron_conf.task_id,
                                         execute_time=execute_time
                                         ))
        self.timer_list = sorted(self.timer_list, key=lambda info:info.execute_time)

    def calcCronEtlDay(self, cron_conf, execute_time):
        """
        calcCronEtlDay
        :param cron_conf: cron_conf
        :param execute_time: datetime
        :return: etl_day string
        """
        now = datetime.now()
        etl_day = None
        if cron_conf.cron_type == State.CRON_SINGLE:
            etl_day = cron_conf.start_time # 配置单次任务时，开始日期格式:'%Y-%m-%d %H:%M:%S'
        elif cron_conf.cron_type == State.CRON_INTERVAL:
            etl_day = (now - timedelta(seconds=self.calcInterval(cron_conf.start_time))) \
                .strftime('%Y%m%d%H%M%S')
        elif cron_conf.cron_type == State.CRON_HOUR:
            etl_day = (now - timedelta(seconds=self.calcInterval(cron_conf.start_time))) \
                .strftime('%Y%m%d%H%M%S')
        elif cron_conf.cron_type == State.CRON_DAY:
            etl_day = (execute_time + timedelta(days=-1)).strftime('%Y%m%d')
        elif cron_conf.cron_type == State.CRON_MONTH:
            print('###################################')
            etl_day = (dt.date.today().replace(day=1) - dt.timedelta(1)) \
                .strftime('%Y%m')
            print(etl_day)
            print('###################################')
        else:
            etl_day = now.strftime('%Y%m%d%H%M%S')
        return etl_day

    def calcInterval(self, cron_format):
        """
        "*/5 * * * *"
        :return 5 * 60
        :param format:
        :return: seconds
        """
        first = cron.croniter(cron_format, datetime.now()).get_next(datetime)
        second = cron.croniter(cron_format, first).get_next(datetime)
        return (second - first).total_seconds()

    def run_timer(self, timer):
        """
        :param task: timer info
        :return: err
        """
        log.logger.info(" begin run timer {} with time {}".format(timer.task_id, timer.execute_time))
        task_list = models.CronConf().getCronTask(timer.task_id)
        err = None
        print('####task_list#####')
        print(task_list)
        for cron_conf in task_list:
            if cron_conf.enable != State.Enabled:
                err = " task {}, status {} is not enabled, stop running ".format(cron_conf.task_id,cron_conf.enable)
                log.logger.info(err)
                continue
            timer.etl_day = self.calcCronEtlDay(cron_conf, timer.execute_time)
            self.create_instance(cron_conf, timer.etl_day)
        return err

    def create_instance(self, cron_conf, etl_day):
        instance_list = []
        cron_log = models.CronLog().create_cron_log(cron_conf, etl_day)
        print('-----------------------------------------')
        #根任务
        if cron_conf.task_id == State.ROOT_TASK:
            job_list = models.TaskDefine().get_valid_job(cron_type=cron_conf.cron_type)
            models.TaskInstance().create_job_task_instance(execute_date=etl_day, job_list=job_list)
        #定时任务
        elif cron_conf.type == State.TASK_CRON:
            instance_list = models.TaskInstance().create_cron_task_instance(execute_date=etl_day, cron_list=[cron_conf])
        # #触发月、小时、任务
        elif cron_conf.type == State.TASK_JOB:
            instance_list = models.TaskInstance().create_cron_task_instance(execute_date=etl_day, cron_list=[cron_conf])
            job_list = models.TaskDefine().get_valid_job(cron_type=cron_conf.cron_type)
            models.TaskInstance().create_job_task_instance(execute_date=etl_day, job_list=job_list)

        else:
            err = "task_id:{} name:{} type:{}, unknow task type".format(cron_conf.task_id, cron_conf.name, cron_conf.type)
            log.logger.info("{}".format(err))
            cron_log.update_cron_status(State.SHUTDOWN)
            return

        for instance in instance_list:
            err = kafka_utils.PushMsgWithRetry(kafka_utils.TOPIC_DISPATCHER,
                                           kafka_utils.TaskBeginMsg(
                                               instance_id=instance.id,
                                               task_id=instance.task_id,
                                               execute_date=instance.etl_day)
                                           )
            log.logger.info("push task to queue, instance {}, err {}".format(instance, err))
        cron_log.update_cron_status(State.SUCCESS)

    def retryZombieInstance(self):
        """
        fetchZombieInstance
        :param session:
        :return:
        """
        log.logger.debug("begin retry timeout task instance")
        instance_list = models.TaskInstance().create_retry_instance(timer_out=self.config["woker_timeout"],
                                                                    max_schedule=self.config["retry_push_times"])
        for instance in instance_list:
            err = kafka_utils.PushMsgWithRetry(kafka_utils.TOPIC_DISPATCHER,
                                               kafka_utils.TaskBeginMsg(
                                                   instance_id=instance.id,
                                                   task_id=instance.task_id,
                                                   execute_date=instance.etl_day)
                                               )
            log.logger.debug("retry timeout task instance {}, err {}".format(instance, err))

        log.logger.info("end retry timeout task instance")

class DependencyScheduler(threading.Thread):
    """
    DependencyScheduler is for dependency task
    Keyword Arguments:
        broker: 'host[:port]' string (or list of 'host[:port]'strings)
        fetch_interval (int): scheduler fetch db interval seconds. Default: 30.
        woker_timeout (int): worker timeout milliseconds. Default: 300
        retry_push_times (int): repush cron job to queue times. Default:3
    """
    DEFAULT_CONFIG = {
        'broker': "localhost:9092",
        'fetch_interval': 1000,
        'woker_timeout': 10000,
        'retry_push_times': 3,
    }
    def __init__(self, **configs):
        super(DependencyScheduler, self).__init__(name="DependencyScheduler")
        self.config = copy.copy(self.DEFAULT_CONFIG)
        for key in self.config:
            if key in configs:
                self.config[key] = configs.pop(key)

    def run(self):
        log.logger.info("Starting the DependencyScheduler")
        producer=kafka_utils.setup_kafka(config.G_Conf.Common.Broker)
        def gen_obj(d):
            return kafka_utils.TaskOverMsg(d['instance_id'],
                                           d['task_id'],
                                           d['status'],
                                           d['execute_date'])
        exception_count = 0
        exception_begin = datetime.now()
        max_exception_count = 5
        max_exception_seconds = 3 * 60

        while True:
            try:
                # for msg in kafka_utils.TOPIC_TASK_RESULT:
                if producer.llen(kafka_utils.TOPIC_TASK_RESULT):
                    msg = producer.rpop(kafka_utils.TOPIC_TASK_RESULT)#这里可以用StrictRedis实例的brpop改善，去掉llen轮询。
                    msg_obj = gen_obj(json.loads(msg))
                    log.logger.info("get task result:{}".format(msg_obj))
                    #kafka_utils.scheduler_consumer.commit()

                    # the worker push msg only success
                    met_task = models.TaskDependency().downstream_met_dependency(task_id=msg_obj.task_id,
                                                                                execute_date=msg_obj.execute_date)
                    if len(met_task) > 0:
                        self.run_task(msg_obj.execute_date, met_task)
                else:
                    log.logger.info("begin fetch waiting_dep task list")
                    self.run_task()
                    log.logger.info("end fetch waiting_dep task list ")
                    time.sleep(10)
            except Exception as e:
                exception_count += 1
                if exception_count == 1:
                    exception_begin = datetime.now()
                exception_duration = (datetime.now() - exception_begin).total_seconds()
                alert_msg = "if get exception {} times in {} seconds, " \
                            "the DependencyScheduler will exit, current:{} times/{} seconds, exception:{}-{}". \
                    format(max_exception_count, max_exception_seconds, exception_count, exception_duration, type(e), str(e))
                if exception_count >= max_exception_count and exception_duration >= max_exception_seconds:
                    alert_msg = "scheduler exit, do somthing {}".format(alert_msg)
                    log.logger.error(alert_msg)
                    process_utils.Alert(alert_msg)
                    return
                else:
                    log.logger.error(alert_msg)
                    process_utils.Alert(alert_msg)
                time.sleep(10)
        log.logger.info("Quit the DependencyScheduler")

    def run_task(self, execute_date=None, task_list=None):
        """
        run_dep_task
        :param execute_date: YYYY-MM-DD
        :param task_list: task_list
        :return:
        """
        new_instance = []
        if execute_date is None or task_list is None:
            waiting_dep_instance = models.TaskInstance().get_waiting_dep_instance()
            for waiting_task in waiting_dep_instance:
                etl_day = waiting_task.etl_day
                met, msg = models.TaskDependency().\
                    is_met_dependency(waiting_task.task_id,
                                      waiting_task.etl_day)
                if met:
                    tmp = models.TaskInstance(). \
                        job_prepare_running(etl_day, [waiting_task.task_id])
                    if len(tmp) > 0:
                        new_instance.extend(tmp)
                else:
                    log.logger.info("etl_day: {}, task {} not met dependency -> {}".format(etl_day, waiting_task.task_id, msg))
        else:
            new_instance = models.TaskInstance(). \
                job_prepare_running(execute_date, task_list)

        log.logger.info(" queued new_instance {}".format(new_instance))
        for instance in new_instance:
            err = kafka_utils.PushMsgWithRetry(kafka_utils.TOPIC_DISPATCHER,
                                               kafka_utils.TaskBeginMsg(
                                                   instance_id=instance.id,
                                                   task_id=instance.task_id,
                                                   execute_date=instance.etl_day)
                                       )
            log.logger.info("push task to queue, instance {}, err {}".format(instance, err))

class SchedulerHelper(threading.Thread):
    """
    SchedulerHelper SchedulerHelper
    """
    DEFAULT_CONFIG = {
    }
    def __init__(self, **configs):
        super(SchedulerHelper, self).__init__(name="SchedulerHelper")
        self.config = copy.copy(self.DEFAULT_CONFIG)
        for key in self.config:
            if key in configs:
                self.config[key] = configs.pop(key)
        self.scheduler_finished_day = {}

    def run(self):
        log.logger.info("Starting SchedulerHelper")
        exception_count = 0
        exception_begin = datetime.now()
        max_exception_count = 5
        max_exception_seconds = 3 * 60

        while True:
            try:
                self.check_scheduler_result()
                time.sleep(30)
            except Exception as e:
                exception_count += 1
                if exception_count == 1:
                    exception_begin = datetime.now()
                exception_duration = (datetime.now() - exception_begin).total_seconds()
                alert_msg = "if get exception {} times in {} seconds, " \
                            "the SchedulerHelper will exit, current:{} times/{} seconds, exception:{}-{}". \
                    format(max_exception_count, max_exception_seconds, exception_count, exception_duration, type(e), str(e))
                if exception_count >= max_exception_count and exception_duration >= max_exception_seconds:
                    alert_msg = "scheduler exit, do somthing {}".format(alert_msg)
                    log.logger.error(alert_msg)
                    process_utils.Alert(alert_msg)
                    return
                else:
                    log.logger.error(alert_msg)
                    process_utils.Alert(alert_msg)
                time.sleep(10)
        log.logger.info("Quit the SchedulerHelper")

    def check_scheduler_result(self, etl_day=None):
        """
        check_scheduler_result, collect execution results
        :param etl_day: YYYY-MM-DD
        :return:
        """
        if etl_day is None:
            etl_day = (datetime.now() + timedelta(days=-1)).strftime('%Y-%m-%d')
        if etl_day in self.scheduler_finished_day:
            pass

        finished = models.StatResult().update_stat(etl_day)
        if finished:
            self.scheduler_finished_day[etl_day] = True

class Admin(object):
    def __init__(self):
        pass

    def run_all_job(self, date_list):
        """
        run_all_job
        :param date_list:
        :return:
        """
        job_list = models.TaskDefine().get_valid_job()
        msg = ""
        for etl_day in date_list:
            print (len(job_list), etl_day)
            models.TaskInstance().create_job_task_instance(etl_day, job_list)
        msg = "generate {} job task instance ".format(len(date_list) * len(job_list))
        return msg

    def rerun_task(self, task_id, date_list, up_and_down=False, run_up=False, run_down=False, force=False):
        """
        rerun_task
        :param task_id: task_id
        :param date_list: range list
        :param run_up:run upstream
        :param run_down: run downstream
        :return:
        """
        kafka_utils.setup_kafka(config.G_Conf.Common.Broker)
        # run job define
        instance_list = []
        msg = ""
        run_type = ""
        for loop in ["looop"]:
            _ = loop
            job = models.TaskDefine().get_job_by_task_id(task_id_list=[task_id])
            if job and len(job) > 0:
                run_type="job"
                job_list = []
                if run_up:
                    job_list = models.TaskDependency().get_all_upstream(task_id)
                elif run_down:
                    job_list = models.TaskDependency().get_all_downstream(task_id)
                elif up_and_down:
                    up_job = models.TaskDependency().get_all_upstream(task_id)
                    down_job = models.TaskDependency().get_all_downstream(task_id)
                    if len(up_job) > 0:
                        job_list.extend(up_job)
                    if len(down_job) > 0:
                        job_list.extend(down_job)
                else:
                    # run a job with force
                    if force:
                        for etl_day in date_list:
                            tmp = models.TaskInstance().direct_run_single_job_task(etl_day, job)
                            if tmp > 0:
                                instance_list.extend(tmp)
                        break
                    else:
                        # run single waiting dependency
                        pass

                # add self
                job_list.append(task_id)
                need_run_job_list = models.TaskDefine().get_job_by_task_id(task_id_list=job_list)
                if need_run_job_list and len(need_run_job_list) > 0:
                    for etl_day in date_list:
                        models.TaskInstance().create_job_task_instance(execute_date=etl_day, job_list=need_run_job_list)
                    msg = "generate {} TaskDefine task instance ".format(len(need_run_job_list) * len(date_list))
                break

            # run cron task
            cron = models.CronConf().get_cron_by_task_id(task_id=task_id)
            if cron:
                run_type = "cron"
                for etl_day in date_list:
                    tmp = models.TaskInstance().create_cron_task_instance(execute_date=etl_day, cron_list=[cron])
                    if len(tmp) > 0:
                        instance_list.extend(tmp)
                break

        for instance in instance_list:
            err = kafka_utils.PushMsgWithRetry(kafka_utils.TOPIC_DISPATCHER,
                                               kafka_utils.TaskBeginMsg(
                                                   instance_id=instance.id,
                                                   task_id=instance.task_id,
                                                   execute_date=instance.etl_day)
                                               )
            log.logger.info("push task to queue, instance {}, err {}".format(instance, err))
        if len(instance_list) > 0:
            msg = "generate {} {} task instance ".format(len(instance_list), run_type)
        return msg

    def migrate_dependency(self,  job_id=None, delete=False):
        """
        migrate_dependency
        :param delete:  delete data
        :param job_id:  if job_id is None, migrate all job
        :return:
        """
        models.TaskDependency().migrateDep(job_id=job_id, delete=delete)

    def migrate_lastid(self, etl_day):
        models.migrate_last_id(etl_day)

    def query_dep(self, task_id, etl_day):
        met, msg = models.TaskDependency(). \
            is_met_dependency(task_id, etl_day)
        if met:
            print ("task {}, etl_day {} met dependency".format(task_id, etl_day))
        else:
            print ("task {}, etl_day {} not met dependency: {}".format(task_id, etl_day, msg))

    def kill_task(self, task_id, date_list):
        """
        kill_task
        :param task_id:
        :param date_list:
        :return:
        """
        return models.TaskInstance().kill_instance(task_id, date_list)


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

import random

if __name__ == "__main__":
    length = 12
    result = set()
    keywords = ['p', 'P', '0']

    for each in range(1, 100000):
        for length in range(6, 13):
            temp = keywords[random.randint(0, 1)]
            for i in range(1, length + 1):
                temp += random.choice(keywords)
            result.add(temp)

    print("成功生成字典，数量：", len(result))

    with open("/Users/weijiazheng/Desktop/dictionary_rules.txt", mode='w+', encoding='utf-8') as f:
        f.writelines("\n".join(result))
        f.flush()


import random
import numpy

import pygame

from music_player.MusicPlayer import MusicPlayer
from music_player_properties.Model import Model
from music_player_properties.Song import Song
from music_player_properties.SongPlayer import play_song, pause_song, resume_song, stop_song, is_song_playing

SONG_END = pygame.USEREVENT + 1
pygame.mixer.music.set_endevent(SONG_END)

def shuffle(playlist):
    if playlist is None:
        return
    shuffle_playlist(playlist)
    '''for song in playlist.get_shuffled_playlist():
        print(song.get_song_name())'''
    return playlist_to_player(playlist, True)

def playlist_to_player(playlist, is_shuffled):
    if playlist is None:
        return

    '''for song in playlist.get_shuffled_playlist():
        print(song.get_song_name())'''

    music_player = MusicPlayer()

    music_player.set_model_head(None)

    if is_shuffled is True:
        return shuffled_playlist_to_player(music_player, playlist)

    if is_shuffled is False:
        return default_playlist_to_player(music_player, playlist)

def shuffled_playlist_to_player(music_player, playlist):
    for current_song in playlist.get_shuffled_playlist():
        song = current_song
        model = Model(song)
        append_to_player(music_player, model)

    return music_player

def default_playlist_to_player(music_player, playlist):
    real_music_player = music_player
    for current_song in playlist.get_playlist():
        song = current_song
        model = Model(song)
        append_to_player(real_music_player, model)
    return real_music_player

def append_to_player(music_player, model):
    if music_player.get_model_head() is None:
        music_player.set_model_head(model)
        return
    # print(music_player.get_model_head().get_song().get_song_name())

    current_model = music_player.get_model_head()

    prev_model = None

    while current_model.get_next_model() is not None:
        if current_model.get_next_model().get_next_model() is None:
            prev_model = current_model
        current_model = current_model.get_next_model()

    current_model.set_prev_model(prev_model)
    current_model.set_next_model(model)
    # current_model.get_next_model().set_next_model(music_player.get_model_head())
    music_player.get_model_head().set_prev_model(model)
    # print(music_player.get_model_head().get_next_model().get_song().get_song_name())

def make_player_circular(music_player):

    if music_player is None:
        return
    current_model = music_player.get_model_head()

    prev_model = None
    while current_model.get_next_model() is not None:
        if current_model.get_next_model().get_next_model() is None:
            prev_model = current_model
        current_model = current_model.get_next_model()

    current_model.set_next_model(music_player.get_model_head())
    current_model.set_prev_model(prev_model)

def shuffle_playlist(playlist):
    shuffled_playlist = playlist.get_song_list().copy()

    '''for song in shuffled_playlist:
        print(song.get_song_name())'''

    for index in range(0, len(shuffled_playlist) - 1):
        random_index = random.randint(0, len(shuffled_playlist) - 1)
        if random_index == index:
            random_index = random.randint(0, len(shuffled_playlist) - 1)

        temp = shuffled_playlist[index]
        shuffled_playlist[index] = shuffled_playlist[random_index]
        shuffled_playlist[random_index] = temp

    playlist.set_shuffled_playlist(shuffled_playlist)

    '''for song in shuffled_playlist:
        print(song.get_song_name())'''

def start_music_player_demo(music_player):
    pygame.init()
    screen = pygame.display.set_mode((1000, 700))
    screen.fill((255, 255, 255))
    make_player_circular(music_player)
    current_model = music_player.get_model_head()
    # current_model.get_prev_model().get_next_model().set_next_model(music_player.get_model_head())

    running = True
    play_song(current_model.get_song())

    print(current_model.get_song().get_song_name(), "is now playing...")
    is_song_playing()
    is_pause_song = False

    while running:

        for event in pygame.event.get():

            if event.type == pygame.QUIT:
                running = False
            elif event.type == SONG_END:
                current_model = current_model.get_next_model()
                play_song(current_model.get_song())
                print(current_model.get_song().get_song_name(), "is now playing...")

            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    if is_pause_song is False:
                        print("Entered")
                        pause_song(current_model.get_song())
                        is_pause_song = True
                    elif is_pause_song is True:
                        resume_song(current_model.get_song())
                        is_pause_song = False

                elif event.key == pygame.K_LEFT:
                    current_model = current_model.get_prev_model()
                    play_song(current_model.get_song())
                    print(current_model.get_song().get_song_name(), "is now playing...")
                elif event.key == pygame.K_RIGHT:
                    current_model = current_model.get_next_model()
                    play_song(current_model.get_song())
                    print(current_model.get_song().get_song_name(), "is now playing...")

def print_player(music_player):
    model_head = music_player.get_model_head()

    if model_head is not None:
        current_model = model_head
        while current_model is not None:
            print(current_model.get_song().get_song_name())
            current_model = current_model.get_next_model()


largest = None
smallest = None
while True:
    num = input("Enter a number: ")
    if num == "done" : break
    try:
        f=float(num)

    except:
        print("Invalid Input")

    if smallest is None :
        smallest = f
    elif smallest> f :
        smallest = f

    if largest is None :
        largest = f
    elif largest< f :
        largest = f

print("Maximum is ", int(largest))
print("Minimum is ", int(smallest))


t = int(input())

for _ in range(t):
    a, b = map(int, input().split())
    a = a%10

    # a가 0이면 10의 거듭제곱
    if a == 0:
        print(10)
    elif a==1 or a==5 or a==6: # 1,5,6은 매번 자기 자신이 나옴
        print(a)
    elif a==4 or a==9: # 거듭제곱을 10으로 나눈 나머지가 두 가지 경우
        b = b%2
        if b==0:
            print(a*a%10)
        else:
            print(a)
    else: # 4가지 경우의 거듭 제곱은 b가 4의 배수일 경우만 최적화
        b=b%4
        if b==0:
            print(a**4%10)
        else:
            print(a**b%10)

# 시간 초과
# for _ in range(t):
#     a, b = map(int, input().split())
#     print((a**b)%10)


import trimesh
import numpy as np

class Mesh(object):
    def __init__(self, model_path, transform=None):
        self.model_path = model_path
        self.file_name = self.model_path.split('/')[-1]
        self.transform = transform

    def load(self, with_transform=False):
        mesh = trimesh.load(self.model_path)
        if with_transform and self.transform is not None:
            self.transform = np.asarray(self.transform, dtype=np.float).reshape(4, 4).transpose()
            mesh.apply_transform(self.transform)
        return mesh


def nearest_smaller_left(arr):
    res = []  # to store the index of nearest smaller element
    stack = []  # for comaparison

    for i in range(len(arr)):
        if len(stack) == 0:
            res.append(-1)

        elif len(stack) > 0 and arr[stack[-1]] <= arr[i]:
            res.append(stack[-1])

        elif len(stack) > 0 and arr[stack[-1]] > arr[i]:
            while len(stack) > 0 and arr[stack[-1]] >= arr[i]:
                stack.pop()

            if len(stack) == 0:
                res.append(-1)
            else:
                res.append(stack[-1])

        stack.append(i)

    return res

def nearest_smaller_right(arr):
    res = []
    stack = []

    pseudoIndex = len(arr)

    for i in range(len(arr) - 1, -1, -1):
        if len(stack) == 0:
            # res.append(-1)
            res.append(pseudoIndex)

        elif len(stack) > 0 and arr[stack[-1]] <= arr[i]:
            res.append(stack[-1])

        elif len(stack) > 0 and arr[stack[-1]] > arr[i]:
            while len(stack) > 0 and arr[stack[-1]] >= arr[i]:
                stack.pop()

            if len(stack) == 0:
                res.append(pseudoIndex)
            else:
                res.append(stack[-1])

        stack.append(i)

    return res[::-1]

def find_max_area(arr):
    left_index = nearest_smaller_left(arr)
    right_index = nearest_smaller_right(arr)

    result = [x - y - 1 for x, y in zip(right_index, left_index)]

    max_area = float("-inf")
    for i in range(len(arr)):
        width = right_index[i] - left_index[i] - 1
        area = arr[i] * width
        max_area = max(max_area, area)

    print(max_area)

find_max_area([9, 10, 4, 10, 4, 5, 16])


#NOTE: variable names don't match agreed-upon lab coordinate names. bz==vertical, bx==along B0, by==orthogonal. In lab coords, z and y are swapped so that y is vertical. The plot titles and file names reflect this.

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import pandas as pd
#plt.rcParams["figure.figsize"] = 6,4

fileOff = "/Users/alexandraklipfel/Desktop/senior_thesis/data_3-29/deltaB/averaged_off.txt"
datOff = np.loadtxt(fileOff)
print("Data Off Shape: ", datOff.shape)
lengthOff = datOff.shape[0]
print("Number of Off Data Points: ", lengthOff)

fileOn = "/Users/alexandraklipfel/Desktop/senior_thesis/data_3-29/deltaB/averaged_on.txt"
datOn = np.loadtxt(fileOn)
print("Data On Shape: ", datOn.shape)
lengthOn = datOn.shape[0]
print("Number of On Data Points: ", lengthOn)

print(datOn[:, 5])
#print(datOff[:, 5])

#first have to transfrom the field values into the lab frame (this was done in the averaging file but only for the plots not saved to the output text files)

#subtract the off field values from the on field values
#TO DO: propagate errors

#final data:
# y axis values
dat = datOn.copy()
y = []
bx = []
by = []
bz = []

yleft = []
bxleft = []
byleft = []
bzleft = []
for i in range(lengthOn):
    #print(datOn[:, 5])
    #print(i)
    if (dat[i, 2] == -5000) and (dat[i, 1] == 3900) :
        y += [dat[i,0]]
        dat[i, 3] = datOn[i, 3] - datOff[i, 3]
        bx += [dat[i, 3]]
        dat[i, 5] = datOn[i, 7] - datOff[i, 7]
        by += [dat[i, 5]]
        dat[i, 7] = -datOn[i, 5] + datOff[i, 5]
        bz += [dat[i, 7]]
        #print(datOn[i, 5])
    if (dat[i, 2] == -5000) and (dat[i, 1] == -4300) :
        yleft += [-dat[i,0]]
        dat[i, 3] = -datOn[i, 3] + datOff[i, 3]
        bxleft += [dat[i, 3]]
        dat[i, 5] = -datOn[i, 7] + datOff[i, 7]
        byleft += [dat[i, 5]]
        dat[i, 7] = -datOn[i, 5] + datOff[i, 5]
        bzleft += [dat[i, 7]]
        #print(datOn[i, 5])

# make y plots---these are actually labeled "z" because i'm switching to the lab coordinates that Umit's using
#along B0
plt.scatter(y, bx, color="red")
plt.scatter(yleft, bxleft, color="blue")

plt.xlabel("z")
plt.ylabel("Bx")
plt.title("delta Bx (along B0) vs z")
plt.savefig("Bx_z-deltaB.png", dpi=1000)
plt.show()

#orthogonal
plt.scatter(y, by, color="red")
plt.scatter(yleft, byleft, color="blue")

plt.xlabel("z")
plt.ylabel("Bz")
plt.title("delta Bz vs z")
plt.savefig("Bz_z-deltaB.png", dpi=1000)
plt.show()

#vertical
plt.scatter(y, bz, color="red")
plt.scatter(yleft, bzleft, color="blue")

plt.xlabel("z")
plt.ylabel("By")
plt.title("delta By (vertical) vs z")
plt.savefig("By_z-deltaB.png", dpi=1000)
plt.show()

# y axis values
dat = datOn.copy()
x = []
bxX = []
byX = []
bzX = []

xleft = []
bxXleft = []
byXleft = []
bzXleft = []
for i in range(lengthOn):
    #print(datOn[:, 5])
    #print(i)
    if (dat[i, 2] == -5000) and (dat[i, 1] == -200) :
        x += [dat[i,0]]
        dat[i, 3] = datOn[i, 7] - datOff[i, 7]
        bxX += [dat[i, 3]]
        dat[i, 5] = -datOn[i, 3] - -datOff[i, 3]
        byX += [dat[i, 5]]
        dat[i, 7] = -datOn[i, 5] + datOff[i, 5]
        bzX += [dat[i, 7]]
        #print(datOn[i, 5])
    if (dat[i, 2] == -5000) and (dat[i, 1] == 7900) :
        xleft += [-dat[i,0]]
        dat[i, 3] = -datOn[i, 7] + datOff[i, 7]
        bxXleft += [dat[i, 3]]
        dat[i, 5] = datOn[i, 3] - datOff[i, 3]
        byXleft += [dat[i, 5]]
        dat[i, 7] = -datOn[i, 5] + datOff[i, 5]
        bzXleft += [dat[i, 7]]
        #print(datOn[i, 5])

#along B0
plt.scatter(x, bxX, color="red")
plt.scatter(xleft, bxXleft, color="blue")

plt.xlabel("x")
plt.ylabel("Bx")
plt.title("delta Bx (along B0) vs x")
plt.savefig("Bx_x-deltaB.png", dpi=1000)
plt.show()

#orthogonal
plt.scatter(x, byX, color="red")
plt.scatter(xleft, byXleft, color="blue")

plt.xlabel("x")
plt.ylabel("Bz")
plt.title("delta Bz vs x")
plt.savefig("Bz_x-deltaB.png", dpi=1000)
plt.show()

#vertical
plt.scatter(x, bzX, color="red")
plt.scatter(xleft, bzXleft, color="blue")

plt.xlabel("x")
plt.ylabel("By")
plt.title("delta By (vertical) vs x")
plt.savefig("By_x-deltaB.png", dpi=1000)
plt.show()

# now the new file should be ready to be plotted--note that the errors are currently meaningless and need to be fixed
np.savetxt("averaged_deltaB.txt", data, delimiter=" ")


def main():
    from m5stack import lcd, buttonA
    from mpu9250 import MPU9250
    from time import sleep_ms
    from machine import I2C
    import network

	# lcd.font(lcd.FONT_Small, transparent=True, fixedwidth=False)

    try:
        sta_if = network.WLAN(network.STA_IF)
        if sta_if.active() == True:
            m_acc = network.mqtt('acc', 'mqtt://srdmobilex.ddns.net', port=65530, clientid='a')
            m_gyro = network.mqtt('gyro', 'mqtt://srdmobilex.ddns.net', port=65530, clientid='g')
            m_acc.start()
            m_gyro.start()
            m_acc.subscribe('acc', 2)
            m_gyro.subscribe('gyro', 0)

        i2c = I2C(sda = 21, scl = 22)

        imu = MPU9250(i2c)

        lcd.clear()
        lcd.setColor(lcd.WHITE)
        lcd.font(lcd.FONT_Small, transparent=False)

        counter = 0

        while not buttonA.isPressed():
            accel = imu.acceleration
            gyro = imu.gyro
            mag = imu.magnetic
            lcd.print("ACCEL: {:+7.2f}  {:+7.2f}  {:+7.2f}".format(accel[0], accel[1], accel[2]), lcd.CENTER, 20)
            lcd.print("GYRO:  {:+7.2f}  {:+7.2f}  {:+7.2f}".format(gyro[0], gyro[1], gyro[2]), lcd.CENTER, 40)
            lcd.print("MAG:   {:+7.2f}  {:+7.2f}  {:+7.2f}".format(mag[0], mag[1], mag[2]), lcd.CENTER, 60)
            if sta_if.active() == True:
                m_acc.publish('acc', '{:+7.2f},{:+7.2f},{:+7.2f}'.format(accel[0], accel[1], accel[2]) + '(%d)'%counter)
                m_gyro.publish('gyro', '{:+7.2f}  {:+7.2f}  {:+7.2f}'.format(gyro[0], gyro[1], gyro[2]) + '(%d)'%counter)
                counter += 1
            sleep_ms(20)

        m_acc.free()
        m_gyro.free()
        i2c.deinit()
        lcd.print('Exit.', 0, 100)
    except:
        return -1


# -*- coding: utf-8 -*-
"""
Created on Sun Mar  8 10:29:09 2020

@author: Alex

code for windows
"""
class Solution:
    def numTimesAllBlue(self, light):
        n = len(light)
        opened = [0]*n
        count = 0
        head = 0
        tail = 0
        for i in range(n):
            if light[i] > tail:
                tail = light[i]
                lengh = tail-head

            opened[light[i]-1] = 1
            while head < tail and opened[head] == 1:
                head += 1
                lengh -= 1
            if lengh == 0:
                count += 1
            #print(opened, opened[head:tail], light[i]-1,lengh)
        return count

if __name__ == "__main__":
    s = Solution()
    a1 = [2,1,3,5,4]
    #a2 =
    print(s.numTimesAllBlue(a1))


import inspect

def decorator_near(func):
    # Декоратор-монстр. Позволяет функциям взаимодействовать с соседними координатами
    def wrapper(collection, row, column, h, w):

        # Если выполняется функция по созданию маски, то есть возможность взаимодействовать с текущими координатами
        if inspect.signature(func) == inspect.signature(make_mask):
            func(collection, row, column)

        if column > 0:  # влево
            if func(collection, row, column-1):
                wrapper.counter += 1

        if row > 0 and column > 0:  # влево-вверх
            if func(collection, row-1, column-1):
                wrapper.counter += 1

        if row > 0:  # вверх
            if func(collection, row-1, column):
                wrapper.counter += 1

        if row > 0 and column < w-1:  # вправо-вверх
            if func(collection, row-1, column+1):
                wrapper.counter += 1

        if column < w-1:  # вправо
            if func(collection, row, column+1):
                wrapper.counter += 1

        if row < h-1 and column < w-1:  # вправо-вниз
             if func(collection, row+1, column+1):
                wrapper.counter += 1

        if row < h-1:  # вниз
            if func(collection, row+1, column):
                wrapper.counter += 1

        if row < h-1 and column > 0:  # влево-вниз
            if func(collection, row+1, column-1):
                wrapper.counter += 1

        if wrapper.counter:
            # если изменился счетчик, то мы его возвращаем. Нужно для проверки живых клеток вокруг.
            for_return = wrapper.counter
            wrapper.counter = 0
            return for_return
    wrapper.counter = 0
    return wrapper

@decorator_near
def check_near_lst(lst_here, row, column):
    if lst_here[row][column]:
        return True

@decorator_near
def check_near_set(set_here, row, column):
    if (row, column) in set_here:
        return True

@decorator_near
def make_mask(set_here, row, column):
    set_here.add((row, column))

height = 10
width = 10
# current_generation_lst = [[0, 0, 1, 0, 0, 0],
#                           [1, 0, 1, 0, 0, 0],
#                           [0, 1, 1, 0, 0, 0],
#                           [0, 0, 0, 0, 0, 0],
#                           [0, 0, 0, 0, 0, 0],
#                           [0, 0, 0, 0, 0, 0]]
#next_generation = [[0, 0, 0, 0, 0, 0],
#                   [0, 0, 0, 0, 0, 0],
#                   [0, 0, 0, 0, 0, 0],
#                   [0, 0, 0, 0, 0, 0],
#                   [0, 0, 0, 0, 0, 0],
#                   [0, 0, 0, 0, 0, 0]]
#CLEAR = [[0, 0, 0, 0, 0, 0],
#         [0, 0, 0, 0, 0, 0],
#         [0, 0, 0, 0, 0, 0],
#         [0, 0, 0, 0, 0, 0],
#         [0, 0, 0, 0, 0, 0],
#         [0, 0, 0, 0, 0, 0]]

current_mask = set()
next_mask = set()

current_generation_set = set()
next_generation_set = set()

# x, y = 0, 0
#
# while x < height:
#     while y < width:
#         alives = check_near_lst(current_generation_lst, x, y, height, width)
#         if current_generation_lst[x][y] and alives < 2:
#             pass
#         elif current_generation_lst[x][y] and alives > 3:
#             pass
#         elif current_generation_lst[x][y] and 2 <= alives <= 3:
#             current_generation_set.add((x, y))
#             make_mask(current_mask, x, y, height, width)
#         elif not current_generation_lst[x][y] and alives == 3:
#             current_generation_set.add((x, y))
#             make_mask(current_mask, x, y, height, width)
#         y += 1
#     x += 1
#     y = 0
# else:
#     x = 0
#
#
# visualization = list()
#
# for _ in range(15):
#     for coordinates_in_mask in current_mask:
#         x, y = coordinates_in_mask[0], coordinates_in_mask[1]
#         alives = check_near_set(current_generation_set, x, y, height, width)
#         if (x, y) in current_generation_set and alives < 2:
#             pass
#         elif (x, y) in current_generation_set and alives > 3:
#             pass
#         elif (x, y) in current_generation_set and 2 <= alives <= 3:
#             next_generation_set.add((x, y))
#             make_mask(next_mask, x, y, height, width)
#         elif (x, y) not in current_generation_set and alives == 3:
#             next_generation_set.add((x, y))
#             make_mask(next_mask, x, y, height, width)
#     visualization = [[0 for _ in range(width)] for s in range(height)]
#     for cell in next_generation_set:
#         x, y = cell[0], cell[1]
#         visualization[x][y] = 1
#     for line in visualization:
#         print(line)
#     print()
#     current_generation_set = next_generation_set
#     next_generation_set = set()
#     current_mask = next_mask
#     next_mask = set()

def step(current_generation_set, current_mask, next_generation_set, next_mask):
    for coordinates_in_mask in current_mask:
        x, y = coordinates_in_mask[0], coordinates_in_mask[1]
        alives = check_near_set(current_generation_set, x, y, height, width)
        if (x, y) in current_generation_set and alives < 2:
            pass
        elif (x, y) in current_generation_set and alives > 3:
            pass
        elif (x, y) in current_generation_set and 2 <= alives <= 3:
            next_generation_set.add((x, y))
            make_mask(next_mask, x, y, height, width)
        elif (x, y) not in current_generation_set and alives == 3:
            next_generation_set.add((x, y))
            make_mask(next_mask, x, y, height, width)
    print()
    current_generation_set = next_generation_set
    next_generation_set = set()
    current_mask = next_mask
    next_mask = set()


# -*- coding: utf-8 -*-
"""
Created on Wed Dec 15 13:17:53 2021

@author: Oscar
"""

def merge(L1, L2):
    i1 = 0
    i2 = 0
    L = []
    done1 = False
    done2 = False
    while not (done1 and done2):
        if not done1 and (done2 or L1[i1]<L2[i2]):
            L.append(L1[i1])
            i1 += 1
            done1 = i1>=len(L1)
        else:
            L.append(L2[i2])
            i2 += 1
            done2 = i2>=len(L2)

        return L

def merge(L1, L2):
    i1 = 0
    i2 = 0
    L = []
    while i1<= len(L1) and i2<= len(L2):
        if L1[i1] < L2[i2]:
            L.append(L1[i1])
            i1+=1
        elif L1[i1]> L2[i2]:
            L.append(L2[i2])
            i2 +=1
        else:
            L.append(L2[i2])
            i1+=1
            i2+=1
    L.extend(L1[i1:])
    L.extend(L2[i2:])
    return L


from django.shortcuts import render

from django.http.response import JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework import status

from .forms import CsvModelForm
from .models import Csv, BedTemplate
from .serializers import BedSerializer
from rest_framework.decorators import api_view
from dateutil.parser import parse
from datahub.exceptions import APIIntegrityException

import csv

def upload_file_view(request):
    form = CsvModelForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        form.save()
        form = CsvModelForm()
        obj = Csv.objects.get(published=False)
        with open(obj.file_name.path, 'r') as f:
            reader = csv.reader(f)
            for i, row in enumerate(reader):
                if i == 0:
                    pass
                else:
                    BedTemplate.objects.create(
                        interaction_title=row[0],
                        interaction_date=parse(row[1]),
                        lead_minister_or_official=row[2],
                        type=row[3],
                        country=row[4],
                        region=row[5],
                        city_or_town=row[6],
                        attending_organisations=row[7],
                        attending_contacts=row[8],
                    )
                obj.published = True
                obj.save()
    # else:
    #     raise APIIntegrityException()
    return render(request, 'upload.html', {'form': form})

@api_view(['GET', 'POST'])
def interaction_list(request):
    # GET list of interactions, POST a new interaction
    if request.method == 'GET':
        interactions = BedTemplate.objects.all()

        title = request.GET.get('interaction_title', None)
        if title is not None:
            interactions = interactions.filter(interaction_title__icontains=title)

        interactions_serializer = BedSerializer(interactions, many=True)
        return JsonResponse(interactions_serializer.data, safe=False)
        # 'safe=False' for objects serialization

    elif request.method == 'POST':
        interaction_data = JSONParser().parse(request)
        interaction_serializer = BedSerializer(data=interaction_data)
        if interaction_serializer.is_valid(raise_exception=True):
            interaction_serializer.save()
            return JsonResponse(interaction_serializer.data, status=status.HTTP_201_CREATED)
        return JsonResponse(interaction_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET', 'PUT', 'DELETE'])
def interaction_detail(request, pk):
    # find interaction by id
    try:
        interaction = BedTemplate.objects.get(pk=pk)
    except BedTemplate.DoesNotExist:
        return JsonResponse({'message': 'This interaction does not exist'}, status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        interaction_serializer = BedSerializer(interaction)
        return JsonResponse(interaction_serializer.data)

    elif request.method == 'PUT':
        interaction_data = JSONParser().parse(request)
        interaction_serializer = BedSerializer(interaction, data=interaction_data)
        if interaction_serializer.is_valid(raise_exception=True):
            interaction_serializer.save()
            return JsonResponse(interaction_serializer.data)
        return JsonResponse(interaction_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        interaction.delete()
        return JsonResponse({'message': 'Interaction was deleted successfully.'}, status=status.HTTP_204_NO_CONTENT)

@api_view(['GET'])
def interaction_list_published(request):
    # GET all published interactions
    interactions = BedTemplate.objects.filter(published=True)

    if request.method == 'GET':
        interactions_serializer = BedSerializer(interactions, many=True)
        return JsonResponse(interactions_serializer, safe=False)


# -*- coding: utf-8 -*-
"""Collect Vray Proxy."""
import pyblish.api

class CollectVrayProxy(pyblish.api.InstancePlugin):
    """Collect Vray Proxy instance.

    Add `pointcache` family for it.
    """
    order = pyblish.api.CollectorOrder + 0.01
    label = "Collect Vray Proxy"
    families = ["vrayproxy"]

    def process(self, instance):
        """Collector entry point."""
        if not instance.data.get('families'):
            instance.data["families"] = []

        if instance.data.get("vrmesh"):
            instance.data["families"].append("vrayproxy.vrmesh")

        if instance.data.get("alembic"):
            instance.data["families"].append("vrayproxy.alembic")


import time

from rpi_lcd import LCD

from observer_design_pattern.observer import Observer
import logging

LOGGER = logging.getLogger(__name__)

class MessageObserver(Observer):
    def __init__(self, subject, default_message):
        super().__init__(subject)
        self.lcd = LCD()
        self.subject.add_observer(self)
        self.default_message = default_message
        self.display_default_message()

    def update(self):
        self.display_text(self.subject.get_state())
        time.sleep(5)
        self.display_default_message()

    def display_default_message(self):
        self.lcd.clear()
        self.display_text(self.default_message)

    def display_text(self, text):
        self.lcd.clear()
        first_row_text = text[0:16]
        second_row_text = text[16:32]
        self.lcd.text(first_row_text, 1)
        self.lcd.text(second_row_text, 2)
        if text[32:] is not '':
            LOGGER.error(f"Could not fit '%s' onto display.", text[32:])


import pandas as pd
import numpy as np

def calculate_rs():

    # Excelファイルからデータを読み込む
    df = pd.read_excel('stock_prices.xlsx', index_col=0)

    # RS値を計算するための空のリストを作成
    rs_values = []

    # 各行（企業）についてループ
    for index, row in df.iterrows():
        # 各要素を変数に代入
        current_price = row['現在']
        price_63_days_ago = row['63日前']
        price_126_days_ago = row['126日前']
        price_189_days_ago = row['189日前']
        price_252_days_ago = row['252日前']

        # NaNが含まれる場合はRS値を1とする
        if pd.isnull(current_price) or pd.isnull(price_63_days_ago) or pd.isnull(price_126_days_ago) or pd.isnull(price_189_days_ago) or pd.isnull(price_252_days_ago):
            rs = 1
        else:
            # RS値を計算
            rs = ((((current_price - price_63_days_ago) / price_63_days_ago) * .4) +
                (((current_price - price_126_days_ago) / price_126_days_ago) * .2) +
                (((current_price - price_189_days_ago) / price_189_days_ago) * .2) +
                (((current_price - price_252_days_ago) / price_252_days_ago) * .2)) * 100

        # RS値をリストに追加
        rs_values.append(rs)

    # RS値をデータフレームに追加
    df['RS'] = rs_values

    # RS値を降順に並び替え
    df = df.sort_values('RS', ascending=False)

    # 素点を計算
    df['素点'] = np.floor(100 - np.arange(len(df)) / len(df) * 100)

    # データフレームをExcelファイルに保存
    df.to_excel('RS_calc.xlsx')

    print("RS_calc.xlsxとして保存しました")


__author__ = 'anders'

# Problem 1
#
# Write three functions that compute the sum of the numbers
# in a given list using a for-loop, a while-loop, and recursion.

def sum_for(list):
    sum = 0
    for i in range(0, len(list)):
        sum += list[i]
    return sum

def sum_while(list):
    sum = 0
    i = 0
    while i < len(list):
        sum += list[i]
        i += 1
    return sum

def sum_rec(list):
    i = 0

if __name__ == '__main__':
    list = [1, 2, 3, 4, 5] #Sum should be 15

    print(str(sum_for(list)))
    print(str(sum_while(list)))


from math import sqrt
from time import sleep

import keyboard
import PySimpleGUI as sg
from lakeshore import SSMSystem  # M81のこと

import csv
import datetime
import os

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

is_connected = False

Header = ["距離[mm]", "R[V]", "theta[θ]"]
Data = []

distance = 50
step = 2

def ConnectM81():
    M81 = SSMSystem() #引数なし:USB,Serial接続
    return 0

def SetupM81(fq,cr):
    S1 = M81.get_source_module(1) #ソースモジュール
    M1 = M81.get_measure_module(1) #計測モジュール
    S1.set_shape('SINUSOID') #sin波のこと
    S1.set_frequency(fq) #周波数[Hz]
    S1.set_current_amplitude(cr) #電流[A]
    S1.set_current_offset(0)
    S1.configure_i_range(0, max_ac_level=0.1) #Range設定(autoを使うか、max_level,max_ac_level,max_dc_level)どれか一つ指定
    S1.set_cmr_source('INTernal') #CMRのソースを設定
    S1.enable_cmr() #CMRを有効化
    #advanced setting
    S1.use_ac_coupling() #カップリングをACに設定
    M1.setup_lock_in_measurement('S1', 0.1) #S1の周波数を参照信号にし、timeconstantを100msに設定
    return 0

Titlesize = (20,1)
Textsize = (10,1)
TitleFont = ("meiryo", 30)
Font = ("meiryo", 15)

layout = [
    [sg.Text("M81計測App", size=Titlesize, font=TitleFont, justification='center'), ],
    [sg.Text("M81に接続", size=Textsize, font=Font), sg.Button("接続", font=Font, key="Connect")],
    [sg.Text("周波数[Hz]:", size=Textsize, font=Font), sg.InputText(font=Font, size=Textsize, default_text="1000", key="-FQ-")],
    [sg.Text("電流[A]:", size=Textsize, font=Font),  sg.InputText(font=Font, size=Textsize, default_text="0.01", key="-CR-")],
    [sg.Text("初期位置[mm]:", size=Textsize, font=Font),  sg.InputText(font=Font, size=Textsize, default_text="50", key="-DT-")],
    [sg.Text("ステップ[mm]:", size=Textsize, font=Font),  sg.InputText(font=Font, size=Textsize, default_text="2", key="-ST-")],
    [sg.Button("Set", disabled=not is_connected, font=Font, key="Setup")],
    [sg.Button("ON", disabled=not is_connected, font=Font, key="ON"), sg.Button("OFF(CSVに保存)", disabled=not is_connected, font=Font, key="OFF")],
    [sg.Text("Aで計測,Nで一つ消す", font=Font)],

    [sg.Table(Data, headings=Header, auto_size_columns=True, key='-TABLE-')],
]

#layout = [sg.Column(layout_settings), sg.Column(layout_canvas)]

window = sg.Window("M81ロックイン計測", layout, return_keyboard_events=True)

while True:
    event, value = window.read()

    if event == "Connect": #接続ボタン押したとき
        print(f"event:{event}")
        try:
            ConnectM81()
            is_connected = True #接続状態を更新
            sg.Popup("接続されました", auto_close=True, auto_close_duration=1)
        except Exception as e: #接続できなかったとき
            sg.PopupError(f'エラー:{e}')

    if event == "Setup":
        print(f"event:{event}")
        try:
            frequency = int(value["-FQ-"])
            current   = float(value["-CR-"])
            distance  = int(value["-DT-"])
            step = int(value["-ST-"])
            SetupM81(frequency, current)

        except ValueError:
            sg.PopupError("数値を入力してください")
        except Exception:
            sg.PopupError(f'機器を接続してください')

    if event == "ON":
        print(f"event:{event}")
        S1.enable() #S1を起動
        sleep(1.5)
        sg.Popup("起動中(wait:1.5[s])", auto_close=True, auto_close_duration=2)
        Data = ["distance[mm]", "R[V]", "theta[θ]"]

    if event == "OFF":
        print(f"event:{event}")
        print("ソースモジュールを停止")
        S1.disable() #S1を停止
        print(Data)

        #csv setting
        now = datetime.datetime.today()
        hourstr = "_" + now.strftime("%H%M%S")
        filename = "record_" + now.strftime("%Y%m%d") + hourstr + ".csv"
        os.makedirs('M81_CSVrecords',exist_ok=True)
        #create CSV
        print("create csv.")
        with open(os.path.join('M81_CSVrecords',filename), 'a', newline= '') as f:
            writer = csv.writer(f)
            writer.writerow(["距離[mm]","R[V]","theta[Θ]"])
            writer.writerows(Data)
            print("")
        Data.clear()
        print(Data)
        # Table ウィジェットを更新
        window['-TABLE-'].update(values=Data)

    if event == "a": #データを保存
        print(f"event:{event}")
        try:
            lock_in_magnitude = M1.get_lock_in_r() #LockinモードのRを取得
            lock_in_theta = M1.get_lock_in_theta()
            d = [distance, lock_in_magnitude, lock_in_theta]
            Data.append(d)
            print(f"append:{d},")
            distance = distance + step
            # Table ウィジェットを更新
            window['-TABLE-'].update(values=Data)

        except Exception:
            sg.PopupError(f'機器を接続し状態:ONにしてください')

    if event == "b": #データを保存test
        print(f"event:{event}")
        try:
            d = [distance,2,3]
            Data.append(d)
            distance = distance + step
            # Table ウィジェットを更新
            window['-TABLE-'].update(values=Data)
        except Exception:
            sg.PopupError(f'機器を接続し状態:ONにしてください')

    if event == "n": #データを一つ消去
        print(f"event:{event}")
        try:
            Data.pop()
            distance = distance - step
            # Table ウィジェットを更新
            window['-TABLE-'].update(values=Data)
        except Exception:
            sg.PopupError(f'データがありません')

    if event == None:
        break

window.close()


from populator import populator

shade = 0

def argumentparser():
    global shade
    try:
        import argparse
        import sys
    except:
        print("\nxx Error importing arparse or sys module\n")
        exit(1)

    parser = argparse.ArgumentParser(
        description='To process tables in images.', prog='populator')
    parser.add_argument(
        '-p', '--path', help='Path for the tabular source image')
    parser.add_argument('-db', '--database',
                        help='Name of database')
    parser.add_argument(
        '-t', '--table', help='Name of the table')
    parser.add_argument('-s', '--shade', help="Shade of heading", default=0)

    if len(sys.argv) > 1:
        args = parser.parse_args()
        path = args.path
        try:
            f = open(path)
            f.close()
        except FileNotFoundError:
            print("File not accessible")
            print("\n### EXITING ###")
            exit(1)
        database_name = args.database if len(
            args.database) != 0 else input("Enter the name of database: ")
        table_name = args.table if len(args.table) != 0 else input(
            "Enter the name of table: ")
        shade = args.shade
    else:
        path = input("Enter image path: ")
        try:
            f = open(path)
            f.close()
        except FileNotFoundError:
            print("\nxx File not accessible\n")
            exit(1)
        database_name = input("Enter the name of database: ")
        table_name = input("Enter the name of table: ")
    return (path, database_name, table_name)

def main():
    print("\n==================== SEQUEL INJECTOR ====================\n")
    path, database_name, table_name = argumentparser()
    populator(path, database_name, table_name, shade)
    print("\n=========================================================\n")

if __name__ == "__main__":
    main()


# -*- coding: utf-8 -*-
from functools import wraps

class Staticator(object):
    def __init__(self, *args, **kw):
        self.types = args
        self.kw_types = kw

    def __call__(self, function):
        self.func_name = function.func_name
        @wraps(function)
        def new_function(*args, **kw):
            self.check_args(args, kw)
            return function(*args, **kw)
        return new_function

    def raise_type_error(self, arg, type_):
        raise TypeError(
            "Incorrect argument %s - should be of type %s in call to %s()" %
            (str(arg), str(type_), self.func_name))

    def check_args(self, args, kw):
        for type_, arg in zip(self.types, args):
            if not isinstance(arg, type_):
                self.raise_type_error(arg, type_)
        for key in kw:
            try:
                if not isinstance(kw[key], self.kw_types[key]):
                    self.raise_type_error(kw[key], type_)
            except KeyError:
                 raise TypeError("%s() got an unexpected "
                                 "keyword argument '%s'" %
                                 (self.func_name, key))

if __name__ == "__main__":
    @Staticator(int, int)
    def sum(a, b):
        return a + b

    sum(2,3)
    sum(2.0, 3)


# Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

# You should preserve the original relative order of the nodes in each of the two partitions.

# Example:

# Input: head = 1->4->3->2->5->2, x = 3
# Output: 1->2->2->4->3->5

# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def partition(self, head, x):
        """
        :type head: ListNode
        :type x: int
        :rtype: ListNode
        """
        if not head:
            return head

        new_head = None
        small = new_head
        big_head = None
        big = big_head
        while head:
            if head.val >= x:
                if big:
                    big.next = head
                    big = head
                else:
                    big_head = head
                    big = big_head
            else:
                if small:
                    small.next = head
                    small = head
                else:
                    new_head = head
                    small = new_head
            head = head.next
        if big:
            big.next = None
        if small:
            small.next = big_head
        if new_head:
            return new_head
        return big_head


from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import smtplib
from email.mime.text import MIMEText
import time
import tkinter as tk
from threading import Timer

def send_email():
    msg_from = ''  # 发送方邮箱
    passwd = ''  # 填入发送方邮箱的授权码
    msg_to = 'hizyx97@gmail.com,junkrat@qq.com,yzhou168@syr.edu'  # 收件人邮箱

    subject = "[淘宝订单已生成，请尽快付款]"  # 主题
    content = "**********淘宝订单已生成，请尽快付款!**********"
    msg = MIMEText(content)
    msg['Subject'] = subject
    msg['From'] = msg_from
    msg['To'] = msg_to
    try:
        s = smtplib.SMTP_SSL("smtp.qq.com", 465)  # 邮件服务器及端口号
        s.login(msg_from, passwd)
        s.sendmail(msg_from, msg_to, msg.as_string())
        txt = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + "提醒邮件已发送至："+ msg_to
        print(txt)
        # txt_panel.insert('insert', txt + '\n')
        # txt_panel.see('end')
        # txt_panel.update()
        # print("提醒邮件已发送至：", msg_to)
    finally:
        s.quit()

chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
chrome_driver = "C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe"
driver = webdriver.Chrome(chrome_driver, chrome_options=chrome_options)
#url="https://detail.tmall.com/item.htm?spm=a1z10.3-b-s.w4011-15160618060.68.1ec02172QWpe7D&id=615886665551&rn=55e53f42a861a2e224dd5231be7f05ed&abbucket=12&skuId=4339622732765#"
#url="https://detail.tmall.com/item.htm?spm=a1z10.3-b-s.w4011-15160618060.36.a54a2172DH0Y2d&id=615886665551&rn=1fc70735dc7da32f59a93e11fec4a517&abbucket=9"
# url="https://detail.tmall.com/item.htm?spm=a1z10.3-b-s.w4011-15160618060.36.a54a2172DH0Y2d&id=615886665551&rn=1fc70735dc7da32f59a93e11fec4a517&abbucket=9&skuId=4339622732763#"

session_expire = 600
refresh_inteval = 30
wait_load = 2
act_sess =int(session_expire/refresh_inteval)
i=0

# window = tk.Tk()
#
# window.title('天猫淘宝检查库存自动下单')
#
# # 第3步，设定窗口的大小(长 * 宽)
# window.geometry('600x400')  # 这里的乘是小x
#
#
# tk.Label(window, text='有库存则下单，没库存则持续刷新', bg='red', font=('Arial', 16)).pack()
# frame = tk.Frame(window)
# frame.pack()
#
# frame_1 = tk.Frame(frame)
# frame_2 = tk.Frame(frame)
# frame_3 = tk.Frame(frame)
# frame_4 = tk.Frame(frame)
# frame_5 = tk.Frame(frame)
# frame_6 = tk.Frame(frame)
# frame_1.pack()
# frame_2.pack()
# frame_3.pack()
# frame_4.pack()
# frame_5.pack()
# frame_6.pack()
#
# tk.Label(frame_1, text='商品立即购买的链接').pack()
# ety_link = tk.Entry(frame_1, width=80)
# ety_link.pack()
#
# tk.Label(frame_2, text='间隔时间(秒), 因为有刷新和页面加载时间，建议不要低于5秒').pack()
# ety_interv = tk.Entry(frame_2, width=10)
# ety_interv.insert('insert', '5')
# ety_interv.pack()
#
# tk.Label(frame_3, text='下单成功则向如下邮箱发送确认邮件，用英文","分隔').pack()
# ety_email= tk.Entry(frame_3, width=80)
# ety_email.pack()

def main():
    timer_interval = 1
    t = Timer(timer_interval, timedTask)
    txt = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + "任务启动"
    print(txt)
    t.start()

def timedTask():
    # global timer_interval
    # timer_interval = int(ety_interv.get())
    shopping()
    global t
    t = Timer(timer_interval, timedTask)
    t.start()

url = "https://h5.m.taobao.com/cart/order.html?itemId=557183774959&item_num_id=557183774959&_input_charset=utf-8&buyNow=true&v=0&skuId=4529363923901&quantity=1"
def shopping():
    global i
    i+=1
    driver.get(url)
    txt=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))+"第"+ str(i)+ "次刷新"
    print(txt)
    try :
        driver.find_element_by_xpath('//*[@title="提交订单"]').click()
        # print("进入订单提交页面")
        txt = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + "进入订单提交页面"
        print(txt)
        txt_panel.insert('insert', txt + '\n')
        txt_panel.see('end')
        txt_panel.update()
        driver.find_element_by_xpath('//*[@title="提交订单"]').click()
        print("订单已提交")
        txt = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + "订单已提交"
        print(txt)
        txt_panel.insert('insert', txt + '\n')
        txt_panel.see('end')
        txt_panel.update()
        send_email(ety_email.get())
        t.cancel()
    except :
        txt = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + "暂无库存，等待再次刷新"
        print(txt)
        txt_panel.insert('insert', txt + '\n')
        txt_panel.see('end')
        txt_panel.update()

if __name__ == "__main__":
    main()


import json
from random import randrange, sample

start=1
end=78

class user:
        def __init__(self,userid,username):

            self.userid=userid
            self.username=username

        def reg(username):
            userid=randrange(start,end) # creating acc number for every new user between the start and end limits \n",
            with open('user.json','r+') as f:
                data=json.load(f)
            while userid in data: # checks if acc_no already exists \n",
                userid=randrange(start,end)
            u1=user(userid,username)

class librarian:

    def __init__(self, lib_name, phone_num):
        self.lib_name = lib_name
        self.phone_num = phone_num

    def Lib_login():
        with open('lib.json', 'r') as f:
            data=json.load(f)
        while Libid in data:
            Libid= randrange(start,end)
        l1=librarian()


# -*- coding: utf-8 -*-
from mongoengine import Document, StringField, IntField
from core.const import TEXT_MAX, TAG_KEY_PREFIX, TAG_DEFAULT_SCORE
from core.cache import cache
from django.template.defaultfilters import slugify
from unidecode import unidecode
from core.util import to_unicode
from core.instant_search import SearchIndex
import logging

logger = logging.getLogger('default')

class Tag(Document):
    slug = StringField(max_length=TEXT_MAX, required=True, unique=True)
    name_en = StringField(max_length=TEXT_MAX, required=True)
    name_zh = StringField(max_length=TEXT_MAX, required=True)
    author_slug = StringField(max_length=TEXT_MAX, default='admin')
    score = IntField(default=TAG_DEFAULT_SCORE)
    description = StringField(max_length=TEXT_MAX, default='')

    @classmethod
    def create_tag(cls, name_zh, *args, **kwargs):
        name_zh = to_unicode(name_zh)
        name_en = unidecode(name_zh)
        slug = slugify(name_en)
        tag = cls(slug=slug, name_en=name_en, name_zh=name_zh, *args, **kwargs)
        try:
            tag.save()
        except Exception as err:
            logging.info("Save Tag Err name_zh %s: err %s" %(name_zh, err))
            return None
        tag.to_info()
        si = SearchIndex()
        si.add_tag(tag)
        return tag

    @property
    def cache_key(self):
        return TAG_KEY_PREFIX + self.slug

    @classmethod
    def get_cache_key(cls, slug):
        return TAG_KEY_PREFIX + slug

    def to_info(self):
        mapping = {
            'slug': self.slug,
            'name_en': self.name_en,
            'name_zh': self.name_zh,
            'author_slug': self.author_slug,
            'description': self.description
        }
        cache.hmset(self.cache_key, mapping)

    @classmethod
    def all_to_info(cls):
        tags = cls.objects()
        for tag in tags:
            tag.to_info()

    @classmethod
    def all_to_search_index(cls):
        tags = cls.objects()
        si = SearchIndex()
        for tag in tags:
            si.add_tag(tag)