from typing import Optional, Tuple, List, Union

from ovos_bus_client.client import MessageBusClient
from ovos_plugin_common_play.ocp import OCP_ID
from ovos_plugin_common_play.ocp.status import *
from ovos_plugin_common_play.ocp.utils import ocp_plugins, find_mime
from ovos_utils.json_helper import merge_dict
from ovos_utils.log import LOG
from ovos_utils.messagebus import Message
from os.path import join, dirname
from dbus_next.service import Variant

# TODO subclass from dict (?)
class MediaEntry:
    def __init__(self, title="", uri="", skill_id=OCP_ID,
                 image=None, match_confidence=0,
                 playback=PlaybackType.UNDEFINED,
                 status=TrackState.DISAMBIGUATION, phrase=None,
                 position=0, length=None, bg_image=None, skill_icon=None,
                 artist=None, is_cps=False, cps_data=None, javascript="",
                 **kwargs):
        self.match_confidence = match_confidence
        self.title = title
        uri = uri or ""  # handle None
        self.uri = f'file://{uri}' if uri.startswith('/') else uri
        self.artist = artist
        self.skill_id = skill_id
        self.status = status
        self.playback = PlaybackType(playback) if isinstance(playback, int) \
            else playback
        self.image = image or join(dirname(__file__),
                                   "res/ui/images/ocp_bg.png")
        self.position = position
        self.phrase = phrase
        self.length = length  # None -> live stream
        self.skill_icon = skill_icon or join(dirname(__file__),
                                             "res/ui/images/ocp.png")
        self.bg_image = bg_image or join(dirname(__file__),
                                         "res/ui/images/ocp_bg.png")
        self.is_cps = is_cps
        self.data = kwargs
        self.cps_data = cps_data or {}
        self.javascript = javascript  # custom code to run in Webview after page load

    def update(self, entry: dict, skipkeys: list = None, newonly: bool = False):
        """
        Update this MediaEntry object with keys from the provided entry
        @param entry: dict or MediaEntry object to update this object with
        @param skipkeys: list of keys to not change
        @param newonly: if True, only adds new keys; existing keys are unchanged
        """
        skipkeys = skipkeys or []
        if isinstance(entry, MediaEntry):
            entry = entry.as_dict
        entry = entry or {}
        for k, v in entry.items():
            if k not in skipkeys and hasattr(self, k):
                if newonly and self.__getattribute__(k):
                    # skip, do not replace existing values
                    continue
                self.__setattr__(k, v)

    @staticmethod
    def from_dict(data: dict):
        """
        Construct a `MediaEntry` object from dict data.
        @param data: dict information to build the `MediaEntry` for
        @return: MediaEntry object
        """
        if data.get("bg_image") and data["bg_image"].startswith("/"):
            data["bg_image"] = "file:/" + data["bg_image"]
        data["skill"] = data.get("skill_id") or OCP_ID
        data["position"] = data.get("position", 0)
        data["length"] = data.get("length") or \
                         data.get("track_length") or \
                         data.get("duration")  # or get_duration_from_url(url)
        data["skill_icon"] = data.get("skill_icon") or data.get("skill_logo")
        data["status"] = data.get("status") or TrackState.DISAMBIGUATION
        data["playback"] = data.get("playback", PlaybackType.UNDEFINED)
        data["uri"] = data.get("stream") or data.get("uri") or data.get("url")
        data["title"] = data.get("title") or data["uri"]
        data["artist"] = data.get("artist") or data.get("author")
        data["is_cps"] = data.get("is_old_style") or data.get("is_cps", False)
        data["cps_data"] = data.get("cps_data") or {}
        return MediaEntry(**data)

    @property
    def info(self) -> dict:
        """
        Return a dict representation of this MediaEntry + infocard for QML model
        """
        return merge_dict(self.as_dict, self.infocard)

    @property
    def infocard(self) -> dict:
        """
        Return dict data used for a UI display
        """
        return {
            "duration": self.length,
            "track": self.title,
            "image": self.image,
            "album": self.skill_id,
            "source": self.skill_icon,
            "uri": self.uri
        }

    @property
    def mpris_metadata(self) -> dict:
        """
        Return dict data used by MPRIS
        """
        meta = {"xesam:url": Variant('s', self.uri)}
        if self.artist:
            meta['xesam:artist'] = Variant('as', [self.artist])
        if self.title:
            meta['xesam:title'] = Variant('s', self.title)
        if self.image:
            meta['mpris:artUrl'] = Variant('s', self.image)
        if self.length:
            meta['mpris:length'] = Variant('d', self.length)
        return meta

    @property
    def as_dict(self) -> dict:
        """
        Return a dict reporesentation of this MediaEntry
        """
        return {k: v for k, v in self.__dict__.items()
                if not k.startswith("_")}

    @property
    def mimetype(self) -> Optional[Tuple[Optional[str], Optional[str]]]:
        """
        Get the detected mimetype tuple (type, encoding) if it can be determined
        """
        if self.uri:
            return find_mime(self.uri)

    def __eq__(self, other):
        if isinstance(other, MediaEntry):
            other = other.infocard
        # dict compatison
        return other == self.infocard

    def __repr__(self):
        return str(self.as_dict)

    def __str__(self):
        return str(self.as_dict)

class Playlist(list):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._position = 0

    @property
    def position(self) -> int:
        """
        Return the current position in the playlist
        """
        return self._position

    @property
    def entries(self) -> List[MediaEntry]:
        """
        Return a list of MediaEntry objects in the playlist
        """
        entries = []
        for e in self:
            if isinstance(e, dict):
                e = MediaEntry.from_dict(e)
            if isinstance(e, MediaEntry):
                entries.append(e)
        return entries

    @property
    def current_track(self) -> Optional[MediaEntry]:
        """
        Return the current MediaEntry or None if the playlist is empty
        """
        if len(self) == 0:
            return None
        self._validate_position()
        track = self[self.position]
        if isinstance(track, dict):
            track = MediaEntry.from_dict(track)
        return track

    @property
    def is_first_track(self) -> bool:
        """
        Return `True` if the current position is the first track or if the
        playlist is empty
        """
        if len(self) == 0:
            return True
        return self.position == 0

    @property
    def is_last_track(self) -> bool:
        """
        Return `True` if the current position is the last track of if the
        playlist is empty
        """
        if len(self) == 0:
            return True
        return self.position == len(self) - 1

    def goto_start(self) -> None:
        """
        Move to the first entry in the playlist
        """
        self._position = 0

    def clear(self) -> None:
        """
        Remove all entries from the Playlist and reset the position
        """
        super(Playlist, self).clear()
        self._position = 0

    def sort_by_conf(self):
        """
        Sort the Playlist by `match_confidence` with high confidence first
        """
        self.sort(key=lambda k: k.match_confidence
                  if isinstance(k, MediaEntry) else
                  k.get("match_confidence", 0), reverse=True)

    def add_entry(self, entry: MediaEntry, index: int = -1) -> None:
        """
        Add an entry at the requested index
        @param entry: MediaEntry to add to playlist
        @param index: index to insert entry at (default -1 to append)
        """
        assert isinstance(index, int)
        # TODO: Handle index out of range
        if isinstance(entry, dict):
            entry = MediaEntry.from_dict(entry)
        assert isinstance(entry, MediaEntry)
        if index == -1:
            index = len(self)

        if index < self.position:
            self.set_position(self.position + 1)

        self.insert(index, entry)

    def remove_entry(self, entry: Union[int, dict, MediaEntry]) -> None:
        """
        Remove the requested entry from the playlist or raise a ValueError
        @param entry: index or MediaEntry to remove from the playlist
        """
        if isinstance(entry, int):
            self.pop(entry)
            return
        if isinstance(entry, dict):
            entry = MediaEntry.from_dict(entry)
        assert isinstance(entry, MediaEntry)
        for idx, e in self.entries:
            if e == entry:
                self.pop(idx)
                break
        else:
            raise ValueError(f"entry not in playlist: {entry}")

    def replace(self, new_list: List[Union[dict, MediaEntry]]) -> None:
        """
        Replace the contents of this Playlist with new_list
        @param new_list: list of MediaEntry or dict objects to set this list to
        """
        self.clear()
        for e in new_list:
            self.add_entry(e)

    def set_position(self, idx: int):
        """
        Set the position in the playlist to a specific index
        @param idx: Index to set position to
        """
        self._position = idx
        self._validate_position()

    def goto_track(self, track: Union[MediaEntry, dict]) -> None:
        """
        Go to the requested track in the playlist
        @param track: MediaEntry to find and go to in the playlist
        """
        if isinstance(track, MediaEntry):
            requested_uri = track.uri
        else:
            requested_uri = track.get("uri", "")
        for idx, t in enumerate(self):
            if isinstance(t, MediaEntry):
                pl_entry_uri = t.uri
            else:
                pl_entry_uri = t.get("uri", "")
            if requested_uri == pl_entry_uri:
                self.set_position(idx)
                LOG.debug(f"New playlist position: {self.position}")
                return
        LOG.error(f"requested track not in the playlist: {track}")

    def next_track(self) -> None:
        """
        Go to the next track in the playlist
        """
        self.set_position(self.position + 1)

    def prev_track(self) -> None:
        """
        Go to the previous track in the playlist
        """
        self.set_position(self.position - 1)

    def _validate_position(self) -> None:
        """
        Make sure the current position is valid; default `position` to 0
        """
        if self.position < 0 or self.position >= len(self):
            LOG.error(f"Playlist pointer is in an invalid position "
                      f"({self.position}! Going to start of playlist")
            self._position = 0

    def __contains__(self, item):
        if isinstance(item, dict):
            item = MediaEntry.from_dict(item)
        if not isinstance(item, MediaEntry):
            return False
        for e in self.entries:
            if not e.uri and e.data.get("playlist"):
                if e.title == item.title and not item.uri:
                    return True
                # track in playlist
                for t in e.data["playlist"]:
                    if t.get("uri") == item.uri:
                        return True
            elif e.uri == item.uri:
                return True
        return False

class NowPlaying(MediaEntry):
    def __init__(self, *args, **kwargs):
        MediaEntry.__init__(self, *args, **kwargs)
        self._player = None

    @property
    def bus(self) -> MessageBusClient:
        """
        Return the MessageBusClient inherited from the bound OCPMediaPlayer
        """
        return self._player.bus

    @property
    def _settings(self) -> dict:
        """
        Return the dict settings inherited from the bound OCPMediaPlayer
        """
        return self._player.settings

    def as_entry(self) -> MediaEntry:
        """
        Return a MediaEntry representation of this object
        """
        return MediaEntry.from_dict(self.as_dict)

    def bind(self, player):
        """
        Bind an OCPMediaPlayer object to this NowPlaying instance. Registers
        messagebus event handlers and defines `self._player`
        @param player: OCPMediaPlayer instance to bind
        """
        # needs to start with _ to avoid json serialization errors
        self._player = player
        self._player.add_event("ovos.common_play.track.state",
                               self.handle_track_state_change)
        self._player.add_event("ovos.common_play.media.state",
                               self.handle_media_state_change)
        self._player.add_event("ovos.common_play.play",
                               self.handle_external_play)
        self._player.add_event("ovos.common_play.playback_time",
                               self.handle_sync_seekbar)
        self._player.add_event('gui.player.media.service.get.meta',
                               self.handle_player_metadata_request)
        self._player.add_event('mycroft.audio.service.track_info_reply',
                               self.handle_sync_trackinfo)
        self._player.add_event('mycroft.audio.service.play',
                               self.handle_audio_service_play)
        self._player.add_event('mycroft.audio.playing_track',
                               self.handle_audio_service_play_start)

    def shutdown(self):
        """
        Remove NowPlaying events from the MessageBusClient
        """
        self._player.remove_event("ovos.common_play.track.state")
        self._player.remove_event("ovos.common_play.playback_time")
        self._player.remove_event('gui.player.media.service.get.meta')
        self._player.remove_event('mycroft.audio_only.service.track_info_reply')

    def reset(self):
        """
        Reset the NowPlaying MediaEntry to default parameters
        """
        LOG.debug("Resetting NowPlaying")
        self.title = ""
        self.artist = None
        self.skill_icon = None
        self.skill_id = None
        self.position = 0
        self.length = None
        self.is_cps = False
        self.cps_data = {}
        self.data = {}
        self.phrase = None
        self.javascript = ""
        self.playback = PlaybackType.UNDEFINED
        self.status = TrackState.DISAMBIGUATION

    def update(self, entry: dict, skipkeys: list = None, newonly: bool = False):
        """
        Update this MediaEntry and emit `gui.player.media.service.set.meta`
        @param entry: dict or MediaEntry object to update this object with
        @param skipkeys: list of keys to not change
        @param newonly: if True, only adds new keys; existing keys are unchanged
        """
        if isinstance(entry, MediaEntry):
            entry = entry.as_dict
        super().update(entry, skipkeys, newonly)
        # uri updates should not be skipped
        if newonly and entry.get("uri"):
            super().update({"uri": entry["uri"]})
        # sync with gui media player on track change
        if not self._player:
            LOG.error("Instance not bound! Call `bind` before trying to use "
                      "the messagebus.")
            return
        self.bus.emit(Message("gui.player.media.service.set.meta",
                              {"title": self.title,
                               "image": self.image,
                               "artist": self.artist}))

    def extract_stream(self):
        """
        Get metadata from ocp_plugins and add it to this MediaEntry
        """
        uri = self.uri
        if not uri:
            raise ValueError("No URI to extract stream from")
        if self.playback == PlaybackType.VIDEO:
            video = True
        else:
            video = False
        meta = ocp_plugins.extract_stream(uri, video)
        # update media entry with new data
        if meta:
            LOG.info(f"OCP plugins metadata: {meta}")
            self.update(meta, newonly=True)
        elif not any((uri.startswith(s) for s in ["http", "file", "/"])):
            LOG.info(f"OCP WARNING: plugins returned no metadata for uri {uri}")

    # events from gui_player/audio_service
    def handle_external_play(self, message):
        """
        Handle 'ovos.common_play.play' Messages. Update the metadata with new
        data received unconditionally, otherwise previous song keys might
        bleed into the new track
        @param message: Message associated with request
        """
        if message.data.get("tracks"):
            # backwards compat / old style
            playlist = message.data["tracks"]
            media = playlist[0]
        else:
            media = message.data.get("media", {})
        if media:
            self.update(media, newonly=False)

    def handle_player_metadata_request(self, message):
        """
        Handle 'gui.player.media.service.get.meta' Messages. Emit a response for
        the GUI to handle new metadata.
        @param message: Message associated with request
        """
        self.bus.emit(message.reply("gui.player.media.service.set.meta",
                                    {"title": self.title,
                                     "image": self.image,
                                     "artist": self.artist}))

    def handle_track_state_change(self, message):
        """
        Handle 'ovos.common_play.track.state' Messages. Update status
        @param message: Message with updated `state` data
        @return:
        """
        state = message.data.get("state")
        if state is None:
            raise ValueError(f"Got state update message with no state: "
                             f"{message}")
        if isinstance(state, int):
            state = TrackState(state)
        if not isinstance(state, TrackState):
            raise ValueError(f"Expected int or TrackState, but got: {state}")

        if state == self.status:
            return
        self.status = state
        LOG.info(f"TrackState changed: {repr(state)}")

        if state == TrackState.PLAYING_SKILL:
            # skill is handling playback internally
            pass
        elif state == TrackState.PLAYING_AUDIOSERVICE:
            # audio service is handling playback
            pass
        elif state == TrackState.PLAYING_VIDEO:
            # ovos common play is handling playback in GUI
            pass
        elif state == TrackState.PLAYING_AUDIO:
            # ovos common play is handling playback in GUI
            pass

        elif state == TrackState.DISAMBIGUATION:
            # alternative results # TODO its this 1 track or a list ?
            pass
        elif state in [TrackState.QUEUED_SKILL,
                        TrackState.QUEUED_VIDEO,
                        TrackState.QUEUED_AUDIOSERVICE]:
            # audio service is handling playback and this is in playlist
            pass

    def handle_media_state_change(self, message):
        """
        Handle 'ovos.common_play.media.state' Messages. If ended, reset.
        @param message: Message with updated MediaState
        """
        state = message.data.get("state")
        if state is None:
            raise ValueError(f"Got state update message with no state: "
                             f"{message}")
        if isinstance(state, int):
            state = MediaState(state)
        if not isinstance(state, MediaState):
            raise ValueError(f"Expected int or TrackState, but got: {state}")
        # Don't do anything. Let OCP manage this object's state
        # if state == MediaState.END_OF_MEDIA:
        #     # playback ended, allow next track to change metadata again
        #     self.reset()

    def handle_sync_seekbar(self, message):
        """
        Handle 'ovos.common_play.playback_time' Messages sent by audio backend
        @param message: Message with 'length' and 'position' data
        """
        self.length = message.data["length"]
        self.position = message.data["position"]

    def handle_sync_trackinfo(self, message):
        """
        Handle 'mycroft.audio.service.track_info_reply' Messages with current
        media defined in message.data
        @param message: Message with dict MediaEntry data
        """
        self.update(message.data)

    def handle_audio_service_play(self, message):
        """
        Handle 'mycroft.audio.service.play' Messages with list of tracks in data
        @param message: Message with 'tracks' data
        """
        tracks = message.data.get("tracks") or []
        # only present in ovos-core
        skill_id = message.context.get("skill_id") or 'mycroft.audio_interface'
        for idx, track in enumerate(tracks):
            # TODO try to extract metadata from uri (latency ?)
            if idx == 0:
                self.update(
                    {"uri": track,
                     "title": track.split("/")[-1],
                     "status": TrackState.QUEUED_AUDIOSERVICE,
                     'skill_id': skill_id,
                     "playback": PlaybackType.AUDIO_SERVICE}
                )
            else:
                # TODO sync playlist ?
                pass

    def handle_audio_service_play_start(self, message):
        """
        Handle 'mycroft.audio.playing_track' Messages
        @param message: Message notifying playback has started
        """
        self.update(
            {"status": TrackState.PLAYING_AUDIOSERVICE,
             "playback": PlaybackType.AUDIO_SERVICE})


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('catalog', '0002_product_product_price'),
    ]

    operations = [
        migrations.CreateModel(
            name='Agent',
            fields=[
                ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),
                ('agent_first_name', models.CharField(verbose_name='First Name', max_length=200, default='John')),
                ('agent_last_name', models.CharField(verbose_name='Last Name', max_length=200, default='Smith')),
            ],
        ),
        migrations.AlterField(
            model_name='product',
            name='product_name',
            field=models.CharField(verbose_name='Product Name', max_length=200, default='product name'),
        ),
    ]


#!/usr/bin/env python

def quicksort(array, first, last):
  beginning = first
  end = last
  pivot = array[end]
  last -= 1

  while first < last:
    while array[first] <= pivot and first < end:
      first += 1
    while array[last] >= pivot and beginning < last:
      last -= 1

    tmp = array[first]
    array[first] = array[last]
    array[last] = tmp

  array[end] = array[last]
  array[last] = pivot

  quicksort(array, 0, last)
  quicksort(array, first, end)


#!/usr/bin/env python 3.7.2
# -*- coding: utf-8 -*-

import argparse
from termcolor import colored
import sys
try:
	import scapy.all as scapy
except KeyboardInterrupt:
	print(colored("\n[-] CTRL+C basıldı... Lütfen bekleyiniz...", "red"))
	print(colored("[-] Uygulamadan çıkış yapıldı!", "red"))
	sys.exit()
import scapy_http.http as http

class Sniffer():
	def __init__(self):
		self.about()
		self.script_desc()

	def arguman_al(self):
		parser = argparse.ArgumentParser(description=self.description,epilog=self.kullanim,prog=self.program,formatter_class=argparse.RawTextHelpFormatter)
		parser.add_argument("--interface",dest="interface",help=" Arayuz secimi")
		options=parser.parse_args()
		if not options.interface:
			parser.error('[-] Lütfen bir arayüz belirleyiniz,daha fazla bilgi için --help kullanın.')
		else:
			return options.interface

	def sniff(self,interface):
		scapy.sniff(iface=interface,store=False,prn=self.process_sniffed_packet)

	def get_url(self,paket):
		return paket[http.HTTPRequest].Host+paket[http.HTTPRequest].Path

	def get_login_info(self,paket):
		if paket.haslayer(scapy.Raw):
			try:
				load = (paket[scapy.Raw].load).decode("utf-8")
				keywords = ["username", "user", "pass", "password", "sifre", "ad", "login", "kullanici", "kullaniciadi","kullaniciAdi", "parola", "session_key", "session_password", "log", "pwd"]
				for keyword in keywords:
					if keyword in load:
						return load
			except UnicodeDecodeError:
				pass

	def process_sniffed_packet(self,paket):
		if paket.haslayer(http.HTTPRequest):
			url=self.get_url(paket)
			print("[+] HTTP Request >> "+url.decode("utf-8"))
			login_info=self.get_login_info(paket)
			if login_info:
				print("\n\n[+] Olası kullanıcı adı / Parola > "+str(login_info)+"\n\n")

	def script_desc(self):
		self.program = "packet_sniffer"
		self.kullanim ="""Kullanim: python packet_sniffer.py --interface ARAYUZ\nOrnek Kullanim: python packet_sniffer.py --interface eth0"""
		self.description = "Arp Spoofer ile hedef bilgisayar üzerinde ARP zehirlemesi yaparken ,Bu script ile aynı anda http isteklerini dinlemeye alarak olası kullanıcı adı / parola girişlerini görüntüler."

	def about(self):
		print(colored(" ____            _        _     ____        _  __  __           ", "green"))
		print(colored("|  _ \ __ _  ___| | _____| |_  / ___| _ __ (_)/ _|/ _| ___ _ __ ", "green"))
		print(colored("| |_) / _` |/ __| |/ / _ \ __| \___ \| '_ \| | |_| |_ / _ \ '__|", "green"))
		print(colored("|  __/ (_| | (__|   <  __/ |_   ___) | | | | |  _|  _|  __/ |   ", "green"))
		print(colored("|_|   \__,_|\___|_|\_\___|\__| |____/|_| |_|_|_| |_|  \___|_|   ", "green"))
		print(colored("# author  	:", "green") + "Mustafa Dalga")
		print(colored("# linkedin  	:", "green") + "https://www.linkedin.com/in/mustafadalga")
		print(colored("# github   	:", "green") + "https://github.com/mustafadalga")
		print(colored("# title     	:", "green") + "packet_sniffer.py")
		print(colored("# description   :", "green") + "Arp Spoofer ile hedef bilgisayar üzerinde ARP zehirlemesi yaparken ,Bu script ile aynı anda http isteklerini dinlemeye alarak olası kullanıcı adı / parola girişlerini görüntüler.")
		print(colored("# date          :", "green") + "22.02.2019")
		print(colored("# version       :", "green") + "1.0")
		print(colored("# python_version:", "green") + "3.7.2")
		print(colored("# ==============================================================================", "green"))

try:
	sniffer=Sniffer()
	sniffer.sniff(sniffer.arguman_al())
except KeyboardInterrupt:
	sys.exit()


# https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings/

class Solution:
    def maxUniqueSplit(self, s: str) -> int:
        self.res = 0
        self.split(s, 0, set())
        return self.res

    def split(self, s, start, prev):
        if start == len(s):
            self.res = max(self.res, len(prev))
            return

        for i in range(start + 1, len(s) + 1):
            if s[start:i] not in prev:
                self.split(s, i, prev | {s[start:i]})

1593. Split a String Into the Max Number of Unique Substrings - medium.py


"""
クイックソート
軸となる基準値を変数pivotに設定し、pivot未満からなる配列の範囲とpivot以上からなる配列の範囲を作成し、
この作業を再帰的に行うことで、数値を昇順に整列するアルゴリズムである。
以下のプログラムでは、配列内をpivot未満とpivot以上の数値に分ける関数arrangeと、基準値を設定するfind_pivotと、
範囲を設定し、再帰処理を行い配列を返すquick_sortを使う。
"""

#配列の範囲内の最小要素番号と最大要素番号を引数とする
def arrange(A,min,max,pivot):
    l = min
    r = max
    #pivot未満の要素がmin～l-1、pivot以上の要素がl～maxにくるようにする
    while l <= r:
        tmp = A[l]
        A[l] = A[r]
        A[r] = tmp
        while A[l] < pivot:
            l += 1
        while A[r] >= pivot:
            r -= 1
    #pivotの要素番号をretとする
    ret = l
    #retを返す
    return ret

#引数として渡した配列とその範囲内からpivotを見つけ出す
def find_pivot(A,min,max):
    #配列の最初の要素を基準値とする
    pivot = A[min]
    k = min + 1
    ret = -1
    found = False
    #A[min]と異なる要素を見つけ、値が大きいほうを基準値とする
    while k <= max and found == False:
        if A[k] == pivot:
            k += 1
        else :
            found = True
            if A[k] > pivot:
                ret = k
            else:
                ret = min
    #基準値とする要素の要素番号retを返す
    return ret

def quick_sort(A,min,max):
    j = find_pivot(A,min,max)
    if j > -1:
        pivot = A[j]
        k = arrange(A,min,max,pivot)
        l = k-1
        #基準値未満の値を集めた配列について再帰処理
        quick_sort(A,min,l)
        #基準値以上の値を集めた配列について再帰処理
        quick_sort(A,k,max)
    #整列済みの配列Aを返す
    return A

#適当な配列を用意
A = [3,5,4,7,1,2,8,9,6,0]
#整列済みの配列をBに設定
B = quick_sort(A,0,len(A)-1)
#結果の表示
print(B)


from channels.routing import ProtocolTypeRouter
from django.core.asgi import get_asgi_application

# Initialize Django ASGI application early to ensure the AppRegistry
# is populated before importing code that may import ORM models.
django_asgi_app = get_asgi_application()

application = ProtocolTypeRouter(
    {
        "http": django_asgi_app,
    }
)


import cv2
import matplotlib.pyplot as plt
import numpy as np
import skimage.transform
import skimage.filters
import torch

# for generating ground truth heatmaps
def gen_hmaps(img, pts, sigma_valu=2):
    '''
    Generate 17 heatmaps
    :param img: np arrray img, (H,W,C)
    :param pts: joint points coords, np array, same resolu as img
    :param sigma: should be a tuple with odd values (obsolete)
    :param sigma_valu: vaalue for gaussian blur
    :return: np array heatmaps, (H,W,num_pts)
    '''
    H, W = img.shape[0], img.shape[1]
    num_pts = len(pts)
    heatmaps = np.zeros((H, W, num_pts + 1))
    for i, pt in enumerate(pts):
        # Filter unavailable heatmaps
        if pt[0] == 0 and pt[1] == 0: continue

        # Filter some points out of the image
        if pt[0] >= W: pt[0] = W-1
        if pt[1] >= H: pt[1] = H-1
        heatmap = heatmaps[:, :, i]
        heatmap[int(pt[1])][int(pt[0])] = 1  # reverse sequence
        heatmap = skimage.filters.gaussian(heatmap, sigma=sigma_valu)  ##(H,W,1) -> (H,W)
        am = np.max(heatmap)
        heatmap = heatmap / am  # scale to [0,1]
        heatmaps[:, :, i] = heatmap

    heatmaps[:, :, num_pts] = 1.0 - np.max(heatmaps[:, :, :num_pts], axis=2) # add background dim

    return heatmaps

def crop(img, ele_anno, crop_size=256):

    # get bbox
    pts = ele_anno['landmarks']

    bbox = ele_anno['bbox']
    vis = np.array(ele_anno['visibility'])
    # image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    # plt.imshow(image)
    # plt.show()

    xs = np.array(pts[0::2]).T
    ys = np.array(pts[1::2]).T
    # print("ptsx", xs)
    # print("ptsy", ys)

    H, W = img.shape[0], img.shape[1]

    # topleft:x1,y1  bottomright:x2,y2
    bb_x1 = int(bbox[0])
    bb_y1 = int(bbox[1])
    bb_x2 = int(bbox[0] + bbox[2])
    bb_y2 = int(bbox[1] + bbox[3])

    newX = bb_x2-bb_x1
    newY = bb_y2-bb_y1

    if(newX>newY):
        dif = newX-newY
        bb_y1-=int(dif/2)
        bb_y2+=int(dif/2)
    else:
        dif=newY-newX
        bb_x1-=int(dif/2)
        bb_x2+=int(dif/2)

    if bb_x1<0 or bb_x2>W or bb_y1<0 or bb_y2>H:
        pad = int(max(-bb_x1, bb_x2-W, -bb_y1, bb_y2-H))
        img = np.pad(img, ((pad, pad),(pad,pad),(0,0)), 'constant')
    else:
        pad = 0
    # image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    # plt.imshow(image)
    # plt.show()
    img = img[bb_y1+pad:bb_y2+pad, bb_x1+pad:bb_x2+pad]

    xs = np.where(xs != 0, xs-bb_x1, xs)
    ys = np.where(ys != 0, ys-bb_y1, ys)
    #ys = np.array([ys[i]-bb_y1 for i in range(len(ys)) if i in pts_nonzero])
    bbox[0] -= bb_x1
    bbox[1] -= bb_y1

    # resize
    H,W = img.shape[0], img.shape[1]
    xs = xs*crop_size/W
    ys = ys*crop_size/H

    # print("scale", scale)
    # print("bbox", bbox)

    # image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    # plt.imshow(image)
    # plt.show()
    img = cv2.resize(img, (crop_size, crop_size))
    # image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    # plt.imshow(image)
    # plt.show()

    pts = [[xs[i], ys[i]] for i in range(len(xs))]

    return img, pts


import socket

hote = "127.0.0.1"
port = 12800

connexion = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connexion.connect((hote, port))
print("Connexion établie avec le serveur sur le port {}".format(port))

valeur1 = input()
valeur2 = input()
signe = input()

    # Peut planter si vous tapez des caractères spéciaux
valeur1 = valeur1.encode()
valeur2 = valeur2.encode()
signe = signe.encode()

    # On envoie le message
connexion.send(valeur1)
connexion.send(valeur2)
connexion.send(signe)

msg_recu = connexion.recv(1024)
print(msg_recu.decode()) # Là encore, peut planter s'il y a des accents

print("Fermeture de la connexion")
connexion.close()


from queue import Empty, Full
from collections import defaultdict
import queue
import itertools
import string
import re

nums=list(range(1,100))
nums_str=[]
for x in nums:
    nums_str.append(str(x))
alphas=list(string.ascii_lowercase)

#debugg
step=0

main_list=[]
level0=queue.Queue(maxsize=30)
level1=queue.Queue(maxsize=30)
level2=queue.Queue(maxsize=30)
first=1
level=0
level0_last_elem=0
level1_last_elem=0
level2_last_elem=0
last_of_type=["NUM","",""]

def queue_get_all(q):
    items = []
    maxItemsToRetreive = 10
    for numOfItemsRetrieved in range(0, maxItemsToRetreive):
        try:
            if numOfItemsRetrieved == maxItemsToRetreive:
                break
            items.append(q.get_nowait())
        except Empty:
            break
    return items

def check_seq(elem,of_type):
    global level0_last_elem
    global level1_last_elem
    global level2_last_elem
    return 1

def add_to_main_list():
    global level

def add_to_queue(elem,of_type):

    global main_list
    global level
    global level0
    global level1
    global level2
    global last_of_type

    if(of_type=="final"):
        main_list.append(queue_get_all(level0))
        return

    #if type is same
    if(last_of_type[level]==of_type):
        level=level

    #type not same but similar to previous level
    elif(last_of_type[level-1]==of_type):
        level=level-1
        main_list.append(queue_get_all(level0))
        main_list[len(main_list)-1].append(list(["sub-level"]+queue_get_all(level1)))
        change=1

    #type not same also not similar to previous level
    else:
        level=level+1

    #level0
    if(level==0):
        if(of_type=="NUM"):
            level0.put(elem)
            level0_last_elem=elem[1]
            last_of_type[0]="NUM"

        elif(of_type=="ALPHA"):
            level0.put(elem)
            level0_last_elem=elem[1]
            last_of_type[0]="ALPHA"

        else:
            print("Type not found")

    #level1
    elif(level==1):
        if(of_type=="NUM"):
            level1.put(elem)
            leve1_last_elem=elem[1]
            last_of_type[1]="NUM"

        elif(of_type=="ALPHA"):
            level1.put(elem)
            leve1_last_elem=elem[1]
            last_of_type[1]="ALPHA"

        else:
            print("Type not found")

    #level2
    elif(level==2):
        if(of_type=="NUM"):
            level2.put(elem)
            leve2_last_elem=elem[1]
            last_of_type[2]="NUM"

        elif(of_type=="ALPHA"):
            level2.put(elem)
            leve1_last_elem=elem[1]
            last_of_type[2]="ALPHA"

        else:
            print("Type not found")

    #level exceeded
    else:
        print("level error")

def create_topology(input):
    global first
    global level
    global level0_last_elem
    global level1_last_elem

    x=next(input, None)
    if(x):
        if(first==1):
            level0=queue.Queue(maxsize=20)
            level0.put(x[1])
            last_elem=x[1]
            first=0

        if(x[1] in nums_str):
            type="NUM"
            add_to_queue(x,type)

        if(x[1] in alphas):
            type="ALPHA"
            add_to_queue(x,type)

        create_topology(input)
    else:
        add_to_queue(x,"final")
        return

def cal_structure(paths):

    output=[]

    for path in paths:

        global main_topics
        global doc_structure
        global main_list
        global nums_str
        global alphas
        global level0
        global level1
        global level2
        global first
        global level
        global level0_last_elem
        global level1_last_elem
        global level2_last_elem
        global last_of_type

        main_topics=[]
        doc_structure=[]
        main_list=[]

        level0=queue.Queue(maxsize=30)
        level1=queue.Queue(maxsize=30)
        level2=queue.Queue(maxsize=30)
        first=1
        level=0
        level0_last_elem=0
        level1_last_elem=0
        level2_last_elem=0
        last_of_type=["NUM","",""]

        text = open(path,encoding='utf-8').read()
        text=text.lower()
        main_topics_re=re.compile(r'([\n\r])(\w\w?\w?\w?)([):.])')

        for match in re.finditer(main_topics_re, text):
            topic = []
            if match.group(1):
                topic.append(match.group(1))
            else:
                topic.append("None")
            if match.group(2):
                topic.append(match.group(2))
            else:
                topic.append("None")
            if match.group(3):
                topic.append(match.group(3))
            else:
                topic.append("None")
            topic.append(match.span())
            main_topics.append(topic)

        if not main_topics:
            print(text)
            continue

        for i in range(0,len(main_topics)-1):
            start=main_topics[i][3][1]
            end=main_topics[i+1][3][0]
            main_topics[i].append(text[start:end])

        main_topics[i+1].append(text[main_topics[i+1][3][1]:])
        nums=list(range(1,100))

        for x in nums:
            nums_str.append(str(x))

        input=iter(main_topics)
        create_topology(input)

        for x in main_list:
            for y in x:
                doc_structure.append(y)

        output.append(["policy name",[],path])

        sub_topics_re=re.compile(r'\s?\S*\s?\S*\s?\S*\s?[(]?\S*\s?\S*\s?\S*\s?\S*[)]?\s?[\n:]')
        sub_topics_re1=re.compile(r'[\n:,.;-][\s]')

        for x in doc_structure:
            if(x[0]=='\n'):
                try:
                    found=False
                    for match in re.finditer(sub_topics_re1, x[4]):
                        temp=match.span()
                        print(str(x[1])+" : "+x[4][:temp[1]])
                        output.append(["main",x[1],x[4][:temp[1]]])
                        found=True
                        break

                    if(not found):
                        print(str(x[1])," : ",x[4])
                        output.append(["main",x[1],x[4]])
                except:
                    print("\nSOME ERROR OCCURED in X\n",x)

            else:
                for y in x:

                    if(y[1]=="u"):
                        print()
                    else:
                        try:
                            found=False
                            for match in re.finditer(sub_topics_re1, y[4]):
                                temp=match.span()
                                print("----------"+str(y[1])+" : "+y[4][:temp[1]])
                                output.append(["sublevel",y[1],y[4][:temp[1]]])
                                found=True
                                break

                            if(not found):
                                print("----------",str(y[1])," : ",y[4])
                                output.append(["sublevel",y[1],y[4]])

                        except:
                            print("\nSOME ERROR OCCURED in Y\n",y)

    return output


from collections import deque

di = [0,0,1,-1]
dj = [1,-1,0,0]
n, m = map(int,input().split())

a = [list(input()) for _ in range(n)]
d = [[[[-1]*4 for _ in range(4)]for _ in range(m)] for _ in range(n)]

q = deque()

x1,y1,x2,y2 = -1,-1,-1,-1
ans = -1

for i in range(n):
    for j in range(m):
        if a[i][j] == 'S':
            for k in range(4):
                q.append((i,j,k,0))
                d[i][j][k][0] = 0
        elif a[i][j] == 'C':
            if x1 == -1: x1, y1 = i, j
            else: x2, y2 = i, j

while q:
    i, j, dir, s = q.popleft()

    if s == 3: ans = d[i][j][dir][s]; break

    for k in range(4):
        if dir == k: continue
        ni, nj = i + di[k], j + dj[k]
        if 0 <= ni < n and 0 <= nj < m:
            if a[ni][nj] != '#':
                ns = s
                if a[ni][nj] == 'C':
                    if ni == x1 and nj == y1: ns |= 1
                    else: ns |= 2

                if d[ni][nj][k][ns] == -1:
                    d[ni][nj][k][ns] = d[i][j][dir][s] + 1
                    q.append((ni,nj,k,ns))

print(ans)


"""The DePaul Club Bot."""

import json
import os
import typing as t

from telethon.sync import TelegramClient
from telethon.sync import events

__author__ = "Akshay Mestry (XAMES3) <xa@mes3.dev>"
__version__ = "1.0.1"

# Server credentials
API_ID: t.Final[str] = os.environ["API_ID"]
API_HASH: t.Final[str] = os.environ["API_HASH"]
INPUT_CHANNEL_ID: t.Final[str] = os.environ["INPUT_CHANNEL_ID"]

# Client credentials
BOT_TOKEN: t.Final[str] = os.environ["BOT_TOKEN"]
CHANNEL_ID: t.Final[str] = os.environ["CHANNEL_ID"]

_base_url: str = f"https://discordapp.com/api/channels/{CHANNEL_ID}/messages"
_headers: dict[str, str] = {
    "Authorization": f"Bot {BOT_TOKEN}",
    "Content-Type": "application/json",
}

def headers(_headers: dict[str, str] = _headers) -> list[str]:
    """Return list of headers."""
    return [f"-H {f'{key}: {value}'!r}" for key, value in _headers.items()]

def post(message: str) -> None:
    """Post message on client devices."""
    _h = " ".join(headers())
    cmd = ["curl", _h, "-X", "POST", "-d", f"'{message}'", _base_url]
    os.system(f'{" ".join(cmd)}')

with TelegramClient("the-depaul-bot", api_id=API_ID, api_hash=API_HASH) as ctx:

    @ctx.on(events.NewMessage(chats=[int(INPUT_CHANNEL_ID)]))
    async def handler(event: events) -> None:
        _message = event.message.message
        if _message.lower().startswith("no vi"):
            _data = json.dumps({"content": _message})
            print(f"Got: {_message}")
            post(_data)

    init_msg = "Bot initialized..."
    _data = json.dumps({"content": init_msg})
    post(_data)
    ctx.run_until_disconnected()


from functools import cache

@cache
def _get_input(input_file):
    with open(input_file, "r") as f:
        output = [tuple(line.split()) for line in f.read().split("\n") if line != ""]
        return output

scores = {
        "A": 1,
        "B": 2,
        "C": 3,
}

to_defeat = {
    "A": "B",
    "B": "C",
    "C": "A",
}

defeated_by = {
    "B": "A",
    "C": "B",
    "A": "C",
}

p1_transform = {
    "X": "A",
    "Y": "B",
    "Z": "C",
}

@cache
def game_p1(pair):
    right = p1_transform[pair[1]]
    left = pair[0]
    score = 0
    if left == right:
        score = 3
    elif to_defeat[left] == right:
        score = 6
    score += scores[right]
    return score

@cache
def game_p2(pair):
    if pair[1] == "Z":
        return 6 + scores[to_defeat[pair[0]]]
    if pair[1] == "Y":
        return 3 + scores[pair[0]]
    if pair[1] == "X":
        return     scores[defeated_by[pair[0]]]

def part_1(input_file):
    games = _get_input(input_file)
    return sum([game_p1(g) for g in games])

def part_2(input_file):
    games = _get_input(input_file)
    return sum([game_p2(g) for g in games])

if __name__=="__main__":
    print(part_1("sample.txt"))
    print(part_1("input.txt"))
    print(part_2("sample.txt"))
    print(part_2("input.txt"))


from torch import nn

class Net(nn.Module):

  def __init__(self, input_dim, hidden_dim, n_layers):
    super().__init__()
    self.input_dim = input_dim
    self.hidden_dim = hidden_dim
    self.n_layers = n_layers

    self.input_layer = nn.Sequential(
        nn.BatchNorm1d(input_dim),
        nn.Linear(input_dim, hidden_dim),
        nn.ReLU(inplace=True)
    )

    middle = []
    for _ in range(n_layers):
      middle.append(nn.BatchNorm1d(hidden_dim),)
      middle.append(nn.Linear(hidden_dim, hidden_dim))
      middle.append(nn.ReLU(inplace=True))

    self.middle_layers = nn.Sequential(*middle)

    self.output_layer = nn.Linear(hidden_dim, 9)

  def forward(self, x):
    x = self.input_layer(x)
    x = self.middle_layers(x)
    x = self.output_layer(x)
    return x


"""
Приклад 3.10. Задано послідовність чисел, що завершується числом 0,
серед елементів якої є принаймні одне додатне число.
Потрібно знайти найбільше серед додатних чисел.
"""

max = 0    # Поточний найбільший член послідовності
while True:       # Завершення циклу буде через break
    a = float(input("Задайте член послідовності"))
    if a == 0:    # якщо введене число 0,
        break     # завершуємо цикл
    elif a < 0:   # якщо введене число < 0,
        continue  # переходимо на початок циклу
    max = a if a > max else max

print("Найбільшим є число", max)


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

import os
import pickle
import numpy as np
import pandas as pd
import statsmodels.api as sm

industry = pd.read_pickle('C:/Users/wuwangchuxin/Desktop/yinhua_\
    min/data/industry.pkl').drop_duplicates()

return_data = pd.read_pickle('G:short_period_mf/dailyreturn.pick\
    le').rename(columns={'symbol':'code'})

def resid(x, y):
    return sm.OLS(x, y).fit().resid

def Neutral_process(alpha_data, saf):
    num_mint = alpha_data.shape[1]
    num_inds = industry.shape[1]
    data = pd.merge(alpha_data, industry, on=['code']).dropna()
    X = data.iloc[:, 1:num_mint]
    y = data.iloc[:, num_mint:num_mint+num_inds]
    X = X.apply(lambda x:resid(x, y))
    X['code'] = alpha_data['code']
    output = open(r'G:/short_period_mf/netual_process/netual_%s'%saf[-16:],'wb')
    pickle.dump(X,output)
    output.close()
    return 0

def IC_computing(alpha_data, saf):
    data = pd.merge(alpha_data,return_data,on = ['code'])
    dailyReturn = data.daily_return
    factors = Neutral_process(alpha_data)
    IC = dailyReturn.corr(factors, method='spearman')
    output = open(r'G:/short_period_mf/ic_value/ic_%s'%saf[-16:],'wb')
    pickle.dump(IC,output)
    output.close()
    return 0

################
standard_alpha = os.listdir(r'G:/short_period_mf/alpha_min_stand')
for saf in standard_alpha:
    alpha_d = pd.read_pickle(r'G:/short_period_mf/alpha_min_stand/%s'%saf)
    IC_computing(alpha_d, saf)

for saf in standard_alpha:
    alpha_d = pd.read_pickle(r'G:/short_period_mf/alpha_min_stand/%s'%saf)
    Neutral_process(alpha_d,saf)


#!/usr/bin/env python
from builtins import range
import argparse

#extract mtDNA annotation from gtf file
parser = argparse.ArgumentParser(usage = "\n" +"python %(prog)s <input_file> <output_file> \n" +"\n" + "Usage examples\
:\npython mt_annotation.py mouse.gtf mouse_mt.gtf n\n"+ "\n" + "Description:\nExtracts mtDNa annotaions from GTF file\n", add_help=False)
required = parser.add_argument_group('required arguments')
required.add_argument("input_file", help = "path to input GTF file")
required.add_argument("output_file", help = "path to output GTF file")
optional = parser.add_argument_group('optional arguments')
optional.add_argument("-h", "--help", action='help', help='print help message')
args = parser.parse_args()

#read input file
infile = open(args.input_file, "r")
#skip the header lines
lines = infile.readlines()[5:]

# and output file name in the second
outfile = args.output_file
fo = open(outfile,"w")
fo.write("#!genome-build GRCz10"+ "\n"+ "#!genome-version GRCz10"+ "\n"+"#!genome-date 2014-09"+ "\n"+"#!genome-build-accession NCBI:GCA_000002035.3"+ "\n"+"#!genebuild-last-updated 2016-07"+"\n")
fo.write("seqname" + "\t"+ "source" + "\t" + "feature" +"\t" + "start" + "\t"+ "end" + "\t" + "score" +"\t" + "\t"+ "strand" + "\t" + "frame" +"\t"+ "attribute" + "\t" + "\n" )
for line in lines:
 line= line.strip().split("\t")
 if (line[0] == 'MT' and line[2]== 'gene'):
     #print line
     ten =''
     for i in range(0,len(line)):
       ten=ten+ line[i] +"\t"
     #print ten
     fo.write(ten+"\n")
fo.close()
infile.close()


import matplotlib.pyplot as plt
from pylab import mpl
import math

# Ajuste lineal unario
# Los datos de ajuste utilizados son xi = 1,2,3,4,5,6,7
# El valor correspondiente de la función correspondiente yi = 0.5,2.5,2,4,3.5,6,5.5

# Completar el cálculo de los parámetros de la curva de ajuste

def liner_fitting(data_x,data_y):
    size = len(data_x)
    i=0
    sum_xy=0
    sum_y=0
    sum_x=0
    sum_sqare_x=0
    average_x=0
    average_y=0
    while i<size:
        sum_xy+=data_x[i]*data_y[i]
        sum_y+=data_y[i]
        sum_x+=data_x[i]
        sum_sqare_x+=data_x[i]*data_x[i]
        i+=1
    average_x=sum_x/size
    average_y=sum_y/size
    return_k=(size*sum_xy-sum_x*sum_y)/(size*sum_sqare_x-sum_x*sum_x)
    return_b=average_y-average_x*return_k
    return [return_k,return_b]

# Después de completar el cálculo del valor de función correspondiente en la curva

def calculate_lin(data_x,k,b):
    datay=[]
    for x in data_x:
        datay.append(k*x+b)
    return datay

# Finalizar dibujo de función
def draw_lin(data_x,data_y_new,data_y_old):
    plt.plot (data_x, data_y_new, label = "test", color = "black")
    plt.scatter (data_x, data_y_old, label = "discrete data")
    mpl.rcParams['axes.unicode_minus'] = False
    plt.title ("Datos de ajuste lineal de una variable")
    plt.legend(loc="upper left")
    plt.show()

#Completar el cálculo de las variables correspondientes antes del cálculo de parámetros de la curva ajustada
def polynomial_fitting(data_x,data_y):
    size=len(data_x)
    i=0
    sum_x = 0
    sum_sqare_x =0
    sum_third_power_x = 0
    sum_four_power_x = 0
    average_x = 0
    average_y = 0
    sum_y = 0
    sum_xy = 0
    sum_sqare_xy = 0
    while i<size:
        sum_x += data_x[i]
        sum_y += data_y[i]
        sum_sqare_x += math.pow(data_x[i],2)
        sum_third_power_x +=math.pow(data_x[i],3)
        sum_four_power_x +=math.pow(data_x[i],4)
        sum_xy +=data_x[i]*data_y[i]
        sum_sqare_xy +=math.pow(data_x[i],2)*data_y[i]
        i += 1
    average_x=sum_x/size
    average_y=sum_y/size
    return [[size, sum_x, sum_sqare_x, sum_y]
        , [sum_x, sum_sqare_x, sum_third_power_x, sum_xy]
        , [sum_sqare_x,sum_third_power_x,sum_four_power_x,sum_sqare_xy]]

#Completar el cálculo de los parámetros de la curva de ajuste
# Al resolver la ecuación, use el método de eliminación gaussiano para calcular el valor del parámetro correspondiente

def calculate_parameter(data):
    #i se usa para controlar elementos de columna, línea es un elemento de línea, j se usa para controlar el número de bucles y los datos se usan para almacenar variables locales. Guardar el valor modificado
    i = 0
    j = 0
    line_size = len(data)
    #Convierta el determinante al determinante triangular superior
    while j < line_size-1:
        line = data[j]
        temp = line[j]
        templete=[]
        for x in line:
            x=x/temp
            templete.append(x)
        data[j]=templete
        #flag sign el número de líneas que deben eliminarse
        flag = j+1
        while flag < line_size:
            templete1 = []
            temp1=data[flag][j]
            i = 0
            for x1 in data[flag]:
                if x1!=0:
                   x1 = x1-(temp1*templete[i])
                   templete1.append(x1)
                else:
                   templete1.append(0)
                i += 1
            data[flag] = templete1
            flag +=1
        j += 1

         #Buscando el valor del parámetro correspondiente

    parameters=[]
    i=line_size-1
         #j Identificación menos el número de elementos
         #flag_rolIdentifique qué columna excepto
    flag_j=0
    rol_size=len(data[0])
    flag_rol=rol_size-2
         #Obtener la cantidad de soluciones
    while i>=0:
        operate_line = data[i]
        if i==line_size-1:
            parameter=operate_line[rol_size-1]/operate_line[flag_rol]
            parameters.append(parameter)
        else:
            flag_j=(rol_size-flag_rol-2)
            temp2=operate_line[rol_size-1]
                         #result_flag es la bandera para acceder a la solución que se ha resuelto
            result_flag=0
            while flag_j>0:
                temp2-=operate_line[flag_rol+flag_j]*parameters[result_flag]
                result_flag+=1
                flag_j-=1
            parameter=temp2/operate_line[flag_rol]
            parameters.append(parameter)
        flag_rol-=1
        i-=1
    return parameters

#Calcular el valor de la curva ajustada
def calculate_bin(data_x,parameters):
    datay=[]
    for x in data_x:
        datay.append(parameters[2]+parameters[1]*x+parameters[0]*x*x)
    return datay

#Finalizar dibujo de función
def draw_bin(data_x,data_y_new,data_y_old):
    plt.plot (data_x, data_y_new, label = "curva de ajuste", color = "black")
    plt.scatter (data_x, data_y_old, label = "datos discretos")
    mpl.rcParams['axes.unicode_minus'] = False
    plt.title ("Datos de ajuste polinomial de una variable")
    plt.legend(loc="upper left")
    plt.show()


import os
import webbrowser
import folium

carte = folium.Map([46.59, 2.48],
                   zoom_start=10,
                   control_scale=True)
l_icones = [([46.4, 2.3], "fontawesome 4.7", "green", "mixcloud", 'fa'),
            ([46.4, 2.4], "fontawesome 4.7", "green", "space-shuttle", 'fa'),
            ([46.4, 2.5], "fontawesome 4.7", "green", "arrows", 'fa'),
            ([46.5, 2.3], "glyphicons", "red", "camera", 'glyphicon'),
            ([46.5, 2.4], "glyphicons", "red", "book", 'glyphicon'),
            ([46.5, 2.5], "glyphicons", "red", "signal", 'glyphicon'),
            ]
for p_marqueur in l_icones:
    marqueur = folium.Marker(p_marqueur[0],
                             popup=p_marqueur[1],
                             icon=folium.Icon(color=p_marqueur[2],
                                              icon=p_marqueur[3],
                                              prefix=p_marqueur[4]))
    marqueur.add_to(carte)
chemin_fichier = os.path.splitdrive(os.getcwd())[0] + \
                 "/tmp/ma_carte_centre.html"
carte.save(chemin_fichier)
webbrowser.open("file:///" + chemin_fichier)


def read_input():
    inputs = []
    outputs = []
    with open("input8.txt") as f:
        for line in f:
            split = line.split('|')
            inputs.append(split[0].split())
            outputs.append(split[1].split())
    return inputs, outputs

"""
 0000
1    2
1    2
 3333
4    5
4    5
 6666
"""

digit_segments = {0: 6, 1: 2, 2: 5, 3: 5, 4: 4, 5: 5, 6: 6, 7: 3, 8: 7, 9: 6}
digit_map = {0: [0, 1, 2, 4, 5, 6],
             1: [2, 5],
             2: [0, 2, 3, 4, 6],
             3: [0, 2, 3, 5, 6],
             4: [1, 2, 3, 5],
             5: [0, 1, 3, 5, 6],
             6: [0, 1, 3, 4, 5, 6],
             7: [0, 2, 5],
             8: [0, 1, 2, 3, 4, 5, 6],
             9: [0, 1, 2, 3, 5, 6]}
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

def part1():
    _, outputs = read_input()
    total = 0
    to_check = [1, 4, 7, 8]
    for output in outputs:
        for digit in to_check:
            total += sum([1 for entry in output if len(entry) == digit_segments[digit]])
    return total

def get_unique_inputs(input):
    # return the inputs for numbers 1, 4, 7, 8
    number_input = dict()
    to_check = [1, 4, 7, 8]
    for number in to_check:
        for entry in input:
            if len(entry) == digit_segments[number]:
                number_input[number] = entry
                break
    return number_input

def check_intersections_complements(number_string, mapping):
    new_mapping = True
    while new_mapping:
        new_mapping = False
        for number1, string1 in number_string.items():
            for number2, string2 in number_string.items():
                if number1 != number2:
                    segments1 = digit_map[number1]
                    segments2 = digit_map[number2]

                    # check intersection
                    intersection = list(set(segments1).intersection(segments2))
                    intersection = [entry for entry in intersection if entry not in mapping]
                    if len(intersection) == 1 and intersection[0] not in mapping:
                        new_mapping = True
                        new_letter = list(set(string1).intersection(string2))
                        new_letter = [letter for letter in new_letter if letter not in mapping.values()]
                        mapping[intersection[0]] = new_letter[0]

                    # check complement
                    if len(segments1) < len(segments2):
                        segments1, segments2 = segments2, segments1
                        string1, string2 = string2, string1
                        number1, number2 = number2, number1
                    complement = [entry for entry in segments1 if entry not in segments2]
                    complement = [entry for entry in complement if entry not in mapping]
                    if len(complement) == 1 and complement[0] not in mapping:
                        new_mapping = True
                        new_letter = [char for char in string1 if char not in string2]
                        new_letter = [letter for letter in new_letter if letter not in mapping.values()]
                        mapping[complement[0]] = new_letter[0]
    return mapping

def find_string_candidate(number, number_string, mapping, strings):
    # first, find all strings that match the number based on the current known mapping of segments
    segments = digit_map[number]
    candidates = [_ for _ in strings]
    for segment in segments:
        if segment in mapping:
            for string in strings:
                if mapping[segment] not in string or len(string) != len(segments) or string in number_string.values():
                    candidates.remove(string)

    # now check if candidates can be trimmed down, preferably to one
    # do this by checking the strings that numbers are known for, and comparing
    for compare_number, compare_string in number_string.items():
        # check by how many segments intersect, how many letters in the string should be the same
        compare_segments = digit_map[compare_number]
        amount = len(set(segments).intersection(compare_segments))

        # loop over candidates and remove candidates that do not satisfy the string intersection
        remaining_candidates = []
        for candidate in candidates:
            if len(set(candidate).intersection(compare_string)) == amount:
                remaining_candidates.append(candidate)
        candidates = remaining_candidates
    return candidates

def create_mapping(string_input):
    # create a mapping to determine which segment of the digital number is represented by which letter
    # to do this, knowing which input represent which number helps us
    number_string = get_unique_inputs(string_input)
    mapping = dict()
    while len(mapping) != 7:
        # determine which segment represent which number by taking the intersections and complement of the known numbers
        mapping = check_intersections_complements(number_string, mapping)

        # based on new mapping and known string, find string for unknown numbers
        for number in range(10):
            if number not in number_string:
                candidates = find_string_candidate(number, number_string, mapping, string_input)
                if len(candidates) == 1:
                    number_string[number] = candidates[0]

    return number_string, mapping

def translate_number(strings, number_string):
    digits = ""
    for input in strings:
        for number, string in number_string.items():
            if sorted(input) == sorted(string):
                digits += str(number)
                break

    return int(digits)

def part2():
    inputs, outputs = read_input()
    total = 0
    for i, input in enumerate(inputs):
        number_string, mapping = create_mapping(input)
        total += translate_number(outputs[i], number_string)
    return total

print(part2())


import os
from pathlib import Path

testPath = "F:/teamescape/git_repos"

def get_files(directory):
    files = []
    os.chdir(directory)
    for root, dirs, localfiles in os.walk(directory, topdown=True, onerror=None, followlinks=False):
        files.extend(localfiles)
        for directory in dirs:
            directory = os.path.join(root, directory)
            files.extend(get_files(directory))
    files = list(files)
    return files
    '''
    filtered = list(filter(lambda entry: os.path.isfile(entry), dir_list))
    dirs = set(dir_list) - set(filtered)
    files.append(filtered)
    return files
    '''

def main():
    files = get_files(testPath)
    print("files are {}".format(files))

if __name__ == "__main__":
    main()


from framework.button import Button
from framework.util.font import font
from framework.util.util import WHITE, GREEN

class TextButton(Button):
    def __init__(self, text, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.text = text
        self.color = WHITE

    def draw(self, surface, debug):
        super().draw(surface, debug)
        text = font(self.rect.width//len(self.text)).render(self.text, True, self.color)
        surface.blit(text, text.get_rect(center=self.rect.center))

    def toggle(self):
        if self.color == WHITE:
            self.color = GREEN
        else:
            self.color = WHITE

    def to_dict(self):
        temp_button_dict = super().to_dict()
        temp_button_dict['type'] = TextButton.__name__
        temp_button_dict['text'] = self.text
        return temp_button_dict

    @classmethod
    def from_dict(cls, button_dict):
        assert button_dict['type'] == TextButton.__name__
        del button_dict['type']

        orig_rect = button_dict['rect']
        new_button = cls(pos=(TextButton.scale_size(orig_rect['left']), TextButton.scale_size(orig_rect['top'])),
                    width=TextButton.scale_size(orig_rect['right']) - TextButton.scale_size(orig_rect['left']),
                    height=TextButton.scale_size(orig_rect['bottom']) - TextButton.scale_size(orig_rect['top']),
                    callback=button_dict['callback'],
                    click_rv=button_dict['click_rv'],
                    name=button_dict['name'],
                    text=button_dict['text'])

        new_button.original_values = [orig_rect['left'], orig_rect['top'], orig_rect['right'], orig_rect['bottom']]
        return new_button


import arcade
from vector import Vector2
from constants import *
from entity import Entity

class Player(Entity):
    def __init__(self, node, fname: str="sprites\eyer.png", scale: float=SCALE/2):
        super().__init__(node, fname, scale)
        self.name = PLAYER
        self.color = WHITE
        self.velocity = (0, 0)
        self.key = STOP
        self.aim = Vector2()

    def set_velocity(self, dt):
        super().set_velocity(dt)

    def draw(self):
        print("Player is drawn")
        super().draw()

    def on_update(self, dt):
        super().update()

        if self.overshot_target():
            self.node = self.target
            if self.node.neighbors[PORTAL] is not None:
                self.node = self.node.neighbors[PORTAL]
            self.target = self.get_new_target(self.key)
            if self.target is not self.node:
                self.direction = self.key
            else:
                self.target = self.get_new_target(self.direction)

            if self.target is self.node:
                self.direction = STOP
            self.set_position()
            self.set_velocity(dt)
        else:
            if self.opposite_direction(self.key):
                self.reverse_direction()
                self.set_velocity(dt)

    def on_key_press(self, symbol, modifiers):
        if symbol == arcade.key.UP or symbol == arcade.key.W:
            self.key = UP
            self.aim = Vector2(0, SCALEHEIGHT)
        if symbol == arcade.key.DOWN or symbol == arcade.key.S:
            self.key = DOWN
            self.aim = Vector2(0, -SCALEHEIGHT)
        if symbol == arcade.key.LEFT or symbol == arcade.key.A:
            self.key = LEFT
            self.aim = Vector2(-SCALEWIDTH, 0)
        if symbol == arcade.key.RIGHT or symbol == arcade.key.D:
            self.key = RIGHT
            self.aim = Vector2(SCALEWIDTH, 0)

    def draw_thoughts(self):
        point = self.position + self.aim
        arcade.draw_line(self.center_x, self.center_y, point.x, point.y, self.color, 2*SCALE)


def countPairs(arr, n):
	map = dict()
	for i in range(n):
		map[arr[i] - i] = map.get(arr[i] - i, 0) + 1	# To store the required count
	res = 0
	for x in map:
		cnt = map[x]
		res += ((cnt * (cnt - 1)) // 2)

	return res

for _ in range(int(input())):
    n = int(input())
    arr = list(map(int,input().split()))
    print(countPairs(arr, n))


from operator import attrgetter
import numpy as np
import sys
import random
import math
import copy
import pacman

"""
A genetic algorithm that attempts to find the optimal path to collect all of the coins
based off of the pacman problem's board
Board size, starting position, and walls are specified with an input file of the same
format as the pacman input file (path can be empty).

TODO:
    -Create a better stoping condition
    -try k-point crossovers
    -experiment with different variations on mutation
"""

siblings = 1000
# Currently the only stopping condition is this number of generations.  Better stopping conditions may be nice
num_generations = 500
# I ahev found that 1 works well here on my test boards
mutation_rate = 1
# This can be any number >= 1
# The lower it is, the shorter the intial paths will be, and the algorithm will mostly focus on getting all coins.
# The larger it is, the larger initial path lengths, and the algorithm will mostly focus on finding faster routes
path_start_ratio = 1.5

# Open file and intialize board
if(len(sys.argv) != 2):
    print("Requires 1 input file")
    exit()

try:
    f = open(sys.argv[1])
except IOError:
    print("Error opening file")
    exit()

# File must include board size and starting position at least
lines = f.readlines()
if(len(lines) < 2):
    print("Not enought lines")
    exit()

# Close file
try:
    f.close()
except IOError:
    print("Error closing file")
    exit()

# Get board size
try:
    w, h = (int(s) for s in lines[0].split())
except ValueError:
    print("Non-int in input")
    exit()
motherboard = np.ones((w, h))

# Helper function for detecting errors in input file
def good_position(x, y):
    if (x < 0 or x >= motherboard.shape[0] or y < 0 or y >= motherboard.shape[1] or motherboard[x,y] > 1):
        return 0
    return 1

# Get wall positions
for line in lines[3:]:
    try:
        x, y = (int(s) for s in line.split())
    except ValueError:
        print("Non-int in input")
        exit()
    if(good_position(x, y)):
        motherboard[x,y] = 3
    else:
        print("wall outside of board or on top of another wall")
        exit()

# Get starting position
try:
    start_x, start_y = (int(s) for s in lines[1].split())
except ValueError:
    print("Non-int in input")
    exit()
if(good_position(start_x, start_y)):
    motherboard[start_x,start_y] = 0
else:
    print("Starting position outside of board or on top of wall")
    exit()

class path_set:
    path = ""
    score = -1
    fitness = -1
    def print_me(self):
        print(f"{self.score}  in {len(self.path)} moves")

# prints the batch of the current paths, used in debugging
def print_siblings(paths):
    for p in paths:
        p.print_me()

# Returnes the average fitness of all the paths.  Used in analytics
def average_fitness(paths):
    tot = 0
    for p in paths:
        tot += p.fitness
    return tot/len(paths)

# a very simple fitness function.  Tries to balance # of coins collected and path length
def calculate_fitness(path_obj):
    return path_obj.score**2 / len(path_obj.path)

# Runs the computational part of the pacman solution which returns
# the final x and y position, along with # of coins (x and y position ignored)
def run_inhouse(path_obj):
    fresh_board = copy.deepcopy(motherboard)
    x, y, score = pacman.compute(fresh_board,start_x,start_y,path_obj.path)
    path_obj.score = score
    path_obj.fitness = calculate_fitness(path_obj)

# preform a single point crossover from two parents
# k-point crossover may be better for this problem but uniform crossover is not
# practical for this problem
def crossover(p1, p2):
    point = random.randint(1,min(len(p1.path),len(p2.path)))
    combined = p1.path[:point] + p2.path[point:]
    #print(min(len(p1.path),len(p2.path)), len(combined))
    return combined

# preforms point mutations based on mutation rate
# I chose to choose spots to mutate with replacement
def mutation(child_path):
    num_mutations = random.randint(0,int(len(child_path) * mutation_rate))
    for i in range(num_mutations):
        spot = random.randint(0,len(child_path)-1)
        child_path = child_path[:spot] + generate_cardinal() + child_path[spot+1:]
    return child_path

# Has a chance to drop a random part of the path
# This is the only method which shortens the path
def drop(child_path):
    start = random.randint(0,len(child_path)-1)
    # On small inputs, end-start is rarely positine.  Ceiling allows this to work much better
    end = math.ceil(np.random.normal(start, len(child_path)*0.05, 1))
    if(end-start > 0):
        child_path = child_path[:start] + child_path[end:]
    return child_path

# This was just an experiment of mine.  It does not help
def swap_crossover(child_path):
    if(random.random() < mutation_rate/4):
        point = random.randint(0,len(child_path)-1)
        child_path = child_path[point:] + child_path[:point]
    return child_path

def evolution(paths):
    global siblings
    generation = 0
    #for analytics
    f = open("export.csv","w")
    while(generation < num_generations):
        # Most fit path will be at the start of the list
        paths = sorted(paths,key=attrgetter('fitness'), reverse = True)

        print(f"\nGeneration {generation}:")
        print(f"Top score: {paths[0].score} in {len(paths[0].path)} moves (fitness: {paths[0].fitness})")
        f.write(f"{generation},{paths[0].score},{len(paths[0].path)},{paths[0].fitness},{average_fitness(paths)}\n")
        print(f"Optimal path: {paths[0].path}")
        generation += 1

        parents = int(siblings/5)
        for i in range(parents+1,siblings):
            #print('|', end='')
            child_path = crossover(random.choice(paths[:parents]),random.choice(paths[:parents]))
            child_path = mutation(child_path)
            child_path = drop(child_path)
            #child_path = swap_crossover(child_path)
            paths[i].path = child_path
            #test path and calculate fitness
            run_inhouse(paths[i])
    f.close()

def generate_cardinal():
    return random.choice("NSEW")

# generates initial paths
def generate_random_path():
    global w, h
    new_path = ""
    # initial paths will be of size w*h* the path start ratio.  with no walls, the optimal path should be equal to w*h-1
    for i in range(int(w*h*path_start_ratio)):
        new_path += generate_cardinal()
    return new_path

#initialize
paths = np.empty(siblings, dtype=object)
for i in range(siblings):
    new_path = path_set()
    new_path.path = generate_random_path()
    run_inhouse(new_path)
    paths[i] = new_path

evolution(paths)


import torch, torch_xla
from transformers import AutoTokenizer, GPT2LMHeadModel, AutoConfig, TrainingArguments
from optimum.neuron import TrainiumTrainer
from transformers.data.data_collator import DataCollatorForLanguageModeling
from datasets import load_from_disk
import os

ds = load_from_disk("poems_dataset_64")
tokenizer = AutoTokenizer.from_pretrained("gpt2")
tokenizer.pad_token = tokenizer.eos_token
model = GPT2LMHeadModel.from_pretrained("gpt2")
print(f"# model params: {sum([p.numel() for p in model.parameters()]):,}")
col = DataCollatorForLanguageModeling(tokenizer, mlm=False)

print(f"WORLD_SIZE: {os.environ.get('WORLD_SIZE', 1)}")
if os.environ.get("NEURON_PARALLEL_COMPILE", None):
    max_steps = 20
else:
    max_steps = 1000

training_args = TrainingArguments(
    output_dir="./output/",
    overwrite_output_dir=True,
    num_train_epochs=10,
    max_steps=max_steps,
    warmup_steps=300,
    save_strategy="steps",
    save_steps=200,
    save_total_limit=50,
    logging_steps=10,
    learning_rate=5e-5,
    per_device_train_batch_size=4,
    gradient_accumulation_steps=1,
    report_to="tensorboard",
    dataloader_drop_last=True
)

trainer = TrainiumTrainer(
    model=model,
    args=training_args,
    train_dataset=ds,
    data_collator=col,
)

trainer.train()


'''
Queue implementation using a circular numpy array.
'''

import numpy as np
from stack import Stack

class QueueNP:
    def __init__(self, capacity=3):
        self.array = np.empty(capacity, dtype=np.uint8)
        self.length = capacity
        self.count = 0
        self.front = 0
        self.rear = 0

    def is_empty(self):
        return self.count == 0

    def is_full(self):
        return self.count == self.length

    def peek(self):
        return self.array[self.front]

    def increment_front(self):
        self.front = (self.front + 1) % self.length

    def increment_rear(self):
        self.rear = (self.rear + 1) % self.length

    def enqueue(self, item):
        self.array[self.rear] = item
        self.increment_rear()
        if self.is_full():
            self.increment_front()
        else:
            self.count += 1

    def dequeue(self):
        if self.is_empty(): raise IndexError()
        item =  self.array[self.front]
        self.array[self.front] = 0
        self.increment_front()
        self.count -= 1
        return item

    def reverse(self):
        stack = Stack()

        while not self.is_empty():
            stack.push(self.dequeue())

        while not stack.is_empty():
            self.enqueue(stack.pop())

    def __str__(self):
        lst = list(self.array)
        front, length  = self.front, self.length
        ans = []
        for _ in range(self.count):
            ans.append(lst[front])
            front = (front + 1) % length
        return f'{ans}'

def main():
    def prnq(q):
        print('\n\t q: ', q)

    def prndq(q):
        print('\n\t dequeue: ', q.dequeue())

    q = QueueNP()
    for x in range(1, 5):
        q.enqueue(x)
        prnq(q)

    prndq(q)
    prnq(q)
    print()
    quit()

    for y in range(55, 66):
        q.enqueue(y)
        print('\t q.enqueue', y, ':  ', q)
        print('\t dequeue: ', q.dequeue(), ':  ', q)

main()


'''
The program must accept N integers as the input.
The program must traverse the given integers and if the integer 5 is encountered then the following integers must be added till the integer 10 occurs.
Finally, the program must print the total sum as the output.

Boundary Condition(s): 1 <= N <= 1000

Input Format:  The first line contains N.
               The second line contains N integers separated by space(s).
Output Format: The first line contains the sum as per the given conditions.

Example Input/Output 1:

Input:  9
        2 5 3 2 10 3 10 5 4
Output: 9

Explanation:  The integer 5 occurs at position 2 and the immediate next integer value 10 occurs at position 5.
              There are two integers (3 and 2) between them which are added to 5.
              The next integer value 5 occurs at position 8 the integers after 5 is 4 which is also added to the result.
              Hence the output is 9

Example Input/Output 2:

Input:  8
        1 5 5 12 10 5 6 10
Output: 23

SOLUTION:
'''

#Michael
n=int(input())
l=list(map(int, input().split()))
s, i = 0, 0
while i<n:
    if(l[i]==5):
        j=i+1
        while (j < n and (l[j]!=10)):
                s+=l[j]
                j+=1
        if(j<n and l[j]==10):
            i=j+1
        else:
            break
    else:
        i+=1
print(s)


# 프로그래머스_레벨 2_큰 수 만들기
# 220804
# 핵심 개념: 스택(LIFO)

def solution(number, k):
    num_list = [int(i) for i in list(number)]
    answer = []

    # num_list의 값을 하나하나 answer에 append
    # 단, answer[-1]보다 큰 값이 들어오면 계속 pop
    for num in num_list:
        while True:
            if not answer or k == 0 or num <= answer[-1]: break
            if k > 0 and num > answer[-1]:
                answer.pop()
                k -= 1

        answer.append(num)

    ret = ''.join([str(x) for x in answer[:(len(number)-k)]])

    return ret

프로그래머스/레벨 2_큰 수 만들기.py

레벨 2_큰 수 만들기.py


import requests
from urllib.parse import urljoin

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

base = 'https://malura.de'

redirect_count = 0
redirect_success_count = 0

with open('redirects.map') as fp:
    for cnt, line in enumerate(fp):
        redirect_count += 1
        [url, redirect] = [urljoin(base, chunk.strip().replace(';', '')) for chunk in line.split(' ')]
        r = requests.get(url, allow_redirects=False)

        redirected_location = r.headers['Location']
        if redirected_location != redirect:
            print("{} -> {} = {}".format(url, redirect, redirected_location))
        else:
            redirect_success_count += 1

if redirect_success_count != redirect_count:
    print(f"{bcolors.FAIL}{redirect_count - redirect_success_count} redirects didnt work{bcolors.ENDC}")


import torch
import torch.nn as nn

class RNN(nn.Module):
    def __init__(self, input_size, hidden_size, output_size):
        super().__init__()
        self.W_xh = nn.Parameter(torch.zeros(input_size, hidden_size))
        self.W_hh = nn.Parameter(torch.zeros(hidden_size, hidden_size))
        self.W_hy = nn.Parameter(torch.zeros(hidden_size, output_size))

        nn.init.xavier_normal_(self.W_xh)
        nn.init.xavier_normal_(self.W_hh)
        nn.init.xavier_normal_(self.W_hy)

    def forward(self, x, hidden_state):
        hidden_state = torch.tanh(hidden_state @ self.W_hh + x @ self.W_xh)
        y = hidden_state @ self.W_hy
        return y, hidden_state


# https://www.geeksforgeeks.org/find-co-ordinates-of-contours-using-opencv-python/
# https://www.pyimagesearch.com/2016/02/01/opencv-center-of-contour/
# https://www.nkp.hu/tankonyv/matematika_11/lecke_04_068

import numpy as np
import cv2

# Reading image
font = cv2.QT_FONT_NORMAL
img2 = cv2.imread('test.jpg', cv2.IMREAD_COLOR)

# Reading same image in another variable and converting to gray scale.
img = cv2.imread('test.jpg', cv2.IMREAD_GRAYSCALE)

# Converting image to a binary image ( black and white only image).
_, threshold = cv2.threshold(img, 110, 255, cv2.THRESH_BINARY)

# Detecting contours in image.
_, contours, _ = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Going through every contours found in the image.
for cnt in contours:

    M = cv2.moments(cnt)
    if (M["m00"] == 0):
        M["m00"] = 1
    cX = int(M["m10"] / M["m00"])
    cY = int(M["m01"] / M["m00"])

    # draw the contour and center of the shape on the image
    cv2.drawContours(img2, [cnt], -1, (0, 255, 0), 2)

    approx = cv2.approxPolyDP(cnt, 0.009 * cv2.arcLength(cnt, True), True)

    # draws boundary of contours.
    cv2.drawContours(img2, [approx], 0, (0, 0, 255), 5)

    # Used to flatted the array containing the co-ordinates of the vertices.
    n = approx.ravel()
    i = 0
    points = []

    for j in n:
        if i < 3:
            # Calculating the angle from the vector co-ordinates.
            v1x = n[0 + i] - n[2 + i]
            v2x = n[4 + i] - n[2 + i]
            v1y = n[1 + i] - n[3 + i]
            v2y = n[5 + i] - n[3 + i]
            v1v2 = (v1x * v2x) + (v1y * v2y)
            abs_v1v2 = np.sqrt(np.square(v1x) + np.square(v1y)) * np.sqrt(np.square(v2x) + np.square(v2y))
            cos_alpha = v1v2/abs_v1v2
            angle = np.degrees(np.arccos(cos_alpha))
            rounded_angle = str(np.round(angle, 2))
        if (i % 2 == 0):
            x = n[i]
            y = n[i + 1]
            cv2.putText(img2, rounded_angle, (x, y), font, 0.5, (0, 255, 0))
        i = i + 1
    cv2.putText(img2, str(i//2), (cX, cY), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

# Showing the final image.
cv2.imshow('image2', img2)
# Exiting the window if 'q' is pressed on the keyboard.
if cv2.waitKey(0) & 0xFF == ord('q'):
    cv2.destroyAllWindows()


#!/usr/bin/env python3
# coding: utf-8

"""
一些实用的小功能
"""

import os
from collections import Counter
from datetime import datetime, timedelta

from .core import Deck, Decks, MODE_STANDARD

def diff_decks(*decks):
    """
    卡组对比
    :param decks: 两个或以上的卡组
    :return: 返回每个卡组特有的部分
    """
    intersection = decks[0].cards & decks[1].cards
    for deck in decks[2:]:
        intersection &= deck.cards

    differs = dict()
    for deck in decks:
        differs[deck] = deck.cards - intersection

    return differs

def gen_deck(career, from_decks, mode=MODE_STANDARD):
    """
    根据给定的卡组合集生成指定职业和模式的新卡组
    :param career: 职业
    :param from_decks: 卡组合集
    :param mode: 模式
    :return: 新的卡组
    """

    if not isinstance(from_decks, Decks):
        raise TypeError('应为 Decks 对象')

    cards_stats, top_decks = from_decks.career_cards_stats(career, mode=mode)

    cards = Counter()
    for card, stats in cards_stats.items():
        count = 2 if stats['avg_count'] >= 1.75 else 1
        cards[card] = count
        if sum(cards.values()) == 30:
            break
        elif sum(cards.values()) > 30:
            cards.subtract([card])
            break

    new_deck = Deck()
    new_deck.cards = cards
    return new_deck, top_decks

def decks_expired(decks, expired=timedelta(days=1)):
    """
    检查 Decks 是否已过期
    :param decks: Decks 对象
    :param expired: 有效期长度
    :return: 若已过期则返回True
    """
    if os.path.isfile(decks.json_path):
        m_time = os.path.getmtime(decks.json_path)
        if datetime.fromtimestamp(m_time) < (datetime.today() - expired):
            return True
        else:
            return False
    return True


__author__ = 'suixin'

import sys
import threading
import socketserver
import numpy as np
import cv2
from predict import predict2
from carCtrHelper import RCTest

# distance data measured by ultrasonic sensor
sensor_data = None

class SensorDataHandler(socketserver.BaseRequestHandler):

    data = " "

    def handle(self):
        global sensor_data
        while self.data:
            self.data = self.request.recv(1024)
            sensor_data = round(float(self.data), 1)
            # print "{} sent:".format(self.client_address[0])
            print(sensor_data)

class VideoStreamHandler(socketserver.StreamRequestHandler):
    car = RCTest()
    count =0
    def handle(self):

        global sensor_data
        stream_bytes = b' '

        try:
            # stream video frames one by one
            while True:
                stream_bytes += self.rfile.read(1024)
                first = stream_bytes.find(b'\xff\xd8')
                last = stream_bytes.find(b'\xff\xd9')
                if first != -1 and last != -1:
                    jpg = stream_bytes[first:last + 2]
                    stream_bytes = stream_bytes[last + 2:]
                    #gray = cv2.imdecode(np.frombuffer(jpg, dtype=np.uint8), cv2.IMREAD_GRAYSCALE)
                    image = cv2.imdecode(np.frombuffer(jpg, dtype=np.uint8), cv2.IMREAD_COLOR)
                    cv2.imshow('image', image)
                    if cv2.waitKey(1) & 0xFF == ord('q'):
                        print("car stopped")
                        break
                    self.count = self.count+1
                    while self.count>50:
                        self.count = 0
                        #predict
                        direction  = predict2(image)
                        self.car.steer(direction)

        finally:
            cv2.destroyAllWindows()
            sys.exit()

class Server(object):
    def __init__(self, host, port1, port2):
        self.host = host
        self.port1 = port1
        self.port2 = port2

    def video_stream(self, host, port):
        s = socketserver.TCPServer((host, port), VideoStreamHandler)
        s.serve_forever()

    def sensor_stream(self, host, port):
        s = socketserver.TCPServer((host, port), SensorDataHandler)
        s.serve_forever()

    def start(self):
        sensor_thread = threading.Thread(target=self.sensor_stream, args=(self.host, self.port2))
        sensor_thread.daemon = True
        sensor_thread.start()
        self.video_stream(self.host, self.port1)

if __name__ == '__main__':
    h, p1, p2 = "192.168.0.104", 8000, 8002

    ts = Server(h, p1, p2)
    ts.start()


from typing import List, Optional

import numpy as np

def find_pareto_frontier_points(all_points: np.ndarray,
                                is_decreasing: Optional[bool] = True) -> List[int]:
    """Takes in a list of n-dimensional points, one per row, returns the list of row indices
        which are Pareto-frontier points.

    Assumes that lower values on every dimension are better.

    Args:
        all_points: N-dimensional points.
        is_decreasing: Whether Pareto-frontier decreases or not.

    Returns:
        List of Pareto-frontier indexes.

    """

    # For each point see if there exists  any other point which dominates it on all dimensions
    # If that is true, then it is not a pareto point and vice-versa

    # Inputs should alwyas be a two-dimensional array
    assert len(all_points.shape) == 2

    pareto_inds = []

    dim = all_points.shape[1]

    for i in range(all_points.shape[0]):
        this_point = all_points[i,:]
        is_pareto = True

        for j in range(all_points.shape[0]):
            if j == i:
                continue

            other_point = all_points[j,:]

            if is_decreasing:
                diff = this_point - other_point
            else:
                diff = other_point - this_point

            if sum(diff > 0) == dim:
                # Other point is smaller/larger on all dimensions
                # so we have found at least one dominating point
                is_pareto = False
                break

        if is_pareto:
            pareto_inds.append(i)

    return pareto_inds


from typing import List, Union, Tuple
from data_structure import ListNode, TreeNode

def singly_list(nodes: Union[List[int], List[list]] = []) -> Union[ListNode, None]:
    nextNode = None
    for e in nodes[::-1]:
        nextNode = ListNode(e, next = nextNode)
    return nextNode

def binary_tree(array: List) -> Union[TreeNode, None]:
    """return the binary tree represented in array using preorder traversal order. For example [1, 2, 4, None, None, 5, None, None, 3, None, None] returns the following tree:
         1
        / \
       2   3
      / \
     4   5
    Args:
        array (List, optional): array representation of the output binary tree. Defaults to [].

    Returns:
        Union[TreeNode, None]: root node of the binary tree.
    """

    if len(array) == 0:
        return None
    root = TreeNode(val = array[0])
    path = [root]
    goLeft = [True]
    for x in array[1:]:
        currentNode = path[-1]
        if x is None:
            if goLeft[-1]:
                goLeft[-1] = False
            else:
                goLeft.pop()
                path.pop()
                while((len(path) > 0) and (not goLeft[-1]) and (path[-1].right is not None)):
                    goLeft.pop()
                    path.pop()
        else:
            if goLeft[-1]:
                currentNode.left = TreeNode(val = x)
                path.append(currentNode.left)
                goLeft[-1] = False
                goLeft.append(True)
            else:
                currentNode.right = TreeNode(val = x)
                path.append(currentNode.right)
                goLeft.append(True)
    return root


from typing import List
from collections import deque, defaultdict

n = 0
mmap = []
dx, dy = (1, 0, -1, 0), (0, 1, 0, -1)
db = defaultdict(list)

def encode(lst):
    ret = 0
    for l in lst:
        ret *= 10
        ret += l
    return ret

def decode(num):
    return list(map(int, list(str(num))))

def _gen_db(lst, sx, sy, d):
    dp = deque([lst[0]])
    for i in range(1, 5):
        item = dp[-1] * 10 + lst[i]
        dp.append(item)
        db[item].append((sx, sy, d))
    for i in range(1, len(lst)):
        sx += dx[d]
        sy += dy[d]
        for j in range(2, len(dp)):
            item = dp[j] % (10**j)
            dp[j] = item
            db[item].append((sx, sy, d))
        try:
            item = dp[-1] * 10 + lst[i + 4]
            dp.append(item)
            db[item].append((sx, sy, d))
        except:
            pass
        dp.popleft()

def init(N:int, mMap:List[List[int]]) -> None:
    global n, mmap, db
    n = N
    mmap = [mMap[i][:n] for i in range(n)]
    db.clear()
    for i in range(n):
        _gen_db(mmap[i], i, 0, 1)
        _gen_db([mmap[j][i] for j in range(n)], 0, i, 0)

def _get_candi_list(M, mStructure):
    global n, db
    ret = []
    structure = mStructure[:M]
    tg = max(structure) + 1
    rg = 6 - tg + min(structure)
    candi = [tg - item for item in structure]
    while rg:
        rg -= 1
        key = encode(candi)
        for cd in db[key]:
            ret.append((key, cd))
        rev_key = encode(candi[::-1])
        if key != rev_key:
            for cd in db[rev_key]:
                ret.append((rev_key, cd))
        for i in range(M):
            candi[i] += 1
    return ret

def numberOfCandidate(M:int, mStructure:List[int]) -> int:
    global n
    if M == 1:
        return n * n
    return len(_get_candi_list(M, mStructure))

def _bfs(structure, candidate, h):
    global n, mmap
    x, y, d = candidate
    copied_map = [[item for item in line] for line in mmap]
    for i in range(len(structure)):
        copied_map[x][y] += structure[i]
        x += dx[d]
        y += dy[d]

    q = deque([])
    start_pos = []
    for i in range(n):
        start_pos.append((0, i))
        start_pos.append((n-1, i))
        if i == 0 or i == n-1:
            continue
        start_pos.append((i, 0))
        start_pos.append((i, n-1))
    for sx, sy in start_pos:
        if not (0 < copied_map[sx][sy] < h):
            continue
        copied_map[sx][sy] = 0
        q.append((sx, sy))
        while q:
            cx, cy = q.popleft()
            for i in range(4):
                nx, ny = cx + dx[i], cy + dy[i]
                if not (0 <= nx < n) or not (0 <= ny < n):
                    continue
                if not (0 < copied_map[nx][ny] < h):
                    continue
                copied_map[nx][ny] = 0
                q.append((nx, ny))

    ret = 0
    for i in range(n):
        for j in range(n):
            if not copied_map[i][j]:
                continue
            ret += 1

    return ret

def maxArea(M:int, mStructure:List[int], mSeaLevel:int) -> int:
    global db
    ret = -1
    structure = mStructure[:M]
    if M == 1:
        candies = []
        k = mStructure[0]
        for i in range(n):
            for j in range(n):
                candies.append((k, (i, j, 0)))
    else:
        candies = _get_candi_list(M, structure)
    for candi in candies:
        ret = max(ret, _bfs(decode(candi[0]), candi[1], mSeaLevel))
    return ret


import tensorflow as tf

import readData
readData.read_data_sets("/media/charles/study/Organized_Nodules")

def weight_variable(shape):
	initial = tf.truncated_normal(shape,stddev=0.1)
	return tf.Variable(initial)

def bias_variable(shape):
	initial = tf.constant(0.1,shape = shape)
	return tf.Variable(initial)

def conv2d(x,W):
	return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding = 'VALID')

#Note that it has a  ifferent pooling scheme in the original LeNet-5
def max_pool_2x2(x):
	return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
x = tf.placeholder(tf.float32,shape=[None,34 * 34])
y = tf.placeholder(tf.float32,shape=[None,1])

#We temmporarily assume that the input CTs has 1 charnel
W_conv1 = weight_variable([3,3,1,32])
b_conv1 = bias_variable([32])

x_image = tf.reshape(x,[-1,34,34,1])

h_conv1 = tf.nn.relu(conv2d(x_image,W_conv1) + b_conv1)# 32 *32 bitmap
h_pool1 = max_pool_2x2(h_conv1)#16 * 16 bitmap

#Note that in LeNet-5 different filter use di fferent conbination of the last level filters
#while we have NOT adopted this scheme
W_conv2 = weight_variable([5,5,32,32])
b_conv2 = bias_variable([32])

h_conv2 = tf.nn.relu(conv2d(h_pool1,W_conv2) + b_conv2)#12 * 12 bitmap
h_pool2 = max_pool_2x2(h_conv2)# 6 * 6 bitmap

W_conv3 = weight_variable([3,3,32,64])
b_conv3 = bias_variable([64])

#4 * 4 bitmap
h_conv3 = tf.nn.relu(conv2d(h_pool2,W_conv3) + b_conv3)

W_fc1 = weight_variable([4 * 4 * 64,64])
b_fc1 = bias_variable([64])

h_conv3_flat = tf.reshape(h_conv3,[-1,4*4*64])

h_fc1 = tf.nn.relu(tf.matmul(h_conv3_flat,W_fc1) + b_fc1)

#dropout omitted

W_fc2 = weight_variable([64,1])
b_fc2 = bias_variable([1])

y_conv = tf.nn.relu(tf.matmul(h_fc1,W_fc2) + b_fc2)

cross_entropy = tf.reduce_mean(#Note: implicit line joining
	tf.nn.softmax_cross_entropy_with_logits(labels = y,logits = y_conv))
train_step = tf.train.AdamOptimizer(0.00001).minimize(cross_entropy)
correct_prediction = tf.equal(y_conv,y)
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))

print("Lung Nodule Classification Experiment")

with tf.Session() as sess:
	sess.run(tf.global_variables_initializer())
	for i in range(2000):
		batch = readData.next_batch(36)
		if i % 100 == 0:

			train_accuracy = accuracy.eval(feed_dict = {
				x : batch[0],y : batch[1]})
			print("step %d, training_accuracy %g" % (i,train_accuracy))
		train_step.run(feed_dict = {x : batch[0],y : batch[1]})

	print("test accuracy %g" % accuracy.eval(feed_dict={
		x : readData.test_data[0],y : readData.test_data[1]}))


import time
import threading
try:
    from greenlet import getcurrent as get_ident
except ImportError:
    try:
        from thread import get_ident
    except ImportError:
        from _thread import get_ident

class CameraEvent(object):
    # Uma classe semelhante a um evento que sinaliza a todos os clientes ativos quando um novo quadro é acessível.
    def __init__(self):
        self.events = {}

    def wait(self):
        # Invocado da thread dos clientes para esperar o novo quadro.
        ident = get_ident()
        if ident not in self.events:
            # Este é um cliente novo
            # Adiciona uma entrada no self.events dict
            # Cada entrada possui dois elementos, threading.Event() e timestamp
            self.events[ident] = [threading.Event(), time.time()]
        return self.events[ident][0].wait()

    def set(self):
        # Invocado pela thread da câmera quando um novo quadro esta disponível.
        now = time.time()
        remove = None
        for ident, event in self.events.items():
            if not event[0].isSet():
                # Se o client's event não está setado, seta ele
                # Atualiza o timestamp
                event[0].set()
                event[1] = now
            else:
                # Se o client's event já está setado, significa que
                # ele não processou um frame anterior, e se
                # o evento fica setado por mais que 5 segundos, o programa
                # assume que o client não está presente e é removido
                if now - event[1] > 5:
                    remove = ident
        if remove:
            del self.events[remove]

    def clear(self):
        # Invoca a thread de cada cliente depois que o quadro for processado.
        self.events[get_ident()][0].clear()

class BaseCamera(object):
    thread = None  # background thread -> lê os frames da câmera.
    frame = None  # current frame -> está armazenado aqui pela background thread.
    last_access = 0  # horário em que houve o último acesso do cliente à câmera.
    event = CameraEvent()

    def __init__(self):
        # Inicia a thread da câmera de fundo, se ainda não estiver em execução.
        if BaseCamera.thread is None:
            BaseCamera.last_access = time.time()

            # Inicia o quadro da background thread.
            BaseCamera.thread = threading.Thread(target=self._thread)
            BaseCamera.thread.start()

            # Espera até que os quadros estejam disponível.
            while self.get_frame() is None:
                time.sleep(0)

    def get_frame(self):
        # Retorna o quadro atual da câmera.
        BaseCamera.last_access = time.time()

        # Espera pelo sinal da thread da câmera.
        BaseCamera.event.wait()
        BaseCamera.event.clear()

        return BaseCamera.frame

    @staticmethod
    def frames():
        # Gerador que retorna os quadros da câmera.
        raise RuntimeError('Must be implemented by subclasses.')

    @classmethod
    def _thread(cls):
        # Background thread câmera.
        print('Starting camera thread.')
        frames_iterator = cls.frames()
        for frame in frames_iterator:
            BaseCamera.frame = frame
            BaseCamera.event.set()  # Envie o sinal para os clientes.
            time.sleep(0)

            # Se não houver clientes requisitando quadros nos últimos 10 segundos então para a thread
            if time.time() - BaseCamera.last_access > 10:
                frames_iterator.close()
                print('Stopping camera thread due to inactivity.')
                break
        BaseCamera.thread = None


print("Enter a string")
s = input()
l = 0
u = len(s)-1
f = 1
while l < u:
    if(s[l] != s[u]):
        print(s+" is not a palindrome")
        f = 0
        break
    l = l+1
    u = u-1
if f==1:
    print(s+" is a palindrome")


def expect(xDistribution, function):
    fxProduct=[px*function(x) for x, px in xDistribution.items()]
    expectation=sum(fxProduct)
    return expectation

def forward(xT_1Distribution, eT, transitionTable, sensorTable):

##################################################
#		Your code here
##################################################
    xTDistribution = {x_t : sensorTable[x_t][eT] * sum(transitionTable[x_t_1][x_t] * xT_1Distribution[x_t_1] for x_t_1 in transitionTable) for x_t in sensorTable}
    alpha = 1 / sum(xTDistribution.values())
    xTDistribution = {x_t : xTDistribution[x_t] * alpha for x_t in xTDistribution}
    return xTDistribution

def main():

    pX0={0:0.3, 1:0.7}
    e=1
    transitionTable={0:{0:0.6, 1:0.4}, 1:{0:0.3, 1:0.7}}
    sensorTable={0:{0:0.6, 1:0.3, 2:0.1}, 1:{0:0, 1:0.5, 2:0.5}}

    xTDistribution=forward(pX0, e, transitionTable, sensorTable)
    print(xTDistribution)

if __name__=="__main__":
    main()