import xml.etree.ElementTree as ET
from xml.dom import minidom
debug_level = 2
function_uid = 1342649436

def debug_print(text, level = 1):
    global debug_level

    if (debug_level >= level):
        print(text)

    def printItems(self):
        print(self.items)

class Snixception(RuntimeError):
    def __init__(self, offset, msg):
        self.args = (offset, msg)

class ItemBase:
    items = []

    def addItem(self, item, values = []):
        self.items.append((item, values))

    def compile(self, type):
        raise Exception("SBS Writer: Compile not yet implemented for this object!")

class Option(ItemBase):
    name = ""
    value = ""

    def __init__(self, name, value):
        self.items = []
        self.name = name
        self.value = value
        self.addItem('name', [("v", self.name)])
        self.addItem('value', [("v", self.value)])

    def compile(self, xml_options):
        xml_option = ET.SubElement(xml_options, 'option')
        for item in self.items:
            debug_print('        ' + item[0] + ':')
            xml_item = ET.SubElement(xml_option, item[0])
            for value in item[1]:
                debug_print('            ' + value[0] + ': ' + value[1])
                xml_item.set(value[0], value[1])

class Graph(ItemBase):
    options = [Option("defaultParentSize", "9x9")]
    identifier = ""
    uid = "1332648088"

    def __init__(self, identifier = "Snix Functions"):
        self.items = []
        self.identifier = identifier
        self.addItem('identifier', [("v", self.identifier)])
        self.addItem('uid', [("v", self.uid)])
        self.addItem('graphOutputs')
        self.addItem('compNodes')
        self.addItem('baseParameters')
        self.addItem('options')
        self.addItem('root')

    def compile(self, xml_graph):
            for item in self.items:
                debug_print('    ' + item[0] + ':')
                xml_item = ET.SubElement(xml_graph, item[0])
                for value in item[1]:
                    debug_print('        ' + value[0] + ': ' + value[1])
                    xml_item.set(value[0], value[1])

            debug_print('    Graph options:')
            xml_options = ET.SubElement(xml_graph, 'options')
            for option in self.options:
                option.compile(xml_options)

class Connection(ItemBase):
    identifier = ""
    connRef = "";

    def __init__(self, identifier, connection):
        self.items = []
        self.identifier = identifier
        self.connRef = connection
        self.addItem('identifier', [("v", self.identifier)])
        self.addItem('connRef', [("v", self.connRef)])

    def compile(self, xml_connections):
        for item in self.items:
            debug_print('    ' + item[0] + ':')
            xml_item = ET.SubElement(xml_connections, item[0])
            for value in item[1]:
                debug_print('        ' + value[0] + ': ' + value[1])
                xml_item.set(value[0], value[1])

class Widget(ItemBase):
    type = ''
    stepSize = 1
    options = []

    def __init__(self, type, step = 1, createDefaults = 1):
        self.items = []
        self.type = type
        self.stepSize = step
        self.addItem('name', [("v", self.type)])

        if (createDefaults):
            if (type == 'slider'):
                self.addSliderOptions()
            elif  (type == 'buttons'):
                self.addButtonsOptions()
            elif  (type == 'text'):
                self.addTextOptions()
            else:
                raise Exception("SBS Writer: Unknown widget type '" + type + "'")

    def addOption(self, option):
        self.options.append(option)

    def addSliderOptions(self):
        self.addOption(Option('clamp', '0'))
        self.addOption(Option('default', '0'))
        self.addOption(Option('max', str(self.stepSize * 100)))
        self.addOption(Option('min', '0'))
        self.addOption(Option('step', str(self.stepSize)))

    def addButtonsOptions(self):
        self.addOption(Option('booleditortype', 'pushbuttons'))
        self.addOption(Option('default', '0'))
        self.addOption(Option('label0', 'False'))
        self.addOption(Option('label1', 'True'))

    def addTextOptions(self):
        self.addOption(Option('default', ''))

    def compile(self, xml_connections):
        debug_print('    Widget options:')
        xml_options = ET.SubElement(xml_graph, 'options')
        for option in self.options:
            option.compile(xml_options)

class ParamInput(ItemBase):
    uid = "1332649438"
    name = ""
    label = ""
    size = 1
    type = "256"
    widget = "slider"
    constValue = "constantValueFloat1"
    defaultValue = "1"
    defaultWidget = None
    customData = []

    def __init__(self, name, uid = "1332649438", type = "256", constValue = "constantValueFloat1", size = 1, label = ""):
        self.items = []
        self.customData = []
        self.inputOptions = []
        self.uid = uid
        self.type = type
        self.name = name
        self.label = label
        self.constValue = constValue
        self.defaultValue = ''
        self.addItem('uid', [("v", self.uid)])
        self.addItem('identifier', [("v", self.name)])
        self.addItem('type', [("v", self.type)])

        if (int(type) == 4):
            self.setTypeBool()
        elif (int(type) >= 16 and int(type) <= 128):
            self.setTypeInt(type, size)
        elif (int(type) >= 256 and int(type) <= 4096):
            self.setTypeFloat(type, size)
        elif (int(type) >= 16384):
            self.setTypeString(type, size)

    def setTypeBool(self):
        self.defaultValue = "0"
        self.constValue = 'constantValueBool'
        self.defaultWidget = Widget('buttons')

    def setTypeString(self):
        self.defaultValue = ""
        self.constValue = 'constantValueString'
        self.defaultWidget = Widget('text')

    def setTypeFloat(self, type, size):
        for i in range(int(size)):
            self.defaultValue += '1 '

        self.defaultValue = self.defaultValue[:-1]
        self.defaultWidget = Widget('slider', step=0.01)

    def setTypeInt(self, type, size):
        for i in range(int(size)):
            self.defaultValue += '1 '

        self.defaultValue = self.defaultValue[:-1]
        self.defaultWidget = Widget('slider', step=1)

    def addCustomData(self, item, values = []):
        self.customData.append((item, values))

    def compile(self, xml_paramInput):
        for item in self.items:
            debug_print('    ' + item[0] + ':')
            xml_item = ET.SubElement(xml_paramInput, item[0])
            for value in item[1]:
                debug_print('        ' + value[0] + ': ' + value[1])
                xml_item.set(value[0], value[1])

        debug_print('    Custom Data:')
        for item in self.customData:
            debug_print('        ' + item[0] + ':')
            xml_item = ET.SubElement(xml_paramInput, item[0])
            for value in item[1]:
                debug_print('              ' + value[0] + '.' + value[1] + ': ' + value[2])
                xml_value = ET.SubElement(xml_item, value[0])
                xml_value.set(value[1], value[2])

        debug_print('Attributes:')
        xml_attributes = ET.SubElement(xml_paramInput, 'attributes')
        xml_value = ET.SubElement(xml_attributes, 'label')
        xml_value.set('v', self.label)

        debug_print('Default Value:')
        xml_attributes = ET.SubElement(xml_paramInput, 'defaultValue')
        xml_value = ET.SubElement(xml_attributes, self.constValue)
        xml_value.set('v', str(self.defaultValue))

        debug_print('Default Widget:')
        xml_defaultWidget = ET.SubElement(xml_paramInput, 'defaultWidget')
        xml_widgetName = ET.SubElement(xml_defaultWidget, 'name')
        xml_widgetName.set('v', self.widget)
        xml_widgetOptions = ET.SubElement(xml_defaultWidget, 'options')

        debug_print('Widget Options:')
        for item in self.inputOptions:
            debug_print('        ' + item[0] + ':')
            xml_widgetOption = ET.SubElement(xml_widgetOptions, 'option')
            xml_optionName = ET.SubElement(xml_widgetOption, 'name')
            xml_optionValue = ET.SubElement(xml_widgetOption, 'value')
            xml_optionName.set('v', item[0])
            xml_optionValue.set('v', item[1])

class FuncData(ItemBase):
    name = ""
    customData = []

    def __init__(self, name):
        self.items = []
        self.customData = []
        self.name = name
        self.addItem('name', [("v", self.name)])

    def addCustomData(self, item, values = []):
        self.customData.append((item, values))

    def compile(self, xml_funcData):
        for item in self.items:
            debug_print('    ' + item[0] + ':')
            xml_item = ET.SubElement(xml_funcData, item[0])
            for value in item[1]:
                debug_print('        ' + value[0] + ': ' + value[1])
                xml_item.set(value[0], value[1])

        debug_print('    Custom Data:')
        for item in self.customData:
            debug_print('        ' + item[0] + ':')
            xml_item = ET.SubElement(xml_funcData, item[0])
            for value in item[1]:
                debug_print('              ' + value[0] + '.' + value[1] + ': ' + value[2])
                xml_value = ET.SubElement(xml_item, value[0])
                xml_value.set(value[1], value[2])

class ParamNode(ItemBase):
    uid = "1332649438"
    function = "none"
    type = "256"
    pos = ("192", "50", "1")
    connections = []
    funcDatas = []

    def __init__(self, function, uid = "1332649438", type = "256"):
        self.items = []
        self.connections = []
        self.funcDatas = []
        self.uid = uid
        self.type = type
        self.function = function
        self.addItem('uid', [("v", self.uid)])
        self.addItem('function', [("v", self.function)])
        self.addItem('type', [("v", self.type)])

    def addFuncData(self, funcData):
        self.funcDatas.append(funcData)

    def addConnection(self, connection):
        self.connections.append(connection)

    def compile(self, xml_paramNode):
        for item in self.items:
            debug_print('    ' + item[0] + ':')
            xml_item = ET.SubElement(xml_paramNode, item[0])
            for value in item[1]:
                debug_print('        ' + value[0] + ': ' + value[1])
                xml_item.set(value[0], value[1])

        debug_print('    FuncDatas:')
        xml_funcDatas = ET.SubElement(xml_paramNode, 'funcDatas')
        for funcData in self.funcDatas:
            xml_funcData = ET.SubElement(xml_funcDatas, 'funcData')
            funcData.compile(xml_funcData)

        debug_print('    Connections:')
        xml_connections = ET.SubElement(xml_paramNode, 'connections')
        for connection in self.connections:
            xml_connection = ET.SubElement(xml_connections, 'connection')
            connection.compile(xml_connection)

        debug_print('    GUILayout:', 3)
        xml_GUILayout = ET.SubElement(xml_paramNode, 'GUILayout')
        xml_gpos = ET.SubElement(xml_GUILayout, 'gpos')
        xml_gpos.set('v', self.pos[0] + ' ' + self.pos[1] + ' ' + self.pos[2])

class Function(ItemBase):
    identifier = "snixel"
    uid = "0"
    type = "256"
    rootnode = "0";
    inputs = []
    paramNodes = []

    def __init__(self, name, uid, type):
        self.items = []
        self.inputs = []
        self.paramNodes = []
        self.identifier = name
        self.type = type
        self.uid = uid
        self.addItem('identifier', [("v", self.identifier)])
        self.addItem('uid', [("v", self.uid)])
        self.addItem('type', [("v", self.type)])

    def addParamNode(self, paramNode):
        self.paramNodes.append(paramNode)

    def addInput(self, inputNode):
        self.inputs.append(inputNode)

    def setRootNode(self, rootnode):
        self.rootnode = rootnode

    def compile(self, xml_function):
        for item in self.items:
            debug_print('    ' + item[0] + ':')
            xml_item = ET.SubElement(xml_function, item[0])
            for value in item[1]:
                debug_print('        ' + value[0] + ': ' + value[1])
                xml_item.set(value[0], value[1])

        debug_print('Function Inputs:')
        xml_paramInputs = ET.SubElement(xml_function, 'paraminputs')
        for input in self.inputs:
            debug_print('    ' + input.name + ':')
            xml_paramInput = ET.SubElement(xml_paramInputs, 'paraminput')
            input.compile(xml_paramInput)

        debug_print('Param Nodes:')
        xml_paramValue = ET.SubElement(xml_function, 'paramValue')
        xml_dynamicValue = ET.SubElement(xml_paramValue, 'dynamicValue')
        xml_rootnode = ET.SubElement(xml_dynamicValue, 'rootnode')
        xml_rootnode.set('v', self.rootnode)
        xml_paramNodes = ET.SubElement(xml_dynamicValue, 'paramNodes')

        for node in self.paramNodes:
            debug_print('Node: ' + node.function + '(' + node.uid + '):', 3)
            xml_paramNode = ET.SubElement(xml_paramNodes, 'paramNode')
            node.compile(xml_paramNode)

class Dependency(ItemBase):
    uid = 0
    type = 'package'
    filename = "?himself"
    fileUID = 0
    versionUID = 0

    def __init__(self, filename, uid):
        self.items = []
        self.uid = str(uid);
        self.type = 'package'
        self.filename = str(filename)
        self.fileUID = str(0)
        self.versionUID = str(0)
        self.addItem('filename', [("v", self.filename)])
        self.addItem('uid', [("v", self.uid)])
        self.addItem('type', [("v", self.type)])
        self.addItem('fileUID', [("v", self.fileUID)])
        self.addItem('versionUID', [("v", self.versionUID)])

    def compile(self, xml_dependency):
        for item in self.items:
            debug_print('    ' + item[0] + ':')
            xml_item = ET.SubElement(xml_dependency, item[0])
            for value in item[1]:
                debug_print('        ' + value[0] + ': ' + value[1])
                xml_item.set(value[0], value[1])

class Package(ItemBase):
    identifier = ""
    version = "1.1.0.201804"
    fileUID = "{55849f0d-25a5-427a-9dc9-878a510b4270}"
    versionUID = "0"
    graphs = []
    functions = []
    dependencies = []

    def __init__(self, identifier = "Snix Package"):
        self.items = []
        self.graphs = []
        self.functions = []
        self.identifier = identifier
        self.addItem('identifier', [("v", self.identifier)])
        self.addItem('formatVersion', [("v", self.version)])
        self.addItem('updaterVersion', [("v", self.version)])
        self.addItem('fileUID', [("v", self.fileUID)])
        self.addItem('versionUID', [("v", self.versionUID)])

    def compile(self):
        xml_package = ET.Element('package')
        for item in self.items:
            debug_print('    ' + item[0] + ':')
            xml_item = ET.SubElement(xml_package, item[0])
            for value in item[1]:
                debug_print('        ' + value[0] + ': ' + value[1])
                xml_item.set(value[0], value[1])

        xml_dependencies = ET.SubElement(xml_package, 'dependencies')
        for dependency in self.dependencies:
            debug_print('Dependency: ' + dependency.uid + ':')
            xml_dependency = ET.SubElement(xml_dependencies, 'dependency')
            dependency.compile(xml_dependency)

        debug_print('Content:')
        xml_content = ET.SubElement(xml_package, 'content')

        for graph in self.graphs:
            debug_print('Graph: ' + graph.identifier + ':')
            xml_graph = ET.SubElement(xml_content, 'graph')
            graph.compile(xml_graph)

        for function in self.functions:
            debug_print('Function: ' + function.identifier + ':')
            xml_function = ET.SubElement(xml_content, 'function')
            function.compile(xml_function)

        return xml_package

    def addDependency(self, depenency):
        self.dependencies.append(depenency)

    def addGraph(self, graph):
        self.graphs.append(graph)

    def addFunction(self, function):
        self.functions.append(function)

class SBSWriter:
    package = []

    def __init__(self):
        self.package = Package();
        self.graphs = []
        self.functions = []
        self.addGraph()

    def addGraph(self):
        graph = Graph()
        self.package.addGraph(graph)
        return graph

    def addFunction(self, name, type):
        global function_uid
        function_uid += 1
        function = Function(name, str(function_uid), type)
        self.package.addFunction(function)
        return function

    def write(self, outfile = None):
        debug_print('Package:')
        xml_package = self.package.compile()
        xml_data = ET.tostring(xml_package)

        if (outfile == None):
            outfile = 'out.sbs'

        ET.ElementTree(xml_package).write(outfile, encoding="UTF-8")

        debug_print(xml_data, 2)
        return xml_data


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

import pycurl
from pyload.core.network.browser import Browser
from pyload.core.network.http.http_request import HTTPRequest

from ..base.addon import BaseAddon

class UserAgentSwitcher(BaseAddon):
    __name__ = "UserAgentSwitcher"
    __type__ = "addon"
    __version__ = "0.18"
    __status__ = "testing"

    __config__ = [
        ("enabled", "bool", "Activated", True),
        ("connecttimeout", "int", "Max timeout for link connection in seconds", 60),
        ("maxredirs", "int", "Maximum number of redirects to follow", 10),
        (
            "useragent",
            "str",
            "Custom user-agent string",
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:87.0) Gecko/20100101 Firefox/87.0",
        ),
    ]

    __description__ = """Custom user-agent"""
    __license__ = "GPLv3"
    __authors__ = [("Walter Purcaro", "vuolter@gmail.com")]

    def download_preparing(self, pyfile):
        if not isinstance(pyfile.plugin.req, HTTPRequest) and not isinstance(
            pyfile.plugin.req, Browser
        ):
            return

        connecttimeout = self.config.get("connecttimeout")
        maxredirs = self.config.get("maxredirs")
        useragent = self.config.get("useragent")

        if connecttimeout:
            self.log_debug(
                "Setting connection timeout to {} seconds".format(connecttimeout)
            )
            pyfile.plugin.req.http.c.setopt(pycurl.CONNECTTIMEOUT, connecttimeout)

        if maxredirs:
            self.log_debug(f"Setting maximum redirections to {maxredirs}")
            pyfile.plugin.req.http.c.setopt(pycurl.MAXREDIRS, maxredirs)

        if useragent:
            self.log_debug(f"Use custom user-agent string `{useragent}`")
            pyfile.plugin.req.http.c.setopt(pycurl.USERAGENT, useragent.encode())


import bisect

class Solution(object):
    def findRadius(self, houses, heaters):
        """
        :type houses: List[int]
        :type heaters: List[int]
        :rtype: int
        """
        radious, n, heaters = 0, len(heaters), sorted(heaters)
        for house in houses:
            distance, i = 0, bisect.bisect_left(heaters, house)
            if i == 0: distance = heaters[0] - house
            elif i == n: distance = house - heaters[-1]
            else: distance = min(house - heaters[i-1], heaters[i] - house)
            if radious < distance: radious = distance
        return radious


def set_parameters():
    parameters = {
        "model":{
            "weight":{
                "color":"weights/metric_color_weight.pth",
                "type":"weights/metric_id_weight.pth"
            }
        },
        "sys":{
            "use_feature":["type"],#使用する特徴量"color" or "type"
            "search_num":10,#検索数
            "custom":False,#組み合わせによる検索
            # "custom_pair":[(49,15),(32,47),(5,0),(53,5),(2,5),(10,28),(29,53),(5,30),(47,49),(53,47)],
            "custom_pair":[(49,15),(32,47),(5,0),(53,5),(29,53),(5,30),(47,49),(53,47),
                           (49,43),(5,1),(7,41),(2,14),(29,30),(5,42),(47,41),(53,7),
                           (41,30),(3,5),(30,28),(8,53),(5,30),(57,49),(53,47),
                           (41,15),(3,0),(22,25),(8,30),(59,42),(57,41),(51,7)
                        ],
            "search_method":"concat",#検索手法"concat" or "step"
            "step_search_num":{"0":50, "1":10},#段階検索に使用する検索数
            "map_type":2,#MAPの計算に使用する情報    0：color, 1:type, 2:color&type
            "calc":False,
            "calc_DB":False,#GUI使用時のみ使う
            "calc_query":True,#GUI使用時のみ使う
            "dimension_reduction":False#次元削限による結合を使用するか
        },
        "dataset":{
            "use_DB":"DB2",
            "root":"/Users/buyuu/Desktop/pystd/git_codes/metric-learning-divide-and-conquer/data/img/",
            "DB1":{#600枚DB
                "DB_file_path":"evaluation_dataset/evaluation_DB2.txt",
                "query_file_path":"evaluation_dataset/evaluation_query2.txt",
                "label_file_path":"evaluation_dataset/image_data2.json"
            },
            "DB2":{#自分の写真を使用
                "DB_file_path":"evaluation_dataset/evaluation_DB_mydata.txt",
                "query_file_path":"evaluation_dataset/evaluation_query_mydata.txt",
                "label_file_path":"evaluation_dataset/image_data_mydata.json"
            }
        },
        "image_out":{
            "first_plot":False,
            "show":False
        },
        "gui":{#画像に対してyoloを使用するか
            "use_yolo":False
        }
    }

    return parameters


a = 5
b = 4
h = 4
c = 3
tupla = tuple((a, h , b, c))

x = tupla.count(4)
y = tupla.index(3)

print(tupla)
print(f"O valor aparece {x} vezes. ")
print(f"A posição do valor é {y}. ")

tupla_pares = tuple(x for x in tupla if x % 2 == 0)
print(tupla_pares)


from django.db import connection

from django.shortcuts import render, redirect

from SMS_MYSQL import models
from SMS_MYSQL.utils.bootstrap import BootStrapModelForm

from SMS_MYSQL.utils.raw import custom_sql_get_dict
from SMS_MYSQL.models import TeachingPlan
# Create your views here.

# 采用modelform

from django import forms

# from django.forms import DateInput
#
# class UDateInput(DateInput):
#     input_type = 'date'

def student_expel_list(request):
    """ 学生额外信息列表 """
    # 绕过模型层采用原生SQL

    # ST1 查出所有不及格选课信息的学号 课程号 学分
    ST1 = "select  A.students_id, A.courses_id, B.course_credit \
            from sms_mysql_studentcourse A, sms_mysql_courses B \
            where A.courses_id=B.course_id and A.grade<60 and A.grade is not NULL"
    # print(custom_sql_get_dict(ST1))
    # ST2 查出所有学号对应的专业号
    ST2 = "select  C.student_id, D.majors_id\
            from sms_mysql_students C, sms_mysql_classes D \
            where C.classes_id=D.class_id "
    #print(custom_sql_get_dict(ST2))
    # ST3 将ST1，ST2 与 授课计划连接 得到 不及格的必修课学号 总学分 总数
    ST3 = "select  E.students_id, sum(E.course_credit) sum_compulsory_credit, count(*) count_compulsory \
            from ( %s ) E, ( %s ) F, sms_mysql_teachingplan G \
            where G.tp_type=1 and E.students_id=F.student_id and E.courses_id=G.courses_id and F.majors_id=G.majors_id \
            group by E.students_id " % (ST1, ST2)
    #print(custom_sql_get_dict(ST3))
    # ST4 将ST1，ST2 与 授课计划连接 得到 不及格的选修课学号 总学分 总数
    ST4 = "select  H.students_id, sum(H.course_credit) sum_option_credit, count(*) count_option \
                from ( %s ) H, ( %s ) I, sms_mysql_teachingplan J \
                where J.tp_type=0 and H.students_id=I.student_id and H.courses_id=J.courses_id and I.majors_id=J.majors_id \
                group by H.students_id  " % (ST1, ST2)
    #print(custom_sql_get_dict(ST4))
    # ST5 将ST3和ST4连接得到结果
    ST5 = "select  K.students_id, K.sum_compulsory_credit, K.count_compulsory, L.sum_option_credit, L.count_option \
                    from ( %s ) K, ( %s ) L \
                    where K.students_id=L.students_id and (K.sum_compulsory_credit>=7 or L.sum_option_credit>=12)" % (ST3, ST4)

    # print(ST5)
    querydict = {}
    querydict = custom_sql_get_dict(ST5)
    #print(querydict)
    # # # 查询结果一摸一样!
    # # # queryset = models.Students.objects.all()
    # # # print(queryset.values())
    # return render(request, "student_extra_list.html",
    #               {'queryset': querydict,
    #                'search_data': search_data,
    #                'qst': querydict_student_teacher,
    #                'aga': querydict_all_avg_grade,
    #                'agc': querydict_compulsory_avg_grade})
    return render(request, "student_expel_list.html", {"queryset": querydict})


from typing import Any
import contextlib
import itertools

from object_trace.object_trace import Tracer

def trace(x: Any, labe: str = "") -> Any:
    """Start tracing the object `x`, if tracing is active."""
    if Tracer.ACTIVE_TRACER is not None:
        Tracer.ACTIVE_TRACER.add_object(x, labe)
    return x

@contextlib.contextmanager
def print_traces():
    with Tracer() as traces:
        yield

    for t in traces:
        print(f"# Trace for label=`{t.label}`")
        for line, _ in itertools.groupby(t.format_lines()):
            print(line)
        print("-" * 80)


#!/usr/bin/env python3
# echo "aaa" | zerofill.py 4
#  0aaa
# Created by f-tommy, 2018/09/04
import fileinput
import argparse

# Obtain argument
parser = argparse.ArgumentParser()
parser.add_argument("td",type=int)
parser.add_argument("files",metavar='FILE', nargs='*')
args = parser.parse_args()

# Process line input
for line in fileinput.input(files=args.files):
    lin = line.rstrip('\n')
    col = lin.split()
    tmp = str(col[0])
    tmp0 = tmp.rjust(args.td,'0')
    tmp1 = ' '.join(col[1:]) # list to string
    print(tmp0,tmp1)


import numpy as np

# dataset params
amp_range = [0.1, 5.0]
phase_range = [0, np.pi]
input_range = [-5.0, 5.0]

# model params
dim_input = 1
dim_output = 1
dim_hidden = [40,40]

# training params
task_lr = 1e-3
meta_lr = 1e-3
task_batch_size = 5   # number of samples, i.e. K in K-shot learning
meta_batch_size = 25  # number of tasks sampled per meta update in metalearning setting

# saving model
saving_freq = 100


def valid(board: 'List[List[int]]', coords: 'tuple(x, y)') -> bool:
    rows = len(board)
    cols = len(board[0])
    x, y = coords
    return 0 <= x < rows and 0 <= y < cols

def find_word(board: 'List[List[int]]', word: str, i: int, coords: 'tuple(x, y)', seen: set) -> bool:
    if not valid(board, coords):
        return False

    if coords in seen:
        return False
    else:
        seen.add(coords)

    x, y = coords
    if word[i] != board[x][y]:
        return False

    i += 1

    if i == len(word):
        return True

    if find_word(board, word, i, (x - 1, y), set(seen)):
        return True
    if find_word(board, word, i, (x + 1, y), set(seen)):
        return True
    if find_word(board, word, i, (x, y - 1), set(seen)):
        return True
    if find_word(board, word, i, (x, y + 1), set(seen)):
        return True

    return False

class Solution:
    def exist(self, board: 'List[List[str]]', word: str) -> bool:
        rows = len(board)
        cols = len(board[0])

        for x in range(rows):
            for y in range(cols):
                if find_word(board, word, 0, (x, y), set()):
                    return True
        return False


"""
"""

import random
import itertools
import colorsys
import numpy as np
from skimage.measure import find_contours
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.lines as lines
from matplotlib.patches import Polygon
import IPython.display

import mrcnn_utils
import visualize

############################################################
#  Visualization
############################################################

def display_nuclei(image, boxes, masks, title="",figsize=(16, 16), ax=None):
    """
    boxes: [num_instance, (y1, x1, y2, x2, class_id)] in image coordinates.
    masks: [height, width, num_instances]
    figsize: (optional) the size of the image.
    """
    # Number of instances
    N = boxes.shape[0]
    if not N:
        print("\n*** No instances to display *** \n")
    else:
        assert boxes.shape[0] == masks.shape[-1]

    if not ax:
        _, ax = plt.subplots(1, figsize=figsize)

    # Generate random colors
    colors = visualize.random_colors(N)

    # Show area outside image boundaries.
    height, width = image.shape[:2]
    ax.set_ylim(height + 10, -10)
    ax.set_xlim(-10, width + 10)
    ax.axis('off')
    ax.set_title(title)

    masked_image = image.astype(np.uint32).copy()
    for i in range(N):
        color = colors[i]

        # Bounding box
        if not np.any(boxes[i]):
            # Skip this instance. Has no bbox. Likely lost in image cropping.
            continue
        y1, x1, y2, x2 = boxes[i]
        p = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=2,
                              alpha=0.7, linestyle="dashed",
                              edgecolor=color, facecolor='none')
        ax.add_patch(p)

        # Mask
        mask = masks[:, :, i]
        masked_image = visualize.apply_mask(masked_image, mask, color)

        # Mask Polygon
        # Pad to ensure proper polygons for masks that touch image edges.
        padded_mask = np.zeros(
            (mask.shape[0] + 2, mask.shape[1] + 2), dtype=np.uint8)
        padded_mask[1:-1, 1:-1] = mask
        contours = visualize.find_contours(padded_mask, 0.5)
        for verts in contours:
            # Subtract the padding and flip (y, x) to (x, y)
            verts = np.fliplr(verts) - 1
            p = Polygon(verts, facecolor="none", edgecolor=color)
            ax.add_patch(p)
    ax.imshow(masked_image.astype(np.uint8))
    plt.show()


# -*- coding: utf-8 -*-
"""
Created on Wed Nov 14 21:45:36 2018

@author: Ahmet
"""

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

data = pd.read_csv("sales.csv")
months = data[["Months"]]
sales = data[["Sales"]]

#train and test
from sklearn.cross_validation import train_test_split
x_train, x_test, y_train, y_test = train_test_split(
        months, sales, test_size = 0.33, random_state = 0 )

#feature scaling
from sklearn.preprocessing import StandardScaler
scale = StandardScaler()

x1_train = scale.fit_transform(x_train)
x1_test = scale.fit_transform(x_test)
y1_train = scale.fit_transform(y_train)
y1_test = scale.fit_transform(y_test)

#modeling
from sklearn.linear_model import LinearRegression
linear_reg = LinearRegression()
linear_reg.fit(x_train, y_train)
y_pred = linear_reg.predict(months)

linear_reg.predict(x_test)

#visuzalition

x_train = x_train.sort_index()
y_train = y_train.sort_index()

plt.plot(x_train, y_train)
plt.plot(x_test, linear_reg.predict(x_test))

from sklearn.metrics import r2_score
print("linear r2:", r2_score(sales,y_pred))