from dotenv import load_dotenv
import os
import tweepy
import time

load_dotenv()

TWITTER_CONSUMER_KEY= os.getenv("TWITTER_CONSUMER_KEY")
TWITTER_CONSUMER_SECRET= os.getenv("TWITTER_CONSUMER_SECRET")
TWITTER_ACCESS_TOKEN= os.getenv("TWITTER_ACCESS_TOKEN")
TWITTER_ACCESS_TOKEN_SECRET= os.getenv("TWITTER_ACCESS_TOKEN_SECRET")

client = tweepy.Client(consumer_key=TWITTER_CONSUMER_KEY,
                    consumer_secret=TWITTER_CONSUMER_SECRET,
                    access_token=TWITTER_ACCESS_TOKEN,
                    access_token_secret=TWITTER_ACCESS_TOKEN_SECRET, wait_on_rate_limit=True)

query = '#kaavish -is:retweet'
kaavish_id = '74840248'
hashtag_file = 'last_hashtag.txt'
mentioned_file = 'last_mentioned.txt'

def read_sinceid():
    file_read = open(hashtag_file, 'r')
    since_id = int(file_read.read().strip())
    file_read.close()
    return since_id

def store_untilid(since_id):
    file_write = open(hashtag_file, 'w')
    file_write.write(str(since_id))
    file_write.close()
    return

def read_mentionedId():
    file_read = open(mentioned_file, 'r')
    since_id = int(file_read.read().strip())
    file_read.close()
    return since_id

def store_mentionedId(since_id):
    file_write = open(mentioned_file, 'w')
    file_write.write(str(since_id))
    file_write.close()
    return

def split_date(id):
    id = str(id)
    datestr = "".join(list(id)[:14])
    return int(datestr)

def like_retweet_hashags():
    since = read_sinceid()
    tweets = client.search_recent_tweets(query=query, since_id=since, max_results=10, user_auth=True)
    if tweets.data != None:
        for tweet in tweets.data:
            client.like(tweet_id=tweet.id)
            client.retweet(tweet_id=tweet.id)
            if tweet.id > since:
                store_untilid(tweet.id)
    else:
        print("Found nothing to like and retweet in hashtags")

def like_mentions():
    since = read_mentionedId()
    tweets = client.get_users_mentions(id=kaavish_id, since_id=since, max_results=10, user_auth=True)
    if tweets.data != None:
        for tweet in tweets.data:
            client.like(tweet_id=tweet.id)
            print(tweet.id)
            if tweet.id > since:
                store_mentionedId(tweet.id)
    else:
        print("Found nothing to like in mentioned tweets")

while True:
    print("Liking and retweeting hashtags")
    like_retweet_hashags()
    print("Liking mentions")
    like_mentions()
    print("Now Sleeping")
    time.sleep(900)


# giu0_rpinoir
# Version: 1.0
# Author: Nuno Sidonio Andrade Pereira
# Date: 2017-05-24
# Description: Uses guizero to build an interface to control RPi NoIR camera
# Developed for: Raspberry Pi 3 B with Raspbian PIXEL and python 3.4
# License: copy, modify, distribute, delete, be happy and enjoy life :-)
#
# Install guizero: sudo pip3 install guizero

# Import from packages
import picamera
import time
from guizero import App, Combo, Slider, Text, TextBox, PushButton, CheckBox, info, yesno, error, warn
from bluedot import BlueDot

# Begin: global variables----------------------------------------------------------
ExposureMode_list = [ 'auto', 'off', 'nightpreview', 'backlight', 'spotlight',
                  'sports', 'snow', 'beach', 'verylong', 'fixedfps',
                  'antishake', 'fireworks' ]

EffectMode_list = [ 'none', 'negative', 'solarize', 'sketch', 'denoise', 'emboss', 'oilpaint',
                'hatch', 'gpen', 'pastel', 'watercolor', 'film', 'blur', 'saturation',
                'colorswap', 'posterise', 'colourpoint', 'colorbalance', 'cartoon',
                'deinterlace1', 'deinterlace2', 'washedout' ]

MeteringMode_list = [ 'average', 'spot', 'backlit', 'matrix' ]

AWBMode_list = [ 'auto', 'off', 'sunlight', 'cloudy', 'shade', 'tungsten', 'fluorescent',
             'incandescent', 'flash', 'horizon' ]

DynamicRangeComp_list = [ 'off', 'low', 'med', 'high' ]

ISO_list = [ 0, 100, 200, 320, 400, 500, 640, 800 ]

Resolution_list = [ '2592x1944', '1920x1080', '1296x972', '1296x730', '1080x720',
                    '1024x768', '800x600', '640x480' ]

Rotation_list = [ 0, 90, 180, 270 ]

picCounter = 1

# Define BluedDot to interact with BluedDot (Android)
BlueDot = BlueDot(auto_start_server=True, print_messages=True)

# Slider values
previewTime_min = 2.
previewTime_max = 20.
AWBgains_scale = 10.

# End: global variables----------------------------------------------------------

# Functions definition

def camera_Modes():

    camera = picamera.PiCamera()

    try:
        print( '\nAWB modes:\n', camera.AWB_MODES )
        print( '\nExposures modes:\n', camera.EXPOSURE_MODES )
        print( '\nMetering modes:\n', camera.METER_MODES )
        print( '\nImage effects:\n', camera.IMAGE_EFFECTS )

    finally:
        camera.close()

def preview_Image():

    global AWBgains_scale
    camera = picamera.PiCamera()

    try:
        camera.framerate = 10
        camera.exposure_mode = Exposure_mode.get()
        effect =  Effect_mode.get()
        camera.image_effect = effect
        camera.meter_mode = Metering_mode.get()
        camera.awb_mode = AWB_mode.get()
        camera.drc_strength = DynamicRangeComp_mode.get()
        camera.iso = int( ISO_value.get() )
        camera.rotation = Rotation_value.get()
        camera.hflip = HFlip_chkbox.get_value()
        camera.vflip = VFlip_chkbox.get_value()
        camera.contrast = int( Contrast.get() )
        camera.awb_gains = float( AWBgains.get() ) / AWBgains_scale
        camera.brightness = int( Brightness.get() )
        camera.saturation = int( Saturation.get() )
        camera.shutter_speed = 0
        camera.start_preview(fullscreen=False, window=(100,100, 640, 480))
        print( '\nPreview is:', camera.previewing )
        fileName = 'RPiNoIR_test_imageEffect_{0}{1}'
        time.sleep( int( previewTime.get() ) )
        camera.exif_tags[ 'IFD=.Artist' ] = 'Nuno S. A. Pereira'
        camera.exif_tags[ 'IFD0.Copyrights' ] = '2017 | nsap'
        # the method format() is used to pass variables to the string fileName
        camera.stop_preview()
        print( 'Preview is:', camera.previewing )

    finally:
        camera.close()

def capture_Image():

    camera = picamera.PiCamera()

    global picCounter
    global AWBgains_scale

    try:
        camera.exposure_mode = Exposure_mode.get()
        effect =  Effect_mode.get()
        camera.image_effect = effect
        camera.meter_mode = Metering_mode.get()
        camera.awb_mode = AWB_mode.get()
        camera.drc_strength = DynamicRangeComp_mode.get()
        camera.iso = int( ISO_value.get() )
        camera.rotation = Rotation_value.get()
        camera.hflip = HFlip_chkbox.get_value()
        camera.vflip = VFlip_chkbox.get_value()
        camera.contrast = int( Contrast.get() )
        camera.awb_gains = float( AWBgains.get() ) / AWBgains_scale
        camera.brightness = int( Brightness.get() )
        camera.saturation = int( Saturation.get() )
        camera.shutter_speed = 0
        camera.resolution = Resolution.get()
        fileName = 'RPiNoIR_%02d_{0}{1}' % picCounter
        camera.exif_tags[ 'IFD=.Artist' ] = 'Nuno S. A. Pereira'
        camera.exif_tags[ 'IFD0.Copyrights' ] = '2017 | nsap'
        # the method format() is used to pass variables to the string fileName
        camera.capture( fileName.format(effect, '.jpg') )
        picCounter += 1
    finally:
        camera.close()

def BlueDot_control():

    if BlueDot.is_connected == True:
        info( 'BlueDot', 'Press bluedot when ready to capture' )
        try:
            BlueDot.wait_for_press()
            BlueDot.wait_for_release()
            capture_Image()
        finally:
            return
    else:
        error( 'BlueDot', 'Device not connected' )

def exit_mode():
    if yesno( 'Exit', 'Do you want to quit?' ):
        print( "Closing application" )
        app.destroy()
    return

# Define master App
app = App( title='RPi NoIR control (v1.0)', width=425, height=335, layout='grid' )

# Exposure mode combo
ExposureMode_label = Text( app, text='Exposure', grid=[1,0], size=10, font='Helvetica', color='Blue', align='left' )
Exposure_mode = Combo( app, options=ExposureMode_list, grid=[1,1], align='left' )

# Image Effect combo
EffectMode_label = Text( app, text='Effect', grid=[2,0], size=10, font='Helvetica', color='Blue', align='left' )
Effect_mode = Combo( app, options=EffectMode_list, grid=[2,1], align='left' )

# Metering mode combo
MeteringMode_label = Text( app, text='Metering', grid=[3,0], size=10, font='Helvetica', color='Blue', align='left' )
Metering_mode = Combo( app, options=MeteringMode_list, grid=[3,1], align='left' )

# AWB mode combo
AWBMode_label = Text( app, text='AWB', grid=[4,0], size=10, font='Helvetica', color='Blue', align='left' )
AWB_mode = Combo( app, options=AWBMode_list, grid=[4,1], align='left' )

# Dynamic range compression combo
DynamicRangeComp_label = Text( app, text='DynRangComp', grid=[5,0], size=10, font='Helvetica', color='Blue', align='left' )
DynamicRangeComp_mode  = Combo( app, options=DynamicRangeComp_list, grid=[5,1], align='left' )

# ISO combo
ISO_label = Text( app, text='ISO', grid=[6,0], size=10, font='Helvetica', color='Blue', align='left' )
ISO_value = Combo( app, options=ISO_list, grid=[6,1], align='left' )

# Rotation combo
Rotation_label = Text( app, text='Rotation', grid=[1,2], size=10, font='Helvetica', color='Blue', align='left' )
Rotation_value = Combo( app, options=Rotation_list, grid=[1,3], align='left' )

# Push buttons
preview_button = PushButton( app, command=preview_Image, text='Preview (s)', grid=[7,0], align='left' )
capture_button = PushButton( app, command=capture_Image, text='  Capture  ', grid=[8,0], align='left' )
exit_button = PushButton( app, command=exit_mode, text='Exit', grid=[9,2], align='left' )
modes_button = PushButton( app, command=camera_Modes, text='Modes', grid=[9,3], align='left' )

# Resolution combo
Resolution_label = Text( app, text='Resolution', grid=[8,1], size=10, font='Helvetica', color='Blue', align='left' )
Resolution = Combo( app, options=Resolution_list, grid=[8,2], align='left')

# BlueDot_button
BlueDot_label = Text( app, text='BlueDot available', grid=[7,2], size=10, font='Helvetica', color='Blue', align='left' )
BlueDot_button = PushButton( app, command=BlueDot_control, text='BlueDot', grid=[8,3], align='left' )

# Check boxes
HFlip_chkbox = CheckBox(app, text='Hflip', grid=[2,2], align="left")
VFlip_chkbox = CheckBox(app, text='Vflip', grid=[2,3], align="left")

# Sliders
previewTime = Slider( app, start=previewTime_min, end=previewTime_max, grid=[7,1] )

# Contrast slider
Contrast_label = Text( app, text='Contrast', grid=[3,2], size=10, font='Helvetica', color='Blue', align='left' )
Contrast = Slider( app, start=-100, end=100, grid=[3,3] )

# AWB gain slider
AWBgains_label = Text( app, text='AWB gains (x10)', grid=[4,2], size=10, font='Helvetica', color='Blue', align='left' )
AWBgains = Slider( app, start=0, end=8*AWBgains_scale, grid=[4,3] )

# Brightness slider
Brightness_label = Text( app, text='Brightness', grid=[5,2], size=10, font='Helvetica', color='Blue', align='left' )
Brightness = Slider( app, start=0, end=100, grid=[5,3] )

# Saturation slider
Saturation_label = Text( app, text='Saturation', grid=[6,2], size=10, font='Helvetica', color='Blue', align='left' )
Saturation = Slider( app, start=-100, end=100, grid=[6,3] )

# Footnote text
footnote = Text( app, text='2017|nsap', grid=[9,0], size='9', font='Helvetica', align='left' )

# execute exit_mode() when user tries to close window
app.on_close( exit_mode )

# Console text
print( '\nRPi NoIR control (v1.0)\n2017|nsap' )

app.display()


from typing import List

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        nums1.sort()
        nums2.sort()
        result = set()

        p1, p2 = 0, 0
        while p1 < len(nums1) and p2 < len(nums2):
            if nums1[p1] == nums2[p2]:
                result.add(nums1[p1])
                p1 += 1
                p2 += 1
            elif nums1[p1] < nums2[p2]:
                p1 += 1
            else:
                p2 += 1
        return list(result)

print(Solution().intersection([1,2],
[1,1]))

LeetCode/3회차/B67_Intersection of Two Arrays3.py


from typing import List  # noqa: F401

from libqtile import bar, layout, widget, extension
from libqtile.config import Click, Drag, Group, Key, Match, Screen
from libqtile.lazy import lazy
from libqtile.utils import guess_terminal
import sys
import os

config_dir = os.path.dirname(__file__)
print("Amy's debug: The config dir is : " + config_dir)
from colour import Colour

logo = "mod4"
alt="mod1"

terminal = guess_terminal()
launcher = "amys-launcher"
keyHelp = "key-help " + config_dir

print("Amy's debug: keyHelp=" + keyHelp)

keys = [
    # A list of available commands that can be bound to keys can be found
    # at https://docs.qtile.org/en/latest/manual/config/lazy.html

    Key([logo], "menu", lazy.spawn(keyHelp), desc="Show key help"),
    Key([], "pause", lazy.spawn(swaylock), desc="Lock screen"),

    # Switch between windows
    Key([logo], "Left", lazy.layout.left(), desc="Move focus to left"),
    Key([logo], "Right", lazy.layout.right(), desc="Move focus to right"),
    Key([logo], "Down", lazy.layout.down(), desc="Move focus down"),
    Key([logo], "Up", lazy.layout.up(), desc="Move focus up"),
    Key([alt], "Tab", lazy.group.next_window(), desc="Move focus to next window"),
    Key([alt, "shift"], "Tab", lazy.group.next_window(), desc="Move focus to next window"),
    # Key([alt], ".", lazy.next_screen(), desc='Next monitor')
    Key([logo], "Tab", lazy.next_screen(), desc="Next monitor"),

    # Move windows between left/right columns or move up/down in current stack.
    # Moving out of range in Columns layout will create new column.
    Key([logo, "shift"], "Left", lazy.layout.shuffle_left(), desc="Move window to the left"),
    Key([logo, "shift"], "Right", lazy.layout.shuffle_right(), desc="Move window to the right"),
    Key([logo, "shift"], "Down", lazy.layout.shuffle_down(), desc="Move window down"),
    Key([logo, "shift"], "Up", lazy.layout.shuffle_up(), desc="Move window up"),

    # Grow windows. If current window is on the edge of screen and direction
    # will be to screen edge - window would shrink.
    Key([logo, "control"], "Left", lazy.layout.grow_left(), desc="Grow window to the left"),
    Key([logo, "control"], "Right", lazy.layout.grow_right(), desc="Grow window to the right"),
    Key([logo, "control"], "Down", lazy.layout.grow_down(), desc="Grow window down"),
    Key([logo, "control"], "Up", lazy.layout.grow_up(), desc="Grow window up"),
    Key([logo], "n", lazy.layout.normalize(), desc="Reset all window sizes"),

    Key([logo, alt], "d", lazy.screen.next_group(), desc="Go to next screen"),

    # Swap??? windows between left/right columns or up/down in current stack.
    Key([logo, alt], "Left", lazy.layout.flip_left(), desc="Move window to the left"),
    Key([logo, alt], "Right", lazy.layout.flip_right(), desc="Move window to the right"),
    Key([logo, alt], "Down", lazy.layout.flip_down(), desc="Move window down"),
    Key([logo, alt], "Up", lazy.layout.flip_up(), desc="Move window up"),

    # Key([logo, "control"], 'Return', lazy.run_extension(extension.WindowList(
    #     dmenu_prompt=">"
    # ))),

    # Toggle between split and unsplit sides of stack.
    # Split = all windows displayed
    # Unsplit = 1 window displayed, like Max layout, but still with
    # multiple stack panes
    # Key([logo, "shift"], "Return", lazy.layout.toggle_split(),
    #     desc="Toggle between split and unsplit sides of stack"),
    Key([logo], "Return", lazy.spawn(launcher), desc="Show launch menu"),
    Key([logo, "shift"], "Return", lazy.spawn(terminal), desc="Launch terminal"),

    # Toggle between different layouts as defined below
    Key([logo, "control"], "l", lazy.next_layout(), desc="Toggle between layouts"),

    Key([logo], "Delete", lazy.window.kill(), desc="Kill focused window"),

    Key([logo, "control"], "r", lazy.reload_config(), desc="Reload the config"),
    Key([logo, "control"], "q", lazy.shutdown(), desc="Shutdown Qtile"),
    # Key([logo], "r", lazy.spawncmd(),
    #     desc="Spawn a command using a prompt widget"),

    Key([logo, "control"], "f", lazy.window.toggle_floating(), desc="Toggle floating"),
    Key([logo, "control", "shift"], "f", lazy.window.toggle_fullscreen(), desc="Toggle fullscreen"),

    Key([alt, "control"], "F1", lazy.core.change_vt(1), desc="Go to virtual console 1"),
    Key([alt, "control"], "F2", lazy.core.change_vt(2), desc="Go to virtual console 2"),
    Key([alt, "control"], "F3", lazy.core.change_vt(3), desc="Go to virtual console 3"),
    Key([alt, "control"], "F4", lazy.core.change_vt(4), desc="Go to virtual console 4"),
    Key([alt, "control"], "F5", lazy.core.change_vt(5), desc="Go to virtual console 5"),
    Key([alt, "control"], "F6", lazy.core.change_vt(6), desc="Go to virtual console 6"),
    Key([alt, "control"], "F7", lazy.core.change_vt(7), desc="Go to virtual console 7"),
    Key([alt, "control"], "F8", lazy.core.change_vt(8), desc="Go to virtual console 8"),
    Key([alt, "control"], "F9", lazy.core.change_vt(9), desc="Go to virtual console 9"),
]

# What other window managers often call "workspaces".
groups = [Group(i) for i in ["1", "2", "3", "4", "5", "6", "7", "8", "9",
                             "nixos", "vmware", "maths", "haskell", "qtile"]]

for g in groups:
    shortcut_key=g.name[0];
    # print(f"DEBUG g={g}, shortcut_key={shortcut_key}")
    keys.extend([
        # mod1 + letter of group = switch to group
        Key([logo], shortcut_key, lazy.group[g.name].toscreen(), desc="Switch to group {}".format(g.name)),

        # mod1 + shift + letter of group = move focused window to group
        Key([logo, "shift"], shortcut_key, lazy.window.togroup(g.name), desc="move focused window to group {}".format(g.name)),
    ])

layouts = [
#    layout.Columns(border_focus_stack=['#d75f5f', '#8f3d3d'], border_width=4),
    layout.Bsp(
        # Border colour(s) for the focused window.
        border_focus=Colour.base0D,
        # Border colour(s) for un-focused windows.
        border_normal=Colour.base04,
	# Border width.
        border_width=6,
        # New clients are inserted in the shortest branch.
	#fair=True,      jupyterlab      jupyterlab

        # Amount by which to grow a window/column.
	#grow_amount=10,
        # New client occupies lower or right subspace.
	#lower_right=True,
	# Margin of the layout (int or list of ints [N E S W]).
        #margin=0,
        # Width/height ratio that defines the partition direction.
        #ratio=1.6
    ),
    layout.Tile(
        # Border colour(s) for the focused window.
        border_focus=Colour.base0D,
        # Border colour(s) for un-focused windows.
        border_normal=Colour.base04,
    )
]

widget_defaults = dict(
    font='sans',
    fontsize=12,
    padding=3,
)
extension_defaults = widget_defaults.copy()

status_bar_widgets = [
    widget.CurrentLayout(),
    widget.CurrentLayoutIcon(),
    widget.CurrentScreen(active_color=Colour.base0A, inactive_colour=Colour.base0D),
    widget.GroupBox(),
    widget.Prompt(),
    # widget.Wlan(
    #         format='{essid} {quality}/70',
    #         update_interval=5
    #     ),
    widget.WindowName(),
    widget.Spacer(length=10),
    widget.Net(
        format='  {interface}: {down} ↓↑ {up}',
        update_interval=10
    ),
    widget.Spacer(length=10),
    widget.Chord(
        chords_colors={
            'launch': ("#ff0000", "#ffffff"),
        },
        name_transform=lambda name: name.upper(),
    ),
    widget.Spacer(length=10),
    widget.ThermalSensor(),
    widget.Spacer(length=10),
    widget.Memory(
        format=' {MemUsed: .0f}{mm}/{MemTotal: .0f}{mm}',
        update_interval=10
    ),
    widget.Spacer(length=10),
    widget.CPU(
        format=' {freq_current}GHz {load_percent}%',
        update_interval=10
    ),
    widget.Spacer(length=10),
    widget.Clock(
        foreground=Colour.base00,
        background=Colour.base0D,
        format='%A, %d %B %Y %H:%M'
    ),
]

screens = [
    Screen(
        bottom=bar.Bar([
            widget.CurrentLayout(),
            widget.CurrentLayoutIcon(),
            widget.CurrentScreen(active_color=Colour.base0A, inactive_colour=Colour.base0D),
            widget.GroupBox(),
            widget.Prompt(),
            # widget.Wlan(
            #         format='{essid} {quality}/70',
            #         update_interval=5
            #     ),
            widget.WindowName(),
            widget.Spacer(length=10),
            widget.Net(
                format='  {interface}: {down} ↓↑ {up}',
                update_interval=10
            ),
            widget.Spacer(length=10),
            widget.Chord(
                chords_colors={
                    'launch': ("#ff0000", "#ffffff"),
                },
                name_transform=lambda name: name.upper(),
            ),
            widget.Spacer(length=10),
            widget.ThermalSensor(),
            widget.Spacer(length=10),
            widget.Memory(
                format=' {MemUsed: .0f}{mm}/{MemTotal: .0f}{mm}',
                update_interval=10
            ),
            widget.Spacer(length=10),
            widget.CPU(
                format=' {freq_current}GHz {load_percent}%',
                update_interval=10
            ),
            widget.Spacer(length=10),
            widget.Clock(
                foreground=Colour.base00,
                background=Colour.base0D,
                format='%A, %d %B %Y %H:%M'
            ),
        ],
        24)),
    Screen(
        bottom=bar.Bar([
            widget.CurrentLayout(),
            widget.CurrentLayoutIcon(),
            widget.CurrentScreen(active_color=Colour.base0A, inactive_colour=Colour.base0D),
            widget.GroupBox(),
            widget.Prompt(),
            # widget.Wlan(
            #         format='{essid} {quality}/70',
            #         update_interval=5
            #     ),
            widget.WindowName(),
            widget.Spacer(length=10),
            widget.Net(
                format='  {interface}: {down} ↓↑ {up}',
                update_interval=10
            ),
            widget.Spacer(length=10),
            widget.Chord(
                chords_colors={
                    'launch': ("#ff0000", "#ffffff"),
                },
                name_transform=lambda name: name.upper(),
            ),
            widget.Spacer(length=10),
            widget.ThermalSensor(),
            widget.Spacer(length=10),
            widget.Memory(
                format=' {MemUsed: .0f}{mm}/{MemTotal: .0f}{mm}',
                update_interval=10
            ),
            widget.Spacer(length=10),
            widget.CPU(
                format=' {freq_current}GHz {load_percent}%',
                update_interval=10
            ),
            widget.Spacer(length=10),
            widget.Clock(
                foreground=Colour.base00,
                background=Colour.base0D,
                format='%A, %d %B %Y %H:%M'
            ),
        ],
        24))
]

# Drag floating layouts.
mouse = [
    Drag([logo], "Button1", lazy.window.set_position_floating(),
         start=lazy.window.get_position()),
    Drag([logo], "Button3", lazy.window.set_size_floating(),
         start=lazy.window.get_size()),
    Click([logo], "Button2", lazy.window.bring_to_front())
]

dgroups_key_binder = None
dgroups_app_rules = []  # type: List
follow_mouse_focus = False
bring_front_click = False
cursor_warp = False
# floating_layout = layout.Floating(float_rules=[
#     # Run the utility of `xprop` to see the wm class and name of an X client.
#     *layout.Floating.default_float_rules,
#     Match(wm_class='confirmreset'),  # gitk
#     Match(wm_class='makebranch'),  # gitk
#     Match(wm_class='maketag'),  # gitk
#     Match(wm_class='ssh-askpass'),  # ssh-askpass
#     Match(title='branchdialog'),  # gitk
#     Match(title='pinentry'),  # GPG key password entry
# ])
auto_fullscreen = True
focus_on_window_activation = "smart"
reconfigure_screens = True

# If things like steam games want to auto-minimize themselves when losing
# focus, should we respect this or not?
auto_minimize = True

# XXX: Gasp! We're lying here. In fact, nobody really uses or cares about this
# string besides java UI toolkits; you can see several discussions on the
# mailing lists, GitHub issues, and other WM documentation that suggest setting
# this string if your java app doesn't work correctly. We may as well just lie
# and say that we're a working one by default.
#
# We choose LG3D to maximize irony: it is a 3D non-reparenting WM written in
# java that happens to be on java's whitelist.
wmname = "LG3D"


import tkinter as tk
import win32api
import win32con
import win32gui
import keyboard
import time

#请安装
#pip install pywin32
#pip install keyboard
#带有蓄能的，使用祭礼的不能使用，除非你保证每次都连续释放。
#夜兰及类似情况的E无法使用，因为无法辨别哪一次E进入冷却。
#当然你也可以通过将预留“时间”加到冷却时间上的办法使用，但准确性无法保证。

#原始参数
cha_skill_cooldown = [20,18,6,8]#输入E技能冷却时间
cha_skillq_cooldown = [20,18,13.5,20]#输入Q技能冷却时间

time.sleep(0.5)
countdown = [0,0,0,0] # 创建一个全局变量来存储倒计时的秒数
create_all = [] #创建所有字符串/图片结合
character_flag = 0 #当前登场人物

# 创建一个窗口
window = tk.Tk()
window.title("genshinSkillCooldown")
window.geometry("400x960")

# 创建一个画布
canvas = tk.Canvas(window, width=640, height=960)
canvas.pack()
textE = canvas.create_text(100, 50, text="E", fill="red", font=("SimHei", 32), tags="texte")
textQ = canvas.create_text(300, 50, text="Q", fill="red", font=("SimHei", 32), tags="textq")
# 加载图片
image1 = tk.PhotoImage(file="image1.png")
image2 = tk.PhotoImage(file="image2.png")
image3 = tk.PhotoImage(file="image3.png")
image4 = tk.PhotoImage(file="image4.png")
image = [image1,image2,image3,image4]

class Pic:
    def __init__(self, name, image,  cha_skill_cooldown, lockkeyb = True):
        self.name = name
        self.image = image
        self.text_id = canvas.create_text(100, 100 + 200 * int(self.name) - 100, text="准备就绪", fill="red", font=("SimHei", 32), tags="text" + self.name)
        self.pic = None
        self.lockkeyb = lockkeyb
        self.lockkeyq = True
        self.cha_skill_cooldown = cha_skill_cooldown
        self.countdown = cha_skill_cooldown

    def create_etext(self, canvas):

        if self.lockkeyb:
            self.lockkeyb = False
            canvas.delete(self.text_id)
            self.text_id = None

            self.text_id = canvas.create_text(100, 100 + 200 * int(self.name) - 100, text=str(self.countdown) + "s", fill="red", font=("Arial", 36), tags="text" + self.name)
            self.update_countdown(canvas)

    def create_qpic(self, time, canvas):
        if self.lockkeyq:
            self.lockkeyq = False
            self.pic = canvas.create_image(200, 200 * int(self.name) - 100, anchor="nw", image=self.image)
            print(int(time*1000))
            canvas.after(int(time*1000), lambda: self.unlockq())

    def unlockq(self):
        canvas.delete(self.pic)
        self.lockkeyq = True

    def update_countdown(self, canvas):
        if self.countdown > 0:
            self.countdown -= 1
            canvas.itemconfig(self.text_id, text=str(self.countdown) + "s")
            canvas.after(1000, lambda: self.update_countdown(canvas))
        else:
            canvas.itemconfig(self.text_id, text="准备就绪", fill="red", font=("SimHei", 32)) # 修改文本内容和属性
            self.countdown = self.cha_skill_cooldown
            self.lockkeyb = True
            #canvas.delete(self.text_id)
            #self.text_id = None

def set_chara(e, chara):
    print(e)
    global character_flag
    chara -= 1
    character_flag = chara
    keyboard.press(str(chara+1))
    #create_all[chara].create_picandtext(chara, canvas)

def input_e(e, character_flag):

    print(e)
    keyboard.press("e")
    create_all[character_flag].create_etext(canvas)

def input_q(e, character_flag):
    print(e)
    keyboard.press("q")
    create_all[character_flag].create_qpic(cha_skillq_cooldown[character_flag], canvas)

for i in range(4):
    create_all.append(Pic(str(i+1), image[i], cha_skill_cooldown[i]))

keyboard.on_press_key("1", lambda e: set_chara(e, 1))
keyboard.on_press_key("2", lambda e: set_chara(e, 2))
keyboard.on_press_key("3", lambda e: set_chara(e, 3))
keyboard.on_press_key("4", lambda e: set_chara(e, 4))

keyboard.on_press_key("e", lambda e: input_e(e, character_flag))
keyboard.on_press_key("q", lambda e: input_q(e, character_flag))

# 获取窗口句柄
hwnd = window.winfo_id()

# 设置窗口为置顶
win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, 0, 0, 0, 0, win32con.SWP_NOMOVE | win32con.SWP_NOSIZE)

# 设置窗口为透明
win32gui.SetWindowLong(hwnd, win32con.GWL_EXSTYLE, win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE) | win32con.WS_EX_LAYERED)
win32gui.SetLayeredWindowAttributes(hwnd, 0, 255, win32con.LWA_ALPHA)

# 进入主循环
window.mainloop()


import torch
import torch.nn as nn
import torchvision.models as models
from build_ssd_layer import SSDLayer

class SSD(nn.Module):
    def __init__(self, num_classes):
        super(SSD, self).__init__()

        basenet = models.resnet50(pretrained=True)

        self.basenet = list(basenet.children())[:-2]
        self.attr_num = num_classes + 4 + 1
        self.encodes = [nn.Conv2d(c, self.attr_num * s, 3, 1, 1) for c, s in zip([512, 1024, 2048], [5, 7, 7])]

        self.ssdlayer = SSDLayer()

    def forward(self, x, target=None):

        features = []

        for m in self.basenet[:-3]:
            x = m(x)

        for i, m in enumerate(self.basenet[-3:]):
            x = m(x)
            out = self.encodes[i](x)
            out = out.view(out.shape[0], self.attr_num, -1, out.shape[2] * out.shape[3]).permute(0, 3, 2, 1).contiguous()
            out = out.view(out.shape[0], -1, self.attr_num).contiguous()
            features += [out]

        features = torch.cat(features, dim=1)
        # print('features: ', features.shape)
        out = self.ssdlayer(features, target)

        return out

if __name__ == '__main__':

    data = torch.rand(2, 3, 320, 320)
    target = [torch.rand(7, 5)] * 2

    ssd = SSD(8)

    ssd(data, target)


from pulsesensor import Pulsesensor
import time
import urlparse
import urllib
import MySQLdb

p = Pulsesensor()
p.startAsyncBPM()

try:
    while True:
        db=MySQLdb.connect("localhost","root","root","location")
        con=db.cursor()
        bpm = p.BPM
        if bpm > 0:
            print("BPM: %d" % bpm)
            #url="http://presentationism-fan.000webhostapp.com/update.php?heart="+str(bpm)
            #urllib.urlopen(url);
        else:
            print("No Heartbeat found")
        time.sleep(1)
        con.execute("UPDATE `state` SET `heart`="+str(bpm)+" WHERE 1")
        db.commit()
        if(bpm>=90):
            con.execute("UPDATE `state` SET `button`=1 WHERE 1")
            db.commit()
        else:
            con.execute("UPDATE `state` SET `button`=0 WHERE 1")
            db.commit()

except:
    p.stopAsyncBPM()


class Solution(object):
    def transpose(self, matrix):
        ROWS, COLS = len(matrix), len(matrix[0])
        ans = []
        for j in range(COLS):
            row = []
            for i in range(ROWS):
                row.append(matrix[i][j])
            ans.append(row)
            row = []

        return ans

answer = Solution()
print(answer.transpose(matrix=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]))


import yaml
import argparse
from edgeutils import ApiSession

parser = argparse.ArgumentParser()
parser.add_argument('-s', '--segment_name', required=True,
                    help='Name of the host segment to modify.')
parser.add_argument('-H', '--hosts_list', required=True,
                    help='Name of the hosts to add to the segment. Comma separated list.',
                    type=str)
group = parser.add_mutually_exclusive_group()
group.add_argument('-u', '--update', action='store_true',
                    help='If host segment exists, merge hosts_list with list of existing hosts.')
group.add_argument('-f', '--force', action='store_true',
                    help='If host segment exists, replace existing hosts with hosts_list.')
args = parser.parse_args()

with open('config.yaml') as f:
    config = yaml.safe_load(f)

api = ApiSession(config)

# Get new hosts
hosts = api.get('agents')
arg_hosts_list = [x.strip().lower() for x in args.hosts_list.split(',')]
new_hosts = [{'id': x['id']} for x in hosts if x['name'].lower() in arg_hosts_list]

if not new_hosts:
    raise Exception('No hosts found for segment')

# Get segments
collections = api.get('collections')['content']
user_collections = [x for x in collections if x['owner'] == 'USER']
segments = [x for x in user_collections if x['query']['type'] == 'HOST']

# Get existing segment, if specified, else None
segment = next((x for x in segments if x['name'] == args.segment_name), None)

# Update/overwrite if exists else create segment
response = None
if segment:
    print("Existing segment '{}' found".format(args.segment_name))
    payload = {}

    # Update the segment if exists and update flag is True
    if args.update:
        print('Updating segment hosts list')
        r = api.get('scopes/{}/scope-data?scopeType=COLLECTION'.format(segment['id']))
        existing_hosts = [{'id': x['id']} for x in r['childScopes'] if x['type'] == 'HOST']
        all_hosts = [*existing_hosts, *new_hosts]
        payload = {'type': 'COLLECTION', 'id': segment['id'], 'name': args.segment_name, 'query': {'type': 'HOST', 'hosts': all_hosts}}

    # Overwrite the segment if exists and force flag is True
    elif args.force:
        print('Overwriting segment hosts list')
        payload = {'type': 'COLLECTION', 'id': segment['id'], 'name': args.segment_name, 'query': {'type': 'HOST', 'hosts': new_hosts}}

    # Error out if segment exists but no update or force flag set
    else:
        raise Exception('Existing segment found, modifying it requires either update or force flag but none set')

    # Execute the update/overwrite
    response = api.put('collections/{}'.format(segment['id']), payload)

else:
    # Create the new segment
    print("Segment '{}' does not exist\nCreating a new segment".format(args.segment_name))
    payload = {'type': 'COLLECTION', 'name': args.segment_name, 'dynamic': True, 'query': {'type': 'HOST', 'hosts': new_hosts}}
    response = api.post('collections', payload)

# Verify and print result
result_hosts = [x['name'].lower() for x in hosts if x['id'] in [y['id'] for y in response['query']['hosts']]]
print("Segment '{}' now contains hosts: {}".format(response['name'], sorted(result_hosts)))


"""Solution to day 23 of Advent of Code"""

from collections import namedtuple, defaultdict
from enum import Enum
from get_input import get_input
from itertools import product
from queue import PriorityQueue
import os

class AmphException(Exception):
    pass

class State(Enum):
    START = "START"
    IN_HALLWAY = "IN_HALLWAY"
    DONE = "DONE"

class Species(Enum):
    AMBER = 1
    BRONZE = 10
    COPPER = 100
    DESERT = 1000

    @staticmethod
    def get_species(letter):
        if letter == 'A':
            return Species.AMBER
        if letter == 'B':
            return Species.BRONZE
        if letter == 'C':
            return Species.COPPER
        if letter == 'D':
            return Species.DESERT

    def get_letter(self):
        if self.name == 'AMBER':
            return 'A'
        if self.name == 'BRONZE':
            return 'B'
        if self.name == 'COPPER':
            return 'C'
        if self.name == 'DESERT':
            return 'D'
        raise NotImplementedError

class Amphipod(namedtuple('Amphipod',
                          ['position', 'species', 'state', 'goal_room'])):
    def __lt__(self, other):
        return (self.species, self.goal_room) < \
               (other.species, other.goal_room)

    def in_room(self):
        return self.position.real > 1 and self.position.imag == self.goal_room

def move_to_room(amp, board):
    position = amp.position
    for row in range(2, 6):
        point = complex(row, amp.goal_room)
        if point not in board.open_spaces:
            break
        if point in board.amps and not board.amps[point].in_room():
            raise AmphException("Room full")
    horiz = 1j if amp.goal_room > position.imag else -1j
    used = 0
    while position.imag != amp.goal_room:
        position += horiz
        used += amp.species.value
        if position in board.amps:
            raise AmphException("No path")
    while board.is_open(position + 1):
        position += 1
        used += amp.species.value
    if position not in board.open_spaces:
        raise NotImplementedError
    return (used, Amphipod(
        position, amp.species, State.DONE, amp.goal_room))

def move_to_hallway(amp, board):
    used, position = 0, amp.position
    # Move to hallway
    while position.real > 1:
        position -= 1
        used += amp.species.value
        if not board.is_open(position):
            # Blocked in
            return
    # move left and right
    queue = [(used, -1j, position), (used, 1j, position)]
    while queue:
        used, step, position = queue.pop()
        if not board.is_open(position):
            continue
        if board.in_hallway(position):
            yield used, Amphipod(
                position, amp.species, State.IN_HALLWAY, amp.goal_room)
        queue.append((used+amp.species.value, step, position+step))

class Board:
    def __init__(self, open_spaces):
        self.open_spaces = open_spaces
        self.room_map = defaultdict(list)
        self.hallway = set()
        for space in open_spaces:
            if space.real > 1:
                self.room_map[space.imag].append(space)
            else:
                self.hallway.add(space)
        self.hallway.difference_update(
            complex(1, rid) for rid in self.room_map.keys()
        )
        for room in self.room_map.values():
            room.sort(key=lambda p: p.real)

    def add_amps(self, amps):
        self.amps = {a.position: a for a in amps}

    def remove_amps(self):
        self.amps.clear()

    @property
    def room(self):
        rooms = {}
        for rid, room in self.room_map.items():
            rooms[rid] = []
            for depth in range(2, 5):
                if complex(depth, rid) in self.amps:
                    rooms[rid].append(self.amps[complex(depth, rid)])
        return rooms

    def is_open(self, position):
        if position not in self.open_spaces:
            return False
        return position not in self.amps

    def in_hallway(self, position):
        return position in self.hallway

    def __str__(self):
        lines = []
        for r in range(7):
            lines.append([])
            for c in range(13):
                point = complex(r, c)
                char = '#'
                if point in self.amps:
                    char = self.amps[point].species.get_letter()
                elif point in self.open_spaces:
                    char = '.'
                lines[-1].append(char)
        return '\n'.join(''.join(line) for line in lines)

def part1(lines):
    amphipods, spaces = lines[:]
    board = Board(spaces)

    room_ids = tuple(sorted(set(p.imag for p in spaces if p.real > 1)))
    assignments = dict(zip(tuple(s for s in Species), room_ids))

    state = [Amphipod(position, species, State.START, assignments[species])
             for species, position in amphipods]
    queue = PriorityQueue()
    queue.put((0, 0, tuple(state)))
    seen = set()
    while not queue.empty():
        energy, steps, state = queue.get()
        board.add_amps(state)
        if state in seen:
            continue
        seen.add(state)
        if all(amp.position.imag == amp.goal_room for amp in state):
            print(' ' * os.get_terminal_size().columns, end='\r')
            return energy
        print(energy, steps, end='\r')
        for a, amp in enumerate(state):
            if amp.state == State.DONE:
                continue
            if amp.state == State.IN_HALLWAY:
                try:
                    used, moved_amp = move_to_room(amp, board)
                except AmphException:
                    pass
                else:
                    moved_state = list(state)
                    moved_state[a] = moved_amp
                    queue.put((energy+used, steps+1, tuple(moved_state)))
            elif amp.state == State.START:
                for used, moved_amp in move_to_hallway(amp, board):
                    moved_state = list(state)
                    moved_state[a] = moved_amp
                    queue.put((energy+used, steps+1, tuple(moved_state)))
        board.remove_amps()

    raise NotImplementedError

def part2(lines):
    amphipods, spaces = lines[:]
    unfolded = list()
    for species, position in amphipods:
        if position.real > 2:
            unfolded.append((species, position+2))
        else:
            unfolded.append((species, position))
    additional = (
        (Species.DESERT, 3+3j),
        (Species.DESERT, 4+3j),
        (Species.COPPER, 3+5j),
        (Species.BRONZE, 4+5j),
        (Species.BRONZE, 3+7j),
        (Species.AMBER, 4+7j),
        (Species.AMBER, 3+9j),
        (Species.COPPER, 4+9j),
    )
    unfolded.extend(additional)
    for c, r in product((3, 5, 7, 9), (4, 5)):
        spaces.add(complex(r, c))
    return part1((unfolded, spaces))

def parse(lines):
    spaces = set()
    amphipods = []
    for r, row in enumerate(lines.splitlines()):
        for c, char in enumerate(row):
            if char == '#' or char == ' ':
                continue
            point = complex(r, c)
            spaces.add(point)
            if char in ('A', 'B', 'C', 'D'):
                amphipods.append((Species.get_species(char), point))
    return amphipods, spaces

TEST = """#############
#...........#
###B#C#B#D###
  #A#D#C#A#
  #########"""

SIMPLE = """#############
#...........#
###B#A#C#D###
  #A#B#C#D#
  #########"""

if __name__ == "__main__":
    LINES = parse(get_input(day=23, year=2021))
    test = parse(TEST)

    assert part1(parse(SIMPLE)) == 46
    assert part1(test) == 12521
    print(f"Part 1: {part1(LINES)}")

    assert part2(test) == 44169
    print(f"Part 2: {part2(LINES)}")


import pygame
from creatures.creature import Creature
from world.world_builder import World
from screens.screen import Screen
from sprites.tileset import TileSet
from misc.helpers import get_line, get_tile_position, is_ne_wall, is_nw_wall, is_outer_corner

def initialize_screen(width, height):
  display = pygame.display.set_mode((width, height))
  tileset = TileSet()
  return Screen(width, height, display, tileset)

def write_active_player(screen: Screen, active: Creature):
  x = screen.width - 192
  y = screen.height - 64
  if active.ap == 0 and active.free_movement == 0:
    y -= 26
    screen.write_right_aligned("Out of AP, press Enter to end turn", (x, y), screen.tileset.get_font())
  if active.loaded_skill:
    y -= 26
    screen.write_right_aligned("Casting " + active.loaded_skill.name, (x, y), screen.tileset.get_font())

def draw_player_stats(screen: Screen, active: Creature, path=[], target: Creature = None):
  x, y = screen.width - 256, 0
  x, y = draw_player_name_box(screen, active, x, y)
  x, y = draw_player_health_mana_armor(screen, active, x, y)

  screen.blit(screen.tileset.get_ui("player_action_points"), (x, y))

  if active.world.in_combat():
    if active.loaded_skill:
      cost = active.loaded_skill.ap_cost
      free_movement = active.free_movement
    elif target:
      cost = active.get_attack_cost()
      free_movement = active.free_movement
    else:
      cost, free_movement = active.cost_of_path(path)
  else:
    cost = 0
    free_movement = active.free_movement

  leftover_ap = active.ap - cost
  for i in range(leftover_ap):
    screen.blit(screen.tileset.get_ui("ap_active"), (x + 3 + i * 25, y + 4))
  for i in range(cost):
    screen.blit(screen.tileset.get_ui("ap_cost"), (x + 3 + leftover_ap * 25 + i * 25, y + 4))
  for i in range(active.max_ap - active.ap):
    screen.blit(screen.tileset.get_ui("ap_inactive"), (x + 3 + active.ap * 25 + i * 25, y + 4))

  if free_movement == active.free_movement:
    colour = screen.tileset.WHITE
  else:
    colour = screen.tileset.HP_RED
  screen.write_centered(str(free_movement), (x + 238, y + 4), screen.tileset.get_font(20), colour)

  x = screen.width - 48 - 4
  y += 33
  for e in active.effects:
    screen.blit(e.icon, (x, y))
    screen.write_right_aligned(e.name + " [" + str(e.duration) + "]", (x - 8, y + 14), screen.tileset.get_font(20))
    y += 22

def display_messages(screen: Screen, messages):
  y = screen.height - 30
  message_height = 20
  y -= message_height * len(messages)
  for i in range(len(messages)):
    message = messages[i]
    screen.write(message.text, (12, y + i * message_height), screen.tileset.get_font(18), message.colour)

def draw_world(screen: Screen, world: World):
  width, height = world.dimensions()
  creature_locations = world.creature_location_dict()
  for x in range(width):
    for y in range(height):
      if not world.has_seen(x,y):
        continue
      sx, sy = get_tile_position(screen.offset_x, screen.offset_y, x * 32, y * 32)
      if sx < -96 or sy < -64 or sx > screen.width or sy > screen.height:
        continue

      can_see = world.can_see(x,y)

      tileset_id = world.tile(x,y).tileset_id
      if world.is_floor(x,y):
        screen.blit(screen.tileset.get_floor(tileset_id), (sx, sy))

        feature = world.get_feature(x,y)
        if feature:
          screen.blit(feature.get_image(), (sx + feature.get_tile_blit_x_mod(), sy + feature.get_tile_blit_y_mod()))
          if not can_see:
            screen.blit(feature.get_shadow(), (sx + feature.get_tile_blit_x_mod(), sy + feature.get_tile_blit_y_mod()))
        items = world.get_inventory(x,y)
        if items:
          screen.blit(screen.tileset.get_misc("satchel"), (sx + 16, sy - 4))

        if can_see:
          if (x,y) in creature_locations:
            creature = creature_locations[(x,y)]
            screen.blit(creature.sprite, (sx + 16, sy - 16))
            ex = sx + 48
            ey = sy - 16
            for e in creature.effects:
              screen.blit(e.sprite, (ex,ey))
              ey += 16

            draw_healthbar(screen, creature, sx, sy)
          if (x,y) in world.projectiles:
            image = world.projectiles[(x,y)]

            offset_x = (64 - image.get_width()) // 2
            offset_y = (24 - image.get_height())
            screen.blit(world.projectiles[(x,y)], (sx + offset_x, sy + offset_y))
        else:
          screen.blit(screen.tileset.get_shadow("floor"), (sx, sy))
      else:
        # These need to be if statements in case its both NW and NE wall (corners)
        nw_wall = is_nw_wall(world, x, y)
        ne_wall = is_ne_wall(world, x, y)
        if is_outer_corner(world, x, y):
          corner_x, corner_y = get_tile_position(screen.offset_x, screen.offset_y, x * 32 + 4, y * 32 - 20)
          screen.blit(screen.tileset.get_corner(tileset_id), (corner_x, corner_y))
        if nw_wall:
          screen.blit(screen.tileset.get_nw_wall(tileset_id), (sx + 24, sy - 20))
        if ne_wall:
          screen.blit(screen.tileset.get_ne_wall(tileset_id), (sx, sy - 20))
        if nw_wall and ne_wall:
          corner_x, corner_y = get_tile_position(screen.offset_x, screen.offset_y, x * 32 + 4, y * 32 - 20)
          screen.blit(screen.tileset.get_corner(tileset_id), (corner_x, corner_y))

        if not world.can_see(x,y):
          if nw_wall or ne_wall:
            screen.blit(screen.tileset.get_shadow("wall"), (sx, sy-16))

def get_healthbar(tileset: TileSet, creature: Creature):
  quarter = creature.get_max_hp() / 4
  if creature.hp == creature.get_max_hp():
    return None
  elif creature.hp > 3 * quarter:
    return tileset.get_ui("health_full")
  elif creature.hp > 2 * quarter:
    return tileset.get_ui("health_most")
  elif creature.hp > quarter:
    return tileset.get_ui("health_half")
  else:
    return tileset.get_ui("health_quarter")

def draw_healthbar(screen: Screen, creature: Creature, x, y):
  healthbar = get_healthbar(screen.tileset, creature)
  p_arm = screen.tileset.get_ui("armor_physical_bar")
  m_arm = screen.tileset.get_ui("armor_magical_bar")
  ax = x + 16
  ay = y + 14
  for i in range(creature.p_armor):
    screen.blit(p_arm, (ax + 5 * i, ay))

  # Start layering the p_armor and m_armor
  if creature.p_armor + creature.m_armor > 6:
    ay -= 6

  # Otherwise show p_armor to the left and m_armor to the right
  else:
    ax += 34 - 5 * creature.m_armor

  for i in range(creature.m_armor):
    screen.blit(m_arm, (ax + 5 * i, ay))

  if healthbar:
    screen.blit(healthbar, (x + 16, y + 20))

  # For debugging a creatures active state
  if not creature.is_active() and creature.can_be_activated():
    ay -= 10
    screen.blit(screen.tileset.get_ui("inactive_icon"), (x + 16, ay))

def draw_player_name_box(screen: Screen, creature: Creature, x, y):
  screen.blit(screen.tileset.get_ui("player_name"), (x + 7, y))
  screen.write_centered(creature.name, (x + 128, y + 5), screen.tileset.get_font(20))
  return (x, y + 32)

def draw_player_health_mana_armor(screen: Screen, creature: Creature, start_x, start_y):
  screen.blit(screen.tileset.get_ui("player_health_and_armor"), (start_x, start_y))

  hp_x = start_x
  hp_y = start_y
  percentage = creature.hp / creature.get_max_hp()
  pygame.draw.rect(screen.display, screen.tileset.HP_RED, (hp_x + 5, hp_y + 5, max(0, int(246 * percentage)), 23))
  hp_string = str(creature.hp) + "/" + str(creature.get_max_hp())
  screen.write_centered(hp_string, (hp_x + 128, hp_y + 6), screen.tileset.get_font(20))

  mana_x = hp_x
  mana_y = hp_y + 31
  if creature.mana > 0:
    percentage = creature.mana / creature.get_max_mana()
    pygame.draw.rect(screen.display, screen.tileset.MANA_BLUE, (mana_x + 5, mana_y + 6, max(0, int(246 * percentage)), 23))
  mana_string = str(creature.mana) + "/" + str(creature.get_max_mana())
  screen.write_centered(mana_string, (mana_x + 128, mana_y + 6), screen.tileset.get_font(20))

  p_armor_x = mana_x
  armor_y = mana_y + 32
  p_armor = creature.p_armor
  rem = creature.get_p_armor_cap() - p_armor
  for i in range(p_armor):
    screen.blit(screen.tileset.get_ui("armor_physical"), (p_armor_x + 5 + i * 20, armor_y + 4))
  for i in range(rem):
    screen.blit(screen.tileset.get_ui("armor_used"), (p_armor_x + 5 + p_armor * 20 + i * 20, armor_y + 4))
  m_armor_x = mana_x + 128
  m_armor = creature.m_armor
  rem = creature.get_m_armor_cap() - m_armor
  for i in range(m_armor):
    screen.blit(screen.tileset.get_ui("armor_magical"), (m_armor_x + 3 + i * 20, armor_y + 4))
  for i in range(rem):
    screen.blit(screen.tileset.get_ui("armor_used"), (m_armor_x + 3 + m_armor * 20 + i * 20, armor_y + 4))

  # Return the bottom left coordinate of this UI element so we can stack more underneath it
  return (p_armor_x, armor_y + 32)

def draw_path_to_mouse(screen: Screen, creature: Creature, x, y):
  # If we are not in combat and we mouse over an inventory or feature, highlight it in yellow
  i = creature.world.get_inventory(x,y)
  f = creature.world.get_feature(x,y)
  if not creature.world.in_combat():
    if (i or f) and creature.simple_distance_to(x,y) <= 1:
      iso_x, iso_y = get_tile_position(screen.offset_x, screen.offset_y, x * 32, y * 32)
      screen.blit(screen.tileset.get_ui("floor_highlight_yellow"), (iso_x, iso_y))
      return [], None

  # If we mouse over a creature and are able to attack it, show the attack interface
  c = creature.world.get_creature_at_location(x, y)
  if c:
    # If we aren't in combat and mouse over a player, highlight them in purple to select them
    if c.is_player() and not creature.world.in_combat():
        iso_x, iso_y = get_tile_position(screen.offset_x, screen.offset_y, c.x * 32, c.y * 32)
        screen.blit(screen.tileset.get_ui("floor_highlight_purple"), (iso_x, iso_y))
        return [], None

    if creature.can_attack(c.x, c.y):
      path = get_line(creature.x, creature.y, c.x, c.y)
      for (dx,dy) in path[1:-1]:
        iso_x, iso_y = get_tile_position(screen.offset_x, screen.offset_y, dx * 32, dy * 32)
        screen.blit(screen.tileset.get_ui("floor_highlight_yellow"), (iso_x, iso_y))
      dx,dy = path[-1]
      iso_x, iso_y = get_tile_position(screen.offset_x, screen.offset_y, dx * 32, dy * 32)
      screen.blit(screen.tileset.get_ui("floor_highlight_red"), (iso_x, iso_y))
      return [], c

  path = creature.get_path_to(x, y)

  # If we mouse over something and are not in range to attack/interact with it, show movement next to it
  if c or i or f:
    path = path[:-creature.get_attack_range()]
  elif i or f:
    path = path[:-1]

  # Highlight the tiles in green to move to the location
  path = path[:creature.get_possible_distance()]
  for tile in path:
    tile_x, tile_y = tile
    iso_x, iso_y = get_tile_position(screen.offset_x, screen.offset_y, tile_x * 32, tile_y * 32)
    screen.blit(screen.tileset.get_ui("floor_highlight_green"), (iso_x, iso_y))
  return path, None

def highlight_ability_target(screen: Screen, creature: Creature, tile_x, tile_y):
  tiles = creature.loaded_skill.get_target_tiles(creature.x, creature.y, tile_x, tile_y)
  creatures = creature.world.creature_location_dict()
  for x,y in tiles:
    if creature.world.is_floor(x,y):
      if (x,y) in creatures:
        if not creature.loaded_skill.friendly_fire:
          if creatures[(x,y)].faction == creature.faction:
            continue
        highlight = screen.tileset.get_ui("floor_highlight_red")
      else:
        highlight = screen.tileset.get_ui("floor_highlight_blue")
      iso_x, iso_y = get_tile_position(screen.offset_x, screen.offset_y, x * 32, y * 32)
      screen.blit(highlight, (iso_x, iso_y))
  return tiles

def show_mouse_tooltips(screen: Screen, world: World, mouse_x, mouse_y, tile_x, tile_y):
  if world.outside_world(tile_x, tile_y) or not world.has_seen(tile_x, tile_y):
    return
  lines = []

  # Showing creature names in tooltips gets cluttered quickly
  # c = world.get_creature_at_location(tile_x, tile_y)
  # if c:
  #   lines.append(c.name)

  i = world.get_inventory(tile_x, tile_y)
  if i:
    c = i.number_of_different_items()
    if c > 3:
      lines.append(str(c) + " different items...")
    for item, quantity in i.get_items():
      s = ""
      if quantity > 1:
        s += str(quantity) + " "
      s += item.name
      if quantity > 1:
        s += "s"
      lines.append(s)

  font = screen.tileset.get_font(16)
  if lines:
    line_height = 18
    line_width = 0
    for line in lines:
      new_width, _ = font.size(line)
      if new_width > line_width:
        line_width = new_width
    x = mouse_x
    y = mouse_y - line_height * len(lines)
    i = 0
    for line in lines:
      pygame.draw.rect(screen.display, screen.tileset.DARK_GREY, (x, y + i * line_height, line_width + 4, line_height))
      screen.write(line, (x+2, y + i * line_height), font)
      i += 1

def draw_buttons(screen: Screen, buttons, mouse_x, mouse_y):
  for b in buttons:
    b.draw(screen, mouse_x, mouse_y)

def draw_end_turn_button(screen: Screen, button, active, mouse_x, mouse_y):
  button.draw(screen, mouse_x, mouse_y)
  if active.ap == 0 and active.free_movement == 0:
    screen.blit(screen.tileset.get_ui("end_turn_highlight"), (button.x, button.y))


#
#
#  File: load_redis_access_py3.py
#
#
#
import json

class Load_Redis_Access(object):

   def __init__( self, app, auth, request, redis_handle ):
       self.app           = app
       self.auth          = auth
       self.request      = request
       self.redis_handle  = redis_handle

       #
       # Redis simple values
       #
       self.rules = [ # simple key, values
                      [ "redis_keys",            self.redis_keys],
                      [ "redis_get",             self.redis_get],
                      [ "redis_set",             self.redis_set],
                      [ "redis_del",             self.redis_del],
                      # list operations
                      ["redis_llen"      , self.redis_llen    ],
                      ["redis_rpush"     , self.redis_rpush   ],
                      ["redis_rpop"       , self.redis_rpop     ],
                      ["redis_lpush"     , self.redis_lpush   ],
                      ["redis_lpop"       , self.redis_lpop    ],
                      ["redis_lget"      , self.redis_lget    ],
                      ["redis_lset"      , self.redis_lset    ],
                      ["redis_ldelete"   , self.redis_ldelete ],
                      ["redis_lrange"     , self.redis_lrange  ],
                      ["redis_ltrim"      , self.redis_ltrim    ],
                      # hash operations
                      [ "redis_hset",               self.redis_hset    ],
                      [ "redis_hkeys",              self.redis_hkeys   ],
                      [ "redis_hget",               self.redis_hget    ],
                      [ "redis_hgetall",            self.redis_hgetall ],
                      [ "redis_hexist",             self.redis_hexist  ],
                      [ "redis_hdel",               self.redis_hdel    ]]

       for i in self.rules:
          a1 = auth.login_required( i[1] )
          app.add_url_rule('/ajax/'+i[0],i[0],a1,methods=["POST"])

   #
   # Functions
   #
   #

   #
   #  Redis Key Value Functions
   #
   #

   def redis_keys( self ):
       parm = self.request.get_json()
       return_value = []
       for i in parm:
           return_value.extend(self.redis_handle.keys(i))
       return return_value

   def redis_get(self):
       return_value = {}
       param = self.request.get_json()
       for i in param:
           temp = self.redis_handle.get( i )
           return_value[i] = temp
       return json.dumps( return_value )

   def redis_set(self):
       return_value = []
       param = self.request.get_json()
       for i,item in param.items():
           self.redis_handle.set( i,item )
       return json.dumps('SUCCESS')

   def redis_del(self):
       return_value = []
       param = self.request.get_json()
       for i in param.keys():
           self.redis_handle.delete( i )
       return json.dumps('SUCCESS')

   #
   #
   # list functions llen rpush, rop, lpush,lpop,  lrange ,ltrim, lset,ldelete
   # list insert is not implemented right now
   #
   #

   def redis_llen( self ):
       return_value = {}
       param = self.request.get_json()
       for i in param:
           temp = self.redis_handle.llen( i )
           return_value[i] = temp
       return json.dumps( return_value )

   def redis_rpush( self ):
       return_value = []
       param = self.request.get_json()
       for i,item in param.items():
           self.redis_handle.rpush( i,item )
       return json.dumps('SUCCESS')

   def redis_rpop( self ):
       return_value = {}
       param = self.request.get_json()
       for i in param:
           temp = self.redis_handle.rpop( i )
           return_value[i] = temp
       return json.dumps( return_value )

   def redis_lpush( self ):
       return_value = []
       param = self.request.get_json()
       for i,item in param.items():
           self.redis_handle.lpush( i,item )
       return json.dumps('SUCCESS')

   def redis_lpop(self ):
       return_value = {}
       param = self.request.get_json()
       for i in param:
           temp = self.redis_handle.rpop( i )
           return_value[i] = temp
       return json.dumps( return_value )

   def redis_lget( self ):
       return_value = {}
       param = self.request.get_json()
       for i in params:
           temp = self.redis_handle.lget( i, items["index"] )
           return_value[i] = { index: items["index"], "value": temp }
       return json.dumps( return_value )

   def redis_lset( self ):
       return_value = []
       param = self.request.get_json()
       for i,items in param.items():
           self.redis_handle.set( i,items["index"],items["value"] )
       return json.dumps('SUCCESS')

   def redis_ldelete(self ):
       param = self.request.get_json()
       token = "------------~~~~~~~~~~~~~~~~~~-----------------"
       key = param["key"]
       list_indexes = param["list_indexes"]
       for i in list_indexes:

           self.redis_handle.lset( key, i, token)
       self.redis_handle.lrem(key,0,token)
       return json.dumps('SUCCESS')

   def redis_lrange( self ):
       return_value = []
       param    = self.request.get_json()
       key      = param["key"]
       start    = param["start"]
       end      = param["end"]
       temp  = self.redis_handle.lrange(key,start,end)
       for i in temp:
          return_value.append(i)
       return json.dumps(return_value)

   def redis_ltrim( self ):
       param    = self.request.get_json()
       key      = param["key"]
       start    = param["start"]
       end      = param["end"]
       self.redis_handle.ltrim(key,start,end)
       return json.dumps('SUCCESS')

   #
   #
   # Hash functions
   #
   #
   #

   def redis_hset(self ):
       return_value = []
       param = self.request.get_json()

       for j in param:
           self.redis_handle.hset( j["redis_key"],j["hash"],j["value"] )
       return json.dumps('SUCCESS')

   def redis_hkeys(self ):
       return_value = {}
       param = self.request.get_json()

       for i in params:
           temp = self.redis_handle.hkeys( i )
           return_value[i] = { "keys":temp }
       return json.dumps( return_value )

   def redis_hget(self ):  # tested
       return_value = {}
       param = self.request.get_json()
       for i in param["key_list"]:
           temp = self.redis_handle.hget( param["hash_name"], i )
           #print("***********",param["hash_name"],i,temp)
           return_value[i] = temp
       return json.dumps( return_value )

   def redis_hgetall(self ): #tested
       return_value = {}
       param = self.request.get_json()
       temp = self.redis_handle.hgetall(param)
       for i,item in temp.items():
           return_value[i] = item
       return json.dumps( return_value )

   def redis_hexist(self ):
       return_value = {}
       param = self.request.get_json()
       for i in params:
           temp = self.redis_handle.hexit( i, items["key"] )
           return_value[i] = temp
       return json.dumps( return_value )

   def redis_hdel(self ):
       return_value = []
       param = self.request.get_json()
       for i,items in param.items():
           self.redis_handle.set( i,items["key"] )
       return json.dumps('SUCCESS')


from time import time
import numpy

bit_length = 32
size = 2 ** 14

print('bit', bit_length)
print('size', size)

dtype_from_bit = {
    8: 'uint8',
    16: 'uint16',
    32: 'uint32',
    64: 'uint64',
}

begin_gen = time()
matrix = numpy.random.randint(
    0, 1 << bit_length, (size, size), dtype_from_bit[bit_length]
)
end_gen = time()
print('mem', matrix.__sizeof__())
print('gen', end_gen - begin_gen)

begin_cpu = time()
parity0 = numpy.bitwise_xor.reduce(matrix)
parity1 = numpy.bitwise_xor.reduce(matrix, 1)
end_cpu = time()
print('cpu', end_cpu - begin_cpu)


import unittest
from balls.language_models.lstm_model import LSTMLanguageModel
from balls.language_models.decoders import FullSoftmaxDecoder
from balls.language_models.language_model import LanguageModel
from balls.language_models.vocab import Vocabulary

class BatchNLLCorrectnessTests(unittest.TestCase):
    def setUp(self):
        vocab = Vocabulary('<unk>', 0)
        vocab.add_from_text('a b c')
        model = LSTMLanguageModel(len(vocab), 10, 10, 2, dropout=0.0)
        decoder = FullSoftmaxDecoder(10, len(vocab))
        self.lm = LanguageModel(model, decoder, vocab)

    def test_no_input(self):
        self.assertEqual(self.lm.batch_nll([], (['a useless prefix'])), [])

    def test_single_sentence(self):
        sentence = 'ab'
        prefix = None
        single_sentence_nll = self.lm.single_sentence_nll(list(sentence), prefix)
        self.assertEqual(self.lm.batch_nll([list(sentence)], prefix), [single_sentence_nll])

    def test_several_sentences(self):
        sentences = ['ab', 'aaab', 'aaca', 'cacc']
        batch = [list(s) for s in sentences]
        prefix = None

        target = [self.lm.single_sentence_nll(s, prefix) for s in sentences]
        self.assertEqual(self.lm.batch_nll(batch, prefix), target)


from AIPlayer import AIPlayer
class SticksGameAI():

    def __init__(self, a_max = 10):
        self.sticks_count = a_max
        self.player_state = 1
        self.game_run = True
        self.f = AIPlayer()

    def game_logic(self):

        while self.game_run == True:

            #player turn
            if self.sticks_count > 1 and self.player_state == 1:

                self.print_current_game_status()
                user_response = self.test_user_input()
                self.dec_sticks(user_response)
                self.player_state = 2

            #AI Turn
            elif self.sticks_count > 1 and self.player_state == 2:
                #setting AI's stick count
                print("There are {} sticks on the table".format(self.sticks_count))
                self.f.set_cur_sticks(self.sticks_count)
                self.dec_sticks(self.f.get_guess())
                self.player_state = 1

            elif self.sticks_count == 1 and self.player_state == 2:
                self.game_run = self.f.ai_lost()
            elif self.sticks_count == 1 and self.player_state == 1:
                self.game_run = self.f.ai_won()
            elif self.sticks_count == 0 and self.player_state == 1:
                self.game_run = self.f.ai_lost()
            elif self.sticks_count == 0 and self.player_state == 2:
                self.game_run = self.f.ai_won()
            else:
                raise UnknownGameState("A player entered too many")

        #storing the smart AI
        self.f.store_win_dict()

    def print_current_game_status(self):
        print("There are {} sticks on the table".format(self.sticks_count))
        print("Player {}: How many do you take? 1, 2, or 3?".format(self.player_state))

    """Decrement stick count"""
    def dec_sticks(self, a_num):
        self.sticks_count -= a_num

    def test_user_input(self):
        valid = True
        while (True):
            a_response = int(input(">>> "))
            if a_response in {1, 2, 3}:
                return int(a_response)
            else:
                print("Please enter a valid response")

    def winner(self, a_winning_player):
        print("%s Wins!" %self.player_state)
        return False

class UnknownGameState(Exception):
    pass

if __name__ == '__main__':
    f = SticksGameAI()
    f.game_logic()


import math
import os
import pickle
from tqdm import tqdm
import random
import copy

import torch
import torch.nn as nn
import gensim
import faiss
import time
from modules import Encoder, LayerNorm

class KMeans(object):
    def __init__(self, num_cluster, seed, hidden_size, gpu_id=0, device="cpu"):
        """
        Args:
            k: number of clusters
        """
        self.seed = seed
        self.num_cluster = num_cluster
        self.max_points_per_centroid = 4096
        self.min_points_per_centroid = 0
        self.gpu_id = 0
        self.device = device
        self.first_batch = True
        self.hidden_size = hidden_size
        self.clus, self.index = self.__init_cluster(self.hidden_size)
        self.centroids = []

    def __init_cluster(
        self, hidden_size, verbose=False, niter=20, nredo=5, max_points_per_centroid=4096, min_points_per_centroid=0
    ):
        print(" cluster train iterations:", niter)
        clus = faiss.Clustering(hidden_size, self.num_cluster)
        clus.verbose = verbose
        clus.niter = niter
        clus.nredo = nredo
        clus.seed = self.seed
        clus.max_points_per_centroid = max_points_per_centroid
        clus.min_points_per_centroid = min_points_per_centroid

        res = faiss.StandardGpuResources()
        res.noTempMemory()
        cfg = faiss.GpuIndexFlatConfig()
        cfg.useFloat16 = False
        cfg.device = self.gpu_id
        index = faiss.GpuIndexFlatL2(res, hidden_size, cfg)
        return clus, index

    def train(self, x):
        # train to get centroids
        if x.shape[0] > self.num_cluster:
            self.clus.train(x, self.index)
        # get cluster centroids
        centroids = faiss.vector_to_array(self.clus.centroids).reshape(self.num_cluster, self.hidden_size)
        # convert to cuda Tensors for broadcast
        centroids = torch.Tensor(centroids).to(self.device)
        self.centroids = nn.functional.normalize(centroids, p=2, dim=1)

    def query(self, x):
        # self.index.add(x)
        D, I = self.index.search(x, 1)  # for each sample, find cluster distance and assignments
        seq2cluster = [int(n[0]) for n in I]
        # print("cluster number:", self.num_cluster,"cluster in batch:", len(set(seq2cluster)))
        seq2cluster = torch.LongTensor(seq2cluster).to(self.device)
        return seq2cluster, self.centroids[seq2cluster]

class SASRecModel(nn.Module):
    def __init__(self, args):
        super(SASRecModel, self).__init__()
        self.item_embeddings = nn.Embedding(args.item_size, args.hidden_size, padding_idx=0)
        self.position_embeddings = nn.Embedding(args.max_seq_length, args.hidden_size)
        self.item_encoder = Encoder(args)
        self.LayerNorm = LayerNorm(args.hidden_size, eps=1e-12)
        self.dropout = nn.Dropout(args.hidden_dropout_prob)
        self.args = args

        self.criterion = nn.BCELoss(reduction="none")
        self.apply(self.init_weights)

    # Positional Embedding
    def add_position_embedding(self, sequence):

        seq_length = sequence.size(1)
        position_ids = torch.arange(seq_length, dtype=torch.long, device=sequence.device)
        position_ids = position_ids.unsqueeze(0).expand_as(sequence)

        item_embeddings = self.item_embeddings(sequence)
        position_embeddings = self.position_embeddings(position_ids)
        sequence_emb = item_embeddings + position_embeddings
        sequence_emb = self.LayerNorm(sequence_emb)
        sequence_emb = self.dropout(sequence_emb)

        return sequence_emb

    # model same as SASRec
    def forward(self, input_ids):

        attention_mask = (input_ids > 0).long()
        extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)  # torch.int64
        max_len = attention_mask.size(-1)
        attn_shape = (1, max_len, max_len)
        subsequent_mask = torch.triu(torch.ones(attn_shape), diagonal=1)  # torch.uint8
        subsequent_mask = (subsequent_mask == 0).unsqueeze(1)
        subsequent_mask = subsequent_mask.long()

        if self.args.cuda_condition:
            subsequent_mask = subsequent_mask.cuda()

        extended_attention_mask = extended_attention_mask * subsequent_mask
        extended_attention_mask = extended_attention_mask.to(dtype=next(self.parameters()).dtype)  # fp16 compatibility
        extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0

        sequence_emb = self.add_position_embedding(input_ids)

        item_encoded_layers = self.item_encoder(sequence_emb, extended_attention_mask, output_all_encoded_layers=True)

        sequence_output = item_encoded_layers[-1]
        return sequence_output

    def init_weights(self, module):
        """ Initialize the weights.
        """
        if isinstance(module, (nn.Linear, nn.Embedding)):
            # Slightly different from the TF version which uses truncated_normal for initialization
            # cf https://github.com/pytorch/pytorch/pull/5617
            module.weight.data.normal_(mean=0.0, std=self.args.initializer_range)
        elif isinstance(module, LayerNorm):
            module.bias.data.zero_()
            module.weight.data.fill_(1.0)
        if isinstance(module, nn.Linear) and module.bias is not None:
            module.bias.data.zero_()

# GRU Encoder
class GRUEncoder(nn.Module):
    r"""GRU4Rec is a model that incorporate RNN for recommendation.

    Note:

        Regarding the innovation of this article,we can only achieve the data augmentation mentioned
        in the paper and directly output the embedding of the item,
        in order that the generation method we used is common to other sequential models.
    """

    def __init__(self, args):
        super(GRUEncoder, self).__init__()

        # load parameters info
        self.item_embeddings = nn.Embedding(args.item_size, args.hidden_size, padding_idx=0)
        self.args = args
        self.embedding_size = args.hidden_size #64
        self.hidden_size = args.hidden_size*2  #128
        self.num_layers = args.num_hidden_layers-1 #1
        self.dropout_prob =args.hidden_dropout_prob #0.3

        # define layers and loss
        self.emb_dropout = nn.Dropout(args.hidden_dropout_prob)
        self.gru_layers = nn.GRU(
            input_size=self.embedding_size,
            hidden_size=self.hidden_size,
            num_layers=self.num_layers,
            bias=False,
            batch_first=True,
        )
        self.dense = nn.Linear(self.hidden_size, self.embedding_size)

    def forward(self, item_seq):
        item_seq_emb = self.item_embeddings(item_seq)
        item_seq_emb_dropout = self.emb_dropout(item_seq_emb)
        gru_output, _ = self.gru_layers(item_seq_emb_dropout)
        gru_output = self.dense(gru_output)
        # the embedding of the predicted item, shape of (batch_size, embedding_size)
        # seq_output = self.gather_indexes(gru_output, item_seq_len - 1)
        seq_output=gru_output
        return seq_output


from django.shortcuts import render
from django.views import View
from verifications.libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from django import http
import random,logging

from . import constants
from meiduo.utils.response_code import RETCODE
from verifications.libs.yuntongxun.ccp_sms import CPP
# Create your views here.

# 创建日志输出器，来记录短信日志
logger = logging.getLogger('django')

class SMSCodeView(View):
    """短信验证码"""
    def get(self,request,mobile):
        """
        :param request:
        :param mobile:手机号
        :return: json
        """
        # 接收参数
        img_code_client = request.GET.get('image_code')
        # print(img_code_client)
        uuid = request.GET.get('uuid')
        # 校验参数
        if not all([img_code_client,uuid]):
            return http.HttpResponseForbidden('缺少必要参数')
        # 创建链接redis的对象
        redis_conn = get_redis_connection('verify_code')

        # 判断用户是否频繁发送短信验证码
        send_flg = redis_conn.get('send_flg_%s' % mobile)
        if send_flg:    # 已经发送过了
            return http.JsonResponse({'code':RETCODE.THROTTLINGERR,'errmsg':'发送短信过于频繁'})

        # 提取图形验证码

        img_code_server = redis_conn.get("img_%s" % uuid)   # 这是一个bytes类型
        if img_code_server is None:
            return http.JsonResponse({'code':RETCODE.IMAGECODEERR,'errmsg':'图形验证码已经失效'})
        # 删除图形验证码
        redis_conn.delete("img_%s" % uuid)
        # 对比图形验证码，将bytes类型转为字符串再比较
        img_code_server = img_code_server.decode()
        if img_code_server.lower() != img_code_client.lower():
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图形验证码有误'})

        # 生产短信验证码 %06d代表，如果不够6位，前面补0
        sms_code = '%06d' % random.randint(0,999999)
        # 手动输出日志，记录短信验证码
        logger.info(sms_code)
        # # 保存短信验证码
        # redis_conn.setex("sms_%s" % mobile,constants.SMS_CODE_REDIS_EXPIRES,sms_code)
        # # 保存发送短信验证码的标记
        # redis_conn.setex('send_flg_%s' % mobile,constants.SEND_SMS_CODE_INTERVAL,1)

        # 创建redis管道
        pl = redis_conn.pipeline()
        # 将命令添加到队列中
        # 保存短信验证码
        pl.setex("sms_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # 保存发送短信验证码的标记
        pl.setex('send_flg_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        # 执行
        pl.execute()

        # 发送短信验证码
        CPP().send_message_sms(mobile,[sms_code,constants.SMS_CODE_REDIS_EXPIRES // 60],constants.SEND_SMS_TEMPLATE_ID)
        return http.JsonResponse({'code':RETCODE.OK,'errmsg':'发送短信成功'})

class ImageCodeView(View):
    """图形验证码"""
    def get(self,request,uuid):
        """
        :param request:
        :param uuid: 通用唯一识别码，用于唯一表示该图形验证码属于哪个用户的
        :return:
        """
        # 接受和校验参数
        # 实现主体业务逻辑：生成图形验证码，保存，响应图形验证码
        # 生成图形验证码
        text,image = captcha.generate_captcha()
        # 保存图片验证码
        redis_conn = get_redis_connection('verify_code')    # 找到dev中配置的redis库
        # 设置键为uuid，值为text，超时时间为300秒
        redis_conn.setex("img_%s" % uuid,constants.IMAGE_CODE_REDIS_EXPIRES,text)  # setex可以设置生存时间
        # 响应图片验证码
        return http.HttpResponse(image,content_type='image/jpg')


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

"""
Created on 03.05.17 15:59

@author: pavel
"""
import logging

from gi.repository import Gtk

log = logging.getLogger(__name__)
from locale import gettext as _

class TextColumn(Gtk.TreeViewColumn):
    def __init__(self, column_name, tooltip_text, model_index_txt,
                 *args, **kwargs):
        super(TextColumn, self).__init__(*args, **kwargs)

        self.title = Gtk.Label(column_name)
        self.title.set_tooltip_text(tooltip_text)
        self.title.show()
        self.set_widget(self.title)

        renderer_text = Gtk.CellRendererText()
        self.cell_renderers = (renderer_text,)

        self.pack_start(renderer_text, expand=True)
        self.add_attribute(renderer_text, "text", model_index_txt)

        self.set_resizable(True)

    def set_attribute(self, name, model_column):
        for renderer in self.cell_renderers:
            self.add_attribute(renderer, name, model_column)

class FlagColumn(Gtk.TreeViewColumn):
    def __init__(self, column_name, tooltip_text, model_index_bool,
                 on_toggle, *args, on_toggle_data=None, **kwargs):
        super(FlagColumn, self).__init__(*args, **kwargs)

        self.title = Gtk.Label(column_name)
        self.title.set_tooltip_text(tooltip_text)
        self.title.show()
        self.set_widget(self.title)

        renderer_flag = Gtk.CellRendererToggle()
        renderer_flag.set_property("activatable", True)
        self.cell_renderers = (renderer_flag,)

        renderer_flag.connect("toggled", on_toggle, on_toggle_data)

        self.pack_start(renderer_flag, expand=False)
        self.add_attribute(renderer_flag, "active", model_index_bool)

        self.set_clickable(True)
        self.set_resizable(False)

        # self.set_sort_indicator(True)

    def set_attribute(self, name, model_column):
        for renderer in self.cell_renderers:
            self.add_attribute(renderer, name, model_column)

class ProfilesViewModel():
    PROF_ID_COL = 0  # int
    PROF_NAME_COL = 1 # str
    PROF_ACTIVE_COL = 2 # bool

    TOOLTIP_COL = 3 #str

    # id, name, active, tooltip
    LIST_STORE_COLUMN_TYPES = [int, str, bool, str]

    TOOLTIP_TEMPLATE = _("<b>{name}:</b> 127.0.0.1:{loc_port} <-> {serv_addr}:{serv_port}")

    def __init__(self, preferences, active_profiles):
        self.preferences = preferences
        self.active_profiles = active_profiles
        self.list_store = Gtk.ListStore(*self.LIST_STORE_COLUMN_TYPES)

        self.load()

    def get_model(self):
        return self.list_store

    def load(self):
        profiles = [(p.get("id"), p) for (k, p) in self.preferences.list_parameters("ssh_profiles")]
        for id_, profile in sorted(profiles):
            active = id_ in self.active_profiles
            name = profile.get("name")

            tooltip = self.TOOLTIP_TEMPLATE.format(name = name,
                                                    loc_port = profile.get("local_port"),
                                                    serv_addr = profile.get("server_addr"),
                                                    serv_port = profile.get("server_port")
                                                  )

            data = [id_, name, active, tooltip]
            self.list_store.append(data)

    def reload(self):
        self.list_store.clear()
        self.load()

    def set_value(self, path, column, value):
        iter_ = self.list_store.get_iter(path)
        self.list_store.set_value(iter_, column, value)

    def get_value(self, path, column):
        iter_ = self.list_store.get_iter(path)
        return self.list_store.get_value(iter_, column)

    def update_active(self):
        iter_ = self.list_store.get_iter_first()
        while iter_ is not None:
            profile_id = self.list_store.get_value(iter_, self.PROF_ID_COL)
            active = profile_id in self.active_profiles
            self.list_store.set_value(iter_, self.PROF_ACTIVE_COL, active)

            #go to next profile
            iter_ = self.list_store.iter_next(iter_)

    def switch_active(self, path):
        actual = self.get_value(path, self.PROF_ACTIVE_COL)
        log.debug(_("Force toggle %s"), path)

        self.set_value(path, self.PROF_ACTIVE_COL, not actual)

    def get_profile_id(self, path):
        return self.get_value(path, self.PROF_ID_COL)

class ProfilesView:
    def __init__(self, builder, preferences, active_profiles, sig_handler):
        self.sig_handler = sig_handler
        self.view = builder.get_object("ssh_profiles_view")
        self.selection = self.view.get_selection()

        self.model = ProfilesViewModel(preferences, active_profiles)

        self.view.set_model(self.model.get_model())
        self.view.set_tooltip_column(self.model.TOOLTIP_COL)

        active_column = FlagColumn(_("Active"), _("Is connected"),
                                   self.model.PROF_ACTIVE_COL,
                                   self.on_profile_activation)
        name_column = TextColumn(_("Profile name"), _("Profile name"),
                                 self.model.PROF_NAME_COL)
        self.view.append_column(active_column)
        self.view.append_column(name_column)

    def update(self):
        self.model.update_active()

    def reload(self):
        self.model.reload()

    def on_profile_activation(self, widget, path, *args):
        print(widget, path, args)
        profile_id = self.model.get_profile_id(path)

        # UI hack
        self.model.switch_active(path)

        self.sig_handler.on_profile_action(profile_id)
        return True

    def get_selected(self):
        if self.selection.count_selected_rows() >= 1:
            path = self.selection.get_selected_rows()[1][0]

            return self.model.get_profile_id(path)


import time

with open('input.txt') as f:
    start = time.time()
    coordinates = set()
    offsets = [(0, 0, 1),
               (0, 0, -1),
               (0, 1, 0),
               (0, -1, 0),
               (1, 0, 0),
               (-1, 0, 0)]
    for line in f.read().split('\n'):
        x, y, z = list(map(int, line.split(',')))
        coordinates.add((x, y, z))
    total_edges = len(coordinates) * 6
    for coordinate in list(coordinates):
        x1, y1, z1 = coordinate
        for offset in offsets:
            x2, y2, z2 = offset
            if (x1 + x2, y1 + y2, z1 + z2) in coordinates:
                total_edges -= 1
    print('Number of exposed edges :', total_edges)
    print('Time taken :', time.time() - start)


import sys
sys.path.append('../')
import numpy as np
from torch.utils.data import DataLoader
import torch
import argparse
import os
from util.util import *
from train.eval import *
from util.scheduler import *
from clustering.domain_split import domain_split
from dataloader.dataloader import random_split_dataloader
from model.purity_predictor import *

if __name__ == '__main__':

    parser = argparse.ArgumentParser()

    parser.add_argument('--data-root', default='/home/arfeen/papers_code/dom_gen_aaai_2020/PACS/kfold/')
    parser.add_argument('--save-root', default='/home/arfeen/papers_code/dom_gen_aaai_2020/')
    parser.add_argument('--result-dir', default='default')
    parser.add_argument('--train', default='general')
    parser.add_argument('--data', default='PACS')
    parser.add_argument('--model', default='caffenet')
    parser.add_argument('--clustering', action='store_true')
    parser.add_argument('--clustering-method', default='Kmeans')
    parser.add_argument('--num-clustering', type=int, default=3)
    parser.add_argument('--clustering-step', type=int, default=1)
    parser.add_argument('--entropy', choices=['default', 'maximum_square'])

    parser.add_argument('--exp-num', type=int, default=0)
    parser.add_argument('--gpu', type=int, default=0)

    parser.add_argument('--num-epoch', type=int, default=30)
    parser.add_argument('--eval-step', type=int, default=1)
    parser.add_argument('--save-step', type=int, default=100)

    parser.add_argument('--batch-size', type=int, default=128)
    #parser.add_argument('--batch-size', type=int, default=16)

    parser.add_argument('--scheduler', default='step')
    parser.add_argument('--lr', type=float, default=0.001)
    parser.add_argument('--lr-step', type=int, default=24)
    parser.add_argument('--lr-decay-gamma', type=float, default=0.1)
    parser.add_argument('--momentum', type=float, default=0.9)

    parser.add_argument('--weight-decay', type=float, default=5e-4)
    parser.add_argument('--nesterov', action='store_true')
                        # default=True,help='use nesterov momentum')

    parser.add_argument('--fc-weight', type=float, default=1.0)
    parser.add_argument('--disc-weight', type=float, default=1.0)
    parser.add_argument('--entropy-weight', type=float, default=1.0)
    parser.add_argument('--grl-weight', type=float, default=1.0)
    parser.add_argument('--loss-disc-weight', action='store_true')

    parser.add_argument('--color-jitter', action='store_true')
    parser.add_argument('--min-scale', type=float, default=0.8)

    parser.add_argument('--instance-stat', action='store_true')
    parser.add_argument('--feature-fixed', action='store_true')
    parser.add_argument('--alpha-mixup', type=float, default=1.0,
                        help='mixup interpolation coefficient (default: 1)')

    args = parser.parse_args()

    path = args.save_root + args.result_dir
    if not os.path.isdir(path):
        os.makedirs(path)
        os.makedirs(path + '/models')

    with open(path+'/args.txt', 'w') as f:
        f.write(str(args))

    domain = get_domain(args.data)
    source_domain, target_domain = split_domain(domain, args.exp_num)

    device = torch.device("cuda:" + str(args.gpu) if torch.cuda.is_available() else "cpu")
    print('device is :', device)
    print("no of epoch:", args.num_epoch)

    get_domain_label, get_cluster = train_to_get_label(args.train, args.clustering)

    print('alpha_mixup is :', args.alpha_mixup)
    print("lr is:", args.lr)
    print("lr step is:", args.lr_step)
    # print('get_domain_label :', get_domain_label)
    # print('get_cluster :', get_cluster)

    source_lbl_train_ldr, source_unlbl_train_ldr, source_val,  target_test, source_lbl_train, source_lbl_train_eval\
        = random_split_dataloader(
        data=args.data, data_root=args.data_root, source_domain=source_domain, target_domain=target_domain,
        batch_size=args.batch_size, get_domain_label=get_domain_label, get_cluster=get_cluster, num_workers=4,
        color_jitter=args.color_jitter, min_scale=args.min_scale)

    # print('source_unlbl_train_ldr is :', list(source_unlbl_train_ldr)[0])
    # print('cls_lbl is :', cls_lbl)
#     num_epoch = int(args.num_iteration / len(source_train))
#     lr_step = int(args.lr_step / min([len(domain) for domain in source_train]))
#     print(num_epoch)
    num_epoch = args.num_epoch
    lr_step = args.lr_step

    disc_dim = get_disc_dim(args.train, args.clustering, len(source_domain), args.num_clustering)

    # print('no of class :',source_lbl_train_ldr.dataset.num_class)
    # model = get_model(args.model, args.train)(
        # num_classes=source_lbl_train.dataset.dataset.num_class, num_domains=disc_dim, pretrained=True)
    model = get_model(args.model, args.train)(
        num_classes=source_lbl_train_ldr.dataset.num_class, num_domains=disc_dim, pretrained=True)

    model = model.to(device)
    reg_model = Purity()
    reg_model = reg_model.to(device)
    #print('model is :', model)
    model_lr = get_model_lr(args.model, args.train, model, reg_model,  fc_weight=args.fc_weight, disc_weight=args.disc_weight)
    #print("model lr:", model_lr)
    optimizers = [get_optimizer( model_part, args.lr * alpha, args.momentum, args.weight_decay,
                                args.feature_fixed, args.nesterov, per_layer=False) for model_part, alpha in model_lr]
    #print("optimizers:", optimizers)
    reg_optimizers = reg_optimizer(reg_model, reg_lr=0.001, momentum=args.momentum, weight_decay=args.weight_decay, nesterov=args.nesterov)
    # "Regression model optimizer"

    if args.scheduler == 'inv':
        schedulers = [get_scheduler(args.scheduler)(optimizer=opt, alpha=10, beta=0.75, total_epoch=num_epoch)
                     for opt in optimizers]
    elif args.scheduler == 'step':
        schedulers = [get_scheduler(args.scheduler)(optimizer=opt, step_size=lr_step, gamma=args.lr_decay_gamma)
                     for opt in optimizers]
        reg_scheduler = get_scheduler('multistep')(optimizer=reg_optimizers, milestones=[10, 40, 80, 150, 200],
                                                   gamma=0.1)
    elif args.scheduler == 'multistep':
        schedulers = [get_scheduler(args.scheduler)(optimizer=opt, milestones =[20, 40, 100, 200], gamma=args.lr_decay_gamma)
                     for opt in optimizers]
        reg_scheduler = get_scheduler('multistep')(optimizer=reg_optimizers, milestones=[10, 40, 80, 150, 200], gamma=0.1)
        print('multistep scheduler is used')
    else:
        raise ValueError('Name of scheduler unknown %s' %args.scheduler)

    best_acc = 0.0
    test_acc = 0.0
    best_epoch = 0
    best_reg_acc = 0

    # if args.alpha_mixup > 0:
    #     lam = np.random.beta(args.alpha_mixup, args.alpha_mixup)
    # else:
    #     lam = 1
    #
    # index = torch.randperm(args.batch_size)

    for epoch in range(num_epoch):

        print('Epoch: {}/{}, Lr: {:.6f}'.format(epoch, num_epoch-1, optimizers[0].param_groups[0]['lr']))
        print('Temporary Best Accuracy is {:.4f} ({:.4f} at Epoch {})'.format(test_acc, best_acc, best_epoch))

        unlbl_dataset = source_unlbl_train_ldr.dataset.dataset
        lbl_dataset = source_lbl_train_ldr.dataset
        if args.clustering:
            if epoch % args.clustering_step == 0:
                pseudo_lbl_domain_label = domain_split(lbl_dataset, model, device=device,
                                                       cluster_before=lbl_dataset.clusters,
                                                       filename=path + '/nmi.txt', epoch=epoch,
                                                       nmb_cluster=args.num_clustering, method=args.clustering_method,
                                                       pca_dim=256, whitening=False, L2norm=False,
                                                       instance_stat=args.instance_stat)
                lbl_dataset.set_cluster(np.array(pseudo_lbl_domain_label))

                pseudo_unlbl_domain_label = domain_split(unlbl_dataset, model, device=device,
                                                         cluster_before=unlbl_dataset.clusters,
                                                         filename=path + '/nmi.txt', epoch=epoch,
                                                         nmb_cluster=args.num_clustering, method=args.clustering_method,
                                                         pca_dim=256, whitening=False, L2norm=False,
                                                         instance_stat=args.instance_stat)
                unlbl_dataset.set_cluster(np.array(pseudo_unlbl_domain_label))

        if args.loss_disc_weight:
            if args.clustering:
                lbl_hist = lbl_dataset.clusters
                unlbl_hist = unlbl_dataset.clusters

            else:
                lbl_hist = lbl_dataset.domains
                unlbl_hist = unlbl_dataset.domains

            lbl_weight = 1. / np.histogram(lbl_hist, bins=model.num_domains)[0]
            lbl_weight = lbl_weight / lbl_weight.sum() * model.num_domains
            lbl_weight = torch.from_numpy(lbl_weight).float().to(device)
            unlbl_weight = 1. / np.histogram(unlbl_hist, bins=model.num_domains)[0]
            unlbl_weight = unlbl_weight / unlbl_weight.sum() * model.num_domains
            unlbl_weight = torch.from_numpy(unlbl_weight).float().to(device)
            weight = (lbl_weight + unlbl_weight)/2

        else:
            weight = None

        # print('weight :', weight)
        # print('unlbl_weight :', unlbl_weight)
        model, optimizers = get_train(args.train)(
            model=model,reg_model = reg_model, reg_optimizers=reg_optimizers, source_lbl_train_ldr=source_lbl_train_ldr, source_unlbl_train_ldr=source_unlbl_train_ldr,
            source_lbl_train=source_lbl_train, optimizers=optimizers, device=device, epoch=epoch, num_epoch=num_epoch,
            filename=path+'/source_train.txt', entropy=args.entropy, alpha_mixup=args.alpha_mixup, disc_weight=weight, entropy_weight=args.entropy_weight,
            grl_weight=args.grl_weight)

        if epoch % args.eval_step == 0:
            acc, reg_acc = eval_model(model, reg_model, source_val, source_lbl_train_eval, device, epoch, path+'/source_eval.txt')
            acc_, reg_acc_ = eval_model(model, reg_model, target_test, source_lbl_train_eval, device, epoch, path+'/target_test.txt')

        if epoch % args.save_step == 0:
            torch.save(model.state_dict(), os.path.join(
                path, 'models',
                "model_{}.pt".format(epoch)))

        if acc >= best_acc:
            best_acc = acc
            test_acc = acc_
            best_epoch = epoch
            torch.save(model.state_dict(), os.path.join(
                path, 'models',
                "model_best.pt"))

        # if reg_acc>=best_reg_acc:
        #     best_reg_acc=reg_acc

        curr_reg_lr = get_reg_lr(reg_optimizers)
        print("Current reg model lr :", curr_reg_lr)
        for scheduler in schedulers:
            scheduler.step()
        reg_scheduler.step()

    best_model = get_model(args.model, args.train)(num_classes=source_lbl_train_ldr.dataset.num_class, num_domains=disc_dim, pretrained=False)
    best_model.load_state_dict(torch.load(os.path.join(
                path, 'models',
                "model_best.pt"), map_location=device))
    best_model = best_model.to(device)
    test_acc = eval_model(best_model, reg_model, target_test, source_lbl_train_eval, device, best_epoch, path+'/target_best.txt')
    print('Test Accuracy by the best model on the source domain is {} (at Epoch {})'.format(test_acc, best_epoch))


import dask
import dask.dataframe

import pyarrow as pa

from .dataset import ReadConfig, Dataset

class ReadArgs(object):
    def __init__(
        self,
        uri,
        cfg,
        attrs,
        region_partitions,
        sample_partitions,
        samples,
        regions,
        samples_file,
        bed_file,
        fnc,
    ):
        self.uri = uri
        self.cfg = cfg
        self.attrs = attrs
        self.region_partitions = region_partitions
        self.sample_partitions = sample_partitions
        self.samples = samples
        self.regions = regions
        self.samples_file = samples_file
        self.bed_file = bed_file
        self.fnc = fnc

def _read_partition(read_args):
    table_fragments = []

    ds = Dataset(read_args.uri, "r", read_args.cfg)
    pyar = ds.read_arrow(
        attrs=read_args.attrs,
        samples=read_args.samples,
        regions=read_args.regions,
        samples_file=read_args.samples_file,
        bed_file=read_args.bed_file,
    )
    table_fragments.append(pyar)

    while not ds.read_completed():
        table_fragments.append(ds.continue_read_arrow(release_buffers=True))

    table = pa.concat_tables(table_fragments, promote=False)

    df = table.to_pandas()

    if read_args.fnc is not None:
        df = read_args.fnc(df)

    return df

def map_dask(
    self,
    fnc,
    attrs,
    region_partitions=1,
    sample_partitions=1,
    limit_partitions=None,
    samples=None,
    regions=None,
    samples_file=None,
    bed_file=None,
):
    """Maps a function on a Dask dataframe obtained by reading from the dataset.

    May be more efficient in some cases than read_dask() followed by a regular
    Dask map operation.

    The remaining parameters are the same as the read_dask() function.

    :return: Dask DataFrame with results
    """
    cfg = self.cfg if self.cfg is not None else ReadConfig()
    partitions = []
    for r in range(0, region_partitions):
        for s in range(0, sample_partitions):
            r_part = (r, region_partitions)
            s_part = (s, sample_partitions)
            cfg = cfg._replace(region_partition=r_part, sample_partition=s_part)
            read_args = ReadArgs(
                self.uri,
                cfg,
                attrs,
                region_partitions,
                sample_partitions,
                samples,
                regions,
                samples_file,
                bed_file,
                fnc,
            )
            partitions.append(dask.delayed(_read_partition)(read_args))

            if limit_partitions is not None and len(partitions) >= limit_partitions:
                break
        else:
            continue
        break

    return dask.dataframe.from_delayed(partitions)

def read_dask(
    self,
    attrs,
    region_partitions=1,
    sample_partitions=1,
    limit_partitions=None,
    samples=None,
    regions=None,
    samples_file=None,
    bed_file=None,
):
    """Reads data from a TileDB-VCF into a Dask DataFrame.

    Partitioning proceeds by a straightforward block distribution, parameterized
    by the total number of partitions and the particular partition index that
    a particular read operation is responsible for.

    Both region and sample partitioning can be used together.

    The remaining parameters are the same as the normal read() function.

    :param int region_partition: Number of partitions over regions
    :param int sample_partition: Number of partitions over samples
    :param int limit_partitions: Maximum number of partitions to read (for testing/debugging)

    :return: Dask DataFrame with results
    """

    return map_dask(
        self,
        None,
        attrs,
        region_partitions,
        sample_partitions,
        limit_partitions,
        samples,
        regions,
        samples_file,
        bed_file,
    )

# Patch functions and members into dataset class
Dataset.read_dask = read_dask
Dataset.map_dask = map_dask