<commit_before>// Scintilla source code edit control
/** @file LexMSSQL.cxx
 ** Lexer for MSSQL.
 **/
// By Filip Yaghob <fyaghob@gmail.com>

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>

#include "Platform.h"

#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"

#define KW_MSSQL_STATEMENTS         0
#define KW_MSSQL_DATA_TYPES         1
#define KW_MSSQL_SYSTEM_TABLES      2
#define KW_MSSQL_GLOBAL_VARIABLES   3
#define KW_MSSQL_FUNCTIONS          4
#define KW_MSSQL_STORED_PROCEDURES  5
#define KW_MSSQL_OPERATORS          6

static bool isMSSQLOperator(char ch) {
	if (isascii(ch) && isalnum(ch))
		return false;
	// '.' left out as it is used to make up numbers
	if (ch == '%' || ch == '^' || ch == '&' || ch == '*' ||
        ch == '-' || ch == '+' || ch == '=' || ch == '|' ||
        ch == '<' || ch == '>' || ch == '/' ||
        ch == '!' || ch == '~' || ch == '(' || ch == ')' ||
		ch == ',')
		return true;
	return false;
}

static char classifyWordSQL(unsigned int start,
                            unsigned int end,
                            WordList *keywordlists[],
                            Accessor &styler,
                            unsigned int actualState,
							unsigned int prevState) {
	char s[256];
	bool wordIsNumber = isdigit(styler[start]) || (styler[start] == '.');

	WordList &kwStatements          = *keywordlists[KW_MSSQL_STATEMENTS];
    WordList &kwDataTypes           = *keywordlists[KW_MSSQL_DATA_TYPES];
    WordList &kwSystemTables        = *keywordlists[KW_MSSQL_SYSTEM_TABLES];
    WordList &kwGlobalVariables     = *keywordlists[KW_MSSQL_GLOBAL_VARIABLES];
    WordList &kwFunctions           = *keywordlists[KW_MSSQL_FUNCTIONS];
    WordList &kwStoredProcedures    = *keywordlists[KW_MSSQL_STORED_PROCEDURES];
    WordList &kwOperators           = *keywordlists[KW_MSSQL_OPERATORS];

	for (unsigned int i = 0; i < end - start + 1 && i < 128; i++) {
		s[i] = static_cast<char>(tolower(styler[start + i]));
		s[i + 1] = '\0';
	}
	char chAttr = SCE_MSSQL_IDENTIFIER;

	if (actualState == SCE_MSSQL_GLOBAL_VARIABLE) {

        if (kwGlobalVariables.InList(&s[2]))
            chAttr = SCE_MSSQL_GLOBAL_VARIABLE;

	} else if (wordIsNumber) {
		chAttr = SCE_MSSQL_NUMBER;

	} else if (prevState == SCE_MSSQL_DEFAULT_PREF_DATATYPE) {
		// Look first in datatypes
        if (kwDataTypes.InList(s))
            chAttr = SCE_MSSQL_DATATYPE;
		else if (kwOperators.InList(s))
			chAttr = SCE_MSSQL_OPERATOR;
		else if (kwStatements.InList(s))
			chAttr = SCE_MSSQL_STATEMENT;
		else if (kwSystemTables.InList(s))
			chAttr = SCE_MSSQL_SYSTABLE;
		else if (kwFunctions.InList(s))
            chAttr = SCE_MSSQL_FUNCTION;
		else if (kwStoredProcedures.InList(s))
			chAttr = SCE_MSSQL_STORED_PROCEDURE;

	} else {
		if (kwOperators.InList(s))
			chAttr = SCE_MSSQL_OPERATOR;
		else if (kwStatements.InList(s))
			chAttr = SCE_MSSQL_STATEMENT;
		else if (kwSystemTables.InList(s))
			chAttr = SCE_MSSQL_SYSTABLE;
		else if (kwFunctions.InList(s))
			chAttr = SCE_MSSQL_FUNCTION;
		else if (kwStoredProcedures.InList(s))
			chAttr = SCE_MSSQL_STORED_PROCEDURE;
		else if (kwDataTypes.InList(s))
			chAttr = SCE_MSSQL_DATATYPE;
	}

	styler.ColourTo(end, chAttr);

	return chAttr;
}

static void ColouriseMSSQLDoc(unsigned int startPos, int length,
                              int initStyle, WordList *keywordlists[], Accessor &styler) {

	styler.StartAt(startPos);

	bool fold = styler.GetPropertyInt("fold") != 0;
	int lineCurrent = styler.GetLine(startPos);
	int spaceFlags = 0;

	int state = initStyle;
	int prevState = initStyle;
	char chPrev = ' ';
	char chNext = styler[startPos];
	styler.StartSegment(startPos);
	unsigned int lengthDoc = startPos + length;
	for (unsigned int i = startPos; i < lengthDoc; i++) {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);

		if ((ch == '\r' && chNext != '\n') || (ch == '\n')) {
			int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags);
			int lev = indentCurrent;
			if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) {
				// Only non whitespace lines can be headers
				int indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags);
				if (indentCurrent < (indentNext & ~SC_FOLDLEVELWHITEFLAG)) {
					lev |= SC_FOLDLEVELHEADERFLAG;
				}
			}
			if (fold) {
				styler.SetLevel(lineCurrent, lev);
			}
		}

		if (styler.IsLeadByte(ch)) {
			chNext = styler.SafeGetCharAt(i + 2);
			chPrev = ' ';
			i += 1;
			continue;
		}

		// When the last char isn't part of the state (have to deal with it too)...
		if ( (state == SCE_MSSQL_IDENTIFIER) ||
                    (state == SCE_MSSQL_STORED_PROCEDURE) ||
                    (state == SCE_MSSQL_DATATYPE) ||
                    //~ (state == SCE_MSSQL_COLUMN_NAME) ||
                    (state == SCE_MSSQL_FUNCTION) ||
                    //~ (state == SCE_MSSQL_GLOBAL_VARIABLE) ||
                    (state == SCE_MSSQL_VARIABLE)) {
			if (!iswordchar(ch)) {
				int stateTmp;

                if ((state == SCE_MSSQL_VARIABLE) || (state == SCE_MSSQL_COLUMN_NAME)) {
                    styler.ColourTo(i - 1, state);
					stateTmp = state;
                } else
                    stateTmp = classifyWordSQL(styler.GetStartSegment(), i - 1, keywordlists, styler, state, prevState);

				prevState = state;

				if (stateTmp == SCE_MSSQL_IDENTIFIER || stateTmp == SCE_MSSQL_VARIABLE)
					state = SCE_MSSQL_DEFAULT_PREF_DATATYPE;
				else
					state = SCE_MSSQL_DEFAULT;
			}
		} else if (state == SCE_MSSQL_LINE_COMMENT) {
			if (ch == '\r' || ch == '\n') {
				styler.ColourTo(i - 1, state);
				prevState = state;
				state = SCE_MSSQL_DEFAULT;
			}
		} else if (state == SCE_MSSQL_GLOBAL_VARIABLE) {
			if ((ch != '@') && !iswordchar(ch)) {
				classifyWordSQL(styler.GetStartSegment(), i - 1, keywordlists, styler, state, prevState);
				prevState = state;
				state = SCE_MSSQL_DEFAULT;
			}
		}

		// If is the default or one of the above succeeded
		if (state == SCE_MSSQL_DEFAULT || state == SCE_MSSQL_DEFAULT_PREF_DATATYPE) {
			if (iswordstart(ch)) {
				styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				prevState = state;
				state = SCE_MSSQL_IDENTIFIER;
			} else if (ch == '/' && chNext == '*') {
				styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				prevState = state;
				state = SCE_MSSQL_COMMENT;
			} else if (ch == '-' && chNext == '-') {
				styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				prevState = state;
				state = SCE_MSSQL_LINE_COMMENT;
			} else if (ch == '\'') {
				styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				prevState = state;
				state = SCE_MSSQL_STRING;
			} else if (ch == '"') {
				styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				prevState = state;
				state = SCE_MSSQL_COLUMN_NAME;
			} else if (ch == '[') {
				styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				prevState = state;
				state = SCE_MSSQL_COLUMN_NAME_2;
			} else if (isMSSQLOperator(ch)) {
				styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				styler.ColourTo(i, SCE_MSSQL_OPERATOR);
                //~ style = SCE_MSSQL_DEFAULT;
				prevState = state;
				state = SCE_MSSQL_DEFAULT;
			} else if (ch == '@') {
                styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				prevState = state;
                if (chNext == '@') {
                    state = SCE_MSSQL_GLOBAL_VARIABLE;
//                    i += 2;
                } else
                    state = SCE_MSSQL_VARIABLE;
            }

		// When the last char is part of the state...
		} else if (state == SCE_MSSQL_COMMENT) {
				if (ch == '/' && chPrev == '*') {
					if (((i > (styler.GetStartSegment() + 2)) || ((initStyle == SCE_MSSQL_COMMENT) &&
					    (styler.GetStartSegment() == startPos)))) {
						styler.ColourTo(i, state);
						//~ state = SCE_MSSQL_COMMENT;
					prevState = state;
                        state = SCE_MSSQL_DEFAULT;
					}
				}
			} else if (state == SCE_MSSQL_STRING) {
				if (ch == '\'') {
					if ( chNext == '\'' ) {
						i++;
					ch = chNext;
					chNext = styler.SafeGetCharAt(i + 1);
					} else {
						styler.ColourTo(i, state);
					prevState = state;
						state = SCE_MSSQL_DEFAULT;
					//i++;
					}
				//ch = chNext;
				//chNext = styler.SafeGetCharAt(i + 1);
				}
			} else if (state == SCE_MSSQL_COLUMN_NAME) {
				if (ch == '"') {
					if (chNext == '"') {
						i++;
					ch = chNext;
					chNext = styler.SafeGetCharAt(i + 1);
				} else {
                    styler.ColourTo(i, state);
					prevState = state;
					state = SCE_MSSQL_DEFAULT_PREF_DATATYPE;
					//i++;
                }
                }
		} else if (state == SCE_MSSQL_COLUMN_NAME_2) {
			if (ch == ']') {
                styler.ColourTo(i, state);
				prevState = state;
                state = SCE_MSSQL_DEFAULT_PREF_DATATYPE;
                //i++;
			}
		}

		chPrev = ch;
	}
	styler.ColourTo(lengthDoc - 1, state);
}

static void FoldMSSQLDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) {
	bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
	bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
	unsigned int endPos = startPos + length;
	int visibleChars = 0;
	int lineCurrent = styler.GetLine(startPos);
	int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
	int levelCurrent = levelPrev;
	char chNext = styler[startPos];
	bool inComment = (styler.StyleAt(startPos-1) == SCE_MSSQL_COMMENT);
    char s[10];
	for (unsigned int i = startPos; i < endPos; i++) {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);
		int style = styler.StyleAt(i);
		bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
        // Comment folding
		if (foldComment) {
			if (!inComment && (style == SCE_MSSQL_COMMENT))
				levelCurrent++;
			else if (inComment && (style != SCE_MSSQL_COMMENT))
				levelCurrent--;
			inComment = (style == SCE_MSSQL_COMMENT);
		}
        if (style == SCE_MSSQL_STATEMENT) {
            // Folding between begin and end
            if (ch == 'b' || ch == 'e') {
                for (unsigned int j = 0; j < 5; j++) {
					if (!iswordchar(styler[i + j])) {
						break;
					}
					s[j] = styler[i + j];
					s[j + 1] = '\0';
                }
				if (strcmp(s, "begin") == 0) {
					levelCurrent++;
				}
				if (strcmp(s, "end") == 0) {
					levelCurrent--;
				}
            }
        }
		if (atEOL) {
			int lev = levelPrev;
			if (visibleChars == 0 && foldCompact)
				lev |= SC_FOLDLEVELWHITEFLAG;
			if ((levelCurrent > levelPrev) && (visibleChars > 0))
				lev |= SC_FOLDLEVELHEADERFLAG;
			if (lev != styler.LevelAt(lineCurrent)) {
				styler.SetLevel(lineCurrent, lev);
			}
			lineCurrent++;
			levelPrev = levelCurrent;
			visibleChars = 0;
		}
		if (!isspacechar(ch))
			visibleChars++;
	}
	// Fill in the real level of the next line, keeping the current flags as they will be filled in later
	int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
	styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}

static const char * const sqlWordListDesc[] = {
	"Statements",
    "Data Types",
    "System tables",
    "Global variables",
    "Functions",
    "System Stored Procedures",
    "Operators",
	0,
};

LexerModule lmMSSQL(SCLEX_MSSQL, ColouriseMSSQLDoc, "mssql", FoldMSSQLDoc, sqlWordListDesc);
<commit_msg>Added license reference to help the picky.<commit_after>// Scintilla source code edit control
/** @file LexMSSQL.cxx
 ** Lexer for MSSQL.
 **/
// By Filip Yaghob <fyaghob@gmail.com>
// The License.txt file describes the conditions under which this software may be distributed.

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>

#include "Platform.h"

#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"

#define KW_MSSQL_STATEMENTS         0
#define KW_MSSQL_DATA_TYPES         1
#define KW_MSSQL_SYSTEM_TABLES      2
#define KW_MSSQL_GLOBAL_VARIABLES   3
#define KW_MSSQL_FUNCTIONS          4
#define KW_MSSQL_STORED_PROCEDURES  5
#define KW_MSSQL_OPERATORS          6

static bool isMSSQLOperator(char ch) {
	if (isascii(ch) && isalnum(ch))
		return false;
	// '.' left out as it is used to make up numbers
	if (ch == '%' || ch == '^' || ch == '&' || ch == '*' ||
        ch == '-' || ch == '+' || ch == '=' || ch == '|' ||
        ch == '<' || ch == '>' || ch == '/' ||
        ch == '!' || ch == '~' || ch == '(' || ch == ')' ||
		ch == ',')
		return true;
	return false;
}

static char classifyWordSQL(unsigned int start,
                            unsigned int end,
                            WordList *keywordlists[],
                            Accessor &styler,
                            unsigned int actualState,
							unsigned int prevState) {
	char s[256];
	bool wordIsNumber = isdigit(styler[start]) || (styler[start] == '.');

	WordList &kwStatements          = *keywordlists[KW_MSSQL_STATEMENTS];
    WordList &kwDataTypes           = *keywordlists[KW_MSSQL_DATA_TYPES];
    WordList &kwSystemTables        = *keywordlists[KW_MSSQL_SYSTEM_TABLES];
    WordList &kwGlobalVariables     = *keywordlists[KW_MSSQL_GLOBAL_VARIABLES];
    WordList &kwFunctions           = *keywordlists[KW_MSSQL_FUNCTIONS];
    WordList &kwStoredProcedures    = *keywordlists[KW_MSSQL_STORED_PROCEDURES];
    WordList &kwOperators           = *keywordlists[KW_MSSQL_OPERATORS];

	for (unsigned int i = 0; i < end - start + 1 && i < 128; i++) {
		s[i] = static_cast<char>(tolower(styler[start + i]));
		s[i + 1] = '\0';
	}
	char chAttr = SCE_MSSQL_IDENTIFIER;

	if (actualState == SCE_MSSQL_GLOBAL_VARIABLE) {

        if (kwGlobalVariables.InList(&s[2]))
            chAttr = SCE_MSSQL_GLOBAL_VARIABLE;

	} else if (wordIsNumber) {
		chAttr = SCE_MSSQL_NUMBER;

	} else if (prevState == SCE_MSSQL_DEFAULT_PREF_DATATYPE) {
		// Look first in datatypes
        if (kwDataTypes.InList(s))
            chAttr = SCE_MSSQL_DATATYPE;
		else if (kwOperators.InList(s))
			chAttr = SCE_MSSQL_OPERATOR;
		else if (kwStatements.InList(s))
			chAttr = SCE_MSSQL_STATEMENT;
		else if (kwSystemTables.InList(s))
			chAttr = SCE_MSSQL_SYSTABLE;
		else if (kwFunctions.InList(s))
            chAttr = SCE_MSSQL_FUNCTION;
		else if (kwStoredProcedures.InList(s))
			chAttr = SCE_MSSQL_STORED_PROCEDURE;

	} else {
		if (kwOperators.InList(s))
			chAttr = SCE_MSSQL_OPERATOR;
		else if (kwStatements.InList(s))
			chAttr = SCE_MSSQL_STATEMENT;
		else if (kwSystemTables.InList(s))
			chAttr = SCE_MSSQL_SYSTABLE;
		else if (kwFunctions.InList(s))
			chAttr = SCE_MSSQL_FUNCTION;
		else if (kwStoredProcedures.InList(s))
			chAttr = SCE_MSSQL_STORED_PROCEDURE;
		else if (kwDataTypes.InList(s))
			chAttr = SCE_MSSQL_DATATYPE;
	}

	styler.ColourTo(end, chAttr);

	return chAttr;
}

static void ColouriseMSSQLDoc(unsigned int startPos, int length,
                              int initStyle, WordList *keywordlists[], Accessor &styler) {

	styler.StartAt(startPos);

	bool fold = styler.GetPropertyInt("fold") != 0;
	int lineCurrent = styler.GetLine(startPos);
	int spaceFlags = 0;

	int state = initStyle;
	int prevState = initStyle;
	char chPrev = ' ';
	char chNext = styler[startPos];
	styler.StartSegment(startPos);
	unsigned int lengthDoc = startPos + length;
	for (unsigned int i = startPos; i < lengthDoc; i++) {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);

		if ((ch == '\r' && chNext != '\n') || (ch == '\n')) {
			int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags);
			int lev = indentCurrent;
			if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) {
				// Only non whitespace lines can be headers
				int indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags);
				if (indentCurrent < (indentNext & ~SC_FOLDLEVELWHITEFLAG)) {
					lev |= SC_FOLDLEVELHEADERFLAG;
				}
			}
			if (fold) {
				styler.SetLevel(lineCurrent, lev);
			}
		}

		if (styler.IsLeadByte(ch)) {
			chNext = styler.SafeGetCharAt(i + 2);
			chPrev = ' ';
			i += 1;
			continue;
		}

		// When the last char isn't part of the state (have to deal with it too)...
		if ( (state == SCE_MSSQL_IDENTIFIER) ||
                    (state == SCE_MSSQL_STORED_PROCEDURE) ||
                    (state == SCE_MSSQL_DATATYPE) ||
                    //~ (state == SCE_MSSQL_COLUMN_NAME) ||
                    (state == SCE_MSSQL_FUNCTION) ||
                    //~ (state == SCE_MSSQL_GLOBAL_VARIABLE) ||
                    (state == SCE_MSSQL_VARIABLE)) {
			if (!iswordchar(ch)) {
				int stateTmp;

                if ((state == SCE_MSSQL_VARIABLE) || (state == SCE_MSSQL_COLUMN_NAME)) {
                    styler.ColourTo(i - 1, state);
					stateTmp = state;
                } else
                    stateTmp = classifyWordSQL(styler.GetStartSegment(), i - 1, keywordlists, styler, state, prevState);

				prevState = state;

				if (stateTmp == SCE_MSSQL_IDENTIFIER || stateTmp == SCE_MSSQL_VARIABLE)
					state = SCE_MSSQL_DEFAULT_PREF_DATATYPE;
				else
					state = SCE_MSSQL_DEFAULT;
			}
		} else if (state == SCE_MSSQL_LINE_COMMENT) {
			if (ch == '\r' || ch == '\n') {
				styler.ColourTo(i - 1, state);
				prevState = state;
				state = SCE_MSSQL_DEFAULT;
			}
		} else if (state == SCE_MSSQL_GLOBAL_VARIABLE) {
			if ((ch != '@') && !iswordchar(ch)) {
				classifyWordSQL(styler.GetStartSegment(), i - 1, keywordlists, styler, state, prevState);
				prevState = state;
				state = SCE_MSSQL_DEFAULT;
			}
		}

		// If is the default or one of the above succeeded
		if (state == SCE_MSSQL_DEFAULT || state == SCE_MSSQL_DEFAULT_PREF_DATATYPE) {
			if (iswordstart(ch)) {
				styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				prevState = state;
				state = SCE_MSSQL_IDENTIFIER;
			} else if (ch == '/' && chNext == '*') {
				styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				prevState = state;
				state = SCE_MSSQL_COMMENT;
			} else if (ch == '-' && chNext == '-') {
				styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				prevState = state;
				state = SCE_MSSQL_LINE_COMMENT;
			} else if (ch == '\'') {
				styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				prevState = state;
				state = SCE_MSSQL_STRING;
			} else if (ch == '"') {
				styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				prevState = state;
				state = SCE_MSSQL_COLUMN_NAME;
			} else if (ch == '[') {
				styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				prevState = state;
				state = SCE_MSSQL_COLUMN_NAME_2;
			} else if (isMSSQLOperator(ch)) {
				styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				styler.ColourTo(i, SCE_MSSQL_OPERATOR);
                //~ style = SCE_MSSQL_DEFAULT;
				prevState = state;
				state = SCE_MSSQL_DEFAULT;
			} else if (ch == '@') {
                styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
				prevState = state;
                if (chNext == '@') {
                    state = SCE_MSSQL_GLOBAL_VARIABLE;
//                    i += 2;
                } else
                    state = SCE_MSSQL_VARIABLE;
            }

		// When the last char is part of the state...
		} else if (state == SCE_MSSQL_COMMENT) {
				if (ch == '/' && chPrev == '*') {
					if (((i > (styler.GetStartSegment() + 2)) || ((initStyle == SCE_MSSQL_COMMENT) &&
					    (styler.GetStartSegment() == startPos)))) {
						styler.ColourTo(i, state);
						//~ state = SCE_MSSQL_COMMENT;
					prevState = state;
                        state = SCE_MSSQL_DEFAULT;
					}
				}
			} else if (state == SCE_MSSQL_STRING) {
				if (ch == '\'') {
					if ( chNext == '\'' ) {
						i++;
					ch = chNext;
					chNext = styler.SafeGetCharAt(i + 1);
					} else {
						styler.ColourTo(i, state);
					prevState = state;
						state = SCE_MSSQL_DEFAULT;
					//i++;
					}
				//ch = chNext;
				//chNext = styler.SafeGetCharAt(i + 1);
				}
			} else if (state == SCE_MSSQL_COLUMN_NAME) {
				if (ch == '"') {
					if (chNext == '"') {
						i++;
					ch = chNext;
					chNext = styler.SafeGetCharAt(i + 1);
				} else {
                    styler.ColourTo(i, state);
					prevState = state;
					state = SCE_MSSQL_DEFAULT_PREF_DATATYPE;
					//i++;
                }
                }
		} else if (state == SCE_MSSQL_COLUMN_NAME_2) {
			if (ch == ']') {
                styler.ColourTo(i, state);
				prevState = state;
                state = SCE_MSSQL_DEFAULT_PREF_DATATYPE;
                //i++;
			}
		}

		chPrev = ch;
	}
	styler.ColourTo(lengthDoc - 1, state);
}

static void FoldMSSQLDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) {
	bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
	bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
	unsigned int endPos = startPos + length;
	int visibleChars = 0;
	int lineCurrent = styler.GetLine(startPos);
	int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
	int levelCurrent = levelPrev;
	char chNext = styler[startPos];
	bool inComment = (styler.StyleAt(startPos-1) == SCE_MSSQL_COMMENT);
    char s[10];
	for (unsigned int i = startPos; i < endPos; i++) {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);
		int style = styler.StyleAt(i);
		bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
        // Comment folding
		if (foldComment) {
			if (!inComment && (style == SCE_MSSQL_COMMENT))
				levelCurrent++;
			else if (inComment && (style != SCE_MSSQL_COMMENT))
				levelCurrent--;
			inComment = (style == SCE_MSSQL_COMMENT);
		}
        if (style == SCE_MSSQL_STATEMENT) {
            // Folding between begin and end
            if (ch == 'b' || ch == 'e') {
                for (unsigned int j = 0; j < 5; j++) {
					if (!iswordchar(styler[i + j])) {
						break;
					}
					s[j] = styler[i + j];
					s[j + 1] = '\0';
                }
				if (strcmp(s, "begin") == 0) {
					levelCurrent++;
				}
				if (strcmp(s, "end") == 0) {
					levelCurrent--;
				}
            }
        }
		if (atEOL) {
			int lev = levelPrev;
			if (visibleChars == 0 && foldCompact)
				lev |= SC_FOLDLEVELWHITEFLAG;
			if ((levelCurrent > levelPrev) && (visibleChars > 0))
				lev |= SC_FOLDLEVELHEADERFLAG;
			if (lev != styler.LevelAt(lineCurrent)) {
				styler.SetLevel(lineCurrent, lev);
			}
			lineCurrent++;
			levelPrev = levelCurrent;
			visibleChars = 0;
		}
		if (!isspacechar(ch))
			visibleChars++;
	}
	// Fill in the real level of the next line, keeping the current flags as they will be filled in later
	int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
	styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}

static const char * const sqlWordListDesc[] = {
	"Statements",
    "Data Types",
    "System tables",
    "Global variables",
    "Functions",
    "System Stored Procedures",
    "Operators",
	0,
};

LexerModule lmMSSQL(SCLEX_MSSQL, ColouriseMSSQLDoc, "mssql", FoldMSSQLDoc, sqlWordListDesc);
<|endoftext|>


<commit_before>#ifndef NEU_LAYER_LOAD_HPP
#define NEU_LAYER_LOAD_HPP
//20151211
#include <exception>
#include <yaml-cpp/yaml.h>
#include <neu/layer/inner_product.hpp>
#include <neu/layer/bias.hpp>
#include <neu/layer/activation/sigmoid.hpp>
#include <neu/layer/activation/rectifier.hpp>
#include <neu/layer/activation/sigmoid_loss.hpp>
#include <neu/layer/any_layer_vector.hpp>
namespace neu {
	namespace layer {
		class load_error : public std::exception {
		public:
			virtual const char* what() const noexcept {
				return "Unknown layer is loaded. Check layer data and load function.";
			}
		};
		any_layer load(YAML::Node const& node,
				boost::compute::command_queue& queue) {
			auto lt = node["layer_type"].as<std::string>();
			if(lt == "inner_product") {
				return static_cast<any_layer>(load_inner_product(node, queue));
			} else
			if(lt == "bias") {
				return static_cast<any_layer>(load_bias(node, queue));
			} else
			if(lt == "sigmoid") {
				return static_cast<any_layer>(load_sigmoid(node, queue));
			} else
			if(lt == "rectifier") {
				return static_cast<any_layer>(load_rectifier(node, queue));
			} else
			if(lt == "sigmoid_loss") {
				return static_cast<any_layer>(load_sigmoid_loss(node, queue));
			} else
			if(lt == "any_layer_vector") {
				return static_cast<any_layer>(load_any_layer_vector(node, queue));
			}
			else {
				throw load_error();
			}
		}
	}
}// namespace neu

#endif //NEU_LAYER_LOAD_HPP
<commit_msg>fix load_error<commit_after>#ifndef NEU_LAYER_LOAD_HPP
#define NEU_LAYER_LOAD_HPP
//20151211
#include <exception>
#include <yaml-cpp/yaml.h>
#include <neu/layer/inner_product.hpp>
#include <neu/layer/bias.hpp>
#include <neu/layer/activation/sigmoid.hpp>
#include <neu/layer/activation/rectifier.hpp>
#include <neu/layer/activation/sigmoid_loss.hpp>
#include <neu/layer/any_layer_vector.hpp>
namespace neu {
	namespace layer {
		class load_error : public std::exception {
		public:
			explicit load_error(std::string const& layer_id) : layer_id_(layer_id) {}

			virtual const char* what() const noexcept {
				return ("Unknown layer \""+ layer_id_
					+ "\" is loaded. Check layer data and load function.").c_str();
			}
		private:
			std::string layer_id_;
		};
		any_layer load(YAML::Node const& node,
				boost::compute::command_queue& queue) {
			auto lt = node["layer_type"].as<std::string>();
			if(lt == "inner_product") {
				return static_cast<any_layer>(load_inner_product(node, queue));
			} else
			if(lt == "bias") {
				return static_cast<any_layer>(load_bias(node, queue));
			} else
			if(lt == "sigmoid") {
				return static_cast<any_layer>(load_sigmoid(node, queue));
			} else
			if(lt == "rectifier") {
				return static_cast<any_layer>(load_rectifier(node, queue));
			} else
			if(lt == "sigmoid_loss") {
				return static_cast<any_layer>(load_sigmoid_loss(node, queue));
			} else
			if(lt == "any_layer_vector") {
				return static_cast<any_layer>(load_any_layer_vector(node, queue));
			}
			else {
				throw load_error(lt);
			}
		}
	}
}// namespace neu

#endif //NEU_LAYER_LOAD_HPP
<|endoftext|>


<commit_before>#line 2 "togo/resource/resource_package.cpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
*/

#include <togo/config.hpp>
#include <togo/utility/utility.hpp>
#include <togo/error/assert.hpp>
#include <togo/log/log.hpp>
#include <togo/hash/hash.hpp>
#include <togo/collection/hash_map.hpp>
#include <togo/io/io.hpp>
#include <togo/io/file_stream.hpp>
#include <togo/resource/types.hpp>
#include <togo/resource/resource.hpp>
#include <togo/resource/resource_package.hpp>
#include <togo/resource/resource_manager.hpp>
#include <togo/serialization/serializer.hpp>
#include <togo/serialization/support.hpp>
#include <togo/serialization/binary_serializer.hpp>
#include <togo/serialization/array.hpp>
#include <togo/serialization/resource/resource_metadata.hpp>

namespace togo {

ResourcePackage::ResourcePackage(
	StringRef const& name,
	StringRef const& path,
	Allocator& allocator
)
	: _name_hash(resource::hash_package_name(name))
	, _open_resource_id(0)
	, _stream()
	, _lookup(allocator)
	, _manifest(allocator)
	, _name()
	, _path()
{
	string::copy(_name, name);
	string::copy(_path, path);
}

void resource_package::open(
	ResourcePackage& pkg,
	ResourceManager const& rm
) {
	TOGO_ASSERT(!pkg._stream.is_open(), "package is already open");

	StringRef const name{pkg._name};
	StringRef const path{pkg._path};
	TOGO_ASSERTF(
		pkg._stream.open(path),
		"failed to open package '%.*s' at '%.*s'",
		name.size, name.data,
		path.size, path.data
	);

	BinaryInputSerializer ser{pkg._stream};
	u32 format_version = 0;
	ser % format_version;
	TOGO_ASSERTF(
		format_version == SER_FORMAT_VERSION_PKG_MANIFEST,
		"manifest version %u unsupported from package '%.*s' at '%.*s'",
		format_version,
		name.size, name.data,
		path.size, path.data
	);

	ser % make_ser_collection<u32>(pkg._manifest);
	for (u32 i = 0; i < array::size(pkg._manifest); ++i) {
		auto& metadata = pkg._manifest[i];
		if (metadata.type == RES_TYPE_NULL) {
			metadata.id = 0;
			continue;
		}
		metadata.id = i + 1;
		hash_map::push(pkg._lookup, metadata.name_hash, metadata.id);
		TOGO_ASSERTF(
			resource_manager::has_handler(rm, metadata.type),
			"no handler registered for resource %16lx's type %08x",
			metadata.name_hash, metadata.type
		);
	}
}

void resource_package::close(
	ResourcePackage& pkg
) {
	TOGO_ASSERT(pkg._stream.is_open(), "package is already closed");
	pkg._stream.close();
}

ResourceMetadata const& resource_package::resource_metadata(
	ResourcePackage const& pkg,
	u32 const id
) {
	TOGO_ASSERT(id > 0 && id <= array::size(pkg._manifest), "invalid ID");
	auto const& metadata = pkg._manifest[id - 1];
	TOGO_DEBUG_ASSERT(metadata.id != 0, "null entry");
	return metadata;
}

ResourcePackage::LookupNode* resource_package::find_resource(
	ResourcePackage& pkg,
	ResourceType const type,
	ResourceNameHash const name_hash
) {
	auto* const node = hash_map::get_node(pkg._lookup, name_hash);
	return (node && pkg._manifest[node->value - 1].type == type) ? node : nullptr;
}

IReader* resource_package::open_resource_stream(
	ResourcePackage& pkg,
	u32 const id
) {
	TOGO_ASSERT(pkg._stream.is_open(), "package is not open");
	TOGO_ASSERT(pkg._open_resource_id == 0, "a resource stream is already open");
	TOGO_ASSERT(id > 0 && id <= array::size(pkg._manifest), "invalid ID");
	auto const& metadata = pkg._manifest[id - 1];
	TOGO_ASSERTE(io::seek_to(pkg._stream, metadata.data_offset));
	pkg._open_resource_id = id;
	return &pkg._stream;
}

void resource_package::close_resource_stream(
	ResourcePackage& pkg
) {
	TOGO_ASSERT(pkg._stream.is_open(), "package is not open");
	TOGO_ASSERT(pkg._open_resource_id != 0, "no resource stream is open");
	#if defined(TOGO_DEBUG)
		auto const& metadata = pkg._manifest[pkg._open_resource_id - 1];
		auto const stream_pos = io::position(pkg._stream);
		TOGO_DEBUG_ASSERTE(
			stream_pos >= metadata.data_offset &&
			stream_pos <= metadata.data_offset + metadata.data_size
		);
	#endif
	pkg._open_resource_id = 0;
}

} // namespace togo
<commit_msg>resource/resource_package: lookup metadata with resource_metadata().<commit_after>#line 2 "togo/resource/resource_package.cpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
*/

#include <togo/config.hpp>
#include <togo/utility/utility.hpp>
#include <togo/error/assert.hpp>
#include <togo/log/log.hpp>
#include <togo/hash/hash.hpp>
#include <togo/collection/hash_map.hpp>
#include <togo/io/io.hpp>
#include <togo/io/file_stream.hpp>
#include <togo/resource/types.hpp>
#include <togo/resource/resource.hpp>
#include <togo/resource/resource_package.hpp>
#include <togo/resource/resource_manager.hpp>
#include <togo/serialization/serializer.hpp>
#include <togo/serialization/support.hpp>
#include <togo/serialization/binary_serializer.hpp>
#include <togo/serialization/array.hpp>
#include <togo/serialization/resource/resource_metadata.hpp>

namespace togo {

ResourcePackage::ResourcePackage(
	StringRef const& name,
	StringRef const& path,
	Allocator& allocator
)
	: _name_hash(resource::hash_package_name(name))
	, _open_resource_id(0)
	, _stream()
	, _lookup(allocator)
	, _manifest(allocator)
	, _name()
	, _path()
{
	string::copy(_name, name);
	string::copy(_path, path);
}

void resource_package::open(
	ResourcePackage& pkg,
	ResourceManager const& rm
) {
	TOGO_ASSERT(!pkg._stream.is_open(), "package is already open");

	StringRef const name{pkg._name};
	StringRef const path{pkg._path};
	TOGO_ASSERTF(
		pkg._stream.open(path),
		"failed to open package '%.*s' at '%.*s'",
		name.size, name.data,
		path.size, path.data
	);

	BinaryInputSerializer ser{pkg._stream};
	u32 format_version = 0;
	ser % format_version;
	TOGO_ASSERTF(
		format_version == SER_FORMAT_VERSION_PKG_MANIFEST,
		"manifest version %u unsupported from package '%.*s' at '%.*s'",
		format_version,
		name.size, name.data,
		path.size, path.data
	);

	ser % make_ser_collection<u32>(pkg._manifest);
	for (u32 i = 0; i < array::size(pkg._manifest); ++i) {
		auto& metadata = pkg._manifest[i];
		if (metadata.type == RES_TYPE_NULL) {
			metadata.id = 0;
			continue;
		}
		metadata.id = i + 1;
		hash_map::push(pkg._lookup, metadata.name_hash, metadata.id);
		TOGO_ASSERTF(
			resource_manager::has_handler(rm, metadata.type),
			"no handler registered for resource %16lx's type %08x",
			metadata.name_hash, metadata.type
		);
	}
}

void resource_package::close(
	ResourcePackage& pkg
) {
	TOGO_ASSERT(pkg._stream.is_open(), "package is already closed");
	pkg._stream.close();
}

ResourceMetadata const& resource_package::resource_metadata(
	ResourcePackage const& pkg,
	u32 const id
) {
	TOGO_ASSERT(id > 0 && id <= array::size(pkg._manifest), "invalid ID");
	auto const& metadata = pkg._manifest[id - 1];
	TOGO_DEBUG_ASSERT(metadata.id != 0, "null entry");
	return metadata;
}

ResourcePackage::LookupNode* resource_package::find_resource(
	ResourcePackage& pkg,
	ResourceType const type,
	ResourceNameHash const name_hash
) {
	auto* const node = hash_map::get_node(pkg._lookup, name_hash);
	return (node && pkg._manifest[node->value - 1].type == type) ? node : nullptr;
}

IReader* resource_package::open_resource_stream(
	ResourcePackage& pkg,
	u32 const id
) {
	TOGO_ASSERT(pkg._stream.is_open(), "package is not open");
	TOGO_ASSERT(pkg._open_resource_id == 0, "a resource stream is already open");
	auto const& metadata = resource_package::resource_metadata(pkg, id);
	TOGO_ASSERTE(io::seek_to(pkg._stream, metadata.data_offset));
	pkg._open_resource_id = id;
	return &pkg._stream;
}

void resource_package::close_resource_stream(
	ResourcePackage& pkg
) {
	TOGO_ASSERT(pkg._stream.is_open(), "package is not open");
	TOGO_ASSERT(pkg._open_resource_id != 0, "no resource stream is open");
	#if defined(TOGO_DEBUG)
		auto const& metadata = resource_package::resource_metadata(
			pkg, pkg._open_resource_id
		);
		auto const stream_pos = io::position(pkg._stream);
		TOGO_DEBUG_ASSERTE(
			stream_pos >= metadata.data_offset &&
			stream_pos <= metadata.data_offset + metadata.data_size
		);
	#endif
	pkg._open_resource_id = 0;
}

} // namespace togo
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_ASSEMBLER_GRIDWALKER_HH
#define DUNE_GDT_ASSEMBLER_GRIDWALKER_HH

#include <vector>
#include <memory>
#include <type_traits>

#include <dune/stuff/grid/boundaryinfo.hh>

namespace Dune {
namespace GDT {
namespace Functor {

template <class GridViewImp>
class Codim0
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim<0>::Entity EntityType;

  virtual ~Codim0()
  {
  }

  virtual void prepare()
  {
  }

  virtual void apply_local(const EntityType& entity) = 0;

  virtual void finalize()
  {
  }
}; // class Codim0

template <class GridViewImp>
class Codim1
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim<0>::Entity EntityType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual ~Codim1()
  {
  }

  virtual void prepare()
  {
  }

  virtual void apply_local(const IntersectionType& intersection) = 0;

  virtual void finalize()
  {
  }
}; // class Codim1

} // namespace Functor
namespace ApplyOn {

/**
 *  \brief Interface for functors to tell on which entity to apply.
 *
 *  The derived class has to provide a method with the following signature:
 *  \code
virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const
{
  ...
}
\endcode
 */
template <class GridViewImp>
class WhichEntity
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim<0>::Entity EntityType;

  virtual ~WhichEntity()
  {
  }

  virtual bool apply_on(const GridViewType& /*grid_view*/, const EntityType& /*entity*/) const = 0;
}; // class WhichEntity

/**
 *  \brief Selects all entities.
 */
template <class GridViewImp>
class AllEntities : public WhichEntity<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim<0>::Entity EntityType;

  virtual bool apply_on(const GridViewType& /*grid_view*/, const EntityType& /*entity*/) const DS_OVERRIDE DS_FINAL
  {
    return true;
  }
}; // class AllEntities

/**
 *  \brief Selects entities which have a boundary intersection.
 */
template <class GridViewImp>
class BoundaryEntities : public WhichEntity<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim<0>::Entity EntityType;

  virtual bool apply_on(const GridViewType& /*grid_view*/, const EntityType& entity) const DS_OVERRIDE DS_FINAL
  {
    return entity.hasBoundaryIntersections();
  }
}; // class BoundaryEntities

/**
 *  \brief Interface for functors to tell on which intersection to apply.
 *
 *  The derived class has to provide a method with the following signature:
 *  \code
virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const
{
  ...
}
\endcode
 */
template <class GridViewImp>
class WhichIntersection
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual ~WhichIntersection<GridViewImp>()
  {
  }

  virtual bool apply_on(const GridViewType& /*grid_view*/, const IntersectionType& /*intersection*/) const = 0;
}; // class WhichIntersection< GridViewImp >

/**
 *  \brief Selects all intersections.
 */
template <class GridViewImp>
class AllIntersections : public WhichIntersection<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual bool apply_on(const GridViewType& /*grid_view*/,
                        const IntersectionType& /*intersection*/) const DS_OVERRIDE DS_FINAL
  {
    return true;
  }
}; // class AllIntersections

/**
 *  \brief Selects each inner intersection.
 *
 *  To decide if this in an inner intersection,
\code
intersection.neighbor() && !intersection.boundary()
\endcode
 *  is used.
 */
template <class GridViewImp>
class InnerIntersections : public WhichIntersection<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual bool apply_on(const GridViewType& /*grid_view*/,
                        const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL
  {
    return intersection.neighbor() && !intersection.boundary();
  }
}; // class InnerIntersections

/**
 *  \brief Selects each inner intersection only once.
 *
 *  To decide if this in an inner intersection,
\code
intersection.neighbor() && !intersection.boundary()
\endcode
 *  is used, and true is returned, if the index of the inside() entity is smaller than the index of the outside()
 *  entity.
 */
template <class GridViewImp>
class InnerIntersectionsPrimally : public WhichIntersection<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL
  {
    if (intersection.neighbor() && !intersection.boundary()) {
      const auto insideEntityPtr    = intersection.inside();
      const auto& insideEntity      = *insideEntityPtr;
      const auto outsideNeighborPtr = intersection.outside();
      const auto& outsideNeighbor = *outsideNeighborPtr;
      return grid_view.indexSet().index(insideEntity) < grid_view.indexSet().index(outsideNeighbor);
    } else
      return false;
  }
}; // class InnerIntersections

template <class GridViewImp>
class BoundaryIntersections : public WhichIntersection<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual bool apply_on(const GridViewType& /*grid_view*/,
                        const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL
  {
    return intersection.boundary();
  }
}; // class BoundaryIntersections

template <class GridViewImp>
class DirichletIntersections : public WhichIntersection<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;
  typedef Stuff::GridboundaryInterface<IntersectionType> BoundaryInfoType;

  DirichletIntersections(const BoundaryInfoType& boundary_info)
    : boundary_info_(boundary_info)
  {
  }

  virtual bool apply_on(const GridViewType& /*grid_view*/,
                        const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL
  {
    return boundary_info_.dirichlet(intersection);
  }

private:
  const BoundaryInfoType& boundary_info_;
}; // class DirichletIntersections

template <class GridViewImp>
class NeumannIntersections : public WhichIntersection<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;
  typedef Stuff::GridboundaryInterface<IntersectionType> BoundaryInfoType;

  NeumannIntersections(const BoundaryInfoType& boundary_info)
    : boundary_info_(boundary_info)
  {
  }

  virtual bool apply_on(const GridViewType& /*grid_view*/,
                        const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL
  {
    return boundary_info_.neumann(intersection);
  }

private:
  const BoundaryInfoType& boundary_info_;
}; // class NeumannIntersections

} // namespace ApplyOn

template <class GridViewImp>
class GridWalker
{
  typedef GridWalker<GridViewImp> ThisType;

public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim<0>::Entity EntityType;
  typedef typename GridViewType::Intersection IntersectionType;

protected:
  typedef Stuff::GridboundaryInterface<IntersectionType> BoundaryInfoType;

  class Codim0Object : public Functor::Codim0<GridViewType>
  {
  public:
    ~Codim0Object()
    {
    }
    virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const = 0;
  };

  template <class Codim0FunctorType>
  class Codim0FunctorWrapper : public Codim0Object
  {
  public:
    Codim0FunctorWrapper(Codim0FunctorType& wrapped_functor, const ApplyOn::WhichEntity<GridViewType>* where)
      : wrapped_functor_(wrapped_functor)
      , where_(where)
    {
    }

    virtual ~Codim0FunctorWrapper()
    {
    }

    virtual void prepare() DS_OVERRIDE DS_FINAL
    {
      wrapped_functor_.prepare();
    }

    virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const DS_OVERRIDE DS_FINAL
    {
      return where_->apply_on(grid_view, entity);
    }

    virtual void apply_local(const EntityType& entity) DS_OVERRIDE DS_FINAL
    {
      wrapped_functor_.apply_local(entity);
    }

    virtual void finalize() DS_OVERRIDE DS_FINAL
    {
      wrapped_functor_.finalize();
    }

  private:
    Codim0FunctorType& wrapped_functor_;
    std::unique_ptr<const ApplyOn::WhichEntity<GridViewType>> where_;
  }; // class Codim0FunctorWrapper

  class Codim1Object : public Functor::Codim1<GridViewType>
  {
  public:
    ~Codim1Object()
    {
    }
    virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const = 0;
  };

  template <class Codim1FunctorType>
  class Codim1FunctorWrapper : public Codim1Object
  {
  public:
    Codim1FunctorWrapper(Codim1FunctorType& wrapped_functor, const ApplyOn::WhichIntersection<GridViewType>* where)
      : wrapped_functor_(wrapped_functor)
      , where_(where)
    {
    }

    virtual void prepare() DS_OVERRIDE DS_FINAL
    {
      wrapped_functor_.prepare();
    }

    virtual bool apply_on(const GridViewType& grid_view,
                          const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL
    {
      return where_->apply_on(grid_view, intersection);
    }

    virtual void apply_local(const IntersectionType& intersection) DS_OVERRIDE DS_FINAL
    {
      wrapped_functor_.apply_local(intersection);
    }

    virtual void finalize() DS_OVERRIDE DS_FINAL
    {
      wrapped_functor_.finalize();
    }

  private:
    Codim1FunctorType& wrapped_functor_;
    std::unique_ptr<const ApplyOn::WhichIntersection<GridViewType>> where_;
  }; // class Codim1FunctorWrapper

public:
  GridWalker(const GridViewType& grid_view)
    : grid_view_(grid_view)
  {
  }

  const GridViewType& grid_view() const
  {
    return grid_view_;
  }

  void add(Functor::Codim0<GridViewType>& functor,
           const ApplyOn::WhichEntity<GridViewType>* where = new ApplyOn::AllEntities<GridViewType>())
  {
    codim0_functors_.emplace_back(new Codim0FunctorWrapper<Functor::Codim0<GridViewType>>(functor, where));
  }

  void add(Functor::Codim1<GridViewType>& functor,
           const ApplyOn::WhichIntersection<GridViewType>* where = new ApplyOn::AllIntersections<GridViewType>())
  {
    codim1_functors_.emplace_back(new Codim1FunctorWrapper<Functor::Codim1<GridViewType>>(functor, where));
  }

  void walk(const bool clear_stack = true)
  {
    // prepare functors
    for (auto& functor : codim0_functors_)
      functor->prepare();
    for (auto& functor : codim1_functors_)
      functor->prepare();

    // only do something, if we have to
    if ((codim0_functors_.size() + codim1_functors_.size()) > 0) {
      // walk the grid
      const auto entity_it_end = grid_view_.template end<0>();
      for (auto entity_it = grid_view_.template begin<0>(); entity_it != entity_it_end; ++entity_it) {
        const EntityType& entity = *entity_it;

        // apply codim0 functors
        for (auto& functor : codim0_functors_)
          if (functor->apply_on(grid_view_, entity))
            functor->apply_local(entity);

        // only walk the intersections, if there are codim1 functors present
        if (codim1_functors_.size() > 0) {
          // walk the intersections
          const auto intersection_it_end = grid_view_.iend(entity);
          for (auto intersection_it = grid_view_.ibegin(entity); intersection_it != intersection_it_end;
               ++intersection_it) {
            const auto& intersection = *intersection_it;

            // apply codim1 functors
            for (auto& functor : codim1_functors_)
              if (functor->apply_on(grid_view_, intersection))
                functor->apply_local(intersection);

          } // walk the intersections
        } // only walk the intersections, if there are codim1 functors present
      } // walk the grid
    } // only do something, if we have to

    // finalize functors
    for (auto& functor : codim0_functors_)
      functor->finalize();
    for (auto& functor : codim1_functors_)
      functor->finalize();

    // clear the stack of functors
    if (clear_stack)
      clear();
  } // ... walk(...)

  void clear()
  {
    codim0_functors_ = std::vector<std::unique_ptr<Codim0Object>>();
    codim1_functors_ = std::vector<std::unique_ptr<Codim1Object>>();
  } // ... clear()

protected:
  const GridViewType& grid_view_;
  std::vector<std::unique_ptr<Codim0Object>> codim0_functors_;
  std::vector<std::unique_ptr<Codim1Object>> codim1_functors_;
}; // class GridWalker

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_ASSEMBLER_GRIDWALKER_HH
<commit_msg>[assembler.gridwalker] * call codim 1 functors with inside and outside entity * adden combinde codim 0 and 1 functor<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_ASSEMBLER_GRIDWALKER_HH
#define DUNE_GDT_ASSEMBLER_GRIDWALKER_HH

#include <vector>
#include <memory>
#include <type_traits>

#include <dune/stuff/grid/boundaryinfo.hh>

namespace Dune {
namespace GDT {
namespace Functor {

template <class GridViewImp>
class Codim0
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim<0>::Entity EntityType;

  virtual ~Codim0()
  {
  }

  virtual void prepare()
  {
  }

  virtual void apply_local(const EntityType& entity) = 0;

  virtual void finalize()
  {
  }
}; // class Codim0

template <class GridViewImp>
class Codim1
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim<0>::Entity EntityType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual ~Codim1()
  {
  }

  virtual void prepare()
  {
  }

  virtual void apply_local(const IntersectionType& /*intersection*/, const EntityType& /*inside_entity*/,
                           const EntityType& /*outside_entity*/) = 0;

  virtual void finalize()
  {
  }
}; // class Codim1

template <class GridViewImp>
class Codim0And1
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim<0>::Entity EntityType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual ~Codim0And1()
  {
  }

  virtual void prepare()
  {
  }

  virtual void apply_local(const EntityType& entity) = 0;

  virtual void apply_local(const IntersectionType& /*intersection*/, const EntityType& /*inside_entity*/,
                           const EntityType& /*outside_entity*/) = 0;

  virtual void finalize()
  {
  }
}; // class Codim0And1

} // namespace Functor
namespace ApplyOn {

/**
 *  \brief Interface for functors to tell on which entity to apply.
 *
 *  The derived class has to provide a method with the following signature:
 *  \code
virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const
{
  ...
}
\endcode
 */
template <class GridViewImp>
class WhichEntity
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim<0>::Entity EntityType;

  virtual ~WhichEntity()
  {
  }

  virtual bool apply_on(const GridViewType& /*grid_view*/, const EntityType& /*entity*/) const = 0;
}; // class WhichEntity

/**
 *  \brief Selects all entities.
 */
template <class GridViewImp>
class AllEntities : public WhichEntity<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim<0>::Entity EntityType;

  virtual bool apply_on(const GridViewType& /*grid_view*/, const EntityType& /*entity*/) const DS_OVERRIDE DS_FINAL
  {
    return true;
  }
}; // class AllEntities

/**
 *  \brief Selects entities which have a boundary intersection.
 */
template <class GridViewImp>
class BoundaryEntities : public WhichEntity<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim<0>::Entity EntityType;

  virtual bool apply_on(const GridViewType& /*grid_view*/, const EntityType& entity) const DS_OVERRIDE DS_FINAL
  {
    return entity.hasBoundaryIntersections();
  }
}; // class BoundaryEntities

/**
 *  \brief Interface for functors to tell on which intersection to apply.
 *
 *  The derived class has to provide a method with the following signature:
 *  \code
virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const
{
  ...
}
\endcode
 */
template <class GridViewImp>
class WhichIntersection
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual ~WhichIntersection<GridViewImp>()
  {
  }

  virtual bool apply_on(const GridViewType& /*grid_view*/, const IntersectionType& /*intersection*/) const = 0;
}; // class WhichIntersection< GridViewImp >

/**
 *  \brief Selects all intersections.
 */
template <class GridViewImp>
class AllIntersections : public WhichIntersection<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual bool apply_on(const GridViewType& /*grid_view*/,
                        const IntersectionType& /*intersection*/) const DS_OVERRIDE DS_FINAL
  {
    return true;
  }
}; // class AllIntersections

/**
 *  \brief Selects each inner intersection.
 *
 *  To decide if this in an inner intersection,
\code
intersection.neighbor() && !intersection.boundary()
\endcode
 *  is used.
 */
template <class GridViewImp>
class InnerIntersections : public WhichIntersection<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual bool apply_on(const GridViewType& /*grid_view*/,
                        const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL
  {
    return intersection.neighbor() && !intersection.boundary();
  }
}; // class InnerIntersections

/**
 *  \brief Selects each inner intersection only once.
 *
 *  To decide if this in an inner intersection,
\code
intersection.neighbor() && !intersection.boundary()
\endcode
 *  is used, and true is returned, if the index of the inside() entity is smaller than the index of the outside()
 *  entity.
 */
template <class GridViewImp>
class InnerIntersectionsPrimally : public WhichIntersection<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL
  {
    if (intersection.neighbor() && !intersection.boundary()) {
      const auto insideEntityPtr    = intersection.inside();
      const auto& insideEntity      = *insideEntityPtr;
      const auto outsideNeighborPtr = intersection.outside();
      const auto& outsideNeighbor = *outsideNeighborPtr;
      return grid_view.indexSet().index(insideEntity) < grid_view.indexSet().index(outsideNeighbor);
    } else
      return false;
  }
}; // class InnerIntersections

template <class GridViewImp>
class BoundaryIntersections : public WhichIntersection<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  virtual bool apply_on(const GridViewType& /*grid_view*/,
                        const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL
  {
    return intersection.boundary();
  }
}; // class BoundaryIntersections

template <class GridViewImp>
class DirichletIntersections : public WhichIntersection<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;
  typedef Stuff::GridboundaryInterface<IntersectionType> BoundaryInfoType;

  DirichletIntersections(const BoundaryInfoType& boundary_info)
    : boundary_info_(boundary_info)
  {
  }

  virtual bool apply_on(const GridViewType& /*grid_view*/,
                        const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL
  {
    return boundary_info_.dirichlet(intersection);
  }

private:
  const BoundaryInfoType& boundary_info_;
}; // class DirichletIntersections

template <class GridViewImp>
class NeumannIntersections : public WhichIntersection<GridViewImp>
{
public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;
  typedef Stuff::GridboundaryInterface<IntersectionType> BoundaryInfoType;

  NeumannIntersections(const BoundaryInfoType& boundary_info)
    : boundary_info_(boundary_info)
  {
  }

  virtual bool apply_on(const GridViewType& /*grid_view*/,
                        const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL
  {
    return boundary_info_.neumann(intersection);
  }

private:
  const BoundaryInfoType& boundary_info_;
}; // class NeumannIntersections

} // namespace ApplyOn

template <class GridViewImp>
class GridWalker
{
  typedef GridWalker<GridViewImp> ThisType;

public:
  typedef GridViewImp GridViewType;
  typedef typename GridViewType::template Codim<0>::Entity EntityType;
  typedef typename GridViewType::Intersection IntersectionType;

protected:
  typedef Stuff::GridboundaryInterface<IntersectionType> BoundaryInfoType;

  class Codim0Object : public Functor::Codim0<GridViewType>
  {
  public:
    ~Codim0Object()
    {
    }
    virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const = 0;
  };

  template <class Codim0FunctorType>
  class Codim0FunctorWrapper : public Codim0Object
  {
  public:
    Codim0FunctorWrapper(Codim0FunctorType& wrapped_functor, const ApplyOn::WhichEntity<GridViewType>* where)
      : wrapped_functor_(wrapped_functor)
      , where_(where)
    {
    }

    virtual ~Codim0FunctorWrapper()
    {
    }

    virtual void prepare() DS_OVERRIDE DS_FINAL
    {
      wrapped_functor_.prepare();
    }

    virtual bool apply_on(const GridViewType& grid_view, const EntityType& entity) const DS_OVERRIDE DS_FINAL
    {
      return where_->apply_on(grid_view, entity);
    }

    virtual void apply_local(const EntityType& entity) DS_OVERRIDE DS_FINAL
    {
      wrapped_functor_.apply_local(entity);
    }

    virtual void finalize() DS_OVERRIDE DS_FINAL
    {
      wrapped_functor_.finalize();
    }

  private:
    Codim0FunctorType& wrapped_functor_;
    std::unique_ptr<const ApplyOn::WhichEntity<GridViewType>> where_;
  }; // class Codim0FunctorWrapper

  class Codim1Object : public Functor::Codim1<GridViewType>
  {
  public:
    ~Codim1Object()
    {
    }
    virtual bool apply_on(const GridViewType& grid_view, const IntersectionType& intersection) const = 0;
  };

  template <class Codim1FunctorType>
  class Codim1FunctorWrapper : public Codim1Object
  {
  public:
    Codim1FunctorWrapper(Codim1FunctorType& wrapped_functor, const ApplyOn::WhichIntersection<GridViewType>* where)
      : wrapped_functor_(wrapped_functor)
      , where_(where)
    {
    }

    virtual void prepare() DS_OVERRIDE DS_FINAL
    {
      wrapped_functor_.prepare();
    }

    virtual bool apply_on(const GridViewType& grid_view,
                          const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL
    {
      return where_->apply_on(grid_view, intersection);
    }

    virtual void apply_local(const IntersectionType& intersection, const EntityType& inside_entity,
                             const EntityType& outside_entity) DS_OVERRIDE DS_FINAL
    {
      wrapped_functor_.apply_local(intersection, inside_entity, outside_entity);
    }

    virtual void finalize() DS_OVERRIDE DS_FINAL
    {
      wrapped_functor_.finalize();
    }

  private:
    Codim1FunctorType& wrapped_functor_;
    std::unique_ptr<const ApplyOn::WhichIntersection<GridViewType>> where_;
  }; // class Codim1FunctorWrapper

public:
  GridWalker(const GridViewType& grid_view)
    : grid_view_(grid_view)
  {
  }

  const GridViewType& grid_view() const
  {
    return grid_view_;
  }

  void add(Functor::Codim0<GridViewType>& functor,
           const ApplyOn::WhichEntity<GridViewType>* where = new ApplyOn::AllEntities<GridViewType>())
  {
    codim0_functors_.emplace_back(new Codim0FunctorWrapper<Functor::Codim0<GridViewType>>(functor, where));
  }

  void add(Functor::Codim1<GridViewType>& functor,
           const ApplyOn::WhichIntersection<GridViewType>* where = new ApplyOn::AllIntersections<GridViewType>())
  {
    codim1_functors_.emplace_back(new Codim1FunctorWrapper<Functor::Codim1<GridViewType>>(functor, where));
  }

  void add(Functor::Codim0And1<GridViewType>& functor,
           const ApplyOn::WhichEntity<GridViewType>* which_entities = new ApplyOn::AllEntities<GridViewType>(),
           const ApplyOn::WhichIntersection<GridViewType>* which_intersections =
               new ApplyOn::AllIntersections<GridViewType>())
  {
    codim0_functors_.emplace_back(new Codim0FunctorWrapper<Functor::Codim0And1<GridViewType>>(functor, which_entities));
    codim1_functors_.emplace_back(
        new Codim1FunctorWrapper<Functor::Codim0And1<GridViewType>>(functor, which_intersections));
  }

  void add(Functor::Codim0And1<GridViewType>& functor,
           const ApplyOn::WhichIntersection<GridViewType>* which_intersections,
           const ApplyOn::WhichEntity<GridViewType>* which_entities = new ApplyOn::AllEntities<GridViewType>())
  {
    codim0_functors_.emplace_back(new Codim0FunctorWrapper<Functor::Codim0And1<GridViewType>>(functor, which_entities));
    codim1_functors_.emplace_back(
        new Codim1FunctorWrapper<Functor::Codim0And1<GridViewType>>(functor, which_intersections));
  }

  void walk(const bool clear_stack = true)
  {
    // prepare functors
    for (auto& functor : codim0_functors_)
      functor->prepare();
    for (auto& functor : codim1_functors_)
      functor->prepare();

    // only do something, if we have to
    if ((codim0_functors_.size() + codim1_functors_.size()) > 0) {
      // walk the grid
      const auto entity_it_end = grid_view_.template end<0>();
      for (auto entity_it = grid_view_.template begin<0>(); entity_it != entity_it_end; ++entity_it) {
        const EntityType& entity = *entity_it;

        // apply codim0 functors
        for (auto& functor : codim0_functors_)
          if (functor->apply_on(grid_view_, entity))
            functor->apply_local(entity);

        // only walk the intersections, if there are codim1 functors present
        if (codim1_functors_.size() > 0) {
          // walk the intersections
          const auto intersection_it_end = grid_view_.iend(entity);
          for (auto intersection_it = grid_view_.ibegin(entity); intersection_it != intersection_it_end;
               ++intersection_it) {
            const auto& intersection = *intersection_it;

            // apply codim1 functors
            if (intersection.neighbor()) {
              const auto neighbor_ptr = intersection.outside();
              const auto& neighbor = *neighbor_ptr;
              for (auto& functor : codim1_functors_)
                if (functor->apply_on(grid_view_, intersection))
                  functor->apply_local(intersection, entity, neighbor);
            } else {
              for (auto& functor : codim1_functors_)
                if (functor->apply_on(grid_view_, intersection))
                  functor->apply_local(intersection, entity, entity);
            }

          } // walk the intersections
        } // only walk the intersections, if there are codim1 functors present
      } // walk the grid
    } // only do something, if we have to

    // finalize functors
    for (auto& functor : codim0_functors_)
      functor->finalize();
    for (auto& functor : codim1_functors_)
      functor->finalize();

    // clear the stack of functors
    if (clear_stack)
      clear();
  } // ... walk(...)

  void clear()
  {
    codim0_functors_ = std::vector<std::unique_ptr<Codim0Object>>();
    codim1_functors_ = std::vector<std::unique_ptr<Codim1Object>>();
  } // ... clear()

protected:
  const GridViewType& grid_view_;
  std::vector<std::unique_ptr<Codim0Object>> codim0_functors_;
  std::vector<std::unique_ptr<Codim1Object>> codim1_functors_;
}; // class GridWalker

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_ASSEMBLER_GRIDWALKER_HH
<|endoftext|>


<commit_before><commit_msg>DNS code: fix one more place was using 'stringexception' to use (SystemErrorException (... DNS_error_category); and fixed DNS_error_category message report to look a little better on widnows<commit_after><|endoftext|>


<commit_before><commit_msg>[GL3+] Add GLSL 4.4 shader profile for OpenGL 4.4<commit_after><|endoftext|>


<commit_before><commit_msg>GLES 2 - removed some broken code.<commit_after><|endoftext|>


<commit_before>/**
 * @file   spline.cpp
 * @brief  definition of spline functions
 * @author Peter & Nigel, Design Software, 42 Gubberley St, Kenmore, 4069, Australia.
 */

#undef k
#undef ss

/************************************************/
/*  adapted from                                */
/*  CMATH.  Copyright (c) 1989 Design Software  */
/*                                              */
/************************************************/

/**

   Evaluate the coefficients b[i], c[i], d[i], i = 0, 1, .. n-1 for
   a cubic interpolating spline

   S(xx) = Y[i] + b[i] * w + c[i] * w**2 + d[i] * w**3
   where w = xx - x[i]
   and   x[i] <= xx <= x[i+1]

   The n supplied data points are x[i], y[i], i = 0 ... n-1.

   @param[in] n The number of data points or knots (n >= 2)
   @param[in] end1 0: default condition 1: specify the slopes at x[0]
   @param[in] end2 0: default condition 1: specify the slopes at x[n-1]
   @param[in] slope1 slope at x[0]
   @param[in] slope2 slope at x[n-1]
   @param[in] x[] the abscissas of the knots in strictly increasing order
   @param[in] y[] the ordinates of the knots
   @param[out] b[] array of spline coefficients
   @param[out] c[] array of spline coefficients
   @param[out] d[] array of spline coefficients

   @retval 0 normal return
   @retval 1 less than two data points; cannot interpolate
   @retval 2 x[] are not in ascending order

   Notes
   -----
     - The accompanying function seval() may be used to evaluate the
       spline while deriv will provide the first derivative.
     - Using p to denote differentiation
       y[i] = S(X[i])
       b[i] = Sp(X[i])
       c[i] = Spp(X[i])/2
       d[i] = Sppp(X[i])/6  ( Derivative from the right )
     - Since the zero elements of the arrays ARE NOW used here,
       all arrays to be passed from the main program should be
       dimensioned at least [n].  These routines will use elements
       [0 .. n-1].
     - Adapted from the text
       Forsythe, G.E., Malcolm, M.A. and Moler, C.B. (1977)
       "Computer Methods for Mathematical Computations"
       Prentice Hall
     - Note that although there are only n-1 polynomial segments,
       n elements are requird in b, c, d.  The elements b[n-1],
       c[n-1] and d[n-1] are set to continue the last segment
       past x[n-1].
*/
int spline (int n, int end1, int end2,
            double slope1, double slope2,
            double x[], double y[],
            double b[], double c[], double d[])

{  /* begin procedure spline() */

int    nm1, ib, i;
double t;
int    ascend;

nm1    = n - 1;

if (n < 2)
  {  /* no possible interpolation */
  goto LeaveSpline;
  }

ascend = 1;
for (i = 1; i < n; ++i) if (x[i] <= x[i-1]) ascend = 0;
if (!ascend)
   {
   goto LeaveSpline;
   }

if (n >= 3)
   {    /* ---- At least quadratic ---- */

   /* ---- Set up the symmetric tri-diagonal system
           b = diagonal
           d = offdiagonal
           c = right-hand-side  */
   d[0] = x[1] - x[0];
   c[1] = (y[1] - y[0]) / d[0];
   for (i = 1; i < nm1; ++i)
      {
      d[i]   = x[i+1] - x[i];
      b[i]   = 2.0 * (d[i-1] + d[i]);
      c[i+1] = (y[i+1] - y[i]) / d[i];
      c[i]   = c[i+1] - c[i];
      }

   /* ---- Default End conditions
           Third derivatives at x[0] and x[n-1] obtained
           from divided differences  */
   b[0]   = -d[0];
   b[nm1] = -d[n-2];
   c[0]   = 0.0;
   c[nm1] = 0.0;
   if (n != 3)
      {
      c[0]   = c[2] / (x[3] - x[1]) - c[1] / (x[2] - x[0]);
      c[nm1] = c[n-2] / (x[nm1] - x[n-3]) - c[n-3] / (x[n-2] - x[n-4]);
      c[0]   = c[0] * d[0] * d[0] / (x[3] - x[0]);
      c[nm1] = -c[nm1] * d[n-2] * d[n-2] / (x[nm1] - x[n-4]);
      }

   /* Alternative end conditions -- known slopes */
   if (end1 == 1)
      {
      b[0] = 2.0 * (x[1] - x[0]);
      c[0] = (y[1] - y[0]) / (x[1] - x[0]) - slope1;
      }
   if (end2 == 1)
      {
      b[nm1] = 2.0 * (x[nm1] - x[n-2]);
      c[nm1] = slope2 - (y[nm1] - y[n-2]) / (x[nm1] - x[n-2]);
      }

   /* Forward elimination */
   for (i = 1; i < n; ++i)
     {
     t    = d[i-1] / b[i-1];
     b[i] = b[i] - t * d[i-1];
     c[i] = c[i] - t * c[i-1];
     }

   /* Back substitution */
   c[nm1] = c[nm1] / b[nm1];
   for (ib = 0; ib < nm1; ++ib)
      {
      i    = n - ib - 2;
      c[i] = (c[i] - d[i] * c[i+1]) / b[i];
      }

   /* c[i] is now the sigma[i] of the text */

   /* Compute the polynomial coefficients */
   b[nm1] = (y[nm1] - y[n-2]) / d[n-2] + d[n-2] * (c[n-2] + 2.0 * c[nm1]);
   for (i = 0; i < nm1; ++i)
      {
      b[i] = (y[i+1] - y[i]) / d[i] - d[i] * (c[i+1] + 2.0 * c[i]);
      d[i] = (c[i+1] - c[i]) / d[i];
      c[i] = 3.0 * c[i];
      }
   c[nm1] = 3.0 * c[nm1];
   d[nm1] = d[n-2];

   }  /* at least quadratic */

else  /* if n >= 3 */
   {  /* linear segment only  */
   b[0] = (y[1] - y[0]) / (x[1] - x[0]);
   c[0] = 0.0;
   d[0] = 0.0;
   b[1] = b[0];
   c[1] = 0.0;
   d[1] = 0.0;
   }

LeaveSpline:
return 0;
}  /* end of spline() */

/**
  Evaluate the cubic spline function

  S(xx) = y[i] + b[i] * w + c[i] * w**2 + d[i] * w**3
  where w = u - x[i]
  and   x[i] <= u <= x[i+1]
  Note that Horner's rule is used.
  If u < x[0]   then i = 0 is used.
  If u > x[n-1] then i = n-1 is used.

  @param[in] n The number of data points or knots (n >= 2)
  @param[in] u the abscissa at which the spline is to be evaluated
  @param[in] x[] the abscissas of the knots in strictly increasing order
  @param[in] y[] the ordinates of the knots
  @param[in] b array of spline coefficients computed by spline().
  @param[in] c array of spline coefficients computed by spline().
  @param[in] d array of spline coefficients computed by spline().

  @return the value of the spline function at u

  Notes
    - If u is not in the same interval as the previous call then a
      binary search is performed to determine the proper interval.

*/

double seval (int n, double u,
              double x[], double y[],
              double b[], double c[], double d[])

{  /* begin function seval() */

    int    i, j, k;
    double w;

    if (u <= x[0]) {
        i = 0;
    } else {
        if (u >= x[n-1]) {
            i = n-1;
        } else {
            i = 0;
            j = n;
            do
            {
                k = (i + j) / 2;         /* split the domain to search */
                if (u < x[k])  j = k;    /* move the upper bound */
                if (u >= x[k]) i = k;    /* move the lower bound */
            }                        /* there are no more segments to search */
            while (j > i+1);
        }
    }

    /* ---- Evaluate the spline ---- */
    w = u - x[i];
    w = y[i] + w * (b[i] + w * (c[i] + w * d[i]));
    return (w);
}

/**
   Evaluate the derivative of the cubic spline function

   S(x) = B[i] + 2.0 * C[i] * w + 3.0 * D[i] * w**2
   where w = u - X[i]
   and   X[i] <= u <= X[i+1]
   Note that Horner's rule is used.
   If U < X[0] then i = 0 is used.
   If U > X[n-1] then i = n-1 is used.

   @param[in] n the number of data points or knots (n >= 2)
   @param[in] u the abscissa at which the derivative is to be evaluated
   @param[in] x the abscissas of the knots in strictly increasing order
   @param[in] b array of spline coefficients computed by spline()
   @param[in] c array of spline coefficients computed by spline()
   @param[in] d array of spline coefficients computed by spline()

   @return the value of the derivative of the spline function at u

   Notes
     - If u is not in the same interval as the previous call then a
       binary search is performed to determine the proper interval.

*/

double deriv (int n, double u,
              double x[],
              double b[], double c[], double d[])
{  /* begin function deriv() */

int    i, j, k;
double w;

if (i >= n-1) i = 0;
if (i < 0) i = 0;

if ((x[i] > u) || (x[i+1] < u))
  {  /* ---- perform a binary search ---- */
  i = 0;
  j = n;
  do
    {
    k = (i + j) / 2;          /* split the domain to search */
    if (u < x[k])  j = k;     /* move the upper bound */
    if (u >= x[k]) i = k;     /* move the lower bound */
    }                         /* there are no more segments to search */
  while (j > i+1);
  }

/* ---- Evaluate the derivative ---- */
w = u - x[i];
w = b[i] + w * (2.0 * c[i] + w * 3.0 * d[i]);
return (w);

} /* end of deriv() */

/**
  Integrate the cubic spline function

  S(xx) = y[i] + b[i] * w + c[i] * w**2 + d[i] * w**3
  where w = u - x[i]
  and   x[i] <= u <= x[i+1]

  The integral is zero at u = x[0].

  If u < x[0]   then i = 0 segment is extrapolated.
  If u > x[n-1] then i = n-1 segment is extrapolated.

  @param[in] n the number of data points or knots (n >= 2)
  @param[in] u the abscissa at which the spline is to be evaluated
  @param[in] x[] the abscissas of the knots in strictly increasing order
  @param[in] y[] the ordinates of the knots
  @param[in] b array of spline coefficients computed by spline().
  @param[in] c array of spline coefficients computed by spline().
  @param[in] d array of spline coefficients computed by spline().

  @return the value of the spline function at u

  Notes
    - If u is not in the same interval as the previous call then a
      binary search is performed to determine the proper interval.

*/

double sinteg (int n, double u,
              double x[], double y[],
              double b[], double c[], double d[])
{  /* begin function sinteg() */

int    i, j, k;
double sum, dx;

if (i >= n-1) i = 0;
if (i < 0)  i = 0;

if ((x[i] > u) || (x[i+1] < u))
  {  /* ---- perform a binary search ---- */
  i = 0;
  j = n;
  do
    {
    k = (i + j) / 2;         /* split the domain to search */
    if (u < x[k])  j = k;    /* move the upper bound */
    if (u >= x[k]) i = k;    /* move the lower bound */
    }                        /* there are no more segments to search */
  while (j > i+1);
  }

sum = 0.0;
/* ---- Evaluate the integral for segments x < u ---- */
for (j = 0; j < i; ++j)
   {
   dx = x[j+1] - x[j];
   sum += dx *
          (y[j] + dx *
          (0.5 * b[j] + dx *
          (c[j] / 3.0 + dx * 0.25 * d[j])));
   }

/* ---- Evaluate the integral fot this segment ---- */
dx = u - x[i];
sum += dx *
       (y[i] + dx *
       (0.5 * b[i] + dx *
       (c[i] / 3.0 + dx * 0.25 * d[i])));

return (sum);
}
<commit_msg>fixes #102<commit_after>/**
 * @file   spline.cpp
 * @brief  definition of spline functions
 * @author Peter & Nigel, Design Software, 42 Gubberley St, Kenmore, 4069, Australia.
 */

#undef k
#undef ss

/************************************************/
/*  adapted from                                */
/*  CMATH.  Copyright (c) 1989 Design Software  */
/*                                              */
/************************************************/

/**

   Evaluate the coefficients b[i], c[i], d[i], i = 0, 1, .. n-1 for
   a cubic interpolating spline

   S(xx) = Y[i] + b[i] * w + c[i] * w**2 + d[i] * w**3
   where w = xx - x[i]
   and   x[i] <= xx <= x[i+1]

   The n supplied data points are x[i], y[i], i = 0 ... n-1.

   @param[in] n The number of data points or knots (n >= 2)
   @param[in] end1 0: default condition 1: specify the slopes at x[0]
   @param[in] end2 0: default condition 1: specify the slopes at x[n-1]
   @param[in] slope1 slope at x[0]
   @param[in] slope2 slope at x[n-1]
   @param[in] x[] the abscissas of the knots in strictly increasing order
   @param[in] y[] the ordinates of the knots
   @param[out] b[] array of spline coefficients
   @param[out] c[] array of spline coefficients
   @param[out] d[] array of spline coefficients

   @retval 0 normal return
   @retval 1 less than two data points; cannot interpolate
   @retval 2 x[] are not in ascending order

   Notes
   -----
     - The accompanying function seval() may be used to evaluate the
       spline while deriv will provide the first derivative.
     - Using p to denote differentiation
       y[i] = S(X[i])
       b[i] = Sp(X[i])
       c[i] = Spp(X[i])/2
       d[i] = Sppp(X[i])/6  ( Derivative from the right )
     - Since the zero elements of the arrays ARE NOW used here,
       all arrays to be passed from the main program should be
       dimensioned at least [n].  These routines will use elements
       [0 .. n-1].
     - Adapted from the text
       Forsythe, G.E., Malcolm, M.A. and Moler, C.B. (1977)
       "Computer Methods for Mathematical Computations"
       Prentice Hall
     - Note that although there are only n-1 polynomial segments,
       n elements are requird in b, c, d.  The elements b[n-1],
       c[n-1] and d[n-1] are set to continue the last segment
       past x[n-1].
*/
int spline (int n, int end1, int end2,
            double slope1, double slope2,
            double x[], double y[],
            double b[], double c[], double d[])

{  /* begin procedure spline() */

int    nm1, ib, i;
double t;
int    ascend;

nm1    = n - 1;

if (n < 2)
  {  /* no possible interpolation */
  goto LeaveSpline;
  }

ascend = 1;
for (i = 1; i < n; ++i) if (x[i] <= x[i-1]) ascend = 0;
if (!ascend)
   {
   goto LeaveSpline;
   }

if (n >= 3)
   {    /* ---- At least quadratic ---- */

   /* ---- Set up the symmetric tri-diagonal system
           b = diagonal
           d = offdiagonal
           c = right-hand-side  */
   d[0] = x[1] - x[0];
   c[1] = (y[1] - y[0]) / d[0];
   for (i = 1; i < nm1; ++i)
      {
      d[i]   = x[i+1] - x[i];
      b[i]   = 2.0 * (d[i-1] + d[i]);
      c[i+1] = (y[i+1] - y[i]) / d[i];
      c[i]   = c[i+1] - c[i];
      }

   /* ---- Default End conditions
           Third derivatives at x[0] and x[n-1] obtained
           from divided differences  */
   b[0]   = -d[0];
   b[nm1] = -d[n-2];
   c[0]   = 0.0;
   c[nm1] = 0.0;
   if (n != 3)
      {
      c[0]   = c[2] / (x[3] - x[1]) - c[1] / (x[2] - x[0]);
      c[nm1] = c[n-2] / (x[nm1] - x[n-3]) - c[n-3] / (x[n-2] - x[n-4]);
      c[0]   = c[0] * d[0] * d[0] / (x[3] - x[0]);
      c[nm1] = -c[nm1] * d[n-2] * d[n-2] / (x[nm1] - x[n-4]);
      }

   /* Alternative end conditions -- known slopes */
   if (end1 == 1)
      {
      b[0] = 2.0 * (x[1] - x[0]);
      c[0] = (y[1] - y[0]) / (x[1] - x[0]) - slope1;
      }
   if (end2 == 1)
      {
      b[nm1] = 2.0 * (x[nm1] - x[n-2]);
      c[nm1] = slope2 - (y[nm1] - y[n-2]) / (x[nm1] - x[n-2]);
      }

   /* Forward elimination */
   for (i = 1; i < n; ++i)
     {
     t    = d[i-1] / b[i-1];
     b[i] = b[i] - t * d[i-1];
     c[i] = c[i] - t * c[i-1];
     }

   /* Back substitution */
   c[nm1] = c[nm1] / b[nm1];
   for (ib = 0; ib < nm1; ++ib)
      {
      i    = n - ib - 2;
      c[i] = (c[i] - d[i] * c[i+1]) / b[i];
      }

   /* c[i] is now the sigma[i] of the text */

   /* Compute the polynomial coefficients */
   b[nm1] = (y[nm1] - y[n-2]) / d[n-2] + d[n-2] * (c[n-2] + 2.0 * c[nm1]);
   for (i = 0; i < nm1; ++i)
      {
      b[i] = (y[i+1] - y[i]) / d[i] - d[i] * (c[i+1] + 2.0 * c[i]);
      d[i] = (c[i+1] - c[i]) / d[i];
      c[i] = 3.0 * c[i];
      }
   c[nm1] = 3.0 * c[nm1];
   d[nm1] = d[n-2];

   }  /* at least quadratic */

else  /* if n >= 3 */
   {  /* linear segment only  */
   b[0] = (y[1] - y[0]) / (x[1] - x[0]);
   c[0] = 0.0;
   d[0] = 0.0;
   b[1] = b[0];
   c[1] = 0.0;
   d[1] = 0.0;
   }

LeaveSpline:
return 0;
}  /* end of spline() */

/**
  Evaluate the cubic spline function

  S(xx) = y[i] + b[i] * w + c[i] * w**2 + d[i] * w**3
  where w = u - x[i]
  and   x[i] <= u <= x[i+1]
  Note that Horner's rule is used.
  If u < x[0]   then i = 0 is used.
  If u > x[n-1] then i = n-1 is used.

  @param[in] n The number of data points or knots (n >= 2)
  @param[in] u the abscissa at which the spline is to be evaluated
  @param[in] x[] the abscissas of the knots in strictly increasing order
  @param[in] y[] the ordinates of the knots
  @param[in] b array of spline coefficients computed by spline().
  @param[in] c array of spline coefficients computed by spline().
  @param[in] d array of spline coefficients computed by spline().

  @return the value of the spline function at u

  Notes
    - If u is not in the same interval as the previous call then a
      binary search is performed to determine the proper interval.

*/

double seval (int n, double u,
              double x[], double y[],
              double b[], double c[], double d[])

{  /* begin function seval() */

    int    i, j, k;
    double w;

    if (u <= x[0]) {
        i = 0;
    } else {
        if (u >= x[n-1]) {
            i = n-1;
        } else {
            i = 0;
            j = n;
            do
            {
                k = (i + j) / 2;         /* split the domain to search */
                if (u < x[k])  j = k;    /* move the upper bound */
                if (u >= x[k]) i = k;    /* move the lower bound */
            }                        /* there are no more segments to search */
            while (j > i+1);
        }
    }

    /* ---- Evaluate the spline ---- */
    w = u - x[i];
    w = y[i] + w * (b[i] + w * (c[i] + w * d[i]));
    return (w);
}

/**
  Integrate the cubic spline function

  S(xx) = y[i] + b[i] * w + c[i] * w**2 + d[i] * w**3
  where w = u - x[i]
  and   x[i] <= u <= x[i+1]

  The integral is zero at u = x[0].

  If u < x[0]   then i = 0 segment is extrapolated.
  If u > x[n-1] then i = n-1 segment is extrapolated.

  @param[in] n the number of data points or knots (n >= 2)
  @param[in] u the abscissa at which the spline is to be evaluated
  @param[in] x[] the abscissas of the knots in strictly increasing order
  @param[in] y[] the ordinates of the knots
  @param[in] b array of spline coefficients computed by spline().
  @param[in] c array of spline coefficients computed by spline().
  @param[in] d array of spline coefficients computed by spline().

  @return the value of the spline function at u

  Notes
    - If u is not in the same interval as the previous call then a
      binary search is performed to determine the proper interval.

*/

double sinteg (int n, double u,
              double x[], double y[],
              double b[], double c[], double d[])
{  /* begin function sinteg() */

int    i, j, k;
double sum, dx;

i = 0;

if ((x[i] > u) || (x[i+1] < u))
  {  /* ---- perform a binary search ---- */
  j = n;
  do
    {
    k = (i + j) / 2;         /* split the domain to search */
    if (u < x[k])  j = k;    /* move the upper bound */
    if (u >= x[k]) i = k;    /* move the lower bound */
    }                        /* there are no more segments to search */
  while (j > i+1);
  }

sum = 0.0;
/* ---- Evaluate the integral for segments x < u ---- */
for (j = 0; j < i; ++j)
   {
   dx = x[j+1] - x[j];
   sum += dx *
          (y[j] + dx *
          (0.5 * b[j] + dx *
          (c[j] / 3.0 + dx * 0.25 * d[j])));
   }

/* ---- Evaluate the integral fot this segment ---- */
dx = u - x[i];
sum += dx *
       (y[i] + dx *
       (0.5 * b[i] + dx *
       (c[i] / 3.0 + dx * 0.25 * d[i])));

return (sum);
}
<|endoftext|>


<commit_before>/*
 * objtest
 *
 * $Date$
 * $Revision$
 *
 */

// Access the internals of the object module
#include "../src/lib/conf.h"
#include <libtpt/object.h>
#include <iostream>
#include <map>

using TPT::Object;

void test1();

int main(int argc, char* argv[])
{
	try {
		test1();
	} catch(const std::exception& e) {
		std::cout << "Exception " << e.what() << std::endl;
	} catch(...) {
		std::cout << "Unknown exception" << std::endl;
	}

	return 0;
}

void test1()
{
	Object obj(Object::type_hash);
	Object::HashType& hash = obj.hash();
	std::cout << "Allocating new object" << std::endl;

	Object::PtrType temp1(new Object("Test"));
	Object::PtrType temp2(temp1);
	temp1 = new Object("Test");
	temp2 = temp1;
	temp1 = new Object("Test");
	Object::PtrType temp3(temp2);
	temp2 = temp1;
	Object::PtrType pobj(new Object("Test"));
	hash["var"] = pobj;
	std::cout << "Type: " << pobj.get()->gettype() << std::endl;
	std::cout << "Read: " << hash["var"].get()->scalar() << std::endl;
	hash["var"] = new Object("Value");
	std::cout << "Type: " << hash["var"].get()->gettype() << std::endl;
	std::cout << "Read: " << hash["var"].get()->scalar() << std::endl;
	hash["test1"] = new Object(Object::type_array);
	hash["test2"] = new Object(Object::type_hash);
	hash["test3"] = new Object;
}
<commit_msg>cleaned up unused parameters<commit_after>/*
 * objtest
 *
 * $Date$
 * $Revision$
 *
 */

// Access the internals of the object module
#include "../src/lib/conf.h"
#include <libtpt/object.h>
#include <iostream>
#include <map>

using TPT::Object;

void test1();

int main()
{
	try {
		test1();
	} catch(const std::exception& e) {
		std::cout << "Exception " << e.what() << std::endl;
	} catch(...) {
		std::cout << "Unknown exception" << std::endl;
	}

	return 0;
}

void test1()
{
	Object obj(Object::type_hash);
	Object::HashType& hash = obj.hash();
	std::cout << "Allocating new object" << std::endl;

	Object::PtrType temp1(new Object("Test"));
	Object::PtrType temp2(temp1);
	temp1 = new Object("Test");
	temp2 = temp1;
	temp1 = new Object("Test");
	Object::PtrType temp3(temp2);
	temp2 = temp1;
	Object::PtrType pobj(new Object("Test"));
	hash["var"] = pobj;
	std::cout << "Type: " << pobj.get()->gettype() << std::endl;
	std::cout << "Read: " << hash["var"].get()->scalar() << std::endl;
	hash["var"] = new Object("Value");
	std::cout << "Type: " << hash["var"].get()->gettype() << std::endl;
	std::cout << "Read: " << hash["var"].get()->scalar() << std::endl;
	hash["test1"] = new Object(Object::type_array);
	hash["test2"] = new Object(Object::type_hash);
	hash["test3"] = new Object;
}
<|endoftext|>


<commit_before><commit_msg>[cpp]26. Remove Duplicates from Sorted  add a more efficient solution<commit_after><|endoftext|>


<commit_before><commit_msg>Fixing build.<commit_after><|endoftext|>