import subprocess
import cmd
import os
import sys
import platform
import readline
import logging
import rlcompleter
import time
import frida

if 'libedit' in readline.__doc__:
    readline.parse_and_bind("bind ^I rl_complete")
else:
    readline.parse_and_bind("tab: complete")

RED   = "\033[1;31m"
BLUE  = "\033[1;34m"
CYAN  = "\033[1;36m"
WHITE = "\033[1;37m"
YELLOW= "\033[1;33m"
GREEN = "\033[0;32m"
RESET = "\033[0;0m"
BOLD    = "\033[;1m"
REVERSE = "\033[;7m"

class parser(cmd.Cmd):

    prompt = BLUE+'apkutils>'+RESET
    INSTALL = False
    device = None
    package = None
    permissions = None
    activities = None
    services = None
    receivers = None
    providers = None
    deeplinks = None
    deeplinks_= []
    strings = []
    filters = []

    # classes = []
    packages = []

    def do_search(self, line):
        found = False
        try:
            what = line.split(' ')[0]
            print(RED+'Searching Activities:'+RESET)
            for module in self.activities:
                if what.lower() in module.lower():
                    print('[+] '+module[:str(module.lower()).find(what.lower())]+GREEN+what+RESET+module[str(module.lower()).find(what.lower())+len(what.lower()):])
                    print("[Original String: {}]\n".format(module))
                    found = True
            if not found:
                print('No Activities found containing: {} !'.format(what))
            found = False

            print(RED+'Searching Services:'+RESET)
            for module in self.services:
                if what.lower() in module.lower():
                    print('[+] '+module[:str(module.lower()).find(what.lower())]+GREEN+what+RESET+module[str(module.lower()).find(what.lower())+len(what.lower()):])
                    print("[Original String: {}]\n".format(module))
                    found = True
            if not found:
                print('No Services found containing: {} !'.format(what))
            found = False

            print(RED+'Searching Receivers:'+RESET)
            for module in self.receivers:
                if what.lower() in module.lower():
                    print('[+] '+module[:str(module.lower()).find(what.lower())]+GREEN+what+RESET+module[str(module.lower()).find(what.lower())+len(what.lower()):])
                    print("[Original String: {}]\n".format(module))
                    found = True
            if not found:
                print('No Receivers found containing: {} !'.format(what))
            found = False

            print(RED+'Searching Providers:'+RESET)
            for module in self.providers:
                if what.lower() in module.lower():
                    print('[+] '+module[:str(module.lower()).find(what.lower())]+GREEN+what+RESET+module[str(module.lower()).find(what.lower())+len(what.lower()):])
                    print("[Original String: {}]\n".format(module))
                    found = True
            if not found:
                print('No Providers found containing: {} !'.format(what))
            found = False

            print(RED+'Searching Strings.xml:'+RESET)
            for module in self.strings:
                if what.lower() in module.lower():
                    print('[+] '+module[:str(module.lower()).find(what.lower())]+GREEN+what+RESET+module[str(module.lower()).find(what.lower())+len(what.lower()):])
                    print("[Original String: {}]\n".format(module))
                    found = True
            if not found:
                print('No Strings found containing: {} !'.format(what))
            found = False

        except Exception as e:
            print(e)

    def do_deeplink(self,line):
        try:
            if len(line.split()) > 1 and '--poc' in line.split()[1]:
                print("[+] Creating POC")
                poc = ''+''+'DEEPLINK POC'
                f = open("poc.html",'w')
                f.write(poc)
                f.close()
                print("[+] POC created")

            else:
                output=os.popen("adb -s {} shell am start -W -a android.intent.action.VIEW -d {}".format(self.device.id,line.split(' ')[0])).read()
                print(output)
        except Exception as e:
            print(e)

    def complete_deeplink(self, text, line, begidx, endidx):

        if not text:
            completions = self.deeplinks_[:]
        else:
            completions = [ f
                            for f in self.deeplinks_
                            if f.startswith(text)
                            ]
        return completions

    def printDeepLinksMap(self):
        a = 0
        print(GREEN+'\n'+'-'*40+'DeepLinks Map'+'-'*40+':'+RESET)
        try:
            for key in self.deeplinks:
                print(BLUE+'Deeplinks that trigger: '+GREEN+key+RESET)
                for value in self.deeplinks[key]:
                    self.deeplinks_.append(value)
                    print('\t|-> '+RED+value+RESET)
                    a = a+1
            print(GREEN+'-'*40+'Total Deeplinks:{}'.format(a)+'-'*40+'|')
        except Exception as e:
            print(e)

    def do_trace(self,line):

        opsys = platform.system()
        script = self.create_script(opsys,line)

        if not 'Error' in script:

            if 'Darwin' in opsys:
                subprocess.run("""osascript -e 'tell application "Terminal" to do script "{}" ' """.format(script), shell=True)
            elif 'Linux' in opsys:
                subprocess.run("""x-terminal-emulator -e {}""".format(script))
            elif 'Windows' in opsys:
                subprocess.call('start /wait {}'.format(script), shell=True)

    def do_pull(self, line):
        try:
            base_apk = os.popen("adb -s {} shell pm path {} | grep apk".format(self.device.id,line.split(' ')[0])).read()
            base_apk = base_apk[ base_apk.find(':')+1:]
            print("Extracting: "+base_apk)
            output = os.popen("adb -s {} pull {}".format(self.device.id,base_apk)).read()
            print(output)
        except Exception as e:
            print(e)

    def complete_pull(self, text, line, begidx, endidx):
        self.init_packages()
        if not text:
            completions = self.packages[:]
            self.packages = []
        else:
            completions = [ f
                            for f in self.packages
                            if f.startswith(text)
                            ]
            self.packages = []
        return completions

    def create_script(self,opsys,line):

        switch = line.split(' ')[0].strip()
        valid = True

        if '-j' in switch:
            param1 = line.split(' ')[1]+ '*!*'
            param = """frida-trace -D {} {} -j '{}' """.format(self.device.id,self.package,param1)
        elif '-n' in switch:
            param1 = line.split(' ')[1]+ '*'
            param = """frida-trace -D {} -i '{}' {}""".format(self.device.id,param1,self.package)
        elif '-a' in switch:
            param1 = line.split(' ')[1].strip()
            param = """frida-trace -D {} -I '{}' {}""".format(self.device.id,param1,self.package)
        else:
            print('[E] Invalid command, run help for options!')
            valid = False

        if valid:
            path = os.getcwd()

            if 'Windows' in opsys:
                script = path + '/script.bat'
                with open(script,'w') as file:
                    file.write(param)
            else:
                script = path + '/script.sh'
                with open(script,'w') as file:
                    file.write(param)
                os.chmod(script, 0o775)
        else:
            script = 'Error'

        return script

    def do_notify(self,line):
        try:
            output=os.popen("adb -s {} shell am broadcast  -a com.medusa.NOTIFY --es subject {} --es body {}".format(self.device.id,line.split(' ')[0],line.split(' ')[1])).read()
            print(output)
        except Exception as e:
            print(e)
            return

    def init_packages(self):
        for line1 in os.popen('adb -s {} shell pm list packages -3'.format(self.device.id)):
            self.packages.append(line1.split(':')[1].strip('\n'))

    def do_uninstall(self,package):
        try:
            output=os.popen("adb -s {} uninstall {}".format(self.device.id,package.split(' ')[0])).read()
            print(output)
        except Exception as e:
            print(e)
            return

    def do_kill(self,package):

        try:
            print(package)
            output=os.popen("adb -s {} shell  am force-stop {}".format(self.device.id,package.split(' ')[0])).read()
            print(output)
        except Exception as e:
            print(e)
            return

    def do_spawn(self,package):
        try:
            print('[+] Starting {}'.format(package))
            os.popen("adb -s {} shell  monkey -p {} -c 'android.intent.category.LAUNCHER 1'".format(self.device.id,package.split(' ')[0])).read()
            print('[+] {} started'.format(package))
        except Exception as e:
            print(e)
            return

    def complete_spawn(self, text, line, begidx, endidx):

        self.init_packages()
        if not text:
            completions = self.packages[:]
            self.packages = []
        else:
            completions = [ f
                            for f in self.packages
                            if f.startswith(text)
                            ]
            self.packages = []
        return completions

    def complete_kill(self, text, line, begidx, endidx):

        self.init_packages()
        if not text:
            completions = self.packages[:]
            self.packages = []
        else:
            completions = [ f
                            for f in self.packages
                            if f.startswith(text)
                            ]
            self.packages = []
        return completions

    def complete_uninstall(self, text, line, begidx, endidx):

        self.init_packages()
        if not text:
            completions = self.packages[:]
            self.packages = []
        else:
            completions = [ f
                            for f in self.packages
                            if f.startswith(text)
                            ]
            self.packages = []
        return completions

    def do_broadcast(self,line):
        try:
            output=os.popen("adb -s {} shell 'am broadcast -a {}'".format(self.device.id,line.split(' ')[0])).read()
            print(output)
        except Exception as e:
            print(e)
            return

    def complete_broadcast(self, text, line, begidx, endidx):

        if not text:
            completions = self.filters[:]
        else:
            completions = [ f
                            for f in self.filters
                            if f.startswith(text)
                            ]
        return completions

    def print_list(self,lst):
        print(GREEN)
        for item in lst:
            if type(item) is str:
                print('\t\t'+item)
        print(RESET)

    def print_strings(self,lst):

        for item in lst:
            print(GREEN+'KEY:' +RESET+'{}'.format(item.split('=')[0],) + GREEN+'\t,VAL:'+RESET+' {}'.format(item.split('=')[1] ))

    def do_show(self,line):
        what = line.split(' ')[0]
        if 'permissions' in what:
            self.print_list(self.permissions)
        elif 'activities' in what:
            self.print_list(self.activities)
        elif 'services' in what:
            self.print_list(self.services)
        elif 'receivers' in what:
            self.print_list(self.receivers)
        elif 'filters' in what:
            self.print_list(self.filters)
        elif 'providers' in what:
            self.print_list(self.providers)
        elif 'strings' in what:
            self.print_strings(self.strings)
        else:
            print('[i] Usage: show [permissions, activities, services, receivers, filters, providers, strings]')

    def complete_show(self, text, line, begidx, endidx):
        components = ['permissions', 'activities', 'services', 'receivers', 'filters','providers', 'strings']
        if not text:
            completions = components[:]
        else:
            completions = [ f
                            for f in components
                            if f.startswith(text)
                            ]
        return completions

    def do_adb(self,line):
        print("[i] Type 'exit' to return ")
        cmd = ''
        while cmd != 'exit':
            cmd = input(GREEN+'{}:adb:'.format(self.device.id)+RESET)
            if cmd != 'exit':
                subprocess.run('adb -s {} {}'.format(self.device.id,cmd), shell=True)

    def do_proxy(self,line):

        command = line.split(' ')[0]
        try:
            if 'get' in command:
                self.print_proxy()
            elif 'reset' in command:
                os.popen("adb -s {} shell settings put global http_proxy :0".format(self.device.id))
                os.popen("adb -s {} shell iptables -t nat -F".format(self.device.id))
                time.sleep(2)
                self.print_proxy()
            elif 'set' in command:
                switch = ip = line.split(' ')[1].split(':')[0]
                if '-t' in switch:
                    ip = line.split(' ')[2].split(':')[0]
                    port = line.split(' ')[2].split(':')[1]
                    self.transproxy(ip,port)
                else:
                    ip = line.split(' ')[1].split(':')[0]
                    port = line.split(' ')[1].split(':')[1]
                    os.popen("adb -s {} shell settings put global http_proxy {}:{}".format(self.device.id,ip,port))
                    time.sleep(2)
                    self.print_proxy()
            else:
                print('[!] Usage: proxy [set,get,reset] [<ip>:<port>] [-t]')
        except Exception as e:
            print(e)

    def transproxy(self,ip,port):
        try:
            print('[i] Pushing transproxy script !')
            os.popen("adb -s {} push utils/transproxy.sh /data/local/tmp/transproxy.sh".format(self.device.id))
            print('[i] Executing script')
            os.popen("adb -s {} shell 'chmod +x /data/local/tmp/transproxy.sh; /data/local/tmp/transproxy.sh {} {}; rm /data/local/tmp/transproxy.sh'".format(self.device.id,ip,port))
            self.print_proxy()
        except Exception as e:
            print(e)

    def do_installBurpCert(self,line):
        try:
            a = ''
            while a != 'y' and a !='x':
                a = input("""[!] Make sure that burp is running on 127.0.0.1:8080\n\nType 'y' to continue or 'x' to cancel:""")

            if a == 'y':
                os.popen("chmod +x utils/installBurpCert.sh; utils/installBurpCert.sh {}".format(self.device.id))
                os.popen("adb -s {} shell am broadcast -a com.medusa.INSTALL_CERTIFICATE -n com.medusa.agent/.Receiver".format(self.device.id))
                time.sleep(1)
                print()
        except Exception as e:
            print('')

    def complete_proxy(self, text, line, begidx, endidx):
        proxy_cmd = ['set','get','reset']
        if not text:
            completions = proxy_cmd[:]
        else:
            completions = [ f
                            for f in proxy_cmd
                            if f.startswith(text)
                            ]
        return completions

    def print_proxy(self):

        settings = os.popen("adb -s {} shell settings get global http_proxy".format(self.device.id)).read()
        print (WHITE+"--------------Global proxy settings-----------------:"+RESET)
        print ('Current proxy: {}'.format(settings))
        print (WHITE+"--------------IP tables settings--------------------:"+RESET)
        output = subprocess.run("adb -s {} shell iptables -t nat -L".format(self.device.id), shell=True)
        print(output)

    def do_screencap(self, line):
        try:
            if '-o' in line.split(' ')[0]:
                os.popen("adb -s {} exec-out screencap -p > {}".format(self.device.id,line.split(' ')[1]))
                print('[!] Screencap saved successfully to {}'.format(line.split(' ')[1]))
            else:
                print('[!] Usage: screencap -o filename.png')
        except Exception as e:
            print(e)
            print('[!] Usage: screencap -o filename.png')

    def do_jdwp(self,line):
        try:
            pid = os.popen("adb -s {} shell pidof {}".format(self.device.id,line.split(' ')[0])).read()
            output = os.popen("adb -s {} forward tcp:6667 jdwp:{}".format(self.device.id,pid)).read()
            print(output)

            subprocess.run('jdb -attach localhost:6667', shell=True)

        except Exception as e:
            print(e)
            print('[!] Usage: jdwp package_name')

    def complete_jdwp(self, text, line, begidx, endidx):

        self.init_packages()
        if not text:
            completions = self.packages[:]
            self.packages = []
        else:
            completions = [ f
                            for f in self.packages
                            if f.startswith(text)
                            ]
            self.packages = []
        return completions

    def do_start(self,line):
        try:
            output=os.popen("adb -s {} shell 'am start -n {}/{}'".format(self.device.id,self.package,line.split(' ')[0])).read()
            print(output)
        except Exception as e:
            print(e)
            return

    def complete_start(self, text, line, begidx, endidx):
        if not text:
            completions = self.activities[:]
        else:
            completions = [ f
                            for f in self.activities
                            if f.startswith(text)
                            ]
        return completions

    def do_startsrv(self,line):
        try:
            output=os.popen("adb -s {} shell 'am startservice -n {}/{}'".format(self.device.id,self.package,line.split(' ')[0])).read()
            print(output)
        except Exception as e:
            print(e)
            return

    def complete_startsrv(self, text, line, begidx, endidx):
        if not text:
            completions = self.services[:]
        else:
            completions = [ f
                            for f in self.services
                            if f.startswith(text)
                            ]
        return completions

    def do_stopsrv(self,line):
        try:
            output=os.popen("adb -s {} shell 'am stopservice -n {}/{}'".format(self.device.id,self.package,line.split(' ')[0])).read()
            print(output)
        except Exception as e:
            print(e)
            return

    def complete_stopsrv(self, text, line, begidx, endidx):
        if not text:
            completions = self.services[:]
        else:
            completions = [ f
                            for f in self.services
                            if f.startswith(text)
                            ]
        return completions

    def do_type(self,line):

        print("Type 'exit' to quit")

        while 'exit' not in line:
            line = input(':')
            os.popen("adb -s {} shell input text {}".format(self.device.id,line))

    def do_clear(self,line):
        os.system('clear')

    def do_shell(self,line):
        shell = os.environ['SHELL']
        subprocess.run('{}'.format(shell), shell=True)

    def do_exit(self,line):
        print('[i] Cleaning working directory: ')
        try:
            if os.path.isfile('./manifest.xml'):
                ask = input('\n[!] do you want to delete the manifest file ? (yes/no) ')
                if 'yes' in ask:
                    os.remove('./manifest.xml')

            if os.path.isfile('./strings.xml'):
                ask = input('\n[!] do you want to delete the strings.xml file ? (yes/no) ')
                if 'yes' in ask:
                    os.remove('./strings.xml')

            if os.path.isfile('./script.sh'):
                ask = input('\n[!] do you want to delete the trace script file ? (yes/no) ')
                if 'yes' in ask:
                    os.remove('./script.sh')

            if os.path.isfile('./script.bat'):
                ask = input('\n[!] do you want to delete the trace script file ? (yes/no) ')
                if 'yes' in ask:
                    os.remove('./script.bat')

            if self.INSTALL == True:
                uninstall = input("[!] Do you want to uninstall the apk ? (yes/no)")
                if 'yes' in uninstall:
                    subprocess.run('adb -s {} uninstall {}'.format(self.device.id,self.package),shell=True)

            if os.path.exists("__handlers__/"):
                uninstall = input("[!] Do you want to delete the __handlers__ folder? (yes/no)")
                if 'yes' in uninstall:
                    os.system("rm -r __handlers__/")

        except Exception as e:
            print(e)

        print('Bye !!')
        exit()

    def do_installagent(self,line):
        try:
            subprocess.run('adb -s {} install -g {}'.format(self.device.id, os.getcwd()+'/dependencies/agent.apk'),shell=True)
        except Exception as e:
            print(e)

    def do_help(self,line):
        if line != '':
            print('\n'+BLUE+self.display_tag(line,'Help')+RESET)
        else:
            print("""Available commands:

                    [+] TRACE Functions using frida-trace:
                    ---------------------

                    - trace -j com.myapp.name*          : Trace all the functions of the com.myapp.name* class
                    - trace -n foo                      : Trace a native function
                    - trace -a library.so               : Trace the functions of the library.so

                    Will spawn a new frida-trace instance with the given options

                    ===========================================================================================

                    [+] MANIFEST PARSER:
                    ---------------------

                    - show permissions          : Print the application's permissions
                    - show activities           : Print a list with the application's activities
                    - show services             : Print a list with the application's services
                    - show receivers            : Print a list with the application's receivers
                    - show providers            : Print a list with the application's content providers
                    - show filters              : Print broadcast filters
                    - show strings              : print application's strings
                    - search [keyword]          : Search components containing the given keyword
                    ===========================================================================================

                    [+] TRIGERS:
                    ---------------------

                    - start      [tab]          : Start and activity
                    - deeplink   [tab]          : Trigger a deeplink
                                                  Add the --poc to create an html poc file
                    - startsrv   [tab]          : Start a service
                    - stopsrv    [tab]          : Stop a service
                    - broadcast  [tab]          : Broadcast an intent
                    - spawn      [tab]          : Spawn an application

                    ===========================================================================================

                    [+] UTILITIES:
                    ---------------------
                    - pull       [tab]              : extract apk from the device
                    - installagent                  : Install the Medusa apk
                    - installBurpCert               : Install Burp Certificate
                    - notify subject body           : Display a notification to the phone's notification bar
                    e.g. notify test foo            (Requires the medusa agent to be installed and run)

                    - jdwp  package_name            : Open a jdb session with the debugger attached to the package
                                                    (Requires the --patch option)

                    - adb [cmd]                     : Send an adb command to the connected device
                    - clear                         : Clears the screen
                    - kill [tab]                    : Kill an app by the package name
                    - type                          : Type text to send to the device
                    - screencap -o filename         : Takes a device screenshot and saves it as 'filaname'
                    - shell                         : Opens an interactive shell
                    - proxy set [-t] <ip>:<port>    : Sets a global proxy at a given ip and port
                                                    ('-t' for transparent)
                    - proxy get                     : Displays proxy settings of the device
                    - proxy reset                   : Resets proxy settings
                    - uninstall [tab]               : Uninstals a packages from the device

                            """)


# Database of sales is given. Every record is client, product and quantity.
# Create a list of all clients and quantity of products bought by him.

matrix_a = list()
try:
    while True:
        matrix_a.append(input().split())
except EOFError:
    True

A = dict()
for i in range(len(matrix_a)):
    string = matrix_a[i][0]+' '+matrix_a[i][1]
    if string not in A:
        A[string] = int(matrix_a[i][2])
    else:
        A[string] += int(matrix_a[i][2])

keys_A = list(A.keys())
keys_A.sort()
name_old=''
for key in keys_A:
    name,item = key.split()
    if name_old!=name:
        name_old=name
        print(name+':')
    print(item,A[key])


import sys

if len(sys.argv) < 4:
    print('there are some missing parameters')
    exit(1)

try:
    n1 = int(sys.argv[1])
    sign = sys.argv[2]
    n2 = int(sys.argv[3])
except ValueError:
    print('there is some invalid number')
    exit(2)
else:
    if sign == '+':
        print(n1+n2)
    elif sign == '-':
        print(n1-n2)
    else:
        print('invalid sign')
        exit(3)


"""
Given a string you need to print all possible strings that can be made by placing spaces (zero or one) in between them.

Input:
Input indicates the string

Output:
Print all possible strings by inserting spaces in between letters

Input:
ABC

Output:
ABC
AB C
A BC
A B C

Input:
ABCD

Output:
ABCD
ABC D
AB CD
AB C D
A BCD
A BC D
A B CD
A B C D

Input:
BGH
Output:
BGH
BG H
B GH
B G H

Input:
D
Output:
D

Input:
HJKI
Output:
HJKI
HJK I
HJ KI
HJ K I
H JKI
H JK I
H J KI
H J K I
"""
def toString(List):
    s = ""
    for x in List:
        if x == '':
            break
        s += x
    return s

def printPatternUtil(string, buff, i, j, n):
    if i == n:
        buff[j] = ''
        print(toString(buff))
        return
    buff[j] = string[i]
    printPatternUtil(string, buff, i+1, j+1, n)
    buff[j] = ' '
    buff[j+1] = string[i]

    printPatternUtil(string, buff, i+1, j+2, n)
def printPattern(string):
    n = len(string)
    buff = [""]*(2*n)
    buff[0] = string[0]
    printPatternUtil(string, buff, 1, 1, n)
s=input()
printPattern(s)

possible strings with replacing spaces.py


# API version=2
import numpy as np
from django.shortcuts import redirect
from rest_framework.decorators import api_view
import random
import string
from random import randint
from rest_framework.response import Response
from .models import SignalSet

COLORS = ['navy', 'blue', 'teal', 'aqua', 'green', 'lime', 'olive', 'yellow', 'maroon', 'red', 'purple', 'fuchsia',
          'gray', 'black']

def generate_random_string(length):
    letters = string.ascii_lowercase
    rand_string = ''.join(random.choice(letters) for _ in range(length))
    return rand_string

@api_view(['GET'])
def previous_signals_list_view(request):
    try:
        qs = SignalSet.objects.first()
        return Response(qs.signals, status=200)
    except AttributeError:
        return redirect('signal-list')

@api_view(['GET'])
def signal_list_view(request):
    value = []
    list_of_signals = []
    signals_quantity = randint(5, 25)
    length_of_lst = randint(100, 1000)
    read_only_values = np.random.choice([True, False], size=(signals_quantity,), p=[1 / 3, 2 / 3])
    for index in range(signals_quantity):
        for _ in range(length_of_lst):
            level = randint(0, 1)
            value.append(level)
        list_of_signals.append({"id": signals_quantity - index,
                                "name": f'Сигнал {generate_random_string(5) + str(signals_quantity - index)}',
                                "readOnly": read_only_values[index],
                                "color": random.choice(COLORS),
                                "value": value[:]})
        value.clear()
    signal_set = SignalSet()
    signal_set.signals = list_of_signals
    signal_set.save()
    if SignalSet.objects.all().count() > 2:
        SignalSet.objects.first().delete()
    return Response(list_of_signals, status=200)


from glob import glob
from os import path
from itertools import cycle
from vispy import gloo
from vispy import app
import numpy as np

VERT_SHADER = """

uniform float blend;
uniform float view_size;

attribute vec2  a_position;
attribute float a_size;
attribute vec3  a_color;

attribute vec2  a_position2;
attribute float a_size2;
attribute vec3  a_color2;

varying vec4 v_fg_color;
varying vec4 v_bg_color;
varying float v_radius;

void main (void) {

    v_radius = (a_size * (1.0 - blend) + a_size2 * blend) * view_size;
    v_fg_color  = vec4(0.0, 0.0, 0.0, 0.5);
    v_bg_color  = vec4(a_color, 1.0) * (1 - blend) + vec4(a_color2, 1.0) * blend;

    gl_Position = vec4(a_position, 0, 1.0) * (1 - blend) + vec4(a_position2, 0, 1.0) * blend;
    gl_PointSize = 2.0*v_radius + 2;
}
"""

FRAG_SHADER = """
#version 120

varying vec4 v_fg_color;
varying vec4 v_bg_color;
varying float v_radius;
void main()
{

    float size = 2.0*v_radius + 2;
    float r = length((gl_PointCoord.xy - vec2(0.5,0.5))*size);
    if(r < v_radius)
        gl_FragColor = v_bg_color;
    else if(r < v_radius + 1)
    {
        gl_FragColor = vec4(v_bg_color[0], v_bg_color[1], v_bg_color[2], (v_radius + 1 - r) * 0.5);
    }
    else
        gl_FragColor = vec4(0, 0, 0, 0);
}
"""

def load_circles():
    photo_circles = []

    circle_dtype = [("position", np.float32, 2),
                    ("size", np.float32),
                    ("color", np.float32, 3)]

    for fn in glob(path.join(path.dirname(__file__), "*.csv")):
        data = np.loadtxt(fn, delimiter=",")
        circles = np.zeros(len(data), dtype=circle_dtype)
        circles["position"] = data[:, :2] / 256.0 - 1
        circles["size"] = data[:, 2] / 512.0 * 1.01
        circles["color"] = data[:, 3:] / 256.0
        circles["position"][:, 1] *= -1
        photo_circles.append(circles)

    photos = cycle(photo_circles)
    return photos

class Canvas(app.Canvas):

    def __init__(self):
        app.Canvas.__init__(self, keys='interactive', size=(400, 400))
        self.photos = load_circles()

    def set_data(self, circles1, circles2):
        self.program['a_color'] = circles1["color"].copy()
        self.program['a_position'] = circles1["position"].copy()
        self.program['a_size'] = circles1["size"].copy()

        self.program['a_color2'] = circles2["color"].copy()
        self.program['a_position2'] = circles2["position"].copy()
        self.program['a_size2'] = circles2["size"].copy()

    def on_initialize(self, event):
        self.program = gloo.Program(VERT_SHADER, FRAG_SHADER)

        self.circles1 = next(self.photos)
        self.circles2 = next(self.photos)
        self.set_data(self.circles1, self.circles2)

        self.blend = 0.01
        self.target_blend = 1.0
        self.program['blend'] = self.blend
        self.count = 0

        gloo.set_state(clear_color='white', blend=True,
                       blend_func=('src_alpha', 'one_minus_src_alpha'))

        self._timer = app.Timer('auto', connect=self.on_timer, start=True)

    def on_timer(self, event):
        step = min((self.blend * 0.96 + self.target_blend * 0.04) - self.blend, 0.02)
        self.blend += step

        if self.blend > 0.999 or self.blend < 0.001:
            self.blend = self.target_blend
            self.count += 1
        if self.count == 100:
            self.count = 0
            self.blend = 0.0
            self.circles1, self.circles2 = self.circles2, next(self.photos)
            self.set_data(self.circles1, self.circles2)
        self.program['blend'] = self.blend
        self.update()

    def on_resize(self, event):
        w, h = event.size
        s = min(w, h)
        gloo.set_viewport(0, 0, s, s)
        self.program['view_size'] = s

    def on_draw(self, event):
        gloo.clear(color=True, depth=True)
        self.program.draw('points')

if __name__ == '__main__':
    c = Canvas()
    c.show()
    app.run()


import cv2
import chainer
import numpy as np
import chainer.functions as F
from vggface import VGGFace
from chainercv.links.model.vgg import VGG16
# pylint: disable=E1101

vgg = VGGFace(n_class=2622)
vgg.pick = 'prob'
vgg.remove_unused()
chainer.serializers.load_npz('vggface.npz', vgg)

x = cv2.imread('./images/ak.png', cv2.IMREAD_COLOR)
x = cv2.resize(x, dsize=(224, 224)).astype('f')
x = x[None, ].transpose(0, 3, 1, 2)

x[:, 0, :, :] -= 93.5940   # B
x[:, 1, :, :] -= 104.7624  # G
x[:, 2, :, :] -= 129.1863  # R

with open('./names.txt', 'r') as f:
    names = f.readlines()

with chainer.no_backprop_mode(), chainer.using_config('train', False):
    score = vgg(x).data

idx = np.argmax(score)

print('Predict: %s' % names[idx])
print('Score: %.02f' % score[0][idx])


from random import random

names = [
    ['Alice', 'Ariel', 'Aurora', 'Bambi', 'Belle', 'Bolt', 'Dumbo', 'Genie', 'Jiminy'],
    ['Phil', 'Peter', 'Olaf', 'Mulan', 'Mowgli', 'Mickey', 'Kuzko', 'Kida', 'Kenai'],
    ['Phoebus', 'Ralph', 'Robin', 'Silver', 'Simba', 'Stitch', 'Tarzan', 'Tiana', 'Winnie']
]
i = 0
while i < 1000:
    j = int(random() * 10) % 3
    k = int(random() * 100) % 9
    print(names[j][k])
    i+=1


from Factura import Factura , FacturaCredito, FacturaContado
import os

class Lectura:
    def LeeDatosFactura(self):
        factura = Factura()
        os.system('clear') #os.system('cls') #en windows
        factura.Captura()
        return factura
    def LeeDatosFacturaCredito(self):
        facturaCredito = FacturaCredito()
        os.system('clear') #os.system('cls') #en windows
        facturaCredito.Captura()
        return facturaCredito
    def LeeDatosFacturaContado(self):
        facturaContado = FacturaContado()
        os.system('clear') #os.system('cls') #en windows
        facturaContado.Captura()
        return facturaContado


import world
import random
import torch
import numpy as np
import torch.optim as optim
from world import ARGS
from models import DQN
from collections import namedtuple

# ------------------------------------------------
def getOptimizer(optimizer=None):
    '''
        combine optimizer with related setting
    '''
    OptimizerSpec = namedtuple("OptimizerSpec", ["constructor", "kwargs"])
    if optimizer is None:
        optimizer = optim.RMSprop

    wrapped_optimizer = OptimizerSpec(
            constructor = optimizer,
            kwargs      = dict(lr = ARGS.lr, alpha=ARGS.alpha, eps=ARGS.eps)
        )
    return wrapped_optimizer
# ------------------------------------------------
def init_model(env,
               model : DQN):
    '''
        using the env information to init DQN model
    '''
    channel = ARGS.framelen * 1
    # we assert that all the obs are gray images
    num_actions = env.action_space.n
    # obtain Discrete actions of an env
    return model(in_channels=channel, num_actions=num_actions)
# ------------------------------------------------
def set_global_seeds(i):
    try:
        import torch
    except ImportError:
        pass
    else:
        torch.manual_seed(i)
    np.random.seed(i)
    random.seed(i)
# ------------------------------------------------
def linear_interpolation(l, r, alpha):
    return l + alpha * (r - l)

def TENSOR(*tensors):
    results = []
    for tensor in tensors:
        results.append(torch.from_numpy(tensor).float())
    return results

def TO(*tensors, **kwargs):
    results = []
    for tensor in tensors:
        results.append(tensor.to(world.DEVICE))
    return results
# ------------------------------------------------
class Schedule(object):
    def value(self, t):
        """Value of the schedule at time t"""
        raise NotImplementedError()
# ------------------------------------------------
class ConstantSchedule(object):
    def __init__(self, value):
        """Value remains constant over time.
        Parameters
        ----------
        value: float
            Constant value of the schedule
        """
        self._v = value

    def value(self, t):
        """See Schedule.value"""
        return self._v
# ------------------------------------------------
class PiecewiseSchedule(object):
    def __init__(self, endpoints, interpolation=linear_interpolation, outside_value=None):
        """Piecewise schedule.
        endpoints: [(int, int)]
            list of pairs `(time, value)` meanining that schedule should output
            `value` when `t==time`. All the values for time must be sorted in
            an increasing order. When t is between two times, e.g. `(time_a, value_a)`
            and `(time_b, value_b)`, such that `time_a <= t < time_b` then value outputs
            `interpolation(value_a, value_b, alpha)` where alpha is a fraction of
            time passed between `time_a` and `time_b` for time `t`.
        interpolation: lambda float, float, float: float
            a function that takes value to the left and to the right of t according
            to the `endpoints`. Alpha is the fraction of distance from left endpoint to
            right endpoint that t has covered. See linear_interpolation for example.
        outside_value: float
            if the value is requested outside of all the intervals sepecified in
            `endpoints` this value is returned. If None then AssertionError is
            raised when outside value is requested.
        """
        idxes = [e[0] for e in endpoints]
        assert idxes == sorted(idxes)
        self._interpolation = interpolation
        self._outside_value = outside_value
        self._endpoints      = endpoints

    def value(self, t):
        """See Schedule.value"""
        for (l_t, l), (r_t, r) in zip(self._endpoints[:-1], self._endpoints[1:]):
            if l_t <= t and t < r_t:
                alpha = float(t - l_t) / (r_t - l_t)
                return self._interpolation(l, r, alpha)

        # t does not belong to any of the pieces, so doom.
        assert self._outside_value is not None
        return self._outside_value
# ------------------------------------------------
class LinearSchedule(object):
    def __init__(self, schedule_timesteps, final_p, initial_p=1.0):
        """Linear interpolation between initial_p and final_p over
        schedule_timesteps. After this many timesteps pass final_p is
        returned.
        Parameters
        ----------
        schedule_timesteps: int
            Number of timesteps for which to linearly anneal initial_p
            to final_p
        initial_p: float
            initial output value
        final_p: float
            final output value
        """
        self.schedule_timesteps = schedule_timesteps
        self.final_p             = final_p
        self.initial_p          = initial_p

    def value(self, t):
        """See Schedule.value"""
        fraction  = min(float(t) / self.schedule_timesteps, 1.0)
        return self.initial_p + fraction * (self.final_p - self.initial_p)


class Material:
    def __init__(self, rodzaj, dlugosc, szerokosc):
        self.rodzaj = rodzaj
        self.dlugosc = dlugosc
        self.szerokosc = szerokosc

    def wyswietl_nazwe(self):
        print(self.rodzaj)

class Ubranie(Material):
    def __init__(self, rodzaj, rozmiar, kolor, dlakogo):
        self.rodzaj = rodzaj
        self.rozmiar = rozmiar
        self.kolor = kolor
        self.dlakogo = dlakogo

    def wyswietl_dane(self):
        print('Rozmiar: ', self.rozmiar)
        print('Kolor: ', self.kolor)
        print('Dla: ', self.dlakogo)

class Sweter(Ubranie):
    def __init__(self, rodzaj, rozmiar, kolor, dlakogo, rodzajswetra):
        super().__init__(rodzaj, rozmiar, kolor, dlakogo)
        self.rodzajswetra = rodzajswetra

    def wyswietl_dane(self):
        print('Rodzaj swetra: ', self.rodzajswetra)

bluza = Ubranie('Bawełna', 'S', 'Zielona', 'Grzegorz')
bluza.wyswietl_dane()
bluza.wyswietl_nazwe()

print('    ')

sweter1 = Sweter('Bawełna', 'M', 'Czerwony', 'Adam', 'Z zamkiem')
sweter1.wyswietl_dane()
sweter1.wyswietl_nazwe()


def neighbours(i, j):
    return [(i, j - 1), (i, j + 1), (i - 1, j), (i + 1, j)]  # , (i-1, j-1), (i-1, j+1), (i+1, j-1), (i+1, j+1)]

def is_valid(i, j, board):
    return all((i >= 0, i < len(board), j >= 0, j < len(board[0])))

def check_teritory(i, j, visited, board, b_w_teritories):
    surrounded_by_black = False
    surrounded_by_white = False
    count = 1
    queue = [(i, j)]
    while queue:
        row, col = queue.pop()
        for neigh in neighbours(row, col):
            k, m = neigh
            if is_valid(k, m, board):
                if board[k][m] == "+" and (k, m) not in visited:
                    count += 1
                    queue.append(neigh)
                    visited.add(neigh)
                elif board[k][m] == "B":
                    surrounded_by_black = True
                elif board[k][m] == "W":
                    surrounded_by_white = True
    if all((surrounded_by_white, surrounded_by_black)):
        return
    elif surrounded_by_white:
        b_w_teritories["W"] += count
    else:
        b_w_teritories["B"] += count
    return

def territory(board):
    visited = set()
    b_w_teritories = {"B": 0, "W": 0}
    for i, row in enumerate(board):
        for j, cell in enumerate(row):
            if (i, j) not in visited:
                visited.add((i, j))
                if cell == "+":
                    check_teritory(i, j, visited, board, b_w_teritories)
    return b_w_teritories

#Asserts written by task's creator
if __name__ == '__main__':
    print("Example:")
    print(territory(['++B++++++',
                     '+BB++++++',
                     'BB+++++++',
                     '+++++++++',
                     '+++++++++',
                     '++WWW++++',
                     '++W+W++++',
                     '++WWW++++',
                     '+++++++++']))

    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert territory(['++B++++++',
                      '+BB++++++',
                      'BB+++++++',
                      '+++++++++',
                      '+++++++++',
                      '++WWW++++',
                      '++W+W++++',
                      '++WWW++++',
                      '+++++++++']) == {'B': 3, 'W': 1}
    print("Coding complete? Click 'Check' to earn cool rewards!")

moderate/the territory of go/solution.py


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests the GoogleCloudCollector."""

from __future__ import unicode_literals

import unittest

import mock
from libcloudforensics import gcp

from dftimewolf import config
from dftimewolf.lib import state
from dftimewolf.lib.collectors import gcloud

FAKE_PROJECT = gcp.GoogleCloudProject(
    'test-target-project-name',
    'fake_zone')
FAKE_ANALYSIS_VM = gcp.GoogleComputeInstance(
    FAKE_PROJECT,
    'fake_zone',
    'fake-analysis-vm')
FAKE_INSTANCE = gcp.GoogleComputeInstance(
    FAKE_PROJECT,
    'fake_zone',
    'fake-instance')
FAKE_DISK = gcp.GoogleComputeDisk(
    FAKE_PROJECT,
    'fake_zone',
    'disk1')
FAKE_BOOT_DISK = gcp.GoogleComputeDisk(
    FAKE_PROJECT,
    'fake_zone',
    'bootdisk')
FAKE_SNAPSHOT = gcp.GoogleComputeSnapshot(
    FAKE_DISK,
    FAKE_PROJECT)
FAKE_DISK_COPY = gcp.GoogleComputeDisk(
    FAKE_PROJECT,
    'fake_zone',
    'disk1-copy')

def ReturnFakeDisk(disk_name):
  """Generate fake GoogleCloudComputeDisk objects depending on provided name."""
  return gcp.GoogleComputeDisk(
      FAKE_PROJECT, 'fakezone', disk_name)

class GoogleCloudCollectorTest(unittest.TestCase):
  """Tests for the Stackdriver collector."""

  def testInitialization(self):
    """Tests that the collector can be initialized."""
    test_state = state.DFTimewolfState(config.Config)
    gcloud_collector = gcloud.GoogleCloudCollector(test_state)
    self.assertIsNotNone(gcloud_collector)

  # pylint: disable=invalid-name
  @mock.patch(
      'libcloudforensics.gcp.GoogleComputeBaseResource.AddLabels')
  @mock.patch('libcloudforensics.gcp.GoogleComputeBaseResource')
  @mock.patch('libcloudforensics.gcp.StartAnalysisVm')
  def testSetUp(self,
                mock_StartAnalysisVm,
                mock_GoogleComputeBaseResource,
                mock_AddLabels):
    """Tests that the collector can be initialized."""
    test_state = state.DFTimewolfState(config.Config)
    mock_StartAnalysisVm.return_value = (mock_GoogleComputeBaseResource, None)

    gcloud_collector = gcloud.GoogleCloudCollector(test_state)
    gcloud_collector.SetUp(
        'test-analysis-project-name',
        'test-target-project-name',
        'fake_incident_id',
        'fake_zone',
        42.0,
        16,
        remote_instance_name='my-owned-instance',
    )
    self.assertEqual(test_state.errors, [])
    self.assertEqual(gcloud_collector.disk_names, [])
    self.assertEqual(gcloud_collector.analysis_project.project_id,
                     'test-analysis-project-name')
    self.assertEqual(gcloud_collector.remote_project.project_id,
                     'test-target-project-name')
    self.assertEqual(gcloud_collector.remote_instance_name,
                     'my-owned-instance')
    self.assertEqual(gcloud_collector.all_disks, False)

    mock_StartAnalysisVm.assert_called_with(
        'test-analysis-project-name',
        'gcp-forensics-vm-fake_incident_id',
        'fake_zone',
        42.0,
        16,
        attach_disk=None,
        image_family='ubuntu-1804-lts',
        image_project='ubuntu-os-cloud'
    )
    mock_AddLabels.assert_has_calls(
        [mock.call({'incident_id': 'fake_incident_id'})])

  # pylint: disable=line-too-long
  @mock.patch('libcloudforensics.gcp.GoogleComputeInstance.GetBootDisk')
  @mock.patch('libcloudforensics.gcp.GoogleComputeBaseResource.AddLabels')
  @mock.patch('libcloudforensics.gcp.StartAnalysisVm')
  @mock.patch('libcloudforensics.gcp.GoogleCloudProject.CreateDiskFromSnapshot')
  @mock.patch('dftimewolf.lib.collectors.gcloud.GoogleCloudCollector._FindDisksToCopy')
  @mock.patch('libcloudforensics.gcp.GoogleComputeDisk.Snapshot')
  @mock.patch('libcloudforensics.gcp.GoogleComputeSnapshot.Delete')
  @mock.patch('libcloudforensics.gcp.GoogleComputeInstance.AttachDisk')
  def testProcess(self,
                  unused_MockAttachDisk,
                  mock_Delete,
                  mock_Snapshot,
                  mock_FindDisks,
                  mock_CreateDiskFromSnapshot,
                  mock_StartAnalysisVm,
                  mock_AddLabels,
                  mock_GetBootDisk):
    """Tests the collector's Process() function."""
    mock_StartAnalysisVm.return_value = (FAKE_ANALYSIS_VM, None)
    mock_FindDisks.return_value = [
        gcp.GoogleComputeDisk(
            FAKE_PROJECT,
            'fake_zone',
            'disk1')
    ]
    mock_CreateDiskFromSnapshot.return_value = FAKE_DISK_COPY
    mock_Snapshot.return_value = FAKE_SNAPSHOT
    FAKE_ANALYSIS_VM.AddLabels = mock_AddLabels
    FAKE_ANALYSIS_VM.GetBootDisk = mock_GetBootDisk
    FAKE_DISK_COPY.AddLabels = mock_AddLabels

    test_state = state.DFTimewolfState(config.Config)
    gcloud_collector = gcloud.GoogleCloudCollector(test_state)
    gcloud_collector.SetUp(
        'test-analysis-project-name',
        'test-target-project-name',
        'fake_incident_id',
        'fake_zone',
        42.0,
        16,
        remote_instance_name='my-owned-instance',
    )
    gcloud_collector.Process()

    mock_Snapshot.assert_called_once()
    mock_CreateDiskFromSnapshot.assert_called_with(
        FAKE_SNAPSHOT, disk_name_prefix='incidentfake_incident_id')
    mock_Delete.assert_called_once()
    self.assertEqual(test_state.output[0][0], 'fake-analysis-vm')
    self.assertEqual(test_state.output[0][1].name, 'disk1-copy')
    mock_AddLabels.assert_has_calls([mock.call({'incident_id': 'fake_incident_id'})])

  # pylint: disable=line-too-long,invalid-name
  @mock.patch('libcloudforensics.gcp.GoogleComputeBaseResource')
  @mock.patch('libcloudforensics.gcp.GoogleComputeInstance.GetBootDisk')
  @mock.patch('libcloudforensics.gcp.GoogleCloudProject.GetDisk')
  @mock.patch('libcloudforensics.gcp.GoogleComputeInstance.ListDisks')
  @mock.patch('libcloudforensics.gcp.GoogleCloudProject.GetInstance')
  @mock.patch('libcloudforensics.gcp.StartAnalysisVm')
  # We're manually calling protected functions
  # pylint: disable=protected-access
  def testFindDisksToCopy(self,
                          mock_StartAnalysisVm,
                          mock_get_instance,
                          mock_list_disks,
                          mock_get_disk,
                          mock_GetBootDisk,
                          mock_GoogleComputeBaseResource):
    """Tests the FindDisksToCopy function with different SetUp() calls."""
    test_state = state.DFTimewolfState(config.Config)
    gcloud_collector = gcloud.GoogleCloudCollector(test_state)
    mock_StartAnalysisVm.return_value = (mock_GoogleComputeBaseResource, None)
    mock_list_disks.return_value = ['bootdisk', 'disk1']
    mock_get_disk.side_effect = ReturnFakeDisk
    mock_get_instance.return_value = FAKE_INSTANCE
    mock_GetBootDisk.return_value = FAKE_BOOT_DISK

    # Nothing is specified, GoogleCloudCollector should collect the instance's
    # boot disk
    gcloud_collector.SetUp(
        'test-analysis-project-name',
        'test-target-project-name',
        'fake_incident_id',
        'fake_zone',
        42.0,
        16,
        remote_instance_name='my-owned-instance',
    )
    disks = gcloud_collector._FindDisksToCopy()
    self.assertEqual(len(disks), 1)
    self.assertEqual(disks[0].name, 'bootdisk')
    mock_GetBootDisk.assert_called_once()

    # Specifying all_disks should return all disks for the instance
    # (see mock_list_disks return value)
    gcloud_collector.SetUp(
        'test-analysis-project-name',
        'test-target-project-name',
        'fake_incident_id',
        'fake_zone',
        42.0,
        16,
        remote_instance_name='my-owned-instance',
        all_disks=True
    )
    disks = gcloud_collector._FindDisksToCopy()
    self.assertEqual(len(disks), 2)
    self.assertEqual(disks[0].name, 'bootdisk')
    self.assertEqual(disks[1].name, 'disk1')

    # If a list of disks is passed, that disk only should be returned
    gcloud_collector.SetUp(
        'test-analysis-project-name',
        'test-target-project-name',
        'fake_incident_id',
        'fake_zone',
        42.0,
        16,
        remote_instance_name='my-owned-instance',
        disk_names='disk1'
    )
    disks = gcloud_collector._FindDisksToCopy()
    self.assertEqual(len(disks), 1)
    self.assertEqual(disks[0].name, 'disk1')

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


#Imports
import json
from PIL import Image, ImageDraw, ImageFont
import numpy as np

def plot_boxes(image_dict, image, location = None, saver = 0): # Write the required arguments
	# The function should plot the predicted boxes on the images and save them.
	# Tip: keep the dimensions of the output image less than 800 to avoid RAM crashes.

	num_of_bboxes = len(image_dict['bboxes'])
	if num_of_bboxes > 5:
		num_of_bboxes = 5

	for j in image_dict['bboxes']: # for one bbox
		x_min, y_min, x_max, y_max = j['bbox']
		shape = [(x_min, y_min), (x_max, y_max)]
		drawer = ImageDraw.Draw(image)
		drawer.rectangle(shape, outline ="red", width=5)
		my_font = ImageFont.truetype('arial.ttf', 20)
		drawer.text((x_min,y_min), j['category'], font=my_font, fill = (255, 255, 0))
	if saver == 1:
		image.save(location + image_dict['img_fn'].split('/')[-1])
	return image


# -*- coding: utf-8 -*-
import utils, MasterData, BOD_model, excel_template_validation
from copy import copy
import excel_template_utils
import spold2_reader as spold2
filters = True
MD = MasterData.get_current_MD()
folder = r'C:\Dropbox (ecoinvent)\ei-int\technical\external\SRI\data collection\SRI_Modelling Tool for Agriculture\Technical'
filename = 'mapping_20171122.xlsx'
df = utils.read_excel(folder, filename, 'elementaryExchange')
df = df[df['to add in ecoinvent'] == True]
exchanges = []
meta = copy(excel_template_utils.default_meta)
meta['dataEntryBy_personName'] = 'Guillaume Bourgault'
meta['dataGeneratorAndPublication_personName'] = 'Guillaume Bourgault'
meta = copy([meta])
if not filters:
    to_add = dict(zip(excel_template_utils.columns_for_excel['exchanges'],
        ['']*len(excel_template_utils.columns_for_excel['exchanges'])))
    to_add['name'] = '1-propanol'
    to_add['amount'] = 1.
    to_add['unitName'] = 'kg'
    to_add['group'] = 'ReferenceProduct'
    to_add['PV_amount'] = 1.
    to_add['PV_comment'] = 'bla'
    exchanges.append(to_add)
    properties = []
    ElementaryExchanges = []
    MD['ElementaryExchanges prop.'] = MD['ElementaryExchanges prop.'].set_index(
        ['name', 'propertyName']).sort_index(level=0)
    for i, sel in df.iterrows():
        to_add = dict(zip(excel_template_utils.columns_for_excel['exchanges'],
            ['']*len(excel_template_utils.columns_for_excel['exchanges'])))
        for key in ['name', 'compartment', 'subcompartment']:
            to_add[key] = copy(sel['ecoinvent {}'.format(key)])
        to_add['amount'] = 1.
        to_add['unitName'] = 'kg'
        if 'resource' in to_add['compartment']:
            to_add['group'] = 'FromEnvironment'
        else:
            to_add['group'] = 'ToEnvironment'
        exchanges.append(to_add)
        ElementaryExchangeId = utils.uuid_generator('IntermediateExchanges', to_add)
        to_add = {'id': copy(ElementaryExchangeId),
                  'name': to_add['name'], 'compartment': to_add['compartment'],
                  'subcompartment': to_add['subcompartment'],
                    'unitName': to_add['unitName'],
                    'casNumber': sel['CAS'],
                    'synonym': '',
                    'comment': '',
                    'formula': sel['formula']}
        ElementaryExchanges.append(to_add)
        if sel['present in other compartment/subcompartment'] == True:
            md_sel = MD['ElementaryExchanges prop.'].loc[to_add['name']]
            for p_name in set(md_sel.index):
                to_add = utils.dataframe_to_series(md_sel.loc[p_name], allow_multiple_line = True).to_dict()
                to_add['id'] = copy(ElementaryExchangeId)
                to_add['name'] = sel['ecoinvent name']
                to_add['propertyName'] = p_name
                to_add['compartment'] = sel['ecoinvent compartment']
                to_add['subcompartment'] = sel['ecoinvent subcompartment']
                properties.append(to_add)
        else:
            for to_add in excel_template_utils.mandatory_properties:
                to_add = copy(to_add)
                if to_add['propertyName'] in ['dry mass', 'wet mass']:
                    to_add['amount'] = 1.
                elif to_add['propertyName'] in ['water in wet mass', 'water content', 'carbon content, non-fossil']:
                    to_add['amount'] = 0.
                else:
                    if utils.is_empty(sel['formula']):
                        if sel['ecoinvent name'] == 'Pyrethrum':
                            to_add['amount'] = .3
                        elif sel['ecoinvent name'] == 'Potassium soap':
                            to_add['amount'] = 0.
                    else:
                        to_add['amount'] = BOD_model.carbon_content(sel['formula'])
                to_add['id'] = copy(ElementaryExchangeId)
                to_add['name'] = copy(ElementaryExchanges[-1]['name'])
                to_add['compartment'] = sel['ecoinvent compartment']
                to_add['subcompartment'] = sel['ecoinvent subcompartment']
                to_add['isDefiningValue'] = False
                properties.append(to_add)
df = utils.read_excel(folder, filename, 'activityName')
df = df[df['reference product'].isin(['blueberry', 'cranberry', 'raspberry'])]
dfs = []
intermediateExchanges = []
intermediateExchanges_prop = []
for i, sel in df.iterrows():
    m = copy(meta[0])
    m['activityName'] = copy(sel['activityName'])
    m['ISIC'] = copy(sel['ISIC'])
    meta.append(m)
    to_add = dict(zip(excel_template_utils.columns_for_excel['exchanges'],
        ['']*len(excel_template_utils.columns_for_excel['exchanges'])))
    to_add['group'] = 'ReferenceProduct'
    to_add['PV_amount'] = 4.
    to_add['PV_comment'] = 'bla'
    to_add['amount'] = 1.
    to_add['unitName'] = 'kg'
    to_add['activityName'] = m['activityName']
    to_add['geography'] = m['geography']
    to_add['name'] = copy(sel['reference product'])
    exchanges.append(copy(to_add))
    to_add = {}
    to_add['name'] = copy(sel['reference product'])
    to_add['comment'] = copy(sel['comment'])
    to_add['CPC'] = copy(sel['CPC'])
    intermediateExchanges.append(copy(to_add))
    to_add['propertyName'] = 'dry mass'
    to_add['amount'] = sel['dry mass']
    to_add['unitName'] = 'kg'
    to_add['comment'] = copy(sel['comment'])
    intermediateExchanges_prop.append(copy(to_add))
    to_add['comment'] = ''
    to_add['propertyName'] = 'wet mass'
    to_add['amount'] = 1.
    to_add['unitName'] = 'kg'
    intermediateExchanges_prop.append(copy(to_add))
    to_add['propertyName'] = 'carbon content, fossil'
    to_add['amount'] = 0.
    to_add['unitName'] = 'dimensionless'
    intermediateExchanges_prop.append(copy(to_add))
    to_add['propertyName'] = 'carbon content, non-fossil'
    to_add['amount'] = 0.475
    to_add['comment'] = 'http://www.fao.org/forestry/17111/en/'
    to_add['unitName'] = 'dimensionless'
    intermediateExchanges_prop.append(copy(to_add))
    to_add['comment'] = ''
    to_add['propertyName'] = 'water in wet mass'
    to_add['amount'] = 1. - sel['dry mass']
    to_add['unitName'] = 'kg'
    intermediateExchanges_prop.append(copy(to_add))
    to_add['propertyName'] = 'water content'
    to_add['amount'] = (1. - sel['dry mass']) / sel['dry mass']
    to_add['unitName'] = 'dimensionless'
    intermediateExchanges_prop.append(copy(to_add))
intermediateExchanges_prop = utils.list_to_df(intermediateExchanges_prop)
intermediateExchanges = utils.list_to_df(intermediateExchanges)
intermediateExchanges['unitName'] = 'kg'
intermediateExchanges['By-product classification'] = 'allocatable product'
intermediateExchanges = utils.add_empty_columns(
    intermediateExchanges, list(MD['IntermediateExchanges'].columns))
intermediateExchanges['id'] = intermediateExchanges[['name']].apply(
    lambda x: utils.uuid_generator('IntermediateExchanges', x), axis = 1)
intermediateExchanges['comment'] = ''
intermediateExchanges_prop['id'] = intermediateExchanges_prop[['name']].apply(
    lambda x: utils.uuid_generator('IntermediateExchanges', x), axis = 1)
MD = MasterData.get_current_MD()
MD['Properties'] = MD['Properties'].rename(columns = {
    'id': 'propertyId', 'name': 'propertyName'}).set_index('propertyName')
intermediateExchanges_prop = intermediateExchanges_prop.set_index('propertyName').join(
    MD['Properties'][['propertyId']]).reset_index()
intermediateExchanges_prop = utils.add_empty_columns(
    intermediateExchanges_prop, MasterData.excel_columns['IntermediateExchanges prop.'])
exchanges = utils.list_to_df(exchanges)
meta = utils.list_to_df(meta)
meta['fileAttributes_majorRevision'] = 1
meta['fileAttributes_minoRevision'] = 2
meta = meta[meta['activityName'] != 'TO_DELETE']
dfs.append((meta, 'meta', excel_template_utils.columns_for_excel['meta']))
dfs.append((exchanges, 'exchanges',
    excel_template_utils.columns_for_excel['exchanges']))
if not filters:
    dfs.append((utils.list_to_df(ElementaryExchanges), 'ElementaryExchanges',
        MasterData.excel_columns['ElementaryExchanges']))
    properties = utils.list_to_df(properties)
    dfs.append((properties, 'ElementaryExchanges prop.',
        MasterData.excel_columns['ElementaryExchanges prop.']))
dfs.append((intermediateExchanges, 'IntermediateExchanges',
    MasterData.excel_columns['IntermediateExchanges']))
dfs.append((intermediateExchanges_prop, 'IntermediateExchanges prop.',
    MasterData.excel_columns['IntermediateExchanges prop.']))
folder = r'C:\Dropbox (ecoinvent)\ei-int\technical\external\SRI\data collection\SRI_Modelling Tool for Agriculture\Technical'
filename = 'template_for_new_MD.xlsx'
utils.dataframe_to_excel(folder, filename, dfs, feedback = True)

do_recalc_test = False
excel_template_validation.validate_template(folder, filename, do_recalc_test = do_recalc_test)
filename = 'template_for_new_MD_validated.xlsx'
result_folder = r'C:\Dropbox (ecoinvent)\ei-int\technical\external\SRI\data collection\SRI_Modelling Tool for Agriculture\Technical\spolds'
spold2.template_to_spold2(folder, filename, result_folder, restricted = True)


"""
Crawler for Empregos.com.br based on ATSSpider

scrapy crawl empregos -a extract=1 -a url="http://www.empregos.com.br/vagas"

Sample URLS:
    http://www.empregos.com.br/vagas/modal/3806075?4847345
"""

from re import compile
from scrapy.http import Request
from scrapy.selector import Selector

from brightcorp.base.atsspiders import ATSSpider
from brightcorp.items import BrightcorpItemLoader
from brightcorp.processors import Prefix, NormalizedJoin

REF_REGEX = compile(r'/(\d+)?(\d+)')
LOCATION_RE = compile(r'([^-]+)')
DATE_RE = compile(r'Publicada em (\S+)')

class Empregos(ATSSpider):

    name = 'empregos'
    allowed_domains = ['empregos.com.br']

    def parse(self, response):
        """
            GET request method to find out all the jobs.
        """
        sel = Selector(response)
        for result in sel.xpath('//div[@class="vaga"]'):
            meta= {}
            meta['title'] = result.xpath('.//a[contains(@id, "tituloVaga")]/text()').extract()
            meta['company'] = result.xpath('.//div[contains(@id, "dvItemsVerdes")]//a/text()').extract()
            url = result.xpath('.//a[contains(@id, "tituloVaga")]/@href').extract()
            if url:
                yield Request(callback=self.parse_job_callback(), url=url[0], meta=meta)

        next_page = sel.xpath('//a[@class="proximo"]/@href').extract()
        if next_page:
            yield Request(callback=self.parse, url=next_page[0])

    def parse_job(self, response):
        """
            Extract all required information.
            If response url is same as domain, loader object will returns the items.
        """
        sel = Selector(response)
        loader = BrightcorpItemLoader(selector=sel)
        for key in ['title', 'company', 'date']:
            loader.add_value(key, response.meta.get(key))

        loader.add_xpath('title', '//div[contains(@class, "titulo-outros")]/h1/text()')
        loader.add_xpath('company', '//div[contains(@class, "titulo-outros")]/p/a//text()')
        loader.add_xpath('date', '//div[contains(@class, "titulo-outros")]/p//text()', re=DATE_RE)

        loader.add_xpath('description', '(//tr[contains(@id, "Descricao")])[1]/td[@class="col-dir"]/p/text()')
        loader.add_xpath('qualifications', '(//tr[contains(@id, "trQualificacao")])[1]/td[@class="col-dir"]/p/text()')
        loader.add_xpath('educationrequirements', '(//tr[contains(@id, "trFormacao")])[1]/td[@class="col-dir"]/p/text()')
        loader.add_xpath('location', '(//tr[contains(@id, "trLocalTrabalho")])[1]/td[@class="col-dir"]/p/text()[1]')
        loader.add_xpath('location', '//div[contains(@class, "titulo-outros")]/p/strong//text()', re=LOCATION_RE)

        loader.add_value('referencenumber', response.url, NormalizedJoin('-'), Prefix('empregos-'), re=REF_REGEX)
        loader.add_value('url', response.url)
        loader.add_value('apply_url', response.url)
        yield loader.load_item()


def stufe1():
    """Gibt ein Dict der am häufigsten benutzten Wörter zurück"""

    return {
        'die': None, 'der': None, 'und': None, 'in': None, 'zu': None,
        'den': None, 'das': None, 'nicht': None, 'von': None, 'sie': None,
        'ist': None, 'des': None, 'sich': None, 'mit': None, 'dem': None,
        'dass': None, 'er': None, 'es': None, 'ein': None, 'ich': None,
        'auf': None, 'so': None, 'eine': None, 'auch': None, 'als': None,
        'an': None, 'nach': None, 'wie': None, 'im': None, 'für': None,
        'man': None, 'aber': None, 'aus': None, 'durch': None, 'wenn': None,
        'nur': None, 'war': None, 'noch': None, 'werden': None, 'bei': None,
        'hat': None, 'wir': None, 'was': None, 'wird': None, 'sein': None,
        'einen': None, 'welche': None, 'sind': None, 'oder': None, 'zur': None,
        'um': None, 'haben': None, 'einer': None, 'mir': None, 'über': None,
        'ihm': None, 'diese': None, 'einem': None, 'ihr': None, 'uns': None,
        'da': None, 'zum': None, 'kann': None, 'doch': None, 'vor': None,
        'dieser': None, 'mich': None, 'ihn': None, 'du': None, 'hatte': None,
        'seine': None, 'mehr': None, 'am': None, 'denn': None, 'nun': None,
        'unter': None, 'sehr': None, 'selbst': None, 'schon': None,
        'hier': None, 'bis': None, 'habe': None, 'ihre': None, 'dann': None,
        'ihnen': None, 'seiner': None, 'alle': None, 'wieder': None,
        'meine': None, 'Zeit': None, 'gegen': None, 'vom': None, 'ganz': None,
        'einzelnen': None, 'wo': None, 'muss': None, 'ohne': None,
        'eines': None, 'können': None, 'sei': None, 'ja': None, 'wurde': None,
        'jetzt': None, 'immer': None, 'seinen': None, 'wohl': None,
        'dieses': None, 'ihren': None, 'würde': None, 'diesen': None,
        'sondern': None, 'weil': None, 'welcher': None, 'nichts': None,
        'diesem': None, 'alles': None, 'waren': None, 'will': None,
        'Herr': None, 'viel': None, 'mein': None, 'also': None, 'soll': None,
        'worden': None, 'lassen': None, 'dies': None, 'machen': None,
        'ihrer': None, 'weiter': None, 'Leben': None, 'recht': None,
        'etwas': None, 'keine': None, 'seinem': None, 'ob': None, 'dir': None,
        'allen': None, 'großen': None, 'Jahre': None, 'Weise': None,
        'müssen': None, 'welches': None, 'wäre': None, 'erst': None,
        'einmal': None, 'Mann': None, 'hätte': None, 'zwei': None, 'dich': None,
        'allein': None, 'Herren': None, 'während': None, 'Paragraph': None,
        'anders': None, 'Liebe': None, 'kein': None, 'damit': None, 'gar': None,
        'Hand': None, 'Herrn': None, 'euch': None, 'sollte': None,
        'konnte': None, 'ersten': None, 'deren': None, 'zwischen': None,
        'wollen': None, 'denen': None, 'dessen': None, 'sagen': None,
        'bin': None, 'Menschen': None, 'gut': None, 'darauf': None,
        'wurden': None, 'weiß': None, 'gewesen': None, 'Seite': None,
        'bald': None, 'weit': None, 'große': None, 'solche': None,
        'hatten': None, 'eben': None, 'andern': None, 'beiden': None,
        'macht': None, 'sehen': None, 'ganze': None, 'anderen': None,
        'lange': None, 'wer': None, 'ihrem': None, 'zwar': None,
        'gemacht': None, 'dort': None, 'kommen': None, 'Welt': None,
        'heute': None, 'Frau': None, 'werde': None, 'derselben': None,
        'ganzen': None, 'deutschen': None, 'lässt': None, 'vielleicht': None,
        'meiner': None
    }

def stufe2():
    """Gibt ein Dict des Grundwortschatzes zurück"""

    return {
        'ab': None, 'Abend': None, 'abends': None, 'aber': None,
        'abfahren': None, 'Abfahrt': None, 'abgeben': None, 'abholen': None,
        'abschließen': None, 'abstellen': None, 'Acht': None, 'geben': None,
        'achtgeben': None, 'acht': None, 'achte': None, 'Achtung!': None,
        'achtzehn': None, 'achtzehnte': None, 'achtzig': None,
        'achtzigste': None, 'Adresse': None, 'Alkohol': None, 'all': None,
        'allein': None, 'also': None, 'alt': None, 'Alter': None, 'Ampel': None,
        'an': None, 'anbieten': None, 'Angebot': None, 'aner': None,
        'ans': None, 'änn': None, 'anfangen': None, 'Anfang': None,
        'Angestellte': None, 'Angst': None, 'anklicken': None, 'ankommen': None,
        'Ankunft': None, 'ankreuzen': None, 'anmachen': None, '(sich)': None,
        'anmelden': None, 'Anmeldung': None, 'Anrede': None, 'anrufen': None,
        'Anruf': None, 'Anrufbeantworter': None, 'Ansage': None,
        'Anschluss': None, 'sein': None, 'antworten': None, 'Antwort': None,
        'Anzeige': None, 'anziehen': None, 'Anzug': None, 'Apfel': None,
        'Appartement': None, 'Apotheke': None, 'Appetit': None, 'April': None,
        'arbeiten': None, 'Arbeit': None, 'Arbeiter': None, 'arbeitslos': None,
        'Arbeitsplatz': None, 'ärgern': None, 'Ärger': None, 'arm': None,
        'Arm': None, 'Arzt': None, 'Ärztin': None, 'auch': None, 'auf': None,
        'Aufenthalt': None, 'keinen': None, 'Fall': None, 'Aufgabe': None,
        'aufhören': None, 'aufmachen': None, 'aufpassen': None,
        'aufräumen': None, 'aufstehen': None, 'Aufzug': None, 'Auge': None,
        'August': None, 'aus': None, 'Ausbildung': None, 'Ausflug': None,
        'ausfüllen': None, 'Ausgang': None, 'ausgeben': None, 'Auskunft': None,
        'Ausland': None, 'Auslän': None, 'Auslänin': None, 'ausländisch': None,
        'ausmachen': None, 'auspacken': None, 'ausruhen': None, 'Aussage': None,
        'aussehen': None, 'Ausstellung': None, 'außen': None, 'außer': None,
        'außerdem': None, 'außerhalb': None, 'aussteigen': None,
        'Ausweis': None, 'ausziehen': None, 'Auto': None, 'Autobahn': None,
        'Automat': None, 'automatisch': None, 'Baby': None, 'backen': None,
        'Bäckerei': None, 'Bad': None, 'baden': None, 'Bahn': None,
        'Bahnhof': None, 'Bahnsteig': None, 'bald': None, 'Balkon': None,
        'Banane': None, 'Bank': None, 'bar': None, 'Batterie': None,
        'Bauch': None, 'Baum': None, 'Beamte': None, 'Beamtin': None,
        'beeilen': None, 'bedeuten': None, 'beginnen': None, 'behalten': None,
        'bei': None, 'beide': None, 'Bein': None, 'Beispiel': None, 'zum': None,
        'z.': None, 'B.': None, 'bekannt': None, 'Bekannte': None,
        'bekommen': None, 'benutzen': None, 'Benzin': None, 'Beratung': None,
        'Berg': None, 'Beruf': None, 'Berufsschule': None, 'Bescheid': None,
        'sagen': None, 'beschweren': None, 'besetzt': None, 'besichtigen': None,
        'besons': None, 'besser': None, 'am': None, 'besten': None,
        'bestehen': None, 'bestellen': None, 'besuchen': None, 'Besuch': None,
        'Betrag': None, 'in': None, 'Betrieb': None, 'Bett': None,
        'betrunken': None, 'Bewerbung': None, 'bezahlen': None, 'Bier': None,
        'Bild': None, 'Bildschirm': None, 'billig': None, 'Birne': None,
        'bis': None, 'bisschen': None, 'bitte': None, 'Bitte': None,
        'bitten': None, 'bitter': None, 'Blatt': None, 'blau': None,
        'bleiben': None, 'Bleistift': None, 'Blick': None, 'blond': None,
        'Blume': None, 'Bluse': None, 'bluten': None, 'Blut': None,
        'böse': None, 'Bogen': None, 'Bohne': None, 'braten': None,
        'brauchen': None, 'braun': None, 'breit': None, 'bremsen': None,
        'Brief': None, 'Briefkasten': None, 'Briefmarke': None,
        'Briefumschlag': None, 'Brieftasche': None, 'Brille': None,
        'bringen': None, 'Brot': None, 'Brötchen': None, 'Bru': None,
        'Brücke': None, 'Buch': None, 'buchen': None, 'Buchstabe': None,
        'buchstabieren': None, 'Büro': None, 'Bus': None, 'ButterCafé': None,
        'CD': None, 'CD-ROM': None, 'Cent': None, 'Chef': None, 'circa': None,
        'ca.': None, 'Computer': None, 'Cremeda': None, 'dabei': None,
        'darauf': None, 'darüber': None, 'Dach': None, 'dafür': None,
        'dagegen': None, 'Dame': None, 'daneben': None, 'danken': None,
        'Dank': None, 'danke': None, 'dann': None, 's': None, 'Datum': None,
        'dauern': None, 'Dauer': None, 'dein': None, 'deins': None,
        'denn': None, 'denken': None, 'deshalb': None, 'deutlich': None,
        'deutsch': None, 'Deutsche': None, 'Deutschland': None,
        'Dezember': None, 'dich': None, 'dick': None, 'Dienstag': None,
        'dienstags': None, 'ser': None, 'se': None, 'Diesel': None,
        'Ding': None, 'dir': None, 'direkt': None, 'Disco': None,
        'diskutieren': None, 'doch': None, 'Doktor': None, 'Dom': None,
        'Donnerstag': None, 'donnerstags': None, 'Doppelzimmer': None,
        'Dorf': None, 'dort': None, 'dorther': None, 'dorthin': None,
        'Dose': None, 'draußen': None, 'dringend': None, 'drinnen': None,
        'drei': None, 'dreißig': None, 'dreißigste': None, 'dreizehn': None,
        'dreizehnte': None, 'dritte': None, 'drucken': None, 'Drucker': None,
        'drücken': None, 'du': None, 'dumm': None, 'dunkel': None, 'dünn': None,
        'durch': None, 'Durchsage': None, 'dürfen': None, 'Durst': None,
        'duschen': None, 'DuscheEcke': None, 'egal': None, 'Ehefrau': None,
        'Ehemann': None, 'Ei': None, 'eigen': None, 'eilig': None, 'ein': None,
        'eine': None, 'einer': None, 'einfach': None, 'einfallen': None,
        'Einführung': None, 'eins': None, 'Eingang': None, 'einkaufen': None,
        'einladen': None, 'Einladung': None, 'einmal': None, 'einrichten': None,
        'einundzwanzig': None, 'einundzwanzigste': None, 'einsteigen': None,
        'Eintritt': None, 'Einwohner': None, 'einzahlen': None,
        'Einzelzimmer': None, 'einziehen': None, 'Eis': None,
        'elektrisch': None, 'elf': None, 'elfte': None, 'Eltern': None,
        'E-Mail': None, 'Empfänger': None, 'Empfängerin': None, 'Empfang': None,
        'empfehlen': None, 'Enkel': None, 'enden': None, 'Ende': None,
        'endlich': None, 'eng': None, 'entschuldigen': None,
        'Entschuldigung': None, 'er': None, 'sie': None, 'es': None,
        'Erdgeschoss': None, 'erinnern': None, 'Erfahrung': None,
        'ergänzen': None, 'erkältet': None, 'Ergebnis': None, 'erklären': None,
        'erlauben': None, 'Erlaubnis': None, 'Ermäßigung': None,
        'erreichen': None, 'erst': None, 'erste': None, 'Erwachsene': None,
        'erzählen': None, 'essen': None, 'Essen': None, 'etwas': None,
        'euer': None, 'Euro': None, 'ExportFabrik': None, 'Fähre': None,
        'fahren': None, 'Fahrer': None, 'Fahrkarte': None, 'Fahrplan': None,
        'Fahrrad': None, 'fallen': None, 'falsch': None, 'Familie': None,
        'Familienname': None, 'Familienstand': None, 'Farbe': None,
        'fast': None, 'Fax': None, 'Februar': None, 'fehlen': None,
        'Fehler': None, 'Feierabend': None, 'feiern': None, 'Feiertag': None,
        'Fenster': None, 'Ferien': None, 'fernsehen': None,
        'Fernsehgerät': None, 'fertig': None, 'Fest': None, 'fett': None,
        'Feuer': None, 'Feuerzeug': None, 'Feuerwehr': None, 'Fieber': None,
        'Film': None, 'finden': None, 'Firma': None, 'Fisch': None, 'fit': None,
        'Flasche': None, 'Fleisch': None, 'fleißig': None, 'fliegen': None,
        'abfliegen': None, 'Abflug': None, 'Flughafen': None, 'Flugzeug': None,
        'Flur': None, 'Fluss': None, 'Formular': None, 'Foto': None,
        'Fotoapparat': None, 'Frage': None, 'fragen': None, 'Frau': None,
        'frei': None, 'Freitag': None, 'freitags': None, 'Freizeit': None,
        'freiwillig': None, 'fremd': None, 'freuen': None, 'Freund': None,
        'Freundin': None, 'freundlich': None, 'frisch': None, 'Friseur': None,
        'Frist': None, 'befristet': None, 'froh': None, 'früh': None,
        'früher': None, 'Frühjahr': None, 'Frühling': None, 'frühstücken': None,
        'Frühstück': None, 'sich': None, 'fühlen': None, 'Führerschein': None,
        'Führung': None, 'Fundbüro': None, 'fünf': None, 'fünfte': None,
        'fünfzehn': None, 'fünfzehnte': None, 'fünfzig': None,
        'fünfzigste': None, 'für': None, 'Fuß': None, 'Fußball': None,
        'Gabel': None, 'ganz': None, 'Garage': None, 'Garantie': None,
        'Garten': None, 'Gas': None, 'Gast': None, 'geboren': None,
        'Geburtsjahr': None, 'Geburtsort': None, 'Geburtstag': None,
        'Gebühr': None, 'geehrt': None, 'gefährlich': None, 'gefallen': None,
        'gegen': None, 'Gegenteil': None, 'gegenüber': None, 'gehen': None,
        'gehören': None, 'gelb': None, 'Geld': None, 'Geldbörse': None,
        'Gemüse': None, 'genau': None, 'genug': None, 'Gepäck': None,
        'gerade': None, 'geradeaus': None, 'Gericht': None, 'gern': None,
        'gerne': None, 'Gesamtschule': None, 'Geschäft': None, 'Geschenk': None,
        'geschieden': None, 'Geschirr': None, 'Geschwister': None,
        'Gesicht': None, 'Gespräch': None, 'gestern': None, 'gestorben': None,
        'gesund': None, 'Gesundheit': None, 'Getränk': None, 'getrennt': None,
        'leben': None, 'Gewicht': None, 'gewinnen': None, 'Gewitter': None,
        'giftig': None, 'Glas': None, 'glauben': None, 'gleich': None,
        'gleichfalls': None, 'Gleis': None, 'Glück': None, 'glücklich': None,
        'Glückwunsch': None, 'Goethe-Institut': None, 'Grad': None,
        '(Celsius)': None, 'Gramm': None, 'gratulieren': None, 'Grenze': None,
        'grau': None, 'grillen': None, 'Grippe': None, 'groß': None,
        'Größe': None, 'Großeltern': None, 'Großmutter': None,
        'Großvater': None, 'grün': None, 'Grundschule': None, 'Gruppe': None,
        'Gruß': None, 'gültig': None, 'günstig': None, 'gut': None,
        'Gymnasium': None, 'Haar': None, 'haben': None, 'Hähnchen': None,
        'halb': None, 'Halbpension': None, 'Halle': None, 'hallo': None,
        'Hals': None, 'halten': None, 'Haltestelle': None, 'Hand': None,
        'Handtuch': None, 'Handy': None, 'hängen': None, 'hart': None,
        'hässlich': None, 'Haus': None, 'Hausaufgabe': None, 'Hausfrau': None,
        'Hausmann': None, 'Haushalt': None, 'Heimat': None, 'heiraten': None,
        'heiß': None, 'heißen': None, 'Heizung': None, 'helfen': None,
        'hell': None, 'Hemd': None, 'her': None, 'herein': None, 'Herd': None,
        'Herbst': None, 'Herr': None, 'herstellen': None, 'Herz': None,
        'herzlich': None, 'heute': None, 'hier': None, 'Hilfe': None,
        'hin': None, 'hinein': None, 'hinaus': None, 'hinten': None,
        'hinter': None, 'Hobby': None, 'hoch': None, 'Hochzeit': None,
        'höflich': None, 'hoffentlich': None, 'holen': None, 'Holz': None,
        'hören': None, 'Hose': None, 'Hotel': None, 'hübsch': None,
        'Hund': None, '(ein)hunt': None, 'huntste': None, 'hunteins': None,
        'hunterste': None, 'Hunger': None, 'husten': None, 'Kaffee': None,
        'Kalen': None, 'kalt': None, 'Kamera': None, 'Kanne': None,
        'kaputt': None, 'Karte': None, 'Kreditkarte': None, 'Scheckkarte': None,
        'Kartoffel': None, 'Käse': None, 'Kasse': None, 'Kassette': None,
        'Kassettenrecor': None, 'Katze': None, 'kaufen': None, 'kaum': None,
        'kein': None, 'Keller': None, 'Kellner': None, 'kennen': None,
        'lernen': None, 'Kenntnisse': None, 'Kennzeichen': None, 'Kette': None,
        'Kfz': None, 'Kilo': None, 'Kilogramm': None, 'Kilometer': None,
        'Kind': None, 'Kingarten': None, 'Kinwagen': None, 'Kino': None,
        'Kiosk': None, 'Kirche': None, 'klar': None, 'Klasse': None,
        'Kleid': None, 'Kleidung': None, 'klein': None, 'klingeln': None,
        'klopfen': None, 'Kneipe': None, 'kochen': None, 'Koffer': None,
        'Kollege': None, 'Kollegin': None, 'komisch': None, 'kommen': None,
        'kompliziert': None, 'können': None, 'Konsulat': None, 'Kontakt': None,
        'Konto': None, 'Kontrolle': None, 'Konzert': None, 'Kopf': None,
        'Körper': None, 'korrigieren': None, 'Kosmetik': None, 'kosten': None,
        'kostenlos': None, 'krank': None, 'Krankenkasse': None,
        'Krankheit': None, 'Kredit': None, 'Kreis': None, 'Kreuzung': None,
        'kriegen': None, 'Küche': None, 'Kuchen': None, 'Kugelschreiber': None,
        'kühl': None, 'Kühlschrank': None, 'kulturell': None, 'kümmern': None,
        'Kunde': None, 'Kundin': None, 'Kündigung': None, 'Kurs': None,
        'kurz': None, 'Idee': None, 'ihr': None, 'ihm': None, 'ihn': None,
        'immer': None, 'Import': None, 'Industrie': None, 'Information': None,
        'Inhalt': None, 'inklusive': None, 'intelligent': None,
        'interessant': None, 'Interesse': None, 'interessieren': None,
        'international': None, 'Internet': None, 'ja': None, 'Jahr': None,
        'Jacke': None, 'Jugendherberge': None, 'Januar': None, 'je': None,
        'jede': None, 'jedes': None, 'jemand': None, 'jetzt': None, 'Job': None,
        'Juli': None, 'Jugendliche': None, 'Juni': None, 'jung': None,
        'JungeKaffee': None, 'lachen': None, 'Laden': None, 'Lager': None,
        'Lampe': None, 'Land': None, 'Landschaft': None, 'lang': None,
        'lange': None, 'langsam': None, 'langweilig': None, 'lassen': None,
        'laufen': None, 'laut': None, 'Leben': None, 'Lebensmittel': None,
        'ledig': None, 'leer': None, 'legen': None, 'Lehre': None,
        'Lehrer': None, 'Lehrerin': None, 'leicht': None, 'leidtun': None,
        'lei': None, 'leihen': None, 'leise': None, 'lesen': None,
        'letzter': None, 'Leute': None, 'Licht': None, 'lieb': None,
        'lieben': None, 'lieber': None, 'Lieblings-': None, 'Lied': None,
        'liefern': None, 'liegen': None, 'links': None, 'Liter': None,
        'Lkw': None, 'Loch': None, 'Löffel': None, 'Lohn': None, 'Lokal': None,
        'los': None, 'lösen': None, 'Lösung': None, 'Luft': None, 'lügen': None,
        'Lust': None, 'lustig': None, 'machen': None, 'Mädchen': None,
        'Magen': None, 'Mai': None, 'Mal': None, 'mal': None, 'man': None,
        'manch': None, 'manchmal': None, 'Mann': None, 'männlich': None,
        'Mantel': None, 'Markt': None, 'März': None, 'Maschine': None,
        'Material': None, 'Mechaniker': None, 'Medikament': None, 'Meer': None,
        'mehr': None, 'Mehrwertsteuer': None, 'mein': None, 'meine': None,
        'meinen': None, 'Meinung': None, 'meist': None, 'meistens': None,
        'Menge': None, 'Mensch': None, 'merken': None, 'Messer': None,
        'Metall': None, 'Meter': None, 'mieten': None, 'Miete': None,
        'Milch': None, 'Million': None, 'millionste': None, 'Milliarde': None,
        'milliardste': None, 'mindestens': None, 'minus': None, 'Minute': None,
        'mit': None, 'mitbringen': None, 'mitkommen': None, 'mitmachen': None,
        'mitnehmen': None, 'Mittag': None, 'mittags': None, 'Mitte': None,
        'Mitteilung': None, 'Mittel': None, 'Mittelschule': None,
        'Mittwoch': None, 'mittwochs': None, 'Möbel': None, 'möbliert': None,
        'möchten': None, 'Mode': None, 'mon': None, 'mögen': None,
        'möglich': None, 'Moment': None, 'Monat': None, 'Montag': None,
        'montags': None, 'morgen': None, 'Morgen': None, 'morgens': None,
        'Motor': None, 'müde': None, 'Müll': None, 'Mülltonne': None,
        'Mund': None, 'Museum': None, 'Musik': None, 'müssen': None,
        'Mutter': None, 'nach': None, 'Nachbar': None, 'Nachbarin': None,
        'Nachrichten': None, 'Nachmittag': None, 'nachmittags': None,
        'Nacht': None, 'nachts': None, 'nächster': None, 'nächste': None,
        'Nähe': None, 'Name': None, 'nämlich': None, 'nass': None,
        'Natur': None, 'natürlich': None, 'Nebel': None, 'neben': None,
        'nebenan': None, 'nehmen': None, 'negativ': None, 'nein': None,
        'nervös': None, 'nett': None, 'netto': None, 'neu': None,
        'neugierig': None, 'Neujahr': None, 'neulich': None, 'neun': None,
        'neunte': None, 'neunzehn': None, 'neunzehnte': None, 'neunzig': None,
        'neunzigste': None, 'nicht': None, 'nichts': None, 'nie': None,
        'niedrig': None, 'niemand': None, 'nirgends': None, 'noch': None,
        'Norden': None, 'normal': None, 'Notarzt': None, 'Note': None,
        'Notfall': None, 'notieren': None, 'nötig': None, 'Notiz': None,
        'Nudel': None, 'November': None, 'Null': None, 'Nummer': None,
        'nur': None, 'ob': None, 'oben': None, 'Ober': None, 'Obst': None,
        'o': None, 'öffnen': None, 'geöffnet': None, 'oft': None, 'ohne': None,
        'Öl': None, 'offen': None, 'Oktober': None, 'Oma': None, 'Opa': None,
        'Operation': None, 'Orange': None, 'Ordnung': None, 'Ort': None,
        'Osten': None, 'Osternpaar': None, 'Päckchen': None, 'Paket': None,
        'Panne': None, 'Parfüm': None, 'Papier': None, 'Papiere': None,
        'Park': None, 'parken': None, 'Partner': None, 'Partnerin': None,
        'Party': None, 'Pass': None, 'passen': None, 'passieren': None,
        'Pause': None, 'Pension': None, 'pensioniert': None, 'Pfund': None,
        'Pkw': None, 'Plan': None, 'Plastik': None, 'Platz': None,
        'plötzlich': None, 'plus': None, 'Polizei': None, 'Pommes': None,
        'frites': None, 'Portion': None, 'positiv': None, 'Post': None,
        'Postleitzahl': None, 'praktisch': None, 'Praktikum': None,
        'Praxis': None, 'Preis': None, 'preiswert': None, 'prima': None,
        'privat': None, 'probieren': None, 'Problem': None, 'Produkt': None,
        'Programm': None, 'Prospekt': None, 'Prüfung': None, 'Pullover': None,
        'Prozent': None, 'pünktlich': None, 'putzen': None,
        'Quadratmeter': None, 'Qualität': None, 'Quatsch': None,
        'Quittung': None, 'Rabatt': None, 'Rad': None, 'Radio': None,
        'Rathaus': None, 'rauchen': None, 'Raucher': None, 'Raucherin': None,
        'Raum': None, 'Realschule': None, 'Rechnung': None, 'Recht': None,
        'rechts': None, 'regnen': None, 'Regen': None, 'reich': None,
        'Reifen': None, 'Reinigung': None, 'Reis': None, 'reisen': None,
        'Reise': None, 'Reisebüro': None, 'Reiseführer': None,
        'renovieren': None, 'reparieren': None, 'Reparatur': None,
        'reservieren': None, 'Restaurant': None, 'Rezept': None,
        'Rezeption': None, 'richtig': None, 'riechen': None, 'Rind': None,
        'Rock': None, 'Rose': None, 'Rücken': None, 'rückwärts': None,
        'rot': None, 'ruhig': None, 'rund': None, 'RundgangSache': None,
        'Saft': None, 'Salat': None, 'Salz': None, 'sammeln': None,
        'Samstag': None, 'Sonnabend': None, 'samstags': None,
        'sonnabends': None, 'Satz': None, 'sauber': None, 'sauer': None,
        'S-Bahn': None, 'schade': None, 'Schalter': None, 'scharf': None,
        'scheinen': None, 'schenken': None, 'schicken': None, 'Schiff': None,
        'Schild': None, 'Schinken': None, 'Schirm': None, 'schlafen': None,
        'schlecht': None, 'schließen': None, 'geschlossen': None,
        'schlimm': None, 'Schloss': None, 'Schluss': None, 'Schlüssel': None,
        'schmecken': None, 'Schmerzen': None, 'schmutzig': None, 'Schnee': None,
        'schneien': None, 'schneiden': None, 'schnell': None,
        'Schokolade': None, 'schon': None, 'Schnupfen': None, 'schön': None,
        'Schrank': None, 'schrecklich': None, 'schreiben': None,
        'aufschreiben': None, 'schriftlich': None, 'Schuh': None,
        'Schule': None, 'Schüler': None, 'schwach': None, 'schwanger': None,
        'Schwein': None, 'Schülerin': None, 'schwarz': None, 'schwer': None,
        'Schwester': None, 'schwimmen': None, 'Schwimmbad': None, 'sechs': None,
        'sechste': None, 'sechzehn': None, 'sechzehnte': None, 'sechzig': None,
        'sechzigste': None, 'See': None, 'sehen': None, 'Sendung': None,
        'Sehenswürdigkeit': None, 'sehr': None, 'Seife': None, 'weg': None,
        'zu': None, 'seit': None, 'Sekretärin': None, 'Sekunde': None,
        'selbst': None, 'selbstständig': None, 'Senioren': None,
        'Service': None, 'Sessel': None, 'setzen': None, 'September': None,
        'sicher': None, 'Sie': None, 'sieben': None, 'siebte': None,
        'siebzehn': None, 'siebzehnte': None, 'siebzig': None,
        'siebzigste': None, 'Silvester': None, 'singen': None, 'sitzen': None,
        'so': None, 'Sofa': None, 'sofort': None, 'Sohn': None, 'sollen': None,
        'Sommer': None, 'Sonangebot': None, 'Sonne': None, 'Sonntag': None,
        'sonntags': None, 'sonst': None, 'Sorge': None, 'Sozial-': None,
        'sparen': None, 'Spaß': None, 'spät': None, 'später': None,
        'spazieren': None, 'Spaziergang': None, 'speichern': None,
        'Speisekarte': None, 'spielen': None, 'Spielplatz': None, 'Sport': None,
        'Sprache': None, 'Sprachenschule': None, 'sprechen': None,
        'Sprechstunde': None, 'spülen': None, 'Spülmaschine': None,
        'Stadt': None, 'Standesamt': None, 'stark': None, 'stattfinden': None,
        'stecken': None, 'stehen': None, 'Stelle': None, 'stellen': None,
        'Stempel': None, 'sterben': None, 'Steuer': None, 'stimmen': None,
        'Stock': None, 'Stoff': None, 'stören': None, 'Strand': None,
        'Straße': None, 'Straßenbahn': None, 'Streichholz': None,
        'streiten': None, 'Strom': None, 'Stück': None, 'sturen': None,
        'Studium': None, 'Student': None, 'Studentin': None, 'Stuhl': None,
        'Stunde': None, 'suchen': None, 'Süden': None, 'Supermarkt': None,
        'Suppe': None, 'süß': None, 'sympathisch': None, 'tanken': None,
        'Tankstelle': None, 'Tag': None, 'täglich': None, 'tanzen': None,
        'Tasche': None, 'Tasse': None, 'tausend': None, 'ausendste': None,
        'Taxi': None, 'Tee': None, 'Teil': None, 'teilnehmen': None,
        'telefonieren': None, 'Telefon': None, 'Telefonbuch': None,
        'Teller': None, 'Tennis': None, 'Teppich': None, 'Termin': None,
        'Test': None, 'teuer': None, 'Text': None, 'Theater': None,
        'Thema': None, 'Ticket': None, 'tief': None, 'Tier': None, 'Tipp': None,
        'Tisch': None, 'Tochter': None, 'Toilette': None, 'toll': None,
        'Tomate': None, 'Topf': None, 'tot': None, 'Tourist': None,
        'träumen': None, 'tragen': None, 'traurig': None, 'treffen': None,
        'Treppe': None, 'trinken': None, 'Trinkgeld': None, 'trocken': None,
        'tschüss': None, 'tun': None, 'Tür': None, 'Tüte': None, 'Turm': None,
        'U-Bahn': None, 'über': None, 'überall': None, 'übermorgen': None,
        'übernachten': None, 'Übernachtung': None, 'übersetzen': None,
        'übertragen': None, 'überweisen': None, 'Uhr': None, 'um': None,
        'umsteigen': None, 'umziehen': None, 'und': None, 'Unfall': None,
        'Universität': None, 'unser': None, 'unsere': None, 'unten': None,
        'unter': None, 'unterhalten': None, 'Unterkunft': None,
        'unternehmen': None, 'Unterricht': None, 'Unterschied': None,
        'unterschreiben': None, 'Unterschrift': None, 'untersuchen': None,
        'Untersuchung': None, 'UrlaubVater': None, 'verabredet': None,
        'Verbindung': None, 'verboten': None, 'vernen': None, 'Verein': None,
        'vereinbaren': None, 'vergessen': None, 'vergleichen': None,
        'verheiratet': None, 'verkaufen': None, 'Verkäufer': None,
        'Verkäuferin': None, 'Verkehr': None, 'verlängern': None,
        'verletzen': None, 'verlieren': None, 'vermieten': None,
        'Vermieter': None, 'verpassen': None, 'verrückt': None,
        'verschieben': None, 'verschieden': None, 'Versicherung': None,
        'Verspätung': None, 'versprechen': None, 'verstehen': None,
        'versuchen': None, 'Vertrag': None, 'verwandt': None, 'Verwandte': None,
        'Video': None, 'viel': None, 'vielleicht': None, 'vier': None,
        'vierte': None, 'Viertel': None, 'vierzehn': None, 'vierzehnte': None,
        'vierzig': None, 'vierzigste': None, 'Vogel': None, 'Volksschule': None,
        'voll': None, 'von': None, 'vor': None, 'vorbei': None,
        'vorgestern': None, 'vorher': None, 'vorn': None, 'Vormittag': None,
        'vormittags': None, 'Vorname': None, 'vorschlagen': None,
        'Vorsicht': None, 'vorsichtig': None, 'vorstellen': None,
        'Vorwahl': None, 'vorwärts': None, 'wach': None, 'Wagen': None,
        'wählen': None, 'wahr': None, 'wahrscheinlich': None, 'Wald': None,
        'wann': None, 'warm': None, 'warten': None, 'warum': None, 'was': None,
        'Wäsche': None, 'waschen': None, 'Wasser': None, 'wechseln': None,
        'wecken': None, 'Weg': None, 'wegen': None, 'weggehen': None,
        'wegwerfen': None, 'weh': None, 'weiblich': None, 'weich': None,
        'Weihnachten': None, 'weil': None, 'Wein': None, 'weinen': None,
        'weiß': None, 'weit': None, 'weiter': None, 'welcher': None,
        'welche': None, 'welches': None, 'Welt': None, 'wenig': None,
        'wenigstens': None, 'wenn': None, 'wer': None, 'werden': None,
        'Werkstatt': None, 'werktags': None, 'Werkzeug': None, 'Westen': None,
        'Wetter': None, 'wichtig': None, 'wie': None, 'wieholen': None,
        'Wiehören': None, 'Wiesehen': None, 'willkommen': None, 'Wind': None,
        'Winter': None, 'wir': None, 'wirklich': None, 'Wirtschaft': None,
        'wissen': None, 'wo': None, 'Woche': None, 'Wochenende': None,
        'Wochentag': None, 'wochentags': None, 'woher': None, 'wohin': None,
        'wohnen': None, 'Wohnung': None, 'Wolke': None, 'wollen': None,
        'Wort': None, 'wunbar': None, 'wünschen': None, 'Wunsch': None,
        'WurstZahl': None, 'zahlen': None, 'Zahn': None, 'zeigen': None,
        'Zeit': None, 'zurzeit': None, 'zehn': None, 'zehnte': None,
        'Zeitung': None, 'Zeitschrift': None, 'Zentimeter': None,
        'Zentrum': None, 'Zettel': None, 'Zeugnis': None, 'ziemlich': None,
        'Zigarette': None, 'Zimmer': None, 'Zoll': None, 'Zitrone': None,
        'zumachen': None, 'Zucker': None, 'zuerst': None, 'zufrieden': None,
        'Zug': None, 'zuhören': None, 'zuletzt': None, 'zuordnen': None,
        'zurechtkommen': None, 'zurück': None, 'zusammen': None,
        'zusammenleben': None, 'zwanzig': None, 'zwanzigste': None,
        'zwei': None, 'zweihunt': None, 'zweihuntste': None, 'zweite': None,
        'zwischen': None, 'zwölf': None, 'zwölfte': None
    }

def haeufigkeit(wort):
    """Die Funktion Häufigkeit dient der Einstufung der jeweiligen Wörter, je
    nach dem wie häufig diese gebraucht werden. Ein Wort wird auf der Skala von
    1 bis 3 eingestuft, wobei 1 die 207 häufigsten Wortformen im Deutschen
    umfasst, die 2 für den Grundwortschatz steht. Alle anderen Wörter werden der
    3. Stufe zugewiesen."""

    if wort in stufe1() or wort.lower() in stufe1():
        return 1
    elif wort in stufe2() or wort.lower() in stufe2():
        return 2
    else:
        return 3

def satz_durchschnitt(satz):
    summe = 0
    anzahl = 0

    woerter = satz.split()

    for wort in woerter:
        print(wort)
        print(haeufigkeit(wort))
        summe += haeufigkeit(wort)
        anzahl += 1

    durchschnitt = summe / anzahl

    return durchschnitt


#kamptan august 2017
class Input:

    # creating a method to take the radius of the circle as an input provided by the user
    def inputradius(self):
        while True:
            n = raw_input("Enter the radius: R = ")  # takes the radius as an input form the user
            try:
                # The user input is tried to convert into float
                self.radius= float(n)
                # if input is negative or zero raise an exception
                if self.radius<=0:
                    raise Exception
            # if the user input not valid to convert into float then give the error message
            except ValueError:
                print('You must put an interger, not a charecter! Try again...')
            except Exception:
                print('Invalid input! Radius can not be negative or zero. Please put a postive value. Try again...')
            else:
                break
        # returns the value of the radius
        return self.radius

radius = Input()
# radius.inputradius()


class Color:
    """A color defined in RGB

    Attributes:
        red1(int)
        green1(int)
        blue1(int)
        red2(int)
        green2(int)
        blue2(int)
    """

    def __init__(self):
        self.red1 = None
        self.green1 = None
        self.blue1 = None
        self.red2 = None
        self.green2 = None
        self.blue2 = None

    def from_csv(self, df_color):
        """Modifies self according to df_color.

        Args:
            csv_color_1(string): a string from the color column of a DataFrame
            generated by the create_diplomacy_data_file
            function in the parser module.
            Each color is defined using the rgb scale like this: rgb { R G B }
            R G and B are the values for the intensity of respectively, the red,
            the green and the blue in the color.
            0 <= R, G or B <= 255

        Returns:
            None
        """
        colors = []
        color1 = df_color.split("=")[0]
        color2 = df_color.split("=")[0]
        raw_colors = (color1, color2)
        # We extract the numbers between the brackets.
        for color in raw_colors:
            color = df_color.split("{")[1]
            color = df_color.split("}")[0]
            color = df_color.strip().split()
            for num in color:
                colors.append(int(num))
        color
        self.red1 = colors[0]
        self.green1 = colors[1]
        self.blue1 = colors[2]
        self.red2 = colors[3]
        self.green2 = colors[4]
        self.blue2 = colors[5]

    def __str__(self):
        template = "color = rgb {} {} {} {} {}\ncolor2 = rgb {} {} {} {} {}\n"
        return template.format("{", self.red1, self.green1, self.blue1, "}",
                               "{", self.red2, self.green2, self.blue2, "}")


MOD = 10 ** 9 + 7
for _ in range(int(input())):
    N, A, B = map(int, input().split())

    pt = (pow((N - A + 1), 2, MOD) * pow((N - B + 1), 2, MOD)) % MOD

    for i in range((N + 1) // 2):
        t = ((N - i * 2) - A) * 4
        if t < 0:
            break
        elif t == 0:
            t = 1