from src.episode.episode import ALL_OUTCOMES, POS_XLEFT, POS_LEFT, POS_CENTRAL, POS_RIGHT, POS_XRIGHT

OBJ_NONE = "None"
OBJ_LEFT = "Single Left"
OBJ_MULTIPLE_LEFT = "Multiple Left"
OBJ_RIGHT = "Single Right"
OBJ_MULTIPLE_RIGHT = "Multiple Right"
OBJ_BOTH = "Left and Right"

OBJECT_POSITIONS = ["", OBJ_NONE, OBJ_LEFT, OBJ_MULTIPLE_LEFT, OBJ_RIGHT, OBJ_MULTIPLE_RIGHT, OBJ_BOTH]

class EpisodeFilter:

    def __init__(self):
        self.filter_from_start_line = False
        self.filter_max_steps = None
        self.filter_min_percent = None
        self.filter_min_average_reward = None
        self.filter_peak_track_speed = None

        self.filter_complete_section = None
        self.filter_complete_section_time = None
        self.filter_complete_section_steps = None

        self.filter_object_section = None
        self.filter_object_section_positions = None

        self.filter_specific_waypoint_id = None
        self.filter_specific_waypoint_min_reward = None
        self.filter_specific_waypoint_min_future_reward = None
        self.filter_specific_waypoint_min_track_speed = None
        self.filter_specific_waypoint_max_track_speed = None
        self.filter_specific_waypoint_track_position = None

        self.filter_quarters = [ True, True, True, True ]
        self.filter_debug_contains = None
        self.filter_max_slide = None
        self.filter_outcome = None

        self.all_episodes = None

    def reset(self):
        self.filter_from_start_line = False
        self.filter_max_steps = None
        self.filter_min_percent = None
        self.filter_min_average_reward = None
        self.filter_peak_track_speed = None

        self.filter_complete_section = None
        self.filter_complete_section_time = None
        self.filter_complete_section_steps = None

        self.filter_object_section = None
        self.filter_object_section_positions = None

        self.filter_specific_waypoint_id = None
        self.filter_specific_waypoint_min_reward = None
        self.filter_specific_waypoint_min_future_reward = None
        self.filter_specific_waypoint_min_track_speed = None
        self.filter_specific_waypoint_max_track_speed = None
        self.filter_specific_waypoint_track_position = None

        self.filter_quarters = [ True, True, True, True ]
        self.filter_debug_contains = None
        self.filter_max_slide = None
        self.filter_outcome = None

    def set_filter_from_start_line(self, setting :bool):
        self.filter_from_start_line = setting

    def set_filter_max_steps(self, setting: int):
        self.filter_max_steps = setting

    def set_filter_min_percent(self, percent: int):
        self.filter_min_percent = percent

    def set_filter_min_average_reward(self, min_reward: int):
        self.filter_min_average_reward = min_reward

    def set_filter_quarters(self, q1: bool, q2: bool, q3: bool, q4: bool):
        self.filter_quarters = [ q1, q2, q3, q4 ]

    def set_filter_complete_section_and_time(self, start_waypoint_id, finish_waypoint_id, optional_time, optional_steps):
        self.filter_complete_section_time = optional_time
        self.filter_complete_section_steps = optional_steps

        if start_waypoint_id is not None and finish_waypoint_id is not None:
            self.filter_complete_section = (start_waypoint_id, finish_waypoint_id)
        elif start_waypoint_id is not None:
            self.filter_complete_section = (start_waypoint_id, start_waypoint_id)
        elif finish_waypoint_id is not None:
            self.filter_complete_section = (finish_waypoint_id, finish_waypoint_id)
        else:
            self.filter_complete_section = None

    def set_filter_object_section_and_positions(self, start_waypoint_id, finish_waypoint_id, positions):
        self.filter_object_section_positions = positions

        if start_waypoint_id is not None and finish_waypoint_id is not None:
            self.filter_object_section = (start_waypoint_id, finish_waypoint_id)
        elif start_waypoint_id is not None:
            self.filter_object_section = (start_waypoint_id, start_waypoint_id)
        elif finish_waypoint_id is not None:
            self.filter_object_section = (finish_waypoint_id, finish_waypoint_id)
        else:
            self.filter_object_section = None

    def set_filter_peak_track_speed(self, peak_track_speed):
        self.filter_peak_track_speed = peak_track_speed

    def set_filter_specific_waypoint_reward(self, waypoint_id: int, min_reward: float):
        self.filter_specific_waypoint_id = waypoint_id

        if waypoint_id is not None:
            self.filter_specific_waypoint_min_reward = min_reward
        else:
            self.filter_specific_waypoint_min_reward = None

    def set_filter_specific_waypoint_future_reward(self, waypoint_id: int, min_future_reward: float):
        self.filter_specific_waypoint_id = waypoint_id

        if waypoint_id is not None:
            self.filter_specific_waypoint_min_future_reward = min_future_reward
        else:
            self.filter_specific_waypoint_min_future_reward = None

    def set_filter_specific_waypoint_min_track_speed(self, waypoint_id: int, min_track_speed: float):
        self.filter_specific_waypoint_id = waypoint_id

        if waypoint_id is not None:
            self.filter_specific_waypoint_min_track_speed = min_track_speed
        else:
            self.filter_specific_waypoint_min_track_speed = None

    def set_filter_specific_waypoint_max_track_speed(self, waypoint_id: int, max_track_speed: float):
        self.filter_specific_waypoint_id = waypoint_id

        if waypoint_id is not None:
            self.filter_specific_waypoint_max_track_speed = max_track_speed
        else:
            self.filter_specific_waypoint_max_track_speed = None

    def set_filter_specific_waypoint_track_position(self, waypoint_id: int, track_position: float):
        self.filter_specific_waypoint_id = waypoint_id

        if waypoint_id is not None:
            self.filter_specific_waypoint_track_position = track_position
        else:
            self.filter_specific_waypoint_track_position = None

    def set_filter_debug_contains(self, debug_contains):
        self.filter_debug_contains = debug_contains

    def set_filter_max_slide(self, max_slide):
        self.filter_max_slide = max_slide

    def set_filter_outcome(self, outcome):
        assert outcome in ALL_OUTCOMES
        self.filter_outcome = outcome

    def set_all_episodes(self, all_episodes):
        self.all_episodes = all_episodes

    def get_filtered_episodes(self, track):
        if not self.all_episodes:
            return None

        result = []
        for e in self.all_episodes:
            if self.filter_quarters[e.quarter - 1]:
                if e.is_real_start or not self.filter_from_start_line:
                    if self.filter_max_steps is None or e.step_count <= self.filter_max_steps:
                        if self.filter_min_percent is None or e.percent_complete >= self.filter_min_percent:
                            if self.filter_min_average_reward is None or e.average_reward >= self.filter_min_average_reward:
                                if self.filter_peak_track_speed is None or e.peak_track_speed >= self.filter_peak_track_speed:
                                    if self.filter_max_slide is None or e.max_slide <= self.filter_max_slide:
                                        if self.filter_outcome is None or e.outcome == self.filter_outcome:
                                            if self.matches_complete_section_filter(e, track):
                                                if self.matches_object_section_filter(e):
                                                    if self.matches_specific_waypoint_reward_filter(e):
                                                        if self.filter_debug_contains is None or e.does_debug_contain(self.filter_debug_contains):
                                                            result.append(e)
        return result

    def matches_specific_waypoint_reward_filter(self, episode):
        if self.filter_specific_waypoint_id is None:
            return True
        else:
            for e in episode.events:
                if e.closest_waypoint_index == self.filter_specific_waypoint_id:
                    matches = True
                    if self.filter_specific_waypoint_min_reward is not None and e.reward < self.filter_specific_waypoint_min_reward:
                        matches = False
                    if self.filter_specific_waypoint_min_future_reward is not None and e.discounted_future_rewards[0] < self.filter_specific_waypoint_min_future_reward:
                        matches = False
                    if self.filter_specific_waypoint_min_track_speed is not None and e.track_speed < self.filter_specific_waypoint_min_track_speed:
                        matches = False
                    if self.filter_specific_waypoint_max_track_speed is not None and e.track_speed > self.filter_specific_waypoint_max_track_speed:
                        matches = False
                    if self.filter_specific_waypoint_track_position is not None and not self._matches_track_position(e):
                        matches = False
                    if matches:
                        return True
        return False

    def _matches_track_position(self, event):
        if self.filter_specific_waypoint_track_position == POS_XLEFT:
            return event.track_side == "L" and not event.all_wheels_on_track
        if self.filter_specific_waypoint_track_position == POS_LEFT:
            return event.track_side == "L"
        if self.filter_specific_waypoint_track_position == POS_CENTRAL:
            return event.distance_from_center <= 0.1
        if self.filter_specific_waypoint_track_position == POS_RIGHT:
            return event.track_side == "R"
        if self.filter_specific_waypoint_track_position == POS_XRIGHT:
            return event.track_side == "R" and not event.all_wheels_on_track

        return False

    def matches_complete_section_filter(self, episode, track):
        if not self.filter_complete_section:
            return True

        (start, finish) = self.filter_complete_section

        events = episode.get_section_start_and_finish_events(start, finish, track)
        if not events:
            return False

        (start_event, finish_event) = events

        time_ok = not self.filter_complete_section_time or finish_event.time - start_event.time <= self.filter_complete_section_time
        steps_ok = not self.filter_complete_section_steps or finish_event.step - start_event.step <= self.filter_complete_section_steps

        return time_ok and steps_ok

    def matches_object_section_filter(self, episode):
        if not self.filter_object_section:
            return True

        (start, finish) = self.filter_object_section

        left, right = episode.count_objects_in_section(start, finish)

        if self.filter_object_section_positions == OBJ_RIGHT:
            return left == 0 and right == 1
        if self.filter_object_section_positions == OBJ_LEFT:
            return left == 1 and right == 0
        if self.filter_object_section_positions == OBJ_MULTIPLE_RIGHT:
            return left == 0 and right >= 2
        if self.filter_object_section_positions == OBJ_MULTIPLE_LEFT:
            return left >= 2 and right == 0
        if self.filter_object_section_positions == OBJ_BOTH:
            return left >= 1 and right >= 1
        if self.filter_object_section_positions == OBJ_NONE:
            return left == 0 and right == 0
        else:
            assert self.filter_object_section_positions is None or self.filter_object_section_positions == ""
            return True


from tkinter import *
import csv

root = Tk()
root.title("Text to Check")

#Menu bar (just gonna have saving and loading for now)

menubar = Menu(root)
filemenu = Menu(menubar)
menubar.add_command(label="Save", command=lambda:saver())
menubar.add_command(label="Load", command=lambda:loader())
root.config(menu=menubar)

#First Column: Task Entry

lbl = Label(root, text="Put Tasks Here", font=("Arial", 18), fg="white", bg="green", width=15)
lbl.grid(column=0, row=0)

todo = Text(root, width=20, height=20, font=("Arial", 12))
todo.grid(column=0, row=1)

ent_but = Button(root, text="Save to Tasklist", command=lambda:getter())
ent_but.grid(column=0, row=2)

#Second Column: Checklist

slbl = Label(root, text="To Do List", font=("Arial", 18), fg="white", bg="red", width=15)
slbl.grid(column=1, row=0)

scheck = Frame(root)
scheck.grid(column=1, row=1)

sent = Button(root, text="Clear Completed Tasks", command=lambda:deleter())
sent.grid(column=1, row=2)

#gets the user input after they click the button to add to the checklist

class Logging:
	log_count = 0

variable_list = []
checklist_name = []

def getter():
	input = todo.get("1.0", 'end-1c')
	var = IntVar()
	cb = Checkbutton(scheck, text=input, font=("Arial", 12), offvalue=0, onvalue=1, variable=var)
	cb.grid(row=Logging.log_count)
	checklist_name.append(input)
	variable_list.append(var)
	Logging.log_count += 1

#deletes all completed tasks

def deleter():
	global variable_list, checklist_name

	vl2 = [variable_list[i] for i in range(len(variable_list)) if variable_list[i].get() == 0]
	cl2 = [checklist_name[i] for i in range(len(variable_list)) if variable_list[i].get() == 0]

	variable_list = vl2
	checklist_name = cl2

	for child in scheck.winfo_children():
		child.destroy()

	for i in range(len(variable_list)):
		var = variable_list[i]
		cb = Checkbutton(scheck, text=checklist_name[i], font=("Arial", "12"), offvalue=0, onvalue=1, variable=var)
		cb.grid(row=i)

	Logging.log_count = len(variable_list)

#Saves the tasklist file

def saver():
	global variable_list, checklist_name
	file = open(r"C:\Users\User\Documents\PythonWork\savedlist.txt", "w")
	for i in range(len(variable_list)):
		if i != range(len(variable_list)):
			file.write(str(variable_list[i].get()) + "," + str(checklist_name[i]) + "\n")
		else:
			file.write(str(variable_list[i].get()) + "," + str(checklist_name[i]))
	file.close()
	return

#Loads the tasklist file

def loader():
	global variable_list, checklist_name

	vl = []
	cl = []

	file = open(r"C:\Users\User\Documents\PythonWork\savedlist.txt", "r")
	readCSV = csv.reader(file, delimiter=",")
	for row in readCSV:
		vl.append(int(row[0]))
		cl.append(row[1])
	file.close()

	for child in scheck.winfo_children():
		child.destroy()

	new_vl = []

	for i in range(len(vl)):
		var = IntVar()
		if vl[i] == 0:
			cb = Checkbutton(scheck, text=cl[i], font=("Arial", "12"), offvalue=0, onvalue=1, variable=var)
			cb.grid(row=i)
			cb.deselect()
			new_vl.append(var)
		elif vl[i] == 1:
			cb = Checkbutton(scheck, text=cl[i], font=("Arial", "12"), offvalue=0, onvalue=1, variable=var)
			cb.grid(row=i)
			cb.select()
			new_vl.append(var)

	variable_list = new_vl
	checklist_name = cl
	Logging.log_count = len(vl)

root.mainloop()


#from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from .models import Issue
from .serializers import IssueSerializer

@csrf_exempt
def issue_list(request):
    """
    Create, get an issue.
    """
    if request.method == 'GET':
        issues = Issue.objects.all()
        serializer = IssueSerializer(issues, many=True)
        return JsonResponse(serializer.data, safe=False)
    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = IssueSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)

@csrf_exempt
def issue_detail(request, pk):
    """
    Retrieve, update or delete an issue.
    corresponds to an individual issue.
    """
    try:
        issue = Issue.objects.get(pk=pk)
    except Issue.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = IssueSerializer(issue)
        return JsonResponse(serializer.data)

    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        serializer = IssueSerializer(issue, data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data)
        return JsonResponse(serializer.errors, status=400)

    elif request.method == 'DELETE':
        issue.delete()
        return HttpResponse(status=204)


import math
# Even + Even = Even
# Odd + Even = Odd
# Even + Odd = Odd
# Odd + Odd = Even

N = int(input())

lower = math.floor(N / 2)
higher = math.ceil(N / 2)

# Check to see if it can be perfectly split in half
if lower == higher:
    if lower % 2 == 1:
        print("Odd")
    else:
        print("Even")
else:
    print("Either")


import re

import click
from mne_bids.tsv_handler import _from_tsv

from eztrack.base.utils.file_utils import _get_subject_channels_tsvs
from eztrack.cli.base.config import logger as logger

def print_channel_status(bids_root, subject_id, session_id, acquisition_id):
    """
    Print the channel and status of every channel for a certain acquisition type.

    Parameters
    ----------
    bids_root : Union[Path or str]
        The directory where data is being stored.
    subject_id : str
        The unique identifier of the subject
    session_id: str
        The identifier of the recording session, usually 'seizure' or 'interictal'
    acquisition_id : str
        One of 'eeg', 'ecog', or 'seeg'

    """
    channel_fpaths = _get_subject_channels_tsvs(
        bids_root, subject_id, session_id, acquisition_id
    )
    logger.info(f"Found channel files for subject {subject_id}: {channel_fpaths}")
    if len(channel_fpaths) == 0:
        logger.error(f"No channel files for subject: {subject_id}")
        raise RuntimeError(f"No channel files for subject: {subject_id}.")
    channel_fpath = channel_fpaths[0]
    logger.info(f"Using channel file '{channel_fpath}'")

    # Read in current channel statuses
    channel_tsv = _from_tsv(channel_fpath)
    bad_chs = []
    good_chs = []
    for i, ch in enumerate(channel_tsv["name"]):
        if channel_tsv["status"][i] == "bad":
            bad_chs.append(ch)
        else:
            good_chs.append(ch)

    # create string of channels to display to user
    if len(bad_chs) == 0:
        bad_channels_str = "None"
    else:
        bad_channels_str = ", ".join(bad_chs)
    if len(bad_chs) == 0:
        good_channels_str = "None"
    else:
        good_channels_str = ", ".join(good_chs)

    click.echo(f"Bad channels for {subject_id}:")
    click.echo(bad_channels_str)
    click.echo(f"Channels included in analysis for {subject_id}:")
    click.echo(good_channels_str)

def channels_to_list(channel_string):
    """
    Convert a string of a channel list into a list.

    Parameters
    ----------
    channel_string : str
        The list of channels, separated by commas, spaces, and/or semicolons

    Returns
    -------
    channel_list: list[str]
        The list object of channels

    """
    channel_string = channel_string.replace(" ", "")
    channel_list = re.split(";|,|; |, ", channel_string)
    channel_list = [ch.upper() for ch in channel_list]
    return channel_list


import datetime
from lib.sguilsql import getSguilSql

def playbookInput(event):
    event.setOutPath()
    event.setDateRange()
    event.setAttribute('_sqlLimit', confVars.sqlLimit)

def adhocInput(event):
    inputHeader = '%s Query Options' % FORMAL_NAME
    event.setOutPath()
    event.setDateRange()
    event.setAttribute('ip_address_list', prompt='IP Address(es)', header=inputHeader, multiline=True, description="Provide a newline delimited list of one or more IP addresses")
    event.ip_address_list = [x.strip() for x in event.ip_address_list.splitlines() if x]
    event.setAttribute('_sqlLimit', prompt='Maximum Number of Events', default=confVars.sqlLimit)

def execute(event):

    print('Querying Sguil DB...\n')

    if (datetime.datetime.now() - event._startDate).days < 7:
        start = event._DT - datetime.timedelta(days=7)
    else:
        start = event._startDate

    if not hasattr(event, 'ip_address_list'):
        event.ip_address_list = [event.ip_address]

    for ip in event.ip_address_list:
        print("Pulling events for %s..." % ip)

        query = "( SELECT event.status, event.priority, sensor.hostname, event.sid, event.cid, event.timestamp as datetime, "
        query += "INET_NTOA(event.src_ip), event.src_port, INET_NTOA(event.dst_ip), event.dst_port, event.ip_proto, event.signature, "
        query += "event.signature_gen, event.signature_id, event.signature_rev FROM event IGNORE INDEX (event_p_key, sid_time) "
        query += "INNER JOIN sensor ON event.sid=sensor.sid WHERE event.timestamp > '%s' and event.src_ip = INET_ATON('%s')) " % (start.date().isoformat(), ip)
        query += "UNION "
        query += "( SELECT event.status, event.priority, sensor.hostname, event.sid, event.cid, event.timestamp as datetime, "
        query += "INET_NTOA(event.src_ip), event.src_port, INET_NTOA(event.dst_ip), event.dst_port, event.ip_proto, event.signature, "
        query += "event.signature_gen, event.signature_id, event.signature_rev FROM event IGNORE INDEX (event_p_key, sid_time) "
        query += "INNER JOIN sensor ON event.sid=sensor.sid WHERE event.timestamp > '%s' and event.dst_ip = INET_ATON('%s')) ORDER BY datetime, " % (start.date().isoformat(), ip)
        query += "src_port ASC LIMIT %s" % event._sqlLimit

        log.debug('msg="Sguil Events Query" query="%s"' % query)

        queryResults = getSguilSql(query, sguilserver=so_server, serverUser='cirta', serverKey='/nsm/scripts/python/cirta/resources/nsm/.cirtaid', tableSplit=True)

        orf = '%s.%s' % (event._baseFilePath, confVars.outputExtension)

        outRawFile = open(orf, 'a')

        for line in queryResults:
            outRawFile.write(','.join(line[:-3]) + '\n')

        outRawFile.close()

#    splunkSguilEvents = []
#    for line in open(orf, 'rb'):
#        if 'INET_NTOA' not in line:
#            splunkSguilEvents.append(line)

#    event._splunk.push(sourcetype=confVars.splunkSourcetype, eventList=splunkSguilEvents)
    event._splunk.push(sourcetype=confVars.splunkSourcetype, filename=orf, exclusionRegex='INET_NTOA')

    print('\n%s results saved to: %s' % (FORMAL_NAME, orf))


# imports
from bs4 import BeautifulSoup as bs
from collections import OrderedDict
import urllib.request

class Crawler:
    def __init__(self, seed_urls, base_url):
        self.__seed_urls = seed_urls
        self.__base_url = base_url
        self.__frontier = []
        self.__visited = []
        self.__internal_url_structure = {}
        self.__tokens = {}
        self.__document_soups = self.__crawl()
        self.__COLLECTION_SIZE = len(self.__internal_url_structure)

    def __crawl(self):
        document_soups = {}
        for url in self.__seed_urls:
            self.__frontier.append(self.__base_url + url)
            while len(self.__frontier) > 0:
                current_url = self.__frontier[0]
                page = urllib.request.urlopen(current_url)
                soup = bs(page.read(), "html.parser")
                self.__visited.append(current_url)
                self.__frontier.pop(0)
                key = soup.title.string
                self.__internal_url_structure[key] = []

                document_soups[key] = soup

                for internal_url in soup.find_all('a'):
                    doc_title = internal_url.get('href')
                    current_internal_url = self.__base_url + doc_title
                    value = doc_title.rsplit('.')[0]
                    self.__internal_url_structure[key].append(value)
                    if current_internal_url not in self.__visited:
                        self.__frontier.append(current_internal_url)
                        self.__visited.append(current_internal_url)

        self.__tokens = self.__sort_keys_in_dict(self.__tokens)
        self.__internal_url_structure = self.__sort_values_in_dict(self.__sort_keys_in_dict(self.__internal_url_structure))

        self.__print_internal_url_structure()
        return document_soups

    def __sort_keys_in_dict(self, dict):
        return OrderedDict(sorted(dict.items()))

    def __sort_values_in_dict(self, dict):
        for key in dict:
            dict[key] = sorted(dict[key])
        return dict

    def __print_internal_url_structure(self):
        print('# INTERNAL URL STRUCTURE:')
        for key, value in self.__internal_url_structure.items():
            print(key + ': ' + ','.join(value))
        print('--------------------')

    def get_internal_url_structure(self):
        return self.__internal_url_structure

    def get_document_soups(self):
        return self.__document_soups

    def get_collection_size(self):
        return self.__COLLECTION_SIZE


"""
Reverse every other word in a given string, then return the string.
Throw away any leading or trailing whitespace, while ensuring there is exactly one space between each word.
Punctuation marks should be treated as if they are apart of the word in this kata.
"""

import re

def reverse_alternate(string):
  # Check if the string input is whitespace only, if yes, return ''
  space_only_regex = re.compile('^\s+$')
  if space_only_regex.match(string):
    return ''

  # Declare variables and create string split which is array with no white space elements
  counter = 0
  string_split = list(filter(lambda x: x != '', string.split(' ')))
  return_string = list()

  # While loop through the string split array and create return_string variable
  while counter < len(string_split):
      if counter % 2 == 0:
          return_string.append(string_split[counter])
      else:
          return_string.append(string_split[counter][::-1])

      counter += 1

  # Return return_string array converted to string with a space divider
  return ' '.join(return_string)


from fcutils.maths import coordinates

import numpy as np
from numpy.random import uniform

def test_coordinates_transformations():
    for i in range(5):
        x, y = uniform(-100, 100), uniform(-100, 100)

        r, p = coordinates.cart2pol(x, y)

        x2, y2 = coordinates.pol2cart(r, p)

        assert np.abs(x - x2) < 0.1
        assert np.abs(y - y2) < 0.1


#ファイル名、フォルダ名にスペースを入れるとエラーが発生(sys.args内)
#実行する際はファイル名に加えて画像データ名を入力
#import
import cv2
import sys #コマンドの実行時に画像ファイルを渡すために必要

image_file = None #画像ファイルのパスを保存するための変数を宣言
cascade_file = './haarcascades/haarcascade_frontalface_alt.xml' #カスケードファイル(学習データ)の指定

args = sys.argv

if len(args) > 1: #実行時に渡された画像ファイル名の取得
    image_file = args[1] #python 実行ファイル名=0　画像のパス=1....が中身なので1を指定。変数には文字列でパスが入る

image = cv2.imread(image_file) #プログラム内で使える画像データの生成

cv2.imshow('image', image) #読み取った画像を表示する。imshow(windowname, 生成したオブジェクト)
cv2.waitKey(0)

image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #ノイズを減らすためにモノクロ画像へと変換する

cv2.imshow('image', image_gray) #モノクロ化した画像を表示
cv2.waitKey(0)

cascade = cv2.CascadeClassifier(cascade_file) #カスケードファイルを用いてカスケード検出器を作成

front_face_list = cascade.detectMultiScale(image_gray, minSize = (30, 30)) #顔の検出処理を行う #minSizeは顔の最小サイズ(30ピクセル以上を顔と認識する)

print(front_face_list) #x座標,y座標(顔の左上),横幅,縦幅

if len(front_face_list): #検出された顔を赤い線で囲む
    for (x,y,w,h) in front_face_list:
        print("[x,y] = %d,%d [w,h] = %d,%d" %(x, y, w, h))
        cv2.rectangle(image, (x,y), (x+w, y+h), (0, 0, 255), thickness=10) #rectangle(画像, 左上座標, 右下座標, 色, 線の太さ)

    cv2.imshow('image', image)
    cv2.waitKey(0)
else:
    print('not detected')


__author__ = 'fcaramia'
import optparse
from readinputs import *
from utils import *
from writeresults import *
import networkx as nx

def main():

    parser = optparse.OptionParser()

    parser.add_option('-i', '--interactome', type='string', dest="interactome", help="interactome file")
    parser.add_option('-c', '--config', type='string', dest="config_file", help="config file")
    parser.add_option('-s', '--siRNA', type='string', dest="siRNA_file", help="siRNA candidates file")
    parser.add_option('-o', '--outfile', dest='out', help="output file", default='out.txt', type='string')
    parser.add_option('-m', '--miRNA', dest='miRNA_file', help="miRNA file", type='string')
    (options, args) = parser.parse_args()

    if not options.config_file:
        parser.error("config file is needed")

    if not options.siRNA_file:
        parser.error("siRNA file is needed")

    # Read Config
    config = {}
    config = read_config(options.config_file, config)

    # Print config
    for k in config:
        print(k, config[k])

    if not validate_config(config):
        parser.error("Invalid config file")

    # Read Candidates
    candidates = {}
    candidates = read_candidates(options.siRNA_file, candidates)

    miRNAs = {}
    # Read miRNA
    if options.miRNA_file:
        miRNAs = read_candidates(options.miRNA_file, miRNAs)
        # Check sign of miRNAs
        miRNAs = check_sign_of_candidates(miRNAs, parser)

    interactome = {}
    # Read interactome
    if options.interactome:
        interactome = read_interactome(options.interactome, interactome)

    # Check sign of candidates
    candidates = check_sign_of_candidates(candidates, parser)
    candidates_raw = candidates.copy()
    # set graph
    graph = nx.DiGraph()
    mir_graph = nx.DiGraph()

    # Read DBs
    marks = {}

    if config["mirTarBase"] != '':
        print("Loading mirTarBase")
        mir_graph = read_db(config["gene_db_dir"] + config['mirTarBase'], mir_graph)

    for db in config['gene_dbs']:

        graph = read_db(config["gene_db_dir"] + db, graph, config['directed'], float(config["min_score"]))

    # Mark genes that are connected to each other
    if config["expand"] == 0:
        # Check only for direct regulation
        marks = check_reg_graph(list(candidates.keys()), graph, marks)
    else:
        if config['directed'] == 'no':
            print("Warning: creating a non directed network could add false positives")
        print("Expanding Search")
        print(len(candidates), "siRNA candidates")
        print(len(graph.nodes()), "nodes")
        print(len(graph.edges()), "edges")

        marks = check_graph(list(candidates.keys()), graph, marks, config['expand'])

    i = 0
    for r in marks:
        i += len(marks[r])

    not_in_db = 0
    nodes = list(graph.nodes())
    for c in candidates:
        if c not in nodes:
            not_in_db += 1

    print("Candidate genes with no evidence for selected score: " + str(not_in_db))

    # Generate Network score for marked genes
    norm_network_scores_neg = {}
    norm_network_scores_pos = {}
    paths_for_scoring = marks
    network_scores_neg = {}
    network_scores_pos = {}

    if len(marks) > 0:

        if config['filter_by_si']:
            paths_for_scoring = mark_for_scoring(candidates, marks, config['std_dev_val'])
        # Generate network scores
        get_network_scores(paths_for_scoring, graph, config['score_reduce_fun'], network_scores_neg, network_scores_pos)

        if config['scoring'] in ["neg", "pos_neg"]:
            norm_network_scores_neg = normalize_scores(network_scores_neg, 0.0, float(config["network"]), 0.0)

        if config['scoring'] in ["pos", "pos_neg"]:
            norm_network_scores_pos = normalize_scores(network_scores_pos, 0.0, float(config["network"]), 0.0)

    # Generate miRNA scores
    norm_mir_scores = {}
    if len(mir_graph) > 0 and len(miRNAs) > 0:
        # Search predecessors of genes and compute mir scores
        mir_scores = get_mir_scores(candidates, mir_graph, miRNAs, config['mir_score_select'])
        norm_mir_scores = normalize_scores(mir_scores, 0.0, float(config["miRNA"]), 0.0)

    norm_si_scores = normalize_scores(candidates, 0.0, float(config["siRNA"]), float(config["std_capping"]))

    total_scores = process_total_scores(norm_si_scores, norm_network_scores_neg, norm_network_scores_pos,
                                        norm_mir_scores)

    print_results(options.out, graph, paths_for_scoring, mir_graph, total_scores, norm_si_scores,
                  norm_network_scores_neg, norm_network_scores_pos, norm_mir_scores, config, candidates_raw,
                  network_scores_neg, network_scores_pos, mir_scores, miRNAs, interactome)

    print_stats(norm_si_scores, norm_network_scores_neg, norm_network_scores_pos, norm_mir_scores, total_scores, options.out)

if __name__ == '__main__':
    main()


import numpy as np
from scipy.ndimage import label
from sklearn.mixture import GaussianMixture
import math
import nd2
import cv2
from tqdm import tqdm

def create_circular_mask(h, w, center, radius):
    '''
    Helper function to mask out cirular region of 2D array
    '''
    Y, X = np.ogrid[:h, :w]
    dist_from_center = np.sqrt((X - center[0])**2 + (Y-center[1])**2)

    mask = dist_from_center <= radius
    return mask

def return_overlapping_set(vertex, adj_matrix):
    '''
    Helper function to return set of all circles overlapping with a given circle by searching the
    overlapping graphs adjacency matrix in a BFS manner
    '''
    # Put initial adjacent vertecies in set and populate queue
    queue = list(np.nonzero(adj_matrix[vertex]))[0]
    ol_set = [vertex]

    # while queue is not empty
    while len(queue) > 0:
        # pop vertex
        vert = queue[0]
        queue = queue[1:]

        # Ad vertex to visited set
        ol_set.append(vert)

        # Get adjacent to new vertes
        vert_adj = list(np.nonzero(adj_matrix[vert]))[0]
    return ol_set

def circle_rect(rectangle):
    '''
    Enscribe a circle around a rectangle
    '''
    a = abs(rectangle[0][0] - rectangle[0][1])
    b = abs(rectangle[1][0] - rectangle[1][1])
    r = 0.5 * math.sqrt(a**2 + b **2)
    c = (rectangle[0][1] - a//2, rectangle[1][1] - b//2)
    return [c, r]

def circle_weight(circle, points):
    '''
    Compute the prportion of a circle (in an integer grid) that a point cloud covers.
    Used as a metric of circlularity
    '''
    # Get how many points should be in the circle

    # we could easily approximate this
    denom = round(circle[1]**2 * np.pi) // 1
    # Return fraction represented in points
    return len(points) / denom

def clean_satellites(image, verbose=True, brightness_threshold_percentile=99, elimination_threshold=50, overlap_padding=20, circle_mask_padding=10):
    '''
    Apply satellite dropplet cleaning technique to image (grayscale array).
    Techinque should be applied to the large images and will not work properly with individual droplets

    verbose                         <--- Report progress
    brightness_threshold_percentile <--- 100 - percetnage of brightest points to consider
    elimination_threshold           <--- minimum size of contiguous bright region to be considered when checking for sattelites,
                                         smaller regions will be automatically discardeds
    overlap_padding                 <--- padd circles when checking for overlap, in theory this should be large enough to account
                                         for dark bands cutting through sattelite dropplets
    circle_mask_padding             <--- enlarge border of circle used to mask out a sattelite dropplet. Should be thickness of dark rim of sattelite
    '''
    #TODO: Sanity checks

    # Brightness threshold percentile of 99 percent means top 1% of brightest points will be considered
    if verbose:
        print('1/6 | Determining brightness threshold and masking brightest points')
    sample = np.random.choice(a=image.flatten(), size=1000000)
    brightness_threshold = np.percentile(sample, brightness_threshold_percentile)

    # Create mask of brightest points in image
    mask = np.zeros(image.shape)
    mask[image > brightness_threshold] = 1

    # Get contiguous objects (regions of 1's) in mask
    if verbose:
        print('2/6 | Computing objects')
    labeled_features, num_features = label(mask)

    # Enscribe features with boxes
    if verbose:
        print('3/6 | Determining object bounding boxes and circles')
    feature_squares = []
    feature_points = []

    # X and Y naming is a bit wierd here
    for feat in tqdm(range(1, num_features + 1)):
        feat_coords = np.argwhere(labeled_features == feat)
        #TODO: Do something to remove features that are only a couple of pixels
        if len(feat_coords) > elimination_threshold:
            feature_points.append(feat_coords)
            x_coords = feat_coords[:,0]
            y_coords = feat_coords[:,1]
            x_axis = [min(x_coords), max(x_coords)]
            y_axis = [min(y_coords), max(y_coords)]
            feature_squares.append([y_axis, x_axis])

    # Enscribe circles around identified rectangular regions
    feature_circles = []

    for rect in feature_squares:
        feature_circles.append(circle_rect(rect))

    # Determine threshold of circle-similarity to seperate sattelites from dropplet edge segments
    if verbose:
        print('4/6 | Computing circle similarity threshold and circle similarity')
    scores = []
    for i in tqdm(range(len(feature_circles))):
        scores.append(circle_weight(feature_circles[i], feature_points[i]))

    gm = GaussianMixture(n_components=2, random_state=0)

    gm.fit(np.array(scores).reshape(-1, 1))

    x_den = np.linspace(0, 1, num=100)
    y_lab = gm.predict(x_den.reshape(-1, 1))

    decision_boundary = np.where(y_lab[:-1] != y_lab[1:])[0][0] + 2

    circle_weight_threshold = decision_boundary / 100

    mask_cw = []
    fil_circles = []
    fil_points = []

    for i in range(len(feature_circles)):
        score = scores[i]
        if score >= circle_weight_threshold:
            fil_circles.append(feature_circles[i])
            fil_points.append(feature_points[i])

    # Merge overlapping segments into larger based on padded circle collision
    # Determine threshold of circle-similarity to seperate sattelites from dropplet edge segments
    if verbose:
        print('5/6 | Merging overlapping sattelites')
    intersect_matrix = np.zeros((len(fil_circles), len(fil_circles)))

    for x in tqdm(range(len(fil_circles))):
        #only need to compute half and no diagonals
        for y in range(len(fil_circles)):
            if x == y:
                continue
            # Two ifcles intersect if distance between center points is less than sum of radii
            dR1R2 = np.linalg.norm(np.subtract(fil_circles[x][0], fil_circles[y][0]))
            intersect_matrix[x][y] = (dR1R2 <= fil_circles[x][1] + fil_circles[y][1] + overlap_padding)
            intersect_matrix[y][x] = (dR1R2 <= fil_circles[x][1] + fil_circles[y][1]+ overlap_padding)

    # Get sets of overlapping circles
    ol_circles = []
    ol_points = []
    ol_set = []
    considered_verticies = []

    # Copy intersect matrx
    ol_intersect = intersect_matrix

    for circ_index in tqdm(range(len(fil_circles))):
        # If circle not overlapping with anyone
        if sum(ol_intersect[circ_index]) == 0:
            # Just put it in the output array
            ol_circles.append(fil_circles[circ_index])
            ol_points.append(fil_points[circ_index])
        else:
            # Theres some overlapping afoot!

            # If vertex already considered, ignore
            if circ_index in considered_verticies:
                continue
            # Get indecies of all overlapping circles
            new_ol_set = return_overlapping_set(circ_index, ol_intersect)

            ol_set.append(new_ol_set)
            considered_verticies = considered_verticies + new_ol_set

            # Merge point clouds in new_ol_set
            new_points = fil_points[new_ol_set[0]]
            for i in new_ol_set[1:]:
                new_points = list(new_points) + list(fil_points[i])
            ol_points.append(new_points)

            # Compute new boxes
            x_coords = np.array(new_points)[:,0]
            y_coords = np.array(new_points)[:,1]
            x_axis = [min(x_coords), max(x_coords)]
            y_axis = [min(y_coords), max(y_coords)]
            new_box = [y_axis, x_axis]

            ol_circles.append(circle_rect(new_box))

    gs_image = image

    ip_mask = np.zeros(gs_image.shape)

    # For each circle, paint it in the mask
    if verbose:
        print('6/6 | Masking sattelites')

    for circle in tqdm(ol_circles):
        cv2.circle(ip_mask, circle[0], math.ceil(circle[1]) + circle_mask_padding ,255,-1)

    ip_mask =  np.array(ip_mask, dtype = np.uint8)

    #mask_content = cv2.bitwise_and(gs_image, gs_image, mask = ip_mask)

    masked_image = cv2.bitwise_and(gs_image, gs_image, mask = cv2.bitwise_not(ip_mask))

    return masked_image

if __name__ == "__main__":
    # Run test
    # Import test

    #path = "notebooks/data/20220722PM_ATTO2_T1_Split1.nd2"
    path = "notebooks/data/20220722PM_Calcein2_T1_Split1.nd2"
    #path = "notebooks/data/20220722PM_SulfoB1_T1_Split2.nd2"
    #path = "notebooks/data/20220722PM_CF405S_2_t1.nd2"
    #path = "notebooks/data/20220722PM_Calcein1_T1_Split2.nd2"

    test_image = nd2.imread(path)[-1]

    masked_image = clean_satellites(test_image)

    from matplotlib import pyplot as plt
    plt.imshow(test_image)
    plt.show()

    plt.imshow(masked_image)
    plt.show()


from lister import ListInstance

class Spam(ListInstance): # Наследует метод __str__
    def __init__(self):
        self.data1 = "food"

x = Spam()
print(x) # print() и str() вызывают __str__
#<Instance of Spam, address 40240880:
#name data1=food

print(str(x))
#‘<Instance of Spam, address 40240880:\n\tname data1=food\n>’
print(x) # По умолчанию используется __repr__
#<__main__.Spam object at 0x026606F0>

ООП/ООП_tasks/Примесные классы/lister_run.py


import sys

def find(parent, x):
    if parent[x] != x:
        parent[x] = find(parent, parent[x])
    return parent[x]

def union(parent, a, b):
    ap = find(parent, a)
    bp = find(parent, b)

    if ap < bp:
        parent[bp] = ap
    else:
        parent[ap] = bp

n, m = map(int, sys.stdin.readline().split())
result = 0

knower = list(map(int, sys.stdin.readline().split()))[1:]
parent = [j for j in range(n+1)]
stranger = []
for i in range(m):
    temp = list(map(int, sys.stdin.readline().split()))
    stranger.append(temp[1:])

    if temp[0] >= 2:
        for j in range(2, len(temp)):
            if find(parent, temp[j - 1] != find(parent, temp[j])):
                union(parent, temp[j - 1], temp[j])

for j in stranger:
    flag = 1
    for t in knower:
        if find(parent, j[0]) == find(parent, t):
            flag = 0
    if flag:
        result += 1

print(result)


from PyQt5 import QtCore, QtGui, QtWidgets
import os
from PyPDF3 import PdfFileReader, PdfFileMerger

def checkEncryption(filename):
    obj = PdfFileReader(filename)
    global trueFalse
    trueFalse = obj.getIsEncrypted()
    return trueFalse

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(506, 427)
        MainWindow.setMinimumSize(QtCore.QSize(506, 427))
        MainWindow.setMaximumSize(QtCore.QSize(506, 427))
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(10, 10, 491, 51))
        self.label.setStyleSheet("QLabel{font-size:40px;font-family:\'Times New Roman\', cursive;color:white;background-color:#000;border-radius:20px;}")
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setObjectName("label")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget,clicked=self.extractFromFolder)
        self.pushButton.setGeometry(QtCore.QRect(10, 80, 241, 51))
        self.pushButton.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.pushButton.setStyleSheet("QPushButton{font-size:20px;font-family:\'Times New Roman\', cursive;color:white;background-color:#000;border-radius:20px;}QPushButton:hover{background-color:crimson;color:gold;font-weight:bold;}")
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget,clicked=self.selectFiles)
        self.pushButton_2.setGeometry(QtCore.QRect(270, 80, 231, 51))
        self.pushButton_2.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.pushButton_2.setStyleSheet("QPushButton{font-size:20px;font-family:\'Times New Roman\', cursive;color:white;background-color:#000;border-radius:20px;}QPushButton:hover{background-color:crimson;color:gold;font-weight:bold;}")
        self.pushButton_2.setObjectName("pushButton_2")
        self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
        self.groupBox.setGeometry(QtCore.QRect(10, 150, 221, 201))
        self.groupBox.setStyleSheet("border:2px solid #000;")
        self.groupBox.setObjectName("groupBox")
        self.listWidget = QtWidgets.QListWidget(self.groupBox)
        self.listWidget.setGeometry(QtCore.QRect(10, 20, 201, 171))
        self.listWidget.setStyleSheet("border:0;")
        self.listWidget.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.listWidget.setObjectName("listWidget")
        self.groupBox_2 = QtWidgets.QGroupBox(self.centralwidget)
        self.groupBox_2.setGeometry(QtCore.QRect(290, 150, 211, 201))
        self.groupBox_2.setStyleSheet("border:2px solid #000;")
        self.groupBox_2.setObjectName("groupBox_2")
        self.listWidget_2 = QtWidgets.QListWidget(self.groupBox_2)
        self.listWidget_2.setGeometry(QtCore.QRect(10, 20, 191, 171))
        self.listWidget_2.setStyleSheet("border:0;")
        self.listWidget_2.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.listWidget_2.setObjectName("listWidget_2")
        self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget,clicked=self.mergePDFFile)
        self.pushButton_3.setGeometry(QtCore.QRect(10, 360, 491, 51))
        self.pushButton_3.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.pushButton_3.setStyleSheet("QPushButton{font-size:20px;font-family:\'Times New Roman\', cursive;color:white;background-color:#000;border-radius:20px;}QPushButton:hover{background-color:crimson;color:gold;font-weight:bold;}")
        self.pushButton_3.setObjectName("pushButton_3")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(240, 170, 41, 41))
        self.label_2.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.label_2.setText("")
        self.label_2.setPixmap(QtGui.QPixmap("transferFileIcon.png"))
        self.label_2.setObjectName("label_2")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(240, 300, 41, 41))
        self.label_3.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.label_3.setText("")
        self.label_3.setPixmap(QtGui.QPixmap("backupFileIcon.png"))
        self.label_3.setObjectName("label_3")
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        self.mainPDFDictionary = {}
        self.mergePDFDictionary = {}
        self.label_2.mousePressEvent=self.transferFile
        self.label_3.mousePressEvent=self.reverseTransferFile

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "PDF Merger"))
        self.label.setText(_translate("MainWindow", "PDF MERGER"))
        self.pushButton.setText(_translate("MainWindow", "Select folder"))
        self.pushButton_2.setText(_translate("MainWindow", "Select multiple PDF Files"))
        self.groupBox.setTitle(_translate("MainWindow", "Files Found"))
        self.groupBox_2.setTitle(_translate("MainWindow", "Files to be merged"))
        self.pushButton_3.setText(_translate("MainWindow", "Merge"))

    def selectFiles(self):
        listPdfFiles = QtWidgets.QFileDialog.getOpenFileNames(None,'Select PDF Files','/','PDF (*.pdf)')

        if listPdfFiles[0]!=[]:
            for i in listPdfFiles[0]:
                checkEncryption(i)
                if trueFalse==False:
                    self.listWidget.addItem(i.split('/')[-1])
                    self.mainPDFDictionary[i.split('/')[-1]]=i

    def extractFromFolder(self):
        pdfInsideFolderListPath = QtWidgets.QFileDialog.getExistingDirectory(None,'Select folder which contains PDF','/')

        if pdfInsideFolderListPath!='':
            for i in os.listdir(pdfInsideFolderListPath):
                if i.endswith('.pdf'):
                    checkEncryption(pdfInsideFolderListPath+'/'+str(i))
                    if trueFalse==False:
                        self.listWidget.addItem(str(i))
                        self.mainPDFDictionary[str(i)]=pdfInsideFolderListPath+'/'+str(i)

    def transferFile(self,e):
        try:
            transferFileName = self.listWidget.currentIndex().data()
            curr_selected=self.listWidget.currentRow()
            self.listWidget.takeItem(curr_selected)

            self.listWidget_2.addItem(transferFileName)
            self.mergePDFDictionary[transferFileName]=self.mainPDFDictionary.pop(transferFileName)
        except KeyError:
            pass

    def reverseTransferFile(self,e):
        try:
            transferFileName = self.listWidget_2.currentIndex().data()
            curr_selected=self.listWidget_2.currentRow()
            self.listWidget_2.takeItem(curr_selected)

            self.listWidget.addItem(transferFileName)
            self.mainPDFDictionary[transferFileName]=self.mergePDFDictionary.pop(transferFileName)
        except KeyError:
            pass

    def mergePDFFile(self):
        try:
            if self.mergePDFDictionary!={}:
                saveFileName = QtWidgets.QFileDialog.getSaveFileName(None,'Save As','/','PDF (*.pdf)')
                if saveFileName[0]:
                    merger = PdfFileMerger()
                    [merger.append(self.mergePDFDictionary[i]) for i in self.mergePDFDictionary]
                    merger.write(saveFileName[0])
                    merger.close()

                    self.listWidget.clear()
                    self.listWidget_2.clear()
                    self.mainPDFDictionary={}
                    self.mergePDFDictionary={}
            else:
                QtWidgets.QMessageBox.information(None,'!-Error-!','Oops!, No files found to be merged.',QtWidgets.QMessageBox.StandardButton(1),QtWidgets.QMessageBox.StandardButton(1))
        except KeyError:
            pass

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())


import logging
import re
from decimal import Decimal
from queue import Empty, Queue
from threading import Event as ThreadEvent
from typing import Optional

from .event import SilenceEvent
from .stream import StreamListenerHandler

logger = logging.getLogger(__name__)

SILENCE_DETECT_RE = re.compile(
    r"\[silencedetect.*\] silence_(start|end): (\d+(?:\.\d+)?)(?: \| silence_duration: (\d+\.\d+))?"
)

# https://ffmpeg.org/ffmpeg-filters.html#silencedetect
DEFAULT_SILENCE_DETECT_RAW: str = "silencedetect=noise={noise}:d={duration}"
DEFAULT_SILENCE_DETECT_NOISE: str = "-60dB"
# https://ffmpeg.org/ffmpeg-utils.html#time-duration-syntax
DEFAULT_SILENCE_DETECT_DURATION: str = "2.0"

def parse_silence_detect(line: str) -> Optional[SilenceEvent]:
    line = line.strip()
    match = SILENCE_DETECT_RE.search(line)
    if match is None:
        return None

    logger.debug(line)

    return SilenceEvent(
        kind=match.group(1),  # type: ignore[arg-type]
        seconds=Decimal(match.group(2)),
        duration=Decimal(match.group(3)) if match.group(3) else None,
    )

# pylint: disable=too-few-public-methods
class SilenceHandler(StreamListenerHandler):
    name = "silence_handler"
    stop: ThreadEvent
    queue: Queue

    event_queue: Queue

    noise: str
    duration: str
    raw: str

    # pylint: disable=too-many-arguments
    def __init__(
        self,
        stop: ThreadEvent,
        event_queue: Queue,
        noise: str = DEFAULT_SILENCE_DETECT_NOISE,
        duration: str = DEFAULT_SILENCE_DETECT_DURATION,
        raw: str = DEFAULT_SILENCE_DETECT_RAW,
    ):
        super().__init__()
        self.stop = stop
        self.queue = Queue()

        self.event_queue = event_queue
        self.noise = noise
        self.duration = duration
        self.raw = raw

    def ffmpeg_output(self):
        return [
            *("-af", self.raw.format(noise=self.noise, duration=self.duration)),
            *("-f", "null", "/dev/null"),
        ]

    def run(self):
        logger.info("starting %s", self.name)

        # pylint: disable=duplicate-code
        while not self.stop.is_set() or not self.queue.empty():
            try:
                line = self.queue.get(timeout=1.0)
            except Empty:
                continue

            event = parse_silence_detect(line)
            if event is not None:
                logger.info(f"silence {event.kind}: {event.when}")
                self.event_queue.put(event)

            self.queue.task_done()

        logger.info("%s stopped", self.name)


import os

from sqlalchemy import text

from application import db

class Topic(db.Model):
    __tablename__ = "topic"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100))
    created = db.Column(db.DateTime, default=db.func.current_timestamp())

    account_id = db.Column(db.Integer, db.ForeignKey('account.id'), nullable=False)
    account = db.relationship("User", back_populates="topics", lazy=True)

    area_id = db.Column(db.Integer, db.ForeignKey('area.id'), nullable=False)
    area = db.relationship("Area", back_populates="topics", lazy=True)

    messages = db.relationship("Message", back_populates='topic', lazy=True)

    def __init__(self, name, area_id):
        self.name = name
        self.area_id = area_id

    def last_post(self):
        return self.messages[-1]

    def last_post_by(self):
        return self.last_post().account.name

    def last_post_created(self):
        return self.last_post().created

    @staticmethod
    def find_topic_count():
        stmt = text("SELECT COUNT(*) as c FROM topic LIMIT 1")
        res = db.engine.execute(stmt)
        for row in res:
            return row[0]

    @staticmethod
    def find_hot_topic():
        stmt = None
        if os.environ.get("HEROKU"):
            stmt = text("SELECT topic.name, COUNT(*) as c FROM message"
                        " JOIN topic on message.topic_id = topic.id"
                        " WHERE message.created > now() - INTERVAL '1 WEEK'"
                        " GROUP BY topic.id"
                        " ORDER BY c DESC"
                        " LIMIT 1"
                        )

        else:
            stmt = text("SELECT topic.name, COUNT(*) as c FROM message"
                        " JOIN topic on message.topic_id = topic.id"
                        " WHERE message.created > datetime('now', '-7 day')"
                        " GROUP BY topic.id"
                        " ORDER BY c DESC"
                        " LIMIT 1"
                        )
        res = db.engine.execute(stmt)
        for row in res:
            return row[0]


from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from django.shortcuts import render
from django.http import Http404
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from el_pagination.views import AjaxListView
from django.contrib.auth.decorators import login_required, user_passes_test

from .models import News
from .forms import NewsForm

def index(request):
    context = {'news_list_1': News.objects.order_by('-pub_date')[1:3],
               'news_list_2': News.objects.order_by('-pub_date')[3:5],
    		   'main_news': News.objects.order_by('-pub_date')[0]}
    return render(request, 'home/index.html', context)

def news_feed(request,
    template='home/news-feed-list.html',
    page_template='home/news-feed-page.html'):
    context = {
        'news_list': News.objects.order_by('-pub_date'),
        'page_template': page_template,
    }
    if request.is_ajax():
        template = page_template
    return render(request, template, context)

def news(request):
    id_parameter = request.GET['id']
    context = {'news': News.objects.filter(id=id_parameter)[0]}
    return render(request, 'home/news.html', context)

@login_required
@user_passes_test(lambda u: u.groups.filter(name='CASD').count() == 1, login_url='/')
def news_manager(request):
    context = {
        'news_list': News.objects.order_by('-pub_date')
    }
    return render(request, 'home/manager/news-manager.html', context)

def news_create(request):
    form = NewsForm(request.POST or None)

    if form.is_valid():
        form.save()
    else:
        form = NewsForm()

    context = {
        'form': form,
    }
    return render(request, 'home/manager/news-add.html', context)

def news_remove(request, pk):
    news = get_object_or_404(News, pk=pk)
    news.delete()

    context = {
        'news_list': News.objects.order_by('-pub_date')
    }
    return render(request, 'home/manager/news-manager.html', context)

def news_update(request, pk):
    news = get_object_or_404(News, pk=pk)
    if request.method == 'POST':
        form = NewsForm(request.POST, instance=news)
        if form.is_valid():
            form.save()
    else:
        form = NewsForm(instance=news)

    context = {
        'form': form,
        'news': news,
    }
    return render(request, 'home/manager/news-edit.html', context)


import operator

def parse(expr:str):
    n1, sign, n2 = expr.split()
    ops = {
        "+": operator.add,
        "-": operator.sub,
        "*": operator.mul,
        "/": operator.truediv,
        "^": operator.pow,
    }
    op = ops[sign]
    return op, float(n1), float(n2)


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

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('migrator', '0009_auto_20150701_1432'),
    ]

    operations = [
        migrations.AlterField(
            model_name='migration',
            name='creation_date',
            field=models.DateTimeField(verbose_name='Created Date', auto_now_add=True),
        ),
    ]


import sys
sys.path.append('../')
from ex05.mylinearregression import MyLinearRegression as MyLR
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

def add_polynomial_features(x, power):
    try:
        if type(x) != np.ndarray or x.shape[1] != 1 or not isinstance(power, (int, float)):
            return None
        return np.vander(x.reshape(-1), power + 1 , increasing=True)[:,1:]
    except:
        return None

def perform_regression(X, Y, theta):
    myLR =  MyLR(theta, alpha = 1.5e-10, max_iter = 1500000)
    y_pred = myLR.predict_(X)
    myLR.fit_(X, Y)
    y_pred = myLR.predict_(X)
    print(myLR.mse_(y_pred,Y))
    return y_pred

def output_graph(x, y, y_preds):
    plt.scatter(x, y, label="Pills Score")
    for i, y_pred in zip(range(len(y_preds)), y_preds):
        plt.plot(x, y_pred, label=f"degree{i + 1} polynomial expression")
    plt.xlabel("Micrograms")
    plt.ylabel("Scores")
    plt.grid()
    plt.legend()
    plt.show()

def polynomial_regression(data):
    XMicrograms = np.array(data[["Micrograms"]])[:,0].reshape(-1,1)
    Y = np.array(data[["Score"]])[:,0].reshape(-1,1)
    y_preds = []
    for i in range(1, 7):
        poly_X = add_polynomial_features(XMicrograms, i)
        theta = np.ones((poly_X.shape[1] + 1, 1)).reshape(-1, 1)
        if i == 1:
            theta = np.array([[88.67822162],[-8.92106849]]).reshape(-1,1)
        elif i == 2:
            theta = np.array([[65.92627185],[ 3.63987692],[-1.47092799]]).reshape(-1, 1)
        elif i == 3:
          theta = np.array([[ 52.01405471], [ 33.19711719], [-12.9595629 ], [  1.15407571]]).reshape(-1, 1)
        if i == 4:
            theta = np.array([[-20],[ 160],[ -80],[ 10],[ -1]]).reshape(-1,1)
        elif i == 5:
            theta = np.array([[1140],[ -1850],[ 1110],[ -305],[ 40],[ -2]]).reshape(-1,1)
        elif i == 6:
            theta = np.array([[9110],[ -18015],[ 13400],[ -4935],[ 966],[ -96.4],[ 3.86]]).reshape(-1,1)
        y_preds.append(perform_regression(poly_X, Y, theta))
    output_graph(XMicrograms, Y, y_preds)

def main():
    data = pd.read_csv("are_blue_pills_magics.csv")
    polynomial_regression(data)
    return

if __name__ == "__main__":
    main()


from distutils.core import setup
import os

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(
    name="apns-python",
    packages=["apns_python"],
    version="0.1.2",
    description="A Python client for Apple Push Notification service(APNs)",
    author="Ping",
    author_email="yuanta11@gmail.com",
    url="https://github.com/mr-ping/apns-python",
    download_url="https://github.com/mr-ping/apns-python/archive/master.zip",
    keywords=["apns", "python", "python2", "http2", "http2.0"],
    install_requires=["hyper", "ujson"],
    classifiers=[
        "Programming Language :: Python",
        "Programming Language :: Python :: 2",
        "Development Status :: 4 - Beta",
        "Environment :: Other Environment",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
        "Topic :: Software Development :: Libraries :: Python Modules",
        ],
    long_description=read('README.md'),
)


import json

import cv2
import numpy as np
import pandas as pd
from pathlib import Path
import matplotlib.pyplot as plt

class HeatMap:
    def __init__(self, plates_path):
        self.plates_path = Path(plates_path)

    def get_max_plate_shape(self):
        plate_shapes_y = []
        plate_shapes_x = []
        for folder_path in self.plates_path.iterdir():
            with open(str(folder_path / 'plate_info.json'), 'r') as f:
                plate_info = json.load(f)
            plate_shape = [int(plate_info['info']['plate_info']['plate_shape'][0] -
                               plate_info['info']['plate_info']['margin_boundaries']['upper_boundary'] -
                               plate_info['info']['plate_info']['margin_boundaries']['bottom_boundaries']),
                           int(plate_info['info']['plate_info']['plate_shape'][1] -
                               plate_info['info']['plate_info']['margin_boundaries']['left_boundary'] -
                               plate_info['info']['plate_info']['margin_boundaries']['right_boundary'])]
            plate_shapes_y.append(plate_shape[0])
            plate_shapes_x.append(plate_shape[1])
        return [max(plate_shapes_y), max(plate_shapes_x)]

    @staticmethod
    def get_plate_info(df, plate_number):
        results_dict = {}
        temp_dict = {}
        for _, row in df.iterrows():
            temp_dict[row['crop_id_plate']] = {'x1': row['bounding_box_x'], 'y1': row['bounding_box_y'],
                                               'w': row['defect_width'], 'h': row['defect_height'],
                                               'area': row['defect_width'] * row['defect_height'],
                                               'defect': row['is_defect'], 'type': row['defect_type'],
                                               'b_nb': row['buffer_number'], 'c_nb': row['crop_id_buffer']}
        results_dict[plate_number] = temp_dict
        return results_dict

    @staticmethod
    def draw_defects_per_plate(info_plate, temp):
        for plate_number, val in info_plate.items():
            for id in val.keys():
                x1 = info_plate[plate_number][id]['x1']
                x2 = x1 + info_plate[plate_number][id]['w']
                y1 = info_plate[plate_number][id]['y1']
                y2 = y1 + info_plate[plate_number][id]['h']
                temp = cv2.rectangle(temp, (x1, y1), (x2, y2), 1, -1)
        return temp

    def _sum_defects_of_plates(self, path_list, background):
        drawn_defects = background.copy()
        temp = background.copy()
        for folder_path in path_list:
            defects = pd.read_csv(folder_path / 'defects_in_plate.csv')
            plate_info = self.get_plate_info(defects, folder_path.name)
            print(folder_path.name)
            temp = self.draw_defects_per_plate(plate_info, temp)
            drawn_defects = drawn_defects + temp
        return drawn_defects

    def draw_plate_defects(self, max_shape):
        background = np.zeros(max_shape, dtype='int32')
        path_list = [p for p in self.plates_path.iterdir()]
        results = self._sum_defects_of_plates(path_list, background)
        return results

    @staticmethod
    def draw_heatmap(plates_defects):
        plt.imshow(plates_defects * 1000, cmap='YlOrRd', interpolation='bilinear')
        plt.axis('off')
        plt.show()

if __name__ == '__main__':
    run_path = '/home/schneian/data/fis_knb/08sep20/daimler-mfa-2-brush-3w177-0001-2b45'
    heatmap = HeatMap(run_path)
    shape = heatmap.get_max_plate_shape()
    plates_sum = heatmap.draw_plate_defects(shape)
    heatmap.draw_heatmap(plates_sum)


import configparser
from collections import OrderedDict
import numpy as np
from scipy.integrate import quad
import os
import sys
import io
import re

UNITS = OrderedDict()
UNITS['T'] = 'K'                    # temperature
UNITS['Cv'] = 'kB'                  # heat capacity in kB
UNITS['Kappa_min'] = 'W/(m*K)'      # minimum limit kappa under tau=pi/omega
UNITS['Kappa_min_A'] = 'W/(m*K)'    # contribution of acoustic branches
UNITS['Kappa_min_O'] = 'W/(m*K)'    # contribution of optical branches
UNITS['vs'] = 'km/s'                # average sound velocity, vs = (3/(2/vT**3+1/vL**3))**(1/3)
UNITS['Tau_min'] = 'ps'             # Kappa_min/(1/3*Cv*vs^2)
UNITS['MFP_min'] = 'A'              # Kappa_min/(1/3*Cv*vs)
UNITS['Omega_a_T'] = 'rad/ps'       # Cut-off angular frequency of TA
UNITS['Omega_a_L'] = 'rad/ps'       # Cut-off angular frequency of LA
UNITS['T_a_T'] = 'K'                # Debye temperature of TA
UNITS['T_a_L'] = 'K'                # Debye temperature of LA

def _kernel(x):
    '''
    x^2*exp(x)/(exp(x)-1)^2
    '''
    p = np.power(x, 2) * np.exp(-x)
    q = np.power(1-np.exp(-x), 2)
    v = np.divide(p, q,
                  out=np.ones_like(p+q),
                  where=(np.absolute(q)>1E-4))
    return v

def _core_cv(x):
    '''
    3*t^2
    '''
    v = 3 * x**2
    return v

def _core_debye(x):
    '''
    3*t
    '''
    v = 3 * x
    return v

def _core_bvk(x):
    '''
    3 * x^2 * (cos(pi/2 * x))^2 / sin(pi/2 * t)
    '''
    p = 3 * x**2 * np.cos(np.pi/2 * x)**2
    q = np.sin(np.pi/2 * x)
    v = np.divide(p, q,
                  out=np.zeros_like(p+q),
                  where=(np.absolute(q)>1E-4))
    return v

def _quad_t(func, Tr):
    '''
    Calculate integral in reduced k-space with an additional parameter
    '''
    def itg(Trx):
        return quad(func, 0, 1, args=(Trx,))[0]
    itg_v = np.vectorize(itg)
    return itg_v(Tr)

def Debye(vT, vL, Natom, Vcell, T):
    '''
    Calculate Debye-Cahill minimum limit to thermal conductivity.
    All  parameters in common units.
    '''

    # define constants for matching common units
    kB = 13.80649
    hb = 105.457182

    # define some factors and integrals
    Vatom = Vcell/Natom     # [A^3]
    Kc = np.power(6*np.pi*np.pi/Vatom, 1/3)  # [1/A]
    WcT = vT * Kc * 10       # [km/s * 1/A] = [10 rad/ps] to [rad/ps]
    WcL = vL * Kc * 10
    TaT = hb/kB * WcT   # [K]
    TaL = hb/kB * WcL
    vs = (3/(2/vT**3+1/vL**3))**(1/3)
    factor_cv = 3       # [kB]
    factor_kmT = (kB*vT*vT)/Vatom * np.pi/WcT  # [W/m.K]
    factor_kmL = (kB*vL*vL)/Vatom * np.pi/WcL
    # factor_tmT = np.pi/WcT      # [ps]
    # factor_tmL = np.pi/WcL
    # factor_mfp = np.pi/Kc       # [A]

    # calculate
    out = dict()
    if isinstance(T, float) and (T == float('inf')):
        # kernel --> 1
        # factor_itg = quad(_core_debye, 0, 1)[0]
        factor_itg = 3/2
        out['T'] = T
        out['Cv'] = factor_cv
        out['Kappa_min'] = (2*factor_kmT+factor_kmL)/3 * factor_itg
        out['Omega_a_T'] = WcT
        out['Omega_a_L'] = WcL
        out['T_a_T'] = TaT
        out['T_a_L'] = TaL
        out['vs'] = vs
    else:
        T = np.array(T)
        f_cv = lambda t, u: _core_cv(t)*_kernel(u*t)
        f_km = lambda t, u: _core_debye(t)*_kernel(u*t)
        CrT = _quad_t(f_cv, TaT/T)
        CrL = _quad_t(f_cv, TaL/T)
        KMrT = _quad_t(f_km, TaT/T)
        KMrL = _quad_t(f_km, TaL/T)
        out['T'] = T
        out['Cv'] = factor_cv * (2*CrT+CrL)/3
        out['Kappa_min'] = (2*factor_kmT*KMrT+factor_kmL*KMrL)/3
        out['Omega_a_T'] = WcT*np.ones_like(T)
        out['Omega_a_L'] = WcL*np.ones_like(T)
        out['T_a_T'] = TaT*np.ones_like(T)
        out['T_a_L'] = TaL*np.ones_like(T)
        out['vs'] = vs*np.ones_like(T)

    out['Kappa_min_A'] = out['Kappa_min']
    out['Kappa_min_O'] = 0 * out['Kappa_min']
    out['Tau_min'] = out['Kappa_min']/(1/3 * out['Cv']*kB/Vatom * out['vs']**2)     # [ps]
    out['MFP_min'] = out['Tau_min'] * out['vs'] * 10 # [ps*km/s] = [ps*nm/ps] = [nm] to [A]
    return out

def BvK(vT, vL, Natom, Vcell, T):
    '''
    Calculate BvK-Cahill minimum limit to thermal conductivity.
    All  parameters in common units.
    '''

    # define constants for matching common units
    kB = 13.80649
    hb = 105.457182

    # define some factors and integrals
    Vatom = Vcell/Natom     # [A^3]
    Kc = np.power(6*np.pi*np.pi/Vatom, 1/3)  # [1/A]
    WcT = 2/np.pi * vT * Kc * 10    # [km/s * 1/A] = [10 rad/ps] to [rad/ps]
    WcL = 2/np.pi * vL * Kc * 10
    TaT = hb/kB * WcT   # [K]
    TaL = hb/kB * WcL
    factor_cv = 3       # [kB]
    vs = (3/(2/vT**3+1/vL**3))**(1/3)
    factor_kmT = (kB*vT*vT)/Vatom * np.pi/WcT  # [W/m.K]
    factor_kmL = (kB*vL*vL)/Vatom * np.pi/WcL
    # factor_tmT = np.pi/WcT      # [ps]
    # factor_tmL = np.pi/WcL
    # factor_mfp = (np.pi/Kc) * np.pi/2   # [A]

    # calculate
    out = dict()
    if isinstance(T, float) and (T == float('inf')):
        # kernel --> 1
        # factor_itg = quad(_core_bvk, 0, 1)[0]
        factor_itg = 0.31456063126172384
        out['T'] = T
        out['Cv'] = factor_cv
        out['Kappa_min'] = (2*factor_kmT+factor_kmL)/3 * factor_itg
        out['Omega_a_T'] = WcT
        out['Omega_a_L'] = WcL
        out['T_a_T'] = TaT
        out['T_a_L'] = TaL
        out['vs'] = vs
    else:
        T = np.array(T)
        f_cv = lambda t, u: _core_cv(t)*_kernel(u*np.sin(np.pi/2 * t))
        f_km = lambda t, u: _core_bvk(t)*_kernel(u*np.sin(np.pi/2 * t))
        CrT = _quad_t(f_cv, TaT/T)
        CrL = _quad_t(f_cv, TaL/T)
        KMrT = _quad_t(f_km, TaT/T)
        KMrL = _quad_t(f_km, TaL/T)
        out['T'] = T
        out['Cv'] = factor_cv * (2*CrT+CrL)/3
        out['Kappa_min'] = (2*factor_kmT*KMrT+factor_kmL*KMrL)/3
        out['Omega_a_T'] = WcT*np.ones_like(T)
        out['Omega_a_L'] = WcL*np.ones_like(T)
        out['T_a_T'] = TaT*np.ones_like(T)
        out['T_a_L'] = TaL*np.ones_like(T)
        out['vs'] = vs*np.ones_like(T)

    out['Kappa_min_A'] = out['Kappa_min']
    out['Kappa_min_O'] = 0 * out['Kappa_min']
    out['Tau_min'] = out['Kappa_min']/(1/3 * out['Cv']*kB/Vatom * out['vs']**2)     # [ps]
    out['MFP_min'] = out['Tau_min'] * out['vs'] * 10 # [ps*km/s] = [ps*nm/ps] = [nm] to [A]
    return out

def Pei(vT, vL, Natom, Vcell, T):
    '''
    Calculate Pei-Cahill minimum limit to thermal conductivity.
    All  parameters in common units.
    '''

    vs = (3/(2/vT**3+1/vL**3))**(1/3)
    out = BvK(vT=vs,
              vL=vs,
              Natom=1,
              Vcell=Vcell,
              T=T)

    # same as BvK model when Natom = 1
    if Natom == 1:
        return out
    # else:
    #     raise NotImplementedError('Only support Natom = 1')

    # for Natom != 1
    # define constants for matching common units
    kB = 13.80649
    hb = 105.457182

    # define some factors and integrals
    Vatom = Vcell/Natom     # [A^3]
    Kc = np.power(6*np.pi*np.pi/Vatom, 1/3)  # [1/A], Kc ~ Vatom, Kcc ~ Vcell
    Wc = 2/np.pi * vs * Kc * 10     # [km/s * 1/A] = [10 rad/ps] to [rad/ps]
    To = hb/kB * Wc     # [K]
    factor_cv = 3       # [kB]
    factor_km = (kB*vs*vs)/Vcell * np.pi/Wc  # [W/m.K], here Vcell=Natom*Natom
    # factor_tm = np.pi/Wc      # [ps]
    # factor_mfp = (np.pi/Kc) * np.pi/2   # [A]

    # calculate
    kir = [(np.power(i/Natom, 1/3)+np.power((i+1)/Natom, 1/3))/2 for i in range(1,round(Natom))]
    if isinstance(T, float) and (T == float('inf')):
        kir = np.array(kir)
        wr = np.sin(np.pi/2 * kir)
        vr = np.cos(np.pi/2 * kir)
        km_O = factor_km * vr**2 / wr
        out['Kappa_min_O'] = np.sum(km_O)
        out['Kappa_min'] = out['Kappa_min_A'] + out['Kappa_min_O']
    else:
        T = out['T']
        shp = [-1,]+[1 for _ in range(T.ndim)]
        kir = np.array(kir).reshape(shp)
        wr = np.sin(np.pi/2 * kir)
        vr = np.cos(np.pi/2 * kir)
        km_O = factor_km * vr**2 / wr * _kernel(To/T*wr)
        cv_O = factor_cv * _kernel(To/T*wr)
        out['Kappa_min_O'] = np.sum(km_O, axis=0)
        out['Kappa_min'] = out['Kappa_min_A'] + out['Kappa_min_O']
        out['Cv'] = (out['Cv']+np.sum(cv_O, axis=0))/Natom

    out['Tau_min'] = out['Kappa_min']/(1/3 * out['Cv']*kB/Vatom * out['vs']**2)     # [ps]
    out['MFP_min'] = out['Tau_min'] * out['vs'] * 10 # [ps*km/s] = [ps*nm/ps] = [nm] to [A]
    return out

def fileparser(filename, ktypes=None):
    '''
    Parser the configuration file and return a ConfigParser() object.
    '''
    # read config file
    config = configparser.ConfigParser(inline_comment_prefixes=('#',))
    config.SECTCRE = re.compile(r"\[ *(?P<header>[^]]+?) *\]")  # ignore blanks in section name
    config.read(filename)

    # optional: refine config file
    if ktypes is None:
        return config
    else:
        config2 = configparser.ConfigParser()
        for sect in config.sections():
            for ktype in ktypes:
                if sect.lower() == ktype.lower():
                    config2[ktype] = config[sect]
        return config2

def _section_parser(config, modeltype):
    '''
    Parser parameters from a specific model-section.
    '''

    # TODO: config = fileparser(config) if is string else config
    # keys = ['vT', 'vL', 'Natom', 'Vcell', 'T']

    paras = dict()

    # parser float
    for key in ['vT', 'vL', 'Natom', 'Vcell']:
        paras[key] = config.getfloat(modeltype, key)

    # parser temperature
    valueT = config[modeltype]['T']
    isStep, valueT = _sequence_parser(valueT, func=float, defaultstep=1)
    if isStep:
        start, step, end = valueT
        valueT = np.arange(start, end+0.01, step)

    # check type and return
    if len(valueT) == 0:
        raise ValueError('Failed to read temperature [T].')
    elif len(valueT) == 1:
        isSingle = True
        paras['T'] = valueT[0]
    else:
        isSingle = False
        paras['T'] = valueT
    return isSingle, paras

def _sequence_parser(value, func=float, defaultstep=1):
    '''
    Parser a sequence or slice from a string.
    '''

    if ':' in value:
        # sequence with step
        values = value.strip().split(':')
        if func is not None:
            values = list(map(func, values))
        if len(values) == 2:
            start, end = values
            step = defaultstep
        elif len(values) == 3:
            start, step, end = values
        else:
            raise ValueError('Failed to parser the sequence data.')
        isStep = True
        return isStep, (start, step, end)
    else:
        # any sequence
        values = value.strip().split()
        if func is not None:
            values = map(func, values)
        isStep = False
        return isStep, list(values)

def _savedat_to_file(filename, datas, keys=None,
                     fmt='%.6f', header='auto',
                     isSingle=None):
    '''
    Save output of model calculation to a file.
    Default header(='auto') is Properties & Units, while is ignored if it is None.
    '''

    # TODO: fix isSingle check bug if datas['Kappa_min'] not a ndarray

    # check default
    if keys is None:
        keys = UNITS.keys()
    if isSingle is None:
        if datas['Kappa_min'].ndim == 0:
            isSingle = True
        else:
            isSingle = False
    if header.lower().startswith('auto'):
        props = []
        units = []
        for prop in keys:
            unit = UNITS[prop]
            Nmax = max(map(len, [prop, unit]))
            props.append(prop.rjust(Nmax))
            units.append(unit.rjust(Nmax))
        propsline = ', '.join(props)
        unitsline = ', '.join(units)
        header = '\n'.join([propsline, unitsline])

    # access output datas
    out = [datas[key] for key in keys]
    if isSingle:
        out = np.atleast_2d(out)
    else:
        out = np.vstack(out).T
    s = io.StringIO()
    np.savetxt(s, out, fmt=fmt, header=header)
    rst = s.getvalue().replace('\ninf', '\ninf       ')
    with open(filename, 'w') as f:
        f.write(rst)

def execute(filename=None, toFile=True, hasReturn=False):
    '''
    Read configuration file and do calculation.
    '''

    # TODO: allow muilt-output result when muilt-model

    # access filename of config
    ktypes = ['Debye', 'BvK', 'Pei']
    if filename is None:
        # auto-detect filename
        prefix = 'KAPPAMIN'
        suffix = ['cfg', 'ini', 'txt']
        for fn in ['{}.{}'.format(prefix, suf) for suf in suffix]:
            if os.path.exists(fn):
                filename = fn
                break
        else:
            raise FileNotFoundError('Failed to find configuration file')
    config = fileparser(filename, ktypes)

    # parser config file and calculate
    if 'Debye' in config.sections():
        fileout = 'Kappamin_Debye.dat'
        isSingle, paras = _section_parser(config, 'Debye')
        out = Debye(**paras)
    elif 'BvK' in config.sections():
        fileout = 'Kappamin_BvK.dat'
        isSingle, paras = _section_parser(config, 'BvK')
        out = BvK(**paras)
    elif 'Pei' in config.sections():
        fileout = 'Kappamin_Pei.dat'
        isSingle, paras = _section_parser(config, 'Pei')
        out = Pei(**paras)
    else:
        raise ValueError('Unknown method.(Valid: %s)', ', '.join(ktypes))

    # output and(or) save to file
    if hasReturn:
        return out
    if toFile:
        _savedat_to_file(fileout, out, isSingle=isSingle)

if __name__ == '__main__':
    if len(sys.argv) > 1:
        filename = sys.argv[1]
    else:
        filename = None
    execute(filename)


# House Robber II [Medium]
# https://leetcode.com/problems/house-robber-ii/

# Solution1
# [idea]
# If rob house[0] then cannot rob house[n - 1].
# Choose either house[0] or house[n-1] then it becomes 'House Robber I'.

# [code]
class Solution:
    def rob(self, nums: List[int]) -> int:
        return max(nums[0], self.house_robber_1(nums[:-1]), self.house_robber_1(nums[1:])) # edge case when len(nums) = 1 -> nums[0]

    def house_robber_1(self, nums: List[int]) -> int:
        rob1, rob2 = 0, 0

        for num in nums:
            tmp = max(num + rob1, rob2)
            rob1 = rob2
            rob2 = tmp

        return rob2

# time complexity : O(n)
# space complexity : O(1)


import os
import json
import shutil
import numpy as np
from jobmanager.psi4_utils.run import run_general_hfx

psi4_config = {'bashrc': '/home/crduan/.bashrc',
               'conda_env': '/home/crduan/miniconda/envs/mols_py36'}
with open("psi4_config.json", "r") as f:
    psi4_config.update(json.load(f))
alphalist = [20, 15, 10, 5, 2]
rescued = 0
success_count = 0
basedir = os.getcwd()
for ii, functional in enumerate(psi4_config["functional"]):
    failed = False
    print("===%d: %s===" % (ii, functional))
    with open(functional + "/output.dat", "r") as fo:
        txt = "".join(fo.readlines())
    if 'PsiException: Could not converge SCF iterations' in txt or txt == "":
        success = False
        e_dict = {}
        e0 = np.nan
        for jj, alpha in enumerate(alphalist):
            print(alpha)
            if jj == 0:
                wfn = "../b3lyp/wfn.180.npy"
                wfn_b = "b3lyp/wfn.180.npy"
            else:
                wfn = "../%s/wfn.180.npy" % (functional + "-%d" %
                                             alphalist[jj-1])
                wfn_b = "%s/wfn.180.npy" % (functional + "-%d" %
                                            alphalist[jj-1])
            if not os.path.isdir(functional + "-%d" % alpha) and not failed:
                os.makedirs(functional + "-%d" % alpha)
                shutil.copyfile(psi4_config['xyzfile'], functional + "-%d" %
                                alpha + '/' + psi4_config['xyzfile'])
                success = run_general_hfx(psi4_config, functional, hfx=alpha, wfn=wfn)
                print("success: ", success)
                if success:
                    success_count += 1
                else:
                    failed = True
            else:
                print("attempted rescue: ", functional)
                resubed = False
                if not os.path.isfile(functional + "-%d" % alpha + "/output.dat"):
                    resubed = True
                else:
                    with open(functional + "-%d" % alpha + "/output.dat", "r") as fo:
                        txt = "".join(fo.readlines())
                    if "==> Iterations <==" not in txt:
                        resubed = True
                if resubed and os.path.isfile(wfn_b):
                    print("previously errored out. resubmitting...")
                    success = run_general_hfx(psi4_config, functional, hfx=alpha, wfn=wfn)
                    print("success: ", success)
                    if success:
                        success_count += 1
                    else:
                        failed = True
                elif ('PsiException: Could not converge SCF iterations') not in txt and (not os.path.isfile(functional + "-%d" % alpha + "/wfn.180.npy")):
                    _functional = functional + "-%d" % alpha
                    if not os.path.isfile(_functional + "/output-timeout.dat"):
                        shutil.copy(_functional + "/output.dat",
                                    _functional + "/output-timeout.dat")
                        print("Time out, direct resub...")
                        success = run_general_hfx(psi4_config, functional, hfx=alpha, wfn=wfn)
                        print("success: ", success)
                        if success:
                            success_count += 1
                        else:
                            failed = True
                    else:
                        failed = True
                        print("Already submit once for timeout.")
                else:
                    print("give up resubmission.")
        if not failed:
            rescued += 1
            print("rescued: ", functional)
    else:
        rescued += 1
        print("%s has already succeeded!" % functional)
print("all finished!")


# Method-1

def isHappy(n):
    visit = set()

    while n not in visit:
        visit.add(n)
        n = sumOfSquare(n)

        if n == 1:
            return True

    return False

def sumOfSquare(n):
    result = 0

    while n:
        result += (n % 10) ** 2
        n //= 10

    return result

# Time Complexity : O(nlogn)
# Space Complexity : O(n)


primeiroDigito = int(input("Digite o primeiro dígito do seu CPF: "))
segundoDigito = int(input("Digite o segundo dígito do seu CPF: "))
terceiroDigito = int(input("Digite o terceiro dígito do seu CPF: "))
quartoDigito = int(input("Digite o quarto dígito do seu CPF: "))
quintoDigito = int(input("Digite o quinto dígito do seu CPF: "))
sextoDigito = int(input("Digite o sexto dígito do seu CPF: "))
setimoDigito = int(input("Digite o sétimo dígito do seu CPF: "))
oitavoDigito = int(input("Digite o oitavo dígito do seu CPF: "))
nonoDigito = int(input("Digite o nono dígito do seu CPF: "))
decimoDigito = int(input("Digite o décimo dígito do seu CPF: "))
decimoPrimeiroDigito = int(
    input("Digite o décimo primeiro dígito do seu CPF: "))

# PRIMEIRO DÍGITO VERIFICADOR

"""
Calculando a soma da multiplicação dos 9 primeiros dígitos, respectivamente,
por 10, 9, 8, ..., 3, 2:
"""

soma1 = (primeiroDigito * 10) + (segundoDigito * 9) + \
    (terceiroDigito * 8) + (quartoDigito * 7) + (quintoDigito * 6) \
    + (sextoDigito * 5) + (setimoDigito * 4) + (oitavoDigito * 3) \
    + (nonoDigito * 2)

# Calculando a divisão inteira e a multiplicação da soma por 11:
valor1 = (soma1 // 11) * 11

# Calculando a subtração de soma e do valor:
resultado1 = soma1 - valor1

if (resultado1 == 1 or resultado1 == 0):
    digito1 = 0
else:
    digito1 = (11 - resultado1)

# SEGUNDO DÍGITO VERIFICADOR:

"""
Calculando a soma da multiplicação dos 9 primeiros dígitos por 11, 10, 9, ... ,
4, 3, respectivamente, e, em seguida, calculamos a soma com (Digito1*2), sendo
que Digito1 é o valor encontrado para o 1º dígito verificador:
"""

soma2 = ((primeiroDigito * 11) + (segundoDigito * 10) +
         (terceiroDigito * 9) + (quartoDigito * 8) + (quintoDigito * 7)
         + (sextoDigito * 6) + (setimoDigito * 5) + (oitavoDigito * 4)
         + (nonoDigito * 3)) + (digito1 * 2)

# Calculando a divisão inteira e a multiplicação da soma por 11:
valor2 = (soma2 // 11) * 11

# Calculando a subtração de soma e do valor:
resultado2 = soma2 - valor2

if (resultado2 == 1 or resultado2 == 0):
    digito2 = 0
else:
    digito2 = (11 - resultado2)

if (digito1 == decimoDigito and digito2 == decimoPrimeiroDigito):
    print("CPF válido!")
else:
    print("CPF inválido!")


#!/usr/bin/env python
import os
import re
from typing import Any, Dict

from setuptools import find_namespace_packages, setup

this_directory = os.path.abspath(os.path.dirname(__file__))

with open(os.path.join(this_directory, "README.md"), encoding="utf-8") as f:
    long_description = f.read()

package_name = "dbt-athena-community"

# get version from a separate file
def _get_plugin_version_dict() -> Dict[str, Any]:
    _version_path = os.path.join(this_directory, "dbt", "adapters", "athena", "__version__.py")
    _semver = r"""(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)"""
    _pre = r"""((?P<prekind>a|b|rc)(?P<pre>\d+))?"""
    _version_pattern = rf"""version\s*=\s*["']{_semver}{_pre}["']"""
    with open(_version_path) as f:
        match = re.search(_version_pattern, f.read().strip())
        if match is None:
            raise ValueError(f"invalid version at {_version_path}")
        return match.groupdict()

def _get_package_version() -> str:
    parts = _get_plugin_version_dict()
    return f'{parts["major"]}.{parts["minor"]}.{parts["patch"]}'

dbt_version = "1.6"
package_version = _get_package_version()
description = "The athena adapter plugin for dbt (data build tool)"

if not package_version.startswith(dbt_version):
    raise ValueError(f"Invalid setup.py: package_version={package_version} must start with dbt_version={dbt_version}")

setup(
    name=package_name,
    version=package_version,
    description=description,
    long_description=long_description,
    long_description_content_type="text/markdown",
    platforms="any",
    license="Apache License 2.0",
    license_files=("LICENSE.txt",),
    url="https://github.com/dbt-athena/dbt-athena",
    packages=find_namespace_packages(include=["dbt", "dbt.*"]),
    include_package_data=True,
    install_requires=[
        # In order to control dbt-core version and package version
        "boto3~=1.26",
        "boto3-stubs[athena,glue,lakeformation,sts]~=1.26",
        "dbt-core~=1.6.0",
        "pyathena>=2.25,<4.0",
        "pydantic>=1.10,<3.0",
        "tenacity~=8.2",
    ],
    classifiers=[
        "Development Status :: 5 - Production/Stable",
        "License :: OSI Approved :: Apache Software License",
        "Operating System :: Microsoft :: Windows",
        "Operating System :: MacOS :: MacOS X",
        "Operating System :: POSIX :: Linux",
        "Programming Language :: Python :: 3.8",
        "Programming Language :: Python :: 3.9",
        "Programming Language :: Python :: 3.10",
        "Programming Language :: Python :: 3.11",
        "Programming Language :: Python :: 3.12",
    ],
    python_requires=">=3.8",
)


#!/opt/splunk/bin/python
"""
Description:

Source:

Instructions:

Rate Limit: None

Results Limit: None

Debugger: open("/tmp/splunk_script.txt", "a").write("{}: <MSG>\n".format(<VAR>))
"""

import os
import re
import sys

app_home   = "{}/etc/apps/OSweep".format(os.environ['SPLUNK_HOME'])
tp_modules = "{}/bin/_tp_modules".format(app_home)
sys.path.insert(0, tp_modules)
import validators

import commons

api = "https://{}/api/v2/search/{}".lower()

def process_iocs(results):
    """Return data formatted for Splunk from Hybrid-Analysis."""
    params = [
        'authentihash',
        'av_detect',
        'context',
        'country',
        'domain',
        'env_id',
        'filename',
        'filetype_desc',
        'filetype',
        'hash',
        'host',
        'imp_hash',
        'port',
        'similar_to',
        'ssdeep',
        'tag',
        'url',
        'verdict',
        'vx_family'
    ]

    if results != None:
        provided_iocs = [y for x in results for y in x.values()]
    elif sys.argv[1] == "terms" and sys.argv[2] in params:
        if len(sys.argv) > 2:
            endpoint = sys.argv[1]
            param = sys.argv[2]
            provided_iocs = sys.argv[3:]
    elif sys.argv[1] == "hash" and sys.argv[2] == "hash":
        if len(sys.argv) > 2:
            endpoint = sys.argv[1]
            param = sys.argv[2]
            provided_iocs = sys.argv[3:]

    session    = commons.create_session()
    api_domain = commons.get_apidomain("hybrid-analysis")
    api_key    = commons.get_apikey("hybrid-analysis")
    splunk_table = []

    for provided_ioc in set(provided_iocs):
        provided_ioc = commons.deobfuscate_string(provided_ioc)
        provided_ioc = provided_ioc.lower()

        ioc_dicts = query_hybridanalysis(endpoint, param, provided_ioc, api_domain, api_key, session)

        for ioc_dict in ioc_dicts:
            splunk_table.append(ioc_dict)

    session.close()
    return splunk_table

def query_hybridanalysis(endpoint, param, provided_ioc, api_domain, api_key, session):
    """ """
    ioc_dicts = []

    session.headers.update({
        "api-key":api_key,
        "Accept":"application/json",
        "User-Agent":"Falcon Sandbox"
    })
    resp = session.post(api.format(api_domain, endpoint), data={param:provided_ioc}, timeout=180)

    if resp.status_code == 200 and resp.content != '':
        results = resp.json()
    else:
        ioc_dicts.append({"no data": provided_ioc})
        return ioc_dicts

    if isinstance(results, dict):
        if "result" in results.keys() and len(results["result"]) > 0:
            results = results["result"]
        else:
            ioc_dicts.append({"no data": provided_ioc})
            return ioc_dicts

    for result in results:
        ioc_dict = {}
        ioc_dict["type"] = result.get("type", None)
        ioc_dict["target_url"] = result.get("target_url", None)
        ioc_dict["submit_name"] = result.get("submit_name", None)
        ioc_dict["md5"] = result.get("md5", None)
        ioc_dict["sha256"] = result.get("sha256", None)
        ioc_dict["ssdeep"] = result.get("ssdeep", None)
        ioc_dict["imphash"] = result.get("imphash", None)
        ioc_dict["av_detect"] = result.get("av_detect", None)
        ioc_dict["analysis_start_time"] = result.get("analysis_start_time", None)
        ioc_dict["threat_score"] = result.get("threat_score", None)
        ioc_dict["interesting"] = result.get("interesting", None)
        ioc_dict["threat_level"] = result.get("threat_level", None)
        ioc_dict["verdict"] = result.get("verdict", None)
        ioc_dict["domains"] = result.get("domains", None)
        if ioc_dict["domains"] != None:
            ioc_dict["domains"] = "\n".join(ioc_dict["domains"])
        ioc_dict["classification_tags"] = result.get("classification_tags", None)
        if ioc_dict["classification_tags"] != None:
            ioc_dict["classification_tags"] = "\n".join(ioc_dict["classification_tags"])
        ioc_dict["compromised_hosts"]   = result.get("compromised_hosts", None)
        if ioc_dict["compromised_hosts"] != None:
            ioc_dict["compromised_hosts"] = "\n".join(ioc_dict["compromised_hosts"])
        ioc_dict["hosts"] = result.get("hosts", None)
        if ioc_dict["hosts"] != None:
            ioc_dict["hosts"] = "\n".join(ioc_dict["hosts"])
        ioc_dict["total_network_connections"] = result.get("total_network_connections", None)
        ioc_dict["total_processes"] = result.get("total_processes", None)
        ioc_dict["extracted_files"] = result.get("extracted_files", None)
        if ioc_dict["extracted_files"] != None:
            ioc_dict["extracted_files"] = "\n".join(ioc_dict["extracted_files"])
        ioc_dict["processes"] = result.get("processes", None)
        if ioc_dict["processes"] != None:
            ioc_dict["processes"] = "\n".join(ioc_dict["processes"])
        ioc_dict["tags"] = result.get("tags", None)
        if ioc_dict["tags"] != None:
            ioc_dict["tags"] = "\n".join(ioc_dict["tags"])
        ioc_dicts.append(ioc_dict)
    return ioc_dicts

if __name__ == "__main__":
    current_module = sys.modules[__name__]
    commons.return_results(current_module)


#Kullanıcıdan aldığınız 3 tane sayıyı çarparak ekrana yazdırın. Ekrana yazdırma işlemini format metoduyla yapmaya çalışın.

sayi1 = int(input("1.sayiyi giriniz: "))
sayi2 = int(input("2.sayiyi giriniz: "))
sayi3 = int(input("3.sayiyi giriniz: "))

sayilar = [sayi1, sayi2, sayi3]
carpim = sayi1 * sayi2 * sayi3
print("Sayilarin carpimi: ", carpim)

#Kullanıcıdan aldığınız boy ve kilo değerlerine göre kullanıcının beden kitle indeksini bulun.
#Beden Kitle İndeksi : Kilo / Boy(m)*Boy(m)

boy=float(input("Boyunuzu giriniz(or:1.72) : "))
kilo=int(input("Kilonuzu giriniz: "))

bki=kilo/(boy*boy)

print("Beden Kitle Endeksiniz: ",bki)

#Bir aracın kilometrede ne kadar yaktığı ve kaç kilometre yol yaptığı bilgilerini alın ve sürücünü toplam ne kadar
#ödemesini gerektiğini hesaplayın.

kmbasiyakit=float(input("Araciniz km basi kac tl yakiyor? : "))
gidilenyol=float(input("Kac km yol gittiniz? : "))

odenecekmiktar=kmbasiyakit*gidilenyol

print("Odemeniz gereken miktar: ",odenecekmiktar)

#Kullanıcıdan ad,soyad ve numara bilgisini alarak bunları alt alta ekrana yazdırın.

ad=input("Adiniz:")
soyad=input("Soyadiniz:")
numara=input("Numaraniz:")
bilgiler=[ad,soyad,numara]

for i in bilgiler:
    print(i)

#Kullanıcıdan iki tane sayı isteyin ve bu sayıların değerlerini birbirleriyle değiştirin.

sayi1=int(input("1.sayiyi giriniz:"))
sayi2=int(input("2.sayiyi giriniz:"))

print("Sayi1 : {}\nSayi2 : {}\nSayilar degistiriliyor...".format(sayi1,sayi2))

sayi1=sayi1+sayi2
sayi2=sayi1-sayi2
sayi1=sayi1-sayi2

print("Sayi1 : {}\nSayi2 : {}\nSayilar degistirildi.".format(sayi1,sayi2))

#Kullanıcıdan bir dik üçgenin dik olan iki kenarını(a,b) alın ve hipotenüs uzunluğunu bulmaya çalışın.
#Hipotenüs Formülü: a^2 + b^2 = c^2
import math

kenar1=float(input("Dik ucgenin birinci dik kenarini giriniz: "))
kenar2=float(input("Dik ucgenin ikinci dik kenarini giriniz: "))

hipotenusunkaresi=(kenar1*kenar1)+(kenar2*kenar2)
hipotenus=math.sqrt(hipotenusunkaresi)

print("Kenar1:{}\nKenar2:{}\nHipotenus:{}".format(kenar1,kenar2,hipotenus))

Temel Veri Yapilari ve Objeler/bolum_sonu_odevleri.py


from __future__ import print_function
import numpy as np
from astropy.io import fits
import matplotlib.pyplot as plt
from math import sqrt, pi

w1sgk = fits.open('w1rot.fits')[0].data
w3sgk = fits.open('w3rot.fits')[0].data
w5sgk = fits.open('w5rot.fits')[0].data
rsgk = fits.open('rad.fits')[0].data

w1antia = np.loadtxt('rotgongs414.1d23')[:,1]
w3antia = np.loadtxt('rotgongs414.3d23n')[:,1]
w5antia = np.loadtxt('rotgongs414.5d23n')[:,1]
rantia = np.loadtxt('rotgongs414.5d23n')[:,0]

maxratio = abs(w3antia).max()/(abs(w3sgk)/rsgk).max()
print("mag ratio, s3 = %10.5e" %(maxratio))
plt.plot(rsgk, abs(w3sgk)/rsgk, 'r')
plt.plot(rsgk, abs(w3sgk)/rsgk*maxratio, 'g')
plt.plot(rantia, abs(w3antia), 'b')
plt.show()
plt.close()

maxratio = abs(w5antia).max()/(abs(w5sgk)/rsgk).max()
print("mag ratio, s5 %10.5e" %(maxratio))
plt.plot(rsgk, abs(w5sgk)/rsgk, 'r')
plt.plot(rsgk, abs(w5sgk)/rsgk*maxratio, 'g')
plt.plot(rantia, abs(w5antia), 'b')
plt.show()
plt.close()

maxratio = abs(w1antia).max()/(abs(w1sgk)/rsgk).max()
print("mag ratio, s1 = %10.5e" %(maxratio))
plt.plot(rsgk, abs(w1sgk)/rsgk, 'r')
plt.plot(rsgk, abs(w1sgk)/rsgk*maxratio, 'g')
plt.plot(rantia, abs(w1antia), 'b')
plt.show()


import matplotlib.pyplot as plt
import numpy as np
import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')

def f(item):
    try:
        return f'{item:,.2f}'
    except Exception as e:
        return str(item)
# li = list(zip(range(1, 14), range(14, 27)))

def chart(*pairs, **kwargs):
    for num, pair in enumerate(pairs):
        axes = []
        axes.append([x[0] for x in pair])
        axes.append([x[1] for x in pair])
        # plt.plot(*[np.array(i) for i in axes], ls=":", label=f"{f(pair.initial)} @ {f(pair.perc)}% {'Compounded' if pair.compounding else ''}")
        plt.plot(*[np.array(i) for i in axes], ls="-",  label=f"{f(pair.initial)} @ {f(pair.perc)}% {'Compd' if pair.compounding else ''}")

    plt.legend()
    # plt.figure(figsize=(8, 6), dpi=300)
    plt.xticks(range(0, 21))
    # plt.ticklabel_format(useOffset=False)
    plt.ylim(ymin=0)
    plt.xlim(xmin=0)
    plt.ticklabel_format(style='plain', useLocale=True)
    plt.grid(color='green', linestyle='--', linewidth = 0.5)
    return plt

    """
    Introducing interactivity
    fig = plt.figure()

    with plt.ion():
        # interactive mode will be on
        # figures will automatically be shown
        fig2 = plt.figure()
        fig2.show()
    """

def deposit_chart(*args, **kwargs):
    plot = chart(*args, **kwargs)
    if not kwargs['times']:
        plot.yticks(range(0, 32000000*kwargs['multiplier'], 2500000*kwargs['multiplier']))
    plot.xlabel("Time in years")
    plot.ylabel("Deposits")
    plot.title('Accumulated Deposit')
    plot.savefig('deposits.png', dpi=300)
    plt.tight_layout()
    plot.show()

def monthly_return_chart(*args, **kwargs):
    plot = chart(*args, **kwargs)
    if not kwargs['times']:
        plot.yticks(range(0, 450000*kwargs['multiplier'], 25000*kwargs['multiplier']))
    plot.xlabel("Time in years")
    plot.ylabel("Monthly Return")
    plot.title('Monthly Return Chart')
    plot.savefig('monthly_return.png', dpi=300)
    plt.tight_layout()
    plot.show()