import pandas as pd
import sys
import os
import profile_datasets as prod

in_dir = sys.argv[1]
out_dir = sys.argv[2]

files = os.listdir(in_dir)

file_formats = []

for i in files:
    file_formats.append(prod.detect_format(i))

df = pd.DataFrame(file_formats, columns = ['file','format'])

# Get all formats
formats = df['format'].unique().tolist()

# Get list of files of all formats for logs
df_grouped = df.groupby('format')

# Combine xls and xlsx formats
df_xls = df_grouped.get_group('xls').reset_index(drop=True)
df_xlsx = df_grouped.get_group('xlsx').reset_index(drop=True)
df_xl = pd.concat([df_xls,df_xlsx])

# Of the xls or xlsx files, which are workbooks that have multiple pages?
workbooks = []
xl_files = []

for i in df_xl['file']:
    i_file = ('%s/%s') % (in_dir, i)
    if prod.calc_wb_tab(i_file) == 1:
        workbooks.append(i)
    else:
        xl_files.append(i)

# Create files
outfile_wb = '%s/xl_workbooks.txt' % out_dir
pd.Series(workbooks).to_csv(outfile_wb, index = False, header = False)

outfile_xl = '%s/xl.txt' % out_dir
pd.Series(xl_files).to_csv(outfile_xl, index = False, header = False)

# Remove excel formats since we deal with those above
# Remove DS Store if it exists
if 'DS_Store' in formats:
    formats.remove('DS_Store')

for i in ['xls','xlsx']:
    formats.remove(i)

for i in formats:
    dff = df_grouped.get_group(i)
    file_filtered = dff['file']
    outfile = '%s/%s_files.txt' % (out_dir, i)
    file_filtered.to_csv(outfile, index=False, header=False)


import logging
from types import TracebackType

logger = logging.getLogger(__name__)

def exception_handler(
    _type: type,
    value: BaseException,
    traceback: TracebackType
) -> None:
    """Error handler for all exceptions."""
    if str(value):
        msg = f"{_type.__name__}: {value}"
    else:
        msg = f"{_type.__name__}"
    logger.error(msg)

class InvalidObjectData(Exception):
    """Exception raised when object data cannot be validated against the API
    schema.
    """

class InvalidResponseError(Exception):
    """Exception raised when an invalid API response is encountered."""

class InvalidURI(Exception):
    """Exception raised for invalid URIs."""


from health_app.config.mysqlconnection import connectToMySQL

class Vitamin:
    def __init__(self,data):
        self.id = data["id"]
        self.vitamin_name= data["vitamin_name"]
        self.dosage = data["dosage"]
        self.user_id = data["user_id"]

    @classmethod
    def new_vitamin(cls,data):
        query = "INSERT INTO vitamins (vitamin_name, dosage, user_id) VALUES (%(vitamin_name)s, %(dosage)s, %(user_id)s);"
        return connectToMySQL("fitness").query_db(query, data)

    @classmethod
    def get_all_vitamins(cls):
        query = "SELECT * FROM vitamins;"
        results = connectToMySQL("fitness").query_db(query)
        all_vitamins = []
        for row in results:
            all_vitamins.append( cls(row) )
        return all_vitamins

    @classmethod
    def delete_vitamin(cls,data):
        query = "DELETE FROM vitamins WHERE id = %(id)s;"
        return connectToMySQL("fitness").query_db(query, data)


from model.credits.course import Course
import re  # Regular expression

class CoursesByStudent:

    coursesData = []

    def __init__(self):
        pass

    # 0. The Id will be int
    # 1. The name will be string
    # 2. The prerequisites will be a list of strings
    # 3. Optional will be int (0 or 1)
    # 4. The semester will be string
    # 5. The credits will be int
    # 6. The state will be int (-1, 0, 1)

    # Keys for the dictionary of the elective courses String
    elegibilityCourseStr = {
        "Obligatorio": "1",
        "Opcional": "0"
    }
    # List of options to state of the course
    stateCourseStr = {
        "Aprobado": "0",
        "Cursando": "1",
        "Pendiente": "-1"
    }

    # List of options to elective of the course int
    # List of options to elegibility of the course
    elegibilityCourse = {
        1: "Obligatorio",
        0: "Opcional"
    }
    # List of options to state of the course
    stateCourse = {
        0: "Aprobado",
        1: "Cursando",
        - 1: "Pendiente"
    }

    # Regex to validate the fields
    allowValuesForId = re.compile(r'^[0-9]{1,4}$')
    allowValuesForName = re.compile(
        r'.+')  # Allow only letters and numbers and spaces
    allowValuesForPrecourses = re.compile(r'(\d*;?)*')
    allowValuesForOptionals = re.compile(r'(0|1)')
    allowValuesForSemesterAndCredits = re.compile(r'^[0-9]{1,2}$')
    allowValuesForState = re.compile(r'(-1|0|1)')

    # Create a error report to show the errors in the file
    errorReport = ""
    count = 1

    def validateFields(self, idCourse, nameCourse, prerequisites, optional, semester, credits, state):
        if idCourse is None or not re.fullmatch(self.allowValuesForId, idCourse.strip()):
            self.errorReport += "Error en la línea " + \
                str(self.count) + \
                ": El valor - " + \
                idCourse + " - no es válido para Id\n"
            return False
        elif nameCourse is None or not re.fullmatch(self.allowValuesForName, nameCourse.strip()):
            self.errorReport += "Error en la línea " + \
                str(self.count) + \
                ": El valor - " + \
                nameCourse + \
                " - no es válido para Curso\n"
            return False
        elif prerequisites is None or not re.fullmatch(self.allowValuesForPrecourses, prerequisites.strip()):
            self.errorReport += "Error en la línea " + \
                str(self.count) + \
                ": El valor - " + \
                prerequisites + " - no es válido para Prerrequisitos\n"
            return False
        elif optional is None or not re.fullmatch(self.allowValuesForOptionals, optional.strip()):
            self.errorReport += "Error en la línea " + \
                str(self.count) + \
                ": El valor " + \
                optional+" no es válido para Opción\n"
            return False
        elif semester is None or not re.fullmatch(self.allowValuesForSemesterAndCredits, semester.strip()):
            self.errorReport += "Error en la línea " + \
                str(self.count) + \
                ": El valor - " + \
                semester + \
                " - no es válido para Semestre\n"
            return False
        elif credits is None or not re.fullmatch(self.allowValuesForSemesterAndCredits, credits.strip()):
            self.errorReport += "Error en la línea " + \
                str(self.count) + \
                ": El valor - " + \
                credits + " - no es válido para Créditos\n"
            return False
        elif state is None or not re.fullmatch(self.allowValuesForState, state.strip()):

            self.errorReport += "Error en la línea " + \
                str(self.count) + \
                ": El valor - " + \
                state + \
                " - no es válido para Estado\n"
            return False
        if re.fullmatch(self.allowValuesForSemesterAndCredits, semester.strip()):
            if int(semester) > 12 or int(semester) < 1:
                self.errorReport += "Error en la línea " + \
                    str(self.count) + \
                    ": El valor - " + \
                    semester + \
                    " - no es válido para Semestre\n"
                return False
        if re.fullmatch(self.allowValuesForSemesterAndCredits, credits.strip()):
            if int(credits) > 10 or int(credits) < 0:
                self.errorReport += "Error en la línea " + \
                    str(self.count) + \
                    ": El valor - " + \
                    credits + \
                    " - no es válido para Créditos\n"
                return False

    '''Read the file and create the courses'''

    def uploadCourses(self, routeFile):
        if(routeFile == ""):
            self.errorReport = "No se seleccionó ningun archivo"
        else:
            file = open(routeFile, "r", encoding="utf8", errors='ignore')
            for line in file:
                if(line != ""):
                    verifyCourse = line.split(",")
                    if len(verifyCourse) == 7:
                        # Define a regex to validate just numbers and limite the length of the field to 3-4 characters
                        isValidate = self.validateFields(verifyCourse[0], verifyCourse[1], verifyCourse[2],
                                                         verifyCourse[3], verifyCourse[4], verifyCourse[5], verifyCourse[6])

                        if isValidate is None:
                            newCourse = Course(int(verifyCourse[0]), verifyCourse[1], verifyCourse[2],
                                               int(verifyCourse[3]), int(verifyCourse[4]), int(verifyCourse[5]), int(verifyCourse[6]))
                            # Verify if the course exist in the system
                            for course in self.coursesData:
                                if newCourse.idCourse == course.idCourse:
                                    self.coursesData.remove(course)
                            self.coursesData.append(newCourse)
                    else:
                        self.errorReport += "Error en la línea " + \
                            str(self.count) + ": " + \
                            line + " - Error en la cantidad de campos\n"
                else:
                    self.errorReport += "Error en la línea " + \
                        str(self.count) + ": " + " - La línea está vacía\n"

                self.count += 1
            file.close()
            return self.errorReport

    def getCoursesData(self):
        return self.coursesData

    def createCourseByForm(self, idCourse, nameCourse, prerequisites, semester, optional,  credits, state):
        optional = self.elegibilityCourseStr[optional]
        state = self.stateCourseStr[state]

        self.validateFields(idCourse, nameCourse, prerequisites,
                            optional, semester, credits, state)
        if self.errorReport == "":
            idCourse = int(idCourse)
            newCourse = Course(idCourse, nameCourse, prerequisites, int(
                optional), semester, int(credits), int(state))
            # Verify if the course exist in the system
            for course in self.coursesData:
                if self.getCourseById(idCourse) is not None:
                    self.coursesData.remove(course)
            self.coursesData.append(newCourse)
            return self.errorReport
        else:
            return self.errorReport

    def getCourseById(self, idCourse):
        for course in self.coursesData:
            if course.idCourse == idCourse:
                return course
        return None

    def getLengthCoursesData(self):
        return len(self.coursesData)

    def updateCourse(self, idCourse, nameCourse, prerequisites, semester, optional,  credits, state):

        optional = self.elegibilityCourseStr[optional]
        state = self.stateCourseStr[state]

        self.validateFields(idCourse, nameCourse, prerequisites,
                            optional, semester, credits, state)
        if self.errorReport == "":
            idCourse = int(idCourse)
            if self.getCourseById(idCourse) is not None:
                for course in self.coursesData:
                    if course.idCourse == idCourse:
                        course.setName(nameCourse)
                        course.setIdCoursesRequired(prerequisites)
                        course.setIsRequired(int(optional))
                        course.setSemester(int(semester))
                        course.setCredits(int(credits))
                        course.setCurrentState(int(state))

                        return self.errorReport
            else:
                self.errorReport += "Error en la línea " + \
                    str(self.count) + ": " + \
                    " - El curso no existe\n"
                return self.errorReport
        else:
            return self.errorReport

    def deleteCourse(self, idCourse):
        for course in self.coursesData:
            if course.idCourse == int(idCourse):
                self.coursesData.remove(course)
                return True
        return False

    '''Create the functions to count credits'''

    def countApprovedCredits(self):
        count = 0
        for course in self.coursesData:
            if course.getCurrentState() == 0:
                count += course.getCredits()
        return count

    def countCurrentCredits(self):
        count = 0
        for course in self.coursesData:
            if course.getCurrentState() == 1:
                count += course.getCredits()
        return count

    def countPendingCredits(self):
        count = 0
        for course in self.coursesData:
            if course.getCurrentState() == -1:
                if course.getIsRequired() == 1:
                    count += course.getCredits()
        return count

    def countCreditsAtCurrentSemester(self, semester):
        count = 0
        for course in self.coursesData:
            if course.getSemester() <= semester:
                if course.getIsRequired() == 1:
                    count += course.getCredits()
        return count

    def countCreditsBySemester(self, semester):
        count = 0
        for course in self.coursesData:
            if course.getSemester() == semester:
                count += course.getCredits()
        return count


from flask import render_template, redirect, url_for, session
import data.db as db
import time
import datetime
import zipcodes
import pandas as pd
from services.UserService import UserService
from services.SharedService import CoreService, InsightsService
from services.AdminService import AdminService, AdminUserService, MessagingService, TaskService, TacticService
from services.CompetitorService import CompetitorService
from services.TacticsService import TacticsService
from services.AdSpend import GetRec
from services.Blog import Blog
import services.forms as forms
import json
import itertools
from services.PaymentsService import PaymentsService

class SplashViewModel:
	def __init__(self, next_step=None):
		self.next_step = next_step

	def splashes(self):
		return ['begin', 'competitors', 'company', 'audience', 'product', 'salescycle', 'history']

	def compile_splash(self):
		tup = (self.next_step,)
		query = "SELECT heading, paragraph FROM dbo.splash WHERE after_page = ?"
		data, cursor = db.execute(query, True, tup)
		del data
		heading, paragraph = cursor.fetchone()
		self.heading = heading.replace("`", "'")
		self.paragraph = paragraph.replace("`", "'")
		cursor.close()

class ContainerViewModel:
	def __init__(self, page=None, user=None):
		if page == 'audience':
			self.table = page
		elif page == 'product_2':
			self.table = 'product_list'
		self.user = user

	def GetData(self):
		if self.table == 'audience':
			params = ('persona_name', 'audience_id', self.table, self.user)
		elif self.table == 'product_list':
			params = ('name', 'p_id', self.table, self.user)

		query = "SELECT %s, %s FROM %s WHERE customer_id = %s" % params
		data, cursor = db.execute(query, True, ())
		data = cursor.fetchall()

		column_list = ['name', 'id']
		data = UserService.parseCursor(data, column_list)

		return data

class IntakeViewModel:
	def __init__(self, id, user_name, title=None):
		stage_1 = ['competitors', 'company', 'audience', 'product', 'product_2', 'salescycle']
		stage_2 = ['goals']
		stage_3 = ['history', 'platforms', 'past']
		stage_4 = ['creative']
		custom = ['salescycle', 'history', 'platforms']
		self.id = id
		self.title = title
		self.name = user_name

		if self.title in stage_1:
			self.stage = 1
		elif self.title in stage_2:
			self.stage = 2
		elif self.title in stage_3:
			self.stage = 3
		elif self.title in stage_4:
			self.stage = 4
		else:
			self.stage = 0

		def get_copy(self):
			query = """

					SELECT * FROM dbo.everything as e
					WHERE
					e.page_title = '%s'

					and
					(
						NOT EXISTS (select * from should_show(e.relevant_tags, %s))
						OR
						e.relevant_tags IS null
					)

					ORDER BY e.order_on_page

					""" % (self.title, self.id)

			data, cursor = db.execute(query, True, ())
			data = data.fetchall()
			cursor.close()
			return data

		columns = ['q_id', 'page_id', 'page_title', 'page_h1', 'page_p', 'label', 'why_asking_binary', 'why_label', 'what_binary', 'what_label', 'required_binary', 'label_p', 'horizontal_separator_binary', 'container_binary', 'answer_type', 'placeholder', 'a_format', 'html_name', 'route', 'tiles_name_h6', 'tiles_name_p', 'icon_file_path', 'sub_name', 'relevant_tags', 'order_on_page', 'q_group']
		if self.title not in custom:
			self.questions = UserService.parseCursor(get_copy(self), columns)
		else:
			self.questions = None

class AdminViewFuncs:
	def __init__(self, customer_id):
		self.service = AdminService()
		self.customer_id = customer_id

	def ValidView(self, validity=False):
		validity = self.service.validate_view(session['admin'], self.customer_id)
		if validity == True or session['owner_logged_in'] == True:
			return True
		else:
			return False

class AdminViewModel:
	def __init__(self,
				permission_level: str,
				page: str,
				user=None,
				admin=None,
				view=None,
				tag_id=None) -> None:

		self.tag_id = tag_id
		self.permission_level = permission_level
		self.page = page
		self.admin_service = AdminService()
		self.admin = admin
		self.view = view
		self.user = user
		self.view_type = 'admin'
		self.admins = self.admin_service.get_admins()
		self.switch(page)()

	def switch(self, case: str) -> None:
		switcher = {
			"personnel": self.personnel,
			"customers": self.customers,
			"home": self.home,
			"acct_mgmt": self.acct_mgmt,
			"tags": self.tags,
			"campaigns": self.campaigns,
			"None": True
		}
		return switcher[case]

	def campaigns(self):
		query = "select facebook_id, google_id, twitter_id from customer_basic where id = ?"
		data, cursor = db.execute(query, True, (self.user,))
		data = cursor.fetchone()

		meta = self.admin_dashboard()
		self.accounts = {
			'facebook_id': data[0],
			'google_id': data[1],
			'twitter_id': data[2],
			'meta': self.admin_dashboard()
		}

	def tags(self):
		tags = TacticService(tag_id=self.tag_id)
		meta = tags.meta()
		self.total_tags = tags.count()
		self.tactic_id = meta['0']['tactic_id']
		self.tactic_title = meta['0']['title']
		self.tactic_description = meta['0']['description']
		self.image = meta['0']['image']
		self.category = meta['0']['category']

	def admin_dashboard(self):
		query = 'SELECT * from admin_dashboard(?)'
		returned, cursor = db.execute(query, True, (self.user,))
		returned = cursor.fetchone()

		if returned[2]:
			num_campaigns = returned[5]
			plan = f'{num_campaigns} active campaigns'
		elif returned[3]:
			plan = 'Almost free'
		elif returned[4]:
			plan = 'Ads Premium'
		else:
			plan = 'No Active Plan'
			temp_data = None

		_return = {
			'funds_remaining': returned[0],
			'spend_rate': returned[1],
			'plan': plan,
			'num_campaigns': returned[5],
			'data_synced': True if returned[6] else False,
			'phone': returned[7],
			'email': returned[8],
			'analytics': returned[9],
			'company_name': returned[10],
			'real_customer': returned[11]
		}

		return _return

	def acct_mgmt(self):
		service = AdminUserService(self.user, self.admin)
		messages = service.messaging.get_messages()
		tasks = service.tasks.get_tasks()
		self.task_form = forms.TaskForm()
		self.customer_name = self.admin_service.get_customer_name(self.user)
		insights_service = InsightsService(self.user, admin_id=self.admin, user='admin')
		insights = insights_service.fetch()

		returned = self.admin_dashboard()

		self.data = {
			'tasks': tasks,
			'insights': insights,
			'messages': messages,
			'customer': returned
		}

	def personnel(self) -> None:
		self.data = self.admin_service.get_admin_info()

	def customers(self) -> None:
		if self.permission_level != "owner":
			conditional = " WHERE admin_id = %s" % (self.admin,)
		else:
			conditional = None
		self.data = self.admin_service.get_customers(conditional=conditional)

	def home(self) -> None:
		query = db.sql_to_df("SELECT customer_basic.id, customer_basic.company_name, customer_basic.account_created, customer_basic.perc_complete, customer_basic.last_modified, admins.first_name FROM customer_basic, admins WHERE admins.ID = '" + self.admin + "' ORDER BY company_name ASC")
		self.data = query

class CustomerDataViewModel:
	def __init__(self, customer_id=1, init=False, admin=False) -> None:
		self.customer_id = customer_id
		self.core_service = CoreService(self.customer_id)
		self.admin = admin

		if init == True:
			self.compile_all()

	def compile_core(self) -> dict:
		query = "select * from compile_home_page(?)"
		core_data, cursor = db.execute(query, True, (self.customer_id,))
		core_data = cursor.fetchone()
		return_dict = {} #anchor2
		for i in range(len(core_data)):
			return_dict[i] = core_data[i]

		return return_dict

	def compile_products(self) -> dict:
		data = self.core_service.get_products()
		columns = [
			'complexity', 'price',
			'product_or_service', 'frequency_of_use',
			'frequency_of_purchase', 'warranties_or_guarantee',
			'warranty_guarantee_freeform', 'num_skus',
			'level_of_customization', 'customer_id',
			'name', 'category',
			'cogs', 'sales_price',
			'qty_sold', 'est_unique_buyers',
			'p_id', 'price_model',
			'value_prop_1', 'value_prop_2',
			'value_prop_3', 'value_prop_4',
			'value_prop_5'
		]
		product_list = {}
		for i in range(len(data)):
			product_list[i] = {}
			for x in range(len(data[i])):
				product_list[i].update([(columns[x], data[i][x])])

		return product_list

	def compile_audience(self) -> dict:
		data = self.core_service.get_audience()
		columns = [
			'customer_id', 'gender',
			'age_group_1', 'age_group_2',
			'age_group_3', 'age_group_4',
			'age_group_5', 'age_group_6',
			'age_group_7', 'age_group_8',
			'location', 'why',
			'before_1', 'before_2',
			'before_3', 'before_4',
			'before_5', 'before_6',
			'before_7', 'before_8',
			'before_9', 'before_10',
			'before_freeform', 'after_1',
			'after_2', 'after_3',
			'after_4', 'after_5',
			'after_6', 'after_7',
			'after_8', 'after_9',
			'after_10', 'after_freeform',
			'audience_id', 'formality',
			'buying_for', 'tech_savvy',
			'decision_making', 'details',
			'motive', 'persona_name',
			'company_size'
		]
		audience_list = {}
		for i in range(len(data)):
			audience_list[i] = {}
			for x in range(len(data[i])):
				audience_list[i].update([(columns[x], data[i][x])])

		return audience_list

	def compile_platforms(self) -> dict:
		data = self.core_service.get_platforms()
		columns = [
			'platform_id',
			'customer_id',
			'platform_name',
			'currently_using',
			'results'
		]
		platform_list = {}
		for i in range(len(data)):
			platform_list[i] = {}
			for x in range(len(data[i])):
				platform_list[i].update([(columns[x], data[i][x])])

		return platform_list

	def compile_messages(self) -> dict:
		data = self.core_service.get_messages()
		return data

	def compile_tasks(self) -> dict:
		data = self.core_service.get_tasks()
		return data

	def compile_salescycle(self) -> dict:
		data = self.core_service.get_salescycle()
		try:
			return_data = {
				'awareness': data[0].split("^") if data[0] else None,
				'evaluation': data[1].split("^") if data[1] else None,
				'conversion': data[2].split("^") if data[2] else None,
				'retention': data[3].split("^") if data[3] else None,
				'referral': data[4].split("^") if data[4] else None
			}
		except KeyError:
			return_data = {
				'awareness',
				'evaluation',
				'conversion',
				'retention',
				'referral'
			}

		return return_data

	def compile_google(self) -> dict:
		data = self.core_service.get_google()
		return data

	def compile_tests(self) -> dict:
		data = self.core_service.get_tests()
		return data

	def compile_insights(self) -> dict:
		insights_service = InsightsService(self.customer_id, self.admin)
		return insights_service.fetch()

	def compile_tactics(self) -> dict:
		tactics = TacticsService(self.customer_id)
		return tactics.get()

	def compile_all(self) -> None:
		core = self.compile_core()
		core_data = core
		core_values = eval(core[0])

		def clean_salescycle(row):
			if row:
				core = eval(row)
			else:
				return None
			base = core['salescycle'][0]
			struct = {
				'awareness': base.get('awareness').split('^') if base.get('awareness') else "",
				'evaluation': base.get('evaluation').split('^') if base.get('evaluation') else "",
				'conversion': base.get('conversion').split('^') if base.get('conversion') else "",
				'retention': base.get('retention').split('^') if base.get('retention') else "",
				'referral': base.get('referral').split('^') if base.get('referral') else ""
			}
			return struct

		return_data = {
			'core': core_values,
			'products': eval(core_data[1]) if core_data[1] else "",
			'audiences': eval(core_data[2]) if core_data[2] else "",
			'platforms': eval(core_data[3]) if core_data[3] else "",
			'messages': eval(core_data[4]) if core_data[4] else "",
			'tasks': eval(core_data[5]) if core_data[5] else "",
			'google': eval(core_data[6]) if core_data[6] else "",
			'tests': eval(core_data[7]) if core_data[7] else "",
			'salescycle': clean_salescycle(core_data[8]),
			'insights': eval(core_data[9]) if core_data[9] else "",
			'temp_ad_data': eval(core_data[10]) if core_data[10] else None,
			'achievements': eval(core_data[11]) if core_data[11] else None,
			'all_tactics': eval(core_data[12]) if core_data[12] else None,
			'rewards': eval(core_data[13]) if core_data[13] else None,
			'spend_rec': eval(core_data[14] if core_data[14] else None),
			'recommendations': eval(core_data[15]) if core_data[15] else None
		}

		self.data = return_data

class ViewFuncs:

	def view_page(user_name=None, user=None, form=None, view_page=None, next_page=None, coming_home=True, splash=False, onboarding_complete=False, onboarding=False):

		page = IntakeViewModel(user, user_name, title=view_page)
		splashVM = SplashViewModel(next_step=view_page)
		splashes = splashVM.splashes()

		if view_page in splashes and splash == None and coming_home == None:
			return redirect(url_for('splash', next_step=view_page))
		elif view_page not in splashes or splash:
			return render_template("layouts/intake_layout.html", onboarding=onboarding, onboarding_complete=onboarding_complete, page=page, form=form)
		else:
			return render_template("layouts/intake_layout.html", onboarding=onboarding, onboarding_complete=onboarding_complete, page=page, form=form)

	def view_admin(page=None, tag_id=None, owner=False, admin=False, manager=False, form=None, temp_form=None, csv_form=None, ab_form=None, insight_form=None):
		return render_template(
			'layouts/admin_layout.html',
			page=page,
			sub=True, owner=owner,
			admin=admin,
			manager=manager,
			form=form,
			csv_form=csv_form,
			temp_form=temp_form,
			ab_form=ab_form,
			insight_form=insight_form,
			tag_id=tag_id
		)

	def ValidSubmission(form=None, method=None):
		if method == 'POST' and form.validate_on_submit():
			return True
		else:
			return False

	def past_inputs(page, user, view_id=None):
		intake_pages = ['begin', 'competitors', 'company', 'competitors', 'audience', 'product', 'product_2', 'salescycle', 'goals', 'history', 'platforms', 'past', 'creative']
		if page in intake_pages:
			if page == 'begin':
				query = "SELECT first_name, last_name, company_name, revenue, employees, zip, stage, website FROM dbo.customer_basic WHERE ID = %s" % (user,)
				result = db.sql_to_df(query)
			elif page == 'salescycle':
				awareness = db.sql_to_df("select distinct tactic from dbo.awareness WHERE customer_id=%d" % (user,))
				awareness.insert(loc=0, column='stage', value='awareness')

				evaluation = db.sql_to_df("select distinct tactic from dbo.evaluation WHERE customer_id=%d" % (user,))
				evaluation.insert(loc=0, column='stage', value='evaluation')

				conversion = db.sql_to_df("select distinct tactic from dbo.conversion WHERE customer_id=%d" % (user,))
				conversion.insert(loc=0, column='stage', value='conversion')

				retention = db.sql_to_df("select distinct tactic from dbo.retention WHERE customer_id=%d" % (user,))
				retention.insert(loc=0, column='stage', value='retention')

				referral = db.sql_to_df("select distinct tactic from dbo.referral WHERE customer_id=%d" % (user,))
				referral.insert(loc=0, column='stage', value='referral')
				stages = [awareness, evaluation, conversion, retention, referral]

				result = pd.concat(stages)

			elif page == 'audience':
				query = "SELECT * FROM dbo.audience WHERE customer_id = %s and audience_id = %s" % (user, view_id)
				result = db.sql_to_df(query)

			elif page == 'product_2':
				query = "SELECT * FROM dbo.product_list WHERE customer_id = %d and p_id = %s" % (user,view_id)
				result = db.sql_to_df(query)
			elif page == 'past':
				query = "SELECT freeform FROM dbo.past WHERE customer_id = %d" % (user,)
				result = db.sql_to_df(query)
			elif page == 'creative':
				result = 'nah'
			elif page == 'splash':
				result = 'nah'
			else:
				query = "SELECT * FROM dbo.%s WHERE customer_id = %d" % (page, user)
				result = db.sql_to_df(query)

			return result

		else:
			return False

class SettingsViewModel:
	def __init__(self, email, customer_id=None, stripe_id=None, root=True, sub_id=None):
		self.customer_id = customer_id
		self.stripe_id = stripe_id
		self.root = root
		self.sub_id = sub_id
		self.stripe_obj = PaymentsService(email, customer_id=stripe_id)
		self.compile()

	def get_stripe(self):
		self.plans = self.stripe_obj.fetch_plans()
		self.invoices = self.stripe_obj.invoices()

	def get_customer_data(self):
		query = "SELECT * FROM settings_view(?)"
		data, cursor = db.execute(query, True, (self.customer_id,))
		data = cursor.fetchone()
		self.customer = {
			'first_name': data[0],
			'current_plan': False if not data[1] else True,
			'almost_free': False if not data[2] else True,
			'ad_mid': False if not data[3] else True,
			'ad_premium': False if not data[4] else True,
			'funds_remaining': data[5],
			'spend_rate': data[6],
			'analytics': data[7]
		}

	def subscription(self):
		data = self.stripe_obj.get_plan_meta(self.sub_id)
		self.plan_meta = {
			'amount': (data['plan']['amount']/100) if data['plan']['amount'] else 0,
			'start_date': data.get('start_date') if data.get('start_date') else 0,
			'canceled_at': data.get('canceled_at') if data['canceled_at'] else 0,
			'cancel_at': data.get('cancel_at') if data['cancel_at'] else 0
		}

	def compile(self):
		self.get_stripe()
		self.get_customer_data()

		if self.root == False:
			self.subscription()
			upcoming_invoices = self.stripe_obj.upcoming_invoices()
			past_invoices = self.stripe_obj.invoices(sub_num=self.sub_id)

			self.upcoming_invoices = {
				'amount': (upcoming_invoices['data'][0]['amount']/100),
				'start': upcoming_invoices['data'][0]['period']['start'],
				'end': upcoming_invoices['data'][0]['period']['end']
			}
			invoices = {}
			for i in range(len(past_invoices['data'])):
				invoices[i] = {
					'id': past_invoices['data'][i]['id'],
					'amount_due': (past_invoices['data'][i]['amount_due']/100),
					'status': 'paid' if past_invoices['data'][i]['amount_due'] == past_invoices['data'][i]['amount_paid'] else 'open',
					'due': past_invoices['data'][i]['created']
				}
			self.past_invoices = invoices

class AdAuditViewModel:
	def __init__(self, admin_id=None, customer_id=None):
		self.admin_id = admin_id
		self.user = customer_id

	def history(self):
		pass

class TacticViewModel:
	def __init__(self, tactic_id):
		self.tactic_id = tactic_id

	def compile(self):
		query = "SELECT title, description, tactic_id FROM tactics WHERE tactic_id = ?"
		data, cursor = db.execute(query, True, (self.tactic_id,))
		data = cursor.fetchone()
		self.data = {
			'title': data[0],
			'description': data[1],
			'id': data[2]
		}

class TacticOfTheDay:
	def __init__(self, customer_id):
		self.customer_id = customer_id

	def get(self):
		query = """EXEC get_tactics @customer_id = ?"""
		data, cursor = db.execute(query, True, (self.customer_id,))
		data = cursor.fetchone()
		returned = {
			'title': data[0] if data else None,
			'description': data[1] if data else None,
			'id': data[2] if data else None
		}
		return returned

class CompetitorViewModel:
	def __init__(self, customer_id=None):
		self.customer_id = customer_id

	def get_meta(self):
		query = "SELECT comp_1_name, comp_1_website, comp_1_type, comp_2_name, comp_2_website, comp_2_type FROM competitors WHERE customer_id = ?"
		data, cursor = db.execute(query, True, (self.customer_id,))
		data = cursor.fetchone()
		returned = {
			'comp_1_name': data[0],
			'comp_1_website': data[1],
			'comp_1_type': data[2],
			'comp_2_name': data[3],
			'comp_2_website': data[4],
			'comp_2_type': data[5]
		}
		return returned

	def get(self, service):
		def clean_urls(struct):
			def clean(val):
				struct[val] = struct[val].replace('\\', '').replace('http://', '').replace('/','').replace('https://','')

			clean_list = ['comp_1_website', 'comp_2_website']
			for url in clean_list:
				clean(url)

		core_values = self.get_meta()
		clean_urls(core_values)

		try:
			core_values.update([('competitor_intro_1', service.intro(core_values.get('comp_1_website')))])
		except:
			core_values.update([('competitor_intro_1', "")])
		try:
			core_values.update([('competitor_intro_2', service.intro(core_values.get('comp_2_website')))])
		except:
			core_values.update([('competitor_intro_2', "")])

		return core_values


from flask import Flask, request, render_template
import pandas as pd
from detoxify import Detoxify

def create_app(test_config=None):
    app = Flask(__name__)
    predictor = Detoxify('original')
    @app.route('/main')
    def my_form():
        return render_template('my-form.html')
    @app.route('/main', methods=['POST'])
    def my_form_post():
        text = request.form['text']
        processed_text = text.lower()
        results = predictor.predict(processed_text)
        return '%.7f'%float(str(results['toxicity']))
    if __name__ =='__main__':
        app.run(host='0.0.0.0',port=5000)
    return app
create_app()


# -*- coding:utf-8 -*-
import numpy as np
import json

f = open(r"D:\code\check\detections_test2017__results.json", 'r', encoding='utf-8')
arr = json.loads(f.read())
f.close()

file_ = open(r"D:\code\check\detections_test2017__results.txt", 'w')
for i in arr:
    if i['category_id'] == 5:
        file_.write(
            "%08d %d %f %f %f %f %f\n" % (
            i['image_id'], i['category_id'], i['score'],
            i['bbox'][0], i['bbox'][1], i['bbox'][2], i['bbox'][3]))


from os.path import join, abspath, dirname
from Bio.Data import IUPACData

# Directories
BASE_DIR = abspath(join(dirname(__file__), '..'))
BIN_DIR = join(BASE_DIR, '..', 'bin')
TEST_DATA_DIR = join(BASE_DIR, 'test', 'data')
DATASETS_DIR = join(BASE_DIR, 'datasets')
RAW_DATA_DIR = join(DATASETS_DIR, 'raw')
PROCESSED_DIR = join(DATASETS_DIR, 'data')
LANDSCAPES_DIR = join(DATASETS_DIR, 'landscapes')
VIZ_DIR = join(DATASETS_DIR, 'visualizations')

# File paths
PLOTS_FORMAT = 'png'

ALPHABET = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
            'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
            'U', 'V', 'W', 'X', 'Y', 'Z']
DNA_ALPHABET = ['A', 'C', 'G', 'T']
RNA_ALPHABET = ['A', 'C', 'G', 'U']
PROTEIN_ALPHABET = ['A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L',
                    'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y']

ALPHABETS = {'dna': DNA_ALPHABET,
             'rna': RNA_ALPHABET,
             'protein': PROTEIN_ALPHABET}

PROT_AMBIGUOUS_VALUES = {'X': ''.join(PROTEIN_ALPHABET)}
PROT_AMBIGUOUS_VALUES.update(dict(zip(PROTEIN_ALPHABET, PROTEIN_ALPHABET)))
DNA_AMBIGUOUS_VALUES = IUPACData.ambiguous_dna_values
RNA_AMBIGUOUS_VALUES = IUPACData.ambiguous_rna_values
AMBIGUOUS_VALUES = {'dna': DNA_AMBIGUOUS_VALUES,
                    'rna': RNA_AMBIGUOUS_VALUES,
                    'protein': PROT_AMBIGUOUS_VALUES}

MAX_STATES = 2e7
U_MAX = 500
PHI_UB, PHI_LB = 100, 0

NUCLEOTIDES = ['A', 'U', 'G', 'C']
COMPLEMENT = {'U': 'A', 'A': 'U', 'G': 'C', 'C': 'G', 'N': 'N',
              'T': 'A', '[': ']', ']': '['}

DATASETS = ['serine', 'gb1', 'f1u', 'smn1', 'dmsc', '5ss', 'pard']


import os
import sys
import zlib

def topo_order_commits():
    git_path = get_git_directory()  #get the git directory

    local_branch_files = []         #array with absolute path of branches
    local_branch_hashes = {}        #dictionary that matches the absolute path to the hash value

    #fill out the values
    get_local_branches(git_path + "/refs/heads", local_branch_files, local_branch_hashes)

    #build the commit graph, return a dictionary of commit nodes and root hashes
    #commit_nodes matches a hash to a CommitNode object - sorted in function
    #root_hashes is just a sorted array of the hashes of root nodes - sorted in function
    commit_nodes, root_hashes = build_commit_graph(git_path, local_branch_files, local_branch_hashes)

    #sort the nodes topoligically and return an order stack
    order = get_topo_ordered_commits(commit_nodes, root_hashes)

    #make a dictionary that matches hash values to an array of branch names
    head_to_branches = {}
    for entry in local_branch_files:
        hash_value = local_branch_hashes[entry]
        index = entry.find("/refs/heads/") + len("/refs/heads/")
        head_to_branches.setdefault(hash_value,[]).append(entry[index:])

    #print output
    print_topo_ordered_commits_with_branch_names(commit_nodes, order, head_to_branches)

class CommitNode:
    def __init__(self, commit_hash):
        """
        :type commit_hash: str
        """
        self.commit_hash = commit_hash
        self.parents = set()
        self.children = set()

def print_topo_ordered_commits_with_branch_names(commit_nodes, topo_ordered_commits, head_to_branches):
    jumped = False
    for i in range(len(topo_ordered_commits)):
        commit_hash = topo_ordered_commits[i]
        if jumped:
            jumped = False
            sticky_hash = ' '.join(commit_nodes[commit_hash].children)
            print(f'={sticky_hash}')
        branches = sorted(head_to_branches[commit_hash]) if commit_hash in head_to_branches else []
        print(commit_hash + (' ' + ' '.join(branches) if branches else ''))
        if i+1 < len(topo_ordered_commits) and topo_ordered_commits[i+1] not in commit_nodes[commit_hash].parents:
            jumped = True
            sticky_hash = ' '.join(commit_nodes[commit_hash].parents)
            print(f'{sticky_hash}=\n')

def get_topo_ordered_commits(commit_nodes, root_hashes):
    order = []
    visited = set()
    stack = list(root_hashes.copy())
    children_not_processed = []

    while len(stack) != 0:
        v = stack.pop()
        if v in order:
            continue

        visited.add(v)

        children_not_processed.clear()
        for child in commit_nodes[v].children:
            if child not in visited:
                children_not_processed.append(child)

        if len(children_not_processed) == 0:
            order.append(v)
        else:
            stack.append(v)
            stack += children_not_processed

    return order

def build_commit_graph(git_path, local_branch_files, local_branch_hashes):
    commit_nodes = {}
    root_hashes = set()
    visited = set()
    stack = []
    for entry in local_branch_files:
        stack.append(local_branch_hashes[entry])

    while len(stack) != 0:
        commit_hash = stack.pop()
        if commit_hash in visited:
            continue

        visited.add(commit_hash)
        if commit_hash not in commit_nodes:
            commit_nodes[commit_hash] = CommitNode(commit_hash)

        object_file_path = git_path + "/objects/" + commit_hash[:2] + "/" + commit_hash[2:]
        if os.path.isfile(object_file_path):
            binary_contents = open(object_file_path, 'rb').read()
            decomp_contents = zlib.decompress(binary_contents).decode()
            contents_list = decomp_contents.split('\n')
        for line in contents_list:
            if "parent" in line:
                parent_hash_list = line.split(' ')
                if len(parent_hash_list) == 2:
                    commit_nodes[commit_hash].parents.add(parent_hash_list[1])

        if len(commit_nodes[commit_hash].parents) == 0:
            root_hashes.add(commit_hash)

        for parent_hash in commit_nodes[commit_hash].parents:
            if parent_hash not in visited:
                stack.append(parent_hash)
            if parent_hash not in commit_nodes:
                commit_nodes[parent_hash] = CommitNode(parent_hash)
            commit_nodes[parent_hash].children.add(commit_hash)

    #sort the parents and children
    for node in commit_nodes:
        commit_nodes[node].children = sorted(commit_nodes[node].children)
        commit_nodes[node].parents = sorted(commit_nodes[node].parents)

    root_hashes = sorted(root_hashes)
    return commit_nodes, root_hashes

#recursive function to assemble a list with all files in it
#and a dictionary which uses said files to map to their hashes
def get_local_branches(path, local_branch_files, local_branch_hashes):
    #all entries under current directory
    heads = os.listdir(path)

    #check for files in entries and add to list and dictionary
    #if a directory, use recursion
    for entry in heads:
        entry_path = os.path.join(path, entry)

        if os.path.isfile(entry_path):
            f = open(entry_path, 'r')
            contents = f.read().replace('\n','')
            local_branch_files.append(entry_path)
            local_branch_hashes[entry_path] = contents

        elif os.path.isdir(entry_path):
            get_local_branches(entry_path, local_branch_files, local_branch_hashes)

def get_git_directory():
    curr_dir = os.getcwd()
    while True:
        #get all files in current directory
        files_in_curr_dir = os.listdir(curr_dir)

        #check if any are the .git directory
        for entry in files_in_curr_dir:
            if entry == ".git":
                return os.path.join(curr_dir, entry)

        os.chdir(os.pardir)
        #get new directory and make sure its not root directory
        curr_dir = os.getcwd()
        if curr_dir == "/":
            print("Not inside a Git repository", file=sys.stderr)
            exit(1)

if __name__ == "__main__":
    topo_order_commits()


class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

    def insert(self, val):
        cur = self

        if self.val is None:
            self.val = val
        else:
            while True:
                if val < cur.val:
                    if cur.left is None:
                        cur.left = TreeNode(val)
                        break
                    cur = cur.left
                elif val >= cur.val:
                    if cur.right is None:
                        cur.right = TreeNode(val)
                        break
                    cur = cur.right

    def insert_multi(self, vals):
        for val in vals:
            self.insert(val)

    def direct_insert_multi(self, vals):
        nodes = [self]
        vals_clone = vals[:]

        while len(nodes) > 0 and len(vals_clone) > 0:
            node = nodes.pop(0)

            if node.val is None and len(vals_clone) > 0:
                val = vals_clone.pop(0)
                node.val = val
            if node.left is None and len(vals_clone) > 0:
                val = vals_clone.pop(0)
                if val is not None:
                    node.left = TreeNode(val)
                    nodes.append(node.left)
            if node.right is None and len(vals_clone) > 0:
                val = vals_clone.pop(0)
                if val is not None:
                    node.right = TreeNode(val)
                    nodes.append(node.right)

    def print_inorder(self, root):
        if root:
            self.print_inorder(root.left)
            print(root.val)
            self.print_inorder(root.right)

    def print_inorder_reverse(self, root):
        if root:
            self.print_inorder_reverse(root.right)
            print(root.val)
            self.print_inorder_reverse(root.left)

    def print_preorder(self, root):
        if root is not None:
            print(root.val)
            self.print_inorder(root.left)
            self.print_inorder(root.right)

    def __str__(self):
        if self.val:
            if self.left and self.right:
                return "value: {0}, left: {1}, right: {2}".format(self.val, self.left.val, self.right.val)
            elif self.left:
                return "value: {0}, left: {1}, right: None".format(self.val, self.left.val)
            else:
                return "value: {0}, left: None, right: {1}".format(self.val, self.right.val)
        return "None"

if __name__ == "__main__":
    root = TreeNode(None)
    root.direct_insert_multi([1, None, 3, 2])


from django.db import models
from django.db.models import manager
from django_countries.fields import CountryField
from .constants import DONATION_CATEGORY_CHOICES, DONOR_TYPE_CHOICES
from django.contrib.auth.models import User
from accounts.models import Hub

# Create your models here.
class Project(models.Model):
	project_code = models.CharField(max_length=100, unique=True)
	project_name = models.CharField(max_length=100)
	hub = models.ForeignKey(Hub, on_delete=models.CASCADE)
	project_manager = models.ForeignKey(User, on_delete=models.CASCADE)
	project_description = models.TextField()
	project_start_date = models.DateField()
	project_end_date = models.DateField()
	project_budget = models.CharField(max_length=100)

	def __str__(self):
		return self.project_name

class Donor(models.Model):
	donor_name = models.CharField(max_length=100)
	donor_description = models.TextField(default=None, blank=True, help_text="Short Description of the Donor and what the donor normally funds")
	donor_website = models.CharField(max_length=100, default=None, blank=True)
	donor_dates = models.DateField(default=None, blank=True, help_text = "Key Dates for donation or funding application submission")
	donor_email = models.EmailField()
	country = CountryField()
	donor_contact = models.CharField(max_length=100, default=None, blank=True)
	donation_range = models.IntegerField(help_text="Range of How much Funds the Donor Normally Provide")
	donation_category = models.CharField(max_length=30, choices=DONATION_CATEGORY_CHOICES)
	donor_type = models.CharField(max_length=30, choices=DONOR_TYPE_CHOICES)
	key_contact_name = models.CharField(max_length=100,default=None, blank=True)
	key_contact_email = models.EmailField(default=None, blank=True)

	def __str__(self):
		return self.donor_name

class Partner(models.Model):
	partner_name = models.CharField(max_length=100)
	partner_adress = models.CharField(max_length=250)
	partner_country = CountryField()
	key_contact_name = models.CharField(max_length=100)
	key_contact_email = models.EmailField()
	partner_website = models.CharField(max_length=200, blank=True, default=None)
	partner_description = models.TextField(blank=True, default=None, help_text="Short description of the partners expertise and how it fits with Camara")
	partnership_start = models.DateField()
	areas_of_patnership = models.TextField(help_text="Agreed areas of partnership")
	# partner_mou = models.FileField(help_text="Copy of the MOU with the partner (if any)")

	def __str__(self):
		return self.partner_name

class Project_Partner(models.Model):
	project_name = models.ForeignKey(Project, on_delete=models.CASCADE)
	partner_name = models.ForeignKey(Partner, on_delete=models.CASCADE)
	partner_role = models.CharField(max_length=200, default=None, blank=True)
	start_Date = models.DateField(help_text="Date the Partnership This Project Begins  (Same or different as project dates)")
	end_Date = models.DateField(help_text="Date the Partnership This Project Ends (Same or different as project dates)")
	key_contact_name_1 = models.CharField(max_length=100, default=None, blank=True)
	key_contact_email_1 = models.EmailField(max_length=100, default=None, blank=True)
	key_contact_name_2 = models.CharField(max_length=100, default=None, blank=True, help_text="(Optional)")
	key_contact_email_2 = models.EmailField(max_length=100, default=None, blank=True, help_text="(Optional)")
	partner_Budget =models.IntegerField()

	def __str__(self):
		return self.project_name

class Project_Donor(models.Model):
	donor_name = models.ForeignKey(Donor, on_delete=models.CASCADE)
	project_name = models.ForeignKey(Project, on_delete=models.CASCADE)
	recruitment_source = models.CharField(max_length=200, help_text="How the donor was secured (e.g Funding Application, SCR, etc)")
	type_of_donation = models.CharField(max_length=200, help_text="Type contribution of the funder in the project")
	value_of_donation = models.CharField(max_length=200, help_text="Monetary value of contribution of the funder in the project")
	key_contact_name = models.CharField(max_length=200)
	key_contact_email = models.EmailField(max_length=200)

	def __str__(self):
		return self.project_name


import random

def geraMatriz(num_linhas,num_colunas,numInicial,numFinal):

    e = []
    for i in range(num_linhas):
        linha = []
        for j in range(num_colunas):
            num = random.randint(numInicial,numFinal)
            linha.append(num)
        e.append(linha)
    return e

def caculaTracoMatriz(e,num_linhas,num_colunas):
    dp=0
    for i in range(num_linhas):
        for j in range(num_colunas):
            if i == j:
                dp+=e[i][j]
    return dp


from unsilence import Unsilence
from ppvid.utilities import log_info, log_warning, get_erase_char, repair_console
from rich.console import Console
from rich.progress import Progress
from tempfile import TemporaryDirectory
from os.path import join
from os import getcwd
import soundfile as sf
import pyloudnorm as pyln
import matchering as mg
import ffmpeg
import click
import sys

@click.command()
@click.argument('infile')
@click.argument('outfile')
@click.option(
    '-s', '--speed', default=2.5,
    help='The speed at which the silent intervals get played back at.')
@click.option(
    '-v', '--vthresh', default=-37.5,
    help='Threshold of what should be classified as silent/audible (default -37.5)')
@click.option(
    '-d', '--dthresh', default=0.75,
    help='The shortest allowed interval length (default 0.75 seconds)')
@click.option(
    '-t', '--threads', default=1,
    help='Number of threads to use (default 1)')
def speed_up(
    infile: str,
    outfile: str,
    speed: float = 2.5,
    vthresh: float = -37.5,
    dthresh: float = 0.75,
    threads: int = 1,
    exit: bool=True):
    "Front-end to unsilence, with sane defaults."

    if exit:
        erase_char = get_erase_char()
        repair_console(erase_char)

    console = Console()
    progress = Progress()

    u = Unsilence(infile)

    with progress:
        def update_task(current_task):
            def handler(current_val, total):
                progress.update(current_task, total=total, completed=current_val)

            return handler

        silence_detect_task = progress.add_task("Calculating Intervals...", total=1)
        u.detect_silence(
            silence_level = vthresh,
            silence_time_threshold = dthresh,
            short_interval_threshold = max(dthresh / speed, 0.5),
            stretch_time = 0.325,
            on_silence_detect_progress_update = update_task(silence_detect_task))
        progress.stop()
        progress.remove_task(silence_detect_task)

        progress.start()
        rendering_task = progress.add_task("Rendering Intervals...", total=1)
        concat_task = progress.add_task("Combining Intervals...", total=1)

        u.render_media(
            outfile,
            on_render_progress_update=update_task(rendering_task),
            on_concat_progress_update=update_task(concat_task),
            silent_speed=speed, silent_volume=0, threads=threads)

        progress.stop()
        progress.remove_task(concat_task)

    u.cleanup()

    console.print('DONE!')
    if exit:
        repair_console(erase_char)
        sys.exit(0)

@click.command()
@click.argument('infile')
@click.argument('reference')
def master_video(
    infile: str,
    reference: str,
    exit: bool=True):
    """
    Master using matchering. Matchering tries to master the audio of `infile` such that
    it matches the frequency and loudness of the `reference` file. It produces a new
    video with the audio of `infile` replaced by the mastered audio. The new video's
    file name has the string `_mastered` apprended to it.

    ARGUMENTS
    infile (str):       Name of or path to the video to process.

    reference (str):    Name of or path to the reference audio.

    exit (bool):        Should the command exit to the console after it is finished?
                        Option is only available if the function is used from within
                        a script, i.e., if you are running this as a command then
                        you don't have to worry about this argument.
    """

    cwd = getcwd()
    console = Console()

    if exit:
        erase_char = get_erase_char()
        repair_console(erase_char)

    with TemporaryDirectory() as tmp_dir:
        # Extract the audio of our video
        in_video = ffmpeg.input(infile).video
        in_audio = ffmpeg.input(infile).audio
        console.log("Extracting audio from video.")
        in_audio.output(join(tmp_dir, "in_audio.wav")).run()
        console.log("Preparing Matchering...")
        mg.log(
            warning_handler=lambda x: log_warning(x, console),
            info_handler=lambda x: log_info(x, console))
        console.log("Matchering started...")
        mg.process(
            # The track you want to master
            target=join(tmp_dir, "in_audio.wav"),
            # Some "wet" reference track
            reference=reference,
            # Where and how to save your results
            results=[
                mg.pcm16(join(tmp_dir, "master_16bit.wav")),
                mg.pcm24(join(tmp_dir, "master_24bit.wav")),
            ],
            config=mg.Config(max_length = 120 * 60),)
        console.log("Matchering is done...")
        # Normalise the matchering output
        data, rate = sf.read(join(tmp_dir, "master_24bit.wav"))
        meter = pyln.Meter(rate) # create BS.1770 meter
        peak_normalized_audio = pyln.normalize.peak(data, -1.0)
        loudness = meter.integrated_loudness(peak_normalized_audio)
        loudness_normalized_audio = pyln.normalize.loudness(
            peak_normalized_audio, loudness, -15.0)
        sf.write(
            join(tmp_dir, "master_24bit.wav"),
            loudness_normalized_audio,
            rate)
        out_audio = ffmpeg.input(
            join(tmp_dir, "master_24bit.wav")).audio
        outfile = infile.split('.')
        n = len(outfile)
        extension = outfile[n-1]
        outfile = '{}_mastered.{}'.format('.'.join(outfile[:-1]), extension)
        console.log("About to export {}".format(outfile))
        ffmpeg.output(
            in_video,
            out_audio,
            join(cwd, outfile)).run()

    console.print('DONE!')
    if exit:
        repair_console(erase_char)
        sys.exit(0)

@click.command()
@click.argument('infile')
@click.option(
    '-c', '--crf', default=26,
    help='Constant Rate Factor (CRF): Affects quality, lower is better (default 26)\nNOTE: ffmpeg\'s default is 23.')
@click.option(
    '-p', '--preset', default='veryslow',
    help='ffmpeg preset (default \'veryslow\')')
def convert4lecture(
    infile: str,
    crf: int=26,
    preset: str='veryslow',
    exit: bool=True):
    """
    Convert `infile` to a format that is suitable for use on Moodle. For now, this an `mp4`
    file using the `libx264` video codec and `aac` audio codec. The converted video's
    file name has the string `_converted` apprended to it.

    ARGUMENTS
    infile (str):       Name of or path to the video to convert.
    crf (int):          Constant Rate Factor (CRF): Affects quality, lower is better (default 26)
    preset (str):       ffmpeg preset, affects compression.
    exit (bool):        Should the command exit to the console after it is finished?
                        Option is only available if the function is used from within
                        a script, i.e., if you are running this as a command then
                        you don't have to worry about this argument.

    NOTE: ffmpeg\'s defaults are `crf=23` and `preset=\'fast\'`. If you find that the quality
    is too low, lower the `crf` value. If encoding is too slow, try changing the preset.
    """

    if exit:
        erase_char = get_erase_char()
        repair_console(erase_char)

    cwd = getcwd()
    outfile = infile.split('.')
    outfile = '{}_converted.mp4'.format('.'.join(outfile[:-1]))
    ffmpeg.input(
        infile).output(
            join(cwd, outfile),
            vcodec='libx264',
            crf=crf, preset=preset,
            acodec='aac',
            movflags='faststart').run()

    if exit:
        repair_console(erase_char)
        sys.exit(0)


with section("format"):

  # If <use_tabchars> is True, then the value of this variable indicates how
  # fractional indentions are handled during whitespace replacement. If set to
  # 'use-space', fractional indentation is left as spaces (utf-8 0x20). If set
  # to `round-up` fractional indentation is replaced with a single tab character
  # (utf-8 0x09) effectively shifting the column to the next tabstop
  fractional_tab_policy = u'use-space'

  # Format command names consistently as 'lower' or 'upper' case
  command_case = u'canonical'

  # If the statement spelling length (including space and parenthesis) is larger
  # than the tab width by more than this amount, then force reject un-nested
  # layouts.
  max_prefix_chars = 10

  # By default, if cmake-format cannot successfully fit everything into the
  # desired linewidth it will apply the last, most agressive attempt that it
  # made. If this flag is True, however, cmake-format will print error, exit
  # with non-zero status code, and write-out nothing
  require_valid_layout = False

  # If the trailing parenthesis must be 'dangled' on its on line, then align it
  # to this reference: `prefix`: the start of the statement,  `prefix-indent`:
  # the start of the statement, plus one indentation  level, `child`: align to
  # the column of the arguments
  dangle_align = u'prefix'

  # If an argument group contains more than this many sub-groups (parg or kwarg
  # groups) then force it to a vertical layout.
  max_subgroups_hwrap = 2

  # Disable formatting entirely, making cmake-format a no-op
  disable = False

  # If the statement spelling length (including space and parenthesis) is
  # smaller than this amount, then force reject nested layouts.
  min_prefix_chars = 4

  # If a positional argument group contains more than this many arguments, then
  # force it to a vertical layout.
  max_pargs_hwrap = 6

  # If a candidate layout is wrapped horizontally but it exceeds this many
  # lines, then reject the layout.
  max_lines_hwrap = 2

  # If true, the parsers may infer whether or not an argument list is sortable
  # (without annotation).
  autosort = False

  # What style line endings to use in the output.
  line_ending = u'unix'

  # How wide to allow formatted cmake files
  line_width = 80

  # If a statement is wrapped to more than one line, than dangle the closing
  # parenthesis on its own line.
  dangle_parens = False

  # A list of command names which should always be wrapped
  always_wrap = []

  # If true, separate flow control names from their parentheses with a space
  separate_ctrl_name_with_space = False

  # If a cmdline positional group consumes more than this many lines without
  # nesting, then invalidate the layout (and nest)
  max_rows_cmdline = 2

  # If true, separate function names from parentheses with a space
  separate_fn_name_with_space = False

  # How many spaces to tab for indent
  tab_size = 4

  # If true, lines are indented using tab characters (utf-8 0x09) instead of
  # <tab_size> space characters (utf-8 0x20). In cases where the layout would
  # require a fractional tab character, the behavior of the  fractional
  # indentation is governed by <fractional_tab_policy>
  use_tabchars = False

  # Format keywords consistently as 'lower' or 'upper' case
  keyword_case = u'unchanged'

  # If true, the argument lists which are known to be sortable will be sorted
  # lexicographicall
  enable_sort = True

  # A dictionary mapping layout nodes to a list of wrap decisions. See the
  # documentation for more information.
  layout_passes = { }

# ------------------------------------------------
# Options affecting comment reflow and formatting.
# ------------------------------------------------
with section("markup"):

  # If comment markup is enabled, don't reflow any comment block which matches
  # this (regex) pattern. Default is `None` (disabled).
  literal_comment_pattern = None

  # If a comment line starts with at least this many consecutive hash
  # characters, then don't lstrip() them off. This allows for lazy hash rulers
  # where the first hash char is not separated by space
  hashruler_min_length = 10

  # Regular expression to match preformat fences in comments default=
  # ``r'^\s*([`~]{3}[`~]*)(.*)$'``
  fence_pattern = u'^\\s*([`~]{3}[`~]*)(.*)$'

  # If true, then insert a space between the first hash char and remaining hash
  # chars in a hash ruler, and normalize its length to fill the column
  canonicalize_hashrulers = True

  # If a comment line matches starts with this pattern then it is explicitly a
  # trailing comment for the preceeding argument. Default is '#<'
  explicit_trailing_pattern = u'#<'

  # If comment markup is enabled, don't reflow the first comment block in each
  # listfile. Use this to preserve formatting of your copyright/license
  # statements.
  first_comment_is_literal = True

  # enable comment markup parsing and reflow
  enable_markup = True

  # Regular expression to match rulers in comments default=
  # ``r'^\s*[^\w\s]{3}.*[^\w\s]{3}$'``
  ruler_pattern = u'^\\s*[^\\w\\s]{3}.*[^\\w\\s]{3}$'

  # What character to use as punctuation after numerals in an enumerated list
  enum_char = u'.'

  # What character to use for bulleted lists
  bullet_char = u'*'

# ----------------------------
# Options affecting the linter
# ----------------------------
with section("lint"):

  # regular expression pattern describing valid function names
  function_pattern = u'[0-9a-z_]+'

  # regular expression pattern describing valid names for function/macro
  # arguments and loop variables.
  argument_var_pattern = u'[a-z][a-z0-9_]+'

  # a list of lint codes to disable
  disabled_codes = []

  # Require at least this many newlines between statements
  min_statement_spacing = 1

  # regular expression pattern describing valid macro names
  macro_pattern = u'scp_[0-9a-z_]+'

  # regular expression pattern describing valid names for public directory
  # variables
  public_var_pattern = u'(CMAKE|SCP)_[A-Z][0-9A-Z_]+'
  max_statements = 50

  # In the heuristic for C0201, how many conditionals to match within a loop in
  # before considering the loop a parser.
  max_conditionals_custom_parser = 2

  # regular expression pattern describing valid names for variables with global
  # (cache) scope
  global_var_pattern = u'(CMAKE|SCP)_[A-Z][0-9A-Z_]+'

  # regular expression pattern describing valid names for keywords used in
  # functions or macros
  keyword_pattern = u'[A-Z][0-9A-Z_]+'
  max_arguments = 5

  # regular expression pattern describing valid names for privatedirectory
  # variables
  private_var_pattern = u'scp_[0-9a-z_]+'
  max_localvars = 15
  max_branches = 12

  # regular expression pattern describing valid names for variables with local
  # scope
  local_var_pattern = u'[a-z][a-z0-9_]+'

  # Require no more than this many newlines between statements
  max_statement_spacing = 2

  # regular expression pattern describing valid names for variables with global
  # scope (but internal semantic)
  internal_var_pattern = u'(CMAKE|SCP)?_[A-Z][0-9A-Z_]+'
  max_returns = 6

# -------------------------------------
# Miscellaneous configurations options.
# -------------------------------------
with section("misc"):

  # A dictionary containing any per-command configuration overrides. Currently
  # only `command_case` is supported.
  per_command = { }

# ----------------------------------
# Options affecting listfile parsing
# ----------------------------------
with section("parse"):

  # Specify structure for custom cmake functions
  additional_commands = {
    "set_property": {
      "kwargs": {
        "GLOBAL": {
          "kwargs": {
            "PROPERTY": {
              "kwargs": {
                "ALLOW_DUPLICATE_CUSTOM_TARGETS": "*",
                "AUTOGEN_SOURCE_GROUP": "*",
                "AUTOGEN_TARGETS_FOLDER": "*",
                "AUTOMOC_SOURCE_GROUP": "*",
                "AUTOMOC_TARGETS_FOLDER": "*",
                "AUTORCC_SOURCE_GROUP": "*",
                "CMAKE_C_KNOWN_FEATURES": "*",
                "CMAKE_CUDA_KNOWN_FEATURES": "*",
                "CMAKE_CXX_KNOWN_FEATURES": "*",
                "CMAKE_ROLE": "*",
                "DEBUG_CONFIGURATIONS": "*",
                "DISABLED_FEATURES": "*",
                "ECLIPSE_EXTRA_CPROJECT_CONTENTS": "*",
                "ECLIPSE_EXTRA_NATURES": "*",
                "ENABLED_FEATURES": "*",
                "ENABLED_LANGUAGES": "*",
                "FIND_LIBRARY_USE_LIB32_PATHS": "*",
                "FIND_LIBRARY_USE_LIB64_PATHS": "*",
                "FIND_LIBRARY_USE_LIBX32_PATHS": "*",
                "FIND_LIBRARY_USE_OPENBSD_VERSIONING": "*",
                "GENERATOR_IS_MULTI_CONFIG": "*",
                "GLOBAL_DEPENDS_DEBUG_MODE": "*",
                "GLOBAL_DEPENDS_NO_CYCLES": "*",
                "IN_TRY_COMPILE": "*",
                "JOB_POOLS": "*",
                "PACKAGES_FOUND": "*",
                "PACKAGES_NOT_FOUND": "*",
                "PREDEFINED_TARGETS_FOLDER": "*",
                "REPORT_UNDEFINED_PROPERTIES": "*",
                "RULE_LAUNCH_COMPILE": "*",
                "RULE_LAUNCH_CUSTOM": "*",
                "RULE_LAUNCH_LINK": "*",
                "RULE_MESSAGES": "*",
                "TARGET_ARCHIVES_MAY_BE_SHARED_LIBS": "*",
                "TARGET_MESSAGES": "*",
                "TARGET_SUPPORTS_SHARED_LIBS": "*",
                "USE_FOLDERS": "*",
                "XCODE_EMIT_EFFECTIVE_PLATFORM_NAME": "*",
              },
            },
          },
        },
        "DIRECTORY": {
          "pargs": 1,
          "kwargs": {
            "PROPERTY": {
              "kwargs": {
                "ADDITIONAL_CLEAN_FILES": "*",
                "BINARY_DIR": "*",
                "BUILDSYSTEM_TARGETS": "*",
                "CACHE_VARIABLES": "*",
                "CLEAN_NO_CUSTOM": "*",
                "CMAKE_CONFIGURE_DEPENDS": "*",
                "COMPILE_DEFINITIONS": "*",
                "COMPILE_OPTIONS": "*",
                "DEFINITIONS": "*",
                "EXCLUDE_FROM_ALL": "*",
                "IMPLICIT_DEPENDS_INCLUDE_TRANSFORM": "*",
                "INCLUDE_DIRECTORIES": "*",
                "INCLUDE_REGULAR_EXPRESSION": "*",
                "INTERPROCEDURAL_OPTIMIZATION_DEBUG": "*",
                "INTERPROCEDURAL_OPTIMIZATION_RELEASE": "*",
                "INTERPROCEDURAL_OPTIMIZATION_MINSIZEREL": "*",
                "INTERPROCEDURAL_OPTIMIZATION_RELWITHDEBINFO": "*",
                "INTERPROCEDURAL_OPTIMIZATION": "*",
                "LABELS": "*",
                "LINK_DIRECTORIES": "*",
                "LINK_OPTIONS": "*",
                "LISTFILE_STACK": "*",
                "MACROS": "*",
                "PARENT_DIRECTORY": "*",
                "RULE_LAUNCH_COMPILE": "*",
                "RULE_LAUNCH_CUSTOM": "*",
                "RULE_LAUNCH_LINK": "*",
                "SOURCE_DIR": "*",
                "SUBDIRECTORIES": "*",
                "TESTS": "*",
                "TEST_INCLUDE_FILES": "*",
                "VARIABLES": "*",
                "VS_GLOBAL_SECTION_POST_ExtensibilityAddIns": "*",
                "VS_GLOBAL_SECTION_POST_ExtensibilityGlobals": "*",
                "VS_GLOBAL_SECTION_PRE_ExtensibilityAddIns": "*",
                "VS_GLOBAL_SECTION_PRE_ExtensibilityGlobals": "*",
                "VS_STARTUP_PROJECT": "*",
              },
            },
          },
        },
        "TARGET": {
          "kwargs": {
            "PROPERTY": {
              "kwargs": {
                "ADDITIONAL_CLEAN_FILES": "*",
                "AIX_EXPORT_ALL_SYMBOLS": "*",
                "ALIAS_GLOBAL": "*",
                "ALIASED_TARGET": "*",
                "ANDROID_ANT_ADDITIONAL_OPTIONS": "*",
                "ANDROID_API": "*",
                "ANDROID_API_MIN": "*",
                "ANDROID_ARCH": "*",
                "ANDROID_ASSETS_DIRECTORIES": "*",
                "ANDROID_GUI": "*",
                "ANDROID_JAR_DEPENDENCIES": "*",
                "ANDROID_JAR_DIRECTORIES": "*",
                "ANDROID_JAVA_SOURCE_DIR": "*",
                "ANDROID_NATIVE_LIB_DEPENDENCIES": "*",
                "ANDROID_NATIVE_LIB_DIRECTORIES": "*",
                "ANDROID_PROCESS_MAX": "*",
                "ANDROID_PROGUARD": "*",
                "ANDROID_PROGUARD_CONFIG_PATH": "*",
                "ANDROID_SECURE_PROPS_PATH": "*",
                "ANDROID_SKIP_ANT_STEP": "*",
                "ANDROID_STL_TYPE": "*",
                "ARCHIVE_OUTPUT_DIRECTORY": "*",
                "ARCHIVE_OUTPUT_NAME": "*",
                "AUTOGEN_BUILD_DIR": "*",
                "AUTOGEN_ORIGIN_DEPENDS": "*",
                "AUTOGEN_PARALLEL": "*",
                "AUTOGEN_TARGET_DEPENDS": "*",
                "AUTOMOC": "*",
                "AUTOMOC_COMPILER_PREDEFINES": "*",
                "AUTOMOC_DEPEND_FILTERS": "*",
                "AUTOMOC_EXECUTABLE": "*",
                "AUTOMOC_MACRO_NAMES": "*",
                "AUTOMOC_MOC_OPTIONS": "*",
                "AUTOMOC_PATH_PREFIX": "*",
                "AUTORCC": "*",
                "AUTORCC_EXECUTABLE": "*",
                "AUTORCC_OPTIONS": "*",
                "AUTOUIC": "*",
                "AUTOUIC_EXECUTABLE": "*",
                "AUTOUIC_OPTIONS": "*",
                "AUTOUIC_SEARCH_PATHS": "*",
                "BINARY_DIR": "*",
                "BUILD_RPATH": "*",
                "BUILD_RPATH_USE_ORIGIN": "*",
                "BUILD_WITH_INSTALL_NAME_DIR": "*",
                "BUILD_WITH_INSTALL_RPATH": "*",
                "BUNDLE_EXTENSION": "*",
                "BUNDLE": "*",
                "C_EXTENSIONS": "*",
                "C_STANDARD": "*",
                "C_STANDARD_REQUIRED": "*",
                "COMMON_LANGUAGE_RUNTIME": "*",
                "COMPATIBLE_INTERFACE_BOOL": "*",
                "COMPATIBLE_INTERFACE_NUMBER_MAX": "*",
                "COMPATIBLE_INTERFACE_NUMBER_MIN": "*",
                "COMPATIBLE_INTERFACE_STRING": "*",
                "COMPILE_DEFINITIONS": "*",
                "COMPILE_FEATURES": "*",
                "COMPILE_FLAGS": "*",
                "COMPILE_OPTIONS": "*",
                "COMPILE_PDB_NAME": "*",
                "COMPILE_PDB_OUTPUT_DIRECTORY": "*",
                "CROSSCOMPILING_EMULATOR": "*",
                "CUDA_ARCHITECTURES": "*",
                "CUDA_PTX_COMPILATION": "*",
                "CUDA_SEPARABLE_COMPILATION": "*",
                "CUDA_RESOLVE_DEVICE_SYMBOLS": "*",
                "CUDA_RUNTIME_LIBRARY": "*",
                "CUDA_EXTENSIONS": "*",
                "CUDA_STANDARD": "*",
                "CUDA_STANDARD_REQUIRED": "*",
                "CXX_EXTENSIONS": "*",
                "CXX_STANDARD": "*",
                "CXX_STANDARD_REQUIRED": "*",
                "DEBUG_POSTFIX": "*",
                "DEFINE_SYMBOL": "*",
                "DEPLOYMENT_REMOTE_DIRECTORY": "*",
                "DEPLOYMENT_ADDITIONAL_FILES": "*",
                "DEPRECATION": "*",
                "DISABLE_PRECOMPILE_HEADERS": "*",
                "DOTNET_TARGET_FRAMEWORK": "*",
                "DOTNET_TARGET_FRAMEWORK_VERSION": "*",
                "EchoString": "*",
                "ENABLE_EXPORTS": "*",
                "EXCLUDE_FROM_ALL": "*",
                "EXCLUDE_FROM_DEFAULT_BUILD": "*",
                "EXPORT_NAME": "*",
                "EXPORT_PROPERTIES": "*",
                "FOLDER": "*",
                "Fortran_FORMAT": "*",
                "Fortran_MODULE_DIRECTORY": "*",
                "Fortran_PREPROCESS": "*",
                "FRAMEWORK": "*",
                "FRAMEWORK_VERSION": "*",
                "GENERATOR_FILE_NAME": "*",
                "GHS_INTEGRITY_APP": "*",
                "GHS_NO_SOURCE_GROUP_FILE": "*",
                "GNUtoMS": "*",
                "HAS_CXX": "*",
                "IMPLICIT_DEPENDS_INCLUDE_TRANSFORM": "*",
                "IMPORTED_COMMON_LANGUAGE_RUNTIME": "*",
                "IMPORTED_CONFIGURATIONS": "*",
                "IMPORTED_GLOBAL": "*",
                "IMPORTED_IMPLIB": "*",
                "IMPORTED_LIBNAME": "*",
                "IMPORTED_LINK_DEPENDENT_LIBRARIES": "*",
                "IMPORTED_LINK_INTERFACE_LANGUAGES": "*",
                "IMPORTED_LINK_INTERFACE_LIBRARIES": "*",
                "IMPORTED_LINK_INTERFACE_MULTIPLICITY": "*",
                "IMPORTED_LOCATION": "*",
                "IMPORTED_NO_SONAME": "*",
                "IMPORTED_OBJECTS": "*",
                "IMPORTED": "*",
                "IMPORTED_SONAME": "*",
                "IMPORT_PREFIX": "*",
                "IMPORT_SUFFIX": "*",
                "INCLUDE_DIRECTORIES": "*",
                "INSTALL_NAME_DIR": "*",
                "INSTALL_REMOVE_ENVIRONMENT_RPATH": "*",
                "INSTALL_RPATH": "*",
                "INSTALL_RPATH_USE_LINK_PATH": "*",
                "INTERFACE_AUTOUIC_OPTIONS": "*",
                "INTERFACE_COMPILE_DEFINITIONS": "*",
                "INTERFACE_COMPILE_FEATURES": "*",
                "INTERFACE_COMPILE_OPTIONS": "*",
                "INTERFACE_INCLUDE_DIRECTORIES": "*",
                "INTERFACE_LINK_DEPENDS": "*",
                "INTERFACE_LINK_DIRECTORIES": "*",
                "INTERFACE_LINK_LIBRARIES": "*",
                "INTERFACE_LINK_OPTIONS": "*",
                "INTERFACE_PRECOMPILE_HEADERS": "*",
                "INTERFACE_POSITION_INDEPENDENT_CODE": "*",
                "INTERFACE_SOURCES": "*",
                "INTERFACE_SYSTEM_INCLUDE_DIRECTORIES": "*",
                "INTERPROCEDURAL_OPTIMIZATION": "*",
                "IOS_INSTALL_COMBINED": "*",
                "JOB_POOL_COMPILE": "*",
                "JOB_POOL_LINK": "*",
                "JOB_POOL_PRECOMPILE_HEADER": "*",
                "LABELS": "*",
                "LIBRARY_OUTPUT_DIRECTORY": "*",
                "LIBRARY_OUTPUT_NAME": "*",
                "LINK_DEPENDS_NO_SHARED": "*",
                "LINK_DEPENDS": "*",
                "LINKER_LANGUAGE": "*",
                "LINK_DIRECTORIES": "*",
                "LINK_FLAGS": "*",
                "LINK_INTERFACE_LIBRARIES": "*",
                "LINK_INTERFACE_MULTIPLICITY": "*",
                "LINK_LIBRARIES": "*",
                "LINK_OPTIONS": "*",
                "LINK_SEARCH_END_STATIC": "*",
                "LINK_SEARCH_START_STATIC": "*",
                "LINK_WHAT_YOU_USE": "*",
                "LOCATION": "*",
                "MACHO_COMPATIBILITY_VERSION": "*",
                "MACHO_CURRENT_VERSION": "*",
                "MACOSX_BUNDLE_INFO_PLIST": "*",
                "MACOSX_BUNDLE": "*",
                "MACOSX_FRAMEWORK_INFO_PLIST": "*",
                "MACOSX_RPATH": "*",
                "MANUALLY_ADDED_DEPENDENCIES": "*",
                "MSVC_RUNTIME_LIBRARY": "*",
                "NAME": "*",
                "NO_SONAME": "*",
                "NO_SYSTEM_FROM_IMPORTED": "*",
                "OBJC_EXTENSIONS": "*",
                "OBJC_STANDARD": "*",
                "OBJC_STANDARD_REQUIRED": "*",
                "OBJCXX_EXTENSIONS": "*",
                "OBJCXX_STANDARD": "*",
                "OBJCXX_STANDARD_REQUIRED": "*",
                "OSX_ARCHITECTURES": "*",
                "OUTPUT_NAME": "*",
                "PCH_WARN_INVALID": "*",
                "PDB_NAME": "*",
                "PDB_OUTPUT_DIRECTORY": "*",
                "POSITION_INDEPENDENT_CODE": "*",
                "PRECOMPILE_HEADERS": "*",
                "PRECOMPILE_HEADERS_REUSE_FROM": "*",
                "PREFIX": "*",
                "PRIVATE_HEADER": "*",
                "PROJECT_LABEL": "*",
                "PUBLIC_HEADER": "*",
                "RESOURCE": "*",
                "RULE_LAUNCH_COMPILE": "*",
                "RULE_LAUNCH_CUSTOM": "*",
                "RULE_LAUNCH_LINK": "*",
                "RUNTIME_OUTPUT_DIRECTORY": "*",
                "RUNTIME_OUTPUT_NAME": "*",
                "SKIP_BUILD_RPATH": "*",
                "SOURCE_DIR": "*",
                "SOURCES": "*",
                "SOVERSION": "*",
                "STATIC_LIBRARY_FLAGS": "*",
                "STATIC_LIBRARY_OPTIONS": "*",
                "SUFFIX": "*",
                "Swift_DEPENDENCIES_FILE": "*",
                "Swift_LANGUAGE_VERSION": "*",
                "Swift_MODULE_DIRECTORY": "*",
                "Swift_MODULE_NAME": "*",
                "TYPE": "*",
                "UNITY_BUILD": "*",
                "UNITY_BUILD_BATCH_SIZE": "*",
                "UNITY_BUILD_CODE_AFTER_INCLUDE": "*",
                "UNITY_BUILD_CODE_BEFORE_INCLUDE": "*",
                "UNITY_BUILD_MODE": "*",
                "VERSION": "*",
                "VISIBILITY_INLINES_HIDDEN": "*",
                "VS_CONFIGURATION_TYPE": "*",
                "VS_DEBUGGER_COMMAND": "*",
                "VS_DEBUGGER_COMMAND_ARGUMENTS": "*",
                "VS_DEBUGGER_ENVIRONMENT": "*",
                "VS_DEBUGGER_WORKING_DIRECTORY": "*",
                "VS_DESKTOP_EXTENSIONS_VERSION": "*",
                "VS_DOTNET_REFERENCES": "*",
                "VS_DOTNET_REFERENCES_COPY_LOCAL": "*",
                "VS_DOTNET_TARGET_FRAMEWORK_VERSION": "*",
                "VS_DOTNET_DOCUMENTATION_FILE": "*",
                "VS_DPI_AWARE": "*",
                "VS_GLOBAL_KEYWORD": "*",
                "VS_GLOBAL_PROJECT_TYPES": "*",
                "VS_GLOBAL_ROOTNAMESPACE": "*",
                "VS_IOT_EXTENSIONS_VERSION": "*",
                "VS_IOT_STARTUP_TASK": "*",
                "VS_JUST_MY_CODE_DEBUGGING": "*",
                "VS_KEYWORD": "*",
                "VS_MOBILE_EXTENSIONS_VERSION": "*",
                "VS_NO_SOLUTION_DEPLOY": "*",
                "VS_PACKAGE_REFERENCES": "*",
                "VS_PLATFORM_TOOLSET": "*",
                "VS_PROJECT_IMPORT": "*",
                "VS_SCC_AUXPATH": "*",
                "VS_SCC_LOCALPATH": "*",
                "VS_SCC_PROJECTNAME": "*",
                "VS_SCC_PROVIDER": "*",
                "VS_SDK_REFERENCES": "*",
                "VS_SOLUTION_DEPLOY": "*",
                "VS_USER_PROPS": "*",
                "VS_WINDOWS_TARGET_PLATFORM_MIN_VERSION": "*",
                "VS_WINRT_COMPONENT": "*",
                "VS_WINRT_EXTENSIONS": "*",
                "VS_WINRT_REFERENCES": "*",
                "WIN32_EXECUTABLE": "*",
                "WINDOWS_EXPORT_ALL_SYMBOLS": "*",
                "XCODE_EXPLICIT_FILE_TYPE": "*",
                "XCODE_GENERATE_SCHEME": "*",
                "XCODE_PRODUCT_TYPE": "*",
                "XCODE_SCHEME_ADDRESS_SANITIZER": "*",
                "XCODE_SCHEME_ADDRESS_SANITIZER_USE_AFTER_RETURN": "*",
                "XCODE_SCHEME_ARGUMENTS": "*",
                "XCODE_SCHEME_DEBUG_AS_ROOT": "*",
                "XCODE_SCHEME_DEBUG_DOCUMENT_VERSIONING": "*",
                "XCODE_SCHEME_DISABLE_MAIN_THREAD_CHECKER": "*",
                "XCODE_SCHEME_DYNAMIC_LIBRARY_LOADS": "*",
                "XCODE_SCHEME_DYNAMIC_LINKER_API_USAGE": "*",
                "XCODE_SCHEME_ENVIRONMENT": "*",
                "XCODE_SCHEME_EXECUTABLE": "*",
                "XCODE_SCHEME_GUARD_MALLOC": "*",
                "XCODE_SCHEME_MAIN_THREAD_CHECKER_STOP": "*",
                "XCODE_SCHEME_MALLOC_GUARD_EDGES": "*",
                "XCODE_SCHEME_MALLOC_SCRIBBLE": "*",
                "XCODE_SCHEME_MALLOC_STACK": "*",
                "XCODE_SCHEME_THREAD_SANITIZER": "*",
                "XCODE_SCHEME_THREAD_SANITIZER_STOP": "*",
                "XCODE_SCHEME_UNDEFINED_BEHAVIOUR_SANITIZER": "*",
                "XCODE_SCHEME_UNDEFINED_BEHAVIOUR_SANITIZER_STOP": "*",
                "XCODE_SCHEME_WORKING_DIRECTORY": "*",
                "XCODE_SCHEME_ZOMBIE_OBJECTS": "*",
                "XCTEST": "*",
              },
            },
          },
        },
        "SOURCE": {
          "pargs": "*",
          "kwargs": {
            "DIRECTORY": "+",
            "TARGET_DIRECTORY": "+",
            "PROPERTY": {
              "kwargs": {
                "ABSTRACT": "*",
                "AUTORCC_OPTIONS": "*",
                "AUTOUIC_OPTIONS": "*",
                "COMPILE_DEFINITIONS": "*",
                "COMPILE_FLAGS": "*",
                "COMPILE_OPTIONS": "*",
                "EXTERNAL_OBJECT": "*",
                "Fortran_FORMAT": "*",
                "Fortran_PREPROCESS": "*",
                "GENERATED": "*",
                "HEADER_FILE_ONLY": "*",
                "INCLUDE_DIRECTORIES": "*",
                "KEEP_EXTENSION": "*",
                "LABELS": "*",
                "LANGUAGE": "*",
                "LOCATION": "*",
                "MACOSX_PACKAGE_LOCATION": "*",
                "OBJECT_DEPENDS": "*",
                "OBJECT_OUTPUTS": "*",
                "SKIP_AUTOGEN": "*",
                "SKIP_AUTOMOC": "*",
                "SKIP_AUTORCC": "*",
                "SKIP_AUTOUIC": "*",
                "SKIP_PRECOMPILE_HEADERS": "*",
                "SKIP_UNITY_BUILD_INCLUSION": "*",
                "Swift_DEPENDENCIES_FILE": "*",
                "Swift_DIAGNOSTICS_FILE": "*",
                "SYMBOLIC": "*",
                "UNITY_GROUP": "*",
                "VS_COPY_TO_OUT_DIR": "*",
                "VS_CSHARP_<tagname>": "*",
                "VS_DEPLOYMENT_CONTENT": "*",
                "VS_DEPLOYMENT_LOCATION": "*",
                "VS_INCLUDE_IN_VSIX": "*",
                "VS_RESOURCE_GENERATOR": "*",
                "VS_SETTINGS": "*",
                "VS_SHADER_DISABLE_OPTIMIZATIONS": "*",
                "VS_SHADER_ENABLE_DEBUG": "*",
                "VS_SHADER_ENTRYPOINT": "*",
                "VS_SHADER_FLAGS": "*",
                "VS_SHADER_MODEL": "*",
                "VS_SHADER_OBJECT_FILE_NAME": "*",
                "VS_SHADER_OUTPUT_HEADER_FILE": "*",
                "VS_SHADER_TYPE": "*",
                "VS_SHADER_VARIABLE_NAME": "*",
                "VS_TOOL_OVERRIDE": "*",
                "VS_XAML_TYPE": "*",
                "WRAP_EXCLUDE": "*",
                "XCODE_EXPLICIT_FILE_TYPE": "*",
                "XCODE_FILE_ATTRIBUTES": "*",
                "XCODE_LAST_KNOWN_FILE_TYPE": "*",
              },
            },
          },
        },
        "INSTALL": {
          "pargs": "*",
          "kwargs": {
            "PROPERTY": {
              "kwargs": {
                "CPACK_DESKTOP_SHORTCUTS": "*",
                "CPACK_NEVER_OVERWRITE": "*",
                "CPACK_PERMANENT": "*",
                "CPACK_START_MENU_SHORTCUTS": "*",
                "CPACK_STARTUP_SHORTCUTS": "*",
                "CPACK_WIX_ACL": "*",
              },
            },
          },
        },
        "TEST": {
          "pargs": "*",
          "kwargs": {
            "PROPERTY": {
              "kwargs": {
                "ATTACHED_FILES_ON_FAIL": "*",
                "ATTACHED_FILES": "*",
                "COST": "*",
                "DEPENDS": "*",
                "DISABLED": "*",
                "ENVIRONMENT": "*",
                "FAIL_REGULAR_EXPRESSION": "*",
                "FIXTURES_CLEANUP": "*",
                "FIXTURES_REQUIRED": "*",
                "FIXTURES_SETUP": "*",
                "LABELS": "*",
                "MEASUREMENT": "*",
                "PASS_REGULAR_EXPRESSION": "*",
                "PROCESSOR_AFFINITY": "*",
                "PROCESSORS": "*",
                "REQUIRED_FILES": "*",
                "RESOURCE_GROUPS": "*",
                "RESOURCE_LOCK": "*",
                "RUN_SERIAL": "*",
                "SKIP_REGULAR_EXPRESSION": "*",
                "SKIP_RETURN_CODE": "*",
                "TIMEOUT": "*",
                "TIMEOUT_AFTER_MATCH": "*",
                "WILL_FAIL": "*",
                "WORKING_DIRECTORY": "*",
              },
            },
          },
        },
        "CACHE": {
          "pargs": "*",
          "kwargs": {
            "PROPERTY": {
              "kwargs": {
                "ADVANCED": "*",
                "HELPSTRING": "*",
                "MODIFIED": "*",
                "STRINGS": "*",
                "TYPE": "*",
                "VALUE": "*",
              },
            },
          },
        },
      },
    },
    "set_target_properties": {
      "pargs": "+",
      "kwargs": {
        "PROPERTIES": {
          "kwargs": {
            "ADDITIONAL_CLEAN_FILES": 1,
            "AIX_EXPORT_ALL_SYMBOLS": 1,
            "ALIAS_GLOBAL": 1,
            "ALIASED_TARGET": 1,
            "ANDROID_ANT_ADDITIONAL_OPTIONS": 1,
            "ANDROID_API": 1,
            "ANDROID_API_MIN": 1,
            "ANDROID_ARCH": 1,
            "ANDROID_ASSETS_DIRECTORIES": 1,
            "ANDROID_GUI": 1,
            "ANDROID_JAR_DEPENDENCIES": 1,
            "ANDROID_JAR_DIRECTORIES": 1,
            "ANDROID_JAVA_SOURCE_DIR": 1,
            "ANDROID_NATIVE_LIB_DEPENDENCIES": 1,
            "ANDROID_NATIVE_LIB_DIRECTORIES": 1,
            "ANDROID_PROCESS_MAX": 1,
            "ANDROID_PROGUARD": 1,
            "ANDROID_PROGUARD_CONFIG_PATH": 1,
            "ANDROID_SECURE_PROPS_PATH": 1,
            "ANDROID_SKIP_ANT_STEP": 1,
            "ANDROID_STL_TYPE": 1,
            "ARCHIVE_OUTPUT_DIRECTORY": 1,
            "ARCHIVE_OUTPUT_NAME": 1,
            "AUTOGEN_BUILD_DIR": 1,
            "AUTOGEN_ORIGIN_DEPENDS": 1,
            "AUTOGEN_PARALLEL": 1,
            "AUTOGEN_TARGET_DEPENDS": 1,
            "AUTOMOC": 1,
            "AUTOMOC_COMPILER_PREDEFINES": 1,
            "AUTOMOC_DEPEND_FILTERS": 1,
            "AUTOMOC_EXECUTABLE": 1,
            "AUTOMOC_MACRO_NAMES": 1,
            "AUTOMOC_MOC_OPTIONS": 1,
            "AUTOMOC_PATH_PREFIX": 1,
            "AUTORCC": 1,
            "AUTORCC_EXECUTABLE": 1,
            "AUTORCC_OPTIONS": 1,
            "AUTOUIC": 1,
            "AUTOUIC_EXECUTABLE": 1,
            "AUTOUIC_OPTIONS": 1,
            "AUTOUIC_SEARCH_PATHS": 1,
            "BINARY_DIR": 1,
            "BUILD_RPATH": 1,
            "BUILD_RPATH_USE_ORIGIN": 1,
            "BUILD_WITH_INSTALL_NAME_DIR": 1,
            "BUILD_WITH_INSTALL_RPATH": 1,
            "BUNDLE_EXTENSION": 1,
            "BUNDLE": 1,
            "C_EXTENSIONS": 1,
            "C_STANDARD": 1,
            "C_STANDARD_REQUIRED": 1,
            "COMMON_LANGUAGE_RUNTIME": 1,
            "COMPATIBLE_INTERFACE_BOOL": 1,
            "COMPATIBLE_INTERFACE_NUMBER_MAX": 1,
            "COMPATIBLE_INTERFACE_NUMBER_MIN": 1,
            "COMPATIBLE_INTERFACE_STRING": 1,
            "COMPILE_DEFINITIONS": 1,
            "COMPILE_FEATURES": 1,
            "COMPILE_FLAGS": 1,
            "COMPILE_OPTIONS": 1,
            "COMPILE_PDB_NAME": 1,
            "COMPILE_PDB_OUTPUT_DIRECTORY": 1,
            "CROSSCOMPILING_EMULATOR": 1,
            "CUDA_ARCHITECTURES": 1,
            "CUDA_PTX_COMPILATION": 1,
            "CUDA_SEPARABLE_COMPILATION": 1,
            "CUDA_RESOLVE_DEVICE_SYMBOLS": 1,
            "CUDA_RUNTIME_LIBRARY": 1,
            "CUDA_EXTENSIONS": 1,
            "CUDA_STANDARD": 1,
            "CUDA_STANDARD_REQUIRED": 1,
            "CXX_EXTENSIONS": 1,
            "CXX_STANDARD": 1,
            "CXX_STANDARD_REQUIRED": 1,
            "DEBUG_POSTFIX": 1,
            "DEFINE_SYMBOL": 1,
            "DEPLOYMENT_REMOTE_DIRECTORY": 1,
            "DEPLOYMENT_ADDITIONAL_FILES": 1,
            "DEPRECATION": 1,
            "DISABLE_PRECOMPILE_HEADERS": 1,
            "DOTNET_TARGET_FRAMEWORK": 1,
            "DOTNET_TARGET_FRAMEWORK_VERSION": 1,
            "EchoString": 1,
            "ENABLE_EXPORTS": 1,
            "EXCLUDE_FROM_ALL": 1,
            "EXCLUDE_FROM_DEFAULT_BUILD": 1,
            "EXPORT_NAME": 1,
            "EXPORT_PROPERTIES": 1,
            "FOLDER": 1,
            "Fortran_FORMAT": 1,
            "Fortran_MODULE_DIRECTORY": 1,
            "Fortran_PREPROCESS": 1,
            "FRAMEWORK": 1,
            "FRAMEWORK_VERSION": 1,
            "GENERATOR_FILE_NAME": 1,
            "GHS_INTEGRITY_APP": 1,
            "GHS_NO_SOURCE_GROUP_FILE": 1,
            "GNUtoMS": 1,
            "HAS_CXX": 1,
            "IMPLICIT_DEPENDS_INCLUDE_TRANSFORM": 1,
            "IMPORTED_COMMON_LANGUAGE_RUNTIME": 1,
            "IMPORTED_CONFIGURATIONS": 1,
            "IMPORTED_GLOBAL": 1,
            "IMPORTED_IMPLIB": 1,
            "IMPORTED_LIBNAME": 1,
            "IMPORTED_LINK_DEPENDENT_LIBRARIES": 1,
            "IMPORTED_LINK_INTERFACE_LANGUAGES": 1,
            "IMPORTED_LINK_INTERFACE_LIBRARIES": 1,
            "IMPORTED_LINK_INTERFACE_MULTIPLICITY": 1,
            "IMPORTED_LOCATION": 1,
            "IMPORTED_NO_SONAME": 1,
            "IMPORTED_OBJECTS": 1,
            "IMPORTED": 1,
            "IMPORTED_SONAME": 1,
            "IMPORT_PREFIX": 1,
            "IMPORT_SUFFIX": 1,
            "INCLUDE_DIRECTORIES": 1,
            "INSTALL_NAME_DIR": 1,
            "INSTALL_REMOVE_ENVIRONMENT_RPATH": 1,
            "INSTALL_RPATH": 1,
            "INSTALL_RPATH_USE_LINK_PATH": 1,
            "INTERFACE_AUTOUIC_OPTIONS": 1,
            "INTERFACE_COMPILE_DEFINITIONS": 1,
            "INTERFACE_COMPILE_FEATURES": 1,
            "INTERFACE_COMPILE_OPTIONS": 1,
            "INTERFACE_INCLUDE_DIRECTORIES": 1,
            "INTERFACE_LINK_DEPENDS": 1,
            "INTERFACE_LINK_DIRECTORIES": 1,
            "INTERFACE_LINK_LIBRARIES": 1,
            "INTERFACE_LINK_OPTIONS": 1,
            "INTERFACE_PRECOMPILE_HEADERS": 1,
            "INTERFACE_POSITION_INDEPENDENT_CODE": 1,
            "INTERFACE_SOURCES": 1,
            "INTERFACE_SYSTEM_INCLUDE_DIRECTORIES": 1,
            "INTERPROCEDURAL_OPTIMIZATION": 1,
            "IOS_INSTALL_COMBINED": 1,
            "JOB_POOL_COMPILE": 1,
            "JOB_POOL_LINK": 1,
            "JOB_POOL_PRECOMPILE_HEADER": 1,
            "LABELS": 1,
            "LIBRARY_OUTPUT_DIRECTORY": 1,
            "LIBRARY_OUTPUT_NAME": 1,
            "LINK_DEPENDS_NO_SHARED": 1,
            "LINK_DEPENDS": 1,
            "LINKER_LANGUAGE": 1,
            "LINK_DIRECTORIES": 1,
            "LINK_FLAGS": 1,
            "LINK_INTERFACE_LIBRARIES": 1,
            "LINK_INTERFACE_MULTIPLICITY": 1,
            "LINK_LIBRARIES": 1,
            "LINK_OPTIONS": 1,
            "LINK_SEARCH_END_STATIC": 1,
            "LINK_SEARCH_START_STATIC": 1,
            "LINK_WHAT_YOU_USE": 1,
            "LOCATION": 1,
            "MACHO_COMPATIBILITY_VERSION": 1,
            "MACHO_CURRENT_VERSION": 1,
            "MACOSX_BUNDLE_INFO_PLIST": 1,
            "MACOSX_BUNDLE": 1,
            "MACOSX_FRAMEWORK_INFO_PLIST": 1,
            "MACOSX_RPATH": 1,
            "MANUALLY_ADDED_DEPENDENCIES": 1,
            "MSVC_RUNTIME_LIBRARY": 1,
            "NAME": 1,
            "NO_SONAME": 1,
            "NO_SYSTEM_FROM_IMPORTED": 1,
            "OBJC_EXTENSIONS": 1,
            "OBJC_STANDARD": 1,
            "OBJC_STANDARD_REQUIRED": 1,
            "OBJCXX_EXTENSIONS": 1,
            "OBJCXX_STANDARD": 1,
            "OBJCXX_STANDARD_REQUIRED": 1,
            "OSX_ARCHITECTURES": 1,
            "OUTPUT_NAME": 1,
            "PCH_WARN_INVALID": 1,
            "PDB_NAME": 1,
            "PDB_OUTPUT_DIRECTORY": 1,
            "POSITION_INDEPENDENT_CODE": 1,
            "PRECOMPILE_HEADERS": 1,
            "PRECOMPILE_HEADERS_REUSE_FROM": 1,
            "PREFIX": 1,
            "PRIVATE_HEADER": 1,
            "PROJECT_LABEL": 1,
            "PUBLIC_HEADER": 1,
            "RESOURCE": 1,
            "RULE_LAUNCH_COMPILE": 1,
            "RULE_LAUNCH_CUSTOM": 1,
            "RULE_LAUNCH_LINK": 1,
            "RUNTIME_OUTPUT_DIRECTORY": 1,
            "RUNTIME_OUTPUT_NAME": 1,
            "SKIP_BUILD_RPATH": 1,
            "SOURCE_DIR": 1,
            "SOURCES": 1,
            "SOVERSION": 1,
            "STATIC_LIBRARY_FLAGS": 1,
            "STATIC_LIBRARY_OPTIONS": 1,
            "SUFFIX": 1,
            "Swift_DEPENDENCIES_FILE": 1,
            "Swift_LANGUAGE_VERSION": 1,
            "Swift_MODULE_DIRECTORY": 1,
            "Swift_MODULE_NAME": 1,
            "TYPE": 1,
            "UNITY_BUILD": 1,
            "UNITY_BUILD_BATCH_SIZE": 1,
            "UNITY_BUILD_CODE_AFTER_INCLUDE": 1,
            "UNITY_BUILD_CODE_BEFORE_INCLUDE": 1,
            "UNITY_BUILD_MODE": 1,
            "VERSION": 1,
            "VISIBILITY_INLINES_HIDDEN": 1,
            "VS_CONFIGURATION_TYPE": 1,
            "VS_DEBUGGER_COMMAND": 1,
            "VS_DEBUGGER_COMMAND_ARGUMENTS": 1,
            "VS_DEBUGGER_ENVIRONMENT": 1,
            "VS_DEBUGGER_WORKING_DIRECTORY": 1,
            "VS_DESKTOP_EXTENSIONS_VERSION": 1,
            "VS_DOTNET_REFERENCES": 1,
            "VS_DOTNET_REFERENCES_COPY_LOCAL": 1,
            "VS_DOTNET_TARGET_FRAMEWORK_VERSION": 1,
            "VS_DOTNET_DOCUMENTATION_FILE": 1,
            "VS_DPI_AWARE": 1,
            "VS_GLOBAL_KEYWORD": 1,
            "VS_GLOBAL_PROJECT_TYPES": 1,
            "VS_GLOBAL_ROOTNAMESPACE": 1,
            "VS_IOT_EXTENSIONS_VERSION": 1,
            "VS_IOT_STARTUP_TASK": 1,
            "VS_JUST_MY_CODE_DEBUGGING": 1,
            "VS_KEYWORD": 1,
            "VS_MOBILE_EXTENSIONS_VERSION": 1,
            "VS_NO_SOLUTION_DEPLOY": 1,
            "VS_PACKAGE_REFERENCES": 1,
            "VS_PLATFORM_TOOLSET": 1,
            "VS_PROJECT_IMPORT": 1,
            "VS_SCC_AUXPATH": 1,
            "VS_SCC_LOCALPATH": 1,
            "VS_SCC_PROJECTNAME": 1,
            "VS_SCC_PROVIDER": 1,
            "VS_SDK_REFERENCES": 1,
            "VS_SOLUTION_DEPLOY": 1,
            "VS_USER_PROPS": 1,
            "VS_WINDOWS_TARGET_PLATFORM_MIN_VERSION": 1,
            "VS_WINRT_COMPONENT": 1,
            "VS_WINRT_EXTENSIONS": 1,
            "VS_WINRT_REFERENCES": 1,
            "WIN32_EXECUTABLE": 1,
            "WINDOWS_EXPORT_ALL_SYMBOLS": 1,
            "XCODE_EXPLICIT_FILE_TYPE": 1,
            "XCODE_GENERATE_SCHEME": 1,
            "XCODE_PRODUCT_TYPE": 1,
            "XCODE_SCHEME_ADDRESS_SANITIZER": 1,
            "XCODE_SCHEME_ADDRESS_SANITIZER_USE_AFTER_RETURN": 1,
            "XCODE_SCHEME_ARGUMENTS": 1,
            "XCODE_SCHEME_DEBUG_AS_ROOT": 1,
            "XCODE_SCHEME_DEBUG_DOCUMENT_VERSIONING": 1,
            "XCODE_SCHEME_DISABLE_MAIN_THREAD_CHECKER": 1,
            "XCODE_SCHEME_DYNAMIC_LIBRARY_LOADS": 1,
            "XCODE_SCHEME_DYNAMIC_LINKER_API_USAGE": 1,
            "XCODE_SCHEME_ENVIRONMENT": 1,
            "XCODE_SCHEME_EXECUTABLE": 1,
            "XCODE_SCHEME_GUARD_MALLOC": 1,
            "XCODE_SCHEME_MAIN_THREAD_CHECKER_STOP": 1,
            "XCODE_SCHEME_MALLOC_GUARD_EDGES": 1,
            "XCODE_SCHEME_MALLOC_SCRIBBLE": 1,
            "XCODE_SCHEME_MALLOC_STACK": 1,
            "XCODE_SCHEME_THREAD_SANITIZER": 1,
            "XCODE_SCHEME_THREAD_SANITIZER_STOP": 1,
            "XCODE_SCHEME_UNDEFINED_BEHAVIOUR_SANITIZER": 1,
            "XCODE_SCHEME_UNDEFINED_BEHAVIOUR_SANITIZER_STOP": 1,
            "XCODE_SCHEME_WORKING_DIRECTORY": 1,
            "XCODE_SCHEME_ZOMBIE_OBJECTS": 1,
            "XCTEST": 1,
          },
        },
      },
    },
    "target_link_options": {
      "pargs": 1,
      "flags": ["BEFORE"],
      "kwargs": {
        "INTERFACE": "*",
        "PUBLIC": "*",
        "PRIVATE": "*",
      },
    },
  }

  # Specify property tags.
  proptags = []

  # Specify variable tags.
  vartags = []

  # Override configurations per-command where available
  override_spec = { }

# -------------------------------
# Options affecting file encoding
# -------------------------------
with section("encode"):

  # If true, emit the unicode byte-order mark (BOM) at the start of the file
  emit_byteorder_mark = False

  # Specify the encoding of the input file. Defaults to utf-8
  input_encoding = u'utf-8'

  # Specify the encoding of the output file. Defaults to utf-8. Note that cmake
  # only claims to support utf-8 so be careful when using anything else
  output_encoding = u'utf-8'