import os.path,click
from localstack_ext.bootstrap.licensingv2 import AuthToken,DevLocalstackEnvironment,LicensingError,get_credentials_from_environment,get_licensed_environment
@click.group(name='license',short_help='(Beta) Manage and verify your LocalStack license')
def license():0
@license.command('info')
def cmd_info():
	I='test'
	try:A=get_credentials_from_environment()
	except Exception as B:click.echo(f"credentials: {B}");return
	if A:
		if isinstance(A,AuthToken):
			if A.encoded()==I:E=I
			else:E='valid syntax'if A.is_valid()else'invalid'
		else:E=''
		click.echo(f"credentials: {type(A).__name__}({A.encoded()}) {E}")
	else:click.echo('credentials: none found in environment')
	D=get_licensed_environment()
	if isinstance(D,DevLocalstackEnvironment):click.echo('test credentials used, using unlicensed dev environment');return
	C=None
	for G in D.get_license_file_read_locations():
		if os.path.isfile(G):C=G;break
	F=None
	if C:
		try:
			with open(C,'rb')as J:H=J.read();F=D.parser.parse(H);click.echo(f"license location: {C}");click.echo(f"license: {H.decode('utf-8')}")
		except LicensingError as B:click.echo(f"license location: {C}");click.echo(f"license: error reading license file {B}")
	if F:
		try:D.client.validate(F);click.echo('license validity: valid')
		except LicensingError as B:click.echo(f"license validity: invalid ({B})")
@license.command('activate')
def cmd_activate():
	try:A=get_licensed_environment();A.activate();click.echo('license activation completed');click.echo(f"license: {A.serializer.serialize(A.license).decode('utf-8')}")
	except LicensingError as B:click.echo(B.get_user_friendly())


"""
A module for managing and solving sudokus of variable size
"""
import constraint

class Sudoku(object):

    """
    This class manages Sudoku grids of variable sizes.

    It allows for easy access to the individual rows, columns and blocks of
    the grid. Sudokus can be solved using constraint processing.
    """

    def __init__(self, grid):
        """
        The constructor expects a flat list as a grid, for example:

        >>> grid4x4 = [0, 1, 0, 0,
        ...            0, 0, 4, 0,
        ...            0, 0, 0, 0,
        ...            0, 0, 3, 0]
        >> Sudoku(grid4x4)

        Where zeros indicate an empty field.
        The grid's length must be a a square number.
        """
        self.grid = grid
        self.size = int(len(grid) ** 0.5)
        self.block_size = int(self.size ** 0.5)

        if self.size ** 2 != len(grid):
            raise ValueError('Expecting a square grid')

    @property
    def rows(self):
        """
        Generator expression for accessing the individual rows of the grid
        """
        for n in range(self.size):
            yield self.grid[n * self.size:self.size * (n + 1)]

    @property
    def columns(self):
        """
        Returns a generator for accessing the individual columns of the grid
        """
        for n in range(self.size):
            yield self.grid[n::self.size]

    @property
    def blocks(self):
        """
        Returns a generator for accessing the individual blocks of the grid
        """
        for _y in range(self.block_size):
            for _x in range(self.block_size):
                block = []
                x = _x * self.block_size
                y = _y * self.block_size * self.size
                start = x + y
                for r in range(self.block_size):
                    block += self.grid[start:start + self.block_size]
                    start += self.size
                yield block

    def solve(self):
        """
        Solves the sudoku.

        This will replace the empty cells in this sudoku with the solutions.
        """
        problem = constraint.Problem()
        all_different = constraint.AllDifferentConstraint()

        for i, n in enumerate(self.grid):
            problem.addVariable(i, range(1, self.size + 1) if n == 0 else [n])

        _s = Sudoku(range(len(self.grid)))
        for row in _s.rows:
            problem.addConstraint(all_different, row)
        for col in _s.columns:
            problem.addConstraint(all_different, col)
        for block in _s.blocks:
            problem.addConstraint(all_different, block)

        solution = problem.getSolution()
        if solution:
            self.grid = solution.values()
        else:
            raise ValueError('No solutions found')

    def __str__(self):
        """
        Shows the string representation of the sudoku grid.
        """
        result = ''
        number_width = len(str(self.size)) + 1
        block_count = int(self.size / self.block_size)
        block_width = block_count * number_width

        # Formatting has gotten bit complex because we need to handle grids of
        # variable size. As a result, numbers are often longer than one char.
        for y, row in enumerate(self.rows):
            if y % self.block_size == 0 and y > 0:
                # insert horizontal line
                result += "+-".join(["-" * block_width] * block_count) + "\n"
            for x, num in enumerate(row):
                if x % self.block_size == 0 and x > 0:
                    # insert vertical line
                    result += "| "
                # draw numbers
                result += str(num).ljust(number_width)
            result += "\n"
        return result

if __name__ == '__main__':
    small = [0, 1, 0, 0,
             0, 0, 4, 0,
             0, 0, 0, 0,
             0, 2, 3, 0]

    hardest = [8, 0, 0, 0, 0, 0, 0, 0, 0,
               0, 0, 3, 6, 0, 0, 0, 0, 0,
               0, 7, 0, 0, 9, 0, 2, 0, 0,
               0, 5, 0, 0, 0, 7, 0, 0, 0,
               0, 0, 0, 0, 4, 5, 7, 0, 0,
               0, 0, 0, 1, 0, 0, 0, 3, 0,
               0, 0, 1, 0, 0, 0, 0, 6, 8,
               0, 0, 8, 5, 0, 0, 0, 1, 0,
               0, 9, 0, 0, 0, 0, 4, 0, 0]

    empty_normal = [0] * (9 ** 2)
    empty_big = [0] * (16 ** 2)

    s = Sudoku(hardest)
    s.solve()

    print(s)


from django.urls import path
from .views import *

app_name = "news"
urlpatterns = [
    # path("news/", NewsView.as_view(), name="news"),
    path("news-detail/<int:pk>/", NewsDetailView.as_view(), name="news-detail"),
    path("news/list/", NewsView.as_view(), name="news"),
    path("news/all-list/", AllNewsView.as_view(), name="news-all"),
    # news crud
    path("category", CategoryView.as_view(), name="category-table"),
    path("category-create/", CategoryCreateView.as_view(), name="category-create"),
    path(
        "category-update/<int:pk>/",
        CategoryUpdateView.as_view(),
        name="category-update",
    ),
    path(
        "category-delete/<int:pk>/",
        CategoryDeleteView.as_view(),
        name="category-delete",
    ),
    path("news-table/", NewsTableView.as_view(), name="news-table"),
    # add news/notice
    path("admin/add-news/", AddAdminNewsView.as_view(), name="add-anews"),
    # update news/notice
    path("admin/edit-news/<int:pk>/", EditAdminNewsView.as_view(), name="edit-anews"),
    ##########################
    path("news-delete/<int:pk>/", NewsDeleteView.as_view(), name="news-delete"),
    path(
        "recentactivity-detail/<int:pk>/",
        RecentActivityDetailView.as_view(),
        name="recentactivity-detail",
    ),
    path("recent-activity/list/", RecentActivityView.as_view(), name="recent-activity"),
     path("recent-activity/all-list/", AllRecentActivityView.as_view(), name="all-recent-activity"),
    # recent actvities crud
    path(
        "recent-activity/table/",
        RecentActivityTableView.as_view(),
        name="recentactivity-table",
    ),
    #####################recent activity #########
     path("recent-activity/add-recent-activity/", AddAdminRecentView.as_view(), name="add-arecent-activity"),
    # update news/notice
    path("recent-activity/edit-recent-activity/<int:pk>/", EditAdminRecentView.as_view(), name="edit-arecent-activity"),
    ##########################
    path(
        "recent-activity-delete/<int:pk>/",
        RecentActivityDeleteView.as_view(),
        name="recentactivity-delete",
    ),
    # dam knowledge
    path("damknowledge-salient-features/", DamKnowledgeSalientFeaturesView.as_view(), name="damknowledge"),
    path("pipeline/", PipeLineView.as_view(), name="pipeline"),
    path("name-of-dam/", NameOfDamView.as_view(), name="name-of-dam"),
    path("lake/", LakeView.as_view(), name="lake"),
    path("literature/", LiteratureView.as_view(), name="literatures"),
    # admin dam knowledge

    # administration
    path(
        "administration/login",
        AdministrationLoginView.as_view(),
        name="administration-login",
    ),
    path(
        "administration/darta-chalani", DartaChalaniView.as_view(), name="darta-chalani"
    ),
    path("administration/darta-list", DartaListView.as_view(), name="darta-list"),
    path("administration/darta-form", DartaFormView.as_view(), name="darta-form"),
    path("administration/chalani-list", ChalaniListView.as_view(), name="chalani-list"),
    path("administration/chalani-form", ChalaniFormView.as_view(), name="chalani-form"),
    path("darta/<int:pk>", DartaDetailView.as_view(), name="darta-detail"),
    path("darta/<int:pk>/update", DartaUpdateView.as_view(), name="darta-update"),
    path("darta/<int:pk>/delete", DartaDeleteView.as_view(), name="darta-delete"),
    path("chalani/<int:pk>", ChalaniDetailView.as_view(), name="chalani-detail"),
    path("chalani/<int:pk>/update", ChalaniUpdateView.as_view(), name="chalani-update"),
    path("chalani/<int:pk>/delete", ChalaniDeleteView.as_view(), name="chalani-delete"),
    path("administration/upload-file/", CUploadFileView.as_view(), name="c-upload-file"),
    path("administration/upload-file/add", CAddUploadFileView.as_view(), name="c-add-file"),
    path("administration/upload-file/edit/<int:pk>/", CEditUploadUpdateFileView.as_view(), name="c-edit-file"),
    path("administration/upload-file/delete/<int:pk>/", CEditUploadDeleteFileView.as_view(), name="c-delete-file"),

    # ========= Notice ========
    path("notice/", NoticeView.as_view(), name="notice"),
    path("notice/create/", NoticeCreateView.as_view(), name="notice-create"),
    path("notice/update/<int:pk>/", NoticeUpdateView.as_view(), name="notice-update"),
    path("notice/delete/<int:pk>/", NoticeDeleteView.as_view(), name="notice-delete"),
    path("admin/profile/", AdminProfileView.as_view(), name="admin-profile"),
    # message
    path("admin/messages/", MessageView.as_view(), name="admin-message"),
    path("messages/create/", MessageCreateView.as_view(), name="message-create"),
    path("messages/update/<int:pk>/", MessageUpdateView.as_view(), name="messages-update"),
    path("messages/delete/<int:pk>/", MessageDeleteView.as_view(), name="message-delete"),

    path("darta/search",DartaSearch.as_view(),name="darta-search")
    # for displying pdf
    #     path("admin/message/create/", MessageCreateView.as_view(), name="message-create"),
    #     path("admin/message/update/<int:pk>/", MessageUpdateView.as_view(), name="message-update"),
    #     path("admin/message/delete/<int:pk>/", MessageDeleteView.as_view(), name="message-delete"),
]


import random
from tkinter import*

window = Tk()
window.title("dice")
window.geometry("300x300")
def dice():
    label["text"] = str(random.randint(1,6))

label = Label(window, text="1", fg="red", font=("Arial", 100, "bold"))
label.pack(side=LEFT, padx=75)
button = Button(window, text="굴리기", fg="blue", font=("Arial", 20, "bold"), height=2, width=30, command=dice)
button.pack(side=RIGHT)

window.mainloop()


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

from App.App_2.app import App

class TestContact:
    def setup_class(self):
        self.app = App()
        self.contact = self.app.start().main().goto_contact()

    @pytest.mark.parametrize("name, gender, tel",
                             yaml.safe_load(open("../data/data.yml", encoding='utf-8'))['add_data'])
    def test_add_contact(self, name, gender, tel):
        assert "成功" in self.contact.add_member().invite_manual().input_name(name).set_gender(
            gender).input_tel(tel).click_save().get_toast()

    @pytest.mark.parametrize("name", yaml.safe_load(open("../data/data.yml", encoding='utf-8'))['del_data'])
    def test_del_member(self, name):
        assert self.contact.goto_profile(name).goto_edit().del_member().get_member(name) is False


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Inputs for script 1
"""

model_name="inputs/recon3d.sbml" #base model used for analysis
metabolomics_file=None#Set to none if not present
constraint_file="inputs/constraints.xlsx" #Basic description of  medium composition, normalizyed by cell number. Restricts the maximum uptake of cells
col_reaction='Unnamed: 0' #name of the colum that stores reaction ids
medium_kpcs_file="inputs/kpc_cobas_biocrates(medium)_seahorse.xlsx"#Measured consumption and production rates. Metabolites being consumed should be negative, metabolites being produced should be positive
colum_replicates=['KPC (umol/10e6 cell · h)']#name of the colum that indicates the condition of the replicates.
col_to_erase_l=['condition', 'Replicado', 'Unnamed: 0']

#Gene expression inputs
gene_expression_file=file_name="inputs/fpkm.xlsx"  #Absolute gene expression file, in FPKM or equivalent units
conditions_of_interest=["CT",	"CK",	]#What experimental conditions we want to analyse

#Remove gene inputs
force_remove_th=1 #Genes with expression bellow 1 FPKM (absolute) will be removed
objective="BIOMASS_reaction" #Objective reactions
biomass_fraction=0.1 #Whats is the minimum fraction of bioamss allowed when removing genes

gene_entrez_column="entrezgene_id" #Name of the column with the entrez id
#reference_condition="WT" #Control condition, used for other comparissons

#Reactions to keep and kill
#Reactions that you dont want to be removed from the model
reactions_to_keep=["r1435","THFtm","GHMT2rm","MTHFDm","MTHFD2m","MTHFCm","FTHFLmi","FORtm","PDHm","ATPS4mi","CYOR_u10mi","NADH2_u10mi","CYOOm3i","CYOOm2i","ETF","ETFQO"]
#Reactions that form unfeasible loops and should be removed
reactions_to_kill=["HMR_4957","r1109", "CITL", "r2381","MALOAAtm","GALt1r","RE1342C","SBTD_D2","BALAPAT1tc2","CALAtr","PCRNte","LNELDCCRNte","ODECRNte","STCRNte","PMTCRNte","HDCECRNte", "AKGICITtm", "r2386", "r2387", "r2388", "r2389", "r2390", "r2391", "r2392", "r2393", "r2394", "r2371", "r2372", "r2375", "r2376", "r2377", "r2378", "r2379", "r2380", "MALITm", "CITtm", "r2385", "CITtcm", "MALICITtm", "AKGCITtm", "r2374", "r2382", "r0915", "HMR_4964"]

#Output directories
out_dir="OUTPUT" #Where the output files will be saved. Directory must exist

#Check essential reactions using FVA
fraction_essential_genes=0.1 #Reactions that must be active to allow growth above this fraction will be considered essential when looking for targets.


# https://leetcode-cn.com/problems/reformat-date/
# reformat date
class Solution:
    def reformatDate(self, date: str) -> str:
        months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
        indexs = list(range(1, 13, 1))
        months = dict(zip(months, indexs))

        new_date = date.split(" ")
        d = int(new_date[0][0:-2])
        m = months[new_date[1]]

        return "{0}-{1:02d}-{2:02d}".format(new_date[2], m, d)


#trims initial csv file raw from sqlite conversion to relevent information for FWI calculations (precipitation, moisture, relative humidity, etc.)

import csv
import datetime
import numpy as np
import os
from netCDF4 import Dataset

def core():
	dirname = '/home/***/Desktop/fire/netcdfreader/MERRA2'

	with open("merrafires2015.csv", "r") as csvinput:
		with open("merra2015final.csv", "w") as csvoutput:
			reader = csv.reader(csvinput)
			writer = csv.writer(csvoutput)
			for row in reader:
				ary = []
				ary.append(str(row[6]))
				ary.append(str(row[11]))
				ary.append(str(row[12]))
				ary.append(str(row[13]))
				ary.append(str(row[14]))
				writer.writerow(ary)

if __name__=='__main__':
	core()


from typer.testing import CliRunner

from sim_dev import __app_name__
from sim_dev import __author__
from sim_dev import __version__
from sim_dev import cli
from sim_dev.config import AppConfiguration

runner = CliRunner()

def test_version():
    result = runner.invoke(cli.app, ["--version"])
    assert result.exit_code == 0
    assert f"{__app_name__} v{__version__} made by {__author__}\n" in result.stdout

def test_commands_args():
    conf = AppConfiguration()
    config = AppConfiguration()
    result = conf._get_args_command("change-directory")
    result1 = config._get_args_command("")
    result2 = config._get_args_command(None)

    assert not result is None
    assert conf is config
    assert not result == result1
    assert result2 is None