import numpy as np
import pandas as pd
from sklearn.impute import KNNImputer
from sklearn.neighbors import KNeighborsRegressor

# Load the dataset
data = pd.read_csv("/Users/bunty/Documents/elephantinindia.csv")

# Replace "Census not conducted" with NaN for easier handling
data = data.replace("Census not conducted", np.nan)

# Convert numerical columns to numeric type
numeric_columns = data.columns[1:]
data[numeric_columns] = data[numeric_columns].apply(pd.to_numeric)

# Separate instances with missing values and complete instances
missing_data = data[data.isnull().any(axis=1)]
missing_data.to_csv('missing_data.csv')
complete_data = data.dropna()
complete_data.to_csv('complete_data.csv')

# Set the number of neighbors (K) for imputation
K = 3

# Iterate over each feature with missing values
for column in numeric_columns:
    # Separate the feature with missing values and other features
    X_train = complete_data.drop([column, 'STATE'], axis=1)
    y_train = complete_data[column]
    X_test = missing_data.drop([column, 'STATE'], axis=1)

    # Handle missing values in X_test
    imputer = KNNImputer()
    X_test_imputed = imputer.fit_transform(X_test)

    # Create the K-Nearest Neighbors regressor
    knn = KNeighborsRegressor(n_neighbors=K)

    # Fit the model and predict missing values
    knn.fit(X_train, y_train)
    y_pred = knn.predict(X_test_imputed)

    # Assign the predicted values back to missing_data
    missing_data.loc[:, column] = y_pred

# Combine the imputed data with the complete data
imputed_data = pd.concat([complete_data, missing_data])

# Sort the data by state (optional)
imputed_data = imputed_data.sort_values(by=["STATE"])

# Print the imputed dataset
imputed_data = imputed_data.astype({'ELEPHANT POPULATION IN 1993': 'int',
                                    'ELEPHANT POPULATION IN 1997': 'int',
                                    'ELEPHANT POPULATION IN 2002': 'int',
                                    'ELEPHANT POPULATION IN 2007': 'int',
                                    'ELEPHANT POPULATION IN 2012': 'int',
                                    'ELEPHANT POPULATION IN 2017': 'int'})

# Save the imputed dataset to a CSV file
imputed_data.to_csv("imputed_elephant_population.csv", index=False)


#!/usr/bin/python3

import asyncio
import os
from typing import Dict, List, Optional, Set, Tuple, Any, cast
from datetime import datetime, timedelta

import aiohttp
import requests

class PRStats(object):

    def __init__(
        self,
        username: str,
        access_token: str,
        session: aiohttp.ClientSession,
        repo_owner: str = None,
        startDateTime: datetime = datetime.now() - timedelta(days = 365),
        endDateTime: datetime = datetime.now(),
    ):
        self.username = username
        self.access_token = access_token
        self.session = session

        self.repo_owner = repo_owner
        self.startDateTime = startDateTime
        self.endDateTime = endDateTime
        self.maxNumberOfRepos = 100

        self._prContributions: Optional[int] = None

    async def to_str(self) -> str:
        """
        :return: summary of all available statistics
        """
        return f"""Pull Request Contributions: {await self.prContributions}"""

    @property
    async def prContributions(self) -> int:
        """
        :return: total number of pull request contributions the user has performed (approvals, etc.)
        """
        if self._prContributions is not None:
            return self._prContributions
        await self.get_stats()
        assert self._prContributions is not None
        return self._prContributions

    async def get_stats(self) -> None:
        """
        Get lots of summary statistics using one big query. Sets many attributes
        """
        self._prContributions = 0

        url = 'https://api.github.com/graphql'
        query = (
        f"""
        {{
          user(login: "{self.username}") {{
            contributionsCollection(from: "{self.startDateTime.isoformat(sep='T', timespec='seconds')}", to: "{self.endDateTime.isoformat(sep='T', timespec='seconds')}") {{
              pullRequestReviewContributionsByRepository(maxRepositories: {self.maxNumberOfRepos}) {{
                contributions {{
                  totalCount
                }}
                repository {{
                  nameWithOwner
                }}
              }}
            }}
          }}
        }}
        """
        )
        json = { 'query' : query}
        api_token = f"{self.access_token}"
        headers = {'Authorization': 'token %s' % api_token}
        r = requests.post(url=url, json=json, headers=headers)

        #print(f"query: {query}")

        #print(f"json_data {r.json()}")
        json_data = r.json()['data']['user']['contributionsCollection']['pullRequestReviewContributionsByRepository']
        if self.repo_owner is None:
            self._prContributions = sum([i['contributions']['totalCount'] for i in json_data])
        else:
            self._prContributions = sum([i['contributions']['totalCount'] for i in json_data if i['repository']['nameWithOwner'].startswith(self.repo_owner)])
        print(f'Number of reviews: {self._prContributions}')
        self._prContributions = self._prContributions

###############################################################################
# Main Function
###############################################################################

async def main() -> None:
    """
    Used mostly for testing; this module is not usually run standalone
    """
    access_token = os.getenv("ACCESS_TOKEN")
    user = os.getenv("GITHUB_ACTOR")
    if access_token is None or user is None:
        raise RuntimeError(
            "ACCESS_TOKEN and GITHUB_ACTOR environment variables cannot be None!"
        )
    async with aiohttp.ClientSession() as session:
        s = PRStats(user, access_token, session)
        print(await s.to_str())

if __name__ == "__main__":
    asyncio.run(main())


from django.views.generic import DetailView, RedirectView
from django.views.generic.detail import SingleObjectMixin
from django.contrib.auth.mixins import LoginRequiredMixin

from .models import Battle, Challenger

import os
import random

class RandomQuestion():
    def question(self):
        path = "python_questions"
        append_string = ''
        list_of_strings = []
        names = os.listdir(path)
        # removes hidden files, just in case.
        names = [f for f in names if not f.startswith('.')]
        list_of_paths = []
        for root, dirs, files in os.walk(path):
            for f in files:
                x = os.path.join(root, f)
                list_of_paths.append(x)

        question = random.choice(list_of_paths)
        open_question = open(question, 'r')
        display_question = open_question.read()
        display_question = display_question[3:-4]

        for i in display_question:
            if i != '\n':
                append_string += i
            if i == '/':
                list_of_strings.append(append_string[0:-1])
                append_string = ""
        return list_of_strings

    def name(self):
        path = "python_questions"
        names = os.listdir(path)
        # removes hidden files, just in case.
        names = [f for f in names if not f.startswith('.')]
        name = random.choice(names)
        return name

my_class = RandomQuestion()

class BattleView(DetailView):
    model = Battle
    template_name = 'battle/battle.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['battle_id'] = self.get_object().pk
        return context

class PreBattleView(LoginRequiredMixin, SingleObjectMixin, RedirectView):
    model = Battle
    pattern_name = 'battle'

    def get(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        if request.user.profile.in_battle():
            self.current_pk = request.user.profile.current_battle().pk
        elif queryset.filter(state=Battle.WAITING).count() > 0:
            battle = queryset.filter(state=Battle.WAITING).order_by('-pk')[0]
            if battle.challengers.count() == 0:
                battle.challengers.add(request.user)
                battle.save()
                self.current_pk = battle.pk
            else:
                color = Challenger.BLUE
                if battle.challenger_set.get().color == Challenger.BLUE:
                    color = Challenger.RED
                battle.challengers.add(request.user, through_defaults={'color': color})
                battle.state = Battle.READY
                battle.save()
                self.current_pk = battle.pk
        else:
            battle = Battle.objects.create()
            battle.challengers.add(request.user)
            battle.save()
            self.current_pk = battle.pk
        if request.user.battles.exclude(state=Battle.ARCHIVED).count() > 2:
            print('DEBUG LN 89 battle/views.py')
            request.user.challenges.exclude(
                battle__state=Battle.ARCHIVED, battle__pk=self.current_pk
            ).delete()
        return super().get(request, *args, **kwargs)

    def get_redirect_url(self, *args, **kwargs):
        return super().get_redirect_url(self.current_pk, *args, **kwargs)


import heapq

class Solution:
    def maxScore(self, nums1: List[int], nums2: List[int], k: int) -> int:
        a = []
        n = len(nums1)
        for i in range(n):
            a.append((nums2[i], nums1[i]))

        a.sort(key=lambda x: (-x[1], x[0]))
        total = 0
        pq = []
        for i in range(k):
            total += a[i][1]
            heapq.heappush(pq, a[i])

        ans = total * pq[0][0]
        for i in range(k, n):
            if a[i][0] > pq[0][0]:
                total += a[i][1] - pq[0][1]
                heapq.heapreplace(pq, a[i])
            ans = max(ans, total * pq[0][0])

        return ans


""" Run a backtest """
from pathlib import Path

import datamaker.db as db

from datamaker.backtest import Market, Backtest

import IPython

def run_backtest(path=Path(".")):

    session = db.Session()
    strategy = session.query(db.Strategy).first()
    historical = strategy.currency_pair.historical_data(path)

    market = Market(
        historical, instrument="EUR_USD", account_size=100000, leverage=1)

    backtest = Backtest(historical, strategy=strategy, market=market)

    backtest.run()
    IPython.embed()

if __name__ == "__main__":
    run_backtest()


def sumOfLeftLeaves(root):
    if root is None:
        return 0
    leftSum = 0
    queue = [root]
    while queue:
        cur = queue.pop(0)
        if cur.left and not cur.left.left and not cur.left.right:
            leftSum += cur.left.val
        if cur.left:
            queue.append(cur.left)
        if cur.right:
            queue.append(cur.right)
    return leftSum


#Function to count number of digits in a number
def Number_of_digits(number):

	quotient = int(number)
	count = 1
	while(quotient >= 10):

		quotient = quotient/10
		count = count + 1

	return count

#print("Enter a Palindrome number to get next smallest Palindrome number")
num = int(input())

#Work only if give number is Palindrome
if str(num) == str(num)[::-1]:

	Digits = Number_of_digits(num)

	string = str(num)
	front_half = ''

#To calculate the next Palindrome number, there exist 3 possible cases

#Case 1: Entire number consist of 9, eg:999,99,9,etc.

	if Digits == (Number_of_digits(num + 1) - 1):

		print(num + 2)

#Case 2: Number of digits in given Number is even

	elif Digits%2 == 0:

		for i in range(int(len(string)/2)):

			front_half = front_half + string[i]

		front_half = int(front_half) + 1

		next_half = str(front_half)[::-1]

		print(str(front_half) + next_half)

#Case 3: Number of Digits in given Number is Odd

	else:

		for i in range(int(len(string)/2+1)):

			front_half = front_half + string[i]

		front_half = int(front_half) + 1

		next_half = str(int(front_half/10))[::-1]

		print(str(front_half) + next_half)

#Error message for non-palindrome number

else:

	print("Entered Number is not Palindrome Number")


# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
""" Drives an android device.
"""
import os
import posixpath
import tempfile
import contextlib
import time
import logging

import attr
from arsenic.services import Geckodriver, free_port, subprocess_based_service
from mozdevice import ADBDeviceFactory, ADBError

from condprof.util import write_yml_file, logger, DEFAULT_PREFS, BaseEnv

# XXX most of this code should migrate into mozdevice - see Bug 1574849
class AndroidDevice:
    def __init__(
        self,
        app_name,
        marionette_port=2828,
        verbose=False,
        remote_test_root="/sdcard/test_root/",
    ):
        self.app_name = app_name

        # XXX make that an option
        if "fenix" in app_name:
            self.activity = "org.mozilla.fenix.IntentReceiverActivity"
        else:
            self.activity = "org.mozilla.geckoview_example.GeckoViewActivity"
        self.verbose = verbose
        self.device = None
        self.marionette_port = marionette_port
        self.profile = None
        self.remote_profile = None
        self.log_file = None
        self.remote_test_root = remote_test_root
        self._adb_fh = None

    def _set_adb_logger(self, log_file):
        self.log_file = log_file
        if self.log_file is None:
            return
        logger.info("Setting ADB log file to %s" % self.log_file)
        adb_logger = logging.getLogger("adb")
        adb_logger.setLevel(logging.DEBUG)
        self._adb_fh = logging.FileHandler(self.log_file)
        self._adb_fh.setLevel(logging.DEBUG)
        adb_logger.addHandler(self._adb_fh)

    def _unset_adb_logger(self):
        if self._adb_fh is None:
            return
        logging.getLogger("adb").removeHandler(self._adb_fh)
        self._adb_fh = None

    def clear_logcat(self, timeout=None, buffers=[]):
        if not self.device:
            return
        self.device.clear_logcat(timeout, buffers)

    def get_logcat(self):
        if not self.device:
            return None
        # we don't want to have ADBCommand dump the command
        # in the debug stream so we reduce its verbosity here
        # temporarely
        old_verbose = self.device._verbose
        self.device._verbose = False
        try:
            return self.device.get_logcat()
        finally:
            self.device._verbose = old_verbose

    def prepare(self, profile, logfile):
        self._set_adb_logger(logfile)
        try:
            # See android_emulator_pgo.py run_tests for more
            # details on why test_root must be /sdcard/test_root
            # for android pgo due to Android 4.3.
            self.device = ADBDeviceFactory(
                verbose=self.verbose, logger_name="adb", test_root=self.remote_test_root
            )
        except Exception:
            logger.error("Cannot initialize device")
            raise
        device = self.device
        self.profile = profile

        # checking that the app is installed
        if not device.is_app_installed(self.app_name):
            raise Exception("%s is not installed" % self.app_name)

        # debug flag
        logger.info("Setting %s as the debug app on the phone" % self.app_name)
        device.shell(
            "am set-debug-app --persistent %s" % self.app_name,
            stdout_callback=logger.info,
        )

        # creating the profile on the device
        logger.info("Creating the profile on the device")

        remote_profile = posixpath.join(self.remote_test_root, "profile")
        logger.info("The profile on the phone will be at %s" % remote_profile)

        device.rm(remote_profile, force=True, recursive=True)
        logger.info("Pushing %s on the phone" % self.profile)
        device.push(profile, remote_profile)
        device.chmod(remote_profile, recursive=True)
        self.profile = profile
        self.remote_profile = remote_profile

        # creating the yml file
        yml_data = {
            "args": ["-marionette", "-profile", self.remote_profile],
            "prefs": DEFAULT_PREFS,
            "env": {"LOG_VERBOSE": 1, "R_LOG_LEVEL": 6, "MOZ_LOG": ""},
        }

        yml_name = "%s-geckoview-config.yaml" % self.app_name
        yml_on_host = posixpath.join(tempfile.mkdtemp(), yml_name)
        write_yml_file(yml_on_host, yml_data)
        tmp_on_device = posixpath.join("/data", "local", "tmp")
        if not device.exists(tmp_on_device):
            raise IOError("%s does not exists on the device" % tmp_on_device)
        yml_on_device = posixpath.join(tmp_on_device, yml_name)
        try:
            device.rm(yml_on_device, force=True, recursive=True)
            device.push(yml_on_host, yml_on_device)
            device.chmod(yml_on_device, recursive=True)
        except Exception:
            logger.info("could not create the yaml file on device. Permission issue?")
            raise

        # command line 'extra' args not used with geckoview apps; instead we use
        # an on-device config.yml file
        intent = "android.intent.action.VIEW"
        device.stop_application(self.app_name)
        device.launch_application(
            self.app_name, self.activity, intent, extras=None, url="about:blank"
        )
        if not device.process_exist(self.app_name):
            raise Exception("Could not start %s" % self.app_name)

        logger.info("Creating socket forwarding on port %d" % self.marionette_port)
        device.forward(
            local="tcp:%d" % self.marionette_port,
            remote="tcp:%d" % self.marionette_port,
        )

        # we don't have a clean way for now to check that GV or Fenix
        # is ready to handle our tests. So here we just wait 30s
        logger.info("Sleeping for 30s")
        time.sleep(30)

    def stop_browser(self):
        logger.info("Stopping %s" % self.app_name)
        try:
            self.device.stop_application(self.app_name)
        except ADBError:
            logger.info("Could not stop the application using force-stop")

        time.sleep(5)
        if self.device.process_exist(self.app_name):
            logger.info("%s still running, trying SIGKILL" % self.app_name)
            num_tries = 0
            while self.device.process_exist(self.app_name) and num_tries < 5:
                try:
                    self.device.pkill(self.app_name)
                except ADBError:
                    pass
                num_tries += 1
                time.sleep(1)
        logger.info("%s stopped" % self.app_name)

    def collect_profile(self):
        logger.info("Collecting profile from %s" % self.remote_profile)
        self.device.pull(self.remote_profile, self.profile)

    def close(self):
        self._unset_adb_logger()
        if self.device is None:
            return
        try:
            self.device.remove_forwards("tcp:%d" % self.marionette_port)
        except ADBError:
            logger.warning("Could not remove forward port")

# XXX redundant, remove
@contextlib.contextmanager
def device(
    app_name, marionette_port=2828, verbose=True, remote_test_root="/sdcard/test_root/"
):
    device_ = AndroidDevice(
        app_name, marionette_port, verbose, remote_test_root=remote_test_root
    )
    try:
        yield device_
    finally:
        device_.close()

@attr.s
class AndroidGeckodriver(Geckodriver):
    async def start(self):
        port = free_port()
        await self._check_version()
        logger.info("Running Webdriver on port %d" % port)
        logger.info("Running Marionette on port 2828")
        pargs = [
            self.binary,
            "--log",
            "trace",
            "--port",
            str(port),
            "--marionette-port",
            "2828",
        ]
        logger.info("Connecting on Android device")
        pargs.append("--connect-existing")
        return await subprocess_based_service(
            pargs, f"http://localhost:{port}", self.log_file
        )

class AndroidEnv(BaseEnv):
    @contextlib.contextmanager
    def get_device(self, *args, **kw):
        with device(self.firefox, *args, **kw) as d:
            self.device = d
            yield self.device

    def get_target_platform(self):
        app = self.firefox.split("org.mozilla.")[-1]
        if self.device_name is None:
            return app
        return "%s-%s" % (self.device_name, app)

    def dump_logs(self):
        logger.info("Dumping Android logs")
        try:
            logcat = self.device.get_logcat()
            if logcat:
                # local path, not using posixpath
                logfile = os.path.join(self.archive, "logcat.log")
                logger.info("Writing logcat at %s" % logfile)
                with open(logfile, "wb") as f:
                    for line in logcat:
                        f.write(line.encode("utf8", errors="replace") + b"\n")
            else:
                logger.info("logcat came back empty")
        except Exception:
            logger.error("Could not extract the logcat", exc_info=True)

    @contextlib.contextmanager
    def get_browser(self):
        yield

    def get_browser_args(self, headless, prefs=None):
        # XXX merge with DesktopEnv.get_browser_args
        options = ["--allow-downgrade"]
        if headless:
            options.append("-headless")
        if prefs is None:
            prefs = {}
        return {"moz:firefoxOptions": {"args": options, "prefs": prefs}}

    def prepare(self, logfile):
        self.device.prepare(self.profile, logfile)

    def get_browser_version(self):
        return self.target_platform + "-XXXneedtograbversion"

    def get_geckodriver(self, log_file):
        return AndroidGeckodriver(binary=self.geckodriver, log_file=log_file)

    def check_session(self, session):
        async def fake_close(*args):
            pass

        session.close = fake_close

    def collect_profile(self):
        self.device.collect_profile()

    def stop_browser(self):
        self.device.stop_browser()


import numpy as np
import cv2

cap = cv2.VideoCapture(0)

while(True):
    # Capture the video frame by frame
    ret, frame = cap.read()

    # convert to gray picture
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Display the picture
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# release the capture when quit
cap.release()
cv2.destroyAllWindows()


N = n = int(input())
A, c = [0]*10, 1
while n:
    n, r = divmod(n, 10)
    for i in range(10):
        A[i] += (n+(1 <= i <= r))*c-(c-(N % c)-1)*(i == r)
    c *= 10
print(*A)

# 풀이 참고 : https://latter2005.tistory.com/54


import pickle
from random import sample
from sklearn.externals import joblib
from sklearn.linear_model import LogisticRegression
from numpy import set_printoptions , inf

def accuarcy(a,b):
    i = 0
    count = 0
    for i in range(len(a)):
        if a[i] == b[i]:
            count = count + 1
    return count/len(a)
set_printoptions(threshold=inf)
data = open("../notMNIST.pickle","rb")

values = pickle.load(data)

test_dataset = values['test_dataset']

nsamples , nx , ny = test_dataset.shape

test_dataset = test_dataset.reshape((nsamples,nx*ny))

#valid_dataset = sample(valid_dataset,10)
model = joblib.load('initial_model_saga_10000.pkl')

result = model.predict(test_dataset)

print(accuarcy(result,values['test_labels']))
#print(result)
#print(values['valid_labels'])
#print(type(model))


from __future__ import print_function

from random import randint
import socket
import sys

import pymnl
from pymnl.attributes import Attr
from pymnl.message import Message, Payload
from pymnl.nlsocket import Socket

import if_
import if_link
import rtnetlink

change = 0
flags = 0

if (len(sys.argv) != 3):
    print("Usage: %s [ifname] [up|down]" % (sys.argv[0],))
    sys.exit()

if (sys.argv[2].lower() == "up"):
    change |= if_.IFF_UP
    flags |= if_.IFF_UP
elif (sys.argv[2].lower() == "down"):
    change |= if_.IFF_UP;
    flags &= ~if_.IFF_UP;
else:
    print("%s is not `up' nor `down'" % (sys.argv[2],))
    sys.exit()

# init and build request message
rtnlmsg = Message()
rtnlmsg.set_type(rtnetlink.RTM_NEWLINK)
rtnlmsg.set_flags(pymnl.message.NLM_F_REQUEST | pymnl.message.NLM_F_ACK)

sequence = randint(0, pow(2, 31))
rtnlmsg.set_seq(sequence)

# build ifm header and add it to the message
ifm = if_.IfInfoMessage()
ifm.family = socket.AF_UNSPEC
ifm.change = change
ifm.flags = flags

rtnlmsg.put_extra_header(ifm)

payload = rtnlmsg.get_payload()
payload.add_attr(Attr.new_str(if_link.IFLA_IFNAME, sys.argv[1].encode()))

# init and bind netlink socket
sock = Socket(pymnl.NETLINK_ROUTE)
sock.bind(pymnl.nlsocket.SOCKET_AUTOPID, 0)

rtnlmsg.printf(len(ifm))

# send message through socket
sock.send(rtnlmsg)

# read returned message from netlink
return_msg = sock.recv(flags=socket.MSG_DONTWAIT)

sock.close()

# process the messages returned
for msg in return_msg:
    if (msg.get_errno()):
        # tell the user what error occurred
        print("error:", msg.get_errstr())


from django.shortcuts import render
from django.http import HttpResponse
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles import finders
from django.template import Template, Context
import os
import yaml
from pathlib import Path
import mistune

# Create your views here.
def index(request):
    ctxt = {'projects': [
        {'image': 'images/image5.png',
         'name': 'Prediction of Steering Angles',
         'description': 'Using Keras to predict steering angles from images of the road',
         'link': 'https://google.com'},
        {'image': 'images/melee_thumb.jpg',
         'name': 'Super Smash Bros. Melee AI',
         'description': 'Creation of a Machine Learning Melee AI Using Keras',
         'link': 'https://google.com'},
        {'image': 'images/OW_thumb.jpg',
         'name': 'Overwatch Fight Prediction',
         'description': 'Final part of a Data Science project to predict the winners of fights in Overwatch',
         'link': 'https://google.com'},
        {'image': 'images/vlight_thumb.png',
         'name': 'Volumetric Lighting',
         'description': 'OpenGL implementation of Volumetric Lighting',
         'link': 'https://google.com'},
    ]}
    project_files_dir = finders.find('portfolio/projects/')
    project_files = os.listdir(project_files_dir)
    ctxt = {'projects': []}
    for project in project_files:
        project_path = Path(project_files_dir).joinpath(project)
        details, content = process_project_page(project_path)
        details['link'] = project.split('.')[0]
        ctxt['projects'].append(details)

    return render(request, 'portfolio/index.html', ctxt)

def process_project_page(project_page_path):
    with open(project_page_path) as pfile:
        project_details = ''
        for line in pfile:
            if line == '---\n':
                break
            project_details += line
        project_details = yaml.load(project_details, Loader=yaml.FullLoader)
        project_content = pfile.read()
    return project_details, project_content

def project_page(request, project_name):
    project_file = finders.find(f'portfolio/projects/{project_name}.md')
    details, content = process_project_page(project_file)
    content = Template(content).render(Context({}))
    content = mistune.html(content)
        #project_details = yaml.load(pfile, Loader=yaml.FullLoader)

    ctxt = {
        'name': project_name,
        'content': content,
    }
    ctxt.update(details)

    #ctxt = project_details
    return render(request, 'portfolio/project.html', ctxt)

def resume(request):
    return render(request, 'portfolio/resume.html')


#pip list: 파이썬 모듈들 표시
#'pip install (streamlit)파이썬 모듈 이름'으로 설치
#streamlit --version
#conda activate base: base로
#streamlit: 웹 앱 만드는데 최적화, 웹브라우저에 출력

import streamlit as st
st.text("streamlit ver. : " + st.__version__) #text함수 이용해 버전 출력
#'streamlit run st_01_start.py' 출력 실행

# ## Text
# ## Title
st.title('Streamlit Tutorial: start by pdm00, 이상훈')
# ## Header/Subheader
st.header('This is header')
st.subheader('This is subheader')
# ## Text
st.text("Hello Streamlit! 이 글은 튜토리얼 입니다.")

# ## Markdown
st.header('Markdown')
st.markdown('# header-1')
st.markdown('## header-2')
st.markdown('#### header-4')
st.markdown('###### header-6')

# # list
st.header('markdown: List')
st.markdown('- list1')
# st.markdown('list1')
st.markdown('- list2')
st.markdown('- list3\n'
            '   * inner list1\n'
            '   * inner list2\n'
            '       - inner_inner list\n')

# ## Message
st.info("End of first note: **text, markdown, latex**!") #info(문자): 색 있는 타이틀 바 - 문자 강조

## streamlit messages <안내 추가>
st.success("Successful") #초록
st.info("Information!") #밝은 하늘
st.warning("This is a warning") #노랑
st.error("This is an error!") #빨강
st.exception("NameError('Error name is not defined')") #빨강 - 에러의 일종

## Code block
st.header('Code block')
code1 = '''def hello():
    print("Hello, Streamlit!")''' #''' ''', """ """: 두 줄 이상의 문자열// 콜론 후 들여쓰기

st.code(code1, language='python') #코드가 파이썬 포맷으로, 회색 배경

code2 = '''
def add(a,b):
    return a+b
'''

st.code(code2, language='python')

# ## Latex, raw
st.header('latex') #수식
st.latex(r"\alpha_n, \beta, \gamma, \cdots, \omega") #r: 특수코드 없는 문자열, _n:아래첨자 n, \:그리스어
st.latex(r"Y = \alpha + \beta X_i") #1차원 회귀식
# ## Latex-inline
st.markdown(r"회귀분석에서 오차는 다음과 같습니다 $e_i = y_i - \hat{y}_i$") #라텍스 inline 수식 - $안에 수식 넣기
# ## Mean squared error
st.subheader("Mean squared error")
st.markdown(r"#### $MSE = \frac{1}{N-1} \sum_{i=1}^{N-1} (y_i - \hat{y}_i)^2$")


from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium import webdriver

class BasePage():

    def __init__(self, driver):
        self.driver = driver
        self.driver.maximize_window()
        self.wait = WebDriverWait(self.driver, 5)
        self.actions = ActionChains(self.driver)
        if self.url:
            self.driver.get(self.url)

    def click(self, locator):
        try:
            self.wait.until(
                EC.element_to_be_clickable((*locator,))
            )
            self.driver.find_element(*locator).click()
        except Exception as err:
            print("Element not found or clickable. Error: ", err)
            raise

    def click_js(self, locator):
        try:
            self.wait.until(
                EC.element_to_be_clickable((*locator,))
            )
            field = self.driver.find_element(*locator)
            self.driver.execute_script("arguments[0].click();", field)
        except Exception as err:
            print("Element not found or clickable. Error: ", err)
            raise

    def enter_text(self, locator, text):
        try:
            self.wait.until(
                EC.visibility_of_element_located((*locator,))
            )
        except Exception as err:
            print("Unable to find input field. Error: ", err)
            raise
        self.driver.find_element(*locator).send_keys(text)

    def get_element(self, locator):
        try:
            self.wait.until(
                EC.visibility_of_element_located((*locator,))
            )
        except Exception as err:
            print("Unable to find element. Error: ", err)
            raise
        return self.driver.find_element(*locator)

    def wait_until_not_visible(self, locator):
        try:
            self.wait.until(
                EC.invisibility_of_element_located((*locator,))
            )
        except Exception as err:
            print("Element still visbile. Error: ", err)
            raise

    def wait_until_visible(self, locator):
        try:
            self.wait.until(
                EC.visibility_of_element_located((*locator,))
            )
        except Exception as err:
            print("Element not found. Error: ", err)
            raise

    def is_element_visibile(self, locator):
        try:
            self.wait.until(
                EC.visibility_of_element_located((*locator,))
            )
            return True
        except Exception as err:
            print("Cound not find element. Error: ", err)
            return False

    def get_all_elements(self, locator):
        try:
            self.wait_until_visible(locator)
            elements = self.driver.find_elements(*locator)
            return elements
        except Exception as err:
            print("Could not find elements. Error: ", err)
            raise

    def get_current_url(self):
        return self.driver.current_url


#Logic, Control Flow and Filtering

#Equality
# Comparison of booleans
print(True == False)

# Comparison of integers
print(-5 * 15 != 75)

# Comparison of strings
print("pyscript" == "PyScript")

# Compare a boolean with a numeric
print(True == 1)

#Greater and less than
# Comparison of integers
x = -3 * 6
print(x >= -10)

# Comparison of strings
y = "test"
print("test" <= y)

# Comparison of booleans
print(True > False)

#Compare arrays
# Create arrays
import numpy as np
my_house = np.array([18.0, 20.0, 10.75, 9.50])
your_house = np.array([14.0, 24.0, 14.25, 9.0])

# my_house greater than or equal to 18
print(my_house >= 18)

# my_house less than your_house
print(my_house < your_house)

# and, or, not (1)
# Define variables
my_kitchen = 18.0
your_kitchen = 14.0

# my_kitchen bigger than 10 and smaller than 18?
print(my_kitchen > 10 and my_kitchen < 18)

# my_kitchen smaller than 14 or bigger than 17?
print(my_kitchen < 14 or my_kitchen > 17)

# Double my_kitchen smaller than triple your_kitchen?
print(my_kitchen * 2 < your_kitchen * 3)

#Boolean operators with Numpy
# Create arrays
import numpy as np
my_house = np.array([18.0, 20.0, 10.75, 9.50])
your_house = np.array([14.0, 24.0, 14.25, 9.0])

# my_house greater than 18.5 or smaller than 10
print(np.logical_or(my_house > 18.5, my_house < 10))

# Both my_house and your_house smaller than 11
print(np.logical_and(my_house < 11, your_house < 11))

#if
# Define variables
room = "kit"
area = 14.0

# if statement for room
if room == "kit" :
    print("looking around in the kitchen.")

# if statement for area
if area > 15 :
    print("big place!")

#Add else
# Define variables
room = "kit"
area = 14.0

# if-else construct for room
if room == "kit" :
    print("looking around in the kitchen.")
else :
    print("looking around elsewhere.")

# if-else construct for area :
if area > 15 :
    print("big place!")
else :
    print("pretty small.")

##Customize further: elif
# Define variables
room = "bed"
area = 14.0

# if-elif-else construct for room
if room == "kit" :
    print("looking around in the kitchen.")
elif room == "bed":
    print("looking around in the bedroom.")
else :
    print("looking around elsewhere.")

# if-elif-else construct for area
if area > 15 :
    print("big place!")
elif area > 10 :
    print("medium size, nice!")
else :
    print("pretty small.")

#Driving right (1)
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Extract drives_right column as Series: dr
dr = cars['drives_right']

# Use dr to subset cars: sel
sel = cars[dr]

# Print sel
print(sel)

#Driving right (2)
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Convert code to a one-liner
sel = cars[cars['drives_right']]

# Print sel
print(sel)

#Cars per capita (1)
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Create car_maniac: observations that have a cars_per_cap over 500
cpc = cars['cars_per_cap']
many_cars = cpc > 500
car_maniac = cars[many_cars]

# Print car_maniac
print(car_maniac)

#Cars per capita (2)
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Import numpy, you'll need this
import numpy as np

# Create medium: observations with cars_per_cap between 100 and 500
cpc = cars['cars_per_cap']
between = np.logical_and(cpc > 100, cpc < 500)
medium = cars[between]

# Print medium
print(medium)

Intermediate Python for Data Science/Chapter 3 - Logic, Control Flow and Filtering.py


import datetime
from time import sleep

from django.core.urlresolvers import reverse

from ft.base import FunctionalTestBase

class ItemPurchaseFormVisit(FunctionalTestBase):
    """
    Test for item purchase form actions when user opens the pop-up via
    "Purchase" button on item maintenance page.

    """

    test_uri = reverse('item_maintenance')

    test_data_items = [
        {'name': 'test item #1', 'extended_threshold': 5, },
        {'name': 'test item #2', },
    ]

    def test_submitting_form_blank_fields_show_the_error_messages(self):
        """
        Verify that hitting the submit button with quantity field blank on the
        form is showing the appropriate error message.

        """

        error_messages = [
            'Quantity cannot be blank',
            'Quantity must be a number',
        ]

        # Shopper opens the add item form
        modal = self.open_purchase_item_form(1)

        # Form shows no error messages
        for msg in error_messages:
            self.assertNotIn(msg, modal.text)

        # then she and click the submit button.
        modal.find_element_by_css_selector(
            '.modal-footer button.btn-primary').click()

        # Error message is displayed saying that name is required
        self.assertIn(error_messages[0], modal.text)

        # Then shopper start to enter a non-numeric text to quantity, and the
        # message now says that it should be a number.
        modal.find_element_by_id('id_quantity').send_keys('a')
        self.assertIn(error_messages[1], modal.text)

        # Entering a numeric value in the quantity box clears the error
        # message.
        modal.find_element_by_id('id_quantity').clear()
        modal.find_element_by_id('id_quantity').send_keys('1')
        self.assertNotIn(error_messages[0], modal.text)
        self.assertNotIn(error_messages[1], modal.text)

    def test_focus_on_date_brings_up_the_datepicker(self):
        """
        Verify the focusing on the (readonly) date field rinds up the
        datepicker dialog.

        """

        # Shopper opens the add item form
        modal = self.open_purchase_item_form(1)

        # and click on the date text box
        modal.find_element_by_id('id_date').click()

        # Datepicker pop-up is not visible
        self.assertTrue(modal.find_element_by_class_name(
            'purchase-date').is_displayed())

    def test_saved_purchas_date_show_up_in_the_items_table(self):
        """
        Verify that after adding a new purchase,the date in the item list gets
        updated.

        """

        # Shopper opens the add item form,
        modal = self.open_purchase_item_form(1)

        # enter a quantity value
        modal.find_element_by_id('id_quantity').send_keys('1')

        # then she and click the submit button.
        modal.find_element_by_css_selector(
            '.modal-footer button.btn-primary').click()

        # wait for the animation
        sleep(.1)

        # Purchase date now shows up in the item maintenance page
        self.assertIn(datetime.date.today().strftime('%B, %-d'),
                      self.browser.find_element_by_css_selector(
                          '.items-table tbody tr:nth-child(1) .last_purchase')
                      .text)
        self.assertEqual('21 days',
                         self.browser.find_element_by_css_selector(
                             '.items-table tbody tr:nth-child(1) ' +
                             '.purchase_threshold').text)


'''
File: Audiolyze.py
Author: Tristan van Vaalen

Audio stream analyzer
'''

import config
import microphone
from audiolazy import z
# import audiolazy

class Audiolyze:

    def __init__(self, filt):
        self.config = config.Config()
        self.microphone = microphone.Microphone(filt, **self.config.args)

if __name__ == '__main__':
    # filt = (0.2 * (1 - z ** 5)) / (z ** 4)(1 - z)
    # filt = 0.2 * (1 + z ** -1 + z ** -2 + z ** -3 + z ** -4)
    # filt = 0.2 * (1 - z**5) / (z**2 * (1-z))
    # filt = 0.03824 * (z**2 - 1) / (z**2 + 0.9235)
    # filt = (-z + 3)/(z - 9.5)
    # filt = (0.18 * z) / ((z - 1) * (z - 0.82))
    # filt = audiolazy.comb.tau(delay=30*2, tau=40*4)
    filt = 1 / ((2 * (z - 1)) / (0.1 * (z + 1)) + 1)
    # filt = 1 - z ** -1
    audiolyze = Audiolyze(filt)


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

# Страшный костыль
class SelectResult(tuple):
    pass

class Obj:
    def __init__(self, data, conn=None, user_id=None):
        self._data = self._map(dict(data))
        self._conn = conn
        self._uid = user_id

    @property
    def id(self):
        return self._data['id']

    @property
    def attrs(self):
        return self._data['attributes']

    @property
    def meta(self):
        return self._data['meta']

    def __repr__(self):
        return f'<{type(self).__name__} id={self.id}>'

    _type = ''
    _meta: tuple = None

    @classmethod
    def _map(cls, data: dict) -> dict:
        resp = dict(type=cls._type, id=data.pop('id'))

        if cls._meta is not None:
            _m = {x: data.pop(x) for x in cls._meta if x in data}
            if _m:
                resp['meta'] = _m

        resp['attributes'] = data

        return resp

class Commands:
    def __new__(cls, __type: int=0, **sqls: str):
        if __type == 0:
            action = 'fetch'
        elif __type == 1:
            action = 'execute'
        elif __type == 2:
            action = 'fetchval'
        else:
            action = 'fetchrow'

        definition = 'class _Commands:\n'

        for (key, val) in sqls.items():
            definition += f'    @staticmethod\n' \
                          f'    async def {key}(conn, *args):\n' \
                          f'        return await conn.{action}(\n' \
                          f'            {repr(val)}, *args\n' \
                          f'        )\n\n'

        if __type == 0:
            definition += f'    e = Commands(1, **{str(sqls)})\n'\
                          f'    v = Commands(2, **{str(sqls)})\n'\
                          f'    r = Commands(3, **{str(sqls)})\n'

        local = dict()

        exec(definition, globals(), local)
        result = local['_Commands']

        return result


import sys
import time
from collections import namedtuple
from tuplestate import *
from timebudget import timebudget
from policies import *

sys.setrecursionlimit(10 ** 6)

def solve(state, max_states=50_000, **solver_params):
    visited = set()
    moveseq = []
    i = 0
    while True:
        v = len(visited)
        if i >= max_states:
            return EndState(solved=False, visited=v, msg="exceeded max states")
        if state in visited:
            return EndState(solved=False, msg="revisited state", visited=v)
        visited.add(state)
        # Yan et al. Section 4 "Machine Play"
        # 1. identify set of legal moves
        result = yan_et_al_rollout(state, **solver_params)
        # 2. select and execute a legal move
        if result is None:
            return EndState(solved=False, msg="no avail moves", visited=v)
        if hasattr(result, "solved"):
            return result  # solved in rollout
        # otherwise the rollout gives the old heuristic strategy
        action = result
        moveseq.append(action)
        state = play_move(state, action)
        # 3. If all cards are on suit stacks, declare victory and terminate.
        if state_is_win(state):
            return EndState(solved=True, moveseq=moveseq, visited=v)
        # 4. If new card configuration repeats a previous one, declare loss and terminate.
        # 5. Repeat procedure.
        i += 1

if __name__ == "__main__":
    from benchmarking import convert_shootme_to_solvitaire_json

    timebudget.report_atexit()

    import os

    for fname in os.listdir("./fixtures/shootme/solvedmin"):
        with open(f"./fixtures/shootme/solvedmin/{fname}") as f:
            ret = f.read()
        print(fname)
        deck_json = convert_shootme_to_solvitaire_json(ret)
        state = init_from_solvitaire(deck_json)
        solution = solve(state, max_states=100_000, k=1)
        # print()
        if solution.solved:
            moveseq = list(solution.moveseq)
            visited = solution.visited
            print(f"solved, visited {visited} states, solved in {len(moveseq)} moves")
            # print(moveseq)
        else:
            print("no solution")
        # print()


from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import unittest
from SampleProjects.POMDemo.Pages.loginPage import LoginPage
from SampleProjects.POMDemo.Pages.homePage import HomePage
import HtmlTestRunner
class LoginTest(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.driver = webdriver.Chrome(executable_path="drivers/chromedriver.exe")
        cls.driver.implicitly_wait(10)
        cls.driver.maximize_window()

    def test01_login_valid(self):
        driver = self.driver
        driver.get("https://opensource-demo.orangehrmlive.com/")
        login = LoginPage(driver)
        login.enter_username("Admin")
        login.enter_password("admin123")
        login.click_login()

        homepage = HomePage(driver)
        homepage.click_welcome()
        homepage.click_logout()
        time.sleep(2)

    def test02_login_invalid_username(self):
        driver = self.driver
        driver.get("https://opensource-demo.orangehrmlive.com/")
        login = LoginPage(driver)
        login.enter_username("Admin1")
        login.enter_password("admin123")
        login.click_login()
        message = driver.find_element(By.XPATH,"//p[@class='oxd-text oxd-text--p oxd-alert-content-text']").text
        self.assertEqual(message,"Invalid credentials")
        time.sleep(2)

    @classmethod
    def tearDownClass(cls):
        cls.driver.close()
        cls.driver.quit()
        print("Test Completed")

if __name__ == '__main__':
    unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output="reports"))


#!/usr/bin/python3
"""This module defines the function island_perimeter"""

def island_perimeter(grid):
    """
    Calculate the perimeter of the island described in the grid.

    Args:
        grid (list of list of integers): The grid representing the island.

    Returns:
        int: The perimeter of the island.
    """
    rows = len(grid)
    cols = len(grid[0])
    perimeter = 0

    for i in range(rows):
        for j in range(cols):
            if grid[i][j] == 1:
                perimeter += 4
                if i > 0 and grid[i - 1][j] == 1:
                    perimeter -= 2
                if j > 0 and grid[i][j - 1] == 1:
                    perimeter -= 2

    return perimeter


import random

class AdditionCategory2:

    instance_no_list = []
    answer_calculated_list = []

    def __init__(self, original_number_list):
        self.instance_no_list = []
        self.answer_calculated_list = []
        for i in range(0, len(original_number_list)):
            self.instance_no_list.append(original_number_list[i])

    def is_category_condition_satisfied(cls):
        temp_list = list(cls.instance_no_list)
        while(all(v != 0 for v in temp_list)):
            sum_of_digits = 0
            for i in range(0, len(temp_list)):
                sum_of_digits = sum_of_digits + (temp_list[i] % 10)
                temp_list[i] = temp_list[i] // 10
            if(sum_of_digits > 9):
                return True
        return False

    def generate_answer_utility(cls, carry, temp_list, answer_string):
        if(all(v == 0 for v in temp_list)):
            if(carry > 0):
                answer_string = str(carry) + answer_string
            cls.answer_calculated_list.append(int(answer_string))
            answer_string = ''
            return
        sum_of_digits = carry
        for i in range(0, len(temp_list)):
            sum_of_digits = sum_of_digits + (temp_list[i] % 10)
            temp_list[i] = temp_list[i] // 10
        answer_string = str(sum_of_digits % 10) + answer_string
        temp_list_copy = list(temp_list)
        if(sum_of_digits > 9):
            cls.generate_answer_utility(sum_of_digits // 10, temp_list, answer_string)
        cls.generate_answer_utility(0, temp_list_copy, answer_string)

    def generate_answer(cls):
        cls.answer_calculated_list = []
        temp_list = list(cls.instance_no_list)
        cls.generate_answer_utility(0, temp_list, '')
        return cls.answer_calculated_list

    def generate_question(cls, no_of_numbers):

        question_generated = []
        no_of_digits = random.randint(1, 3)

        if(no_of_digits == 1):
            num1 = random.randint(5, 9)
            num2 = random.randint(5, 9)
        elif(no_of_digits == 2):
            digit_randomized = random.randint(1, 3)
            if(digit_randomized == 1):
                num1 = random.randint(5, 9) + random.randint(1, 9) * 10;
                num2 = random.randint(5, 9) + random.randint(1, 9) * 10;
            else:
                num1 = random.randint(1, 9) + random.randint(5, 9) * 10;
                num2 = random.randint(1, 9) + random.randint(5, 9) * 10;
        else:
            digit_randomized = random.randint(1, 4)
            if(digit_randomized == 1):
                num1 = random.randint(5, 9) + random.randint(1, 9) * 10 + random.randint(1, 9) * 100;
                num2 = random.randint(5, 9) + random.randint(1, 9) * 10 + random.randint(1, 9) * 100;
            elif(digit_randomized == 2):
                num1 = random.randint(1, 9) + random.randint(5, 9) * 10 + random.randint(1, 9) * 100;
                num2 = random.randint(1, 9) + random.randint(5, 9) * 10 + random.randint(1, 9) * 100;
            else:
                num1 = random.randint(1, 9) + random.randint(1, 9) * 10 + random.randint(5, 9) * 100;
                num2 = random.randint(1, 9) + random.randint(1, 9) * 10 + random.randint(5, 9) * 100;

        question_generated.append(num1)
        question_generated.append(num2)

        if(no_of_numbers > 2):
            number_left_to_generate = no_of_numbers - 2
            for i in range(0, number_left_to_generate):
                question_generated.append(random.randint(1, 999))
        return random.sample(question_generated, len(question_generated))

list1 = [99, 99, 99]
ac1 = AdditionCategory2(list1)
print(ac1.is_category_condition_satisfied())
print(ac1.generate_answer())
print(ac1.generate_question(len(list1)))


#!/usr/bin/env python
"""Test file for the physbiblio.webimport subpackage.

This file is part of the physbiblio package.
"""
import datetime
import os
import traceback
import unittest

import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry

try:
    from physbiblio.config import pbConfig
    from physbiblio.parseAccents import parse_accents_str
    from physbiblio.setuptests import *
    from physbiblio.webimport.webInterf import PBSession, WebInterf, physBiblioWeb
except ImportError:
    print("Could not find physbiblio and its modules!")
    raise
except Exception:
    print(traceback.format_exc())

@unittest.skipIf(skipTestsSettings.online, "Online tests")
class TestWebImportMethods(unittest.TestCase):
    """Test the functions that import entries from the web.
    Should not fail if everything works fine.
    """

    def test_methods_success(self):
        """Test webimport with known results"""
        self.maxDiff = None
        tests = {
            "arxiv": [
                "1507.08204",
                "@Article{1507.08204,\n         title = "
                + '"{Light sterile neutrinos}",\n          year = "2015",'
                + '\n archiveprefix = "arXiv",\n  primaryclass = '
                + '"hep-ph",\n           doi = '
                + '"10.1088/0954-3899/43/3/033001",\n      abstract = '
                + '"{The theory and phenomenology of light sterile neutrinos'
                + " at the eV mass scale is reviewed. The reactor, Gallium "
                + "and LSND anomalies are briefly described and interpreted "
                + "as indications of the existence of short-baseline "
                + "oscillations which require the existence of light sterile"
                + " neutrinos. The global fits of short-baseline oscillation"
                + " data in 3+1 and 3+2 schemes are discussed, together "
                + "with the implications for beta-decay and neutrinoless "
                + "double-beta decay. The cosmological effects of light "
                + "sterile neutrinos are briefly reviewed and the "
                + "implications of existing cosmological data are discussed."
                + " The review concludes with a summary of future "
                + 'perspectives.}",\n         arxiv = "1507.08204",\n    '
                + '   authors = "S. Gariazzo and C. Giunti and M. Laveder '
                + 'and Y. F. Li and E. M. Zavanin",\n}',
            ],
            "doi": [
                "10.1088/0954-3899/43/3/033001",
                """@article{Gariazzo_2015,
	doi = {10.1088/0954-3899/43/3/033001},
	url = {"""
                + pbConfig.doiUrl
                + """10.1088%2F0954-3899%2F43%2F3%2F033001},
	year = 2015,
	month = {mar},
	publisher = {{IOP} Publishing},
	volume = {43},
	number = {3},
	pages = {033001},
	author = {S Gariazzo and C Giunti and M Laveder and Y F Li and E M Zavanin},
	title = {Light sterile neutrinos},
	journal = {Journal of Physics G: Nuclear and Particle Physics}
}""",
            ],
            "inspire": [
                "Gariazzo:2015rra",
                """@article{Gariazzo:2015rra,
    author = "Gariazzo, S. and Giunti, C. and Laveder, M. and Li, Y. F. and Zavanin, E. M.",
    title = "{Light sterile neutrinos}",
    eprint = "1507.08204",
    archivePrefix = "arXiv",
    primaryClass = "hep-ph",
    doi = "10.1088/0954-3899/43/3/033001",
    journal = "J. Phys. G",
    volume = "43",
    pages = "033001",
    year = "2016"
}""",
            ],
        }
        for method, strings in tests.items():
            print(method)
            if method == "arxiv":
                self.assertEqual(
                    physBiblioWeb.webSearch[method]
                    .retrieveUrlFirst(strings[0], searchType="id")
                    .strip(),
                    strings[1].strip(),
                )
                self.assertEqual(
                    physBiblioWeb.webSearch[method]
                    .retrieveUrlAll(strings[0], searchType="id")
                    .strip(),
                    strings[1].strip(),
                )
            else:
                self.assertEqual(
                    physBiblioWeb.webSearch[method]
                    .retrieveUrlFirst(strings[0])
                    .strip(),
                    strings[1].strip(),
                )
                self.assertEqual(
                    physBiblioWeb.webSearch[method].retrieveUrlAll(strings[0]).strip(),
                    strings[1].strip(),
                )

    def test_methods_insuccess(self):
        """Test webimport using missing and/or invalid identifiers"""
        print(physBiblioWeb.webSearch.keys())
        self.maxDiff = None
        tests = {
            "arxiv": ["1801.15000", ""],
            "doi": ["10.1088/9999-3899/43/a/033001", ""],
            "inspire": ["Gariazzo:2014rra", ""],
        }
        self.assertFalse(physBiblioWeb.webSearch["inspire"].retrieveOAIData("9999999"))
        for method, strings in tests.items():
            print(method)
            res = physBiblioWeb.webSearch[method].retrieveUrlFirst(strings[0])
            print(res)
            self.assertEqual(res.strip(), strings[1].strip())
            self.assertEqual(
                physBiblioWeb.webSearch[method].retrieveUrlAll(strings[0]).strip(),
                strings[1].strip(),
            )

class TestWebImportOffline(unittest.TestCase):
    """Offline test for some functions of the webImport package."""

    def test_PBSession(self):
        """test the PBSession class"""
        pbs = PBSession()
        self.assertIsInstance(pbs, requests.Session)
        fr = Retry()
        ha = HTTPAdapter(max_retries=fr)
        with patch(
            "physbiblio.webimport.webInterf.Retry", return_value=fr
        ) as _r, patch(
            "physbiblio.webimport.webInterf.HTTPAdapter", return_value=ha
        ) as _ha, patch(
            "requests.Session.mount"
        ) as _m:
            pbs = PBSession()
            _r.assert_called_once_with(
                total=5,
                backoff_factor=1.0,
                status_forcelist=[429, 500, 502, 503, 504],
                allowed_methods=["HEAD", "GET", "OPTIONS"],
            )
            _ha.assert_called_once_with(max_retries=fr)
            _m.assert_any_call("https://", ha)
            _m.assert_any_call("http://", ha)

    def test_createUrl(self):
        """Test createUrl"""
        pbw = WebInterf()
        pbw.url = pbConfig.inspireLiteratureAPI
        pbw.urlArgs = {"abc": "1", "def": "2"}
        self.assertEqual(
            pbw.createUrl(), "https://inspirehep.net/api/literature/?abc=1&def=2"
        )
        self.assertEqual(
            pbw.createUrl({"abc": "2", "def": "1"}),
            "https://inspirehep.net/api/literature/?abc=2&def=1",
        )
        self.assertEqual(
            pbw.createUrl({}),
            "https://inspirehep.net/api/literature/",
        )
        self.assertEqual(
            pbw.createUrl({}, ""),
            "https://inspirehep.net/api/literature/",
        )
        self.assertEqual(
            pbw.createUrl({"def": "1"}, "abc"),
            "abc?def=1",
        )

    def test_inspire_retrieve(self):
        """Test retrieveUrlFirst and retrieveUrlAll from inspire module"""
        with patch(
            "physbiblio.webimport.inspire.WebSearch.retrieveBibtex",
            autospec=True,
            side_effect=["abc", "def"],
        ) as _f:
            self.assertEqual(
                physBiblioWeb.webSearch["inspire"].retrieveUrlFirst("abc"), "abc"
            )
            _f.assert_called_once_with(
                physBiblioWeb.webSearch["inspire"], "abc", size=1
            )
            _f.reset_mock()
            self.assertEqual(
                physBiblioWeb.webSearch["inspire"].retrieveUrlAll("abc"), "def"
            )
            _f.assert_called_once_with(
                physBiblioWeb.webSearch["inspire"], "abc", size=250
            )

    def test_arxivYear(self):
        """test the arxivDaily method in the arxiv module"""
        self.assertEqual(physBiblioWeb.webSearch["arxiv"].getYear("abc"), None)
        self.assertEqual(physBiblioWeb.webSearch["arxiv"].getYear("0123.345"), None)
        self.assertEqual(
            physBiblioWeb.webSearch["arxiv"].getYear("hep-ph/9900000"), "1999"
        )
        self.assertEqual(
            physBiblioWeb.webSearch["arxiv"].getYear("hep-ph/990000"), None
        )
        self.assertEqual(physBiblioWeb.webSearch["arxiv"].getYear("1234.5678"), "2012")
        self.assertEqual(physBiblioWeb.webSearch["arxiv"].getYear("1678.56789"), "2016")

    def test_arxivDaily(self):
        """test the arxivDaily method in the arxiv module"""
        with patch("logging.Logger.warning") as _w:
            self.assertFalse(physBiblioWeb.webSearch["arxiv"].arxivDaily("missing"))
            self.assertFalse(
                physBiblioWeb.webSearch["arxiv"].arxivDaily("physics.missing")
            )
        content_example = (
            """<?xml version="1.0" encoding="UTF-8"?>

<rdf:RDF
 xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
 xmlns="http://purl.org/rss/1.0/"
 xmlns:content="http://purl.org/rss/1.0/modules/content/"
 xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/"
 xmlns:dc="http://purl.org/dc/elements/1.1/"
 xmlns:syn="http://purl.org/rss/1.0/modules/syndication/"
 xmlns:admin="http://webns.net/mvcb/"
>

<channel rdf:about="http://arxiv.org/">
<title>hep-ex updates on arXiv.org</title>
<link>http://arxiv.org/</link>
<description rdf:parseType="Literal">High Energy Physics - """
            + """Experiment (hep-ex) updates on the arXiv.org e-print archive</description>
<dc:language>en-us</dc:language>
<dc:date>2018-05-23T20:30:00-05:00</dc:date>
<dc:publisher>www-admin@arxiv.org</dc:publisher>
<dc:subject>High Energy Physics - Experiment</dc:subject>
<syn:updateBase>1901-01-01T00:00+00:00</syn:updateBase>
<syn:updateFrequency>1</syn:updateFrequency>
<syn:updatePeriod>daily</syn:updatePeriod>
<items>
 <rdf:Seq>
  <rdf:li rdf:resource="http://arxiv.org/abs/1805.08875" />
  <rdf:li rdf:resource="http://arxiv.org/abs/1805.09166" />
  <rdf:li rdf:resource="http://arxiv.org/abs/1805.06430" />
 </rdf:Seq>
</items>
<image rdf:resource="http://arxiv.org/icons/sfx.gif" />
</channel>
<image rdf:about="http://arxiv.org/icons/sfx.gif">
<title>arXiv.org</title>
<url>http://arxiv.org/icons/sfx.gif</url>
<link>http://arxiv.org/</link>
</image>
<item rdf:about="http://arxiv.org/abs/1805.08875">
<title>Measurement of Transverse Single Spin Asymmetries. """
            + """(arXiv:1805.08875v1 [hep-ex])</title>
<link>http://arxiv.org/abs/1805.08875</link>
<description rdf:parseType="Literal">
In 2015 the first """
            + """collisions between polarized protons and nuclei occurred at
the Relativistic Heavy Ion Collider (RHIC), at a center-of-mass energy of
$\sqrt{s_{NN}}=200$ GeV. Comparisons between spin asymmetries and
cross-sections in $p+p$ production to those in $p+A$ production provide insight
into nuclear structure, namely nuclear modification factors, nuclear dependence
of spin asymmetries, and comparison to models with saturation effects. The
transverse single-spin asymmetry, $A_{N}$, has been measured in $\pi^{0}$
production in the STAR Forward Meson Spectrometer (FMS), an electromagnetic
calorimeter covering a forward psuedorapidity range """
            + """of $2.6&lt;\eta&lt;4$. Within
this kinematic range, STAR has previously reported the persistence of large
$\pi^0$ asymmetries with unexpected dependences on $p_T$ and event topology in
$p+p$ collisions. This talk will compare these dependences to those in $p+A$
production.

</description>
<dc:creator> Christopher Dilks """
            + """(STAR Collaboration)</dc:creator>
</item>
<item rdf:about="http://arxiv.org/abs/1805.09166">
<title>Recent Top quark results from the Tevatron. """
            + """(arXiv:1805.09166v1 [hep-ex] CROSS LISTED)</title>
<link>http://arxiv.org/abs/1805.09166</link>
<description rdf:parseType="Literal">
We present recent measurements

</description>
<dc:creator> """
            + """Boris Tuchming</dc:creator>
</item>
<item rdf:about="http://arxiv.org/abs/1805.06430">
<title>New Perspective on Hybrid Mesons. (arXiv:1805.06430v2 """
            + """[nucl-th] UPDATED)</title>
<link>http://arxiv.org/abs/1805.06430</link>
<description rdf:parseType="Literal">
It is thought that """
            + """strong interactions within the Standard Model can generate
bound-states in which non-Abelian gauge-bosons play a dual role, serving both
as force and matter fields.

</description>
<dc:creator> Shu-Sheng Xu, Zhu-Fang Cui, Lei Chang</"""
            + """a>, Joannis """
            + """Papavassiliou, Craig D. Roberts, Hong-Shi Zong"""
            + """</dc:creator>
</item>
</rdf:RDF>"""
        )
        with patch(
            "physbiblio.webimport.webInterf.WebInterf.textFromUrl",
            return_value=content_example,
            autospec=True,
        ) as _fromUrl, patch.dict(pbConfig.params, {"maxAuthorNames": 3}, clear=False):
            result = physBiblioWeb.webSearch["arxiv"].arxivDaily("hep-ex")
            _fromUrl.assert_called_once_with(
                physBiblioWeb.webSearch["arxiv"], "https://export.arxiv.org/rss/hep-ex"
            )
            self.assertEqual(
                result[0],
                {
                    "primaryclass": "hep-ex",
                    "author": "Christopher Dilks",
                    "title": "Measurement of Transverse Single Spin Asymmetries.",
                    "abstract": "In 2015 the first collisions between "
                    + "polarized protons and nuclei occurred at the "
                    + "Relativistic Heavy Ion Collider (RHIC), at a "
                    + "center-of-mass energy of $\\sqrt{s_{NN}}=200$ GeV. "
                    + "Comparisons between spin asymmetries and cross-sections "
                    + "in $p+p$ production to those in $p+A$ production "
                    + "provide insight into nuclear structure, namely "
                    + "nuclear modification factors, nuclear dependence "
                    + "of spin asymmetries, and comparison to models "
                    + "with saturation effects. The transverse single-spin "
                    + "asymmetry, $A_{N}$, has been measured in $\\pi^{0}$ "
                    + "production in the STAR Forward Meson Spectrometer "
                    + "(FMS), an electromagnetic calorimeter covering a "
                    + "forward psuedorapidity range of $2.6<\\eta<4$. "
                    + "Within this kinematic range, STAR has previously "
                    + "reported the persistence of large $\\pi^0$ asymmetries "
                    + "with unexpected dependences on $p_T$ and event topology "
                    + "in $p+p$ collisions. This talk will compare "
                    + "these dependences to those in $p+A$ production. ",
                    "cross": False,
                    "version": "1805.08875v1",
                    "eprint": "1805.08875",
                    "authors": ["Christopher Dilks"],
                    "replacement": False,
                },
            )
            self.assertEqual(
                result[1],
                {
                    "primaryclass": "hep-ex",
                    "author": "Boris Tuchming",
                    "title": "Recent Top quark results from the Tevatron.",
                    "abstract": "We present recent measurements ",
                    "cross": True,
                    "version": "1805.09166v1",
                    "eprint": "1805.09166",
                    "authors": ["Boris Tuchming"],
                    "replacement": False,
                },
            )
            self.assertEqual(
                result[2],
                {
                    "primaryclass": "nucl-th",
                    "author": "Shu-Sheng Xu and Zhu-Fang Cui and "
                    + "Lei Chang and others",
                    "title": "New Perspective on Hybrid Mesons.",
                    "abstract": "It is thought that strong interactions "
                    + "within the Standard Model can generate bound-states "
                    + "in which non-Abelian gauge-bosons play a dual role, "
                    + "serving both as force and matter fields. ",
                    "cross": True,
                    "version": "1805.06430v2",
                    "eprint": "1805.06430",
                    "authors": [
                        "Shu-Sheng Xu",
                        "Zhu-Fang Cui",
                        "Lei Chang",
                        "Joannis Papavassiliou",
                        "Craig D. Roberts",
                        "Hong-Shi Zong",
                    ],
                    "replacement": True,
                },
            )

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


from utility.util import MenuResponses
import pygame
import ctypes
from ConvertToPython import PythonConvertMenu
from mainmenu import MainMenu
from executeMenu import ExecuteMenu

# pygame yahoo
def main():
    myappid = u'alterra.software.simplehotkey.testing'  # arbitrary string
    ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)

    pygame.init()

    RES = (1080, 720)  # idek what resolution this is
    pygame.display.set_caption("Simple Hotkey (SHK)")
    window = pygame.display.set_mode(RES)
    fpsClock = pygame.time.Clock()
    fps = 60
    pcm = PythonConvertMenu(window, fpsClock, fps, RES)
    mm = MainMenu(window, fpsClock, fps, RES)
    em = ExecuteMenu(window, fpsClock, fps, RES)
    response = mm.run()
    while True:
        if response == MenuResponses.QUIT:
            return
        elif response == MenuResponses.EnterPCMMenu:
            pcm.reset()
            response = pcm.run()
        elif response == MenuResponses.EnterMainMenu:
            mm.reset()
            response = mm.run()
        elif response == MenuResponses.EnterExecuteMenu:
            em.reset()
            response = em.run()

if __name__ == "__main__":
    main()

    # since the pygame interface is currently not working, please just uncomment the code below when actually using SHK.
    # directoryToFile = input("What's the exact directory to the file you are converting? ")
    #
    # with open(directoryToFile) as f:
    #     pyhk = parse(f.read())
    #
    # print(pyhk)


"""
The test module for :mod:`algos.text` . Consists of a data class :class:`DataText` that stores expected inputs and
outputs for the different text based algorithms. The class also provides data for exception handling tests.

Each function in :mod:`algos.text` is assigned to a test class and the expected inputs and unexpected inputs tests are
performed within. The inputs and outputs are then tested in a parametrized fashion.
"""
import pytest
from algos.text import anagrams

class DataText:
    """
    Holds the data for :mod:`algos.text` .
    """
    anagrams__expected = [
        (
            {'the', 'car', 'can', 'caused', 'a', 'and', 'during', 'cried', 'by', 'its', 'rat', 'bowel', 'drinking',
             'elbow', 'bending', 'that', 'while', 'an', 'thing', 'cider', 'like', 'pain', 'cat', 'which', 'in', 'this',
             'act', 'below', 'is', 'night', 'arc'},
            [['act', 'cat'], ['arc', 'car'], ['below', 'bowel', 'elbow'], ['cider', 'cried'], ['night', 'thing']]
        ),
        (
            {"elbow", "below", "bowel"},
            [['below', 'bowel', 'elbow']]
        ),
        (
            {""},
            []
        )
    ]
    """
    Test cases for :func:`algos.text.anagrams`, testing that it functions correctly for expected inputs. The test
    cases are as follows

    +--------------------------------------+----------------------------------------------------------------------+
    | description                          | reason                                                               |
    +======================================+======================================================================+
    | many anagram lists                   | Test to see if multiple lists of anagrams are produced when input    |
    |                                      | set has multiple instances of different words which are anagrams of  |
    |                                      | each other.                                                          |
    +--------------------------------------+----------------------------------------------------------------------+
    | single anagram list                  | Test to see if a single set of anagrams is identified.               |
    +--------------------------------------+----------------------------------------------------------------------+
    | no anagrams                          | Test to see if a non-empty set with no anagrams produces no results  |
    +--------------------------------------+----------------------------------------------------------------------+

    """

    anagrams__unexpected = [
        (set(), [ValueError, "Empty Set"]),
        (["hello"], [TypeError, "Input Data Type Not Set"]),
        ({1, 2, 3}, [TypeError, "Not All Elements of Type str"])
    ]
    """
    Test cases for :func:`algos.text.anagrams`, testing that it raises an error for unexpected inputs. The test cases
    are as follows

    +--------------------------------------+----------------------------------------------------------------------+
    | description                          | reason                                                               |
    +======================================+======================================================================+
    | empty set input                      | Check that :class:`ValueError` is raised for empty input             |
    +--------------------------------------+----------------------------------------------------------------------+
    | incorrect input type                 | Check that :class:`TypeError` is raised if input is not a set        |
    +--------------------------------------+----------------------------------------------------------------------+
    | incorrect elements type              | Check that :class:`TypeError` is raised if any element of the set is |
    |                                      | not :class:`str` .                                                   |
    +--------------------------------------+----------------------------------------------------------------------+

    """

class TestAnagrams:
    """
    Class to test :func:`algos.text.anagrams` . Holds the expected input tests and exception handlings tests.
    """
    @pytest.mark.parametrize(
        "test_input,expected",
        DataText.anagrams__expected,
        ids=[str(v) for v in range(len(DataText.anagrams__expected))]
    )
    def test_anagrams__expected(self, test_input, expected):
        """
        Test that the :func:`algos.text.anagrams` function works properly for expected inputs. Test input can be found
        in :attr:`DataText.anagrams__expected` along with a description of their purpose.
        """
        # Assign a meaningful name to the test set.
        word_set = test_input

        # Find the anagrams.
        anagrams_found = anagrams(word_set)

        # Sort in order to compare generated anagrams against expected value.
        anagrams_found = [sorted(x) for x in anagrams_found]
        anagrams_found.sort()

        # Check that the output is as expected.
        assert anagrams_found == expected

    @pytest.mark.parametrize(
        "test_input,error",
        DataText.anagrams__unexpected,
        ids=[repr(v) for v in DataText.anagrams__unexpected]
    )
    def test_anagrams__unexpected(self, test_input, error):
        """
        Test that the :func:`algos.text.anagrams` raises exceptions for unexpected inputs. Test input can be found
        in :attr:`DataText.anagrams__unexpected` along with a description of their purpose.
        """
        # Check if error is raised.
        with pytest.raises(error[0]) as excinfo:
            anagrams(test_input)

        assert excinfo.match(error[1])