text:
use crate::intermediate::{Token, CompileErrorList, TokenValue, CompileError};
use crate::intermediate::ast::{Document, Definition, ModelDefinition, FunctionDefinition, Statement, ImplementDefinition, ApplyDefinition, LocalDefinition, IncludeDefinition, ReturnStatement, Expression, IdentifierExpression, IntegerExpression, FloatExpression, BooleanExpression, ThisExpression, NullExpression, PrefixExpression, IfExpression, InfixExpression, CallExpression, StringExpression, InstanceGetExpression, LocalStatement, ArrayExpression, IndexGetExpression, ForStatement, BreakStatement, RescueStatement};
use crate::frontend::lexer::lex;
use std::slice::Iter;
use std::mem::discriminant;
use crate::intermediate::TokenValue::Identifier;

#[derive(Debug, PartialEq, PartialOrd)]
enum SymbolPriority {
    Lowest      = 0,
    Assign      = 1,
    Boolean     = 2,
    Equals      = 3,
    LessGreater = 4,
    Sum         = 5,
    Product     = 6,
    Prefix      = 7,
    Call        = 8,
    InstanceGet = 9
}

struct ParserState<'a> {
    tokens: Iter<'a, Token>,
    last_token: Token,
    current_token: Token,
    peek_token: Token,
    errors: CompileErrorList
}

impl<'a> ParserState<'a> {
    fn next_token(&mut self) {
        self.last_token = self.current_token.clone();
        self.current_token = self.peek_token.clone();

        if let Some(token) = self.tokens.next() {
            self.peek_token = token.clone();
        } else {
            self.peek_token = Token::none();
        };
    }

    fn push_error(&mut self, token: &Token, message: String) {
        let error = CompileError {
            token: token.clone(),
            message
        };

        self.errors.push(error);
    }

    fn get_current_precedence(&self) -> SymbolPriority {
        match self.current_token.value {
            TokenValue::Assign | TokenValue::PlusAssign | TokenValue::MinusAssign | TokenValue::StarAssign | TokenValue::SlashAssign | TokenValue::PercentAssign => SymbolPriority::Assign,
            TokenValue::And | TokenValue::Or => SymbolPriority::Boolean,
            TokenValue::Equal | TokenValue::NotEqual => SymbolPriority::Equals,
            TokenValue::Less | TokenValue::Greater | TokenValue::LessEqual | TokenValue::GreaterEqual => SymbolPriority::LessGreater,
            TokenValue::Plus | TokenValue::Minus => SymbolPriority::Sum,
            TokenValue::Star | TokenValue::Slash | TokenValue::Percent | TokenValue::BitAnd | TokenValue::BitOr => SymbolPriority::Product,
            TokenValue::Dot | TokenValue::LeftBracket => SymbolPriority::InstanceGet,
            TokenValue::LeftParentheses => SymbolPriority::Call,
            _ => SymbolPriority::Lowest
        }
    }

    fn current_token_is_any_of(&self, token_values: &[TokenValue]) -> bool {
        for token_value in token_values {
            if discriminant(&self.current_token.value) == discriminant(token_value) {
                return true;
            }
        };

        false
    }

    fn skip_until(&mut self, token_values: &[TokenValue]) {
        while !self.current_token_is_any_of(token_values) {
            self.next_token();
        };
    }

    fn expect_token(&mut self, token_value: TokenValue) -> bool {
        if discriminant(&self.current_token.value) == discriminant(&token_value) {
            return true;
        };

        self.push_error(&self.current_token.clone(), format!("Unexpect token [{:?}] (expert [{:?}])", self.current_token.value, token_value));

        self.skip_until(&[ token_value.clone(), TokenValue::Eof, TokenValue::None ]);

        discriminant(&self.current_token.value) == discriminant(&token_value)
    }

    fn expect_and_pop_token(&mut self, token_value: TokenValue) -> bool {
        if self.expect_token(token_value) {
            self.next_token();
            true
        } else {
            false
        }
    }

    fn parse_identifier_expression(&mut self) -> Option<Expression> {
        if !self.expect_token(TokenValue::Identifier("".to_string())) {
            return None;
        };

        let token = self.current_token.clone();
        self.next_token();

        Some(Expression::Identifier(IdentifierExpression { token }))
    }

    fn parse_integer_expression(&mut self) -> Option<Expression> {
        if !self.expect_token(TokenValue::Integer(0)) {
            return None;
        };

        let token = self.current_token.clone();
        self.next_token();

        Some(Expression::Integer(IntegerExpression { token }))
    }

    fn parse_float_expression(&mut self) -> Option<Expression> {
        if !self.expect_token(TokenValue::Float(0.0)) {
            return None;
        };

        let token = self.current_token.clone();
        self.next_token();

        Some(Expression::Float(FloatExpression { token }))
    }

    fn parse_string_expression(&mut self) -> Option<Expression> {
        if !self.expect_token(TokenValue::String("".to_string())) {
            return None;
        };

        let token = self.current_token.clone();
        self.next_token();

        Some(Expression::String(StringExpression { token }))
    }

    fn parse_boolean_expression(&mut self) -> Option<Expression> {
        let token = self.current_token.clone();
        self.next_token();
        match token.value {
            TokenValue::True | TokenValue::False => Some(Expression::Boolean(BooleanExpression { token })),
            _ => None
        }
    }

    fn parse_keyword_expression(&mut self) -> Option<Expression> {
        let token = self.current_token.clone();
        self.next_token();
        match token.value {
            TokenValue::This => Some(Expression::This(ThisExpression { token })),
            TokenValue::Null => Some(Expression::Null(NullExpression { token })),
            _ => None
        }
    }

    fn parse_prefix_expression(&mut self) -> Option<Expression> {
        let token = self.current_token.clone();
        self.next_token();

        match token.value {
            TokenValue::Minus | TokenValue::Not => {
                if let Some(expression) = self.parse_expression(SymbolPriority::Prefix) {
                    Some(Expression::Prefix(PrefixExpression {
                        prefix: token,
                        right: Box::new(expression)
                    }))
                } else {
                    None
                }
            },
            _ => None
        }

    }

    fn parse_group_expression(&mut self) -> Option<Expression> {
        if !self.expect_and_pop_token(TokenValue::LeftParentheses) {
            return None;
        };

        if let Some(expression) = self.parse_expression(SymbolPriority::Lowest) {
            if !self.expect_and_pop_token(TokenValue::RightParentheses) {
                return None;
            }

            Some(expression)
        } else {
            None
        }
    }

    fn parse_if_expression(&mut self) -> Option<Expression> {
        if !self.current_token_is_any_of(&[ TokenValue::If, TokenValue::ElseIf ]) {
            return None;
        }
        self.next_token();

        let mut expect_end = true;

        if let Some(condition) = self.parse_expression(SymbolPriority::Lowest) {
            let true_part = self.parse_body(&[ TokenValue::End, TokenValue::Else, TokenValue::ElseIf, TokenValue::Eof ]);

            let mut false_part = None;

            if self.current_token.value == TokenValue::Else {
                self.next_token();
                false_part = Some(self.parse_body(&[ TokenValue::End, TokenValue::Eof ]))
            } else if self.current_token.value == TokenValue::ElseIf {
                expect_end = false;

                if let Some(expression) = self.parse_if_expression() {
                    let statements = vec![ Statement::Expression(expression) ];
                    false_part = Some(statements);
                } else {
                    return None;
                };
            }

            if expect_end && !self.expect_and_pop_token(TokenValue::End) {
                return None;
            };

            Some(Expression::If(IfExpression {
                condition: Box::new(condition),
                true_part,
                false_part
            }))
        } else {
            None
        }
    }

    fn parse_comma_expressions(&mut self, end_tokens: &[ TokenValue ]) -> Option<Vec<Expression>> {
        let mut values = Vec::new();

        let mut last_comma = None;

        while !self.current_token_is_any_of(end_tokens) {
            last_comma = None;

            if let Some(parameter) = self.parse_expression(SymbolPriority::Lowest) {
                values.push(parameter);

                if self.current_token.value == TokenValue::Comma {
                    last_comma = Some(self.current_token.clone());
                    self.next_token();
                }

            } else {
                return None;
            }
        }

        if let Some(token) = last_comma {
            self.push_error(&token, "Unexpect token".to_string());
        };

        Some(values)
    }

    fn parse_array_expression(&mut self) -> Option<Expression> {
        self.expect_token(TokenValue::LeftBracket);

        let token = self.current_token.clone();
        self.next_token();

        if let Some(values) = self.parse_comma_expressions(&[ TokenValue::RightBracket, TokenValue::Eof ]) {
            self.expect_and_pop_token(TokenValue::RightBracket);

            Some(Expression::Array(ArrayExpression {
                token,
                values
            }))
        } else {
            None
        }
    }

    fn parse_start_expression(&mut self) -> Option<Expression> {
        match self.current_token.value {
            TokenValue::Identifier(_) => self.parse_identifier_expression(),
            TokenValue::Integer(_) => self.parse_integer_expression(),
            TokenValue::Float(_) => self.parse_float_expression(),
            TokenValue::String(_) => self.parse_string_expression(),
            TokenValue::True | TokenValue::False => self.parse_boolean_expression(),
            TokenValue::This | TokenValue::Null => self.parse_keyword_expression(),
            TokenValue::Minus | TokenValue::Not => self.parse_prefix_expression(),
            TokenValue::LeftParentheses => self.parse_group_expression(),
            TokenValue::LeftBracket => self.parse_array_expression(),
            TokenValue::If => self.parse_if_expression(),
            _ => {
                self.push_error(&self.current_token.clone(), "Unexpect token when parse expression".to_string());
                None
            }
        }
    }

    fn parse_call_expression(&mut self, expression: Expression) -> Option<Expression> {
        self.expect_token(TokenValue::LeftParentheses);

        let token = self.current_token.clone();
        self.next_token();

        if let Some(parameters) = self.parse_comma_expressions(&[ TokenValue::RightParentheses, TokenValue::Eof ]) {
            self.expect_and_pop_token(TokenValue::RightParentheses);

            Some(Expression::Call(CallExpression {
                token,
                function: Box::new(expression),
                parameters
            }))
        } else {
            None
        }
    }

    fn parse_instance_get_expression(&mut self, expression: Expression) -> Option<Expression> {
        let token = self.current_token.clone();
        self.next_token();

        match token.value.clone() {
            TokenValue::Dot => {
                let identifier_token = self.current_token.clone();
                if let TokenValue::Identifier(identifier) = identifier_token.value.clone() {
                    self.next_token();
                    let index = Expression::String(StringExpression { token: Token::new(TokenValue::String(identifier), identifier_token.position) });

                    Some(Expression::InstanceGet(InstanceGetExpression {
                        token,
                        instance: Box::new(expression),
                        index: Box::new(index)
                    }))

                } else {
                    self.push_error(&identifier_token, "Unexpect Token".to_string());
                    None
                }
            },
            TokenValue::LeftBracket => {
                if let Some(index) = self.parse_expression(SymbolPriority::Lowest) {
                    if !self.expect_and_pop_token(TokenValue::RightBracket) {
                        return None;
                    };

                    Some(Expression::IndexGet(IndexGetExpression {
                        token,
                        instance: Box::new(expression),
                        index: Box::new(index)
                    }))
                } else {
                    None
                }
            }
            _ => {
                self.push_error(&token, "Unexpect Token".to_string());
                None
            }
        }
    }

    fn parse_infix_expression(&mut self, expression: Expression) -> Option<Expression> {
        // if '-' or '(' or '[' is the first token at line, it's not a infix expression
        match self.current_token.value {
            TokenValue::Minus | TokenValue::LeftParentheses | TokenValue::LeftBracket => {
                if self.current_token.position.line > self.last_token.position.line {
                    return None;
                };
            },
            _ => {}
        }

        match self.current_token.value {
            TokenValue::Assign | TokenValue::PlusAssign | TokenValue::MinusAssign | TokenValue::StarAssign | TokenValue::SlashAssign | TokenValue::PercentAssign |
            TokenValue::And | TokenValue::Or | TokenValue::Equal | TokenValue::NotEqual | TokenValue::Less | TokenValue::Greater | TokenValue::LessEqual | TokenValue::GreaterEqual |
            TokenValue::BitAnd | TokenValue::BitOr | TokenValue::Plus | TokenValue::Minus | TokenValue::Star | TokenValue::Slash | TokenValue::Percent
            => {
                let token = self.current_token.clone();
                let precedence = self.get_current_precedence();

                self.next_token();

                if let Some(right) = self.parse_expression(precedence) {
                    Some(Expression::Infix(InfixExpression {
                        left: Box::new(expression),
                        infix: token,
                        right: Box::new(right)
                    }))
                } else {
                    None
                }
            }
            TokenValue::LeftParentheses => self.parse_call_expression(expression),
            TokenValue::Dot | TokenValue::LeftBracket => self.parse_instance_get_expression(expression),
            _ => None
        }
    }

    fn parse_expression(&mut self, precedence: SymbolPriority) -> Option<Expression> {
        if let Some(start_expression) = self.parse_start_expression() {
            let mut left_expression = start_expression;

            while self.current_token.value != TokenValue::Eof && precedence < self.get_current_precedence() {
                let expression = left_expression.clone();

                if let Some(new_expression) = self.parse_infix_expression(expression) {
                    left_expression = new_expression;
                } else {
                    return Some(left_expression);
                }
            }

            Some(left_expression)
        } else {
            None
        }
    }

    fn parse_return_statement(&mut self) -> Option<Statement> {
        let return_statement = ReturnStatement {
            token: self.current_token.clone()
        };
        self.next_token();

        Some(Statement::Return(return_statement))
    }

    fn parse_break_statement(&mut self) -> Option<Statement> {
        let break_statement = BreakStatement {
            token: self.current_token.clone()
        };
        self.next_token();

        Some(Statement::Break(break_statement))
    }

    fn parse_rescue_statement(&mut self) -> Option<Statement> {
        let rescue_statement = RescueStatement {
            token: self.current_token.clone()
        };
        self.next_token();

        Some(Statement::Rescue(rescue_statement))
    }

    fn parse_expression_statement(&mut self) -> Option<Statement> {
        if let Some(expression) = self.parse_expression(SymbolPriority::Lowest) {
            Some(Statement::Expression(expression))
        } else {
            None
        }
    }

    fn parse_local_statement(&mut self) -> Option<Statement> {
        self.expect_and_pop_token(TokenValue::Local);

        let mut variables = Vec::new();
        let mut values = Vec::new();

        let mut last_is_comma = true;

        while last_is_comma {
            if !self.expect_token(TokenValue::Identifier("".to_string())) {
                return None;
            };
            variables.push(self.current_token.clone());
            self.next_token();

            if self.current_token.value == TokenValue::Assign {
                self.next_token();
                values.push(self.parse_expression(SymbolPriority::Lowest));
            } else {
                values.push(None)
            }

            last_is_comma = self.current_token.value == TokenValue::Comma;

            if last_is_comma {
                self.next_token();
            };
        }

        Some(Statement::Local(LocalStatement {
            variables,
            values
        }))
    }

    fn parse_for_statement(&mut self) -> Option<Statement> {
        let token = self.current_token.clone();

        if !self.expect_and_pop_token(TokenValue::For) {
            return None;
        };

        if !self.expect_token(TokenValue::Identifier("".to_string())) {
            return None;
        };

        let identifier = self.current_token.clone();
        self.next_token();

        if !self.expect_and_pop_token(TokenValue::In) {
            return None;
        };

        let expression = self.parse_expression(SymbolPriority::Lowest);

        if expression.is_none() {
            return None;
        };

        let statements = self.parse_body(&[ TokenValue::Eof, TokenValue::End ]);

        if !self.expect_and_pop_token(TokenValue::End) {
            return None;
        };

        Some(Statement::For(ForStatement{
            token,
            identifier,
            enumerable: expression.unwrap(),
            statements
        }))
    }

    fn parse_statement(&mut self) -> Option<Statement> {
        match self.current_token.value {
            TokenValue::Local => self.parse_local_statement(),
            TokenValue::Return => self.parse_return_statement(),
            TokenValue::Break => self.parse_break_statement(),
            TokenValue::Rescue => self.parse_rescue_statement(),
            TokenValue::For => self.parse_for_statement(),
            _ => self.parse_expression_statement()
        }
    }

    fn parse_model_definition(&mut self) -> Option<Definition> {
        // skip model token
        self.next_token();

        // model name
        if !self.expect_token(TokenValue::Identifier("".to_string())) {
            return None;
        }
        let name = self.current_token.clone();
        self.next_token();

        let mut properties = Vec::new();

        // TODO : add annotation

        while let TokenValue::Identifier(_) = self.current_token.value {
            properties.push(self.current_token.clone());
            self.next_token();
        };

        if !self.expect_and_pop_token(TokenValue::End) {
            return None;
        }

        Some(Definition::Model(ModelDefinition {
            name,
            properties
        }))
    }

    fn parse_body(&mut self, terminators: &[TokenValue]) -> Vec<Statement> {
        let mut statements = Vec::new();

        while !self.current_token_is_any_of(terminators) {
            if let Some(statement) = self.parse_statement() {
                statements.push(statement);
            };
        };

        statements
    }

    fn parse_function_definition(&mut self) -> Option<Definition> {
        // skip function token
        self.next_token();

        // function name
        if !self.expect_token(TokenValue::Identifier("".to_string())) {
            return None;
        }
        let name = self.current_token.clone();
        self.next_token();

        if !self.expect_and_pop_token(TokenValue::LeftParentheses) {
            return None;
        };

        // parse parameters
        let mut parameters = Vec::new();
        let mut last_comma = None;

        while self.current_token.value != TokenValue::RightParentheses {
            last_comma = None;

            if parameters.len() == 0 {
                if !self.current_token_is_any_of(&[ TokenValue::Identifier("".to_string()), TokenValue::This ]) {
                    self.errors.push_error(&self.current_token.clone(), "Unexpect token");
                    self.skip_until(&[ TokenValue::Identifier("".to_string()), TokenValue::This, TokenValue::Eof ]);
                };
            } else if !self.expect_token(TokenValue::Identifier("".to_string())) {
                return None;
            };

            parameters.push(self.current_token.clone());
            self.next_token();

            if self.current_token.value == TokenValue::Comma {
                last_comma = Some(self.current_token.clone());
                self.next_token();
            }
        }

        if let Some(comma) = last_comma {
            self.push_error(&comma.clone(), format!("Unexpect token [{:?}]", comma.value));
        };

        if !self.expect_and_pop_token(TokenValue::RightParentheses) {
            return None;
        };

        // parse function body
        let body = self.parse_body(&[ TokenValue::End, TokenValue::Eof ]);

        if !self.expect_and_pop_token(TokenValue::End) {
            return None;
        };

        Some(Definition::Function(FunctionDefinition {
            name,
            parameters,
            body
        }))
    }

    fn parse_implement_definition(&mut self) -> Option<Definition> {
        self.next_token();

        if !self.expect_token(TokenValue::Identifier("".to_string())) {
            return None;
        }
        let model_name = self.current_token.clone();
        self.next_token();

        let mut functions = Vec::new();

        while self.current_token.value == TokenValue::Function {
            if let Some(definition) = self.parse_function_definition() {
                if let Definition::Function(function_definition) = definition {
                    functions.push(function_definition);
                };
            };
        };

        if !self.expect_and_pop_token(TokenValue::End) {
            return None;
        };

        Some(Definition::Implement(ImplementDefinition {
            model_name,
            functions
        }))
    }

    fn parse_apply_definition(&mut self) -> Option<Definition> {
        self.next_token();

        if !self.expect_token(TokenValue::Identifier("".to_string())) {
            return None;
        }
        let source_model = self.current_token.clone();
        self.next_token();

        if !self.expect_and_pop_token(TokenValue::To) {
            return None;
        };

        if !self.expect_token(TokenValue::Identifier("".to_string())) {
            return None;
        }
        let target_model = self.current_token.clone();
        self.next_token();

        Some(Definition::Apply(ApplyDefinition {
            source_model,
            target_model
        }))
    }

    fn parse_local_definition(&mut self) -> Option<Definition> {
        self.expect_and_pop_token(TokenValue::Local);

        let mut variables = Vec::new();
        let mut values = Vec::new();

        let mut last_is_comma = true;

        while last_is_comma {
            if !self.expect_token(TokenValue::Identifier("".to_string())) {
                return None;
            };
            variables.push(self.current_token.clone());
            self.next_token();

            if self.current_token.value == TokenValue::Assign {
                self.next_token();

                if self.current_token_is_any_of(&[ TokenValue::Null, TokenValue::True, TokenValue::False, TokenValue::Integer(0), TokenValue::Float(0.0), TokenValue::String("".to_string()) ]) {
                    values.push(Some(self.current_token.clone()));
                } else {
                    self.push_error(&self.current_token.clone(), "can use constant value only".to_string());
                    values.push(None);
                }

                self.next_token();
            } else {
                values.push(None);
            };

            last_is_comma = self.current_token.value == TokenValue::Comma;

            if last_is_comma {
                self.next_token();
            };
        }

        Some(Definition::Local(LocalDefinition {
            variables,
            values
        }))
    }

    fn parse_include_definition(&mut self) -> Option<Definition> {
        self.next_token();

        let mut models = Vec::new();
        let mut aliases = Vec::new();

        let mut last_comma = None;

        while models.len() == 0 || self.current_token_is_any_of(&[ Identifier("".to_string()) ]) {
            last_comma = None;

            if !self.expect_token(TokenValue::Identifier("".to_string())) {
                return None;
            };
            models.push(self.current_token.clone());
            self.next_token();

            if self.current_token.value == TokenValue::As {
                self.next_token();
                if !self.expect_token(TokenValue::Identifier("".to_string())) {
                    return None;
                };
                aliases.push(self.current_token.clone());
                self.next_token();
            } else {
                aliases.push(models.last().unwrap().clone());
            }

            if self.current_token.value == TokenValue::Comma {
                last_comma = Some(self.current_token.clone());
                self.next_token();
            }
        };

        if let Some(comma) = last_comma {
            self.push_error(&comma.clone(), format!("Unexpect token [{:?}]", comma.value));
        };

        if !self.expect_and_pop_token(TokenValue::From) {
            return None;
        };

        if !self.expect_token(TokenValue::String("".to_string())) {
            return None;
        }
        let filename = self.current_token.clone();
        self.next_token();

        Some(Definition::Include(IncludeDefinition {
            public_names: models,
            aliases,
            filename
        }))
    }

    fn parse_public_definition(&mut self) -> Option<Definition> {
        self.expect_and_pop_token(TokenValue::Public);

        match self.current_token.value {
            TokenValue::Model => {
                if let Some(Definition::Model(model_definition)) = self.parse_model_definition() {
                    Some(Definition::PublicModel(model_definition))
                } else {
                    None
                }
            },
            TokenValue::Function => {
                if let Some(Definition::Function(function_definition)) = self.parse_function_definition() {
                    Some(Definition::PublicFunction(function_definition))
                } else {
                    None
                }
            },
            _ => {
                self.push_error(&self.current_token.clone(), "Unexpect token".to_string());
                None
            }
        }
    }

    fn parse_definition(&mut self) -> Option<Definition> {
        match self.current_token.value {
            TokenValue::Model => self.parse_model_definition(),
            TokenValue::Function => self.parse_function_definition(),
            TokenValue::Implement => self.parse_implement_definition(),
            TokenValue::Apply => self.parse_apply_definition(),
            TokenValue::Include => self.parse_include_definition(),
            TokenValue::Local => self.parse_local_definition(),
            TokenValue::Public => self.parse_public_definition(),
            _ => {
                self.push_error(&self.current_token.clone(), format!("Unexcpet token [{:?}]", self.current_token.clone()));
                self.skip_until(&[ TokenValue::Include, TokenValue::Public, TokenValue::Model, TokenValue::Implement, TokenValue::Apply, TokenValue::Local, TokenValue::Function ]);
                None
            }
        }
    }

    fn parse_definitions(&mut self) -> Vec<Definition> {
        let mut definitions = Vec::new();

        let mut include_definitions_ended = false;

        while self.current_token.value != TokenValue::Eof && self.current_token.value != TokenValue::None {
            let current_token = self.current_token.clone();

            if let Some(definition) = self.parse_definition() {

                if let Definition::Include(_) = definition {
                    if include_definitions_ended {
                        self.push_error(&current_token, "include definition must at the top of files".to_string());
                    };
                } else {
                    include_definitions_ended = true;
                };

                definitions.push(definition);
            };
        };

        definitions
    }

    fn parse_document(&mut self, filename: String) -> Document {
        let mut document = Document {
            definitions: self.parse_definitions(),
            filename
        };

        document.normalize_include_paths();

        document
    }
}

pub fn parse(source: &str, filename: &str) -> Result<Document, CompileErrorList> {
    let token_list = lex(source)?;

    let mut state = ParserState {
        tokens: token_list.iter(),
        last_token: Token::none(),
        current_token: Token::none(),
        peek_token: Token::none(),
        errors: CompileErrorList::new(filename)
    };

    state.next_token();
    state.next_token();

    let document = state.parse_document(filename.to_string());

    if state.errors.is_empty() {
        Ok(document)
    } else {
        Err(state.errors)
    }
}


text:
module SimpleMongoidSlugs
  VERSION = "0.0.1"
end

redpajama_set_name: RedPajamaGithub


text:
//
// OrcVersion.java -- Java class OrcVersion
// Project Orchard
//
// Created by jthywiss on Jan 20, 2013.
//
// Copyright (c) 2016 The University of Texas at Austin. All rights reserved.
//
// Use and redistribution of this file is governed by the license terms in
// the LICENSE file found in the project's top-level directory and also found at
// URL: http://orc.csres.utexas.edu/license.shtml .
//

package orc.lib.orchard;

import orc.error.runtime.ArityMismatchException;
import orc.error.runtime.TokenException;
import orc.orchard.OrchardProperties;
import orc.types.Type;
import orc.values.sites.TypedSite;
import orc.values.sites.compatibility.Args;
import orc.values.sites.compatibility.EvalSite;
import orc.values.sites.compatibility.Types;

public class OrcVersion extends EvalSite implements TypedSite {

    @Override
    public Object evaluate(final Args args) throws TokenException {
        if (args.size() != 0) {
            throw new ArityMismatchException(0, args.size());
        }
        return OrchardProperties.getProperty("war.manifest.Implementation-Title") + ' ' + OrchardProperties.getProperty("war.manifest.Implementation-Version") + " rev. " + OrchardProperties.getProperty("war.manifest.SCM-Revision") + '\n' + orc.Main.orcImplName() + ' ' + orc.Main.orcVersion() + '\n' + orc.Main.orcURL() + '\n' + orc.Main.orcCopyright();
    }

    @Override
    public Type orcType() {
        return Types.function(Types.integer());
    }

}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System.Collections.Generic;
using Azure.AI.TextAnalytics.Models;

namespace Azure.AI.TextAnalytics
{
    /// <summary>
    /// A model which contains information about the detected healthcare entity.
    /// </summary>
    public class HealthcareEntity
    {
        internal HealthcareEntity(HealthcareEntityInternal entity)
        {
            Category = entity.Category;
            Text = entity.Text;
            SubCategory = entity.Subcategory;
            ConfidenceScore = entity.ConfidenceScore;
            Offset = entity.Offset;
            Length = entity.Length;
            DataSources = entity.Links;
            Assertion = entity.Assertion;
            NormalizedText = entity.Name;
        }
        /// <summary>
        /// Gets the entity text as it appears in the input document.
        /// </summary>
        public string Text { get; }

        /// <summary>
        /// Gets the entity category inferred by the Text Analytics service's
        /// healthcare model.  The list of available categories is
        /// described at
        /// <see href="https://docs.microsoft.com/azure/cognitive-services/text-analytics/named-entity-types?tabs=health"/>.
        /// </summary>
        public HealthcareEntityCategory Category { get; }

        /// <summary>
        /// Gets the sub category of the entity inferred by the Text Analytics service's
        /// healthcare model.  This property may not have a value if
        /// a sub category doesn't exist for this entity.  The list of available categories and
        /// subcategories is described at
        /// <see href="https://docs.microsoft.com/azure/cognitive-services/text-analytics/named-entity-types?tabs=health"/>.
        /// </summary>
        public string SubCategory { get; }

        /// <summary>
        /// Gets a score between 0 and 1, indicating the confidence that the
        /// text substring matches this inferred entity.
        /// </summary>
        public double ConfidenceScore { get; }

        /// <summary>
        /// Gets the starting position for the matching text in the input document.
        /// </summary>
        public int Offset { get; }

        /// <summary>
        /// Gets the length for the matching entity in the input document.
        /// </summary>
        public int Length { get; }

        /// <summary>
        /// Get the list of data sources for the entity.
        /// </summary>
        public IReadOnlyCollection<EntityDataSource> DataSources { get; }

        /// <summary>
        /// Gets the healthcare assertions for the entity.
        /// </summary>
        public HealthcareEntityAssertion Assertion { get; }

        /// <summary>
        /// Gets the normalized text for the entity.
        /// </summary>
        public string NormalizedText { get; }
    }
}


text:
export default function capitalize(string) {
  if (typeof string !== 'string') {
    return '';
  }

  return string.charAt(0).toUpperCase() + string.slice(1);
}


text:
package org.eclipse.flux.ui.integration;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.flux.client.ConnectionStatus;
import org.eclipse.flux.client.util.Listener;
import org.eclipse.flux.client.util.Observable;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.progress.UIJob;

/**
 * Connection listener attached to flux message bus on startup to report
 * problems creating the connection because of authorization failure.
 *
 * @author Kris De Volder
 */
public class AuthFailureReporter implements Listener<ConnectionStatus> {

	private Observable<ConnectionStatus> state;

	public AuthFailureReporter(Observable<ConnectionStatus> observable) {
		this.state = observable;
		this.state.addListener(this);
	}

	@Override
	public void newValue(Observable<ConnectionStatus> o, ConnectionStatus v) {
		if (v.isAuthFailure()) {
			UIJob job = new UIJob("Flux Error Reporter") {
				@Override
				public IStatus runInUIThread(IProgressMonitor monitor) {
					MessageDialog.openError(null, "Flux Connection Failed",
							"Flux Web Socket handshake failed. Most likely this means " +
							"your Flux credentials are invalid."
					);
					return Status.OK_STATUS;
				}
			};
			job.schedule();
			//We only report this error once.
			// since this error is all we handle... there's no point to continue listening
		} else if (v.isConnected()) {
			//This means credentials must be valid and this listener now useless.
			dispose();
		}
	}

	void dispose() {
		Observable<ConnectionStatus> s = state;
		if (s!=null) {
			state = null;
			s.removeListener(this);
		}
	}

}


text:
const debug = require('ghost-ignition').debug('services:routing:helpers:render-post'),
    formatResponse = require('./format-response'),
    renderer = require('./renderer');
/**
 * @description Helper to handle rendering multiple resources.
 *
 * @param {Object} req
 * @param {Object} res
 * @returns {Closure)
 */
module.exports = function renderEntry(req, res) {
    debug('renderEntry called');
    return function renderEntry(entry) {
        // Format data 2 - 1 is in preview/entry
        // Render
        return renderer(req, res, formatResponse.entry(entry));
    };
};


text:
@interface MHImportListView ()
@property (weak) IBOutlet NSTableView *tableView;
@property (weak) IBOutlet NSProgressIndicator *activityIndicator;
@end

@implementation MHImportListView

- (void)awakeFromNib {
    [self.tableView setDoubleAction:@selector(onDoubleClick:)];
}

- (void)startLoading {
    [self.activityIndicator startAnimation:self];
}

- (void)stopLoading {
    [self.activityIndicator stopAnimation:self];
}

#pragma mark - Setters

- (void)setNumberOfRows:(NSUInteger)numberOfRows {
    _numberOfRows = numberOfRows;
    [self.tableView reloadData];
    [self.tableView selectRowIndexes:[NSIndexSet indexSetWithIndex:0] byExtendingSelection:NO];
}

#pragma mark - NSTableViewDataSource

- (void)onDoubleClick:(NSTableView *)sender {
    [self onSelectedRow:sender.clickedRow];
}

- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
    NSString *currentString = [self.dataSource searchStringForImportList:self];

    if (self.numberOfRows > 0) {
        NSString *header          = [self.dataSource importList:self stringForRow:row];
        NSString *formattedHeader = [self.dataSource importList:self formattedStringForRow:row];

        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:formattedHeader];

        // invert black->white for selected row
        if (tableView.selectedRow == row) {
            [string addAttributes:[self whiteForegroundTextAttribute] range:NSMakeRange(0, formattedHeader.length)];
        }

        // highlight matched substring
        if (currentString.length > 0) {
            // modify range to exclude leading "#import"
            NSRange range = [header rangeOfString:currentString options:NSCaseInsensitiveSearch];
            range.location += [formattedHeader rangeOfString:header].location;

            [string addAttributes:[self highlightedTextAttribute] range:range];
        }

        return string;
    }
    else {
        if (currentString > 0) {
            NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:currentString];
            NSRange range = NSMakeRange(0, currentString.length);

            [string addAttributes:[self whiteForegroundTextAttribute] range:range];

            return string;
        }
    }
    return nil;
}

- (NSInteger) numberOfRowsInTableView:(NSTableView *)tableView {
    return self.numberOfRows > 0 ? self.numberOfRows : 1;
}

- (void)tableViewSelectionDidChange:(NSNotification *)aNotification {
}

- (CGFloat)tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row {
    return 20.0;
}

#pragma mark - MHTableViewDelegate

- (void)tableView:(MHTableView *)tableView onKeyPress:(NSEvent *)key {
    NSString *currentString = [self.dataSource searchStringForImportList:self];
    NSInteger selectedRow = [self.tableView selectedRow];

    if (key.modifierFlags & NSControlKeyMask) {
        if ([key.charactersIgnoringModifiers isEqualToString:@"n"]) {
            // equivalent to down arrow
            selectedRow += 1;
            if (selectedRow == self.numberOfRows) {
                selectedRow = 0;
            }
            [self selectRow:selectedRow];
        }
        else if ([key.charactersIgnoringModifiers isEqualToString:@"p"]) {
            // equivalent to up arrow
            selectedRow -= 1;
            if (selectedRow < 0) {
                selectedRow = self.numberOfRows-1;
            }
            [self selectRow:selectedRow];
        }
        else if ([key.charactersIgnoringModifiers isEqualToString:@"h"]) {
            // equivalent to delete key
            NSUInteger length = currentString.length;
            if (length > 0) {
                currentString = [currentString substringToIndex:length-1];
            }
            [self performSearch:currentString];
        }
        else if ([key.charactersIgnoringModifiers isEqualToString:@"["]) {
            // equivalent to esc key
            [self.delegate importListDidDismiss:self];
        }
    }
    else if ((key.modifierFlags & NSDeviceIndependentModifierFlagsMask) == NSCommandKeyMask) {
        // paste via command-v
        if ([key.characters isEqualToString:@"v"]) {
            currentString = [[NSPasteboard generalPasteboard] stringForType:NSPasteboardTypeString];
            [self performSearch:currentString];
        }
    }
    else if ([self isValidKeyForSearching:key]) {
        currentString = [currentString stringByAppendingString:key.characters];
        [self performSearch:currentString];
    }
    else if (key.keyCode == kVK_Delete) {
        NSUInteger length = currentString.length;
        if (length > 0) {
            currentString = [currentString substringToIndex:length-1];
        }
        [self performSearch:currentString];
    }
    else if (key.keyCode == kVK_Escape) {
        [self.delegate importListDidDismiss:self];
    }
    else if (key.keyCode == kVK_Return ||
		   key.keyCode == kVK_ANSI_KeypadEnter) {

        [self onSelectedRow:selectedRow];
    }
}

- (void)onSelectedRow:(NSInteger) selectedRow {
    if (selectedRow != -1 && self.numberOfRows > 0) {
        [self.delegate importList:self didSelectRow:selectedRow];
    }
}

- (void)performSearch:(NSString *)searchString {
    [self.dataSource importList:self performSearch:searchString];
}

- (void) selectRow:(NSInteger) row {
    [self.tableView selectRowIndexes:[NSIndexSet indexSetWithIndex:row]
                byExtendingSelection:NO];
    [self.tableView scrollRowToVisible:row];
}

#pragma mark - MHImportListView table text styles

- (NSDictionary *)whiteForegroundTextAttribute {
    return @{NSForegroundColorAttributeName: [NSColor whiteColor]};
}

- (NSDictionary *)highlightedTextAttribute {
    return @{NSForegroundColorAttributeName: [NSColor blackColor],
             NSBackgroundColorAttributeName: [NSColor colorWithRed:235/255.f green:222/255.f blue:184/255.f alpha:1.0f],
             NSStrokeWidthAttributeName: @(-1)};
}

#pragma mark - Keystroke helpers

- (BOOL)isValidKeyForSearching:(NSEvent *)key {
    return [key.characters mh_isAlphaNumeric] ||
           key.keyCode == kVK_ANSI_Period ||
           (key.modifierFlags & NSShiftKeyMask && key.keyCode == kVK_ANSI_Equal) ||
           (key.modifierFlags & NSShiftKeyMask && key.keyCode == kVK_ANSI_Minus);
}

@end


text:
package com.hanleybrand.xnamer;

import java.util.ArrayList;
import java.util.List;

public class Namer {

    private String capitalize_name(String name) {
        return Character.toString(name.charAt(0)).toUpperCase() + name.substring(1);
    }

    public String choice_from_list(ArrayList<String> list){
        int idx = (int)(Math.random() * (list.size() + 1));
        return list.get(idx);
    }

}


text:
package com.cbooy.mmpa.activity.views;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * 自动具有焦点
 * @author chenhao24
 *
 */
public class FocusedTextView extends TextView {

	public FocusedTextView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	/**
	 * 默认获得焦点
	 */
	@Override
	public boolean isFocused() {
		return true;
	}
}


text:
static NSString * (*TDOriginalDescription)(id, SEL);

static NSString *TDFormattedStringForComplexType(const char *encoding) {
    NSString *type;
    if (*encoding == '(') {
        type = @"union";
    } else if (*encoding == '{') {
        type = @"struct";
    } else {
        return nil;
    }

    const char *namePtr = encoding + 1;
    unsigned length = 0;
    while (*namePtr && *namePtr != '=' && *namePtr != '}' && *namePtr != ')') {
        namePtr++;
        length++;
    }
    NSString *name = [[NSString alloc] initWithBytes:(encoding + 1) length:length encoding:NSUTF8StringEncoding];

    return [NSString stringWithFormat:@"%@%@%@", type, name.length ? @" " : @"", name];
}

static NSString *TDFormattedStringForType(const char *encoding) {
    char type = *encoding;

    switch (type) {
        case 'c': return @"char";
        case 'i': return @"int";
        case 's': return @"short";
        case 'l': return @"long";
        case 'q': return @"long long";
        case 'C': return @"unsigned char";
        case 'I': return @"unsigned int";
        case 'S': return @"unsigned short";
        case 'L': return @"unsigned long";
        case 'Q': return @"unsigned long long";
        case 'f': return @"float";
        case 'd': return @"double";
        case 'D': return @"long double";
        case 'B': return @"_Bool"; // C99 _Bool or C++ bool
        case 'v': return @"void";
        case '*': return @"STR";
        case '#': return @"Class";
        case ':': return @"SEL";
        case '%': return @"NXAtom";
        case '?': return @"void";
        case 'j': return @"_Complex";
        case 'r': return @"const";
        case 'n': return @"in";
        case 'N': return @"inout";
        case 'o': return @"out";
        case 'O': return @"bycopy";
        case 'R': return @"byref";
        case 'V': return @"oneway";
        case '@': return @"id";
        case '^': return [NSString stringWithFormat:@"%@*", TDFormattedStringForType(encoding + 1)];
        case '[': {
            char *type;
            long size = strtol(encoding + 1, &type, 10);
            return [NSString stringWithFormat:@"%@[%li]", TDFormattedStringForType(type), size];
        }
        case '(':
        case '{':
            return TDFormattedStringForComplexType(encoding);
        default:
            break;
    }

    return @"";
}

NSString *TDFormattedStringForBlockSignature(id block) {
    struct TD_Block_literal_1 *blockRef = (__bridge struct TD_Block_literal_1 *)block;
    int flags = blockRef->flags;

    if ((flags & TD_BLOCK_HAS_SIGNATURE) == 0) return nil;

    struct TD_Block_descriptor_1 *descriptor = blockRef->descriptor;

    void *signaturePtr = descriptor;
    signaturePtr += sizeof(descriptor->reserved);
    signaturePtr += sizeof(descriptor->size);

    if (flags & TD_BLOCK_HAS_COPY_DISPOSE) {
        signaturePtr += sizeof(descriptor->copy_helper);
        signaturePtr += sizeof(descriptor->dispose_helper);
    }

    const char *signature = *(const char **)signaturePtr;
    NSMethodSignature *methodSignature = [NSMethodSignature signatureWithObjCTypes:signature];

    // Purposefully ignore first argument, it is a reference to the block itself
    NSMutableArray *arguments = [NSMutableArray array];
    for (int i=1; i < methodSignature.numberOfArguments; i++) {
        NSString *type = TDFormattedStringForType([methodSignature getArgumentTypeAtIndex:i]);
        [arguments addObject:type];
    }

    NSString *returnType = TDFormattedStringForType(methodSignature.methodReturnType);
    return [NSString stringWithFormat:@"(%@ (^)(%@))", returnType, [arguments componentsJoinedByString:@", "]];
}

static NSString * TDReplacedDescription(id self, SEL _cmd) {
    NSString *blockType = TDFormattedStringForBlockSignature(self);

    if (blockType) {
        return [NSString stringWithFormat:@"<%@: %@>", NSStringFromClass([self class]), blockType];
    } else {
        return TDOriginalDescription(self, _cmd);
    }
}

static __attribute__((constructor)) void constructor() {
    Method descriptionMethod = class_getInstanceMethod(NSClassFromString(@"NSBlock"), @selector(description));
    TDOriginalDescription = (NSString * (*)(id, SEL))method_setImplementation(descriptionMethod, (IMP)&TDReplacedDescription);
}


text:
/* eslint-env jest */
import { imgSnapshotTest, renderGraph } from '../../helpers/util';

describe('State diagram', () => {
  it('should render a simple state diagrams', () => {
    imgSnapshotTest(
      `
    stateDiagram
    [*] --> State1
    State1 --> [*]
      `,
      { logLevel: 0, fontFamily: 'courier' }
    );
    cy.get('svg');
  });
  it('should render a long descriptions instead of id when available', () => {
    imgSnapshotTest(
      `
      stateDiagram

      [*] --> S1
      state "Some long name" as S1
      `,
      { logLevel: 0, fontFamily: 'courier' }
    );
    cy.get('svg');
  });
  it('should render a long descriptions with additional descriptions', () => {
    imgSnapshotTest(
      `
      stateDiagram

      [*] --> S1
      state "Some long name" as S1: The description
      `,
      { logLevel: 0, fontFamily: 'courier' }
    );
    cy.get('svg');
  });
  it('should render a single state with short descriptions', () => {
    imgSnapshotTest(
      `
    stateDiagram
      state "A long long name" as long1
      state "A" as longlonglongid
      `,
      { logLevel: 0, fontFamily: 'courier' }
    );
    cy.get('svg');
  });
  it('should render a transition descriptions with new lines', () => {
    imgSnapshotTest(
      `
      stateDiagram

      [*] --> S1
      S1 --> S2: long line using
should work
      S1 --> S3: long line using
should work
      S1 --> S4: long line using \\nshould work
      `,
      { logLevel: 0, fontFamily: 'courier' }
    );
    cy.get('svg');
  });
  it('should render a state with a note', () => {
    imgSnapshotTest(
      `
    stateDiagram
    State1: The state with a note
    note right of State1
      Important information! You can write
      notes.
    end note
      `,
      { logLevel: 0, fontFamily: 'courier' }
    );
    cy.get('svg');
  });
  it('should render a state with on the left side when so specified', () => {
    imgSnapshotTest(
      `
    stateDiagram
    State1: The state with a note with minus - and plus + in it
    note left of State1
      Important information! You can write
      notes with . and  in them.
    end note
      `,
      { logLevel: 0, fontFamily: 'courier' }
    );
    cy.get('svg');
  });
  it('should render a state with a note together with another state', () => {
    imgSnapshotTest(
      `
    stateDiagram
    State1: The state with a note +,-
    note right of State1
      Important information! You can write +,-
      notes.
    end note
    State1 --> State2 : With +,-
    note left of State2 : This is the note +,-

      `,
      { logLevel: 0, fontFamily: 'courier' }
    );
    cy.get('svg');
  });
  it('should render a note with multiple lines in it', () => {
    imgSnapshotTest(
      `
    stateDiagram
    State1: The state with a note
    note right of State1
      Important information! You\ncan write
      notes with multiple lines...
      Here is another line...
      And another line...
    end note
    `,
      { logLevel: 0, fontFamily: 'courier' }
    );
  });
  it('should handle multiline notes with different line breaks', () => {
    imgSnapshotTest(
      `
      stateDiagram
      State1
      note right of State1
      Line1
Line2
Line3
Line4
Line5
      end note
      `,
      { logLevel: 0, fontFamily: 'courier' }
    );
  });

  it('should render a states with descriptions including multi-line descriptions', () => {
    imgSnapshotTest(
      `
    stateDiagram
    State1: This a a single line description
    State2: This a a multi line description
    State2: here comes the multi part
    [*] --> State1
    State1 --> State2
    State2 --> [*]
      `,
      { logLevel: 0, fontFamily: 'courier' }
    );
    cy.get('svg');
  });
  it('should render a simple state diagrams', () => {
    imgSnapshotTest(
      `
    stateDiagram
    [*] --> State1
    State1 --> State2
    State1 --> State3
    State1 --> [*]
      `,
      { logLevel: 0, fontFamily: 'courier' }
    );
    cy.get('svg');
  });
  it('should render a simple state diagrams with labels', () => {
    imgSnapshotTest(
      `
    stateDiagram
    [*] --> State1
    State1 --> State2 : Transition 1
    State1 --> State3 : Transition 2
    State1 --> State4 : Transition 3
    State1 --> State5 : Transition 4
    State2 --> State3 : Transition 5
    State1 --> [*]
      `,
      { logLevel: 0, fontFamily: 'courier' }
    );
    cy.get('svg');
  });
  it('should render state descriptions', () => {
    imgSnapshotTest(
      `
      stateDiagram
        state "Long state description" as XState1
        state "Another Long state description" as XState2
        XState2 : New line
        XState1 --> XState2
      `,
      { logLevel: 0, fontFamily: 'courier' }
    );
    cy.get('svg');
  });
  it('should render composite states', () => {
    imgSnapshotTest(
      `
      stateDiagram
      [*] --> NotShooting: Pacifist
      NotShooting --> A
      NotShooting --> B
      NotShooting --> C

      state NotShooting {
        [*] --> Idle: Yet another long long öong öong öong label
        Idle --> Configuring : EvConfig
        Configuring --> Idle : EvConfig  EvConfig EvConfig  EvConfig EvConfig
      }
      `,
      { logLevel: 0, fontFamily: 'courier' }
    );
    cy.get('svg');
  });
  it('should render multiple composit states', () => {
    imgSnapshotTest(
      `
      stateDiagram
      [*]-->TV

      state TV {
        [*] --> Off: Off to start with
        On --> Off : Turn off
        Off --> On : Turn on
      }

      TV--> Console

      state Console {
        [*] --> Off2: Off to start with
        On2--> Off2 : Turn off
        Off2 --> On2 : Turn on
        On2-->Playing

        state Playing {
          Alive --> Dead
          Dead-->Alive
         }
      }
      `,
      { logLevel: 0, fontFamily: 'courier' }
    );
  });
  it('should render forks in composit states', () => {
    imgSnapshotTest(
      `
      stateDiagram
      [*]-->TV

      state TV {
        state fork_state <<fork>>
        [*] --> fork_state
        fork_state --> State2
        fork_state --> State3

        state join_state <<join>>
        State2 --> join_state
        State3 --> join_state
        join_state --> State4
        State4 --> [*]
      }
      `,
      { logLevel: 0, fontFamily: 'courier' }
    );
  });
  it('should render forks and joins', () => {
    imgSnapshotTest(
      `
    stateDiagram
    state fork_state <<fork>>
      [*] --> fork_state
      fork_state --> State2
      fork_state --> State3

      state join_state <<join>>
      State2 --> join_state
      State3 --> join_state
      join_state --> State4
      State4 --> [*]
    `,
      { logLevel: 0, fontFamily: 'courier' }
    );
    cy.get('svg');
  });
  it('should render concurrency states', () => {
    imgSnapshotTest(
      `
    stateDiagram
    [*] --> Active

    state Active {
      [*] --> NumLockOff
      NumLockOff --> NumLockOn : EvNumLockPressed
      NumLockOn --> NumLockOff : EvNumLockPressed
      --
      [*] --> CapsLockOff
      CapsLockOff --> CapsLockOn : EvCapsLockPressed
      CapsLockOn --> CapsLockOff : EvCapsLockPressed
      --
      [*] --> ScrollLockOff
      ScrollLockOff --> ScrollLockOn : EvCapsLockPressed
      ScrollLockOn --> ScrollLockOff : EvCapsLockPressed
    }
    `,
      { logLevel: 0, fontFamily: 'courier' }
    );
    cy.get('svg');
  });
  it('should render a state with states in it', () => {
    imgSnapshotTest(
      `
      stateDiagram
      state PilotCockpit {
        state  Parent {
          C
        }
    }
    `,
      {
        logLevel: 0, fontFamily: 'courier'
      }
    );
  });
  it('Simplest composite state', () => {
    imgSnapshotTest(
      `
      stateDiagram
        state  Parent {
          C
        }
    `,
      {
        logLevel: 0, fontFamily: 'courier'
      }
    );
  });
  it('should handle multiple arrows from one node to another', () => {
    imgSnapshotTest(
      `
      stateDiagram
        a --> b: Start
        a --> b: Stop
    `,
      {
        logLevel: 0, fontFamily: 'courier'
      }
    );
  });
  it('should render a state diagram when useMaxWidth is true (default)', () => {
    renderGraph(
      `
    stateDiagram
    [*] --> State1
    State1 --> [*]
      `,
      { state: { useMaxWidth: true } }
    );
    cy.get('svg')
      .should((svg) => {
        expect(svg).to.have.attr('width', '100%');
        expect(svg).to.have.attr('height');
        const height = parseFloat(svg.attr('height'));
        expect(height).to.eq(139);
        const style = svg.attr('style');
        expect(style).to.match(/^max-width: [\d.]+px;$/);
        const maxWidthValue = parseFloat(style.match(/[\d.]+/g).join(''));
        // use within because the absolute value can be slightly different depending on the environment ±5%
        expect(maxWidthValue).to.be.within(112 * .95, 112 * 1.05);
      });
  });
  it('should render a state diagram when useMaxWidth is false', () => {
    renderGraph(
      `
    stateDiagram
    [*] --> State1
    State1 --> [*]
      `,
      { state: { useMaxWidth: false } }
    );
    cy.get('svg')
      .should((svg) => {
        const height = parseFloat(svg.attr('height'));
        const width = parseFloat(svg.attr('width'));
        expect(height).to.eq(139);
        // use within because the absolute value can be slightly different depending on the environment ±5%
        expect(width).to.be.within(112 * .95, 112 * 1.05);
        expect(svg).to.not.have.attr('style');
      });
  });
});


text:
package com.marksomnian.icat;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Marks Polakovs <totallyupdown@gmail.com>
 */
public class IcatSettings implements Serializable, Cloneable {

    @Override
    public IcatSettings clone() throws CloneNotSupportedException {
        IcatSettings result = new IcatSettings();
        result.setThemeClassName(this.getThemeClassName());
        return result;
    }
    private static final long serialVersionUID = 14475888255L;
    private String themeClassName;

    public String getThemeClassName() {
        return themeClassName;
    }

    public void setThemeClassName(String themeClassName) {
        this.themeClassName = themeClassName;
    }
    public void save() {
        try {
            FileOutputStream fos = new FileOutputStream(new File("default.icat.settings"));
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(this);
            Utils.closeIgnoringException(fos);
            Utils.closeIgnoringException(oos);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(IcatSettings.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(IcatSettings.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public static void save(IcatSettings instance) {
        try {
            FileOutputStream fos = new FileOutputStream(new File("default.icat.settings"));
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(instance);
            Utils.closeIgnoringException(fos);
            Utils.closeIgnoringException(oos);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(IcatSettings.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(IcatSettings.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    /**
     * Loads settings from a file named icat.settings in the
     * program's directory;
     * @return loaded settings
     * @throws FileNotFoundException if the file icat.settings
     * cannot be found. At this point, load some defaults and save them.
     * @throws IOException if an I/O error occurs;
     * @throws ClassNotFoundException shouldn't do
     * @throws ClassCastException if the object stored in the file is not an
     * instance of icat.settings, meaning that there is a file
     * named icat.settings in the directory from another program,
     * feel free to decide how to deal with it.
     * @see IcatSettings#save
     */
    public static IcatSettings load() throws FileNotFoundException, IOException, ClassNotFoundException, ClassCastException {
            FileInputStream fos = new FileInputStream(new File("default.icat.settings"));
            ObjectInputStream oos = new ObjectInputStream(fos);
            IcatSettings settings = (IcatSettings)oos.readObject();
            Utils.closeIgnoringException(fos);
            Utils.closeIgnoringException(oos);
            return settings;
    }
}


text:
require 'open-uri'

module ICharger
  module Log

    class File

      attr_reader :rows

      # Determines if the file at the given URI is an iCharger log file.
      #
      # @param uri URI to file to read
      # @return [ICharger::Log::File] loaded file if the file is an iCharger log file, nil otherwise
      def self.icharger?(uri)
        File.new(uri) rescue nil
      end

      def initialize(uri)
        open(uri, 'r') do |file|
          @rows = file.readlines.map { |row| ICharger::Log::Row.new(row) }
        end
        raise ArgumentError, 'No records found in file' if @rows.empty?
      rescue => e
        raise ArgumentError, "File does not appear to be an iCharger log (#{e})"
      end

      # Gets the charger channel number.
      #
      # @return [Number] charger channel number
      def channel
        @rows.first.channel
      end

      # Gets the duration of the log, in seconds.
      #
      # @return [Float] duration of the log, in seconds
      def duration
        @rows.last.time / 10000.0
      end

      def milliseconds
        @rows.map(&:time)
      end

      def currents
        @rows.map(&:current)
      end

      def input_voltages
        @rows.map(&:input_voltage)
      end

      def pack_voltages
        @rows.map(&:pack_voltage)
      end

      def capacities
        @rows.map(&:capacity)
      end

      def internal_temperatures?
        @rows.map(&:internal_temperature?).any? { |t| t }
      end

      def internal_temperatures(unit = :c)
        @rows.each_with_object(unit).map(&:internal_temperature)
      end

      def external_temperatures?
        @rows.map(&:external_temperature?).any? { |t| t }
      end

      def external_temperatures(unit = :c)
        @rows.each_with_object(unit).map(&:internal_temperature)
      end

      def cell_voltages(index)
        @rows.each_with_object(index).map(&:cell_voltage)
      end

      def cell_count
        @rows.map(&:cell_count).max
      end

    end

  end
end


text:
class CreateAppointments < ActiveRecord::Migration[5.0]
  def change
    create_table :appointments do |t|
      t.datetime :appointment_date
      t.integer :physician_id
      t.integer :patient_id

      t.timestamps
    end
  end
end


text:
<?php

use ClassPreloader\ClassLoader;

return ClassLoader::getIncludes(function (ClassLoader $loader) {
    $loader->register();
    new Foo();
});


text:
from __future__ import absolute_import

import six

from django.core.urlresolvers import reverse

from sentry.api.serializers import serialize
from sentry.models import Integration, Repository, RepositoryProjectPathConfig
from sentry.testutils import APITestCase

class OrganizationIntegrationRepositoryProjectPathConfigTest(APITestCase):
    def setUp(self):
        super(OrganizationIntegrationRepositoryProjectPathConfigTest, self).setUp()

        self.login_as(user=self.user)
        self.org = self.create_organization(owner=self.user, name="baz")
        self.team = self.create_team(organization=self.org, name="Mariachi Band")
        self.project = self.create_project(organization=self.org, teams=[self.team], name="Bengal")
        self.integration = Integration.objects.create(
            provider="github", name="Example", external_id="abcd"
        )
        self.org_integration = self.integration.add_organization(self.org, self.user)
        self.repo = Repository.objects.create(
            name="example", organization_id=self.org.id, integration_id=self.integration.id
        )
        self.config = RepositoryProjectPathConfig.objects.create(
            repository_id=six.text_type(self.repo.id),
            project_id=six.text_type(self.project.id),
            organization_integration_id=six.text_type(self.org_integration.id),
            stack_root="/stack/root",
            source_root="/source/root",
            default_branch="master",
        )

        self.url = reverse(
            "sentry-api-0-organization-integration-repository-project-path-config-details",
            args=[self.org.slug, self.integration.id, self.config.id],
        )

    def make_put(self, data):
        # reconstruct the original object
        config_data = serialize(self.config, self.user)
        config_data["repositoryId"] = six.text_type(self.repo.id)
        # update with the new fields
        config_data.update(data)
        return self.client.put(self.url, config_data)

    def test_basic_delete(self):
        resp = self.client.delete(self.url)
        assert resp.status_code == 204
        assert not RepositoryProjectPathConfig.objects.filter(
            id=six.text_type(self.config.id)
        ).exists()

    def test_basic_edit(self):
        resp = self.make_put({"sourceRoot": "newRoot"})
        assert resp.status_code == 200
        assert resp.data["id"] == six.text_type(self.config.id)
        assert resp.data["sourceRoot"] == "newRoot"


text:
namespace autofill {
struct PasswordForm;
}

class PasswordUIView;

class Profile;

// Contains the common logic used by a PasswordUIView to
// interact with PasswordStore. It provides completion callbacks for
// PasswordStore operations and updates the view on PasswordStore changes.
class PasswordManagerPresenter : public PasswordStore::Observer {
 public:
  // |password_view| the UI view that owns this presenter, must not be NULL.
  explicit PasswordManagerPresenter(PasswordUIView* password_view);
  virtual ~PasswordManagerPresenter();

  // PasswordStore::Observer implementation.
  virtual void OnLoginsChanged() OVERRIDE;

  // Repopulates the password and exception entries.
  void UpdatePasswordLists();

  void Initialize();

  // Gets the password entry at |index|.
  const autofill::PasswordForm& GetPassword(size_t index);

  // Gets the password exception entry at |index|.
  const autofill::PasswordForm& GetPasswordException(size_t index);

  // Removes the saved password entry at |index|.
  // |index| the entry index to be removed.
  void RemoveSavedPassword(size_t index);

  // Removes the saved password exception entry at |index|.
  // |index| the entry index to be removed.
  void RemovePasswordException(size_t index);

  // Requests the plain text password for entry at |index| to be revealed.
  // |index| The index of the entry.
  void RequestShowPassword(size_t index);

 private:
  friend class PasswordManagerPresenterTest;

  // Returns the password store associated with the currently active profile.
  PasswordStore* GetPasswordStore();

  // Returns true if the user needs to be authenticated before a plaintext
  // password is revealed.
  bool IsAuthenticationRequired();

  // Sets the password and exception list of the UI view.
  void SetPasswordList();
  void SetPasswordExceptionList();

  // A short class to mediate requests to the password store.
  class ListPopulater : public PasswordStoreConsumer {
   public:
    explicit ListPopulater(PasswordManagerPresenter* page);
    virtual ~ListPopulater();

    // Send a query to the password store to populate a list.
    virtual void Populate() = 0;

   protected:
    PasswordManagerPresenter* page_;
    CancelableRequestProvider::Handle pending_login_query_;
  };

  // A short class to mediate requests to the password store for passwordlist.
  class PasswordListPopulater : public ListPopulater {
   public:
    explicit PasswordListPopulater(PasswordManagerPresenter* page);

    // Send a query to the password store to populate a password list.
    virtual void Populate() OVERRIDE;

    // Send the password store's reply back to the handler.
    virtual void OnPasswordStoreRequestDone(
        CancelableRequestProvider::Handle handle,
        const std::vector<autofill::PasswordForm*>& result) OVERRIDE;
    virtual void OnGetPasswordStoreResults(
        const std::vector<autofill::PasswordForm*>& results) OVERRIDE;
  };

  // A short class to mediate requests to the password store for exceptions.
  class PasswordExceptionListPopulater : public ListPopulater {
   public:
    explicit PasswordExceptionListPopulater(PasswordManagerPresenter* page);

    // Send a query to the password store to populate a passwordException list.
    virtual void Populate() OVERRIDE;

    // Send the password store's reply back to the handler.
    virtual void OnPasswordStoreRequestDone(
        CancelableRequestProvider::Handle handle,
        const std::vector<autofill::PasswordForm*>& result) OVERRIDE;
    virtual void OnGetPasswordStoreResults(
        const std::vector<autofill::PasswordForm*>& results) OVERRIDE;
  };

  // Password store consumer for populating the password list and exceptions.
  PasswordListPopulater populater_;
  PasswordExceptionListPopulater exception_populater_;

  ScopedVector<autofill::PasswordForm> password_list_;
  ScopedVector<autofill::PasswordForm> password_exception_list_;

  // Whether to show stored passwords or not.
  BooleanPrefMember show_passwords_;

  // Indicates whether or not the password manager should require the user to
  // reauthenticate before revealing plaintext passwords.
  bool require_reauthentication_;

  // The last time the user was successfully authenticated.
  // Used to determine whether or not to reveal plaintext passwords.
  base::TimeTicks last_authentication_time_;

  // UI view that owns this presenter.
  PasswordUIView* password_view_;

  DISALLOW_COPY_AND_ASSIGN(PasswordManagerPresenter);
};

#endif  // CHROME_BROWSER_UI_PASSWORDS_PASSWORD_MANAGER_PRESENTER_H_


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

package com.google.devtools.build.lib.bazel.rules;

import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.analysis.BlazeDirectories;
import com.google.devtools.build.lib.analysis.ConfiguredRuleClassProvider;
import com.google.devtools.build.lib.bazel.rules.cpp.BazelCppRuleClasses;
import com.google.devtools.build.lib.bazel.rules.sh.BazelShRuleClasses;
import com.google.devtools.build.lib.remote.options.RemoteOptions;
import com.google.devtools.build.lib.rules.cpp.CcSkyframeFdoSupportFunction;
import com.google.devtools.build.lib.rules.cpp.CcSkyframeFdoSupportValue;
import com.google.devtools.build.lib.rules.cpp.CppOptions;
import com.google.devtools.build.lib.rules.java.JavaOptions;
import com.google.devtools.build.lib.runtime.BlazeModule;
import com.google.devtools.build.lib.runtime.BlazeRuntime;
import com.google.devtools.build.lib.runtime.Command;
import com.google.devtools.build.lib.runtime.CommandEnvironment;
import com.google.devtools.build.lib.runtime.WorkspaceBuilder;
import com.google.devtools.build.lib.server.FailureDetails.FailureDetail;
import com.google.devtools.build.lib.server.FailureDetails.RemoteExecution;
import com.google.devtools.build.lib.server.FailureDetails.RemoteExecution.Code;
import com.google.devtools.build.lib.util.AbruptExitException;
import com.google.devtools.build.lib.util.DetailedExitCode;
import com.google.devtools.build.lib.util.ResourceFileLoader;
import com.google.devtools.common.options.Option;
import com.google.devtools.common.options.OptionDocumentationCategory;
import com.google.devtools.common.options.OptionEffectTag;
import com.google.devtools.common.options.OptionMetadataTag;
import com.google.devtools.common.options.OptionsBase;
import java.io.IOException;

/** Module implementing the rule set of Bazel. */
public final class BazelRulesModule extends BlazeModule {

  /**
   * This is where deprecated options used by both Bazel and Blaze but only needed for the build
   * command go to die.
   */
  @SuppressWarnings("deprecation") // These fields have no JavaDoc by design
  public static class BuildGraveyardOptions extends OptionsBase {

    @Option(
        name = "incompatible_disable_crosstool_file",
        defaultValue = "true",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.LOADING_AND_ANALYSIS},
        metadataTags = {OptionMetadataTag.DEPRECATED, OptionMetadataTag.INCOMPATIBLE_CHANGE},
        help = "Deprecated no-op.")
    public boolean disableCrosstool;

    @Option(
        name = "incompatible_disable_legacy_crosstool_fields",
        oldName = "experimental_disable_legacy_crosstool_fields",
        defaultValue = "true",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.LOADING_AND_ANALYSIS},
        metadataTags = {OptionMetadataTag.INCOMPATIBLE_CHANGE},
        help = "Deprecated no-op.")
    public boolean disableLegacyCrosstoolFields;

    @Option(
        name = "incompatible_require_feature_configuration_for_pic",
        defaultValue = "true",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.LOADING_AND_ANALYSIS},
        metadataTags = {OptionMetadataTag.DEPRECATED, OptionMetadataTag.INCOMPATIBLE_CHANGE},
        help = "Deprecated no-op.")
    public boolean requireFeatureConfigurationForPic;

    @Option(
        name = "incompatible_disable_depset_in_cc_user_flags",
        defaultValue = "true",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.LOADING_AND_ANALYSIS},
        metadataTags = {OptionMetadataTag.DEPRECATED, OptionMetadataTag.INCOMPATIBLE_CHANGE},
        help = "Deprecated no-op.")
    public boolean disableDepsetInUserFlags;

    @Option(
        name = "incompatible_dont_emit_static_libgcc",
        oldName = "experimental_dont_emit_static_libgcc",
        defaultValue = "true",
        documentationCategory = OptionDocumentationCategory.TOOLCHAIN,
        effectTags = {OptionEffectTag.ACTION_COMMAND_LINES, OptionEffectTag.LOADING_AND_ANALYSIS},
        metadataTags = {OptionMetadataTag.DEPRECATED, OptionMetadataTag.INCOMPATIBLE_CHANGE},
        help = "Deprecated no-op.")
    public boolean disableEmittingStaticLibgcc;

    @Option(
        name = "incompatible_linkopts_in_user_link_flags",
        defaultValue = "true",
        documentationCategory = OptionDocumentationCategory.TOOLCHAIN,
        effectTags = {OptionEffectTag.ACTION_COMMAND_LINES, OptionEffectTag.LOADING_AND_ANALYSIS},
        metadataTags = {OptionMetadataTag.DEPRECATED, OptionMetadataTag.INCOMPATIBLE_CHANGE},
        help = "Deprecated no-op.")
    public boolean enableLinkoptsInUserLinkFlags;

    @Option(
        name = "incompatible_disable_runtimes_filegroups",
        defaultValue = "false",
        documentationCategory = OptionDocumentationCategory.TOOLCHAIN,
        effectTags = {OptionEffectTag.ACTION_COMMAND_LINES, OptionEffectTag.LOADING_AND_ANALYSIS},
        metadataTags = {OptionMetadataTag.DEPRECATED, OptionMetadataTag.INCOMPATIBLE_CHANGE},
        help = "Deprecated no-op.")
    public boolean disableRuntimesFilegroups;

    @Option(
        name = "incompatible_disable_tools_defaults_package",
        defaultValue = "false",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.AFFECTS_OUTPUTS, OptionEffectTag.LOADING_AND_ANALYSIS},
        metadataTags = {OptionMetadataTag.DEPRECATED, OptionMetadataTag.INCOMPATIBLE_CHANGE},
        help = "Deprecated no-op.")
    public boolean incompatibleDisableInMemoryToolsDefaultsPackage;

    @Option(
        name = "incompatible_disable_sysroot_from_configuration",
        defaultValue = "true",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.LOADING_AND_ANALYSIS},
        metadataTags = {OptionMetadataTag.DEPRECATED, OptionMetadataTag.INCOMPATIBLE_CHANGE},
        help = "Deprecated no-op.")
    public boolean disableSysrootFromConfiguration;

    @Option(
        name = "incompatible_provide_cc_toolchain_info_from_cc_toolchain_suite",
        defaultValue = "true",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.LOADING_AND_ANALYSIS},
        metadataTags = {OptionMetadataTag.DEPRECATED, OptionMetadataTag.INCOMPATIBLE_CHANGE},
        help = "Deprecated no-op.")
    public boolean provideCcToolchainInfoFromCcToolchainSuite;

    @Option(
        name = "incompatible_disable_cc_toolchain_label_from_crosstool_proto",
        defaultValue = "true",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.LOADING_AND_ANALYSIS, OptionEffectTag.EAGERNESS_TO_EXIT},
        metadataTags = {OptionMetadataTag.DEPRECATED, OptionMetadataTag.INCOMPATIBLE_CHANGE},
        help = "Deprecated no-op.")
    public boolean disableCcToolchainFromCrosstool;

    @Option(
        name = "incompatible_disable_cc_configuration_make_variables",
        defaultValue = "true",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.UNKNOWN},
        metadataTags = {
          OptionMetadataTag.INCOMPATIBLE_CHANGE,
          OptionMetadataTag.DEPRECATED,
        },
        help = "Deprecated no-op.")
    public boolean disableMakeVariables;

    @Option(
        name = "incompatible_disable_legacy_flags_cc_toolchain_api",
        defaultValue = "true",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.LOADING_AND_ANALYSIS},
        metadataTags = {OptionMetadataTag.INCOMPATIBLE_CHANGE, OptionMetadataTag.DEPRECATED},
        help =
            "Flag for disabling the legacy cc_toolchain Starlark API for accessing legacy "
                + "CROSSTOOL fields.")
    public boolean disableLegacyFlagsCcToolchainApi;

    @Option(
        name = "incompatible_enable_legacy_cpp_toolchain_skylark_api",
        defaultValue = "true",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.UNKNOWN},
        metadataTags = {OptionMetadataTag.INCOMPATIBLE_CHANGE, OptionMetadataTag.DEPRECATED},
        help = "Obsolete, no effect.")
    public boolean enableLegacyToolchainStarlarkApi;

    @Option(
        name = "incompatible_disable_legacy_cpp_toolchain_skylark_api",
        defaultValue = "true",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.UNKNOWN},
        metadataTags = {OptionMetadataTag.INCOMPATIBLE_CHANGE, OptionMetadataTag.DEPRECATED},
        help = "Obsolete, no effect.")
    public boolean disableLegacyToolchainStarlarkApi;

    @Option(
        name = "incompatible_enable_profile_by_default",
        defaultValue = "true",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.UNKNOWN},
        metadataTags = {OptionMetadataTag.INCOMPATIBLE_CHANGE},
        help = "No-op.")
    public boolean enableProfileByDefault;

    @Option(
        name = "legacy_spawn_scheduler",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.UNKNOWN},
        defaultValue = "false",
        deprecationWarning =
            "The --legacy_spawn_scheduler flag is a no-op and will be removed soon.",
        help = "Was used to enable the old spawn scheduler. Now a no-op.")
    public boolean legacySpawnScheduler;

    @Option(
        name = "experimental_multi_threaded_digest",
        defaultValue = "true",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.UNKNOWN},
        help = "No-op")
    public boolean experimentalMultiThreadedDigest;

    @Option(
        name = "incompatible_override_toolchain_transition",
        defaultValue = "true",
        deprecationWarning = "This is now always set, please remove this flag.",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = OptionEffectTag.UNKNOWN,
        help = "Deprecated, this is no longer in use and should be removed.")
    public boolean overrideToolchainTransition;

    @Option(
        name = "experimental_dynamic_execution_cpu_limited",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {
          OptionEffectTag.EXECUTION,
          OptionEffectTag.HOST_MACHINE_RESOURCE_OPTIMIZATIONS
        },
        defaultValue = "false",
        help =
            "Deprecated no-op. Use --experimental_dynamic_local_load_factor instead, with the "
                + "values 0 for false and 1 for true, or with a value in between.")
    public boolean cpuLimited;

    @Option(
        name = "dynamic_worker_strategy",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.UNKNOWN},
        metadataTags = {OptionMetadataTag.DEPRECATED},
        defaultValue = "",
        help = "Deprecated no-op. Please use --dynamic_local_strategy=worker,....")
    @Deprecated
    public String dynamicWorkerStrategy;

    @Option(
        name = "experimental_dynamic_skip_first_build",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.UNKNOWN},
        defaultValue = "false",
        help = "Deprecated no-op. Use --experimental_dynamic_local_load_factor instead.")
    @Deprecated
    public boolean skipFirstBuild;
  }

  /** This is where deprecated Bazel-specific options only used by the build command go to die. */
  @SuppressWarnings("deprecation") // These fields have no JavaDoc by design
  public static final class BazelBuildGraveyardOptions extends BuildGraveyardOptions {
    @Option(
        name = "incompatible_load_python_rules_from_bzl",
        defaultValue = "false",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.LOADING_AND_ANALYSIS},
        metadataTags = {OptionMetadataTag.INCOMPATIBLE_CHANGE},
        help = "Deprecated no-op.")
    public boolean loadPythonRulesFromBzl;

    @Option(
        name = "incompatible_load_proto_rules_from_bzl",
        defaultValue = "false",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.LOADING_AND_ANALYSIS},
        metadataTags = {OptionMetadataTag.INCOMPATIBLE_CHANGE},
        help = "Deprecated no-op.")
    public boolean loadProtoRulesFromBzl;

    @Option(
        name = "incompatible_load_java_rules_from_bzl",
        defaultValue = "false",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.LOADING_AND_ANALYSIS},
        metadataTags = {OptionMetadataTag.INCOMPATIBLE_CHANGE},
        help = "Deprecated no-op.")
    public boolean loadJavaRulesFromBzl;

    @Option(
        name = "make_variables_source",
        defaultValue = "configuration",
        metadataTags = {OptionMetadataTag.HIDDEN, OptionMetadataTag.DEPRECATED},
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.UNKNOWN})
    public String makeVariableSource;

    @Option(
        name = "incompatible_cc_coverage",
        defaultValue = "true",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {
          OptionEffectTag.UNKNOWN,
        },
        oldName = "experimental_cc_coverage",
        metadataTags = {OptionMetadataTag.INCOMPATIBLE_CHANGE, OptionMetadataTag.DEPRECATED},
        help = "Obsolete, no effect.")
    public boolean useGcovCoverage;

    @Deprecated
    @Option(
        name = "direct_run",
        defaultValue = "true",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.UNKNOWN},
        metadataTags = {OptionMetadataTag.DEPRECATED},
        help = "Deprecated no-op.")
    public boolean directRun;

    @Deprecated
    @Option(
        name = "glibc",
        defaultValue = "null",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.UNKNOWN},
        metadataTags = {OptionMetadataTag.DEPRECATED},
        help = "Deprecated no-op.")
    public String glibc;

    @Deprecated
    @Option(
        name = "experimental_shortened_obj_file_path",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.EXECUTION},
        defaultValue = "true",
        help = "This option is deprecated and has no effect.")
    public boolean shortenObjFilePath;

    @Option(
        name = "force_ignore_dash_static",
        defaultValue = "false",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.LOADING_AND_ANALYSIS, OptionEffectTag.AFFECTS_OUTPUTS},
        help = "noop")
    public boolean forceIgnoreDashStatic;

    @Option(
        name = "experimental_profile_action_counts",
        defaultValue = "true",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.UNKNOWN},
        help = "No-op.")
    public boolean enableActionCountProfile;

    @Option(
        name = "incompatible_remove_binary_profile",
        defaultValue = "true",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.UNKNOWN},
        metadataTags = {OptionMetadataTag.INCOMPATIBLE_CHANGE},
        help = "No-op.")
    public boolean removeBinaryProfile;

    @Option(
        name = "experimental_post_profile_started_event",
        defaultValue = "true",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.UNKNOWN},
        help = "No-op.")
    public boolean postProfileStartedEvent;

    @Option(
        name = "incompatible_dont_use_javasourceinfoprovider",
        defaultValue = "false",
        documentationCategory = OptionDocumentationCategory.UNCATEGORIZED,
        effectTags = {OptionEffectTag.UNKNOWN},
        metadataTags = {OptionMetadataTag.INCOMPATIBLE_CHANGE},
        help = "No-op")
    public boolean dontUseJavaSourceInfoProvider;

    @Option(
        name = "experimental_local_memory_estimate",
        defaultValue = "false",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        metadataTags = {OptionMetadataTag.DEPRECATED},
        effectTags = {OptionEffectTag.NO_OP},
        help = "No-op.")
    public boolean localMemoryEstimate;
  }

  /**
   * This is where deprecated options which need to be available for all commands go to die. If you
   * want to graveyard an all-command option specific to Blaze or Bazel, create a subclass.
   */
  public static final class AllCommandGraveyardOptions extends OptionsBase {
    // Historically passed to all Bazel commands by certain tools.
    @Option(
        name = "experimental_allow_top_level_aspects_parameters",
        defaultValue = "true",
        documentationCategory = OptionDocumentationCategory.STARLARK_SEMANTICS,
        metadataTags = {OptionMetadataTag.DEPRECATED, OptionMetadataTag.EXPERIMENTAL},
        effectTags = {OptionEffectTag.NO_OP},
        help = "No-op")
    public boolean experimentalAllowTopLevelAspectsParameters;

    @Option(
        name = "bes_best_effort",
        defaultValue = "false",
        deprecationWarning =
            "BES best effort upload has been removed. The flag has no more "
                + "functionality attached to it and will be removed in a future release.",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.AFFECTS_OUTPUTS},
        help = "No-op")
    public boolean besBestEffort;

    @Option(
        name = "distinct_host_configuration",
        defaultValue = "false",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.NO_OP},
        metadataTags = {OptionMetadataTag.INCOMPATIBLE_CHANGE},
        help = "No-op.")
    public boolean useDistinctHostConfiguration;

    @Option(
        name = "experimental_keep_config_nodes_on_analysis_discard",
        defaultValue = "false",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.NO_OP},
        help = "No-op")
    public boolean keepConfigNodes;

    @Option(
        name = "incompatible_disable_managed_directories",
        defaultValue = "false",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.NO_OP},
        help = "No-op")
    public boolean incompatibleDisableManagedDirectories;

    @Option(
        name = "experimental_use_event_based_build_completion_status",
        defaultValue = "true",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        metadataTags = OptionMetadataTag.EXPERIMENTAL,
        effectTags = {OptionEffectTag.LOADING_AND_ANALYSIS, OptionEffectTag.EXECUTION},
        help = "No-op")
    public boolean useEventBasedBuildCompletionStatus;

    // Moved here 2022/08/29
    @Option(
        name = "incompatible_disable_third_party_license_checking",
        defaultValue = "true",
        documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
        effectTags = {OptionEffectTag.NO_OP},
        help = "No-op")
    public boolean incompatibleDisableThirdPartyLicenseChecking;
  }

  @Override
  public void initializeRuleClasses(ConfiguredRuleClassProvider.Builder builder) {
    BazelRuleClassProvider.setup(builder);

    try {
      // Load auto-configuration files, it is made outside of the rule class provider so that it
      // will not be loaded for our Java tests.
      builder.addWorkspaceFileSuffix(
          ResourceFileLoader.loadResource(BazelCppRuleClasses.class, "cc_configure.WORKSPACE"));
      builder.addWorkspaceFileSuffix(
          ResourceFileLoader.loadResource(BazelRulesModule.class, "xcode_configure.WORKSPACE"));
      builder.addWorkspaceFileSuffix(
          ResourceFileLoader.loadResource(BazelShRuleClasses.class, "sh_configure.WORKSPACE"));

      // Load rules_license, which is needed for license attestations for many rules, including
      // things in @bazel_tools
      builder.addWorkspaceFileSuffix(
          ResourceFileLoader.loadResource(BazelRulesModule.class, "rules_license.WORKSPACE"));
    } catch (IOException e) {
      throw new IllegalStateException(e);
    }
  }

  @Override
  public void beforeCommand(CommandEnvironment env) throws AbruptExitException {
    validateRemoteOutputsMode(env);
  }

  @Override
  public void workspaceInit(
      BlazeRuntime runtime, BlazeDirectories directories, WorkspaceBuilder builder) {
    builder.addSkyFunction(
        CcSkyframeFdoSupportValue.SKYFUNCTION, new CcSkyframeFdoSupportFunction(directories));
  }

  @Override
  public Iterable<Class<? extends OptionsBase>> getCommandOptions(Command command) {
    return "build".equals(command.name())
        ? ImmutableList.of(BazelBuildGraveyardOptions.class, AllCommandGraveyardOptions.class)
        : ImmutableList.of(AllCommandGraveyardOptions.class);
  }

  private static void validateRemoteOutputsMode(CommandEnvironment env) throws AbruptExitException {
    RemoteOptions remoteOptions = env.getOptions().getOptions(RemoteOptions.class);
    if (remoteOptions == null) {
      return;
    }
    if (!remoteOptions.remoteOutputsMode.downloadAllOutputs()) {
      JavaOptions javaOptions = env.getOptions().getOptions(JavaOptions.class);
      if (javaOptions != null && !javaOptions.inmemoryJdepsFiles) {
        throw createRemoteExecutionExitException(
            "--experimental_remote_download_outputs=minimal requires"
                + " --experimental_inmemory_jdeps_files to be enabled",
            Code.REMOTE_DOWNLOAD_OUTPUTS_MINIMAL_WITHOUT_INMEMORY_JDEPS);
      }
      CppOptions cppOptions = env.getOptions().getOptions(CppOptions.class);
      if (cppOptions != null && !cppOptions.inmemoryDotdFiles) {
        throw createRemoteExecutionExitException(
            "--experimental_remote_download_outputs=minimal requires"
                + " --experimental_inmemory_dotd_files to be enabled",
            Code.REMOTE_DOWNLOAD_OUTPUTS_MINIMAL_WITHOUT_INMEMORY_DOTD);
      }
    }
  }

  private static AbruptExitException createRemoteExecutionExitException(
      String message, Code remoteExecutionCode) {
    return new AbruptExitException(
        DetailedExitCode.of(
            FailureDetail.newBuilder()
                .setMessage(message)
                .setRemoteExecution(RemoteExecution.newBuilder().setCode(remoteExecutionCode))
                .build()));
  }
}


text:
from numpy import linspace
from scipy.special import jn

from chaco.api import ArrayPlotData, Plot
from enable.component_editor import ComponentEditor
from traits.api import Dict, Enum, HasTraits, Instance
from traitsui.api import Item, View

class DataChooser(HasTraits):

    plot = Instance(Plot)
    data_name = Enum("jn0", "jn1", "jn2")
    traits_view = View(Item('data_name', label="Y data"),
                       Item('plot', editor=ComponentEditor(), show_label=False),
                       width=800, height=600, resizable=True,
                       title="Data Chooser")

    def __init__(self):
        x = linspace(-5, 10, 100)
        self.data = {"jn0": jn(0, x),
                     "jn1": jn(1, x),
                     "jn2": jn(2, x)}

        # Create the data and the PlotData object
        self.plotdata = ArrayPlotData(x=x, y=self.data["jn0"])

        # Create a Plot and associate it with the PlotData
        plot = Plot(self.plotdata)
        # Create a line plot in the Plot
        plot.plot(("x", "y"), type="line", color="blue")
        self.plot = plot

    def _data_name_changed(self, old, new):
        self.plotdata.set_data("y", self.data[self.data_name])

#===============================================================================
# demo object that is used by the demo.py application.
#===============================================================================
demo=DataChooser()
if __name__ == "__main__":
    demo.configure_traits()