text:
package com.siyeh.ig.controlflow;

import com.intellij.codeInspection.CleanupLocalInspectionTool;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.util.containers.ContainerUtil;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import com.siyeh.ig.PsiReplacementUtil;
import com.siyeh.ig.psiutils.BoolUtils;
import com.siyeh.ig.psiutils.ControlFlowUtils;
import com.siyeh.ig.psiutils.EquivalenceChecker;
import com.siyeh.ig.psiutils.ParenthesesUtils;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

import java.util.Collection;

public class TrivialIfInspection extends BaseInspection implements CleanupLocalInspectionTool {

  @Override
  @NotNull
  public String getID() {
    return "RedundantIfStatement";
  }

  @Override
  @NotNull
  public String getDisplayName() {
    return InspectionGadgetsBundle.message("trivial.if.display.name");
  }

  @Override
  public boolean isEnabledByDefault() {
    return true;
  }

  @Override
  @NotNull
  protected String buildErrorString(Object... infos) {
    return InspectionGadgetsBundle.message("trivial.if.problem.descriptor");
  }

  @Override
  public InspectionGadgetsFix buildFix(Object... infos) {
    return new TrivialIfFix();
  }

  private static class TrivialIfFix extends InspectionGadgetsFix {

    @Override
    @NotNull
    public String getFamilyName() {
      return InspectionGadgetsBundle.message(
        "constant.conditional.expression.simplify.quickfix");
    }

    @Override
    public void doFix(Project project, ProblemDescriptor descriptor) {
      final PsiElement ifKeywordElement = descriptor.getPsiElement();
      final PsiIfStatement statement = (PsiIfStatement)ifKeywordElement.getParent();
      simplify(statement);
    }
  }

  public static void simplify(PsiIfStatement statement) {
    if (isSimplifiableAssignment(statement)) {
      replaceSimplifiableAssignment(statement);
    }
    else if (isSimplifiableReturn(statement)) {
      replaceSimplifiableReturn(statement);
    }
    else if (isSimplifiableImplicitReturn(statement)) {
      replaceSimplifiableImplicitReturn(statement);
    }
    else if (isSimplifiableAssignmentNegated(statement)) {
      replaceSimplifiableAssignmentNegated(statement);
    }
    else if (isSimplifiableReturnNegated(statement)) {
      replaceSimplifiableReturnNegated(statement);
    }
    else if (isSimplifiableImplicitReturnNegated(statement)) {
      replaceSimplifiableImplicitReturnNegated(statement);
    }
    else if (isSimplifiableImplicitAssignment(statement)) {
      replaceSimplifiableImplicitAssignment(statement);
    }
    else if (isSimplifiableImplicitAssignmentNegated(statement)) {
      replaceSimplifiableImplicitAssignmentNegated(statement);
    }
    else if (isSimplifiableAssert(statement)) {
      replaceSimplifiableAssert(statement);
    }
  }

  private static void replaceSimplifiableAssert(PsiIfStatement statement) {
    final PsiExpression condition = statement.getCondition();
    if (condition == null) {
      return;
    }
    final String conditionText = BoolUtils.getNegatedExpressionText(condition);
    if (statement.getElseBranch() != null) {
      return;
    }
    final PsiStatement thenBranch = ControlFlowUtils.stripBraces(statement.getThenBranch());
    if (!(thenBranch instanceof PsiAssertStatement)) {
      return;
    }
    final PsiAssertStatement assertStatement = (PsiAssertStatement)thenBranch;
    final PsiExpression assertCondition = assertStatement.getAssertCondition();
    if (assertCondition == null) {
      return;
    }
    final PsiExpression replacementCondition = JavaPsiFacade.getElementFactory(statement.getProject()).createExpressionFromText(
      BoolUtils.isFalse(assertCondition) ? conditionText : conditionText + "||" + assertCondition.getText(), statement);
    assertCondition.replace(replacementCondition);
    statement.replace(assertStatement);
  }

  private static void replaceSimplifiableImplicitReturn(PsiIfStatement statement) {
    final PsiExpression condition = statement.getCondition();
    if (condition == null) {
      return;
    }
    final String conditionText = condition.getText();
    final PsiElement nextStatement = PsiTreeUtil.skipWhitespacesForward(statement);
    @NonNls final String newStatement = "return " + conditionText + ';';
    PsiReplacementUtil.replaceStatement(statement, newStatement);
    assert nextStatement != null;
    nextStatement.delete();
  }

  private static void replaceSimplifiableReturn(PsiIfStatement statement) {
    final PsiExpression condition = statement.getCondition();
    if (condition == null) {
      return;
    }
    final Collection<PsiComment> comments = PsiTreeUtil.findChildrenOfType(statement, PsiComment.class);
    final PsiElement parent = statement.getParent();
    for (PsiComment comment : comments) {
      parent.addBefore(comment.copy(), statement);
    }
    final String conditionText = condition.getText();
    final @NonNls String newStatement = "return " + conditionText + ';';
    PsiReplacementUtil.replaceStatement(statement, newStatement);
  }

  private static void replaceSimplifiableAssignment(PsiIfStatement statement) {
    final PsiExpression condition = statement.getCondition();
    if (condition == null) {
      return;
    }
    final Collection<PsiComment> comments = ContainerUtil.map(PsiTreeUtil.findChildrenOfType(statement, PsiComment.class),
                                                              comment -> (PsiComment)comment.copy());
    final String conditionText = condition.getText();
    final PsiStatement thenBranch = statement.getThenBranch();
    final PsiExpressionStatement assignmentStatement = (PsiExpressionStatement)ControlFlowUtils.stripBraces(thenBranch);
    if (assignmentStatement == null) {
      return;
    }
    final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression)assignmentStatement.getExpression();
    final PsiJavaToken operator = assignmentExpression.getOperationSign();
    final String operand = operator.getText();
    final PsiExpression lhs = assignmentExpression.getLExpression();
    final String lhsText = lhs.getText();
    final PsiElement parent = statement.getParent();
    for (PsiComment comment : comments) {
      parent.addBefore(comment, statement);
    }
    PsiReplacementUtil.replaceStatement(statement, lhsText + operand + conditionText + ';');
  }

  private static void replaceSimplifiableImplicitAssignment(PsiIfStatement statement) {
    final PsiElement prevStatement = PsiTreeUtil.skipWhitespacesBackward(statement);
    if (prevStatement == null) {
      return;
    }
    final PsiExpression condition = statement.getCondition();
    if (condition == null) {
      return;
    }
    final String conditionText = condition.getText();
    final PsiStatement thenBranch = statement.getThenBranch();
    final PsiExpressionStatement assignmentStatement = (PsiExpressionStatement)ControlFlowUtils.stripBraces(thenBranch);
    if (assignmentStatement == null) {
      return;
    }
    final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression)assignmentStatement.getExpression();
    final PsiJavaToken operator = assignmentExpression.getOperationSign();
    final String operand = operator.getText();
    final PsiExpression lhs = assignmentExpression.getLExpression();
    final String lhsText = lhs.getText();
    PsiReplacementUtil.replaceStatement(statement, lhsText + operand + conditionText + ';');
    prevStatement.delete();
  }

  private static void replaceSimplifiableImplicitAssignmentNegated(PsiIfStatement statement) {
    final PsiElement prevStatement = PsiTreeUtil.skipWhitespacesBackward(statement);
    final PsiExpression condition = statement.getCondition();
    if (condition == null) {
      return;
    }
    final String conditionText = BoolUtils.getNegatedExpressionText(condition);
    final PsiStatement thenBranch = statement.getThenBranch();
    final PsiExpressionStatement assignmentStatement = (PsiExpressionStatement)ControlFlowUtils.stripBraces(thenBranch);
    if (assignmentStatement == null) {
      return;
    }
    final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression) assignmentStatement.getExpression();
    final PsiJavaToken operator = assignmentExpression.getOperationSign();
    final String operand = operator.getText();
    final PsiExpression lhs = assignmentExpression.getLExpression();
    final String lhsText = lhs.getText();
    PsiReplacementUtil.replaceStatement(statement, lhsText + operand + conditionText + ';');
    assert prevStatement != null;
    prevStatement.delete();
  }

  private static void replaceSimplifiableImplicitReturnNegated(PsiIfStatement statement) {
    final PsiExpression condition = statement.getCondition();
    if (condition == null) {
      return;
    }
    final String conditionText = BoolUtils.getNegatedExpressionText(condition);
    final PsiElement nextStatement = PsiTreeUtil.skipWhitespacesForward(statement);
    if (nextStatement == null) {
      return;
    }
    final PsiElement nextSibling = statement.getNextSibling();
    if (nextSibling != nextStatement) {
      statement.getParent().deleteChildRange(nextSibling, nextStatement.getPrevSibling());
    }
    @NonNls final String newStatement = "return " + conditionText + ';';
    PsiReplacementUtil.replaceStatement(statement, newStatement);
    nextStatement.delete();
  }

  private static void replaceSimplifiableReturnNegated(PsiIfStatement statement) {
    final PsiExpression condition = statement.getCondition();
    if (condition == null) {
      return;
    }
    final String conditionText = BoolUtils.getNegatedExpressionText(condition);
    @NonNls final String newStatement = "return " + conditionText + ';';
    PsiReplacementUtil.replaceStatement(statement, newStatement);
  }

  private static void replaceSimplifiableAssignmentNegated(PsiIfStatement statement) {
    final PsiExpression condition = statement.getCondition();
    if (condition == null) {
      return;
    }
    final String conditionText = BoolUtils.getNegatedExpressionText(condition);
    final PsiStatement thenBranch = statement.getThenBranch();
    final PsiExpressionStatement assignmentStatement = (PsiExpressionStatement)ControlFlowUtils.stripBraces(thenBranch);
    if (assignmentStatement == null) {
      return;
    }
    final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression)assignmentStatement.getExpression();
    final PsiJavaToken operator = assignmentExpression.getOperationSign();
    final String operand = operator.getText();
    final PsiExpression lhs = assignmentExpression.getLExpression();
    final String lhsText = lhs.getText();
    PsiReplacementUtil.replaceStatement(statement, lhsText + operand + conditionText + ';');
  }

  @Override
  public BaseInspectionVisitor buildVisitor() {
    return new TrivialIfVisitor();
  }

  private static class TrivialIfVisitor extends BaseInspectionVisitor {

    @Override
    public void visitIfStatement(@NotNull PsiIfStatement ifStatement) {
      super.visitIfStatement(ifStatement);
      final PsiExpression condition = ifStatement.getCondition();
      if (condition == null) {
        return;
      }
      if (isTrivial(ifStatement)) {
        registerStatementError(ifStatement);
      }
    }
  }

  public static boolean isTrivial(PsiIfStatement ifStatement) {
    if (PsiUtilCore.hasErrorElementChild(ifStatement)) {
      return false;
    }
    return isSimplifiableAssignment(ifStatement) ||
           isSimplifiableReturn(ifStatement) ||
           isSimplifiableImplicitReturn(ifStatement) ||
           isSimplifiableAssignmentNegated(ifStatement) ||
           isSimplifiableReturnNegated(ifStatement) ||
           isSimplifiableImplicitReturnNegated(ifStatement) ||
           isSimplifiableImplicitAssignment(ifStatement) ||
           isSimplifiableImplicitAssignmentNegated(ifStatement) ||
           isSimplifiableAssert(ifStatement);
  }

  private static boolean isSimplifiableImplicitReturn(PsiIfStatement ifStatement) {
    return isSimplifiableImplicitReturn(ifStatement, PsiKeyword.TRUE, PsiKeyword.FALSE);
  }

  private static boolean isSimplifiableImplicitReturnNegated(PsiIfStatement ifStatement) {
    return isSimplifiableImplicitReturn(ifStatement, PsiKeyword.FALSE, PsiKeyword.TRUE);
  }

  private static boolean isSimplifiableImplicitReturn(PsiIfStatement ifStatement, String thenReturn, String elseReturn) {
    if (ifStatement.getElseBranch() != null) {
      return false;
    }
    PsiStatement thenBranch = ifStatement.getThenBranch();
    thenBranch = ControlFlowUtils.stripBraces(thenBranch);
    final PsiElement nextStatement = PsiTreeUtil.skipWhitespacesForward(ifStatement);
    if (!(nextStatement instanceof PsiStatement)) {
      return false;
    }
    final PsiStatement elseBranch = (PsiStatement)nextStatement;
    return isReturn(thenBranch, thenReturn) && isReturn(elseBranch, elseReturn);
  }

  private static boolean isSimplifiableReturn(PsiIfStatement ifStatement) {
    return isSimplifiableReturn(ifStatement, PsiKeyword.TRUE, PsiKeyword.FALSE);
  }

  private static boolean isSimplifiableReturnNegated(PsiIfStatement ifStatement) {
    return isSimplifiableReturn(ifStatement, PsiKeyword.FALSE, PsiKeyword.TRUE);
  }

  private static boolean isSimplifiableReturn(PsiIfStatement ifStatement, String thenReturn, String elseReturn) {
    final PsiStatement thenBranch = ControlFlowUtils.stripBraces(ifStatement.getThenBranch());
    final PsiStatement elseBranch = ControlFlowUtils.stripBraces(ifStatement.getElseBranch());
    return isReturn(thenBranch, thenReturn) && isReturn(elseBranch, elseReturn);
  }

  private static boolean isSimplifiableAssignment(PsiIfStatement ifStatement) {
    return isSimplifiableAssignment(ifStatement, PsiKeyword.TRUE, PsiKeyword.FALSE);
  }

  private static boolean isSimplifiableAssignmentNegated(PsiIfStatement ifStatement) {
    return isSimplifiableAssignment(ifStatement, PsiKeyword.FALSE, PsiKeyword.TRUE);
  }

  private static boolean isSimplifiableAssignment(PsiIfStatement ifStatement, String thenAssignment, String elseAssignment) {
    final PsiStatement thenBranch = ControlFlowUtils.stripBraces(ifStatement.getThenBranch());
    final PsiStatement elseBranch = ControlFlowUtils.stripBraces(ifStatement.getElseBranch());
    return isSimplifiableAssignment(thenBranch, elseBranch, thenAssignment, elseAssignment);
  }

  private static boolean isSimplifiableImplicitAssignment(PsiIfStatement ifStatement) {
    return isSimplifiableImplicitAssignment(ifStatement, PsiKeyword.TRUE, PsiKeyword.FALSE);
  }

  private static boolean isSimplifiableImplicitAssignmentNegated(PsiIfStatement ifStatement) {
    return isSimplifiableImplicitAssignment(ifStatement, PsiKeyword.FALSE, PsiKeyword.TRUE);
  }

  private static boolean isSimplifiableImplicitAssignment(PsiIfStatement ifStatement, String thenAssignment, String elseAssignment) {
    if (ifStatement.getElseBranch() != null) {
      return false;
    }
    PsiStatement thenBranch = ifStatement.getThenBranch();
    thenBranch = ControlFlowUtils.stripBraces(thenBranch);
    final PsiElement nextStatement = PsiTreeUtil.skipWhitespacesBackward(ifStatement);
    if (!(nextStatement instanceof PsiStatement)) {
      return false;
    }
    PsiStatement elseBranch = (PsiStatement)nextStatement;
    elseBranch = ControlFlowUtils.stripBraces(elseBranch);
    return isSimplifiableAssignment(thenBranch, elseBranch, thenAssignment, elseAssignment);
  }

  private static boolean isSimplifiableAssignment(PsiStatement thenBranch,
                                                  PsiStatement elseBranch,
                                                  String thenAssignment,
                                                  String elseAssignment) {
    if (!isAssignment(thenBranch, thenAssignment) || !isAssignment(elseBranch, elseAssignment)) {
      return false;
    }
    final PsiExpressionStatement thenExpressionStatement = (PsiExpressionStatement)thenBranch;
    final PsiAssignmentExpression thenExpression = (PsiAssignmentExpression)thenExpressionStatement.getExpression();
    final PsiExpressionStatement elseExpressionStatement = (PsiExpressionStatement)elseBranch;
    final PsiAssignmentExpression elseExpression = (PsiAssignmentExpression)elseExpressionStatement.getExpression();
    final IElementType thenTokenType = thenExpression.getOperationTokenType();
    if (!thenTokenType.equals(elseExpression.getOperationTokenType())) {
      return false;
    }
    final PsiExpression thenLhs = thenExpression.getLExpression();
    final PsiExpression elseLhs = elseExpression.getLExpression();
    return EquivalenceChecker.getCanonicalPsiEquivalence().expressionsAreEquivalent(thenLhs, elseLhs);
  }

  private static boolean isReturn(PsiStatement statement, String value) {
    if (!(statement instanceof PsiReturnStatement)) {
      return false;
    }
    final PsiReturnStatement returnStatement = (PsiReturnStatement)statement;
    final PsiExpression returnValue = ParenthesesUtils.stripParentheses(returnStatement.getReturnValue());
    return returnValue != null && value.equals(returnValue.getText());
  }

  private static boolean isAssignment(PsiStatement statement, String value) {
    if (!(statement instanceof PsiExpressionStatement)) {
      return false;
    }
    final PsiExpressionStatement expressionStatement = (PsiExpressionStatement)statement;
    final PsiExpression expression = expressionStatement.getExpression();
    if (!(expression instanceof PsiAssignmentExpression)) {
      return false;
    }
    final PsiAssignmentExpression assignment = (PsiAssignmentExpression)expression;
    final PsiExpression rhs = ParenthesesUtils.stripParentheses(assignment.getRExpression());
    return rhs != null && value.equals(rhs.getText());
  }

  private static boolean isSimplifiableAssert(PsiIfStatement ifStatement) {
    if (ifStatement.getElseBranch() != null) {
      return false;
    }
    final PsiStatement thenBranch = ControlFlowUtils.stripBraces(ifStatement.getThenBranch());
    if (!(thenBranch instanceof PsiAssertStatement)) {
      return false;
    }
    final PsiAssertStatement assertStatement = (PsiAssertStatement)thenBranch;
    return assertStatement.getAssertCondition() != null;
  }
}


text:
/**
 * Forge SDK
 * The Forge Platform contains an expanding collection of web service components that can be used with Autodesk cloud-based products or your own technologies. Take advantage of Autodesk's expertise in design and engineering.
 *
 * Contact: forge.help@autodesk.com
 *
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen.git
 * Do not edit the class manually.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

module.exports = (function () {
  'use strict';

  var ApiClient = require('../ApiClient'),
    Item = require('./Item'),
    JsonApiDocument = require('./JsonApiDocument'),
    JsonApiLinksSelf = require('./JsonApiLinksSelf'),
    JsonApiResource = require('./JsonApiResource'),
    JsonApiVersionJsonapi = require('./JsonApiVersionJsonapi');

  /**
   * The ItemCreated model module.
   * @module model/ItemCreated
   */

  /**
   * Constructs a ItemCreated from a plain JavaScript object, optionally creating a new instance.
   * Copies all relevant properties from data to obj if supplied or a new instance if not.
   * @param {Object} data The plain JavaScript object bearing properties of interest.
   * @param {module:model/ItemCreated} obj Optional instance to populate.
   * @return {module:model/ItemCreated} The populated ItemCreated instance.
   */
  var constructFromObject = function (data, obj) {
    if (data) {
      obj = obj || new exports();

      JsonApiDocument.constructFromObject(data, obj);
      if (data.hasOwnProperty('jsonapi')) {
        obj.jsonapi = JsonApiVersionJsonapi.constructFromObject(data.jsonapi);
      }
      if (data.hasOwnProperty('data')) {
        obj.data = Item.constructFromObject(data.data);
      }
      if (data.hasOwnProperty('included')) {
        obj.included = ApiClient.convertToType(data.included, [JsonApiResource]);
      }
      if (data.hasOwnProperty('links')) {
        obj.links = JsonApiLinksSelf.constructFromObject(data.links);
      }
    }
    return obj;
  };

  /**
   * Constructs a new ItemCreated.
   * @alias module:model/ItemCreated
   * @class
   * @implements module:model/JsonApiDocument
   * @param data {module:model/Item}
   * @param links {module:model/JsonApiLinksSelf}
   * @param {Object} theData The plain JavaScript object bearing properties of interest.
   * @param {module:model/ItemCreated} obj Optional instance to populate.
   */
  var exports = function (data, links, theData, obj) {
    var _this = this;

    JsonApiDocument.call(_this, data, links);

    _this.data = data;
    _this.links = links;

    return constructFromObject(theData, obj || _this);
  };

  /**
   * Constructs a ItemCreated from a plain JavaScript object, optionally creating a new instance.
   * Copies all relevant properties from data to obj if supplied or a new instance if not.
   * @param {Object} data The plain JavaScript object bearing properties of interest.
   * @param {module:model/ItemCreated} obj Optional instance to populate.
   * @return {module:model/ItemCreated} The populated ItemCreated instance.
   */
  exports.constructFromObject = constructFromObject;

  /**
   * @member {module:model/JsonApiVersionJsonapi} jsonapi
   */
  exports.prototype.jsonapi = undefined;
  /**
   * @member {module:model/Item} data
   */
  exports.prototype.data = undefined;
  /**
   * @member {Array.<module:model/JsonApiResource>} included
   */
  exports.prototype.included = undefined;
  /**
   * @member {module:model/JsonApiLinksSelf} links
   */
  exports.prototype.links = undefined;

  return exports;
}());

redpajama_set_name: RedPajamaGithub


text:
// flow-typed signature: 26c4d2bd22357fb58d73ff00aebc4d94
// flow-typed version: <<STUB>>/cross-env_v^7.0.3/flow_v0.143.1

/**
 * This is an autogenerated libdef stub for:
 *
 *   'cross-env'
 *
 * Fill this stub out by replacing all the `any` types.
 *
 * Once filled out, we encourage you to share your work with the
 * community by sending a pull request to:
 * https://github.com/flowtype/flow-typed
 */

declare module 'cross-env' {
  declare module.exports: any;
}

/**
 * We include stubs for each file inside this npm package in case you need to
 * require those files directly. Feel free to delete any files that aren't
 * needed.
 */
declare module 'cross-env/src/bin/cross-env-shell' {
  declare module.exports: any;
}

declare module 'cross-env/src/bin/cross-env' {
  declare module.exports: any;
}

declare module 'cross-env/src/command' {
  declare module.exports: any;
}

declare module 'cross-env/src' {
  declare module.exports: any;
}

declare module 'cross-env/src/is-windows' {
  declare module.exports: any;
}

declare module 'cross-env/src/variable' {
  declare module.exports: any;
}

// Filename aliases
declare module 'cross-env/src/bin/cross-env-shell.js' {
  declare module.exports: $Exports<'cross-env/src/bin/cross-env-shell'>;
}
declare module 'cross-env/src/bin/cross-env.js' {
  declare module.exports: $Exports<'cross-env/src/bin/cross-env'>;
}
declare module 'cross-env/src/command.js' {
  declare module.exports: $Exports<'cross-env/src/command'>;
}
declare module 'cross-env/src/index' {
  declare module.exports: $Exports<'cross-env/src'>;
}
declare module 'cross-env/src/index.js' {
  declare module.exports: $Exports<'cross-env/src'>;
}
declare module 'cross-env/src/is-windows.js' {
  declare module.exports: $Exports<'cross-env/src/is-windows'>;
}
declare module 'cross-env/src/variable.js' {
  declare module.exports: $Exports<'cross-env/src/variable'>;
}


text:
using Orchard.Environment.Extensions;
using Orchard.Localization;
using Orchard.Packaging.Helpers;
using Orchard.UI.Navigation;

namespace Orchard.Packaging.Navigation {
    [OrchardFeature("Gallery")]
    public class AdminMenu : INavigationProvider {
        public Localizer T { get; set; }

        public string MenuName { get { return "admin"; } }

        public void GetNavigation(NavigationBuilder builder) {
            builder
                .Add(T("Modules"),
                    menu => menu
                        .Add(T("Gallery"), "3", item => NavigationHelpers.Describe(item, "Modules", "Gallery", true)),
                    new[] {"plugin"})
                .Add(T("Themes"),
                    menu => menu
                        .Add(T("Gallery"), "3", item => NavigationHelpers.Describe(item, "Themes", "Gallery", true)),
                    new[] {"paint"});
        }
    }
}


text:
#include "JTrack.h"
#include "XTrack.h"
//#include "XNotesView.h"
#include "JMessages.h"
#include "GraphicsDef.h"
#include "Pattern.h"
#include "PictureButton.h"
#include "Track.h"
#include "GfxMsg.h"
//#include "PopUpMenu.h"
#include "pot.h"
#include "stdio.h"
#include "Xed_Utils.h"

#include "TextControlFloater.h"

#define	POT_X		TRACK_LX+TRACK_MENU_LX+70+SBUTTON_W+10
#define	POT_Y		0
#define	POT_H		24
#define	POT_L		24

#include "ColorsDef.h"

#define	MSG_N		'plut'
const 	rgb_color  	onc 	={255,52,49};//{81,110,117,255};
//const 	rgb_color  	offc 	={57,186,255};//{107,146,156,255};

JTrack::JTrack(BRect rect,int16 n,BView* v,uint32 type,const char*na):BView(rect,"_jtrack",B_FOLLOW_LEFT ,B_WILL_DRAW|B_FRAME_EVENTS|B_NAVIGABLE_JUMP),
id(n),flags(type),name_pad(na)
{
	SetViewColor(bkColor);

	tv=v;
	popup=NULL;

	SetHighColor(0, 0, 0, 0);
	FillRect(Bounds());
        	SetDrawingMode(B_OP_ALPHA);
        	SetHighColor(0, 0, 0, 128);
        	SetBlendingMode(B_CONSTANT_ALPHA, B_ALPHA_COMPOSITE);
        //	DrawBitmap(mSmallIcon);

	AddChild(volpot=new BPot(BRect(545,POT_Y,545+POT_H,POT_Y+POT_L), "name","pippo",new BMessage(TRACK_VOL),new BMessage(TRACK_ON),0, 100, ::MakeBitmapSkin("volpad"),::MakeBitmapSkin("volpadoff"),B_FOLLOW_NONE,B_WILL_DRAW|B_FRAME_EVENTS|B_NAVIGABLE_JUMP));
	AddChild(panpot=new BPot(BRect(550+POT_H+3,POT_Y+3,550+POT_H+3+18,POT_Y+21), "pan","pippo",new BMessage(TRACK_PAN),new BMessage(PAN_RESET),-100, 100,::MakeBitmapSkin("panpad"),NULL, B_FOLLOW_NONE,B_WILL_DRAW|B_FRAME_EVENTS|B_NAVIGABLE_JUMP));

}

void
JTrack::RControl()
{
	//popup = new BPopUpMenu("");
	//popup->SetLabelFromMarked(true);
	AddChild(button_mode = new BPictureButton(BRect(530,2,530+TRACK_MENU_LX,11),"button_mode",::MakePictureSkin("TrackModeVolumeOff",tv),::MakePictureSkin("TrackModeVolumeOn",tv),new BMessage(TRACK_MODE),B_TWO_STATE_BUTTON));
	if(flags&JTRACK_VST) AddChild(button_fx1 =new BPictureButton(BRect(0,6,SBUTTON_W-12,6+SBUTTON_H),"",::MakePictureSkin("ButtonFXOff",tv),::MakePictureSkin("ButtonFXOn",tv),new BMessage(TRACK_FX1),B_TWO_STATE_BUTTON));
	if(flags&JTRACK_VST) AddChild(button_fx_line=new BPictureButton(BRect(21,6,SBUTTON_W,6+SBUTTON_H),"",::MakePictureSkin("ButtonFXLine1",tv),::MakePictureSkin("ButtonFXLine2",tv),new BMessage(TRACK_FXLINE),B_TWO_STATE_BUTTON));
	if(flags&JTRACK_MENU) AddChild(trackmenu=new BPictureButton(BRect(1+SBUTTON_W+TRACK_LX+1,0,1+SBUTTON_W+TRACK_MENU_LX+TRACK_LX,TRACK_MENU_LY),"_menu",::MakePictureSkin("TrackMenuOff",tv),::MakePictureSkin("TrackMenuOn",tv),new BMessage(POPUPMENU),B_ONE_STATE_BUTTON));
	AddChild(xtr=new XTrack(BRect(1+SBUTTON_W,0,1+SBUTTON_W+TRACK_LX,TRACK_LY-1),::MakeBitmapSkin("TrackNameOn"),::MakeBitmapSkin(name_pad),"UnSet!"));
	AddChild(vnc=new XNotesView( BRect(160,0,530,BUTTON_LY),tv,id));
	if(flags&JTRACK_NOTE) AddChild( button_piano=new BPictureButton(BRect(530,13,530+TRACK_MENU_LX,22),"button_mode",::MakePictureSkin("TrackModePianoOff",tv),::MakePictureSkin("TrackModePianoOn",tv),new BMessage(MSG_N),B_ONE_STATE_BUTTON));
}

void
JTrack::MessageReceived(BMessage* message)
{

	if(message->what>1000 && message->what<2000)
	{
		if(message->what>1900) Window()->PostMessage(message);
		else Window()->PostMessage(new BMessage(GENERIC));
	}

	switch(message->what)
	{

	case TRACK_ON:
		myTrack->setOn(volpot->isOn());
	break;
	case TRACK_VOL:
		myTrack->setVolume((float)volpot->Value()/(float)100);
	break;
	case TRACK_PAN:
		myTrack->setPan((float)panpot->Value()/(float)100);
	break;
	case	B_SIMPLE_DATA:
	break;
	case PAN_RESET:
		myTrack->setPan(0);
		panpot->SetValue(0);
	break;

	case MSG_N:
		vnc->ShowPiano(false);
	break;

	case TRACK_MODE:

		if(vnc->getType()==0) vnc->setType(1);
			else
			vnc->setType(0);
	break;
	case TRACK_FX1:
		if(flags&JTRACK_VST) myTrack->setFX1On(button_fx1->Value());
	break;
	case TRACK_FXLINE:
	if(flags&JTRACK_VST)
		if(button_fx_line->Value())
			myTrack->setFX1Line(1);
			else
			myTrack->setFX1Line(0);

	break;
	case TRACK_SET:
		Window()->PostMessage(message,Parent());
	break;

	case JMSG_NAME_SET:

		if(myTrack==NULL) return;

		const char* name;
		message->FindString("_value", &name);

		myTrack->LockName(false);

		if(strlen(name)>0)
			{
				SetName(name);
				myTrack->LockName(true);
			}

			else
				{
					myTrack->ResetName();
					xtr->SetName(myTrack->getName());
				}

		Window()->CurrentFocus()->SetEventMask(B_KEYBOARD_EVENTS);
	break;
	case JMSG_NAME_NOTSET:
		//Window()->PostMessage(2227);
		//printf("Activationz..\n");
		Window()->CurrentFocus()->SetEventMask(B_KEYBOARD_EVENTS);
	break;

	case 'ttt':
		{

		BPoint f,t;

		message->FindPoint("from", &f);
		message->FindPoint("to", &t);
		/*  Disabling KeyBoard for MainWindow */
		Window()->CurrentFocus()->SetEventMask(0);

		new TextControlFloater(BRect(f,t),B_ALIGN_LEFT,be_plain_font,myTrack->getName(),this,new BMessage(JMSG_NAME_SET),new BMessage(JMSG_NAME_NOTSET));

		}
	break;
	default:

		BView::MessageReceived(message);

		break;
	}

}
void
JTrack::ShowMenu()
{
	BMenuItem*	selected;
	BPoint	point(TRACK_LX,0);

	ConvertToScreen(&point);
	selected=popup->Go(point,true,true,true);
}
void
JTrack::Init(BView *t,BMessage *m)
{
	// Init del XNotesView
	xtr->Init(this,m);
	vnc->Init();
	if(flags&JTRACK_NOTE) button_piano->SetTarget(this);
	if(flags&JTRACK_VST) button_fx1->SetTarget(this);
	if(flags&JTRACK_VST) button_fx_line->SetTarget(this);
	button_mode->SetTarget(this);
	if(flags&JTRACK_MENU) trackmenu->SetTarget(this);
	volpot->SetTarget(this);
	panpot->SetTarget(this);
}
void
JTrack::Reset(Pattern* p ,Track* tr)
{

	myTrack=tr;
	myPat=p;

	int poz;
	if(myPat->getNumberNotes()>NUM_NOTES) poz=myPat->getNumberNotes();
	else
	poz=NUM_NOTES;

		vnc->ResizeTo(23*poz+2,vnc->Frame().Height());
		vnc->ClosePiano();

		ResizeTo(160+23*poz+2+97,Frame().Height());

		volpot->MoveTo(160+23*poz+17,volpot->Frame().top);
		panpot->MoveTo(160+23*poz+49,panpot->Frame().top);
		button_mode->MoveTo(160+23*poz+2,button_mode->Frame().top);
		if(flags&JTRACK_NOTE)
							button_piano->MoveTo(160+23*poz+2,button_piano->Frame().top);

	if(flags&JTRACK_VST) button_fx1->SetValue(myTrack->isFX1On());
	if(flags&JTRACK_VST) button_fx_line->SetValue(myTrack->getFX1Line());
	volpot->SetValue(myTrack->getVolume()*100);
	volpot->SetOn(myTrack->isOn());
	panpot->SetValue(myTrack->getPan()*100);

	if(tr->getType()==UNSET_TYPE) SetName("UnSet!");
	else
		SetName(tr->getName());

	vnc->Reset(p,false);

}
void
JTrack::SetName(const char* t)
{
	if(myTrack==NULL) return;

	if(Window()->Lock())
	{
		myTrack->setName(t);
		xtr->SetName(myTrack->getName());
		Window()->Unlock();
	}
}

void
JTrack::Refresh(Pattern* p )
{

	myPat=p;
	vnc->Reset(p,false);
}
void
JTrack::Select()
{
	xtr->Select();
}
int
JTrack::getModel()
{
	return 0;
}
void
JTrack::Deselect()
{
	xtr->Deselect();
}
void
JTrack::Mute(bool b,bool c)
{

	//ATTENZIONE! ->Mute() si comporta non come sembra..

	if(!c)
		volpot->SetOn(!volpot->isOn());

	else
		volpot->SetOn(b);

	myTrack->setOn(volpot->isOn());
}


text:
package io.netty.resolver;

import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.FutureListener;
import io.netty.util.concurrent.Promise;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.UnstableApi;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * A {@link NameResolver} that resolves {@link InetAddress} and force Round Robin by choosing a single address
 * randomly in {@link #resolve(String)} and {@link #resolve(String, Promise)}
 * if multiple are returned by the {@link NameResolver}.
 * Use {@link #asAddressResolver()} to create a {@link InetSocketAddress} resolver
 */
@UnstableApi
public class RoundRobinInetAddressResolver extends InetNameResolver {
    private final NameResolver<InetAddress> nameResolver;

    /**
     * @param executor the {@link EventExecutor} which is used to notify the listeners of the {@link Future} returned by
     * {@link #resolve(String)}
     * @param nameResolver the {@link NameResolver} used for name resolution
     */
    public RoundRobinInetAddressResolver(EventExecutor executor, NameResolver<InetAddress> nameResolver) {
        super(executor);
        this.nameResolver = nameResolver;
    }

    @Override
    protected void doResolve(final String inetHost, final Promise<InetAddress> promise) throws Exception {
        // hijack the doResolve request, but do a doResolveAll request under the hood.
        // Note that InetSocketAddress.getHostName() will never incur a reverse lookup here,
        // because an unresolved address always has a host name.
        nameResolver.resolveAll(inetHost).addListener(new FutureListener<List<InetAddress>>() {
            @Override
            public void operationComplete(Future<List<InetAddress>> future) throws Exception {
                if (future.isSuccess()) {
                    List<InetAddress> inetAddresses = future.getNow();
                    int numAddresses = inetAddresses.size();
                    if (numAddresses > 0) {
                        // if there are multiple addresses: we shall pick one by one
                        // to support the round robin distribution
                        promise.setSuccess(inetAddresses.get(randomIndex(numAddresses)));
                    } else {
                        promise.setFailure(new UnknownHostException(inetHost));
                    }
                } else {
                    promise.setFailure(future.cause());
                }
            }
        });
    }

    @Override
    protected void doResolveAll(String inetHost, final Promise<List<InetAddress>> promise) throws Exception {
        nameResolver.resolveAll(inetHost).addListener(new FutureListener<List<InetAddress>>() {
            @Override
            public void operationComplete(Future<List<InetAddress>> future) throws Exception {
                if (future.isSuccess()) {
                    List<InetAddress> inetAddresses = future.getNow();
                    if (!inetAddresses.isEmpty()) {
                        // create a copy to make sure that it's modifiable random access collection
                        List<InetAddress> result = new ArrayList<InetAddress>(inetAddresses);
                        // rotate by different distance each time to force round robin distribution
                        Collections.rotate(result, randomIndex(inetAddresses.size()));
                        promise.setSuccess(result);
                    } else {
                        promise.setSuccess(inetAddresses);
                    }
                } else {
                    promise.setFailure(future.cause());
                }
            }
        });
    }

    private static int randomIndex(int numAddresses) {
        return numAddresses == 1 ? 0 : PlatformDependent.threadLocalRandom().nextInt(numAddresses);
    }

    @Override
    public void close() {
        nameResolver.close();
    }
}


text:
using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Newtonsoft.Json;

namespace MiniPie.Core
{
    public static class Helper
    {
        public static void OpenUrl(string url)
        {
            Process.Start(url);
        }

        public static string MakeNiceSize(double size)
        {
            var suffix = new[] { "B", "KB", "MB", "GB", "TB", "PB", "EB" };
            var run = 0;
            while (size >= 1024)
            {
                size /= 1024;
                run++;
            }
            return Math.Round(size, 2).ToString("0.00") + " " + suffix[run];
        }

        public static ImageSource GetImageSourceFromResource(string psResourceName)
        {
            try
            {
                var oUri = new Uri("pack://application:,,,/MiniPie;component/" + psResourceName,
                    UriKind.RelativeOrAbsolute);
                return BitmapFrame.Create(oUri);
            }
            catch (FileFormatException)
            {
                return null;
            }
        }

        public static Task<string> SerializeObjectAsync<T>(T value)
        {
            return Task.Run(() => JsonConvert.SerializeObject(value));
        }

        public static Task SerializeToStreamAsync<T>(T value, Stream stream)
        {
            return Task.Run(() =>
            {
                var sw = new StreamWriter(stream);
                var serializer = new JsonSerializer();
                serializer.Serialize(sw, value);
                sw.Flush();
            });
        }

        public static Task<T> DeserializeStringAsync<T>(string value)
        {
            return Task.Run(() => JsonConvert.DeserializeObject<T>(value));
        }

        public static Task<T> DeserializeStreamAsync<T>(Stream input)
        {
            return Task.Run(() =>
            {
                using (StreamReader sr = new StreamReader(input))
                using (JsonReader reader = new JsonTextReader(sr))
                {
                    var serializer = new JsonSerializer();

                    // read the json from a stream
                    // json size doesn't matter because only a small piece is read at a time from the HTTP request
                    var result = serializer.Deserialize<T>(reader);
                    return result;
                }
            });
        }
    }
}


text:
tempfile=`mktemp`
result=1

# cleanup on exit
trap 'rm -f ${tempfile}; exit ${result}' EXIT TERM ALRM

# save data to temp file
cat > ${tempfile}

# make up some complicated rules
test $(grep -c A ${tempfile}) -ge 8 || exit                     # more than 8 lines with 'A'
test $(grep -c ^puppy$ ${tempfile}) -eq 1 || exit               # must contain a puppy
test $(sort ${tempfile} | uniq -d | wc -l) -eq 0  || exit       # no repeats

# looks good
result=0


text:
Bulgaria, 2015-06-09

Prodax Ltd. agrees to the terms of the Odoo Corporate Contributor License
Agreement v1.0.

I declare that I am authorized and able to make this agreement and sign this
declaration.

Signed,

Donka Lapunova donka64@mail.bg https://github.com/OdooBulgaria

List of contributors:

Donka Lapunova donka64@mail.bg https://github.com/donchetoo

Vassil Toumbev vassy@mail.bg https://github.com/vassy


text:
package org.iotivity.test.rfw.common.devicecontroller.linux;

import java.util.HashMap;
import java.util.logging.Logger;

import org.iotivity.test.rfw.common.devicecontroller.interfaces.ILogObservable;
import org.iotivity.test.rfw.common.devicecontroller.interfaces.ILogObserver;
import org.iotivity.test.rfw.common.devicecontroller.interfaces.IProcess;
import org.iotivity.test.rfw.common.devicecontroller.interfaces.IProcessManager;
import org.iotivity.test.rfw.common.util.IoTivityLogger;

import org.iotivity.test.rfw.common.devicecontroller.linux.LinuxProcess;

public class LinuxProcessManager implements IProcessManager {
    private Logger                    logger = IoTivityLogger.GetLogger();
    private HashMap<String, IProcess> processMap;

    public LinuxProcessManager() {
        processMap = new HashMap<String, IProcess>();
    }

    @Override
    public boolean createProcess(String processName, String processCommand) {
        processName = convertProcessName(processName);

        LinuxProcess linuxProcess = new LinuxProcess(processName, processCommand);

        processMap.put(processName, linuxProcess);

        return true;
    }

    @Override
    public boolean removeProcess(String processName) {
        try {
            processName = convertProcessName(processName);

            if (processMap.get(processName).isProcessRunning())
                processMap.get(processName).destroy();

            processMap.remove(processName);

            return true;
        } catch (Exception ex) {
            return false;
        }
    }

    @Override
    public boolean removeAllProcess() {
        for (String tempProcessID : processMap.keySet()) {
            if (processMap.get(tempProcessID).isProcessRunning())
                processMap.get(tempProcessID).destroy();
        }
        processMap.clear();

        return true;
    }

    @Override
    public boolean inputProcessCommand(String processName, String command) {
        processName = convertProcessName(processName);

        if (processMap.containsKey(processName))
            return processMap.get(processName).inputCommand(command);
        else
            return false;
    }

    @Override
    public boolean registerOutput(String processName, ILogObserver observer) {
        processName = convertProcessName(processName);

        if (processMap.containsKey(processName)) {

            ILogObservable logObservable = processMap.get(processName).getObserverable();
            logObservable.addObserver(observer);
            logObservable.notifyObervers();

            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean unregisterOutput(String processName, ILogObserver observer) {
        processName = convertProcessName(processName);

        if (processMap.containsKey(processName))
            return processMap.get(processName).getObserverable()
                    .removeObserver(observer);
        else
            return false;
    }

    @Override
    public boolean isProcessRunning(String processName) {
        processName = convertProcessName(processName);

        if (processMap.containsKey(processName))
            return processMap.get(processName).isProcessRunning();
        else
            return false;
    }

    @Override
    public ILogObservable getObserverable(String processName) {
        processName = convertProcessName(processName);

        if (processMap.containsKey(processName))
            return processMap.get(processName).getObserverable();

        return null;
    }

    private String convertProcessName(String processName) {
        String simpleProcessName = processName.replaceAll(" ", "_").split(
                "/")[processName.replaceAll(" ", "_").split("/").length - 1];

        return simpleProcessName;
    }
}


text:
from __future__ import absolute_import
from scapy.packet import *
from scapy.fields import *
from scapy.layers.inet6 import *
from scapy.modules.six.moves import range

#####################################################################
# Helpers and constants
#####################################################################

# CDP TLV classes keyed by type
_cdp_tlv_cls = { 0x0001: "CDPMsgDeviceID",
                 0x0002: "CDPMsgAddr",
                 0x0003: "CDPMsgPortID",
                 0x0004: "CDPMsgCapabilities",
                 0x0005: "CDPMsgSoftwareVersion",
                 0x0006: "CDPMsgPlatform",
                 0x0007: "CDPMsgIPPrefix",
                 0x0008: "CDPMsgProtoHello",
                 0x0009: "CDPMsgVTPMgmtDomain", # CDPv2
                 0x000a: "CDPMsgNativeVLAN",    # CDPv2
                 0x000b: "CDPMsgDuplex",        #
#                 0x000c: "CDPMsgGeneric",
#                 0x000d: "CDPMsgGeneric",
                 0x000e: "CDPMsgVoIPVLANReply",
                 0x000f: "CDPMsgVoIPVLANQuery",
                 0x0010: "CDPMsgPower",
                 0x0011: "CDPMsgMTU",
                 0x0012: "CDPMsgTrustBitmap",
                 0x0013: "CDPMsgUntrustedPortCoS",
#                 0x0014: "CDPMsgSystemName",
#                 0x0015: "CDPMsgSystemOID",
                 0x0016: "CDPMsgMgmtAddr",
#                 0x0017: "CDPMsgLocation",
                 0x0019: "CDPMsgUnknown19",
#                 0x001a: "CDPPowerAvailable"
                 }

_cdp_tlv_types = { 0x0001: "Device ID",
                   0x0002: "Addresses",
                   0x0003: "Port ID",
                   0x0004: "Capabilities",
                   0x0005: "Software Version",
                   0x0006: "Platform",
                   0x0007: "IP Prefix",
                   0x0008: "Protocol Hello",
                   0x0009: "VTP Management Domain", # CDPv2
                   0x000a: "Native VLAN",    # CDPv2
                   0x000b: "Duplex",        #
                   0x000c: "CDP Unknown command (send us a pcap file)",
                   0x000d: "CDP Unknown command (send us a pcap file)",
                   0x000e: "VoIP VLAN Reply",
                   0x000f: "VoIP VLAN Query",
                   0x0010: "Power",
                   0x0011: "MTU",
                   0x0012: "Trust Bitmap",
                   0x0013: "Untrusted Port CoS",
                   0x0014: "System Name",
                   0x0015: "System OID",
                   0x0016: "Management Address",
                   0x0017: "Location",
                   0x0018: "CDP Unknown command (send us a pcap file)",
                   0x0019: "CDP Unknown command (send us a pcap file)",
                   0x001a: "Power Available"}

def _CDPGuessPayloadClass(p, **kargs):
    cls = conf.raw_layer
    if len(p) >= 2:
        t = struct.unpack("!H", p[:2])[0]
        clsname = _cdp_tlv_cls.get(t, "CDPMsgGeneric")
        cls = globals()[clsname]

    return cls(p, **kargs)

class CDPMsgGeneric(Packet):
    name = "CDP Generic Message"
    fields_desc = [ XShortEnumField("type", None, _cdp_tlv_types),
                    FieldLenField("len", None, "val", "!H"),
                    StrLenField("val", "", length_from=lambda x:x.len - 4) ]

    def guess_payload_class(self, p):
        return conf.padding_layer # _CDPGuessPayloadClass

class CDPMsgDeviceID(CDPMsgGeneric):
    name = "Device ID"
    type = 0x0001

_cdp_addr_record_ptype = {0x01: "NLPID", 0x02: "802.2"}
_cdp_addrrecord_proto_ip = b"\xcc"
_cdp_addrrecord_proto_ipv6 = b"\xaa\xaa\x03\x00\x00\x00\x86\xdd"

class CDPAddrRecord(Packet):
    name = "CDP Address"
    fields_desc = [ ByteEnumField("ptype", 0x01, _cdp_addr_record_ptype),
                    FieldLenField("plen", None, "proto", "B"),
                    StrLenField("proto", None, length_from=lambda x:x.plen),
                    FieldLenField("addrlen", None, length_of=lambda x:x.addr),
                    StrLenField("addr", None, length_from=lambda x:x.addrlen)]

    def guess_payload_class(self, p):
        return conf.padding_layer

class CDPAddrRecordIPv4(CDPAddrRecord):
    name = "CDP Address IPv4"
    fields_desc = [ ByteEnumField("ptype", 0x01, _cdp_addr_record_ptype),
                    FieldLenField("plen", 1, "proto", "B"),
                    StrLenField("proto", _cdp_addrrecord_proto_ip, length_from=lambda x:x.plen),
                    ShortField("addrlen", 4),
                    IPField("addr", "0.0.0.0")]

class CDPAddrRecordIPv6(CDPAddrRecord):
    name = "CDP Address IPv6"
    fields_desc = [ ByteEnumField("ptype", 0x02, _cdp_addr_record_ptype),
                    FieldLenField("plen", 8, "proto", "B"),
                    StrLenField("proto", _cdp_addrrecord_proto_ipv6, length_from=lambda x:x.plen),
                    ShortField("addrlen", 16),
                    IP6Field("addr", "::1")]

def _CDPGuessAddrRecord(p, **kargs):
    cls = conf.raw_layer
    if len(p) >= 2:
        plen = struct.unpack("B", p[1])[0]
        proto = ''.join(struct.unpack("s" * plen, p[2:plen + 2])[0:plen])

        if proto == _cdp_addrrecord_proto_ip:
            clsname = "CDPAddrRecordIPv4"
        elif proto == _cdp_addrrecord_proto_ipv6:
            clsname = "CDPAddrRecordIPv6"
        else:
            clsname = "CDPAddrRecord"

        cls = globals()[clsname]

    return cls(p, **kargs)

class CDPMsgAddr(CDPMsgGeneric):
    name = "Addresses"
    fields_desc = [ XShortEnumField("type", 0x0002, _cdp_tlv_types),
                    ShortField("len", None),
                    FieldLenField("naddr", None, "addr", "!I"),
                    PacketListField("addr", [], _CDPGuessAddrRecord, count_from=lambda x:x.naddr) ]

    def post_build(self, pkt, pay):
        if self.len is None:
            l = 8 + len(self.addr) * 9
            pkt = pkt[:2] + struct.pack("!H", l) + pkt[4:]
        p = pkt + pay
        return p

class CDPMsgPortID(CDPMsgGeneric):
    name = "Port ID"
    fields_desc = [ XShortEnumField("type", 0x0003, _cdp_tlv_types),
                    FieldLenField("len", None, "iface", "!H"),
                    StrLenField("iface", "Port 1", length_from=lambda x:x.len - 4) ]

_cdp_capabilities = ["Router",
                     "TransparentBridge",
                     "SourceRouteBridge",
                     "Switch",
                     "Host",
                     "IGMPCapable",
                     "Repeater"] + ["Bit%d" % x for x in range(25, 0, -1)]

class CDPMsgCapabilities(CDPMsgGeneric):
    name = "Capabilities"
    fields_desc = [ XShortEnumField("type", 0x0004, _cdp_tlv_types),
                    ShortField("len", 8),
                    FlagsField("cap", 0, 32,  _cdp_capabilities) ]

class CDPMsgSoftwareVersion(CDPMsgGeneric):
    name = "Software Version"
    type = 0x0005

class CDPMsgPlatform(CDPMsgGeneric):
    name = "Platform"
    type = 0x0006

_cdp_duplex = { 0x00: "Half", 0x01: "Full" }

# ODR Routing
class CDPMsgIPPrefix(CDPMsgGeneric):
    name = "IP Prefix"
    type = 0x0007
    fields_desc = [ XShortEnumField("type", 0x0007, _cdp_tlv_types),
                    ShortField("len", 8),
                    IPField("defaultgw", "192.168.0.1") ]

class CDPMsgProtoHello(CDPMsgGeneric):
    name = "Protocol Hello"
    type = 0x0008
    fields_desc = [ XShortEnumField("type", 0x0008, _cdp_tlv_types),
                    ShortField("len", 32),
                    X3BytesField("oui", 0x00000c),
                    XShortField("protocol_id", 0x0),
                    # TLV length (len) - 2 (type) - 2 (len) - 3 (OUI) - 2
                    # (Protocol ID)
                    StrLenField("data", "", length_from=lambda p: p.len - 9) ]

class CDPMsgVTPMgmtDomain(CDPMsgGeneric):
    name = "VTP Management Domain"
    type = 0x0009

class CDPMsgNativeVLAN(CDPMsgGeneric):
    name = "Native VLAN"
    fields_desc = [ XShortEnumField("type", 0x000a, _cdp_tlv_types),
                    ShortField("len", 6),
                    ShortField("vlan", 1) ]

class CDPMsgDuplex(CDPMsgGeneric):
    name = "Duplex"
    fields_desc = [ XShortEnumField("type", 0x000b, _cdp_tlv_types),
                    ShortField("len", 5),
                    ByteEnumField("duplex", 0x00, _cdp_duplex) ]

class CDPMsgVoIPVLANReply(CDPMsgGeneric):
    name = "VoIP VLAN Reply"
    fields_desc = [ XShortEnumField("type", 0x000e, _cdp_tlv_types),
                    ShortField("len", 7),
                    ByteField("status?", 1),
                    ShortField("vlan", 1) ]

class CDPMsgVoIPVLANQuery(CDPMsgGeneric):
    name = "VoIP VLAN Query"
    type = 0x000f
    fields_desc = [ XShortEnumField("type", 0x000f, _cdp_tlv_types),
                    ShortField("len", 7),
                    XByteField("unknown1", 0),
                    ShortField("vlan", 1),
                    # TLV length (len) - 2 (type) - 2 (len) - 1 (unknown1) - 2 (vlan)
                    StrLenField("unknown2", "", length_from=lambda p: p.len - 7) ]

class _CDPPowerField(ShortField):
    def i2repr(self, pkt, x):
        if x is None:
            x = 0
        return "%d mW" % x

class CDPMsgPower(CDPMsgGeneric):
    name = "Power"
    # Check if field length is fixed (2 bytes)
    fields_desc = [ XShortEnumField("type", 0x0010, _cdp_tlv_types),
                    ShortField("len", 6),
                    _CDPPowerField("power", 1337)]

class CDPMsgMTU(CDPMsgGeneric):
    name = "MTU"
    # Check if field length is fixed (2 bytes)
    fields_desc = [ XShortEnumField("type", 0x0011, _cdp_tlv_types),
                    ShortField("len", 6),
                    ShortField("mtu", 1500)]

class CDPMsgTrustBitmap(CDPMsgGeneric):
    name = "Trust Bitmap"
    fields_desc = [ XShortEnumField("type", 0x0012, _cdp_tlv_types),
                    ShortField("len", 5),
                    XByteField("trust_bitmap", 0x0) ]

class CDPMsgUntrustedPortCoS(CDPMsgGeneric):
    name = "Untrusted Port CoS"
    fields_desc = [ XShortEnumField("type", 0x0013, _cdp_tlv_types),
                    ShortField("len", 5),
                    XByteField("untrusted_port_cos", 0x0) ]

class CDPMsgMgmtAddr(CDPMsgAddr):
    name = "Management Address"
    type = 0x0016

class CDPMsgUnknown19(CDPMsgGeneric):
    name = "Unknown CDP Message"
    type = 0x0019

class CDPMsg(CDPMsgGeneric):
    name = "CDP "
    fields_desc = [ XShortEnumField("type", None, _cdp_tlv_types),
                    FieldLenField("len", None, "val", "!H"),
                    StrLenField("val", "", length_from=lambda x:x.len - 4) ]

class _CDPChecksum:
    def _check_len(self, pkt):
        """Check for odd packet length and pad according to Cisco spec.
        This padding is only used for checksum computation.  The original
        packet should not be altered."""
        if len(pkt) % 2:
            last_chr = pkt[-1]
            if last_chr <= b'\x80':
                return pkt[:-1] + b'\x00' + last_chr
            else:
                return pkt[:-1] + b'\xff' + chr(ord(last_chr) - 1)
        else:
            return pkt

    def post_build(self, pkt, pay):
        p = pkt + pay
        if self.cksum is None:
            cksum = checksum(self._check_len(p))
            p = p[:2] + struct.pack("!H", cksum) + p[4:]
        return p

class CDPv2_HDR(_CDPChecksum, CDPMsgGeneric):
    name = "Cisco Discovery Protocol version 2"
    fields_desc = [ ByteField("vers", 2),
                    ByteField("ttl", 180),
                    XShortField("cksum", None),
                    PacketListField("msg", [], _CDPGuessPayloadClass) ]

bind_layers(SNAP, CDPv2_HDR, {"code": 0x2000, "OUI": 0xC})


text:
<?php

class WCML_Compatibility_Helper{

    function get_product_type($product_id){

        if ( $terms = wp_get_object_terms( $product_id, 'product_type' ) ) {
            $product_type = sanitize_title( current( $terms )->name );
        } else {
            $product_type = apply_filters( 'default_product_type', 'simple' );
        }

        return $product_type;

    }

}

?>


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package org.dionizdev;

/**
 *
 * @author eduardo
 */
public class main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        TimeHandler timer = new TimeHandler();
        AlgorithmHandler algorithm = new AlgorithmHandler("org.dionizdev.Knapsack_dinamic", 10,5);
        algorithm.generate_test();

        timer.start();
            algorithm.run();
        timer.stop();

        System.out.println("Tiempo de ejecución total: " + timer.last() + "ns");
        algorithm.output_toFile();
    }

}


text:
using bvmfscrapper.helpers;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;

namespace bvmfscrapper
{
    public static class DbContextExtensions
    {
        public static DbContext UseLog4NetAsLogger(this DbContext context)
        {
            var serviceProvider = context.GetInfrastructure<IServiceProvider>();
            var loggerFactory = (ILoggerFactory)serviceProvider.GetService(typeof(ILoggerFactory));
            loggerFactory.AddProvider(Log4NetProvider.Instance);
            return context;
        }

        public static T UseLog4NetAsLogger<T>(this T context) where T: DbContext
        {
            var serviceProvider = context.GetInfrastructure<IServiceProvider>();
            var loggerFactory = (ILoggerFactory)serviceProvider.GetService(typeof(ILoggerFactory));
            loggerFactory.AddProvider(Log4NetProvider.Instance);
            return context;
        }
    }
}


text:
layout: post
title: AutoMapping with FluentNHibernate
date: 2009-09-09T07:25:00.001Z
author: Marcus Hammarberg
tags:
  - DDD
  - .NET - NHibernate
modified_time: 2010-12-14T15:19:35.817Z
blogger_id: tag:blogger.com,1999:blog-36533086.post-5160606586149394728
blogger_orig_url: http://www.marcusoft.net/2009/09/automapping-with-fluentnhibernate.html
---

I ran across this post by Ayende and it pretty much sums up where
I want to reach with my persistence ignorance efforts:

> "After that, you are done. Just create an entity in the proper place,
> hit the /database/create and have a *lot* of fun."

I of course like the fun-part of the quote the most. :) But seriously –
that what I want to reach – to configure my conventions. And then simply
code the model as I want it and let the framework
(NHibernate in this case) figure out how to store it.

Well, as it seems, the
Fluent
NHibernate framework has been updated since the Ayende post. So I've
read, and
read, and
read and discovered
some shortcuts. By the way – here is an article on
how to make the transition from the "old" convention-style
into the new.

I have put together an updated sample for what
Ayende did in that
post above. I also added a feature to be able to automatically set
cascades for OneToMany- and ManyToMany-relationships.

Here is the most
important parts of the code.

**\[UPDATED\]
**Here is the complete sample.

Did I mention that I LOVE Fluent NHibernate? Well I do!


text:
PEAR_Config->readConfigFile()
--SKIPIF--
<?php
if (!getenv('PHP_PEAR_RUNTESTS')) {
    echo 'skip';
}
?>
--FILE--
<?php

require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'setup.php.inc';
$config = new PEAR_Config(dirname(__FILE__) . DIRECTORY_SEPARATOR .
    'ini' . DIRECTORY_SEPARATOR . 'user.input', $temp_path .
    DIRECTORY_SEPARATOR . 'nofile');
$config->setChannels(array('pear.php.net', '__uri', 'test2'));
$ret = $config->readConfigFile('foo', 'foo');
$config->set('php_dir', $temp_path); // use sandbox
$phpunit->assertErrors(array(
    array('package' => 'PEAR_Error', 'message' => 'unknown config layer `foo\''),
), 'unknown layer');
$phpunit->assertIsa('PEAR_Error', $ret, 'err object');
$ret = $config->readConfigFile(dirname(__FILE__) . DIRECTORY_SEPARATOR .
    'ini' . DIRECTORY_SEPARATOR . 'toonew.conf');
$config->set('php_dir', $temp_path); // use sandbox
$phpunit->assertErrors(array(
    array('package' => 'PEAR_Error', 'message' => dirname(__FILE__) . DIRECTORY_SEPARATOR .
    'ini' . DIRECTORY_SEPARATOR . 'toonew.conf: unknown version `2.0\''),
), 'unknown layer');
$phpunit->assertIsa('PEAR_Error', $ret, 'err object');

$phpunit->assertEquals(1, $config->get('verbose'), '$config->get(verbose)');
$phpunit->assertNull($config->get('verbose', 'user'), '$config->get(verbose, user)');
$phpunit->assertNull($config->get('verbose', 'system'), '$config->get(verbose, system)');
$phpunit->assertTrue($config->readConfigFile(dirname(__FILE__) . DIRECTORY_SEPARATOR .
    'ini' . DIRECTORY_SEPARATOR . 'user2.input'), 'read user2.input');
$config->set('php_dir', $temp_path); // use sandbox

$phpunit->assertEquals(2, $config->get('verbose'), '$config->get(verbose) after');
$phpunit->assertEquals(2, $config->get('verbose', 'user'), '$config->get(verbose, user) after');
$phpunit->assertEquals(null, $config->get('verbose', 'system'), '$config->get(verbose, system) after');

$phpunit->assertTrue($config->readConfigFile(dirname(__FILE__) . DIRECTORY_SEPARATOR .
    'ini' . DIRECTORY_SEPARATOR . 'user3.input', 'system'), 'read user3.input');
$config->set('php_dir', $temp_path); // use sandbox

$phpunit->assertEquals(2, $config->get('verbose'), '$config->get(verbose) after system');
$phpunit->assertEquals(2, $config->get('verbose', 'user'), '$config->get(verbose, user) after system');
$phpunit->assertEquals(60, $config->get('verbose', 'system'), '$config->get(verbose, system) after system');
$phpunit->assertEquals(70, $config->get('verbose', 'system', '__uri'), '$config->get(verbose, system) after system __uri');
$phpunit->assertEquals(71, $config->get('verbose', 'system', 'test2'), '$config->get(verbose, system) after system test2');

echo 'tests done';
?>
--CLEAN--
<?php
require_once dirname(__FILE__) . '/teardown.php.inc';
?>
--EXPECT--
tests done


text:
function nav_activate(elem_id) {
  // Deselect all primary navigation elements that have the class 'active'
  $.each($('[id^="pri_nav"].active'), function(e) {
    $(this).removeClass("active");
  });

  // Set the currently active element
  $(elem_id).addClass("active");
}

$(function(){
  window.Project = Backbone.Model.extend({
    urlRoot: API_PROJECTS
  });

  window.Projects = Backbone.Collection.extend({
    urlRoot: API_PROJECTS,
    model: Project,

    maybeFetch: function(options){
      // Helper function to fetch only if this collection has not been fetched before.
      if(this._fetched){
        // If this has already been fetched, call the success, if it exists
        options.success && options.success();
        return;
      }

      // when the original success function completes mark this collection as fetched
      var self = this, successWrapper = function(success){
        return function(){
          self._fetched = true;
          success && success.apply(this, arguments);
        };
      };

      options.success = successWrapper(options.success);
      this.fetch(options);
    },

    getOrFetch: function(id, options){
      // Helper function to use this collection as a cache for models on the server
      var model = this.get(id);

      if(model){
        options.success && options.success(model);
        return;
      }

      model = new Project({
        resource_uri: id
      });

      model.fetch(options);
    }
  });

  window.ProjectView = Backbone.View.extend({
    tagName: 'tr',

    events: {
      'click .permalink': 'navigate'
    },

    initialize: function(){
      this.model.bind('change', this.render, this);
    },

    navigate: function(e){
      this.trigger('navigate', this.model);
      e.preventDefault();
    },

    render: function(){
      var modeljson = this.model.toJSON();
      //modeljson.added = "foo"+modeljson.added;
      soy.renderElement($(this.el).get(0), spm.ui.project, modeljson);
      return this;
    }
  });

  window.DetailApp = Backbone.View.extend({
    events: {
      'click .home': 'home'
    },

    home: function(e){
      this.trigger('home');
      e.preventDefault();
    },

    render: function(){
      //$(this.el).html(ich.detailApp(this.model.toJSON()));
      console.log(this.model);
      return this;
    }
  });

  window.InputView = Backbone.View.extend({
    events: {
      'click .tweet': 'createTweet',
      'keypress #message': 'createOnEnter'
    },

    createOnEnter: function(e){
      if((e.keyCode || e.which) == 13){
        this.createTweet();
        e.preventDefault();
      }
    },

    createTweet: function(){
      var message = this.$('#message').val();
      if(message){
        this.collection.create({
          message: message
        });
        this.$('#message').val('');
      }
    }
  });

  window.ListView = Backbone.View.extend({
    initialize: function(){
      _.bindAll(this, 'addOne', 'addAll');

      this.collection.bind('add', this.addOne);
      this.collection.bind('reset', this.addAll, this);
      this.views = [];
    },

    addAll: function(){
      this.views = [];
      this.collection.each(this.addOne);
    },

    addOne: function(tweet){
      var view = new ProjectView({
        model: tweet
      });
      $(this.el).prepend(view.render().el);
      this.views.push(view);
      view.bind('all', this.rethrow, this);
    },

    rethrow: function(){
      this.trigger.apply(this, arguments);
    }
  });

  window.ListApp = Backbone.View.extend({
    el: "#main",

    rethrow: function(){
      this.trigger.apply(this, arguments);
    },

    render: function(){
      nav_activate('#pri_nav_projects');
      soy.renderElement($(this.el).get(0), spm.ui.projects, {});
      var list = new ListView({
        collection: this.collection,
        el: this.$('#projects')
      });
      list.addAll();
      list.bind('all', this.rethrow, this);
      new InputView({
        collection: this.collection,
          el: this.$('#input')
      });
    }
  });

  window.AppRouter = Backbone.Router.extend({
    routes: {
      '': 'dashboard',
      'projects': 'list',
      'projects/:id': 'detail'
    },

    navigate_to: function(model){
      var path = (model && model.get('id') + '/') || '';
      this.navigate(path, true);
    },

    detail: function(){},

    list: function(){}
  });

  //var AppRouter = Backbone.Router.extend({
  //  routes: {
  //    "": "dashboard",
  //    "projects": "projects"
  //  },

  //  dashboard: function() {
  //    var v = {
  //      'current_sprint': {
  //        'ends_in_days': 4
  //      },
  //      'tickets': {
  //        'closed': Math.floor((Math.random()*100)+1)
  //      }
  //    };
  //    nav_activate('#pri_nav_dashboard');
  //    soy.renderElement($('#main').get(0), spm.ui.dashboard, v);
  //  },

  //  projects: function() {
  //    var p = {
  //      'projects': [
  //        {
  //          'name': 'Project 1'
  //        },
  //        {
  //          'name': 'Project 2'
  //        }
  //      ]
  //    };
  //    nav_activate('#pri_nav_projects');
  //    soy.renderElement($('#main').get(0), spm.ui.projects, p);
  //  }
  //});
  //var app = new AppRouter();

  window.app = window.app || {};
  app.router = new AppRouter();
  app.projects = new Projects();
  app.list = new ListApp({
    el: $("#main"),
    collection: app.projects
  });
  app.detail = new DetailApp({
    el: $("#main")
  });
  app.router.bind('route:list', function(){
    app.projects.maybeFetch({
      success: _.bind(app.list.render, app.list)
    });
  });
  app.router.bind('route:detail', function(id){
    app.projects.getOrFetch(app.projects.urlRoot + id + '/', {
      success: function(model){
        app.detail.model = model;
        app.detail.render();
      }
    });
  });

  app.list.bind('navigate', app.router.navigate_to, app.router);
  app.detail.bind('home', app.router.navigate_to, app.router);
  //Backbone.history.start({
  //    pushState: true,
  //    silent: app.loaded
  //});
  Backbone.history.start();
});