from art import logo
import random
from replit import clear

BEGINNER = 10
AMATEUR = 8
PROFFESIONAL = 6
SUPERSTAR = 4
number_range = []
lives = 0
for i in range(1, 101):
    number_range.append(i)
print(number_range)
number = 0

def choose_number():
    """returns a random number"""
    number = random.choice(number_range)
    return number

# def choose_level():
#   """asigns the number of lives with respect to the level the player choses"""
#   chose_level = input("choose a level of your choice\n biginner \n Amateur\n professional,\n superstar").lower()
#   if chose_level == "biginner":
#     lives = BEGINNER
#   elif chose_level == "amateur":
#     lives = AMATEUR
#   elif chose_level == "professional":
#     lives = PROFFESIONAL
#   elif chose_level == "superstar":
#     lives = SUPERSTAR
#   return lives

def play_again():
    """restarts or ends the game"""
    continue_playing = input("type 'p' too continue playing or 'q' to quit: ").lower()
    if continue_playing == "p":
        clear()
        game(lives)
    else:
        clear()

def game(lives):
    print(logo)
    print("Welcome to my guess a number game")
    print("i am thinking of a number between 1-100")
    number = choose_number()
    chose_level = input(
        "choose a level of difficulty. Type: 'beginner', 'Amateur', 'professional', 'superstar'\n\n"
    ).lower()
    if chose_level == "beginner":
        lives = BEGINNER
    elif chose_level == "amateur":
        lives = AMATEUR
    elif chose_level == "professional":
        lives = PROFFESIONAL
    elif chose_level == "superstar":
        lives = SUPERSTAR
    else:
        print("howdy you missed something ")

    while lives > 0:
        print(f"you have {lives} attempts remaining to guess the number")
        guess = int(input("make a guess:"))
        if guess > number:
            lives -= 1
            print(
                f"Too high.\nGuess again.\nYou have {lives} attempts remaining to guess the number"
            )
        elif guess < number:
            lives -= 1
            print(
                f"Too low.\nGuess again.\nYou have {lives} attempts remaining to guess the number."
            )
        elif guess == number:
            print(f"Yes! you won.The correct number is {number}")
            play_again()
    play_again()

game(lives)

# new one
from random import randint
from replit import clear
EASY_LEVEL_TURNS = 10
HARD_LEVEL_TURNS = 5
def game():
  answer = randint(1, 100)
  print(f"psst the answer is {answer}")
  print("welcome to my game of guess a number")
  print("I am thinking of a number between 1 - 100")
  def level():
    level = input("choose a level: type 'hard' or 'easy': ").lower()
    if level == "hard":
      return HARD_LEVEL_TURNS
    elif level == "easy":
      return EASY_LEVEL_TURNS

  def check():
    if guess > answer:
      return f"Too high\nGuess again: \nyou have {lives -1} attempts remaining to make a guess"
    elif guess < answer:
      return f"Too low\nGuess again: \nyou have {lives -1} attempts remaining to make a guess"
    else:
      return "You win"

  lives= level()
  while lives > 0:
    guess = int(input("Guess a number: "))
    compare = check()
    if compare == "You win":
      print(f"{compare} the right number is {answer}")
      play_again = input("type 'p' to play again or 'q' to quit: ").lower()
      if play_again == "p":
        clear()
        game()
      else:
        clear()
    else:
      lives -= 1
      print(compare)

  print("You lose but all hope os not lost")
  play_again = input("type 'p' to play again or 'q' to quit: ").lower()
  if play_again == "p":
    clear()
    game()
  else:
    clear()

game()

#TEACHERS'S CORRECTION

from random import randint
from art import logo

EASY_LEVEL_TURNS = 10
HARD_LEVEL_TURNS = 5

#Function to check user's guess against actual answer.
def check_answer(guess, answer, turns):
  """checks answer against guess. Returns the number of turns remaining."""
  if guess > answer:
    print("Too high.")
    return turns - 1
  elif guess < answer:
    print("Too low.")
    return turns - 1
  else:
    print(f"You got it! The answer was {answer}.")

#Make function to set difficulty.
def set_difficulty():
  level = input("Choose a difficulty. Type 'easy' or 'hard': ")
  if level == "easy":
    return EASY_LEVEL_TURNS
  else:
    return HARD_LEVEL_TURNS

def game():
  print(logo)
  #Choosing a random number between 1 and 100.
  print("Welcome to the Number Guessing Game!")
  print("I'm thinking of a number between 1 and 100.")
  answer = randint(1, 100)
  print(f"Pssst, the correct answer is {answer}")

  turns = set_difficulty()
  #Repeat the guessing functionality if they get it wrong.
  guess = 0
  while guess != answer:
    print(f"You have {turns} attempts remaining to guess the number.")

    #Let the user guess a number.
    guess = int(input("Make a guess: "))

    #Track the number of turns and reduce by 1 if they get it wrong.
    turns = check_answer(guess, answer, turns)
    if turns == 0:
      print("You've run out of guesses, you lose.")
      return
    elif guess != answer:
      print("Guess again.")

game()


import person_pb2

def setperson(info):
    person = info.people.add()
    person.name = "Shany"
    person.id = 99
    person.email = "aaa@sohu.com"

    phone = person.phones.add()
    phone.number = "82081234"
    phone.type = person.PhoneType.WORK

    return info

first_info = person_pb2.AddressBook()
person = setperson(first_info)

# 序列化
serializeToString = first_info.SerializeToString()
print(serializeToString, type(serializeToString))

first_info.ParseFromString(serializeToString)

for person in first_info.people:
    print("name: {}, id: {}, email: {}".format(person.name, person.id, person.email))

for phone_number in person.phones:
    print(phone_number.number, phone_number.type)


import asyncio
import pkgutil
import sys

from werkzeug.wrappers import Response
from werkzeug.utils import cached_property
from werkzeug.urls import Href
from werkzeug.exceptions import MethodNotAllowed
from markupsafe import Markup

from galerka.util import asyncached, AsyncGetter

class View:
    def __init__(self, parent, url_fragment, *, request=None):
        self.parent = parent
        self.request = request or parent.request
        if getattr(self, 'url_fragment', None) is None:
            assert isinstance(url_fragment, str)
            self.url_fragment = url_fragment

    @asyncio.coroutine
    def traverse(self, pathinfo):
        if not pathinfo:
            return self
        url_fragment = pathinfo[0]
        if url_fragment == '..':
            if self.parent:
                child = self.parent
            else:
                child = self
        elif url_fragment == '.' or not url_fragment:
            child = self
        elif url_fragment in getattr(self, 'child_classes', {}):
            child = self.child_classes[url_fragment](self, url_fragment)
        else:
            child = (yield from self.get_child(url_fragment))
        return (yield from child.traverse(pathinfo[1:]))

    def __getitem__(self, *path):
        pathinfo = []
        for fragment in path:
            if isinstance(fragment, str):
                pathinfo.extend(fragment.split('/'))
            else:
                pathinfo.append(fragment)
        return self.traverse(pathinfo)

    @cached_property
    def redis_key(self):
        return self.request.redis_prefix + self.path

    @asyncio.coroutine
    def get_child(self, url_fragment):
        raise LookupError(url_fragment)

    @cached_property
    def path(self):
        path = '/'.join(parent.url_fragment for parent in self.lineage)
        if not path:
            return '/'
        else:
            return path

    @cached_property
    def lineage(self):
        parent = self.parent
        if parent:
            parent_lineage = parent.lineage
        else:
            parent_lineage = ()
        return parent_lineage + (self, )

    @cached_property
    def url(self):
        return self.root.href(self.path)

    @cached_property
    def href(self):
        if self.parent:
            return getattr(self.parent.href, self.url_fragment)
        else:
            return Href(self.request.url_root)

    def static_url(self, path):
        static_files = self.request.environ['galerka.static_files']
        item = static_files[path]
        try:
            sha = item.sha
        except AttributeError:
            return self.root.href.static(path)
        else:
            return '%s?%s' % (self.root.href.static(path), sha)

    @cached_property
    def root(self):
        return self.lineage[0]

    @classmethod
    def child(cls, name):
        def decorator(child):
            try:
                child_classes = cls.child_classes
            except AttributeError:
                child_classes = cls.child_classes = {}
            child_classes[name] = child
            return child
        return decorator

    @cached_property
    def allowed_methods(self):
        methods = ('GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'TRACE', 'OPTIONS')
        return [m for m in methods if getattr(self, m, None)]

    def get_response(self, method):
        method = method.upper()
        if method in self.allowed_methods:
            return getattr(self, method)
        else:
            return AsyncGetter(MethodNotAllowed(self.allowed_methods))

    @cached_property
    def HEAD(self):
        return self.GET

    @asyncached
    def OPTIONS(self):
        return Response('', headers={'Allow': ', '.join(self.allowed_methods)})

    @classmethod
    def _load_all_views(cls):
        for pkg in cls.view_packages:
            walk = pkgutil.walk_packages(pkg.__path__, pkg.__name__ + '.')
            for loader, name, is_pkg in walk:
                if name not in sys.modules:
                    module = loader.find_module(name).load_module(name)
                    yield module

class GalerkaView(View):
    extra_javascripts = ['main']
    styles = ['style.css']

    @cached_property
    def GET(self):
        try:
            rendered_page = self.rendered_page
        except AttributeError:
            return None
        else:
            @asyncio.coroutine
            def get():
                rendered = yield from rendered_page
                return Response(rendered, mimetype='text/html')
            return get()

    @property
    def POST(self):
        try:
            do_post = self.do_post
        except AttributeError:
            return None
        else:
            return self.handle_post()

    @asyncio.coroutine
    def handle_post(self):
        status, data, url = yield from self.do_post()
        if self.request.headers['accept'] == 'application/json':
            return Response(data,
                            status=status,
                            headers={'Content-Type':
                                     'application/json'})
        else:
            content = Markup('''

                    <title>OK</title>

OK

→ {}

({})

            ''').format(Markup(url), url, status)
            return Response(content, 303, mimetype='text/html',
                            headers={'Location': url})

    @asyncached
    def rendered_page(self):
        return (yield from self.render_template('base.mako'))

    @asyncached
    def rendered_hierarchy(self):
        result = []
        for page in self.lineage:
            result.append(Markup('
{}
').format(
                page.url,
                (yield from page.title),
            ))
        return Markup('').join(result)

    def get_template(self, name):
        return self.request.environ['galerka.mako'].get_template(name)

    @asyncio.coroutine
    def render_template(self, name):
        template = self.get_template(name)
        result = yield from template.render_async(
            this=self,
            request=self.request,
            static_url=self.static_url,
            redis=self.request.redis,
        )
        return Markup(result)

    @cached_property
    def javascripts(self):
        result = set(self.extra_javascripts)
        for cls in type(self).mro():
            result.update(getattr(cls, 'extra_javascripts', ()))
        return result


import numpy as np
import tqdm
import os
import h5py as h5

from sklearn.model_selection import KFold
from sklearn.cluster import KMeans
from .paths import *

from canopy.vector_utils import *
from canopy.extract import *

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--out',required=True,help='directory prefix for output files')
parser.add_argument('--rgb',action='store_true',help='use RGB data instead of hyperspectral')

args = parser.parse_args()

# make output directory if necessary
for i in range(10):
  if not os.path.exists(args.out+str(i)):
      os.makedirs(args.out+str(i))

if args.rgb:
    my_image_uri = rgb_image_uri
else:
    my_image_uri = image_uri

# Load the metadata from the image.
with rasterio.open(my_image_uri) as src:
  image_meta = src.meta.copy()

# Load the shapefile and transform it to the hypersectral image's CRS.
polygons, labels = load_and_transform_shapefile(labels_shp_uri,'SP',image_meta['crs'])

cluster_ids = np.loadtxt('./data/clusters.txt',dtype='int')

for fold in range(10):
  os.makedirs(args.out + str(fold),exist_ok=True)
  with open(args.out + str(fold) + '/' + train_ids_uri,'w') as f:
    pass
  with open(args.out + str(fold) + '/' + test_ids_uri,'w') as f:
    pass

kfold = KFold(n_splits=10, shuffle=True, random_state=0)
for cluster in range(10):
  subset = np.where(cluster_ids==cluster)[0]

  fold = 0
  for train_idx, test_idx in kfold.split(X=subset):
    train_inds = subset[train_idx]
    test_inds = subset[test_idx]
    # Save ids of train,val,test polygons
    with open(args.out + str(fold) + '/' + train_ids_uri,'a') as f:
      f.writelines(["%d\n"%ind for ind in train_inds])
    with open(args.out + str(fold) + '/' + test_ids_uri,'a') as f:
      f.writelines(["%d\n"%ind for ind in test_inds])
    fold = fold + 1

for fold in range(10):
  train_inds = np.loadtxt(args.out + str(fold) + '/' + train_ids_uri,dtype='int')
  test_inds = np.loadtxt(args.out + str(fold) + '/' + test_ids_uri,dtype='int')

  # Separate out polygons
  train_polygons = [polygons[ind] for ind in train_inds]
  train_labels = [labels[ind] for ind in train_inds]
  test_polygons = [polygons[ind] for ind in test_inds]
  test_labels = [labels[ind] for ind in test_inds]

  # Rasterize the shapefile to a TIFF.  Using LZW compression, the resulting file is pretty small.
  train_labels_raster = rasterize_shapefile(train_polygons, train_labels, image_meta, args.out + str(fold) + '/' + train_labels_uri)
  test_labels_raster = rasterize_shapefile(test_polygons, test_labels, image_meta, args.out + str(fold) + '/' + test_labels_uri)

  # Extract patches and labels
  patch_radius = 7
  height_threshold = 5
  train_image_patches, train_patch_labels = extract_patches(my_image_uri,patch_radius,chm_uri,height_threshold,args.out + str(fold) + '/' + train_labels_uri)
  test_image_patches, test_patch_labels = extract_patches(my_image_uri,patch_radius,chm_uri,height_threshold,args.out + str(fold) + '/' + test_labels_uri)

  # Store the patches and labels into an HDF5 file for easy use in Keras.
  with h5.File(args.out + str(fold) + '/' + train_data_uri,'w') as f:
    f.create_dataset('data',data=train_image_patches)
    f.create_dataset('label',data=train_patch_labels)
  with h5.File(args.out  + str(fold)+ '/' + test_data_uri,'w') as f:
    f.create_dataset('data',data=test_image_patches)
    f.create_dataset('label',data=test_patch_labels)


import re
from queue import Queue, Full

class Token:
    LEFT_BRACKETS = 'LEFT_BRACKETS'
    RIGHT_BRACKETS = 'RIGHT_BRACKETS'
    SYMBOL = 'SYMBOL'
    EXPRESSION = 'EXPRESSION'
    SYMBOLS = '&|!'

    def __init__(self, value, type):
        self.value = value
        self.type = type

    def __str__(self):
        return '{0}<{1}>'.format(self.value, self.type)

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

class ASTree:
    def __init__(self, token):
        self.root = token
        self.left = None
        self.right = None

    def visit(self):
        ret = []
        q = Queue()
        q.put(self)
        while not q.empty():
            t = q.get()
            ret.append(t.root)
            if t.left:
                q.put(t.left)
            if t.right:
                q.put(t.right)
        return ret

def tokenize(origin):
    tokens = []
    is_expr = False
    expr = []
    for c in origin:
        if c == '#':
            if not is_expr:
                is_expr = True
            else:
                is_expr = False
                token = Token(''.join(expr), Token.EXPRESSION)
                tokens.append(token)
                expr = []
        elif is_expr:
            expr.append(c)
        elif c in Token.SYMBOLS:
            token = Token(c, Token.SYMBOL)
            tokens.append(token)
        elif c == '(':
            token = Token(c, Token.LEFT_BRACKETS)
            tokens.append(token)
        elif c == ')':
            token = Token(c, Token.RIGHT_BRACKETS)
            tokens.append(token)

    return tokens

def make_sub_ast(stack, t):
    current = t
    while stack and stack[-1].root.type != Token.LEFT_BRACKETS:
        node = stack.pop()
        if node.root.type != Token.SYMBOL:
            raise Exception('parse error, excepted {0} but {1}'.format(Token.SYMBOL, node.root))
        node.right = current
        if node.root.value == '&' or node.root.value == '|':
            left = stack.pop()
            if left.root.type != Token.SYMBOL and left.root.type != Token.EXPRESSION:
                raise Exception('parse error, excepted {0} or {1} but {2}'.format(Token.SYMBOL,
                                                                                Token.EXPRESSION, left.root))
            node.left = left
        current = node
    stack.append(current)

def make_ast(tokens):
    stack = []
    for t in tokens:
        tree = ASTree(t)
        if tree.root.type == Token.SYMBOL or tree.root.type == Token.LEFT_BRACKETS:
            stack.append(tree)
        elif tree.root.type == Token.EXPRESSION:
            make_sub_ast(stack, tree)
        else:
            sub_tree = stack.pop()
            if sub_tree.root.type != Token.SYMBOL and sub_tree.root.type != Token.EXPRESSION:
                raise Exception('parse error, excepted {0} or {1} but {2}'.format(Token.SYMBOL,
                                                                                Token.EXPRESSION, sub_tree))
            tmp = stack.pop()
            if tmp.root.type != Token.LEFT_BRACKETS:
                raise Exception('paser error, excepted {0} but {1}'.format(Token.LEFT_BRACKETS, tmp))
            make_sub_ast(stack, sub_tree)
    return stack.pop()

def cacl(ast, line):
    if ast.root.type != Token.EXPRESSION:
        if ast.root.value == '!':
            return not cacl(ast.right, line)
        if ast.root.value == '&':
            return cacl(ast.left, line) and cacl(ast.right, line)
        if ast.root.value == '|':
            return cacl(ast.left, line) or cacl(ast.right, line)
    else:
        return re.search(ast.root.value, line) is not None

class Matcher:
    def __init__(self, name, origin):
        self.name = name
        self.origin = origin
        self.ast = make_ast(tokenize(origin))

    def match(self, line):
        return cacl(self.ast, line)


"""
Modifies a PDB file to be used for motif-scaffolding in order to make it monomeric.

1. Changes all chain-ids to be A (so that the protein is a monomer)
2. Aligns the axis of symmetry along the z-axis (requirement of RFDiffusion)
"""

from pathlib import Path
from shutil import copy as copy_file

import typer
import pandas as pd
from biotite.structure.io import load_structure, save_structure

from monomerizer import monomerizer, pdb

def main(
    input_pdb: Path = typer.Argument(..., help="PDB to be modified"),
    output_dir: Path = typer.Argument(..., help="Directory to hold outputs"),
    generator_steps: int = typer.Option(
        default=25, help="How many denoising steps to take."
    ),
    num_designs: int = typer.Option(
        default=3,
        help="How many structures RFDiffusion should generate per linker length",
    ),
    linker_lengths: str = typer.Option(
        default=None,
        help="List of lengths to use for linking, e.g. '10-20' or '12,15,17`, if not provided then choose automatically",
    ),
    trim_n: int = typer.Option(
        default=0, help="How many N-terminal residues to trim from each chain"
    ),
    trim_c: int = typer.Option(
        default=0, help="How many C-terminal residues to trim from each chain"
    ),
    num_selected: int = typer.Option(
        default=3, help="Top designs by symmetry to copy into the top output directory."
    ),
):
    """
    Change all chain-ids to A and align axis of cyclic symmetry to the z-axis for a given input PDB.

    Examples:
    make_monomer.py tests/pdbs/2XQS_short.pdb tmp/ --generator-steps=25 --linker-lengths=15 --num-designs=5
    make_monomer.py tests/pdbs/2XQS_short.pdb tmp/ --generator-steps=10 --linker-lengths=10-20 --num-designs=3
    make_monomer.py tests/pdbs/4JPP_short.pdb tmp/ --generator-steps=15 --linker-lengths=30 --num-designs=1
    """
    output_dir.mkdir(exist_ok=True, parents=True)

    # load, modify, and save the pdb structure
    unified_structure = load_structure(input_pdb)

    # perform structure modifications
    if (trim_n > 0) or (trim_c > 0):
        unified_structure = pdb.trim_termini(unified_structure, trim_n, trim_c)
    unified_structure = pdb.unify_chain_ids(unified_structure)

    # generate a template for what the contig map will look like
    base_contigs = monomerizer.generate_base_contigs(unified_structure)

    # add the pore
    pore_res_ids, pore_res_chain_id, unified_structure = pdb.fill_pore(
        unified_structure
    )
    # determine which residues the pore contacts or are buried, these should be fixed
    fixed_res_ids = monomerizer.get_fixed_res_ids(unified_structure, pore_res_ids)
    inpaint_contigs = monomerizer.generate_inpaint_contig(
        unified_structure, fixed_res_ids, pore_res_chain_id
    )

    unified_pdb = (output_dir / input_pdb.stem).with_suffix(".unified.pdb")
    save_structure(unified_pdb, unified_structure)

    # get the number of lengths/runs we need to complete
    if linker_lengths is None:
        res_lengths = monomerizer.get_res_range(unified_structure)
    else:
        res_lengths = monomerizer.parse_manual_res_range(linker_lengths)

    # scan over residue lengths and generate structures
    structures = monomerizer.generate_linked_structures(
        unified_pdb,
        pore_res_ids,
        pore_res_chain_id,
        output_dir,
        res_lengths,
        num_designs,
        base_contigs,
        inpaint_contigs,
        steps=generator_steps,
    )

    results = {
        "pdb": [structure.pdb_file for structure in structures],
        "linker_length": [structure.linker_length for structure in structures],
        "symmetry_rmsd": [structure.symmetry_rmsd for structure in structures],
    }
    results_df = pd.DataFrame().from_dict(results)
    results_df = results_df.sort_values(by="symmetry_rmsd")
    selected_dir = output_dir / "top"
    selected_dir.mkdir(exist_ok=True)
    for idx in range(min(num_selected, num_designs * len(res_lengths))):
        copy_file(
            results_df.iloc[idx].pdb,
            selected_dir / results_df.iloc[idx].pdb.name,
        )
    results_df.to_csv(output_dir / "results.csv")
    print(results_df)

if __name__ == "__main__":
    typer.run(main)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : redis.py
# @Author: Fred Yangxiaofei
# @Date  : 2019/9/4
# @Role  : 获取Aliyun Redis实例信息

import json
from aliyunsdkcore.client import AcsClient
from aliyunsdkr_kvstore.request.v20150101.DescribeInstancesRequest import DescribeInstancesRequest
from libs.db_context import DBContext
from libs.web_logs import ins_log
from models.db import DB
from models.server import AssetConfigs, model_to_dict
from opssdk.operate import MyCryptV2
import fire

class RedisApi():
    def __init__(self, access_id, access_key, region):
        self.idc = '阿里云'
        self.region = region
        self.access_id = access_id
        self.access_key = access_key

    def get_region_redis(self, page_number=1, page_size=50):
        try:
            clt = AcsClient(self.access_id, self.access_key, self.region)
            request = DescribeInstancesRequest()
            request.set_accept_format('json')
            request.set_PageNumber(page_number)
            request.set_PageSize(page_size)
            response = clt.do_action_with_exception(request)
            return json.loads(str(response, encoding="utf8"))
        except Exception as err:
            print(err)

        return {}

    def get_redis_all(self):
        page_num = 1
        while True:
            data = self.get_region_redis(page_num)
            if not data and 'Instances' not in data: break
            page_num += 1
            row = data['Instances']['KVStoreInstance']
            if not row: break
            # print的时候将yield去掉
            # print(list(map(self.format_redis, row)))
            res = list(map(self.format_redis, row))
            yield res

    def format_redis(self, redis_info):
        """
        处理下我们要入库的信息
        :return:
        """
        if not isinstance(redis_info, dict):
            raise TypeError

        asset_data = dict()

        asset_data['db_instance_id'] = redis_info.get('InstanceId')
        asset_data['db_code'] = redis_info.get('InstanceName')
        asset_data['db_region'] = redis_info.get('RegionId')
        asset_data['db_version'] = redis_info.get('EngineVersion')
        asset_data['db_port'] = redis_info.get('Port')
        asset_data['db_public_ip'] = redis_info.get('ConnectionDomain')
        asset_data['db_type'] = redis_info.get('InstanceType')
        asset_data['db_class'] = redis_info.get('ArchitectureType')
        asset_data['state'] = redis_info.get('InstanceStatus')
        asset_data['db_user'] = 'root'  # 没看到user的接口信息，但是我是必填项
        asset_data['db_host'] = redis_info.get('PrivateIp')
        if not asset_data['db_host']: asset_data['db_host'] = asset_data['db_public_ip']

        return asset_data

    def sync_cmdb(self):
        """
        入库
        :return:
        """
        redis_info_list = self.get_redis_all()
        if not redis_info_list: return False
        with DBContext('w') as session:
            for data in redis_info_list:
                for redis in data:
                    ins_log.read_log('info', 'redis信息：{}'.format(redis))
                    db_code = redis.get('db_code')

                    exist_redis = session.query(DB).filter(DB.db_code == db_code).first()

                    if exist_redis:
                        session.query(DB).filter(DB.db_code == db_code).update({
                            DB.idc: self.idc, DB.db_class: redis.get('db_class'), DB.db_host: redis.get('db_host'),
                            DB.db_port: redis.get('db_port'), DB.db_user: redis.get('db_user'),
                            DB.db_disk: redis.get('db_disk'), DB.db_region: redis.get('db_region'),
                            DB.db_type: redis.get('db_type'), DB.db_version: redis.get('db_version'),
                            DB.state: redis.get('state'), DB.db_mark: redis.get('db_mark'),
                            DB.db_public_ip: redis.get('db_public_ip'),
                            DB.db_instance_id: redis.get('db_instance_id')})
                    else:
                        new_db = DB(idc=self.idc, db_code=db_code, db_class=redis.get('db_class'),
                                    db_host=redis.get('db_host'), db_port=redis.get('db_port'),
                                    db_user=redis.get('db_user'), db_region=redis.get('db_region'),
                                    db_type=redis.get('db_type'),
                                    db_disk=redis.get('db_disk'), db_version=redis.get('db_version'),
                                    state=redis.get('state'), db_public_ip=redis.get('db_public_ip'),
                                    db_instance_id=redis.get('db_instance_id'))
                        session.add(new_db)
            session.commit()

    @staticmethod
    def permission_auth(access_id, access_key, region, page_number=1, page_size=1):
        """
        没有异常正常获取到1-1数据就是权限认证通过
        :param access_id: AccessID
        :param access_key:  AccessKey
        :param region:  RegionID
        :param page_number: 第几页
        :param page_size:  一页多少数量
        :return:
        """
        clt = AcsClient(access_id, access_key, region, timeout=5)
        request = DescribeInstancesRequest()
        request.set_accept_format('json')
        request.set_PageNumber(page_number)
        request.set_PageSize(page_size)
        response = clt.do_action_with_exception(request)
        # print('Permission_auth_res-->',response)
        return json.loads(str(response, encoding="utf8"))

def get_configs():
    """
    get id / key / region info
    :return:
    """

    aliyun_configs_list = []
    with DBContext('r') as session:
        aliyun_configs_info = session.query(AssetConfigs).filter(AssetConfigs.account == '阿里云',
                                                                 AssetConfigs.state == 'true').all()
        for data in aliyun_configs_info:
            data_dict = model_to_dict(data)
            data_dict['create_time'] = str(data_dict['create_time'])
            data_dict['update_time'] = str(data_dict['update_time'])
            aliyun_configs_list.append(data_dict)
    return aliyun_configs_list

def main():
    """
    从接口获取已经启用的配置
    :return:
    """
    mc = MyCryptV2()
    aliyun_configs_list = get_configs()
    if not aliyun_configs_list:
        ins_log.read_log('error', '没有获取到阿里云资产配置信息，跳过')
        return False
    for config in aliyun_configs_list:
        access_id = config.get('access_id')
        access_key = mc.my_decrypt(config.get('access_key'))  # 解密后使用
        region = config.get('region')
        obj = RedisApi(access_id, access_key, region)
        obj.sync_cmdb()

if __name__ == '__main__':
    fire.Fire(main)


class Solution:
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        if not digits:
            return []
        d_ch = {
            '2': 'abc',
            '3': 'def',
            '4': 'ghi',
            '5': 'jkl',
            '6': 'mno',
            '7': 'pqrs',
            '8': 'tuv',
            '9': 'wxyz'
        }
        return [''.join(x) for x in
                itertools.product(*[d_ch[c] for c in digits])]

python/17-Letter Combinations of a Phone Number.py


"""

Code to start the simulation

"""
import simpy
import random
import CacheNode as cn
import InterestGenerator as ig
import json
import os
import gc

config_file = 'config.json'

def config_loader(config_filename):
    # Read the generator parameters
    with open(config_filename) as json_data_file:
        data = json.load(json_data_file)
        duration = float(data["Simulator"]["Duration"])
        experiments = int(data["Simulator"]["nExperiments"])
        return duration, experiments

def launch_simulation(env, simulation_id=0):
    # Setup and start the simulation

    # Create traffic generator
    generator = ig.InterestGenerator(env)

    # Create a caching node
    cache = cn.CacheNode(env, duration=sim_duration, sim_identifier=simulation_id)
    generator.add_out_port(cache)

    # Start simulation
    generator.start(env)
    env.run(until=sim_duration)

    del generator
    del cache
    gc.collect()

def remove_previous_results():
    folder = 'Stats/'
    file_list = os.listdir(folder)

    for f in file_list:
        file_path = folder + '/' + f

        if os.path.isfile(file_path):
            os.remove(file_path)

    folder = 'Plots/Results/'
    file_list = os.listdir(folder)

    for f in file_list:
        file_path = folder + '/' + f

        if os.path.isfile(file_path):
            os.remove(file_path)

def modify_configuration(traffic_profile=1.2, cache_size=100):
    alpha = traffic_profile
    cache = cache_size
    with open(config_file, 'r+') as f:
        data = json.load(f)
        data["ContentStore"]["Alpha"] = str(alpha).replace("'", '"')
        data["Cache"]["Size"] = str(cache).replace("'", '"')
        f.seek(0)
        json.dump(data, f, indent=2)
        f.truncate()

traffic_prof = [1.2]
cache_size = [4]
sim_duration, n_experiments = config_loader(config_filename=config_file)
remove_previous_results()

Env = []

for prof in traffic_prof:
    for size in cache_size:
        modify_configuration(traffic_profile=prof, cache_size=size)
        for exp in range(n_experiments):
            print("Simulation %d/%d" % (exp+1, n_experiments))
            Env.append(simpy.Environment())
            random.seed(random.randint(0, 30000))
            launch_simulation(Env[-1], simulation_id=exp)


from django.contrib import messages
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.views import View
from django.db import connection
from pymysql import IntegrityError
import datetime
from .forms import CarPlate, MakeReservationForm, VehicleRate, CreateRequestForm, BranchRate, ReservationNo, Pay
from datetime import date

class PayVehicle(View):
    def post(self, request, resno):
        form = Pay(request.POST)

        if form.is_valid():
            branch_id = form.cleaned_data['branch']
            money = form.cleaned_data['money']
            plate = form.cleaned_data['plate']
            required_payment = form.cleaned_data['required_payment']
            res_no = form.cleaned_data['res_no']
            required_payment = float(required_payment)

            if required_payment != money:
                messages.error(request, 'Please enter correct amount.')
                return self.get(request, res_no)
            else:
                cursor = connection.cursor()
                sql = "UPDATE branch SET budget = budget + {} where branch_id = {};".format(money, branch_id)
                cursor.execute(sql)

                sql = "update vehicle set status = 'available', branch_id = {} where license_plate =  '{}';".format(
                    branch_id, plate)
                cursor.execute(sql)

                sql = "UPDATE reservation set status = 'paid' where reservation_number = {}".format(res_no)
                cursor.execute(sql)
                messages.success(request, 'Payment is taken. Thank you :)')
                return self.get(request, res_no)

        return redirect('/customer/error')

    def get(self, request, resno) -> 'html':
        user_id = request.session['logged_in_user']
        cursor = connection.cursor()
        sql = "SELECT discount_rate, user_id,customer_status FROM customer_discount NATURAL JOIN user WHERE user_id ={}".format(
            user_id)
        cursor.execute(sql)
        user_data = cursor.fetchall()
        discount_rate = user_data[0][0]

        sql = "SELECT reservation_number, license_plate, end_date, cost FROM reservation WHERE reservation_number = {}".format(
            resno)
        cursor.execute(sql)
        reservation = cursor.fetchall()

        res_no = reservation[0][0]
        license_plate = reservation[0][1]
        end_date = reservation[0][2]
        cost = reservation[0][3]

        today = date.today()
        if (((today - end_date).days) >= 0):
            fee_time = ((today - end_date).days)
        else:
            fee_time = 0

        if fee_time > 0:
            penalty = fee_time * 100
        else:
            penalty = 0
        total = cost + penalty

        discount = (total * int(discount_rate)) / 100

        form = Pay()
        context = {
            'res_no': res_no,
            'license_plate': license_plate,
            'discount_rate': discount_rate,
            'cost': cost,
            'penalty': penalty,
            'total': total,
            'discount': discount,
            'required_payment': total - discount,
            'form': form
        }
        return render(request, 'payVehicle.html', context)

class ReturnVehicle(View):

    def post(self, request):
        form = ReservationNo(request.POST)

        if form.is_valid():
            return redirect('customer:customer_pay_vehicle', resno=form.cleaned_data['ReservationNo'])

        return self.get(request)

    def get(self, request) -> 'html':
        user_id = request.session['logged_in_user']
        cursor = connection.cursor()
        sql = "SELECT reservation_number, license_plate, start_date,end_date,cost, status FROM `reservation` WHERE reserver = {} and status = 'accepted';".format(
            user_id)
        cursor.execute(sql)
        active_res = cursor.fetchall()

        sql = "SELECT discount_rate, user_id, customer_status FROM customer_discount NATURAL JOIN user WHERE user_id ={}".format(
            user_id)
        cursor.execute(sql)
        user_data = cursor.fetchall()

        discount_rate = user_data[0][0]
        user_status = user_data[0][2]

        form = ReservationNo()
        context = {
            'old_res': active_res,
            'form': form,
            'discount_rate': discount_rate,
            'user_status': user_status
        }
        return render(request, 'returnvehicles.html', context)

class RateBranch(View):

    def post(self, request):
        form = BranchRate(request.POST)

        if form.is_valid():
            customer_id = request.session['logged_in_user']
            branch_id = form.cleaned_data['branch']
            comment = form.cleaned_data['comment']
            score = form.cleaned_data['score']

            try:
                print("asdjkgnkjadfnhkadf")
                cursor = connection.cursor()
                sql = "INSERT INTO branch_rate (customer_id, branch_id, comment, score) VALUES ({}, {}, '{}', {});".format(
                    customer_id, branch_id, comment, score)
                cursor.execute(sql)
            except:
                messages.error(request, 'You already evaluated this branch.')
                return self.get(request)

            messages.success(request, 'You evaluation is saved.')
            return self.get(request)

        return redirect('/customer/error')

    def get(self, request):
        form = BranchRate()
        context = {
            'form': form,
            'message': ''
        }
        return render(request, 'ratebranch.html', context)

class CreateRequest(View):

    def post(self, request):
        form = CreateRequestForm(request.POST)
        user_id = request.session['logged_in_user']
        if form.is_valid():
            user_id = request.session['logged_in_user']
            license_plate = form.cleaned_data['license_plate']
            to_branch = form.cleaned_data['to_branch']
            reason = form.cleaned_data['reason']
            cursor = connection.cursor()

            sql = """SELECT branch_id FROM vehicle WHERE license_plate = "{}";""".format(license_plate)
            cursor.execute(sql)
            from_branch = cursor.fetchall()[0][0]
            if int(from_branch) == int(to_branch):
                cursor = connection.cursor()
                sql = "SELECT * FROM request, (SELECT branch_id, branch_name FROM branch) AS from_branch_name, " \
                      "(SELECT branch_id, branch_name FROM branch) AS to_branch_name " \
                      "WHERE from_branch = from_branch_name.branch_id and to_branch = to_branch_name.branch_id and made_by_customer = {};".format(user_id)
                cursor.execute(sql)
                old_req = cursor.fetchall()
                form = CreateRequestForm()
                context = {
                    'old_req': old_req,
                    'form': form,
                    'message': 'Error occured.'
                }
                return render(request, 'customerRequest.html', context)
            sql = "INSERT INTO request " \
                  "(req_id, made_by_customer, from_branch, to_branch, requested_vehicle, checked_by_employee, isApproved, reason) " \
                  "VALUES (NULL, {}, {}, {}, '{}', NULL, NULL, '{}');".format(user_id, from_branch, to_branch,
                                                                              license_plate, reason)
            cursor.execute(sql)
            sql = "SELECT * FROM request, (SELECT branch_id, branch_name FROM branch) AS from_branch_name, (SELECT branch_id, branch_name FROM branch) AS to_branch_name WHERE from_branch = from_branch_name.branch_id and to_branch = to_branch_name.branch_id and made_by_customer = {};".format(user_id)
            cursor.execute(sql)
            old_req = cursor.fetchall()
            form = CreateRequestForm()
            context = {
                'old_req': old_req,
                'form': form,
                'message': 'Request is taken.',
            }
            return render(request, 'customerRequest.html', context)

        cursor = connection.cursor()
        sql = "SELECT * FROM request, (SELECT branch_id, branch_name FROM branch) AS from_branch_name, (SELECT branch_id, branch_name FROM branch) AS to_branch_name WHERE from_branch = from_branch_name.branch_id and to_branch = to_branch_name.branch_id and made_by_customer = {};".format(user_id)
        cursor.execute(sql)
        old_req = cursor.fetchall()
        form = CreateRequestForm()
        context = {
            'old_req': old_req,
            'form': form,
            'message': 'Error occured.'
        }
        return render(request, 'customerRequest.html', context)

    def get(self, request) -> 'html':
        user_id = request.session['logged_in_user']
        cursor = connection.cursor()
        sql = "SELECT * FROM request, (SELECT branch_id, branch_name FROM branch) AS from_branch_name, (SELECT branch_id, branch_name FROM branch) AS to_branch_name WHERE from_branch = from_branch_name.branch_id and to_branch = to_branch_name.branch_id and made_by_customer = {};".format(user_id)
        cursor.execute(sql)
        old_req = cursor.fetchall()
        form = CreateRequestForm()
        context = {
            'old_req': old_req,
            'form': form,
            'message': ''
        }
        return render(request, 'customerRequest.html', context)

class RateCar(View):

    def post(self, request):
        form = VehicleRate(request.POST)

        if form.is_valid():
            license_plate = form.cleaned_data['license_plate']
            comment = form.cleaned_data['comment']
            rate = form.cleaned_data['rate']
            user_id = request.session['logged_in_user']
            cursor = connection.cursor()
            try:
                sql = "INSERT INTO vehicle_rate (customer_id, license_plate, comment, score) " \
                      "VALUES ({}, '{}', '{}', {});".format(user_id, license_plate, comment, rate)
                cursor.execute(sql)
            except:
                messages.error(request, 'You already evaluated this vehicle.')
                return self.get(request)

            messages.success(request, 'Your evaluation is saved.')
            return self.get(request)

    def get(self, request) -> 'html':
        user_id = request.session['logged_in_user']
        cursor = connection.cursor()
        sql = "SELECT * FROM `reservation` WHERE reserver = {} and status = 'paid';".format(user_id)
        cursor.execute(sql)
        old_res = cursor.fetchall()
        form = VehicleRate()
        context = {
            'old_res': old_res,
            'userid': user_id,
            'form': form
        }
        return render(request, 'ratevehicles.html', context)

class MakeReservation(View):

    def post(self, request):

        user_id = request.session['logged_in_user']
        error_message = ''

        form = MakeReservationForm(request.POST, user=user_id, license_plate=None, daily_cost=None)
        if form.is_valid():
            reserver_id = form.cleaned_data['reserver_id']
            reason = form.cleaned_data['reason']
            license_plate = form.cleaned_data['license_plate']
            daily_cost = form.cleaned_data['daily_cost']
            start_date = form.cleaned_data['start_date']
            end_date = form.cleaned_data['end_date']
            chauffeur_id = form.cleaned_data['chauffeur_id']
            insurance_type = form.cleaned_data['insurance_type']
            if start_date > end_date:
                return redirect('/customer/errorDate')

            rental_period_in_days = abs((end_date - start_date).days)
            if rental_period_in_days == 0:
                rental_period_in_days = 1

            cost = rental_period_in_days * daily_cost

            cursor = connection.cursor()
            print(insurance_type != 'NULL')
            if insurance_type != 'NULL':
                sql = "SELECT insurance_type FROM `insurance` WHERE insurance_price = {};".format(insurance_type)
                cursor.execute(sql)
                insurances = cursor.fetchall()
                insurance_type = insurances[0][0]

            # some assertions are needed before inserting a new reservation

            # assertion 1- if the car to be reserved is not available

            #assertion 2- if you already have an reservation that day

            #these two assertions are provided at triggers

            #assertion 3- if the user has not paid for a reservation before
            assertion_3_sql = " select * from reservation where reserver = " + str(user_id) + " and status = \'not_paid\'"
            cursor.execute(assertion_3_sql)
            result = cursor.fetchall()
            if len(result) != 0:
                print('hfjdfhdjfj')
                error_message = 'First pay your previous reservations'
                return render(request, 'error.html', {'message': error_message})

            #assertion 4- if user driving license info doesnt allow it to rent this car
            assertion_4_sql = "select car_type from vehicle natural join car where license_plate = \'" + str(license_plate) + '\';'
            cursor.execute(assertion_4_sql)
            result_car_type = cursor.fetchall()
            result_car_type = result_car_type[0]

            cursor.execute('select license_type from driving_license where user_id = \'' + str(user_id) + '\';')
            result_user_license = cursor.fetchall()
            result_user_license = result_user_license[0]
            if result_user_license[0][0:1] != result_car_type[0] and chauffeur_id == 'NULL':
                error_message = 'You cannot drive this car, you need a chaeffuer'
                return render(request, 'error.html', {'message': error_message})

            sql = """
            INSERT INTO `reservation`
            (`start_date`, `end_date`, `status`, `cost`, `reserver`,
            `checked_by`, `isApproved`, `reason`, `insurance_type`, `license_plate`, `reserved_chauf_id`, `isChaufAccepted`)
            VALUES ('{}', '{}', 'not_accepted', '{}', '{}', NULL, 'false', '{}', '{}', '{}', {}, NULL);
        """.format(start_date, end_date, cost, reserver_id, reason, insurance_type, license_plate,
                   chauffeur_id)

            print(sql)
            try:
                cursor.execute(sql)
            except Exception as ex:
                error_message = 'It is not available to make reservation'
                return render(request, 'error.html', {'message': error_message})

            return redirect('/customer/reservationsuccess')

        return render(request, 'error.html', {'message': error_message})

    def get(self, request, plate) -> 'html':
        cursor = connection.cursor()
        sql = "SELECT * FROM vehicle where license_plate = \'{}\';".format(plate)
        cursor.execute(sql)
        vehicle = cursor.fetchall()
        vehicleTuple = vehicle[0]

        user_id = request.session['logged_in_user']

        form = MakeReservationForm(user=user_id, license_plate=vehicleTuple[0], daily_cost=vehicleTuple[2])
        context = {
            'vehicle': vehicle[0],
            'userid': request.session['logged_in_user'],
            'form': form
        }
        return render(request, 'makeReservation.html', context)

class CustomerDashboard(View):

    def post(self, request):
        form = CarPlate(request.POST)

        if form.is_valid():
            return redirect('customer:customer_make_res', plate=form.cleaned_data['plate'])

        return render(request, 'customerDashboard.html')

    def get(self, request) -> 'html':
        user_id = request.session['logged_in_user']
        cursor = connection.cursor()
        cursor.execute(
            'SELECT * FROM vehicle NATURAL JOIN branch WHERE status = \'available\';'
        )
        desc = cursor.fetchall()

        # some statistics for the customer
        cursor.execute('SELECT (select branch_name from branch where branch_id = V.branch_id) as name, count(*) as number_of_reservations, (select score from branch_rate where branch_id = V.branch_id and customer_id = R.reserver) as your_score, avg(cost) as cost FROM reservation R, vehicle V where R.license_plate = V.license_plate and R.reserver = ' + str(user_id) + ' and R.status <> \'canceled\' group by V.branch_id;')
        result = cursor.fetchall()
        for res in result:
            print(res)

        context = {
            'vehicles': desc,
            'info': result,
        }
        return render(request, 'customerDashboard.html', context)

class Error(View):

    def get(self, request):
        return render(request, 'error.html')

class DateError(View):
    def get(self, request):
        return render(request, 'errorDate.html')

class ReservationComplate(View):
    def get(self, request):
        return render(request, 'reservationcomplate.html')

class ListReservations(View):
    def get(self, request):
        reserver = request.session['logged_in_user']

        cursor = connection.cursor()
        cursor.execute(
            'SELECT * FROM reservation WHERE reserver =' + str(reserver) + ';'
        )
        result = cursor.fetchall()
        context = {
            'reservations': result
        }
        return render(request, 'listReservations.html', context)

class OrderReservations(View):
    def post(self, request):
        order = request.POST['order-by']
        reserver = request.session['logged_in_user']
        cursor = connection.cursor()

        if int(order) == 1:
            cursor.execute(
                'SELECT * FROM reservation WHERE reserver =' + str(reserver) + ' order by start_date;'
            )
        elif int(order) == 2:
            cursor.execute(
                'SELECT * FROM reservation WHERE reserver =' + str(reserver) + ' order by cost;'
            )
        else:
            cursor.execute(
                'SELECT * FROM reservation WHERE reserver =' + str(reserver) + ' order by end_date;'
            )
        result = cursor.fetchall()
        context = {
            'reservations': result
        }
        return render(request, 'listReservations.html', context)

class PenaltiesView(View):
    def get(self, request):
        reserver = request.session['logged_in_user']
        sql = "SELECT issue_id, description, dr.cost, author_expertise_id, license_plate FROM damage_report dr, reservation r WHERE r.reservation_number = dr.issued_reservation and r.reserver = {}".format(reserver)
        cursor = connection.cursor()
        cursor.execute(sql)
        userPenalties = cursor.fetchall()
        context = {'penalties' : userPenalties, 'message' : ""}
        return render(request, 'listPenalties.html', context)
    def post(self, request):
        reserver = request.session['logged_in_user']
        issue = request.POST.get('issueId', "")
        sql = "DELETE FROM damage_report WHERE issue_id = {}".format(issue)
        cursor = connection.cursor()
        cursor.execute(sql)
        sql = "SELECT issue_id, description, dr.cost, author_expertise_id, license_plate FROM damage_report dr, reservation r WHERE r.reservation_number = dr.issued_reservation and r.reserver = {}".format(reserver)
        cursor = connection.cursor()
        cursor.execute(sql)
        userPenalties = cursor.fetchall()
        context = {'penalties' : userPenalties, 'message' : "Successfully paid penalty."}
        return render(request, 'listPenalties.html', context)

def cancelReservation( request):
    reservation = request.GET.get('reservation', None)
    customer = request.GET.get('customer', None)

    cursor = connection.cursor()
    cursor.execute('update reservation set status = \'canceled\' where reservation_number = ' + str(reservation) + ';')

    data = {}
    data['canceled'] = True
    return JsonResponse(data)


from pygame import *

init()
size = width, height = 800, 600
screen = display.set_mode(size)

green = 0, 255, 0
red = 255, 0, 0
black=0,0,0
white=255,255,255
baymax=image.load("Paint Project/Pictures/Baymax.png")

running = True

while running:
    for evnt in event.get():
        if evnt.type == QUIT:
            running = False
    mx,my=mouse.get_pos()
    mb=mouse.get_pressed()

    if mouse.get_pressed()[0]==1:
                                  #to make it centred move by half the length.width
        screen.blit(baymax,(mx,my))

    display.flip()

quit()


import sys
import os
from distutils.core import setup, Extension

USE_CPP = (os.environ.get('TEST_USE_CPP') == 'yes')

# The C/C++ source is the same, but GCC recognizes the language by extension,
# so use a symlink named 'test_py3c.cpp' for C++.
# (there's also a gcc -x switch, but it needs to go before the filename;
# I don't think setuptools allows that)
if USE_CPP:
    sources = ['test_py3c.cpp', 'test_empty.cpp']
else:
    sources = ['test_py3c.c', 'test_empty.c']

extra_compile_args = []
extra_compile_args.extend(['-Werror', '-Wall'])
if sys.version_info < (2, 7):
    # XXX: The PyCapsule (2.6) shim tests aren't yet warning-free in GCC
    extra_compile_args.extend(['-Wno-format'])

test_py3c_module = Extension(
    'test_py3c',
    sources=sources,
    include_dirs=['../include'],
    extra_compile_args=extra_compile_args,
)
test_py3c_module.extra_compile_args=extra_compile_args

setup_args = dict(
    name='test_py3c',
    version='0.0',
    description = '',
    ext_modules = [test_py3c_module]
)

if __name__ == '__main__':
    setup(**setup_args)


from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission

def set_permissions(api_client, permissions):
    """
    Set permissions for api_client user.

    Just setting the permissions for the user isn't enough because then
    Django will use cached permissions in views.
    """
    if type(permissions) == str:
        permissions = [permissions]

    codenames = [perm.split('.')[1] for perm in permissions]

    user = api_client.user
    user.user_permissions.set(Permission.objects.filter(codename__in=codenames))
    user = get_user_model().objects.get(pk=user.pk)
    api_client.force_authenticate(user)

def check_attribute_errors(errors, attribute, expected_error):
    """
    Assert attribute error exists in given error dict

    :param errors: attribute error dict
    :param attribute: Attribute object to check
    :param expected_error: part of expected error message
    """
    error_list = errors['attributes'].get(attribute.identifier)
    assert error_list is not None, 'no attribute "%s" in errors' % attribute.identifier
    assert any(expected_error in error for error in error_list), '"%s" not in %s' % (expected_error, errors)

def assert_response_functions(response, objects):
    """
    Assert Function object or objects exist in response data.
    """
    data = response.data
    if 'results' in data:
        data = data['results']

    if not (isinstance(objects, list) or isinstance(objects, tuple)):
        objects = [objects]

    expected_ids = {obj.uuid.hex for obj in objects}
    actual_ids = {str(obj['id']) for obj in data}
    assert expected_ids == actual_ids, '%s does not match %s' % (expected_ids, actual_ids)

def get_bulk_update_function_key(function):
    return '{uuid}__{version}'.format(uuid=function.uuid.hex, version=function.version)


from typing import List, Optional

import pytest

from langchain_community.docstore.document import Document
from langchain_community.vectorstores import Yellowbrick
from tests.integration_tests.vectorstores.fake_embeddings import (
    FakeEmbeddings,
    fake_texts,
)

YELLOWBRICK_URL = "postgres://username:password@host:port/database"
YELLOWBRICK_TABLE = "test_table"

def _yellowbrick_vector_from_texts(
    metadatas: Optional[List[dict]] = None, drop: bool = True
) -> Yellowbrick:
    return Yellowbrick.from_texts(
        fake_texts,
        FakeEmbeddings(),
        metadatas,
        YELLOWBRICK_URL,
        YELLOWBRICK_TABLE,
    )

@pytest.mark.requires("yb-vss")
def test_yellowbrick() -> None:
    """Test end to end construction and search."""
    docsearch = _yellowbrick_vector_from_texts()
    output = docsearch.similarity_search("foo", k=1)
    docsearch.drop(YELLOWBRICK_TABLE)
    assert output == [Document(page_content="foo", metadata={})]

@pytest.mark.requires("yb-vss")
def test_yellowbrick_with_score() -> None:
    """Test end to end construction and search with scores and IDs."""
    texts = ["foo", "bar", "baz"]
    metadatas = [{"page": i} for i in range(len(texts))]
    docsearch = _yellowbrick_vector_from_texts(metadatas=metadatas)
    output = docsearch.similarity_search_with_score("foo", k=3)
    docs = [o[0] for o in output]
    distances = [o[1] for o in output]
    docsearch.drop(YELLOWBRICK_TABLE)
    assert docs == [
        Document(page_content="foo", metadata={"page": 0}),
        Document(page_content="bar", metadata={"page": 1}),
        Document(page_content="baz", metadata={"page": 2}),
    ]
    assert distances[0] > distances[1] > distances[2]

@pytest.mark.requires("yb-vss")
def test_yellowbrick_add_extra() -> None:
    """Test end to end construction and MRR search."""
    texts = ["foo", "bar", "baz"]
    metadatas = [{"page": i} for i in range(len(texts))]
    docsearch = _yellowbrick_vector_from_texts(metadatas=metadatas)
    docsearch.add_texts(texts, metadatas)
    output = docsearch.similarity_search("foo", k=10)
    docsearch.drop(YELLOWBRICK_TABLE)
    assert len(output) == 6


import serial
import numpy as np
import time
import threading

portx="COM2"
bps=9600
timex=5
#串口执行到这已经打开 再用open命令会报错
exit = 0

class myThread1 (threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        index = 0
        while(True):
            if exit:
                break
            data_send = "s"+str(index)+"e\n"
            ser.write(data_send.encode())
            index = index + 1
            if index > 200:
                index = 0
            time.sleep(0.05)

class myThread2 (threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        global exit ;
        a = input()
        if a == "e":
            exit = 1

ser = serial.Serial(portx, int(bps), timeout=1, parity=serial.PARITY_NONE,stopbits=1)
if (ser.isOpen()):
    print("open success")
else:
	print("open failed")

thread1 = myThread1()
thread2 = myThread2()

thread1.start()
thread2.start()

thread1.join()
thread2.join()

print("exit!!!")


class Node:
    def __init__(self, d):
        self.next = None
        self.data = d

def init_nodes():
    node_1 = Node(1)
    node_2 = Node(2)
    node_3 = Node(3)
    node_4 = Node(4)

    node_1.next = node_2
    node_2.next = node_3
    node_3.next = node_4

    return node_1

def swap_nodes(head, x, y):
    if x == y:
        return head

    prev_x = None
    cur_node_x = head
    cur_node_y = head
    while cur_node_x and cur_node_x.data != x:
        prev_x = cur_node_x
        cur_node_x = cur_node_x.next

    prev_y = None
    while cur_node_y and cur_node_y.data != y:
        prev_y = cur_node_y
        cur_node_y = cur_node_y.next

    if prev_y != None:
        prev_y.next = cur_node_x
    else:
        head = cur_node_x

    if cur_node_y == None or cur_node_x == None:
        return False

    if prev_x != None:
        prev_x.next = cur_node_y
    else:
        head = cur_node_y

    temp_next_node_y = cur_node_y.next
    cur_node_y.next = cur_node_x.next
    cur_node_x.next = temp_next_node_y

    return head

def print_linkedlist(current_node):
    while current_node != None:
        print(current_node.data)
        current_node = current_node.next

def swap_nodes_in_pairs(node):

    i = 1
    head = node

    for i in range(1,4):
        if i % 2 == 1:
            head = swap_nodes(head, i, i+1)
    return head

node_1 = init_nodes()
# print(swap_nodes_in_pairs(node_1).data)
print_linkedlist(swap_nodes_in_pairs(node_1))

# swap_nodes(node_1, 2, 4)

# head_1 = swap_nodes(node_1, 1, 2)
# print("1st test")
# print(print_linkedlist(head_1))
# print()
# head_2 = swap_nodes(node_1, 2, 3)
# print("2nd test")
# print(print_linkedlist(head_2))
# print()
# head_3 = swap_nodes(head_1, 3, 4)
# print("3rd test")
# print(print_linkedlist(head_3))


# brute force
def sortedSquares(self, nums):
        nArr = []
        for i in nums:
           nArr.append(i * i)

        return sorted(nArr)

def sortedSquares2(nums):
      nArr = []
      l,r = 0, len(nums)-1

      while l<=r:
            if nums[l] * nums[l] >  nums[r] * nums[r]:
                  nArr.append(nums[l] * nums[l])
                  l += 1
            else:
                  nArr.append(nums[r]*nums[r])
                  r -= 1

      return nArr[::-1]

print(sortedSquares2([-4,-1,0,3,10]))

DongheonRyu/2023-09-13-Squares of a Sorted Array.py


#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time  : 12/8/2021 10:53 PM
# @Author: yzf
import os
import sys
import argparse
import logging
import random
import time
import shutil
import importlib
import numpy as np
from torch.utils.data import DataLoader
from datasets.augmentations import MeanStdNorm
from datasets.chaos.chaos_dataset import CHAOSTwoStream
from losses.losses import *
from utils.utils import *
from utils.metrics import compute_dice
from models.consistency_reglur_memory import ConsistencyRegulr
import matplotlib.pyplot as plt

parser = argparse.ArgumentParser()
## Baseline options
## Session
parser.add_argument('--gpu', type=str, default='0')

parser.add_argument('--seed', type=int, default=1)

parser.add_argument('--dataset', type=str, default='chaos',
                    help='dataset name')

parser.add_argument('--root', type=str, default='./outputs/chaos',
                    help='root directory')

parser.add_argument('--session', type=str, default='Control',
                    choices=['Control', 'Experiment'],
                    help='session name')

parser.add_argument('--tag', type=str, required=True,
                    help='experiment name')

## Dataset
parser.add_argument('--fold', type=int, default=1, choices=[0, 1, 2, 3, 4],
                    help='fold index to perform cross-validation')

parser.add_argument('--modality', type=str, default='t1', choices=['t1', 't2'],
                    help='modality of MRI images')

parser.add_argument('--num_classes', type=int, default=5,
                    help='number of classes (including background and not including ignored class)')

parser.add_argument('--num_workers', type=int, default=4,
                    help='number of processes to load data')

parser.add_argument('--augmentation_configs', type=str, default='datasets.chaos.chaos_aug_configs',
                    help='augmentation configuration module')

parser.add_argument('--augmentations', type=str, default='TransformsColor',
                    choices=['TransformsColor', 'TransformsColorBlur', 'TransformsColorMixup', 'TransformsColorLow'],
                    help='specify augmentation sequence')

## Network
# Backbone
parser.add_argument('--input_ch', type=int, default=1,
                    help='number of network input channel(s)')

parser.add_argument('--init_ch', type=int, default=32, choices=[32],
                    help='number of channels')

parser.add_argument('--max_ch', type=int, default=512, choices=[512, 1024, 728],
                    help='maximum number of channels')

parser.add_argument('--output_stride', type=int, default=8, choices=[32, 16, 8],
                    help='the stride of encoder output')

parser.add_argument('--is_stride_conv', type=bool, default=False,
                    help='whether to use stride conv or maxpool')

parser.add_argument('--is_trans_conv', type=bool, default=False,
                    help='whether to use trans conv or upsample')

parser.add_argument('--elab_end_points', type=bool, default=True,
                    help='whether to elaborate end points')

## Optimizer
parser.add_argument('--ignored_index', type=int, default=5,
                    help='the value indexing ignored regions')

parser.add_argument('--epoch', type=int, default=400, choices=[200, 400, 600],
                    help='number of epoch')

parser.add_argument('--batch_size', type=int, default=12, choices=[8, 12, 16, 24],
                    help='bacth size')

parser.add_argument('--optimizer', type=str, default='adam', choices=['adam', 'momentum'],
                    help='the optimizer')

parser.add_argument('--momentum', type=float, default=0.9,
                    help='the momentum value of SGD optimizer')

parser.add_argument('--lr', type=float, default=0.0001, choices=[0.0001, 0.0003, 0.0005],
                    help='base learning rate')

parser.add_argument('--lr_decay', type=str, default='poly', choices=['linear', 'poly', 'cosine'],
                    help='learning rate decay policy')

parser.add_argument('--wd', type=float, default=0.0003, choices=[0.0003, 0.0001, 0.0005],
                    help='weight decay')

parser.add_argument('--ckp_interval', type=int, default=10000,
                    help='interval of saving checkpoints')

## Baseline plus options
## Entropy minimization
parser.add_argument('--do_loss_ent', action='store_true', default=False,
                    help='whether to use entropy minimization loss')

parser.add_argument('--loss_ent_weight', type=float, default=1.,
                    help='weight of entropy minimization loss')

parser.add_argument('--ramp_up_loss_ent', action='store_true', default=True,
                    help='whether to ramp up entropy minimization loss')

parser.add_argument('--ramp_up_scale', type=float, default=8., choices=[5., 8., 10.],
                    help='exponential scale of ramping up')

## Consistency options
parser.add_argument('--do_decoder_consistency', action='store_true', default=False,
                    help='whether to impose consistency regularization on decoder outputs')

parser.add_argument('--ramp_up_loss_cr', action='store_true', default=True,
                    help='whether to ramp up consistency regularization loss')

parser.add_argument('--detach_weak_cr', action='store_true', default=False,
                    help='whether to detach the weak probability')

parser.add_argument('--loss_cr_variants', type=str, default='ce_loss', choices=['ce_loss', 'l1_loss', 'l2_loss', 'kl_loss'],
                    help='specify variants of consistency regularization loss')

parser.add_argument('--strength', type=float, default=1., choices=[0.125, 0.25, 0.5, 1.],
                    help='the strength of color distortion')

parser.add_argument('--loss_cr_weight', type=float, default=1.,
                    help='weight of consistency regularization loss')

## Auxiliary path
parser.add_argument('--do_aux_path', action='store_true', default=False,
                    help='whether to adopt auxiliary path')

parser.add_argument('--feat_stage', type=list, default=['encoder/stage6', 'encoder/stage5'],
                    choices=[['encoder/stage6'], ['encoder/stage6', 'encoder/stage5'], ['encoder/stage6', 'encoder/stage5', 'encoder/stage4']],
                    help='feature from which stage to perform memory storage')

parser.add_argument('--feat_ch', type=list, default=[512, 512],
                    choices=[[512], [512, 512], [512, 512, 256]],
                    help='number of channels of the encoder output')

parser.add_argument('--loss_aux_weight', type=float, default=0.01, choices=[1., 0.01, 0.001],
                    help='weight of auxiliary loss')

parser.add_argument('--hid_ch', type=int, default=64, choices=[256, 128, 64],
                    help='number of channels of features in memory bank')

parser.add_argument('--aux_drop_prob', type=float, default=0., choices=[0., 0.5, 0.8],
                    help='dropout probability')

## Memory bank options
parser.add_argument('--do_memory', action='store_true', default=False,
                    help='whether to do memory bank')

parser.add_argument('--loss_memory_weight', type=float, default=1, choices=[1., 0.01],
                    help='weight of memory loss')

parser.add_argument('--update_momentum', type=float, default=0.9,
                    help='memory update momentum')

parser.add_argument('--ensemble_mode', type=str, default='cosine_similarity', choices=['cosine_similarity', 'mean'],
                    help='method to ensemble pixel features')

def train_interface(args):
    # This line makes specifying cuda devices ineffective.
    from torch.utils.tensorboard import SummaryWriter
    os.makedirs(os.path.join(args.child, 'tb_summary'))
    tb_writer = SummaryWriter(log_dir=os.path.join(args.child, 'tb_summary'))
    best_avg, best_epoch, best_avg_class = 0, 0, []

    model = ConsistencyRegulr(
        # Backbone kwargs
        kwargs_unet=dict(
            input_ch=args.input_ch,
            init_ch=args.init_ch,
            max_ch=args.max_ch,
            num_classes=args.num_classes,
            output_stride=args.output_stride,
            is_stride_conv=args.is_stride_conv,
            is_trans_conv=args.is_trans_conv,
            elab_end_points=args.elab_end_points,
            ),
        # Auxiliary path kwargs
        kwargs_aux_path=dict(
            num_classes=args.num_classes,
            feat_stage=args.feat_stage,
            feat_ch=args.feat_ch,
            hid_ch=args.hid_ch,
            aux_drop_prob=args.aux_drop_prob,
            do_memory=args.do_memory,
            max_step=args.epoch,
            update_momentum=args.update_momentum,
            ensemble_mode=args.ensemble_mode,
        ),
        args_parser=args
        ).cuda()
    logging.info(model)
    model_path, _, model_name = model.__module__.rpartition('.')
    shutil.copy(os.path.join(model_path, model_name+'.py'), os.path.join(args.child, model_name+'.py'))

    if args.optimizer == 'adam':
        optimizer = torch.optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.wd)
    elif args.optimizer == 'momentum':
        optimizer = torch.optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum, weight_decay=args.wd)
    else:
        raise ValueError('Unimplemented optimizer')

    # Prepare dataset
    transforms = getattr(importlib.import_module(args.augmentation_configs), args.augmentations)(args.strength)
    train_dataset = CHAOSTwoStream(args.train_ls,
                                  args.num_classes,
                                  base_transforms=transforms.base_transforms,
                                  strong_transforms=transforms.strong_transforms,
                                  do_strong=args.do_decoder_consistency)
    val_dataset = CHAOSTwoStream(args.val_ls,
                                args.num_classes,
                                base_transforms=[MeanStdNorm()],
                                strong_transforms=None,
                                do_strong=False)
    train_dataloader = DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True, num_workers=args.num_workers, drop_last=True)
    val_dataloader = DataLoader(val_dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers, drop_last=False)
    num_iterations = args.epoch * (len(train_dataset) // args.batch_size)

    # Training
    valdice = np.zeros(args.epoch)
    for curr_epoch in range(args.epoch):
        epoch_tic = time.time()
        meter_loss_pce = AvgMeter()
        meter_loss_ent = AvgMeter()
        meter_loss_cr = AvgMeter()
        meter_loss_aux_cls = AvgMeter()
        meter_loss_memory = AvgMeter()

        # Learning rate decay strategy
        # new_lr can be got by optimizer.param_groups[0]['lr']
        if args.lr_decay == 'poly':
            optimizer, new_lr = poly_lr_decay(optimizer, curr_epoch, args.epoch, args.lr)
        elif args.lr_decay == 'cosine':
            optimizer, new_lr = cosine_lr_decay(optimizer, curr_epoch, args.epoch, args.lr)
        elif args.lr_decay == 'linear':
            optimizer, new_lr = linear_lr_decay(optimizer, curr_epoch, args.epoch, args.lr)
        else:
            raise ValueError('Unimplemented learning rate decay policy.')

        ## Training
        for idx, batch in enumerate(train_dataloader):
            del batch['label']
            if args.do_decoder_consistency:
                del batch['label_strong']
            for key, val in batch.items():
                if isinstance(val, torch.Tensor):
                    batch[key] = val.cuda()

            # Forward
            net_outputs = model(batch, mode='train', step=curr_epoch)
            loss_pce = net_outputs['loss_pce']
            loss = loss_pce
            meter_loss_pce.update(loss_pce.item(), n=batch['image'].shape[0])

            if args.do_loss_ent:
                loss_ent = net_outputs['loss_ent']
                if args.ramp_up_loss_ent:
                    w = gaussian_ramp_up(t=curr_epoch, base_value=args.loss_ent_weight, scale=args.ramp_up_scale)
                    loss_ent = loss_ent * w
                loss += loss_ent
                meter_loss_ent.update(loss_ent.item(), n=batch['image'].shape[0])

            if args.do_decoder_consistency:
                loss_cr = net_outputs['loss_cr']
                if args.ramp_up_loss_cr:
                    w = gaussian_ramp_up(t=curr_epoch, base_value=args.loss_cr_weight, scale=args.ramp_up_scale)
                    loss_cr = loss_cr * w
                loss += loss_cr
                meter_loss_cr.update(loss_cr.item(), n=batch['image'].shape[0])

            # The memory classification could regularize training with improved performance.
            if args.do_aux_path:
                loss_aux_cls = net_outputs['loss_aux_cls']
                w = args.loss_aux_weight
                # if args.ramp_up_loss_aux:
                #     w = gaussian_ramp_up(t=curr_epoch, base_value=args.loss_aux_weight, scale=args.ramp_up_scale)
                loss_aux_cls *= w
                loss += loss_aux_cls
                meter_loss_aux_cls.update(loss_aux_cls.item(), n=batch['image'].shape[0])

                if args.do_memory:
                    loss_memory = net_outputs['loss_memory']
                    w = args.loss_memory_weight
                    # if args.ramp_up_loss_aux:
                    #     w = gaussian_ramp_up(t=curr_epoch, base_value=args.loss_memory_weight, scale=args.ramp_up_scale)
                    loss_memory *= w
                    loss += loss_memory
                    meter_loss_memory.update(loss_memory.item())

            # Update
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
        epoch_toc = time.time()
        # After one epoch, log information
        logging.info("epoch: {:03d}, lr: {:.6f}, loss_pce: {:.6f}, loss_ent: {:.6f}, loss_cr: {:.6f}, loss_aux_cls: {:.6f}, loss_memory: {:.6f}, {:.2f} s/epoch"
                     .format(curr_epoch, new_lr, meter_loss_pce.avg, meter_loss_ent.avg, meter_loss_cr.avg, meter_loss_aux_cls.avg, meter_loss_memory.avg, epoch_toc-epoch_tic))

        # Tensorboard monitoring
        # Weak image
        summary_image = batch['image'].detach().cpu()[0, 0]
        fig = plt.figure(); plt.subplot(); plt.imshow(summary_image, 'gray')
        tb_writer.add_figure('predictions/image', fig, curr_epoch)

        # Scribble image
        summary_scribble = batch['scribble'].detach().cpu().argmax(1)[0]
        fig = plt.figure(); plt.subplot(); plt.imshow(summary_scribble, interpolation='nearest')
        tb_writer.add_figure('predictions/scribble', fig, curr_epoch)

        # Weak probability
        logits_weak = net_outputs.get('segmentation/logits')
        prediction_weak = logits_weak.detach().cpu().softmax(1).argmax(1)[0]
        fig = plt.figure(); plt.subplot(); plt.imshow(prediction_weak)
        tb_writer.add_figure('predictions/prediction_decoder_weak', fig, curr_epoch)
        # Histogram of probability weak maximum
        prob_weak_max = logits_weak.detach().cpu().softmax(1).max(1)[0]
        tb_writer.add_histogram('histogram/prob_weak_max', prob_weak_max, curr_epoch)

        logits_strong = net_outputs.get('segmentation/logits_strong')
        if logits_strong is not None:
            # Strong image
            summary_image = batch['image_strong'].detach().cpu()[0, 0]
            fig = plt.figure(); plt.subplot(); plt.imshow(summary_image, 'gray')
            tb_writer.add_figure('predicitons/image_strong', fig, curr_epoch)
            # Strong prediction
            prediction_strong = logits_strong.detach().cpu().softmax(1).argmax(1)[0]
            fig = plt.figure(); plt.subplot(); plt.imshow(prediction_strong)
            tb_writer.add_figure('predictions/prediction_decoder_strong', fig, curr_epoch)
            # Histogram of probability strong maximum
            prob_strong_max = logits_strong.detach().cpu().softmax(1).max(1)[0]
            tb_writer.add_histogram('histogram/prob_strong_max', prob_weak_max, curr_epoch)

        logits_aux_cls = net_outputs.get('logits_aux_cls')
        if logits_aux_cls is not None:
            # Auxiliary prediction
            prediction_aux = logits_aux_cls.detach().cpu().softmax(1).argmax(1)[0]
            fig = plt.figure(); plt.subplot(); plt.imshow(prediction_aux)
            tb_writer.add_figure('predictions/prediction_auxiliary_segmentation', fig, curr_epoch)

        tb_writer.add_scalar('losses/loss_pce_train', meter_loss_pce.avg, curr_epoch)
        tb_writer.add_scalar('losses/loss_cr', meter_loss_cr.avg, curr_epoch)
        tb_writer.add_scalar('losses/loss_ent', meter_loss_ent.avg, curr_epoch)
        tb_writer.add_scalar('losses/loss_aux_cls', meter_loss_aux_cls.avg, curr_epoch)
        tb_writer.add_scalar('losses/loss_memory', meter_loss_memory.avg, curr_epoch)
        tb_writer.add_scalar('lr/current_lr', new_lr, curr_epoch)

        ## Validation
        model.eval()
        meter_loss_pce_val = AvgMeter()
        meter_dsc = [AvgMeter() for _ in range(args.num_classes)]
        tic = time.time()
        for idx, batch in enumerate(val_dataloader):
            for key, val in batch.items():
                if isinstance(val, torch.Tensor):
                    batch[key] = val.cuda()
            # Forward
            with torch.no_grad():
                net_outputs = model(batch, mode='val')
            # Compute PCE
            loss_pce_val = net_outputs['loss_pce']
            meter_loss_pce_val.update(loss_pce_val.item(), n=batch['image'].shape[0])
            # Compute class Dice metrics
            logits_seg = net_outputs['segmentation/logits']
            value_sm = torch.softmax(logits_seg, dim=1)
            for n in range(batch['image'].shape[0]):
                dice_ls = compute_dice(value_sm.cpu().numpy()[n], batch['label'].cpu().numpy()[n])  # compute class Dice values per sample
                for cls, dice in enumerate(dice_ls):
                    if not np.isnan(dice):
                        meter_dsc[cls].update(dice)
        toc = time.time()

        # After one epoch, report information
        avg_all = np.mean([meter_dsc[_].avg for _ in range(1, args.num_classes)])  # should exclude background
        logging.info("val: {:03d}, loss_pce: {:.6f}, time: {:.2f} s/epoch".format(
            curr_epoch, meter_loss_pce_val.avg, toc-tic))
        logging.info("[BG: {:.4f}, Liver: {:.4f}, R-Kidney: {:.4f}, L-Kidney: {:.4f}, Spleen: {:.4f}, All: {:.4f}]".format(
            meter_dsc[0].avg, meter_dsc[1].avg, meter_dsc[2].avg, meter_dsc[3].avg, meter_dsc[4].avg, avg_all))

        # Log overall Dice every epoch
        valdice[curr_epoch] = avg_all

        # Save checkpoints every 10 epochs
        if curr_epoch+1 % args.ckp_interval == 0 or curr_epoch+1 == args.epoch:
            torch.save(model.state_dict(), os.path.join(args.child, 'ckps', 'ckp_{:d}.pth'.format(curr_epoch)))

        # Log best checkpoint
        if avg_all > best_avg:
            best_epoch = curr_epoch
            best_avg = avg_all
            best_avg_class = [meter_dsc[_].avg for _ in range(1, args.num_classes)]
            torch.save(model.state_dict(), args.child+'/best_ckp.pth')

        ## Tensorboard summary
        tb_writer.add_scalar('losses/loss_pce_val', meter_loss_pce_val.avg, curr_epoch)
        tb_writer.add_scalar('DSC/BG', meter_dsc[0].avg, curr_epoch)
        tb_writer.add_scalar('DSC/Liver', meter_dsc[1].avg, curr_epoch)
        tb_writer.add_scalar('DSC/R-Kidney', meter_dsc[2].avg, curr_epoch)
        tb_writer.add_scalar('DSC/L-Kidney', meter_dsc[3].avg, curr_epoch)
        tb_writer.add_scalar('DSC/Spleen', meter_dsc[4].avg, curr_epoch)
        tb_writer.add_scalar('DSC/All', avg_all, curr_epoch)
        tb_writer.add_scalar('DSC/Best', best_avg, curr_epoch)

    # Log final checkpoint
    logging.info("The best at epoch: {:d}, Liver: {:.4f}, R-Kidney: {:.4f}, L-Kidney: {:.4f}, Spleen: {:.4f},"
                 " All: {:.4f}".format(best_epoch, *best_avg_class, best_avg))
    np.savez(os.path.join(args.child, 'valdice'), valdice=valdice)
    tb_writer.close()

def train_main():
    # Environment and random seed
    args = parser.parse_args()
    os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu
    random.seed(args.seed)
    np.random.seed(args.seed)
    torch.manual_seed(args.seed)
    torch.backends.cudnn.benchmark = False  # deterministically select an algorithm

    # Make run directory
    args.child = os.path.join(os.path.join(args.root, args.modality), args.session,
                              f'{args.session}-{time.strftime("%H-%M-%S-%m%d")}-fold{args.fold}-{args.tag}')
    os.makedirs(args.child, exist_ok=False)
    os.makedirs(os.path.join(args.child, 'ckps'), exist_ok=True)
    shutil.copy(sys.argv[0], os.path.join(args.child, sys.argv[0].split('/')[-1]))

    # Logger configuration
    logging.basicConfig(filename=args.child + "/log.txt", level=logging.INFO,
                        format='[%(asctime)s.%(msecs)03d] %(message)s', datefmt='%H:%M:%S')
    logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))
    args_info = ''.join(f'{k}={v}\n' for k, v in args._get_kwargs())
    logging.info(args_info)

    # Parse txt
    with open(f'./data/{args.dataset}/train_test_split/five_fold_split/{args.modality}/train_fold{args.fold}.txt', 'r') as f:
        train_ls = f.readlines()
    with open(f'./data/{args.dataset}/train_test_split/five_fold_split/{args.modality}/test_fold{args.fold}.txt', 'r') as f:
        val_ls = f.readlines()

    args.train_ls = [(f'./data/{args.dataset}/' + p).rstrip('\n') for p in train_ls]
    args.val_ls = [(f'./data/{args.dataset}/' + p).rstrip('\n') for p in val_ls]

    train_interface(args)

if __name__ == '__main__':
    train_main()


import sys
import os
def f1(a):
    print ('hello function a=',a)

# comment1
def f2(r):
    if type(r) != list:
        print ('not a list',r)
        return

    index=0
    for item in r:
        print ('item[',index,']=',item)
        index=index+1

    for i in range(0,len(r)):
        item=r[i]
        print ('item[',i,']=',r[i])

print (sys.version)
print ('making functions')
a=1
b='1'
c=[1,2,3]
d={'key1':1,'key2':2}
full_list=[]
full_list.append(a)
full_list.append(b)
full_list.append(c)
full_list.append(d)
print ('full_list=',full_list)
f2(a)
f2(b)
f2(c)
f2(d)


from django.urls import include, path
from rest_framework.routers import DefaultRouter

from . import views

app_name = 'game'

router = DefaultRouter()
router.register(r'user', views.UserViewSet)
router.register(r'pilot', views.PilotViewSet)

urlpatterns = [
    path('pilot/<int:pk>', views.PilotUpdate.as_view(), name='pilot'),
    path('rulebook/<int:pk>', views.RulebookView.as_view(), name='rulebook'),

    path('campaign/<int:pk>', views.CampaignView.as_view(), name='campaign'),
    #path('campaign/<int:pk>/plan', views.CampaignUpdate.as_view(), name='campaign-plan'),

    path('campaign/<int:pk>/plan', views.SessionPlan.as_view(), name='next-mission'),

    path('session/<int:session_id>', views.session_summary, name='session'),
    path('session/<int:pk>/debrief', views.SessionDebrief.as_view(), name='session-debrief'),

    path('profile/', views.player_page, name='player_profile'),
    path('player/<int:player_id>', views.player_page, name="player_update"),

    path('api/', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]


import torch
import numpy as np
import random

from torch.utils.data import Dataset, DataLoader
from torchvision import datasets
from torchvision import transforms
from torch.utils.data.sampler import SubsetRandomSampler
import torchvision.transforms.functional as TF

import datasets.data_util as data_util
import constants

def get_mnist_train_valid_loader(data_dir,
                           batch_size,
                           random_seed,
                           valid_size=0.1,
                           shuffle=True,
                           num_workers=4,
                           pin_memory=False):
    """
    Utility function for loading and returning train and valid
    multi-process iterators over the MNIST dataset.
    If using CUDA, num_workers should be set to 1 and pin_memory to True.

    Parameters
    ------
    - data_dir (str): path directory to the dataset.
    - batch_size (int): how many samples per batch to load.
    - augment (bool): whether to apply the data augmentation scheme
      mentioned in the paper. Only applied on the train split.
    - random_seed (int): fix seed for reproducibility.
    - valid_size (float): fraction of the training set used for
      the validation set. Should be in the range [0, 1].
    - shuffle (bool): whether to shuffle the train/validation indices.
    - num_workers (int): number of subprocesses to use when loading the dataset.
    - pin_memory (bool): whether to copy tensors into CUDA pinned memory. Set it to
      True if using GPU

    Returns
    -------
    - train_loader: training set iterator.
    - valid_loader: validation set iterator.
    """

    normalize = transforms.Normalize(constants.MNIST_MEAN, constants.MNIST_STD )

    # define transforms
    valid_transform = transforms.Compose([
            transforms.ToTensor(),
            normalize,
    ])

    train_transform = valid_transform

    train_loader, valid_loader = data_util.get_train_valid_loader(data_dir, batch_size,
                                    random_seed, train_transform, valid_transform, datasets.MNIST,
                                    valid_size, shuffle, num_workers, pin_memory)

    return (train_loader, valid_loader)

def get_test_loader(data_dir,
                    batch_size,
                    shuffle=True,
                    num_workers=4,
                    pin_memory=False,
                    corrupted=False,
                    intensity=10,
                    corruption='rotation'):
    """
    Utility function for loading and returning a multi-process
    test iterator over the MNIST dataset.
    If using CUDA, num_workers should be set to 1 and pin_memory to True.

    Parameters
    ------
    - data_dir (str): path directory to the dataset.
    - batch_size (int): how many samples per batch to load.
    - shuffle (bool): whether to shuffle the dataset after every epoch.
    - num_workers (int): number of subprocesses to use when loading the dataset.
    - pin_memory (bool): whether to copy tensors into CUDA pinned memory. Set it to
      True if using GPU.
    - corrupted (bool): whether to return original test images or rotate them.
    - intensity (int): rotation angle in degrees or shift in pixels.
    - corruption (str): type of corruption, rotation or translation

    Returns
    -------
    - data_loader: test set iterator.
    """
    normalize = transforms.Normalize(constants.MNIST_MEAN, constants.MNIST_STD)

    # define transform
    transform = transforms.Compose([
        transforms.ToTensor(),
        normalize,
    ])

    if corrupted:
        if corruption == 'rotation':
            dataset = RotatedMNISTTest(f'{data_dir}/MNIST/raw', intensity, transform=transform)
        else:
            dataset = TranslatedMNISTTest(f'{data_dir}/MNIST/raw', intensity, transform=transform)
    else:
        dataset = datasets.MNIST(
            root=data_dir, train=False,
            download=False, transform=transform,
        )

    data_loader = torch.utils.data.DataLoader(
        dataset, batch_size=batch_size, shuffle=shuffle,
        num_workers=num_workers, pin_memory=pin_memory,
    )

    return data_loader

class RotatedMNISTTest(Dataset):
    """Class to wrap the MNIST test set with applied rotations"""

    def __init__(self, data_dir, rotation, transform=None):
        """
        Initialise the dataset and load data

        Parameters
        ------
        - data_dir (str): path to the dataset directory.
        - rotation (int): rotation angle in degrees.
        - transform (torchvision.transform): transformation
        to apply to images prior to rotation.
        """
        self.images, self.labels = data_util.load_mnist(data_dir, 't10k')
        self.transform=transform
        self.rotation=rotation

    def __len__(self):
        return(self.images.shape[0])

    def __getitem__(self, idx):

        img = self.images[idx].reshape((28, 28, 1)).copy()

        if self.transform:
            img = self.transform(img)

        img = TF.rotate(img, float(random.choice([-1, 1])*self.rotation))

        return img, int(self.labels[idx])

class TranslatedMNISTTest(Dataset):
    """Class to wrap the MNIST test set with applied cyclic translation"""

    def __init__(self, data_dir, translation, transform=None):
        """
        Initialise the dataset and load data

        Parameters
        ------
        - data_dir (str): path to the dataset directory.
        - translation (int): translation shift in pixels.
        - transform (torchvision.transform): transformation
        to apply to images prior to translaiton.
        """
        self.images, self.labels = data_util.load_mnist(data_dir, 't10k')
        self.transform=transform
        self.translation=translation

    def __len__(self):
        return(self.images.shape[0])

    def __getitem__(self, idx):

        img = self.images[idx].reshape((28, 28, 1)).copy()

        if self.translation > 0:
            translated_img = np.zeros_like(img)
            translated_img[:, :-1*self.translation, :] = img[:, self.translation:, :]
            translated_img[:, -1*self.translation:, :] = img[:, :self.translation, :]
        else:
            translated_img = img

        if self.transform:
            translated_img = self.transform(translated_img)

        return translated_img, int(self.labels[idx])

def get_MNIST_loaders(data_dir,
                        batch_size,
                        random_seed,
                        valid_size=0.1,
                        shuffle=True,
                        num_workers=4,
                        pin_memory=False,
                        corrupted_test=False,
                        intensity=10,
                        corruption='rotation'):

    """
    Utility function for loading and returning training, validation and testing
    multi-process iterators over the MNIST dataset.
    If using CUDA, num_workers should be set to 1 and pin_memory to True.

    Parameters
    ------
    - data_dir (str): path directory to the dataset.
    - batch_size (int): how many samples per batch to load.
    - shuffle (bool): whether to shuffle the dataset after every epoch.
    - num_workers (int): number of subprocesses to use when loading the dataset.
    - pin_memory (bool): whether to copy tensors into CUDA pinned memory. Set it to
      True if using GPU.
    - corrupted_test (bool): whether to return original test images or rotate them.
    - intensity (int): rotation angle in degrees or shift in pixels.
    - corruption (str): type of corruption, rotation or translation

    Returns
    -------
    - train_loader: training set iterator.
    - valid_loader: validation set iterator.
    - test_loader: test set iterator.
    """

    train_loader, valid_loader = get_mnist_train_valid_loader(data_dir, batch_size,
                                    random_seed, valid_size, shuffle, num_workers, pin_memory)
    test_loader = get_test_loader(data_dir, batch_size, shuffle, num_workers, pin_memory,
                                    corrupted_test, intensity, corruption)

    return train_loader, valid_loader, test_loader


import configparser as cp
import pathlib
import sys
from os import path, mkdir

class Config(cp.ConfigParser):
    def __init__(self, program_name, default_template):
        super().__init__(self)
        if getattr(sys, 'frozen', False):
            exec_path = path.dirname(path.abspath(str(sys.executable)))
        else:
            exec_path = ".\\"
        self.program_name = program_name
        self.path = str(pathlib.Path.home()) + f"\\.config\\{program_name}\\config.ini"
        if not path.isdir(str(pathlib.Path.home()) + "\\.config\\"):
            mkdir(str(pathlib.Path.home()) + "\\.config\\")
        if not path.isdir(str(pathlib.Path.home()) + f"\\.config\\{program_name}\\"):
            mkdir(str(pathlib.Path.home()) + f"\\.config\\{program_name}\\")
        if not path.exists(str(pathlib.Path.home()) + f"\\.config\\{program_name}\\config.ini"):
            self._generate_default_config_file(default_template)
        self.read(self.path)

    def _generate_default_config_file(self, default_template):
        self['DEFAULT'] = {
            "Program": self.program_name}
        self.update(default_template)
        with open(self.path, 'w') as configfile:
            self.write(configfile)

    def save(self):
        with open(self.path, 'w') as configfile:
            self.write(configfile)


import os
from nextcord.ext import commands
from dotenv import load_dotenv
from cogs.buttons.sr_view import SRView
import nextcord, datetime

load_dotenv()

client = commands.Bot(command_prefix='!')
client.persistent_views_added = False

@client.event
async def on_ready():
    print("Bot is ready!")
    client.load_extension("cogs.buttons.sr_message")
    if not client.persistent_views_added:
        client.add_view(SRView())
    client.persistent_views_added = True
    print('loading persistent views')

# for loop that loads all the commands
for filename in os.listdir("./cogs"):
    if filename.endswith(".py"):
        client.load_extension(f"cogs.{filename[:-3]}")

client.run(os.getenv("TOKEN"))


"""2:35pm - 2:40pm"""

class Solution:
    def countSubstrings(self, s: str) -> int:
        counter = 0

        for i in range(len(s)):
            # even palindromes, center @ i-1 and i
            l, r = i - 1, i
            while l >= 0 and r < len((s)) and s[l] == s[r]:
                l -= 1
                r += 1
                counter += 1

            # odd palindromes, center @ i
            l, r = i, i
            while l >= 0 and r < len((s)) and s[l] == s[r]:
                l -= 1
                r += 1
                counter += 1

        return counter


#
# @lc app=leetcode id=10 lang=python3
#
# [10] Regular Expression Matching
#

# @lc code=start
class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        l_s, l_p = len(s), len(p)
        @cache
        def match(i, j):
            if j == l_p: return i == l_s
            if l_p - j == 1 or p[j+1] != '*':
                if i == l_s or (p[j] != s[i] and p[j] != '.'): return False
                else: return match(i + 1, j + 1)
            if i == l_s or (s[i] != p[j] and p[j] != '.'): return match(i, j + 2)
            return match(i, j + 2) or match(i + 1, j)
        return match(0,0)

# @lc code=end


from collections.abc import Mapping, Sequence

def npu(o, id=0):
    """
    Applies npu recursively to modules and tensors.
    """
    if isinstance(o, Mapping):
        return type(o)((k, npu(v,id=id)) for (k, v) in o.items())
    if isinstance(o, Sequence):
        return type(o)(npu(v) for v in o)
    if hasattr(o, 'npu'):
        return o.npu(id)
    return o