import sys
import gmpy2
import argparse

def xgcd(a, b):
    if b == 0:
        return 0,1,0

    u0 = 1
    u1 = 0
    v0 = 0
    v1 = 1

    while b != 0:
        q = a//b
        r = a - b * q
        u = u0 - q * u1
        v = v0 - q * v1
        #Update a,b
        a = b
        b = r
        #Update for next iteration
        u0 = u1
        u1 = u
        v0 = v1
        v1 = v

    return  a, u0, v0

def rsa(c1, c2, n, a, b, gcd):
    if(a < 0):
    	# invert(c1, n) -> c1_invert: c1 * c1_invert = 1 mod n
    	c1_inv = gmpy2.invert(c1, n)
    	c1 = pow(c1_inv, -a , n)
    else:
    	# tercer numero es el mod
    	c1 = pow(c1, a, n)

    if(b < 0):
        # invert(c1, n) -> c1_invert: c1 * c1_invert = 1 mod n
        c2_inv = gmpy2.invert(c2, n)
        c2 = pow(c2_inv, -b , n)

    else:
        c2 = pow(c2, b, n)

    cp = c2*c1 % n
    # True si la raiz es exacta
    m = gmpy2.iroot(cp, gcd)
    h=hex(m[0])

    return h[2:].decode('hex')

def main():
    print("RSA CTF - From n, e1, e2, c1 and c2 to m\n")
    parser = argparse.ArgumentParser()
    parser.add_argument("e1", metavar='e1', type=int, nargs='+', help='e1 value')
    parser.add_argument("e2", metavar='e2', type=int, nargs='+', help='e1 value')
    parser.add_argument("n", metavar='n', type=int, nargs='+', help='e1 value')
    parser.add_argument("c1", metavar='c1', type=int, nargs='+', help='e1 value')
    parser.add_argument("c2", metavar='c2', type=int, nargs='+', help='e1 value')
    args = parser.parse_args()

    e1, e2, n, c1, c2 = args.e1[0], args.e2[0], args.n[0], args.c1[0], args.c2[0]
    gcd, a, b = xgcd(e1, e2)
    resultado = rsa(c1, c2, n, a, b, gcd)

    print("---------------------------------------------")
    print("RSA message:")
    print(resultado)
    print("---------------------------------------------")

if __name__ == "__main__":
    main()


# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

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

"""Exceptions for the IonQ Provider."""

from qiskit.exceptions import QiskitError
from qiskit.providers import JobError, JobTimeoutError

class IonQError(QiskitError):
    """Base class for errors raised by an IonQProvider."""

    def __str__(self):
        return f"{self.__class__.__name__}({self.message!r})"

    def __repr__(self):
        return repr(str(self))

class IonQCredentialsError(IonQError):
    """Errors generated from bad credentials or config"""

class IonQClientError(IonQError):
    """Errors that arise from unexpected behavior while using IonQClient."""

class IonQAPIError(IonQError):
    """Base exception for fatal API errors.

    Attributes:
        status_code(int): An HTTP response status code.
        error_type(str): An error type string from the IonQ REST API.
    """

    @classmethod
    def from_response(cls, response):
        """Raise an instance of the exception class from an API response object.

        Args:
            response (:class:`Response <requests.Response>`): An IonQ REST API response.

        Raises:
            IonQAPIError: instance of `cls` with error detail from `response`.

        """
        status_code = response.status_code
        response_json = response.json()
        error = response_json.get("error") or {}
        raise cls(error.get("message"), status_code, error.get("type"))

    def __init__(self, message, status_code, error_type):
        self.status_code = status_code
        self.error_type = error_type
        super().__init__(message)

    def __str__(self):
        return (
            f"{self.__class__.__name__}("
            f"message={self.message!r},"
            f"status_code={self.status_code},"
            f"error_type={self.error_type!r})"
        )

class IonQBackendError(IonQError):
    """Errors generated from improper usage of IonQBackend objects."""

class IonQJobError(IonQError, JobError):
    """Errors generated from improper usage of IonQJob objects."""

class IonQGateError(IonQError, JobError):
    """Errors generated from invalid gate defs

    Attributes:
        gate_name: The name of the gate which caused this error.
    """

    def __init__(self, gate_name):
        self.gate_name = gate_name
        super().__init__(f"gate '{gate_name}' not supported")

    def __str__(self):
        return f"{self.__class__.__name__}(gate_name={self.gate_name!r})"

class IonQJobTimeoutError(IonQError, JobTimeoutError):
    """Errors generated from job timeouts"""

__all__ = [
    "IonQError",
    "IonQCredentialsError",
    "IonQClientError",
    "IonQAPIError",
    "IonQBackendError",
    "IonQJobError",
    "IonQGateError",
    "IonQJobTimeoutError",
]


class MethodMixin:
    def get_all_config(self):
        resp = self.request_list('GetAllConfig')
        config = {}
        for attr in resp:
            # If there is multiple attributes with the same name
            if attr['n'] in config:
                if isinstance(config[attr['n']], str):
                    config[attr['n']] = [config[attr['n']], attr['_content']]
                else:
                    config[attr['n']].append(attr['_content'])
            else:
                config[attr['n']] = attr['_content']
        return config

    def get_config(self, attr):
        resp = self.request_list('GetConfig', {'a': {'n': attr}})
        if len(resp) > 1:
            config = {attr: []}
            for a in resp:
                config[attr].append(a['_content'])
        elif len(resp) == 1:
            config = {attr: resp[0]['_content']}
        else:
            raise KeyError('{} not found'.format(attr))
        return config

    def modify_config(self, attr, value):
        self.request('ModifyConfig', {
            'a': {
                'n': attr,
                '_content': value
            }})
        if attr[0] == '-' or attr[0] == '+':
            attr = attr[1::]
        return self.get_config(attr)


import fire
import json
import logging
import os

import gensim.models
import numpy as np

from utils.recipe_handling import (
    parse_raw_recipes,
    filter_recipes,
    predict_recipes,
)

from utils.regression import (
    load_regression,
)

logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO"))

def evaluate(
    input_recipes_path: str,
    input_embedding_model_path: str,
    input_regression_model_path: str,
):
    # load Word2Vec & regression models
    embedding_model = gensim.models.Word2Vec.load(input_embedding_model_path)
    regression_model = load_regression(input_regression_model_path)

    # load recipes
    recipes_json = json.load(open(input_recipes_path, 'r'))
    logging.info(f'original #recipes: {len(recipes_json)}')

    # pre-process recipes
    recipes = parse_raw_recipes(recipes_json)
    recipes = filter_recipes(embedding_model, recipes)
    logging.info(f'filtered #recipes: {len(recipes)}')

    # predict recipe names
    predictions = predict_recipes(embedding_model, regression_model, recipes)

    # summarise
    num_recipes = len(predictions)
    top_1 = 0
    top_3 = 0
    for recipe, prediction in zip(recipes, predictions):
        if recipe['name'] == prediction[0][0]:
            top_1 += 1
        if recipe['name'] in [ name for name, score in prediction ]:
            top_3 += 1
    top_1_accuracy = top_1 / num_recipes
    top_3_accuracy = top_3 / num_recipes
    logging.info(f'Top-1 Accuracy: {top_1_accuracy} ({top_1}/{num_recipes})')
    logging.info(f'Top-3 Accuracy: {top_3_accuracy} ({top_3}/{num_recipes})')

if __name__ == '__main__':
    fire.Fire(evaluate)


import sys
import argparse
import numpy as np
import pandas as pd
import math
from joblib import dump, load
from sklearn.linear_model import LogisticRegression

def load_data(datafile):
    """Reads filename as a dataframe. Removes brackets from all vectors. Converts
       vectors from strings to arrays. Returns the columns (vectors and labels) of
       vectorfile_df.
    """
    vectorfile_df = pd.read_csv(datafile)
    vectors = [doc[1:-1] for doc in vectorfile_df['vector']]
    vectors = [np.fromstring(doc,sep=' ') for doc in vectors]
    vectorfile_df['vector'] = vectors

    vectors = np.stack(vectorfile_df['vector'])
    labels = np.stack(vectorfile_df['label'])

    return vectors,labels

def load_model(modelfile):
    """Loads and returns model from modelfile.
    """
    model = load(modelfile)

    return model

def accuracy(vectors,actual_labels,model):
    """Predicts labels for vectors by model. Compares predicted_labels with
       actual_labels. Calculates and returns (rounded) accuracy.
    """
    predicted_labels = model.predict(vectors)

    similar_labels = [i for i, j in zip(predicted_labels,actual_labels) if i == j]

    accuracy = round((len(similar_labels) / len(predicted_labels)) * 100,2)

    return accuracy

def perplexity(vectors,actual_labels,model):
    """Gets the probabilities for each class in model. Finds the probability of the
       actual class (label) of the n-gram, and calculates entropy and perplexity by
       this value. Returns perplexity.
    """

    probabilities = model.predict_proba(vectors)
    classes = model.classes_.tolist()

    probabilities_actual_labels = []
    for i,label in enumerate(actual_labels):
        if label in classes:
            index = classes.index(label)
            probability_actual_label = probabilities[i][index]
        else:
            probability_actual_label = 0.0000000001
        probabilities_actual_labels.append(probability_actual_label)

    total = 0
    for probability in probabilities_actual_labels:
        part = math.log2(probability)
        total += part
    total = -total
    entropy = total / len(actual_labels)
    perplexity = math.pow(2,entropy)

    return perplexity

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Test a maximum entropy model.")
    parser.add_argument("-N", "--ngram", metavar="N", dest="ngram", type=int,
                        default=3,
                        help="The length of ngram to be considered (default 3).")
    parser.add_argument("datafile", type=str,
                    help="The file name containing the features in the test data.")
    parser.add_argument("modelfile", type=str,
                    help="The name of the saved model file.")

    args = parser.parse_args()

    print("Loading data from file {}.".format(args.datafile))
    vectors,labels = load_data(args.datafile)
    print("Loading model from file {}.".format(args.modelfile))
    model = load_model(args.modelfile)

    print("Testing {}-gram model.".format(args.ngram))
    accuracy = accuracy(vectors,labels,model)
    perplexity = perplexity(vectors,labels,model)

    print("Accuracy is {}.".format(accuracy))
    print("Perplexity is {}.".format(perplexity))


#! /usr/bin/env python
from commander import Commander,Command
import commander
#commender comes from https://github.com/izderadicka/xmpp-tester.git
from threading import Thread
import threading

import serial
#import Queue #synced thread queues
import threading #threads for multiple serial ports
import time
#import binascii

if __name__=='__main__':
    class TestCmd(Command):
        def do_echo(self, *args):
            '''echo - Just echos all arguments'''
            return ' '.join(args)
        def do_raise(self, *args):
            raise Exception('Some Error')
        def do_add(self, *args):
            '''add numbers:\nadd 1 2 3'''
            out=0
            c.output("Adding:")
            for i in args:
                c.output(i)
                out=out+int(i)
            c.output("---------")
            return "Total: %s" % out
        def do_set(self, *args):
            '''set c.variables:\nset name1=param1 name2=param2'''
            txt=""
            for i in args:
                c.output(i)
                nme,par=i.split('=')
                setattr(c,nme,par)
            return txt
        def do_watch_set(self,*args):
            '''set dmx watch variable:\nwatch set dmx_chan1 dmx_chan2'''
            tmp_watch=[]
            for i in args:
                tmp_watch.append(int(i))
            setattr(c,"watch",tmp_watch)
        def do_watch_get(self,*args):
            '''print list of dmx watch channels'''
            return getattr(c,"watch")
        def do_get(self,*args):
            '''get c.variable'''
            return getattr(c,args[0])
        def do_test(self,*args):
            return c.output(args[0])
        def do_thread1_start(self,*args):
            '''start thread on serialX, optional paramater serial port:\nthread1_start /dev/ttyUSB0'''
            if args:
                t1_enable(args[0])
            else:
                t1_enable()
        def do_thread2_start(self,*args):
            '''start thread on serialX, optional paramater serial port:\nthread2_start /dev/ttyUSB0'''
            if args:
                t2_enable(args[0])
            else:
                t2_enable()
        def do_run(self,*args):
            '''enable test thread'''
            c.t.start()
        def do_start(self,*args):
            '''stop test thread'''
            c.t.do_run=True
        def do_stop(self,*args):
            '''stop test thread'''
            c.t.do_run=False
        def do_eval(self,*args):
            '''run eval on parameter, any python command, one param only'''
            return eval(args[0])
        def do_history(self,*args):
            '''dump list of command history'''
            return c.input.history
        def do_history_save(self,*args):
            import pickle
            with open('history_data.pkl', 'wb') as output:
                    pickle.dump(c.input.history, output, pickle.HIGHEST_PROTOCOL)
        def do_clear_buffer(self,*args):
            '''empty time buffer'''
            c.times_table=[]

    c=Commander('SENTINEL - SpEed aNd revoluTIoN mEter tooL', cmd_cb=TestCmd())
    PACKET_START=0xa5
    RDM_UID=0x24
    DMX_IN=0x04
    DMX_SNIFFER=0x34

    def make_buffer(type):
        buffer=bytearray(6)
        buffer[0]=PACKET_START
        buffer[1]=type
        buffer[2]=0x0
        buffer[3]=0x0
        buffer[4]=buffer[0]+buffer[1]
        buffer[5]=(sum(buffer)&0xff)
        return buffer

    #ser.write(make_buffer(RDM_UID))
    #ser.write(make_buffer(DMX_SNIFFER))

    #while ser.readable():
    dmx=bytearray(512)
    c.watch=[11,12]
    c.watch_time=time.time()
    save=[20,21]
    save_chan=36
    saved=False
    last=bytearray(512)

    def saving():
        global saved
        if len(save):
            if dmx[save_chan-1]!=0:
                if not saved:
                    saved=True
                    for i in save:
                        c.output("Saved DMX %s: %s" % (i,dmx[i-1]))
                        #.set_text="Saved DMX %s: %s" % (i,dmx[i-1])
                        c.output("%s" % c.telo[1])
            else:
                saved=False

    def difference():
        diff=False
        global last
        if len(c.watch):
            for i in c.watch:
                if last[i] != dmx[i-1]:
                    diff=True
                    last[i]=dmx[i-1]
            if diff:
                for i in c.watch:
                    c.output("Watched DMX %s: %s" % (i,dmx[i-1]))
                    c.watch_time=time.time()

    def process_data():
        difference()
        saving()
    def read_sensor(ser,c):
        c.times_table=[]
        while True:
            a=ser.readline()
            try:
                value,time_value=a.split('\t')
            except:
                continue
            if len(c.times_table)==4:
                c.times_table.pop(0)
            c.times_table.append(float(time_value.replace("\r\n","")))
            if len(c.times_table)==4:
                c.output("Average: %s" % str(sum(c.times_table)/float(len(c.times_table))),'green',3)
            c.output("Last: %s" % str(int(time_value.replace("\r\n",""))),'blue',2)
            c.output("Since DMX change: %s" % str(time.time()-c.watch_time),'magenta',4)
            c.output("Time buffer: %s" % str(c.times_table),'magenta',5)

    def read_runit(ser,c):
        ser.write(make_buffer(DMX_IN))
        time.sleep(.1)
        header=bytearray(5)
        catch_header=0
        catch_data=False
        data=0
        while True:
            a=ser.read()
            #if ord(a) !=0:
            #    print ord(a)
            #print ord(a)
            if catch_data==False:
                if ord(a)==165: #packet start
                    #print "start"
                    header=bytearray(5) #reset
                    header[0]=a
                    catch_header=1
                else:
                    if catch_header:
                        if catch_header<4:
                            header[catch_header]=a
                            catch_header+=1
                        elif catch_header==4: #header full, check
                            chsum=sum(header[0:4])
                            header[catch_header]=a
                            if chsum==ord(a):
                                #print "OK"
                                catch_data=True
                                catch_header=0
                                data=0
            else:
                if data==header[3] << 8 | header[2]: #data length
                #if data==512:
                    data=0
                    catch_header=0
                    catch_data=False
                    ttlchsum=(sum(dmx)+sum(header)) & 0xff
                    if ttlchsum==ord(a): #full frame
                        process_data()
                else:
                    dmx[data]=a
                    data+=1
            #a=ord(ser.read())
            #print a
            #if a !=0:
            #    print a

    #read_runit(serial0)
    #read_sensor(serial1)

    #queue = Queue.Queue(1000)
    def t1_enable(ser='/dev/ttyACM0'):
        c.serial1=serial.Serial(ser,115200)
        c.thread1 = threading.Thread(target=read_runit, args=(c.serial1,c),)
        c.thread1.daemon=True
        c.thread1.start()
        c.output("thread 1 started")
    def t2_enable(ser='/dev/ttyUSB0'):
        c.serial2=serial.Serial(ser,115200)
        c.thread2 = threading.Thread(target=read_sensor, args=(c.serial2,c),)
        c.thread2.daemon=True
        c.thread2.start()
        c.output("thread 2 started")

    #Test asynch output -  e.g. comming from different thread
    def run():
        t = threading.currentThread()
        time.sleep(1)
        c.output('Empty', 'green')
        while getattr(t, "do_run", True):
            time.sleep(1)
            c.output('Tick', 'green')
    c.t=Thread(target=run)
    c.t.daemon=True
    #c.t.start()
    c.last_redraw=time.time()
    c.force_redraw=False

    def tick(self=c):
        while True:
            time.sleep(0.5)
            if self.eloop and self._eloop_thread != threading.current_thread():
                if (time.time()- self.last_redraw)>0.1:
                    if self.force_redraw:
                        self.last_redraw=time.time()
                        self.eloop.draw_screen()
                        self.force_redraw=False

    t0=Thread(target=tick)
    t0.daemon=True
    t0.start()
    #start main loop
    c.loop()


from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk import  RegexpTokenizer
import re

def regex_clean_ruidos(text):
    '''
        função manual para eliminação de ruídos através de regex, descartar qualquer coisa
        que na composição possua uma 'não letra', como símbolos e números...

        Ex: ',ola' - '...'  - 'email@alguem'
    '''
    return ' '.join([
        t for t in text.strip().split() if re.match(r'[^\W\d]*$', t)
    ])

def regex_clean(text):

    '''
        função pronta da lib NLTK para limpeza de ruído
    '''
    return regex_clean_ruidos(
        ' '.join(RegexpTokenizer(r'\w+').tokenize(text)).lower()
    )

def make_tokens(text, lang):

    stop_words = set(stopwords.words(lang))

    word_tokens = word_tokenize(
        regex_clean(text) #Vai tirar algumas impurezas do texto, como números e alguns simbolos
    )

    filtered_sentence = [w for w in word_tokens if not w in stop_words]

    filtered_sentence = []

    for w in word_tokens:
        if w not in stop_words:
            filtered_sentence.append(w)
    return ' '.join(filtered_sentence)


import io
import picamera
import logging
import socketserver
from threading import Condition
from http import server
import deepspeech_demo

PAGE="""\

<title>FOCUS</title>

Bill, Your Anti-Procrastinator

 Speak
        <input type="text" id='wordsIn'>
        <button name="send" value="false">send</button>

"""

class StreamingOutput(object):
    def __init__(self):
        self.frame = None
        self.buffer = io.BytesIO()
        self.condition = Condition()

    def write(self, buf):
        if buf.startswith(b'\xff\xd8'):
            # New frame, copy the existing buffer's content and notify all
            # clients it's available
            self.buffer.truncate()
            with self.condition:
                self.frame = self.buffer.getvalue()
                self.condition.notify_all()
            self.buffer.seek(0)
        return self.buffer.write(buf)

class StreamingHandler(server.BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/':
            self.send_response(301)
            self.send_header('Location', '/index.html')
            self.end_headers()
        elif self.path == '/index.html':
            content = PAGE.encode('utf-8')
            self.send_response(200)
            self.send_header('Content-Type', 'text/html')
            self.send_header('Content-Length', len(content))
            self.end_headers()
            self.wfile.write(content)
        elif self.path == '/stream.mjpg':
            self.send_response(200)
            self.send_header('Age', 0)
            self.send_header('Cache-Control', 'no-cache, private')
            self.send_header('Pragma', 'no-cache')
            self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=FRAME')
            self.end_headers()
            try:
                while True:
                    global output #needs to be a global to operate properly!!
                    with output.condition:
                        output.condition.wait()
                        frame = output.frame
                    self.wfile.write(b'--FRAME\r\n')
                    self.send_header('Content-Type', 'image/jpeg')
                    self.send_header('Content-Length', len(frame))
                    self.end_headers()
                    self.wfile.write(frame)
                    self.wfile.write(b'\r\n')
            except Exception as e:
                logging.warning(
                    'Removed streaming client %s: %s',
                    self.client_address, str(e))
        else:
            self.send_error(404)
            self.end_headers()

class StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer):
    allow_reuse_address = True
    daemon_threads = True

output = StreamingOutput()

def main(ARGS):
    model = deepspeech_demo.setup(ARGS)
    vad_audio = deepspeech_demo.VADAudio(aggressiveness=ARGS.vad_aggressiveness,
                         device=ARGS.device,
                         input_rate=ARGS.rate,
                         file=ARGS.file)
    print("Listening (ctrl-C to exit)...")

    not_active = True
    while not_active:
        frames = vad_audio.vad_collector()
        not_active = deepspeech_demo.interpret(ARGS,model,frames)
    print("done")
    with picamera.PiCamera(resolution='640x480', framerate=24) as camera:
        global output
        camera.start_recording(output, format='mjpeg')
        try:
            address = ('', 8000)
            server = StreamingServer(address, StreamingHandler)
            server.serve_forever()
        finally:
            camera.stop_recording()

if __name__ == '__main__':
    DEFAULT_SAMPLE_RATE = 16000

    import argparse
    parser = argparse.ArgumentParser(description="Stream from microphone to DeepSpeech using VAD")

    parser.add_argument('-v', '--vad_aggressiveness', type=int, default=2,
                        help="Set aggressiveness of VAD: an integer between 0 and 3, 0 being the least aggressive about filtering out non-speech, 3 the most aggressive. Default: 3")
    parser.add_argument('--nospinner', action='store_true',
                        help="Disable spinner")
    parser.add_argument('-w', '--savewav',
                        help="Save .wav files of utterences to given directory")
    parser.add_argument('-f', '--file',
                        help="Read from .wav file instead of microphone")

    parser.add_argument('-m', '--model', required=True,
                        help="Path to the model (protocol buffer binary file, or entire directory containing all standard-named files for model)")
    parser.add_argument('-s', '--scorer',
                        help="Path to the external scorer file.")
    parser.add_argument('-d', '--device', type=int, default=None,
                        help="Device input index (Int) as listed by pyaudio.PyAudio.get_device_info_by_index(). If not provided, falls back to PyAudio.get_default_device().")
    parser.add_argument('-r', '--rate', type=int, default=DEFAULT_SAMPLE_RATE,
                        help=f"Input device sample rate. Default: {DEFAULT_SAMPLE_RATE}. Your device may require 44100.")

    ARGS = parser.parse_args()
    if ARGS.savewav: os.makedirs(ARGS.savewav, exist_ok=True)
    main(ARGS)


import os
print(os.getcwd())

from . import check_host
from . import check_port

import nmap

print('--nmapScan-')

def nmapScan(args):
    # choose mode
    mode_choices = {
        'intense':' -T4 -A -v ',
        'intense_udp':' -sS -sU -T4 -A -v ',
        'intense_all_tcp':' -p 1-65535 -T4 -A -v ',
        'intense_no_ping':' -T4 -A -v -Pn ',
        'ping':' -sn ',
        'quick':' -T4 -F ',
        'quick_plus':' -sV -T4 -O -F --version-light ',
        'quick_trace':' -sn --traceroute ',
        'regular':' ',
        'slow_comp':' -sS -sU -T4 -A -v -PE -PP -PS80,443 -PA3389 -PU40125 -PY -g 53 --script "default or (discovery and safe)" '
    }

    tcp_choices = {
        'ACK':'-sA',
        'FIN':'-sF',
        'Maimon':'-sM',
        'Null':'-sN',
        'SYN':'-sS',
        'Connect':'-sT',
        'Window':'-sW',
        'Xmas':'-sX'
    }

    nontcp_choices = {
        'UDP':'-sU',
        'IP':'-sO',
        'List':'-sL',
        'Ping':'-sn',
        'SCTP INIT':'-sY',
        'SCTP COOKIE-ECHO':'-sZ'
    }

    host = args.pop('host')
    port = args.pop('port')
    mode = args.pop('mode')
    tcp  = args.pop('tcp')
    nontcp = args.pop('nontcp')

    if mode is not None:
        arguments = mode_choices[mode]
    else:
        arguments = ''

    if tcp is not None:
        arguments += tcp_choices[tcp]

    if nontcp is not None:
        arguments += nontcp_choices[nontcp]

    for v in args.values():
        if v is not None:
            arguments += " "
            arguments += v

    # check host
    try:
        check_host.check_host(host)
    except check_host.HostError:
        code = 400
        message = 'HostError: wrong host'
        return code, message

    # check port
    if port is not None:
        # check ports
        if (arguments.find('sO')>=0):
            # ip protocol scan
            ip_flag = 1
        else:
            ip_flag = 0

        try:
            check_port.check_port(port, ip_flag)
        except check_port.PortError as e:
            code = 400
            message = e.value
            return code, message

    try:
        nm = nmap.PortScanner()
        result = nm.scan(host, port, arguments, True)
    except nmap.nmap.PortScannerError as e:
        result = e.value
        code = 400
    else:
        code = 200

    return code, result


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

from odoo import models, fields, api
from odoo.exceptions import UserError, ValidationError

class AddAmountDifference(models.Model):
    _inherit = 'account.invoice'

    def action_register_inbound_payment(self):
        payment_form = self.env.ref('account.view_account_payment_invoice_form', False)
        return {
            'name': '登记收款',
            'type': 'ir.actions.act_window',
            'view_type': 'form',
            'view_mode': 'form',
            'res_model': 'account.payment',
            'view_id': payment_form.id,
            'target': 'new',
            'context': {'default_invoice_ids': [(4, self.id, None)]},
        }

class AccountAbstractPayment(models.AbstractModel):
    _inherit = "account.abstract.payment"

    writeoff_save_id = fields.Many2many('account.account', string="Difference Account",
                                        domain=[('deprecated', '=', False)], copy=False)
    total_price = fields.Monetary(string="金额总计", default=0.0)

class AccountAccount(models.Model):
    _inherit = "account.account"

    money = fields.Monetary(string="金额", defaule=0.0)
    remark = fields.Char(string="标签", default="Write-Off")
    self_amount = fields.Float(string=u'本币金额')
    currencys_id = fields.Many2one('res.currency', string='币种')

class AccountPayment(models.Model):
    _inherit = "account.payment"

    received_price = fields.Float(string='本币金额')
    unit_id = fields.Many2one('res.currency', string='Currency', required=True,
                              default=lambda self: self.env.user.company_id.currency_id)
    self_amount = fields.Float(string=u'收付款本币金额')
    flag = fields.Char(string=u'标识', default=0, store=True)

    @api.depends('invoice_ids', 'amount', 'payment_date', 'currency_id', 'total_price', 'self_amount')
    def _compute_payment_difference(self):
        self.flag = 0
        for pay in self.filtered(lambda p: p.invoice_ids):
            payment_amount = -pay.amount if pay.payment_type == 'outbound' else pay.amount
            payment_total = -pay.total_price if pay.payment_type == 'outbound' else pay.total_price
            pay.payment_difference = pay._compute_payment_amount() - payment_amount - payment_total
            total = pay._compute_payment_amount()
            if payment_amount != total:
                self.flag = 1

    @api.onchange('writeoff_save_id')
    def _compute_total_price(self):
        self.total_price = 0
        if self.writeoff_save_id:
            for count in self.writeoff_save_id:
                self.total_price += count.money

    @api.onchange('writeoff_save_id', 'currency_id')
    def _get_currency_value(self):
        for cur in self.writeoff_save_id:
            cur.currencys_id = self.currency_id

    @api.onchange('currency_id')
    def _clear_writeoff_id(self):
        """
        再次更改货币单位时，差异明细行的记录清除
        :return:
        """
        for i in self.writeoff_save_id:
            self.writeoff_save_id = [(2, i.id)]

    def action_validate_inbound_payment(self):
        """
        登记收款验证方法
        """
        if any(len(record.invoice_ids) != 1 for record in self):
            # For multiple invoices, there is account.register.payments wizard
            raise UserError("这个方法只被用来处理单个发票的支付。")
        return self.inbound_post()

    @api.multi
    def inbound_post(self):
        """ Create the journal items for the payment and update the payment's state to 'posted'.
            A journal entry is created containing an item in the source liquidity account (selected journal's default_debit or default_credit)
            and another in the destination reconcilable account (see _compute_destination_account_id).
            If invoice_ids is not empty, there will be one reconcilable move line per invoice to reconcile with.
            If the payment is a transfer, a second journal entry is created in the destination journal to receive money from the transfer account.
        """
        for rec in self:

            if rec.state != 'draft':
                raise UserError("只有草稿付款才能被发布。")

            if any(inv.state != 'open' for inv in rec.invoice_ids):
                raise ValidationError("因为发票不是打开状态所以付款不能完成!")

            # keep the name in case of a payment reset to draft
            if not rec.name:
                # Use the right sequence to set the name
                if rec.payment_type == 'transfer':
                    sequence_code = 'account.payment.transfer'
                else:
                    if rec.partner_type == 'customer':
                        if rec.payment_type == 'inbound':
                            sequence_code = 'account.payment.customer.invoice'
                        if rec.payment_type == 'outbound':
                            sequence_code = 'account.payment.customer.refund'
                    if rec.partner_type == 'supplier':
                        if rec.payment_type == 'inbound':
                            sequence_code = 'account.payment.supplier.refund'
                        if rec.payment_type == 'outbound':
                            sequence_code = 'account.payment.supplier.invoice'
                rec.name = self.env['ir.sequence'].with_context(ir_sequence_date=rec.payment_date).next_by_code(
                    sequence_code)
                if not rec.name and rec.payment_type != 'transfer':
                    raise UserError("你需要定义公司的%s序列." % (sequence_code,))

            # Create the journal entry
            amount = rec.amount * (rec.payment_type in ('outbound', 'transfer') and 1 or -1)
            move = rec._create_inbound_payment_entry(amount)

            # In case of a transfer, the first journal entry created debited the source liquidity account and credited
            # the transfer account. Now we debit the transfer account and credit the destination liquidity account.
            if rec.payment_type == 'transfer':
                transfer_credit_aml = move.line_ids.filtered(
                    lambda r: r.account_id == rec.company_id.transfer_account_id)
                transfer_debit_aml = rec._create_transfer_entry(amount)
                (transfer_credit_aml + transfer_debit_aml).reconcile()

            rec.write({'state': 'posted', 'move_name': move.name})
        return True

    def _create_inbound_payment_entry(self, amount):
        """ Create a journal entry corresponding to a payment, if the payment references invoice(s) they are reconciled.
            Return the journal entry.
        """
        # super(AccountPayment)._create_payment_entry(amount)
        aml_obj = self.env['account.move.line'].with_context(check_move_validity=False)
        debit, credit, amount_currency, currency_id = aml_obj.with_context(
            date=self.payment_date)._compute_amount_fields(
            amount, self.currency_id, self.company_id.currency_id)
        move = self.env['account.move'].create(self._get_move_vals())
        # print('payment_move', move)

        # Write line corresponding to invoice payment
        counterpart_aml_dict = self._get_shared_move_line_vals(debit, credit, amount_currency, move.id, False)
        counterpart_aml_dict.update(self._get_counterpart_move_line_vals(self.invoice_ids))
        counterpart_aml_dict.update({'currency_id': currency_id})

        if self.self_amount > 0 and credit > 0:
            counterpart_aml_dict.update({'credit': self.self_amount})
        elif self.self_amount > 0 and debit > 0:
            counterpart_aml_dict.update({'debit': self.self_amount})
        counterpart_aml = aml_obj.create(counterpart_aml_dict)
        # print('payment1', counterpart_aml_dict)

        # Reconcile with the invoices
        if self.payment_difference_handling == 'reconcile' and self.writeoff_save_id:
            # print("reconcile")
            for acc in self.writeoff_save_id:
                writeoff_line = self._get_shared_move_line_vals(0, 0, 0, move.id, False)
                debit_wo, credit_wo, amount_currency_wo, currency_id = aml_obj.with_context(
                    date=self.payment_date)._compute_amount_fields(self.payment_difference, self.currency_id,
                                                                   self.company_id.currency_id)
                writeoff_line['name'] = acc.remark
                writeoff_line['account_id'] = acc.id
                writeoff_line['amount_currency'] = amount_currency_wo
                writeoff_line['currency_id'] = currency_id

                if acc.self_amount > 0:
                    if debit_wo > 0:
                        writeoff_line['debit'] = acc.self_amount
                        writeoff_line['credit'] = credit_wo
                    elif credit_wo > 0:
                        writeoff_line['debit'] = debit_wo
                        writeoff_line['credit'] = acc.self_amount
                else:
                    if debit_wo > 0:
                        writeoff_line['debit'] = acc.money
                        writeoff_line['credit'] = credit_wo
                    elif credit_wo > 0:
                        writeoff_line['debit'] = debit_wo
                        writeoff_line['credit'] = acc.money

                writeoff_line = aml_obj.create(writeoff_line)
                # print('reconcile_move', writeoff_line)

                # 采购
                if counterpart_aml['debit'] or (writeoff_line['credit'] and not counterpart_aml['credit']):
                    counterpart_aml['debit'] += credit_wo - debit_wo
                # 销售
                if counterpart_aml['credit'] or (writeoff_line['debit'] and not counterpart_aml['debit']):
                    counterpart_aml['credit'] += debit_wo - credit_wo
                counterpart_aml['amount_currency'] -= amount_currency_wo

        if self.payment_difference_handling == 'open' and self.writeoff_save_id:
            # print("open")
            for acc in self.writeoff_save_id:
                writeoff_line = self._get_shared_move_line_vals(0, 0, 0, move.id, False)

                debit_wo, credit_wo, amount_currency_wo, currency_id = aml_obj.with_context(
                    date=self.payment_date)._compute_amount_fields(acc.money, self.currency_id,
                                                                   self.company_id.currency_id)
                writeoff_line['name'] = acc.remark
                writeoff_line['account_id'] = acc.id
                writeoff_line['amount_currency'] = amount_currency_wo
                writeoff_line['currency_id'] = currency_id

                if acc.self_amount > 0:
                    if debit_wo > 0:
                        writeoff_line['debit'] = acc.self_amount
                        writeoff_line['credit'] = credit_wo
                    elif credit_wo > 0:
                        writeoff_line['debit'] = debit_wo
                        writeoff_line['credit'] = acc.self_amount
                else:
                    if debit_wo > 0:
                        writeoff_line['debit'] = debit_wo
                        writeoff_line['credit'] = credit_wo
                    elif credit_wo > 0:
                        writeoff_line['debit'] = debit_wo
                        writeoff_line['credit'] = credit_wo
                # print("writeoff_line", writeoff_line)
                writeoff_line = aml_obj.create(writeoff_line)

                if counterpart_aml['debit'] or (writeoff_line['credit'] and not counterpart_aml['credit']):
                    counterpart_aml['debit'] += writeoff_line['credit'] - writeoff_line['debit']
                    counterpart_aml['amount_currency'] = abs(counterpart_aml['amount_currency']) + writeoff_line[
                        'amount_currency']
                if counterpart_aml['credit'] or (writeoff_line['debit'] and not counterpart_aml['debit']):
                    # 发票付款记录金额加上金额差异记录金额
                    counterpart_aml['credit'] += writeoff_line['debit'] - writeoff_line['credit']
                    counterpart_aml['amount_currency'] = counterpart_aml['amount_currency'] - writeoff_line[
                        'amount_currency']

        # Write counterpart lines
        if not self.currency_id.is_zero(self.amount):
            if not self.currency_id != self.company_id.currency_id:
                amount_currency = 0
            liquidity_aml_dict = self._get_shared_move_line_vals(credit, debit, -amount_currency, move.id, False)
            # print('liquidity_aml_dict', liquidity_aml_dict)
            liquidity_aml_dict.update(self._get_liquidity_move_line_vals(-amount))
            if self.self_amount > 0 and liquidity_aml_dict['debit'] > 0:
                liquidity_aml_dict.update({'debit': self.self_amount})
            elif self.self_amount > 0 and liquidity_aml_dict['credit'] > 0:
                liquidity_aml_dict.update({'credit': self.self_amount})
            aml_obj.create(liquidity_aml_dict)
            # print('payment2', liquidity_aml_dict)

        # validate the payment
        if not self.journal_id.post_at_bank_rec:
            move.post()

        # reconcile the invoice receivable/payable line(s) with the payment
        if self.invoice_ids:
            self.invoice_ids.register_payment(counterpart_aml)

        # 金额差异修改默认值为0
        account_list = self.env['account.account'].search(['|', ('money', '!=', 0), ('self_amount', '!=', 0)])
        for i in account_list:
            if i.money:
                i.money = 0
            if i.remark != "Write-Off":
                i.remark = "Write-Off"
            if i.self_amount:
                i.self_amount = 0
        return move

class AccountMove(models.Model):
    _inherit = "account.move"

    @api.multi
    def assert_balanced(self):
        if not self.ids:
            return True
        prec = self.env.user.company_id.currency_id.decimal_places

        self._cr.execute("""\
            SELECT      move_id
            FROM        account_move_line
            WHERE       move_id in %s
            GROUP BY    move_id
            HAVING      abs(sum(debit) - sum(credit)) > %s
            """, (tuple(self.ids), 10 ** (-max(5, prec))))
        if len(self._cr.fetchall()) != 0:
            pass
            # raise UserError(_("Cannot create unbalanced journal entry."))
        return True


import sys
import subprocess
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox
from PyQt5.QtGui import QCursor
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import QUrl, Qt
from PyQt5.QtWebEngineWidgets import QWebEngineView

class MyApp(QWidget):

	def __init__(self):
		super().__init__()
		QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
		self.initUI()

	def closeEvent(self, event):

		msg_box = QMessageBox()
		msg_box.setIcon(QMessageBox.Warning)
		msg_box.setWindowTitle("Alert")
		msg_box.setText("Are you sure you want to exit the program?")
		msg_box.setWindowIcon(QIcon("resources/icons/trello.ico"))
		msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)

		retval = msg_box.exec_()

		if retval == QMessageBox.Yes:
			event.accept()
		else:
			event.ignore()

	def initUI(self):

		self.web = QWebEngineView()
		self.web.setWindowTitle("Trello")
		self.web.setWindowIcon(QIcon("resources/icons/trello.ico"))
		self.web.load(QUrl("https://trello.com/"))
		self.web.showMaximized()
		self.web.setContextMenuPolicy(Qt.NoContextMenu)
		self.web.show()
		self.web.loadFinished.connect(self.webpageLoaded)

		self.web.closeEvent = self.closeEvent

	def webpageLoaded(self):
		QApplication.restoreOverrideCursor()

def hide_console():
		import win32gui, win32con

		cmd_terminal = win32gui.GetForegroundWindow()
		win32gui.ShowWindow(cmd_terminal , win32con.SW_HIDE)

if __name__ == '__main__':
	hide_console()

	app = QApplication(sys.argv)
	my_app = MyApp()
	sys.exit(app.exec_())


#!/usr/bin/env python

import sys
import matplotlib.pyplot as plt
import argparse
from utilities import filesFromList, inputIfNone
from plotTools import userLabels, plotXX
'''
Description: A script to plot multiple files with data in [x, y1, y2, ..., yn] format.
Run the script in the directory where you have the data files:
$ uniplot.py <search string> [options]

Author: Mikko Auvinen
        mikko.auvinen@helsinki.fi
        University of Helsinki &
        Finnish Meteorological Institute
'''
#=======MAIN PROGRAM========================================#
parser = argparse.ArgumentParser()
parser.add_argument("strKey", nargs='?', default=None,\
  help="Search string for collecting files.")
parser.add_argument("--log", action="store_true", default=False,\
  help="Logarithmic y-axis.")
parser.add_argument("--labels", action="store_true", default=False,\
  help="User specified labels.")
parser.add_argument("-fx", "--factorX", type=float, default=1.0,\
  help="Multiplication factor for x-values: fx*x")
parser.add_argument("-fy", "--factorY", type=float, default=1.0,\
  help="Multiplication factor for y-values: fy*y")
parser.add_argument("-s", "--save", type=str, default=None, \
  help="Name of the saved figure. Default=None")
args = parser.parse_args()
#==========================================================#
# Rename ...
strKey  = args.strKey
factorX = args.factorX
factorY = args.factorY
logOn   = args.log
labelsOn= args.labels
saveFig = args.save

strKey = inputIfNone( strKey , " Enter search string: " )

plt.rc('xtick', labelsize=24); #plt.rc('ytick.major', size=10)
plt.rc('ytick', labelsize=24); #plt.rc('ytick.minor', size=6)

while 1:

  fileNos, fileList = filesFromList( "*"+strKey+"*" )

  pfig = plt.figure(num=1, figsize=(12.,9.5));
  for fn in fileNos:
    pfig = plotXX( pfig, fileList[fn], logOn, factorX, factorY )

  if( labelsOn ):
    pfig = userLabels( pfig )
  plt.grid(True)
  plt.legend(loc=0)

  if( saveFig ):
    pfig.savefig( saveFig, format='jpg', dpi=300)

  plt.show()


#!/usr/bin/env python3
'''
    booksdatasource.py
    Jeff Ondich, 18 September 2018

    For use in some assignments at the beginning of Carleton's
    CS 257 Software Design class, Fall 2018.
'''

import csv
from operator import itemgetter

def scanner(file):
    '''parses the csv file and returns an array of csv rows'''
    Data = []
    with open(file, newline='') as f:
        # reader takes in the csv file
        reader = csv.reader(f)
        # copies all the information from the csv file into a new list
        for row in reader:
            Data.append(row)
    return Data

class BooksDataSource:
    '''
    A BooksDataSource object provides access to data about books and authors.
    The particular form in which the books and authors are stored will
    depend on the context (i.e. on the particular assignment you're
    working on at the time).

    Most of this class's methods return Python lists, dictionaries, or
    strings representing books, authors, and related information.

    An author is represented as a dictionary with the keys
    'id', 'last_name', 'first_name', 'birth_year', and 'death_year'.
    For example, Jane Austen would be represented like this
    (assuming her database-internal ID number is 72):

        {'id': 72, 'last_name': 'Austen', 'first_name': 'Jane',
         'birth_year': 1775, 'death_year': 1817}

    For a living author, the death_year is represented in the author's
    Python dictionary as None.

        {'id': 77, 'last_name': 'Murakami', 'first_name': 'Haruki',
         'birth_year': 1949, 'death_year': None}

    Note that this is a simple-minded representation of a person in
    several ways. For example, how do you represent the birth year
    of Sophocles? What is the last name of Gabriel García Márquez?
    Should we refer to the author of "Tom Sawyer" as Samuel Clemens or
    Mark Twain? Are Voltaire and Molière first names or last names? etc.

    A book is represented as a dictionary with the keys 'id', 'title',
    and 'publication_year'. For example, "Pride and Prejudice"
    (assuming an ID of 132) would look like this:

        {'id': 193, 'title': 'A Wild Sheep Chase', 'publication_year': 1982}

    '''

    def __init__(self, books_filename, authors_filename, books_authors_link_filename):
        ''' Initializes this data source from the three specified  CSV files, whose
            CSV fields are:

                books: ID,title,publication-year
                  e.g. 6,Good Omens,1990
                       41,Middlemarch,1871

                authors: ID,last-name,first-name,birth-year,death-year
                  e.g. 5,Gaiman,Neil,1960,NULL
                       6,Pratchett,Terry,1948,2015
                       22,Eliot,George,1819,1880

                link between books and authors: book_id,author_id
                  e.g. 41,22
                       6,5
                       6,6

                  [that is, book 41 was written by author 22, while book 6
                    was written by both author 5 and author 6]

            Note that NULL is used to represent a non-existent (or rather, future and
            unknown) year in the cases of living authors.

            NOTE TO STUDENTS: I have not specified how you will store the books/authors
            data in a BooksDataSource object. That will be up to you, in Phase 3.
        '''

        self.booksFile = scanner(books_filename)
        self.authorsFile = scanner(authors_filename)
        self.linkFile = scanner(books_authors_link_filename)
        self.authorsList = []
        self.booksList = []
        self.bookLink =[]
        self.authorLink = []

        dictionary = {}
        for row in self.booksFile:
            dictionary = {'id': int(row[0]), 'title': row[1], 'publication_year': int(row[2])}
            self.booksList.append(dictionary)

        dictionary = {}
        for row in self.authorsFile:
            dictionary = {'id': int(row[0]), 'last_name': row[1], 'first_name': row[2],
            'birth_year': int(row[3]), 'death_year': int(row[4])}
            self.authorsList.append(dictionary)

        i = 0
        for row in self.linkFile:
            if i == int(row[0]):
                self.bookLink.append([int(row[1])])
                i += 1

            else:
                self.bookLink[int(row[0])].append(int(row[1]))
            self.authorLink.append("null")

        for row in self.linkFile:
            if self.authorLink[int(row[1])] == "null":
                self.authorLink[int(row[1])] = [int(row[0])]
            else:

                self.authorLink[int(row[1])].append(int(row[0]))

        pass

    def book(self, book_id):
        ''' Returns the book with the specified ID. (See the BooksDataSource comment
            for a description of how a book is represented.) '''

        '''A book is represented as a dictionary with the keys 'id', 'title',
        and 'publication_year'. For example, "Pride and Prejudice"
        (assuming an ID of 132) would look like this:

            {'id': 193, 'title': 'A Wild Sheep Chase', 'publication_year': 1982}

        '''

        # returns the the specified book using the book_id
        return self.booksList[book_id].copy()

    def books(self, *, author_id=None, search_text=None, start_year=None, end_year=None, sort_by='title'):
        ''' Returns a list of all the books in this data source matching all of
            the specified non-None criteria.

                author_id - only returns books by the specified author
                search_text - only returns books whose titles contain (case-insensitively) the search text
                start_year - only returns books published during or after this year
                end_year - only returns books published during or before this year

            Note that parameters with value None do not affect the list of books returned.
            Thus, for example, calling books() with no parameters will return JSON for
            a list of all the books in the data source.

            The list of books is sorted in an order depending on the sort_by parameter:

                'year' -- sorts by publication_year, breaking ties with (case-insenstive) title
                default -- sorts by (case-insensitive) title, breaking ties with publication_year

            See the BooksDataSource comment for a description of how a book is represented.
        '''

        # creates new list to input the full book list into
        books_matching_criteria = self.booksList

        # questions if author_id is inputted and returns books that match value
        if author_id != None:
            books_matching_criteria = self.list_by_author_id(author_id)
        # questions if search_text is inputted and returns books that match value
        if search_text != None:
            books_matching_criteria = self.list_by_search_text(books_matching_criteria, search_text)
        # questions if start_year is inputted and returns books that match value
        if start_year != None or end_year != None:
            books_matching_criteria = self.list_by_year(books_matching_criteria, start_year, end_year)
        # sorts by year if the sort_by value is 'year'
        if sort_by == 'year':
            books_matching_criteria = self.sort_by_year(books_matching_criteria)
        # sorts by title if the sort value is anything else
        else:
            books_matching_criteria = self.sort_by_title(books_matching_criteria)

        # returns resulting book list sorted by terms
        return books_matching_criteria

    # author_id is inputted and books that contain the same author_id are appended into a list
    def list_by_author_id(self, author_id):

        booksReturn = []
        for bookId in self.authorLink[int(author_id)]:
            booksReturn.append(self.booksList[int(bookId)])

        return booksReturn

    # returns books that contain search text in title
    def list_by_search_text(self, bookList, string):
        newList = []

        for x in bookList:

            if (x['title'].upper()).find(string.upper()) > -1:
                newList.append(x)
        return newList

    # returns books that were published between start and/or end year
    def list_by_year(self, bookList, start_year, end_year):
        newList = []

        for x in bookList:
            if (x['publication_year'] >= start_year or start_year == None) and (x['publication_year'] <= end_year or end_year == None):
                newList.append(x)
        return newList

    # sorts the books titles alphabetically breaks ties by publication year
    def sort_by_title(self, bookList):
        bookList1 = sorted(bookList, key=lambda k: k['publication_year'])
        bookList2 = sorted(bookList1, key=lambda k: k['title'])
        return bookList2

    # sorts the books by publication year and then sorts the titles alphabetically during ties
    def sort_by_year(self, bookList):
        bookList1 = sorted(bookList, key=lambda k: k['title'])
        bookList2 = sorted(bookList1, key=lambda k: k['publication_year'])
        return bookList2

    def author(self, author_id):
        ''' Returns the author with the specified ID. (See the BooksDataSource comment for a
            description of how an author is represented.)
            An author is represented as a dictionary with the keys
            'id', 'last_name', 'first_name', 'birth_year', and 'death_year'.
            For example, Jane Austen would be represented like this
            (assuming her database-internal ID number is 72):

                {'id': 72, 'last_name': 'Austen', 'first_name': 'Jane',
                 'birth_year': 1775, 'death_year': 1817}

            For a living author, the death_year is represented in the author's
            Python dictionary as None.

                {'id': 77, 'last_name': 'Murakami', 'first_name': 'Haruki',
                 'birth_year': 1949, 'death_year': None} '''

        return self.authorsList[author_id].copy()

    def authors(self, *, book_id=None, search_text=None, start_year=None, end_year=None, sort_by='birth_year'):

        ''' Returns a list of all the authors in this data source matching all of the
            specified non-None criteria.

                book_id - only returns authors of the specified book
                search_text - only returns authors whose first or last names contain
                    (case-insensitively) the search text
                start_year - only returns authors who were alive during or after
                    the specified year
                end_year - only returns authors who were alive during or before
                    the specified year

            Note that parameters with value None do not affect the list of authors returned.
            Thus, for example, calling authors() with no parameters will return JSON for
            a list of all the authors in the data source.

            The list of authors is sorted in an order depending on the sort_by parameter:

                'birth_year' - sorts by birth_year, breaking ties with (case-insenstive) last_name,
                    then (case-insensitive) first_name
                any other value - sorts by (case-insensitive)
                last_name, breaking ties with
                    (case-insensitive) first_name, then birth_year

            See the BooksDataSource comment for a description of how an author is represented.
        '''
        authorsReturn = self.authorsList

        # Checks to see which arguments are given and passes the list of authors
        # through each applicable function

        if book_id != None:
            authorsReturn = self.list_by_book_id(book_id)
        if search_text != None:
            authorsReturn = self.list_by_search_text_author(authorsReturn, search_text)
        if start_year != None or end_year != None:
            authorsReturn = self.list_by_year_author(authorsReturn, start_year, end_year)
        if sort_by == 'birth_year':
            authorsReturn = self.sort_by_birth_year(authorsReturn)
        else:
            authorsReturn = self.sort_by_else(authorsReturn)

        return authorsReturn

    # Returns a list of authors that have written a specific book given a book id
    def list_by_book_id(self, book_id):

        authorsReturn = []
        for authorId in self.bookLink[int(book_id)]:
            authorsReturn.append(self.authorsList[int(authorId)])

        return authorsReturn

    # Returns a list of authors with a string in their first or last name
    # given a list to search through and a string to look for in the author's names
    def list_by_search_text_author(self, authorsList, string):
        newList = []

        for x in authorsList:

            last = (x['last_name'].upper()).find(string.upper())
            first = (x['first_name'].upper()).find(string.upper())
            if last > -1 or first > -1:
                newList.append(x)
        return newList

    # Returns a list of authors that were alive during a time period given
    # a start year and end year and list of authors
    def list_by_year_author(self, authorsList, start_year, end_year):

        newList = []
        for x in authorsList:
            if (int((x['death_year']) >= int(start_year) or start_year == None) and (x['birth_year'] <= int(end_year) or end_year == None)):
                newList.append(x)
        return newList

    # Sorts a list of authors by birthyear then last name then first name
    def sort_by_birth_year(self, authorsList):

        authorsList1 = sorted(authorsList, key=lambda k: k['first_name'])
        authorsList2 = sorted(authorsList1, key=lambda k: k['last_name'])
        authorsList3 = sorted(authorsList2, key=lambda k: k['birth_year'])
        return authorsList3

    # Sorts a list of authors by last name then first name then birth year
    def sort_by_else(self, authorsList):

        authorsList1 = sorted(authorsList, key=lambda k: k['birth_year'])
        authorsList2 = sorted(authorsList1, key=lambda k: k['first_name'])
        authorsList3 = sorted(authorsList2, key=lambda k: k['last_name'])
        return authorsList3

    def books_for_author(self, author_id):
        ''' Returns a list of all the books written by the author with the specified author ID.
            See the BooksDataSource comment for a description of how an book is represented. '''
        return self.books(author_id=author_id)

    def authors_for_book(self, book_id):
        ''' Returns a list of all the authors of the book with the specified book ID.
            See the BooksDataSource comment for a description of how an author is represented. '''
        return self.authors(book_id=book_id)


import pygame
from pygame.locals import *
from random import *

# Now our own modules
from MyTank import *
from EnemyTank import *
from Grass import *
from EnemyTank import *
from SoftBrick import *
from HardBrick import *
from Bullet import *
class Bullet(pygame.sprite.Sprite):
	bDead = False
	points = 10
	speed = 0
	arrImages = []
	arrRunImages = []
	arrExplodeImages = []
	idx = 0
	count = 0
	arrFPs = [5,5, 5, 5, 2]
	state = 0
	gvr = None
	owner = None

	#CONSTANTS
	UP=0
	DOWN=1
	LEFT=2
	RIGHT=3
	EXPLOSION=4

	def __init__(self, owner,
		imgRunArray, imgExplodeArray, x, y, direction, gvr):
		self.owner = owner
		pygame.sprite.Sprite.__init__(self)
		self.state = direction
		self.arrRunImages = imgRunArray
		self.arrExplodeImages = imgExplodeArray
		self.arrImages = self.arrRunImages
		self.image = self.arrRunImages[0]
		self.rect = self.image.get_rect()
		self.rect = Rect((x,y), (self.rect.width, self.rect.height))
		self.gvr = gvr
		self.speed = self.gvr.MAX_MY_SPEED * 1
		gvr.lstSprites.add(self)
		gvr.lstBullets.add(self)

	def hit(self):
		if self.state!=self.EXPLOSION:
			self.state = self.EXPLOSION
			self.arrImages = self.arrExplodeImages
			self.idx = 0
		self.gvr.lstBullets.remove(self)
		# note: explosion stage 11 pictures
		# this is to prevent triggering hit many times
		# also avoid triggering hit of tank many times

	def update(self):
		if(self.rect.top<10 or \
				self.rect.top>self.gvr.HEIGHT-10 or \
				self.rect.left<0 or \
				self.rect.left>self.gvr.BATTLEFIELD_WIDTH-10):
			self.hit()
		self.image = self.arrImages[self.idx]
		if self.state==self.UP:
			self.rect.move_ip(0, -self.speed)
		elif self.state==self.DOWN:
			self.rect.move_ip(0, self.speed)
		elif self.state==self.LEFT:
			self.rect.move_ip(-self.speed,0)
		elif self.state==self.RIGHT:
			self.rect.move_ip(self.speed,0)
		else:
			if(self.idx==len(self.arrImages)-1):
				self.kill()
		self.count = (self.count + 1) % 10000
		if self.count% self.arrFPs[self.state]==0:
			self.idx = (self.idx+1)%len(self.arrImages)


import shelve

__author__ = 'Girish'

from scrapper.Snippet import Snippet
from scrapper.DataFinder import DataFinder
import json

import sys
if len(sys.argv) <2:
    print("Havent entered the name of the question")
    sys.exit(-1)
data =0
try:
    with open("data") as store:
        if store.readable():
            data = int(store.read())
        else:
            print("you dont have to permission to read or write")
            sys.exit(0)
except PermissionError:
    print("no permission to read the file")
except Exception:
    pass

try:
    def find(name,data):
        name = name.lower()
        name = name.strip()
        with shelve.open("data",writeback=True) as data_store:
            if name in data_store.keys():
                return data, data_store[name]

            disp =["\\",'|','/','-']

            datafetcher = DataFinder("http://www.spoj.com/problems/classical/sort=0,start={start}",start=data)
            html_snippet = Snippet(Snippet.SPOJ)
            ind=0
            for i in datafetcher.get_page():
                for w in html_snippet.get_data_dicts(i):
                    data_store[w['name'].lower()] = w['id']

                    if w['name'].lower() == name:
                        return data,w['id']
                    print("\r{} indexing ..{} ".format(disp[ind],w['id']),end="")
                    ind+=1
                    ind%=4
                    data+=1
            return None,None

    data,id_ = find(sys.argv[1],data)
    print(data)
    print("the ID of the question is ",id_)

except KeyboardInterrupt:
    with open("data","w") as file:
    	print("Writing to the file")
    	file.write(str(50*(data//50)))
else:
    with open("data","w") as file:
        file.write(str(50*(data//50)))


# Python bytecode 2.7 (decompiled from Python 2.7)
# Embedded file name: e:\jenkins\workspace\client_SERENITY\branches\release\SERENITY\packages\trinity\sceneRenderJobSpaceEmbedded.py
import logging
from . import _trinity as trinity
from .sceneRenderJobSpace import SceneRenderJobSpace
logger = logging.getLogger(__name__)

def CreateEmbeddedRenderJobSpace(name=None, stageKey=None):
    newRJ = SceneRenderJobSpaceEmbedded()
    if name is not None:
        newRJ.ManualInit(name)
    else:
        newRJ.ManualInit()
    newRJ.SetMultiViewStage(stageKey)
    return newRJ

class SceneRenderJobSpaceEmbedded(SceneRenderJobSpace):
    renderStepOrder = ['PUSH_RENDER_TARGET', 'PUSH_DEPTH_STENCIL']
    renderStepOrder += SceneRenderJobSpace.renderStepOrder
    renderStepOrder += ['POP_RENDER_TARGET', 'POP_DEPTH_STENCIL', 'COPY_TO_BLIT_TEXTURE', 'PUSH_BLIT_DEPTH', 'SET_BLIT_VIEWPORT', 'SET_BLENDMODE', 'FINAL_BLIT_EMBEDDED', 'POP_BLIT_DEPTH']

    def _ManualInit(self, name):
        self.stencilBlitEffect = None
        self.stencilPath = ''
        self.SetupStencilBlitEffect()
        self.isOffscreen = False
        self.doFinalBlit = True
        self.offscreenRenderTarget = None
        self.offscreenDepthStencil = None
        self.finalTexture = None
        self.rtWidth = 0
        self.rtHeight = 0
        self.blitViewport = trinity.TriViewport()
        SceneRenderJobSpace._ManualInit(self, name)
        self.updateJob = None
        self.useTAA = False
        return

    def SetupStencilBlitEffect(self):
        self.stencilBlitEffect = trinity.Tr2Effect()
        self.stencilBlitEffect.effectFilePath = 'res:/Graphics/Effect/Managed/Space/system/BlitStencil.fx'
        stencilMap = trinity.TriTextureParameter()
        stencilMap.name = 'StencilMap'
        stencilMap.resourcePath = self.stencilPath
        self.stencilBlitEffect.resources.append(stencilMap)
        self.blitMapParameter = trinity.TriTextureParameter()
        self.blitMapParameter.name = 'BlitSource'
        self.stencilBlitEffect.resources.append(self.blitMapParameter)

    def SetOffscreen(self, isOffscreen):
        self.isOffscreen = isOffscreen

    def SetStencil(self, path=None):
        self.stencilPath = path
        self.SetupStencilBlitEffect()
        self.EnableStep('CLEAR')
        self._RefreshAntiAliasing()
        self._CreateRenderTargets()
        self._RefreshRenderTargets()

    def EnableFXAA(self, enable):
        pass

    def _DoPrepareResources(self):
        self.useDepth = trinity.GetShaderModel().endswith('DEPTH')
        self.prepared = True
        self.SetSettingsBasedOnPerformancePreferences()

    def DoReleaseResources(self, level):
        self.finalTexture = None
        self.offscreenRenderTarget = None
        self.offscreenDepthStencil = None
        self.blitMapParameter.SetResource(None)
        SceneRenderJobSpace.DoReleaseResources(self, level)
        return

    def DoPrepareResources(self):
        if not self.enabled or not self.canCreateRenderTargets:
            return
        try:
            self._DoPrepareResources()
        except trinity.D3DERR_OUTOFVIDEOMEMORY:
            log.LogException()
            self.DoReleaseResources(1)

    def _GetSettings(self):
        currentSettings = SceneRenderJobSpace._GetSettings(self)
        currentSettings['postProcessingQuality'] = 0
        return currentSettings

    def _SetSettingsBasedOnPerformancePreferences(self):
        SceneRenderJobSpace._SetSettingsBasedOnPerformancePreferences(self)
        self.usePostProcessing = False
        self.distortionEffectsEnabled = False

    def _GetSourceRTForPostProcessing(self):
        if self.msaaEnabled or self.hdrEnabled:
            return self.customBackBuffer
        return self.finalTexture

    def _GetDestinationRTForPostProcessing(self):
        if self.customBackBuffer is not None:
            return self.customBackBuffer
        elif self.offscreenRenderTarget is not None:
            return self.offscreenRenderTarget
        else:
            return

    def _CreateRenderTargets(self):
        if not self.prepared:
            return
        else:
            SceneRenderJobSpace._CreateRenderTargets(self)
            vp = self.GetViewport()
            self.rtWidth = vp.width
            self.rtHeight = vp.height
            if self.customBackBuffer is None:
                self.offscreenRenderTarget = trinity.Tr2RenderTarget(vp.width, vp.height, 1, self.bbFormat)
                self.finalTexture = self.offscreenRenderTarget
            else:
                self.finalTexture = trinity.Tr2RenderTarget(vp.width, vp.height, 1, self.customBackBuffer.format)
            if self.customDepthStencil is None:
                self.offscreenDepthStencil = trinity.Tr2DepthStencil(vp.width, vp.height, trinity.DEPTH_STENCIL_FORMAT.AUTO)
            self.finalTexture.name = 'finalTexture'
            return

    def SetRenderTargets(self, *args):
        SceneRenderJobSpace.SetRenderTargets(self, *args)
        self.RemoveStep('PUSH_RENDER_TARGET')
        self.RemoveStep('PUSH_DEPTH_STENCIL')
        self.RemoveStep('POP_RENDER_TARGET')
        self.RemoveStep('POP_DEPTH_STENCIL')
        self.RemoveStep('SET_BLIT_VIEWPORT')
        self.RemoveStep('COPY_TO_BLIT_TEXTURE')
        self.RemoveStep('FINAL_BLIT_EMBEDDED')
        self.RemoveStep('PUSH_BLIT_DEPTH')
        self.RemoveStep('POP_BLIT_DEPTH')
        viewport = self.GetViewport()
        if viewport is not None:
            vpStep = self.GetStep('SET_VIEWPORT')
            if vpStep is not None:
                vpOrigin = trinity.TriViewport(0, 0, viewport.width, viewport.height)
                vpStep.viewport = vpOrigin
        if self.offscreenDepthStencil:
            self.AddStep('PUSH_DEPTH_STENCIL', trinity.TriStepPushDepthStencil(self.offscreenDepthStencil))
            self.AddStep('POP_DEPTH_STENCIL', trinity.TriStepPopDepthStencil())
        if self.offscreenRenderTarget:
            self.AddStep('PUSH_RENDER_TARGET', trinity.TriStepPushRenderTarget(self.offscreenRenderTarget))
            self.AddStep('POP_RENDER_TARGET', trinity.TriStepPopRenderTarget())
        self.AddStep('PUSH_BLIT_DEPTH', trinity.TriStepPushDepthStencil(None))
        self.RemoveStep('FINAL_BLIT')
        if self.customBackBuffer is not None and self.finalTexture is not None:
            step = trinity.TriStepResolve(self.finalTexture, self.customBackBuffer)
            step.name = 'Resolve: finalTexture <== customBackBuffer'
            self.AddStep('COPY_TO_BLIT_TEXTURE', step)
        if self.doFinalBlit:
            self.AddStep('SET_BLIT_VIEWPORT', trinity.TriStepSetViewport(viewport))
            if self.finalTexture:
                if self.stencilPath is None or self.stencilPath == '':
                    self.AddStep('FINAL_BLIT_EMBEDDED', trinity.TriStepRenderTexture(self.finalTexture))
                else:
                    stencilTriTextureRes = trinity.TriTextureRes()
                    stencilTriTextureRes.SetFromRenderTarget(self.finalTexture)
                    self.blitMapParameter.SetResource(stencilTriTextureRes)
                    self.AddStep('FINAL_BLIT_EMBEDDED', trinity.TriStepRenderEffect(self.stencilBlitEffect))
        self.AddStep('POP_BLIT_DEPTH', trinity.TriStepPopDepthStencil())
        return

    def GetBackBufferSize(self):
        vp = self.GetViewport()
        return (
         vp.width, vp.height)

    def DoFinalBlit(self, enabled):
        self.doFinalBlit = enabled

    def UpdateViewport(self, viewport):
        if viewport.width != self.rtWidth or viewport.height != self.rtHeight:
            self._CreateRenderTargets()
            self._RefreshRenderTargets()

    def _GetRTForDepthPass(self):
        if self.finalTexture is not None:
            return self.finalTexture
        else:
            return SceneRenderJobSpace._GetRTForDepthPass(self)

    def ApplyBaseSettings(self):
        SceneRenderJobSpace.ApplyBaseSettings(self)
        self.gpuParticlesEnabled = False


import time

class Dijkstras:

    def __init__(self, tiles, start, stop, gui):
        self.tiles = tiles
        self.leftToVisit = len(self.tiles) * len(self.tiles[0]) - 1 # subtract the start node
        self.startNode = start
        self.stopNode = stop
        self.gui = gui
        self.running = False # defines if the algorithm is still not finished
        self.frontierNodes = [self.startNode] # the tiles that are currently exploring - initialize with startNode

    # do one algorithm step. returns None if path cannot be found; returns PathfindingTile array if path was found
    def step(self):
        self.running = True

        if len(self.frontierNodes) == 0: # no frontier nodes - can't explore any further and therefore cannot find a path
            self.running = False

            return None

        frontiers = self.frontierNodes.copy()
        self.frontierNodes = [] # reset frontiers so the for loop below is not an endless loop

        for node in frontiers:
            self.explore_nodes_around(node) # generate frontier nodes

        return self.check_frontier_nodes()

    # explore all the nodes around a tile
    def explore_nodes_around(self, tile):
        # create a "square" around the current node and takes care of boundaries
        for x in range(max(0, tile.x - 1), min(len(self.tiles), tile.x + 2)):
            for y in range(max(0, tile.y - 1), min(len(self.tiles[0]), tile.y + 2)):
                t = self.tiles[x][y]

                if (tile.x == x and tile.y == y) or t.visited(): # the tile itself or if the tile was already visited => skip it
                    continue

                if t.solid: # tile is a solid block, skip it
                    t.distance = -2 # set it to a number which signalizes that the tile has been visited
                    continue

                distance = self.calculate_distance_between(tile, t)

                if t.distance > distance or t.distance == -1: # shorter path detected; override the previous tile plus distance
                    t.previous = tile
                    t.distance = distance + t.distance if t.distance != -1 else distance # override infinity setting

                if t in self.frontierNodes: # only got better path - do nothing further
                    continue

                self.leftToVisit -= 1
                current = self.gui.get_rectangle(x, y)

                if self.gui.start != current and self.gui.stop != current: # do not color the start/stop node
                    current.setColor('yellow')

                if t not in self.frontierNodes:
                    self.frontierNodes.append(t)

        if tile.x != self.startNode.x or tile.y != self.startNode.y: # color the frontier node gray unless it's the start node
            self.gui.get_rectangle(tile.x, tile.y).setColor('gray')

    # check frontier nodes if the stop node has been hit - do this after exploration to ensure we pick the best path
    def check_frontier_nodes(self):
        for node in self.frontierNodes:
            if node.stop: # node is stop node
                self.running = False
                return self.get_path(node)

        return None

    def get_path(self, tile):
        tiles = [tile]

        while(tile.previous is not None):
            tile = tile.previous
            tiles.append(tile)

        return tiles

    # two cases: direct neighbours or diagonal neighbours
    def calculate_distance_between(self, tile1, tile2):
        absX = abs(tile1.x - tile2.x)
        absY = abs(tile1.y - tile2.y)

        if (absX == 0 and absY == 1) or (absX == 1 and absY == 0): # direct
            return 1

        if absX == 1 and absY == 1: # diagonal
            return 1.4 # ~ square root of 2

        return 0

class PathfindingTile:
    def __init__(self, start=False, stop=False, solid=False, x=0, y=0):
        self.start = start
        self.stop = stop
        self.solid = solid
        self.x = x
        self.y = y

        # Dijkstra's related
        self.distance = 0 if start else -1 # every tile except start has the distance of infinity (or -1 in this case)
        self.previous = None

    def visited(self):
        return self.distance != -1 # if distance has been set - should be infinity if not discovered yet
    # def __eq__(self, value):
    #     return self.x == value.x and self.y == value.y


import numpy as np

def get_params():
    params = {
            "integration_step": 2e-3,
            "random_seed": 0,
            "goal_radius": 2,
            "sst_delta_near": 0.5,
            "sst_delta_drain": 0.1,
            "width": 1,
            "min_time_steps": 50,
            "max_time_steps": 500,
            "number_of_iterations": 600000,

            "max_planning_time": 500
            }

    return params


"""empty message

Revision ID: 8cf10c9efd0e
Revises: 7bee80c80442
Create Date: 2020-01-04 18:44:27.644419

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '8cf10c9efd0e'
down_revision = '7bee80c80442'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('reference', sa.Column('published_day', sa.Integer(), nullable=True))
    op.add_column('reference', sa.Column('published_era_fk', sa.Integer(), nullable=True))
    op.add_column('reference', sa.Column('published_month_fk', sa.Integer(), nullable=True))
    op.add_column('reference', sa.Column('published_year', sa.Integer(), nullable=True))
    op.drop_constraint('reference_month_fk_fkey', 'reference', type_='foreignkey')
    op.drop_constraint('reference_era_fk_fkey', 'reference', type_='foreignkey')
    op.create_foreign_key(None, 'reference', 'era', ['published_era_fk'], ['id'])
    op.create_foreign_key(None, 'reference', 'month', ['published_month_fk'], ['id'])
    op.drop_column('reference', 'month_fk')
    op.drop_column('reference', 'year')
    op.drop_column('reference', 'day')
    op.drop_column('reference', 'era_fk')
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('reference', sa.Column('era_fk', sa.INTEGER(), autoincrement=False, nullable=True))
    op.add_column('reference', sa.Column('day', sa.INTEGER(), autoincrement=False, nullable=True))
    op.add_column('reference', sa.Column('year', sa.INTEGER(), autoincrement=False, nullable=True))
    op.add_column('reference', sa.Column('month_fk', sa.INTEGER(), autoincrement=False, nullable=True))
    op.drop_constraint(None, 'reference', type_='foreignkey')
    op.drop_constraint(None, 'reference', type_='foreignkey')
    op.create_foreign_key('reference_era_fk_fkey', 'reference', 'era', ['era_fk'], ['id'])
    op.create_foreign_key('reference_month_fk_fkey', 'reference', 'month', ['month_fk'], ['id'])
    op.drop_column('reference', 'published_year')
    op.drop_column('reference', 'published_month_fk')
    op.drop_column('reference', 'published_era_fk')
    op.drop_column('reference', 'published_day')
    # ### end Alembic commands ###


import numpy as np
import pandas as pd

# 非劣解を取り出す（高速実装が面倒なのでライブラリからコピー）
def nondominated(costs, return_mask = True):
    """
    Find the pareto-efficient points
    :param costs: An (n_points, n_costs) array
    :param return_mask: True to return a mask
    :return: An array of indices of pareto-efficient points.
        If return_mask is True, this will be an (n_points, ) boolean array
        Otherwise it will be a (n_efficient_points, ) integer array of indices.
    """
    is_efficient = np.arange(costs.shape[0])
    n_points = costs.shape[0]
    next_point_index = 0  # Next index in the is_efficient array to search for
    while next_point_index<len(costs):
        nondominated_point_mask = np.any(costs<costs[next_point_index], axis=1)
        nondominated_point_mask[next_point_index] = True
        is_efficient = is_efficient[nondominated_point_mask]  # Remove dominated points
        costs = costs[nondominated_point_mask]
        next_point_index = np.sum(nondominated_point_mask[:next_point_index])+1
    if return_mask:
        is_efficient_mask = np.zeros(n_points, dtype = bool)
        is_efficient_mask[is_efficient] = True
        return is_efficient_mask
    else:
        return is_efficient

# 非劣解，及び元データにおける非劣解インデックスを返す(最小化問題を仮定)
# ユーザーが希望する科が一致するという条件の基，できるだけ距離が近い/混雑度が近い病院を取り出す
# 希望する科が一致する病院が最初から存在しなければ，それ抜きで考える．
# obj type: pandas.dataframe
def ndextract_main(obj):
    objvalue = obj.values
    # 希望する科が一致する病院のインデックスを取り出す
    if 'match_expert' in obj.columns:
        match_expert_index = np.array(obj['match_expert'].values.tolist(), dtype=bool)
    else:
        match_expert_index = np.ones(len(objvalue), dtype=bool)

    # 希望する科が一致する病院の中で非劣解をとりだす
    if np.any(match_expert_index):
        nondominated_index = nondominated(objvalue[match_expert_index]).tolist()
        i = 0
        for index, bool_value in enumerate(match_expert_index):
            if bool_value:
                if not nondominated_index[i]:
                    match_expert_index[index] = not match_expert_index[index]
                i = i + 1
        nondominated_index = match_expert_index
    else:
        print('No hospital matching users desired expert.')
        nondominated_index = nondominated(objvalue).tolist()

    return nondominated_index, obj[nondominated_index]

if __name__ == "__main__":
    # テスト用データファイル
    objfile = 'testdata/dtlz1Rand_4obj.dat'
    objvalue = np.loadtxt(objfile, delimiter=', ')
    objname = ['col'+str(i) for i in range(1, objvalue.shape[1]+1)]
    obj = pd.DataFrame(-objvalue, columns=objname)
    nondominated_index, nondominated_solutions = ndextract_main(obj)
    print(objvalue[nondominated_index,:])