# vim: ts=4 sw=4 et
# -*- coding: utf-8 -*-

# © 2021 The Board of Trustees of the Leland Stanford Junior University.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

import functools
import logging
import re
from typing import *
import stanford.mais.account

# Set up logging
logger = logging.getLogger(__name__)
debug = logger.debug
info = logger.info

__all__ = (
    'validate',
    'AccountValidationResults',
)

# In __all__, we list `validate` first.  But in the code, we define the results
# class first.  That is so that we can reference the class name directly in
# `validate`.

class AccountValidationResults(NamedTuple):
    """Results of doing an account validation.

    This class contains the results of an account validation, called via
    :func:`validate`.

    .. note::
       Many of these properties are collections.  That means, if you want to
       use things like subscripting, you will want to convert to a
       more-specific type (such as :class:`list` before using it).
    """

    raw: Optional[str]
    """
    The raw input provided for validation.  This is only provided when
    a string was provided to :func:`validate`.
    """

    raw_set: Collection[str]
    """
    The raw input provided for validation.  If a string was provided to
    :func:`validate`, then this is the raw input after being split into a
    collection.  Otherwise, this will be the original list/set/tuple that was
    provided to :func:`validate`, but made into a set.

    The set union of `full`, `base`, `inactive`, and `unknown` is equal to
    this list.
    """

    full: Collection[str]
    """
    The set of active, full (or full-sponsored) SUNetIDs found in `raw_set`.
    """

    base: Collection[str]
    """
    The set of active, base (or base-sponsored) SUNetIDs found in `raw_set`.
    """

    inactive: Collection[str]
    """
    The set of inactive SUNetIDs found in `raw_set`.
    """

    unknown: Collection[str]
    """
    The set of entries from `raw_set` that are not SUNetIDs.
    """

@functools.singledispatch
def validate(
    raw: str,
    client: stanford.mais.account.AccountClient,
) -> AccountValidationResults:
    """Given a list of SUNetIDs; as a string or a list, tuple, or set; validate
    and check status.

    This takes a list of SUNetIDs, and returns a list of SUNetIDs which have
    been checked against the Accounts API for both activity and service level.
    The returned result shows which SUNetIDs are active full (or
    full-sponsored), active base (or base-sponsored), or inactive.

    If the input is a string, then the input string may be separated by commas,
    and/or whitespace, (where "whitespace" is a space, newline/linefeed, form
    feed, carriage return, tab/horizontal tab, or vertical tab character).  If
    the input is a list, tuple, or set; the function assumes that all
    whitespace etc. have been removed.

    .. note::
       "List, tuple, or set" is used instead of the generic "collection"
       because a :class:`str` is also a collection (of other :class:`str`).
       See `typing issue #256 <https://github.com/python/typing/issues/256>`_
       for the discussion around this issue.

    This is designed to catch most exceptions.  Exceptions related to
    validation (for example, attempting to validate an obviously-invalid
    SUNetID like `ab$#`) will result in the 'SUNetID' being added to the
    `unknown` list, instead of throwing an exception.  The only exceptions that
    should be expected from this function are ones related to API issues.

    :param raw: The list of SUNetIDs.  If a `str`, then the list may be comma- and/or whitespace-separated.

    :param client: An :class:`~stanford.mais.account.AccountClient` to connect to the Account API.

    :return: The results of the validation.  See the definition of :class:`~nero_wgcreator.account.validate.AccountValidationResults` for details.  If the input to this function is a string; that string will be in `raw`, and the parsed list will be in `raw_set`.  If the input to this function is not a string, then `raw` will be `None` and `raw_set` will be a copy of the input.

    :raises ChildProcessError: Something went wrong on the server side (a 400 or 500 error was returned).

    :raises PermissionError: You did not use a valid certificate, or do not have permissions to perform the operation.

    :raises requests.Timeout: The MaIS Workgroup API did not respond in time.
    """
    debug('In validate with str')
    debug(f"Validation input: {raw}")

    # Start by spliting on whitespace and comma.
    # NOTE: Repeated instances of whitespace/separators will make empty entries.
    raw_list = re.split(r'\s|,', raw)

    # Filter out all empty entries, and remove duplicates by using the set.
    debug(f"Split list pre-filter has {len(raw_list)} items.")
    raw_list_filtered = set(filter(
        lambda item: len(item)>0,
        raw_list
    ))

    # Validate the list entries.
    debug(f"Post-filter list has {len(raw_list_filtered)} items.")
    result = validate(raw_list_filtered, client)

    # Add in our raw string, and we're done!
    return AccountValidationResults(
        raw=raw,
        raw_set=result.raw_set,
        full=result.full,
        base=result.base,
        inactive=result.inactive,
        unknown=result.unknown,
    )

@validate.register(list)
@validate.register(tuple)
@validate.register(set)
def _(
    raw: Union[List[str], Tuple[str], Set[str]],
    client: stanford.mais.account.AccountClient,
) -> AccountValidationResults:
    """
    (This is a single-dispatch function.  See the documentation above!
    """
    debug('In validate with list/tuple/set')
    debug('Input: ' + ','.join(raw))
    debug(f"Input has {len(raw)} items.")

    # Limit our accounts to only people
    people = client.only_people()

    # If we were not given a set, then convert it into a set.
    if not isinstance(raw, set):
        raw = set(raw)

    # Components of the output
    full = set()
    base = set()
    inactive = set()
    unknown = set()

    for sunetid in raw:
        # Catch unknown entries
        try:
            account = people.get(sunetid)
            debug(f"Account {sunetid} exists.")
        except (ValueError, IndexError, KeyError):
            debug(f"Account {sunetid} not found.")
            unknown.add(sunetid)
            continue

        # Overwrite the input SUNetID with the normalized one.
        sunetid = account.sunetid

        # Next, catch inactives
        if account.is_active is False:
            debug(f"Account {sunetid} NOT active.")
            inactive.add(sunetid)
            continue

        # Finally, sort into full or base
        if account.is_full:
            debug(f"Account {sunetid} is FULL")
            full.add(sunetid)
        else:
            debug(f"Account {sunetid} is base")
            base.add(sunetid)

    # Return the structure
    debug(f"Validation results: full={len(full)} base={len(base)} inactive={len(inactive)} unknown={len(unknown)}")
    return AccountValidationResults(
        raw=None,
        raw_set=raw,
        full=full,
        base=base,
        inactive=inactive,
        unknown=unknown,
    )


stri = input().split()

def sor(arr):
    n = len(arr)

    for i in range(n - 1):
        for j in range(0, n - i - 1):

            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
    return arr

def cou(inp1, s):
    c = 0
    for k in inp1:
        if s == k:
            c = c + 1
    return c

def freq(inp1):
    str2 = []
    inp1 = sor(inp1)
    pos = 0
    for k in inp1:

        if k not in str2:
            str2.append(k)
    max1 = 0
    for k in range(0, len(str2)):
        if max1 < cou(inp1, str2[k]):
            max1 = cou(inp1, str2[k])
            pos = k
    print(str2[pos])

freq(stri)


my_dictionary = {}
all_tracks = []
class Track:
    def __init__(self):
        self.name = 0
        self.eta = 0
        self.phi = 0
        # self.z0 = 0
        # self.d0 = 0
        # self.pT = 0
for i in range(1,100):
    track = Track()
    track.eta = i
    track.phi = i*i
    track.name = 'track {}'.format(i)
    my_dictionary[track.name] = [track.eta, track.phi]

matches = []
failures = []

match = False
def match(a,b):
    if my_dictionary['track {}'.format(a)] == my_dictionary['track {}'.format(b)]:
        #print('match')
        match = True
        matches.append(1)
    else:
        #print('this isnt the same thing')
        match = False
        failures.append(1)
    #if match == True:
        #print('it was true')
    return match

total_matches = 0
total_failed = 0
for i in range(1,10):
    for j in range(1,100):
        if match(i,j):
        #print('it was  a match')
            total_matches = total_matches + 1
        else:
        #print('nah m8')
            total_failed = total_failed + 1
print('failed',total_failed,'matched',total_matches)


from datetime import date
from pathlib import Path
import re
import sys
from typing import Tuple

from invoke import task

TOP_DIR = Path(__file__).parent.resolve()

def update_file(filename: str, sub_line: Tuple[str, str], strip: str = None):
    """Utility function for tasks to read, update, and write files"""
    with open(filename, "r") as handle:
        lines = [
            re.sub(sub_line[0], sub_line[1], line.rstrip(strip)) for line in handle
        ]

    with open(filename, "w") as handle:
        handle.write("\n".join(lines))
        handle.write("\n")

@task
def update_version(_, version=""):
    """Update package version to today's date using CalVer"""
    if version:
        if re.match(r"20[2-9][0-9]\.1?[0-9]\.[1-3]?[0-9].*", version) is None:
            sys.exit(
                f"Error: Passed version ({version}) does to match a date in the format "
                "YYYY.(M)M.(D)D."
            )
    else:
        # Use today's date
        today = date.today()
        version = f"{today.year}.{today.month}.{today.day}"

    update_file(
        TOP_DIR.joinpath("tools_optimade_client/__init__.py"),
        (r"__version__ = .+", f'__version__ = "{version}"'),
    )
    update_file(
        TOP_DIR.joinpath("setup.py"), (r"version=([^,]+),", f'version="{version}",')
    )

    print(f"Bumped version to {version} !")


import numpy as np
from typing import List, Tuple

class Zncc:
    """ZNCC based decoder

    ZNCC(Zero-mean Normalized Cross Correlation) based decoder can decode *arbitrary* structured light.

    Mirdehghan et al. show that the ZNCC-based decoder has
    almost the same performance as the native decoder [1] (see Figure 5).

    References
    ----------
    .. [1] Mirdehghan et al., "Optimal structured light a la carte." CVPR 2018.
    """

    def decode(self, imlist_code: List[np.ndarray], imlist_observe: List[np.ndarray]) -> Tuple[np.ndarray, np.ndarray]:
        """
        Parameters
        ----------
        imlist_code : List[np.ndarray]
          The projected patterns
        imlist_observe : List[np.ndarray]
          The images captured by the camera

        Returns
        -------
        img_index_x : np.ndarray
          index x-axis
        img_index_y : np.ndarray
          index y-axis
        """
        num = len(imlist_code)
        code = np.reshape(imlist_code, (num, -1))
        observe = np.reshape(imlist_observe, (num, -1))

        # Calculate ZNCC
        zncc = self.calculate_zncc(code, observe)

        # Get argmax
        ids = np.argmax(zncc, axis=0)

        index_y, index_x = np.unravel_index(ids, imlist_code[0].shape)

        dsize_observe = imlist_observe[0].shape
        img_index_y = np.reshape(index_y, dsize_observe)
        img_index_x = np.reshape(index_x, dsize_observe)

        return img_index_x, img_index_y

    @staticmethod
    def calculate_zncc(a: np.ndarray, b: np.ndarray) -> np.ndarray:
        """Calculate ZNCC (Zero-mean Normalized Cross-Correlation) for 1D or 2D array.

        Parameters
        ----------
        a : np.ndarray
           1D or 2D array. Shape should be ('N', 'any1').
        b : np.ndarray
           1D or 2D array. Shape should be ('N', 'any2').

        Returns
        -------
        output : np.ndarray
          Scalar or 1D array or 2D array of ZNCC value.
          Shape is ('any1', 'any2').

        Examples
        --------
        Simple 1D array case
        >>> a = np.random.rand(10)
        >>> calculate_zncc(a, a) # same array
        1.0
        >>> calculate_zncc(a, -a) # invert array
        -1.0
        >>> calculate_zncc(a, 0.8*a+1.0) # change amplitude and offset
        1.0
        Simple image case
        >>> img = np.random.rand(256, 256, 3)
        >>> calculate_zncc(img.flatten(), img.flatten())
        1.0

        2D array case
        >>> b = np.random.rand(10, 100)
        >>> c = np.random.rand(10, 200)
        >>> calculate_zncc(b, c).shape
        (100, 200)
        """
        # Subtract the average
        a = a - np.average(a, axis=0)
        b = b - np.average(b, axis=0)

        # Calculate the ZNCC
        aa_sum = np.expand_dims(np.sum(a*a, axis=0), -1)
        bb_sum = np.expand_dims(np.sum(b*b, axis=0), -1)
        output = ( a.T @ b ) / np.sqrt( aa_sum @ bb_sum.T )

        return output


"""
给定一个Excel表格中的列名称，返回其相应的列序号。
"""

def titleToNumber(s):
    res = 0
    for i in s:
        res = (ord(i) - 64) + res * 26
    return res

if __name__ == '__main__':
    print(titleToNumber("ZY"))


#!/usr/bin/env python
from .abstract_window import AbstractWindow
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QImage, QTextCursor, QTextBlockFormat

class QtNotebookWindow(AbstractWindow):
    """
    Simple window that is the same as matplotlib figure window
    """
    parent_notebook = None
    scale_notebook = (0.5, 0.5)

    def __init__(self, *args, **kwargs):
        # Create Figure
        if self.parent_notebook is not None:
            size = self.parent_notebook.frameSize()
            min_size = 1
            dpi = 100.0
            kwargs['figsize'] = (max(min_size, self.scale_notebook[0] * (size.width() / dpi)),
                    max(min_size, self.scale_notebook[1] * (size.height() / dpi)))
            kwargs['dpi'] = dpi
        self.show_count = 0
        self.buf = None
        self.figure = plt.figure(*args, **kwargs)
        self.canvas = FigureCanvas(self.figure)
        self.canvas.mpl_connect('resize_event', self.tight_layout)

    def tight_layout(self, event):
        try:
            self.figure.tight_layout()
        except:
            pass

    def show(self):
        if self.parent_notebook is None:
            print("No parent notebook to print the image to")
            return
        self.figure.tight_layout()
        self.canvas.draw()
        size = self.canvas.size()
        self.buf, (width, height) = self.canvas.print_to_buffer()
        image = QImage(self.buf, width, height, QImage.Format_ARGB32)
        self.parent_notebook.insertImage(image, 'figure_' + str(self.figure.number) + '_' + str(self.show_count))
        self.parent_notebook.resetFontSize()
        self.show_count = self.show_count + 1

    def gcf(self):
        return self.figure


import numpy as np
import cv2
from ppdet.core.workspace import create
from kkdetection.bytetrack import BYTETracker
from kkdetection.ppdet.detector import Detector
from kkdetection.ppdet.dataset import VideoDataset
from kkannotation.streamer import Recorder
from kkannotation.util.image import draw_annotation
from kkdetection.util.image import xyxy_to_xywh
from kkdetection.util.com import get_args

if __name__ == "__main__":
    args     = get_args()
    detector = Detector(**args.autofix())
    dataset = VideoDataset()
    dataset.set_data(args.get("video"), start_frame_id=0, max_frames=10, step=2)
    recorder = Recorder("./output_tracking.mp4", fps=dataset.streamer.get_fps(), width=dataset.streamer.shape()[1], height=dataset.streamer.shape()[0])
    tracker  = BYTETracker(
        dataset.streamer.shape()[0], dataset.streamer.shape()[1],
        thre_bbox_high=0.8, thre_bbox_low=0.2,
        thre_iou_high=0.8, thre_iou_low=0.8, thre_iou_new=0.8,
        max_time_lost=50
    )
    target_class_id = args.get("target", int, 0)
    dataloader = create("TestReader")(dataset, 0)
    outputs     = detector.predict_dataloader(dataloader)
    outputs     = [x["bbox"] for x in outputs]
    list_bboxes = [x[x[:, 0] == target_class_id][:, 2:].astype(float) for x in outputs]
    list_scores = [x[x[:, 0] == target_class_id][:, 1 ].astype(float) for x in outputs]
    tracks      = tracker.tracking(list_bboxes, list_scores)
    for i_frame, dict_output in enumerate(tracks):
        frame = dataset.streamer[i_frame]
        for track_id, bbox in dict_output.items():
            frame = draw_annotation(frame, xyxy_to_xywh([int(x) for x in bbox]), catecory_name=str(track_id), color_id=track_id)
        if args.get("is_show", None, False):
            cv2.imshow(__name__, frame)
            cv2.waitKey(0)
        if recorder is not None:
            recorder.write(frame)
    recorder.close()


import itertools

if __name__ == "__main__":
    # choose your wordle language mutation character set
    czech_characters = "ěščřžýáíéůqwertyuiopasdfghjklzxcvbnm"
    all_chars = set(czech_characters)

    # CHANGE HERE
    #
    # green characters must fit on position and be left-padded by spaces
    precise = ""

    # list of oranges along with zero-index position where it does not fit (3rd position is expressed as 2)
    orange_desc = {"i": [3], "o": [1,3,4], "t": [2,3,4], "k": [0], "s": [2]}

    # set the characters that do not belong to the word
    not_contained = set("áeryupadbn")
    #
    # DO NOT CHANGE ANY FURTHER

    oranges = set(orange_desc.keys())
    orange_options = list(itertools.product("o", oranges, repeat=1))

    free_chars = all_chars - not_contained - oranges
    unused_options = list(itertools.product("f", free_chars, repeat=1))

    FINAL_LENGTH = 5
    while len(precise) < FINAL_LENGTH:
        precise += " "
    precise = precise[:FINAL_LENGTH]  # to be sure if someone is too eager on left blank padding

    word_count = 0
    fillings = itertools.permutations(
        orange_options + unused_options, r=precise.count(" ")
    )
    for f in fillings:
        contained_oranges = set()
        for subf in f:
            if subf[0] == "o":
                contained_oranges.add(subf[1])

        if contained_oranges != oranges:
            continue

        # complete the word into the blanks
        space_index = 0
        completed = ""
        for c in precise:
            if c == " ":
                completed += f[space_index][1]
                space_index += 1
            else:
                completed += c

        # exclude the known orange positions
        is_orange_in_forbidden_position = False
        for idx, c in enumerate(completed):
            if c in orange_desc:
                is_orange_in_forbidden_position = idx in orange_desc[c]
                if is_orange_in_forbidden_position:
                    break

        if is_orange_in_forbidden_position:
            continue

        print(completed)
        word_count += 1

    print(f"\nWord count is {word_count}")


# -*- coding: utf-8 -*-
"""
Created on Mon Jun 10 14:09:23 2019

@author: TRAORE Cheick Amed
"""

"Algorithme de factorisation d'entiers"
"Précondition l'entier doit être composé"
#import prime
from prime import erastothene

def factorisation(Nl):
    k=2
    #global tab
    tab=[]
    while k<=int(Nl**0.5):
        if Nl%k==0 and erastothene(k):
            tab=tab+[k]
        k=k+1
    #print(tab)
    #if tab[0]==2:
     #   k2=tab[1]
    #else:
     #   k2=tab[0]
    #k1=int(Nl/k2)
    #return k1,k2
    k=len(tab)
   # print(k,len(tab))
    k=k//2
   # print(k)
    k2=tab[k]
    k1=Nl//k2
    return k1,k2


import unittest

class BinaryTree:

    def __init__(self):
        self.root_node = None
        self.tree = []

    def insert(self, data):
        if self.root_node is None:
            self.root_node = Node(data)
        else:
            node = self.root_node
            while True:
                if data >= node.data:
                    if node.right is None:
                        node.right = Node(data)
                        break
                    node = node.right
                else:
                    if node.left is None:
                        node.left = Node(data)
                        break
                    node = node.left

    def remove(self, data):
        pass

    def get_tree(self):
        if self.root_node.data is not None:
           self.tree_node(self.root_node)
        return self.tree

    def tree_node(self, node):
        if node is not None:
            self.tree_node(node.left)
            self.tree.append(node.data)
            self.tree_node(node.right)

class Node:

    def __init__(self, data):
        self.data = data
        self.right = None
        self.left = None

def binary_tree(arr):
    pass

class BinaryTreeTest(unittest.TestCase):

    def test_insert_one(self):
        tree = BinaryTree()
        tree.insert(1)
        self.assertEqual(tree.get_tree(), [1])

    def test_insert_three(self):
        tree = BinaryTree()
        tree.insert(1)
        tree.insert(2)
        tree.insert(3)
        self.assertEqual(tree.get_tree(), [1, 2, 3])

    def test_insert_complex(self):
        """Tree:
                    7
                   / \\
                  6    10
                 / \\    \\
                4    6     12
               / \\
              2    5
             / \\
            1    2
        """
        tree = BinaryTree()
        elements = [7, 6, 6, 4, 5, 2, 2, 1, 10, 12]
        for element in elements:
            tree.insert(element)
        self.assertEqual(tree.get_tree(), [1, 2, 2, 4, 5, 6, 6, 7, 10, 12])

if __name__ == '__main__':
    unittest.main()


import requests
import pandas as pd
import json
from pandas import DataFrame

def issues(repo):
    raw=requests.get('https://api.github.com/repos/'+ repo + '/issues')
    df=pd.DataFrame(raw.json())
    df_user=df.loc[:,['user']]
    names=[]
    i=0
    while i<len(df_user):
        names.append(df_user.loc[i][0].get('login'))
        i=i+1

    df_name=DataFrame(names,columns=['user_name'])

    issues_df=df.loc[:,['number','title']].join(df_name)
    print(issues_df)

    return issues_df

issues("numpy/numpy")


from django.contrib import admin
from django import forms

from ncfmusic.apps.content.models import *

class ListenAdmin(admin.ModelAdmin):
    list_display = ('title', 'album_title', 'songwriter', 'church', 'record_date', )
    list_filter = ('church', 'record_date' )
    search_fields = ('title', 'album_title', )
    prepopulated_fields = {'slug': ('title',)}

admin.site.register(Listen, ListenAdmin)

class WatchAdminForm(forms.ModelForm):
    class Meta:
        model = Watch

    def clean_vimeo_url(self):
        return self.cleaned_data['vimeo_url'] or None

    def clean_youtube_url(self):
        return self.cleaned_data['youtube_url'] or None

class WatchAdmin(admin.ModelAdmin):
    form = WatchAdminForm
    list_display = ('title', 'church', 'date', )
    list_filter = ('church', 'date', )
    search_fields = ('title', )
    prepopulated_fields = {'slug': ('title',)}
    readonly_fields = ('insert_date',)

    class Media:
        js = [
            '/media/admin/tinymce/jscripts/tiny_mce/tiny_mce.js',
            '/media/admin/tinymce_setup/tinymce_setup.js',
        ]

admin.site.register(Watch, WatchAdmin)

class TutorialAdmin(admin.ModelAdmin):
    list_display = ('title', 'date', 'author', 'church', )
    list_filter = ('date', 'author', 'church', )
    search_fields = ('title', )
    prepopulated_fields = {'slug': ('title',)}

    class Media:
        js = [
            '/media/admin/tinymce/jscripts/tiny_mce/tiny_mce.js',
            '/media/admin/tinymce_setup/tinymce_setup.js',
        ]

admin.site.register(Tutorial, TutorialAdmin)

class TalkAdmin(admin.ModelAdmin):
    list_display = ('title', 'date', 'author', 'church', )
    list_filter = ('date', 'author', 'church', )
    search_fields = ('title', )
    prepopulated_fields = {'slug': ('title',)}

    class Media:
        js = [
            '/media/admin/tinymce/jscripts/tiny_mce/tiny_mce.js',
            '/media/admin/tinymce_setup/tinymce_setup.js',
        ]

admin.site.register(Talk, TalkAdmin)

class ArticleAdmin(admin.ModelAdmin):
    list_display = ('title', 'date', 'author', 'church', )
    list_filter = ('date', 'author', 'church', )
    search_fields = ('title', )
    prepopulated_fields = {'slug': ('title',)}

    class Media:
        js = [
            '/media/admin/tinymce/jscripts/tiny_mce/tiny_mce.js',
            '/media/admin/tinymce_setup/tinymce_setup.js',
        ]

admin.site.register(Article, ArticleAdmin)

class TagAdmin(admin.ModelAdmin):
    list_display = ('name', 'slug', )
    list_filter = ('name', 'slug', )
    search_fields = ('name', )
    prepopulated_fields = {'slug': ('name',)}

admin.site.register(Tag, TagAdmin)

class SongAdmin(admin.ModelAdmin):
    list_display = ('title', 'album_title', 'songwriter', 'church', 'release_date', )
    list_filter = ('songwriter', 'church', 'release_date', )
    search_fields = ('title', )
    prepopulated_fields = {'slug': ('title',)}

    class Media:
        js = [
            '/media/admin/tinymce/jscripts/tiny_mce/tiny_mce.js',
            '/media/admin/tinymce_setup/tinymce_setup.js',
        ]

admin.site.register(Song, SongAdmin)

class EventAdmin(admin.ModelAdmin):
    list_display = ('title', 'start_date', 'end_date', 'church', )
    list_filter = ('start_date', 'church', )
    search_fields = ('title', )
    prepopulated_fields = {'slug': ('title',)}

    class Media:
        js = [
            '/media/admin/tinymce/jscripts/tiny_mce/tiny_mce.js',
            '/media/admin/tinymce_setup/tinymce_setup.js',
        ]

admin.site.register(Event, EventAdmin)

class ChurchAdmin(admin.ModelAdmin):
    list_display = ('name', 'city', 'state', )
    list_filter = ('state', )
    search_fields = ('name', 'city', 'state', )
    prepopulated_fields = {'slug': ('name',)}

admin.site.register(Church, ChurchAdmin)

class ContributorAdmin(admin.ModelAdmin):
    list_display = ('name', 'title', 'church', )
    list_filter = ('church', )
    search_fields = ('name', 'title', )
    prepopulated_fields = {'slug': ('name',)}

    class Media:
        js = [
            '/media/admin/tinymce/jscripts/tiny_mce/tiny_mce.js',
            '/media/admin/tinymce_setup/tinymce_setup.js',
        ]

admin.site.register(Contributor, ContributorAdmin)

class ContactAdmin(admin.ModelAdmin):
    list_display = ('first_name', 'last_name', 'email_address', )
    search_fields = ('first_name', 'last_name', 'email_address', )

admin.site.register(Contact, ContactAdmin)

class PageAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug': ('title',)}

    class Media:
        js = [
            '/media/admin/tinymce/jscripts/tiny_mce/tiny_mce.js',
            '/media/admin/tinymce_setup/tinymce_setup.js',
        ]

admin.site.register(Page, PageAdmin)

class GenreAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug': ('name',)}

admin.site.register(Genre, GenreAdmin)

class BlogCategoryAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug': ('name',)}

admin.site.register(BlogCategory, BlogCategoryAdmin)

class BlogEntryAdmin(admin.ModelAdmin):
    list_display = ('title', 'date')
    prepopulated_fields = {'slug': ('title',)}

    class Media:
        js = [
            '/media/admin/tinymce/jscripts/tiny_mce/tiny_mce.js',
            '/media/admin/tinymce_setup/tinymce_setup.js',
        ]

    def save_model(self, request, obj, form, change):
        try:
            author = obj.author
        except User.DoesNotExist:
            obj.author = request.user

        obj.save()

admin.site.register(BlogEntry, BlogEntryAdmin)

class ConferenceRegistrantInline(admin.StackedInline):
    model = ConferenceRegistrant

class ConferenceRegistrationAdmin(admin.ModelAdmin):
    list_display = ('last_name', 'first_name', 'insert_date', 'has_paid',)

    inlines = [ConferenceRegistrantInline]

admin.site.register(ConferenceRegistration, ConferenceRegistrationAdmin)


import os
import time
import sys
import shutil
import argparse

# for production stuff, consider the custom container images mentioned in buildNetworkWithAzure.py
#os.system('rm -rd keras-audio')
#os.system('rm -rd model')
os.system('apt update && apt-get install -y python python-dev python-pip build-essential swig git libpulse-dev libasound2-dev portaudio19-dev')
#os.system('git clone https://github.com/chen0040/keras-audio.git')
#os.system('cp -r keras-audio/keras_audio .')
#os.system('mkdir model')

sys.path.append('.')
from azure.storage.blob import BlockBlobService
from keras_audio.library.cifar10 import Cifar10AudioClassifier

azureStorgeAccountName = 'kevinsayazstorage'
azureStorageKeyName = '8H5YxVREMOVEDoHvaXvHgxiA=='
azureStorageContainer = 'completedmodel2'
labels = [100,90,80,70,60,50,40,30,20,10]
parser = argparse.ArgumentParser()
parser.add_argument("--data_dir")
args = parser.parse_args()

def load_path_labels(sourcePath):
    # here we are expecting file in the format XXXXXXX-N.wav, where N is the label
    pairs = []
    for f in os.listdir(sourcePath):
        try:
            if str(f.split('.')[1]).lower() == 'wav':          # only process wav files
                label = int(f.split('.')[0].split('-')[1])
                path = sourcePath + '/' + f
                pairs.append((path, labels.index(label)))
        except:
            print('error with: ' + str(f))
    return pairs

def main():
    block_blob_service = BlockBlobService(account_name=azureStorgeAccountName, account_key=azureStorageKeyName)
    if (block_blob_service.exists(container_name=azureStorageContainer) == False):
        block_blob_service.create_container(container_name=azureStorageContainer)

    audio_path_label_pairs = load_path_labels(str(args.data_dir))
    print('loaded: ' + str(len(audio_path_label_pairs)) + ' files')

    classifier = Cifar10AudioClassifier()
    batch_size = 8
    epochs = 50
    classifier.fit(audio_path_label_pairs=audio_path_label_pairs, model_dir_path='model', batch_size=batch_size, epochs=epochs)

    #zipping and uploading the compiled model to blob storage
    shutil.make_archive(base_name='model', format='zip', base_dir='model')
    block_blob_service.create_blob_from_path(azureStorageContainer, str(int(time.time() * 1000)) + 'model.zip', 'model.zip')

    # copying the model contents to the output directory
    os.system('cp -r ./model outputs')

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
# author: itimor

from django import forms
from blog.models import Article, BlogTypes
from mdeditor.fields import MDTextFormField
from taggit.forms import TagField

class ArticleAddForm(forms.Form):
    name = forms.CharField(label=u'文章标题', max_length=50)
    cover = forms.ImageField(label=u'封面', )
    content = MDTextFormField(label=u'内容', min_length=50)
    type = forms.ChoiceField(label=u'分类', choices=BlogTypes)
    tags = TagField(label=u'标签', max_length=50)

    def save(self):
        cd = self.cleaned_data
        name = cd['name']
        cover = cd['cover']
        type = cd['type']
        content = cd['content']
        tags = cd['tags']
        article = Article(
            name=name,
            cover=cover,
            content=content,
            type=type,
            tags=tags)
        article.save()


"""
Extruding a polygon
along the z-axis
"""
from vtkplotter import *

pol = Star().pos(0,0,0).rotateX(10)

epol = pol.extrude(zshift=1, rotation=10, dR=-0.2, cap=False, res=1)
epol.bc('violet')

show(epol, Text2D(__doc__), axes=1, viewup='z')


import time

import cv2
import numpy as np

# img = cv2.imread('images/stih.jpg')
video=cv2.VideoCapture('videos/i_am_ya_2023-04-14-11-03-46_1681452226541.mp4')
k=0
while cv2.waitKey(1) & 0xFF !=ord('q'):
    # img_shape = cv2.resize(img, (img.shape[1] // 2, img.shape[0] // 2))
    succ,img=video.read()
    img = cv2.GaussianBlur(img, (9, 9), 0)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    img = cv2.Canny(img,55,55)

    kernel = np.ones((3,3),np.uint8)
    img = cv2.dilate(img, kernel,iterations=1)
    cv2.putText(img,f'{k}', (0,0),cv2.FONT_HERSHEY_TRIPLEX,50,(0,0,255),thickness=0)
    img=cv2.erode(img,kernel,iterations=1)
    # img_shape[400:800,400:800]
    # cv2.putText(img, f'{k}', (0, 0), cv2.FONT_HERSHEY_TRIPLEX, 50, (0, 0, 255), thickness=0)
    cv2.imshow('Result', img)
    k+=1
    print(img.shape)

# print(img_shape.shape)
#
    cv2.waitKey(0)


import cv2 as cv
import paho.mqtt.client as mqtt

# mqtt parameters
local_mqtt_host = 'broker'
mqtt_port = 1883
mqtt_topic = 'faces'

# global variable indicating disconnect status
dc_flag = False

# create callback functions
def on_connect_local(local_client, userdata, flags, rc):
    """
    This function handles the callback from the broker when it sends acknowledgement of connection status.
    """

    if rc == 0:
        local_client.connected_flag = True
        print("Connected OK returned code = ", rc)
    else:
        print("Bad connection Returned code = ", rc)

def on_disconnect_local(local_client, userdata, rc):
    #global dc_flag
    print("Disconnected due to ", rc)
    #dc_flag = True

# initiate local client instance
local_client = mqtt.Client("detector")

# connection flag indicating connection status
local_client.connected_flag = False

# bind call back functions
local_client.on_connect = on_connect_local
local_client.on_disconnect = on_disconnect_local

# loop start
local_client.loop_start()

# make connection
local_client.connect(local_mqtt_host, mqtt_port, 60)

while not local_client.connected_flag:
    print("Waiting in loop")
    time.sleep(1)

# 1 should correspond to /dev/video1 , your USB camera.
# The 0 is reserved for the NX onboard camera or webcam on laptop
cap = cv.VideoCapture(0)
#cap.set(3, 640)
#cap.set(4, 480)

# alternative approach using background substractor
backSub = cv.createBackgroundSubtractorMOG2()

while True:

    # read frame by frame
    ret, frame = cap.read()

    ## convert frame to gray scale and implement Gaussian blur to remove unnecessary noise
    gray_frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
    gray_frame = cv.GaussianBlur(gray_frame, (55, 55), 0)

    # generate foreground mask
    fgmask = backSub.apply(gray_frame)
    fgmask = cv.dilate(fgmask, None, iterations=2)

    # identify contours for moving obejct (foreground mask)
    contours, _ = cv.findContours(fgmask, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)

    rectangles = []
    for c in contours:
        try:
            area = cv.contourArea(c)
            rectangles.append((area, cv.boundingRect(c)))
        except:
            pass

        for area, rect in sorted(rectangles, reverse=True):
            if area > 300:
                x, y, w, h = rect
                txt = 'Motion detected'
                txt_2 = 'Sending images to the cloud...'
                cv.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
                cv.putText(frame, txt, (100, 400), cv.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2, cv.LINE_AA)
                cv.putText(frame, txt_2, (100, 430), cv.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 1, cv.LINE_AA)

                # Extract object
                obj_extract = frame[y:y + h, x:x + w]

                # Encode extract to png
                rc, png = cv.imencode('.png', obj_extract)

                # convert png extract to bytes (for messaging)
                msg = png.tobytes()

                #if dc_flag:
                #local_client.connect(local_mqtt_host, mqtt_port, 60)
                local_client.publish(mqtt_topic, msg, qos=1, retain=False)

    cv.imshow('img', frame)
    if cv.waitKey(1) & 0xFF == ord('q'):
        break

# loop end
local_client.disconnect()

cap.release()
cv.destroyAllWindows()


def part1_and_2():
    start = 264360
    end = 746325

    possible_numbers1 = []
    possible_numbers2 = []
    for number in range(start, end):
        number_string = str(number)
        digits = [int(n) for n in number_string]

        # check if the digits are increasing and if there is a pair:
        increasing_flag = True
        pair_flag = False
        for index in range(len(digits)-1):
            if digits[index] > digits[index+1]:
                increasing_flag = False
            if digits[index] == digits[index+1]:
                pair_flag = True
        if increasing_flag is False or pair_flag is False:
            continue
        else:
            possible_numbers1.append(number)
            # check if the number meets the part 2 extra criteria:
            for digit in range(10):
                if number_string.count(str(digit)) == 2:
                    possible_numbers2.append(number)
                    print(number)

    print("part 1:", len(possible_numbers1))
    print("part 2:", len(set(possible_numbers2)))

part1_and_2()


import sys

input = sys.stdin.readline

n = int(input())
crane = list(map(int, input().split()))
m = int(input())
box = list(map(int, input().split()))
crane.sort(reverse=True)
box.sort(reverse=True)
if crane[0] < box[0]:
    print(-1)
else:
    position = [0] * n
    move = [False for _ in range(m)]
    time = 0
    num = m
    while num > 0:
        for i in range(n):
            while position[i] < m:
                if not move[position[i]] and crane[i] >= box[position[i]]:
                    move[position[i]] = True
                    position[i] += 1
                    num -= 1
                    break
                position[i] += 1
        time += 1
    print(time)


import os
import yaml
import json
import socket
import secrets
import platform
import requests

from core.settings import ALIAS_CONFIGS
from core.settings import IS_DEVELOPMENT
from core.settings import IS_TRAVIS
from core.settings import SSH_CONFIGS

from core.data import conf
from core.data import paths
from core.data import remote_repository
from core.type import get_attr_value
from utils.process import git_remote_path
from utils.process import has_git_changes
from utils.process import output
from utils.validator import validate

def _check_user_privileges():
    validate(
        error="This program needs to be not execute as root.",
        target="user privileges",
        valid=(os.getuid() != 0)
    )

def _check_git_branch():
    branch = output("git rev-parse --abbrev-ref HEAD")

    validate(
        error="This program needs to be on master branch before to build.",
        target="git repository",
        valid=(branch == "master")
    )

def _check_is_docker_image():
    validate(
        error="This program needs to be executed in a docker image.",
        target="docker",
        valid=(os.environ.get("IS_DOCKER", False))
    )

def _check_internet_up():
    try:
        socket.create_connection(("www.github.com", 80))
        connected = True
    except OSError:
        connected = False

    validate(
        error="This program needs to be connected to internet.",
        target="internet",
        valid=connected
    )

def _check_deploy_key():
    valid = True
    target = "deploy_key"

    if IS_TRAVIS and os.path.isfile(os.path.join(paths.base, "deploy_key.enc")) is False:
        valid = False
        target = "deploy_key.enc"

    elif os.path.isfile(os.path.join(paths.base, "deploy_key")) is False:
        valid = False

    validate(
        error="%s could not been found." % target,
        target=target,
        valid=valid
    )

def _check_repository():
    valid = True
    target = "repository.yml"

    if IS_TRAVIS and os.path.isfile(os.path.join(paths.base, "repository.yml.enc")) is False:
        valid = False
        target = "repository.yml.enc"

    elif os.path.isfile(os.path.join(paths.base, "repository.yml")) is False:
        valid = False

    validate(
        error="%s could not been found." % target,
        target=target,
        valid=valid
    )

def _check_content():
    valid = True
    content = ALIAS_CONFIGS

    if not remote_repository():
        content = set(content) - set(SSH_CONFIGS)

    for name in content:
        if not get_attr_value(conf, name):
            valid = False
            break

    validate(
        error="%s must be defined in repository.yml" % name,
        target="content",
        valid=valid
    )

def _check_database():
    valid = True
    error_msg = ""

    if conf.db in ("core", "extra", "community"):
        valid = False
        error_msg = "Database must be different than core, community and extra."

    elif conf.db.isalnum() is False:
        valid = False
        error_msg = "Database must be an alphanumeric string."

    validate(
        error=error_msg,
        target="database",
        valid=valid
    )

def _check_port():
    validate(
        error="port must be an interger in repository.yml",
        target="port",
        valid=(type(conf.ssh_port) == int)
    )

def _check_travis_lint(content):
    error_msg = "An error occured while trying to parse your travis file.\nPlease make sure that the file is valid YAML.",

    validate(
        error=error_msg,
        target="lint",
        valid=(type(content) is dict)
    )

def _check_travis_openssl(content):
    valid = False
    error_msg = "No openssl statement could be found in your travis file.\nPlease make sure to execute: travis encrypt-file ./deploy_key --add"

    if "before_install" in content:
        for statement in content["before_install"]:
            if statement.startswith("openssl"):
                valid = True

    validate(
        error=error_msg,
        target="openssl",
        valid=valid
    )

def _check_pkg_directory():
    validate(
        error="No package was found in pkg directory.",
        target="directory",
        valid=(len(conf.packages) > 0)
    )

def _check_pkg_content():
    folders = [f.name for f in os.scandir(paths.pkg) if f.is_dir()]
    diff = set(folders) - set(conf.packages)

    validate(
        error="No package.py was found in pkg subdirectories: %s" % (", ".join(diff)),
        target="content",
        valid=(len(diff) == 0)
    )

def _check_ssh_connection():
    script = "ssh -i ./deploy_key -p %i -q %s@%s [[ -d %s ]] && echo 1 || echo 0" % (
        conf.ssh_port,
        conf.ssh_user,
        conf.ssh_host,
        conf.ssh_path
    )

    validate(
        error="ssh connection could not be established.",
        target="ssh address",
        valid=(output(script) == "1")
    )

def _check_mirror_connection():
    token = secrets.token_hex(15)
    source = os.path.join(paths.mirror, "validation_token")

    with open(source, "w") as f:
        f.write(token)
        f.close()

    os.system("rsync -aqv -e 'ssh -i ./deploy_key -p %i' %s %s@%s:%s" % (
        conf.ssh_port, source, conf.ssh_user, conf.ssh_host, conf.ssh_path)
    )

    try:
        response = requests.get(conf.url + "/validation_token")
        valid = True if response.status_code == 200 else False
    except requests.RequestException:
        valid = False

    validate(
        error="This program can't connect to %s." % conf.url,
        target="mirror host",
        valid=valid
    )

def _check_github_token():
    valid = False
    user = git_remote_path().split("/")[1]
    response = output("curl -su %s:%s https://api.github.com/user" % (user, conf.github_token))
    content = json.loads(response)

    if "login" in content:
        valid = True

    validate(
        error="An error occured while trying to connect to your github repository with your encrypted token.\nPlease make sure that your token is working.",
        target="github token api",
        valid=valid
    )

class Validator():
    def requirements(self):
        print("Validating requirements:")

        _check_user_privileges()
        _check_is_docker_image()
        _check_internet_up()

    def files(self):
        print("Validating files:")

        _check_repository()

        if remote_repository():
            _check_deploy_key()

    def configs(self):
        print("Validating repository:")

        _check_content()
        _check_database()

        if remote_repository():
            _check_port()

    def connection(self):
        print("Validating connection:")

        if remote_repository():
            _check_ssh_connection()
            _check_mirror_connection()

        _check_github_token()

    def content(self):
        print("Validating packages:")

        _check_pkg_directory()
        _check_pkg_content()

    def travis(self):
        if IS_TRAVIS is False:
            return

        print("Validating travis:")

        with open(".travis.yml", "r") as stream:
            try:
                content = yaml.safe_load(stream)
            except yaml.YAMLError as error:
                content = error

        _check_travis_lint(content)
        _check_travis_openssl(content)

validator = Validator()


import torch.nn as nn
import torch
import numpy as np

"""
Since I didn't find an elegant way to find the topology every time after Skeleton pooling
I use a dirty trick to hard-encode the topologies after pooling
So, this means we could only apply our model on Aj and Bigvegas's skeletons
"""
topology_after_1_pool = np.array([0, 0, 1, 0, 3, 0, 5, 6, 6, 8, 6, 10])
ee_id_after_1_pool = [2, 4, 7, 9, 11]

topology_after_2_pool = np.array([0, 0, 0, 0, 3, 3, 3])
ee_id_after_2_pool = [1, 2, 4, 5, 6]

class SkeletonConvolution(nn.Module):
    """
    The skeleton convolution based on the paper
    Use a more intuitive 2D convolution than the 1D convolution in the original source code
    """

    def __init__(self, in_channels, out_channels, k_size: tuple, stride, pad_size: tuple,
                 topology: np.ndarray, neighbor_dist: int, ee_id: list):
        """
        :param k_size: should be (simple_joint_num, a_short_time_length) !!!
        :param topology: A numpy array, the value of the array is parent idx, the idx of the array is child node idx
        it could tell us the topology of the initial simplified skeleton or the pooled skeleton
        """
        super(SkeletonConvolution, self).__init__()
        self.neighbor_list = find_neighbor(topology, neighbor_dist, ee_id)
        self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=k_size, stride=stride, padding=pad_size)

    def forward(self, x):
        """
        :param x: The input tensor should have size [B , IN_C , simple_joint_num , total_time_length]
        :return:
        """
        result_list = []
        for neighbors in self.neighbor_list:
            binary_mask = torch.zeros_like(x, dtype=torch.float)
            # only neighboring joint can has mask value 1
            binary_mask[:, :, neighbors, :] = 1
            tmp_x = x * binary_mask
            # tmp_result should have size [B * OUT_C * 1 * total_time_length]
            tmp_result = self.conv(tmp_x)
            result_list.append(tmp_result)
        return torch.cat(result_list, dim=2)

class SkeletonPool(nn.Module):
    """
    Apply average skeleton pooling on the output of the skeleton convolution layers
    The pooling layer should tell that: what's the topology of the next convolution layer!.
    """
    def __init__(self, topology, ee_id, layer_idx):
        """
        :param topology: 1D numpy array
        :param ee_id: A list
        """
        super(SkeletonPool, self).__init__()
        self.old_topology = topology
        self.old_ee_id = ee_id
        # store the topology after pooling and merge joints
        self.new_topology = topology_after_1_pool if layer_idx == 1 else topology_after_2_pool
        # store the ee_ids after pooling and merge joints
        self.new_ee_id = ee_id_after_1_pool if layer_idx == 1 else ee_id_after_2_pool
        self.seq_list = []
        self.pooling_list = []
        self.old_joint_num = len(self.old_topology.tolist())
        self.new_joint_num = len(self.new_topology.tolist())
        # calculate the degree of each joint in the skeleton graph
        # 经过下面的操作，计算各个joint的degree
        self.degree = calculate_degree(topology)
        # separate the skeleton into multiple sequence
        self.pooling_seq = find_pool_seq(self.degree)  # a list
        self.merge_pairs = self._get_merge_pairs()  # a list
        self.merge_nums = [len(each) for each in self.merge_pairs]

    def _get_merge_pairs(self):
        merge_pair_list = []
        for seq in self.pooling_seq:
            if len(seq) == 1:
                single_joint = [seq.pop(0)]
                merge_pair_list.append(single_joint)
                continue
            elif len(seq) % 2 != 0:
                single_joint = [seq.pop(0)]
                merge_pair_list.append(single_joint)
            for i in range(0, len(seq), 2):
                tmp_pair = [seq[i], seq[i+1]]
                merge_pair_list.append(tmp_pair)
        return merge_pair_list

    def forward(self, x):
        result_list = []
        result_list.append(x[:, :, 0:1, :])  # add the root joint's data into result
        for merge_pair in self.merge_pairs:
            tmp_result = torch.zeros_like(x[:, :, 0:1, :])
            for merge_idx in merge_pair:
                tmp_result += x[:, :, merge_idx: merge_idx+1, :]
            tmp_result /= len(merge_pair)
            result_list.append(tmp_result)
        result = torch.cat(result_list, dim=2)
        if result.shape[2] != self.new_joint_num:
            raise Exception('Joint num does not match after pooling')
        return result

class SkeletonUnPool(nn.Module):
    def __init__(self, un_pool_expand_nums: list):
        """
        :param un_pool_expand_nums: 一个列表，记录着对应的pooling层，每个merge后的joint是由几个关节合并得到的。
        由几个关节merge得到，在UnPool的时候，就把该关节的tensor复制几次。
        需要注意的是，root joint是从未被merge过的，所以也不duplicate它。
        """
        super(SkeletonUnPool, self).__init__()
        self.un_pool_expand_nums = un_pool_expand_nums

    def forward(self, x):
        result_list = []
        result_list.append(x[:, :, 0:1, :])  # add root joint's feature tensor first
        for idx, expand_num in enumerate(self.un_pool_expand_nums):
            tmp_idx = idx + 1
            tmp_x = x[:, :, tmp_idx: tmp_idx + 1, :]
            tmp_x = tmp_x.repeat(1, 1, expand_num, 1)
            result_list.append(tmp_x)
        out = torch.cat(result_list, dim=2)
        return out

def build_bone_topology(topology):
    # The topology is simplified already!
    # get all edges (parents_bone_idx, current_bone_idx)
    # edges 要比topology的个数少1
    edges = []
    joint_num = len(topology)
    # 舍去了root joint
    for i in range(1, joint_num):
        # i 指的是简化后骨骼的index, topology[i] is i's parents bone
        edges.append((topology[i], i))
    return edges

def calculate_neighbor_matrix(topology):
    topology = topology.tolist()
    joint_num = len(topology)
    mat = [[100000] * joint_num for _ in range(joint_num)]
    for i, j in enumerate(topology):
        mat[i][j] = 1
        mat[j][i] = 1
    for i in range(joint_num):
        mat[i][i] = 0
    # Floyd algorithm to calculate distance between nodes of the skeleton graph
    for k in range(joint_num):
        for i in range(joint_num):
            for j in range(joint_num):
                mat[i][j] = min(mat[i][j], mat[i][k] + mat[k][j])
    return mat

def calculate_degree(topology):
    topology = topology.tolist()
    joint_num = len(topology)
    mat = [[0] * joint_num for _ in range(joint_num)]
    for i, j in enumerate(topology):
        mat[i][j] = 1
        mat[j][i] = 1
    for i in range(joint_num):
        mat[i][i] = 0
    degree_list = [sum(each) for each in mat]
    return degree_list

def find_neighbor(topology, dist, ee_id):
    distance_mat = calculate_neighbor_matrix(topology)
    neighbor_list = []
    joint_num = len(distance_mat)
    for i in range(joint_num):
        neighbor = []
        for j in range(joint_num):
            # 距离小于d的，就加入到该骨骼的领接列表中来
            if distance_mat[i][j] <= dist:
                neighbor.append(j)
        # 将每根骨骼的邻接列表插入到一个总的列表中
        neighbor_list.append(neighbor)

    # add neighbor for global part(the root joint's neighbors' index)
    global_part_neighbor = neighbor_list[0].copy()
    # based on the paper, the end_effector should also be regarded as the neighbor of the root joint
    # so we need to add end_effector's index to root joint's neighbor list
    global_part_neighbor = list(set(global_part_neighbor).union(set(ee_id)))
    for i in global_part_neighbor:
        # the index of root joint is 0!
        if 0 not in neighbor_list[i]:
            neighbor_list[i].append(0)
    neighbor_list[0] = global_part_neighbor
    return neighbor_list

def find_pool_seq(degree):
    num_joint = len(degree)
    seq_list = [[]]
    for joint_idx in range(1, num_joint):
        if degree[joint_idx] == 2:
            seq_list[-1].append(joint_idx)
        else:
            seq_list[-1].append(joint_idx)
            seq_list.append([])
            continue
    seq_list = [each for each in seq_list if len(each) != 0]
    return seq_list


from .views import (
                    RegisterAPIView,
                    ProfileDetailApiView,
                    LoginView,
                    RefreshTokenView,
                    LogoutView)
from django.urls import path, include

app_name = "accounts"

urlpatterns = [
    path('register', RegisterAPIView.as_view(), name='register'),
    path('profile/<int:pk>', ProfileDetailApiView.as_view(), name='profile'),
    path('login', LoginView.as_view(), name='login'),
    path('refresh', RefreshTokenView.as_view(), name='refresh'),
    path('logout', LogoutView.as_view(), name='logout'),
]


from pkg.graphics.all import colorFromString as cfs

class ViewConfig(object):
    def __init__(self, viewDict: dict):
        # Track
        self.showTrack, self.trackColor = self.__showColor(viewDict['track'])

        # Runner
        runnerDict = viewDict['runner']
        self.showRunnerPoints, self.runnerPointsColor = self.__showColor(runnerDict['points'])
        self.showRunnerSkeleton, self.runnerSkeletonColor = self.__showColor(runnerDict['skeleton'])
        self.showRunnerRect, self.runnerRectColor = self.__showColor(runnerDict['rect'])

        # Tracking rect
        self.showTrackingRect, self.trackingRectColor = self.__showColor(viewDict['tracking-rect'])

    def __showColor(self, showColorDict: dict):
        return showColorDict['show'], cfs(showColorDict['color'])


from django.contrib import admin
from .models import Women, Category

@admin.register(Women)
class WomenAdmin(admin.ModelAdmin):
    list_display = ("pk", "title", "content")
    search_fields = ("title", "text",)
    list_filter = ("time_create", "time_update")

admin.site.register(Category)


# !/usr/bin/python
# -*- coding: utf-8 -*-
# @time    : 2021/2/23 21:34
# @author  : Mo
# @function: main programing, "训练时候logger不需要考虑"

# 适配linux
from collections import Counter
from argparse import Namespace
import random
import copy
import sys
import os
path_root = os.path.abspath(os.path.join(os.path.dirname(__file__), ""))
sys.path.append(path_root)
# os.environ["CUDA_VISIBLE_DEVICES"] = "-1"

from tsConfig import _TS_MODEL_BERTSUM
from tsTools import get_logger
from tsOffice import Office
from tsData import DataSet

class TextSummary:
    def __init__(self, config):
        self.config = Namespace(**config)
        self.logger = get_logger(self.config.model_save_path)
        self.l2i, self.i2l = {}, {}

    def process(self):
        """ 数据预处理, process """
        # 数据读取
        # 训练集/验证集划分
        if self.config.path_dev:
            self.train_corpus = DataSet(self.config, self.config.path_train, self.logger)
            self.dev_corpus = DataSet(self.config, self.config.path_dev, self.logger)
        else:  # 没有验证集的时候, 默认划分 4:1
            self.train_corpus = DataSet(self.config, self.config.path_train, self.logger)
            xs_train, ys_train = self.train_corpus.data_iter
            len_rate_8 = int(len(ys_train) * 0.8)
            xs_train, ys_train = xs_train[:len_rate_8], ys_train[:len_rate_8]
            xs_dev, ys_dev = xs_train[len_rate_8:], ys_train[len_rate_8:]
            self.train_corpus.data_iter = xs_train, ys_train
            self.dev_corpus = DataSet(self.config, None, self.logger)
            self.dev_corpus.data_iter = xs_dev, ys_dev
        self.tet_corpus = DataSet(self.config, self.config.path_tet, self.logger)
        self.logger.info("read_corpus_from_json ok!")
        # 参数更新
        self.config.len_corpus = self.train_corpus.len_corpus
        self.config.prior_count = self.train_corpus.prior_count
        self.config.prior = self.train_corpus.prior
        self.config.task_type = _TS_MODEL_BERTSUM

    def train(self, path_save=None):
        """ 初始化训练  """
        # 创建模型目录与储存超参信息
        if not os.path.exists(self.config.model_save_path):
            os.makedirs(self.config.model_save_path, exist_ok=True)
        # 训练
        self.office = Office(tokenizer=self.train_corpus.tokenizer,
                             train_corpus=self.train_corpus,
                             dev_corpus=self.dev_corpus,
                             tet_corpus=self.tet_corpus,
                             config=self.config,
                             logger=self.logger)
        # 加载训练好的模型
        if path_save and path_save.strip():
            try:
                self.office.load_model_state(path_save)
            except Exception as e:
                self.logger.info(str(e))
                self.office.load_model(path_save)
        # 训练
        self.office.train_model()

    def eval(self):
        """ 验证评估  """
        try:
            self.office.load_model_state()
        except Exception as e:
            self.logger.info(str(e))
            self.office.load_model()
        tet_results = self.office.evaluate("tet")
        return tet_results

if __name__ == "__main__":
    # 适配linux
    import platform
    import sys
    import os
    path_root = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
    sys.path.append(path_root)
    print(path_root)
    # 分类下的引入, pytorch_textclassification
    from tsConfig import model_config
    from tsTools import get_current_time

    # 预训练模型地址, 本地win10默认只跑2步就评估保存模型
    if platform.system().lower() == 'windows':
        pretrained_model_dir = "D:/DATA/bert-model/00_pytorch"
        evaluate_steps = 32  # 评估步数
        save_steps = 32  # 存储步数
    else:
        pretrained_model_dir = "/pretrain_models/pytorch"
        path_ernie = "/home/moyzh/pretrain_models/pytorch/ernie-tiny"
        evaluate_steps = 320  # 评估步数
        save_steps = 320  # 存储步数
        ee = 0
    # 训练-验证语料地址, 可以只输入训练地址
    path_corpus = path_root + "/corpus/text_summary/maths_toy"
    path_train = os.path.join(path_corpus, "train.json")
    path_dev = os.path.join(path_corpus, "dev.json")

    model_config["evaluate_steps"] = evaluate_steps  # 评估步数
    model_config["save_steps"] = save_steps  # 存储步数
    model_config["path_train"] = path_train
    model_config["path_dev"] = path_dev
    model_config["lr"] = 5e-5  # 测试语料, 可为None
    model_config["max_len"] = 256  # 测试语料, 可为None
    model_config["batch_size"] = 32  # 测试语料, 可为None
    model_config["loss_type"] = "SOFT_MARGIN_LOSS"  # 测试语料, 可为None
    model_config["is_adv"] = False  # 测试语料, 可为None

    # 损失函数类型,
    # multi-class:  可选 None(BCE), BCE, BCE_LOGITS, MSE, FOCAL_LOSS, DICE_LOSS, LABEL_SMOOTH
    # multi-label:  SOFT_MARGIN_LOSS, PRIOR_MARGIN_LOSS, FOCAL_LOSS, CIRCLE_LOSS, DICE_LOSS等
    # model_config["loss_type"] = "SOFT_MARGIN_LOSS"
    # model_config["loss_type"] = "MIX"
    # model_config["loss_type"] = "SOFT_MARGIN_LOSS"

    # 预训练模型适配的class
    model_type = ["BERT", "ERNIE", "BERT_WWM", "ALBERT", "ROBERTA", "XLNET", "ELECTRA"]
    pretrained_model_name_or_path = {
        "BERT_WWM": "hfl/chinese-bert-wwm-ext",
        "ROBERTA": "hfl/chinese-roberta-wwm-ext",
        "ALBERT": "uer/albert-base-chinese-cluecorpussmall",
        "XLNET": "hfl/chinese-xlnet-mid",
        "ERNIE": "nghuyong/ernie-1.0-base-zh",
        # "ERNIE": "nghuyong/ernie-3.0-base-zh",
        "BERT": "bert-base-chinese",
        # "BERT": "hfl/chinese-macbert-base",

    }
    idx = 1  # 选择的预训练模型类型---model_type
    model_config["pretrained_model_name_or_path"] = pretrained_model_name_or_path[model_type[idx]]
    model_config["model_save_path"] = "../output/text_summary/model_{}".format(model_type[idx])
    model_config["model_type"] = model_type[idx]

    model_config["ADDITIONAL_SPECIAL_TOKENS"] = ["＋","－", "＝", "：", "．", "（", "）", "≈", "％",
                                                 "∥", "＜", "＞", "⊙", "≌", "。"]  # 新增特殊字符
    # main
    lc = TextSummary(model_config)
    lc.process()
    lc.train()

# shell
# nohup python  tsRun.py > tc_multi_class.log 2>&1 &
# tail -n 1000  -f tc_multi_class.log
# |myz|


import math

firstRun = True

def bold(string):
    """
    This function returns a bolded string.
    """
    return "\033[1m" + string + "\033[0m"

while True:

    if firstRun:
        print("=== Welcome To The Simple Calculator ===")

    firstRun = False

    print("list of available operations:")
    print("1. Addition: +")
    print("2. Subtraction: -")
    print("3. Multiplication: *")
    print("4. Division: /")
    print("5. Power: ** or ^")
    print("7. Logarithm: log")
    print("8. Sin: sin")
    print("9. Cos: cos")
    print("10. Tan: tan")
    print("11. Cot: cot")
    print("12. Sqrt: sqrt")
    print("13. Factorial: !")
    print("14. Exit: exit or quit")

    print("")
    print("please choose an operator: ")

    operator = input()

    if operator in ["14", "exit", "quit"]:
        break

    twoOperatorsList = ['+', '-', '*', '/', '**', '^']

    print("type your number:")
    inputA = float(input())
    if operator in twoOperatorsList:
        print("type your second number:")
        inputB = float(input())

    if operator == "+":
        result = inputA + inputB

    elif operator == "-":
        result = inputA - inputB

    elif operator == "*":
        result = inputA * inputB

    elif operator == "/":
        if inputB == 0:
            result = "Can't divide by zero"
        else:
            result = inputA / inputB
    elif operator == "**" or operator == "^":
        result = inputA ** inputB

    elif operator == "log":
        result = math.log(inputA)
    elif operator == "sin":
        result = math.sin(inputA)
    elif operator == "cos":
        result = math.cos(inputA)
    elif operator == "tan":
        result = math.tan(inputA)
    elif operator == "cot":
        result = 1 / math.tan(inputA)
    elif operator == "sqrt":
        result = math.sqrt(inputA)
    elif operator == "!":
        result = math.factorial(inputA)

    print(bold("Result: " + str(result) + "\n\r"))


#!/usr/bin/python
# -*- coding: latin-1 -*-
from random import random

from numba import jit, vectorize
import zlib, numpy
from functools import reduce
import os

os.environ[
    "NUMBAPRO_NVVM"
] = r"D:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.1\nvvm\bin\nvvm64_32_0.dll"
os.environ[
    "NUMBAPRO_LIBDEVICE"
] = r"D:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.1\nvvm\libdevice"

@jit(nogil=True)
def xor_numpy(p1, p2):
    if (isinstance(p2, numpy.ndarray) and isinstance(p1, numpy.ndarray)) and (
        (p1.dtype == numpy.uint8 and p2.dtype == numpy.uint8)
        or (p1.dtype == numpy.bool and p2.dtype == numpy.bool)
    ):
        n_p1 = p1
        n_p2 = p2
    else:
        n_p1 = numpy.fromstring(p1, dtype="uint8")
        n_p2 = numpy.fromstring(p2, dtype="uint8")
    return xor_intern(n_p1, n_p2)

@vectorize(["uint8(uint8,uint8)", "boolean(boolean,boolean)"], target="cuda")
def xor_intern(n_p1, n_p2):
    return n_p1 ^ n_p2

@jit(cache=True)
def listXOR(plist):
    return reduce(xor_numpy, plist)

@jit(cache=True)
def logical_xor(plist):
    return reduce(numpy.logical_xor, plist)

@jit(cache=True)
def xor_pakets(packet1, packet2):
    assert len(packet1) == len(packet2)
    a = [a ^ b for (a, b) in zip(bytes(packet1, "utf-8"), bytes(packet2, "utf-8"))]
    return a

@jit(cache=True)
def should_drop_packet(rules, packet):
    rand = random()  # create number from [0,1)
    drop_chance = rules.apply_all_rules(packet)
    packet.set_error_prob(drop_chance)
    # drop packet if rand bigger than the drop_chance for this Packet.
    return drop_chance > rand

@jit(cache=True)
def calc_crc(data):
    return zlib.crc32(data) & 0xFFFFFFFF

@jit(cache=True)
def xor_mask(data, mask=0b11110000101011000011101001101010, enabled=True):
    if not enabled:
        return data
    return numpy.bitwise_xor(data, mask)

# bitSet returns true if x has the b'th bit set
@vectorize(["boolean(uint32, uint32)", "boolean(uint64, uint64)"], target="cuda")
def bitSet(x, b):
    return ((x >> b) & 1) == 1

# bitsSet returns how many bits in x are set.
# This algorithm basically uses shifts and ANDs to sum up the bits in
# a tree fashion.
@vectorize(["int64(uint64)", "int64(uint32)"], target="cuda")
def bitsSet(x):  # x is of type uint64 !
    x -= (x >> numpy.uint64(1)) & numpy.uint64(0x5555555555555555)
    x = (x & numpy.uint64(0x3333333333333333)) + (
        (x >> numpy.uint64(2)) & numpy.uint64(0x3333333333333333)
    )
    x = (x + (x >> numpy.uint64(4))) & numpy.uint64(0x0F0F0F0F0F0F0F0F)
    res = numpy.int64((x * numpy.uint64(0x0101010101010101)) >> numpy.uint64(56))
    return res

# grayCode calculates the gray code representation of the input argument
# The Gray code is a binary representation in which successive values differ
# by exactly one bit. See http://en.wikipedia.org/wiki/Gray_code
@vectorize(["uint64(uint64)", "uint64(uint32)", "uint64(float64)"], target="cuda")
def grayCode(x):
    return (numpy.uint64(x) >> numpy.uint64(1)) ^ numpy.uint64(x)

# buildGraySequence returns a sequence (in ascending order) of "length" Gray numbers,
# all of which have exactly "b" bits set.
@jit("int32(int32,int32)")
def buildGraySequence(length, b):
    s = numpy.empty(length, dtype=int)
    i = 0
    x = numpy.uint64(0)
    while True:
        g = grayCode(x)
        if bitsSet(g) == b:
            s[i] = int(g)
            i += 1
            if i >= length:
                break
        x += 1
    return s


# Create a new song, based on the providede samples, wich are given in json format
# Sound effects: https://mixkit.co/free-sound-effects/
from os import pipe
import wave
import sys
import struct
import os.path
import math
import random

# normalize e modulate nao estão a funcionar

dic = {
    "id": "final_song.wav",
    "bpm": 61,
    "volume": 5,
    "mask": 'none',
    "samples": ["./sounds/arcade-retro-game-over.wav", "./sounds/crickets-and-insects-in-the-wild.wav", "./sounds/dog-barking-twice.wav", "./sounds/fast-rocket-whoosh_2.wav"],
    "effects": {
        0: "fadein", 11: "fadeout"
    },
    "music": [
        [0], [2, 3], [], [0], [1], [], [0], [], [2], [0], [], [2, 3]
    ]
}

# Example of the dictionary
#   {
#       "id" : "final_song.wav",
#        "bpm": 61,
#        "volume" : 5,
#        "mask" : 'none',
#      "samples": ["sample1", "sample2", "sample3", "sample..n"],
#       "effects": {
#       0: "fadein", 11: "fadeout"
#   },
#       "music": [
#           [0], [], [], [0], [1], [], [0], [], [2], [0], [], [2, 4]
#       ]
#   }

# @argumentos -> caminho do ficheiro
# @return -> informação acerca do ficheiro
def readSong(filePath):
    checkFile = checkSong(filePath)  # Verificar a existência do ficheiro
    if not checkFile[0]:
        return checkFile  # Devolver o dicionário de erro

    wf = wave.open(filePath, "rb")  # rb = ler em binário

    result = wf.getparams()  # quardar os parâmetros
    # wave_read.getparams
    # Returns a namedtuple()
    # (nchannels, sampwidth, framerate, nframes, comptype, compname),
    # equivalent to output of the get*() methods.
    wf.close()  # fechar o ficheiro

    return result  # devolver os parâmetros

# @argumentos -> caminho do ficheiro
# @return -> lista com pos 0 True ou False, se o ficheiro existe ou não
#         -> pos 1, informação de sucesso e erro, caso algum exista
#         -> i.e [True, "Song generated"] ou [False, "The provided path doesn't exists"]

def checkSong(filePath):
    if os.path.isfile(filePath):  # Se o caminho fornecido é um ficheiro
        return[True, "success"]
    elif os.path.isdir(filePath):  # Se o caminho fornecido é um diretório
        # retorna uma mensagem de erro
        return[False, "The provided path is a directory"]
    else:  # Se o caminho fornecido não existe
        # retorna uma mensagem de erro
        return [False, "The provided path doesn't exists"]

# @argumentos -> ficheiro
# @return -> duração música em segundos

def durationSong(filePath):
    checkFile = checkSong(filePath)  # Verificar a existência do ficheiro
    if(not checkFile[0]):
        return [checkFile[0], checkFile[1]]  # Devolver o dicionário de erro
    w = wave.open(filePath, 'rb')  # ler o ficheiro em binário
    # devolver a duração em segundos
    return round(w.getnframes() / float(w.getframerate()))

# @argumentos -> bites de Música
# @return -> duração música

# aceita bytes como parâmetros, invés de um filepath (Não está a funcionar muito corretamente)
def durationData(data, framerate):
    # devolver a duração da música em segundos
    return round(data / float(framerate))

# @argumentos -> beats per minute (bpm)
# @return -> Framerate (Frames per second)
# @formula -> 44100hz = 60 bpm

def calculateFramerate(bpm):
    # 60 bpm = 1s
    # Usei esta fórmula, pois penso que o valor default de velocidade de cada música é 44110hz
    # 1hz = 1s
    # I.E 61 * 1 / 60 =  +/- 1.1, mas este valor está errado, pois a música teria horas e horas de duração
    # Assim usei uma fórmula que me parece correta
    return bpm * 44100 / 60  # devolve a framerate para utilizar no ficheiro

# @argumentos -> música, sample_rate (framerate), duração do efeito
# @return -> música com o efeito de Fade In

def fadeInSong(song, sample_rate, duration):
    new_song = []
    duration = float(duration)
    time_start = 0
    time_stop = duration * sample_rate
    step = 1.0 / (sample_rate * duration)
    for index, value in enumerate(song):
        time = index
        if time > time_start and time < time_stop:
            # usar o int para não dar erro de conversão com os outos valores
            new_song.append(value * index * int(step))
        else:
            new_song.append(value)

    return new_song  # devolver nova música com fade-in

# @argumentos -> música, sample_rate (framerate), duração do efeito
# @return -> música com o efeito de Fade out

def fadeOutSong(song, sample_rate, duration):
    new_song = []
    sample_rate = float(sample_rate)
    duration = float(duration)
    index = 0
    time_start = index - (duration * sample_rate)
    time_stop = index
    step = 1.0 / (sample_rate * duration)

    for index2, value in enumerate(song):
        time = index2
        if(time > time_start and time < time_stop):
            new_song.append(value * (index - index2) * step)
        else:
            new_song.append(value)

    return new_song  # devolver nova música com fade-out

# @argumentos -> música
# @return -> música invertida

def reverseSong(song):
    new_song = []
    # reverse() inverte a ordem dos valores, com base no índice
    for value in reversed(song):
        new_song.append(value)
    return new_song  # devolver a música invertida

# @argumentos -> música e novo volume
# @return -> música com o volume ajustado

def volumeSong(song, new_vol):
    # Para controlar o volume basta multiplicar todos os valores de amplitude por um factor
    # multiplicativo. Se este factor for 0.5 o volume deverá ser diminuído em metade. Se for
    # 2.0 o volume deverá ser multiplicado por 2
    new_song = []
    factor = float(new_vol)

    for index, value in enumerate(song):
        # usei o int, para não existirem erros de conversão com os valores
        new_song.append(value * int(factor))

    return new_song  # volume da música alterado

# @argumentos -> música
# @return -> música com o volume normalizado

def normalizeSong(data):  # Não está a funcionar corretamente
    new_song = []
    val_max = 32767
    max = 0

    for index, value in enumerate(data):
        if(abs(value) > max):
            max = abs(value)

    new_song = volumeSong(data, val_max / max)

    return new_song  # devolve a música normalizada

# @argumentos -> Musica, sample_rate (framerate), tipo de máscara, começo, duração
# @return -> Música com a máscara aplicada

def maskSong(song, sample_rate, type, start, duration):
    new_song = []
    start = float(start) * sample_rate
    duration = float(duration) * sample_rate
    end = start + duration

    for index, value in enumerate(song):
        # antes estava index > start, mas isso nunca aconteceria e os filtros nunca eram aplicados,
        #  pois o start seria, i.e 2 * 44100 = 88200. e o index, vai de 0...11.. nunca chegaria a esse valor
        if index < start and index < end:
            if(type == 'silence'):
                new_song.append(0)
            elif(type == 'noise'):
                new_song.append(random.randint(-32768, 32767))
            elif(type == 'tone'):
                new_song.append(
                    10000*math.sin(2 * math.pi * 440 * index / sample_rate))
            else:
                new_song.append(value)
        else:
            new_song.append(value)

    return new_song

# Aplicar uma modulação (multiplicar um som por outro)
# @argumentos -> Musica, sample_rate (Framerate), frequência
# @return -> Música alterada

def modulateSong(song, sample_rate, freq):  # Não está a funcionar corretamente
    new_song = []
    freq = int(freq)
    for index, value in enumerate(song):
        # adicionei o int, pois estava a ter erros de operação com outras variáveis
        new_song.append(value * math.sin(2 * math.pi *
                                         freq * index / int(sample_rate)))

    return new_song  # devolver a música modulada

# @argumentos -> Musica, sample_rate (framerate), quantidade, tempo de delay (atraso)
# @return -> Musica com delay

def delaySong(song, sample_rate, amount, delay):
    amount = float(amount)
    delay = float(delay)

    new_song = [0] * len(song)

    tdelay = delay * sample_rate

    for index, value in enumerate(song):
        if index + int(tdelay) < len(new_song):
            new_song[index] = value
            new_song[index + int(tdelay)] += value * amount
        else:
            new_song[index] = value

    return new_song  # devolve Música com um atraso (delay) aplicado

# Aplicar os efeitos na música
# @argumentos -> Música, bpm (framerate), efeito escolhido
# @return -> Música com o efeito aplicado

def effectsSong(data, bpm, effects):
    if effects == "fadein":  # efeito de Fade In
        data = fadeInSong(data, bpm, 2)
    elif effects == "reverse":  # reverter a música
        data = reverseSong(data)
    elif effects == "normalize":  # normalizar o volume da música
        data = normalizeSong(data)  # Não funciona corretamente
    # Aplicar uma modulação (multiplicar um som por outro)
    elif effects == "modulate":
        data = modulateSong(data, bpm, 441)  # Não funciona corretamente
    elif effects == "delay":  # Introduzir um delay à música
        data = delaySong(data, bpm, 5, 2)
    elif effects == "fadeout":  # efeito de Fade Out
        data = fadeOutSong(data, bpm, 2)
    else:
        print("Effect doesn't exist")

    return data

# @argumentos -> dicionário com informação da música a ser criada
# @return -> lista com pos 0 True ou False, se a música for criada ou não
#         -> pos 1, informação de sucesso e erro, caso algum exista
#         -> i.e [True, "Song generated"] ou [False, "The provided path doesn't exists"]

def createSong(dictionary):
    # dictionary["samples"][i] access each sample
    # certificar que todas as samples existem
    for sample in dictionary["samples"]:
        status = checkSong(sample)
        if(not status[0]):  # verificar que não houve um erro
            print([status[0], status[1]])
            return [status[0], status[1]]  # se houver um erro, devolver

    # verificar a lista das musicas com as samples fornecidas
    for music in dictionary["music"]:
        for pos in music:
            if pos >= len(dictionary["samples"]):
                print([False, "Music indexes and samples provided do not match"])
                return [False, "Music indexes and samples provided do not match"]

    data = []
    # Percorrer o dicionário das músicas
    for i, music in enumerate(dictionary["music"]):
        if len(music) == 1:  # se não for preciso combinar músicas, apenas se acrescenta ao dicionário
            sample = dictionary["samples"][music[0]]
            w = wave.open(sample, 'rb')
            params = w.getparams()  # Obter os parâmetros do excerto
            dataTemp = w.readframes(w.getnframes())  # Ler o excerto
            # Percorrer a lista de efeitos, para determinar se existe algum
            if i in dictionary["effects"]:
                # alterar os dados lidos para o excerto com o efeito aplicado
                dataTemp = bytes(effectsSong(dataTemp, calculateFramerate(
                    dictionary["bpm"]), dictionary["effects"][i]))
            data.append([params, dataTemp])  # guardar os dados na lista
            w.close()  # fechar o excerto
        elif len(music) > 1:  # se houver mais do que uma música no índice da lista de ficheiros, vamos sobrepô-las
            overlay = b''  # inicializar a variável
            # percorrer as músicas presentes no índice
            for l, pos in enumerate(music):
                sample = dictionary["samples"][pos]
                # overlay the samples
                w = wave.open(sample, 'rb')
                params = w.getparams()  # Obter os parâmetros do excerto
                dataTemp = w.readframes(w.getnframes())  # Ler o excerto
                # Percorrer a lista de efeitos, para determinar se existe algum
                if i in dictionary["effects"]:
                    # alterar os dados lidos para o excerto com o efeito aplicado
                    overlay += bytes(effectsSong(dataTemp, calculateFramerate(
                        dictionary["bpm"]), dictionary["effects"][i]))
                else:
                    overlay += dataTemp  # copiar o excerto normal

            data.append([params, overlay])  # guardar os dados na lista
        else:
            data.append([0, bytes(0)])  # Adicionar troço de silêncio

    # Ajustar o volume
    data = volumeSong(data, int(dictionary["volume"]) / 5)

    # Adicionar Máscara, caso seje especificado
    if dictionary["mask"] != "none":
        data[0:][1] = maskSong(data, calculateFramerate(
            dictionary["bpm"]), dictionary["mask"], 2, 5)

    # sample files are saved in dictionary["samples"]

    # Indices - Valores lista data[0][0]
    # 0 - nchannels
    # 1 - sampwidth
    # 2 - framerate (song pace)
    # 3 - nframes
    # 4 - comptype
    # 5 - compname
    # print(data[0][0]) # Mostrar a informação do ficheiro original DEBUG
    # print("Output Framerate : " + str(calculateFramerate(dictionary["bpm"]))) # Mostrar a frequência do ficheiro de saída DEBUG

    # abrir / criar o ficheiro output da música
    output = wave.open(dictionary["id"], 'wb')
    # Escrever os parâmetros do ficheiro original no ficheiro de saída
    output.setparams(data[0][0])
    # Alterar a framerate do ficheiro, tendo em conta os bpm fornecidos
    output.setframerate(calculateFramerate(dictionary["bpm"]))
    for i in range(len(data)):  # percorrer a música gerada
        output.writeframes(data[i][1])  # escrever no ficheiro de saída
    output.close()  # fechar o ficheiro de saída

    print([True, "Song generated"])
    # devolver que todas as operações correram com sucesso
    return [True, "Song generated"]

createSong(dic)  # DEBUG


'''A minesweeper solver, as presented in https://www.reddit.com/r/dailyprogrammer/comments/50s3ax/20160902_challenge_281_hard_minesweeper_solver/'''

def test():
    MS = Minesweeper()
    MS.add_mines((0, 1), (2, 0))
    MS.reveal((1, 1))
    MS.reveal((0, 1))
    MS.reveal((0, 0))
    print(MS.draw())

class Tile:
    def __init__(self, pos, has_mine=False):
        self.x, self.y = pos
        self.has_mine = has_mine
        self.known = False

    def __repr__(self):
        return "<Tile>"

    def as_char(self, ms):
        if not self.known:
            return "?"
        elif self.has_mine:
            return "X"
        else:
            neighbors = [(self.x + i, self.y + j)
                         for i in (-1, 0, 1)
                         for j in (-1, 0, 1)
                         if not i == j == 0
                         and 0 <= self.x + i < ms.x
                         and 0 <= self.y + j < ms.y]
            #print(list(neighbors))
            count = 0
            for n in neighbors:
                #print(n)
                #print(ms.board[n].has_mine)
                if ms.board[n].has_mine:
                    count += 1
            if count == 0:
                for n in neighbors:
                    print(n)
                    ms.reveal(n)

            return str(count) if count else " "

class Minesweeper:
    def __init__(self, size=(10,10), mines=()):
        self.x, self.y = size
        self.board = {(i, j) : Tile((i, j))
                      for i in range(size[0])
                      for j in range(size[1])}
        for m in mines:
            self.board[m].has_mine = True

    def __repr__(self):
        return "<Minesweeper>"

    def add_mines(self, *args):
        for pos in args:
            self.board[pos].has_mine = True

    def reveal(self, pos):
        self.board[pos].known = True

    def reveal_all(self):
        for t in self.board.values():
            t.known = True

    def draw(self):
        return "\n".join(
            "".join(
                self.board[(i, j)].as_char(self) for i in range(self.x)
            ) for j in range(self.y))


# coding=utf-8
from django import template
from django.utils.log import getLogger
from django.conf import settings

import time
import qrcode
import StringIO
import bleach

ALLOWED_NOTE_TAGS = []

register = template.Library()
log = getLogger('django')
image_host = getattr(settings, 'IMAGE_HOST', None)

def enumerate_list(value):
    return enumerate(value)

register.filter(enumerate_list)

def smart_scheme(value, is_secure=False):
    if is_secure and 'guoku.com' in value:
        value = value.replace('http://', 'https://')
    return value

register.filter(smart_scheme)

def safe_note(value):
    return bleach.clean(value, tags=ALLOWED_NOTE_TAGS)

register.filter(safe_note)

def https_image_cdn(value):
    http_host = settings.IMAGE_HOST
    https_host = http_host.replace('http://', 'https://')
    value = value.replace(http_host, https_host)
    return value.replace(http_host, https_host)

register.filter(https_image_cdn)

def oss_resize(url, size=None):
    if all([url, size]):
        if 'taobaocdn.com' in url or 'alicdn.com' in url:
            # 淘宝地址，修改到淘宝规则的地址
            url = '{url}_{size}x{size}.jpg'.format(url=url, size=size)

        elif image_host in url:
            # CDN地址，修改到阿里云规则的地址
            url = '{value}/{size}'.format(value=url, size=size)

    url = url.replace('//images', '/images') if url else url
    return url

register.filter(oss_resize)

def resize(value, size=None):
    host = image_host
    if value is None:
        return value

    if 'taobaocdn.com' in value or 'alicdn.com' in value:
        value = value + '_' + size + 'x' + size + '.jpg'
        return value

    if 'guoku.com/static' in value:
        return value

    if host not in value:
        return value

    if size:
        if host in value:
            uri = value.replace(host, '')
            params = uri.split('/')
            params.insert(1, str(size))
            uri_string = '/'.join(params)
            return host + uri_string

    value = value.replace('//images', '/images')
    return value

register.filter(resize)

def show_category(value):
    title = value.split('-')
    return title[0]

register.filter(show_category)

def timestamp(value):
    return time.mktime(value.timetuple())

register.filter('timestamp', timestamp)

def filter_builder(filter_name, filter_value):
    return '%s=%s' % (filter_name, filter_value)

register.filter('filter_builder', filter_builder)

def entity_qr(value):
    url = "%s%s" % ('http://www.guoku.com', value)
    qr = qrcode.QRCode(
        version=2,
        error_correction=qrcode.constants.ERROR_CORRECT_H,
        box_size=2,
        border=1,
    )
    qr.add_data(url)
    img = qr.make_image()
    output = StringIO.StringIO()
    img.save(output)
    content = output.getvalue()
    output.close()
    return content.encode('base64').replace("\n", "")

register.filter(entity_qr)

def tbsearch_url(word):
    return 'https://s.taobao.com/search?q=%s' % word

register.filter(tbsearch_url)


import turtle
import pandas as pd

IMAGE = "blank_states_img.gif"
data = pd.read_csv("50_states.csv")
screen = turtle.Screen()
screen.title("U.S. States Game")

screen.addshape(IMAGE)
turtle.shape(IMAGE)
all_states = data.state.tolist()
print(all_states)

states_guessed = []

while len(states_guessed) < 50:

    answer_state = (screen.textinput(title=f"{len(states_guessed)}/50 States Correct", prompt="What's the name of the state?")).title()
    if answer_state in all_states:
        states_guessed.append(answer_state)
        t = turtle.Turtle()
        t.hideturtle()
        t.penup()
        state_data = data[data.state == answer_state]
        t.goto(int(state_data.x), int(state_data.y))
        t.write(answer_state)

    elif answer_state == 'Exit':
        missing = [state for state in all_states if state not in states_guessed]
        missing_states = pd.DataFrame(missing)
        missing_states.to_csv("states_to_learn.csv")
        break


from oslo_versionedobjects import base
from oslo_versionedobjects import fields

from heat.db import api as db_api
from heat.objects import fields as heat_fields

class WatchData(base.VersionedObject, base.VersionedObjectDictCompat):

    fields = {
        'id': fields.IntegerField(),
        'data': heat_fields.JsonField(nullable=True),
        'watch_rule_id': fields.StringField(),
        'watch_rule': fields.ObjectField('WatchRule'),
        'created_at': fields.DateTimeField(read_only=True),
        'updated_at': fields.DateTimeField(nullable=True),
    }

    @staticmethod
    def _from_db_object(context, rule, db_data):
        from heat.objects import watch_rule
        for field in rule.fields:
            if field == 'watch_rule':
                rule[field] = watch_rule.WatchRule._from_db_object(
                    context,
                    watch_rule.WatchRule(),
                    db_data['watch_rule'])
            else:
                rule[field] = db_data[field]
        rule._context = context
        rule.obj_reset_changes()
        return rule

    @classmethod
    def create(cls, context, values):
        db_data = db_api.watch_data_create(context, values)
        return cls._from_db_object(context, cls(), db_data)

    @classmethod
    def get_all(cls, context):
        return [cls._from_db_object(context, cls(), db_data)
                for db_data in db_api.watch_data_get_all(context)]

    @classmethod
    def get_all_by_watch_rule_id(cls, context, watch_rule_id):
        return (cls._from_db_object(context, cls(), db_data)
                for db_data in db_api.watch_data_get_all_by_watch_rule_id(
                    context, watch_rule_id))


# %%
import requests
import json
import os

from functools import lru_cache

# API constants, you shouldn't have to change these.
# API_KEY = os.environ["RAKUTEN_API_KEY"]
API_KEY = os.environ['RAKUTEN_API_KEY']
API_HOST = "https://us-restaurant-menus.p.rapidapi.com"
SEARCH_PATH = "/restaurants/search/geo"
DEFAULT_LOCATION = [38.898689814814816, -77.03749537037038]

def request(host, path, api_key, url_params=None):
    """Given your API_KEY, send a GET request to the API.

    Args:
        host (str): The domain host of the API.
        path (str): The path of the API after the domain.
        API_KEY (str): Your API Key.
        url_params (dict): An optional set of query parameters in the request.

    Returns:
        dict: The JSON response from the request.

    Raises:
        HTTPError: An error occurs from the HTTP request.
    """
    url_params = url_params or {}
    url = '{0}{1}'.format(host, path)
    headers = {
        'x-rapidapi-host': "us-restaurant-menus.p.rapidapi.com",
        'x-rapidapi-key': api_key,
    }

    print(u'Querying {0} ...'.format(url))

    response = requests.request('GET', url, headers=headers, params=url_params)

    data = json.loads(response.text)
    if 'error' in data:
        raise Exception(str(data))
    return data

def search(location=DEFAULT_LOCATION, api_key=API_KEY):
    """Given location, get all nearby (whitin 5 mile) restaurants

    Args:
        location (list): geological location of user in the form of [lat, lon].

    Returns:
        dict: JSON response containing information of nearby resturants.
    """
    latitude, longtitude = location[0], location[1]
    url_params = {"page": "1", "lon": longtitude, "lat": latitude, "distance": "5"}

    return request(API_HOST, SEARCH_PATH, api_key, url_params=url_params)['result']['data']

@lru_cache()
def get_menus(id, api_key=API_KEY):
    """Given restaurants id, get menu items of the resturant.

    Args:
        id (int): id of the resturant.

    Returns:
        dict: JSON response containing menu infos of the restaurant.
    """
    path = "/restaurant/" + str(id) + "/menuitems"

    return request(API_HOST, path, api_key, url_params=None)['result']['data']

# def get_ids_from_resonse(response_info_json):
#     # get 25 resturant ids from above response
#     if 'result' in response_info_json:
#         restaurants_data_list = response_info_json['result']['data']
#         ids = map(lambda x: x['restaurant_id'], restaurants_data_list)
#         return list(ids)
#     else:
#         return []

# def get_restaurant_menu_items_from_ids(ids):
#     # for each id get its menu items string
#     menu_items = []
#     for id in ids:
#         response_menu_json = get_menus(id)

#         # bonding all menu_item_name to form a description of the restaurant
#         menu_item_string = ""
#         if 'result' in response_menu_json:
#             for menu_item in response_menu_json['result']['data']:
#                 menu_item_name = menu_item['menu_item_name']
#                 menu_item_string += " " + menu_item_name

#         menu_items.append(menu_items_string)

#     return menu_items

def main():
    data = search()
    print(sorted([restaurant['restaurant_name'] for restaurant in data]))

if __name__ == '__main__':
    main()


# python plot.py
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-5, 5, 100)  # xの範囲を設定
y1 = x**2 - 1
y2 = -x**2 + 1

plt.plot(x, y1, label='Quadratic Curve 1')
plt.plot(x, y2, label='Quadratic Curve 2')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Quadratic Curve')
plt.legend()
plt.grid(True)
plt.show()


from tkinter import *
from tkinter import messagebox

def click_me():
    if i.get() == 0:
        messagebox.showinfo("Result", "Male")
    else:
        messagebox.showinfo("Result", "Female")

root = Tk()

i = IntVar()
radio1 = Radiobutton(root, text="male", value=0, variable=i)
radio2 = Radiobutton(root, text="female", value=1, variable=i)
b = Button(root, text='Ok', command=click_me)
radio1.pack()
radio2.pack()
b.pack()
root.mainloop()


def Sum_to_n(n):
    answer = 0
    for i in range(1, n+1):
        answer = answer + i
        if(answer <= 1):
            print("First number is:", answer)
        else:
            print("First", i, "numbers sums up to: ")
            print(answer)

Sum_to_n(int(input("Enter n numbers to sum up to: ")))