# 定义一个烤地瓜的类 属性 行为(方法)
class kaodigua:

    # 初始化函数
    def __init__(self):  # 传参内容,几分熟的地瓜 返回熟度范围
        self.cookedLevel = 0
        self.cookedString = "生"
        self.condiments = []

    # 添加配料的方法， __str__()
    def __str__(self):
        msg = self.cookedString + "地瓜"
        if len(self.condiments) > 0:
            msg = msg + "("
            for temp in self.condiments:
                msg = msg + temp + ","
            msg = msg.strip(",")

            msg = msg + ")"
        return msg

    # 添加烤地瓜的方法
    # input() #1-3生的 4-6 半生不熟 7-10熟了 10以上: 烤成灰了
    def cook(self, time):
        self.cookedLevel += time
        if self.cookedLevel > 10:
            self.cookedString = "烤成灰了"
        elif self.cookedLevel > 7:
            self.cookedString = "烤好了"
        elif self.cookedLevel > 4:
            self.cookedString = "半生不熟"
        else:
            self.cookedString = "生的"

    # 添加酱料
    def addCondiments(self, condiments):
        self.condiments.append(condiments)

# 进行测试鹿子的好坏
mySweetPotato = kaodigua()
print("------有了一个地瓜，还没有烤-----")
print(mySweetPotato.cookedLevel)
print(mySweetPotato.cookedString)
print(mySweetPotato.condiments)

print("------接下来要进行烤地瓜了-----")
print("------地瓜已经烤了4分钟-----")
mySweetPotato.cook(4)  # 烤4分钟
print(mySweetPotato)
print("------地瓜又已经烤了3分钟-----")
mySweetPotato.cook(3)  # 又烤了3分钟
print(mySweetPotato)
print("------接下来要添加配料-番茄酱------")
mySweetPotato.addCondiments("番茄酱")
print(mySweetPotato)
print("------地瓜又已经烤了5分钟-----")
mySweetPotato.cook(5)  # 又烤了5分钟
print(mySweetPotato)
print("------接下来要添加配料-芥末酱------")
mySweetPotato.addCondiments("芥末酱")
print(mySweetPotato)


# Analyze.py

fn = "Benzene_raman_vib.spm"
data = []
with open(fn)as f:
	for line in f.readlines()[30:60]:
		row = line.split()[1:3]
		floatrow = []
		for r in row: floatrow.append(float(r))
		if floatrow[-1] > 1: data.append(floatrow)

outfile = "results.csv"
with open(outfile, 'w') as f:
	f.write("Frequency (cm^-1),Intensity\n")
	for d in data: f.write("{},{}\n".format(d[0],d[1]))


from django.urls import re_path, include, path

from driver_app.views import RegistrationAPIView
from driver_app.views import LoginAPIView
from driver_app.views import DriverViewSet

app_name = 'driver_app'
urlpatterns = [
    re_path(r'^sign_up/?$', RegistrationAPIView.as_view(), name='driver_sign_up'),
    re_path(r'^login/?$', LoginAPIView.as_view(), name='driver_login'),
    path('update_profile/', DriverViewSet.as_view({'patch': 'update_profile'}), name='driver-update-profile'),
    path('add_vechicle/', DriverViewSet.as_view({'put': 'add_vechicle'}), name='driver-add-vechicle'),
    path('orders/', DriverViewSet.as_view({'get': 'orders'}), name='driver-orders'),
    path('accept_order/<int:order_id>/', DriverViewSet.as_view({'put': 'accept_order'}), name='driver-accept-order'),
    path('drop_order/<int:order_id>/', DriverViewSet.as_view({'put': 'drop_order'}), name='driver-drop-order'),
    path('pick_order/<int:order_id>/', DriverViewSet.as_view({'put': 'pick_order'}), name='driver-pick-order'),
    path('add_photo/', DriverViewSet.as_view({'put': 'add_photo'}), name='driver-add-photo'),
]


import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression

# Load the Excel file
excel_file_path = "Data.xlsx"

# Load Yard Locations Data
yard_locations_data = pd.read_excel(excel_file_path, sheet_name="Yard Locations")

# Load Past In and Out Data
past_in_out_data = pd.read_excel(excel_file_path, sheet_name="Past In and Out Container Data")

# Load Incoming Container Data
incoming_container_data = pd.read_excel(excel_file_path, sheet_name="Incoming Conatiners")

# Filter and select necessary columns for machine learning predictions
selected_columns_yard = ["Container Size", "Location", "Area", "Row", "Bay", "Level"]
filtered_yard_data = yard_locations_data[selected_columns_yard]

selected_columns_past = ["CON_NUM", "IN_TIME", "OUT_TIME", "VALIDITY"]
filtered_past_in_out_data = past_in_out_data[selected_columns_past]

selected_columns_incoming = ["ID", "IN_TIME", "STATUS"]
filtered_incoming_container_data = incoming_container_data[selected_columns_incoming]

# Merge filtered dataframes
merged_data = pd.merge(filtered_incoming_container_data, filtered_past_in_out_data, on="ID")

# Prepare features and target variable
X = merged_data[["ID", "IMPORT_EXPORT", "CON_SIZE"]]  # Features: ID, IMPORT_EXPORT, and CON_SIZE
y = merged_data["Location"]  # Target variable: Assigned Location

# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Initialize and train a Linear Regression model
model = LinearRegression()
model.fit(X_train, y_train)

# Now, let's predict the location based on the given attributes
input_data = pd.DataFrame({
    "ID": [123],               # Example: Container ID
    "IMPORT_EXPORT": [2],      # Example: 2 corresponds to Export
    "CON_SIZE": [20]           # Example: 20 ft container size
})

# Use the trained model to predict the location
predicted_location = model.predict(input_data)

print("Predicted Location:", predicted_location)


import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from get_KONICA_data import get_KONICA_data
import json
import os

# Sigmoid函数
def sigmoid(x, k, x0):
    return 1 / (1 + np.exp(-k * (x - x0)))
# root_path = r'B:\Datasets\Temporal_Flicker_Meter_log\deltaL_L_2s\2023-12-17-05-06-02'
# root_path = r'B:\Datasets\Temporal_Flicker_Meter_log\deltaL_L_5s\2023-12-18-01-08-47'
root_path = r'B:\Datasets\Temporal_Flicker_Meter_log\deltaL_L_10s\2023-12-18-17-18-03'
with open(os.path.join(root_path, 'config.json'), 'r') as fp:
    config_data = json.load(fp)
with open(r'B:\Py_codes\VRR_Real\dL_L\Temporal_Results/dl_L_results_10s.json', 'r') as fp:
    json_result_dict = json.load(fp)
Temporal_L_array = np.array(json_result_dict['L'])
Temporal_dL_array = np.array(json_result_dict['dL'])
Temporal_abnormal_array = np.array(json_result_dict['abnormal'])
size_num, vrr_f_num,repeat_num, color_num = Temporal_L_array.shape
Temporal_dL_L_array = Temporal_dL_array / Temporal_L_array
x_fit = np.linspace(np.min(np.log10(Temporal_L_array))-2, np.max(np.log10(Temporal_L_array))+2, 100)
VRR_Frequency_list = config_data['change_params']['VRR_Frequency']
Size_list = config_data['change_params']['Size']
initial_guess_for_k = 1.0
initial_guess_for_x0 = 0.0
p0 = [initial_guess_for_k, initial_guess_for_x0]
fig1, ax1 = plt.subplots(figsize=(8,6))
for size_i in range(size_num):
    for vrr_f_i in range(vrr_f_num):
        current_L_array = Temporal_L_array[size_i, vrr_f_i, :, :].mean(axis=0)
        current_dl_L_array = Temporal_dL_L_array[size_i, vrr_f_i, :, :].mean(axis=0)
        x = np.log10(current_L_array)
        y = current_dl_L_array
        popt, pcov = curve_fit(sigmoid, x, y, p0=p0)

        # 绘制散点和拟合曲线
        plt.scatter(x, y)
        plt.scatter(x, y, label=f'Size {Size_list[size_i]} VRR_F {VRR_Frequency_list[vrr_f_i]}')
        # plt.plot(x, y, label=f'Size {Size_list[size_i]} VRR_F {VRR_Frequency_list[vrr_f_i]}', linewidth=0.5)
        # plt.plot(x_fit, sigmoid(x_fit, *popt),
        #          label=f'Fit - Size {Size_list[size_i]} VRR_F {VRR_Frequency_list[vrr_f_i]}', linestyle='--')

# Fit all:
current_L_array = Temporal_L_array.mean(axis=2).flatten()
current_dl_L_array = Temporal_dL_L_array.mean(axis=2).flatten()
x = np.log10(current_L_array)
y = current_dl_L_array
popt, pcov = curve_fit(sigmoid, x, y, p0=p0)

# 绘制拟合曲线
plt.plot(x_fit, sigmoid(x_fit, *popt), label=f'Fit - All Sizes', linewidth=4, color='red')

plt.legend(bbox_to_anchor=(1.05, 0.5), loc='center left', borderaxespad=0., prop={'size': 10})
pos1 = ax1.get_position()
pos1.x1 = 0.7
ax1.set_position(pos1)
plt.title('Sigmoid Fit for All Sizes')
plt.xlabel('log10(Luminance)')
plt.ylabel('deltaL/L')
plt.show()


#!/usr/bin/env python3

"""
Downloads Alpine latest iso for ARM, and builds a working headless filesystem
    for a Raspberry PI, with Ansible.
"""
import argparse
import sys

from elevate import elevate
import logging
import os
import os.path
import re
from urllib.parse import urlparse
import shutil
import tempfile
import urllib
import subprocess
from util import *

# Set up logging
logger = logging.getLogger('make_alpine_rpi')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)

# For now use static URL
alpine_url = 'http://dl-cdn.alpinelinux.org/alpine/v3.12/releases/armhf/alpine-rpi-3.12.0-armhf.tar.gz'
alpine_sha256_url = 'http://dl-cdn.alpinelinux.org/alpine/v3.12/releases/armhf/alpine-rpi-3.12.0-armhf.tar.gz.sha256'
# in the future, maybe can scrape "latest" from here?
alpine_downloads_page_url = 'https://alpinelinux.org/downloads/'

sd_target_image_size = 4 * 1024 * 1024 * 1024 #  4 Gig, bytes
sd_part0_size = 32 * 1024 * 1024 # 32 MB, bytes
sd_part1_size = 32 * 1024 * 1024 # 32 MB, bytes
sd_part2_size = 4 * 1024 * 1024 * 1024 #  4 Gig, bytes

def curl_retrieve_if_newer(url: str, targetdir: str, check_newer: bool = True):
    """ Retrieve the specified URL and store to the specified target directory.  Uses the source file name.
        Wraps curl.
    """
    logger.debug('curl_retrieve_if_newer {} {} {}'.format(url, targetdir, check_newer))
    iso_urlpath = urlparse(url)
    os.makedirs(targetdir, exist_ok=True)
    # print("iso_urlpath={}".format(iso_urlpath))
    targetfile = os.path.join(targetdir, os.path.basename(iso_urlpath.path))

    if os.path.exists(targetfile) and check_newer:
        logger.info(" * Retrieving {} to {} if newer".format(url, targetfile))
        subprocess.run(['curl', '-z', targetfile, '-o', targetfile, url], capture_output=True)
    else:
        logger.info(" * Retrieving {} to {}".format(url, targetfile))
        subprocess.run(['curl', '-o', targetfile, url], capture_output=True)

    return os.path.abspath(targetfile)

def check_checksums(directory: str, sha256file: str):
    """
    Check the SHA256 sums using the specified sha256 hash file
    :param directory:
    :param sha256file:
    :return:
    """
    logger.debug('check_checksums {} {}'.format(directory, sha256file))
    os.chdir(directory)
    cp = logged_subcommand_run(['sha256sum', '-c', sha256file], logger, logger.DEBUG)
    return cp.returncode

def check_update_cached_alpine_iso(cachedir: str, iso_url: str, sha256_url: str):
    """
    Retrieve and pass filehandle for ISO.

    :param cachedir: Cache directory to check/download file
    :param iso_url: ISO image to download
    :param sha256_url: SHA256 file to download matching ISO file
    :return: filehandle for downloaded file
    """

    iso_urlpath = urlparse(iso_url)
    sha256_urlpath = urlparse(sha256_url)
    image_tarball_file = os.path.join(cachedir, os.path.basename(iso_urlpath.path))
    sha256file = os.path.join(cachedir, os.path.basename(sha256_urlpath.path))

    # print("Check: {} {} {}".format(os.path.exists(isofile),os.path.exists(sha256file),check_checksums(cachedir, sha256file)))
    if os.path.exists(image_tarball_file) and os.path.exists(sha256file) and check_checksums(cachedir, sha256file) == 0:
        print("Good integrity image file present: "+image_tarball_file)
        return image_tarball_file

    curl_retrieve_if_newer(iso_url, './cache')
    sha256file = curl_retrieve_if_newer(sha256_url, cachedir, check_newer=False)
    if check_checksums(cachedir, sha256file) != 0:
        print("Checksum problem!")
        raise Exception("Foo!")
    # check hash?
    print ("Returning {}".format(image_tarball_file))
    return image_tarball_file

def create_loopback_image(out_dir: str, target_size_bytes: int, tarfile=None, leave_tempfiles=False):
    target_img = os.path.join(out_dir, 'image.img')
    sd_part0_image_size = 1024 * 1024 # 1MB, aligned for disk label
    sd_part1_image = os.path.join(out_dir, 'part_01.img')
    sd_part1_image_size = 256 * 1024 * 1024 # 256MB for now -
    sd_part2_image = os.path.join(out_dir, 'part_02.img')
    sd_part2_image_size = 1 * 1024 * 1024 * 1024 # 1GB for now
    part1_contents_dir = os.path.join(out_dir, 'part1_contents')
    if not tarfile:
        raise Exception("No good tarfile")

    print("Creating Partition 1, FAT32, file={}, size={}".format(sd_part1_image, humanbytes(sd_part1_size)))
    if os.path.exists(sd_part1_image):
        print("Clearing existing tempfile: {}".format(sd_part1_image))
        os.remove(sd_part1_image)

    # Filesystem size is given in kB by default
    cmd = ['mkfs.fat', '-C', '-F32', '-n', '\"BOOT\"', sd_part1_image, str(int(sd_part1_image_size / 1024))]
    cp = logged_subcommand_run(cmd, logger, logger.DEBUG)

    print("Creating Partition 2, ext4, file={}, size={}".format(sd_part2_image, humanbytes(sd_part2_size)))
    if os.path.exists(sd_part2_image):
        print("Clearing existing tempfile: {}".format(sd_part2_image))
        os.remove(sd_part2_image)
    # Filesystem size is given in kB by default
    cmd = ['mkfs.ext4', '-t', 'ext4', '-L', '\"root\"', sd_part2_image, str(int(sd_part2_image_size / 1024))]
    cp = logged_subcommand_run(cmd, logger, logger.DEBUG)

    print("Extracting Alpine image contents...")
    os.makedirs(part1_contents_dir, exist_ok=True)
    cmd = ['tar', '-xzf', tarfile, '-C', part1_contents_dir]
    cp = logged_subcommand_run(cmd, logger, logger.DEBUG)

    print("Populating Partition 1 with Alpine content")
    cmd = ['mcopy', '-mvns', '-i', sd_part1_image, part1_contents_dir, '::']
    cp = logged_subcommand_run(cmd, logger, logger.DEBUG)

    # https://unix.stackexchange.com/questions/281589/how-to-run-mkfs-on-file-image-partitions-without-mounting

    if not leave_tempfiles:
        print(" ... removing {}".format(part1_contents_dir))
        shutil.rmtree(part1_contents_dir)

    for f in [sd_part1_image, sd_part2_image]:
        print(" ... tempfile {}".format(f))
        if not leave_tempfiles:
            print(" ... removing {}".format(f))
            os.remove(f)

def partition_device(blockdev: str):
    """
    Partition the specified device.
    :param blockdev:
    :return:
    """
    logger.info('partition_device({})'.format(blockdev))

    if not legal_block_dev_file(blockdev):
        raise Exception('Block device is not legal block dev: {} '.format(blockdev))
    blockdev_info = block_device_info(blockdev)
    logger.debug("Block Device Info: {}".format(blockdev_info))

    # constraints to calc partition sizes
    # get size of device
    total_size_sectors = block_device_size_sectors(blockdev)

    # need x sectors for MBR
    sd_part0_size: int = 1024 # 1 MiB label
    sd_part0_size_sectors = int(sd_part0_size / blockdev_info['physical_block_size'])

    # need y megabytes for Alpine image (start w/ 64)
    sd_part1_offset_sectors = blockdev_info['first_partition_offset_sectors']
    sd_part1_size_bytes: int = 256 * 1024 * 1024
    sd_part1_size_sectors = int(sd_part1_size_bytes / blockdev_info['physical_block_size'])

    # use remainder for
    sd_part2_alignment_remainder = (sd_part0_size_sectors + sd_part1_size_sectors) % blockdev_info['alignment_boundary_sectors']
    sd_part2_alignment_fix = blockdev_info['alignment_boundary_sectors'] - sd_part2_alignment_remainder
    sd_part2_offset_sectors = sd_part0_size_sectors + sd_part1_size_sectors + sd_part2_alignment_fix
    sd_part2_size_sectors = total_size_sectors - sd_part0_size_sectors - sd_part1_size_sectors
    sd_part2_size_bytes = int(sd_part2_size_sectors * blockdev_info['physical_block_size'])
    logger.debug('sd_part2_alignment_offset={}, sd_part2_alignment_fix={}'.format(sd_part2_alignment_remainder, sd_part2_alignment_fix))

# parted commands
    # call parted: 'sudo parted --script <devname> --script <script>'
    parted_script = 'mklabel msdos '
    parted_script = parted_script + "mkpart primary fat32 {}s {}s ".format(sd_part1_offset_sectors, sd_part1_size_sectors)
    parted_script = parted_script + "mkpart primary ext4 {}s {}s ".format(sd_part2_offset_sectors, sd_part2_size_sectors)
    parted_script = parted_script + "set 1 boot on "
    parted_script = parted_script + "set 1 lba on "
    logger.debug('partition_device parted command: {}'.format(parted_script))

    # elevate()
    # if not elevate.is_root():
    #     logger.error("Unable to elevate privileges to root")
    #     raise Exception("Unable to elevate privileges to root")
    # else:
    #     logger.debug("Privs elevated.")
    parted_cmdline = ['sudo', 'parted', '--script', blockdev, "{}".format(parted_script)]
    logger.debug('partition_device parted command: {}'.format(parted_cmdline))
    cp = subprocess.run(parted_cmdline, capture_output=True)
    cp = logged_subcommand_run(parted_cmdline, logger, logger.DEBUG)
    logger.info('partition_device({}) COMPLETE'.format(blockdev))

def provision_installer_partition(outdir: str, part_blockdev, alpine_tarfile: str, leave_tempfiles=False):

    # Filesystem size is given in kB by default
    cmd = ['sudo', 'mkfs.fat', '-F32', '-n', '\"BOOT\"', part_blockdev]
    logger.debug("Using: "+' '.join(cmd))
    cp = subprocess.run(cmd)

    installer_fs_path = os.path.join(outdir, 'installer.fs')
    os.makedirs(installer_fs_path, exist_ok=True)

    cmd = ['sudo', 'mount', '-t', 'vfat', part_blockdev, installer_fs_path]
    logger.debug("Using: "+' '.join(cmd))
    cp = subprocess.run(cmd)

    logger.info("Extracting Alpine image contents...")
    installer_tarcontents_path = os.path.join(outdir, 'alpine.tar')
    os.makedirs(installer_tarcontents_path, exist_ok=True)
    cmd = ['sudo', 'tar', '-xz', '-f', alpine_tarfile, '-C', installer_tarcontents_path]
    logger.debug("Using: "+' '.join(cmd))
    cp = subprocess.run(cmd)

    cmd = ['sudo', 'cp', '-r', os.path.join(installer_tarcontents_path, '.'), installer_fs_path]
    logger.debug("Copying installer contents from {} to {}, \n  {}".format(installer_tarcontents_path, installer_fs_path, cmd))
    cp = subprocess.run(cmd)

    # copy answerfile
    # cmd = ['sudo', 'cp', '-r', os.path.join(installer_tarcontents_path, '.'), installer_fs_path]
    # logger.debug("Copying installer contents from {} to {}, \n  {}".format(installer_tarcontents_path, installer_fs_path, cmd))
    #cp = subprocess.run(cmd)

    if not leave_tempfiles:
        logger.debug("Cleaning up tarball contents in {}".format(installer_tarcontents_path))
        shutil.rmtree(installer_tarcontents_path)

        cmd = ['sudo', 'umount', installer_fs_path]
        logger.debug("Unwinding mount: "+' '.join(cmd))
        cp = subprocess.run(cmd)
        os.rmdir(installer_fs_path)

def provision_root_partition(outdir: str, part_blockdev, leave_tempfiles=False):

    # Filesystem size is given in kB by default
    cmd = ['sudo', 'mkfs.ext4', '-t', 'ext4', '-L', '\"root\"',  part_blockdev]
    logger.debug("Using: "+' '.join(cmd))
    cp = subprocess.run(cmd)

    root_fs_path = os.path.join(outdir, 'root.fs')
    os.makedirs(root_fs_path, exist_ok=True)

    cmd = ['sudo', 'mount', '-t', 'ext4', part_blockdev, root_fs_path]
    logger.debug("Using: "+' '.join(cmd))
    cp = subprocess.run(cmd)

    if not leave_tempfiles:
        cmd = ['sudo', 'umount', root_fs_path]
        logger.debug("Unwinding mount: "+' '.join(cmd))
        cp = subprocess.run(cmd)
        os.rmdir(root_fs_path)

def makedirs():
    cwd = os.path.abspath(os.path.curdir)
    out = os.path.join(cwd, 'out')
    os.makedirs(out, exist_ok=True)
    cache = os.path.join(cwd, 'cache')
    os.makedirs(out, exist_ok=True)
    return cwd, out, cache

def main():
    parser = argparse.ArgumentParser(description=__doc__,
                                     prog='make_alpine_rpi',
                                     usage='%(prog)s <command> [options]')
    parser.add_argument("command", type=str, help="Specify the action: \n  init - retrieves files but takes no action\n  liveimage - writes image directly to specified device")
    parser.add_argument("--imagesize", help="Target image size in bytes", type=str)
    parser.add_argument("--device", help="Target device handle", type=str)
    parser.add_argument("--messy", help="Don't clean up temp files and mounts", action='count')
    args = parser.parse_args()
    target_image_size = sd_target_image_size
    cwd, out, cache = makedirs()
    blockdev = None
    messy = True if args.messy else False

    if args.imagesize:
        target_image_size = parse_size(args.imagesize)
        print("Setting target image size to: {}".format(args.imagesize))

    if args.device:
        blockdev = args.device
        print('Directly setting up device {}'.format(blockdev))

    if not args.command:
        parser.print_help()
        parser.print_usage()
        sys.exit(0)

    if args.command == 'init':
        alpinefile = check_update_cached_alpine_iso(cache, alpine_url, alpine_sha256_url)
        sys.exit(0)

    if args.command == 'file':
        alpinefile = check_update_cached_alpine_iso(cache, alpine_url, alpine_sha256_url)
        create_loopback_image(out, target_image_size, leave_tempfiles=messy, tarfile=alpinefile)
        sys.exit(0)

    if args.command == 'liveimage':
        if not blockdev:
            print("ERROR: Please specify valid target block device, (set to {})".format(blockdev))
            sys.exit(-1)

        alpinefile = check_update_cached_alpine_iso(cache, alpine_url, alpine_sha256_url)
        partition_device(blockdev)
        provision_installer_partition(out, blockdev+'1', alpinefile, leave_tempfiles=messy)
        provision_root_partition(out, blockdev+'2', leave_tempfiles=messy)
        sys.exit(0)

if __name__ == "__main__":
    main()


# 6603 로또
"""
    단순 정렬된 조합을 구하는 문제, S의 원소는 원래부터 오름차순으로 주어지므로 따로 정렬할 필요도 없다.
    종료조건에 input()[0] == 0으로 비교해야지, 그냥 input() == '0'해도 항상 False가 나오기 때문에 종료안됨.
"""
import sys
from itertools import combinations
input = sys.stdin.readline

while True:
    array = list(map(str, input().split()))
    if len(array) == 1:
        break
    array = array[1:]
    for lst in combinations(array, 6):
        print(' '.join(lst))
    print()


outfile = open('./ribobits.fasta', 'w')
num= 1
with open('/../../../data/E.crassus_Ribo.fq', 'r') as fin:
	for line in fin:
		if line[0] == '@':
			next = True
			continue
		elif (next):
			next = False
			outfile.write('>' + str(num) + '\n')
			outfile.write(line)
			num += 1
			continue
outfile.close()


import os
import pickle
import struct

from pyoram.oblivious_storage.tree.tree_oram_helper import TreeORAMStorage
from pyoram.util.virtual_heap import calculate_bucket_level
from pyoram.encrypted_storage.top_cached_encrypted_heap_storage import TopCachedEncryptedHeapStorage

def save_oram_client_data(oram, path=os.path.curdir):
    """
    Saves an ORAM's client side data to the specified directory.
    :oram: The ORAM object to save
    :path: The path to save (defaults to current directory)
    """
    store_name = oram._oram.storage_heap.storage_name
    key_file_name = "%s.key" % (store_name)
    stash_file_name = "%s.stash" % (store_name)
    pos_file_name = "%s.position" % (store_name)
    with open(os.path.join(path, key_file_name), "wb") as kf:
        kf.write(oram.key)
    with open(os.path.join(path, stash_file_name), "wb") as sf:
        pickle.dump(oram.stash, sf)
    with open(os.path.join(path, pos_file_name), "wb") as pf:
        pickle.dump(oram.position_map, pf)

def read_oram_client_data(store_name, path=os.path.curdir):
    """
    Reads an ORAM's client side data from the specified directory.
    :store_name: The store name to use
    :path: The path to load from (defaults to current directory).
    """
    key_file_name = "%s.key" % (store_name)
    stash_file_name = "%s.stash" % (store_name)
    pos_file_name = "%s.position" % (store_name)
    with open(os.path.join(path, key_file_name), "rb") as kf:
        key = kf.read()
    with open(os.path.join(path, stash_file_name), "rb") as sf:
        stash = pickle.load(sf)
    with open(os.path.join(path, pos_file_name), "rb") as pf:
        position_map = pickle.load(pf)
    return key, stash, position_map

def compute_avg_level_load(oram):
    """
    Returns the average bucket load for each level in a Path ORAM. This
    function is incompatible with caching. To use this function, your ORAM must
    have been initialized with the cached_levels=0 argument.
    :oram: The Path ORAM to use
    """
    assert type(oram.heap_storage) != TopCachedEncryptedHeapStorage
    level_blocks_inuse = {}
    level_blocks_total = {}
    # for each bucket id
    for bucket in range(oram.heap_storage.virtual_heap.bucket_count()):
        # get the bucket level
        level = calculate_bucket_level(oram.heap_storage.virtual_heap.k, bucket)
        # add level to the map if this is the first time we've seen it
        if level not in level_blocks_inuse:
            level_blocks_inuse[level] = 0
        if level not in level_blocks_total:
            level_blocks_total[level] = 0
        # read the bucket from bucket storage
        bucket_data = oram.heap_storage.bucket_storage.read_block(bucket)
        # compute block parameters
        block_info_fmt = TreeORAMStorage.block_info_storage_string
        block_info_size = struct.calcsize(block_info_fmt)
        block_size = oram.block_size + block_info_size
        # now extract the block info for each bucket
        for block in range(oram.heap_storage.blocks_per_bucket):
            start = block * block_size
            block_info_data = bucket_data[start:start+block_info_size]
            (real_block, block_id) = struct.unpack(block_info_fmt, block_info_data)
            level_blocks_total[level] += 1
            if True == real_block:
                level_blocks_inuse[level] += 1
    # compute percentages
    level_percent_inuse = {}
    for level, total in level_blocks_total.items():
        level_percent_inuse[level] = float(level_blocks_inuse[level]) / float(total)
    return level_percent_inuse


import os
import shutil
import glob
import subprocess

COMMAND_NAME = "zaycheski"
USERNAME = "varvarasafonova"
PREFIX = f"/Users/username/"
zaycheski_directory = ""
local_commands_file = ""
local_storage_folder = ""
local_executable_file = ""

def set_main_variables():
	global PREFIX
	global zaycheski_directory
	global local_commands_file
	global local_storage_folder
	global local_executable_file

	PREFIX = f"/Users/{USERNAME}/"
	zaycheski_directory = PREFIX + ".zaycheski"
	local_commands_file = zaycheski_directory + "/" + "custom_bash_commands"
	local_storage_folder = zaycheski_directory + "/" + "stored_cute_images"
	local_executable_file = zaycheski_directory + "/" + "main.py"

def clear_folder(path):
	if path != local_storage_folder:
		return
	for subdir, dirs, files in os.walk(local_storage_folder):
		for file in files:
			filepath = subdir + os.sep + file
			os.system(f"rm {filepath}")

def copy_to_local_storage_folder():
	clear_folder(local_storage_folder)
	for subdir, dirs, files in os.walk("./ascii_images"):
		for file in files:
			filepath = subdir + os.sep + file
			print("filepath = ", filepath, " local_storage_folder = ", local_storage_folder)
			os.system(f"cp {filepath} {local_storage_folder}")

def set_commands_file():
	with open(local_commands_file, mode = "w") as f:
		print("#!/bin/bash", file = f)
		print(f"function {COMMAND_NAME}()", " {", file = f)
		print(f"\tpython3 {local_executable_file}", file = f)
		print("}", file = f)

def set_executable_file():
	with open(local_executable_file, mode = "w") as f:
		print("from random import randint", file = f)
		print("import os", file = f)
		print(f'files = os.listdir("{local_storage_folder}")', file = f)
		print("r = randint(0, len(files) - 1)", file = f)
		print(f'print(open("{local_storage_folder}/" + files[r]).read())', file = f)

def create_zaycheski_environment():
	set_main_variables()

	os.system(f"mkdir {zaycheski_directory}")
	os.system(f"mkdir {local_storage_folder}")
	os.system(f"touch {local_commands_file}")
	os.system(f"touch {local_executable_file}")

	clear_folder(local_storage_folder)

	copy_to_local_storage_folder();
	set_commands_file()
	set_executable_file()

	os.system(f'echo ". {local_commands_file}" > {PREFIX}.zshrc')
	os.system(f". {local_commands_file}")
	os.system("zsh")

def main():
	global COMMAND_NAME
	global USERNAME

	command_name = input("Do you want zaycheski or zaycheskaya (zaycheski default): ")
	entered_username = input("Enter username (varvarasafonova default): ")

	if command_name != "zaycheskaya":
		command_name = "zaycheski"
	COMMAND_NAME = command_name

	if len(entered_username) < 1:
		USERNAME = "varvarasafonova"
	else:
		USERNAME = entered_username

	create_zaycheski_environment()

main()


from pathlib import Path
import sys
path_root = Path(__file__).parents[2]
sys.path.append(str(path_root))
from requirements import *
from Metrics.Regression_metrics import *

class RESET():
    def __init__(self):
        pass

    def test(self, fitted_model, power=3):
        model, X, y, y_pred_restricted, features_names, rss_restricted, target_name = self.read_fitted_model_attributes(fitted_model=fitted_model)
        power = self.check_power(power=power)
        X, features_names = self.add_predictions_to_model(X=X, y_pred_restricted=y_pred_restricted, features_names=features_names, power=power)
        new_model = self.fit_model(model=model, X=X, y=y, features_names=features_names, target_name=target_name)
        self.F_test, self.p_value = self.calculate_F_test_and_p_value(model=new_model, X=X, y=y, features_names=features_names, rss_restricted=rss_restricted, power=power)

    def read_fitted_model_attributes(self, fitted_model):
        mod_class = fitted_model.__class__
        model = mod_class(fit_intercept=False, optimization=False, degree=fitted_model.degree)
        X = fitted_model.X.copy()
        y = fitted_model.y.copy()
        features_names = fitted_model.features_names.copy()
        y_pred = fitted_model.predict(X=X, features_names=features_names).copy()
        rss_original =  RSS(y_true=fitted_model.y, y_pred=y_pred)
        return model, X, y, y_pred, features_names, rss_original, fitted_model.target_name

    def check_power(self, power):
        if(power < 2):
            raise ValueError('Power has to be greater or equal to 2.')
        if(type(power) != int):
            raise TypeError("Power must be int value.")
        return power

    def add_predictions_to_model(self, X, y_pred_restricted, features_names, power):
        for p in range(2, power+1):
            X = np.column_stack([X, y_pred_restricted**p])
            features_names.append(f"y_pred^{p}")
        return X, features_names

    def fit_model(self, model, X, y, features_names, target_name):
        model.fit(X=X, y=y, features_names=features_names, target_name=target_name, diagnostic_test=True)
        return model

    def calculate_F_test_and_p_value(self, model, X, y, features_names, rss_restricted, power):
        y_pred_unrestricted = model.predict(X=X, features_names=features_names)
        rss_unrestricted = RSS(y_true=y, y_pred=y_pred_unrestricted)
        F_test = np.round(((rss_restricted-rss_unrestricted)/(power-1))/((rss_unrestricted)/(len(X)-len(features_names))), 5)
        p_value = np.round(model.calculate_p_value_F_test(F_test=F_test, dfn=power-1, dfd=len(X)-len(features_names)), 5)
        return F_test, p_value


# -*- coding: utf-8 -*-
from setuptools import setup, find_packages

with open('README.md') as f:
    readme = f.read()

with open('LICENSE') as f:
    license = f.read()

setup(
    name='ot_service_wrapper',
    version='0.1',
    description='Biotaphy package for wrapping Open Tree services',
    long_description=readme,
    author='Biotaphy Team',
    author_email='cjgrady@ku.edu',
    url='https://github.com/biotaphy/ot_service_wrapper',
    license=license,
    packages=find_packages(exclude=('tests')),
    install_requires=[
        'dendropy>=4.0.0'
    ]
)


import argparse, sys

import numpy as np
from PIL import Image
from tqdm import tqdm

import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.autograd import Variable

from transform import random_transform_generator
from dataset import SEMDataset
from modules import *
from save_history import *
from loss import masked_bce_loss, masked_dice_loss, masked_dbce_loss

# from model import UNet
from advance_model import UNet

parser = argparse.ArgumentParser()
parser.add_argument('--train', help='Multualy exclusive with --predict.', action='store_true')
parser.add_argument('--predict', help='Multualy exclusive with --train.', action='store_true')
parser.add_argument('--prob_thres', help='Use with --predict.', action='store_true')
parser.add_argument('--evaluate', help='Multualy exclusive with --train.', action='store_true')
parser.add_argument('--transform', help='', action='store_true')
parser.add_argument('--loss_fn', type=str, default="bce")
parser.add_argument('--snapshot', type=str)
parser.add_argument('--train_dir', type=str)
parser.add_argument('--val_dir', type=str)
parser.add_argument('--save_dir', type=str)
parser.add_argument('--lr', type=float, default=1e-3)
parser.add_argument('--weight_decay', type=float, default=1e-3)
parser.add_argument('--init_epoch', type=int, default=0)
parser.add_argument('--n_epoch', type=int, default=100)
parser.add_argument('--batch_size', type=int, default=2)
parser.add_argument('--num_workers', type=int, default=0)
parser.add_argument('--val_interval', type=int, default=5)
parser.add_argument('--save_interval', type=int, default=10)

args = parser.parse_args()

def train():
    # transform generator
    if args.transform:
        transform_generator = random_transform_generator(
            min_rotation=-0.1,
            max_rotation=0.1,
            min_translation=(-0.1, -0.1),
            max_translation=(0.1, 0.1),
            min_shear=-0.1,
            max_shear=0.1,
            min_scaling=(0.9, 0.9),
            max_scaling=(1.1, 1.1),
            flip_x_chance=0.5,
            flip_y_chance=0.5,
        )
    else:
        transform_generator = None

    # create custome dataset
    train_dataset = SEMDataset(os.path.join(args.train_dir, "img"),
                               os.path.join(args.train_dir, "label"),
                               transform_generator=transform_generator)
    val_dataset = SEMDataset(os.path.join(args.val_dir, "img"),
                             os.path.join(args.val_dir, "label"))

    # Dataloader
    train_loader = torch.utils.data.DataLoader(dataset=train_dataset, num_workers=args.num_workers,
                                               batch_size=args.batch_size, shuffle=True)
    val_loader = torch.utils.data.DataLoader(dataset=val_dataset, num_workers=args.num_workers,
                                             batch_size=args.batch_size, shuffle=False)

    # Model
    model = UNet(in_channels=11, n_classes=2, depth=2, batch_norm=True, padding=True)
    # model = UNet(in_channels=11, n_classes=2)

    if args.snapshot:
        model = torch.load(args.snapshot)
    model = model.cuda()

    # Loss function
    if args.loss_fn == "bce":
        criterion = masked_bce_loss
    elif args.loss_fn == "dice":
        criterion = masked_dice_loss
    elif args.loss_fn == 'dbce':
        criterion = masked_dbce_loss
    else:
        RaiseValueError("%s loss function is not supported" % args.loss_fn)

    # Optimizerd
    optimizer = torch.optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.weight_decay)
    scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, patience=10, verbose=True)

    # Saving History to csv
    header = ['epoch', 'train_loss', 'val_loss', 'val_acc']

    save_dir = os.path.join(args.save_dir, args.loss_fn)
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)

    save_file_name = os.path.join(save_dir, "history.csv")
    for i in range(args.init_epoch, args.init_epoch + args.n_epoch):
        # train the model
        train_loss = train_model(model, train_loader, criterion, optimizer, scheduler)

        # validation every 5 epoch
        if (i + 1) % args.val_interval == 0:
            val_loss, val_acc = evaluate_model(model, val_loader, criterion, metric=True)
            print('Epoch %d, Train loss: %.5f, Val loss: %.5f, Val acc: %.4f' % (i + 1, train_loss, val_loss, val_acc))

            values = [i + 1, train_loss, val_loss, val_acc]
            export_history(header, values, save_dir, save_file_name)

        if (i + 1) % args.save_interval == 0:  # save model every save_interval epoch
            save_models(model, save_dir, i + 1)

def evaluate():
    if args.snapshot is None:
        RaiseValueError("--snapshot must be provided!")

    val_dataset = SEMDataset(os.path.join(args.val_dir, "img"),
                             os.path.join(args.val_dir, "label"))
    val_loader = torch.utils.data.DataLoader(dataset=val_dataset,
                                             num_workers=args.num_workers,
                                             batch_size=1,
                                             shuffle=False)
    # model = UNet(in_channels=11, n_classes=2)
    model = torch.load(args.snapshot)
    model = model.cuda()

    score_model(model, val_loader)

def predict():
    if not os.path.exists(args.save_dir):
        os.makedirs(args.save_dir)

    dataset = SEMDataset(os.path.join(args.val_dir, "img"),
                         os.path.join(args.val_dir, "label"),
                         transform_generator=None)
    loader = torch.utils.data.DataLoader(dataset=dataset, num_workers=args.num_workers, batch_size=1, shuffle=False)

    # model = UNet(in_channels=11, n_classes=2)
    model = torch.load(args.snapshot)
    model = model.cuda()

    model.eval()
    with torch.no_grad():
        pbar = tqdm(loader)
        for batch_idx, (images, labels) in enumerate(pbar):
            images = images.cuda()

            probs = model.forward(images).data.cpu().numpy()  # 1 * C * H * W
            preds = np.argmax(probs, axis=1).astype(np.uint8) + 1  # 1 * H * W
            probs = np.max(probs, axis=1)  # 1 * H * W
            if args.prob_thres:
                high_prob_masks = (probs > 0.90).astype(np.uint8)
                preds = preds * high_prob_masks  # 1 * H * W
            pred = preds[0, ...]  # H x W

            no_value_mask = dataset.get_mask(batch_idx)  # H x W

            pred = pred * no_value_mask
            label = Image.fromarray(pred).convert("L")

            basename = dataset.get_basename(batch_idx)
            label.save(os.path.join(args.save_dir, "%s.png" % basename))

if __name__ == "__main__":
    if args.train:
        train()
    elif args.predict:
        predict()
    elif args.evaluate:
        evaluate()
    else:
        print("Please chose --train, --predict, --evaluate. Mutualy exclusive!")


import argparse
from abc import ABC
from pathlib import Path

import numpy as np

import epoch_counter
from main import add_arguments
from qlearning.network import TeacherAgent
from qlearning.teacher import TeacherEnv
from trainer import Trainer

class EpochCounter(epoch_counter.EpochCounter):
    infos_name = "infos"

    def __init__(self, num_processes):
        super().__init__(num_processes)
        keys = ["our_return", "base_return"]
        self.info_lists = {k: [[] for _ in range(num_processes)] for k in keys}
        self.episode_lists = {k: [None for _ in range(num_processes)] for k in keys}

    def update(self, reward, done, infos):
        for k, lists in self.info_lists.items():
            for i, (info, d) in enumerate(zip(infos, done)):
                if k in info:
                    lists[i].append(info[k])
                if d:
                    self.episode_lists[k][i] = lists[i]
                    lists[i] = []

        return super().update(reward, done, infos)

    def items(self, prefix=""):
        episode_lists = {
            k: [x for x in v if x is not None] for k, v in self.episode_lists.items()
        }
        yield prefix + EpochCounter.infos_name, episode_lists
        yield from super().items(prefix)

def main(training_iterations, alpha, q_learning_gamma, **kwargs):
    class TeacherTrainer(Trainer, ABC):
        def step(self):
            result = super().step()

            for prefix in ("", "eval_"):
                name = prefix + EpochCounter.infos_name
                for k, v in result.pop(name).items():
                    path = Path(self.logdir, f"{prefix}{k}")
                    np.save(str(path), np.array(v))

            return result

        def make_env(self, env_id, seed, rank, evaluation):
            return TeacherEnv(
                seed=seed + rank,
                training_iterations=training_iterations,
                env_id=env_id,
                alpha=alpha,
                gamma=q_learning_gamma,
            )

        @staticmethod
        def build_agent(envs, **agent_args):
            return TeacherAgent(envs.observation_space, envs.action_space, **agent_args)

        @classmethod
        def build_epoch_counter(cls, num_processes):
            return EpochCounter(num_processes)

    kwargs.update(recurrent=True)
    TeacherTrainer.main(**kwargs)

if __name__ == "__main__":
    PARSER = argparse.ArgumentParser()
    PARSER.add_argument("--training-iterations", "-T", type=int)
    PARSER.add_argument("--alpha", "-a", type=float)
    PARSER.add_argument("--q-learning-gamma", "-qg", type=float)
    add_arguments(PARSER)
    main(**vars(PARSER.parse_args()))


import os
import re

top = """#include "stdafx.h"
// Using =======================================================================
namespace py = pybind11;

// Module ======================================================================
void Export_pystes_{}(py::module &m)
{{
"""

bottom = """
}"""

files = ['gamedefines.cpp']

dir_path_python = 'C:/Users/abahb/source/repos/BL2-SDK/bl2-sdk/pydefs/'

dir_path_h = 'C:/Users/abahb/source/repos/BL2-SDK/bl2-sdk/'

classes = {}
for filename in os.listdir(dir_path_h):
    if '_classes.h' in filename or '_structs.h' in filename:
        objs = {}
        with open(dir_path_h + filename) as f:
            c = None
            fields = []
            for line in f.readlines():
                if line.startswith('class ') or line.startswith('struct '):
                    c = line.split(' ')[1].strip()
                if ' : 1;' in line:
                    field = line.split(' : 1;')[0].split(' ')[-1]
                    fields.append(field)
                if line == '};\n':
                    objs[c] = fields
                    c = None
                    fields = []
        classes[filename.split('.')[0]] = objs

bitfield_def = '\t\t.def_property("{field_name}", []({class_name} &self){{return self.{field_name};}}, []({class_name} &self, bool value){{self.{field_name} = value ? 1 : 0;}})\n'

for s in classes.keys():
    lines = []
    with open(dir_path_python + s + '.cpp') as f:
        for line in f.readlines():
            lines.append(line)
            if 'class_<' in line:
                c = line.split('class_<')[1].strip().split(' ')[0].split(',')[0].strip()
                if c in classes[s].keys():
                    for field in classes[s][c]:
                        lines.append(bitfield_def.format(field_name=field, class_name=c))
    with open(dir_path_python + s + '.cpp', 'w') as f:
        for line in lines:
            f.write(line)

# for filename in new_files:
# 	print('void Export_pystes{}(py::module &m);'.format(filename))
# 	with open(dir_path_python + filename + '.cpp', 'w') as f:
# 		f.write(top.format(filename))
# 		for line in new_files[filename]:
# 			f.write(line)
# 		f.write(bottom)


#!/usr/bin/env python3

from types import SimpleNamespace

from lilaclib import *

g = SimpleNamespace()

build_prefix = 'extra-x86_64'

def pre_build():
  g.files = download_official_pkgbuild('rsync')

  for line in edit_file('PKGBUILD'):
    if line.startswith('pkgname='):
      line = 'pkgname=rsync-noatime'
    elif line.startswith('depends=('):
      line = line + '''
conflicts=('rsync')
provides=("rsync=$pkgver")'''
    elif line.startswith('build('):
      line = '''\
prepare() {
	cd "$srcdir/rsync-$pkgver"
	patch -p1 -i "${srcdir}/noatime.diff"
}

''' + line
    elif line.startswith('source=('):
      line = f'{line}\n\t"noatime.diff"'
    elif "'SKIP'" in line:
      line = f'{line}\n\t"bff6a2e4682f31b7c0f556c39b8cd227983f9a3e8741d751be8d57455c58ab63"'
    if '$pkgname' in line:
      line = line.replace('$pkgname', 'rsync')
    print(line)

def post_build():
  git_add_files(g.files)
  git_commit()

if __name__ == '__main__':
  single_main()


#!/usr/bin/env python3
'''龟作图范例集：

        tdemo_fractalCurves.py

这个程序绘制了两个分形曲线设计：
（ 1 ）希尔伯特曲线（在一个盒子）
（ 2 ）对科赫 - 曲线的组合。

该CurvesTurtle类和分形曲线 -
方法是从PythonCard示例取
脚本乌龟图形。=== 以上由 Google 翻译，请协助改善 ===
'''
from turtle_tc import *
from time import sleep, clock

class 曲线龟类(笔类):
    # 例如源自
    # 龟几何：计算机作为媒介的探索数学
    # 由哈罗德·阿贝尔森和Andrea diSessa
    # 页。 96-98
    def hilbert(我, 尺寸, 等级, 对等性):
        if 等级 == 0:
            return
        # 旋转并绘制第一subcurve具有相反奇偶性，以大曲线
        我.左转(对等性 * 90)
        我.hilbert(尺寸, 等级 - 1, -对等性)
        # 接口和借鉴第二subcurve具有相同的奇偶大曲线
        我.前进(尺寸)
        我.右转(对等性 * 90)
        我.hilbert(尺寸, 等级 - 1, 对等性)
        # 第三subcurve
        我.前进(尺寸)
        我.hilbert(尺寸, 等级 - 1, 对等性)
        # 第四subcurve
        我.右转(对等性 * 90)
        我.前进(尺寸)
        我.hilbert(尺寸, 等级 - 1, -对等性)
        # 最后又需要作出乌龟
        # 最终朝外从大广场
        我.左转(对等性 * 90)

    # 可视化建模与标志：一种结构方法见此
    # 由詹姆斯·克莱森
    # 科赫曲线，黑尔格·冯·科赫后谁介绍这个几何图形在1904年
    # 页。 146
    def 碎形多边形(我, n, 弪度, lev, dir):
        import math

        # 如果DIR = 1向外转
        # 如果DIR = -1向内转
        边缘 = 2 * 弪度 * math.sin(math.pi / n)
        我.提笔()
        我.前进(弪度)
        我.下笔()
        我.右转(180 - (90 * (n - 2) / n))
        for i in 范围(n):
            我.碎形(边缘, lev, dir)
            我.右转(360 / n)
        我.左转(180 - (90 * (n - 2) / n))
        我.提笔()
        我.后退(弪度)
        我.下笔()

    # 页。 146
    def 碎形(我, 距离, 深度, dir):
        if 深度 < 1:
            我.前进(距离)
            return
        我.碎形(距离 / 3, 深度 - 1, dir)
        我.左转(60 * dir)
        我.碎形(距离 / 3, 深度 - 1, dir)
        我.右转(120 * dir)
        我.碎形(距离 / 3, 深度 - 1, dir)
        我.左转(60 * dir)
        我.碎形(距离 / 3, 深度 - 1, dir)

def 主函数():
    ft = 曲线龟类()

    ft.重设()
    ft.速度(0)
    ft.藏龟()
    ft.取幕().追踪(1,0)
    ft.提笔()

    尺寸 = 6
    ft.设位置(-33*尺寸, -32*尺寸)
    ft.下笔()

    ta=clock()
    ft.填色(红)
    ft.开始填()
    ft.前进(尺寸)

    ft.hilbert(尺寸, 6, 1)

    # 框架
    ft.前进(尺寸)
    for i in 范围(3):
        ft.左转(90)
        ft.前进(尺寸*(64+i%2))
    ft.提笔()
    for i in 范围(2):
        ft.前进(尺寸)
        ft.右转(90)
    ft.下笔()
    for i in 范围(4):
        ft.前进(尺寸*(66+i%2))
        ft.右转(90)
    ft.结束填()
    tb=clock()
    res =  "Hilbert: %.2fsec. " % (tb-ta)

    sleep(3)

    ft.重设()
    ft.速度(0)
    ft.藏龟()
    ft.取幕().追踪(1,0)

    ta=clock()
    ft.颜色(黑, 蓝)
    ft.开始填()
    ft.碎形多边形(3, 250, 4, 1)
    ft.结束填()
    ft.开始填()
    ft.颜色(红)
    ft.碎形多边形(3, 200, 4, -1)
    ft.结束填()
    tb=clock()
    res +=  "Koch: %.2fsec." % (tb-ta)
    return res

if __name__  == '__main__':
    讯息 = 主函数()
    印(讯息)
    主循环()

# Above: "tc_fractalcurves.py", by Renyuan Lyu (吕仁园), 2015-03-06
# Original: "fractalcurves.py", by Gregor Lingl.


# Django settings for wtv project.

import os
from wtvsettings import Private
gettext = lambda s: s
PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))

DEBUG = Private.WTVSettings.debug()
TEMPLATE_DEBUG = DEBUG

ADMINS = (
     ('Josh McNamee', 'josh04@gmail.com'),
)

MANAGERS = ADMINS

DATABASES = Private.WTVSettings.database()

LOGIN_URL = '/login/'
LOGIN_REDIRECT_URL = '/'

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/London'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-gb'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = '/home/django/wtv-dev/media/'

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = os.path.join(PROJECT_PATH, 'media/static/')

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/media/static/'

# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/media/static/admin/'

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = Private.WTVSettings.secret()

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'cms.middleware.page.CurrentPageMiddleware',
    'cms.middleware.user.CurrentUserMiddleware',
    'cms.middleware.toolbar.ToolbarMiddleware',
    'cbv.middleware.DeferredRenderingMiddleware',
)

ROOT_URLCONF = Private.WTVSettings.urls()

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(PROJECT_PATH, 'templates')
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.admin',
    'django.contrib.admindocs',
    'cms',
    'mptt',
    'menus',
    'south',
    'sekizai',
    'cms.plugins.text',
    'cms.plugins.picture',
    'cms.plugins.link',
    'cms.plugins.file',
    'cms.plugins.snippet',
    'cms.plugins.googlemap',
    'cms.plugins.twitter',
    'djangocms_utils',
    'tagging',
    'simple_translation',
    #'cmsplugin_youtube',
    #'django.contrib.comments',
    'zinnia',
    'zinnia.plugins',
    'polls',
    'textvid',
   # 'booking',
    'wtvforms',
    'sortable',
    'executive',
    'facebookgroupbutton',
)

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

LANGUAGES = [
    ('en-gb', 'English'),
]

CMS_TEMPLATES = (
    ('department_page.html', 'Department Template'),
    ('main_page.html', 'Home Page Template'),
    ('static_text.html', 'Single Text Template'),
    ('webcam_page.html', 'Webcam Template'),
    ('hosted_video.html', 'Hosted Video Template (Beta)'),
)

ZINNIA_PLUGINS_TEMPLATES = [
    ('zinnia/cms/big_entry_detail.html', 'Entry Detailed (big)')
]

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.i18n',
    'django.core.context_processors.request',
    'django.core.context_processors.media',
    'django.core.context_processors.static',
    'cms.context_processors.media',
    'zinnia.context_processors.version', # Optional
    'zinnia.context_processors.media',
    'sekizai.context_processors.sekizai',
)

JQUERY_JS = 'https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js'
JQUERY_UI_JS = 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js'
JQUERY_UI_CSS = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/themes/smoothness/jquery-ui.css'

CMSPLUGIN_BLOG_PLACEHOLDERS = ('text', 'video')

ZINNIA_ENTRY_BASE_MODEL = 'zinnia.plugins.placeholder.EntryPlaceholder'


# 4. Найти сумму n элементов следующего ряда чисел: 1, -0.5, 0.25, -0.125,…
# Количество элементов (n) вводится с клавиатуры.
from myfuncs import memory_counter
n = int(input('Введите сумму скольки элементов ряда: 1, -0.5, 0.25, -0.125,… '
              'вы хотите получить: '))
result = 0
curr = 1
for i in range(n):
    result += curr
    curr /= -2
print(f'Сумма {n} элементов ряда будет равна: {result}')
res = 0
lst = list(locals().copy().values())
for i in lst:
    res += memory_counter(i, set())

print(res)

GeekBrains/Урок 2. Циклы, рекурсия, функции/less_2_task_4.py


is_prime = [1]*(1000010)
lpd = [1]*(1000010)
is_prime[0]=is_prime[1]=0
def sieve():
	for i in range(1,1000001):
		if is_prime[i]==1:
			k = i*i
			while k<=1000000:
				if is_prime[k]==1:
					is_prime[k]=0
				k+=i

def lpdd():
	for i in range(2,1000001):
		if i%2==0:
			lpd[i]=2
		elif i%3==0:
			lpd[i]=3
		elif i%5==0:
			lpd[i]=5
		else:
			j=7
			while (j*j)<=i:
				if i%j==0:
					lpd[i]=j
					break
				elif i%(j+4)==0:
					lpd[i]=j+4
					break
				elif i%(j+6)==0:
					lpd[i]=j+6
					break
				elif i%(j+10)==0:
					lpd[i]=j+10
					break
				elif i%(j+12)==0:
					lpd[i]=j+12
					break
				elif i%(j+16)==0:
					lpd[i]=j+16
					break
				elif i%(j+22)==0:
					lpd[i]=j+22
					break
				elif i%(j+24)==0:
					lpd[i]=j+24
					break
				j+=30
			if j*j > i:
				lpd[i] = i

sieve()
lpdd()
while j<=t:
	z = 0
	n = [int(x) for x in input().split()]
	#m = int(input())
	result = [0]*(n[1])
	a = [int(x) for x in input().split()]
	for i in range(0,n[1]):
		b = [int(y) for y in input().split()]
		if b[0]==0:
			update(b[1],b[2],a)
		else:
			result[z] = get(b[1],b[2],a)
			#print(result[z])
			z+=1
	result = result[0:z]
	print(*result)
	j+=1


# Time to check the rest of the slopes - you need to minimize the probability of a sudden arboreal stop, after all.

# Determine the number of trees you would encounter if, for each of the following slopes, you start at the top-left corner and traverse the map all the way to the bottom:

# Right 1, down 1.
# Right 3, down 1. (This is the slope you already checked.)
# Right 5, down 1.
# Right 7, down 1.
# Right 1, down 2.
# In the above example, these slopes would find 2, 7, 3, 4, and 2 tree(s) respectively; multiplied together, these produce the answer 336.

# What do you get if you multiply together the number of trees encountered on each of the listed slopes?

#read in data from text file

#column length

with open('advocd3data.txt', 'r') as f:
    lines = f.read().splitlines()

print(lines)

# print(rows[1][3])
# print(rows[2][6])
# print(rows[3][9])
# print(rows[4][1])
# print(rows[5][4])

slopes = ["1:1","3:1","5:1","7:1",'1:2']
treeMulti = 1

for slope in slopes:
    print (slope)
    stringSplit = slope.split(":")
    colIncrement = int(stringSplit[0])
    rowIncrement = int(stringSplit[1])

    #colIncrement = 1
    #rowIncrement= 2

    row = rowIncrement
    col = colIncrement
    numOfRows = len(lines)
    lenOfRow = len(lines[0])
    print("lenofRow:")
    print(lenOfRow)
    treeCount = 0

    for line in lines:
        if col >= lenOfRow:
            col = col%lenOfRow
        print(row)
        print(col)
        if row < numOfRows:
            print(lines[row][col])
            if lines[row][col] == "#":
                treeCount += 1

        row += rowIncrement
        col += colIncrement

    print("treeCount:")
    print(treeCount)
    treeMulti *= treeCount

print(treeMulti)


str1 = input("Enter the first string: ").strip()
str2 = input("Enter the second string: ").strip()

def isASubstring(s1, s2):
    index_start = 0
    rem_len = len(s2)
    while len(s1) <= rem_len:
        if s1!= s2[index_start : index_start + len(s1)]:
            index_start += 1
            rem_len += 1
        else:
            return index_start
    return -1

if isASubstring(str1,str2) != -1:
    print("First string is a substring of the second string")
else:
    print("First string is not a substring of the second string")


from django.contrib import admin
from django.urls import path
from app import views
# STATIC AND MEDIA
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.HomePage.as_view(), name='home'),
    path('room/new/', views.AddRoom.as_view(), name="add_room"),
    path('room/modify/<int:id>', views.ModifyRoom.as_view(), name="modify_room"),
    path('add-reservation/', views.AddReservation.as_view(), name='add_reservation'),
    path('add-reservation/<int:id>', views.AddReservationById.as_view(),
         name='add_reservation_byid'),
    path('room-info/<int:id>', views.RoomInfo.as_view(), name="room_info"),
    path('test/', views.test),
]

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)