#panggil library
import pandas as pd

#panggil dataset
df = pd.read_csv('https://dqlab-dataset.s3-ap-southeast-1.amazonaws.com/data_retail.csv', sep=';')

#cetak lima data teratas
print(df.head())

#cetak info dataset
print(df.info())

#mengubah kolom waktu transaksi kedalam format tanggal
df['First_Transaction']=pd.to_datetime(df['First_Transaction']/1000, unit='s', origin='1970-01-01')
df['Last_Transaction']=pd.to_datetime(df['Last_Transaction']/1000, unit='s', origin='1970-01-01')

#Pengecekan transaksi terakhir
print(max(df['Last_Transaction']))

#Klasifikasi customer churn atau tidak dan dimasukkan ke kolom is_churn
df.loc[df['Last_Transaction']<='2018-08-01', 'is_churn'] = True
df.loc[df['Last_Transaction']>'2018-08-01', 'is_churn'] = False

#menghapus kolom yang tidak diperlukan
del df['no']
del df['Row_Num']


import sys
import json
import time
import os
from kafka import KafkaConsumer
from elasticsearch import Elasticsearch
import rethinkdb as r
import hashlib

if __name__ == "__main__":

    # db connection
    # conn = r.connect(host='ec2-54-202-215-9.us-west-2.compute.amazonaws.com', port='28015', db='alluvium')
    conn = r.connect(host='10.0.0.11', port='28015', db='alluvium')

    # Listen to Kafka docs topic
    #c = '10.0.0.14:9092'
    c = 'ec2-52-13-241-228.us-west-2.compute.amazonaws.com'
    docs = KafkaConsumer('tweets', bootstrap_servers=c)

    # Create Elasticsearch instance
    es = Elasticsearch()

    for msg in docs:
        in_time = time.time()
        data = json.loads(msg.value.decode("utf-8").strip())
        print(data)

        doc = {
            "query" : {
                "percolate" : {
                    "field" : "query",
                    "document" : {
                        # "message" : data['revision']
                        "message" : data['text']
                    }
                }
            }
        }

        res = es.search(index="my-index", doc_type="_doc", body=doc)

        print(res)

        # Write matches to RethinkDB
        if res['hits']['total'] > 0:
            match = json.loads(msg.value.decode('utf-8').strip(','))
            #print(match)
            for hit in res['hits']['hits']:
                print("Found one!")
                found_match = r.table("queries").insert([{
                    "query_id": hit['_id'],
                    "screen_name": match['screen_name'],
                    "followers": match['followers'],
                    "tweet_id": match['tweet_id'],
                    "compute_time": int((time.time() - in_time)*1000)
                }]).run(conn)
                print(found_match)

        else:
            pass
            #print("Not match")


from PIL import Image, ImageDraw, ImageFilter
import os

def find_all_file(base):
    for root, ds, fs in os.walk(base):
        for f in fs:
            yield f

category = "Scarf"

def main():
    base = r"/work/instant_NGP_with_reinforcement/my/data/"+category+"/train/"
    for i in find_all_file(base):
        if(category in i):
            im_rgb = Image.open(base+i)
            im_rgba = im_rgb.copy()
            im_rgba.putalpha(255)
            im_rgba.save(base+i)

if __name__ == '__main__':
    main()


import sys
import math
from hex_utils.asc import ASC
from hex_utils.hasc import HASC
import argparse
from enum import Enum

RES_FACTOR = 1.134

class Method(Enum):
    MULTIQUADRATIC = 'mq',
    NEAREST_NEIGHBOUR = 'nn'

def setArguments():

    parser = argparse.ArgumentParser(description='Converts an ESRI ASCII grid into an HexASCII (HASC) grid.')
    parser.add_argument("-a", "--area", dest="area", default = 0,
                      type=float, help="cell area of the output mesh" )
    parser.add_argument("-r", "--resolution", action='store_true',
                      help = "preserve original spatial resolution")
    parser.add_argument("-m", "--method", default="mq",
                      help = "Interpolation mehonthod: mq - Multiquadratic, nn - Nearest Neighbour")
    parser.add_argument("-i", "--input", dest="inputFile", required = True,
                      help="input ESRI ASCII raster file" )
    parser.add_argument("-o", "--output", dest="outputFile", default = "out.hasc",
                      help="output HexASCII raster file" )

    return parser.parse_args()

# ------------ Main ------------ #
def main():

    args = setArguments()

    esriGrid = ASC()
    try:
        esriGrid.loadFromFile(args.inputFile)
    except (ValueError, IOError) as ex:
        print("Error loading the raster %s: %s" % (args.inputFile, ex))
        sys.exit()

    esriArea = math.pow(esriGrid.size, 2)
    hexArea = 0

    # Preserve spatial resolution: increase cell area.
    if (args.resolution):
        hexArea = esriArea * RES_FACTOR
    # Use area provided.
    elif (args.area > 0):
        hexArea = args.area
    # Preserve cell area: used the same as the original raster.
    else:
        hexArea = esriArea

    # Compute hexagonal cell geometry as function of area
    hexSide = math.sqrt(2 * hexArea / (3 * math.sqrt(3)))

    hexRaster = HASC()
    hexRaster.initWithExtent(hexSide, esriGrid.xll, esriGrid.yll,
                             esriGrid.xll + esriGrid.ncols * esriGrid.size,
                             esriGrid.yll + esriGrid.nrows * esriGrid.size)

    print("Geometries:" +
          "\n Input square cell area    : " + str(esriArea) +
          "\n Hexagon cell area         : " + str(hexArea)  +
          "\n Hexagon side length       : " + str(hexSide)  +
          "\n Hexagon perpendicular     : " + str(hexRaster.hexPerp)  +
          "\n Number of rows in mesh    : " + str(hexRaster.nrows)  +
          "\n Number of columns in mesh : " + str(hexRaster.ncols))

    if(args.method == Method.MULTIQUADRATIC.value[0]):
        interpol = esriGrid.interpolMultiquadratic
        print("\nConverting with Multi-quadratic interpolation ...")
    else:
        interpol = esriGrid.getNearestNeighbour
        print("\nConverting with Nearest Neighbour interpolation ...")

    for j in range(hexRaster.nrows):
        for i in range(hexRaster.ncols):
            x, y = hexRaster.getCellCentroidCoords(i, j)
            hexRaster.set(i, j, interpol(x, y))

    try:
        hexRaster.save(args.outputFile)
    except (ValueError, IOError) as ex:
        print ("Error saving output file %s: %s" % (args.outputFile, ex))

    print ("Finished successfully.")

main()


from cgitb import text
from re import I
from handlers.handler import Handler
from config.settings import KEYBOARD
from config.messages import MsgTemplates
from config.settings import ADMIN_ID
from telebot.types import CallbackQuery

class HandlerInlineQuery(Handler):

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

    def send_new_student_for_admin(self, user):
        """
        send notification about new student for admin
        """
        student_lesson = self.BD.get_guest_lesson_by_user_id(user.id)
        lesson_type = self.BD.get_lesson_type_by_id(
            student_lesson.lessons_type_id)
        self.bot.send_message(ADMIN_ID,
                              f'{user.first_name} {user.last_name}, '
                              f'хочет прийти на пробное занятие по {lesson_type}. '
                              f'Вы можете связаться с ним по телефону {user.phone}',
                              reply_markup=self.keybords.guest_start_menu())

    def record_on_test_lesson(self, call: CallbackQuery) -> CallbackQuery:
        """
        write user on test lesson
        """
        guest = self.BD.get_user_by_user_id(call.from_user.id)
        last_msg = call.message
        self.BD._add_new_lesson(guest.id, call.data, True)
        self.send_new_student_for_admin(guest)
        self.bot.answer_callback_query(
            call.id, 'Вы записаны - ждите', show_alert=True)
        return last_msg

    def del_last_bot_message(self, message) -> None:
        """
        delete inline btn
        """
        self.bot.edit_message_text(
            chat_id=message.chat.id, text=message.text, message_id=message.id, reply_markup='')

    def more_about_lesson(self, call: CallbackQuery) -> None:
        """
        show extendent information about lessons
        """
        self.bot.answer_callback_query(call.id)

        user = self.BD.get_user_by_user_id(call.from_user.id)
        lesson = self.BD.get_guest_lesson_by_user_id(user.id)

        if call.data == 'Математика':
            if lesson:
                self.bot.send_message(
                    call.from_user.id, MsgTemplates.ABOUT_MATH_MSG)
            else:
                self.bot.send_message(call.from_user.id, MsgTemplates.ABOUT_MATH_MSG,
                                      reply_markup=self.keybords.record_on_lesson_menu(1))

        if call.data == 'Английский язык':
            if lesson:
                self.bot.send_message(
                    call.from_user.id, MsgTemplates.ABOUT_ENG_MSG)
            else:
                self.bot.send_message(call.from_user.id, MsgTemplates.ABOUT_ENG_MSG,
                                      reply_markup=self.keybords.record_on_lesson_menu(2))

        if call.data == 'Обществознание':
            if lesson:
                self.bot.send_message(
                    call.from_user.id, MsgTemplates.ABOUT_SOCIAL_MSG)
            else:
                self.bot.send_message(call.from_user.id, MsgTemplates.ABOUT_SOCIAL_MSG,
                                      reply_markup=self.keybords.record_on_lesson_menu(3))

    def handle(self):
        @self.bot.callback_query_handler(func=lambda call: True)
        def callback_inline(call: CallbackQuery):
            data = call.data
            print(type(call))
            if data.isdigit():
                last_msg = self.record_on_test_lesson(call)
                self.del_last_bot_message(last_msg)

            else:
                self.more_about_lesson(call)


from flask import Blueprint, render_template, request, flash, jsonify, redirect, url_for
from flask_login import login_required, current_user
from fuzzywuzzy import fuzz
from fuzzywuzzy import process
from . import db
import json
import csv
from sqlalchemy import or_
from balanca import ler_valor_arduino, valor_arduino
import time
import serial
from .espe import Esp
from cam_yolo import CamYolo

class Views:
    views = Blueprint('views', __name__)

    peso = 0

    @views.route('/', methods=['GET', 'POST'])
    @login_required
    def home():
        return render_template("home.html", user=current_user)

    @views.route('/iniciar', methods=['GET', 'POST'])
    @login_required
    def iniciar():
        return render_template("separacao.html", user=current_user)

    @views.route('/cotacao', methods=['GET', 'POST'])
    @login_required
    def cotacao():
        return render_template("cotacao.html", user=current_user)

    @views.route('/separando', methods=['GET', 'POST'])
    @login_required
    def separando():
        # Chama a função para ler os valores do Arduino
        return render_template("loading.html", user=current_user)

    @views.route('/separado', methods=['GET', 'POST'])
    @login_required
    def separado():
        return render_template("separeted.html", user=current_user, weight = Views.peso)

    @views.route('/processando', methods=['GET', 'POST'])
    @login_required
    def processando():
        url = 'http://192.168.1.17/cam-hi.jpg'
        cam_yolo_instance = CamYolo(url)
        total_objects = cam_yolo_instance.call_detect()
        total_bottles, total_not_accepted = cam_yolo_instance.process_image()
        total_cans = int(total_objects[1])
        # print("TOTAL DE GARRAFAS: ", total_bottles)
        # print("TOTAL DE LATINHAS: ", total_cans)
        # Chama a função para ler os valores do Arduino
        total_not_accepted = 1
        total_bottles = 0
        total_cans = 0
        with serial.Serial('COM4', 9600, timeout=1) as porta_serial:
            peso = ler_valor_arduino(porta_serial, total_bottles, total_cans, total_not_accepted)
        # peso = 0
        creditos_ganhos = 0
        if(total_cans > 0 and total_bottles == 0):
            creditos_ganhos = 5 * (peso/1000)
        elif(total_cans == 0 and total_bottles > 0):
            creditos_ganhos = 1.20 * (peso/1000)
        current_user.balance += creditos_ganhos
        db.session.commit()

        print(creditos_ganhos)
        print(current_user.balance)
        return render_template("separeted.html", user=current_user, weight = peso, creditos_ganhos = creditos_ganhos)


"""
# Definition for a QuadTree node.
class Node:
    def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):
        self.val = val
        self.isLeaf = isLeaf
        self.topLeft = topLeft
        self.topRight = topRight
        self.bottomLeft = bottomLeft
        self.bottomRight = bottomRight
"""

class Solution:
    def construct(self, grid: List[List[int]]) -> 'Node':
        def helper(r, c, side):
            if side == 1:
                return Node(bool(grid[r][c]), True, None, None, None, None)
            top_left = helper(r, c, side // 2)
            top_right = helper(r, c + side // 2, side // 2)
            bottom_left = helper(r + side // 2, c, side // 2)
            bottom_right = helper(r + side // 2, c + side // 2, side // 2)

            if top_left.isLeaf and top_right.isLeaf and bottom_left.isLeaf and bottom_right.isLeaf:
                if top_left.val == top_right.val == bottom_left.val == bottom_right.val:
                    return Node(top_left.val, True, None, None, None, None)
            node_val = any((top_left.val, top_right.val, bottom_left.val, bottom_right.val))
            return Node(node_val, False, top_left, top_right, bottom_left, bottom_right)

        if not grid:
            return None
        return helper(0, 0, len(grid))

LeetCode/Python3/Medium/427. Construct Quad Tree/0427-construct-quad-tree.py


import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm

nx = 81
ny = 81
nt = 200
c = 1
dx = 2 / (nx - 1)
dy = 2 / (ny - 1)
sigma = .2
dt = sigma * dx

x = np.linspace(0, 2, nx)
y = np.linspace(0, 2, ny)

u = np.ones((nx, ny))
un = np.ones((nx, ny))

# initial conditions
u[int(.5 / dy):int(1 / dy + 1), int(.5 / dx):int(1 / dx + 1)] = 2

for n in range(nt + 1):
    un = u.copy()
    row, col = u.shape

    u[1:, 1:] = (un[1:, 1:] - (c * dt / dx * (un[1:, 1:] - un[1:, :-1])) - (c * dt / dy * (un[1:, 1:] - un[:-1, 1:])))

    u[0, :] = 1
    u[-1, :] = 1
    u[:, 0] = 1
    u[:, -1] = 1

fig, ax = plt.subplots(subplot_kw={"projection": "3d"})

#fig = plt.figure()
#ax = fig.gca(projection='3d')

X, Y = np.meshgrid(x, y)

surf = ax.plot_surface(X, Y, u[:], cmap=cm.viridis)

plt.show()


#!/usr/bin/env micropython

from ev3dev2.motor import MediumMotor, OUTPUT_A
from ev3dev2.sensor.lego import InfraredSensor
from ev3dev2.sensor import INPUT_4
from time import sleep
import math
import sys

#Code is here
IR = InfraredSensor(INPUT_4)
meMotor = MediumMotor(OUTPUT_A)

x = 0
while x < 1000:
        BeaconHeading = IR.heading_and_distance(channel=1)
        print(BeaconHeading,file=sys.stderr)
        (Heading, Distance) = BeaconHeading
        print(Heading,file=sys.stderr)

        if Heading:
                print(Heading,file=sys.stderr)
                Heading = Heading*2
                meMotor.on(speed=Heading)
        else:
                meMotor.off()
        sleep(.01)


import argparse
import logging
from multiprocessing.connection import wait
import os
import glob
import numpy as np
import torch
import torch.nn.functional as F
from PIL import Image
from torchvision import transforms
import monai
from monai.data import list_data_collate
from utils.data_loading import BasicDataset
from torch.utils.data import DataLoader
from unet import UNet
from utils.dice_score import dice_loss, dice_coeff, multiclass_dice_coeff
from utils.utils import plot_img_and_mask
import SimpleITK as sitk
from scipy.signal import resample_poly
from dataload import Data
# from myshow3d import myshow, myshow3d
import cv2
def predict_img(net,
                img,
                device,
                scale_factor=1,
                out_threshold=0.5):
    net.eval()
    # img = torch.from_numpy(full_img)
    # img = img.unsqueeze(0)
    img = img.to(device=device, dtype=torch.float32)

    with torch.no_grad():
        mask_pred = net(img)

        if net.n_classes == 1:
            mask_pred = (F.sigmoid(mask_pred) > 0.5).float()
            # compute the Dice score
            # dice_score += dice_coeff(mask_pred, mask_true, reduce_batch_first=False)
        else:
            mask_pred = F.one_hot(mask_pred.argmax(dim=1), net.n_classes).permute(0, 3, 1, 2).float()
            # compute the Dice score, ignoring background
            # dice_score += multiclass_dice_coeff(mask_pred[:, 1:, ...], mask_true[:, 1:, ...], reduce_batch_first=False)

        return torch.softmax(mask_pred, dim=1).argmax(dim=1)[0].float().cpu()

def get_args():
    parser = argparse.ArgumentParser(description='Predict masks from input images')
    parser.add_argument('--model', '-m', default='MODEL.pth', metavar='FILE',
                        help='Specify the file in which the model is stored')
    parser.add_argument('--input', '-i', metavar='INPUT', nargs='+', help='Filenames of input images', required=True)
    parser.add_argument('--output', '-o', metavar='INPUT', nargs='+', help='Filenames of output images')
    parser.add_argument('--viz', '-v', action='store_true',
                        help='Visualize the images as they are processed')
    parser.add_argument('--no-save', '-n', action='store_true', help='Do not save the output masks')
    parser.add_argument('--mask-threshold', '-t', type=float, default=0.5,
                        help='Minimum probability value to consider a mask pixel white')
    parser.add_argument('--scale', '-s', type=float, default=0.5,
                        help='Scale factor for the input images')

    return parser.parse_args()

def get_output_filenames(args):
    def _generate_name(fn):
        split = os.path.splitext(fn)
        return f'{split[0]}_OUT{split[1]}'

    return args.output or list(map(_generate_name, args.input))

def mask_to_image(mask: np.ndarray):
    if mask.ndim == 2:
        return Image.fromarray((mask * 255).astype(np.uint8))
    elif mask.ndim == 3:
        return Image.fromarray((np.argmax(mask, axis=0)/ mask.shape[0]).astype(np.uint8))

def resolution_match(result_array, data_util, coord1, coord2):
    result_array_np = np.transpose(result_array, (2, 1, 0))
    result_array_temp = sitk.GetImageFromArray(result_array_np)
    result_array_temp.SetSpacing((data_util.resolution) + (1, ))

    # save temporary label
    writer = sitk.ImageFileWriter()
    writer.SetFileName('temp_seg.nii')
    writer.Execute(result_array_temp)

    files = [{"image": 'temp_seg.nii'}]

    files_ds = monai.data.Dataset(data=files, transform=data_util.reverse_transforms)
    files_loader = DataLoader(files_ds, batch_size=1, num_workers=0)

    for files_data in files_loader:
        files_images = files_data["image"]

        res = files_images.squeeze().data.numpy()

    # result_array = np.rint(res)
    result_array = res
    os.remove('./temp_seg.nii')

    # empty_array = np.zeros(original_shape)
    # empty_array[coord1[0]:coord2[0],coord1[1]:coord2[1],coord1[2]:coord2[2]] = result_array

    itk_image = sitk.GetImageFromArray(result_array)
    return itk_image

if __name__ == '__main__':
    input_path = '/Users/mona/workSpace/github_repo/DeepShim/code/python/Pytorch-UNet/data/target_data_originalresolution'
    path = '/Users/mona/workSpace/github_repo/DeepShim/code/python/Pytorch-UNet/dataoutput/test_resolution_2'
    model = f"checkpoints/test_resolution/best_model_fold.pth"

    if not os.path.exists(path):
        os.makedirs(path)

    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    data_util = Data()

    print(f'Using device {device}')

    net = UNet(n_channels=1, n_classes=2)
    net.to(device=device)
    net.load_state_dict(torch.load(model, map_location=device))

    print('Model loaded!')

    input_files = glob.glob(f"{input_path}/*.nii")
    input_files.sort(key=lambda x:int((x.split("/")[-1]).split('_')[-1][:-4]))
    masks = []
    images = []
    for image in input_files:
        original_shape, crop_shape, coord1, coord2, resampled_size, original_resolution = data_util.statistics_crop(image, data_util.resolution)
        files = [{"image": image}]
        test_ds = monai.data.Dataset(data=files, transform=data_util.test_transforms)
        test_loader = DataLoader(test_ds, batch_size=1, num_workers=0, collate_fn=list_data_collate, pin_memory=False)
        for test_data in test_loader:
            test_image = test_data["image"].to(device)
            mask_slice = predict_img(net=net,
                            img=test_image,
                            scale_factor=1,
                            out_threshold=0.5,
                            device=device)
        result_array = mask_slice.squeeze().data.cpu().numpy()
        result_array = result_array[0:resampled_size[0],0:resampled_size[1]]

        result_seg = data_util.from_numpy_to_itk(result_array, image)
        result = os.path.join(path, image.split("/")[-1])
        writer = sitk.ImageFileWriter()
        writer.SetFileName(result)
        writer.Execute(result_seg)

        masks.append(result_array)
        images.append((test_image[0].squeeze().data.cpu().numpy())[0:resampled_size[0],0:resampled_size[1]])

    masks = np.dstack(masks)
    images = np.dstack(images)

    # masks_img = data_util.from_numpy_to_itk(masks, image)
    # images_img = data_util.from_numpy_to_itk(images, image)

    if not (original_resolution == data_util.resolution):
        data_util.init_reverse(crop_shape=(crop_shape+(len(input_files), )))
        masks_img = resolution_match(masks, data_util, coord1, coord2)
        images_img = resolution_match(images, data_util, coord1, coord2)

    else:
        masks_img = sitk.GetImageFromArray(masks)
        images_img = sitk.GetImageFromArray(images)

    sitk.WriteImage(masks_img, os.path.join(path, "3Doutput.nii"))
    sitk.WriteImage(images_img, os.path.join(path, "3Dinput.nii"))


from django.urls import path
from myapp import views
app_name="myapp"

urlpatterns = [

    path('profile/',views.profile,name="profile"),
    path('get_demo/',views.get_demo,name="get_demo"),
    path('post_demo/',views.post_demo,name="post_demo"),
    path('register/',views.register,name="register"),
    path('multi/',views.multi,name="multiselect"),
    path('img/',views.img,name="img"),
       path('img_dis/',views.img_dis,name="img_dis"),
    path('builtin/',views.builtin,name='builtin')
]


"""
Tests for the apply command module
"""
from unittest.mock import call, patch

import pytest
from cli_test_helpers import ArgvContext

import kustomize

@patch('kustomize.commands.apply.apply')
def test_cli_command(mock_command):
    """
    Is the correct code called when invoked via the CLI?
    """
    with ArgvContext('kustomize', 'apply', '.'), pytest.raises(SystemExit):
        kustomize.cli.main()

    assert mock_command.called

@patch('kustomize.commands.apply.binarypath')
@patch('kustomize.commands.apply.shell')
def test_uses_shell(mock_shell, mock_binarypath):
    """
    Does command use the shell function to run commands?
    """
    kustomize.commands.apply.apply(['foo', 'bar'], None)

    assert mock_binarypath.mock_calls[0] == \
        call('kustomize', download_if_missing=True), \
        "We don't ensure all binaries are available"

    assert mock_shell.called, "Doesn't use shell() function"


from direct.directnotify import DirectNotifyGlobal
from direct.distributed import DistributedObject
from direct.interval.IntervalGlobal import *
from toontown.effects import DustCloud

def getDustCloudIval(toon):
    dustCloud = DustCloud.DustCloud(fBillboard=0)
    dustCloud.setBillboardAxis(2.0)
    dustCloud.setZ(3)
    dustCloud.setScale(0.4)
    dustCloud.createTrack()

    if hasattr(toon, 'laffMeter'):
        toon.laffMeter.color = toon.style.getBlackColor()

    sequence = Sequence(Wait(0.5), Func(dustCloud.reparentTo, toon), dustCloud.track, Func(dustCloud.destroy))

    if hasattr(toon, 'laffMeter'):
        sequence.append(Func(toon.laffMeter.adjustFace, toon.hp, toon.maxHp))

    return sequence

class DistributedBlackCatMgr(DistributedObject.DistributedObject):
    neverDisable = 1
    notify = DirectNotifyGlobal.directNotify.newCategory('DistributedBlackCatMgr')

    def announceGenerate(self):
        DistributedObject.DistributedObject.announceGenerate(self)
        base.cr.blackCatMgr = self

    def delete(self):
        base.cr.blackCatMgr = None
        DistributedObject.DistributedObject.delete(self)

    def requestBlackCatTransformation(self):
        self.sendUpdate('requestBlackCatTransformation')

    def doBlackCatTransformation(self):
        getDustCloudIval(base.localAvatar).start()


import os
import pandas as pd

# Get the path
args = {}
args['cwd'] = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))
args['raw_dir'] = os.path.join(args['cwd'], 'data', 'raw')
args['derived_dir'] = os.path.join(args['cwd'], 'data', 'derived', 'production_time_series')
args['czech_dir'] = os.path.join(args['cwd'], 'data', 'derived', 'czech')

# Read the data
network_nodes = pd.read_csv(os.path.join(args['raw_dir'], 'network_nodes.csv'), usecols=['ID','country'])
wind_signal = pd.read_csv(os.path.join(args['raw_dir'], 'wind_signal_COSMO.csv'),index_col=0)
solar_signal = pd.read_csv(os.path.join(args['raw_dir'], 'solar_signal_COSMO.csv'),index_col=0)
wind_layouts = pd.read_csv(os.path.join(args['raw_dir'], 'wind_layouts_COSMO.csv'),index_col=0)
solar_layouts = pd.read_csv(os.path.join(args['raw_dir'], 'solar_layouts_COSMO.csv'),index_col=0)

# fill the NaN values with 0 for solar_signals
solar_signal = solar_signal.fillna(0)

# Multiply the signals with the layouts to get the production time series
wind_production_hourly = wind_signal.multiply(wind_layouts['Proportional'].values.flatten(),axis=1)
solar_production_hourly = solar_signal.multiply(solar_layouts['Proportional'].values.flatten(),axis=1)
# Transform the colnames to integer
wind_production_hourly.columns = wind_production_hourly.columns.astype(int)
solar_production_hourly.columns = solar_production_hourly.columns.astype(int)
# Output the hourly production time series for wind and solar
wind_production_hourly.to_csv(os.path.join(args['derived_dir'], 'wind_production_hourly.csv'))
solar_production_hourly.to_csv(os.path.join(args['derived_dir'], 'solar_production_hourly.csv'))

# Transform the index to datetime
time_format = '%Y-%m-%d %H:%M:%S'
wind_production_hourly.index = pd.to_datetime(wind_production_hourly.index,format=time_format)
solar_production_hourly.index = pd.to_datetime(solar_production_hourly.index,format=time_format)
# Resample to daily
wind_production_daily = wind_production_hourly.resample('D').sum()
solar_production_daily = solar_production_hourly.resample('D').sum()
# Transform the colnames to integer
wind_production_daily.columns = wind_production_daily.columns.astype(int)
solar_production_daily.columns = solar_production_daily.columns.astype(int)
# Output the daily production time series for wind and solar
wind_production_daily.to_csv(os.path.join(args['derived_dir'], 'wind_production_daily.csv'))
solar_production_daily.to_csv(os.path.join(args['derived_dir'], 'solar_production_daily.csv'))

# Average the hourly production over all nodes
average_production_hourly = pd.DataFrame()
average_production_hourly['wind'] = wind_production_hourly.sum(axis=1)/len(wind_production_hourly.columns)
average_production_hourly['solar'] = solar_production_hourly.sum(axis=1)/len(wind_production_hourly.columns)
# Compute date time variables
average_production_hourly['year'] = average_production_hourly.index.year
average_production_hourly['week'] = average_production_hourly.index.isocalendar().week
average_production_hourly['month'] = average_production_hourly.index.month
average_production_hourly['day_of_month'] = average_production_hourly.index.day
# Output the average hourly production time series for wind and solar
average_production_hourly.to_csv(os.path.join(args['derived_dir'], 'average_production_hourly.csv'))

# Average the daily production over all nodes
average_production_daily = pd.DataFrame()
average_production_daily['wind'] = wind_production_daily.sum(axis=1)/len(wind_production_daily.columns)
average_production_daily['solar'] = solar_production_daily.sum(axis=1)/len(wind_production_daily.columns)
# Compute date time variables
average_production_daily['year'] = average_production_daily.index.year
average_production_daily['week'] = average_production_daily.index.isocalendar().week
average_production_daily['month'] = average_production_daily.index.month
average_production_daily['day_of_month'] = average_production_daily.index.day
# Output the average daily production time series for wind and solar
average_production_daily.to_csv(os.path.join(args['derived_dir'], 'average_production_daily.csv'))

# Average the time series over the nodes with the same country
# Melt the dataframe to long format
melted_wind = wind_production_daily.reset_index().melt(id_vars='Time', var_name='ID', value_name='production')
melted_solar = solar_production_daily.reset_index().melt(id_vars='Time', var_name='ID', value_name='production')
# Merge the two dataframes on 'ID'
merged_wind = pd.merge(melted_wind, network_nodes, on='ID')
merged_solar = pd.merge(melted_solar, network_nodes, on='ID')
# Group by 'country' and 'Time', and then take the mean
average_wind_by_country = merged_wind.groupby(['country', 'Time']).mean().reset_index()
average_solar_by_country = merged_solar.groupby(['country', 'Time']).mean().reset_index()
# Pivot the dataframe to get the desired format
average_wind_by_country = average_wind_by_country.pivot(index='Time', columns='country', values='production')
average_solar_by_country = average_solar_by_country.pivot(index='Time', columns='country', values='production')
# Output the average daily production time series for wind and solar
average_wind_by_country.to_csv(os.path.join(args['derived_dir'], 'wind_average_by_country.csv'))
average_solar_by_country.to_csv(os.path.join(args['derived_dir'], 'solar_average_by_country.csv'))

# Get the ID for the nodes in czech
czech_nodes = network_nodes[network_nodes['country']=='CZE']['ID'].values
# Get the production time series for the nodes in czech
czech_wind_production_daily = wind_production_daily.loc[:,czech_nodes]
czech_solar_production_daily = solar_production_daily[czech_nodes]
# Output the daily production time series for wind and solar
czech_wind_production_daily.to_csv(os.path.join(args['czech_dir'], 'wind_time_series.csv'))
czech_solar_production_daily.to_csv(os.path.join(args['czech_dir'], 'solar_time_series.csv'))


from typing import Callable
from functools import partial
import solara as sl
import pandas as pd
from solara.components.file_drop import FileInfo
import io

def load_file_df(file: FileInfo, set_df: Callable):
    if not file["data"]:
        return
    new_df = pd.read_csv(io.BytesIO(file["data"]))
    # Set it before embeddings so the user can see the df while embeddings load
    set_df(new_df)

@sl.component
def df_table(df: pd.DataFrame, num_samples: int, search: str) -> None:
    if not len(df):
        return
    filtered = df.copy()
    if "text" in df.columns:
        filtered = df[df["text"].str.contains(search)]
    sl.DataFrame(filtered[:num_samples])

@sl.component
def file_manager(set_df: Callable) -> None:
    sl.FileDrop(
        label="Drop CSV here (`text` col required)!",
        on_file=partial(load_file_df, set_df=set_df),
        lazy=False,
    )

@sl.component
def menu():
    df, set_df = sl.use_state(pd.DataFrame({}))
    num_samples, set_samples = sl.use_state(10)
    search, set_search = sl.use_state("")

    with sl.Sidebar():
        sl.InputText("What would you like to see?", search, on_value=set_search)
        sl.SliderInt("How many samples?", num_samples, max=100, on_value=set_samples)
        file_manager(set_df)
    df_table(df, num_samples, search)

@sl.component
def Page():
    menu()


import tkinter as tk
from PIL import Image
from PIL import ImageTk

def callback():
    var.set('吹吧你')

root = tk.Tk()

frame1 = tk.Frame(root)
frame2 = tk.Frame(root)

var = tk.StringVar()
var.set('未满18岁禁止点击')

textLabel = tk.Label(frame1, textvariable=var, justify=tk.LEFT)
textLabel.pack(side=tk.LEFT)

img = Image.open('/Users/yangkaiqiang/Desktop/images/cat.jpg')
photo = ImageTk.PhotoImage(img)

imageLabel = tk.Label(frame1, image=photo)
imageLabel.pack(side=tk.RIGHT)

theButton = tk.Button(frame2, text='我已满18岁', command=callback)
theButton.pack()

frame1.pack(padx=10, pady=10)
frame2.pack(padx=10, pady=10)

tk.mainloop()


lines = open("Day 5\input.txt", "r").readlines()

defaultStacks = {}
commands = []

def ProcessInput():
    for i, line in enumerate(lines):
        if line[0] == "\n" or line[0] == " ":
            continue
        elif i < 8:
            stackIndex = 1
            for index in range(1, len(line), 4):
                if i == 0:
                    defaultStacks[stackIndex] = []
                    if line[index] != " ":
                        defaultStacks[stackIndex].append(line[index])
                else:
                    if line[index] != " ":
                        defaultStacks[stackIndex].append(line[index])
                stackIndex += 1
        else:
            if i == len(lines) - 1:
                splitLine = line.split(" ")
                command = {splitLine[0]: int(splitLine[1]), splitLine[2]: int(splitLine[3]), splitLine[4]: int(splitLine[5])}
            else:
                splitLine = line.split(" ")
                lastInt = splitLine[5][:-1]
                command = {splitLine[0]: int(splitLine[1]), splitLine[2]: int(splitLine[3]), splitLine[4]: int(lastInt)}
                commands.append(command)
    commands.append(command)

def Part1(crates):
    answer = ""
    for command in commands:
        for crateIndex in range(command["move"]):
            crates[command["to"]].insert(0, crates[command["from"]][0])
            crates[command["from"]].pop(0)
    for crate in crates.values():
        if len(crate) > 0:
            answer += crate[0]
        else:
            answer += " "
    return answer

def Part2(crates):
    answer = ""
    for command in commands:
        for crateIndex in range(command["move"]):
            crates[command["to"]].insert(crateIndex, crates[command["from"]][0])
            crates[command["from"]].pop(0)
    for crate in crates.values():
        if len(crate) > 0:
            answer += crate[0]
        else:
            answer += " "
    return answer

ProcessInput()
print(Part1(defaultStacks))
# PTWLTDJV

defaultStacks = {}
commands = []
ProcessInput()
print(Part2(defaultStacks))
# WZMFVGGZP


import pandas as pd
import numpy as np
import scipy.stats as stats
from scipy.stats.contingency import association
import warnings
warnings.filterwarnings("ignore")

def intersection(lst1, lst2):
  return list(set(lst1) & set(lst2))

def domain_oriented_analysis(df4):
  categorised_pkg_df = pd.read_csv("../../data/categorized-debian-packages.csv")
  df4_categorized = df4.merge(categorised_pkg_df, left_on='package', right_on='packages')
  max_frequency_domains = df4_categorized.type.value_counts().index

  final_dict = {}
  for domain in max_frequency_domains:
    filtered_df = df4_categorized[df4_categorized.type == domain]
    filtered_df.loc[filtered_df['status'] == 'reproducible', 'status'] = 1
    filtered_df.loc[filtered_df['status'] != 1, 'status'] = 0
    filtered_df.loc[filtered_df['dependency status'] == 'reproducible', 'dependency status'] = 1
    filtered_df.loc[filtered_df['dependency status'] != 1, 'dependency status'] = 0
    domain_df = filtered_df.groupby(['packages', 'status'], as_index=False).agg({'dependency status': 'min'})
    dataset_tbl = pd.crosstab(domain_df.status, domain_df['dependency status'])
    stat, p, dof, expected = stats.chi2_contingency(dataset_tbl)
    effect_size = association(dataset_tbl, method="cramer")
    final_dict[domain] = (stat, p, dof, expected, effect_size)

  significant = []
  not_sig = []
  for keys in final_dict.keys():
    if final_dict[keys][1] <= 0.01:
      significant.append(keys)
    else:
      not_sig.append(keys)

  print("\nDomain Analysis:")
  print('Statistically Significant Correlation for distribution: \nDomain: Effect Size')
  for k, v in final_dict.items():
    if k in significant:
      print(k, v[4])
  print('Number of domains with statistically significant correlation: ', len(significant))
  print("-----------------------------------------")

def get_correlation(package_dep_tbl_subset, stats_build_sorted_instance):
  package_stats_merge = pd.merge(package_dep_tbl_subset, stats_build_sorted_instance, how='left', left_on='name',
                                 right_on='Package_name', validate='m:1')
  df = package_stats_merge
  df1 = df.dropna(subset=["Package_name"], inplace=False)

  deb_status = []
  for dependency in df1['dependency']:
    try:
      package = stats_build_sorted_instance[stats_build_sorted_instance['Package_name'] == dependency]
      status = package['status']
      deb_status.append(status.item())
    except:
      deb_status.append(np.nan)

  df1['dependency status'] = deb_status
  df2 = df1[["package", "status", "dependency", "dependency status"]]
  df3 = df2.dropna(subset=["dependency status"], inplace=False)

  df3.loc[df3['status'] == 'reproducible', 'status'] = 1
  df3.loc[df3['status'] != 1, 'status'] = 0
  df3.loc[df3['dependency status'] == 'reproducible', 'dependency status'] = 1
  df3.loc[df3['dependency status'] != 1, 'dependency status'] = 0
  df4 = df3.groupby(['package', 'status'], as_index=False).agg({'dependency status': 'min'})

  dataset_tbl = pd.crosstab(df4.status, df4['dependency status'])
  observed_values = dataset_tbl.values
  print("Correlation Analysis:")
  print("Observed Values :-\n", observed_values)

  stat, p, dof, expected = stats.chi2_contingency(dataset_tbl)
  print("Values of chi-quare statistics is: %f" % stat)
  print(f"p-value is: {p:.20f}")
  print("Effect size: ", association(dataset_tbl, method="cramer"))

  domain_oriented_analysis(df4)

def main():
  # Load Tables
  distributions_tbl = pd.read_csv("../../data/distributions.csv", sep=",")
  stats_build = pd.read_csv("../../data/stats_build.csv", sep=',')
  package_dep_tbl = pd.read_csv("../../data/transitive_dependency.csv", sep=",")

  stats_build_mod = pd.merge(stats_build, distributions_tbl, left_on="distribution", right_on="id")
  stats_build_filtered_debian = stats_build_mod[(stats_build_mod["name_y"] == "debian")]
  stats_build_filtered = stats_build_filtered_debian[stats_build_filtered_debian["architecture"] == "amd64"]
  stats_build_filtered = stats_build_filtered[stats_build_filtered["suite"] == 'unstable']
  stats_build_sorted = stats_build_filtered.sort_values(by='build_date', ascending=False)
  stats_build_sorted['trim_date'] = pd.to_datetime(stats_build_sorted['build_date']).dt.date
  stats_build_sorted = stats_build_sorted.drop(['id_x', 'id_y', 'distribution'], axis=1)

  # Preprocess package table :
  package_dep_tbl_subset = package_dep_tbl[package_dep_tbl.name == package_dep_tbl.package]
  package_dep_tbl_subset = package_dep_tbl_subset.drop_duplicates()

  # Organize builds.
  stats_build_sorted['rank_num'] = stats_build_sorted.groupby("name_x")['trim_date'].rank(method="first",
                                                                                ascending=False)
  stats_build_sorted = stats_build_sorted.rename(columns={'name_x': 'Package_name'})
  stats_build_sorted_instance = stats_build_sorted[stats_build_sorted['rank_num'] == 1.0]
  get_correlation(package_dep_tbl_subset, stats_build_sorted_instance)
  stats_build_sorted_instance = stats_build_sorted[stats_build_sorted['rank_num'] == 5.0]
  get_correlation(package_dep_tbl_subset, stats_build_sorted_instance)

if __name__ == '__main__':
  main()


# a121_catch_a_turtle.py
# Screen Size: 400x300
#-----import statements-----
import turtle
import random
import leaderboard as lb

#-----game configuration----
leaderboard_file_name = "a122_leaderboard.txt"
leader_names_list = []
leader_scores_list = []
player_name = input("What is your name? ")

turt_color = 'darkgreen'
turt_size = 5
turt_shape = 'circle'

score = 0
#-----initialize turtle-----
turt = turtle.Turtle(shape=turt_shape)
turt.turtlesize(turt_size)
turt.color(turt_color)
turt.speed(0)
turt.penup()

score_writer = turtle.Turtle()
score_writer.hideturtle()
score_writer.penup()
score_writer.goto(250, 220)
font_setup = ("Arial", 20, 'normal')
score_writer.write(score, font=font_setup)

counter = turtle.Turtle()
counter.hideturtle()
counter.penup()
counter.goto(-250, 220)

timer = 5
counter_interval = 1000
timer_up = False

#------game functions------

def turt_clicked(x, y):
    global timer, score

    if (timer+1 >= 0):
        update_score()
        change_position()

    else:
        turt.hideturtle()

def change_position():
    newx = random.randint(-400, 400)
    newy = random.randint(-300, 300)
    turt.goto(newx, newy)

def update_score():
    global score
    score += 1
    score_writer.clear()
    score_writer.write(score, font=font_setup)
    # print(score)

def countdown():
    global timer, timer_up
    counter.clear()
    if (timer < 0):
        counter.write("Time's up!", font=font_setup)
        timer -= 1
        timer_up = True
        manage_leaderboard()
        counter.getscreen().ontimer(countdown, counter_interval)

    else:
        counter.write("Timer: " + str(timer), font=font_setup)
        timer -= 1
        timer_up = False
        counter.getscreen().ontimer(countdown, counter_interval)

# manages the leaderboard for top 5 scorers

def manage_leaderboard():

    global leader_scores_list
    global leader_names_list
    global leaderboard_file_name
    global score
    global turt

    # load all the leaderboard records into the lists
    lb.load_leaderboard(leaderboard_file_name, leader_names_list, leader_scores_list)

    # TODO
    if (len(leader_scores_list) < 5 or score > leader_scores_list[4]):
        lb.update_leaderboard(leaderboard_file_name, leader_names_list, leader_scores_list, player_name, score)
        lb.draw_leaderboard(leader_names_list, leader_scores_list, True, turt, score)

    else:
        lb.draw_leaderboard(leader_names_list, leader_scores_list, False, turt, score)

#-------events-------

turt.onclick(turt_clicked)
wn = turtle.Screen()
wn.ontimer(countdown, counter_interval)
wn.mainloop()


'''
You should write a function that will receive a positive integer and return:
"Fizz Buzz" if the number is divisible by 3 and by 5;
"Fizz" if the number is divisible by 3;
"Buzz" if the number is divisible by 5;
The number as a string for other cases.
'''

#Your optional code here
#You can import some modules or create additional functions

def checkio(number):
    if number%3 == 0:
        if number%5 == 0:
            number = 'Fizz Buzz'
        else:
            number = 'Fizz'
    elif number%5 == 0:
        number ='Buzz'
    return str(number)

#Some hints:
#Convert a number in the string with str(n)

#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
    assert checkio(15) == "Fizz Buzz", "15 is divisible by 3 and 5"
    assert checkio(6) == "Fizz", "6 is divisible by 3"
    assert checkio(5) == "Buzz", "5 is divisible by 5"
    assert checkio(7) == "7", "7 is not divisible by 3 or 5"
    print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")


# using opencv built in face recognizer

import os
import cv2 as cv
import numpy as np

people = []
train_dir = r'A:\GitHub\opencv_practice\Faces\train'
haar_cascade = cv.CascadeClassifier('Face_detection_using_haar_cascade\haar_cascade_face.xml')
for i in os.listdir(r'A:\GitHub\opencv_practice\Faces\train'):
    people.append(i)

features = []
labels = []
def train():
    for person in people:
        path = os.path.join(train_dir, person)
        label = people.index(person)

        for img in os.listdir(path):
            img_path = os.path.join(path, img)

            img_array = cv.imread(img_path)
            gray = cv.cvtColor(img_array, cv.COLOR_BGR2GRAY)
            faces_rect = haar_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=1)

            for (x,y,w,h) in faces_rect:
                faces_roi = gray[y:y+h, x:x+w]
                features.append(faces_roi)
                labels.append(label)

train()
np.save('Features.npy', features)
np.save('Labels.npy', labels)
face_recognizer = cv.face.LBPHFaceRecognizer_create()
face_recognizer.train(np.array(features, dtype='object'), np.array(labels))
np.save('Features.npy', features)
np.save('Labels.npy', labels)
face_recognizer.save('face_trained.yml')


import scrapy

from myprojct.items import ExampleItem

class ExampleSpider(scrapy.Spider):
    name = 'example'
    allowed_domains = ["example.com"]

    start_urls = [
        'http://www.example.com',
    ]

    # 先登录
    def start_requests(self):
        # Cookies数据
        cookies = {'uid': '"1083428ut78j8"', 'v': '30'}
        # 头信息
        headers = {
            'Connection': 'keep-alive',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'
        }

        return [scrapy.FormRequest("http://www.example.com/articles",
                                   # 使用Cookies
                                   cookies=cookies,
                                   # 指定头信息
                                   headers=headers,
                                   # 指定回调函数
                                   callback=self.parse_page)]

    # 解析页面
    def parse_page(self, response):
        item = ExampleItem()
        item["name"] = response.css(".name").extract_first()
        yield item


"""
Counting Numbers:
Description: Write a program that counts and prints numbers from 1 to a user-provided limit.
Instructions: Use a while loop or a for loop to iterate through the numbers and print each one.
"""

print("Counting Numbers\n")
numAsk = int(input("Enter a number: "))

for i in range(numAsk):
    i += 1
    print(i)


import re
import sys
err_occur=[]
original=sys.stdout
count=0
file =open('output.txt', 'w')
pattern=re.compile(r"\bXAH\w*.\b",re.IGNORECASE)
with open ('sample.txt',"rt") as in_file:
    for line in in_file:
        if pattern.search(line)!=None:
            start=line.find('XAH.') +4
            end=line.find(' ',start)
            print (line[start:end])
            file.write(line[start:end]+'\n')

            count=count+1
            i=count

file.close()

        #if pattern.search(line)!=None:
            #print(line,end='')
            #m=re.search('XAH.(.+?) ', line)
            #found=m.group(1)


import socket
import struct
import textwrap

TAB_1 = '\t - '
TAB_2 = '\t\t - '
TAB_3 = '\t\t\t - '
TAB_4 = '\t\t\t\t - '

DATA_TAB_1 = '\t   '
DATA_TAB_2 = '\t\t   '
DATA_TAB_3 = '\t\t\t   '
DATA_TAB_4 = '\t\t\t\t   '

def eth_frame(data):
    dest_mac, src_mac, proto = struct.unpack('! 6s 6s H', data[:14]) # unpacking the ethernet frame to retrieve only the first 14 bytes
    # !-> tells to use standard size and network endianness(big endian) whne unpacking
    # 6s -> takes 6 characters to build a string for the destination address
    # 6s -> takes the sources address
    # H -> takes an unsigned short for the type
    return format_mac(dest_mac), format_mac(src_mac), socket.htons(proto), data[14:]

def format_mac(bytes_addr):
    bytes_str = map('{:02x}'.format, bytes_addr)
     # {:02x} -> Format ints into string of hex
    return ":".join(bytes_str).upper()

def main():
   conn = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(3))
   # SOCK_RAW -> raw packet, instead of processed packet
   # socket.ntohs(3) -> tells to capture everything including ethernet frames, which includes TCP, UDP & ICMP

   while True:
       raw_data, addr = conn.recvfrom(65535)
       dest_mac, src_mac, eth_proto, data = eth_frame(raw_data)
       print('\nEthernet Frame:')
       print(TAB_1 + 'Destination: {}, Source: {}, Protocol: {}'.format(dest_mac, src_mac, eth_proto))
       #print(data)
       if eth_proto == 8:
        (version, header_length, ttl, proto, src, target, data) = ipv4_packets(data)
        print(TAB_1 + 'IPv4 Packet: ')
        print(TAB_2 + 'version: {}, Header Length: {}, TTL: {}'.format(version, header_length, ttl))
        print(TAB_2 + 'Protocol: {}, Source: {}, Target: {}'.format(proto, src, target))

        if proto == 1:
            icmp_type, code, checksum, data = icmp_packet(data)
            print(TAB_1 + 'ICMP Packet: ')
            print(TAB_2 + 'Type: {}, Code: {}, Checksum: {}'.format(icmp_type, code, checksum))
            print(TAB_2 + 'Data: ')
            print(format_multi_line(DATA_TAB_3, data))

        elif proto == 6:
            (src_port, dest_port, sequence, acknowledgement, flag_urg, flag_ack, flag_psh, flag_rst, flag_syn, flag_fin, data) = tcp_segment(data)
            print(TAB_1 + 'TCP Segment:')
            print(TAB_2 + 'Source Port: {}, Destination Port: {}'.format(src_port, dest_port))
            print(TAB_2 + 'Sequence: {}, Acknowledgement: {}'.format(sequence, acknowledgement))
            print(TAB_2 + 'Flags:')
            print(TAB_3 + 'URG: {}, ACK: {}, PSH: {}, RST: {}, SYN:{}, FIN: {}'.format(flag_urg, flag_ack, flag_psh, flag_rst, flag_syn, flag_fin))
            print(TAB_2 + 'Data:')
            print(format_multi_line(DATA_TAB_3, data))

        elif proto == 17:
            src_port, dest_port, length, data = udp_segment(data)
            print(TAB_1 + 'UDP Segment: ')
            print(TAB_2 + 'Source Port: {}, Destination Port: {}, Length {}'.format(src_port, dest_port, length))

        else:
            print('Data: ')
            print(format_multi_line(DATA_TAB_1, data))

## Unpacking Different packets

# unpacking IPv4 packets
def ipv4_packets(data):
    version_data_length = data[0]
    version = version_data_length >> 4  #bit-shifting to right by 4 bits to move header length data out of 1 byte in the version_data_length variable

    header_length = (version_data_length & 15) * 4
    ttl, proto, src, target = struct.unpack('! 8x B B 2x 4s 4s', data[:20])
    # ! 8x B B 2x 4s 4s -> format in which the data is going to be unpacked
    return version, header_length, ttl, proto, ipv4(src), ipv4(target), data[header_length:]

def ipv4(addr):
    return '.'.join(map(str, addr))

# Unpacking ICMP packet
def icmp_packet(data):
    icmp_type, code, checksum = struct.unpack('! B B H', data[:4])
    return icmp_type, code, checksum, data[4:]

# Unpacking TCP segment
def tcp_segment(data):
    (src_port, dest_port, sequence, acknowledgement, offset_reserved_flag) = struct.unpack('! H H L L H', data[:14])
    offset = (offset_reserved_flag >> 12) * 4
    flag_urg = (offset_reserved_flag & 32) >> 5
    flag_ack = (offset_reserved_flag & 16) >> 4
    flag_psh = (offset_reserved_flag & 8) >> 3
    flag_rst = (offset_reserved_flag & 4) >> 2
    flag_syn = (offset_reserved_flag & 2) >> 1
    flag_fin = (offset_reserved_flag & 1)
    return src_port, dest_port, sequence, acknowledgement, flag_urg, flag_ack, flag_psh, flag_rst, flag_syn, flag_fin, data[offset:]

# Unpacking UDP segment
def udp_segment(data):
    src_port, dest_port, length = struct.unpack('! H H 2x, H', data[:8])
    return src_port, dest_port, length, data[8:]

# Formatting multi-line data (Eg: doesnt show 7000 characters on same line while showing the results)
def format_multi_line(prefix, string, size=80):
    size -= len(prefix)
    if isinstance(string, bytes):
        #converting strings  to hexadecimal bytes format
        string = ''.join(r'\x{:02x}'.format(byte) for byte in string)
        if size % 2:
            size -= 1
    return '\n'.join([prefix + line for line in textwrap.wrap(string, size)])

if __name__ == "__main__":
  main()


# 이중배열, 현재위치, 4방위, 거리(str)
def move_dog(board, cur_pos, direction, distance):
    dis = int(distance)
#     현재 위치
    ci, cj = cur_pos
#     이동 방향
    mi = 0
    mj = 0
    if direction == 'N':
        mi = -1
    elif direction == 'S':
        mi = 1
    elif direction == 'W':
        mj = -1
    else:
        mj = 1

    for i in range(dis):
#         이동
        ci += mi
        cj += mj

#         만약 실패조건을 만난다면 원래 위치를 전송
        if 0 > ci or 0 > cj or len(board) == ci or len(board[0]) == cj:
            return cur_pos
        elif board[ci][cj] == 'X' :
            return cur_pos
#     실패하지 않는다면 변경된 위치를 전송
    return (ci, cj)

def solution(park, routes):

# park -> 공원 배열
# routes -> 명령 배열
# 명령은 수행 불가능하면 실행하지 않는다

# 3*3 ~ 50*50
# 시작지는 S, 이동 가능은 O, 이동 불가는 X
# 명령은 최대 50개
# 명령 NSWE각 4방위
# 최대 9칸 이동함

# 리턴은 최종 좌표의 위치를 반환

#     실제로 사용할 맵
    board = [[] for _ in range(len(park))]
#     현재 로봇의 위치
    cur_pos = (0, 0)

    for i in range(len(park)):
        blocks = list(park[i])
        board[i] = blocks
        for j in range(len(blocks)):
            if blocks[j] == 'S':
                cur_pos = (i, j)
#     board, cur_pos를 설정

#     명령을 수행
    for order in routes:

        direction, distance = order.split(' ')

#         유효성을 검사하는 함수가 필요하다
        cur_pos = move_dog(board, cur_pos, direction, distance)

    answer = [cur_pos[0], cur_pos[1]]
    return answer


"""

383. Ransom Note

Given an arbitrary ransom note string and another string containing letters from all the magazines,
write a function that will return true if the ransom note can be constructed from the magazines ;
otherwise, it will return false.

Each letter in the magazine string can only be used once in your ransom note.

Note:
You may assume that both strings contain only lowercase letters.

canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true

"""
import collections

def ransom_note(note, available_chars):
    # using Counter
    note_count = collections.Counter(note)
    available_chars = collections.Counter(available_chars)
    for each_char in note:
        if note_count[each_char] > available_chars[each_char]:
            return False
    return True

# TC: O(n)
# SC: O(26)

ransom_note("a", "b")
ransom_note("aa", "ab")
ransom_note("aa", "aab")

def ransom_note_using_set(note, available_Chars):
    for i in set(note):
        if note.count(i) > magazine.count(i):
            # count takes O(n)
            return False
    return True

# TC: O(n^2)


import json
from urllib import response
from unittest import mock
from django.urls import reverse
import pytest
from apps.fyle.models import Expense, ExpenseGroup, Reimbursement, get_default_expense_group_fields, get_default_expense_state, \
    ExpenseGroupSettings, _group_expenses, get_default_ccc_expense_state
from apps.workspaces.models import Configuration, Workspace
from apps.tasks.models import TaskLog
from apps.fyle.tasks import create_expense_groups
from .fixtures import data

@pytest.mark.django_db()
def test_create_expense(create_temp_workspace):
    mock_expenes = data['expenses']
    expense_count = len(Expense.objects.filter(org_id='or79Cob97KSh'))
    Expense.create_expense_objects(
        mock_expenes
    )

    expense = Expense.objects.filter(org_id='or79Cob97KSh').order_by('created_at')
    assert len(expense) == expense_count+2

    expense = expense.last()
    assert expense.employee_email == 'jhonsnow@fyle.in'
    assert expense.currency == 'USD'
    assert expense.fund_source == 'PERSONAL'

def test_default_fields():
    expense_group_field = get_default_expense_group_fields()
    expense_state = get_default_expense_state()
    ccc_expense_state = get_default_ccc_expense_state()

    assert expense_group_field == ['employee_email', 'report_id', 'claim_number', 'fund_source']
    assert expense_state == 'PAYMENT_PROCESSING'
    assert ccc_expense_state == 'PAID'

@pytest.mark.django_db
def test_expense_group_settings(create_temp_workspace):
    payload = data['expense_group_setting_payload']

    ExpenseGroupSettings.update_expense_group_settings(
        payload, 3
    )

    settings = ExpenseGroupSettings.objects.last()

    assert settings.expense_state == 'PAYMENT_PROCESSING'
    assert settings.ccc_expense_state == 'PAID'
    assert settings.ccc_export_date_type == 'spent_at'

def test_create_expense_groups_by_report_id_fund_source_spent_at(db):
    expenses = data['expenses_spent_at']

    expense_objects = Expense.create_expense_objects(expenses)

    configuration = Configuration.objects.get(workspace_id=1)
    workspace = Workspace.objects.get(id=1)

    expense_group_setting = ExpenseGroupSettings.objects.get(workspace_id=1)
    expense_group_setting.reimbursable_export_date_type = 'spent_at'
    reimbursable_expense_group_fields = expense_group_setting.reimbursable_expense_group_fields
    reimbursable_expense_group_fields.append('spent_at')
    expense_group_setting.reimbursable_expense_group_fields = reimbursable_expense_group_fields
    expense_group_setting.save()

    assert len(expense_objects) == 3

    ExpenseGroup.create_expense_groups_by_report_id_fund_source(expense_objects, configuration, 1)

    expense_group = ExpenseGroup.objects.filter(workspace=workspace).order_by('-created_at').first()

    assert expense_group.expenses.count() == 2

def test_create_expense_groups_by_report_id_fund_source(db):
    expenses = data['expenses']

    expense_objects = Expense.create_expense_objects(expenses)

    configuration = Configuration.objects.get(workspace_id=49)
    workspace = Workspace.objects.get(id=1)

    ExpenseGroup.create_expense_groups_by_report_id_fund_source(expense_objects, configuration, 49)

    expense_groups = ExpenseGroup.objects.filter(workspace=workspace)

    assert len(expense_groups) == 2

    expense_group_setting = ExpenseGroupSettings.objects.get(workspace_id=49)
    corporate_credit_card_expense_group_fields = expense_group_setting.corporate_credit_card_expense_group_fields
    corporate_credit_card_expense_group_fields.append('dummy')
    expense_group_setting.corporate_credit_card_expense_group_fields = corporate_credit_card_expense_group_fields
    expense_group_setting.save()

    ExpenseGroup.create_expense_groups_by_report_id_fund_source(expense_objects, configuration, 49)

    expense_groups = ExpenseGroup.objects.filter(workspace=workspace)

    assert len(expense_groups) == 2

def test_create_reimbursement(db):

    reimbursements = data['reimbursements']

    Reimbursement.create_or_update_reimbursement_objects(reimbursements=reimbursements, workspace_id=1)

    pending_reimbursement = Reimbursement.objects.get(reimbursement_id='reimgCW1Og0BcM')

    pending_reimbursement.state = 'PENDING'
    pending_reimbursement.settlement_id= 'setgCxsr2vTmZ'

    reimbursements[0]['is_paid'] = True

    Reimbursement.create_or_update_reimbursement_objects(reimbursements=reimbursements, workspace_id=1)

    paid_reimbursement = Reimbursement.objects.get(reimbursement_id='reimgCW1Og0BcM')
    paid_reimbursement.state == 'PAID'

def test_get_last_synced_at(db):

    reimbursement = Reimbursement.get_last_synced_at(1)

    assert reimbursement.workspace_id == 1
    assert reimbursement.settlement_id == 'setqi0eM6HUgZ'
    assert reimbursement.state == 'COMPLETE'


import logging, time, json

from flask import Flask, request, Response, make_response
from flask_cors import CORS
from flask_expects_json import expects_json

from randomizer.iogr_rom import Randomizer, generate_filename, VERSION
from randomizer.models.randomizer_data import RandomizerData as Settings

from config import Config
from database import Database

from encoder import JSONEncoder
from models.http.seed_request import SeedRequest
from models.http.seed_response import SeedResponse
from models.http.version_response import VersionResponse
from models.patch import Patch
from models.spoiler import Spoiler
from models.result import Result

logging.basicConfig(level=logging.DEBUG, filename="output.log")

app = Flask(__name__)
app.config['CORS_HEADERS'] = 'Content-Type'
app.json_encoder = JSONEncoder

cors = CORS(app, resources={
    r"/v1/*": {"origins": "*"}
})

config = Config()
database = Database(logging, config)

@app.route("/v1/seed/generate", methods=["POST"])
@expects_json(SeedRequest.schema)
def generateSeed() -> Response:
    request_data = SeedRequest(request.get_json())
    settings = Settings(request_data.seed, request_data.difficulty, request_data.goal,
                        request_data.logic, request_data.statues, request_data.statue_req,
                        request_data.enemizer, request_data.start_location, request_data.firebird,
                        request_data.ohko, request_data.red_jewel_madness, request_data.allow_glitches,
                        request_data.boss_shuffle, request_data.open_mode, request_data.z3_mode,
                        request_data.overworld_shuffle, request_data.entrance_shuffle, request_data.generate_race_rom,
                        request_data.fluteless, request_data.sprite, request_data.dungeon_shuffle)

    randomizer = Randomizer("./data/gaia.bin")
    result = __generate(randomizer, settings, request_data.generate_race_rom, 0, request_data.hide_settings)
    if result is None:
        return make_response("Failed to generate a seed", 500)

    if result.patch is None:
        return make_response("Failed to generate a seed", 500)

    patch = result.patch
    spoiler = result.spoiler
    permalink = result.permalink

    response = SeedResponse(patch.patch, patch.patchName, patch.version, permalink)
    if spoiler is not None:
        response.spoiler = spoiler.spoiler
        response.spoilerName = spoiler.spoilerName

    if permalink is not None:
        response.permalink_id = permalink

    return make_response(response.to_json(), 200)

@app.route("/v1/seed/permalink/<link_id>", methods=["GET"])
def getPermalinkedSeed(link_id: str = "") -> Response:
    try:
        if link_id == "":
            return make_response("Did not send permalink ID", 401)

        logging.info("Attempting to get permalink: " + link_id)
        document = database.get(link_id)
        if document is None:
            return make_response("Permalink Not Found", 404)

        return make_response(json.dumps(document, cls=JSONEncoder), 200)
    except Exception as e:
        logging.exception(e)
        return make_response("An unknown error has occurred", 500)

@app.route("/v1/api/version", methods=["GET"])
def getRandomizerVersion() -> Response:
    version = VersionResponse(VERSION)
    return make_response(version.to_json())

def __generate(randomizer: Randomizer, settings: Settings, race: bool = False, retries: int = 0, hide_settings: bool = False) -> Result:
    if retries >= 3:
        return None

    patch = None
    permalink = None
    spoiler = None

    try:
        patch_start_time = time.perf_counter()
        logging.info(f"({settings.seed}) Generating patch ({retries + 1} / 3)...")
        logging.info(f"({settings.seed}) Settings: {str(request.get_json())}")

        patch = __generatePatch(randomizer, settings, hide_settings)
        if patch is None:
            logging.info(f"({settings.seed}) Failed to generate patch in {time.perf_counter() - patch_start_time} seconds!")
            return __generate(randomizer, settings, race, retries + 1, hide_settings)
        else:
            logging.info(f"({settings.seed}) Generated patch in {time.perf_counter() - patch_start_time} seconds!")

        if not race:
            logging.info(f"({settings.seed}) Race Mode off, generating spoiler...")
            spoiler_start_time = time.perf_counter()
            spoiler = __generateSpoiler(randomizer, settings, hide_settings)
            logging.info(f"({settings.seed}) Generated spoiler in {time.perf_counter() - spoiler_start_time} seconds!")
        else:
            logging.info(f"({settings.seed}) Race Mode on, not generating spoiler...")

        if database.enabled:
            logging.info(f"({settings.seed}) Generating permalink...")
            permalink_start_time = time.perf_counter()
            permalink = database.create(patch, spoiler, settings, hide_settings)
            logging.info(
                f"({settings.seed}) Permalink generated in {time.perf_counter() - permalink_start_time} seconds!")

        return Result(patch, spoiler, permalink)

    except Exception as e:
        logging.exception(e)
        return __generate(randomizer, settings, race, retries + 1, hide_settings)

def __generateFileName(settings: Settings, extension: str, obfuscate_options: bool = False) -> str:
    if obfuscate_options:
        file_name = "IoGR_V" + VERSION + "_" + str(settings.seed) + "." + extension
        return file_name
    return generate_filename(settings, extension)

def __generatePatch(randomizer: Randomizer, settings: Settings, hide_settings: bool = False) -> Patch:
    patch_filename = __generateFileName(settings, "sfc", hide_settings)
    patch = randomizer.generate_rom(patch_filename, settings)
    return Patch(patch, patch_filename, VERSION)

def __generateSpoiler(randomizer: Randomizer, settings: Settings, hide_settings: bool = False) -> Spoiler:
    spoiler_filename = __generateFileName(settings, "txt", hide_settings)
    spoiler = randomizer.generate_spoiler()
    return Spoiler(spoiler, spoiler_filename)

if __name__ == "__main__":
    app.debug = config.DEBUG
    app.run(host="0.0.0.0", port=5000)


import kivy
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import  Button

class Tela1(BoxLayout):
    def on_press_bt(self):
        janela.root_window.remove_widget(janela.root)
        janela.root_window.add_widget(Tela2())
    def __init__(self, **kwargs):
        super(Tela1, self).__init__(**kwargs)
        self.orientation = "vertical"
        bt1 = Button(text="CLICK")
        bt1.on_press = self.on_press_bt
        bt2 = Button(text="CLICK2")
        bt3 = Button(text="CLICK3")
        self.add_widget(bt1)
        self.add_widget(bt2)
        self.add_widget(bt3)

class Tela2(BoxLayout):
    def on_press_bt(self):
        janela.root_window.remove_widget(janela.root)
        janela.root_window.add_widget(Tela1())

    def __init__(self, **kwargs):
        super(Tela2, self).__init__(**kwargs)
        self.orientation = "vertical"
        bt = Button (text= "clique")
        bt.on_press = self.on_press_bt
        self.add_widget(bt)

class PY(App):
    def build(self):
        return Tela1()

janela = PY()
janela.run()


from functools import wraps
from time import time

def timing(f):
    """
    From https://stackoverflow.com/a/27737385/1775741
    """
    @wraps(f)
    def wrap(*args, **kw):
        ts = time()
        result = f(*args, **kw)
        te = time()
        dur = te - ts
        print('func:{!r} args:[{!r}, {!r}] took: {:2.4f} sec'.format(
            f.__name__, args, kw, dur)
        )
        return dur, result
    return wrap


class Solution:
    def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
        if k<=1:return 0
        ans = 0
        prod = 1
        left=-1
        for i in range(len(nums)):
            prod*=nums[i]
            while  prod>=k:
                left+=1
                prod/=nums[left]
            ans+=i-left
        return ans

leetcode/0713.乘积小于K的子数组/0713-乘积小于K的子数组.py


import matplotlib.pyplot as plt
def corelation(px,py):
    n=len(px)
    sumx=0
    sumy=0
    sumXY=0
    sumX2=0
    sumY2=0
    for i in range (n):
        x = px[i]
        y = py[i]
        sumx += x
        sumy += y
    meanx=sumx/n
    meany=sumy/n

    for i in range(n):
         X=px[i]-meanx
         Y=py[i]-meany

         sumX2+= X*X
         sumY2+= Y*Y
         sumXY+= X*Y
    print(sumX2,sumY2,sumXY)
    r=(sumXY)/(sumX2*sumY2)**(1/2)
    return r
x=[105,104,102,101,100,99,98,96,93,92]
y=[101,103,100,98,95,96,104,92,97,94]
result=corelation(x,y)
print(result)
#plt.scatter(x,y,color='red',marker='o')
plt.bar(x,y,color='red')
plt.show()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__copyright__ = """ This code is licensed under the 3-clause BSD license.
Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.
See LICENSE.txt for details.
"""
"""
Functions that abstract sending and receiving data
between a server and a client.
The data is now serialized using json.
"""
import json
import struct
import typing
from socket import socket as Socket

def send_data(data: typing.Any, socket: Socket) -> None:
    """
    Serialise and send data through a socket.
    The size of the dataset is prepended to the real data,
    so that the receiver knows how large is the dataset.
    Retry until it is done.
    """
    serialized = json.dumps(data)
    raw_data = bytes(serialized, encoding="utf-8")
    sizeinfo = struct.pack("!i", len(raw_data))  # Sending an integer

    socket.sendall(sizeinfo)
    socket.sendall(raw_data)

def recv_data(connection: Socket) -> typing.Any:
    """
    Read data from a socket.
    It is expected that the first datum that comes out
    will be the size of the data sent through.
    """
    buf = bytearray()
    while len(buf) < 4:
        buf += connection.recv(4 - len(buf))
    (size_to_receive,) = struct.unpack("!i", buf)
    size_received = 0
    data_received = bytearray()
    while len(data_received) < size_to_receive:
        chunksize = min(4096, size_to_receive - size_received)
        data_received += connection.recv(chunksize)
    data_decoded = data_received.decode("utf-8")

    return json.loads(data_decoded)


from django.shortcuts import render

# End points:
def index(request):
    return render(request,'index.html')

def submission(request):
    # Taking values:
    text = request.POST.get('text', 'default')
    remover = request.POST.get('remover', 'off')
    capital = request.POST.get('capital', 'off')
    lower = request.POST.get('lower', 'off')
    counter = request.POST.get('counter', 'off')
    # Logic implementation:
    puncs = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
    if remover=="on":
        result=""
        for char in text:
            if char not in puncs:
                result = result + char
                text = result
    if capital=="on":
        result = ""
        for char in text:
            result = result + char.upper()
            text =result
    if lower=="on":
        result = ""
        for char in text:
            result = result + char.lower()
            text = result
    if counter=="on":
        resultone = 0
        for char in text:
            resultone = resultone+1
        final = {'clear':resultone}
        return render(request,'submission.html',final)
    if text=="":
        return render(request,'error.html')
    params = {'clear': result}
    return render(request, 'submission.html', params)

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


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

import config
import math
import numpy as np
from twisted.internet import reactor, threads
from score import score

class ProgressBox:
    def __init__(self, nPossibilities):
        self.nPossibilities = nPossibilities
        self.nCompleted = 0

    def getProgress(self):
        return float(self.nCompleted) / self.nPossibilities

    def getPercentProgress(self):
        return (self.nCompleted * 100) / self.nPossibilities

    def addCompleted(self):
        if self.nCompleted < self.nPossibilities:
            self.nCompleted = self.nCompleted + 1

def produceMatrix(chosenSections):
    schedule = np.empty(7, dtype=object)
    for i in range(0,7):
        schedule[i] = np.empty(config.SLOTS_PER_DAY, dtype=object)

    for section in chosenSections:
        sessions = section.sessions
        for sess in sessions:
            tss = sess.timeslots
            for ts in tss:
                sday = int(math.floor(ts / config.SLOTS_PER_DAY))
                sslot = ts % config.SLOTS_PER_DAY

                if schedule[sday][sslot] is not None:
                    return None

                schedule[sday][sslot] = sess

    return schedule

def solve2(socket, nCourse, sectionsForCourse, chosenSections, timeEquivalencies, progressBox, start, end, freeDays):
    # TODO: A better implementation here?
    if nCourse <= 3:
        progress = progressBox.getPercentProgress()
        reactor.callFromThread(socket.sendProgress, progress)

        cancelled = threads.blockingCallFromThread(reactor, socket.isCancelled)
        if cancelled:
            raise ValueError("The request has been cancelled")

    if nCourse == len(sectionsForCourse):
        schedule = produceMatrix(chosenSections)
        progressBox.addCompleted()
        progress = progressBox.getPercentProgress()

        if schedule is not None:
            sc = score(schedule, start, end, freeDays)

            # Copy sections
            chosenSectionsForOutput = []
            for chosenSection in chosenSections:
                chosenSectionsForOutput.append(chosenSection)

            reactor.callFromThread(socket.sendProgress, progress, chosenSectionsForOutput, timeEquivalencies, sc)

        return

    course = sectionsForCourse[nCourse][0]
    sections = sectionsForCourse[nCourse][1]

    for section in sections:
        chosenSections[nCourse] = section
        solve2(socket, nCourse + 1, sectionsForCourse, chosenSections, timeEquivalencies, progressBox, start, end, freeDays)

def startSolution(socket, courses, start, end, freeDays):
    solutions = []
    sectionsForCourse = []
    timeEquivalencies = {}

    nPossibilities = 1
    for course in courses:
        if course is not None:
            sectionsForThisCourse = {}

            for section in course.sections:
                hash = section.time_hash

                if not hash in sectionsForThisCourse:
                    sectionsForThisCourse[hash] = section
                else:
                    timeEquivalentSection = sectionsForThisCourse[hash]

                    if not section in timeEquivalencies:
                        timeEquivalencies[timeEquivalentSection] = []

                    timeEquivalencies[timeEquivalentSection].append(section)

            sectionList = [value for key,value in sectionsForThisCourse.iteritems()]
            sectionsForCourse.append((course, sectionList))

            nPossibilities = nPossibilities * len(sectionList)

    chosenSections = np.empty(len(sectionsForCourse), dtype=object)
    progressBox = ProgressBox(nPossibilities)

    solve2(socket, 0, sectionsForCourse, chosenSections, timeEquivalencies, progressBox, start, end, freeDays)

    reactor.callFromThread(socket.sendCompletion)


from django.urls import re_path

from . import views

lang_urlpatterns = [
    re_path(r"^recurring/?$", views.contribute, name="recurring_payment_initial"),
    re_path(
        r"^recurring/subscription/?$",
        views.contribute,
        name="recurring_payment_subscription",
    ),
    re_path(r"^terms/?$", views.payment_terms, name="payment_terms"),
    re_path(
        r"^recurring/management/?$",
        views.recurring_payment_management,
        name="recurring_payment_management",
    ),
]


"""Definition of the documentRRHH contenttype
"""
from zope.interface import implements
from Products.Archetypes import atapi
from Products.ATContentTypes.content import folder
from Products.ATContentTypes.content import schemata
from notes.rrhh.interfaces import IDocumentRRHH
from notes.rrhh.config import PROJECTNAME
from Products.ATVocabularyManager import NamedVocabulary

DocumentRRHHSchema = folder.ATFolderSchema.copy() + atapi.Schema((

            atapi.TextField(
                name='body',
                allowable_content_types=('text/plain',
                                               'text/structured',
                                               'text/html',),
                 default_output_type='text/x-html-safe',
                 widget=atapi.RichWidget(
                     label='Body',
                     label_msgid='label_body',
                     i18n_domain='notes.rrhh',
                     rows=40,
                 ),
             required=False,
             searchable=True,
             ),

            #CATEGORIES
            #atapi.LinesField(
            #    name='categoryRRHH',
            #    widget=atapi.InAndOutWidget(
            #        format="select",
            #        label_msgid='categoryRRHH_label',
            #        description_msgid='categoryRRHH_help',
            #        i18n_domain='notes.rrhh',
            #    ),
            #    languageIndependent=True,
            #    required=False,
            #    schemata="categorization",
            #    vocabulary=NamedVocabulary('categoryRRHH_keywords'),
            #    enforceVocabulary=True,
            #),

))

DocumentRRHHSchema['title'].storage = atapi.AnnotationStorage()
DocumentRRHHSchema['description'].storage = atapi.AnnotationStorage()

# Hide default category option
DocumentRRHHSchema['description'].widget.visible = {'view': 'invisible', 'edit': 'invisible'}
DocumentRRHHSchema['language'].widget.visible = {'view': 'invisible', 'edit': 'invisible'}
DocumentRRHHSchema['relatedItems'].widget.visible = {'view': 'invisible', 'edit': 'invisible'}
DocumentRRHHSchema['location'].widget.visible = {'view': 'invisible', 'edit': 'invisible'}

schemata.finalizeATCTSchema(DocumentRRHHSchema, folderish=True, moveDiscussion=False)

class DocumentRRHH(folder.ATFolder):
    """Description of the documentRRHH"""
    implements(IDocumentRRHH)

    meta_type = "DocumentRRHH"
    schema = DocumentRRHHSchema

    title = atapi.ATFieldProperty('title')
    description = atapi.ATFieldProperty('description')

atapi.registerType(DocumentRRHH, PROJECTNAME)


import os, shlex
import tempfile, subprocess

def editContent(content=None):
    """ Edit the content with vi editor, the input
    'content' is byte, the returned one is byte also
    """
    tmpfile = tempfile.NamedTemporaryFile(delete=False)
    if content:
        tmpfile.write(content)
        tmpfile.flush()
    cmd = 'vi ' + tmpfile.name
    p = subprocess.Popen(shlex.split(cmd))
    p.communicate()
    p.wait()

    # vim may delete the original file,
    # so we reopen the file to read.
    content = open(tmpfile.name, 'rb').read()
    os.unlink(tmpfile.name)
    return content


size = int(input("How many numbers will you enter ? : "))
list1 = []
for i in range(size):
    number = int(input("Please neter your number : "))
    list1.append(number)

list1.sort()
list2 = [i for i in range(min(list1), max(list1))]
diffrences = [i for i in list2 if i not in list1]

pozitif = min([i for i in diffrences if i > 0])
print(pozitif)


import logging
from _thread import get_ident

from AccessControl.class_init import InitializeClass
from AccessControl.SecurityInfo import ClassSecurityInfo
from Acquisition import aq_base
from OFS.ObjectManager import ObjectManager
from ZODB.POSException import ConflictError
from zope.component import queryUtility

from .interfaces import ISkinsTool

logger = logging.getLogger('CMFCore.Skinnable')

_MARKER = object()  # Create a new marker object.

SKINDATA = {}  # mapping thread-id -> (skinobj, skinname, ignore, resolve)

class SkinDataCleanup:
    """Cleanup at the end of the request."""
    def __init__(self, tid):
        self.tid = tid

    def __del__(self):
        tid = self.tid
        # Be extra careful in __del__
        if SKINDATA is not None:
            if tid in SKINDATA:
                del SKINDATA[tid]

class SkinnableObjectManager(ObjectManager):

    security = ClassSecurityInfo()

    def __getattr__(self, name):
        """
        Looks for the name in an object with wrappers that only reach
        up to the root skins folder.

        This should be fast, flexible, and predictable.
        """
        if not name:
            raise AttributeError(name)
        if name[0] not in ('_', '@', '+') and not name.startswith('aq_'):
            sd = SKINDATA.get(get_ident())
            if sd is not None:
                ob, _skinname, ignore, resolve = sd
                if name not in ignore:
                    if name in resolve:
                        return resolve[name]
                    subob = getattr(ob, name, _MARKER)
                    if subob is not _MARKER:
                        # Return it in context of self, forgetting
                        # its location and acting as if it were located
                        # in self.
                        retval = aq_base(subob)
                        resolve[name] = retval
                        return retval
                    else:
                        ignore[name] = 1
        raise AttributeError(name)

    @security.private
    def getSkin(self, name=None):
        """Returns the requested skin.
        """
        skinob = None
        stool = queryUtility(ISkinsTool)
        if stool is not None:
            if name is not None:
                skinob = stool.getSkinByName(name)
            if skinob is None:
                skinob = stool.getSkinByName(stool.getDefaultSkin())
                if skinob is None:
                    skinob = stool.getSkinByPath('')
        return skinob

    @security.public
    def getSkinNameFromRequest(self, REQUEST=None):
        """Returns the skin name from the Request."""
        if REQUEST is None:
            return None
        stool = queryUtility(ISkinsTool)
        if stool is not None:
            name = REQUEST.get(stool.getRequestVarname(), None)
            if not name or name not in stool.getSkinSelections():
                return None
            return name

    @security.public
    def changeSkin(self, skinname, REQUEST=None):
        """Change the current skin.

        Can be called manually, allowing the user to change
        skins in the middle of a request.
        """
        skinobj = self.getSkin(skinname)
        if skinobj is not None:
            tid = get_ident()
            SKINDATA[tid] = (skinobj, skinname, {}, {})
            if REQUEST is not None:
                REQUEST._hold(SkinDataCleanup(tid))

    @security.public
    def getCurrentSkinName(self):
        """Return the current skin name.
        """
        sd = SKINDATA.get(get_ident())
        if sd is not None:
            _ob, skinname, _ignore, _resolve = sd
            if skinname is not None:
                return skinname
        # nothing here, so assume the default skin
        stool = queryUtility(ISkinsTool)
        if stool is not None:
            return stool.getDefaultSkin()
        # and if that fails...
        return None

    @security.public
    def clearCurrentSkin(self):
        """Clear the current skin."""
        tid = get_ident()
        if tid in SKINDATA:
            del SKINDATA[tid]

    @security.public
    def setupCurrentSkin(self, REQUEST=None):
        """
        Sets up skindata so that __getattr__ can find it.

        Can NOT be called manually to change skins in the middle of a
        request! Use changeSkin for that.
        """
        if REQUEST is None:
            return
        if get_ident() in SKINDATA:
            # Already set up for this request.
            return
        skinname = self.getSkinNameFromRequest(REQUEST)
        try:
            self.changeSkin(skinname, REQUEST)
        except ConflictError:
            raise
        except Exception:
            # This shouldn't happen, even if the requested skin
            # does not exist.
            logger.exception('Unable to setupCurrentSkin()')

    def _checkId(self, id, allow_dup=0):
        """
        Override of ObjectManager._checkId().

        Allows the user to create objects with IDs that match the ID of
        a skin object.
        """
        superCheckId = SkinnableObjectManager.inheritedAttribute('_checkId')
        if not allow_dup:
            # Temporarily disable skindata.
            # Note that this depends heavily on Zope's current thread
            # behavior.
            tid = get_ident()
            sd = SKINDATA.get(tid)
            if sd is not None:
                del SKINDATA[tid]
            try:
                base = getattr(self, 'aq_base', self)
                if not hasattr(base, id):
                    # Cause _checkId to not check for duplication.
                    return superCheckId(self, id, allow_dup=1)
            finally:
                if sd is not None:
                    SKINDATA[tid] = sd
        return superCheckId(self, id, allow_dup)

InitializeClass(SkinnableObjectManager)


# coding: utf-8

# 一応動くが 40min 要する.
#
# n を平方数とする.
# n を分割した合計を s とすると,
# s = Σ(10^e_i * a_i) と書ける. (e_i は a_i の桁数 - 1)
# 10^e = 1 mod 9 より s mod 9 は n の分割方法に依らず一定.
#
# よって, n mod 9 = s mod 9
# √n = s であるためには, √n = n mod 9 より
# n = 0, 1 mod 9

# from itertools import chain, combinations
# from math import log10

# def gen_digit(n):
#     nums = []

#     while n > 0:
#         nums.append(n % 10)
#         n //= 10
#     return reversed(nums)

# def subsets(iterable):
#     '''nums の部分集合を返す.'''

#     s = list(iterable)
#     return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))

# def partitions(iterable):
#     seq = list(iterable)
#     n = len(seq)
#     for i in subsets(range(1, n)):
#         yield [seq[i:j] for i, j in zip((0, ) + i, i + (n, ))]

# def list2num(nums):
#     s = 0
#     for n in nums:
#         s = s * 10 + n
#     return s

# def is_sNumber(n):
#     '''n が sNumber か調べる. ただし n は平方数であること.'''
#     d = int(log10(n)) + 1
#     for ns in partitions(gen_digit(n)):
#         # i 桁の数 n に対して分割された数は i/2 桁を含む必要がある.
#         if not any(len(k) >= d // 2 for k in ns):
#             continue
#         split_nums = [list2num(i) for i in ns]
#         sum_split = sum(split_nums)
#         if n == sum_split**2:
#             # print(n, split_nums)
#             return True
#     return False

# スレッドで見つけた, より効率のよいコード
def sum_partition(a, b):
    '''bを分割して合計したものを a と等しくできるか判定する'''
    if a == b:
        return True
    d = 10
    while d < b:
        p, q = b // d, b % d
        if 0 < a - q <= p and sum_partition(a - q, p):
            return True
        d *= 10
    return False

def main():
    N = 10**12
    return sum(i**2
               for i in filter(lambda x: x % 9 <= 1, range(4,
                                                           int(N**0.5) + 1))
               if sum_partition(i, i**2))

if __name__ == '__main__':
    print(main())