text:
package com.siyeh.ig.psiutils;

import com.intellij.psi.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.HashMap;
import java.util.Map;

public class ParenthesesUtils {

  public static final Map<IElementType, IElementType> tokenMap = new HashMap<>();

  private ParenthesesUtils() {}

  public static final int PARENTHESIZED_PRECEDENCE = 0;
  public static final int LITERAL_PRECEDENCE = 0;
  public static final int METHOD_CALL_PRECEDENCE = 1;
  public static final int POSTFIX_PRECEDENCE = 2;
  public static final int PREFIX_PRECEDENCE = 3;
  public static final int TYPE_CAST_PRECEDENCE = 4;
  public static final int MULTIPLICATIVE_PRECEDENCE = 5;
  public static final int ADDITIVE_PRECEDENCE = 6;
  public static final int SHIFT_PRECEDENCE = 7;
  public static final int RELATIONAL_PRECEDENCE = 8;
  public static final int EQUALITY_PRECEDENCE = 9;
  public static final int BINARY_AND_PRECEDENCE = 10;
  public static final int BINARY_XOR_PRECEDENCE = 11;
  public static final int BINARY_OR_PRECEDENCE = 12;
  public static final int AND_PRECEDENCE = 13;
  public static final int OR_PRECEDENCE = 14;
  public static final int CONDITIONAL_PRECEDENCE = 15;
  public static final int ASSIGNMENT_PRECEDENCE = 16;
  public static final int NUM_PRECEDENCES = 17;

  private static final Map<IElementType, Integer> s_binaryOperatorPrecedence = new HashMap<>(NUM_PRECEDENCES);

  static {
    tokenMap.put(JavaTokenType.PLUSEQ, JavaTokenType.PLUS);
    tokenMap.put(JavaTokenType.MINUSEQ, JavaTokenType.MINUS);
    tokenMap.put(JavaTokenType.ASTERISKEQ, JavaTokenType.ASTERISK);
    tokenMap.put(JavaTokenType.DIVEQ, JavaTokenType.DIV);
    tokenMap.put(JavaTokenType.ANDEQ, JavaTokenType.AND);
    tokenMap.put(JavaTokenType.OREQ, JavaTokenType.OR);
    tokenMap.put(JavaTokenType.XOREQ, JavaTokenType.XOR);
    tokenMap.put(JavaTokenType.PERCEQ, JavaTokenType.PERC);
    tokenMap.put(JavaTokenType.LTLTEQ, JavaTokenType.LTLT);
    tokenMap.put(JavaTokenType.GTGTEQ, JavaTokenType.GTGT);
    tokenMap.put(JavaTokenType.GTGTGTEQ, JavaTokenType.GTGTGT);
  }

  static {
    s_binaryOperatorPrecedence.put(JavaTokenType.PLUS, ADDITIVE_PRECEDENCE);
    s_binaryOperatorPrecedence.put(JavaTokenType.MINUS, ADDITIVE_PRECEDENCE);
    s_binaryOperatorPrecedence.put(JavaTokenType.ASTERISK, MULTIPLICATIVE_PRECEDENCE);
    s_binaryOperatorPrecedence.put(JavaTokenType.DIV, MULTIPLICATIVE_PRECEDENCE);
    s_binaryOperatorPrecedence.put(JavaTokenType.PERC, MULTIPLICATIVE_PRECEDENCE);
    s_binaryOperatorPrecedence.put(JavaTokenType.ANDAND, AND_PRECEDENCE);
    s_binaryOperatorPrecedence.put(JavaTokenType.OROR, OR_PRECEDENCE);
    s_binaryOperatorPrecedence.put(JavaTokenType.AND, BINARY_AND_PRECEDENCE);
    s_binaryOperatorPrecedence.put(JavaTokenType.OR, BINARY_OR_PRECEDENCE);
    s_binaryOperatorPrecedence.put(JavaTokenType.XOR, BINARY_XOR_PRECEDENCE);
    s_binaryOperatorPrecedence.put(JavaTokenType.LTLT, SHIFT_PRECEDENCE);
    s_binaryOperatorPrecedence.put(JavaTokenType.GTGT, SHIFT_PRECEDENCE);
    s_binaryOperatorPrecedence.put(JavaTokenType.GTGTGT, SHIFT_PRECEDENCE);
    s_binaryOperatorPrecedence.put(JavaTokenType.GT, RELATIONAL_PRECEDENCE);
    s_binaryOperatorPrecedence.put(JavaTokenType.GE, RELATIONAL_PRECEDENCE);
    s_binaryOperatorPrecedence.put(JavaTokenType.LT, RELATIONAL_PRECEDENCE);
    s_binaryOperatorPrecedence.put(JavaTokenType.LE, RELATIONAL_PRECEDENCE);
    s_binaryOperatorPrecedence.put(JavaTokenType.EQEQ, EQUALITY_PRECEDENCE);
    s_binaryOperatorPrecedence.put(JavaTokenType.NE, EQUALITY_PRECEDENCE);
  }

  public static String getText(@NotNull PsiExpression expression, int precedence) {
    if (getPrecedence(expression) >= precedence) {
      return '(' + expression.getText() + ')';
    }
    return expression.getText();
  }

  @Nullable public static PsiElement getParentSkipParentheses(PsiElement element) {
    PsiElement parent = element.getParent();
    while (parent instanceof PsiParenthesizedExpression || parent instanceof PsiTypeCastExpression) {
      parent = parent.getParent();
    }
    return parent;
  }

  @Nullable
  public static PsiExpression stripParentheses(@Nullable PsiExpression expression) {
    while (expression instanceof PsiParenthesizedExpression) {
      final PsiParenthesizedExpression parenthesizedExpression = (PsiParenthesizedExpression)expression;
      expression = parenthesizedExpression.getExpression();
    }
    return expression;
  }

  public static boolean isCommutativeOperator(@NotNull IElementType token) {
    return !(token.equals(JavaTokenType.MINUS) ||
             token.equals(JavaTokenType.DIV) ||
             token.equals(JavaTokenType.PERC) ||
             token.equals(JavaTokenType.LTLT) ||
             token.equals(JavaTokenType.GTGT) ||
             token.equals(JavaTokenType.GTGTGT));
  }

  public static boolean isAssociativeOperation(PsiPolyadicExpression expression) {
    final IElementType tokenType = expression.getOperationTokenType();
    final PsiType type = expression.getType();
    final PsiPrimitiveType primitiveType;
    if (type instanceof PsiClassType) {
      primitiveType = PsiPrimitiveType.getUnboxedType(type);
      if (primitiveType == null) {
        return false;
      }
    } else if (type instanceof PsiPrimitiveType) {
      primitiveType = (PsiPrimitiveType)type;
    } else {
      return false;
    }
    if (JavaTokenType.PLUS == tokenType || JavaTokenType.ASTERISK == tokenType) {
      return !PsiType.FLOAT.equals(primitiveType) && !PsiType.DOUBLE.equals(primitiveType);
    } else if (JavaTokenType.EQEQ == tokenType || JavaTokenType.NE == tokenType) {
      return PsiType.BOOLEAN.equals(primitiveType);
    } else if (JavaTokenType.AND == tokenType || JavaTokenType.OR == tokenType || JavaTokenType.XOR == tokenType) {
      return true;
    } else if (JavaTokenType.OROR == tokenType || JavaTokenType.ANDAND == tokenType) {
      return true;
    }
    return false;
  }

  public static int getPrecedence(PsiExpression expression) {
    if (expression instanceof PsiThisExpression ||
        expression instanceof PsiLiteralExpression ||
        expression instanceof PsiSuperExpression ||
        expression instanceof PsiClassObjectAccessExpression ||
        expression instanceof PsiArrayAccessExpression ||
        expression instanceof PsiArrayInitializerExpression) {
      return LITERAL_PRECEDENCE;
    }
    if (expression instanceof PsiReferenceExpression) {
      final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)expression;
      if (referenceExpression.getQualifier() != null) {
        return METHOD_CALL_PRECEDENCE;
      }
      else {
        return LITERAL_PRECEDENCE;
      }
    }
    if (expression instanceof PsiMethodCallExpression || expression instanceof PsiNewExpression) {
      return METHOD_CALL_PRECEDENCE;
    }
    if (expression instanceof PsiTypeCastExpression) {
      return TYPE_CAST_PRECEDENCE;
    }
    if (expression instanceof PsiPrefixExpression) {
      return PREFIX_PRECEDENCE;
    }
    if (expression instanceof PsiPostfixExpression) {
      return POSTFIX_PRECEDENCE;
    }
    if (expression instanceof PsiPolyadicExpression) {
      final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression)expression;
      return getPrecedenceForOperator(polyadicExpression.getOperationTokenType());
    }
    if (expression instanceof PsiInstanceOfExpression) {
      return RELATIONAL_PRECEDENCE;
    }
    if (expression instanceof PsiConditionalExpression) {
      return CONDITIONAL_PRECEDENCE;
    }
    if (expression instanceof PsiAssignmentExpression) {
      return ASSIGNMENT_PRECEDENCE;
    }
    if (expression instanceof PsiParenthesizedExpression) {
      return PARENTHESIZED_PRECEDENCE;
    }
    return -1;
  }

  public static int getPrecedenceForOperator(@NotNull IElementType operator) {
    final Integer precedence = s_binaryOperatorPrecedence.get(operator);
    if (precedence == null) {
      throw new IllegalArgumentException("unknown operator: " + operator);
    }
    return precedence.intValue();
  }

  public static void removeParentheses(@NotNull PsiExpression expression, boolean ignoreClarifyingParentheses) {
    if (expression instanceof PsiMethodCallExpression) {
      final PsiMethodCallExpression methodCall = (PsiMethodCallExpression)expression;
      removeParensFromMethodCallExpression(methodCall, ignoreClarifyingParentheses);
    }
    if (expression instanceof PsiReferenceExpression) {
      final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)expression;
      removeParensFromReferenceExpression(referenceExpression, ignoreClarifyingParentheses);
    }
    if (expression instanceof PsiNewExpression) {
      final PsiNewExpression newExpression = (PsiNewExpression)expression;
      removeParensFromNewExpression(newExpression, ignoreClarifyingParentheses);
    }
    if (expression instanceof PsiAssignmentExpression) {
      final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression)expression;
      removeParensFromAssignmentExpression(assignmentExpression, ignoreClarifyingParentheses);
    }
    if (expression instanceof PsiArrayInitializerExpression) {
      final PsiArrayInitializerExpression arrayInitializerExpression = (PsiArrayInitializerExpression)expression;
      removeParensFromArrayInitializerExpression(arrayInitializerExpression, ignoreClarifyingParentheses);
    }
    if (expression instanceof PsiTypeCastExpression) {
      final PsiTypeCastExpression typeCastExpression = (PsiTypeCastExpression)expression;
      removeParensFromTypeCastExpression(typeCastExpression, ignoreClarifyingParentheses);
    }
    if (expression instanceof PsiArrayAccessExpression) {
      final PsiArrayAccessExpression arrayAccessExpression = (PsiArrayAccessExpression)expression;
      removeParensFromArrayAccessExpression(arrayAccessExpression, ignoreClarifyingParentheses);
    }
    if (expression instanceof PsiPrefixExpression) {
      final PsiPrefixExpression prefixExpression = (PsiPrefixExpression)expression;
      removeParensFromPrefixExpression(prefixExpression, ignoreClarifyingParentheses);
    }
    if (expression instanceof PsiPostfixExpression) {
      final PsiPostfixExpression postfixExpression = (PsiPostfixExpression)expression;
      removeParensFromPostfixExpression(postfixExpression, ignoreClarifyingParentheses);
    }
    if (expression instanceof PsiPolyadicExpression) {
      final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression)expression;
      removeParensFromPolyadicExpression(polyadicExpression, ignoreClarifyingParentheses);
    }
    if (expression instanceof PsiInstanceOfExpression) {
      final PsiInstanceOfExpression instanceofExpression = (PsiInstanceOfExpression)expression;
      removeParensFromInstanceOfExpression(instanceofExpression, ignoreClarifyingParentheses);
    }
    if (expression instanceof PsiConditionalExpression) {
      final PsiConditionalExpression conditionalExpression = (PsiConditionalExpression)expression;
      removeParensFromConditionalExpression(conditionalExpression, ignoreClarifyingParentheses);
    }
    if (expression instanceof PsiParenthesizedExpression) {
      final PsiParenthesizedExpression parenthesizedExpression = (PsiParenthesizedExpression)expression;
      removeParensFromParenthesizedExpression(parenthesizedExpression, ignoreClarifyingParentheses);
    }
  }

  private static void removeParensFromReferenceExpression(@NotNull PsiReferenceExpression referenceExpression,
                                                          boolean ignoreClarifyingParentheses) {
    final PsiExpression qualifier = referenceExpression.getQualifierExpression();
    if (qualifier != null) {
      removeParentheses(qualifier, ignoreClarifyingParentheses);
    }
  }

  private static void removeParensFromParenthesizedExpression(@NotNull PsiParenthesizedExpression parenthesizedExpression,
                                                              boolean ignoreClarifyingParentheses) {
    final PsiExpression body = parenthesizedExpression.getExpression();
    if (body == null) {
      parenthesizedExpression.delete();
      return;
    }
    final PsiElement parent = parenthesizedExpression.getParent();
    if (!(parent instanceof PsiExpression) || parent instanceof PsiParenthesizedExpression ||
        parent instanceof PsiArrayInitializerExpression) {
      final PsiExpression newExpression = (PsiExpression)parenthesizedExpression.replace(body);
      removeParentheses(newExpression, ignoreClarifyingParentheses);
      return;
    }
    else if (parent instanceof PsiArrayAccessExpression) {
      final PsiArrayAccessExpression arrayAccessExpression = (PsiArrayAccessExpression)parent;
      if (parenthesizedExpression == arrayAccessExpression.getIndexExpression()) {
        // use addAfter() + delete() instead of replace() to
        // workaround automatic insertion of parentheses by psi
        final PsiExpression newExpression = (PsiExpression)parent.addAfter(body, parenthesizedExpression);
        parenthesizedExpression.delete();
        removeParentheses(newExpression, ignoreClarifyingParentheses);
        return;
      }
    }
    final PsiExpression parentExpression = (PsiExpression)parent;
    final int parentPrecedence = getPrecedence(parentExpression);
    final int childPrecedence = getPrecedence(body);
    if (parentPrecedence < childPrecedence) {
      final PsiElement bodyParent = body.getParent();
      final PsiParenthesizedExpression newParenthesizedExpression = (PsiParenthesizedExpression)parenthesizedExpression.replace(bodyParent);
      final PsiExpression expression = newParenthesizedExpression.getExpression();
      if (expression != null) {
        removeParentheses(expression, ignoreClarifyingParentheses);
      }
    }
    else if (parentPrecedence == childPrecedence) {
      if (parentExpression instanceof PsiPolyadicExpression && body instanceof PsiPolyadicExpression) {
        final PsiPolyadicExpression parentPolyadicExpression = (PsiPolyadicExpression)parentExpression;
        final IElementType parentOperator = parentPolyadicExpression.getOperationTokenType();
        final PsiPolyadicExpression bodyPolyadicExpression = (PsiPolyadicExpression)body;
        final IElementType bodyOperator = bodyPolyadicExpression.getOperationTokenType();
        final PsiType parentType = parentPolyadicExpression.getType();
        final PsiType bodyType = body.getType();
        if (parentType != null && parentType.equals(bodyType) && parentOperator.equals(bodyOperator)) {
          final PsiExpression[] parentOperands = parentPolyadicExpression.getOperands();
          if (PsiTreeUtil.isAncestor(parentOperands[0], body, true) || isCommutativeOperator(bodyOperator)) {
            // use addAfter() + delete() instead of replace() to
            // workaround automatic insertion of parentheses by psi
            final PsiExpression newExpression = (PsiExpression)parent.addAfter(body, parenthesizedExpression);
            parenthesizedExpression.delete();
            removeParentheses(newExpression, ignoreClarifyingParentheses);
            return;
          }
        }
        if (ignoreClarifyingParentheses) {
          if (parentOperator.equals(bodyOperator)) {
            removeParentheses(body, ignoreClarifyingParentheses);
          }
        }
        else {
          final PsiExpression newExpression = (PsiExpression)parenthesizedExpression.replace(body);
          removeParentheses(newExpression, ignoreClarifyingParentheses);
        }
      }
      else {
        final PsiExpression newExpression = (PsiExpression)parenthesizedExpression.replace(body);
        removeParentheses(newExpression, ignoreClarifyingParentheses);
      }
    }
    else {
      if (ignoreClarifyingParentheses && parent instanceof PsiPolyadicExpression &&
          (body instanceof PsiPolyadicExpression || body instanceof PsiInstanceOfExpression)) {
        removeParentheses(body, ignoreClarifyingParentheses);
      }
      else {
        final PsiExpression newExpression = (PsiExpression)parenthesizedExpression.replace(body);
        removeParentheses(newExpression, ignoreClarifyingParentheses);
      }
    }
  }

  private static void removeParensFromConditionalExpression(@NotNull PsiConditionalExpression conditionalExpression,
                                                            boolean ignoreClarifyingParentheses) {
    final PsiExpression condition = conditionalExpression.getCondition();
    removeParentheses(condition, ignoreClarifyingParentheses);
    final PsiExpression thenBranch = conditionalExpression.getThenExpression();
    if (thenBranch != null) {
      removeParentheses(thenBranch, ignoreClarifyingParentheses);
    }
    final PsiExpression elseBranch = conditionalExpression.getElseExpression();
    if (elseBranch != null) {
      removeParentheses(elseBranch, ignoreClarifyingParentheses);
    }
  }

  private static void removeParensFromInstanceOfExpression(@NotNull PsiInstanceOfExpression instanceofExpression,
                                                           boolean ignoreClarifyingParentheses) {
    final PsiExpression operand = instanceofExpression.getOperand();
    removeParentheses(operand, ignoreClarifyingParentheses);
  }

  private static void removeParensFromPolyadicExpression(@NotNull PsiPolyadicExpression polyadicExpression,
                                                         boolean ignoreClarifyingParentheses) {
    for (PsiExpression operand : polyadicExpression.getOperands()) {
      removeParentheses(operand, ignoreClarifyingParentheses);
    }
  }

  private static void removeParensFromPostfixExpression(@NotNull PsiPostfixExpression postfixExpression,
                                                        boolean ignoreClarifyingParentheses) {
    final PsiExpression operand = postfixExpression.getOperand();
    removeParentheses(operand, ignoreClarifyingParentheses);
  }

  private static void removeParensFromPrefixExpression(@NotNull PsiPrefixExpression prefixExpression, boolean ignoreClarifyingParentheses) {
    final PsiExpression operand = prefixExpression.getOperand();
    if (operand != null) {
      removeParentheses(operand, ignoreClarifyingParentheses);
    }
  }

  private static void removeParensFromArrayAccessExpression(@NotNull PsiArrayAccessExpression arrayAccessExpression,
                                                            boolean ignoreClarifyingParentheses) {
    final PsiExpression arrayExpression = arrayAccessExpression.getArrayExpression();
    removeParentheses(arrayExpression, ignoreClarifyingParentheses);
    final PsiExpression indexExpression = arrayAccessExpression.getIndexExpression();
    if (indexExpression != null) {
      removeParentheses(indexExpression, ignoreClarifyingParentheses);
    }
  }

  private static void removeParensFromTypeCastExpression(@NotNull PsiTypeCastExpression typeCastExpression,
                                                         boolean ignoreClarifyingParentheses) {
    final PsiExpression operand = typeCastExpression.getOperand();
    if (operand != null) {
      removeParentheses(operand, ignoreClarifyingParentheses);
    }
  }

  private static void removeParensFromArrayInitializerExpression(@NotNull PsiArrayInitializerExpression arrayInitializerExpression,
                                                                 boolean ignoreClarifyingParentheses) {
    final PsiExpression[] initializers = arrayInitializerExpression.getInitializers();
    for (final PsiExpression initializer : initializers) {
      removeParentheses(initializer, ignoreClarifyingParentheses);
    }
  }

  private static void removeParensFromAssignmentExpression(@NotNull PsiAssignmentExpression assignment,
                                                           boolean ignoreClarifyingParentheses) {
    final PsiExpression lhs = assignment.getLExpression();
    final PsiExpression rhs = assignment.getRExpression();
    removeParentheses(lhs, ignoreClarifyingParentheses);
    if (rhs != null) {
      removeParentheses(rhs, ignoreClarifyingParentheses);
    }
  }

  private static void removeParensFromNewExpression(@NotNull PsiNewExpression newExpression, boolean ignoreClarifyingParentheses) {
    final PsiExpression[] dimensions = newExpression.getArrayDimensions();
    for (PsiExpression dimension : dimensions) {
      removeParentheses(dimension, ignoreClarifyingParentheses);
    }
    final PsiExpression qualifier = newExpression.getQualifier();
    if (qualifier != null) {
      removeParentheses(qualifier, ignoreClarifyingParentheses);
    }
    final PsiExpression arrayInitializer = newExpression.getArrayInitializer();
    if (arrayInitializer != null) {
      removeParentheses(arrayInitializer, ignoreClarifyingParentheses);
    }
    final PsiExpressionList argumentList = newExpression.getArgumentList();
    if (argumentList != null) {
      final PsiExpression[] arguments = argumentList.getExpressions();
      for (PsiExpression argument : arguments) {
        removeParentheses(argument, ignoreClarifyingParentheses);
      }
    }
  }

  private static void removeParensFromMethodCallExpression(@NotNull PsiMethodCallExpression methodCallExpression,
                                                           boolean ignoreClarifyingParentheses) {
    final PsiReferenceExpression target = methodCallExpression.getMethodExpression();
    final PsiExpressionList argumentList = methodCallExpression.getArgumentList();
    final PsiExpression[] arguments = argumentList.getExpressions();
    removeParentheses(target, ignoreClarifyingParentheses);
    for (final PsiExpression argument : arguments) {
      removeParentheses(argument, ignoreClarifyingParentheses);
    }
  }

  public static boolean areParenthesesNeeded(PsiParenthesizedExpression expression, boolean ignoreClarifyingParentheses) {
    final PsiElement parent = expression.getParent();
    if (!(parent instanceof PsiExpression)) {
      return false;
    }
    final PsiExpression child = expression.getExpression();
    if (child == null) {
      return true;
    }
    if (parent instanceof PsiArrayAccessExpression) {
      final PsiArrayAccessExpression arrayAccessExpression = (PsiArrayAccessExpression)parent;
      final PsiExpression indexExpression = arrayAccessExpression.getIndexExpression();
      if (expression == indexExpression) {
        return false;
      }
    }
    return areParenthesesNeeded(child, (PsiExpression)parent, ignoreClarifyingParentheses);
  }

  public static boolean areParenthesesNeeded(PsiExpression expression, PsiExpression parentExpression,
                                             boolean ignoreClarifyingParentheses) {
    if (parentExpression instanceof PsiParenthesizedExpression || parentExpression instanceof PsiArrayInitializerExpression) {
      return false;
    }
    final int parentPrecedence = getPrecedence(parentExpression);
    final int childPrecedence = getPrecedence(expression);
    if (parentPrecedence > childPrecedence) {
      if (ignoreClarifyingParentheses) {
        if (expression instanceof PsiPolyadicExpression) {
          if (parentExpression instanceof PsiPolyadicExpression ||
              parentExpression instanceof PsiConditionalExpression ||
              parentExpression instanceof PsiInstanceOfExpression) {
            return true;
          }
        }
        else if (expression instanceof PsiInstanceOfExpression) {
          return true;
        }
      }
      return false;
    }
    if (parentExpression instanceof PsiPolyadicExpression && expression instanceof PsiPolyadicExpression) {
      final PsiPolyadicExpression parentPolyadicExpression = (PsiPolyadicExpression)parentExpression;
      final PsiType parentType = parentPolyadicExpression.getType();
      if (parentType == null) {
        return true;
      }
      final PsiPolyadicExpression childPolyadicExpression = (PsiPolyadicExpression)expression;
      final PsiType childType = childPolyadicExpression.getType();
      if (!parentType.equals(childType)) {
        return true;
      }
      if (childType.equalsToText(CommonClassNames.JAVA_LANG_STRING) &&
          !PsiTreeUtil.isAncestor(parentPolyadicExpression.getOperands()[0], childPolyadicExpression, true)) {
        final PsiExpression[] operands = childPolyadicExpression.getOperands();
        for (PsiExpression operand : operands) {
          if (!childType.equals(operand.getType())) {
            return true;
          }
        }
      }
      else if (childType.equals(PsiType.BOOLEAN)) {
        final PsiExpression[] operands = childPolyadicExpression.getOperands();
        for (PsiExpression operand : operands) {
          if (!PsiType.BOOLEAN.equals(operand.getType())) {
            return true;
          }
        }
      }
      final IElementType parentOperator = parentPolyadicExpression.getOperationTokenType();
      final IElementType childOperator = childPolyadicExpression.getOperationTokenType();
      if (ignoreClarifyingParentheses) {
        if (!childOperator.equals(parentOperator)) {
          return true;
        }
      }
      final PsiExpression[] parentOperands = parentPolyadicExpression.getOperands();
      if (!PsiTreeUtil.isAncestor(parentOperands[0], expression, false)) {
        if (!isAssociativeOperation(parentPolyadicExpression) ||
            JavaTokenType.DIV == childOperator || JavaTokenType.PERC == childOperator) {
          return true;
        }
      }
    }
    else if (parentExpression instanceof PsiConditionalExpression && expression instanceof PsiConditionalExpression) {
      final PsiConditionalExpression conditionalExpression = (PsiConditionalExpression)parentExpression;
      final PsiExpression condition = conditionalExpression.getCondition();
      return PsiTreeUtil.isAncestor(condition, expression, true);
    }
    return parentPrecedence < childPrecedence;
  }

  public static boolean areParenthesesNeeded(PsiJavaToken sign, PsiExpression rhs) {
    if (rhs instanceof PsiPolyadicExpression) {
      final PsiPolyadicExpression binaryExpression = (PsiPolyadicExpression)rhs;
      final int precedence1 = getPrecedenceForOperator(binaryExpression.getOperationTokenType());
      final IElementType signTokenType = sign.getTokenType();
      final IElementType newOperatorToken = tokenMap.get(signTokenType);
      final int precedence2 = getPrecedenceForOperator(newOperatorToken);
      return precedence1 >= precedence2 || !isCommutativeOperator(newOperatorToken);
    }
    else {
      return rhs instanceof PsiConditionalExpression;
    }
  }
}


text:
//
//  RadioChooser.m
//  Coniglio
//
//  Created by Giacomo Tufano on 22/01/10.
//
//  Copyright 2011, Giacomo Tufano (gt@ilTofa.it)
//  Licensed under MIT license. See LICENSE file or http://www.opensource.org/licenses/mit-license.php
//

#import "RadioChooser.h"
#import "AddRadio.h"

@implementation RadioChooser

@synthesize theRadioList;
@synthesize delegate;

/*
- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if (self = [super initWithStyle:style]) {
    }
    return self;
}
*/

// FIXME: this and the next one should go to a model class
-(void)saveRadioArray
{
	NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
	NSString *archivePath = [docsDirectory stringByAppendingPathComponent:@"Radio.archive"];
	[NSKeyedArchiver archiveRootObject:self.theRadioList toFile:archivePath];
}

-(void)addANamedRadio:(NSDictionary *)theRadio
{
	NSMutableArray *temp = [NSMutableArray arrayWithArray:self.theRadioList];
	[temp addObject:theRadio];
	self.theRadioList = temp;
	[self saveRadioArray];
	[self.tableView reloadData];
}

-(IBAction)addRadio:(id)sender
{
	AddRadio *addController = [[AddRadio alloc] initWithNibName:@"AddRadio" bundle:nil];
	addController.parent = self;
	[self presentModalViewController:addController animated:YES];
	[addController release];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

	self.navigationItem.title = NSLocalizedString(@"Radio Chooser", @"");

    self.navigationItem.rightBarButtonItem = self.editButtonItem;
	UIBarButtonItem *theLeftButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
																					target:self
																					action:@selector(addRadio:)];
	self.navigationItem.leftBarButtonItem = theLeftButton;
	[theLeftButton release];

	// There is a saved archive?
	NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
	NSString *archivePath = [docsDirectory stringByAppendingPathComponent:@"Radio.archive"];
	if([[NSFileManager defaultManager] fileExistsAtPath:archivePath])
	{ // if YES, load it
		self.theRadioList = [NSKeyedUnarchiver unarchiveObjectWithFile:archivePath];
	}
	else
	{
		// Read default plist of radio station from bundle
		NSString *filePath = [[NSBundle mainBundle] pathForResource:@"ConiglioRadio" ofType:@"plist"];
		self.theRadioList = [NSArray arrayWithContentsOfFile:filePath];
		[self saveRadioArray];
	}
}

/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
	return NSLocalizedString(@"Choose a radio", @"");
}

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.theRadioList count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    // Set up the cell...
	NSDictionary *theOne = [self.theRadioList objectAtIndex:indexPath.row];
	cell.textLabel.text = [theOne objectForKey:@"Name"];
	cell.detailTextLabel.text = [theOne objectForKey:@"Desc"];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSDictionary *theOne = [self.theRadioList objectAtIndex:indexPath.row];
	NSString *retValue = [theOne objectForKey:@"URI"];
	[delegate listenTo:retValue];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete)
	{
		NSMutableArray *temp = [NSMutableArray arrayWithArray:self.theRadioList];
		[temp removeObjectAtIndex:indexPath.row];
		self.theRadioList = temp;
		[self saveRadioArray];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}

// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
	NSMutableArray *temp = [NSMutableArray arrayWithArray:self.theRadioList];
	[temp exchangeObjectAtIndex:fromIndexPath.row withObjectAtIndex:toIndexPath.row];
	self.theRadioList = temp;
	[self saveRadioArray];
}

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
	if(indexPath.row == 1)
		return NO;
    return YES;
}
*/

- (void)dealloc {
    [super dealloc];
}

@end

redpajama_set_name: RedPajamaGithub


text:
module Wood
  class NodeRewriter
    instance_methods.each do |m|
      undef_method m unless m =~ /(^__|^send$|^object_id$)/
    end

    attr_reader :node

    def initialize(node, name = nil, parent = nil)
      @node = node
      @parent = parent
      @name = name
    end

    def method_missing(method, *args, &block)
      NodeRewriter.new(@node.__send__(method, *args, &block), method, self)
    end

    def rewrite(new_node_val)
      if new_node_val.respond_to? :node
        new_node_val = new_node_val.node
      end

      if @parent && @name
        @parent.set_child(@name, new_node_val)
      end
    end
  end
end


text:
<model>
  <mount>//OPNsense/Iperf3</mount>
  <description>Fake model for the API - will be never stored to config (only used for defaults, validation etc.).</description>
  <items>
    <interface type="InterfaceField">
      <default>lan</default>
      <Required>Y</Required>
      <multiple>N</multiple>
    </interface>
  </items>
</model>


text:
<link rel="stylesheet" href="direct-descendents.css" />

woot


text:
package com.pathfinder.model;

import com.backendless.geo.GeoPoint;

import java.util.Date;

public class Place {
    private java.util.Date created;
    private String ownerId;
    private java.util.Date updated;
    private String description;
    private GeoPoint location;
    private String title;
    private String name;
    private String objectId;
    private String image;

    public String getImage() {
        return image;
    }

    public Place setImage(String image) {
        this.image = image;
        return this;
    }

    public Date getCreated() {
        return created;
    }

    public Place setCreated(Date created) {
        this.created = created;
        return this;
    }

    public String getOwnerId() {
        return ownerId;
    }

    public Place setOwnerId(String ownerId) {
        this.ownerId = ownerId;
        return this;
    }

    public Date getUpdated() {
        return updated;
    }

    public Place setUpdated(Date updated) {
        this.updated = updated;
        return this;
    }

    public String getDescription() {
        return description;
    }

    public Place setDescription(String description) {
        this.description = description;
        return this;
    }

    public GeoPoint getLocation() {
        return location;
    }

    public Place setLocation(GeoPoint location) {
        this.location = location;
        return this;
    }

    public String getTitle() {
        return title;
    }

    public Place setTitle(String title) {
        this.title = title;
        return this;
    }

    public String getName() {
        return name;
    }

    public Place setName(String name) {
        this.name = name;
        return this;
    }

    public String getObjectId() {
        return objectId;
    }

    public Place setObjectId(String objectId) {
        this.objectId = objectId;
        return this;
    }
}


text:
import * as URLSchemes from "core/transports/url_schemes";
import URLScheme from 'core/transports/url_scheme'
import Transport from "core/transports/transport";
import Util from "core/util";
import * as Collections from "core/utils/collections";
import TransportHooks from "core/transports/transport_hooks";
import TransportsTable from 'core/transports/transports_table';
import Runtime from 'runtime';

/** WebSocket transport.
 *
 * Uses native WebSocket implementation, including MozWebSocket supported by
 * earlier Firefox versions.
 */
var WSTransport = new Transport(<TransportHooks> {
  urls: URLSchemes.ws,
  handlesActivityChecks: false,
  supportsPing: false,

  isInitialized: function() {
    return Boolean(Runtime.getWebSocketAPI());
  },
  isSupported: function() : boolean {
    return Boolean(Runtime.getWebSocketAPI());
  },
  getSocket: function(url) {
    return Runtime.createWebSocket(url);
  }
});

var httpConfiguration = {
  urls: URLSchemes.http,
  handlesActivityChecks: false,
  supportsPing: true,
  isInitialized: function() {
    return true;
  }
};

export var streamingConfiguration = Collections.extend(
  { getSocket: function(url) {
      return Runtime.HTTPFactory.createStreamingSocket(url);
    }
  },
  httpConfiguration
);
export var pollingConfiguration = Collections.extend(
  { getSocket: function(url) {
      return Runtime.HTTPFactory.createPollingSocket(url);
    }
  },
  httpConfiguration
);

var xhrConfiguration = {
  isSupported: function() : boolean {
    return Runtime.isXHRSupported();
  }
};

/** HTTP streaming transport using CORS-enabled XMLHttpRequest. */
var XHRStreamingTransport = new Transport(
  <TransportHooks> Collections.extend({}, streamingConfiguration, xhrConfiguration)
);

/** HTTP long-polling transport using CORS-enabled XMLHttpRequest. */
var XHRPollingTransport = new Transport(
  <TransportHooks> Collections.extend({}, pollingConfiguration, xhrConfiguration)
);

var Transports : TransportsTable = {
  ws: WSTransport,
  xhr_streaming: XHRStreamingTransport,
  xhr_polling: XHRPollingTransport
}

export default Transports;


text:
package pl.rbolanowski.tw4a.backend.taskwarrior;

import org.junit.Test;
import pl.rbolanowski.tw4a.Task;

import static org.junit.Assert.*;

public class TranslatorTest {

    private Translator mTranslator = new Translator();

    @Test public void translatesNull() {
        assertTrue(mTranslator.translate(null) == null);
    }

    @Test public void translatesNotNullObjects() {
        InternalTask in = new InternalTask();

        in.uuid = "1234";
        in.description = "hello world";
        in.urgency = 9.8401f;
        in.status = InternalTask.Status.Pending;
        assertTaskMatches(mTranslator.translate(in), "1234", "hello world", false, 9.8401f);

        in.status = InternalTask.Status.Recurring;
        assertFalse(mTranslator.translate(in).done);

        in.status = InternalTask.Status.Completed;
        assertTrue(mTranslator.translate(in).done);
    }

    private static final void assertTaskMatches(
        Task task, String uuid, String description, Boolean done, Float urgency) {
        assertEquals(task.uuid, uuid);
        assertEquals(task.description, description);
        assertEquals(task.done, done);
        assertEquals(task.urgency, urgency, Task.EPSILON);
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="br.com.onfriday.xamarinazure" android:installLocation="auto" android:versionCode="1" android:versionName="1">
	<uses-sdk android:minSdkVersion="15" />
	<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
	<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
	<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
	<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
	<uses-permission android:name="android.permission.INTERNET" />
	<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
	<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
	<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
	<uses-permission android:name="android.permission.WAKE_LOCK" />
	<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
	<uses-permission android:name="android.permission.READ_CALENDAR" />
	<uses-permission android:name="android.permission.WRITE_CALENDAR" />
	<uses-permission android:name="android.permission.CAMERA" />
	<uses-permission android:name="android.permission.FLASHLIGHT" />
	<application android:label="@string/app_name" android:theme="@style/OnFridayXamarinAzureTheme" android:icon="@drawable/icon"></application>
</manifest>


text:
                <input autocomplete="off" spellcheck="false" id="loginUsername" class="input-focus" [ngClass]="{'input-error': loginTip}" [(ngModel)]="username" type="text" [placeholder]="usernamePlaceholderText" (keyup)="isButtonAvailableAction('usernameKeyup')" (change)="isButtonAvailableAction('usernameChange')">

{{loginTip}}

                <input autocomplete="off" spellcheck="false" id="loginPassword" class="input-focus" [(ngModel)]="password" type="password" [placeholder]="passwordPlaceholderText" (keyup.enter)="login()" (keyup)="isButtonAvailableAction('passwordKeyup')" (change)="isButtonAvailableAction('passwordChange')">

                    <input spellcheck="false" [(ngModel)]="loginRemember" id="remember" class="float-left" type="checkbox">

                    记住用户名和密码

                <button [disabled]="!isButtonAvailable && !rememberPassword" class="btn-active" type="button" (click)="login()">登录</button>

                没有账号?
                立即注册

        深圳市和讯华谷信息技术有限公司 版权所有 @2011-2017  粤ICP备12056275号-13


text:
package matrix4j.dct;

import java.lang.Math;
import static matrix4j.core.Math.ones;
import static matrix4j.core.Math.multiply;
import static matrix4j.core.Math.product;
import matrix4j.core.Matrix;
import matrix4j.core.Vector;

public class DCT {
    //1d DCT
    public static Matrix dct(Vector v) {
        int N = v.length();
        Matrix m = new Matrix(1, N);
        m.setRow(0, v);  //represent the vector as a 1xN matrix
        Matrix c = new DCTMatrix(N);
        return product(c, m);
    }

    //2d DCT
    public static Matrix dct(Matrix m) {
        if(m.nRows() != m.nColumns()) {
            throw new IllegalArgumentException("Matrix must be square");
        }

        int N = m.nRows();
        Matrix c = new DCTMatrix(N);
        return product(product(c.T(), m), c);
    }
}

class DCTMatrix extends Matrix {
    public DCTMatrix(int N) {
        super(N, N);

        this.setRow(0, multiply(ones(N), Math.sqrt(1.0/N)));
        for(int k = 1; k < N; k++) {
            for(int n = 0; n < N; n++) {
                double v = Math.sqrt(2.0/N) * Math.cos((2*n+1)*k*Math.PI/(2*N));
                this.set(k, n, v);
            }
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Spine Runtimes Software License
  ~ Version 2.3
  ~
  ~ Copyright (c) 2013-2015, Esoteric Software
  ~ All rights reserved.
  ~
  ~ You are granted a perpetual, non-exclusive, non-sublicensable and
  ~ non-transferable license to use, install, execute and perform the Spine
  ~ Runtimes Software (the "Software") and derivative works solely for personal
  ~ or internal use. Without the written permission of Esoteric Software (see
  ~ Section 2 of the Spine Software License Agreement), you may not (a) modify,
  ~ translate, adapt or otherwise create derivative works, improvements of the
  ~ Software or develop new applications using the Software or (b) remove,
  ~ delete, alter or obscure any trademarks or any copyright, trademark, patent
  ~ or other intellectual property or proprietary rights notices on or in the
  ~ Software, including any copy thereof. Redistributions in binary or source
  ~ form must include this license and terms.
  ~
  ~ THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR
  ~ IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  ~ MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  ~ EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  ~ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  ~ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  ~ OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  ~ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  ~ OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  ~ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  -->

<module rename-to="com.esotericsoftware.spine">
	<source path="spine">
		<include name="**/*"/>
	</source>
</module>


text:
package background;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.admin.DevicePolicyManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.media.AudioManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.StatFs;
import android.preference.PreferenceManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.getpebble.android.kit.PebbleKit;
import com.getpebble.android.kit.util.PebbleDictionary;
import com.stericson.RootTools.RootTools;
import com.wordpress.ninedof.dashboard.R;

import activity.Landing;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import cl_toolkit.Logger;
import cl_toolkit.Platform;
import cl_toolkit.Radios;
import cl_toolkit.Root;
import cl_toolkit.UserInterface;
import config.Build;
import config.Keys;
import config.Runtime;
import util.PebbleUtils;
import util.VersionCheck;

public class HandlerService extends Service {
    //Configuration
    private final static String TAG = HandlerService.class.getName();

    private static final int FOREGROUND_ID = 3489343;

    /**
     * See what the watch wants
     * This is the real meat and potatoes of Dashboard!
     *
     * @param dict Incoming data
     */
    public void parse(PebbleDictionary dict) {
        final Context context = getApplicationContext();

        Runtime.log(context, TAG, "Dashboard v" + Build.VERSION
                + " (compatible v" + Build.WATCH_APP_COMPATIBLE_VERSION + ")", Logger.INFO);

        // Version check
        if(PebbleUtils.hasString(dict, Keys.AppKeyVersion)) {
            String version = dict.getString(Keys.AppKeyVersion);
            if(!version.equals(Build.WATCH_APP_COMPATIBLE_VERSION)) {
                Runtime.log(context, TAG, "Wrong version! Watch is at " + version, Logger.ERROR);

                PebbleDictionary out = new PebbleDictionary();
                dict.addInt32(Keys.ErrorCodeWrongVersion, 0);
                PebbleKit.sendDataToPebble(context, Build.WATCH_APP_UUID, out);
                Runtime.log(context, TAG, "Send wrong version key to watch app", Logger.INFO);
                return;  // Nothing more to do here
            }

            Runtime.log(context, TAG, "Correct version: " + version, Logger.INFO);
        }

        //Requesting status of all toggles?
        if (PebbleUtils.hasInt(dict, Keys.MessageTypeRequestAll)) {
            Runtime.log(context, TAG, "Got sync all request", Logger.INFO);
            final PebbleDictionary out = new PebbleDictionary();
            out.addInt8(Keys.MessageTypeRequestAll, (byte) 1);

            addIsLollipop(out);
            addBatteryLevel(out);
//            addBatteryPlugged(out); descoped
            addOperatorName(out);
            addOperatorStrength(out);
            addWifiName(out);
            addFreeSpace(out);
            addToggleOrder(out);
            addQuickLaunchSettings(out);

            addWifiState(out);
            addMobileDataState(out);
            addBluetoothState(out);
            addRingerState(out);
            addAutoSyncState(out);
            addWifiApState(out);
            addPhoneState(out);
            addLockState(out);
            addAutoBrightnessState(out);
//            addFindPhoneState(out); descoped, tempramental

            new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        Thread.sleep(300);  // Delay sending while we gather GSM signal callbacks
                                            // This could be as low as 100ms, but hard to test
                        PebbleKit.sendDataToPebble(context, Build.WATCH_APP_UUID, out);
                        Runtime.log(context, TAG, "Sent MessageTypeRequestAll response!", Logger.INFO);
                    } catch(Exception e) {
                        Runtime.log(context, TAG, "Exception waiting to send dictionary", Logger.ERROR);
                        Runtime.logStackTrace(context, e);
                    }
                }

            }).start();

        // It's an individual toggle request
        } else if(PebbleUtils.hasInt(dict, Keys.MessageTypeToggle)) {
            Runtime.log(context, TAG, "Got toggle request", Logger.INFO);

            // Toggle WiFi
            if (PebbleUtils.hasInt(dict, Keys.AppKeyToggleWifi)) {
                int newState = Keys.ToggleStateOff;
                // These forks may look redundant, but they will guard against improper values from the watchapp
                if (PebbleUtils.getInt(dict, Keys.AppKeyToggleWifi) == Keys.ToggleStateOn) {
                    // Turn it on
                    newState = Keys.ToggleStateOn;
                } else if (PebbleUtils.getInt(dict, Keys.AppKeyToggleWifi) == Keys.ToggleStateOff) {
                    // Turn it off
                    newState = Keys.ToggleStateOff;
                }

                boolean success = Radios.setWiFiState(context, newState == Keys.ToggleStateOn);
                Runtime.log(context, TAG, "Wifi " + newState + " succeeded: " + success, Logger.INFO);

                PebbleDictionary out = new PebbleDictionary();
                out.addInt8(Keys.AppKeyToggleWifi, (byte) newState);
                PebbleKit.sendDataToPebble(context, Build.WATCH_APP_UUID, out);
            }

            // Toggle Data
            if (PebbleUtils.hasInt(dict, Keys.AppKeyToggleData)) {
                PebbleDictionary out = new PebbleDictionary();

                int newState = Keys.ToggleStateOff;
                if (PebbleUtils.getInt(dict, Keys.AppKeyToggleData) == Keys.ToggleStateOn) {
                    newState = Keys.ToggleStateOn;
                } else if (PebbleUtils.getInt(dict, Keys.AppKeyToggleData) == Keys.ToggleStateOff) {
                    newState = Keys.ToggleStateOff;
                }
                boolean newStateB = newState == Keys.ToggleStateOn;
                Runtime.log(context, TAG, "Attempting to toggle data " + (newStateB ? "ON" : "OFF"), Logger.INFO);

                if (!Platform.isLollipopOrAbove()) {
                    // Simple, use the reflected API
                    boolean success = Radios.setMobileDataEnabled(context, newStateB);
                    Runtime.log(context, TAG, "Data " + newState + " succeeded: " + success, Logger.INFO);
                    out.addInt8(Keys.AppKeyToggleData, (byte) newState);
                } else {
                    // Not so simple, we need root!
                    try {
                        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
                        if (prefs.getBoolean(Keys.PREF_KEY_DATA_ENABLED, false)) {
                            Runtime.log(context, TAG, "Using root method.", Logger.INFO);

                            // Attempt with root
                            if (RootTools.isAccessGiven()) {
                                // Attempt to set to new state (we don't actually know how the su command went)
                                boolean success = Root.rootSetMobileDataEnabled(context, newStateB);
                                Runtime.log(context, TAG, "Root Mobile data success: " + success, Logger.INFO);
                                out.addInt8(Keys.AppKeyToggleData, (byte) newState);
                            } else {
                                // Failed to get root, disable
                                out.addInt8(Keys.AppKeyToggleData, (byte) Keys.ErrorCodeNoRoot);
                                Runtime.log(context, TAG, "Root denied when attempting toggle", Logger.ERROR);
                            }
                        } else {
                            // Failed to get root, disable
                            out.addInt8(Keys.AppKeyToggleData, (byte) Keys.ErrorCodeDataNotEnabled);
//                            notifyRootRequest(); User does not want to be bothered
                            Runtime.log(context, TAG, "Data with root not enabled when attempting toggle", Logger.ERROR);
                        }
                    } catch (Exception e) {
                        // Failed to get root, disable
                        out.addInt8(Keys.AppKeyToggleData, (byte) Keys.ErrorCodeNoRoot);
                        Runtime.log(context, TAG, "Root denied when attempting toggle", Logger.ERROR);
                        Runtime.logStackTrace(context, e);
                    }
                }
                PebbleKit.sendDataToPebble(context, Build.WATCH_APP_UUID, out);
            }

            //Toggle BT? (MUST BE MANUALLY RECONNECTED!)
            if (PebbleUtils.hasInt(dict, Keys.AppKeyToggleBluetooth)) {
                boolean success = Radios.setBluetoothState(false);
                Runtime.log(context, TAG, "BT off succeeded: " + success, Logger.INFO);

                PebbleDictionary out = new PebbleDictionary();
                out.addInt8(Keys.AppKeyToggleBluetooth, (byte) Keys.ToggleStateOff);    // Always
                PebbleKit.sendDataToPebble(context, Build.WATCH_APP_UUID, out);
            }

            //Set Ringer?
            if (PebbleUtils.hasInt(dict, Keys.AppKeyToggleRinger)) {
                AudioManager aManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);

                int mode = PebbleUtils.getInt(dict, Keys.AppKeyToggleRinger);

                // Any mode other than silent may require unsetting DnD
                if (mode != Keys.ToggleStateSilent) {
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                        mNotificationManager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_ALL);
                    }
                }

                switch (mode) {
                    case Keys.ToggleStateLoud:
                        aManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
                        Runtime.log(context, TAG, "Loud mode attempted.", Logger.INFO);
                        break;
                    case Keys.ToggleStateVibrate:
                        aManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
                        Runtime.log(context, TAG, "Vibrate mode attempted.", Logger.INFO);
                        break;
                    case Keys.ToggleStateSilent: {
                        try {
                            Runtime.log(context, TAG, "Silent mode attempting....", Logger.INFO);
                            // Damn you Android 5.0 Priority mode with no API!!
                            // Also damn you DND in Android N!
                            // https://stackoverflow.com/questions/58044974/enable-silent-mode-in-android-without-triggering-do-not-disturb
                            aManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
                            aManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
                            int newMode = aManager.getRingerMode();   // WTF but works
                            Runtime.log(context, TAG, "Ringer mode now " + newMode, Logger.INFO);
                            if (newMode != AudioManager.RINGER_MODE_SILENT) {
                                Runtime.log(context, TAG, "New ringer mode does not match requested mode!", Logger.ERROR);
                            } else {
                                Runtime.log(context, TAG, "New ringer mode matched RINGER_MODE_SILENT (" + AudioManager.RINGER_MODE_SILENT + "): " + newMode, Logger.DEBUG);
                            }
                            Runtime.log(context, TAG, "Silent mode attempted.", Logger.INFO);
                        } catch (Exception e) {
                            Runtime.log(context, TAG, "Error toggling silent mode: " + e.getMessage(), Logger.ERROR);
                        }
                    }   break;
                }

                PebbleDictionary out = new PebbleDictionary();
                out.addInt8(Keys.AppKeyToggleRinger, (byte) mode);  // Echo back for updating UI
                PebbleKit.sendDataToPebble(context, Build.WATCH_APP_UUID, out);
            }

            //Set AutoSync?
            if (PebbleUtils.hasInt(dict, Keys.AppKeyToggleSync)) {
                int newState = Keys.ToggleStateOff;
                if (PebbleUtils.getInt(dict, Keys.AppKeyToggleSync) == Keys.ToggleStateOn) {
                    // Turn it on
                    newState = Keys.ToggleStateOn;
                } else if (PebbleUtils.getInt(dict, Keys.AppKeyToggleSync) == Keys.ToggleStateOff) {
                    // Turn it off
                    newState = Keys.ToggleStateOff;
//                } else {
//                    // Invert it
//                    newState = !ContentResolver.getMasterSyncAutomatically();
                }

                ContentResolver.setMasterSyncAutomatically(newState == Keys.ToggleStateOn);   // I'm worried this will go away soon
                Runtime.log(context, TAG, "Sync " + newState + " attempted.", Logger.INFO);

                PebbleDictionary out = new PebbleDictionary();
                out.addInt8(Keys.AppKeyToggleSync, (byte) newState);
                PebbleKit.sendDataToPebble(context, Build.WATCH_APP_UUID, out);
            }

            //Set Wifi AP?
            if (PebbleUtils.hasInt(dict, Keys.AppKeyToggleWifiAP)) {
                int newState = Keys.ToggleStateOff;
                if (PebbleUtils.getInt(dict, Keys.AppKeyToggleWifiAP) == Keys.ToggleStateOn) {
                    // Turn it on
                    newState = Keys.ToggleStateOn;
                } else if (PebbleUtils.getInt(dict, Keys.AppKeyToggleWifiAP) == Keys.ToggleStateOff) {
                    // Turn it off
                    newState = Keys.ToggleStateOff;
//                } else {
//                    // Invert it
//                    newState = !Radios.getWifiApEnabled(context);
                }

                // Disable
                if (newState != Keys.ToggleStateOn) {
                    //Disable AP
                    final boolean success = Radios.setWifiApEnabled(context, false);
                    new Handler().postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            //Wait for AP to disable
                            Runtime.log(context, TAG, "WiFi AP off: " + success, Logger.INFO);

                            //Respond to Pebble
                            PebbleDictionary out = new PebbleDictionary();
                            out.addInt8(Keys.AppKeyToggleWifiAP, (byte) Keys.ToggleStateOff);
                            PebbleKit.sendDataToPebble(context, Build.WATCH_APP_UUID, out);
                        }

                    }, 3000L);
                }

                // Enable
                else {
                    //Turn on Network Data and AP
                    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
                    if (!Platform.isLollipopOrAbove()) {
                        Radios.setMobileDataEnabled(context, true);
                    } else if (prefs.getBoolean(Keys.PREF_KEY_DATA_ENABLED, false)) {
                        try {
                            boolean success = Root.rootSetMobileDataEnabled(context, true);
                            Runtime.log(context, TAG, "Root Mobile data success: " + success, Logger.INFO);
                        } catch (Exception e) {
                            Runtime.log(context, TAG, "Exception performing AP data toggle ON!", Logger.ERROR);
                        }
                    } else {
                        Runtime.log(context, TAG, "5.0+ data state not enabled, user has not opted in to root method.", Logger.INFO);
                    }

                    boolean success = Radios.setWifiApEnabled(context, true);
                    Runtime.log(context, TAG, "WiFi AP on: " + success, Logger.INFO);

                    //Respond to Pebble
                    PebbleDictionary out = new PebbleDictionary();
                    out.addInt8(Keys.AppKeyToggleWifiAP, (byte) Keys.ToggleStateOn);
                    out.addInt8(Keys.AppKeyToggleWifi, (byte) Keys.ToggleStateOff);
                    out.addInt8(Keys.AppKeyToggleData, (byte) Keys.ToggleStateOn);

                    PebbleKit.sendDataToPebble(this, Build.WATCH_APP_UUID, out);
                }
            }

            //Sound find phone alarm - toggle only
            if (PebbleUtils.hasInt(dict, Keys.AppKeyToggleFindPhone)) {
                Runtime.log(context, TAG, "Toggling find phone...", Logger.INFO);
                startService(new Intent(context, FindPhone.class));
            }

            // Lock screen?
            if (PebbleUtils.hasInt(dict, Keys.AppKeyToggleLockPhone)) {
                PebbleDictionary out = new PebbleDictionary();
                boolean success;
                try {
                    DevicePolicyManager man = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
                    man.lockNow();

                    success = true;
                    out.addInt8(Keys.AppKeyToggleLockPhone, (byte) Keys.ErrorCodeLockSuccess);
                } catch (Exception e) {
                    Runtime.log(context, TAG, "Failed to lock. Not device admin?", Logger.ERROR);
                    Runtime.logStackTrace(context, e);

                    success = false;
                    out.addInt8(Keys.AppKeyToggleLockPhone, (byte) Keys.ErrorCodeNoDeviceAdmin);

                    // Remember we failed
                    SharedPreferences.Editor ed = PreferenceManager.getDefaultSharedPreferences(context).edit();
                    ed.putBoolean(Keys.PREF_KEY_ADMIN, false);
                    ed.commit();
                }

                Runtime.log(context, TAG, "Lock screen attempt: " + success, Logger.INFO);
                PebbleKit.sendDataToPebble(context, Build.WATCH_APP_UUID, out);
            }

            // Auto brightness?
            if (PebbleUtils.hasInt(dict, Keys.AppKeyToggleAutoBrightness)) {
                int newState = Keys.ToggleStateBrightnessAutomatic;
                if (PebbleUtils.getInt(dict, Keys.AppKeyToggleAutoBrightness) == Keys.ToggleStateBrightnessAutomatic) {
                    // Turn it on
                    newState = Keys.ToggleStateBrightnessAutomatic;
                } else if (PebbleUtils.getInt(dict, Keys.AppKeyToggleAutoBrightness) == Keys.ToggleStateBrightnessManual) {
                    // Turn it off
                    newState = Keys.ToggleStateBrightnessManual;
//                } else {
//                    // Invert it
//                    newState = !UserInterface.getAutoBrightnessEnabled(context);
                }

                boolean newStateB = newState == Keys.ToggleStateBrightnessAutomatic;
                UserInterface.setAutoBrightnessEnabled(context, newStateB);
                Runtime.log(context, TAG, "Setting auto brightness to " + (newStateB ? "ON" : "OFF"), Logger.INFO);

                PebbleDictionary out = new PebbleDictionary();
                out.addInt8(Keys.AppKeyToggleAutoBrightness, (byte) newState);
                PebbleKit.sendDataToPebble(context, Build.WATCH_APP_UUID, out);
            }
        } else {
            Runtime.log(context, TAG, "Unknown MessageType!", Logger.ERROR);

            // Could be 4.7 asking for version (4.8 won't answer how it expects!)
            PebbleDictionary response = new PebbleDictionary();
            response.addInt32(VersionCheck.KEY_VERSION_CHECK_FAILURE, 0);
            PebbleKit.sendDataToPebble(context, Build.WATCH_APP_UUID, response);
        }
    }

    private void addQuickLaunchSettings(PebbleDictionary out) {
        Context context = getApplicationContext();
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

        boolean enabled = prefs.getBoolean(Keys.PREF_KEY_QUICK_LAUNCH_ENABLED, false);
        Runtime.log(context, TAG, "Quick launch enabled? " + enabled, Logger.INFO);

        int type = prefs.getInt(Keys.PREF_KEY_QUICK_LAUNCH_TYPE, Keys.ToggleTypeWifi);
        Runtime.log(context, TAG, "Chosen quick launch type: " + type, Logger.INFO);

        out.addInt8(Keys.AppKeyQuickLaunchEnabled, (byte)(enabled ? 1 : 0));
        out.addInt8(Keys.AppKeyQuickLaunchType, (byte) type);
    }

    private void addOperatorStrength(final PebbleDictionary out) {
        final Context context = getApplicationContext();

        final TelephonyManager man = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        PSLCallback callback = new PSLCallback() {

            @Override
            public void onPercentKnown(int percent) {
                if(out != null) {
                    out.addInt8(Keys.AppKeyGSMPercent, (byte) percent);
                } else {
                    Runtime.log(context, TAG, "Tried to add new phone state to null dict!", Logger.ERROR);
                }
            }

        };
        final SignalListener listener = new SignalListener(context, callback);
        man.listen(listener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);

        new Thread(new Runnable() {

            @Override
            public void run() {
                // Delay unlistening
                try {
                    Thread.sleep(5000);
                    man.listen(listener, PhoneStateListener.LISTEN_NONE);
                    Runtime.log(context, TAG, "Stopped listening for signal strength updates", Logger.INFO);
                } catch(Exception e) {
                    Runtime.log(context, TAG, "Exception waiting to stop listening to signal changes", Logger.ERROR);
                    Runtime.logStackTrace(context, e);
                }
            }

        }).start();
    }

    private void addWifiName(PebbleDictionary out) {
        WifiManager wifiMgr = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
        String name = wifiInfo.getSSID();
        name = name.replace("\"", "");

        if(name.equals("0x")) {
            // On, but disconnected?
            name = "Disconnected";
        } else if(name.equals("<unknown ssid>")) {
            name = "Unknown";
        }

        out.addString(Keys.AppKeyWifiName, name);
        Runtime.log(getApplicationContext(), TAG, "Wifi network name: " + name, Logger.INFO);
    }

    /**
     * http://stackoverflow.com/questions/4595334/get-free-space-on-internal-memory
     */
    private void addFreeSpace(PebbleDictionary out) {
        StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
        long free = statFs.getFreeBlocksLong() * (statFs.getBlockSizeLong());
        final float gigs =  free / 1073741824F;
        float temp = gigs;

        int major = (int)Math.floor(temp);
        temp -= major;
        temp *= 10.0F;
        int minor = (int)Math.round(temp) % 10;
        out.addInt8(Keys.AppKeyStorageFreeGBMajor, (byte) major);
        out.addInt8(Keys.AppKeyStorageFreeGBMinor, (byte) minor);

        long total = statFs.getBlockCountLong() * statFs.getBlockSizeLong();
        int percent = Math.round(((float)free / (float)total) * 100);
        percent = 100 - percent;
        out.addInt8(Keys.AppKeyStoragePercent, (byte)percent);
        Runtime.log(getApplicationContext(), TAG, "Free space: " + gigs + "GB. Major/minor: " + major + "/" + minor + " (" + percent + "% used)", Logger.INFO);
    }

    private void addAutoBrightnessState(PebbleDictionary out) {
        Context context = getApplicationContext();

        boolean autoEnabled = UserInterface.getAutoBrightnessEnabled(context);
        Runtime.log(context, TAG, "Auto brightness is " + (autoEnabled ? "ON" : "OFF"), Logger.INFO);
        out.addInt8(Keys.AppKeyToggleAutoBrightness, (byte) (autoEnabled ? Keys.ToggleStateBrightnessAutomatic : Keys.ToggleStateBrightnessManual));
    }

    private void addIsLollipop(PebbleDictionary out) {
        boolean isLollipop = Platform.isLollipopOrAbove();
        Runtime.log(getApplicationContext(), TAG, "Platform is " + (isLollipop ? "" : "NOT") + " 5.0+.", Logger.INFO);
        out.addInt8(Keys.AppKeyIsLollipop, (byte) (isLollipop ? 1 : 0));
    }

    private void addPhoneState(PebbleDictionary out) {
        Runtime.log(getApplicationContext(), TAG, "Adding Find Phone state OFF...", Logger.INFO);
        out.addInt8(Keys.AppKeyToggleFindPhone, (byte) 0);
    }

    private void addToggleOrder(PebbleDictionary out) {
        out.addString(Keys.AppKeyToggleOrderString, constructConfigurationString(getApplicationContext()));
    }

    private void addWifiApState(PebbleDictionary out) {
        Context context = getApplicationContext();

        boolean enabled = Radios.getWifiApEnabled(context);
        Runtime.log(context, TAG, "Wifi AP is " + (enabled ? "ON" : "OFF"), Logger.INFO);
        out.addInt8(Keys.AppKeyToggleWifiAP, (enabled ? (byte) 1 : (byte) 0));
    }

    private void addAutoSyncState(PebbleDictionary out) {
        boolean wasSyncing = ContentResolver.getMasterSyncAutomatically();
        Runtime.log(getApplicationContext(), TAG, "Autosync is " + (wasSyncing ? "ON" : "OFF"), Logger.INFO);
        out.addInt8(Keys.AppKeyToggleSync, (wasSyncing ? (byte) 1 : (byte) 0));    //Report the current
    }

    private void addRingerState(PebbleDictionary out) {
        Context context = getApplicationContext();

        //Get ringer state
        AudioManager aManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int mode = aManager.getRingerMode();
        Runtime.log(context, TAG, "GOT RINGER " + mode, Logger.INFO);
        switch (mode) {
            case AudioManager.RINGER_MODE_NORMAL:
                out.addInt8(Keys.AppKeyToggleRinger, (byte) Keys.ToggleStateLoud);
                Runtime.log(context, TAG, "Volume: LOUD", Logger.INFO);
                break;
            case AudioManager.RINGER_MODE_VIBRATE:
                out.addInt8(Keys.AppKeyToggleRinger, (byte) Keys.ToggleStateVibrate);
                Runtime.log(context, TAG, "Volume: VIBRATE", Logger.INFO);
                break;
            case AudioManager.RINGER_MODE_SILENT:
                out.addInt8(Keys.AppKeyToggleRinger, (byte) Keys.ToggleStateSilent);
                Runtime.log(context, TAG, "Volume: SILENT", Logger.INFO);
                break;
        }
    }

    private void addBluetoothState(PebbleDictionary out) {
        boolean btState = Radios.getBluetoothState();
        Runtime.log(getApplicationContext(), TAG, "BT is : " + (btState ? "true" : "false"), Logger.INFO);
        out.addInt8(Keys.AppKeyToggleBluetooth, btState ? (byte) 1 : (byte) 0);
    }

    private void addMobileDataState(PebbleDictionary out) {
        boolean networkState = Radios.getMobileDataEnabled(this);
        Runtime.log(getApplicationContext(), TAG, "Data is : " + (networkState ? "true" : "false"), Logger.INFO);
        out.addInt8(Keys.AppKeyToggleData, networkState ? (byte) 1 : (byte) 0);
    }

    private void addWifiState(PebbleDictionary out) {
        boolean wifiState = Radios.getWiFiEnabled(this);
        Runtime.log(getApplicationContext(), TAG, "Wifi is connected: " + (wifiState ? "true" : "false"), Logger.INFO);
        out.addInt8(Keys.AppKeyToggleWifi, wifiState ? (byte) 1 : (byte) 0);
    }

    private void addOperatorName(PebbleDictionary out) {
        //Get operator name
        TelephonyManager tManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        String operatorName = tManager.getNetworkOperatorName();

        Runtime.log(getApplicationContext(), TAG, "Operator: " + operatorName, Logger.INFO);
        if (operatorName.length() > 0) {
            out.addString(Keys.AppKeyGSMName, operatorName);
        } else {
            //Unknown!
            out.addString(Keys.AppKeyGSMName, "Unknown");
        }
    }

    private void addBatteryLevel(PebbleDictionary out) {
        IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatus = registerReceiver(null, iFilter);

        int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        float batteryPct = (float) level / (float) scale;

        Runtime.log(getApplicationContext(), TAG, "Battery level is " + batteryPct, Logger.INFO);
        out.addInt8(Keys.AppKeyBatteryPercent, (byte) Math.round(batteryPct * 100.0F));
    }

    private void addLockState(PebbleDictionary out) {
        Runtime.log(getApplicationContext(), TAG, "Adding lock state off...", Logger.INFO);
        out.addInt8(Keys.AppKeyToggleLockPhone, (byte) Keys.ToggleStateOff);
    }

    /**
     * Concat a string of array indices indicating toggle positioning choices
     */
    public static String constructConfigurationString(Context context) {
        String result = "";
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        for (int i = 0; i < Landing.spinnerIds.length; i++) {
            int nextValue = prefs.getInt(Keys.PREF_CONFIGURE_BASE + "" + i, -1);
            if (nextValue != -1) {
                result += "" + nextValue;
            }
        }

        Runtime.log(context, TAG, "Config is " + result, Logger.INFO);
        return result;
    }

    /******************************* Implements Service ********************************/

//    private Notification notifyBelowOreo() {
//        Intent notificationIntent = new Intent(this, Landing.class);
//        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
//        return new NotificationCompat.Builder(this)
//                .setSmallIcon(R.drawable.ic_launcher_notif)
//                .setContentTitle("Dashboard for Pebble")
//                .setContentText("Required notification for background toggling")
//                .setContentIntent(pendingIntent)
//                .build();
//    }

    @RequiresApi(android.os.Build.VERSION_CODES.O)
    private Notification notifyAboveOreo() {
        String channelId = Build.PACKAGE_NAME;
        String channelName = "Dashboard Background Service";
        NotificationChannel chan = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.BLUE);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        assert manager != null;
        manager.createNotificationChannel(chan);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId);
        return notificationBuilder.setOngoing(true)
            .setSmallIcon(R.drawable.ic_launcher_notif)
            .setContentTitle("Required notification for background toggling")
            .setPriority(NotificationManager.IMPORTANCE_NONE)
            .setCategory(Notification.CATEGORY_SERVICE)
            .build();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Context context = getApplicationContext();

        // Background apps are cached inactive after API 28 (Oreo) :(
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            startForeground(FOREGROUND_ID, notifyAboveOreo());
        }

        Runtime.log(context, TAG, "onStartCommand", Logger.INFO);

        try {
            if (intent != null) {
                //Get JSON
                String jsonData = intent.getExtras().getString("json");  // Thanks, SteveP!
                if(!Build.RELEASE) {
                    Runtime.log(context, TAG, "Dict JSON: " + jsonData, Logger.DEBUG);
                }

                // Could be 'keep alive' type of launch...
                if (jsonData == null || jsonData.equals("")) {
                    return Service.START_STICKY;
                }

                try {
                    //Get dictionary and parse
                    PebbleDictionary dict = PebbleDictionary.fromJson(jsonData);
                    parse(dict);
                } catch (Exception e) {
                    config.Runtime.logStackTrace(context, e);
                }
            } else {
                Runtime.log(context, TAG, "Intent is null! The Service may have been restarted.", Logger.ERROR);
            }

            Runtime.log(context, TAG, "onStartCommand finished.", Logger.INFO);
        } catch (Exception e) {
            Runtime.log(context, TAG, "onStartCommand() threw exception: " + e.getLocalizedMessage(), Logger.INFO);
            Runtime.logStackTrace(context, e);
        }

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

}


text:
package model;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
@Table(name = "LANCA_CAIXA")
public class LancaCaixa implements Serializable {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	@Id
	@Column(name = "LANCA_CAIXA_ID")
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long lancaCaixaId;

	@ManyToOne(fetch = FetchType.EAGER)
	@JoinColumn(name = "TIPO_DOCUMENTO_ID")
	private TipoDocumento tipoDocumentoId;

	@ManyToOne(fetch = FetchType.EAGER)
	@JoinColumn(name = "PLANO_CONTA_GERENCIAL_ID")
	private PlanoContaGerencial planoContaGerencialId;

	@Column(name = "PARCEIRO_ID")
	private Long parceiroId;

	@Column(name = "DATA_MOVIMENTO")
	@Temporal(TemporalType.DATE)
	private Date dataMovimento;

	@Column(name = "DATA_EMISSAO")
	@Temporal(TemporalType.DATE)
	private Date dataEmissao = new Date();

	@Column(name = "SINAL")
	private String sinal = "S";

	@Column(name = "VALOR")
	private Double valor;

	@Column(name = "NUMERO_DOCUMENTO")
	private String numeroDocumento = "";

	@Column(name = "TIPO_PARCEIRO")
	private String tipoParceiro = "";

	@Column(name = "DESCRICAO_OUTROS")
	private String descricaoOutros = "";

	@Column(name = "TP_GERACAO")
	private String tpGeracao = "";

	@Column(name = "ORIGEM_MOVIMENTO")
	private String origemMovimento = "";

	public Long getLancaCaixaId() {
		return lancaCaixaId;
	}

	public void setLancaCaixaId(Long lancaCaixaId) {
		this.lancaCaixaId = lancaCaixaId;
	}

	public TipoDocumento getTipoDocumentoId() {
		return tipoDocumentoId;
	}

	public void setTipoDocumentoId(TipoDocumento tipoDocumentoId) {
		this.tipoDocumentoId = tipoDocumentoId;
	}

	public PlanoContaGerencial getPlanoContaGerencialId() {
		return planoContaGerencialId;
	}

	public void setPlanoContaGerencialId(
			PlanoContaGerencial planoContaGerencialId) {
		this.planoContaGerencialId = planoContaGerencialId;
	}

	public Date getDataMovimento() {
		return dataMovimento;
	}

	public void setDataMovimento(Date dataMovimento) {
		this.dataMovimento = dataMovimento;
	}

	public Date getDataEmissao() {
		return dataEmissao;
	}

	public void setDataEmissao(Date dataEmissao) {
		this.dataEmissao = dataEmissao;
	}

	public String getSinal() {
		return sinal;
	}

	public void setSinal(String sinal) {
		this.sinal = sinal;
	}

	public Long getParceiroId() {
		return parceiroId;
	}

	public void setParceiroId(Long parceiroId) {
		this.parceiroId = parceiroId;
	}

	public Double getValor() {
		return valor;
	}

	public void setValor(Double valor) {
		this.valor = valor;
	}

	public String getNumeroDocumento() {
		return numeroDocumento;
	}

	public void setNumeroDocumento(String numeroDocumento) {
		this.numeroDocumento = numeroDocumento;
	}

	public String getTipoParceiro() {
		return tipoParceiro;
	}

	public void setTipoParceiro(String tipoParceiro) {
		this.tipoParceiro = tipoParceiro;
	}

	public String getDescricaoOutros() {
		return descricaoOutros;
	}

	public void setDescricaoOutros(String descricaoOutros) {
		this.descricaoOutros = descricaoOutros;
	}

	public String getOrigemMovimento() {
		return origemMovimento;
	}

	public void setOrigemMovimento(String origemMovimento) {
		this.origemMovimento = origemMovimento;
	}

	public String getTpGeracao() {
		return tpGeracao;
	}

	public void setTpGeracao(String tpGeracao) {
		this.tpGeracao = tpGeracao;
	}

}


text:
name: Michel Wermelinger
---


text:
namespace {

const double kStepSize = 0.1;

double ClampToMin(double percent) {
  return std::min(std::max(percent, 0.0), 1.0);
}

}  // namespace

namespace views {
namespace examples {

ProgressBarExample::ProgressBarExample()
    : ExampleBase("Progress Bar"),
      minus_button_(NULL),
      plus_button_(NULL),
      progress_bar_(NULL),
      current_percent_(0.0) {
}

ProgressBarExample::~ProgressBarExample() {
}

void ProgressBarExample::CreateExampleView(View* container) {
  GridLayout* layout = new GridLayout(container);
  container->SetLayoutManager(layout);

  ColumnSet* column_set = layout->AddColumnSet(0);
  column_set->AddColumn(GridLayout::LEADING, GridLayout::FILL,
                        0, GridLayout::USE_PREF, 0, 0);
  column_set->AddPaddingColumn(0, 8);
  column_set->AddColumn(GridLayout::FILL, GridLayout::FILL,
                        1, GridLayout::USE_PREF, 0, 0);
  column_set->AddPaddingColumn(0, 8);
  column_set->AddColumn(GridLayout::TRAILING, GridLayout::FILL,
                        0, GridLayout::USE_PREF, 0, 0);

  layout->StartRow(0, 0);
  minus_button_ = new TextButton(this, ASCIIToUTF16("-"));
  layout->AddView(minus_button_);
  progress_bar_ = new ProgressBar();
  layout->AddView(progress_bar_);
  plus_button_ = new TextButton(this, ASCIIToUTF16("+"));
  layout->AddView(plus_button_);
}

void ProgressBarExample::ButtonPressed(Button* sender, const Event& event) {
  if (sender == minus_button_)
    current_percent_ = ClampToMin(current_percent_ - kStepSize);
  else if (sender == plus_button_)
    current_percent_ = ClampToMin(current_percent_ + kStepSize);

  progress_bar_->SetValue(current_percent_);
}

}  // namespace examples
}  // namespace views


text:
package guava.primitives;

import com.google.common.primitives.Chars;

import java.util.List;

public class CharsTester {
    public static void main(String args[]) {
        CharsTester tester = new CharsTester();
        tester.testChars();
    }

    private void testChars() {
        char[] charArray = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'};

        //convert array of primitives to array of objects
        List<Character> objectArray = Chars.asList(charArray);
        System.out.println(objectArray.toString());

        //convert array of objects to array of primitives
        charArray = Chars.toArray(objectArray);
        System.out.print("[ ");
        for (int i = 0; i < charArray.length; i++) {
            System.out.print(charArray[i] + " ");
        }
        System.out.println("]");
        //check if element is present in the list of primitives or not
        System.out.println("c is in list? " + Chars.contains(charArray, 'c'));

        //return the index of element
        System.out.println("c position in list " + Chars.indexOf(charArray, 'c'));

        //Returns the minimum
        System.out.println("Min: " + Chars.min(charArray));

        //Returns the maximum
        System.out.println("Max: " + Chars.max(charArray));
    }
}


text:
using Microsoft.EntityFrameworkCore;
using System;

namespace Audit.EntityFramework.Core.UnitTest
{
    public class OrderMemoryContext : AuditDbContext
    {
        public class Order
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }

        [AuditIgnore]
        public class AuditLog
        {
            public int Id { get; set; }
            public string AuditData { get; internal set; }
            public string EntityType { get; internal set; }
            public DateTime AuditDate { get; internal set; }
            public string AuditUser { get; internal set; }
            public string TablePk { get; internal set; }
        }

        [AuditIgnore]
        public class OrderAudit : IAudit
        {
            public int Id { get; set; }
            public DateTime AuditDate { get; set; }
            public string UserName { get; set; }
            public string AuditAction { get; set; }
        }
        public class Orderline
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }

        public class Product
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }

        [AuditIgnore]
        public class OrderlineAudit : IAudit
        {
            public int Id { get; set; }
            public DateTime AuditDate { get; set; }
            public string UserName { get; set; }
            public string AuditAction { get; set; }
        }
        public interface IAudit
        {
            DateTime AuditDate { get; set; }
            string UserName { get; set; }
            string AuditAction { get; set; }
        }

        public DbSet<Order> Orders { get; set; }
        public DbSet<Orderline> Orderlines { get; set; }
        public DbSet<Product> Products { get; set; }

        public DbSet<AuditLog> AuditLogs { get; set; }
        public DbSet<OrderAudit> OrderAudits { get; set; }
        public DbSet<OrderlineAudit> OrderlineAudits { get; set; }

        public OrderMemoryContext()
        { }

        public OrderMemoryContext(DbContextOptions<OrderMemoryContext> options)
            : base(options)
        { }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=OrderMemoryContext.InMemory;Trusted_Connection=True;ConnectRetryCount=0");
            }
        }
    }

}


text:
/*
* @flow
*/

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
  View,
  StyleSheet,
  Animated,
} from 'react-native';

type PlaceholderProps = {
  style: Object,
  animatedComponent: React.Element<*>
};

type PlaceholderState = {
  x: number,
  width: number,
  isMeasured: boolean,
  resolved: boolean
};

export default class Placeholder extends Component {
  state: PlaceholderState;
  props: PlaceholderProps;
  constructor(props: PlaceholderProps) {
    super(props);
    this.state = {
      x: 0,
      width: 0,
      isMeasured: false,
      resolved: false
    };
  }

  componentDidMount(): void {
    this.context.registerPlaceholder(this);
  }

  render(): React.Element<*> {
    const { style, children } = this.props;
    const { x, isMeasured, resolved } = this.state;
    const { animatedComponent, position } = this.context;

    if (resolved) {
      return children
    }
    const animatedStyle = {
      height: '100%',
      width: '100%',
      transform: [{ translateX: position }],
      left: -x
    };
    return (
      <View
        ref={ref => {
          this.testRef = ref;
        }}
        onLayout={this._setDimensions}
        style={[style, styles.overflow]}
      >
        {isMeasured &&
          <Animated.View style={animatedStyle}>
            {animatedComponent}
          </Animated.View>}
      </View>
    );
  }
  _resolve = () => {
    this.setState(() => ({ resolved: true }));
  };

  _setDimensions = (event): void => {
    const { x } = event.nativeEvent.layout;
    this.setState(() => ({ x, isMeasured: true }));
  };
}

Placeholder.contextTypes = {
    position: PropTypes.object.isRequired,
    animatedComponent: PropTypes.object.isRequired,
    registerPlaceholder: PropTypes.func.isRequired
}

const styles = StyleSheet.create({
  overflow: {
    overflow: 'hidden'
  }
});


text:
namespace spot
{
  /// \brief Clone and mask an automaton.
  ///
  /// Copy the edges of automaton \a old into the empty automaton \a
  /// cpy, creating new states as needed.  The argument \a trans
  /// should behave as a function with the following prototype:
  ///
  ///   void (*trans) (unsigned src, bdd& cond, acc_cond::mark_t& acc,
  ///   unsigned dst)
  ///
  ///
  /// The \a trans function may modify either the condition or the
  /// acceptance sets of the edges.  Set the condition to bddfalse to
  /// remove the edge (this will also remove the destination state and
  /// its descendants if they are not reachable by another edge).
  ///
  /// The mapping between each state of the resulting automaton
  /// and the original state of the input automaton is stored in the
  /// "original-states" named property of the produced automaton.  Call
  /// `aut->get_named_prop<std::vector<unsigned>>("original-states")`
  /// to retrieve it.
  ///
  /// If \a drop_univ_branches branch is set, universal branching is replaced
  /// by existential branching during the copy.
  ///
  /// \param init The optional new initial state.
  template<typename Trans>
  void transform_accessible(const const_twa_graph_ptr& old,
                            twa_graph_ptr& cpy,
                            Trans trans, unsigned int init,
                            bool drop_univ_branches = false)
  {
    std::vector<unsigned> todo;
    std::vector<unsigned> seen(old->num_states(), -1U);

    auto orig_states = new std::vector<unsigned>();
    orig_states->reserve(old->num_states()); // maybe less are needed.
    cpy->set_named_prop("original-states", orig_states);

    auto new_state =
      [&](unsigned old_state) -> unsigned
      {
        unsigned tmp = seen[old_state];
        if (tmp == -1U)
          {
            tmp = cpy->new_state();
            seen[old_state] = tmp;
            orig_states->emplace_back(old_state);
            todo.emplace_back(old_state);
          }
        return tmp;
      };

    // Deal with alternating automata, possibly.
    std::map<std::vector<unsigned>, unsigned> uniq;
    auto new_univ_state =
      [&](unsigned old_state) -> unsigned
      {
        if (!old->is_univ_dest(old_state))
          return new_state(old_state);

        std::vector<unsigned> tmp;
        for (auto s: old->univ_dests(old_state))
          tmp.emplace_back(new_state(s));
        std::sort(tmp.begin(), tmp.end());
        tmp.erase(std::unique(tmp.begin(), tmp.end()), tmp.end());
        auto p = uniq.emplace(tmp, 0);
        if (p.second)
          p.first->second =
            cpy->get_graph().new_univ_dests(tmp.begin(), tmp.end());
        return p.first->second;
      };

    cpy->set_init_state(new_univ_state(init));
    if (seen[init] != 0)
      throw std::runtime_error
        ("the destination automaton of transform_accessible() should be empty");

    while (!todo.empty())
      {
        unsigned old_src = todo.back();
        todo.pop_back();

        unsigned new_src = seen[old_src];
        SPOT_ASSERT(new_src != -1U);

        for (auto& t: old->out(old_src))
          {
            bdd cond = t.cond;
            acc_cond::mark_t acc = t.acc;
            trans(t.src, cond, acc, t.dst);
            if (cond == bddfalse)
              continue;
            if (drop_univ_branches)
              for (unsigned d: old->univ_dests(t.dst))
                cpy->new_edge(new_src, new_state(d), cond, acc);
            else
              cpy->new_edge(new_src, new_univ_state(t.dst), cond, acc);
          }
      }
    orig_states->shrink_to_fit();
  }

  /// \brief Copy an automaton and update each edge.
  ///
  /// Copy the states of automaton \a old, into automaton
  /// \a cpy. Each state in \a cpy will have the same id as the ones in \a old.
  /// The argument \a trans
  /// should behave as a function with the following prototype:
  ///
  ///   void (*trans) (unsigned srcbdd& cond, acc_cond::mark_t& acc,
  ///   unsigned dst)
  ///
  /// It can modify either the condition or the acceptance sets of
  /// the edges.  Set the condition to bddfalse to remove it.  Note that
  /// all transtions will be processed.
  /// \param init The optional new initial state.
  template<typename Trans>
  void transform_copy(const const_twa_graph_ptr& old,
                      twa_graph_ptr& cpy,
                      Trans trans, unsigned int init)
  {
    if (!old->is_existential())
      throw std::runtime_error
        ("transform_copy() does not support alternation");

    // Each state in cpy corresponds to a unique state in old.
    cpy->new_states(old->num_states());
    cpy->set_init_state(init);

    for (auto& t: old->edges())
      {
        bdd cond = t.cond;
        acc_cond::mark_t acc = t.acc;
        trans(t.src, cond, acc, t.dst);
        // Having the same number of states should assure that state ids are
        // equivilent in old and cpy.
        SPOT_ASSERT(t.src < cpy->num_states() && t.dst < cpy->num_states());
        if (cond != bddfalse)
          cpy->new_edge(t.src, t.dst, cond, acc);
      }
  }

  template<typename Trans>
  void transform_accessible(const const_twa_graph_ptr& old,
                            twa_graph_ptr& cpy,
                            Trans trans)
  {
    transform_accessible(old, cpy, trans, old->get_init_state_number());
  }

  template<typename Trans>
  void transform_copy(const const_twa_graph_ptr& old,
                      twa_graph_ptr& cpy,
                      Trans trans)
  {
    transform_copy(old, cpy, trans, old->get_init_state_number());
  }

  /// \brief Remove all edges that belong to some given acceptance sets.
  SPOT_API
  twa_graph_ptr mask_acc_sets(const const_twa_graph_ptr& in,
                              acc_cond::mark_t to_remove);

  /// \brief Keep only the states as specified by \a to_keep.
  ///
  /// Each index in the vector \a to_keep specifies wether or not to
  /// keep the transition that exit this state.  The initial state
  /// will be set to \a init.
  ///
  /// Note that the number of states in the result automaton is the
  /// same as in the input: only transitions have been removed.
  ///
  /// \see mask_keep_accessible_states
  SPOT_API
  twa_graph_ptr mask_keep_states(const const_twa_graph_ptr& in,
                                 std::vector<bool>& to_keep,
                                 unsigned int init);

  /// \brief Keep only the states specified by \a to_keep that are accessible.
  ///
  /// Each index in the vector \a to_keep specifies wether or not to
  /// keep the transition that exit this state.  The initial state
  /// will be set to \a init.  Only states that are accessible from \a
  /// init via states in \a to_keep will be preserved.
  ///
  /// If \a drop_univ_branches branch is set, universal branching is replaced
  /// by existential branching during the copy.
  ///
  /// \see mask_keep_states
  SPOT_API
  twa_graph_ptr mask_keep_accessible_states(const const_twa_graph_ptr& in,
                                            std::vector<bool>& to_keep,
                                            unsigned int init,
                                            bool drop_univ_branches = false);
}


text:
'use strict';

import './styles/bootswatch/yeti/bootstrap.min.css'
import './styles/custom.css'
import 'riot'


text:
import time
from threading import Timer

class SyncTask:
    def __init__(self, task):
        self.__waiting = True
        self.__task = task

    def start(self, timeout=None):
        # type: (int) -> None
        if timeout is not None:
            Timer(timeout / 1000, self.__callback).start()

    def __callback(self):
        # type: () -> None
        self.__waiting = False

    def alive(self):
        # type: () -> bool
        time.sleep(0.1)
        return self.__waiting

    def do_task(self):
        return self.__task()


text:
<?php

defined('BASEPATH') or exit('No direct script access allowed');

class Migration_Version_207 extends CI_Migration
{
    public function __construct()
    {
        parent::__construct();
    }

    public function up()
    {

    }
}