import importlib
import json
import logging
import os
import tempfile
from io import StringIO

from celery import shared_task
from django.conf import settings
from django.utils.timezone import now
from scrapy.crawler import Crawler, CrawlerProcess
from scrapy.utils.spider import iter_spider_classes

from .models import Spider as SpiderModel, Execution, Item

@shared_task
def start_spiders():
    for spider in SpiderModel.objects.all():
        run_spider.delay(spider.id)

@shared_task
def run_spider(spider_id):
    spider = SpiderModel.objects.get(id=spider_id)
    execution = Execution.objects.create(spider_id=spider_id, time_started=now())

    user_settings = getattr(settings, 'SCRATCHY_SPIDERS', {})

    item_storage = tempfile.NamedTemporaryFile(delete=False)

    default_settings = {
        'DNS_TIMEOUT': 5,
        'DOWNLOAD_TIMEOUT': 5,
        'AUTOTHROTTLE_ENABLED': True,
        'AUTOTHROTTLE_START_DELAY': 1,
        'AUTOTHROTTLE_MAX_DELAY': 5,
        'AUTOTHROTTLE_TARGET_CONCURRENCY': 1.0,
    }

    internal_settings = {
        'FEED_FORMAT': 'jsonlines',
        'FEED_EXPORT_ENCODING': 'utf-8',
        'FEED_URI': item_storage.name,

    }

    scrapy_settings = {
        **default_settings,
        **user_settings,
        **spider.settings,
        **internal_settings,  # last because these must not be overwritten
    }

    scrapy_spider_cls = None

    module = importlib.import_module(spider.module)

    for cls in iter_spider_classes(module):
        scrapy_spider_cls = cls
        break  # use first valid class in module

    if scrapy_spider_cls is None:
        raise RuntimeError(f'No valid spider class found in module {module}')

    process = CrawlerProcess(settings=None, install_root_handler=False)

    log_capture_string = StringIO()
    log_handler = logging.StreamHandler(log_capture_string)
    log_handler.setLevel(spider.log_level)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    log_handler.setFormatter(formatter)
    scrapy_logger = logging.getLogger('scrapy')
    scrapy_logger.addHandler(log_handler)
    spider_logger = logging.getLogger(scrapy_spider_cls.name)  # scrapy uses the spider name as logger id
    spider_logger.addHandler(log_handler)

    crawler = Crawler(scrapy_spider_cls, scrapy_settings)

    process.crawl(crawler)
    process.start()
    # blocks here

    log_contents = log_capture_string.getvalue()
    spider_logger.removeHandler(log_handler)
    scrapy_logger.removeHandler(log_handler)
    log_capture_string.close()

    execution.time_ended = now()
    execution.stats = crawler.stats._stats
    execution.log = log_contents
    execution.save()

    item_storage.seek(0)

    items = []
    for line in item_storage.readlines():
        item_data = json.loads(line)
        item = Item(spider_id=spider_id, execution=execution, data=item_data)
        items.append(item)

    Item.objects.bulk_create(items, batch_size=100)

    item_storage.close()
    os.remove(item_storage.name)


from pyspark import keyword_only
import pyspark.sql.functions as F
from pyspark.sql import DataFrame
from pyspark.sql.types import StringType, DecimalType
from pyspark.ml import Transformer
from pyspark.ml.param.shared import HasInputCol, HasOutputCol, Param

# noinspection PyUnusedLocal,PyUnresolvedReferences
class ValueMappingTransformer(Transformer, HasInputCol, HasOutputCol):

    """
    Maps the key values on inputCol to values in the mapDict
    """

    @keyword_only
    def __init__(self,
                 inputCol: str = None,
                 outputCol: str = None,
                 mapDict: dict = None):
        # call Transformer classes constructor since were extending it.
        super(Transformer, self).__init__()

        # set Parameter objects minimum mapping dictionary
        self.mapDict = Param(self,
                             "mapDict",
                             "A key string to value string dict, key is the value to be replaced with the value.")
        self._setDefault(mapDict={None: None})

        # set the input keyword arguments
        kwargs = self._input_kwargs
        self.setParams(**kwargs)

        # initialize any other objects
        # self.my_obj = my_utility_objects()

    @keyword_only
    def setParams(self,
                  inputCol: str = None,
                  outputCol: str = None,
                  mapDict: dict = None
                  ) -> None:
        kwargs = self._input_kwargs
        return self._set(**kwargs)

    def _trans_func(self, in_map_value: str) -> str:
        """
        Replacing a string value with another string value.
        The input value is looked up as a key on the dictMap and replaced
        by the corresponding dict value.

        Args:
            in_map_value: A string to be replaced with a corresponding value string on mapDict

        Returns:
            The mapped target value to be placed in the output column

        """

        # Get the specified mapping dictionary
        map_dict = self.getMapDict()

        # Select mapping value from dict and assign to out_col
        out_map_value = map_dict[in_map_value]

        return out_map_value

    def _transform(self, df: DataFrame) -> DataFrame:
        # Get the names of the input and output columns to use
        out_col = self.getOutputCol()
        in_col = self.getInputCol()

        # create the transformation function UDF
        trans_func_udf = F.udf(self._trans_func, StringType())

        # apply the UDF to the in_col column in the dataframe and add a
        # new out_col column with the transformed results
        df2 = df.withColumn(out_col, trans_func_udf(df[in_col]))

        return df2

    def setMapDict(self, value):
        self._paramMap[self.mapDict] = value
        return self

    def getMapDict(self) -> int:
        return self.getOrDefault(self.mapDict)

# noinspection PyUnusedLocal,PyUnresolvedReferences
class TitleFoldTransformer(Transformer, HasInputCol, HasOutputCol):
    """
    Converts capitalized strings to start letter capital/title-caps.
    This string folding won't be performed for strings of defined length,
    contain numbers or are title-caps already.
    """

    @keyword_only
    def __init__(self,
                 inputCol: str = None,
                 outputCol: str = None,
                 capLength: int = None,
                 strSep: str = None):
        # call Transformer classes constructor since were extending it.
        super(Transformer, self).__init__()

        # set Parameter objects minimum capital letters and string separator
        self.capLength = Param(self,
                               "capLength",
                               "Number of characters in a String that should remain all-cap.")
        self._setDefault(capLength=0)
        self.strSep = Param(self,
                            "strSep",
                            "Single character String by which to separate multiple consecutive strings in inputCol.")
        self._setDefault(strSep="")

        # set the input keyword arguments
        kwargs = self._input_kwargs
        self.setParams(**kwargs)

        # initialize any other objects
        # self.my_obj = my_utility_objects()

    @keyword_only
    def setParams(self,
                  inputCol: str = None,
                  outputCol: str = None,
                  capLength: int = None,
                  strSep: str = None
                  ) -> None:

        kwargs = self._input_kwargs
        return self._set(**kwargs)

    @staticmethod
    def _contains_number(in_str: str) -> str:
        """
        Checks a single string of any length for any digit.

        Args:
            in_str: A string

        Returns:
            True if a digit is found. False otherwise

        """
        return_bool = False
        return_bool = any(char.isdigit() for char in in_str)

        return return_bool

    def _trans_func(self, in_value: str) -> str:
        """
        Folds all words in an input string into title-caps, where words are
        separated by strSep cannot contain numbers and
        only words longer than capLength are changed.

        Args:
            in_value: A string with one or more words separated by a strSep

        Returns:
            A string with all words in title-cap

        """

        # Get the specified string length to keep capitalized and separator
        cap_length = self.getCapLength()
        str_sep = self.getStrSep()

        if in_value is not None:
            in_value_list = in_value.split(str_sep)
            out_value = ""

            # TODO: Needs good testing; var is only assigned if if-statements completed as expected!!!
            for item in in_value_list:
                done = False
                if in_value_list[-1] == item:
                    # Only convert strings long enough, without numbers and not starting with single capital letter
                    if len(item) <= cap_length or self._contains_number(item) or item.istitle():
                        out_value = out_value + item
                        done = True
                    if (len(item) > cap_length or not self._contains_number(item) or item.istitle()) and not done:
                        out_value = out_value + item.title()
                if in_value_list[-1] != item:
                    # Only convert strings long enough, without numbers and not starting with single capital letter
                    if len(item) <= cap_length or self._contains_number(item) or item.istitle():
                        out_value = out_value + item + str_sep
                        done = True
                    if (len(item) > cap_length or self._contains_number(item) or item.istitle()) and not done:
                        out_value = out_value + item.title() + str_sep
        if in_value is None:
            out_value = None

        return out_value

    def _transform(self, df: DataFrame) -> DataFrame:
        # Get the names of the input and output columns to use
        out_col = self.getOutputCol()
        in_col = self.getInputCol()

        # create the transformation function UDF
        trans_func_udf = F.udf(self._trans_func, StringType())

        # apply the UDF to the in_col column in the dataframe and add a
        # new out_col column with the transformed results
        df2 = df.withColumn(out_col, trans_func_udf(df[in_col]))

        return df2

    def setCapLength(self, value):
        self._paramMap[self.capLength] = value
        return self

    def getCapLength(self) -> int:
        return self.getOrDefault(self.capLength)

    def setStrSep(self, value):
        self._paramMap[self.strSep] = value
        return self

    def getStrSep(self) -> int:
        return self.getOrDefault(self.strSep)

# noinspection PyUnusedLocal,PyUnresolvedReferences
class StringDecimalTransformer(Transformer, HasInputCol, HasOutputCol):
    """
    Converts string numbers into decimals and removing white space,
    commas and thousands indicators as specified in the process
    """

    @keyword_only
    def __init__(self,
                 inputCol: str = None,
                 outputCol: str = None,
                 removeTokens: list = None,
                 decSplitStr: str = None,
                 precision: int = None,
                 scale: int = None):
        # call Transformer classes constructor since were extending it.
        super(Transformer, self).__init__()

        # set Parameter objects
        self.removeTokens = Param(self,
                                  "removeTokens",
                                  "A list of string tokens to remove, if one use [char], e.g., thousands indicators.")
        self._setDefault(removeTokens=[None])
        self.decSplitStr = Param(self,
                                 "decSplitStr",
                                 "A single character string indicating the decimal character, e.g. '.' in '0.1'.")
        self._setDefault(decSplitStr="")
        self.precision = Param(self,
                               "precision",
                               "Int for max digits before decimal, e.g, '2' in '0.1'. Defaults of DecimalType()")
        self._setDefault(precision=None)
        self.scale = Param(self,
                           "scale",
                           "Int number of precision to after decimals, e.g. '1' in '0.1'. Defaults of DecimalType()")
        self._setDefault(scale=None)

        # set the input keyword arguments
        kwargs = self._input_kwargs
        self.setParams(**kwargs)

        # initialize any other objects
        # self.my_obj = my_utility_objects()

    @keyword_only
    def setParams(self,
                  inputCol: str = None,
                  outputCol: str = None,
                  removeTokens: list = None,
                  decSplitStr: str = None,
                  precision: int = None,
                  scale: int = None
                  ) -> None:
        kwargs = self._input_kwargs
        return self._set(**kwargs)

    def _num_formater(self, in_value: str) -> str:
        """
        Checks if the in_value only contains permissible characters such as digits, tokens or separator,
        then removes these items.
        Additionally ensures that there is only a single separator.

        Args:
            in_value: A string to be checked

        Returns:
            A string of digits with tokens removed and a single separator value. None otherwise.

        """
        remove_tokens = self.getRemoveTokens()
        dec_split_str = self.getDecSplitStr()
        digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
        allowed = remove_tokens + [dec_split_str] + digits
        return_val = ""
        split_ct = 0

        for item in in_value:
            if item == dec_split_str:
                split_ct = split_ct + 1
                if split_ct > 1:
                    return_val = None
                    break
            if item not in allowed:
                return_val = None
                break
            if item in remove_tokens:
                in_value = in_value.replace(item, "")
            if item == in_value[-1]:
                return_val = in_value

        # Number formats work poor with anything else than "." therefore replacing dec_split_str
        if dec_split_str != "." and return_val is not None:
            return_val = return_val.replace(dec_split_str, ".")

        return return_val

    def _trans_func(self, in_value: str) -> str:

        clean_in_value = self._num_formater(str(in_value))

        return clean_in_value

    def _transform(self, df: DataFrame) -> DataFrame:
        # Get the names of the input and output columns to use
        # TODO: Make this work for a number of column names
        out_col = self.getOutputCol()
        in_col = self.getInputCol()

        # create the transformation function UDF
        trans_func_udf = F.udf(self._trans_func, StringType())

        # apply the UDF to the in_col column in the dataframe and add a
        # new out_col column with the transformed results
        df = df.withColumn(out_col, trans_func_udf(df[in_col]))

        # Compute precision/scale for adequate decimal value conversion unless defined by user
        # Note: This expects that the decSplitStr has been replaced by _num_formater with a "."!!!
        # TODO: Consider to simplify the query
        if self.getScale() is None or self.getPrecision() is None:
            pre_scl_df = df.select(df[out_col]) \
                .withColumn("pre_dec",
                            F.when(F.instr(out_col, ".") != 0,
                                   F.instr(out_col, ".") - 1) \
                            .otherwise(F.length(df[out_col]))) \
                .withColumn("post_dec",
                            F.when(
                                    F.when(F.instr(out_col, ".") != 0,
                                        F.length(df[out_col]) - 1) \
                                    .otherwise(F.length(df[out_col])) \
                                   - F.when(F.instr(out_col, ".") - 1 > 0,
                                            F.instr(out_col, ".") - 1) \
                                   .otherwise(0) == \
                                    F.when(F.instr(out_col, ".") != 0,
                                        F.length(df[out_col]) - 1) \
                                    .otherwise(F.length(df[out_col])), 0) \
                            .otherwise(
                                    F.when(F.instr(out_col, ".") != 0,
                                        F.length(df[out_col]) - 1) \
                                    .otherwise(F.length(df[out_col])) \
                                       - F.when(F.instr(out_col, ".") - 1 > 0,
                                                F.instr(out_col, ".") - 1) \
                                       .otherwise(0)))

            scale = pre_scl_df.agg(F.max("post_dec")).collect()[0][0]
            precision = pre_scl_df.agg(F.max("pre_dec")).collect()[0][0] + scale

            # TODO: Make this additive so that precision = scale + max characters because now too much of precision
            #       gets used by scale!
            self.setPrecision(precision)
            self.setScale(scale)

        df = df.withColumn(out_col, F.col(out_col).cast(DecimalType(self.getPrecision(),
                                                                    self.getScale())))

        return df

    def setRemoveTokens(self, value):
        self._paramMap[self.removeTokens] = value
        return self

    def getRemoveTokens(self) -> int:
        return self.getOrDefault(self.removeTokens)

    def setDecSplitStr(self, value):
        self._paramMap[self.decSplitStr] = value
        return self

    def getDecSplitStr(self) -> int:
        return self.getOrDefault(self.decSplitStr)

    def setPrecision(self, value):
        self._paramMap[self.precision] = value
        return self

    def getPrecision(self) -> int:
        return self.getOrDefault(self.precision)

    def setScale(self, value):
        self._paramMap[self.scale] = value
        return self

    def getScale(self) -> int:
        return self.getOrDefault(self.scale)


"""
Functions for capturing and redirecting IO streams.

The :class:`CaptureStdout` captures all text sent to stdout and optionally
prevents it from actually reaching stdout.

The :class:`TeeStringIO` does the same thing but for arbitrary streams. It is
how the former is implemented.

"""
import sys
import io

class TeeStringIO(io.StringIO):
    """
    An IO object that writes to itself and another IO stream.

    Attributes:
        redirect (io.IOBase): The other stream to write to.

    Example:
        >>> redirect = io.StringIO()
        >>> self = TeeStringIO(redirect)
    """
    def __init__(self, redirect=None):
        self.redirect = redirect  # type: io.IOBase
        super(TeeStringIO, self).__init__()

        # Logic taken from prompt_toolkit/output/vt100.py version 3.0.5 in
        # flush I don't have a full understanding of what the buffer
        # attribute is supposed to be capturing here, but this seems to
        # allow us to embed in IPython while still capturing and Teeing
        # stdout
        if hasattr(redirect, 'buffer'):
            self.buffer = redirect.buffer  # Py3.
        else:
            self.buffer = redirect

    def isatty(self):  # nocover
        """
        Returns true of the redirect is a terminal.

        Note:
            Needed for IPython.embed to work properly when this class is used
            to override stdout / stderr.
        """
        return (self.redirect is not None and
                hasattr(self.redirect, 'isatty') and self.redirect.isatty())

    def fileno(self):
        """
        Returns underlying file descriptor of the redirected IOBase object
        if one exists.
        """
        if self.redirect is not None:
            return self.redirect.fileno()
        else:
            return super(TeeStringIO, self).fileno()

    @property
    def encoding(self):
        """
        Gets the encoding of the `redirect` IO object

        Example:
            >>> redirect = io.StringIO()
            >>> assert TeeStringIO(redirect).encoding is None
            >>> assert TeeStringIO(None).encoding is None
            >>> assert TeeStringIO(sys.stdout).encoding is sys.stdout.encoding
            >>> redirect = io.TextIOWrapper(io.StringIO())
            >>> assert TeeStringIO(redirect).encoding is redirect.encoding
        """
        if self.redirect is not None:
            return self.redirect.encoding
        else:
            return super(TeeStringIO, self).encoding

    def write(self, msg):
        """
        Write to this and the redirected stream
        """
        if self.redirect is not None:
            self.redirect.write(msg)
        return super(TeeStringIO, self).write(msg)

    def flush(self):  # nocover
        """
        Flush to this and the redirected stream
        """
        if self.redirect is not None:
            self.redirect.flush()
        return super(TeeStringIO, self).flush()

class CaptureStream(object):
    """
    Generic class for capturing streaming output from stdout or stderr
    """

class CaptureStdout(CaptureStream):
    r"""
    Context manager that captures stdout and stores it in an internal stream

    Args:
        suppress (bool, default=True):
            if True, stdout is not printed while captured
        enabled (bool, default=True):
            does nothing if this is False

    Example:
        >>> self = CaptureStdout(suppress=True)
        >>> print('dont capture the table flip (╯°□°）╯︵ ┻━┻')
        >>> with self:
        ...     text = 'capture the heart ♥'
        ...     print(text)
        >>> print('dont capture look of disapproval ಠ_ಠ')
        >>> assert isinstance(self.text, str)
        >>> assert self.text == text + '\n', 'failed capture text'

    Example:
        >>> self = CaptureStdout(suppress=False)
        >>> with self:
        ...     print('I am captured and printed in stdout')
        >>> assert self.text.strip() == 'I am captured and printed in stdout'

    Example:
        >>> self = CaptureStdout(suppress=True, enabled=False)
        >>> with self:
        ...     print('dont capture')
        >>> assert self.text is None
    """
    def __init__(self, suppress=True, enabled=True, **kwargs):
        _misspelled_varname = 'supress'
        if _misspelled_varname in kwargs:  # nocover
            from xdoctest.utils import util_deprecation
            util_deprecation.schedule_deprecation(
                modname='xdoctest',
                name='supress', type='Argument of CaptureStdout',
                migration='Use suppress instead',
                deprecate='1.0.0', error='1.1.0', remove='1.2.0'
            )
            suppress = kwargs.pop(_misspelled_varname)
            if len(kwargs) > 0:
                raise ValueError('unexpected args: {}'.format(kwargs))
        self.enabled = enabled
        self.suppress = suppress
        self.orig_stdout = sys.stdout
        if suppress:
            redirect = None
        else:
            redirect = self.orig_stdout
        self.cap_stdout = TeeStringIO(redirect)
        self.text = None

        self._pos = 0  # keep track of how much has been logged
        self.parts = []
        self.started = False

    def log_part(self):
        """ Log what has been captured so far """
        self.cap_stdout.seek(self._pos)
        text = self.cap_stdout.read()
        self._pos = self.cap_stdout.tell()
        self.parts.append(text)
        self.text = text

    def start(self):
        if self.enabled:
            self.text = ''
            self.started = True
            sys.stdout = self.cap_stdout

    def stop(self):
        """
        Example:
            >>> CaptureStdout(enabled=False).stop()
            >>> CaptureStdout(enabled=True).stop()
        """
        if self.enabled:
            self.started = False
            sys.stdout = self.orig_stdout

    def __enter__(self):
        self.start()
        return self

    def __del__(self):  # nocover
        if self.started:
            self.stop()
        if self.cap_stdout is not None:
            self.close()

    def close(self):
        self.cap_stdout.close()
        self.cap_stdout = None

    def __exit__(self, type_, value, trace):
        if self.enabled:
            try:
                self.log_part()
            except Exception:  # nocover
                raise
            finally:
                self.stop()
        if trace is not None:
            return False  # return a falsey value on error


"""
101. Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

"""

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

# Stack
def isSymmetric(root):
    """
    :type root: TreeNode
    :rtype: bool
    """
    stack = []
    stack.append((root, root))
    while stack:
        t1, t2 = stack.pop()
        if t1 is None and t2 is None:
            continue
        if t1 is None or t2 is None:
            return False
        if t1.val != t2.val:
            return False
        stack.append((t1.left, t2.right))
        stack.append((t1.right, t2.left))
    return True


# -*- coding: utf-8 -*-
"""
Created on Mon Sep 23 14:09:00 2019

@author: huyn
"""

#https://www.hackerrank.com/challenges/repeated-string/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup&h_r=next-challenge&h_v=zen
######### great one
def repeatedString(s, n):
    d= {}
    current = None
    for i in range(len(s)):
        if s[i]=="a":
            if not d:
                d[i]=1
                current = i
            else:
                d[i]=d[current]+1
                current = i
    bigCount = n//len(s)*(len(d))
#    print ("bigCount",bigCount)
    extraLength = n%len(s)
#    print ("extraLength",extraLength)
    if extraLength and d:
        array = list(d.keys())
        start = 0
        stop = len(array)-1
        while start+1<stop:
            mid = (start+stop)//2
            if array[mid] == extraLength-1:
                return bigCount+d[array[mid]]
            elif array[mid]<extraLength-1:
                start=mid
            else:
                stop = mid
#        print (array,start,stop)
        if array[stop]<=extraLength-1:
            return bigCount+d[array[stop]]
        elif array[start]<=extraLength-1:
            return bigCount+d[array[start]]
    return bigCount


#!/usr/bin/env python
import sys
import time
import RPi.GPIO as GPIO

def servo(steps,direction):
    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)
    direction=-direction
    IOpin = [25,8,7,12]

    for pin in IOpin:
        GPIO.setup(pin,GPIO.OUT)
        GPIO.output(pin, False)

    seq = [[1,0,0,1],              # 4 phase half stepping
        [1,0,0,0],
        [1,1,0,0],
        [0,1,0,0],
        [0,1,1,0],
        [0,0,1,0],
        [0,0,1,1],
        [0,0,0,1]]

    # steps = int(sys.argv[1])        # 128 with directon +-1 for 90 degree (total 1024)
    # direction = int(sys.argv[2])    # +1 +2 clock, minus anti
    # sleeptime = float(sys.argv[3])  # in seconds, usually 0.005-0.01
    sleeptime=0.005
    counter = 0

    for x in xrange(steps):
        for s in seq[::direction]:
            for pin in xrange(4):
                GPIO.output(IOpin[pin], False if s[pin]==0 else True)
            time.sleep(sleeptime)

    for pin in xrange(4):
    	GPIO.output(IOpin[pin], False)

if __name__ == "__main__":
    servo(128,1)


import cv2
import numpy as np

######################
nPlateCascade = cv2.CascadeClassifier("D:\Fauzan Alif\Learn Python\Resources/haarcascade_russian_plate_number.xml")
widthImg = 640
heightImg = 480
######################
#kita ingin mendeteksi plat nomor kendaraan menggunakan cascades
#cascades adalah semacam library untuk mendeteksi object tertentu, yg bisa didapatkan dari opencv sndiri
#cascades berupa file .xml

cap = cv2.VideoCapture(0)
cap.set (3,widthImg)
cap.set(4,heightImg)
cap.set(10,100)

count = 0
minArea= 500

while True:
    success, img = cap.read()

    imgGray = cv2.cvtColor(img ,cv2.COLOR_BGR2GRAY)

    #face cascade.detect multi scale (target gambar, luas besar kotaknya
    # , minNeighbor (dapat dilihat pada kite) )
    platDetector = nPlateCascade.detectMultiScale(imgGray, 1.1,4)
    for (x, y, w, h) in platDetector:
        area = w*h
        if area > minArea:
            cv2.rectangle(img, (x, y), (x+w, y+h), (255,0,0), 3)
            cv2.putText(img, "Plat Kendaraan",(x,y-5), cv2.FONT_HERSHEY_COMPLEX, 2, (255,0,0), 2)
            imgRoi = img[y:y+h, x:x+w]

            cv2.imshow("Plat Detector", img)

    #sekarang, setelah kita memunculkan plate detection, kita ingin menyimpan hasil deteksi ke dalam folder
    if cv2.waitKey(1) & 0xFF == ord('q'): #bisa jg ord key nya diganti ke huruf s (karena saved)
        #kita ingin menyimpan hasilnya ke folder tertentu
        cv2.imwrite("D:\Fauzan Alif\Learn Python\Resources/Scanned/No_Plate_"+str(count)+".jpg", imgRoi)
        #kita ingin memberikan block warna pada text
        cv2.rectangle(img, (0,200), (640,300), (0,255,0), cv2.FILLED)
        #kita ingin memberikan kalimat notif klo udah disave
        cv2.putText(img, "Plat Numbernya telah disave", (150,265), cv2.FONT_HERSHEY_COMPLEX, 2, (255,0,0), 2)

        cv2.imshow("Plat telah disave",img)
        cv2.waitKey(500)
        count+=1

cv2.destroyAllWindows()


#!/usr/bin/env python

from ctypes import *
import platform

# we test what platform the code runs on and then
# we load the dynamic library with the corresponding file extension
if platform.system() == "Linux":
    matrix_multiply = CDLL('./matrix_multiply.so')
elif platform.system() == "Windows":
    matrix_multiply = CDLL('.\matrix_multiply.dll')

def matrix_multiply_demo(file, size, repetitions):
    # this syntax creates 4 arrays (3 integer arrays and 1 c-string array)
    n_matrices = (c_int * 1)(repetitions) # integer array of length `1`, initialized to `repetitions`
    matrices = (c_char_p * repetitions)() # c-string array of length `repetitions`
    heights = (c_int * repetitions)() # integer array of length `repetitions`
    widths = (c_int * repetitions)() # integer array of length `repetitions`

    # here we initialize the arrays
    for i in range(repetitions):
        matrices[i] = bytes(file, encoding='utf8')
        heights[i] = size
        widths[i] = size

    # we pass the 4 arrays to the C code, function `matrix_multiply_demo`
    matrix_multiply.matrix_multiply_demo(n_matrices, matrices, heights, widths)

matrix_multiply_demo('data/matrix32.data', 32, 32)
matrix_multiply_demo('data/matrix64.data', 64, 64)
matrix_multiply_demo('data/matrix96.data', 96, 96)


from secrets import *
from pwn import *
import argparse

# OTP Requirements
# 1. Key must be same at least length of message
# 2. Key must never be reused
# 3. Key must be retrieved from random, or in a real case, pseudo-random generator
# 4. Key must be sent over secure medium
    # - Up to user

#Xor byte values
def xor_bytes(message, key):
    value = '{:x}'.format(int(message, 16) ^ int(key, 16))
    return value

#Generate random key that is same length as message
def generate_key(message, used_keys):
    #Used for conditional break
    boolean = 0

    #Used to get list of used keys
    key_list = []

    #Populate list of keys
    for key in used_keys:
        if key != '\n':
            key_list.append(key.strip('\n'))

    # Recursively check to ensure key is new
    while(boolean == 0):
        # Generate key that is the length of the message to support requirement 1
        # (Dividing over 2 because function is length doubling PRG)
        # PRG is pseudo random (https://docs.python.org/3/library/secrets.html) Supports requirement 3
        key = token_hex(int(len(message)/2))

        # IF you wanna test (program will just keep looping) => key = 'c203142209549f'

        #Check if key was already used to support requirement 2
        if(key not in key_list):
            boolean = 1
            used_keys = open('used_keys.txt', 'a+')
            used_keys.write(key+'\n')
            return key

# Encrypt a message
def encrypt(message):
    used_keys = open('used_keys.txt', 'r')
    message = message.encode('utf-8').hex()
    key = generate_key(message, used_keys)
    encrypted_message = xor_bytes(message, key)
    print("Encrypted message: {}, Key: {}".format(encrypted_message, key))

# Decrypt a message
def decrypt(ciphertext, key):
    message = '{:x}'.format(int(ciphertext, 16) ^ int(key, 16))
    print(unhex(message))

#Parse arguments
def main():

    # Create the parser
    parser = argparse.ArgumentParser()

    # Encrypt message
    parser.add_argument('--encrypt', required=False, help='Encrypt a message. Key generated randomly.')

    # Decrypt a message
    parser.add_argument('--decrypt', required=False, help='Decrypt a message. Requires key.')
    parser.add_argument('--key', required=False, help='Key used for decryption. Requires ciphertext.')

    # Parse the argument
    args = parser.parse_args()

    if args.encrypt:
        encrypt(args.encrypt)

    elif args.decrypt:
        # Check if ciphertext but no key
        if args.key == None:
            print("Need key for decryption")
            exit(0)
        else:
            decrypt(args.decrypt, args.key)

    elif args.key:
        # Check if key but no ciphertext
        if args.decrypt == None:
            print("Need ciphertext for decryption")
            exit(0)
        else:
            decrypt(args.decrypt, args.key)

main()


from os import listdir, path

filePath = "../test"
files = listdir(filePath)
totalCsv = 0

def countCsv(folder):
	count = 0
	for file in folder:
		if file.endswith('.csv'):
			count +=1
	return count

for file in files:
	if path.isdir(path.join(filePath, file)):
		subFolder = listdir(path.join(filePath, file))
		totalCsv += countCsv(subFolder)
	elif file.endswith('.csv'):
		totalCsv +=1

print("CSV File Count: {} files".format(totalCsv))


n = int(input())
s = input()

left = 0
stack = []
for i in range(n):
    if s[i] == '(':
        stack.append('(')
    else:
        if len(stack) == 0:
            left += 1
        else:
            stack.pop()
right = len(stack)

t = ('(' * left) + s + (')' * right)
print(t)


from basic.blog.managers import PublicManager
from basic.media.models import Photo
from django.contrib.auth.models import User
from django.db import models
from django.db.models import permalink
from django.utils.translation import ugettext_lazy as _
from tagging.fields import TagField
from tinymce import models as tinymce
import tagging
from filebrowser import fields as filebrowser
import datetime
from django_extensions.db.fields import AutoSlugField

class Category(models.Model):
    """Category model."""
    title       = models.CharField(_('title'), max_length=100)
    slug        = models.SlugField(_('slug'), unique=True)

    class Meta:
        verbose_name = _('category')
        verbose_name_plural = _('categories')
        db_table = 'blog_categories'
        ordering = ('title',)

    class Admin:
        pass

    def __unicode__(self):
        return u'%s' % self.title

    @permalink
    def get_absolute_url(self):
        return ('blog_category_detail', None, {'slug': self.slug})

class Post(models.Model):
    """Post model."""
    STATUS_CHOICES = (
        (1, _('Draft')),
        (2, _('Public')),
    )
    title           = models.CharField(_('title'), max_length=200)
    slug            = AutoSlugField(_('slug'), editable=True, blank=False, populate_from='title')
    author          = models.ForeignKey(User, blank=True, null=True)
    thumb           = filebrowser.FileBrowseField(format='Image', max_length=200, blank=True, null=True)
    body            = tinymce.HTMLField(_('body'))
    tease           = models.TextField(_('tease'), blank=True)
    status          = models.IntegerField(_('status'), choices=STATUS_CHOICES, default=1)
    allow_comments  = models.BooleanField(_('allow comments'), default=True)
    publish         = models.DateTimeField(_('publish'), default=datetime.datetime.now())
    created         = models.DateTimeField(_('created'), auto_now_add=True)
    modified        = models.DateTimeField(_('modified'), auto_now=True)
    categories      = models.ForeignKey(Category, default=1)
    tags            = TagField()
    objects         = PublicManager()

    class Meta:
        verbose_name = _('post')
        verbose_name_plural = _('posts')
        db_table  = 'blog_posts'
        ordering  = ('-publish',)
        get_latest_by = 'publish'

    class Admin:
        list_display  = ('title', 'publish', 'status')
        list_filter   = ('publish', 'categories', 'status')
        search_fields = ('title', 'body')

    def __unicode__(self):
        return u'%s' % self.title

    @permalink
    def get_absolute_url(self):
        return ('blog_detail', None, {
            'year': self.publish.year,
            'month': self.publish.strftime('%b').lower(),
            'day': self.publish.day,
            'slug': self.slug
        })

    def get_previous_post(self):
        return self.get_previous_by_publish(status__gte=2)

    def get_next_post(self):
        return self.get_next_by_publish(status__gte=2)


# string = "me and sara and nikan are friends."
# word = ''
# all_words = []
# for char in string:
#     word += char
#     if char == ' ' or char == '.':
#         all_words.append(word[:-1])
#         word =''

# print(all_words)

import turtle

s = turtle.Screen()

p = turtle.Pen()
p.penup()

p.goto(-100, 20)
p.pendown()
p.goto(100, 20)
p.left(120)
p.forward(200)
p.left(120)
p.forward(200)

p.penup()

p.goto(-100, -20)
p.setheading(0)
p.pendown()
p.forward(200)

s.exitonclick()


from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse, reverse_lazy
from django.http import HttpResponseRedirect, Http404
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from django.core.paginator import Paginator
from django.contrib.auth.models import User
from .models import User
from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm
from Post.models import Post
from Favorite.models import Favorite

def index(request):
    posts = Post.objects.all()
    context = {
        'posts': posts
    }
    return render(request, 'blog/index.html', context)

class PostListView(ListView):
    model = Post
    template_name = 'blog/index.html'
    context_object_name = 'posts'
    paginate_by = 5

class PostDetailView(DetailView):
    model = Post
    context_object_name = 'post'

class PostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    fields = ['title', 'content', 'image']

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

class PostEditView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = Post
    fields = ['title', 'content', 'image']

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

    def test_func(self):
        return self.request.user == self.get_object().author

class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
    model = Post
    success_url = reverse_lazy('index')

    def test_func(self):
        return self.request.user == self.get_object().author

def login(request):
    return render(request, 'blog/login.html')

def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, f'Welcome {username}, your profile  has been created successfully! You can now login.')
            return redirect('login')
    else:
        form = UserRegisterForm()

    context = {
        'form': form
    }
    return render(request, 'blog/register.html', context)

@login_required
def profile(request, *args, **kwargs):
    if request.method == 'POST':
        user_update_form = UserUpdateForm(request.POST, instance=request.user)
        profile_update_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
        if user_update_form.is_valid() and profile_update_form.is_valid():
            user_update_form.save()
            profile_update_form.save()
            messages.success(request, 'Your profile info has been updated successfully!')
            return redirect(reverse('profile') + f'?page=1&username={ request.user.username }')
    else:
        user = get_object_or_404(User, username=request.GET.get('username'))
        page_num = request.GET.get('page')
        user_update_form = UserUpdateForm(instance=user)
        profile_update_form = ProfileUpdateForm(instance=user.profile)
        fav_posts = user.favorite.posts.all()

    paginate_by = 5
    posts = Post.objects.filter(author=user)
    paginator = Paginator(posts, paginate_by)
    user_posts = None

    try:
        page_obj = paginator.page(int(page_num))
        user_posts = page_obj.object_list

    except:
        raise Http404("Page does not exist.")

    context = {
        'page_user': user,
        'user_update_form': user_update_form,
        'profile_update_form': profile_update_form,
        'user_posts': user_posts,
        'page_obj': page_obj,
        'is_paginated': True,
        'fav_posts': fav_posts,
    }

    return render(request, 'users/profile.html', context)


from datetime import datetime

from requests import Response, Session

from . import __version__
from .constants import (
    DAY_END,
    DAY_START,
    DEFAULT_DAY,
    DEFAULT_YEAR,
    URL_PATTERN,
    YEAR_END,
    YEAR_START,
)
from .io import get_session_cookie

class AoCSession(Session):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.headers.update({"User-Agent": f"aocli/{__version__}"})
        self.cookies.update(get_session_cookie(raise_on_missing=False))

    def request(self, method: str, url: str, raise_for_status: bool = False, *args, **kwargs) -> Response:  # type: ignore
        # validate url
        year, day = URL_PATTERN.match(url).groups()  # type: ignore
        year = int(year)
        day = int(day)

        # check for year
        if not YEAR_START <= year <= YEAR_END:
            raise ValueError(
                f"Invalid year: {year}. Must be between {YEAR_START} and {YEAR_END}."
            )
        # check for day
        if not DAY_START <= day <= DAY_END:
            raise ValueError(
                f"Invalid day: {day}. Must be between {DAY_START} and {DAY_END}."
            )
        if year == DEFAULT_YEAR:
            if day > DEFAULT_DAY:
                raise ValueError(
                    f"Invalid day: {day} for year {year}. Must be between 1 and {DEFAULT_DAY}."
                )
            elif day == DEFAULT_DAY and datetime.utcnow().hour - 5 < 0:
                raise ValueError(
                    f"Invalid day: {day} for year {year}. Must be between 1 and {DEFAULT_DAY-1}."
                )

        resp = super().request(method, url, *args, **kwargs)
        if raise_for_status:
            resp.raise_for_status()
        return resp

    def get(self, url: str, *args, raise_for_status: bool = False, **kwargs) -> Response:  # type: ignore
        return self.request("GET", url, *args, raise_for_status, **kwargs)

    def post(self, url: str, *args, raise_for_status: bool = False, **kwargs) -> Response:  # type: ignore
        return self.request("POST", url, *args, raise_for_status, **kwargs)

# initialize Session
session = AoCSession()


'''Create a Bus child class that inherits from the Vehicle class. The default fare charge of any vehicle is seating capacity * 100.
If Vehicle is Bus instance, we need to add an extra 10% on full fare as a maintenance charge. So total fare for bus instance will
become the final amount = total fare + 10% of the total fare.
Note: The bus seating capacity is 50. so the final fare amount should be 5500. You need to override the fare() method of a Vehicle class in Bus class.
Use the following code for your parent Vehicle class. We need to access the parent class from inside a method of a child class.'''
# method-1:
class vehicles:
    def vehicle_fare(self, capacity):
        fare =  capacity*100
        return fare
class busses:
    def bus_fare(self, fare):
        new_fare = ((fare*10)/100)+fare
        return new_fare
bus1 = busses()
fare = bus1.vehicle_fare(50)
print('the total fare of the bus is: Rs.',bus1.bus_fare(fare), 'using method - 1')
# method_2
class busses_(vehicles):
    def bus_fare_(self):
        fare = super().vehicle_fare(50)
        new_fare = ((fare*10)/100)+fare
        return new_fare
bus2 = busses_()
print('the total fare of the bus is: Rs.',bus2.bus_fare_(), 'using method - 2')


import csv
from math import pi
import argparse
import itertools
import numpy as np
from scipy.spatial import distance
import matplotlib.pyplot as plt
from scipy.signal import argrelextrema
import copy

argparser = argparse.ArgumentParser(
    description='Annotate images in a folder')

argparser.add_argument(
    '-kp',
    '--known_points',
    help='path to known points')
argparser.add_argument(
    '-op',
    '--observed_points',
    help='path to observed points')

def read_points_location(points_location):
    with open(points_location, 'r') as f:
        reader = csv.reader(f)
        points2D = list(reader)
    points2Dint = []
    for i in range(len(points2D)):
        points2Dint.append([float(x) for x in points2D[i]])
    return points2Dint

def _main_(args):
    known_points_path = args.known_points
    observed_points_path = args.observed_points
    known_points = read_points_location(known_points_path)
    observed_points = read_points_location(observed_points_path)
    potential_match = PointsMatcher(known_points, observed_points)
    potential_matches = potential_match.get_potential_correspondences()
    pose_estimator = PoseEstimator(known_points, observed_points, potential_matches)
    pose = pose_estimator.get_transform()
    print(pose)

class PointsMatcher:
    def __init__(self, known_points, observed_points):
        self.known_points = known_points
        self.observed_points = observed_points
        # self.dmat = []
        # self.amat = []
        self.correspondence_matrix = self.generate_correspondence_matrix(known_points, observed_points)

    def generate_correspondence_matrix(self, known_points, observed_points):
        known_triangle_idx, known_triangle_sides, known_areas = self.triangle_list_idx(known_points)
        observed_triangle_idx, observed_triangle_sides, observed_areas = self.triangle_list_idx(observed_points)
        correspondance_matrix = np.zeros([len(known_points), len(observed_points)])
        for i in range(len(known_triangle_idx)):
            for j in range(len(observed_triangle_idx)):
                similarity_score = self.shape_parameter(known_triangle_sides[i], observed_triangle_sides[j]) * \
                                    self.surface_parameter(known_areas[i], observed_areas[j])
                for k in range(len(known_triangle_idx[i])):
                    correspondance_matrix[known_triangle_idx[i][k], observed_triangle_idx[j][k]] += similarity_score
        correspondance_matrix = correspondance_matrix / np.linalg.norm(correspondance_matrix)
        return correspondance_matrix

    def triangle_list_idx(self, points):
        distance_mat = distance.cdist(points, points, 'sqeuclidean')
        triangle_lists_idx = []
        triangle_sides = []
        triangle_areas = []
        points = np.asarray(points)
        eps = 1e-3
        for subset in itertools.combinations(range(len(points)), 3):
            cross_prod = np.linalg.norm(np.cross(points[subset[0]]-points[subset[1]],
                                  points[subset[0]]-points[subset[2]]))
            if cross_prod < eps:
                pass
            triangle_side_lengths = [distance_mat[subset[0], subset[1]], distance_mat[subset[1], subset[2]],
                                     distance_mat[subset[0], subset[2]]]
            # TODO: add for isoceles case
            sorted_sides_idx = np.argsort(triangle_side_lengths)
            subset_corrected = [subset[sorted_sides_idx[i]] for i in range(len(sorted_sides_idx))]
            triangle_sides.append(sorted(triangle_side_lengths))
            triangle_lists_idx.append(subset_corrected)
            triangle_areas.append(self.area_from_points([points[subset[0]], points[subset[1]],
                                  points[subset[2]]]))
        return triangle_lists_idx, triangle_sides, triangle_areas

    def area_from_points(self, points):
        points = np.asarray(points)
        ab = points[1]-points[0]
        ac = points[2]-points[0]
        area = 0.5 * np.linalg.norm(np.cross(ab, ac))
        return area

    def shape_parameter(self, triangle_sides_1, triangle_sides_2):
        d = (triangle_sides_1[0]-triangle_sides_2[0])**2 + (triangle_sides_1[0]-triangle_sides_2[0])**2 \
            + (triangle_sides_1[0]-triangle_sides_2[0])**2
        # self.dmat.append(d)
        alpha_l = 1
        shape_param = np.exp(-d/alpha_l)
        return shape_param

    def surface_parameter(self, triangle_area_1, triangle_area_2):
        # self.amat.append((triangle_area_1-triangle_area_2)**2)
        alpha_s = 10
        surface_param = np.exp(-(triangle_area_1-triangle_area_2)**2 / alpha_s)
        return surface_param

    def get_potential_correspondences(self):
        corres_mat = copy.deepcopy(self.correspondence_matrix)
        potential_matches = []
        search_times = 2
        if corres_mat.shape[0] <= corres_mat.shape[1]:
            while search_times > 0:
                local_maximas = []
                for i in range(corres_mat.shape[0]):
                    potentialRightIdx = np.argmax(corres_mat[i, :])
                    potentialLeftIdx = np.argmax(corres_mat[:, potentialRightIdx])
                    if potentialLeftIdx == i:
                        local_maximas.append([potentialLeftIdx, potentialRightIdx])
                for i in range(len(local_maximas)):
                    corres_mat[local_maximas[i][0], local_maximas[i][1]] = 0
                search_times -= 1
                potential_matches.append(local_maximas)
        else:
            while search_times > 0:
                local_maximas = []
                for i in range(corres_mat.shape[1]):
                    potentialLeftIdx = np.argmax(corres_mat[:, i])
                    potentialRightIdx = np.argmax(corres_mat[potentialLeftIdx, :])
                    if potentialRightIdx == i:
                        local_maximas.append([potentialLeftIdx, potentialRightIdx])
                for i in range(len(local_maximas)):
                    corres_mat[local_maximas[i][0], local_maximas[i][1]] = 0
                search_times -= 1
                potential_matches.append(local_maximas)

        # generate subsets of matches
        matches = []
        for i in range(len(potential_matches)):
            matches_subset = []
            if len(potential_matches[i]) > 3:
                for subset in itertools.combinations(range(len(potential_matches[i])), len(potential_matches[i])-1):
                    for i in range(len(potential_matches[i])):
                        match_subset = [potential_matches[i][j] for j in subset]
                        matches_subset.append(match_subset)
            elif len(potential_matches[i]) == 3:
                matches_subset.append(potential_matches[i])
        matches.extend(matches_subset)
        return matches

class PoseEstimator:
    def __init__(self, known_points, observed_points, potential_matches):
        self.known_points = known_points
        self.observed_points = observed_points
        self.potential_matches = potential_matches

    def get_transform(self):
        errors = []
        Ts = []
        Rs = []
        ts = []
        for i in range(len(self.potential_matches)):
            known_combination = np.empty([len(self.potential_matches[i]), 3])
            observed_combination = np.empty([len(self.potential_matches[i]), 3])
            for j in range(len(self.potential_matches[i])):
                known_combination[j, :] = self.known_points[self.potential_matches[i][j][0]]
                observed_combination[j, :] = self.observed_points[self.potential_matches[i][j][1]]
            T, R, t = self.best_fit_transform(known_combination, observed_combination)
            error = self.get_transformation_loss(known_combination, observed_combination, T)
            errors.append(error)
            Ts.append(T)
            Rs.append(R)
            ts.append(t)
        min_error_idx = np.argmin(errors)
        T_best = Ts[min_error_idx]
        R_best = Rs[min_error_idx]
        t_best = ts[min_error_idx]

        return T_best, R_best, t_best

    def best_fit_transform(self, A, B):
        '''
        Calculates the least-squares best-fit transform that maps corresponding points A to B in m spatial dimensions
        Input:
          A: Nxm numpy array of corresponding points
          B: Nxm numpy array of corresponding points
        Returns:
          T: (m+1)x(m+1) homogeneous transformation matrix that maps A on to B
          R: mxm rotation matrix
          t: mx1 translation vector
        '''
        if A.shape != B.shape:
            print('foo')

        assert A.shape == B.shape

        # get number of dimensions
        m = A.shape[1]

        # translate points to their centroids
        centroid_A = np.mean(A, axis=0)
        centroid_B = np.mean(B, axis=0)
        AA = A - centroid_A
        BB = B - centroid_B

        # rotation matrix
        H = np.dot(AA.T, BB)
        U, S, Vt = np.linalg.svd(H)
        R = np.dot(Vt.T, U.T)

        # special reflection case
        if np.linalg.det(R) < 0:
            Vt[m - 1, :] *= -1
            R = np.dot(Vt.T, U.T)

        # translation
        t = centroid_B.T - np.dot(R, centroid_A.T)

        # homogeneous transformation
        T = np.identity(m + 1)
        T[:m, :m] = R
        T[:m, m] = t

        return T, R, t

    def get_transformation_loss(self, A, B, transform):
        m = A.shape[1]
        # make points homogeneous, copy them to maintain the originals
        src = np.ones((m + 1, A.shape[0]))
        dst = np.ones((m + 1, B.shape[0]))
        src[:m, :] = np.copy(A.T)
        dst[:m, :] = np.copy(B.T)

        src = np.dot(transform, src)

        # error
        distances = np.linalg.norm((src - dst), axis=0)
        mean_error = np.mean(distances)

        return mean_error

if __name__ == '__main__':
    args = argparser.parse_args(['-kp', 'tools/pose_estimation/known_markers.csv', '-op', 'tools/pose_estimation/observed_markers.csv'])
    _main_(args)


from PyQt6.QtWidgets import QApplication, QLabel, QWidget

app = QApplication([])

window = QWidget()
window.setWindowTitle("PyQt App")
window.resize(300, 100)
msg = QLabel("
Hello, World!
", parent=window)

window.show()
app.exec()


from itertools import permutations

numbers = "011"

def isprime(n):
    if(n == 0):
        return False
    elif(n == 1):
        return False
    else:
        for i in range(2, n):
            if(n % i == 0):
                return False
                break
    return True

def solution(numbers):
    answer = 0
    temp = []

    for l in range(1, len(numbers)+1):
        pm = list(permutations(numbers, l))
        for el in pm:
            temp.append(int("".join(el)))

    temp = list(set(temp))
    for i in range(len(temp)):
        if(isprime(temp[i])):
            answer += 1

    return answer

solution(numbers)


import cv2
import numpy as np

img = cv2.imread('images/sooji7.jpg')
imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

#threshold를 이용하여 binary image로 변환
ret, thresh = cv2.threshold(imgray,127,255,cv2.THRESH_BINARY)

#contours는 point의 list형태. 예제에서는 사각형이 하나의 contours line을 구성하기 때문에 len(contours) = 1. 값은 사각형의 꼭지점 좌표.
#hierachy는 contours line의 계층 구조
contours, hierachy = cv2.findContours(thresh, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

cv2.imshow('image', img)
cv2.waitKey(0)

image = cv2.drawContours(img, contours, -1, (0,255,0), 2)

cv2.imshow('image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()


import sys

opcode = {
    "mov rax": ("b8",5),
    "mov rdx": ("ba",5),
    "mov rdi": ("bf",5),
    "mov rsi": ("48be",10),
    "mov BYTE": ("c60425",8),

    "cmp BYTE": ("803c25", 2),

    "je": ("74",2),
    "jmp": ("eb",2),

    "call": ("e8",5),
    "syscall": ("0f05",2)
    }

def get_variable(line : str, variables : dict):
    """
    This function gets a variable

    Parameters
    ----------
    line : str
        The line to be checked

    constants : dict
        A dict containing all variables
    """

    var, val = line.split("db")
    variables[var] = val

def get_constant(line : str, constants : dict):
    """
    This function gets a constant

    Parameters
    ----------
    line : str
        The line to be checked

    constants : dict
        A dict containing all constants
    """
    const, value = line.split("equ")
    constants[const] = value

def main():
    """
    This function handles main loop
    """
    file = open("../Trabalho_1/portao.asm", "r")
    txt = file.readlines()
    file.close()

    tokens = dict()

    ILC = 0
    for i, line in enumerate(txt):
        line = line.strip()
        if line:
            for opc in opcode.keys():
                if opc in line:
                    tokens[opc] = tokens[opc] + [ILC] if opc in tokens else [ILC]
                    ILC += opcode[opc][1]

    print(ILC)
    print(f"Tokens: {tokens}\n")

if __name__ == "__main__":
    main()


import os
import time
from ..main_computer.computerInfo import computerInfo
COD4_PATH_ROOT = r"H:\cod4\COD4R\COD4"
# COD4_PATH_SERVERCFG = r"main\server.cfg"
COD4_FILE_SERVERBAT = "server.bat"
COD4_EXE = "h1-mod.exe"

class cod4(computerInfo):
    def __init__(self) -> None:
        pass
    def Check_Server(self):
        if self.getPidByName(COD4_EXE):
            return True,"h1-mod.exe已存在"
        return False,"未找到h1-mod.exe进程"

    def Start_Server(self):
        msg= ""
        server_msg = "connect 192.168.0.103:27020;password 1234"
        StartServer = os.path.join(COD4_PATH_ROOT,COD4_FILE_SERVERBAT)
        os.chdir(COD4_PATH_ROOT)
        os.system(StartServer)
        time.sleep(10)
        status,_ = self.Check_Server()
        if status:
            msg = "服务器已开启!!!\n服务器连接信息{}".format(server_msg)
        else:
            msg = "开启服务器失败,或者h1-mod.exe已经开启"
        return status,msg

    def Kill_Server(self):
        msg = ""
        status = self.killProcess(COD4_EXE)
        if status:
            msg = "服务器已关闭"
        else:
            msg = "服务器未正常关闭或者h1-mod.exe已不存在"
        return status,msg

    def Restart_Server(self):
        if self.Check_Server():
            self.killProcess(COD4_EXE)
        status,msg = self.Start_Server()
        return status,msg

    def returnFun(self):
        return dict({"start":"Start_Server",
        "close":"Kill_Server",
        "restart":"Restart_Server",
        "check":"Check_Server"})

    def test(self):
        print("ttttttttttttttttt")


from django.shortcuts import get_object_or_404
from ninja import Router
from ninja.orm import create_schema
from typing import List
from apiv1.models import Company, Category, Product

product_router = Router(tags=['product'])

ProductIn = create_schema(Product, exclude=['id'])
ProductOut = create_schema(Product)

@product_router.post('')
def create_product(request, payload: ProductIn):
    print(payload.dict())
    test = payload.dict()
    test['company'] = get_object_or_404(Company, id=test['company'])
    test['category'] = get_object_or_404(Category, id=test['category'])
    product = Product.objects.create(**test)
    return {'id': product.id}

@product_router.get('/{id}', response=ProductOut)
def get_product(request, id: int):
    product = get_object_or_404(Product, id=id, is_active=True)
    return product

@product_router.get('', response=List[ProductOut])
def list_products(request):
    if request.user.groups.filter(name='SuperAdmin').exists():
        qs = Product.objects.all()
        return qs
    else:
        qs = Product.objects.filter(is_active=True)
        return qs

@product_router.put('/{id}')
def update_product(request, id: int, payload: ProductIn):
    product = get_object_or_404(Product, id=id)
    test = payload.dict()
    test['company'] = get_object_or_404(Company, id=test['company'])
    test['category'] = get_object_or_404(Category, id=test['category'])
    for attr, value in test.items():
        setattr(product, attr, value)
    product.save()
    return {"success": True}

@product_router.delete('/{id}')
def delete_product(request, id: int):
    product = get_object_or_404(Product, id=id)
    product.delete()
    return {"success": True}


from discord.ext import commands
from random import randint
from textblob import TextBlob

class user_message(commands.Cog):
    phrases = {}
    def __init__(self, bot):
        self.bot = bot

        file = open("texts/greet.txt")
        self.phrases["greet"] = file.read().splitlines()
        file.close()

        file = open("texts/negative.txt")
        self.phrases["negative"] = file.read().splitlines()
        file.close()

        file = open("texts/positive.txt")
        self.phrases["positive"] = file.read().splitlines()
        file.close()

    def check_valid_message(self, message):
        return message.author != self.bot.user and str(message.channel.type) != "private"

    async def is_command(self, message):
        return str(message.channel.type) == "private"

    async def print_negative_message(self, message):
        negatives = self.phrases["negative"]
        await message.channel.send(negatives[randint(0, len(negatives) - 1)])

    async def print_positive_message(self, message):
        positives = self.phrases["positive"]
        await message.channel.send(positives[randint(0, len(positives) - 1)])

    async def handle_message(self, message):
        if "seraphine" in message.content.lower() and TextBlob(message.content).sentiment.polarity >= 0 and not message.content.startswith("$"):
            await self.print_positive_message(message)
        elif "seraphine" in message.content.lower() and not message.content.startswith("$"):
            await self.print_negative_message(message)

    @commands.Cog.listener()
    async def on_message(self, message):
        if not self.check_valid_message(message):
            return
        await self.handle_message(message)
def setup(bot):
    bot.add_cog(user_message(bot))


import random

wordMin = 1e1
wordMax = 1e3
taskNum = 3

with open(f"Input/task{taskNum:02}.txt","w") as f:
    ansList = []
    for i in range(5):
        ansType  = random.randrange(1,1e15)
        wordList = []
        if ansType % 2 == 0 :
            # Yes
            print("YES")
            ansList.append("YES")
            for _ in range(random.randrange(int(wordMin/2),int(wordMax/2))):
                w = chr(random.randrange(65,91))
                wordList.append(w)
                f.write(f"{w}")
                #print(w,end="")
            for w in list(reversed(wordList)):
                f.write(f"{w}")
                #print(w,end="")
        else:
            # No
            print("NO")
            ansList.append("NO")
            for _ in range(random.randrange(int(wordMin),int(wordMax))):
                #print(chr(random.randrange(65,91)),end="")
                f.write(f"{chr(random.randrange(65,91))}")
        f.write("\n")

    f.close()
    with open(f"Output_Python/task{taskNum:02}.txt","w") as f2:
        for ans in ansList:
            f2.write(f"{ans}\n")
    f2.close()


import random
new_file = open("0.1noise.txt","w+")
with open("list_patition_label.txt","r") as file:
	for line in file:
		line = line.strip()
		img_path, label = line.split(' ', 1)
		number = random.uniform(0,1)
		new_label = random.randint(1,7)
		if img_path.startswith("test"):
			new_file.write(img_path + ' ' + str(label) +'\n')
			continue
		if number <= 0.1:
			while(1):
				new_label = random.randint(1,7)
				if new_label != int(label):
					new_file.write(img_path + ' ' + str(new_label) +'\n')
					break
		else:
			new_file.write(img_path + ' ' + str(label) +'\n')


import re

def split_words(s):
    """
    Splits a string into words based on PascalCase, camelCase, snake_case, kebab-case, and numbers attached to strings.

    Args:
        s (str): The string to be split.

    Returns:
        list: The list of words obtained after splitting the string.
    """
    # Split PascalCase or camelCase
    s = re.sub(r"([A-Z][a-z]+)", r" \1", re.sub(r"([A-Z]+)", r" \1", s)).strip()
    # Split snake_case or kebab-case
    s = re.sub(r"[_-]", " ", s)
    # Split numbers attached to strings
    s = re.sub(r"([a-zA-Z])(\d)", r"\1 \2", s)
    s = re.sub(r"(\d)([a-zA-Z])", r"\1 \2", s)
    # Split the string into words based on spaces
    words = s.split()
    return words

def is_camel_case(s):
    """
    Checks if a string is in camelCase.

    Args:
        s (str): The string to be checked.

    Returns:
        bool: True if the string is in camelCase, False otherwise.
    """
    return re.match(r"^[A-Z]+([a-z0-9]*[A-Z]*[a-z0-9]*)*$", s) is not None

def is_snake_case(s):
    """
    Checks if a string is in snake_case.

    Args:
        s (str): The string to be checked.

    Returns:
        bool: True if the string is in snake_case, False otherwise.
    """
    return re.match(r"^[a-z0-9]+(_[a-z0-9]+)*$", s) is not None

def camel_to_snake_case(s):
    """
    Converts a string from camelCase to snake_case.

    Args:
        s (str): The string to be converted.

    Returns:
        str: The string converted to snake_case.
    """
    # Add an underscore before every uppercase letter that is followed by a lowercase letter or digit and not preceded by an underscore, a hyphen or an uppercase letter
    s = re.sub(r"(?<=[^A-Z_-])([A-Z])", r"_\1", s)

    # Ensure there's an underscore before any uppercase letter that's followed by a lowercase letter or digit and comes after a sequence of uppercase letters
    s = re.sub(r"([A-Z]+)([A-Z][a-z0-9])", r"\1_\2", s)

    s = s.lower()
    return s

import shutil

def print_dict(d, indent=0, indent_delta=4, max_chars=None):
    """
    Prints a dictionary in a formatted manner, taking into account the terminal width.

    Args:
        d (dict): The dictionary to be printed.
        indent (int, optional): The current level of indentation. Defaults to 0.
        indent_delta (int, optional): The amount of spaces to add for each level of indentation. Defaults to 4.
        max_chars (int, optional): The maximum number of characters for each line. Defaults to terminal width - 10.
    """
    max_chars = max_chars or shutil.get_terminal_size()[0] - 10  # Get terminal size if max_chars not set
    indent_str = " " * indent
    indent_delta_str = " " * indent_delta

    for key, value in d.items():
        if isinstance(value, dict):
            print(f"{indent_str}{key}:")
            print_dict(value, indent=indent + indent_delta, max_chars=max_chars)
        else:
            # Value is not a dict, print as a string
            str_value = str(value)

            line_width = max_chars - indent
            # Split value by newline characters and handle each line separately
            lines = str_value.split("\n")
            print(f"{indent_str}{key}:")
            for line in lines:
                if len(line) + len(indent_str) + indent_delta > line_width:
                    # Split long lines into multiple lines
                    print(f"{indent_str}{indent_delta_str}{line[:line_width]}")
                    for i in range(line_width, len(line), line_width):
                        print(f"{indent_str}{indent_delta_str}{line[i:i+line_width]}")
                else:
                    print(f"{indent_str}{indent_delta_str}{line}")
                key = ""  # Empty the key for lines after the first one

def nested_tuple_to_string(nested_tuple: tuple) -> str:
    """
    Converts a nested tuple to a string, with elements separated by underscores.

    Args:
        nested_tuple (tuple): The nested tuple to be converted.

    Returns:
        str: The string representation of the nested tuple.
    """
    result = []
    for item in nested_tuple:
        if isinstance(item, tuple):
            result.append(nested_tuple_to_string(item))
        else:
            result.append(str(item))
    return "_".join(result)


class Node:
    def __init__(self, data) -> None:
        self.left = None
        self.right = None
        self.data = data

    def insert(self, data):
        if self.data:
            if data < self.data:
                if self.left is None:
                    self.left = Node(data)
                else:
                    self.left.insert(data)
            elif data > self.data:
                if self.right is None:
                    self.right = Node(data)
                else:
                    self.right.insert(data)
            else:
                self.data = data

    def find(self, value):
        if value < self.data:
            if self.left is None:
                return str(value) + " not found"
            return self.left.find(value)
        elif value > self.data:
            if self.right is None:
                return str(value) + " not found"
            return self.right.find(value)
        else:
            return str(self.data) + " is found"

    def print_tree(self):
        if self.left:
            self.left.print_tree()
        print(self.data),
        if self.right:
            self.right.print_tree()

root = Node(12)
root.insert(6)
root.insert(14)
root.insert(3)
print(root.find(7))
print(root.find(14))


#!/usr/bin/env python
import click
import os
import numpy as np
import matplotlib.pyplot as plt
from deepdiva.utils.visualisation_utils import *

@click.command()
@click.option('--data-path', 'data_path', default="./data/dataset", required=False,
              type=click.Path(exists=True), show_default=True, help='Path to data folder')
@click.option('--show-audio/--no-show-audio', 'show_audio', default=False,
              show_default=True, help='Whether to visualize the audio')
@click.option('--audio-file', 'audio_file', default="audio.npy",
              required=False, type=str, show_default=True, help='File name for audio dataset (.npy)')
@click.option('--show-spectrogram/--no-show-spectrogram', 'show_spectrogram', default=False,
              show_default=True, help='Whether to visualize the mel spectrogram')
@click.option('--spectrogram-file', 'spectrogram_file', default="melspectrogram.npy",
              required=False, type=str, show_default=True, help='File name for mel spectrogram dataset (.npy)')

def click_main(data_path, audio_file, spectrogram_file, show_spectrogram, show_audio):
    """
    Interface for Click CLI.
    """

    main(data_path=data_path, audio_file=audio_file, spectrogram_file=spectrogram_file,
         show_spectrogram=show_spectrogram, show_audio=show_audio)

def main(data_path, audio_file, spectrogram_file, show_spectrogram, show_audio):
    """Runs data visualisation scripts to inspect data"""

    if not show_audio and not show_spectrogram:
        print("Please select at least one type of plot: audio or mel spectrogram")

    if show_audio:
        # Load data file
        audio = np.load(os.path.join(data_path, audio_file))
        print(f"The shape of the audio file: {audio.shape}")

        # Plot 6 audio files
        fig1 = plt.figure(num="Audio signal", figsize=(12, 6))

        for sp in range(6):
            plt.subplot(2, 3, sp+1)
            sample = np.random.choice(audio.shape[0])
            plot_audio(audio[sample])
            plt.title(f"sample: {sample}")

        plt.show()
        plt.close()

    if show_spectrogram:
        # Load data file
        spectrogram = np.load(os.path.join(data_path, spectrogram_file))
        print(f"The shape of the mel spectrogram file: {spectrogram.shape}")

        # Plot 6 mel spectrograms
        fig2 = plt.figure(num="Mel spectrogram", figsize=(12, 6))

        for sp in range(6):
            plt.subplot(2, 3, sp+1)
            sample = np.random.choice(spectrogram.shape[0])
            plot_mel(spectrogram[sample])
            plt.title(f"sample: {sample}")

        plt.show()
        plt.close()

if __name__ == '__main__':

    click_main()


# Size of a tree is the number of elements present in the tree. Size of the below tree is 5.
#
# Size() function recursively calculates the size of a tree. It works as follows:
#
# Size of a tree = Size of left subtree + 1 + Size of right subtree.

class Node:
    def __init__(self,value):
        self.value = value
        self.left = None
        self.right = None

def treeSize(root):
    if root is None:
        return 0
    else:
        size = treeSize(root.left) + 1 + treeSize(root.left)
        return size

tree = Node(1)
tree.left = Node(2)
tree.right = Node(3)
tree.left.left = Node(4)
tree.left.right = Node(5)
tree.right.left = Node(6)
tree.right.right = Node(7)

print(treeSize(tree))


import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0.5,3.5,300)  # 在0.5到3.5之间均匀地取300个数
y = np.sin(x)
z = np.cos(x)

# fig, ax = plt.subplots(figsize=(14,7))  不设置子图
fig, ax = plt.subplots(1,2,figsize=(14,7))
ax[0].plot(x,y)
ax[1].plot(x,z)

ax[0].set_title('sin(x)', fontsize=18)
ax[1].set_title('cos(x)', fontsize=18)

ax[0].set_xlabel('x', fontsize=18, fontfamily = 'sans-serif', fontstyle='italic')
ax[1].set_xlabel('x', fontsize=18, fontfamily = 'sans-serif', fontstyle='italic')

ax[0].set_ylabel('y', fontsize='x-large',fontstyle='oblique')
ax[1].set_ylabel('y', fontsize='x-large',fontstyle='oblique')

ax[0].set_xlim(0,16)
ax[0].grid(axis='both')

ax[1].xaxis.set_tick_params(rotation=45, labelsize=12)
start, end = ax[1].get_xlim()
ax[1].xaxis.set_ticks(np.arange(start, end, 1))  # np.arange(start, end, step)
ax[1].yaxis.tick_right()

plt.savefig('figure.png', dpi=800)
plt.show()


# Описание проекта:
#     программа запрашивает имя пользователя и
#     генерирует случайное число в диапазоне который ввел пользователь от 1 до ...
#     и просит пользователя угадать это число.
#     Если догадка пользователя больше случайного числа,
#      то программа должна вывести сообщение 'Слишком много, попробуйте еще раз'.
#     Если догадка меньше случайного числа,
#      то программа должна вывести сообщение 'Слишком мало, попробуйте еще раз'.
#     Если пользователь угадывает число,
#      то программа должна поздравить его и вывести сообщение 'Вы угадали, поздравляем!'
#      и предлогает поиграть ещё.
from random import randint

def is_valid(number):
    return True if number.isdigit() and int(number) in range(1, num_r + 1) else False

print("Игра - 'Угадайка число!'")
name = input('Пожалуйста введите ваше имя: ')
num = 0
num_r = 0
count = 0
flag = True
yes_no = ''

while True:
    if yes_no == 'нет':
        break
    if count == 0 and flag:
        num_r = input("До какого числа загадываю? от 1 до ... : ")
        if num_r.isdigit() and int(num_r) > 1:
            num_r = int(num_r)
            flag = False
        else:
            print('Не корректный диапазон!')
            continue
        num = randint(1, num_r)

    user_num = input(f'{name} введите целое число от 1 до {num_r}: ')
    if not is_valid(user_num):
        print(f'А может быть все-таки введем целое число от 1 до {num_r}?')
        continue
    user_num = int(user_num)

    if user_num < num:
        count += 1
        print('Ваше число меньше загаданного, попробуйте еще разок')
        print(f'Колличество попыток {count}')
    elif user_num > num:
        count += 1
        print('Ваше число больше загаданного, попробуйте еще разок')
        print(f'Колличество попыток {count}')
    else:
        count += 1
        print('Вы угадали, поздравляем!')
        print(f'Колличество попыток {count}')
        while True:
            yes_no = input(f"{name} сыгрем ещё? Напишите 'Да' или 'Нет': ").lower()
            if yes_no != 'да' and yes_no != 'нет':
                print('А может быть все-таки введем Да или Нет ?')
                continue
            elif yes_no == 'да':
                count = 0
                flag = True
                break
            elif yes_no == 'нет':
                print(f'{name} Спасибо, что играли в числовую угадайку. Еще увидимся...')
                break


import ConfigParser
import logging
import logging.config
import time

import sqlite3

class HumidifierDAO():

    CONFIG_SECTION = 'HumidifierDAO_Options'

    def __init__(self, config):
        self.logger = logging.getLogger('HumidifierDao')
        self.db_file = config.get(HumidifierDAO.CONFIG_SECTION, 'db_fullpath')

    def insert_humid_mode(self, mode):
        ''' Insert new humidifier mode into database.
            The time of the insertion will be used as the [created] field.
        '''

        insert = ''' insert into humidifier(created, mode)
                     values(datetime('now', 'localtime'), ?); '''

        try:
            conn = self.get_connection()
            with conn:
                cur = conn.cursor()
                cur.execute(insert, (mode,))
                return cur.lastrowid

        except Exception as e:
            self.logger.error(e)

        finally:
            conn.close()

    def select_range(self, begin, end):
        ''' Return readings from provided time range.
            begin: datetime string of format %Y-%m-%d %H:%M(:%S)
            end  : datetime string of format %Y-%m-%d %H:%M(:%S)
        '''

        sql = """ select created, mode
                  from humidifier
                  where created > ?
                      and created < ?; """

        self.logger.debug(sql.replace('?', '{}').format(begin, end))

        try:
            conn = self.get_connection()
            with conn:
                cur = conn.cursor()
                cur.execute(sql, (begin, end))
                data = cur.fetchall()
                return data

        except Exception as e:
            self.logger.error(e)

        finally:
            conn.close()

    def get_connection(self):
        return sqlite3.connect(self.db_file)


'''
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation
Fn = Fn-1 + Fn-2

'''

def fib(x):
    if x==1:
        return 0
    elif x==2:
        return 1
    else:
        return fib(x-1)+fib(x-2)

print("Fibonacci sum = ",fib(10))


import os
import numpy as np
import tensorflow as tf
from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping, CSVLogger, ReduceLROnPlateau
from tensorflow.keras.optimizers import Adam, Nadam

##THIS IS IMPORTANT!
tf.compat.v1.disable_eager_execution()

def training(model, train_gen, valid_gen, lr, epochs, save_path, log_path):
    optimizer = Nadam(lr=lr)
    sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(log_device_placement=True))
    model.compile(optimizer=optimizer,
                  loss= 'categorical_crossentropy',
                  metrics= ["accuracy"])

    callbacks = [
        ModelCheckpoint(
                        filepath = save_path,
                        save_weights_only = False,
                        save_best_only = True,
                        monitor='val_loss',
                        mode = "min"),

        EarlyStopping(monitor = "val_loss",
                      patience = 30,
                      mode = "min"),

        CSVLogger(log_path,
                  separator = ",",
                  append = False),

        ReduceLROnPlateau(monitor='val_loss',
                          factor=0.5,
                          patience= 10,
                          mode = "min")
        ]

    #print("curdir:", os.path.abspath(os.curdir))
    #print("save_path:", save_path)

    history = model.fit(
        x = train_gen,
        epochs = epochs,
        callbacks = callbacks,
        validation_data = valid_gen,
        use_multiprocessing = True,
        workers = 8
    )

    return history


"""fortebot URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from bot import views
from bot import jobs
import os

urlpatterns = [
    url(r'^auth', views.auth),
    url(r'^slack/', views.sent_message),
    url(r'^temperature_vote', views.temperature_vote),
    url(r'^forte_vote', views.rating_vote),
    url(r'^anonymous_feedback/', views.anonymous_feedback),
    url(r'^anon_random/', views.anon_random),
    url(r'^forte_help/', views.help),
    url(r'^get_results', views.get_results),
    url(r'^question_vote', views.start_question_vote),
    url(r'^delivery', views.delivery),
    url(r'^send_msg', views.send_msg),
    url(r'^click', views.click),
    url(r'^reply', views.reply),
    url(r'^get_id', views.get_id),
    url(r'^food_job', views.food_job),
    url(r'^post_menu', jobs.get_food_job)
]


import pygame, random, json
pygame.init()

load = input("load? (ak \"\" tak nie) ")
file = input("name of the file: ")
layout = []

num_to_img = []
num_to_name_img = []
size_of_square = 50

def load_from_ts(ts, x, y, w, h):
	rect = pygame.Rect(x*w,y*h,w,h)
	image = pygame.Surface(rect.size, pygame.SRCALPHA)
	image.blit(ts, (0,0), rect)
	return image

if load == "":
	width = int(input("width: "))
	height = int(input("height: "))
	num_of_layers = int(input("number of layers: "))
	tileset_q = input("tileset?(ak \"\" tak ano): ")

	for a in range(num_of_layers):
		layout.append([])
		for b in range(height):
			layout[a].append([])
			for c in range(width):
				layout[a][b].append(0)

else:
	with open(file, "r") as f:
		content = f.readlines()
		size = content[0].split()
		width = int(size[0])
		height = int(size[1])
		num_of_layers = int((len(content) - 1) / (height + 1))

		for a in range(num_of_layers):
			layout.append([])
			for b in range(height):
				layout[a].append([])
				line = content[a * (height + 1) + 2 + b].split()
				for i in line:
					layout[a][b].append(int(i))

	print("If you want to rewrite change or add any image to any layer, do it now")

	with open(file.split(".")[0] + ".json", "r") as f:
		content = json.load(f)
		if("ts" in content):
			tileset_q = ""
			ts = pygame.image.load(content["ts"])
			for i in range(len(content["imgs"])):
				num_to_name_img.append({})
				num_to_img.append({})
				for j in content["imgs"][i]:
					num_to_name_img[i][int(j)] = content["imgs"][i][j]
					num_to_img[i][int(j)] = pygame.transform.scale(load_from_ts(ts, int(content["imgs"][i][j][0]), int(content["imgs"][i][j][1]), content["ts_s"], content["ts_s"]), (size_of_square-1, size_of_square-1))
		else:
			for i in range(len(content)):
				num_to_name_img.append({})
				num_to_img.append({})
				for j in content[i]:
					num_to_name_img[i][int(j)] = content[i][j]
					num_to_img[i][int(j)] = pygame.transform.scale(pygame.image.load(content[i][j]), (size_of_square-1, size_of_square-1))

if tileset_q == "":
	if load=="":
		ts_name = input("tileset file: ")
		t_s = int(input("size of one tile: "))
	else:
		ts_name = content["ts"]
		t_s = content["ts_s"]
	ts = pygame.image.load(ts_name)
	for i in range(num_of_layers):
		print(f"Add image with the number with form <num> <x> <y> for layer {i + 1}, if you are done press ENTER")
		if load == "":
			num_to_img.append({})
			num_to_name_img.append({})
		while True:
			inp = input()
			if inp == "":
				break
			else:
				splitted_inp = inp.split()
				num_to_img[i][int(splitted_inp[0])] = pygame.transform.scale(load_from_ts(ts, int(splitted_inp[1]), int(splitted_inp[2]), t_s, t_s), (size_of_square, size_of_square))
				num_to_name_img[i][int(splitted_inp[0])] = [splitted_inp[1], splitted_inp[2]]
else:
	print(f"Add image with the number with form <num> <image.img> for layer {i + 1}, if you are done press ENTER")
	if load == "":
		num_to_img.append({})
		num_to_name_img.append({})
	while True:
		inp = input()
		if inp == "":
			break
		else:
			splitted_inp = inp.split()
			num_to_img[i][int(splitted_inp[0])] = pygame.transform.scale(pygame.image.load(splitted_inp[1]), (size_of_square, size_of_square))
			num_to_name_img[i][int(splitted_inp[0])] = splitted_inp[1]

win = pygame.display.set_mode((width * size_of_square + 400, height * size_of_square))

current_layer = None

selected_img = []
for i in range(num_of_layers):
	selected_img.append(0)

def save():
	with open(file, "w") as f:
		f.write(f"{width} {height}")

		for i in range(len(layout)):
			f.write("\n")
			for j in range(len(layout[i])):
				f.write("\n")
				for k in range(len(layout[i][j])):
					f.write(f"{layout[i][j][k]} ")
	json_file = file.split(".")

	with open(f"{json_file[0]}.json", "w") as f:
		if tileset_q=="":
			data = {
				"ts":ts_name,
				"ts_s":t_s,
				"imgs":num_to_name_img
			}
			json.dump(data, f)
		else:
			json.dump(num_to_name_img, f)

def draw_window(mouse, click, keys):
	global current_layer, selected_img, layout
	win.fill((245, 64, 236))

	for y in range(height):
		for x in range(width):
			pygame.draw.rect(win, (10, 10, 10), pygame.Rect(100+x*size_of_square, y*size_of_square, size_of_square-1, size_of_square-1))

	for i in range(num_of_layers):
		pygame.draw.rect(win, (128, 128, 128), pygame.Rect(0, i * height*size_of_square/num_of_layers, 100, height*size_of_square/num_of_layers - 1))
		if pygame.Rect.colliderect(mouse, pygame.Rect(0, i * height*size_of_square/num_of_layers, 100, height*size_of_square/num_of_layers - 1)) and click:
			current_layer = i

	pygame.draw.rect(win, (100, 255, 100), pygame.Rect(100+width*size_of_square - size_of_square*2 + 300, height*size_of_square - size_of_square*2, size_of_square*2, size_of_square*2))

	if pygame.Rect.colliderect(mouse, pygame.Rect(100+width*size_of_square - size_of_square*2 + 300, height*size_of_square - size_of_square*2, size_of_square*2, size_of_square*2)) and click:
		save()

	if current_layer != None:
		pygame.draw.rect(win, (255, 100, 100), pygame.Rect(100+width*size_of_square - size_of_square + 300, height*size_of_square - size_of_square*3 - 1, size_of_square, size_of_square))
		if pygame.Rect.colliderect(mouse, pygame.Rect(100+width*size_of_square - size_of_square + 300, height*size_of_square - size_of_square*3 - 1, size_of_square, size_of_square)) and click:
			for y in range(len(layout[current_layer])):
				for x in range(len(layout[current_layer][y])):
					layout[current_layer][y][x] = 0

		for x, i in enumerate(num_to_img[current_layer]):
			win.blit(num_to_img[current_layer][i], (width*size_of_square + 300 - size_of_square * (2 - x // height + 1), (x % height) * size_of_square))
			if pygame.Rect.colliderect(mouse, pygame.Rect(width*size_of_square + 300 - size_of_square * (2 - x // height + 1), (x % height) * size_of_square, size_of_square, size_of_square)) and click:
				selected_img[current_layer] = i

		for y in range(len(layout[current_layer])):
			for x in range(len(layout[current_layer][y])):
				if pygame.Rect.colliderect(mouse, pygame.Rect(100 + x*size_of_square, y*size_of_square, size_of_square, size_of_square)) and click:
					if selected_img[current_layer] == layout[current_layer][y][x]:
						layout[current_layer][y][x] = 0
					else:
						layout[current_layer][y][x] = selected_img[current_layer]

	for i in range(num_of_layers):
		for y in range(len(layout[i])):
			for x in range(len(layout[i][y])):
				if layout[i][y][x] != 0:
					win.blit(num_to_img[i][layout[i][y][x]], (100 + x*size_of_square, y*size_of_square))

	pygame.display.update()

def main():
	run = True
	clock = pygame.time.Clock()
	while run:
		clock.tick(60)
		click = False
		mx, my = pygame.mouse.get_pos()
		mouse = pygame.Rect(mx, my, 1, 1)
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				run = False
			if event.type == pygame.MOUSEBUTTONDOWN:
				click = True
		keys = pygame.key.get_pressed()
		draw_window(mouse, click, keys)
	pygame.quit()
if __name__ == "__main__":
	main()


import string

def load_words(file_name):
    '''
    file_name (string): the name of the file containing
    the list of words to load

    Returns: a list of valid words. Words are strings of lowercase letters.

    Depending on the size of the word list, this function may
    take a while to finish.
    '''
    # inFile: file
    inFile = open(file_name, 'r')
    # wordlist: list of strings
    wordlist = []
    for line in inFile:
        wordlist.extend([word.lower() for word in line.split(' ')])
    return wordlist

def is_word(word_list, word):
    '''
    Determines if word is a valid word, ignoring
    capitalization and punctuation

    word_list (list): list of words in the dictionary.
    word (string): a possible word.

    Returns: True if word is in word_list, False otherwise

    Example:
    >>> is_word(word_list, 'bat') returns
    True
    >>> is_word(word_list, 'asdf') returns
    False
    '''
    word = word.lower()
    word = word.strip(" !@#$%^&*()-_+={}[]|\:;'<>?,./\"")
    return word in word_list

def get_story_string():
    """
    Returns: a story in encrypted text.
    """
    f = open("story.txt", "r")
    story = str(f.read())
    f.close()
    return story

WORDLIST_FILENAME = 'words.txt'

# The code above this line had been provided by MIT

class Message(object):
    def __init__(self, text):
        '''
        Initializes a Message object

        text (string): the message's text

        a Message object has two attributes:
            self.message_text (string, determined by input text)
            self.valid_words (list, determined using helper function load_words)
        '''
        self.message_text = text
        self.valid_words = load_words(WORDLIST_FILENAME)

    def get_message_text(self):
        '''
        Used to safely access self.message_text outside of the class
        Returns: self.message_text
        '''
        return self.message_text

    def get_valid_words(self):
        '''
        Used to safely access a copy of self.valid_words outside of the class.
        Returns: a COPY of self.valid_words
        '''
        words = self.valid_words.copy()
        return words

    def build_shift_dict(self, shift):
        '''
        Creates a dictionary that can be used to apply a cipher to a letter.
        The dictionary maps every uppercase and lowercase letter to a
        character shifted down the alphabet by the input shift. The dictionary
        has 52 keys of all the uppercase letters and all the lowercase
        letters.

        shift (integer): the amount by which to shift every letter of the
        alphabet. 0 <= shift < 26

        Returns: a dictionary mapping a letter (string) to
                 another letter (string).
        '''
        alphalower = string.ascii_lowercase
        alphaupper = string.ascii_uppercase
        alphadict = {}
        for alphabet in alphalower:
            newindex = alphalower.find(alphabet) + shift
            correspondingletter = alphalower[newindex % len(alphalower)]
            alphadict[alphabet] = correspondingletter

        for alphabet in alphaupper:
            newindex = alphaupper.find(alphabet) + shift
            correspondingletter = alphaupper[newindex % len(alphaupper)]
            alphadict[alphabet] = correspondingletter

        return alphadict

    def apply_shift(self, shift):
        '''
        Applies the Caesar Cipher to self.message_text with the input shift.
        Creates a new string that is self.message_text shifted down the
        alphabet by some number of characters determined by the input shift

        shift (integer): the shift with which to encrypt the message.
        0 <= shift < 26

        Returns: the message text (string) in which every character is shifted
             down the alphabet by the input shift
        '''
        mappingdict = self.build_shift_dict(shift)
        newstring = ''

        # goes through the message_text's indexes in ascending order
        # if that position of the string is a letter, add the corresponding value associated with that letter in the mappingdict
        for letter in self.message_text:
            if letter in string.ascii_letters:
                newstring += mappingdict[letter]
            else:
                newstring += letter

        return newstring

class PlaintextMessage(Message):
    def __init__(self, text, shift):
        '''
        Initializes a PlaintextMessage object

        text (string): the message's text
        shift (integer): the shift associated with this message

        A PlaintextMessage object inherits from Message and has five attributes:
            self.message_text (string, determined by input text)
            self.valid_words (list, determined using helper function load_words)
            self.shift (integer, determined by input shift)
            self.encryption_dict (dictionary, built using shift)
            self.message_text_encrypted (string, created using shift)

        '''
        self.message_text = text
        self.valid_words = load_words(WORDLIST_FILENAME)
        self.shift = shift
        self.encryption_dict = super().build_shift_dict(shift)
        self.message_text_encrypted = super().apply_shift(shift)

    def get_shift(self):
        '''
        Used to safely access self.shift outside of the class

        Returns: self.shift
        '''
        return self.shift

    def get_encryption_dict(self):
        '''
        Used to safely access a copy self.encryption_dict outside of the class

        Returns: a COPY of self.encryption_dict
        '''
        dict = self.encryption_dict.copy
        return dict

    def get_message_text_encrypted(self):
        '''
        Used to safely access self.message_text_encrypted outside of the class

        Returns: self.message_text_encrypted
        '''
        return self.message_text_encrypted

    def change_shift(self, shift):
        '''
        Changes self.shift of the PlaintextMessage and updates other
        attributes determined by shift.

        shift (integer): the new shift that should be associated with this message.
        0 <= shift < 26

        Returns: nothing
        '''
        self.shift = shift
        self.encryption_dict = super().build_shift_dict(shift)
        self.message_text_encrypted = super().apply_shift(shift)

class CiphertextMessage(Message):
    def __init__(self, text):
        '''
        Initializes a CiphertextMessage object

        text (string): the message's text

        a CiphertextMessage object has two attributes:
            self.message_text (string, determined by input text)
            self.valid_words (list, determined using helper function load_words)
        '''
        self.message_text = text
        self.valid_words = load_words("words.txt")

    def decrypt_message(self):
        '''
        Decrypt self.message_text by trying every possible shift value
        and find the "best" one. We will define "best" as the shift that
        creates the maximum number of real words when we use apply_shift(shift)
        on the message text. If s is the original shift value used to encrypt
        the message, then we would expect 26 - s to be the best shift value
        for decrypting it.

        Note: if multiple shifts are equally good such that they all create
        the maximum number of valid words, we add them to a list and choose the
        shift at position 0

        Returns: a tuple of the best shift value used to decrypt the message
        and the decrypted message text using that shift value
        '''
        wordcount_dict = {}     # stores shift values as keys and the number of valid words generated by applying that shift value to the text as values

        # applies all possible shift values to the message text
        # checks how many valid words are generated by applying those shift values and stores that in wordcount_dict as wordcount_dict[shift value] = words generated
        for i in range(1,26):
            decryptedstring = super().apply_shift(26-i)
            listofwords = decryptedstring.split(' ')
            for word in listofwords:
                if is_word(self.valid_words, word):
                    wordcount_dict[26-i] = wordcount_dict.get(26-i,0) + 1

        # finds the shift value that generates the highest number of words
        highestvalue = 0
        for value in wordcount_dict.values():
            if value > highestvalue:
                highestvalue = value
        bestshiftvalue = [shiftval for shiftval,numofwords in wordcount_dict.items() if numofwords == highestvalue][0]

        decryptedtext = super().apply_shift(bestshiftvalue)

        return (bestshiftvalue, decryptedtext)

if __name__ == '__main__':

   print("Hello, I provide a 2-in-1 encryption and decryption service.")

   while True:
        enc_or_dec = input("Do you want to encrypt a message or decrypt it? Please enter 'e' for encryption and 'd' for decryption: ")
        textinput = input("Please enter your text: ")
        if (enc_or_dec == 'e' or enc_or_dec == 'd') and isinstance(textinput,str):
            break
        else:
            print("Invalid input! Please try again.")
            continue

   if enc_or_dec == 'e':
        shiftvalue = input("How many letters down the alphabet do you want to shift each letter by? For example, enter 2 if you want 'a' to be changed to 'c': ")
        while True:
            try:
               shiftvalue = int(shiftvalue)
               break
            except:
               print("Invalid input! Please try again.")
               continue

        print("You have chosen to encrypt the text '" + textinput + "' with a shift value " + shiftvalue + ".")
        plaintext = PlaintextMessage(textinput,shiftvalue)
        print("Encrypted text:", plaintext.get_message_text_encrypted())

   else:
        print("You have chosen to decrypt the text '" + textinput + "'")
        ciphertext = CiphertextMessage(textinput)
        print("The shift value and the decrypted text is as follows:", ciphertext.decrypt_message())