text:
package com.jfoenix.controls;

import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.beans.DefaultProperty;
import javafx.beans.property.DoubleProperty;
import javafx.event.EventHandler;
import javafx.geometry.Bounds;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.ScrollPane;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.ScrollEvent;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.transform.Scale;
import javafx.scene.transform.Transform;
import javafx.util.Duration;

import java.util.function.Function;

/**
 * <h1>Material Design ScrollPane with header </h1>
 *
 * @author Shadi Shaheen & Bassel El Mabsout
 * @version 1.0
 * @since 2017-02-06
 */

@DefaultProperty(value = "content")
public class JFXScrollPane extends StackPane {

    private static final String DEFAULT_STYLE_CLASS = "jfx-scroll-pane";

    private final VBox contentContainer = new VBox();
    private final StackPane headerSpace = new StackPane();
    private final StackPane condensedHeaderBackground = new StackPane();
    private final StackPane headerBackground = new StackPane();

    private double initY = -1;
    private double maxHeight = -1;
    private double minHeight = -1;

    private final StackPane bottomBar;
    private final Scale scale = new Scale(1, 1, 0, 0);
    private Transform oldSceneTransform = null;

    private final StackPane midBar;
    private final StackPane topBar;

    public JFXScrollPane() {
        this.getStyleClass().add(DEFAULT_STYLE_CLASS);

        // clip content
        Rectangle clip = new Rectangle();
        this.setClip(clip);
        clip.widthProperty().bind(this.widthProperty());
        clip.heightProperty().bind(this.heightProperty());

        condensedHeaderBackground.setOpacity(0);
        condensedHeaderBackground.getStyleClass().add("condensed-header");
        condensedHeaderBackground.setBackground(new Background(new BackgroundFill(Color.valueOf("#1E88E5"),
                                                                                CornerRadii.EMPTY,
                                                                                Insets.EMPTY)));
        headerBackground.setBackground(new Background(new BackgroundFill(Color.valueOf("#3949AB"),
                                                                         CornerRadii.EMPTY,
                                                                         Insets.EMPTY)));
        headerBackground.getStyleClass().add("main-header");
        StackPane bgContainer = new StackPane();
        bgContainer.getChildren().setAll(condensedHeaderBackground, headerBackground);
        bgContainer.setMouseTransparent(true);

        topBar = new StackPane();
        topBar.setPickOnBounds(false);
        topBar.setMaxHeight(64);

        midBar = new StackPane();
        midBar.setMaxHeight(64);
        midBar.setPickOnBounds(false);

        bottomBar = new StackPane();
        bottomBar.setMaxHeight(64);
        bottomBar.getTransforms().add(scale);
        scale.pivotYProperty().bind(bottomBar.heightProperty().divide(2));
        bottomBar.setPickOnBounds(false);

        final StackPane barsContainer = new StackPane(topBar, midBar, bottomBar);
        StackPane.setAlignment(topBar, Pos.TOP_CENTER);
        StackPane.setAlignment(bottomBar, Pos.BOTTOM_CENTER);

        StackPane header = new StackPane();
        header.setPrefHeight(64 * 3);
        header.maxHeightProperty().bind(header.prefHeightProperty());
        header.getChildren().setAll(bgContainer, barsContainer);
        StackPane.setAlignment(header, Pos.TOP_CENTER);
        headerSpace.minHeightProperty().bind(header.prefHeightProperty());
        headerSpace.maxHeightProperty().bind(header.prefHeightProperty());
        headerSpace.setFocusTraversable(true);

        contentContainer.getChildren().setAll(headerSpace);

        contentContainer.localToSceneTransformProperty().addListener((o, oldVal, newVal) -> oldSceneTransform = oldVal);
        final ScrollPane scrollPane = new ScrollPane();
        scrollPane.setContent(contentContainer);
        scrollPane.setFitToWidth(true);
        scrollPane.vvalueProperty().addListener((o, oldVal, newVal) -> {
            if (minHeight == -1) {
                minHeight = bottomBar.getBoundsInParent().getMinY();
                maxHeight = header.getHeight();
            }
            if (initY == -1) {
                initY = oldSceneTransform.getTy();
            }

            // translation
            double ty = contentContainer.getLocalToSceneTransform().getTy();
            double opacity = Math.abs(ty - initY) / minHeight;
            opacity = opacity > 1 ? 1 : (opacity < 0) ? 0 : opacity;
            // update properties according to the scroll value
            // opacity
            headerBackground.setOpacity(1 - opacity);
            condensedHeaderBackground.setOpacity(opacity);

            if (newVal.doubleValue() == 0) {
                header.setTranslateY(0);
                topBar.setTranslateY(0);
//            } else if (newVal.doubleValue() == 1) {
//                topBar.setTranslateY(minHeight);
//                header.setStyle("-fx-border-color: RED");
//                header.setTranslateY(-maxHeight);
            } else {
                double dy = ty - initY;
                topBar.setTranslateY(-dy <= minHeight ? -dy : minHeight);

                double oldTy = oldSceneTransform.getTy();
                double diff = oldTy - ty;

                if (-dy > minHeight && newVal.doubleValue() < oldVal.doubleValue()) {
                    if (-(header.getTranslateY() - diff) > minHeight) {
                        header.setTranslateY(header.getTranslateY() - diff);
                    } else {
                        header.setTranslateY(-minHeight);
                    }
                } else {
                    if (-dy > maxHeight) {
                        if (-(header.getTranslateY() - diff) < maxHeight) {
                            header.setTranslateY(header.getTranslateY() - diff);
                        } else {
                            header.setTranslateY(-maxHeight);
                        }
                    } else {
                        if (diff > maxHeight) {
                            header.setTranslateY(-maxHeight);
                        } else {
                            header.setTranslateY(dy);
                        }
                    }
                }
            }
            // scale
            scale.setX(map(opacity, 0, 1, 1, 0.75));
            scale.setY(map(opacity, 0, 1, 1, 0.75));
        });
        scrollPane.setPannable(true);
        getChildren().setAll(scrollPane, header);
    }

    private double map(double val, double min1, double max1, double min2, double max2) {
        return min2 + (max2 - min2) * ((val - min1) / (max1 - min1));
    }

    public void setContent(Node content) {
        if (contentContainer.getChildren().size() == 2) {
            contentContainer.getChildren().set(1, content);
        } else if (contentContainer.getChildren().size() == 1) {
            contentContainer.getChildren().add(content);
        } else {
            contentContainer.getChildren().setAll(headerSpace, content);
        }
        VBox.setVgrow(content, Priority.ALWAYS);
    }

    public Node getContent() {
        return contentContainer.getChildren().size() == 2 ? contentContainer.getChildren().get(1) : null;
    }

    public StackPane getTopBar() {
        return topBar;
    }

    public StackPane getMidBar() {
        return midBar;
    }

    public StackPane getBottomBar() {
        return bottomBar;
    }

    public StackPane getMainHeader() {
        return headerBackground;
    }

    public StackPane getCondensedHeader() {
        return condensedHeaderBackground;
    }

    private static void customScrolling(ScrollPane scrollPane, DoubleProperty scrollDriection, Function<Bounds, Double> sizeFunc) {
        final double[] frictions = {0.99, 0.1, 0.05, 0.04, 0.03, 0.02, 0.01, 0.04, 0.01, 0.008, 0.008, 0.008, 0.008, 0.0006, 0.0005, 0.00003, 0.00001};
        final double[] pushes = {1};
        final double[] derivatives = new double[frictions.length];

        Timeline timeline = new Timeline();
        final EventHandler<MouseEvent> dragHandler = event -> timeline.stop();
        final EventHandler<ScrollEvent> scrollHandler = event -> {
            if (event.getEventType() == ScrollEvent.SCROLL) {
                int direction = event.getDeltaY() > 0 ? -1 : 1;
                for (int i = 0; i < pushes.length; i++) {
                    derivatives[i] += direction * pushes[i];
                }
                if (timeline.getStatus() == Animation.Status.STOPPED) {
                    timeline.play();
                }
                event.consume();
            }
        };
        if (scrollPane.getContent().getParent() != null) {
            scrollPane.getContent().getParent().addEventHandler(MouseEvent.DRAG_DETECTED, dragHandler);
            scrollPane.getContent().getParent().addEventHandler(ScrollEvent.ANY, scrollHandler);
        }
        scrollPane.getContent().parentProperty().addListener((o,oldVal, newVal)->{
            if (oldVal != null) {
                oldVal.removeEventHandler(MouseEvent.DRAG_DETECTED, dragHandler);
                oldVal.removeEventHandler(ScrollEvent.ANY, scrollHandler);
            }
            if (newVal != null) {
                newVal.addEventHandler(MouseEvent.DRAG_DETECTED, dragHandler);
                newVal.addEventHandler(ScrollEvent.ANY, scrollHandler);
            }
        });
        timeline.getKeyFrames().add(new KeyFrame(Duration.millis(3), (event) -> {
            for (int i = 0; i < derivatives.length; i++) {
                derivatives[i] *= frictions[i];
            }
            for (int i = 1; i < derivatives.length; i++) {
                derivatives[i] += derivatives[i - 1];
            }
            double dy = derivatives[derivatives.length - 1];
            double size = sizeFunc.apply(scrollPane.getContent().getLayoutBounds());
            scrollDriection.set(Math.min(Math.max(scrollDriection.get() + dy / size, 0), 1));
            if (Math.abs(dy) < 0.001) {
                timeline.stop();
            }
        }));
        timeline.setCycleCount(Animation.INDEFINITE);
    }

    public static void smoothScrolling(ScrollPane scrollPane) {
        customScrolling(scrollPane, scrollPane.vvalueProperty(), bounds -> bounds.getHeight());
    }

    public static void smoothHScrolling(ScrollPane scrollPane) {
        customScrolling(scrollPane, scrollPane.hvalueProperty(), bounds -> bounds.getWidth());
    }

}


text:
package com.blnz.xml.parse;

import java.net.URL;

/**
 * Information about the location of the parse of an XML document.
 * @version $Revision: 1.1 $ $Date: 1998/05/25 03:40:30 $
 */
public interface ParseLocation {

  /**
   * Returns the location of the external entity being
   * parsed in a form suitable for use in a message.
   * Returns null if no location is available.
   * This is typically a URI or a filename.
   */
  String getEntityLocation();

  /**
   * Returns the URL to use as the base URL for resolving relative URLs
   * contained in the entity being parsed.
   */
  public URL getEntityBase();

  /**
   * Returns the line number of the character being parsed
   * or -1 if no line number is available.
   * The number of the first line is 1.
   */
  int getLineNumber();

  /**
   * Returns the column number of the character being parsed
   * or -1 if no column number is available.
   * The number of the first column in a line is 0.
   * A tab character is not treated specially.
   */
  int getColumnNumber();

  /**
   * Returns the byte index of the first byte of the character being parsed
   * or -1 if no byte index is available.
   * The index of the first byte is 0.
   */
  public long getByteIndex();

}

redpajama_set_name: RedPajamaGithub


text:
import React from "react";
import PropTypes from "prop-types";
import UnhideSimulatorCard from "components/macros/unhideSimulatorCard";

class UnhideCard extends React.Component {
  render() {
    const {value = {}, updateValue = () => {}} = this.props;
    return (
      <div
        style={{display: "flex", flexDirection: "column"}}
        onMouseDown={e => e.stopPropagation()}
      >
        <UnhideSimulatorCard
          updateArgs={(key, val) => updateValue({...value, [key]: val})}
          args={value}
        />
        <small>Card Name can be identified through the connection.</small>
      </div>
    );
  }
}

UnhideCard.propTypes = {
  value: PropTypes.any,
  updateValue: PropTypes.func,
};

export default {
  name: "unhideSimulatorCard",
  category: "Actions",
  component: UnhideCard,
  outputs: [],
  inputs: [
    {
      id: "trigger",
      color: "orange",
      title: "Triggers the action",
      type: "Trigger",
    },
    {
      id: "cardName",
      color: "rebeccapurple",
      title: "The name of the card",
      type: "Any",
    },
  ],
  config: [],
};


text:
package org.openbaton.nfvo.api.admin;

import static org.openbaton.nfvo.common.utils.viminstance.VimInstanceUtils.handlePrivateInfo;

import io.swagger.annotations.ApiOperation;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import javax.validation.Valid;
import org.openbaton.catalogue.nfvo.images.BaseNfvImage;
import org.openbaton.catalogue.nfvo.viminstances.BaseVimInstance;
import org.openbaton.exceptions.BadFormatException;
import org.openbaton.exceptions.BadRequestException;
import org.openbaton.exceptions.EntityUnreachableException;
import org.openbaton.exceptions.NotFoundException;
import org.openbaton.exceptions.PluginException;
import org.openbaton.exceptions.VimException;
import org.openbaton.nfvo.core.interfaces.ComponentManager;
import org.openbaton.nfvo.core.interfaces.VimManagement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/v1/datacenters")
public class RestVimInstances {

  private Logger log = LoggerFactory.getLogger(this.getClass());

  @Autowired private VimManagement vimManagement;
  @Autowired private ComponentManager componentManager;

  /**
   * Adds a new VNF software Image to the datacenter repository
   *
   * @param vimInstance : Image to add
   * @return datacenter: The datacenter filled with values from the core
   */
  @ApiOperation(
      value = "Adding a Vim Instance",
      notes = "Takes a Vim Instance json in the request body")
  @RequestMapping(
      method = RequestMethod.POST,
      consumes = MediaType.APPLICATION_JSON_VALUE,
      produces = MediaType.APPLICATION_JSON_VALUE)
  @ResponseStatus(HttpStatus.CREATED)
  public BaseVimInstance create(
      @RequestBody @Valid BaseVimInstance vimInstance,
      @RequestHeader(value = "project-id") String projectId)
      throws VimException, PluginException, IOException, BadRequestException, ExecutionException,
          InterruptedException {
    log.info("Adding vim instance: " + vimInstance);
    return vimManagement.add(vimInstance, projectId).get();
  }

  /**
   * Removes the Datacenter from the Datacenter repository
   *
   * @param id: The Datacenter's id to be deleted
   */
  @ApiOperation(
      value = " Removing a Vim Instance",
      notes = "Deletes the Vim Instance belonging to the id specified in the URL")
  @RequestMapping(value = "{id}", method = RequestMethod.DELETE)
  @ResponseStatus(HttpStatus.NO_CONTENT)
  public void delete(
      @PathVariable("id") String id, @RequestHeader(value = "project-id") String projectId)
      throws NotFoundException, BadRequestException {
    log.info("Deleting vim instance id: " + id);
    vimManagement.delete(id, projectId);
  }

  /**
   * Removes multiple VIM Instances
   *
   * @param ids: the list of VIM Instance IDs
   * @throws NotFoundException if one of the VIM Instances was not found
   * @throws BadRequestException if something is wrong with the request
   */
  @RequestMapping(
      value = "/multipledelete",
      method = RequestMethod.POST,
      consumes = MediaType.APPLICATION_JSON_VALUE)
  @ApiOperation(
      value = "Removing multiple VIM Instances",
      notes = "Delete Request takes a list of VIM Instance IDs")
  @ResponseStatus(HttpStatus.NO_CONTENT)
  public void multipleDelete(
      @RequestBody @Valid List<String> ids, @RequestHeader(value = "project-id") String projectId)
      throws NotFoundException, BadRequestException {
    log.info("Deleting vim instance ids: " + ids);
    for (String id : ids) vimManagement.delete(id, projectId);
  }

  /**
   * Returns the list of the Datacenters available
   *
   * @return List<Datacenter>: The List of Datacenters available
   */
  @ApiOperation(
      value = "Retrieving all Vim Instances",
      notes =
          "This method returns the list of all the VimInstances on-boarded in this project identified by the header project-id")
  @RequestMapping(method = RequestMethod.GET)
  public List<BaseVimInstance> findAll(
      @RequestHeader(value = "project-id") String projectId,
      @RequestHeader(value = "authorization") String token)
      throws BadFormatException {
    String[] tokenArray = token.split(" ");
    if (tokenArray.length < 2) throw new BadFormatException("The passed token has a wrong format.");
    token = tokenArray[1];
    log.info("Retrieving all vim instances");
    Iterable<BaseVimInstance> vimInstances = vimManagement.queryByProjectId(projectId);
    if (!componentManager.isService(token))
      for (BaseVimInstance vim : vimInstances) {
        handlePrivateInfo(vim);
      }
    return (List<BaseVimInstance>) vimInstances;
  }

  /**
   * Returns the Datacenter selected by id
   *
   * @param id: The Datacenter's id selected
   * @return Datacenter: The Datacenter selected
   */
  @ApiOperation(
      value = "Retrieve a Vim Instance",
      notes = "Returns the Vim Instance JSON belonging to the id specified in the URL")
  @RequestMapping(value = "{id}", method = RequestMethod.GET)
  public BaseVimInstance findById(
      @PathVariable("id") String id,
      @RequestHeader(value = "project-id") String projectId,
      @RequestHeader(value = "authorization") String token)
      throws NotFoundException, BadFormatException {
    log.info("Retrieving vim instance id: " + id);
    BaseVimInstance vim = vimManagement.query(id, projectId);
    if (vim == null) throw new NotFoundException("VIM Instance with ID " + id + " not found.");
    String[] tokenArray = token.split(" ");
    if (tokenArray.length < 2) throw new BadFormatException("The passed token has a wrong format.");
    token = tokenArray[1];
    if (!componentManager.isService(token)) {
      handlePrivateInfo(vim);
    }
    return vim;
  }

  /**
   * Returns the Datacenter selected by name
   *
   * @param name: The Datacenter's name
   * @return Datacenter: The Datacenter requested
   */
  @ApiOperation(
      value = "Retrieve a Vim Instance by name",
      notes = "Returns the Vim Instance JSON belonging to the name specified")
  @GetMapping(value = "search/findByName")
  public BaseVimInstance findByName(
      @RequestParam String name, @RequestHeader(value = "project-id") String projectId)
      throws NotFoundException {
    return vimManagement.queryByProjectIdAndName(projectId, name);
  }

  /**
   * This operation updates the Network Service Descriptor (NSD)
   *
   * @param newVimInstance the new datacenter to be updated to
   * @param id the id of the old datacenter
   * @return VimInstance the VimInstance updated
   */
  @ApiOperation(
      value = "Updating a Vim Instance",
      notes =
          "Takes a Vim Instance as JSON and updates the Vim Instance with the id specified in the URL")
  @RequestMapping(
      value = "{id}",
      method = RequestMethod.PUT,
      consumes = MediaType.APPLICATION_JSON_VALUE,
      produces = MediaType.APPLICATION_JSON_VALUE)
  @ResponseStatus(HttpStatus.ACCEPTED)
  public BaseVimInstance update(
      @RequestBody @Valid BaseVimInstance newVimInstance,
      @PathVariable("id") String id,
      @RequestHeader(value = "project-id") String projectId)
      throws VimException, PluginException, IOException, BadRequestException, NotFoundException,
          ExecutionException, InterruptedException {
    log.info("Updating vim instance with id: " + id);
    log.debug("New vim instance: " + newVimInstance);
    return vimManagement.update(newVimInstance, id, projectId).get();
  }

  /**
   * Returns the list of NFVImage into a VimInstance with id
   *
   * @param id of the VimInstance
   * @return Set<NFVImage>
   */
  @ApiOperation(
      value = "Retrieve the data about images on a Vim Instance",
      notes =
          "Retrieve the data for all images on the Vim Instance which id is specified in the URL")
  @RequestMapping(value = "{id}/images", method = RequestMethod.GET)
  public Set<? extends BaseNfvImage> getAllImages(
      @PathVariable("id") String id, @RequestHeader(value = "project-id") String projectId)
      throws NotFoundException {
    log.info("Retrieving images from vim instance id: " + id);
    BaseVimInstance vimInstance = vimManagement.query(id, projectId);
    if (vimInstance == null)
      throw new NotFoundException("VIM Instance with ID " + id + " not found.");
    return vimInstance.getImages();
  }

  /**
   * Returns the {@code NFVImage} selected by idImage from {@code VimInstance} with idVim
   *
   * @param idVim of {@code VimInstance}
   * @param idImage of {@code NFVImage}
   * @return {@code NFVImage} selected
   */
  @ApiOperation(
      value = "Returns the data about an Image from the Vim Instance",
      notes =
          "Retrieve the data for a specific image on the Vim Instance which id is specified in the URL")
  @RequestMapping(value = "{idVim}/images/{idImage}", method = RequestMethod.GET)
  public BaseNfvImage getImage(
      @PathVariable("idVim") String idVim,
      @PathVariable("idImage") String idImage,
      @RequestHeader(value = "project-id") String projectId)
      throws EntityUnreachableException, NotFoundException {
    log.info("Retrieving image " + idImage + " from vim instance id: " + idVim);
    return vimManagement.queryImage(idVim, idImage, projectId);
  }

  /**
   * Adds a new {@code NFVImage} to the {@code VimInstance} with the id
   *
   * @param id of {@code VimInstance}
   * @param nfvImage the {@code NFVImage} to be added
   * @return {@code NFVImage} persisted
   * @throws VimException
   */
  @ApiOperation(
      value = "Adds an image to the Vim Instance",
      notes = "Adds an image to the Vim Instance with id specified in the URL")
  @RequestMapping(value = "{id}/images", method = RequestMethod.POST)
  public BaseNfvImage addImage(
      @PathVariable("id") String id,
      BaseNfvImage nfvImage,
      @RequestHeader(value = "project-id") String projectId)
      throws VimException, PluginException, EntityUnreachableException, IOException,
          NotFoundException {
    log.info("Adding image to vim instance id: " + id);
    log.debug("Image to add: " + nfvImage);
    return vimManagement.addImage(id, nfvImage, projectId);
  }

  /**
   * Updates the {@code NFVImage} with idImage into {@code VimInstance} with idVim
   *
   * @param idVim of {@code VimInstance}
   * @param image of {@code NFVImage}
   * @return {@code NFVImage} updated
   * @throws VimException
   */
  @ApiOperation(
      value = "Updates the data of an image on the Vim Instance",
      notes = "Updates an image to the Vim Instance with id specified in the URL")
  @RequestMapping(value = "{idVim}/images/{idImage}", method = RequestMethod.PUT)
  public BaseNfvImage updateImage(
      @PathVariable("idVim") String idVim,
      @RequestBody @Valid BaseNfvImage image,
      @RequestHeader(value = "project-id") String projectId)
      throws VimException, PluginException, EntityUnreachableException, IOException,
          NotFoundException {
    return vimManagement.addImage(idVim, image, projectId);
  }

  /**
   * Removes the {@code NFVImage} with idImage from {@code VimInstance} with idVim
   *
   * @param idVim of {@code VimInstance}
   * @param idImage of {@code NFVImage}
   * @throws VimException
   */
  @ApiOperation(
      value = "Remove an image on the Vim Instance",
      notes = "Remove the specified by id image from the vim instance")
  @RequestMapping(value = "{idVim}/images/{idImage}", method = RequestMethod.DELETE)
  public void deleteImage(
      @PathVariable("idVim") String idVim,
      @PathVariable("idImage") String idImage,
      @RequestHeader(value = "project-id") String projectId)
      throws VimException, PluginException, EntityUnreachableException, IOException,
          NotFoundException {
    log.info("Deleting image " + idImage + " from vim instance id: " + idVim);
    vimManagement.deleteImage(idVim, idImage, projectId);
  }

  /**
   * Returns the refreshed Datacenter selected by id
   *
   * @param id: The Datacenter's id selected
   * @return Datacenter: The Datacenter selected
   */
  @ApiOperation(
      value = "Refreshes the data about the Vim Instance",
      notes = "Refreshes the data about the Vim Instance and returns it")
  @RequestMapping(value = "{id}/refresh", method = RequestMethod.GET)
  public BaseVimInstance refresh(
      @PathVariable("id") String id, @RequestHeader(value = "project-id") String projectId)
      throws VimException, PluginException, IOException, NotFoundException, ExecutionException,
          InterruptedException {
    BaseVimInstance vimInstance = vimManagement.query(id, projectId);
    if (vimInstance == null)
      throw new NotFoundException("VIM Instance with ID " + id + " not found.");
    log.info("Refreshing vim instance: " + id);
    vimManagement.refresh(vimInstance, true).get();
    return vimInstance;
  }
}


text:
<?php

$installer = $this;
/* @var $installer Mage_Catalog_Model_Resource_Eav_Mysql4_Setup */

$installer->startSetup();
$installer->addAttribute('catalog_product', 'media_gallery',  array(
        'group'         => 'Images',
        'label'         => 'Media Gallery',
        'input'         => 'gallery',
        'backend'       => 'catalog/product_attribute_backend_media',
        'class'         => '',
        'global'        => true,
        'visible'       => true,
        'required'      => false,
        'user_defined'  => false,
        'visible_on_front' => false
    )
);
$installer->run("
    DROP TABLE IF EXISTS `{$this->getTable('catalog_product_entity_media_gallery')}`;
    CREATE TABLE `{$this->getTable('catalog_product_entity_media_gallery')}` (
        `value_id` int(11) unsigned NOT NULL auto_increment,
        `entity_type_id` smallint(5) unsigned NOT NULL default '0',
        `attribute_id` smallint(5) unsigned NOT NULL default '0',
        `entity_id` int(10) unsigned NOT NULL default '0',
        `value` varchar(255) default NULL,
        PRIMARY KEY  (`value_id`),
        KEY `FK_CATALOG_PRODUCT_MEDIA_GALLERY_ATTRIBUTE` (`attribute_id`),
        KEY `FK_CATALOG_PRODUCT_MEDIA_GALLERY_ENTITY` (`entity_id`),
        KEY `FK_CATALOG_PRODUCT_MEDIA_GALLERY_ENTITY_TYPE` (`entity_type_id`),
        CONSTRAINT `FK_CATALOG_PRODUCT_MEDIA_GALLERY_ATTRIBUTE` FOREIGN KEY (`attribute_id`) REFERENCES `{$this->getTable('eav_attribute')}` (`attribute_id`) ON DELETE CASCADE,
        CONSTRAINT `FK_CATALOG_PRODUCT_MEDIA_GALLERY_ENTITY` FOREIGN KEY (`entity_id`) REFERENCES `{$this->getTable('catalog_product_entity')}` (`entity_id`) ON DELETE CASCADE,
        CONSTRAINT `FK_CATALOG_PRODUCT_MEDIA_GALLERY_ENTITY_TYPE` FOREIGN KEY (`entity_type_id`) REFERENCES `{$this->getTable('eav_entity_type')}` (`entity_type_id`) ON DELETE CASCADE
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Catalog product media gallery';

    DROP TABLE IF EXISTS `{$this->getTable('catalog_product_entity_media_gallery_value')}`;
    CREATE TABLE `{$this->getTable('catalog_product_entity_media_gallery_value')}` (
      `value_id` int(11) unsigned NOT NULL default '0',
      `store_id` smallint(5) unsigned NOT NULL default '0',
      `label` varchar(255) default NULL,
      `position` int(11) unsigned default NULL,
      `disabled` tinyint(1) unsigned NOT NULL default '0',
      PRIMARY KEY  (`value_id`,`store_id`),
      KEY `FK_CATALOG_PRODUCT_MEDIA_GALLERY_VALUE_STORE` (`store_id`),
      CONSTRAINT `FK_CATALOG_PRODUCT_MEDIA_GALLERY_VALUE_GALLERY` FOREIGN KEY (`value_id`) REFERENCES `{$this->getTable('catalog_product_entity_media_gallery')}` (`value_id`) ON DELETE CASCADE,
      CONSTRAINT `FK_CATALOG_PRODUCT_MEDIA_GALLERY_VALUE_STORE` FOREIGN KEY (`store_id`) REFERENCES `{$this->getTable('core_store')}` (`store_id`) ON DELETE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Catalog product media gallery values';

    DROP TABLE IF EXISTS `{$this->getTable('catalog_product_entity_media_gallery_image')}`;
    CREATE TABLE `{$this->getTable('catalog_product_entity_media_gallery_image')}` (
      `value_id` int(11) unsigned NOT NULL default '0',
      `store_id` smallint(5) unsigned NOT NULL default '0',
      `type` varchar(50) NOT NULL default '',
      PRIMARY KEY  (`value_id`,`store_id`,`type`),
      CONSTRAINT `FK_CATALOG_PRODUCT_MEDIA_GALLERY_IMAGE_STORE` FOREIGN KEY (`store_id`) REFERENCES `{$this->getTable('core_store')}` (`store_id`) ON DELETE CASCADE,
      CONSTRAINT `FK_CATALOG_PRODUCT_MEDIA_GALLERY_IMAGE_GALLERY` FOREIGN KEY (`value_id`) REFERENCES `{$this->getTable('catalog_product_entity_media_gallery')}` (`value_id`) ON DELETE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Catalog product media gallery images';
");

$installer->endSetup();


text:
import BaseView from 'ghost/views/settings/content-base';

var SettingsTagsView = BaseView.extend();

export default SettingsTagsView;


text:
require 'java'
require 'hailstorm'

# Defines static accessors.
# @author Sayantam Dey
module Hailstorm
  @root = nil
  @app_name = nil
  @application = nil

  # The application root path. Access this by calling <tt>Hailstorm.root</tt>
  # @return [String]
  def self.root
    @root
  end

  # Sets the root path of the application
  # @param [String] new_root path of application
  def self.root=(new_root)
    @root = new_root
  end

  # Application name
  # @return [String]
  def self.app_name
    @app_name
  end

  # @param [String] new_app_name application name
  def self.app_name=(new_app_name)
    @app_name = new_app_name
  end

  # Application instance
  # @return [Hailstorm::Middleware::Application]
  def self.application
    @application
  end

  # @param [Hailstorm::Middleware::Application] new_application
  def self.application=(new_application)
    @application = new_application
  end

  # Directory name used to store database and other files.
  def self.db_dir
    'db'
  end

  def self.tmp_dir
    'tmp'
  end

  def self.tmp_path
    File.join(root, tmp_dir)
  end

  def self.templates_path
    File.expand_path('../../../templates', __FILE__)
  end

  def self.reports_dir
    'reports'
  end

  def self.config_dir
    'config'
  end

  def self.vendor_dir
    'vendor'
  end

  def self.script_dir
    'script'
  end

  def self.environment_file_path
    File.join(self.root, self.config_dir, 'environment.rb')
  end

  def self.results_import_dir
    File.join(self.log_dir, 'import')
  end

  def self.project_directories
    dirs = %i[db_dir app_dir log_dir tmp_dir reports_dir config_dir vendor_dir script_dir]
    dirs.map { |dir| Hailstorm.send(dir) }
  end
end


text:
//
//  SDLConfiguration.h
//  SmartDeviceLink-iOS
//
//  Created by Joel Fischer on 10/13/15.
//  Copyright © 2015 smartdevicelink. All rights reserved.
//

#import <Foundation/Foundation.h>

@class SDLFileManagerConfiguration;
@class SDLLifecycleConfiguration;
@class SDLLockScreenConfiguration;
@class SDLLogConfiguration;
@class SDLStreamingMediaConfiguration;

NS_ASSUME_NONNULL_BEGIN

@interface SDLConfiguration : NSObject <NSCopying>

/**
 *  The lifecycle configuration.
 */
@property (copy, nonatomic, readonly) SDLLifecycleConfiguration *lifecycleConfig;

/**
 *  The lock screen configuration.
 */
@property (copy, nonatomic, readonly) SDLLockScreenConfiguration *lockScreenConfig;

/**
 *  The log configuration.
 */
@property (copy, nonatomic, readonly) SDLLogConfiguration *loggingConfig;

/**
 *  The streaming media configuration.
 */
@property (copy, nonatomic, readonly) SDLStreamingMediaConfiguration *streamingMediaConfig;

/**
 *  The file manager configuration.
 */
@property (copy, nonatomic, readonly) SDLFileManagerConfiguration *fileManagerConfig;

/**
 *  Creates a new configuration to be passed to the SDLManager with custom lifecycle, lock screen and logging configurations.
 *
 *  @param lifecycleConfig      The lifecycle configuration to be used.
 *  @param lockScreenConfig     The lockscreen configuration to be used. If nil, the `enabledConfiguration` will be used.
 *  @param logConfig            The logging configuration to be used. If nil, the `defaultConfiguration` will be used.
 *  @return                     The configuration
 */
- (instancetype)initWithLifecycle:(SDLLifecycleConfiguration *)lifecycleConfig lockScreen:(nullable SDLLockScreenConfiguration *)lockScreenConfig logging:(nullable SDLLogConfiguration *)logConfig __deprecated_msg("Use initWithLifecycle:lockScreen:logging:fileManager: instead");

/**
 *  Creates a new configuration to be passed to the SDLManager with custom lifecycle, lock screen, logging and file manager configurations.
 *
 *  @param lifecycleConfig      The lifecycle configuration to be used.
 *  @param lockScreenConfig     The lockscreen configuration to be used. If nil, the `enabledConfiguration` will be used.
 *  @param logConfig            The logging configuration to be used. If nil, the `defaultConfiguration` will be used.
 *  @param fileManagerConfig    The file manager configuration to be used or `defaultConfiguration` if nil.
 *  @return                     The configuration
 */
- (instancetype)initWithLifecycle:(SDLLifecycleConfiguration *)lifecycleConfig lockScreen:(nullable SDLLockScreenConfiguration *)lockScreenConfig logging:(nullable SDLLogConfiguration *)logConfig fileManager:(nullable SDLFileManagerConfiguration *)fileManagerConfig;

/**
 *  Creates a new configuration to be passed to the SDLManager with custom lifecycle, lock screen and logging configurations.
 *
 *  @param lifecycleConfig      The lifecycle configuration to be used.
 *  @param lockScreenConfig     The lockscreen configuration to be used. If nil, the `enabledConfiguration` will be used.
 *  @param logConfig            The logging configuration to be used. If nil, the `defaultConfiguration` will be used.
 *  @return                     The configuration
 */
+ (instancetype)configurationWithLifecycle:(SDLLifecycleConfiguration *)lifecycleConfig lockScreen:(nullable SDLLockScreenConfiguration *)lockScreenConfig logging:(nullable SDLLogConfiguration *)logConfig __deprecated_msg("Use configurationWithLifecycle:lockScreen:logging:fileManager: instead") NS_SWIFT_UNAVAILABLE("Use an initializer instead");

/**
 *  Creates a new configuration to be passed to the SDLManager with custom lifecycle, lock screen, logging and file manager configurations.
 *
 *  @param lifecycleConfig      The lifecycle configuration to be used.
 *  @param lockScreenConfig     The lockscreen configuration to be used. If nil, the `enabledConfiguration` will be used.
 *  @param logConfig            The logging configuration to be used. If nil, the `defaultConfiguration` will be used.
 *  @param fileManagerConfig    The file manager configuration to be used or `defaultConfiguration` if nil.
 *  @return                     The configuration
 */
+ (instancetype)configurationWithLifecycle:(SDLLifecycleConfiguration *)lifecycleConfig lockScreen:(nullable SDLLockScreenConfiguration *)lockScreenConfig logging:(nullable SDLLogConfiguration *)logConfig fileManager:(nullable SDLFileManagerConfiguration *)fileManagerConfig NS_SWIFT_UNAVAILABLE("Use an initializer instead");

/**
 *  Creates a new configuration to be passed to the SDLManager with custom lifecycle, lock screen, logging and streaming media configurations.
 *
 *  @param lifecycleConfig      The lifecycle configuration to be used.
 *  @param lockScreenConfig     The lockscreen configuration to be used. If nil, the `enabledConfiguration` will be used.
 *  @param logConfig            The logging configuration to be used. If nil, the `defaultConfiguration` will be used.
 *  @param streamingMediaConfig The streaming media configuration to be used or nil if not used.
 *  @return                     The configuration
 */
- (instancetype)initWithLifecycle:(SDLLifecycleConfiguration *)lifecycleConfig lockScreen:(nullable SDLLockScreenConfiguration *)lockScreenConfig logging:(nullable SDLLogConfiguration *)logConfig streamingMedia:(nullable SDLStreamingMediaConfiguration *)streamingMediaConfig __deprecated_msg("Use initWithLifecycle:lockScreen:logging:streamingMedia:fileManager: instead");

/**
 *  Creates a new configuration to be passed to the SDLManager with custom lifecycle, lock screen, logging, streaming media and file manager configurations.
 *
 *  @param lifecycleConfig      The lifecycle configuration to be used.
 *  @param lockScreenConfig     The lockscreen configuration to be used. If nil, the `enabledConfiguration` will be used.
 *  @param logConfig            The logging configuration to be used. If nil, the `defaultConfiguration` will be used.
 *  @param streamingMediaConfig The streaming media configuration to be used or nil if not used.
 *  @param fileManagerConfig    The file manager configuration to be used or `defaultConfiguration` if nil.
 *  @return                     The configuration
 */
- (instancetype)initWithLifecycle:(SDLLifecycleConfiguration *)lifecycleConfig lockScreen:(nullable SDLLockScreenConfiguration *)lockScreenConfig logging:(nullable SDLLogConfiguration *)logConfig streamingMedia:(nullable SDLStreamingMediaConfiguration *)streamingMediaConfig fileManager:(nullable SDLFileManagerConfiguration *)fileManagerConfig;

/**
 *  Creates a new configuration to be passed to the SDLManager with custom lifecycle, lock screen, logging and streaming media configurations.
 *
 *  @param lifecycleConfig      The lifecycle configuration to be used.
 *  @param lockScreenConfig     The lockscreen configuration to be used. If nil, the `enabledConfiguration` will be used.
 *  @param logConfig            The logging configuration to be used. If nil, the `defaultConfiguration` will be used.
 *  @param streamingMediaConfig The streaming media configuration to be used or nil if not used.
 *  @return                     The configuration
 */
+ (instancetype)configurationWithLifecycle:(SDLLifecycleConfiguration *)lifecycleConfig lockScreen:(nullable SDLLockScreenConfiguration *)lockScreenConfig logging:(nullable SDLLogConfiguration *)logConfig streamingMedia:(nullable SDLStreamingMediaConfiguration *)streamingMediaConfig __deprecated_msg("Use configurationWithLifecycle:lockScreen:logging:streamingMedia:fileManager: instead") NS_SWIFT_UNAVAILABLE("Use an initializer instead");

/**
 *  Creates a new configuration to be passed to the SDLManager with custom lifecycle, lock screen, logging, streaming media and file manager configurations.
 *
 *  @param lifecycleConfig      The lifecycle configuration to be used.
 *  @param lockScreenConfig     The lockscreen configuration to be used. If nil, the `enabledConfiguration` will be used.
 *  @param logConfig            The logging configuration to be used. If nil, the `defaultConfiguration` will be used.
 *  @param streamingMediaConfig The streaming media configuration to be used or nil if not used.
 *  @param fileManagerConfig    The file manager configuration to be used or `defaultConfiguration` if nil.
 *  @return                     The configuration
 */
+ (instancetype)configurationWithLifecycle:(SDLLifecycleConfiguration *)lifecycleConfig lockScreen:(nullable SDLLockScreenConfiguration *)lockScreenConfig logging:(nullable SDLLogConfiguration *)logConfig streamingMedia:(nullable SDLStreamingMediaConfiguration *)streamingMediaConfig fileManager:(nullable SDLFileManagerConfiguration *)fileManagerConfig NS_SWIFT_UNAVAILABLE("Use an initializer instead");

@end

NS_ASSUME_NONNULL_END


text:
import { vi } from 'vitest'

class ReplMock {
    start = vi.fn().mockReturnValue({ on: this.on.bind(this) })

    on (event: string, cb: Function) {
        cb(event)
    }
}

export default new ReplMock()


text:
module HydraAttribute
  module HydraEntity
    class RelationDecorator
      def initialize(entity_type, model_class)
        @entity_type = entity_type
        @model_class = model_class
      end

      def create(attributes = {})
        @model_class.create(attributes.merge(entity_type: @entity_type))
      end

      def build(attributes = {})
        @model_class.new(attributes.merge(entity_type: @entity_type))
      end

      private
        def respond_to_missing?(symbol, include_private)
          _models.respond_to?(symbol, include_private)
        end

        def method_missing(method, *args, &block)
          _models.send(method, *args, &block)
        end

        def _models
          @model_class.all_by_entity_type(@entity_type)
        end
    end

    extend ActiveSupport::Concern

    included do
      after_save    :save_hydra_attributes
      after_destroy :destroy_hydra_attributes
    end

    module ClassMethods
      # Returns collection of hydra attributes for current entity
      #
      # @return [HydraAttribute::HydraEntity::RelationDecorator]
      def hydra_attributes
        @hydra_attributes ||= RelationDecorator.new(model_name, ::HydraAttribute::HydraAttribute)
      end

      # Returns collection of hydra sets for current entity
      #
      # @return [HydraAttribute::HydraEntity::RelationDecorator]
      def hydra_sets
        @hydra_sets ||= RelationDecorator.new(model_name, ::HydraAttribute::HydraSet)
      end
    end

    # Returns association between hydra attributes and their values
    #
    # @return [HydraAttribute::HydraEntityAttributeAssociation]
    def hydra_attribute_association
      @hydra_attribute_association ||= HydraEntityAttributeAssociation.new(self)
    end

    # Sets association object which connects hydra attributes with their values
    #
    # @param [HydraAttribute::HydraEntityAttributeAssociation]
    def hydra_attribute_association=(association)
      @hydra_attribute_association = association
    end

    # Return +HydraSet+ object if it exists
    #
    # @return [HydraAttribute::HydraSet]
    def hydra_set
      HydraSet.find(hydra_set_id) if hydra_set_id
    end

    # Returns hydra attribute names with theirs values
    #
    # @return [Hash]
    def hydra_attributes
      hydra_attribute_association.hydra_attributes
    end

    # Returns hydra attribute names with theirs values before type casting
    #
    # @return [Hash]
    def hydra_attributes_before_type_cast
      hydra_attribute_association.hydra_attributes_before_type_cast
    end

    def respond_to?(method, include_private = false)
      hydra_attribute_association.has_proxy_method?(method) || super
    end

    private
      def save_hydra_attributes
        hydra_attribute_association.save
      end

      def destroy_hydra_attributes
        hydra_attribute_association.destroy
      end

      def method_missing(method, *args, &block)
        hydra_attribute_association.delegate(method, *args, &block)
      rescue HydraSet::MissingAttributeInHydraSetError, HydraEntityAttributeAssociation::AttributeWasNotSelectedError
        raise
      rescue
        super
      end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>

<!-- ======================================================================= -->
<!-- Web Service Context Configuration File                                  -->
<!-- Description:                                                            -->
<!--     Defines and configures the web service endpoint proxies and         -->
<!--     controllers that expose the web service application's front end.    -->
<!--     Note that in Spring parlance a web service endpoint is a            -->
<!--     @Controller bean, not a @Service bean because it is invoked to      -->
<!--     handle the web service calls and thus forms the front end of the    -->
<!--     application.                                                        -->
<!-- ======================================================================= -->

<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:context="http://www.springframework.org/schema/context"
	   xmlns:stack-rs="http://code.lds.org/schema/spring/rs"
	   xmlns:sec="http://www.springframework.org/schema/security"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xsi:schemaLocation="
			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
			http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
			http://code.lds.org/schema/spring/rs http://code.lds.org/schema/spring/rs/stack-rs-1.3.xsd
			http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd"
	   default-lazy-init="true">

	<!-- =================================================================== -->
	<!-- Imported Configuration                                              -->
	<!-- =================================================================== -->

	<import resource="classpath:META-INF/cxf/cxf.xml" />
	<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

	<!-- =================================================================== -->
	<!-- Controller Bean Scanning                                            -->
	<!-- =================================================================== -->

	<context:component-scan base-package="org.lds.example" use-default-filters="false">
		<context:include-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
	</context:component-scan>

	<!-- =================================================================== -->
	<!-- Method-level Security                                               -->
	<!-- =================================================================== -->

	<sec:global-method-security jsr250-annotations="enabled" pre-post-annotations="enabled" secured-annotations="enabled" />

	<!-- =================================================================== -->
	<!-- REST Web Services                                                   -->
	<!-- =================================================================== -->

	<stack-rs:produce extensions="true">
		<stack-rs:interfaces>
			<ref bean="exampleWebServiceRest"/>
		</stack-rs:interfaces>
	</stack-rs:produce>

	<!-- =================================================================== -->
	<!-- JMX/Canary Beans                                                    -->
	<!-- =================================================================== -->

	<context:mbean-export default-domain="org.lds.example.java-rest-lab-01"/>

	<bean id="wsContextMBean" class="org.lds.stack.system.spring.SpringContextMBean" lazy-init="false"/>

</beans>


text:
tmuxls() {
    echo "Clients:"
    tmux list-clients

    echo "Sessions:"
    tmux list-sessions

    echo "Windows:"
    tmux list-windows

    echo "Panes:"
    tmux list-panes
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>ViewRegion — Miruken-ES5  documentation</title>

    <link rel="stylesheet" href="../../../_static/css/theme.css" type="text/css" />

    <link rel="stylesheet" href="../../../_static/banner.css" type="text/css" />

        <link rel="index" title="Index"
              href="../../../genindex.html"/>
        <link rel="search" title="Search" href="../../../search.html"/>
    <link rel="top" title="Miruken-ES5  documentation" href="../../../index.html"/>
        <link rel="up" title="Angular" href="index.html"/>
        <link rel="prev" title="Navigation" href="navigation.html"/>

             Miruken-ES5

  <form id="rtd-search-form" class="wy-form" action="../../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

Documentation

Where Can I Get Miruken-ES5?

Miruken

MVC

Angular

Controller

Navigation

ViewRegion

          Miruken-ES5

Docs »

Angular »

ViewRegion

             View page source

ViewRegion¶

show()¶

Controllers are responsible for choosing and showing one or more views.

showTeams() {
    return ViewRegion(this.io).show("app/team/teams");
},

choosePlayer() {
    return ViewRegion(this.io.modal({
        title:   "Select Your Players",
        buttons: [
            { text: "Ok",     css: "btn-sm btn-primary" },
            { text: "Cancel", css: "btn-sm", tag: -1 }
        ]
    })).show("app/player/choosePlayer")
       .then(layer => layer.modalResult.then(result => {
           if (result && result.button.tag != -1) {
               return this.selectedPlayers;
           }
       })).finally(() => this.endContext());
}

         Previous

        © Copyright 2017, Miruken.

  Built with Sphinx using a theme provided by Read the Docs.

         Other Versions
        v: 2.0.24

Tags

2.0.24

2.0.25

2.0.26

2.0.28

2.0.29

2.0.31

2.0.32

2.0.33

2.0.34

2.0.35

2.0.36

2.0.38

2.0.4

Branches

develop

master


text:
using System;

namespace WootzJs.Mvc.Views
{
    public enum TextBoxType
    {
        Text, Password, Color, Email, Number, Range, Search, Telephone, Url, Date, DateTime, Time
    }

    public static class TextBoxTypes
    {
        public static string GetInputType(this TextBoxType type)
        {
            switch (type)
            {
                case TextBoxType.Color:
                    return "color";
                case TextBoxType.Email:
                    return "email";
                case TextBoxType.Number:
                    return "number";
                case TextBoxType.Password:
                    return "password";
                case TextBoxType.Range:
                    return "range";
                case TextBoxType.Url:
                    return "url";
                case TextBoxType.Search:
                    return "search";
                case TextBoxType.Telephone:
                    return "tel";
                case TextBoxType.Text:
                    return "text";
                case TextBoxType.Date:
                    return "date";
                case TextBoxType.DateTime:
                    return "datetime";
                case TextBoxType.Time:
                    return "time";
                default:
                    throw new Exception();
            }
        }

        public static TextBoxType Parse(string s)
        {
            switch (s)
            {
                case "color":
                    return TextBoxType.Color;
                case "email":
                    return TextBoxType.Email;
                case "number":
                    return TextBoxType.Number;
                case "password":
                    return TextBoxType.Password;
                case "range":
                    return TextBoxType.Range;
                case "url":
                    return TextBoxType.Url;
                case "search":
                    return TextBoxType.Search;
                case "tel":
                    return TextBoxType.Telephone;
                case "text":
                    return TextBoxType.Text;
                case "date":
                    return TextBoxType.Date;
                case "datetime":
                    return TextBoxType.DateTime;
                case "time":
                    return TextBoxType.Time;
                default:
                    throw new Exception();
            }
        }
    }
}


text:
layout: post
title: HeapSort
description: "HeapSort"
headline: "Let's Sort it up: the revenge"
categories: algorithms
tags:
  - algorithms
  - recursive sort
  - heap sort
  - sorting
  - recursion
comments: true
mathjax: null
featured: true
published: true
---
### Sorting Algorithms - Part 3
Let's continue with the study of another recursive sorting algorithm: the **HeapSort**.

### HeapSort
Like the [QuickSort]() and the [MergeSort](), the HeapSort is one of the efficient sorting algorithms based on
comparison. It is efficient because the average performance of these methods hit the $$O(n⋅log_2n)$$ runtime, though
with differences in the worst-case. Other inefficient algorithms, such as Selection, Insertion and Bubble Sort,
have $$O(n^2)$$ complexity meaning that they make all the possible comparisons of the elements under analysis.

The HeapSort is an improvement of the SelectionSort but has a better worst-case scenario thanks to the leverage of an
efficient structure that allows the fast selection of the minimum (or maximum) of the data pool.
To understand the HeapSort we need to describe this data structure (the _heap_), a method to create one in a
"reasonable" time, a method to keep its characteristics after a change and a method to translate the _heap_ in a
sorted collection. Furthermore, it is necessary that the total time needed for these methods are less than the
infamous $$O(n^2)$$ but possible near the lower bound of the comparison sorting algorithms $$\Omega(n⋅log_2n)$$
(spoiler: it will be!).

### The _Heap_
The _heap_ is a binary tree-based data structure that satisfied three properties:

1. is a completed binary tree (all levels are filled except possibly the last and all nodes in the last level are as
far left as possible);
2. every data element considered is associated to one and only one node, and one node is associated to one and only
one element;
3. every value of a node is always greater or equals of the values of the children of that node.

An example of an _heap_ with values from 1 to 100:

<img class="image-post" src="{{ site.url }}/images/heapsort/max-heap.png" alt="Heap" style="max-height: 300px;">

An _heap_ with $$n$$ nodes has an height of $$\Theta(log_2n)$$.
It can be easily represented by an array in which if the root of the tree is placed in the index ```i = 0```:

* the left child is placed in ```2i + 1```;
* the right child is placed in ```2i + 2```;
* the parent is placed in ```(i - 1) / 2``` always rounded to the small leading integer.

### Erase the max value
Suppose we already have an _heap_ with all the properties met. It is immediate to see that, for the property 3, the
maximum value is placed in the root. Sooner or later, for sorting purpose, we would like to remove that element and
be sure that all the properties of the _heap_ will still be verified. Than it is necessary a method capable to
"fixing" the _heap_. This means that not only one of the root children must became the new root, but also that the
shift cannot cause the ceasing of property 1.

An handy solution can be swapping the value in the root with the last element ```k``` of the _heap_ and erase it. Doing
that the property 1 is respected but not the property 3. So the method must "pull down" ```k``` and, during the
process, bring a new max value in the root. The pseudo code for the ```fixHeap``` is shown below:

```
fixHeap(node n, heap h)
    if (n is a leaf of h) then return
    else
        c = max(childLeft, childRight)
        if (n < c)
            swap(n, c)
            fixHeap(c, h)
```

The max number of comparisons is given by the height of the tree: $$O(log_2n)$$.

### Building the _Heap_
Given an array of values, it is possible to build an _heap_ in a convenient time? Yes it is and to do so it is possible
to use two already seen methods: the first one is divide and conquer and the second one is ```fixHeap```.
The creation of the tree by a positional array is an operation with no comparisons required. Then the array must
fulfill the 3 properties of the _heap_. The second one is already verified having chosen the positional array as
representation. To satisfy the others it is possible to divide the _heap_ is sub trees similar to the full tree and
with the same properties and then apply the fix seen before. The pseudo code:

```
headpify(Tree T)
    if (T is empty) the return
    heapify(leftChild(T))
    heapify(rightChild(T))
    fixHeap(root(T), T)
```

But what about the time $$T(n)$$ needed by this algorithm? Every recursive call needs $$T(\frac{n}{2})$$ and we already
seen
that ```fixHeap``` needs $$O(log_2n)$$. So:

$$T(n) = 2T(\frac{n}{2}) + O(log_2n)$$

The [master theorem](https://en.wikipedia.org/wiki/Master_theorem) says that, in this case: $$T(n) = O(n)$$.

### Sorting in place
Let's put together the pieces seen until now. Given an array A, if exists a method to create in time $$t_1$$ a data
structure in which finding and erasing the maximum require time $$t_2$$ than it is possible to sorting in time $$O
(t_1 + n⋅t_2)$$. Using the _heap_: $$t_1 = O(n)$$ and $$t_2 = O(log_2n)$$ so:

$$O(n + n⋅log_2n) = O(n⋅log_2n)$$

```
heapSort(array A, count)
    heapify(A)
    end <- count - 1
    while end > 0 do
        swap(A[end], A[0])
        end <- end - 1
        deleteLastNode(A)
        fixHeap(A)
```

Given a generic array the first thing to do is build the _heap_; then the first element (which is the max value) is
put at the end of the array and removed from the _heap_; the _heap_ is then "fixed" and the new max value at the
beginning is put in the new end just before the previous. The loop continues until the full sorting.


text:
/**
 *
 */
package com.browseengine.bobo.search.section;

import java.io.IOException;

import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.util.PriorityQueue;

/**
 * This class represents a section search query plan
 *
 */
public abstract class SectionSearchQueryPlan {
  public static final int NO_MORE_POSITIONS = Integer.MAX_VALUE;
  public static final int NO_MORE_SECTIONS = Integer.MAX_VALUE;

  protected int _curDoc;
  protected int _curSec;

  /*
   * Priority queue of Nodes.
   */
  static public class NodeQueue extends PriorityQueue<Object> {
    public NodeQueue(int size) {
      super(size);
    }

    @Override
    protected boolean lessThan(Object objA, Object objB) {
      SectionSearchQueryPlan nodeA = (SectionSearchQueryPlan) objA;
      SectionSearchQueryPlan nodeB = (SectionSearchQueryPlan) objB;
      if (nodeA._curDoc == nodeB._curDoc) {
        return (nodeA._curSec < nodeB._curSec);
      }
      return (nodeA._curDoc < nodeB._curDoc);
    }
  }

  public SectionSearchQueryPlan() {
    _curDoc = -1;
    _curSec = -1;
  }

  public int getDocId() {
    return _curDoc;
  }

  public int getSecId() {
    return _curSec;
  }

  public int fetch(int targetDoc) throws IOException {
    while (fetchDoc(targetDoc) < DocIdSetIterator.NO_MORE_DOCS) {
      if (fetchSec(0) < SectionSearchQueryPlan.NO_MORE_SECTIONS) return _curDoc;
    }
    return _curDoc;
  }

  abstract public int fetchDoc(int targetDoc) throws IOException;

  abstract public int fetchSec(int targetSec) throws IOException;

  protected int fetchPos() throws IOException {
    return NO_MORE_POSITIONS;
  }
}


text:
require 'gdal-ruby/ogr'
require 'rgdal/overrides/layer'
require 'rgdal/overrides/data_source'
require 'rgdal/overrides/field_defn'
require 'rgdal/overrides/feature'
require 'rgdal/api'
require 'rgdal/version'
require 'rgdal/base'
require 'rgdal/csv'
require 'rgdal/kml'
require 'rgdal/shp'
require 'rgdal/geojson'


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace Csla.Test.Basic
{
    [Serializable()]
    public class GrandChild : BusinessBase<GrandChild>
    {
        private string _data = "";

        protected override object GetIdValue()
        {
            return _data;
        }

        public string Data
        {
            get { return _data; }
            set
            {
                if (_data != value)
                {
                    _data = value;
                    MarkDirty();
                }
            }
        }

        internal static GrandChild NewGrandChild(string data)
        {
            GrandChild obj = new GrandChild();
            obj._data = data;
            return obj;
        }

        internal static GrandChild GetGrandChild(IDataReader dr)
        {
            GrandChild obj = new GrandChild();
            obj.Fetch(dr);
            return obj;
        }

        public GrandChild()
        {
            MarkAsChild();
        }

        private void Fetch(IDataReader dr)
        {
            MarkOld();
        }

        internal void Update(IDbTransaction tr)
        {
            if (IsDeleted)
            {
                //we would delete here
                MarkNew();
            }
            else
            {
                if (IsNew)
                {
                    //we would insert here
                }
                else
                {
                    //we would update here
                }
                MarkOld();
            }
        }

        protected override void OnDeserialized(System.Runtime.Serialization.StreamingContext context)
        {
            base.OnDeserialized(context);
            Csla.ApplicationContext.GlobalContext.Add("GCDeserialized", "GC Deserialized");
        }
    }
}


text:
package com.omnicrola.pixelblaster.powerups;

import com.omnicrola.pixelblaster.map.io.PowerupData;
import com.omnicrola.pixelblaster.physics.IPhysicsEntity;
import com.omnicrola.pixelblaster.physics.IPhysicsManager;

public class PowerupPhysicsFactory {
	private final IPhysicsManager physicsManager;

	public PowerupPhysicsFactory(IPhysicsManager physicsManager) {
		this.physicsManager = physicsManager;
	}

	public IPhysicsEntity build(PowerupData powerupData) {
		//@formatter:off
		final IPhysicsEntity physicsEntity = this.physicsManager.getBuilder()
				.setStatic()
				.density(0)
				.friction(0)
				.build();
		//@formatter:on

		return physicsEntity;
	}

}


text:
UPDATE cpeEcosystemCache set ecosystem='MULTIPLE' where vendor = 'icu-project' and product = 'international_components_for_unicode';
INSERT INTO cpeEcosystemCache (vendor, product, ecosystem) VALUES ('unicode', 'international_components_for_unicode', 'MULTIPLE');

UPDATE Properties SET `value`='5.2.1' WHERE ID='version';


text:
#ifndef BISON_Y_TAB_H
# define BISON_Y_TAB_H

#ifndef YYSTYPE
typedef union
{
  struct accelerator acc;
  struct accelerator *pacc;
  struct dialog_control *dialog_control;
  struct menuitem *menuitem;
  struct
  {
    struct rcdata_item *first;
    struct rcdata_item *last;
  } rcdata;
  struct rcdata_item *rcdata_item;
  struct stringtable_data *stringtable;
  struct fixed_versioninfo *fixver;
  struct ver_info *verinfo;
  struct ver_stringinfo *verstring;
  struct ver_varinfo *vervar;
  struct res_id id;
  struct res_res_info res_info;
  struct
  {
    unsigned short on;
    unsigned short off;
  } memflags;
  struct
  {
    unsigned long val;
    /* Nonzero if this number was explicitly specified as long.  */
    int dword;
  } i;
  unsigned long il;
  unsigned short is;
  const char *s;
  struct
  {
    unsigned long length;
    const char *s;
  } ss;
} yystype;
# define YYSTYPE yystype
# define YYSTYPE_IS_TRIVIAL 1
#endif
# define	BEG	257
# define	END	258
# define	ACCELERATORS	259
# define	VIRTKEY	260
# define	ASCII	261
# define	NOINVERT	262
# define	SHIFT	263
# define	CONTROL	264
# define	ALT	265
# define	BITMAP	266
# define	CURSOR	267
# define	DIALOG	268
# define	DIALOGEX	269
# define	EXSTYLE	270
# define	CAPTION	271
# define	CLASS	272
# define	STYLE	273
# define	AUTO3STATE	274
# define	AUTOCHECKBOX	275
# define	AUTORADIOBUTTON	276
# define	CHECKBOX	277
# define	COMBOBOX	278
# define	CTEXT	279
# define	DEFPUSHBUTTON	280
# define	EDITTEXT	281
# define	GROUPBOX	282
# define	LISTBOX	283
# define	LTEXT	284
# define	PUSHBOX	285
# define	PUSHBUTTON	286
# define	RADIOBUTTON	287
# define	RTEXT	288
# define	SCROLLBAR	289
# define	STATE3	290
# define	USERBUTTON	291
# define	BEDIT	292
# define	HEDIT	293
# define	IEDIT	294
# define	FONT	295
# define	ICON	296
# define	LANGUAGE	297
# define	CHARACTERISTICS	298
# define	VERSIONK	299
# define	MENU	300
# define	MENUEX	301
# define	MENUITEM	302
# define	SEPARATOR	303
# define	POPUP	304
# define	CHECKED	305
# define	GRAYED	306
# define	HELP	307
# define	INACTIVE	308
# define	MENUBARBREAK	309
# define	MENUBREAK	310
# define	MESSAGETABLE	311
# define	RCDATA	312
# define	STRINGTABLE	313
# define	VERSIONINFO	314
# define	FILEVERSION	315
# define	PRODUCTVERSION	316
# define	FILEFLAGSMASK	317
# define	FILEFLAGS	318
# define	FILEOS	319
# define	FILETYPE	320
# define	FILESUBTYPE	321
# define	BLOCKSTRINGFILEINFO	322
# define	BLOCKVARFILEINFO	323
# define	VALUE	324
# define	BLOCK	325
# define	MOVEABLE	326
# define	FIXED	327
# define	PURE	328
# define	IMPURE	329
# define	PRELOAD	330
# define	LOADONCALL	331
# define	DISCARDABLE	332
# define	NOT	333
# define	QUOTEDSTRING	334
# define	STRING	335
# define	NUMBER	336
# define	SIZEDSTRING	337
# define	IGNORED_TOKEN	338
# define	NEG	339

extern YYSTYPE yylval;

#endif /* not BISON_Y_TAB_H */


text:
title: Apple Becomes 'Most Valuable Brand' of 2013
date: 2013-09-30 12:05:04 -05:00
tags:
- Apple
- tech
layout: post
custom_type: link
link_url: http://thenextweb.com/apple/2013/09/30/apple-overtakes-coca-cola-to-become-most-valuable-brand-of-2013/
---

>Apple has taken the top spot as 2013′s Most Valuable Brand, ending Coca-Cola's 13 year streak as number one in the annual Best Global Brands report compiled by Interbrand. Coca-Cola ended up third, surpassed by both Apple and Google this year.

I think this is pretty big news. A company's brand is based a lot on public perception, and for Apple and Google to surpass Coca-Cola, which in my opinion is the one of the best brands ever created,[^1] is quite the compliment on how they're doing.

[^1]: You know you agree with that. Whether you're a Coke lover, or Pepsi lover (Oh god, can I footnote the footnote?), Coca-Cola has been advertising it's drink with bears… bears. If you can advertise your product without taking cheap shots at your competitor, you're doing well.


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>resetStyleInheritance property - ShadowRoot class - polymer_app_layout.behaviors library - Dart API</title>

    <base href="../..">

    <link href='https://fonts.googleapis.com/css?family=Source+Code+Pro|Roboto:500,400italic,300,400' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="static-assets/prettify.css">
    <link rel="stylesheet" href="static-assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="static-assets/styles.css">

    <meta name="description" content="API docs for the resetStyleInheritance property from the ShadowRoot class, for the Dart programming language.">
    <link rel="icon" href="static-assets/favicon.png">

            <button id="sidenav-left-toggle" type="button"> </button>

polymer_app_layout_template

polymer_app_layout.behaviors

ShadowRoot

resetStyleInheritance

resetStyleInheritance

polymer_app_layout_template

polymer_app_layout.behaviors

ShadowRoot

resetStyleInheritance

property
 resetStyleInheritance

polymer_app_layout_template

polymer_app_layout.behaviors

ShadowRoot

Static properties

supported

Properties

activeElement

applyAuthorStyles

baseUri

childNodes

children

firstChild

host

innerHtml

innerHtml

lastChild

nextNode

nodeName

nodes

nodeType

nodeValue

olderShadowRoot

on

ownerDocument

parent

parentNode

previousNode

resetStyleInheritance

styleSheets

text

Methods

addEventListener

append

appendHtml

appendText

clone

contains

dispatchEvent

elementFromPoint

getElementById

getElementsByClassName

getElementsByTagName

getSelection

hasChildNodes

insertAllBefore

insertBefore

query

queryAll

querySelector

querySelectorAll

remove

removeEventListener

replaceWith

setInnerHtml

toString

        bool
        resetStyleInheritance

            read / write

Not documented.

                  polymer_app_layout_template 0.1.0 api docs

                •

                •

                  cc license


text:
package org.broadinstitute.hellbender.tools.spark.pathseq;

import htsjdk.samtools.metrics.MetricsFile;
import org.apache.commons.io.FileUtils;
import org.broadinstitute.hellbender.CommandLineProgramTest;
import org.broadinstitute.hellbender.testutils.ArgumentsBuilder;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class PathSeqScoreIntegrationTest extends CommandLineProgramTest {

    static final int SCORE_TABLE_COLUMNS = 10;
    static final double SCORE_ABSOLUTE_ERROR_TOLERANCE = 1e-6;

    @Override
    public String getTestedClassName() {
        return PathSeqScoreSpark.class.getSimpleName();
    }

    private static boolean testPathogenTaxonScores(final PSPathogenTaxonScore a, final PSPathogenTaxonScore b) {
        if (a.getKingdomTaxonId() != b.getKingdomTaxonId()) return false;
        if (!PathSeqTestUtils.equalWithinTolerance(a.getDescendentScore(),b.getDescendentScore(), SCORE_ABSOLUTE_ERROR_TOLERANCE)) return false;
        if (!PathSeqTestUtils.equalWithinTolerance(a.getTotalReads(),b.getTotalReads(), SCORE_ABSOLUTE_ERROR_TOLERANCE)) return false;
        if (!PathSeqTestUtils.equalWithinTolerance(a.getReferenceLength(),b.getReferenceLength(), SCORE_ABSOLUTE_ERROR_TOLERANCE)) return false;
        if (!PathSeqTestUtils.equalWithinTolerance(a.getSelfScore(),b.getSelfScore(), SCORE_ABSOLUTE_ERROR_TOLERANCE)) return false;
        if (!PathSeqTestUtils.equalWithinTolerance(a.getScoreNormalized(),b.getScoreNormalized(), SCORE_ABSOLUTE_ERROR_TOLERANCE)) return false;
        if (!PathSeqTestUtils.equalWithinTolerance(a.getUnambiguousReads(),b.getUnambiguousReads(), SCORE_ABSOLUTE_ERROR_TOLERANCE)) return false;
        return true;
    }

    private static Map<String, PSPathogenTaxonScore> getScores(final String[] lines) {
        final Map<String, PSPathogenTaxonScore> scores = new HashMap<>(lines.length);
        for (int i = 1; i < lines.length; i++) {
            String[] tok = lines[i].split("\t");
            Assert.assertTrue(tok.length == SCORE_TABLE_COLUMNS, "Expected " + SCORE_TABLE_COLUMNS + " columns, but found " + tok.length);
            final PSPathogenTaxonScore score = new PSPathogenTaxonScore();
            final String taxonId = tok[0];
            score.setKingdomTaxonId(Math.abs(tok[4].hashCode()));
            score.addSelfScore(Double.parseDouble(tok[5]));
            score.addScoreNormalized(Double.parseDouble(tok[6]));
            score.addTotalReads(Integer.parseInt(tok[7]));
            score.addUnambiguousReads(Integer.parseInt((tok[8])));
            score.setReferenceLength(Long.parseLong(tok[9]));
            Assert.assertFalse(scores.containsKey(taxonId), "Found more than one entry for taxon ID " + taxonId);
            scores.put(taxonId, score);
        }
        return scores;
    }

    public static void compareScoreTables(final String expected, final String test) {
        final String[] expectedLines = expected.split("\n");
        final String[] testLines = test.split("\n");
        if (expectedLines.length == 0 && testLines.length == 0) return;
        Assert.assertEquals(expectedLines[0], testLines[0], "Headers did not match");

        final Map<String, PSPathogenTaxonScore> expectedScores = getScores(expectedLines);
        final Map<String, PSPathogenTaxonScore> testScores = getScores(testLines);

        for (final String taxonId : testScores.keySet()) {
            Assert.assertTrue(expectedScores.containsKey(taxonId), "Did not expect the taxon ID: " + taxonId);
        }
        for (final String taxonId : expectedScores.keySet()) {
            Assert.assertTrue(testScores.containsKey(taxonId), "Did not find the expected taxon ID: " + taxonId);
        }
        for (final String taxonId : expectedScores.keySet()) {
            Assert.assertTrue(testPathogenTaxonScores(testScores.get(taxonId), expectedScores.get(taxonId)), "Scores for taxon ID " + taxonId + " did not match.");
        }
    }

    @DataProvider(name = "pathseqScoreTestData")
    public Object[][] getTestData() {
        return new Object[][]{
                {"expected_paired.txt", "expected_paired.metrics",
                        "alignment_paired.bam", null, false, false},
                {"expected_unpaired.txt", "expected_unpaired.metrics",
                        null, "alignment_unpaired.bam", false, false},
                {"expected_paired_genome_length.txt", "expected_paired_genome_length.metrics",
                        "alignment_paired.bam", null, true, false},
                {"expected_paired_kingdom_false.txt", "expected_paired_kingdom_false.metrics",
                        "alignment_paired.bam", null, false, true}
        };
    }
    @Test(dataProvider = "pathseqScoreTestData", groups = "spark")
    public void testPathSeqScoreSpark(final String expectedScoresFilename, final String expectedMetricsFilename,
                     final String inputPairedBamFilename, final String inputUnpairedBamFilename,
                     final boolean divideByGenomeLength, final boolean notNormalizedByKingdom) throws IOException {
        final File expectedScoresFile =  getTestFile(expectedScoresFilename);
        final File expectedMetricsFile = getTestFile(expectedMetricsFilename);
        final File inputPairedBamFile = inputPairedBamFilename == null ? null : getTestFile(inputPairedBamFilename);
        final File inputUnpairedBamFile = inputUnpairedBamFilename == null ? null : getTestFile(inputUnpairedBamFilename);
        final File taxFile = getTestFile("tax.db");
        final File outputScoresFile = createTempFile("test", ".txt");
        final File outputBamFile = createTempFile("output", ".bam");
        final File outputMetricsFile = createTempFile("score", ".metrics");
        final ArgumentsBuilder args = new ArgumentsBuilder();
        if (inputPairedBamFile != null) {
            args.add(PathSeqScoreSpark.PAIRED_INPUT_LONG_NAME, inputPairedBamFile);
        }
        if (inputUnpairedBamFile != null) {
            args.add(PathSeqScoreSpark.UNPAIRED_INPUT_LONG_NAME, inputUnpairedBamFile);
        }
        args.add(PSScoreArgumentCollection.SCORE_METRICS_FILE_LONG_NAME, outputMetricsFile);
        args.add(PSScoreArgumentCollection.TAXONOMIC_DATABASE_LONG_NAME, taxFile);
        args.add(PSScoreArgumentCollection.SCORES_OUTPUT_LONG_NAME, outputScoresFile);
        args.addOutput(outputBamFile);
        args.add(PSScoreArgumentCollection.DIVIDE_BY_GENOME_LENGTH_LONG_NAME, divideByGenomeLength);
        args.add(PSScoreArgumentCollection.NOT_NORMALIZED_BY_KINGDOM_LONG_NAME, notNormalizedByKingdom);

        this.runCommandLine(args.getArgsArray());

        final String expectedScoresString = FileUtils.readFileToString(expectedScoresFile, StandardCharsets.UTF_8);
        final String actualScoresString = FileUtils.readFileToString(outputScoresFile, StandardCharsets.UTF_8);
        compareScoreTables(expectedScoresString, actualScoresString);

        Assert.assertTrue(MetricsFile.areMetricsEqual(outputMetricsFile, expectedMetricsFile));
    }

}


text:
{:L(user_edit_info)}

					<form method='post'  id="myform" action="{:URL('User-Index/password')}">

						{:L('email')}
						<input type="text" class="input-text" id="email" name="email" value="{$vo.email}" validate="required:true,email:true,remote: '{:U('User/Register/checkEmail?userid='.$_COOKIE['YP_userid'])}' , minlength:1, maxlength:40">

{:L('oldpassword')}	<input type="password" class="input-text" name="oldpassword" validate=" required:true, minlength:5, maxlength:20">

{:L('newpassword')}	<input type="password" class="input-text"  name="password" id="password" validate=" required:true, minlength:5, maxlength:20">

{:L('repassword')}	<input type="password" class="input-text"  name="repassword" validate=" required:true,equalTo: '#password', minlength:5, maxlength:20">

{:L('verify')}	<input type="text" class="input-text" size="6" name="verify">

					<INPUT TYPE="submit"  name="dosubmit" value="{:L('dosubmit')}" class="button" >
					<input type="reset"  value="{:L('cancel')}" class="button">

					</form>


text:
using namespace csuf;
using namespace std;

const double EPS = 1e-3,  // tolerance for floating point comparison
             DELTA = .10;
const string PPM_FILENAME = "test.ppm",
             PNG_FILENAME = "test.png";

const int FRAME_COUNT = 1000000,
  SAMPLE_RATE = 44100,
  NOTE_FREQ = 440;
const string WAV_FILENAME = "test.wav",
  WAV_2_FILENAME = "test2.wav",
  FLAC_FILENAME = "test.flac";

BOOST_AUTO_TEST_CASE( test_is_in_range ) {
  // int overload
  BOOST_CHECK(is_in_range(1, 5, 10));   // yes
  BOOST_CHECK(!is_in_range(1, -5, 10)); // no
  BOOST_CHECK(is_in_range(1, 1, 10));   // inclusive
  BOOST_CHECK(is_in_range(1, 10, 10));  // inclusive

  // double overload
  BOOST_CHECK(is_in_range(1.0, 5.0, 10.0));   // yes
  BOOST_CHECK(!is_in_range(1.0, -5.0, 10.0)); // no
  BOOST_CHECK(is_in_range(1.0, 1.0, 10.0));   // inclusive
  BOOST_CHECK(is_in_range(1.0, 10.0, 10.0));  // inclusive
}

BOOST_AUTO_TEST_CASE( test_is_valid_intensity ) {
  BOOST_CHECK(is_valid_intensity(0.0));
  BOOST_CHECK(is_valid_intensity(0.5));
  BOOST_CHECK(is_valid_intensity(1.0));
  BOOST_CHECK(!is_valid_intensity(-1.0));
  BOOST_CHECK(!is_valid_intensity(1.01));
}

BOOST_AUTO_TEST_CASE( test_Color ) {
  // constructor and getters
  Color red(1, 0, 0);
  BOOST_CHECK_EQUAL(1.0, red.get_red());
  BOOST_CHECK_EQUAL(0.0, red.get_green());
  BOOST_CHECK_EQUAL(0.0, red.get_blue());
  Color green(0, 1, 0);
  BOOST_CHECK_EQUAL(0.0, green.get_red());
  BOOST_CHECK_EQUAL(1.0, green.get_green());
  BOOST_CHECK_EQUAL(0.0, green.get_blue());
  Color blue(0, 0, 1);
  BOOST_CHECK_EQUAL(0.0, blue.get_red());
  BOOST_CHECK_EQUAL(0.0, blue.get_green());
  BOOST_CHECK_EQUAL(1.0, blue.get_blue());

  // Mutators
  const double before = 0, after = 0.6;
  Color c = Color(before, before, before);
  // set_red
  BOOST_CHECK_CLOSE(before, c.get_red(), EPS);
  c.set_red(after);
  BOOST_CHECK_CLOSE(after, c.get_red(), EPS);
  // set_green
  BOOST_CHECK_CLOSE(before, c.get_green(), EPS);
  c.set_green(after);
  BOOST_CHECK_CLOSE(after, c.get_green(), EPS);
  // set_blue
  BOOST_CHECK_CLOSE(before, c.get_blue(), EPS);
  c.set_blue(after);
  BOOST_CHECK_CLOSE(after, c.get_blue(), EPS);
}

BOOST_AUTO_TEST_CASE( test_color_constants ) {
  BOOST_CHECK_EQUAL(0, BLACK.get_red());
  BOOST_CHECK_EQUAL(0, BLACK.get_green());
  BOOST_CHECK_EQUAL(0, BLACK.get_blue());

  BOOST_CHECK_EQUAL(1, WHITE.get_red());
  BOOST_CHECK_EQUAL(1, WHITE.get_green());
  BOOST_CHECK_EQUAL(1, WHITE.get_blue());

  BOOST_CHECK_EQUAL(1, RED.get_red());
  BOOST_CHECK_EQUAL(0, RED.get_green());
  BOOST_CHECK_EQUAL(0, RED.get_blue());

  BOOST_CHECK_EQUAL(0, GREEN.get_red());
  BOOST_CHECK_EQUAL(1, GREEN.get_green());
  BOOST_CHECK_EQUAL(0, GREEN.get_blue());

  BOOST_CHECK_EQUAL(0, BLUE.get_red());
  BOOST_CHECK_EQUAL(0, BLUE.get_green());
  BOOST_CHECK_EQUAL(1, BLUE.get_blue());
}

BOOST_AUTO_TEST_CASE( test_Image_empty ) {
  // constructor
  Image im;
  BOOST_CHECK(im.is_empty());
  const int BIG = 200;
  for (int x = -BIG; x <= BIG; ++x)
    for (int y = -BIG; y <= BIG; ++y)
      BOOST_CHECK(!im.is_valid_coordinates(x, y));

  // operator==
  Image im2;
  BOOST_CHECK(im == im2);

  // clear
  Image clear;
  BOOST_CHECK(clear.is_empty());
  im.clear();
  BOOST_CHECK(clear.is_empty());

  // resize
  Image resize;
  BOOST_CHECK(resize.is_empty());
  resize.resize(100, 200, BLACK);
  BOOST_CHECK(!resize.is_empty());
  BOOST_CHECK_EQUAL(100, resize.get_width());
  BOOST_CHECK_EQUAL(200, resize.get_height());

  // fill
  Image fill;
  BOOST_CHECK(fill.is_empty());
  fill.fill(BLACK);
  BOOST_CHECK(fill.is_empty());
}

BOOST_AUTO_TEST_CASE( test_Image_nonempty ) {
  // sized constructor
  // is_empty
  // get_width
  // get_height
  const int W = 100, H = 200;
  BOOST_CHECK(W != H); // should differ
  Image im(W, H, BLACK);
  BOOST_CHECK(!im.is_empty());
  BOOST_CHECK_EQUAL(W, im.get_width());  // get_width
  BOOST_CHECK_EQUAL(H, im.get_height()); // get_height
  for (int x = 0; x < W; ++x)
    for (int y = 0; y < H; ++y)
      BOOST_CHECK(im.get_pixel(x, y) == BLACK);

  // operator==
  // identical
  Image im2(W, H, BLACK);
  BOOST_CHECK(im == im2);
  // same dimensions, one different pixel
  Image im3 = im2;
  im3.set_pixel(W/2, H/2, RED);
  BOOST_CHECK(!(im2 == im3));
  // same colors, different dimensions
  Image im4(H, W, BLACK);
  BOOST_CHECK(!(im3 == im4));

  // is_valid_coordinates
  BOOST_CHECK(im.is_valid_coordinates(0, 0));
  BOOST_CHECK(im.is_valid_coordinates(W-1, H-1));
  BOOST_CHECK(!im.is_valid_coordinates(-1, -1));
  BOOST_CHECK(!im.is_valid_coordinates(W, H));
  BOOST_CHECK(!im.is_valid_coordinates(W*2, H*2));
  const int BIG = 2 * max(W, H);
  for (int x = -BIG; x <= BIG; ++x)
    for (int y = -BIG; y <= BIG; ++y)
      BOOST_CHECK_EQUAL((x >= 0) && (y >= 0) && (x < W) && (y < H),
			im.is_valid_coordinates(x, y) );

  // clear
  Image cleared;
  BOOST_CHECK(cleared.is_empty());
  cleared.resize(W, H, BLACK);
  BOOST_CHECK(!cleared.is_empty());

  // resize
  Image resized;
  BOOST_CHECK(resized.is_empty());
  // from empty
  resized.resize(10, 11, BLACK);
  BOOST_CHECK(!resized.is_empty());
  BOOST_CHECK_EQUAL(10, resized.get_width());
  BOOST_CHECK_EQUAL(11, resized.get_height());
  BOOST_CHECK(resized.get_pixel(0, 0) == BLACK);
  // enlarge
  resized.resize(20, 21, RED);
  BOOST_CHECK(!resized.is_empty());
  BOOST_CHECK_EQUAL(20, resized.get_width());
  BOOST_CHECK_EQUAL(21, resized.get_height());
  BOOST_CHECK(resized.get_pixel(0, 0) == RED);

  // fill
  Image fill(W, H, BLACK);
  fill.fill(RED);
  BOOST_CHECK(fill.get_pixel(0, 0) == RED);
  BOOST_CHECK(fill.get_pixel(W-1, H-1) == RED);
  fill.fill(WHITE);
  BOOST_CHECK(fill.get_pixel(0, 0) == WHITE);
  BOOST_CHECK(fill.get_pixel(W-1, H-1) == WHITE);

  // get_pixel
  // get_mutable_pixel
  Image mutate(W, H, BLACK);
  BOOST_CHECK(mutate.get_pixel(0, 0) == BLACK);
  Color& pixel = mutate.get_mutable_pixel(0, 0);
  pixel.set_red(1);
  BOOST_CHECK(mutate.get_pixel(0, 0) == RED);

  // set_pixel
  Image set(W, H, BLACK);
  BOOST_CHECK(set.get_pixel(0, 0) == BLACK);
  set.set_pixel(0, 0, GREEN);
  BOOST_CHECK(set.get_pixel(0, 0) == GREEN);

}

BOOST_AUTO_TEST_CASE( test_read_ppm_file ) {
  // nonexistent file
  Image junk;
  BOOST_CHECK(!read_ppm_file(junk, "<NOTFOUND>.ppt", false));
  BOOST_CHECK(junk.is_empty());

  // malformed file
  BOOST_CHECK(!read_ppm_file(junk, "SConstruct", false));
  BOOST_CHECK(junk.is_empty());

  Image gimp_ascii;
  BOOST_CHECK(read_ppm_file(gimp_ascii, "elephant_gimp_ascii.ppm", true));
  BOOST_CHECK(!gimp_ascii.is_empty());
  Image proper = gimp_ascii;
  BOOST_CHECK(gimp_ascii == proper);
  BOOST_CHECK(approximate_equal(gimp_ascii, proper, DELTA));

  Image gimp_binary;
  BOOST_CHECK(read_ppm_file(gimp_binary, "elephant_gimp_binary.ppm", true));
  BOOST_CHECK(approximate_equal(gimp_binary, proper, DELTA));

  Image irfan_ascii;
  BOOST_CHECK(read_ppm_file(irfan_ascii, "elephant_irfan_ascii.ppm", true));
  BOOST_CHECK(approximate_equal(irfan_ascii, proper, DELTA));

  Image irfan_binary;
  BOOST_CHECK(read_ppm_file(irfan_binary, "elephant_irfan_ascii.ppm", true));
  BOOST_CHECK(approximate_equal(irfan_binary, proper, DELTA));

  Image magick;
  BOOST_CHECK(read_ppm_file(magick, "elephant_magick.ppm", true));
  BOOST_CHECK(approximate_equal(magick, proper, DELTA));
}

BOOST_AUTO_TEST_CASE( test_write_ppm_ascii ) {
  Image orig;
  BOOST_CHECK(read_ppm_file(orig, "elephant_gimp_ascii.ppm", true));
  BOOST_CHECK(write_ppm_file(orig, PPM_FILENAME, false, true));
  Image fresh;
  BOOST_CHECK(read_ppm_file(fresh, PPM_FILENAME, true));
  BOOST_CHECK(fresh == orig);
  remove(PPM_FILENAME.c_str());
}

BOOST_AUTO_TEST_CASE( test_write_ppm_binary ) {
  Image orig;
  BOOST_CHECK(read_ppm_file(orig, "elephant_gimp_binary.ppm", true));
  BOOST_CHECK(write_ppm_file(orig, PPM_FILENAME, true, true));
  Image fresh;
  BOOST_CHECK(read_ppm_file(fresh, PPM_FILENAME, true));
  BOOST_CHECK(fresh == orig);
  remove(PPM_FILENAME.c_str());
}

BOOST_AUTO_TEST_CASE( test_ppm_ascii_round_trip_magick_compatible ) {
  // write a fresh ASCII PPM
  Image orig;
  BOOST_CHECK(read_ppm_file(orig, "elephant_gimp_binary.ppm", true));
  BOOST_CHECK(write_ppm_file(orig, PPM_FILENAME, false, true));

  // have ImageMagick convert our PPM to PNG
  string command = "convert " + PPM_FILENAME + " " + PNG_FILENAME;
  BOOST_CHECK_EQUAL(0, system(command.c_str()));

  // convert its PNG to PPM
  command = "convert " + PNG_FILENAME + " " + PPM_FILENAME;
  BOOST_CHECK_EQUAL(0, system(command.c_str()));

  // load ImageMagick's PPM
  Image result;
  BOOST_CHECK(read_ppm_file(result, PPM_FILENAME, true));

  // images identical?
  BOOST_CHECK(result == orig);

  // delete temporary files
  remove(PNG_FILENAME.c_str());
  remove(PPM_FILENAME.c_str());
}

BOOST_AUTO_TEST_CASE( test_ppm_binary_round_trip_magick_compatible ) {
  Image orig;
  BOOST_CHECK(read_ppm_file(orig, "elephant_gimp_binary.ppm", true));
  BOOST_CHECK(write_ppm_file(orig, PPM_FILENAME, true, true));

  string command = "convert " + PPM_FILENAME + " " + PNG_FILENAME;
  BOOST_CHECK_EQUAL(0, system(command.c_str()));

  command = "convert " + PNG_FILENAME + " " + PPM_FILENAME;
  BOOST_CHECK_EQUAL(0, system(command.c_str()));

  Image result;
  BOOST_CHECK(read_ppm_file(result, PPM_FILENAME, true));

  BOOST_CHECK(result == orig);

  remove(PNG_FILENAME.c_str());
  remove(PPM_FILENAME.c_str());
}

inline void sin_clip(Clip& clip, int channel_count) {
  double period = SAMPLE_RATE / NOTE_FREQ;
  clip.assign(channel_count, FRAME_COUNT, 44100, 0.0);
  for (int frame = 0; frame < FRAME_COUNT; ++frame) {
    for (int channel = 0; channel < channel_count; ++channel) {
      double radians = (2.0*M_PI*frame/period) + (channel*M_PI/4.0);
      clip.set_sample(channel, frame, .9 * sin(radians));
    }
  }
}

BOOST_AUTO_TEST_CASE( test_read_write_wav ) {
  for (int channels = 1; channels <= 2; ++channels) {
    for (int bytes_per_sample = 1; bytes_per_sample <= 2; ++bytes_per_sample) {
      Clip before;

      sin_clip(before, channels);

      BOOST_ASSERT(write_wav_file(before, WAV_FILENAME, bytes_per_sample, true));

      Clip after;
      BOOST_ASSERT(read_wav_file(after, WAV_FILENAME, true));

      remove(WAV_FILENAME.c_str());

      BOOST_ASSERT(approximate_equal(before, after, DELTA));
    }
  }
}

BOOST_AUTO_TEST_CASE( test_wav_sox_round_trip ) {
  for (int channels = 1; channels <= 2; ++channels) {
    for (int bytes_per_sample = 1; bytes_per_sample <= 2; ++bytes_per_sample) {
      Clip before;

      sin_clip(before, channels);

      BOOST_ASSERT(write_wav_file(before, WAV_FILENAME, bytes_per_sample, true));

      string command = "sox " + WAV_FILENAME + " " + FLAC_FILENAME;
      system(command.c_str());
      command = "sox " + FLAC_FILENAME + " " + WAV_2_FILENAME;
      system(command.c_str());

      Clip after;
      BOOST_ASSERT(read_wav_file(after, WAV_2_FILENAME, true));

      remove(WAV_FILENAME.c_str());
      remove(WAV_2_FILENAME.c_str());
      remove(FLAC_FILENAME.c_str());

      BOOST_ASSERT(approximate_equal(before, after, DELTA));
    }
  }
}


text:
(function () {
    "use strict";
    var App = window.App,
        Router = Backbone.Router.extend({
            navigateOptions: { trigger: true, replace: true },

            routes: {
                "":                         "home",
                "offline":                  "offline",
                "locations":                "locations",
                "progress":                 "progress",
                "feedback":                 "feedback",
                "lost":                     "locations"
            },

            home: function() {
                this.navigate(App.robotBoard.getRoute(), this.navigateOptions);
            },

            offline: function() {
                if (App.robot.isConnected()) {
                    this.navigate("", this.navigateOptions);
                } else {
                    if (App.board != null) App.board.hide();
                    App.board = null;
                    App.robot.connect();
                }
            },

            locations: function() {
                if (!App.robot.isConnected()) {
                    this.navigate("offline", this.navigateOptions);
                } else {
                    if (App.board != null) App.board.hide();
                    App.locationBoard.show().build();
                    App.board = App.locationBoard;
                }
            },

            progress: function() {
                if (!App.robot.isConnected()) {
                    this.navigate("offline", this.navigateOptions);
                } else {
                    if (App.board != null) App.board.hide();
                    App.progressBoard.show().build();
                    App.board = App.progressBoard;
                }
            },

            feedback: function() {
                if (!App.robot.isConnected()) {
                    this.navigate("offline", this.navigateOptions);
                } else {
                    if (App.board != null) App.board.hide();
                    App.feedbackBoard.show().build();
                    App.board = App.feedbackBoard;
                }
            }
        });
    App.router = new Router();
})();


text:
[![view on npm](http://img.shields.io/npm/v/nature.svg)](https://www.npmjs.org/package/nature)
[![npm module downloads per month](http://img.shields.io/npm/dm/nature.svg)](https://www.npmjs.org/package/nature)
[![Build Status](https://travis-ci.org/75lb/nature.svg?branch=master)](https://travis-ci.org/75lb/nature)
[![Dependency Status](https://david-dm.org/75lb/nature.svg)](https://david-dm.org/75lb/nature)
![Analytics](https://ga-beacon.appspot.com/UA-27725889-9/nature/README.md?pixel)

Nature
======
abstract validation tests, for re-usabilty.

Model
-----
A plain object with

- validation per property
- validation per whole object (e.g. values must not match)
- observable, emit change events

Collection
----------

- validation (e.g. all files in a collection exist)

nature module
-------------
provides extra features on models and collections..

- test valid:   nature.isValid(model)
- group:        nature.group(model, [ "name", "type" ], "groupA")
- mixin:        nature.merge(commandLineArgs, fileArgs)
- extract:      nature.where(model, "fileArgs")
- create

    var argv = nature.create([
        { name: "one", alias: "a" },
        { name: "files", alias: "a", required: true, defaultOption: true },
        { name: "verbose", type: "boolean" }
    ]);


text:
import { logout, login, getToken, getInfo } from 'api/login';
import Cookies from 'js-cookie';

const user = {
  state: {
    user: '',
    status: '',
    email: '',
    code: '',
    uid: undefined,
    auth_type: '',
    token: Cookies.get('Admin-Token'),
    name: '',
    avatar: '',
    introduction: '',
    roles: [],
    routers: [],
    setting: {
      articlePlatform: []
    }
  },

  mutations: {
    SET_AUTH_TYPE: (state, type) => {
      state.auth_type = type;
    },
    SET_CODE: (state, code) => {
      state.code = code;
    },
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_UID: (state, uid) => {
      state.uid = uid;
    },
    SET_EMAIL: (state, email) => {
      state.email = email;
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction;
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting;
    },
    SET_STATUS: (state, status) => {
      state.status = status;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_ROUTERS: (state, routers) => {
      state.routers = routers;
    },
    LOGIN_SUCCESS: () => {
      console.log('login success')
    },
    LOGOUT_USER: state => {
      state.user = '';
    }
  },

  actions: {
    // 邮箱登录
    Login({ commit }, userInfo) {
      const uname = userInfo.uname.trim();
      return new Promise((resolve, reject) => {
        login(uname, userInfo.password).then(response => {
          const data = response.data;
          Cookies.set('Admin-Token', data.Msg.Token);
          commit('SET_TOKEN', data.Msg.Token);
          commit('SET_EMAIL', uname);
          resolve();
        }).catch(error => {
          reject(error);
        });
      });
    },

    GetToken({ commit }) {
      return new Promise((resolve, reject) => {
        getToken().then(response => {
          const data = response.data.Msg;
          Cookies.set('Admin-Token', data.Token);
          commit('SET_TOKEN', data.Token);
          commit('SET_EMAIL', data.Uname);
          resolve();
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token).then(response => {
          const data = response.data.Msg;
          var roles = new Array()
          for (var rindex in data.Roles) {
            roles.push(data.Roles[rindex].Name)
          }
          commit('SET_ROLES', roles);
          commit('SET_NAME', data.Name);
          commit('SET_ROUTERS', data.Routers);
          resolve(response);
        }).catch(error => {
          commit('SET_TOKEN', null);  //获取 user信息失败,说明token失效
          reject(error);
        });
      });
    },

    // 第三方验证登录
    LoginByThirdparty({ commit, state }, code) {
      return new Promise((resolve, reject) => {
        commit('SET_CODE', code);
        loginByThirdparty(state.status, state.email, state.code, state.auth_type).then(response => {
          commit('SET_TOKEN', response.data.token);
          Cookies.set('Admin-Token', response.data.token);
          resolve();
        }).catch(error => {
          reject(error);
        });
      });
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '');
          commit('SET_ROLES', []);
          Cookies.remove('Admin-Token');
          resolve();
        }).catch(error => {
          reject(error);
        });
      });
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '');
        Cookies.remove('Admin-Token');
        resolve();
      });
    },

    // 动态修改权限
    ChangeRole({ commit }, role) {
      return new Promise(resolve => {
        commit('SET_ROLES', [role]);
        commit('SET_TOKEN', role);
        Cookies.set('Admin-Token', role);
        resolve();
      })
    }
  }
};

export default user;


text:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
    <defaultCache eternal="false" maxElementsInMemory="100" overflowToDisk="false" />
    <cache name="distinctValuesCountCache" maxElementsInMemory="30" eternal="false" overflowToDisk="false" />
    <cache name="dwcaResourceModelCache" maxElementsInMemory="30" eternal="false" overflowToDisk="false" />
    <cache name="resourceMetadataCache" maxElementsInMemory="30" eternal="false" overflowToDisk="false" />
    <cache name="occurrenceCountCache" maxElementsInMemory="2" eternal="false" overflowToDisk="false" />
</ehcache>


text:
using Stiletto;

namespace Example
{
    [Module(IsComplete = false)]
    class PumpModule
    {
        [Provides]
        public IPump GetPump(Thermosiphon thermosiphon)
        {
            return thermosiphon;
        }
    }
}