import os
import argparse
import logging
import pandas as pd
import pynwb
from allensdk.brain_observatory.nwb import add_stimulus_timestamps, add_stimulus_presentations, \
    add_eye_gaze_mapping_data_to_nwbfile, read_eye_gaze_mappings

from lims_reader import LIMSReader, LIMSReaderAtHome
from ophys_session import OphysSession, OphysSessionAtHome

logger = logging.getLogger(__name__)

pd.set_option('display.max_columns', None)

def add_motion_correction_cis(session, ophys_module, nwbfile):
    corrected_image_series = pynwb.image.ImageSeries(
        name="motion_corrected_movie",
        description="see external file",
        external_file=["URL"],
        starting_frame=[0],
        format="external",
        timestamps=session.twop_timestamps,
        unit="Fluorescence (a.u.)",
    )
    nwbfile.add_acquisition(corrected_image_series)

    orig_image_series = pynwb.image.ImageSeries(
        name="original_movie",
        description="see external file",
        external_file=["URL"],
        starting_frame=[0],
        format="external",
        timestamps=session.twop_timestamps,
        unit="Fluorescence (a.u.)",
    )
    nwbfile.add_acquisition(orig_image_series)

    mot_corr_traces = pynwb.TimeSeries(
        name="MotionCorrection",
        data=session.motion_correction,
        timestamps=session.twop_timestamps,
        description="Number of pixels shifts measured during motion correction",
        unit="pixels",
    )

    nwbfile.add_acquisition(mot_corr_traces)

    corr_obj = pynwb.ophys.CorrectedImageStack(
        corrected=corrected_image_series,
        original=orig_image_series,
        xy_translation=mot_corr_traces,
    )

    # corrected_image_series.parent = corr_obj
    # mot_corr_traces.parent = corr_obj
    ophys_module.add_data_interface(corr_obj)

def add_motion_correction_pm(session, ophys_module, nwbfile):
    xy_mc = pynwb.TimeSeries(
        name="MotionCorrection",
        data=session.motion_correction,
        timestamps=session.twop_timestamps,
        description="Number of pixels shifts measured during motion correction",
        unit="pixels",
    )

    ophys_module.add_data_interface(xy_mc)

def add_events_discrete(session, ophys_module, nwbfile):
    nwbfile.units = pynwb.misc.Units.from_dataframe(session.units, name='units')
    # events_indices = session.event_indices
    nwbfile.units.add_column(
        name='event_times',
        data=session.event_times,
        index=session.event_indices,
        description='times (s) of detected L0 events'
    )

    nwbfile.units.add_column(
        name='event_amplitudes',
        data=session.event_amps,
        index=session.event_indices,
        description='amplitudes (s) of detected L0 events'
    )

def add_events_contiguous(session, ophys_module, nwbfile, roi_table):
    nwbfile.units = pynwb.misc.Units.from_dataframe(session.units, name='units')

    l0_events = pynwb.ophys.Fluorescence(name='l0_events')
    ophys_module.add_data_interface(l0_events)

    dff_events = session.l0_events_dff
    l0_events.create_roi_response_series(
        name='dff_events',
        data=dff_events,
        rois=roi_table,
        unit='lumens',
        timestamps=session.twop_timestamps[:dff_events.shape[1]]
    )

    true_false_events = session.l0_events_true_false
    l0_events.create_roi_response_series(
        name='true_false_events',
        data=true_false_events,
        rois=roi_table,
        unit='lumens',
        timestamps=session.twop_timestamps[:true_false_events.shape[1]]
    )

def add_eye_tracking(session, ophys_module):
    raw_gaze_mapping_mod = pynwb.ProcessingModule(name='raw_gaze_mapping',
                                                  description='Gaze mapping processing module raw outputs')

    raw_gaze_mapping_mod = add_eye_gaze_data_interfaces(raw_gaze_mapping_mod,
                                                        pupil_areas=eye_gaze_data["raw_pupil_areas"],
                                                        eye_areas=eye_gaze_data["raw_eye_areas"],
                                                        screen_coordinates=eye_gaze_data["raw_screen_coordinates"],
                                                        screen_coordinates_spherical=eye_gaze_data["raw_screen_coordinates_spherical"],
                                                        synced_timestamps=eye_gaze_data["synced_frame_timestamps"])

    # Container for filtered gaze mapped data
    filt_gaze_mapping_mod = pynwb.ProcessingModule(name='filtered_gaze_mapping',
                                                   description='Gaze mapping processing module filtered outputs')

    filt_gaze_mapping_mod = add_eye_gaze_data_interfaces(filt_gaze_mapping_mod,
                                                         pupil_areas=eye_gaze_data["new_pupil_areas"],
                                                         eye_areas=eye_gaze_data["new_eye_areas"],
                                                         screen_coordinates=eye_gaze_data["new_screen_coordinates"],
                                                         screen_coordinates_spherical=eye_gaze_data["new_screen_coordinates_spherical"],
                                                         synced_timestamps=eye_gaze_data["synced_frame_timestamps"])

    return (raw_gaze_mapping_mod, filt_gaze_mapping_mod)

def create_nwb_file(session, nwb_file_path):
    logging.info('Staring session {}'.format(session.session_id))
    nwbfile = pynwb.NWBFile(
        session_description=session.description,
        session_id=str(session.session_id),
        identifier=str(session.experiment_metadata['experiment_id']),
        session_start_time=session.start_time,
        # experiment_description=str(session.experiment_metadata['experiment_id'])
    )

    ### Build the stimulus table ###
    stim_table_df = session.stimulus_table
    nwbfile = add_stimulus_timestamps(nwbfile, stim_table_df['start_time'].values)
    nwbfile = add_stimulus_presentations(nwbfile, stim_table_df)

    ### Image Segmentation ###
    optical_channel = pynwb.ophys.OpticalChannel(
        name='optical_channel',
        description='description',
        emission_lambda=session.emission_wavelength)

    # device = pynwb.device.Device(name='Allen Institute two-photon pipeline: {}'.format(session.session_metadata['rig']))
    device = pynwb.device.Device(name='{}'.format(session.session_metadata['rig']))
    nwbfile.add_device(device)

    imaging_plane = nwbfile.create_imaging_plane(
        name=session.imaging_plane_name,
        optical_channel=optical_channel,
        description=session.imaging_plane_name,
        device=device,
        excitation_lambda=session.excitation_lambda,
        imaging_rate=session.imaging_rate,
        indicator=session.calcium_indicator,
        location='area: {},depth: {}'.format(session.experiment_metadata["area"],
                                             str(session.experiment_metadata["depth"])),
        unit="Fluorescence (au)",
        reference_frame="Intrinsic imaging home",
    )

    ophys_module = nwbfile.create_processing_module(session.ophys_module_name, 'contains optical physiology processed data')

    max_projection = pynwb.ophys.TwoPhotonSeries(
        name='max_project',
        data=[session.max_projection],
        imaging_plane=imaging_plane,
        dimension=[session.image_width, session.image_height],
        rate=30.0
    )
    # nwbfile.add_acquisition(max_projection)
    ophys_module.add_data_interface(max_projection)

    img_seg = pynwb.ophys.ImageSegmentation(name=session.image_segmentation_name)
    ophys_module.add_data_interface(img_seg)
    ps = img_seg.create_plane_segmentation(
        name=session.plane_segmentation_name,
        description="Segmentation for imaging plane (de Vries et al., 2019, Nat Neurosci)",
        imaging_plane=imaging_plane,
    )

    for cell_id, roi_mask in session.roi_masks.items():
        ps.add_roi(id=cell_id, image_mask=roi_mask)

    rt_region = ps.create_roi_table_region(description="segmented cells with cell_specimen_ids")

    ### Fluorescence traces ###
    fluorescence = pynwb.ophys.Fluorescence()
    ophys_module.add_data_interface(fluorescence)

    timestamps = session.twop_timestamps
    raw_traces = session.raw_traces
    assert(raw_traces.shape[1] <= timestamps.shape[0])
    fluorescence.create_roi_response_series(
        name='raw_traces',
        data=raw_traces,
        rois=rt_region,
        unit='lumens',
        timestamps=timestamps[:raw_traces.shape[1]]
    )

    neuropil_traces = session.neuropil_traces
    assert(neuropil_traces.shape[1] <= timestamps.shape[0])
    fluorescence.create_roi_response_series(
        name='neuropil_traces',
        data=neuropil_traces,
        rois=rt_region,
        unit='lumens',
        timestamps=timestamps[:neuropil_traces.shape[1]]
    )

    demixed_traces = session.demixed_traces
    assert(demixed_traces.shape[1] <= timestamps.shape[0])
    fluorescence.create_roi_response_series(
        name='demixed_traces',
        data=demixed_traces,
        rois=rt_region,
        unit='lumens',
        timestamps=timestamps[:demixed_traces.shape[1]]
    )

    dff_traces = session.dff_traces
    assert(dff_traces.shape[1] <= timestamps.shape[0])
    fluorescence.create_roi_response_series(
        name='DfOverF',
        data=session.dff_traces,
        rois=rt_region,
        unit='lumens',
        timestamps=timestamps[:dff_traces.shape[1]]
    )

    ### Running Speed ###
    running_velocity = pynwb.base.TimeSeries(
        name="running_speed",
        data=session.running_velocity[:len(session.stimulus_timestamps)],
        timestamps=session.stimulus_timestamps,
        unit="cm/s",
        description="Speed of the mouse on a rotating wheel",
    )

    behavior_module = pynwb.behavior.BehavioralTimeSeries()
    behavior_module.add_timeseries(running_velocity)
    ophys_module.add_data_interface(behavior_module)

    ### Motion Correction ###
    # NOTE: Older versions of pynwb had a schema bug in ophys.CorrectedImageStack class that prevents it from being
    #       acccessed. Unfortunately currently allensdk has frozen pynwb at version 1.0.2. To fix we need to add the
    #       x/y corrections as a time series rather than using CorrectImageStack.
    # add_motion_correction_cis(session, ophys_module, nwbfile)
    add_motion_correction_pm(session, ophys_module, nwbfile)

    ### Subject and lab metadata ###
    sex_lu = {'F': 'female', 'M': 'male'}
    subject_metadata = pynwb.file.Subject(
        age=session.session_metadata['age'][1:],
        genotype=session.session_metadata['full_genotype'],
        sex=sex_lu.get(session.session_metadata['sex'], 'unknown'),
        species='Mus musculus',
        subject_id=str(session.session_metadata['specimen_id']),
        description=session.session_metadata['name']
    )
    nwbfile.subject = subject_metadata

    ### Events ###
    # add_events_discrete(session=session, ophys_module=ophys_module, nwbfile=nwbfile)
    add_events_contiguous(session=session, ophys_module=ophys_module, nwbfile=nwbfile, roi_table=rt_region)

    # pd.set_option('display.max_columns', None)
    # nwbfile.units = pynwb.misc.Units.from_dataframe(session.units, name='units')
    # # events_indices = session.event_indices
    # nwbfile.units.add_column(
    #     name='event_times',
    #     data=session.event_times,
    #     index=session.event_indices,
    #     description='times (s) of detected L0 events'
    # )
    #
    # nwbfile.units.add_column(
    #     name='event_amplitudes',
    #     data=session.event_amps,
    #     index=session.event_indices,
    #     description='amplitudes (s) of detected L0 events'
    # )

    ### Eye Tracking ###
    eye_dlc_path = session.eye_dlc_screen_mapping
    if eye_dlc_path is not None:
        eye_gazing_data = read_eye_gaze_mappings(eye_dlc_path)
        add_eye_gaze_mapping_data_to_nwbfile(nwbfile, eye_gazing_data)

    with pynwb.NWBHDF5IO(str(nwb_file_path), mode="w") as io:
        io.write(nwbfile)

SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
DEFAULT_TARGETED_MANIFEST = os.path.join(SCRIPT_DIR, 'targeted_manifest.csv')
DEFAULT_OUTPUT_DIR = os.path.join(SCRIPT_DIR, 'output')
DEFAULT_STIM_NAME = 'VisCodingTargetedContrast'

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Package ophys session data into NWB 2.0')
    parser.add_argument('session_ids', type=int, nargs='*',
                        help='The ophys_session_id, or space-separated list, being packaged into NWB format. If none '
                             'are specified will use the --manifest csv file to find ids.')

    parser.add_argument('-m', '--manifest', default=DEFAULT_TARGETED_MANIFEST,
                        help='a csv file containing column of ophys_session_ids, used along with --stimulus-names to '
                             'get session-ids if none are explicitly given')

    parser.add_argument('-s', '--stimulus-name', default=DEFAULT_STIM_NAME,
                        help='stimulus_name value used when using manifest or when rebuilding the lims cache '
                             '(ignored if using specified session_ids). Either single value or comma-separted list.')

    parser.add_argument('-o', '--output-dir', type=str, default=DEFAULT_OUTPUT_DIR,
                        help='directory where nwb session file(s) will be written.')

    parser.add_argument('-c', '--create-cache', action='store_true',
                        help='Connects to the lims database (using --lims-conns) and caches relevant information into '
                             '--lims-cache-dir directory.')

    parser.add_argument('-f', '--force-overwrite', action='store_true',
                        help='overwrite existing nwb file(s) if exists.')

    parser.add_argument('--off-network', action='store_true',
                        help='Only use if you are testing this outside the the AIBS network')

    parser.add_argument('--lims-conns', type=str, default='limsdb2_props.json',
                        help='json file containing lims connectivity props')

    parser.add_argument('--lims-cache-dir', type=str, default='lims_cache',
                        help='Directory of csv caches of ophys_sessions, ophys_experiments and well_know_files table')

    args = parser.parse_args()

    logging.basicConfig(level=logging.INFO, format='[%(levelname)s] %(message)s')

    if args.session_ids is None or len(args.session_ids) == 0:
        parsed_stim_names = args.stimulus_name.split(',')
        manifest_df = pd.read_csv(args.manifest, index_col=0)
        selected_sessions_df = manifest_df[manifest_df['stimulus_name'].isin(parsed_stim_names)]
        session_ids = selected_sessions_df['ophys_session_id'].values
        logger.info('Found {} matching session_ids in {} with stimulus_name values {}'.format(
            len(session_ids), args.manifest, ','.join(parsed_stim_names))
        )
    else:
        session_ids = args.session_ids

    os.makedirs(args.output_dir, exist_ok=True)

    if args.off_network:
        session_cls = OphysSessionAtHome
        lims_reader = LIMSReaderAtHome(old_base_dir='/allen/programs/braintv/production/',
                                       new_base_dir='/data/visual_coding/',
                                       lims_conn_props=None)
    else:
        session_cls = OphysSession
        lims_reader = LIMSReader(lims_conn_props=None)

    if args.create_cache:
        cache_dir = args.lims_cache_dir
        logger.info('(Re)generating the lims cache at {}'.format(cache_dir))
        LIMSReader.build_cache(cache_dir=cache_dir,
                               limsdb_props=args.lims_conns,
                               stimulus_name=args.stimulus_name,
                               overwrite=args.force_overwrite)
        exit()

    for ses_id in session_ids:
        nwb_path = os.path.join(args.output_dir, '{}.nwb'.format(ses_id))
        if not args.force_overwrite and os.path.exists(nwb_path):
            logger.warning('file {} already exists, skipping session (use -f option to overwrite).'.format(nwb_path))
            continue

        session = session_cls(ses_id, lims_reader)
        create_nwb_file(session=session, nwb_file_path=nwb_path)


import pyinputplus as pyip
from scapy.all import *
import pyfiglet
import socket
from datetime import datetime
from tqdm import tqdm

class NetworkTools():
    '''
    1- Net DoS Tester
    2- TCP port Scanner
    3- Honeypot
    4- Fuzzer
    5- DNS and host gathering
    6- Mac address geolocation (samy.pl)
    '''

    def dos_tester(self):
        source_IP = input("Enter IP address of Source: ")
        target_IP = input("Enter IP address of Target: ")
        source_port = int(input("Enter Source Port Number:"))
        i = 1

        while True:
            IP1 = IP(src = source_IP, dst = target_IP)
            TCP1 = TCP(sport = source_port, dport = 80)
            pkt = IP1 / TCP1
            send(pkt, inter = .001)
            print ("packet sent ", i)
            i = i + 1

    def tcp_port_scanner(self):
        ascii_banner = pyfiglet.figlet_format("PORT SCANNER")
        print(ascii_banner)

        target = pyip.inputStr('host name: ')

        # Add Banner
        print("-" * 50)
        print("Scanning Target: " + target)
        print("Scanning started at:" + str(datetime.now()))
        print("-" * 50)

        try:

            # will scan ports between 1 to 65,535
            for port in tqdm(range(1,65535)):
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                socket.setdefaulttimeout(1)

                # returns an error indicator
                result = s.connect_ex((target,port))
                if result ==0:
                    print("\nPort {} is open".format(port))
                s.close()

        except KeyboardInterrupt:
            print("\n Exitting Program !!!!")
        except socket.gaierror:
            print("\n Hostname Could Not Be Resolved !!!!")
        except socket.error:
            print("\n Server not responding !!!!")

        return

    @classmethod
    def writeLog(client, data=''):
        separator = '='*50
        fopen = open('./honey.mmh', 'a')
        fopen.write('Time: %s\nIP: %s\nPort: %d\nData: %s\n%s\n\n'%(str(datetime.now()), client[0], client[1], data, separator))
        print('Time: %s\nIP: %s\nPort: %d\nData: %s\n%s\n\n'%(str(datetime.now()), client[0], client[1], data, separator))
        fopen.close()

    def honeypot(self):
        ascii_banner = pyfiglet.figlet_format("HONEYPOT")
        print(ascii_banner)

        motd = input('MOTD: ')
        host = input('IP Address: ')
        while True:
            try:
                port = int(input('Port: '))
            except TypeError:
                print('Error: Invalid port number.')
                continue
            else:
                if (port < 1) or (port > 65535):
                    print('Error: Invalid port number.')
                    continue
                else:
                    print(host, port, motd)
                    break

        print('Starting honeypot!')
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind((host, port))
        s.listen(100)
        while True:
            (insock, address) = s.accept()
            print('Connection from: %s:%d' % (address[0], address[1]))
            try:
                insock.send('%s\n'%(motd))
                data = insock.recv(1024)
                insock.close()
            except(socket.error,e):
                NetworkTools.writeLog(address)
            else:
                NetworkTools.writeLog(address, data)

# net = NetworkTools()
# net.tcp_port_scanner()


# ==========================================================================
# Utility functions to work with sky images
#
# Copyright (C) 2018 Andrea Bulgarelli, Nicolò Parmiggiani
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# ==========================================================================

import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt

from matplotlib.colors import LogNorm
import numpy as np
from astropy.wcs import WCS
from astropy.io import fits
from astropy.utils.data import get_pkg_data_filename
import os
import scipy.ndimage as ndimage

class SkyImage:
	def __init__(self):
		return

	def display(fitsimage, pngimage, smooth, title):
		#filename = get_pkg_data_filename(fitsimage)
		hdu = fits.open(fitsimage)[0]
		wcs = WCS(hdu.header)

		plt.figure(figsize=(10,10))
		ax = plt.subplot(projection=wcs)
		if title:
			ax.set_title(title, fontsize='large')
		Z2 = ndimage.gaussian_filter(hdu.data, sigma=float(4), order=0)

		cmap = plt.cm.CMRmap
		cmap.set_bad(color='black')

		plt.imshow(Z2,  origin='lower', norm=None, cmap=cmap)
		#interpolation = "gaussian",
		plt.grid(color='white', ls='solid')
		plt.colorbar()
		if wcs.wcs.ctype[0].find('LAT') == 0:
			plt.xlabel('Galactic Longitude')
			plt.ylabel('Galactic Latitude')
		if wcs.wcs.ctype[0].find('RA') == 0:
			plt.xlabel('Right ascension')
			plt.ylabel('Declination')

		plt.savefig(pngimage)

	def dispalywithds9_cts1(file, outfilename, smooth):
		cmd = os.environ['PIPELINE'] + "/GammaPipeCommon/ds9.rb " + str(file) + " " + str(outfilename) + " 1 -1 " + str(smooth) + " B all png 1400x1400 "
		#+ existsFile(mle + ".reg") + " " +  existsFile(mle + ".multi.reg") + " " + existsFile(@regfile)
		os.system(cmd)

		return


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

"""Tests for `pyjournal` package."""

import os
from os import path
from unittest.mock import patch

import pytest
from freezegun import freeze_time
from tinydb import where

from pyjournal.journal_commands import init, today, tasks, topic, open_journal
from pyjournal.utils import makedirs_touch

@pytest.fixture()
def initialized_database(runner, journal_test_dir, test_db):
    """Returns an initialized instance of the database"""
    runner.invoke(init, args=['--path', journal_test_dir])
    yield test_db

@freeze_time('Jan 1 2020')
def test_init(runner, journal_test_dir, test_db):
    # The user initializes the journal
    result = runner.invoke(init, args=['--path', journal_test_dir])
    assert result.exit_code == 0
    assert f'Journal initialized at {journal_test_dir}' in result.output

    config = test_db.get(where('journal_path') == journal_test_dir)
    assert config['journal_path'] == journal_test_dir

    # A directory is created for the journal notes
    assert path.exists(journal_test_dir)

@freeze_time('Jan 1 2020')
@patch('pyjournal.journal_commands.open_editor', autospec=True)
def test_today(open_editor, initialized_database, runner,
               journal_test_dir):
    # The user wants to create a journal entry for today
    # A directory is created for the current year and month
    result = runner.invoke(today)
    assert result.exit_code == 0
    journal_file = path.join(journal_test_dir, '2020/1/1.md')

    # The user is cd'ed into the Journal Directory and vim is opened
    # with the new file
    assert os.getcwd() == journal_test_dir

    open_editor.assert_called_with(journal_file)

@patch('pyjournal.journal_commands.open_editor', autospec=True)
def test_open(open_editor, initialized_database, runner, journal_test_dir):
    # The user wants to create a journal entry for today
    # A directory is created for the current year and month
    result = runner.invoke(open_journal)
    assert result.exit_code == 0

    # The user is cd'ed into the Journal Directory and vim is opened
    # with the new file
    assert os.getcwd() == journal_test_dir
    open_editor.assert_called_with(journal_test_dir)

@freeze_time('Jan 1 2020')
@patch('pyjournal.journal_commands.open_editor', autospec=True)
def test_topic(open_editor, runner, journal_test_dir, initialized_database):
    """The user wants to a new journal file for the input topic"""
    result = runner.invoke(topic, args=['dummy topic'])
    assert result.exit_code == 0

    journal_file = path.join(journal_test_dir, f'topics/dummy-topic.md')
    open_editor.assert_called_with(journal_file)

@freeze_time('Jan 1 2020')
def test_todo(runner, journal_test_dir, initialized_database):
    """The user wants to list all the tasks in their journal"""
    journal_file = path.join(journal_test_dir, '2020/1/1.md')
    makedirs_touch(journal_file)

    # The user opens the journal and add some tasks
    task = 'TODO finish this task!'
    with open(journal_file, '+w') as f:
        f.write(task)

    result = runner.invoke(tasks)
    assert result.exit_code == 0
    assert task in result.output


import pygame #sollte klar sein
import random

pygame.init() #initialisiert pygame

clock = pygame.time.Clock() #classe von pygame zum managhen von fps und timing

#farben in rgb
white = (255,255,255)
black = (0,0,0)
red = (200,0,0)
yellow = (200,200,0)
green = (0,200,0)
blue = (0,0,255)

#bilder laden
shot1 = pygame.image.load("bullet1.png")
playersprite = pygame.image.load("vorne1.png")
gegner = pygame.image.load("btblue3.png")
shot2 = pygame.image.load("bullet2.png")
bg = pygame.image.load("bg.png")

window = pygame.display.set_mode((1000,700)) #fenster öffnen mit größe 1000*700
pygame.display.set_caption("hallo peter") #überschrift des fensters auf "hallo peter" setzen

def collision(x1,y1,x2,y2): #methode um festzustellen ob 2 rechteckige objekte kollidieren
    if (x1 <= x2 <= x1+25 and y1 <= y2 <= y1+25):   #ecke 1 testen
        return True
    elif (x1 <= x2+25 <= x1+25 and y1 <= y2 <= y1+25): #ecke 2 testen
        return True
    elif (x1 <= x2+25 <= x1+25 and y1 <= y2+25 <= y1+25): #ecke 3 testen
        return True
    elif (x1 <= x2 <= x1+25 and y1 <= y2+25 <= y1+25): #ecke 4 testen
        return True
    else:
        return False #falls keine kollision vorliegt

class shot(): #klasse der Bullets
    def __init__(self, posx, posy, typ): #konstruktor parameter: posx/posy=position x/y koordinate, typ: schuss des spielers(1) oder gegners(2)
        self.x = posx
        self.y = posy
        self.t = typ

        self.speed = 20 #fluggeschwindigkeit

    def update(self): # update methoden werden 1 mal pro frame gecalled
        if self.t == 1: #je nach typ bewegt sich die Bullet in eine andere richtung
            self.y -= self.speed
        elif self.t == 2:
            self.y += self.speed

    def checkoffield(self): #überprüfen ob sich die bullet außerhalb des feldes befindet
        if self.x > 1000 or self.x < 0:
            return True
        elif self.y > 700 or self.y < 0:
            return True
        else:
            return False

    def draw(self): #zeichnet die bullet auf den screen (je nach typ andere farbe)
        if self.t == 1:
            window.blit(shot1, (self.x, self.y))
        if self.t == 2:
            window.blit(shot2, (self.x, self.y))

class player(): #klasse des spielers
    def __init__(self): #konstruktor
        self.x = 500 #anfangs x koordinate
        self.mover = False #nach rechts gedrückt(D)?
        self.movel = False #nach links gedrückt(A)?
        self.space = False #schießen(space)?
        self.speed = 10 #bewegungsgesch der spielers
        self.shotsfired = [] #alle schüsse des spielers

    def update(self, enemys):
        if self.movel == True:  #bewegung
            self.x -= self.speed
        if self.mover == True:
            self.x += self.speed

        if self.space == True: #schießen
            self.shotsfired.append(shot(self.x, 650, 1))#fügt dem schussarray einen schuss hinzu
            self.space = False #sorgt dafür dass für jeden schuss neu gedrückt werden muss und nicht jeden frame geschossen wird fals gedrücktgehalten

        for st in self.shotsfired: #loopt über das schussarray
            if st.checkoffield() == True: #falls auserhalb des feldes
                self.shotsfired.remove(st) #entfernt den schuss aus dem array
            for en in enemys: #loopt üpber das array in dem alle gegner sind
                if collision(st.x, st.y, en.x, en.y) == True: #falls die bullet mit dem gegner kollidiert
                    try: #try weil entfernung während der iteration kann problkeme machen (ist nicht besonderst wichtig)
                        self.shotsfired.remove(st) #entfernt den schuss beim treffer ausm array
                        enemys.remove(en) #entfernt den gegner ausm gegnerarray (gegner ist tot)
                    except ValueError:
                        pass
            st.update() #called update für jeden schuss im array
            st.draw() #called draw für jeden schuss im array

    def draw(self): #zeichnet den spieler auf den screen
        window.blit(playersprite, (self.x, 650))

class enemy(): #klasse der gegner
    def __init__(self, posx, posy, d):
        self.x = posx
        self.y = posy
        self.dir = d #True=L False=R
        self.speed = 2 #bewegungsgeschwindigkeit

    def checkswitch(self): #prüfen ob die gegner umdrehen sollen (falls einer auserhalb des fensters)
        if self.x > 1000 or self.x < 0:
            return True

    def update(self):
        #bewegung
        if self.dir == True: #links
            self.x -= self.speed
        else: #rechts
            self.x += self.speed
        return self.checkswitch() #gibt checkswitch() ergebnis zurück

    def draw(self): #zeichnet den gegner
        window.blit(gegner, (self.x, self.y))

p = player() #spielerobjekt

gegners = [] #gegner array
for x in range(15): #15 gegner pro reihe
    for y in range(5):# 5 gegner pro spalte
        gegners.append(enemy(x*50, y*50, True))#fügt die gegner dem array hinzu mit 50pixel abstand

#gameloop
on = True #solange das spiel läuft
while on == True:
    #event handeling (von pygame bereitgestellt)
    for event in pygame.event.get(): #nimmt alle events (knopfdrücke, verschiebungen, mausbewegungen,...) die im fenster passieren
        if event.type == pygame.QUIT: #falls das programm beendet wird
            on = False

        if event.type == pygame.KEYDOWN: #falls ein knopf gedrückt wird
            if event.key == pygame.K_a: #A knopf
                p.movel = True
            if event.key == pygame.K_d: #D knopf
                p.mover = True
            if event.key == pygame.K_SPACE: #Leertaste
                p.space = True

        if event.type == pygame.KEYUP: #falls ein knopf losgelassen wird
            if event.key == pygame.K_a: #a
                p.movel = False
            if event.key == pygame.K_d: #d
                p.mover = False

    window.blit(bg, (0, 0)) #zeichnet den hintergrund

    #gegner draw richtungswechsel update
    for g in gegners: #loopt über alle gener im array
        if g.update() == True: #update und prüfung ob einer außerhalb ist gleichzeitig
            #falls ja
            for gg in gegners: #loopt über alle gener
                if gg.dir == True: #dreht die richtung um
                    gg.dir = False
                else:
                    gg.dir = True
                gg.y += 10 #10pixel nach unten
        if g.y > 700: #falls gegner auserhalb des feldes
            gegners.remove(g) #gegner entfernen
        g.draw() #jeden gegenr im array zeichnen

    if len(gegners) < 75: #falls weniger gegner als 75 (len gibt länge des arrays zurück(anzahl der elemente))
        while len(gegners) < 75: #füpgt gegner dem array hinzu (koordinaten zufällig) solange unter 75 gegner
            gegners.append(enemy( random.randrange(25,950) , 50, gegners[0].dir))

    p.update(gegners) #called update für den spieler
    p.draw() #zeichnet den spieler

    pygame.display.update() #updated den screen und gibt den ganzten frame frei
    clock.tick(30)#parameter = fps

pygame.quit() #beendet pygame
quit() #beendet python


# -*- coding: utf-8 -*-
"""
Created on Fri Sep 14 14:49:03 2018

@author: ASerov
"""

import numpy as np

from sklearn import cluster
import skimage.io

import matplotlib.pyplot as plt

import time

#--------------------------------

def fPSNR(X1, X2):
    '''
    Peak signal-to-noise ratio
    '''

    return(10*np.log10(X1.shape[0]*X1.shape[1]/np.sum((X1 - X2)**2)))

#--------------------------------

raw_image = skimage.img_as_float(skimage.io.imread('parrots.jpg'))

#Transforming color intensity to object-feature matrix
Xtr = raw_image.reshape(raw_image.shape[0]*raw_image.shape[1], 3)

#Starting number of clusters and desired PSNR
xclt = 1
maxclt = 25

xPSNR = 0
minPSNR = 25

while (xclt <= maxclt) and (xPSNR < minPSNR):
    t0 = time.clock()
    clt = cluster.k_means(Xtr, xclt, init = 'k-means++', random_state = 241)

    Xclt_av = np.zeros(Xtr.shape) #Filling cluster points with average color
    Xclt_med = np.zeros(Xtr.shape) #Filling cluster points with median color

    for xlab in np.unique(clt[1]):
        Xclt_av[clt[1] == xlab, :] = np.tile(
                np.mean(Xtr[clt[1] == xlab, :], axis = 0),
                (sum(clt[1] == xlab), 1))
        Xclt_med[clt[1] == xlab, :] = np.tile(
                np.median(Xtr[clt[1] == xlab, :], axis = 0),
                (sum(clt[1] == xlab), 1))

    PSNR_av = fPSNR(Xtr, Xclt_av)
    PSNR_med = fPSNR(Xtr, Xclt_med)

    xPSNR = max(PSNR_av, PSNR_med)

    print("Processed {0} clusters. Best PSNR = {1:.2f}. Time taken: {2:.2f} sec".
          format(xclt, xPSNR, time.clock() - t0))

    if xPSNR < minPSNR:
        xclt += 1

#--------------------------------

if xPSNR < minPSNR:
    print('''Unfortunately, PSNR level of {0:.2f}
    could not be reached with {1} or less clusters'''.format(minPSNR, maxclt))
    print("Best level of PSNR is {0:.2f}".format(minPSNR))
else:
    print("PSNR of {0:.2f} reached with {1} clusters".
          format(xPSNR, xclt))

clt_image_av = Xclt_av.reshape((raw_image.shape[0], raw_image.shape[1], 3))
clt_image_med = Xclt_med.reshape((raw_image.shape[0], raw_image.shape[1], 3))

fig = plt.figure(figsize = (8, 6))
plt.imshow(raw_image)
plt.title("Original image")

fig = plt.figure(figsize = (8, 6))
plt.imshow(clt_image_av)
plt.title("Averaging colors, {0} clusters, PSNR = {1:.2f}".
          format(xclt if xclt <= maxclt else maxclt, PSNR_av))

fig = plt.figure(figsize = (8, 6))
plt.imshow(clt_image_med)
plt.title("Median colors, {0} clusters, PSNR = {1:.2f}".
          format(xclt if xclt <= maxclt else maxclt, PSNR_med))


import pytest

from fbchat import Plan, FBchatFacebookError, ThreadType
from utils import random_hex, subset
from time import time

@pytest.fixture(
    scope="module",
    params=[
        Plan(int(time()) + 100, random_hex()),
        pytest.param(
            Plan(int(time()), random_hex()),
            marks=[pytest.mark.xfail(raises=FBchatFacebookError)],
        ),
        pytest.param(Plan(0, None), marks=[pytest.mark.xfail()]),
    ],
)
def plan_data(request, client, user, thread, catch_event, compare):
    with catch_event("onPlanCreated") as x:
        client.createPlan(request.param, thread["id"])
    assert compare(x)
    assert subset(
        vars(x.res["plan"]),
        time=request.param.time,
        title=request.param.title,
        author_id=client.uid,
        going=[client.uid],
        declined=[],
    )
    plan_id = x.res["plan"]
    assert user["id"] in x.res["plan"].invited
    request.param.uid = x.res["plan"].uid
    yield x.res, request.param
    with catch_event("onPlanDeleted") as x:
        client.deletePlan(plan_id)
    assert compare(x)

@pytest.mark.tryfirst
def test_create_delete_plan(plan_data):
    pass

def test_fetch_plan_info(client, catch_event, plan_data):
    event, plan = plan_data
    fetched_plan = client.fetchPlanInfo(plan.uid)
    assert subset(
        vars(fetched_plan), time=plan.time, title=plan.title, author_id=int(client.uid)
    )

@pytest.mark.parametrize("take_part", [False, True])
def test_change_plan_participation(
    client, thread, catch_event, compare, plan_data, take_part
):
    event, plan = plan_data
    with catch_event("onPlanParticipation") as x:
        client.changePlanParticipation(plan, take_part=take_part)
    assert compare(x, take_part=take_part)
    assert subset(
        vars(x.res["plan"]),
        time=plan.time,
        title=plan.title,
        author_id=client.uid,
        going=[client.uid] if take_part else [],
        declined=[client.uid] if not take_part else [],
    )

@pytest.mark.trylast
def test_edit_plan(client, thread, catch_event, compare, plan_data):
    event, plan = plan_data
    new_plan = Plan(plan.time + 100, random_hex())
    with catch_event("onPlanEdited") as x:
        client.editPlan(plan, new_plan)
    assert compare(x)
    assert subset(
        vars(x.res["plan"]),
        time=new_plan.time,
        title=new_plan.title,
        author_id=client.uid,
    )

@pytest.mark.trylast
@pytest.mark.expensive
def test_on_plan_ended(client, thread, catch_event, compare):
    with catch_event("onPlanEnded") as x:
        client.createPlan(Plan(int(time()) + 120, "Wait for ending"))
        x.wait(180)
    assert subset(
        x.res,
        thread_id=client.uid if thread["type"] == ThreadType.USER else thread["id"],
        thread_type=thread["type"],
    )

# createPlan(self, plan, thread_id=None)
# editPlan(self, plan, new_plan)
# deletePlan(self, plan)
# changePlanParticipation(self, plan, take_part=True)

# onPlanCreated(self, mid=None, plan=None, author_id=None, thread_id=None, thread_type=None, ts=None, metadata=None, msg=None)
# onPlanEnded(self, mid=None, plan=None, thread_id=None, thread_type=None, ts=None, metadata=None, msg=None)
# onPlanEdited(self, mid=None, plan=None, author_id=None, thread_id=None, thread_type=None, ts=None, metadata=None, msg=None)
# onPlanDeleted(self, mid=None, plan=None, author_id=None, thread_id=None, thread_type=None, ts=None, metadata=None, msg=None)
# onPlanParticipation(self, mid=None, plan=None, take_part=None, author_id=None, thread_id=None, thread_type=None, ts=None, metadata=None, msg=None)

# fetchPlanInfo(self, plan_id)


# coding: utf-8

"""
    VisWiz.io API Documentation

    This SDK allows you to query and create new projects, builds or images within the VisWiz service.   # noqa: E501

    OpenAPI spec version: 1.1.0
    Contact: support@viswiz.io
    Generated by: https://github.com/swagger-api/swagger-codegen.git
"""

import pprint
import re  # noqa: F401

import six

from viswiz_sdk.models.build import Build  # noqa: F401,E501
from viswiz_sdk.models.build_results_images import BuildResultsImages  # noqa: F401,E501

class BuildResults(object):
    """NOTE: This class is auto generated by the swagger code generator program.

    Do not edit the class manually.
    """

    """
    Attributes:
      swagger_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """
    swagger_types = {
        'build': 'Build',
        'comparison_build': 'Build',
        'images': 'list[BuildResultsImages]'
    }

    attribute_map = {
        'build': 'build',
        'comparison_build': 'comparisonBuild',
        'images': 'images'
    }

    def __init__(self, build=None, comparison_build=None, images=None):  # noqa: E501
        """BuildResults - a model defined in Swagger"""  # noqa: E501

        self._build = None
        self._comparison_build = None
        self._images = None
        self.discriminator = None

        if build is not None:
            self.build = build
        if comparison_build is not None:
            self.comparison_build = comparison_build
        if images is not None:
            self.images = images

    @property
    def build(self):
        """Gets the build of this BuildResults.  # noqa: E501

        :return: The build of this BuildResults.  # noqa: E501
        :rtype: Build
        """
        return self._build

    @build.setter
    def build(self, build):
        """Sets the build of this BuildResults.

        :param build: The build of this BuildResults.  # noqa: E501
        :type: Build
        """

        self._build = build

    @property
    def comparison_build(self):
        """Gets the comparison_build of this BuildResults.  # noqa: E501

        :return: The comparison_build of this BuildResults.  # noqa: E501
        :rtype: Build
        """
        return self._comparison_build

    @comparison_build.setter
    def comparison_build(self, comparison_build):
        """Sets the comparison_build of this BuildResults.

        :param comparison_build: The comparison_build of this BuildResults.  # noqa: E501
        :type: Build
        """

        self._comparison_build = comparison_build

    @property
    def images(self):
        """Gets the images of this BuildResults.  # noqa: E501

        The list of images resulted from the comparison (both identical and different)  # noqa: E501

        :return: The images of this BuildResults.  # noqa: E501
        :rtype: list[BuildResultsImages]
        """
        return self._images

    @images.setter
    def images(self, images):
        """Sets the images of this BuildResults.

        The list of images resulted from the comparison (both identical and different)  # noqa: E501

        :param images: The images of this BuildResults.  # noqa: E501
        :type: list[BuildResultsImages]
        """

        self._images = images

    def to_dict(self):
        """Returns the model properties as a dict"""
        result = {}

        for attr, _ in six.iteritems(self.swagger_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value

        return result

    def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict())

    def __repr__(self):
        """For `print` and `pprint`"""
        return self.to_str()

    def __eq__(self, other):
        """Returns true if both objects are equal"""
        if not isinstance(other, BuildResults):
            return False

        return self.__dict__ == other.__dict__

    def __ne__(self, other):
        """Returns true if both objects are not equal"""
        return not self == other


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

import unittest
from flask import Flask, session, json
from coaster.app import load_config_from_file
from coaster.views import get_current_url, get_next_url, jsonp, requestargs, BadRequest

def index():
    return "index"

def external():
    return "external"

def somewhere():
    return "somewhere"

@requestargs('p1', ('p2', int), ('p3[]', int))
def f(p1, p2=None, p3=None):
    return p1, p2, p3

@requestargs('p1', ('p2', int), ('p3[]'))
def f1(p1, p2=None, p3=None):
    return p1, p2, p3

class TestCoasterViews(unittest.TestCase):
    def setUp(self):
        self.app = Flask(__name__)
        load_config_from_file(self.app, "settings.py")
        self.app.add_url_rule('/', 'index', index)
        self.app.add_url_rule('/', 'external', external)
        self.app.add_url_rule('/somewhere', 'somewhere', )

    def test_get_current_url(self):
        with self.app.test_request_context('/'):
            self.assertEqual(get_current_url(), '/')

        with self.app.test_request_context('/?q=hasgeek'):
            self.assertEqual(get_current_url(), '/?q=hasgeek')

        self.app.config['SERVER_NAME'] = 'example.com'

        with self.app.test_request_context('/somewhere', environ_overrides={'HTTP_HOST': 'example.com'}):
            self.assertEqual(get_current_url(), '/somewhere')

        with self.app.test_request_context('/somewhere', environ_overrides={'HTTP_HOST': 'sub.example.com'}):
            self.assertEqual(get_current_url(), 'http://sub.example.com/somewhere')

    def test_get_next_url(self):
        with self.app.test_request_context('/?next=http://example.com'):
            self.assertEqual(get_next_url(external=True), 'http://example.com')
            self.assertEqual(get_next_url(), '/')
            self.assertEqual(get_next_url(default=()), ())

        with self.app.test_request_context('/'):
            session['next'] = '/external'
            self.assertEqual(get_next_url(session=True), '/external')

    def test_jsonp(self):
        with self.app.test_request_context('/?callback=callback'):
            kwargs = {'lang': 'en-us', 'query': 'python'}
            r = jsonp(**kwargs)
            response = 'callback({\n  "%s": "%s",\n  "%s": "%s"\n});' % ('lang', kwargs['lang'], 'query', kwargs['query'])
            self.assertEqual(response, r.data)

        with self.app.test_request_context('/'):
            param1, param2 = 1, 2
            r = jsonp(param1=param1, param2=param2)
            resp = json.loads(r.response[0])
            self.assertEqual(resp['param1'], param1)
            self.assertEqual(resp['param2'], param2)
            r = jsonp({'param1': param1, 'param2': param2})
            resp = json.loads(r.response[0])
            self.assertEqual(resp['param1'], param1)
            self.assertEqual(resp['param2'], param2)
            r = jsonp([('param1', param1), ('param2', param2)])
            resp = json.loads(r.response[0])
            self.assertEqual(resp['param1'], param1)
            self.assertEqual(resp['param2'], param2)

    def test_requestargs(self):
        with self.app.test_request_context('/?p3=1&p3=2&p2=3&p1=1'):
            self.assertEqual(f(), (u'1', 3, [1, 2]))

        with self.app.test_request_context('/?p2=2'):
            self.assertEqual(f(p1='1'), (u'1', 2, None))

        with self.app.test_request_context('/?p3=1&p3=2&p2=3&p1=1'):
            self.assertEqual(f1(), (u'1', 3, [u'1', u'2']))

        with self.app.test_request_context('/?p2=2&p4=4'):
            self.assertRaises(TypeError, f, p4='4')
            self.assertRaises(BadRequest, f, p4='4')


import tkinter as tk
import tkinter.ttk as ttk
import webbrowser

import requests
from bs4 import BeautifulSoup
from Root import ProgramBase

class PTTCrawler() :
    def __init__(self , board = 'movie'):
        self.domain = 'https://www.ptt.cc'
        self.page = self.domain + '/bbs/{0}/index.html'.format(board)

    def getPosts(self , board) :
        self.page = self.domain + '/bbs/{0}/index.html'.format(board)
        response = requests.get(self.page)
        soup = BeautifulSoup(response.text, 'lxml')

        articles = soup.find_all('div', 'r-ent')
        posts = []
        for article in articles :
            meta = article.find('div', 'title').find('a')
            if not meta :
                continue
            posts.append({
                'title': meta.getText().strip(),
                'link': meta.get('href'),
                'push': article.find('div', 'nrec').getText(),
                'date': article.find('div', 'date').getText(),
                'author': article.find('div', 'author').getText(),
            })
        return posts

    def getPage(self) :
        return self.page

    def getDomain(self):
        return self.domain

class PTTViewer(ProgramBase) :
    postbg = '#ddeedd'
    def __init__(self , root , width = 800 , height = 600) :
        super().__init__(root , width , height)
        self.root.title("PTT Posts")
        self.crawler = PTTCrawler()
        self.posts = []
        self.loadLayout()

    def getBoards(self) :
        url = 'https://www.ptt.cc/bbs/hotboards.html'
        urlbase = 'https://www.ptt.cc'

        r = requests.get(url)
        web_content = r.text
        soup = BeautifulSoup(web_content, 'html.parser')

        boardNameElements = soup.find_all('div', class_='board-name')
        boardNames = [e.text for e in boardNameElements] #becomes a  list
        print (boardNames)
        return boardNames

    def showPage(self , board) :
        self.posts = self.crawler.getPosts(board)
        self.root.title("PTT BOARD - " + board.upper())
        self.showMessage(self.crawler.getPage())
        self.showPosts(self.posts)

    def loadLayout(self) :
        align_mode = 'nswe'
        padding= 2
        msgHeight = 40
        optHeight = 40
        self.dataWidth = self.root.width
        self.dataHeight = self.root.height - optHeight - msgHeight

        self.divOptions = tk.Frame(self.root,  width=self.dataWidth , height=optHeight)
        self.divOptions.grid(row=0 ,padx=padding, pady=padding, sticky=align_mode)

        self.divData = tk.Frame(self.root,  width=self.dataWidth , height=self.dataHeight ,bg=self.postbg)
        self.divData.grid(row=1, padx=padding, pady=padding, sticky=align_mode)

        self.divMsg = tk.Frame(self.root,  width=self.dataWidth , height=msgHeight , bg='black')
        self.divMsg.grid(row=2, columnspan = 4 ,padx=padding, pady=padding, sticky=align_mode)

        self.root.rowconfigure(1, weight=1)
        self.root.columnconfigure(0, weight=1)

        self.divData.columnconfigure(0, weight=1)
        self.divData.columnconfigure(1, weight=10)
        self.divData.columnconfigure(2, weight=1)
        self.divData.columnconfigure(3, weight=2)

        self.lblMsg = tk.Label(self.divMsg, text='show message here', bg='black', fg='white')
        self.lblMsg.grid(row=0, column=0, sticky='w')

    def showOptions(self , boards):
        padding = 1
        label = tk.Label( self.divOptions,  text=" PTT Board Selection: ")
        label.grid(row=0, column=0, sticky='nswe')

        combobox = ttk.Combobox(self.divOptions, values=boards, width=20 , height = 30)
        combobox.current(0)   # select first one
        combobox.grid(row=0, column=1, columnspan=3, padx=padding, pady=padding)
        combobox.bind('<<ComboboxSelected>>', self.optSelected)

    def showPosts(self , posts):
        padding = 2
        for child in self.divData.winfo_children():
            child.destroy()

        for row in range(len(posts)):
            color = 'black'

            number = tk.Label(self.divData, fg=color, bg=self.postbg, text=posts[row]['push'])
            number.grid(row=row, column = 0 ,padx=padding, pady=padding, sticky='e')
            title = tk.Label(self.divData, fg=color, bg=self.postbg, text=posts[row]['title'])
            title.grid(row=row, column=1, padx=padding, pady=padding, sticky='w')
            date = tk.Label(self.divData, fg=color, bg=self.postbg, text=posts[row]['date'])
            date.grid(row=row, column=2, padx=padding, pady=padding, sticky='w')
            author = tk.Label(self.divData, fg=color, bg=self.postbg, text=posts[row]['author'])
            author.grid(row=row, column=3, padx=padding, pady=padding, sticky='w')

            # bind mouse events
            title.bind("<Enter>", self.onEnter)
            title.bind("<Leave>", self.onLeave)
            title.bind("<Button-1>", self.onClick)

    def onEnter(self, event):
        event.widget.config(fg='blue')

    def onLeave(self, event):
        event.widget.config(fg='black')

    def onClick(self , event , row) :
        for i in range(0, len(self.posts)):
            if self.posts[i]['title'] == event.widget['text']:
                link = self.crawer.getDomain() +  self.posts[i]['link']
                webbrowser.open_new(link)

    def optSelected(self , event) :
        print (event.widget.get())
        self.showPage(event.widget.get())

    def showMessage(self, msg):
        self.lblMsg['text'] = msg

if __name__ == '__main__' :
    program = PTTViewer(tk.Tk())
    boards = program.getBoards()
    program.showOptions(boards)
    program.showPage('Gossiping')
    program.run()


import sys
import numpy as np
from sklearn.metrics import roc_curve, auc
import pandas as pd
from itertools import combinations
import matplotlib.pyplot as plt

def compute_matrix(matrixfiles_num, matrixfiles_sergey):
    if matrixfiles_num == 0:
        return pd.DataFrame([0])
    coeffs = [1 for i in range(matrixfiles_num)]
    # matrixfiles_num = int(sys.argv[1])
    # matrixfiles = [sys.argv[i] for i in range(2, matrixfiles_num + 2)]
    # savematrixfile = sys.argv[matrixfiles_num + 2]
    # saveresultfile = sys.argv[matrixfiles_num + 3]
    matrices = [pd.read_csv(f, sep=',').abs() for f in matrixfiles_sergey]
    genes = matrices[0].index
    # print(genes)

    # print(matrices)
    sz = len(matrices[0])

    for matrix in matrices:
        try:
            assert len(matrix) == sz
        except:
            print(sz, len(matrix))
            # print(matrix)
            break

    # for matrix in matrices:
    #     for column in matrix:
    #         temp = matrix[column].argsort()
    #         ranks = np.empty_like(temp)
    #         ranks[temp] = np.arange(len(matrix[column]))
    #         matrix[column] = ranks

    res = np.zeros(shape=(sz, sz))
    for s in range(sz):
        for i, matrix in enumerate(matrices):
            res[s] += matrix.iloc[:, s].values * coeffs[i]
        res[s] /= len(matrices)

    for row in res:
        if row.sum() != 0:
            row /= row.sum()

    result_df = pd.DataFrame(res, columns=genes, index=genes)

    # result_df.to_csv(saveresultfile, index=True, header=True, sep='\t')
    # print(result_df)
    return result_df

def compute_aggregated_matrix(matrixfiles_num, matrixfiles_sergey):
    if matrixfiles_num == 0:
        return pd.DataFrame([0])
    coeffs = [1 for i in range(matrixfiles_num)]
    # matrixfiles_num = int(sys.argv[1])
    # matrixfiles = [sys.argv[i] for i in range(2, matrixfiles_num + 2)]
    # savematrixfile = sys.argv[matrixfiles_num + 2]
    # saveresultfile = sys.argv[matrixfiles_num + 3]
    matrices = [pd.read_csv(f, sep=',').abs() for f in matrixfiles_sergey]
    genes = matrices[0].index
    # print(genes)

    # print(matrices)
    sz = len(matrices[0])

    for matrix in matrices:
        try:
            assert len(matrix) == sz
        except:
            print(sz, len(matrix))
            # print(matrix)
            break

    for matrix in matrices:
        for column in matrix:
            temp = matrix[column].argsort()
            ranks = np.empty_like(temp)
            ranks[temp] = np.arange(len(matrix[column]))
            matrix[column] = ranks

    res = np.zeros(shape=(sz, sz))
    for s in range(sz):
        for i, matrix in enumerate(matrices):
            res[s] += matrix.iloc[:, s].values * coeffs[i]
        res[s] /= len(matrices)

    for row in res:
        if row.sum() != 0:
            row /= row.sum()

    result_df = pd.DataFrame(res, columns=genes, index=genes)

    # result_df.to_csv(saveresultfile, index=True, header=True, sep='\t')
    # print(result_df)
    return result_df

algolist_sergey = ['']

datafolder_sergey = "/home/user/Sirius/sergeysdata"
truedatafolder = "/home/user/Sirius/gene_network_sirius_2019/Matrices_1"

# datalist = ['genes_200_exps_10_bgr', 'genes_200_exps_20_bgr', 'genes_200_exps_40_bgr']
datalist = ['exps_100_2']

truefilename = truedatafolder + "/{1}_{0}_true.txt"
dataname_sergey = datafolder_sergey + "/{0}_{1}.csv"

# savematricesdirname = "/home/user/Sirius/Matrices_Subsets"
# savematricesfilename = savematricesdirname + "/{0}_predicted.txt"
saveresultsfile = "/home/user/Sirius/gene_network_sirius_2019/Graphics/result.txt"

if __name__ == "__main__":
    results = []

    for algo in algolist_sergey:
        for i, dataname in enumerate(datalist):
            true_df = pd.read_csv(truefilename.format(dataname, 'aracne'), index_col=0, sep='\t')
            predicted_df = compute_matrix(1, [dataname_sergey.format(dataname, algo)])
            predicted_agg_df = compute_aggregated_matrix(1, [dataname_sergey.format(dataname, algo)])

            true_array = true_df.values[np.triu_indices(true_df.values.shape[0], k=1)]
            predicted_array = predicted_df.values[np.triu_indices(predicted_df.values.shape[0], k=1)]
            predicted_agg_array = predicted_agg_df.values[np.triu_indices(predicted_agg_df.values.shape[0], k=1)]

            fpr, tpr, thresholds = roc_curve(true_array, predicted_array)
            roc_auc = auc(fpr, tpr)
            print("plotting...", algo, dataname)
            plt.plot(fpr, tpr)
            plt.show()
            fpr1, tpr1, thresholds1 = roc_curve(true_array, predicted_agg_array)
            roc_auc1 = auc(fpr1, tpr1)
            print("plotting...", algo, dataname)
            plt.plot(fpr1, tpr1)
            plt.show()
            print("done", algo, dataname, roc_auc, roc_auc1)


import csv
import numpy as np
from sklearn.model_selection import train_test_split
import nltk
from nltk.tokenize import word_tokenize
from random import shuffle
from sklearn.model_selection import KFold
from statistics import mode
import re

documents = []
with open("data.csv") as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    for record in csv_reader:
        ap = (' '.join(re.sub("(@[A-Za-z0-9]+)|(\w+:\/\/\S+)", " ", record[1]).split()))
        ap = word_tokenize(ap)
        documents.append((ap, record[0]))

shuffle(documents)

all_words = []
for tweet in documents:
    for w in tweet[0]:
        all_words.append(w.lower())

all_words = nltk.FreqDist(all_words)
print("getting features")
word_features = list(all_words.keys())[:1000]
print(word_features)

def find_features(tweet):
    words = set(tweet)
    features = {}
    for w in word_features:
        features[w] = (w in words)
    return features

print("setting features per tweet")
feature_sets = np.array([[find_features(tweet), category] for (tweet, category) in documents])

data = feature_sets[:, 0]
target = feature_sets[:, 1]

testing_set = feature_sets[5000:]
training_set = feature_sets[:5000]

print("training")
X_train, X_test, y_train, y_test = train_test_split(data, target, test_size=0.1, random_state=0)
classifier = nltk.NaiveBayesClassifier.train(training_set)

print("testing")
print("Classifier accuracy percent:", (nltk.classify.accuracy(classifier, testing_set)) * 100)

def sentiment(text):
    feats = find_features(word_tokenize(text))
    v = classifier.classify(feats)
    return mode(v)

print(sentiment("This movie was awesome! The acting was great, plot was wonderful, and there were pythons...so yea!"))
print(sentiment("sorry. Horrible movie, 0/10"))


import requests
from lxml import etree
import re
def fangtx():
    print('数据爬取中,请等待...')
    start_url = 'http://xian.newhouse.fang.com/house/s/b9{}'
    with open('/Users/zlinzhang/Downloads/ftx.csv', 'a') as f:
        f.write('小区，大小，区域，详细信息，价格，电话'+'\n')
        for i in range(36):
            url=start_url.format(i+1)
            headers = {
                "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"

            }
            res = requests.get(url, headers=headers)
            ret = res.content.decode('gbk')
            result = etree.HTML(ret)
            content_list = result.xpath(".//div[@id='newhouse_loupai_list']/ul/li")
            if content_list:
                for content in content_list:
                    if content_list.index(content)==5:
                        continue
                    title=content.xpath(".//div[@class='nlcd_name']/ a / text()")
                    title = title[0].strip() if len(title) > 0 else ''
                    #print(title)

                    area = content.xpath(".//span[@class='sngrey']/text()")
                    area = area[0].strip() if len(area) > 0 else ''
                    #print(area)

                    address = content.xpath(".//span[@class='snarey']/../text()")
                    address = address[1].strip() if len(address) > 0 else ''
                   # print(address)

                    size = content.xpath(".//div[contains(@class,'house_type')]/text()[last()]")
                    size = re.sub(r"\t|\n|", '', size[0]) if len(size) > 0 else ''
                   # print(size)

                    price1 = content.xpath(".//div[@class='nhouse_price']/span/text()")
                    price3 = content.xpath(".//div[@class='kanzx']/h3/a/text()")
                    price2 = content.xpath(".//div[@class='nhouse_price']/em/text()")
                 #   price = html.xpath('//*[@class="nhouse_price"]//span|//*[@class="kanesf"]//p//a|//*[@class="kanzx"]//h3//a')

                    if price3:
                        price = '优惠楼盘'
                    if price1:
                        if price1[0]=='价格待定':
                            price='价格待定'
                        else:
                            price = price1[0]+price2[0]

                    #print(price1)

                    phone=content.xpath(".//div[@class='tel']/p//text()")
                    phone=''.join(phone)

                    f.write(title+','+size+','+area+','+address+'+'+price+','+phone+','+'\n')

if __name__ == '__main__':
    fangtx()
    print('爬取完毕')


#!/usr/bin/env python

# Copyright (c) 2016 Hewlett Packard Enterprise Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not used this file except in compliance with the License. You may obtain
# a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import json
import logging
import os
import unittest

import schema

from monasca_analytics.source import cloud_markov_chain as cloud
from test.mocks import spark_mocks

class MarkovChainSourceTest(unittest.TestCase):

    def setup_logging(self):
        current_dir = os.path.dirname(__file__)
        logging_config_file = os.path.join(current_dir,
                                           "../resources/logging.json")
        with open(logging_config_file, "rt") as f:
            config = json.load(f)
        logging.config.dictConfig(config)

    def setUp(self):
        self.setup_logging()
        params = {
            "server_sleep_in_seconds": 0.1
        }
        transitions = {
            "web_service": {
                "run=>slow": {
                    0: 0.01,
                    8: 0.2,
                    12: 0.7,
                    14: 0.7,
                    22: 0.3,
                    24: 0.1
                },
                "slow=>run": {
                    0: 1,
                    8: 0.7,
                    12: 0.1,
                    14: 0.1,
                    22: 0.8,
                    24: 0.99
                },
                "stop=>run": 0.5
            },
            "switch": {
                "on=>off": 0.1,
                "off=>on": 0.5
            },
            "host": {
                "on=>off": 0.5,
                "off=>on": 0.1
            },
        }
        self.valid_config = {
            "module": "markov_chain_source",
            "transitions": dict(transitions),
            "triggers": {
                "support": {
                    "get_called": {
                        0: 0.1,
                        8: 0.2,
                        12: 0.8,
                        14: 0.8,
                        22: 0.5,
                        24: 0.0
                    }
                }
            },
            "params": dict(params),
            "graph": {
                "h1:host": ["s1"],
                "h2:host": ["s1"],
                "s1:switch": [],
                "w1:web_service": ["h1"],
                "w2:web_service": ["h2"]
            }
        }
        self.config_extra_param = dict(self.valid_config)
        self.config_extra_param["params"] = dict(params)
        self.config_extra_param["params"]["extra_param"] = "john doe"
        self.config_missing_param = dict(self.valid_config)
        self.config_missing_param["transitions"] = dict(transitions)
        self.config_missing_param["transitions"].pop("host")
        self.config_wrong_type = {
            "module": 123,
            "transitions": dict(self.valid_config["transitions"]),
            "params": dict(params),
            "graph": {}
        }
        self.mcs = cloud.CloudMarkovChainSource("fake_id", self.valid_config)

    def tearDown(self):
        pass

    def test_validate_valid_config(self):
        self.assertEqual(self.valid_config, self.mcs._config)

    def test_validate_config_extra_param(self):
        self.assertRaises(
            schema.SchemaError,
            self.mcs.validate_config,
            self.config_extra_param)

    def test_validate_config_missing_param(self):
        self.assertRaises(
            schema.SchemaError,
            self.mcs.validate_config,
            self.config_missing_param)

    def test_validate_config_wrong_type(self):
        self.assertRaises(
            schema.SchemaError,
            self.mcs.validate_config,
            self.config_wrong_type)

    def test_get_default_config(self):
        default_config = cloud.CloudMarkovChainSource.get_default_config()
        cloud.CloudMarkovChainSource.validate_config(default_config)
        self.assertEqual("CloudMarkovChainSource", default_config["module"])

    def test_create_dstream_created(self):
        ssc = spark_mocks.MockStreamingContext(None, None)
        self.assertIsNotNone(self.mcs.create_dstream(ssc))
        self.mcs.terminate_source()
        self.assertEqual(ssc._host, "localhost")

    def test_create_system(self):
        [support_node] = self.mcs._create_system()
        ws = support_node.dependencies
        self.assertEqual(len(ws), 2)
        ws1 = ws[0]
        self.assertEqual(len(ws1.dependencies), 1)
        ws2 = ws[1]
        self.assertEqual(len(ws2.dependencies), 1)
        hs1 = ws1.dependencies[0]
        self.assertEqual(len(hs1.dependencies), 1)
        hs2 = ws2.dependencies[0]
        self.assertEqual(len(hs2.dependencies), 1)
        self.assertEqual(hs1.dependencies[0], hs2.dependencies[0])

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


#!/usr/bin/env python
#-*- coding:utf-8 -*-
"""
Author: 习惯
Email: songbing513@mail.com
"""

app_name = 'deploy'

from django.urls import path
from kube.views import deploy,index,freeze,aliyun
urlpatterns = [
    path('pod-list/<str:namespace>/',deploy.listPod.as_view(),name='pod_list'),
    path('deoloy-ment/',deploy.deoloyMent.as_view(),name='deoloy_ment'),
    path('generate-k8s/',deploy.generateK8s,name='generate_k8s'),
    path('freeze/',freeze.freeZe,name='freeze'),
    path('freeze-run/',freeze.freezRun,name='freeze_run'),
    path('aliyun/',aliyun.index,name='aliyun'),
    path('aliyun-deploy/',aliyun.deoloy.as_view(),name='aliyun_deploy'),
    path('index/',index.index),
]


__author__ = 'Chloe'

'''
Run this file on the box which you would like the
client to run on. Mongo needs to be running first.
This initialises the Mongo Collections

Python3
'''

from pymongo import MongoClient

class PopulateMongo:

    _connection_string = 'mongodb://localhost:27017/'

    def __init__(self, connection_string=None):
        if connection_string:
            self.client = MongoClient(connection_string)
        else:
            self.client = MongoClient(self._connection_string)
        self.db = self.client['CoventryMakerspace']
        self.makers_collection = self.db['Makers']
        self.checkin_collection = self.db['Checkin']

    def populate_db(self):
        maker = {'device_id': "1234",
                  'name': 'TestMaker'}

        checkin = {'device_id': "1234",
                   "x_pos": "1.1234",
                   "y_pos": "1234",
                   "checkin": "True"}
        self.makers_collection.insert(maker)
        self.checkin_collection.insert(checkin)

    def test_db(self):
        result = self.makers_collection.find_one({'name': 'TestMaker'})
        print(result)
        result = self.checkin_collection.find_one({'device_id': '1234'})
        print(result)
        print("The DB creation was a success!")

populate = PopulateMongo()
populate.populate_db()
populate.test_db()


import json
import copy
import stripe
import uuid
from decimal import Decimal

from django.contrib.auth.models import User
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from django.views.decorators.http import require_GET, require_POST
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
from django.http.response import HttpResponse, JsonResponse
from django.db.models import Sum
from django.conf import settings

#from bonusly import *
from giftbit import (
    giftbit_sendcard,
    list_rewards,
)
from credits.models import *
from parent.models import *
from common.exceptions import ApiException
from common.decorators import login_required_api
from pd import settings

def get_total_points(user_id=None):
    # points are thanks
    if not user_id:
        user_id = request.user.id
    current_user = get_object_or_404(User, id=user_id)
    total = Points.objects.filter(user=current_user).aggregate(Sum('amount'))['amount__sum']
    if not total:
        total = 0
    return total

def get_balance(user_id):
    # SocialCoins come from dollars earned and spent on gift cards
    balance = SocialCoins.objects.filter(user__id=user_id).aggregate(balance=Sum('amount'))
    return balance['balance'] if balance['balance'] else 0

def get_dollars_earned(user_id):
    # dollars only come to the system from counterparty's credit card
    total = Transactions.objects.filter(user__id=user_id, amount__gt=0).aggregate(total=Sum('amount'))
    return total

def get_fee(amount):
    return APP_FEE * abs(amount)

def record_transaction_fee(transaction):
    tr = {}
    tr['transaction'] = transaction
    tr['amount'] = get_fee(transaction.amount)
    Fees.objects.create(**tr)

@require_POST
@csrf_exempt
@login_required_api
def give(request, type):
    # credits_points, credits_transactions, credits_fees;
    try:
        give_json = json.loads(request.body)
    except (ValueError, TypeError) as e:
        raise ApiException('Invalid json ' + request.body, 400)
    required_fields = ['counterparty', 'amount']
    for f in required_fields:
        if f not in give_json:
            raise ApiException('{} is required'.format(f), 400)
    try:
        to_user = User.objects.get(id=give_json['counterparty'])
    except User.DoesNotExist:
        raise ApiException('to_user_id {} does not exist'.format(give_json['to_user_id']), 400)
    try:
        give_json['amount'] = abs(int(give_json['amount']))
    except ValueError:
        raise ApiException('amount {} must be an integer '.format(give_json['amount']), 400)
    if type == 'giftcard' and not 'brand_code' in give_json:
        raise ApiException('brand_code is mandatory', 400)

    current_user = get_object_or_404(User, id=request.user.id)
    debit_o = None
    giftcard_info = None
    if (type in ['giftcard', 'money']):
        token = give_json['token'] if 'token' in give_json else None
        save_info = False if 'save_info' in give_json and give_json['save_info'] == 0 else True

        charge_o = charge_user(current_user, give_json['amount'], token, save_info)
        give_json.pop('token', None)

        debit_o = Transactions.objects.create(
            user=to_user,
            counterparty=current_user,
            amount=give_json['amount'],
            charge_id=charge_o["id"],    #  "ch_1Abxo9IbhKiecKLZCindPGrb",
            balance_transaction_id=charge_o["balance_transaction"], # "txn_1Abxo9IbhKiecKLZwT9RTmiQ",
            hashtag=give_json['hashtag'],
            reason=give_json['reason']
        )
        credit_o = Transactions.objects.create(
            user=current_user,
            counterparty=to_user,
            amount=-give_json['amount'],
            charge_id=charge_o["id"],
            balance_transaction_id=charge_o["balance_transaction"],
            hashtag=give_json['hashtag'],
            reason=give_json['reason']
        )
        record_transaction_fee(credit_o)
        # award socail coins. Each coin equals to 1 dollar
        sc = SocialCoins.objects.create(
            user=to_user,
            counterparty=current_user,
            amount=abs(give_json['amount']),
            transaction=debit_o,
            hashtag=give_json['hashtag'],
            reason=give_json['reason']
        )
    if type == 'giftcard':
        giftcard_info = send_giftcard(request, give_json)
    # award 1 thank you point in case a user gives either thanks or dollars
    points_o = Points.objects.create(
        user=to_user,
        counterparty=current_user,
        amount=1,
        transaction=debit_o,
        hashtag=give_json['hashtag'],
        reason=give_json['reason']
    )
    # do not post points to bonusly unless they are monetary or the user will get more than was gifted
    #if (type == 'money'):
    #    post_points(abs(give_json['amount']), give_json['hashtag'] if 'hashtag' in give_json else None)
    return JsonResponse(
        {
        'from' : debit_o.serialize() if debit_o else current_user.id,
        'to' : credit_o.serialize() if debit_o else to_user.id,
        'points' : points_o.serialize(),
        'giftcard': giftcard_info if giftcard_info else {}
        }
    )

def charge_user(user, amount, token=None, save_info=True):
    # Set your secret key: remember to change this to your live secret key in production
    # See your keys here: https://dashboard.stripe.com/account/apikeys
    stripe.api_key = settings.STRIPE_API_KEY
    amount += get_fee(amount)
    amount = int(amount*100)

    if not token and user.parent_profile.stripe_id:
        # No token means the user want to re-use his previous credit card
        # When it's time to charge the customer again, retrieve the customer ID.
        # TODO figure out a way to test this without front-end: get sample stripe_id or generate test token in python.
        try:
            charge = stripe.Charge.create(
              amount=amount,
              currency="usd",
              customer=user.parent_profile.stripe_id, # Previously stored, then retrieved
            )
        # save_info does not matter cause it is the same card.
        except Exception as e:
            raise ApiException('Payment Exception ' + str(e), 400)
    elif token:
        # User got the token from stripe in exchange for his credit card info
        try:
            if not save_info:
                # Charge the user's card:
                charge = stripe.Charge.create(
                    amount=amount,
                    currency="usd",
                    description="{0} {1} was charged {2}".format(user.first_name, user.last_name, amount),
                    source=token,
                    receipt_email=user.email
                )
            else:
                # TODO - will this work?
                # first search to make sure the customer does not yet exist
                # if it does, attach the new token to her.
                if user.parent_profile.stripe_id:
                    # user wants to save on file new credit card
                    customer = stripe.Customer.retrieve(user.parent_profile.stripe_id)
                    customer.source = token
                    customer.save()
                else:
                    # user never saved a cardit card on file
                    customer = stripe.Customer.create(
                        email=user.email,
                        source=token
                    )
                    # Save the customer ID and other info in a database for later.
                    pp = get_object_or_404(ParentProfile, user=user)
                    pp.stripe_id = customer.id
                    pp.save()
                # Charge the Customer instead of the card:
                # This is not that great cause UI probably does better error handling
                charge = stripe.Charge.create(
                    amount=amount,
                    currency="usd",
                    customer=customer.id,
                )
        except Exception as e:
            raise ApiException('Payment Exception ' + str(e), 400)
    else:
        raise ApiException('Token is not provided (card not entered) and no customer.id (credit card) on file', 400)
    return charge

#@login_required_api
def display_rewards(request):
    #ceiling = get_balance(request.user.id)
    #rewards = list_rewards(ceiling=ceiling)
    rewards = list_rewards()
    return JsonResponse(rewards, safe=False)

@login_required_api
@require_POST
@csrf_exempt
def cash_out(request):
    card = json.loads(request.body)
    current_user = get_object_or_404(User, id=request.user.id)
    redemption = redeem_points(card)
    redemption = redemption['redemption']
    r = Redemptions(claim_url=redemption['claim_url'],
        certificate_url=redemption['certificate_url'],
        denomination_id=card['denomination_id'],
        name=card['name'])
    r.save()
    sc = SocialCoins(user=current_user,
        counterparty=bonusly_user,
        amount=-card['price'],
        redemption=r)
    sc.save()
    return show_balance(request, request.user.id)
    #return JsonResponse(r, safe=False) #? TODO why TypeError: <Redemptions: Redemptions object> is not JSON serializable

@login_required_api
def show_dollars_earned(request, user_id=None):
    total = get_dollars_earned(request.user.id if not user_id else user_id)
    return JsonResponse(total)

@login_required_api
def show_points(request, user_id=None):
    total = get_total_points(request.user.id if not user_id else user_id)
    return JsonResponse({'total points' : total})

@login_required_api
def show_balance(request, user_id=None):
    total = get_balance(request.user.id if not user_id else user_id)
    return JsonResponse({'total $$' : total})

@login_required_api
@require_GET
def show_withfee(request):
    amount = request.GET.get('amount', 0)
    if not amount:
        raise ApiException('?amount= is required in the url', 400)
    total = int(amount) + get_fee(int(amount))
    return JsonResponse({'total $$' : total})

def generate_giftcard_id():
    # TODO
    return 0

def send_giftcard(request, gift_info):
    current_user = get_object_or_404(User, id=request.user.id)
    #sender = get_object_or_404(ParentProfile, user=current_user)
    if not 'brand_code' in gift_info:
        raise ApiException('Please select a gift card', 400)
    if not 'amount' in gift_info:
        raise ApiException('Please select a amount', 400)
    if not 'counterparty' in gift_info:
        raise ApiException('Please specify counterparty', 400)
    if not 'reason' in gift_info:
        gift_info['message'] = ('With much gratitude plase accept my '
         'thank you!\n{} {}'.format(current_user.first_name, current_user.last_name))
    else:
        gift_info['message'] = gift_info['reason']
    gift_info['subject'] = '{} {} sent you a gift card.'.format(current_user.first_name, current_user.last_name)
    receiver_u = get_object_or_404(User, id=gift_info['counterparty'])
    gift_info['contacts'] = [
        {
            'email':     receiver_u.email,
            'firstname': receiver_u.first_name,
            'lastname':  receiver_u.last_name
        }
    ]
    gift_info['price_in_cents'] = gift_info['amount'] * 100
    gift_info['brand_codes']    = [gift_info['brand_code']]
    gift_info['id']             = str(uuid.uuid4())
    giftbit_sendcard(gift_info)
    giftcard = UserGiftcards(
        user=receiver_u,
        sender=current_user,
        campaign_id=gift_info['id']
    )
    giftcard.save()
    return giftcard.serialize()


#coding = utf-8
import tornado.web
import tornado.httpserver
import tornado.ioloop
from app.home.handlers import LoginHandler, HomeHandler, LogoutHandler, OverTimeHandler, OverTimeByMonthHandler

from setting import TORNADO_SETTINGS

TORNADO_ROUTES = [
    (r'^/login?', LoginHandler),
    (r'^/?', HomeHandler),
    (r'^/logout?', LogoutHandler),
    (r'^/interface/overtime?', OverTimeHandler),
    (r'^/admin?', OverTimeByMonthHandler),
    # (r'^/updateUserInfo/?', UpdateUserInfo),
    # (r'^/getUserInfo/?', GetUserInfo),
    # (r'^/createPet/?', CreatePet),
    # (r'^/userPets/?', UserPets),
    # (r'/register/?', RegisterHandler),
    # (r'/login/?', LoginHandler),
    # (r'/logout/?', LogoutHandler),
    # (r'/change_password/?', ResetPasswordHandler),
    # (r'/account/?', UserPageHandler),
    #
    #  (r'/api/model/?', ModelCrudHandler),
    #  (r'/api/model/([0-9a-fA-F]{24,})/?', ModelCrudHandler),
    #  (r'/api/model/count/?', ModelCrudHandler),
    #
    # (r'.*', tornado.web.FallbackHandler, dict(fallback=tr)),
]

class Application(tornado.web.Application):
    def __init__(self):
        handlers = TORNADO_ROUTES
        settings = TORNADO_SETTINGS
        tornado.web.Application.__init__(self, handlers, **settings)

if __name__ == '__main__':
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(8522)
    tornado.ioloop.IOLoop.instance().start()


import tkinter as tk
import pygame as pyg
import sys
from random import randint
from pygame.sprite import Group
from Bullet import Bullet
from Player_Settings import Player
from Benefits import Benefits

# initialize
menu = tk.Tk()
menu.geometry("360x200")

def main_game():
    # initialize pygames
    pyg.init()
    SCREEN_SIZE = (750, 750)
    SCREEN = pyg.display.set_mode(SCREEN_SIZE)
    pyg.display.set_caption("Accumul")

    p = Player(SCREEN, 'Arrow.png', 5)
    ammunition = Group()
    benefits = Group()

    # For mouse clicks
    LEFT = 1

    # data exclusive to the 'benefits' in the game
    benefits_min_gen = 1
    benefits_max_gen = 5
    benefits_max_pop = 20

    score_count = 0
    game_over = False

    while not game_over:

        for event in pyg.event.get():
            if event.type == pyg.QUIT:
                pyg.quit()
                sys.exit()
            if event.type == pyg.MOUSEBUTTONDOWN and (event.button == LEFT):
                bullet = Bullet(SCREEN, p)
                ammunition.add(bullet)
            if event.type == pyg.MOUSEBUTTONUP and (event.button == LEFT):
                pass
            if event.type == pyg.KEYDOWN:
                if event.key == pyg.K_a or event.key == pyg.K_RIGHT:
                    p.go_left = True
                elif event.key == pyg.K_d or event.key == pyg.K_LEFT:
                    p.go_right = True  # move right
                elif event.key == pyg.K_s or event.key == pyg.K_DOWN:
                    p.go_down = True  # move down
                elif event.key == pyg.K_w or event.key == pyg.K_UP:
                    p.go_up = True  # move upd
            if event.type == pyg.KEYUP:
                if event.key == pyg.K_a or event.key == pyg.K_LEFT:
                    p.go_left = False
                elif event.key == pyg.K_d or event.key == pyg.K_RIGHT:
                    p.go_right = False  # move right
                elif event.key == pyg.K_s or event.key == pyg.K_DOWN:
                    p.go_down = False  # move down
                elif event.key == pyg.K_w or event.key == pyg.K_UP:
                    p.go_up = False  # move up

        SCREEN.fill((0, 0, 0))  # the background is completely black
        ammunition.update()
        benefits.update()
        p.update_position()
        p.blit_player()  # Shows the update image of the player

        # update the bullets
        for bullet in ammunition.copy():
            if bullet.rect.y <= 0:
                ammunition.remove(bullet)

        for bullet in ammunition.sprites():
            bullet.show_bullet()

        # update benefits
        if len(benefits) < benefits_max_pop:
            for x in range(randint(benefits_min_gen, benefits_max_gen)):
                benefits.add(
                    Benefits(SCREEN, randint(0, SCREEN_SIZE[0]), randint(0, SCREEN_SIZE[1] - (SCREEN_SIZE[1] * 0.90))))

        for benefit in benefits.sprites():
            benefit.benefits_show()

        for benefit in benefits.copy():
            if benefit.rect.y > SCREEN_SIZE[1]:
                benefits.remove(benefit)

        if pyg.sprite.spritecollideany(p, benefits):
            endtxt = pyg.font.SysFont("none", 25)
            endlabel = endtxt.render("Game Over! Score: " + str(score_count), 1, (0, 255, 255))
            SCREEN.blit(endlabel, (SCREEN_SIZE[0]/2, SCREEN_SIZE[1]/2))
            game_over = True

        if pyg.sprite.groupcollide(ammunition, benefits, True, True):
            score_count += 1

        pyg.display.flip()

var = tk.StringVar()
title = tk.Label(menu, textvariable=var).grid(row=0)
start_button = tk.Button(menu, text="start", command=main_game).grid(row=1)
close_button = tk.Button(menu, text="Exit", command=menu.destroy).grid(row=2)
var.set('Welcome to Accumul - "Award winning User Interface"')
tk.mainloop()


import pymunk
from Engine.config import ROLE
from Engine.geometry import Vec2d
from Engine.loading import load_model, cast_model
from game_class import YTGBaseCreature
from Engine.physics import Mount

NAME = __name__.split('.')[-1]
MODEL = load_model('Objects\\Models\\%s' % (NAME,))

CS = Vec2d(42, 77)

class Creature(YTGBaseCreature):
    size_inc = 1
    max_health = 300

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.body = pymunk.Body()
        self.shape = pymunk.Circle(self.body, self.RADIUS)
        self.shape.density = 1

        self.init_mounts((Mount(self, allowed=[ROLE.ENGINE], top=False), 'engine'),
                         (Mount(self, allowed=[ROLE.WEAPON], top=False,
                                position=self.image_to_local((43, 11))), 'weapon_left'),
                         (Mount(self, allowed=[ROLE.WEAPON], top=False,
                                position=self.image_to_local((43, 143))), 'weapon_right'))

    @classmethod
    def init_class(cls):
        cls._frames, cls.IMAGE_SHIFT = cast_model(MODEL, CS, cls.size_inc)
        cls.precalculate_shape()
        cls.calculate_poly_shape()

    @classmethod
    def precalculate_shape(cls):
        radius = 50

        cls.RADIUS = radius * cls.size_inc

    @classmethod
    def calculate_poly_shape(cls):
        img_poly_left = []
        poly_left = [tuple(e[n] - CS[n] for n in range(2)) for e in img_poly_left]
        poly_right = [(e[0], -e[1]) for e in poly_left[::-1]]
        cls.POLY_SHAPE = [(e[0] * cls.size_inc, e[1] * cls.size_inc) for e in poly_left + poly_right]

Creature.init_class()


import os
from conans import ConanFile, CMake

class XeusConan(ConanFile):
    name = "xeus"
    version = "0.2.38"
    settings = "os", "compiler", "build_type", "arch"
    requires = (
        "zmq/4.3.2@bincrafters/stable",
        "cppzmq/4.6.0@_/_",
        "xtl/0.6.12@_/_",
        "openssl/1.0.2u@_/_",
        "nlohmann_json/3.7.3@_/_",
        "libuuid/1.0.3@_/_",
    )
    generators = "cmake", "virtualrunenv"
    build_policy = "missing"
    exports_sources = "*"

    def build(self):
        cmake = CMake(self)
        cmake.verbose = True
        cmake.configure()
        cmake.build()
        cmake.test()

    def package(self):
        self.copy("*.hpp", dst="include", src="include")
        # Not pretty: (sorry, but I just wanted static lib!)
        if False:
            self.copy("*xeus.lib", dst="lib", keep_path=False)
            self.copy("*.dll", dst="lib", keep_path=False)
            self.copy("*.so", dst="lib", keep_path=False)
            self.copy("*.dylib", dst=".", keep_path=False)
        self.copy("*.a", dst="lib", keep_path=False)

    def package_info(self):
        self.cpp_info.libs = ["xeus"]


import multiprocessing
import queue
import threading
from typing import Type
import uuid

import pytest

import singletons
from singletons.exceptions import NoGreenthreadEnvironmentWarning

JOIN_TIMEOUT = 2

def test_singleton() -> None:
    class MySingleton(metaclass=singletons.Singleton):
        pass

    a = MySingleton()
    b = MySingleton()

    assert a is b

@pytest.mark.parametrize('metaclass,queue_cls,process,repetitions', [
    (singletons.ProcessSingleton, multiprocessing.Queue, multiprocessing.Process, 8),
    (singletons.ThreadSingleton, queue.Queue, threading.Thread, 8),
])
def test_process_singleton(metaclass: Type, queue_cls: Type, process: Type, repetitions: int) -> None:
    class MySingleton(metaclass=metaclass):
        def __init__(self) -> None:
            self.uuid = uuid.uuid4()

    def inner_func(q: queue_cls) -> None:
        a = MySingleton()
        b = MySingleton()
        q.put((a.uuid, b.uuid,))

    test_q = queue_cls()
    processes = []
    for _ in range(repetitions):
        p = process(target=inner_func, args=(test_q,))
        p.start()
        processes.append(p)

    seen_uuids = set()
    while len(seen_uuids) < repetitions:
        a, b = test_q.get(timeout=JOIN_TIMEOUT)
        assert a == b
        assert a not in seen_uuids
        seen_uuids.add(a)

def test_greenthread_singleton_with_no_greenthreads():
    class MySingleton(metaclass=singletons.GreenthreadSingleton):
        pass

    with pytest.warns(NoGreenthreadEnvironmentWarning):
        a = MySingleton()
        b = MySingleton()
        assert a is b


import logging

from calibratedservocontroller import CalibratedServoController
from polulomaestroservercontroller import PololuMaestroServoController

logging.basicConfig(level=logging.INFO)
import os.path
import argparse
import cv2
import time

parser = argparse.ArgumentParser(description="""\
        This is a utilityscript that uses the webcamera to take a specified number of images at a specified rate.""")
parser.add_argument("maxcount", type=int)
parser.add_argument("frames_per_second", type=float)
parser.add_argument("--start_angle", type=int, default=None)
parser.add_argument("--end_angle", type=int, default=None)

logging.info("Starting")
args = parser.parse_args()

capture = cv2.VideoCapture(0)
logging.info("Got videocapture")

imagecount = 0

if not args.start_angle is None and not args.end_angle is None:
    servocontroller = CalibratedServoController(PololuMaestroServoController())
    servocontroller.set_servo_target_angle(args.start_angle)
    angle_frame_increment = float(args.start_angle - args.end_angle) / float(args.maxcount)
    while not servocontroller.servo_has_settled():
        time.sleep(0.1)
else:
    servocontroller = None

maxcount = args.maxcount
imagefilenamecounter = 1
while imagecount < maxcount:
    time.sleep(1.0 / args.frames_per_second)
    ret, image = capture.read()
    if ret:
        imagecount += 1

        if not servocontroller is None:
            servocontroller.set_servo_target_angle(args.start_angle + angle_frame_increment * imagecount,
                                                   ignore_settle_timeout=True)

        filename = "%d.png" % (imagefilenamecounter,)
        while os.path.exists(filename):
            imagefilenamecounter += 1
            filename = "%d.png" % (imagefilenamecounter,)
        cv2.imwrite(filename, image)
        logging.info("Wrote image %s (%d/%d)" % (filename, imagecount, maxcount))


from __future__ import print_function
from typing import Optional
from time import sleep
from pymba import Vimba
from pymba import Frame

vimba = None
def FrameCallback(frame: Frame, delay: Optional[int] = 10) -> None:
    bShowFrameInfos = True
    if bShowFrameInfos == True:
        print('Frame ID:%d' %(frame.data.frameID), end=" ")
        print('Size: %d' %(len(frame.buffer_data())), end=" " )
        print("Format:%s" %(frame.pixel_format))
        # print('Status: %s' % (frame.receiveStatus)) -- no such feature up to now
    print(".", end="")

def init_cameras():
    global vimba
    # vimba object
    vimba = Vimba()
    # Start vimba system
    vimba.startup()
    vmFactory = vimba.camera_ids()
    # Get connected cameras
    cams = [vimba.camera(id) for id in vmFactory]
    if len(cams) == 0:
        raise OSError("No camera present.")
    for idx, device in enumerate(vmFactory):
        print("Device {} ID: {}".format(idx, device))
    # Open cameras and print information
    for idx, cam in enumerate(cams):
        try:
            cam.open()
            cam.arm(mode='Continuous', callback=FrameCallback)
            cam.start_frame_acquisition()
        except VimbaException as e:
            if e.error_code == VimbaException.ERR_TIMEOUT:
                print(e)
                cam.disarm()
                cam.arm('Continuous')
            elif e.error_code == VimbaException.ERR_DEVICE_NOT_OPENED:
                print(e)
                cam.open()
                cam.arm(mode='Continuous', callback=FrameCallback)
    return cams

def main():
    global vimba
    cams = init_cameras()
    sleep(2)
    for cam in cams:
        cam.disarm()
        cam.close()
    vimba.shutdown()
    print("Exit Program...")

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
"""
Created on Tue Sep 18 20:23:16 2018

@author: fengl
"""
import scipy.io.wavfile as wavf
import matplotlib.pyplot as plt
import matplotlib as mpl

import numpy as np

#读wav文件，并对声音数据转换为-1~1之间的实数，返回帧率和声音振幅数据（单声道）
def readWav(wavefn):
    (r,s) = wavf.read(wavefn)  #通过wavf.read（）函数读取.wav文件
    if s.dtype == np.int16:    #如果s的数据类型为 np.int16
        s = s/32768.0
    elif s.dtype == np.int32:  #如果s的数据类型为 np.int32:
        s = s/2147483648.0
    elif s.dtype == np.uint8:  #如果s的数据类型为 np.uint8
        s = s/256.0

    if (len(s.shape)>1):
        s = s[:,0]
    else:
        s = s

    return (r,s)

#声音信息分帧函数
def enframe(signal, nw):

    signal_length=len(signal) #信号总长度
    if signal_length<=nw: #若信号长度小于一个帧的长度，则帧数定义为1
        nf=1
    else: #否则，计算帧的总长度
        nf=int(np.ceil((1.0*signal_length)/nw))

    pad_length=int(nf*nw) #所有帧加起来总的铺平后的长度
    zeros=np.zeros((pad_length-signal_length)) #不够的长度使用0填补
    pad_signal=np.concatenate((signal,zeros)) #填补后的信号记为pad_signal
    frames=pad_signal.reshape(nf,nw) #得到帧信号
    return frames   #返回帧信号矩阵

#求帧的一般过零率
def RMS(x):
  return sum(x**2)/len(x);

def fRMS(x):   #x为声音数据 **%
    # 循环计算各帧过零率 ****
    dtm = np.zeros((x.shape[0]))
    for i in range(0,x.shape[0]-1):
        dtm[i]=RMS(x[i,:]);         #求帧的一般过零率

    return (dtm-dtm.min())/(dtm.max()-dtm.min())

#求帧的一般过零率
def ZCR(x):
  signs = np.sign(x)
  signs[signs == 0] = -1

  return len(np.where(np.diff(signs))[0])/len(x)

#计算声音数据的各帧一般过零率
def fZCR(x):   #x为声音数据
    # 循环计算各帧过零率 ****
    dtm = np.zeros((x.shape[0]))
    for i in range(0,x.shape[0]-1):
        dtm[i]=ZCR(x[i,:]);

    return (dtm-dtm.min())/(dtm.max()-dtm.min())

(rate,wav) = readWav("explosion_1.wav")    #读取.wav文件
fwav = enframe(wav,256)   #声音信息分帧函数
m_zcr = fZCR(fwav)   #计算声音数据的各帧一般过零率
m_rms = fRMS(fwav)   # 循环计算各帧过零率 ****

(rate,wav) = readWav("gun_1.wav")    #读取.wav文件
fwav = enframe(wav,256)   #声音信息分帧函数
m_zcr1 = fZCR(fwav)   #计算声音数据的各帧一般过零率
m_rms1 = fRMS(fwav)   # 循环计算各帧过零率 ****

(rate,wav) = readWav("noise_1.wav")    #读取.wav文件
fwav = enframe(wav,256)   #声音信息分帧函数
m_zcr2 = fZCR(fwav)   #计算声音数据的各帧一般过零率
m_rms2 = fRMS(fwav)   # 循环计算各帧过零率 ****

(rate,wav) = readWav("screaming_1.wav")    #读取.wav文件
fwav = enframe(wav,256)   #声音信息分帧函数
m_zcr3 = fZCR(fwav)   #计算声音数据的各帧一般过零率
m_rms3 = fRMS(fwav)   # 循环计算各帧过零率 ****

fig = plt.figure()

mpl.rcParams["font.sans-serif"] = ["SimHei"]
mpl.rcParams["axes.unicode_minus"] = False

x = np.arange(4)
y1 = [m_rms.max(),m_rms1.max(),m_rms2.max(),m_rms3.max()]         #用来存放各个声音最大值的数组
y2 = [m_rms.min(),m_rms1.min(),m_rms2.min(),m_rms3.min()]         #用来存放各个声音最小值的数组
y3 = [m_rms.mean(),m_rms1.mean(),m_rms2.mean(),m_rms3.mean()]     #用来存放各个声音的数组
y4 = [m_rms.std(),m_rms1.std(),m_rms2.std(),m_rms3.std()]         #用来存放各个声音标准差的数组

y5 = [m_zcr.max(),m_zcr1.max(),m_zcr2.max(),m_zcr3.max()]
y6 = [m_zcr.min(),m_zcr1.min(),m_zcr2.min(),m_zcr3.min()]
y7 = [m_zcr.mean(),m_zcr1.mean(),m_zcr2.mean(),m_zcr3.mean()]
y8 = [m_zcr.std(),m_zcr1.std(),m_zcr2.std(),m_zcr3.std()]
bar_width = 0.2
tick_label = ["explosion", "gun", "noise", "screaming"]

plt.subplot(211)
plt.bar(x, y1, bar_width, align="center", color="c", label="explosion", alpha=0.5)
plt.bar(x+bar_width, y2, bar_width, color="b", align="center", label="gun", alpha=0.5)
plt.bar(x+bar_width+bar_width, y3, bar_width, color="g", align="center", label="noise", alpha=0.5)
plt.bar(x+bar_width+bar_width+bar_width, y3, bar_width, color="y", align="center", label="screaming", alpha=0.5)

plt.ylabel("RMS")
plt.xticks(x+bar_width, tick_label)
plt.legend()

plt.subplot(212)
plt.bar(x, y5, bar_width, align="center", color="c", label="explosion", alpha=0.5)
plt.bar(x+bar_width, y6, bar_width, color="b", align="center", label="gun", alpha=0.5)
plt.bar(x+bar_width+bar_width, y7, bar_width, color="g", align="center", label="noise", alpha=0.5)
plt.bar(x+bar_width+bar_width+bar_width, y8, bar_width, color="y", align="center", label="screaming", alpha=0.5)

plt.ylabel("ZCR")
plt.xticks(x+bar_width, tick_label)
plt.legend()
plt.show()