text:
require "test_helper"

# :stopdoc:
class Calculations::V3::StageRaceTest < ActiveSupport::TestCase
  test "#calculate!" do
    category = ::Category.find_or_create_by_normalized_name("Pro/1/2 Women")
    event = MultiDayEvent.create!(date: Time.zone.local(2018, 6, 29))
    Discipline.create!(name: "Road")

    calculation = Calculations::V3::Calculation.create!(
      disciplines: [Discipline[:road]],
      members_only: true,
      name: "Road BAR",
      points_for_place: [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1],
      weekday_events: false,
      year: 2018
    )
    calculation.categories << category

    race = event.races.create!(category: category)
    person = FactoryBot.create(:person)
    gc_result = race.results.create!(place: 4, person: person)

    child = event.children.create!(date: Time.zone.local(2018, 6, 29))
    race = child.races.create!(category: category)
    race.results.create!(place: 1, person: person)

    child = event.children.create!(date: Time.zone.local(2018, 6, 30), discipline: "Time Trial")
    race = child.races.create!(category: category)
    race.results.create!(place: 2, person: person)

    child = event.children.create!(date: Time.zone.local(2018, 7, 1))
    race = child.races.create!(category: category)
    race.results.create!(place: 3, person: person)

    child = event.children.create!(date: Time.zone.local(2018, 7, 1), discipline: "Criterium")
    race = child.races.create!(category: category)
    race.results.create!(place: 5, person: person)

    calculation.calculate!

    bar = calculation.reload.event

    assert_equal 1, bar.races.size, bar.races.map(&:name)
    results = bar.races.first.results
    assert_equal 1, results.size

    result = results.first
    assert_equal 3, result.sources.size
    assert_equal(2, result.sources.count { |s| s.rejection_reason.nil? }, result.sources.map(&:rejection_reason))
    source = result.sources.detect { |s| s.source_result == gc_result }
    assert source.rejected?
    assert_equal "calculated", source.rejection_reason
  end
end


text:
static_assert(sizeof(Message) == 6 * sizeof(uint32_t),
    "This code expects a six-word Message.");

static_assert(sizeof(ReceivedMessage) == 8 * sizeof(uint32_t),
    "This code expects an eight-word ReceivedMessage.");

namespace rt {

ReceivedMessage blocking_receive(unsigned k, uint32_t recv_map) {
  return ipc({
      Descriptor::zero()
        .with_receive_enabled(true)
        .with_source(k)
        .with_block(true)},
      0,
      recv_map);
}

}  // namespace rt

redpajama_set_name: RedPajamaGithub


text:
/** @file This file the information about the video player. */

/** Global reference to the video player
 * @global

 */
var oVP;

/**
 * Creates a video player pointing to files specified by the url
 * @constructor
*/
function JSVideo() {
  var frame_rate = 10;
  var fname_folder = main_media.GetFileInfo().GetImagePath()+"/";
  fname_folder =  fname_folder;

  // *******************************************
  // Private variables:
  // *******************************************

  // Struct with video data:
  var oVideoData = null;

  // HTML elements with video data:
  var aFrameImages = [];

  // Display width/height for video:
  var imageWidth;
  var imageHeight;

  // Current displayed video frame:
  var iFrameCtr = 0;

  // Last "time" for frame rate calculation:
  var iLastTime = -1;

  // Indicates whether the video has started playing:
  var bPlaying = false;

  // Indicates if the video is paused:
  var bPaused = false;

  // Indicates whether it was the user who paused the video
  var uPaused = false;

  // Indicates if the scroll button is clicked:
  var scroll_button_clicked = false;

  // *******************************************
  // Public methods:
  // *******************************************

  // Starting point of video player.  Load a video file from URL.
  this.getnumFrames = function (){
    if (oVideoData == null) return 0;
    else return oVideoData.frames;
  }
  this.getcurrentFrame = function (){
    return iFrameCtr;
  }

/** This function checks that the loaded frames are correct, stores them in the video structure
   * It prepares the polygon for scaling.
   * @param {int} frame - the position corresponding to the first frame in the set
   * @param {bool} first_time - boolean indicating whether it was the first frame load of the video
   * @param {json} response - json with the set of jpg frames being loaded
*/
this.loadFile = function(frame, first_time, isbackground, response) {

    if (first_time || frame == iFrameCtr) $('#oLoading').css('display',"block");

    var fncLoad = function() {
      try {
        console.timeEnd('Load video');
        oVideoData = eval("(" + response + ")");
        if (first_time){
          oVP.imageWidth = oVideoData.width;
          oVP.imageHeight = oVideoData.height;
          oVP.CreateVideoCanvas();
        }
        if (first_time || frame >= iFrameCtr) $('#oLoading').css('display',"none");
        oVP.GenerateFrames();
        if (first_time) oVP.GoToFrame(frame);
        oVP.seekChunkToDownload(frame);
        if (first_time || frame == iFrameCtr ) oVP.Play();
      }
      catch(e) {
         console.log("Error parsing video data ", e);
      }
    }
    var fncError = function() {
      console.log("Error loading video file");
    }
    if (response) fncLoad();
    else fncError();
  }
  this.ShowTemporalBar = function (){
    if (!select_anno) return;
    var selected_object_frames = LMgetObjectField(LM_xml, select_anno.anno_id, 't');
    var oTemporal = '

';
    $('#oScroll').append(oTemporal);
    $('#oTempBar').slider({
      range : true,
      min   : 1,
      max   : oVideoData.frames,
      values : [selected_object_frames[0], selected_object_frames[selected_object_frames.length-1]],
      slide : function (event, ui) {
        var userlab = LMgetObjectField(LM_xml, select_anno.anno_id, 'userlabeled');
        selected_object_frames = LMgetObjectField(LM_xml, select_anno.anno_id, 't');
        var init = ui.values[ 0 ];
        var end = ui.values[1];
        if (init > userlab[0] || end < userlab[userlab.length-1]) return false;
        var i1 = selected_object_frames.indexOf(init);
        var i2 = selected_object_frames.indexOf(end);
        console.log(init, end);
        var obj = $(LM_xml).children("annotation").children("object").eq(select_anno.anno_id);
        var pts_x = (obj.children("polygon").children('x').text()).split(';');
        var pts_y = (obj.children("polygon").children('y').text()).split(';');
        if (i1 == -1){
          while (selected_object_frames[0] > init){
            selected_object_frames.unshift(selected_object_frames[0]-1);
            pts_x.unshift(pts_x[0]);
            pts_y.unshift(pts_y[0]);
          }
          i1 = 0;
        }
        if (i2 == -1){
          while (selected_object_frames[selected_object_frames.length-1] < end){
            selected_object_frames.push(selected_object_frames[selected_object_frames.length-1]+1);
            pts_x.push(pts_x[pts_x.length-1]);
            pts_y.push(pts_y[pts_y.length-1]);
          }
          i2 = pts_x.length-1;
        }
        pts_x = pts_x.slice(i1,i2+1);
        pts_y = pts_y.slice(i1,i2+1);
        selected_object_frames = selected_object_frames.slice(i1, i2+1);
        console.log(selected_object_frames[0]);
        console.log(selected_object_frames[selected_object_frames.length-1]);
        LMsetObjectField(LM_xml, select_anno.anno_id, 'x', pts_x.join(';'));
        LMsetObjectField(LM_xml, select_anno.anno_id, 'y', pts_y.join(';'));
        LMsetObjectField(LM_xml, select_anno.anno_id, 't', selected_object_frames.join(','));
        if (ui.handle.nextSibling){ // left slider
          oVP.DisplayFrame(-init);
        }
        else {
          oVP.DisplayFrame(-end);
        }
      },
      stop: function(event, ui){
        oVP.DisplayFrame(oVP.getcurrentFrame());
      }
    });

    $("#oTempBar .ui-slider-handle").css("top", "-0.1em");
    $("#oTempBar .ui-slider-handle").css("height", "0.75em");
    $("#oTempBar .ui-slider-handle").css("width", "0.5em");

  }

  this.HideTemporalBar = function (){
    $('#oTempBar').remove();
  }
  this.HighLightFrames = function(framestotal, userlabeledframes){
    $('.oObjectshow').remove();
    var offset = 0;
    for (var typeframe = 0; typeframe < 2; typeframe++){

      var frames;
      var color;
      var zind;
      if (typeframe == 0){
        color = 'yellow';
        frames = framestotal;
        zind = 0;
      }
      else {
        color = 'red';
        frames = userlabeledframes;
        zind = 1;

      }
      if (frames.length == 0) return;
      var frame1 = frames[0];
      var frame2 = frames[0];
      var i = 1;

      while (i < frames.length){
        if (frames[i] == frames[i-1]+1){
          frame2 = frames[i];

        }
        else {
          var width = this.imageWidth*(frame2 - frame1)/(oVideoData.frames-1);
          if (width == 0) width = this.imageWidth/(oVideoData.frames-1);
          var posx = this.imageWidth*(frame1 - 1)/(oVideoData.frames-1);
          var oObjectShow = '
';
          offset += (width);
          $('#oControls').before(oObjectShow);
          frame1 = frame2 = frames[i];

        }
        i++;
      }
      var width = this.imageWidth*(frame2 - frame1)/(oVideoData.frames-1);
      if (width == 0) width = this.imageWidth/(oVideoData.frames-1);
      var posx = this.imageWidth*(frame1 - 1)/(oVideoData.frames-1);
      var oObjectShow = '
';
      offset += (width);
      $('#oControls').before(oObjectShow);
    }

  }
  this.ShowLoadedFramesForDebug = function (){
    $('.oObjectshow').remove();
    var offset = 0;
    var frames;
    var color;
    var zind;
    color = 'yellow';
    var framesLoaded = aFrameImages;
    zind = 0;
    if (framesLoaded.length == 0) return;
    var frame1 = 0;
    var frame2 = 0;
    var i = 1;
    console.log(framesLoaded.length);
    while (i < framesLoaded.length){
      if (framesLoaded[i] != null){
        frame2 = i;

      }
      else {
        var width = this.imageWidth*(frame2 - frame1)/(oVideoData.frames-1);
        if (frame2 > frame1){
          var posx = this.imageWidth*(frame1 - 1)/(oVideoData.frames-1);
          console.log(frame2, frame1);
          var oObjectShow = '
';
          offset += (width);
          console.log(oObjectShow);
          $('#oControls').before(oObjectShow);
        }

        frame1 = frame2 = i;

      }
      i++;
    }
    console.log(frame1, frame2)
    var width = this.imageWidth*(frame2 - frame1)/(oVideoData.frames-1);
    if (width > 0){
      var posx = this.imageWidth*(frame1 - 1)/(oVideoData.frames-1);
      var oObjectShow = '
';
      console.log(oObjectShow);
      $('#oControls').before(oObjectShow);
    }

  }

  this.UnHighLightFrames = function (){
    $('.oObjectshow').remove();
    var oObjectShow = '
';
    $('#oControls').before(oObjectShow);

  }
  /** This function creates the html elements (display, scroll bar and buttons) for the video player */
  // Create video canvas elements.
  this.CreateVideoCanvas = function() {

    // Create canvas:
    var oCanvas = '<svg id="canvas" width="' + this.imageWidth + '" height="' + this.imageHeight + '" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="position:absolute;left:8px;top:8px;z-index:-5;"></svg>
';
    $('#videoplayer').append(oCanvas);

    // Create "loading" message:
    var oLoading = '
Loading video file...
';
    $('#oCanvas').append(oLoading);

    // Create scroll bar:
    var oScroll = '

'
    var oLoad = '

'

    $('#videoplayer').append(oScroll);
    $('#oScroll').slider({
            range : "min",
            min   : 1,
            max   : this.imageWidth,
            value : 1,
            slide : function (event, ui) {
                if (wait_for_input || edit_popup_open) return false;
                pos = ui.value/oVP.imageWidth;
                iFrameCtr = Math.max(Math.floor(pos*(oVideoData.frames-1)),1);
                oVP.DisplayFrame(iFrameCtr);
            }

        });
    // Object show
    var oObjectShow = '
';
    $('#oScroll').after(oObjectShow);
    // Create loaded bar

    $('#oScroll').append(oLoad);
    $('#oLoadBar').slider({
            range : "min",
            min   : 1,
            max   : this.imageWidth,
            value : 1,

        });
    $("#oScroll .ui-slider-range").css("background", "red");
    $("#oLoadBar .ui-slider-range").css("background", "gray");
    $("#oLoadBar .ui-slider-handle").css("display", "none");
    $('#oLoadBar.ui-slider, #oLoadBar ui-slider-handler').off();
    // Create controls:
    var oControls = '
';
    $('#videoplayer').append(oControls);

    // Step beginning button:
    var oBtnStepBeginning = '';
    $('#oControls').append(oBtnStepBeginning);

    // Step backward button:
    var oBtnStepBackward = '';
    $('#oControls').append(oBtnStepBackward);

    // Pause button:
    var oBtnPause = '';
    $('#oControls').append(oBtnPause);

    // Step forward button:
    var oBtnStepForward = '';
    $('#oControls').append(oBtnStepForward);

    // Step end button:
    var oBtnStepEnd = '';
    $('#oControls').append(oBtnStepEnd);

    // var frameNumber = '
Frame number:
0

';
    // $('#oControls').append(frameNumber);

    // var goToFrameForm = '<form action="">Go to frame:<input type="text" id="frameinput" placeholder="Frame Number"></input><input type="button" onclick="oVP.GoToFrameButtonClicked()" value="Submit"></input></form>';
    //  $('#oControls').append(goToFrameForm);

  };

  this.poly_id = Array();
  this.X = Array();
  this.Y = Array();
  this.display_polygon = Array();
  /** This function is called when the user clicks the Go to frame button. It displays the frame indicated by the text field */
  this.GoToFrameButtonClicked = function(){
    var framevalue = Math.max(Math.min(this.getnumFrames()-1,$('#frameinput').val()),0);
    this.GoToFrame(parseInt(framevalue));
  }

  /** This function generates the html  elements that contain the loaded frames */
  this.GenerateFrames = function() {
    var shift = oVideoData.firstframe;
    for(var i = 0; i < oVideoData.data.video.length; i++) {
      if (aFrameImages[i+shift] == null){
        var oImage = '';
        aFrameImages[i+shift] = oImage;
      }
    }

  }
  /** This function displays the frame at position i, as well as the annotations corresponding to such frame.
   * If such frame is not available, it pauses the player, loads a chunk of frames starting from i and replays.
   * @param {int} i - the index of the frame to be displayed
  */
  this.DisplayFrame = function(i) {
    // Show frame:
    var slidervalues = [];
    var preview_mode = false;
    if (i < 0 && select_anno){
      slidervalues = $('#oTempBar').slider("option", "values");
      i *= -1;
      preview_mode = true;
    }
    $('#framenum').html(i);

    if (aFrameImages[i] == null){
      this.Pause();
      oVP.loadChunk(i, 4, false, false);
      //return;
    }
    if($('#im').length) {
      $('#im').replaceWith(aFrameImages[i]);
    }
    else {
      $('#oCanvas').append(aFrameImages[i]);
    }
    $('#myCanvas_bg').empty();

    var attr = 'fill="none" stroke="' + HashObjectColor(name) + '" stroke-width="4"';
    var scale = 1;

    // Plot polygons:
    var xml = LM_xml
    var N = $(xml).children("annotation").children("object").length;

    for(var it = 0; it < N; it++) {
        var del = parseInt($(LM_xml).children("annotation").children("object").eq(it).children("deleted").text());
        if (del) continue;
        var obj = $(xml).children("annotation").children("object").eq(it);

        // Get object name:

        // Get points:
        var anno_id = obj.children("id").text();
          var X = LMgetObjectField(LM_xml,it, 'x',i);
          var Y = LMgetObjectField(LM_xml,it, 'y', i);
           var obj_name = "foo";
           if (obj.children("name")) obj_name = obj.children("name").text();
           if (select_anno == null || (select_anno && select_anno.anno_id != anno_id)){
              if (X.length == 0) continue;
              var anoindex = main_canvas.GetAnnoIndex(it);
              polid = main_canvas.annotations[anoindex].DrawPolygon(scale, X,Y);
              $('#'+polid).attr('onmousedown','StartEditEvent('+ it + ',evt); return false;');
              $('#'+polid).attr('onmousemove','main_handler.CanvasMouseMove(evt,'+ it +'); return false;');
              $('#'+polid).attr('oncontextmenu','return false');
              $('#'+polid).css('cursor','pointer');
            }
            else if (adjust_event){
              $('#'+select_anno.polygon_id).parent().remove();
              $('#'+select_anno.polygon_id).remove();
              adjust_event.RemoveScalingPoints();
              adjust_event.RemoveControlPoints();
              adjust_event.RemoveCenterOfMass();
              if (X.length == 0) continue;

              if (!preview_mode && (i < slidervalues[0] || i > slidervalues[1])) continue;
              adjust_event.x  = X;
              adjust_event.y = Y;
              adjust_event.polygon_id = adjust_event.DrawPolygon(adjust_event.dom_attach,X,Y,obj_name,scale);
              select_anno.polygon_id = adjust_event.polygon_id;
              if (adjust_event.bounding_box) adjust_event.ShowScalingPoints();
              else adjust_event.ShowControlPoints();
              adjust_event.ShowCenterOfMass();
            }
        }
  }

  /** This function sets the player to frame 'frame'.
   * @param {int} frame - the index of the frame of interest
  */
  this.GoToFrame = function(frame){
    iFrameCtr = frame;
    this.DisplayFrame(iFrameCtr);
    this.UpdateScrollbar(iFrameCtr/oVideoData.frames);
  }

  this.ShowFirstFrame = function() {
    // We may need to update the selected object points
    this.DisplayFrame(0);
    this.UpdateScrollbar(0);
  }

  /** This function updates the position of the scroll bar.
    * @param {float} pos - float from 0 to 1 indicating the position of the scroll bar
  */
  this.UpdateScrollbar = function(pos) {
    $('#oScroll').slider('value',  pos*this.imageWidth);
  }

  /** This function updates the position of the load bar.
    * @param {float} pos - float from 0 to 1 indicating the position of the load bar
  */
  this.UpdateLoadbar = function(pos){
    //$('#oLoadBar').css('width',pos*this.imageWidth);
    $('#oLoadBar').slider('value',  pos*this.imageWidth);
  }

  /** This function sets the player to play. It can be called when a chunk of needed frames is loaded or when the user hits the play button.
    * @param {bool} buttonClicked - boolean indicating whether the user clicked the play button or the video was played because the chunks got loaded
  */
  this.Play = function(buttonClicked) {
    //if (active_canvas != REST_CANVAS) return;
    if (wait_for_input || edit_popup_open) return;
    if (buttonClicked) uPaused = false;
    else if (uPaused == true) return;
    if (aFrameImages[iFrameCtr] == null) return;
    if (bPlaying) {
      if (bPaused) bPaused = false;

      // Replace with pause button:
      $('#playpausebutton').attr('src','annotationTools/video/icons/video_pause.png');
      $('#playpausebutton').attr('title','Pause');
      $('#playpausebutton').attr('onclick','oVP.Pause(true);');

      if(iFrameCtr == (oVideoData.frames-1)) iFrameCtr = 0;

      return;
    }
    bPlaying = true;
    this.NextFrame();
  }

  /** Displays the next frame in a video file according to the video rate.
  */
  this.NextFrame = function() {
    if (!bPlaying) return;

    var iFrameRate = Math.round(1000 / oVideoData.rate);
    var iNow = new Date().getTime();
    var iLag = 0;
    if (!bPaused) {
      iFrameCtr++;
      if (iLastTime > -1) {
	var iDeltaTime = iNow - iLastTime;
	iLag = iDeltaTime - iFrameRate;
	while (iLag > iFrameRate) {
	  iFrameCtr++;
	  iLag -= iFrameRate;
	}
      }
      if (iLag < 0) iLag = 0;
      if (iFrameCtr >= oVideoData.frames) {
	iFrameCtr = oVideoData.frames-1;
	this.Pause();
      }

      this.DisplayFrame(iFrameCtr);
      this.UpdateScrollbar(iFrameCtr/oVideoData.frames);
    }
    iLastTime = iNow;
    setTimeout(function() {
	oVP.NextFrame();
      }, iFrameRate - iLag);
  }

  // Pause playback:
  this.Pause = function(buttonClicked) {
    if (buttonClicked) uPaused = true;
    bPaused = true;

    // Replace with play button:
    $('#playpausebutton').attr('src','./annotationTools/video/icons/video_play.png');
    $('#playpausebutton').attr('title','Play');
    $('#playpausebutton').attr('onclick','oVP.Play(true);');
  }

  /** This function forces to go to the next frame, regardless of frame rate.
  */
  this.StepForward = function() {
    if (wait_for_input || edit_popup_open) return;
    if(!bPaused) this.Pause();
    else {
      iFrameCtr++;
      if (iFrameCtr >= oVideoData.frames) {
	iFrameCtr = oVideoData.frames-1;
      }

      // Render next frame:
      this.DisplayFrame(iFrameCtr);
      this.UpdateScrollbar(iFrameCtr/oVideoData.frames);
    }
  }

  /** This function goes to the previous frame.
  */
  this.StepBackward = function() {
    if (wait_for_input || edit_popup_open) return;
    if(!bPaused) this.Pause();
    else {
      iFrameCtr--;
      if (iFrameCtr <= 0) {
	iFrameCtr = 1;
      }

      // Render next frame:s
      this.DisplayFrame(iFrameCtr);
      this.UpdateScrollbar(iFrameCtr/oVideoData.frames);
    }
  }

  /** This function goes to the start of the video.
  */
  this.StepBeginning = function() {
    if (wait_for_input || edit_popup_open) return;
    this.Pause();
    iFrameCtr = 1;

    if (select_anno){
      var userlab = LMgetObjectField(LM_xml,select_anno.anno_id, 'userlabeled');
      var obj_name = LMgetObjectField(LM_xml, select_anno.anno_id, 'name');
      if (userlab.length > 0 && userlab[0] > 1){
        var i = userlab[0];
        var X = LMgetObjectField(LM_xml,select_anno.anno_id, 'x',i);
        var Y = LMgetObjectField(LM_xml,select_anno.anno_id, 'y', i);
        $('#'+select_anno.polygon_id).parent().remove();
        $('#'+select_anno.polygon_id).remove();
        adjust_event.x  = X;
        adjust_event.y = Y;
        adjust_event.polygon_id = adjust_event.DrawPolygon(adjust_event.dom_attach,X,Y,obj_name,1);
        select_anno.polygon_id = adjust_event.polygon_id;

        adjust_event.RemoveScalingPoints();
        adjust_event.RemoveControlPoints();
        adjust_event.RemoveCenterOfMass();

        if (adjust_event.bounding_box) adjust_event.ShowScalingPoints();
        else adjust_event.ShowControlPoints();
        adjust_event.ShowCenterOfMass();
      }
    }

    // Render next frame:
    this.DisplayFrame(iFrameCtr);
    this.UpdateScrollbar(iFrameCtr/oVideoData.frames);
  }

  /** This function goes to the end of the video.
  */
  this.StepEnd = function() {
    if (wait_for_input || edit_popup_open) return;
    this.Pause();
    iFrameCtr = oVideoData.frames-1;

    if (select_anno){
      var userlab = LMgetObjectField(LM_xml,select_anno.anno_id, 'userlabeled');
      var obj_name = LMgetObjectField(LM_xml, select_anno.anno_id, 'name');
      if (userlab.length > 0 && userlab[userlab.length-1] < iFrameCtr){
        var i = userlab[userlab.length-1];
        var X = LMgetObjectField(LM_xml,select_anno.anno_id, 'x',i);
        var Y = LMgetObjectField(LM_xml,select_anno.anno_id, 'y', i);
        $('#'+select_anno.polygon_id).parent().remove();
        $('#'+select_anno.polygon_id).remove();
        adjust_event.x  = X;
        adjust_event.y = Y;
        adjust_event.polygon_id = adjust_event.DrawPolygon(adjust_event.dom_attach,X,Y,obj_name,1);
        select_anno.polygon_id = adjust_event.polygon_id;

        adjust_event.RemoveScalingPoints();
        adjust_event.RemoveControlPoints();
        adjust_event.RemoveCenterOfMass();

        if (adjust_event.bounding_box) adjust_event.ShowScalingPoints();
        else adjust_event.ShowControlPoints();
        adjust_event.ShowCenterOfMass();
      }
    }

    // Render next frame:
    this.DisplayFrame(iFrameCtr);
    this.UpdateScrollbar(iFrameCtr/oVideoData.frames);
  }
  /** This function looks for future frames that haven't been loaded yet and loads them into the player.
    * @param {int} frame - the frame index from which to start seeking
  */
  this.seekChunkToDownload = function (frame){
    while (aFrameImages[frame] != null) frame++;
    if (frame < oVideoData.frames && aFrameImages[frame] == null) this.loadChunk(frame, 3, false, true);
    else oVP.UpdateLoadbar(1);
  }
  /** This function loads a set of frames to the player.
    * @param {int} frame - the first frame to load
    * @param {int} duration - the duration of the chunk to be loaded
    * @param {bool} first_time - boolean indicating whether the function is called for the first time
  */
  this.loadChunk = function(frame, duration, first_time, isbackground){
    oVP = this;
    $.ajax({
           async: true,
           type: "POST",
           url: "./annotationTools/php/encode.php",
           data: {width: "640", height: "480", rate:frame_rate.toString(), input: fname_folder,frame: frame.toString(), duration: duration},
           success: function(response){
            last_frame = Math.min(Math.floor(frame + duration*frame_rate), oVP.getnumFrames());
            oVP.loadFile(frame, first_time, isbackground, response);
            while (aFrameImages[last_frame] != null) last_frame++;
            if (oVP.getnumFrames() != 0 && oVP.getcurrentFrame() <= last_frame) oVP.UpdateLoadbar(last_frame/oVP.getnumFrames());

          }
    });
  }
}


text:
# jsprim: utilities for primitive JavaScript types

This module provides miscellaneous facilities for working with strings,
numbers, dates, and objects and arrays of these basic types.

### deepCopy(obj)

Creates a deep copy of a primitive type, object, or array of primitive types.

### deepEqual(obj1, obj2)

Returns whether two objects are equal.

### isEmpty(obj)

Returns true if the given object has no properties and false otherwise.  This
is O(1) (unlike `Object.keys(obj).length === 0`, which is O(N)).

### hasKey(obj, key)

Returns true if the given object has an enumerable, non-inherited property
called `key`.  [For information on enumerability and ownership of properties, see
the MDN
documentation.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)

### forEachKey(obj, callback)

Like Array.forEach, but iterates enumerable, owned properties of an object
rather than elements of an array.  Equivalent to:

    for (var key in obj) {
            if (Object.prototype.hasOwnProperty.call(obj, key)) {
                    callback(key, obj[key]);
            }
    }

### flattenObject(obj, depth)

Flattens an object up to a given level of nesting, returning an array of arrays
of length "depth + 1", where the first "depth" elements correspond to flattened
columns and the last element contains the remaining object .  For example:

    flattenObject({
        'I': {
            'A': {
                'i': {
                    'datum1': [ 1, 2 ],
                    'datum2': [ 3, 4 ]
                },
                'ii': {
                    'datum1': [ 3, 4 ]
                }
            },
            'B': {
                'i': {
                    'datum1': [ 5, 6 ]
                },
                'ii': {
                    'datum1': [ 7, 8 ],
                    'datum2': [ 3, 4 ],
                },
                'iii': {
                }
            }
        },
        'II': {
            'A': {
                'i': {
                    'datum1': [ 1, 2 ],
                    'datum2': [ 3, 4 ]
                }
            }
        }
    }, 3)

becomes:

    [
        [ 'I',  'A', 'i',   { 'datum1': [ 1, 2 ], 'datum2': [ 3, 4 ] } ],
        [ 'I',  'A', 'ii',  { 'datum1': [ 3, 4 ] } ],
        [ 'I',  'B', 'i',   { 'datum1': [ 5, 6 ] } ],
        [ 'I',  'B', 'ii',  { 'datum1': [ 7, 8 ], 'datum2': [ 3, 4 ] } ],
        [ 'I',  'B', 'iii', {} ],
        [ 'II', 'A', 'i',   { 'datum1': [ 1, 2 ], 'datum2': [ 3, 4 ] } ]
    ]

This function is strict: "depth" must be a non-negative integer and "obj" must
be a non-null object with at least "depth" levels of nesting under all keys.

### flattenIter(obj, depth, func)

This is similar to `flattenObject` except that instead of returning an array,
this function invokes `func(entry)` for each `entry` in the array that
`flattenObject` would return.  `flattenIter(obj, depth, func)` is logically
equivalent to `flattenObject(obj, depth).forEach(func)`.  Importantly, this
version never constructs the full array.  Its memory usage is O(depth) rather
than O(n) (where `n` is the number of flattened elements).

There's another difference between `flattenObject` and `flattenIter` that's
related to the special case where `depth === 0`.  In this case, `flattenObject`
omits the array wrapping `obj` (which is regrettable).

### pluck(obj, key)

Fetch nested property "key" from object "obj", traversing objects as needed.
For example, `pluck(obj, "foo.bar.baz")` is roughly equivalent to
`obj.foo.bar.baz`, except that:

1. If traversal fails, the resulting value is undefined, and no error is
   thrown.  For example, `pluck({}, "foo.bar")` is just undefined.
2. If "obj" has property "key" directly (without traversing), the
   corresponding property is returned.  For example,
   `pluck({ 'foo.bar': 1 }, 'foo.bar')` is 1, not undefined.  This is also
   true recursively, so `pluck({ 'a': { 'foo.bar': 1 } }, 'a.foo.bar')` is
   also 1, not undefined.

### randElt(array)

Returns an element from "array" selected uniformly at random.  If "array" is
empty, throws an Error.

### startsWith(str, prefix)

Returns true if the given string starts with the given prefix and false
otherwise.

### endsWith(str, suffix)

Returns true if the given string ends with the given suffix and false
otherwise.

### parseInteger(str, options)

Parses the contents of `str` (a string) as an integer. On success, the integer
value is returned (as a number). On failure, an error is **returned** describing
why parsing failed.

By default, leading and trailing whitespace characters are not allowed, nor are
trailing characters that are not part of the numeric representation. This
behaviour can be toggled by using the options below. The empty string (`''`) is
not considered valid input. If the return value cannot be precisely represented
as a number (i.e., is smaller than `Number.MIN_SAFE_INTEGER` or larger than
`Number.MAX_SAFE_INTEGER`), an error is returned. Additionally, the string
`'-0'` will be parsed as the integer `0`, instead of as the IEEE floating point
value `-0`.

This function accepts both upper and lowercase characters for digits, similar to
`parseInt()`, `Number()`, and [strtol(3C)](https://illumos.org/man/3C/strtol).

The following may be specified in `options`:

Option             | Type    | Default | Meaning
------------------ | ------- | ------- | ---------------------------
base               | number  | 10      | numeric base (radix) to use, in the range 2 to 36
allowSign          | boolean | true    | whether to interpret any leading `+` (positive) and `-` (negative) characters
allowImprecise     | boolean | false   | whether to accept values that may have lost precision (past `MAX_SAFE_INTEGER` or below `MIN_SAFE_INTEGER`)
allowPrefix        | boolean | false   | whether to interpret the prefixes `0b` (base 2), `0o` (base 8), `0t` (base 10), or `0x` (base 16)
allowTrailing      | boolean | false   | whether to ignore trailing characters
trimWhitespace     | boolean | false   | whether to trim any leading or trailing whitespace/line terminators
leadingZeroIsOctal | boolean | false   | whether a leading zero indicates octal

Note that if `base` is unspecified, and `allowPrefix` or `leadingZeroIsOctal`
are, then the leading characters can change the default base from 10. If `base`
is explicitly specified and `allowPrefix` is true, then the prefix will only be
accepted if it matches the specified base. `base` and `leadingZeroIsOctal`
cannot be used together.

**Context:** It's tricky to parse integers with JavaScript's built-in facilities
for several reasons:

- `parseInt()` and `Number()` by default allow the base to be specified in the
  input string by a prefix (e.g., `0x` for hex).
- `parseInt()` allows trailing nonnumeric characters.
- `Number(str)` returns 0 when `str` is the empty string (`''`).
- Both functions return incorrect values when the input string represents a
  valid integer outside the range of integers that can be represented precisely.
  Specifically, `parseInt('9007199254740993')` returns 9007199254740992.
- Both functions always accept `-` and `+` signs before the digit.
- Some older JavaScript engines always interpret a leading 0 as indicating
  octal, which can be surprising when parsing input from users who expect a
  leading zero to be insignificant.

While each of these may be desirable in some contexts, there are also times when
none of them are wanted. `parseInteger()` grants greater control over what
input's permissible.

### iso8601(date)

Converts a Date object to an ISO8601 date string of the form
"YYYY-MM-DDTHH:MM:SS.sssZ".  This format is not customizable.

### parseDateTime(str)

Parses a date expressed as a string, as either a number of milliseconds since
the epoch or any string format that Date accepts, giving preference to the
former where these two sets overlap (e.g., strings containing small numbers).

### hrtimeDiff(timeA, timeB)

Given two hrtime readings (as from Node's `process.hrtime()`), where timeA is
later than timeB, compute the difference and return that as an hrtime.  It is
illegal to invoke this for a pair of times where timeB is newer than timeA.

### hrtimeAdd(timeA, timeB)

Add two hrtime intervals (as from Node's `process.hrtime()`), returning a new
hrtime interval array.  This function does not modify either input argument.

### hrtimeAccum(timeA, timeB)

Add two hrtime intervals (as from Node's `process.hrtime()`), storing the
result in `timeA`.  This function overwrites (and returns) the first argument
passed in.

### hrtimeNanosec(timeA), hrtimeMicrosec(timeA), hrtimeMillisec(timeA)

This suite of functions converts a hrtime interval (as from Node's
`process.hrtime()`) into a scalar number of nanoseconds, microseconds or
milliseconds.  Results are truncated, as with `Math.floor()`.

### validateJsonObject(schema, object)

Uses JSON validation (via JSV) to validate the given object against the given
schema.  On success, returns null.  On failure, *returns* (does not throw) a
useful Error object.

### extraProperties(object, allowed)

Check an object for unexpected properties.  Accepts the object to check, and an
array of allowed property name strings.  If extra properties are detected, an
array of extra property names is returned.  If no properties other than those
in the allowed list are present on the object, the returned array will be of
zero length.

### mergeObjects(provided, overrides, defaults)

Merge properties from objects "provided", "overrides", and "defaults".  The
intended use case is for functions that accept named arguments in an "args"
object, but want to provide some default values and override other values.  In
that case, "provided" is what the caller specified, "overrides" are what the
function wants to override, and "defaults" contains default values.

The function starts with the values in "defaults", overrides them with the
values in "provided", and then overrides those with the values in "overrides".
For convenience, any of these objects may be falsey, in which case they will be
ignored.  The input objects are never modified, but properties in the returned
object are not deep-copied.

For example:

    mergeObjects(undefined, { 'objectMode': true }, { 'highWaterMark': 0 })

returns:

    { 'objectMode': true, 'highWaterMark': 0 }

For another example:

    mergeObjects(
        { 'highWaterMark': 16, 'objectMode': 7 }, /* from caller */
        { 'objectMode': true },                   /* overrides */
        { 'highWaterMark': 0 });                  /* default */

returns:

    { 'objectMode': true, 'highWaterMark': 16 }

# Contributing

Code should be "make check" clean.  This target assumes that
[jsl](http://github.com/davepacheco/javascriptlint) and
[jsstyle](http://github.com/davepacheco/jsstyle) are on your path.

New tests should generally accompany new functions and bug fixes.  The tests
should pass cleanly (run tests/basic.js).


text:
#include "testApp.h"

//--------------------------------------------------------------
void testApp::setup(){

    ofSetFrameRate(30);
    ofSetVerticalSync(true);

	camWidth 		= CAM_WIDTH;	// try to grab at this size.
	camHeight 		= CAM_HEIGHT;

	//ofSetLogLevel(OF_LOG_VERBOSE);

	vidGrabber.listVideoDevices();											// all list... methods also return a vector<string> of devices/codecs
//	vidGrabber.listAudioDevices();

//	vidGrabber.setVideoDeviceID("Built-in iSight");							// can set deviceID's by string
//    vidGrabber.setVideoDeviceID("Logitech Camera #2");
    vidGrabber.setVideoDeviceID(0); //0 is first, iSight is always last, so this is safe...
	vidGrabber.setAudioDeviceID("Built-in Microphone");

	vidGrabber.listVideoCodecs();
//	vidGrabber.listAudioCodecs();

	//vidGrabber.setVideoCodec("QTCompressionOptions240SizeH264Video");		// default is JPEG
	//vidGrabber.setVideoCodec("QTCompressionOptionsHD720SizeH264Video");
    //vidGrabber.setVideoCodec("QTCompressionOptionsSD480SizeH264Video");
    //vidGrabber.setVideoCodec("QTCompressionOptionsLosslessAnimationVideo");
    //vidGrabber.setAudioCodec("QTCompressionOptionsVoiceQualityAACAudio");	// default is High Quality AAC

	//vidGrabber.setUseAudio(true);						// audio recording defaults to false so you need to set this
														// true if you want audio with your video. Need to do it BEFORE
														// initializing the grabber.

    //no audio, max performance, audio is useful for now...

	vidGrabber.initGrabber(camWidth, camHeight);

	//vidGrabber.initGrabberWithoutPreview();			// this can be used to create a recorder with no preview image
                                                        // or texture etc remember NOT to call update or draw!!!

	//vidGrabber.initRecording();							// call this to init recording output
														// see keyPressed below for start/stop commands

	videoInverted 	= new unsigned char[camWidth*camHeight*3];
	videoTexture.allocate(camWidth, camHeight, GL_RGB);

}

//--------------------------------------------------------------
void testApp::update(){

	ofBackground(100,100,100);

	vidGrabber.update();

	if (vidGrabber.isFrameNew()){
		int totalPixels = camWidth*camHeight*3;
		unsigned char * pixels = vidGrabber.getPixels();
		for (int i = 0; i < totalPixels; i++){
			videoInverted[i] = 255 - pixels[i];
		}
		videoTexture.loadData(videoInverted, camWidth,camHeight, GL_RGB);
	}

}

//--------------------------------------------------------------
void testApp::draw(){
	ofSetColor(255,255,255);
	vidGrabber.draw(0,0);
	videoTexture.draw(camWidth,0,camWidth,camHeight);

	ofSetColor(0,255,0);
	string msg;
	msg += "Press the space bar to toggle recording!\n";
	msg += (string)(vidGrabber.isRecording() ? "RECORDING" : "NOT RECORDING");
	ofDrawBitmapString(msg, 20, ofGetHeight()-40);

    float frameRate = ofGetFrameRate();

    ostringstream s;
    s << "Framerate " << frameRate;

    ofDrawBitmapString(s.str(), 20, ofGetHeight() - 80);
}

//--------------------------------------------------------------
void testApp::keyPressed  (int key){
	switch (key) {
		case ' ':
			if (!vidGrabber.isRecording()) {
				vidGrabber.startRecording("output.mov"); // dumps to data folder
			} else vidGrabber.stopRecording();
			break;
        case 's':
            vidGrabber.videoSettings();
            break;
		default:
			break;
	}
}

//--------------------------------------------------------------
void testApp::keyReleased(int key){

}

//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){

}

//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button){

}

//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button){

}

//--------------------------------------------------------------
void testApp::windowResized(int w, int h){

}


text:
  <title>JamesCube | Liar Liar</title>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

  <link rel="stylesheet" href="../../net/flipclock/flipclock.css">
  <link rel="stylesheet" href="../../stylesheets/liarliar.css">
  <link href="https://fonts.googleapis.com/css?family=Cabin+Sketch|Oswald" rel="stylesheet">

JAMESCUBE

Once prompted with a question, you must use your device to enter a bluff to fool your opponent
      into thinking it is true

The game consists of 3 rounds. Each round you get scored based on the following criteria

          Each player you fool
          Finding the truth
          For selecting our lie

          Round 1
          +500 Points
          +1000 Points
          -250 Points

          Round 2
          +1000 Points
          +2000 Points
          -500 Points

          Round 3
          +1500 Points
          +3000 Points
          -750 Points

    <button type="submit" id="gameStartBtn" class="btn btn-success btn-lg" style="margin: auto">
      Understand? Let's Play!

    </button>

        Player
        Round Score
        Total Score

      <button type="submit" id="gameEndBtn" class="btn btn-danger btn-lg btn-block" style="margin: auto">

        Return to lobby
      </button>

      <button type="submit" id="roundBtn" class="btn btn-success btn-lg btn-block" style="margin: auto">
        Round 2

      </button>


text:
title: "This Shirt Has a Lot of Lines"
excerpt: "PaperFaces portrait of @chetyeary drawn with Paper for iOS on an iPad."
image:
  path: &image /assets/images/paperfaces-chetyeary-2-twitter.jpg
  feature: *image
  thumbnail: /assets/images/paperfaces-chetyeary-2-twitter-150.jpg
categories: [paperfaces]
tags: [portrait, illustration, Paper for iOS, black and white, beard]
---

PaperFaces portrait commission of [@chetyeary](https://twitter.com/chetyeary).

{% include_cached boilerplate/paperfaces-2.md %}

{% figure caption:"Work in progress screen captures Made with Paper." class:"gallery-3-col" %}
[![Work in process screenshot](/assets/images/paperfaces-chetyeary-2-process-1-600.jpg)](/assets/images/paperfaces-chetyeary-2-process-1-lg.jpg) [![Work in process screenshot](/assets/images/paperfaces-chetyeary-2-process-2-600.jpg)](/assets/images/paperfaces-chetyeary-2-process-2-lg.jpg) [![Work in process screenshot](/assets/images/paperfaces-chetyeary-2-process-3-600.jpg)](/assets/images/paperfaces-chetyeary-2-process-3-lg.jpg) [![Work in process screenshot](/assets/images/paperfaces-chetyeary-2-process-4-600.jpg)](/assets/images/paperfaces-chetyeary-2-process-4-lg.jpg) [![Work in process screenshot](/assets/images/paperfaces-chetyeary-2-process-5-600.jpg)](/assets/images/paperfaces-chetyeary-2-process-5-lg.jpg)
{% endfigure %}


text:
layout: layout
section: childcare
permalink: /childcare/
title: SRCCON 2019 — Childcare
---

We offer free childcare for the duration of the SRCCON program and welcome families of all sizes.

# Childcare and Caretaking

We are offering free childcare throughout the full SRCCON schedule (including Thursday evening). Our providers are the wonderful [KiddieCorp](https://www.kiddiecorp.com/)  team, whom we welcome back for their fifth year at SRCCON.

For the first time this year, we're also offering one scholarship of $500 for caretaking-related costs. (Either to bring your loved ones to Minneapolis, or help care for them back home while you're at the conference.) There is a question on the call for participation form to apply for this scholarship.

## Our Care Providers

Staff-to-child ratios range from 1:2 for children 6-11 months to 1:7 for children aged 6-12 years, and KiddieCorp will work with SRCCON organizers to handle registration and logistics so your kid(s) can have a great time while you're conferencing. All caregivers act as employees of KiddieCorp (not contractors) and are recruited from local licensed daycare centers, elementary schools, preschools, and collegiate departments of early childhood education.

Two of our own staff members have had their young children happily in KiddieCorp's care during prior SRCCONS, and we were all impressed by the thoughtfulness they brought to every aspect of their services.

## Logistics

Childcare will take place at the conference venue. You can [learn more about KiddieCorp's staffing](https://www.kiddiecorp.com/staffselect.html) and [security procedures](https://www.kiddiecorp.com/security.html).

## Register has closed

The registration deadline for childcare this year has passed, but if you find yourself with last-minute childcare needs [let us know](srccon@opennews.org) and we'll see if we can help.


text:
from indico.core.settings.converters import EnumConverter, ModelListConverter
from indico.modules.users import UserSettingsProxy
from indico.util.enum import RichIntEnum
from indico.util.i18n import _

class RoomEmailMode(RichIntEnum):
    __titles__ = (_('None'), _('Rooms I own'), _('Rooms I manage'), _('Rooms I own or manage'))
    none = 0
    owned = 1
    managed = 2
    all = 3

rb_user_settings = UserSettingsProxy('roombooking', {
    'email_mode': RoomEmailMode.all,
    'email_blacklist': [],
}, converters={
    'email_mode': EnumConverter(RoomEmailMode),
    'email_blacklist': ModelListConverter('Room'),
})


text:
<!doctype html>

      <meta charset="utf-8">
      <meta name="keywords" content="">
      <meta name="description" content="">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <link rel="shortcut icon" type="img/png" href="favicon.png">
      <link rel="stylesheet" type="text/css" href="./css/bootstrap.min.css">
	<link rel="stylesheet" type="text/css" href="./css/style.css">
      <link rel="stylesheet" type="text/css" href="./css/animate.min.css">
      <link rel="stylesheet" type="text/css" href="./css/font-awesome.min.css">
      <link rel="stylesheet" type="text/css" href="./css/feather.min.css">
      <link href='https://fonts.googleapis.com/css?family=Montserrat&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
      <link href='https://fonts.googleapis.com/css?family=Lato:100,300,400,700,900&subset=latin,latin-ext' rel='stylesheet' type='text/css'>

      <title>Listings</title>

Help Is On The Way.<button id="nav-toggle" type="button" class="ui-navbar-toggle navbar-toggle" data-toggle="collapse" data-target=".navbar-1">Toggle navigation</button>

Home

Show Listings

I Have a Need

Log Out

Categories

Baby & Toddlers

Baby & kids clothes, toys and other related stuff

Books, DVDs & Games

Kids Books, Movies, games and consoles

Clothes & Footware

Kids and Adult’s clothes and footware.

Computers

Computers, software and learning material

Furniture

Furniture and electric goods

Musical instruments

Musical instruments and learning material

Sport goods

Sports items and sports clothes & shoes

Household Help

All household help - whatever help you want!

About

                     The teamContact us

Apps coming soon to

                     iPhoneAndroid

Follow Us

                     TwitterFacebook

Company

                     Terms of usePrivacy


text:
const { dest, src } = require('gulp')
const collect = require('gulp-rev-collector')
const config = require('../../config').revision.collect

// Task
function revisionCollect () {
  return src(config.src)
  .pipe(collect())
  .pipe(dest(config.dest))
}

module.exports = revisionCollect


text:
module Properties where

import Data.Either

import Lambda
import BruijnTerm
import FreeEnvironment
import TopologicalSort
import Type

-- TODO rename/remove
normalised :: (Eq i , Eq j) => BruijnTerm i j -> Bool
normalised t = fmap lam2Bruijn (bruijn2Lam t) == return ( return t)

-- TODO rename closed
welFormd :: BruijnTerm i j -> Bool
welFormd t0 = go t0 0
    where go (Lambda _ _ t) dept = go t (dept + 1)
          go (Appl t1 t2) dept = go t1 dept && go t2 dept
          go (Var _ (Bound i) ) dept = i < dept && i >= 0
          go Val {} _ = True
          go (Let _ defs term) dept = all (welFormdDef (dept + length defs)) defs  && go term (dept +length defs)
          welFormdDef i (Def _ _ t)  = go t i

-- TODO uneeded check. Rename
welFormdType :: Type -> Bool
welFormdType = go
    where go (TAppl t1 t2) = go t1 && go t2
          go (TVar (Free i) ()) = i >= 0
          go (TPoly(Free i) ()) = i >= 0
          go TVal {} = True

size :: LamTerm a i j -> Int
size (Lambda _ _ e ) = size e + 1
size (Appl e1 e2) = size e1 + size e2 + 1
size (Let _ defs term) =sum (map (size.implementation) defs) + size term + 1
size _ = 1

isCirculair :: BruijnTerm i i -> Bool
isCirculair = isLeft. sortTerm


text:
CREATE OR REPLACE VIEW AMB_OBJECT_TYPE
AS
  SELECT 'Table' AS DISPLAY_NAME, 'TABLE' AS CODE, 1 AS SORT_KEY FROM dual
  UNION
  SELECT 'View', 'VIEW', 2 FROM dual
  UNION
  SELECT 'Index', 'INDEX', 3 FROM dual
  UNION
  SELECT 'Sequence', 'SEQUENCE', 4 FROM dual
  UNION
  SELECT 'Type', 'TYPE', 5 FROM dual
  UNION
  SELECT 'Type', 'TYPE BODY', 6 FROM dual
  UNION
  SELECT 'Package', 'PACKAGE', 7 FROM dual
  UNION
  SELECT 'Package', 'PACKAGE BODY', 8 FROM dual
  UNION
  SELECT 'Procedure', 'PROCEDURE', 9 FROM dual
  UNION
  SELECT 'Function', 'FUNCTION', 10 FROM dual
  UNION
  SELECT 'Trigger', 'TRIGGER', 11 FROM dual
  UNION
  SELECT 'Database Link', 'DATABASE LINK', 12 FROM dual
  UNION
  SELECT 'Materialized View', 'MATERIALIZED VIEW', 13 FROM dual
  UNION
  SELECT 'Synonym', 'SYNONYM', 14 FROM dual
/

CREATE OR REPLACE VIEW AMB_OBJ_LIST_VW
              AS
  SELECT NULL AS OBJECT_ID,
    AMB_OBJECT.VERSION_ID,
    AMB_OBJECT.TYPE AS NAME,
    NULL            AS TYPE,
    NULL            AS "REFERENCE",
    NULL            AS PARENT,
    AMB_OBJECT.TYPE AS SID
  FROM AMB_OBJECT
  GROUP BY AMB_OBJECT.VERSION_ID,
    AMB_OBJECT.TYPE
  UNION
  SELECT AMB_OBJECT.ID,
    AMB_OBJECT.VERSION_ID,
    AMB_OBJECT.NAME,
    AMB_OBJECT.TYPE,
    AMB_OBJECT."REFERENCE",
    AMB_OBJECT.TYPE AS PARENT,
    NULL            AS SID
  FROM AMB_OBJECT
/
CREATE OR REPLACE VIEW AMB_PROJ_VERSION_VW
AS
  SELECT AMB_VERSION.PROJECT_ID,
    AMB_PROJECT.NAME AS PROJECT_NAME,
    AMB_VERSION.ID   AS VERSION_ID,
    AMB_VERSION.APP_ID,
    AMB_VERSION.APP_NAME,
    AMB_VERSION.WORKSPACE,
    AMB_VERSION.ENVIRONMENT,
    AMB_VERSION.EDITION,
    AMB_VERSION.ACTIVE,
    AMB_VERSION.IS_BASE,
    AMB_PROJECT.DESCRIPTION AS PROJECT_DESC
  FROM AMB_PROJECT
  INNER JOIN AMB_VERSION
  ON AMB_PROJECT.ID = AMB_VERSION.PROJECT_ID
/

CREATE OR REPLACE VIEW AMB_IMPORT_VW
AS
  SELECT AMB_BEIL_LIST.ID,
    AMB_BEIL_LIST.VERSION_ID,
    AMB_BEIL_LIST.NAME,
    AMB_BEIL_LIST.TYPE,
    AMB_BEIL_LIST.NEED_IMPORT,
    AMB_BEIL_LIST.CONTENT,
    AMB_BEIL_LIST.CREATE_DATE,
    AMB_BEIL_LIST.CREATE_BY,
    AMB_BEIL_LIST.DESCRIPTION,
    AMB_OBJECT.ID AS ALREADY_ID,
    CASE
      WHEN AMB_OBJECT.ID IS NOT NULL
      THEN 'Y'
      ELSE 'N'
    END IS_ALREADY_EXIST,
    CASE
      WHEN AMB_OBJECT.ID IS NOT NULL
      THEN 'UPDATE'
      ELSE 'INSERT'
    END AS ACTION,
    AMB_OBJECT_TYPE.SORT_KEY,
    AMB_BEIL_LIST.IS_SUCCESS,
    AMB_BEIL_LIST.FAILED_MSG
  FROM AMB_BEIL_LIST
  LEFT JOIN AMB_OBJECT
  ON AMB_BEIL_LIST.VERSION_ID = AMB_OBJECT.VERSION_ID
  AND AMB_BEIL_LIST.NAME      = AMB_OBJECT.NAME
  AND AMB_BEIL_LIST.TYPE      = AMB_OBJECT.TYPE
  LEFT JOIN AMB_OBJECT_TYPE
  ON AMB_BEIL_LIST.TYPE = AMB_OBJECT_TYPE.CODE
/

CREATE OR REPLACE VIEW AMB_BUILD_VW
AS
  SELECT abl.ID,
    abl.VERSION_ID,
    abl.NAME,
    abl.TYPE,
    abl.CONTENT,
    abl.NEED_BUILD,
    CASE
      WHEN uo.OBJECT_ID IS NOT NULL
      THEN 'Y'
      ELSE 'N'
    END AS IS_ALREADY_EXIST,
    CASE
      WHEN uo.STATUS = 'VALID'
      THEN 'Y'
      WHEN uo.STATUS = 'INVALID'
      THEN 'N'
      ELSE ''
    END AS IS_VALID,
    CASE
      WHEN uo.OBJECT_ID IS NOT NULL
      THEN
        CASE
          WHEN uo.EDITIONABLE = 'Y'
          THEN 'REPLACE'
          ELSE 'MANUAL'
        END
      ELSE 'NEW'
    END AS ACTION,
    AMB_OBJECT_TYPE.SORT_KEY,
    abl.IS_SUCCESS,
    abl.FAILED_MSG
  FROM AMB_BEIL_LIST abl
  LEFT JOIN USER_OBJECTS uo
  ON abl.NAME  = uo.OBJECT_NAME
  AND abl.TYPE = uo.OBJECT_TYPE
  LEFT JOIN AMB_OBJECT_TYPE
  ON abl.TYPE = AMB_OBJECT_TYPE.CODE
/
CREATE OR REPLACE VIEW AMB_LOAD_VW
AS
  SELECT AMB_BEIL_LIST.ID,
    AMB_BEIL_LIST.VERSION_ID,
    AMB_BEIL_LIST.NAME,
    AMB_BEIL_LIST.TYPE,
    AMB_BEIL_LIST.NEED_LOAD,
    CASE
      WHEN AMB_OBJECT.ID IS NOT NULL
      THEN USER_OBJECTS.STATUS
        || '/UPDATE'
      ELSE USER_OBJECTS.STATUS
        || '/INSERT'
    END AS STATUS_ACTION,
    CASE
      WHEN AMB_OBJECT.ID IS NOT NULL
      THEN 'UPDATE'
      ELSE 'INSERT'
    END AS ACTION,
    AMB_OBJECT_TYPE.SORT_KEY,
    AMB_BEIL_LIST.CONTENT,
    AMB_OBJECT.CREATE_DATE,
    AMB_OBJECT.CREATE_BY,
    AMB_OBJECT.DESCRIPTION,
    AMB_BEIL_LIST.IS_SUCCESS,
    AMB_BEIL_LIST.FAILED_MSG
  FROM AMB_BEIL_LIST
  LEFT JOIN AMB_OBJECT_TYPE
  ON AMB_BEIL_LIST.TYPE = AMB_OBJECT_TYPE.CODE
  LEFT JOIN AMB_OBJECT
  ON AMB_BEIL_LIST.VERSION_ID = AMB_OBJECT.VERSION_ID
  AND AMB_BEIL_LIST.NAME      = AMB_OBJECT.NAME
  AND AMB_BEIL_LIST.TYPE      = AMB_OBJECT.TYPE
  LEFT JOIN USER_OBJECTS
  ON AMB_BEIL_LIST.NAME  = USER_OBJECTS.OBJECT_NAME
  AND AMB_BEIL_LIST.TYPE = USER_OBJECTS.OBJECT_TYPE
/

CREATE OR REPLACE VIEW AMB_EXPORT_VW
AS
  SELECT ael.ID,
    ael.VERSION_ID,
    ael.NAME,
    ael.TYPE,
    ael.NEED_EXPORT,
    ael.CONTENT AS CONTENT,
    AMB_OBJECT.CREATE_DATE,
    AMB_OBJECT.CREATE_BY,
    AMB_OBJECT.DESCRIPTION,
    aot.SORT_KEY,
    ael.IS_SUCCESS
  FROM AMB_BEIL_LIST ael
  LEFT JOIN AMB_OBJECT
  ON ael.ID = AMB_OBJECT.ID
  LEFT JOIN AMB_OBJECT_TYPE aot
  ON ael.TYPE = aot.CODE
/


text:
/**
 * Created by nkmathew on 08/08/2016.
 */

var PREV_TEMPLATE = $("#logbook-preview-template").html();

// Displays all the entries for a certain week
function displayWeek(week) {
    $('#entry-list').data('week', week);
    var url = '/site/preview-logbook?week=' + week;
    $("#entry-list").spin({color: 'black'});
    $.getJSON(url, function (json) {
        entryDays = [];
        startDate = json.start;
        $.each(json.entryList, function (index, val) {
            day = moment(val.entry_for).day();
            entryDays[day] = val;
        });
        entries = '';
        for (i = 1; i < 6; i++) {
            val = entryDays[i];
            if (val != undefined) {
                val.entry_for = moment(val.entry_for).format(FMT);
                var html      = PREV_TEMPLATE(val);
                entries += html
            } else {
               var html = PREV_TEMPLATE({
                   entry_class: 'missing-entry',
                   entry_for: moment(startDate).add(i-1, 'day').format(FMT),
                   entry: 'No Entry Found!',
                   center_class: 'centered-text',
                   entry_text_class: 'entry-text-centered'
               });
               entries += html;
            }
        }
        $("#entry-list").spin(false);
        $('#entry-list').html(entries);
        $('#week-number').html('Week ' + json.week);
    });
}

function nextWeek() {
    curr = $('#entry-list').data('week');
    displayWeek(++curr);
}

function prevWeek() {
    curr = $('#entry-list').data('week');
    displayWeek(--curr);
}

$(document).ready(function () {
    PREV_TEMPLATE = Handlebars.compile(PREV_TEMPLATE);
    displayWeek(-1);
});


text:
package org.zalando.intellij.swagger.completion.field.model.common;

import static org.zalando.intellij.swagger.file.FileConstants.CARET;

import org.apache.commons.lang.StringUtils;

public class StringField extends Field {

  public StringField(final String name, final boolean required) {
    super(name, required);
  }

  public StringField(final String name) {
    super(name, false);
  }

  @Override
  public String getJsonPlaceholderSuffix(final int indentation) {
    return ": \"" + CARET + "\"";
  }

  @Override
  public String getYamlPlaceholderSuffix(final int indentation) {
    return ": " + CARET;
  }

  @Override
  public String getCompleteJson(final int indentation) {
    final String leftPadding = StringUtils.repeat(" ", indentation);
    return leftPadding + "\"" + getName() + "\": \"" + CARET + "\"";
  }

  @Override
  public String getCompleteYaml(final int indentation) {
    final String leftPadding = StringUtils.repeat(" ", indentation);
    return leftPadding + getName() + ": " + CARET;
  }
}


text:
<?php

namespace AppBundle\Controller;

use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\BirthdayType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;

/**
 * @Route("/stripe")
 */
class StripeController extends Controller
{
    /**
     * @Route("/callback", name="stripe_callback")
     */
    public function indexAction(Request $request)
    {
        //Get the currently logged in user
        $user = $this->get('security.token_storage')->getToken()->getUser();

        $em = $this->getDoctrine()->getManager();

        //Lookup membership type
        $membershipTypePeriod = $em->getRepository('AppBundle:MembershipTypePeriod')->findOneById($request->request->get('form')['membershipType']);

        //Check that the user hasn't previously paid
        foreach ($user->getMemberRegistration() as $registration) {
            if ($registration->getMembershipTypePeriod()->getMembershipPeriod() == $membershipTypePeriod->getMembershipPeriod()) {
                throw new \Exception('You are already registered.  You will NOT be charged.');
            }
        }

        \Stripe\Stripe::setApiKey($this->getParameter('stripe.secret_key'));

        // Get the credit card details submitted by the form
        $token = $_POST['stripeToken'];

        // Create a charge: this will charge the user's card
        try {
            $charge = \Stripe\Charge::create(array(
                "amount" => ($membershipTypePeriod->getPrice() * 100), // Amount in pence
                "currency" => "gbp",
                "source" => $token,
                "description" => "Membership"
            ));
        } catch (\Stripe\Error\Card $e) {
            // The card has been declined
            throw new \Exception('There was an error taking your payment.');
        }

        $memberRegistration = new \AppBundle\Entity\MemberRegistration();
        $memberRegistration->setPerson($user);
        $memberRegistration->setMembershipTypePeriod($membershipTypePeriod);
        $memberRegistration->setRegistrationDateTime(new \DateTime());

        $em->persist($memberRegistration);
        $em->flush();

        $this->addFlash('notice', 'Your renewal has been successful');

        return $this->redirectToRoute('account_overview');
    }
}


text:
import pandas as pd
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--task-file', '-t', default='task_result.log')
parser.add_argument('--episode-file', '-e', default='episode_result.log')

args = parser.parse_args()

task_file = args.task_file
episode_file = args.episode_file
df_task = pd.read_csv('../log/'+task_file)
df_episode = pd.read_csv('../log/'+episode_file)
# plot task result
labels = df_task.index
label_name = []
for l in labels:
    label_name.append('task' + str(l+1))
ax = df_task.ix[:, 1:].plot.bar(stacked=True)
ax.set_xticklabels(label_name)
plt.savefig('total_task_result.jpg')

# plot episode result
tasks = set(df_episode['task'])
for i in tasks:
    df_task = df_episode[df_episode.task == i].copy()
    fig, ax1 = plt.subplots()
    s = df_task.episode
    ax1.plot(s, df_task['step'], color='r', label='step')
    ax1.set_xlabel('number of episodes')
    ax1.set_ylabel('number of steps')
    ax2 = ax1.twinx()
    ax2.plot(s, df_task['time'], color='g', label='time')
    ax2.set_ylabel('elapsed times')
    file_name = 'task' + str(i) + '.jpg'
    h1, l1 = ax1.get_legend_handles_labels()
    h2, l2 = ax2.get_legend_handles_labels()
    ax1.legend(h1+h2, l1+l2, loc=2)
    plt.savefig(file_name)


text:
<?php

/**
 * Order address entity resource model
 *
 * @category    Mage
 * @package     Mage_Sales
 * @author      Magento Core Team <core@magentocommerce.com>
 */

class Mage_Sales_Model_Entity_Order_Address extends Mage_Eav_Model_Entity_Abstract
{
    public function __construct()
    {
        $resource = Mage::getSingleton('core/resource');
        $this->setType('order_address')->setConnection(
            $resource->getConnection('sales_read'),
            $resource->getConnection('sales_write')
        );
    }
}


text:
This README describes how we build the VM that the templates use.  As a user of these templates, you should not need to do this.

General documentation on this process is here:
https://azure.microsoft.com/en-us/documentation/articles/marketplace-publishing-vm-image-creation/
https://azure.microsoft.com/en-us/documentation/articles/virtual-machines-linux-classic-create-upload-vhd/

## Create a VM

    azure group create DSE-Image-RG SouthCentralUS
    azure vm quick-create --vm-size Standard_DS14_v2 DSE-Image-RG dseimage SouthCentralUS Linux Canonical:UbuntuServer:14.04.4-LTS:latest image-160622

The quick-create command will prompt for a password.  That password is for the SSH credentials to the machine.

SSH into the image.  If the command above was used, the username will be image-160622.

## Install Java on the VM

    sudo su
    apt-get -y install software-properties-common
    add-apt-repository -y ppa:webupd8team/java
    apt-get -y update
    echo debconf shared/accepted-oracle-license-v1-1 select true | sudo debconf-set-selections
    echo debconf shared/accepted-oracle-license-v1-1 seen true | sudo debconf-set-selections

## Download (but don't install) DataStax Enterprise

    dse_version=5.0.1-1
    opscenter_version=6.0.1

    echo "deb http://datastax%40microsoft.com:3A7vadPHbNT@debian.datastax.com/enterprise stable main" | sudo tee -a /etc/apt/sources.list.d/datastax.sources.list
    curl -L http://debian.datastax.com/debian/repo_key | sudo apt-key add -

    apt-get -y update
    apt-get -y -d install dse-full=$dse_version dse=$dse_version dse-hive=$dse_version dse-pig=$dse_version dse-demos=$dse_version dse-libsolr=$dse_version dse-libtomcat=$dse_version dse-libsqoop=$dse_version dse-liblog4j=$dse_version dse-libmahout=$dse_version dse-libhadoop-native=$dse_version dse-libcassandra=$dse_version dse-libhive=$dse_version dse-libpig=$dse_version dse-libhadoop=$dse_version dse-libspark=$dse_version
    apt-get -y -d install opscenter=$opscenter_version datastax-agent=$opscenter_version

## Clear the history

You'll want to run this command twice.  The first time will clear root's history and exit.  The second will clear your user's history and exit.

    cat /dev/null > ~/.bash_history && history -c && exit
    cat /dev/null > ~/.bash_history && history -c && exit

be sure to stop and deallocate the vm

## From the local Azure CLI
    azure vm stop DSE-Image-RG dseimage
    azure vm generalize DSE-Image-RG dseimage

## Get the SAS URL

Run this command to get a URL for the storage account.  You can lookup the name in the portal.  In my case it was clisto2811037585dseimage.

    azure storage account connectionstring show <name of your storage account>

    con="DefaultEndpointsProtocol=https;AccountName=cli15207440163475934758;AccountKey=<your key>"
    azure storage container list -c $con

Make sure the image is a VHD.

    azure storage blob list vhds -c $con

You'll be prompted for the resource group name.  Enter DSE-Image-RG.

    azure storage container sas create vhds rl 09/30/2016 -c $con --start 07/23/2016

This creates a URL for the img:

https://cli15207440163475934758.blob.core.windows.net/vhds?st=2016-07-23T07%3A00%3A00Z&se=2016-09-30T07%3A00%3A00Z&sp=rl&sv=2015-04-05&sr=c&sig=%2BEHZBhu%2FHkZeGTbL3jhKD%2Br1%2F72SvL3btNMHlgD5ERk%3D

to get the sas url, add cli etc after vhds as follows:

https://cli15207440163475934758.blob.core.windows.net/vhds/cli6368b7095406bb59-os-1469464726649.vhd?st=2016-07-23T07%3A00%3A00Z&se=2016-09-30T07%3A00%3A00Z&sp=rl&sv=2015-04-05&sr=c&sig=%2BEHZBhu%2FHkZeGTbL3jhKD%2Br1%2F72SvL3btNMHlgD5ERk%3D

make sure it works by wget -O tmp.vhd <sas url>


text:
<?php

namespace  Tinto\Chart;

use Tinto\Chart;

class PressureGenerator extends AbstractGenerator
{
    protected $table = 'pressure';
}


text:
using JoinRpg.Data.Interfaces;
using JoinRpg.Interfaces;
using JoinRpg.Services.Interfaces;
using JoinRpg.Services.Interfaces.Subscribe;
using JoinRpg.Web.Models.Subscribe;
using JoinRpg.Web.ProjectMasterTools.Subscribe;

namespace JoinRpg.WebPortal.Managers.Subscribe;

public class SubscribeViewService : IGameSubscribeClient
{
    private readonly IUriService uriService;
    private readonly IUserSubscribeRepository userSubscribeRepository;
    private readonly IFinanceReportRepository financeReportRepository;
    private readonly ICurrentUserAccessor currentUserAccessor;
    private readonly IGameSubscribeService gameSubscribeService;
    private readonly IUserRepository userRepository;

    public SubscribeViewService(IUriService uriService,
        IUserSubscribeRepository userSubscribeRepository,
        IUserRepository userRepository,
        IFinanceReportRepository financeReportRepository,
        ICurrentUserAccessor currentUserAccessor,
        IGameSubscribeService gameSubscribeService)
    {
        this.uriService = uriService;
        this.userSubscribeRepository = userSubscribeRepository;
        this.userRepository = userRepository;
        this.financeReportRepository = financeReportRepository;
        this.currentUserAccessor = currentUserAccessor;
        this.gameSubscribeService = gameSubscribeService;
    }

    public async Task<SubscribeListViewModel> GetSubscribeForMaster(int projectId, int masterId)
    {
        var data = await userSubscribeRepository.LoadSubscriptionsForProject(masterId, projectId);
        var currentUser = await userRepository.GetById(currentUserAccessor.UserId);

        var paymentTypes = await financeReportRepository.GetPaymentTypesForMaster(projectId, masterId);

        return data.ToSubscribeListViewModel(currentUser, uriService, projectId, paymentTypes);
    }

    public async Task RemoveSubscription(int projectId, int userSubscriptionsId)
    {
        await gameSubscribeService.RemoveSubscribe(new RemoveSubscribeRequest(projectId, userSubscriptionsId));
    }
}


text:
'''TODO:
1. add in sample_name_abbreviation, sample_name_short, time_point, etc. to
    normalized, replicates/MI, physiologicalRatiosReplicates
2. update tables to include new column data
3. optimize to remove LIMS
4. make add and update functions
5. update executions and io methods to use add/update functions'''

import sys
sys.path.append('C:/Users/dmccloskey-sbrg/Documents/GitHub/SBaaS_base')
from SBaaS_base.postgresql_settings import postgresql_settings
from SBaaS_base.postgresql_orm import postgresql_orm

# read in the settings file
filename = 'C:/Users/dmccloskey-sbrg/Google Drive/SBaaS_settings/settings_metabolomics.ini';
pg_settings = postgresql_settings(filename);

# connect to the database from the settings file
pg_orm = postgresql_orm();
pg_orm.set_sessionFromSettings(pg_settings.database_settings);
session = pg_orm.get_session();
engine = pg_orm.get_engine();

# your app...
sys.path.append(pg_settings.datadir_settings['github']+'/SBaaS_LIMS')
sys.path.append(pg_settings.datadir_settings['github']+'/SBaaS_quantification')
sys.path.append(pg_settings.datadir_settings['github']+'/io_utilities')
sys.path.append(pg_settings.datadir_settings['github']+'/python_statistics')
sys.path.append(pg_settings.datadir_settings['github']+'/r_statistics')
sys.path.append(pg_settings.datadir_settings['github']+'/listDict')
sys.path.append(pg_settings.datadir_settings['github']+'/ddt_python')
sys.path.append(pg_settings.datadir_settings['github']+'/quantification_analysis')
sys.path.append(pg_settings.datadir_settings['github']+'/matplotlib_utilities')

#make the results table
from SBaaS_quantification.stage01_quantification_analysis_execute import stage01_quantification_analysis_execute
analysis01 = stage01_quantification_analysis_execute(session,engine,pg_settings.datadir_settings);
analysis01.initialize_supportedTables();
analysis01.initialize_tables();

#make the results table
from SBaaS_quantification.stage01_quantification_MQResultsTable_execute import stage01_quantification_MQResultsTable_execute
exmqrt01 = stage01_quantification_MQResultsTable_execute(session,engine,pg_settings.datadir_settings);
exmqrt01.initialize_supportedTables();
exmqrt01.initialize_tables();

#make the quantitation methods table (move to SBaaS_quantification)
from SBaaS_quantification.lims_quantitationMethod_execute import lims_quantitationMethod_execute
exquant01 = lims_quantitationMethod_execute(session,engine,pg_settings.datadir_settings);
exquant01.initialize_supportedTables();
exquant01.initialize_tables();

#make the QC methods tables
from SBaaS_quantification.stage01_quantification_QCs_execute import stage01_quantification_QCs_execute
exqcs01 = stage01_quantification_QCs_execute(session,engine,pg_settings.datadir_settings);
exqcs01.initialize_supportedTables();
exqcs01.initialize_tables();

#make the averages methods table
from SBaaS_quantification.stage01_quantification_averages_execute import stage01_quantification_averages_execute
exave01 = stage01_quantification_averages_execute(session,engine,pg_settings.datadir_settings);
exave01.initialize_supportedTables();
exave01.initialize_tables();

##calculate the geometric averages
#exave01.execute_calculateGeoAverages_replicates(
#    'IndustrialStrains03',
#    calculated_concentration_units_I=['umol*gDW-1']);
#    #'BloodProject01',
#    #calculated_concentration_units_I=['uM']);

# export the calibrator concentrations
exquant01.export_calibrationConcentrations(
    pg_settings.datadir_settings['workspace_data']+'/_input/150516_Quantification_BloodProject01_samplesAndComponents.csv',
    pg_settings.datadir_settings['workspace_data']+'/_output/150516_calibration_concentrations.csv');


text:
<!DOCTYPE HTML>

<title>Uses of Class mil.nga.geopackage.extension.nga.style.StyleMappingDao (GeoPackage 6.5.0 API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2022-09-22">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../../../jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

All Classes

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

JavaScript is disabled on your browser.

Uses of Class
mil.nga.geopackage.extension.nga.style.StyleMappingDao

Packages that use StyleMappingDao

Package
Description

mil.nga.geopackage.extension.nga.style

Uses of StyleMappingDao in mil.nga.geopackage.extension.nga.style

Methods in mil.nga.geopackage.extension.nga.style that return StyleMappingDao

Modifier and Type
Method
Description

StyleMappingDao
FeatureStyleExtension.getIconMappingDao(String featureTable)

Get a Icon Mapping DAO

StyleMappingDao
FeatureTableStyles.getIconMappingDao()

Get a Icon Mapping DAO

StyleMappingDao
FeatureStyleExtension.getStyleMappingDao(String featureTable)

Get a Style Mapping DAO

StyleMappingDao
FeatureTableStyles.getStyleMappingDao()

Get a Style Mapping DAO

StyleMappingDao
FeatureStyleExtension.getTableIconMappingDao(String featureTable)

Get a Table Icon Mapping DAO

StyleMappingDao
FeatureTableStyles.getTableIconMappingDao()

Get a Table Icon Mapping DAO

StyleMappingDao
FeatureStyleExtension.getTableStyleMappingDao(String featureTable)

Get a Table Style Mapping DAO

StyleMappingDao
FeatureTableStyles.getTableStyleMappingDao()

Get a Table Style Mapping DAO

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

All Classes

JavaScript is disabled on your browser.

Copyright © 2022 National Geospatial-Intelligence Agency. All rights reserved.


text:
/**
 */
package ajiML;

/**
 *
 * A representation of the model object 'Infrastructure Service'.
 *
 *
 *
 * @see ajiML.AjiMLPackage#getInfrastructureService()
 * @model abstract="true"
 * @generated
 */
public interface InfrastructureService extends Microservice {
} // InfrastructureService


text:
package com.orionplatform.math.statistics.regression.lineardiscriminantanalysis.onefeature.tasks;

import com.orionplatform.core.abstraction.Orion;
import com.orionplatform.math.number.ANumber;
import com.orionplatform.math.number.NumberRules;
import com.orionplatform.math.statistics.regression.lineardiscriminantanalysis.onefeature.LinearDiscriminantAnalysis1FeatureRegression;

public class CalculateDiscriminantFunctionsAndGetClassFor1FeatureTask extends Orion
{
    public static synchronized ANumber run(LinearDiscriminantAnalysis1FeatureRegression regression, ANumber x)
    {
        NumberRules.isNotNull(x);
        ANumber varianceAverage = regression.getWeightedAverageOfDataPointsVariancesForEachClass();
        ANumber maximum = ANumber.ofMin();
        ANumber classForX = ANumber.ofMin();

        for(int i = 0; i < regression.getNumberOfClasses(); i++)
        {
            ANumber average = regression.getAverageOfDataPointsForEachClass(i);
            ANumber a = x.multiplyGET(average).divideGET(varianceAverage);
            a.subtract(average.squareGET().divideGET(varianceAverage.doubleGET()));
            a.add(regression.getProbabilityOfClass(i).getNeperianLogarithm());

            if(a.isGreaterThan(maximum))
            {
                maximum = a;
                classForX = regression.getClassForIndex(i);
            }
        }

        return classForX;
    }
}


text:
package com.network.gui;

/**
 * MainModel.
 *
 * @author ningzhangnj
 */
public class MainModel {
    private int localPort;

    private String remoteHost;

    private int remotePort;

    public int getLocalPort() {
        return localPort;
    }

    public void setLocalPort(int localPort) {
        this.localPort = localPort;
    }

    public String getRemoteHost() {
        return remoteHost;
    }

    public void setRemoteHost(String remoteHost) {
        this.remoteHost = remoteHost;
    }

    public int getRemotePort() {
        return remotePort;
    }

    public void setRemotePort(int remotePort) {
        this.remotePort = remotePort;
    }
}


text:
using System;

namespace ConsoleApplication1 {

  public class SpList {
    public SpListResponse d { get; set; }
  }

  public class SpListResponse {
    public SpListMetadata __metadata { get; set; }
    public Firstuniqueancestorsecurableobject FirstUniqueAncestorSecurableObject { get; set; }
    public Roleassignments RoleAssignments { get; set; }
    public Contenttypes ContentTypes { get; set; }
    public Defaultview DefaultView { get; set; }
    public Eventreceivers EventReceivers { get; set; }
    public Fields Fields { get; set; }
    public Forms Forms { get; set; }
    public Informationrightsmanagementsettings InformationRightsManagementSettings { get; set; }
    public Items Items { get; set; }
    public Parentweb ParentWeb { get; set; }
    public Rootfolder RootFolder { get; set; }
    public Usercustomactions UserCustomActions { get; set; }
    public Views Views { get; set; }
    public Workflowassociations WorkflowAssociations { get; set; }
    public bool AllowContentTypes { get; set; }
    public int BaseTemplate { get; set; }
    public int BaseType { get; set; }
    public bool ContentTypesEnabled { get; set; }
    public DateTime Created { get; set; }
    public string DefaultContentApprovalWorkflowId { get; set; }
    public string Description { get; set; }
    public string Direction { get; set; }
    public string DocumentTemplateUrl { get; set; }
    public int DraftVersionVisibility { get; set; }
    public bool EnableAttachments { get; set; }
    public bool EnableFolderCreation { get; set; }
    public bool EnableMinorVersions { get; set; }
    public bool EnableModeration { get; set; }
    public bool EnableVersioning { get; set; }
    public string EntityTypeName { get; set; }
    public bool ForceCheckout { get; set; }
    public bool HasExternalDataSource { get; set; }
    public bool Hidden { get; set; }
    public string Id { get; set; }
    public string ImageUrl { get; set; }
    public bool IrmEnabled { get; set; }
    public bool IrmExpire { get; set; }
    public bool IrmReject { get; set; }
    public bool IsApplicationList { get; set; }
    public bool IsCatalog { get; set; }
    public bool IsPrivate { get; set; }
    public int ItemCount { get; set; }
    public DateTime LastItemDeletedDate { get; set; }
    public DateTime LastItemModifiedDate { get; set; }
    public string ListItemEntityTypeFullName { get; set; }
    public bool MultipleDataList { get; set; }
    public bool NoCrawl { get; set; }
    public string ParentWebUrl { get; set; }
    public bool ServerTemplateCanCreateFolders { get; set; }
    public string TemplateFeatureId { get; set; }
    public string Title { get; set; }
  }

  public class SpListMetadata {
    public string id { get; set; }
    public string uri { get; set; }
    public string etag { get; set; }
    public string type { get; set; }
  }

  public class Firstuniqueancestorsecurableobject {
    public __Deferred __deferred { get; set; }
  }

  public class __Deferred {
    public string uri { get; set; }
  }

  public class Roleassignments {
    public __Deferred1 __deferred { get; set; }
  }

  public class __Deferred1 {
    public string uri { get; set; }
  }

  public class Contenttypes {
    public __Deferred2 __deferred { get; set; }
  }

  public class __Deferred2 {
    public string uri { get; set; }
  }

  public class Defaultview {
    public __Deferred3 __deferred { get; set; }
  }

  public class __Deferred3 {
    public string uri { get; set; }
  }

  public class Eventreceivers {
    public __Deferred4 __deferred { get; set; }
  }

  public class __Deferred4 {
    public string uri { get; set; }
  }

  public class Fields {
    public __Deferred5 __deferred { get; set; }
  }

  public class __Deferred5 {
    public string uri { get; set; }
  }

  public class Forms {
    public __Deferred6 __deferred { get; set; }
  }

  public class __Deferred6 {
    public string uri { get; set; }
  }

  public class Informationrightsmanagementsettings {
    public __Deferred7 __deferred { get; set; }
  }

  public class __Deferred7 {
    public string uri { get; set; }
  }

  public class Items {
    public __Deferred8 __deferred { get; set; }
  }

  public class __Deferred8 {
    public string uri { get; set; }
  }

  public class Parentweb {
    public __Deferred9 __deferred { get; set; }
  }

  public class __Deferred9 {
    public string uri { get; set; }
  }

  public class Rootfolder {
    public __Deferred10 __deferred { get; set; }
  }

  public class __Deferred10 {
    public string uri { get; set; }
  }

  public class Usercustomactions {
    public __Deferred11 __deferred { get; set; }
  }

  public class __Deferred11 {
    public string uri { get; set; }
  }

  public class Views {
    public __Deferred12 __deferred { get; set; }
  }

  public class __Deferred12 {
    public string uri { get; set; }
  }

  public class Workflowassociations {
    public __Deferred13 __deferred { get; set; }
  }

  public class __Deferred13 {
    public string uri { get; set; }
  }

}


text:
package io.spring.workshop;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
	@Override
	public void addViewControllers(ViewControllerRegistry registry) {
		registry.addViewController("/").setViewName("index");
	}
}


text:
extern crate rebind;
extern crate rustc;
extern crate syntax;

mod derive_action;

use rustc::plugin::Registry;
use syntax::parse::token::intern;
use syntax::ext::base::SyntaxExtension;

use derive_action::expand_derive_action_annotation;

#[plugin_registrar]
#[doc(hidden)]
pub fn plugin_registrar(registry: &mut Registry) {
    registry.register_syntax_extension(intern("derive_Action"),
                                       SyntaxExtension::MultiDecorator(Box::new(expand_derive_action_annotation)));
}


text:
project_path: /web/_project.yaml
book_path: /web/fundamentals/_book.yaml
description: Saiba como integrar um service worker a um aplicativo existente para que o aplicativo funcione off-line.

{# wf_auto_generated #}
{# wf_updated_on: 2016-11-09T18:31:19Z #}
{# wf_published_on: 2016-01-01 #}

# Adicionar um Service Worker e Off-line ao seu App da Web {: .page-title }

{% include "web/_shared/contributors/paulkinlan.html" %}

Visão geral do ##

![9246b0abd8d860da.png](img/9246b0abd8d860da.png)

Neste codelab, você aprenderá a integrar um service worker a um aplicativo existente para que o aplicativo funcione off-line. O aplicativo se chama  [Air Horner](https://airhorner.com). Clique na buzina e ela faz um som.

#### O que você aprenderá

* Como adicionar um service worker básico a um projeto existente
* Como simular o modo off-line e inspecionar e depurar um service worker com Chrome DevTools.
* Uma estratégia simples para o armazenamento em cache off-line.

#### O que será necessário

* Chrome 52 ou superior.
* Conhecimentos básicos sobre [Promises](/web/fundamentals/getting-started/primers/promises), Git e Chrome DevTools.
* O exemplo de código.
* Um editor de texto.
* Um servidor da Web local. Se deseja usar o servidor de Web descrito neste codelab, você precisa do Python instalado em sua linha de comando.

## Obtenha o exemplo de código

Clone o repositório do GitHub pela linha de comando sobre SSH:

    $ git clone git@github.com:GoogleChrome/airhorn.git

Ou HTTPS:

    $ git clone https://github.com/GoogleChrome/airhorn.git

## Execute o exemplo de aplicativo

Primeiro, vejamos qual a aparência do aplicativo de exemplo acabado (dica: é incrível).

Certifique-se de que você esteja na ramificação correta (final), verificando a ramificação `master`.

    $ git checkout master

Execute o site a partir de um servidor de Web local.  Você pode usar qualquer servidor de Web, mas pelo resto deste codelab vamos supor que esteja usando `SimpleHTTPServer` do Python na porta 3000, portanto o aplicativo estará disponível em `localhost:3000`.

    $ cd app
    $ python -m SimpleHTTPServer 3000

Abra o site no Chrome. Você deve ver: ![9246b0abd8d860da.png](img/9246b0abd8d860da.png)

## Teste o aplicativo

Clique na buzina. Ela deve fazer um som.

Agora, você vai simular ficar off-line usando Chrome DevTools.

Abra o DevTools, vá ao painel __Application__, e ative a caixa de seleção __Offline__. Na imagem abaixo, o cursor está parado sobre a caixa de seleção.

![479219dc5f6ea4eb.png](img/479219dc5f6ea4eb.png)

Após clicar na caixa de seleção, observe o ícone de aviso (triângulo amarelo com ponto de exclamação) ao lado da guia __Network__ do painel. Isto indica que você está off-line.

Para provar que você está off-line, vá para [https://google.com](https://google.com). Você deve ver a mensagem de erro "não há conexão com a Internet" do Chrome.

Agora, volte para o seu aplicativo. Embora esteja off-line, a página ainda deve atualizar totalmente. Você ainda deve conseguir usar a buzina.

O motivo para ele funcionar off-line é a base deste codelab: suporte off-line com o service worker.

## Compile o aplicativo inicial

Agora você vai remover todo o suporte off-line do aplicativo e vai aprender como usar um service worker para adicionar o suporte off-line de volta ao aplicativo

Confira a versão "quebrada" do aplicativo que não tem o service worker implementado.

    $ git checkout code-lab

Volte ao painel __Application__ do DevTools e desative a caixa de seleção __Offline__, para voltar a ficar online.

Execute a página. O aplicativo deve funcionar da forma esperada.

Agora, use DevTools para simular o modo off-line novamente (ativando a caixa de seleção  __Offline__ no painel __Application__). __Atenção!__ Se não sabe muito sobre service workers, você está prestes a ver um comportamento inesperado.

O que você espera ver? Bem, como está off-line e esta versão do aplicativo não tem service worker, seria de esperar ver a mensagem de erro "não há conexão com a Internet" típica do Chrome.

Mas o que você realmente vê é ... um aplicativo off-line totalmente funcional!

![9246b0abd8d860da.png](img/9246b0abd8d860da.png)

O que aconteceu? Bem, lembre-se de que ao começar este codelab, você experimentou a versão concluída do aplicativo. Quando aquela versão foi executada, o aplicativo realmente instalou um service worker. Esse service worker agora está sendo executado automaticamente toda vez que você executa o aplicativo. Uma vez que um service worker é instalado para um escopo, como `localhost:3000` (você vai aprender mais sobre escopo na próxima seção), esse service worker é iniciado automaticamente toda vez que se acessa o escopo, a menos que você o exclua programática ou manualmente.

Para corrigir isso, vá para o painel __Application__ do DevTools, clique na guia __Service Workers__ e, em seguida, clique no botão __Unregister__. Na imagem abaixo, o cursor está parado sobre o botão.

![837b46360756810a.png](img/837b46360756810a.png)

Agora, antes de atualizar o site, certifique-se de que você ainda está usando DevTools para simular o modo off-line. Atualize a página, e ela deve exibir a mensagem de erro "não há conexão com a Internet", como esperado.

![da11a350ed38ad2e.png](img/da11a350ed38ad2e.png)

## Registre um service worker no site

Agora é hora de adicionar suporte off-line de volta ao aplicativo. Isso consiste em dois passos:

1. Crie um arquivo JavaScript que será o service worker.
2. Instrua o navegador a registrar o arquivo JavaScript como o "service worker".

Primeiro, crie um arquivo vazio chamado `sw.js` e coloque-o na pasta `/app`.

Agora, abra `index.html` e adicione o código a seguir na parte inferior de `<body>`.

```
<script>
if('serviceWorker' in navigator) {
  navigator.serviceWorker
           .register('/sw.js')
           .then(function() { console.log("Service Worker Registered"); });
}
</script>
```

O script verifica se o navegador suporta service workers. Se suportar, ele registra o nosso arquivo `sw.js` atualmente em branco como o service worker, e, em seguida, registra para o console.

Antes de executar seu site novamente, volte para DevTools e olhe a guia __Service Workers__ do painel __Application__. Ela deve ser atualmente vazia, o que significa que o site não tem service workers instalados.

![37d374c4b51d273.png](img/37d374c4b51d273.png)

Certifique-se de que a caixa de seleção __Offline__ no DevTools esteja desativada. Atualize sua página novamente. Como a página é carregada, você pode ver que um service worker está registrado.

![b9af9805d4535bd3.png](img/b9af9805d4535bd3.png)

Ao lado do rótulo __Source__, você pode ver um link para o código-fonte do service worker registrado.

![3519a5068bc773ea.png](img/3519a5068bc773ea.png)

Se quiser inspecionar o service worker atualmente instalado para uma página, clique no link. Isso vai exibir o código-fonte do service worker no painel __Sources__ do DevTools. Por exemplo, clique no link agora, e você deve ver um arquivo vazio.

![dbc14cbb8ca35312.png](img/dbc14cbb8ca35312.png)

## Instale os ativos do site

Com o service worker registrado, na primeira vez que um usuário acessar a página, um evento `install` é acionado. Este evento é o local onde você deseja armazenar em cache os ativos da sua página.

Adicione o código a seguir ao sw.js.

```
importScripts('/cache-polyfill.js');

self.addEventListener('install', function(e) {
 e.waitUntil(
   caches.open('airhorner').then(function(cache) {
     return cache.addAll([
       '/',
       '/index.html',
       '/index.html?homescreen=1',
       '/?homescreen=1',
       '/styles/main.css',
       '/scripts/main.min.js',
       '/sounds/airhorn.mp3'
     ]);
   })
 );
});
```

A primeira linha adiciona o Cache polyfill. Este polyfill já está incluído no repositório. Precisamos usar o polyfill porque a API Cache ainda não é totalmente suportada em todos os navegadores. Em seguida, vem o ouvinte de evento `install`. O ouvinte de evento `install` abre o objeto `caches` e, em seguida, o preenche com a lista de recursos que queremos armazenar em cache. Uma coisa importante sobre a operação `addAll` é que ela é tudo ou nada. Se um dos arquivos não estiver presente ou não for buscado, toda a operação `addAll` falha. Um bom aplicativo cuidará desse cenário.

O próximo passo é programar nosso service worker para retornar a interceptação das solicitações de qualquer um desses recursos e usar o objeto `caches` para retornar a versão armazenada localmente de cada recurso.

## Intercepte as solicitações da página da Web

Um recurso poderoso dos service workers é que, uma vez que um service worker controla uma página, ele pode interceptar todas as solicitações que a página faz e decidir o que fazer com a solicitação. Nesta seção você vai programar o service worker para interceptar solicitações e retornar as versões em cache de ativos, em vez de ir para a rede para recuperá-los.

A primeira etapa é anexar um gerenciador de eventos ao evento `fetch`. Esse evento é acionado para todas as solicitações realizadas.

Adicione o código a seguir ao à parte inferior do seu `sw.js` para registrar as solicitações feitas a partir da página principal.

Vamos testar isso. __Atenção!__ Você está prestes a ver mais algum comportamento inesperado do service worker.

Abra DevTools e vá para o painel __Application__. A caixa de seleção __Offline__ deve estar desativada. Pressione a tecla `Esc` para abrir a gaveta __Console__ na parte inferior da sua janela DevTools. Sua janela DevTools deve ser semelhante à imagem a seguir:

![c96de824be6852d7.png](img/c96de824be6852d7.png)

Atualize sua página agora e veja a janela de DevTools novamente. Para começar, esperamos ver várias solicitações registradas no Console, mas isso não está acontecendo. Em segundo lugar, no painel __Service Worker__ podemos ver que o __Status__ mudou:

![c7cfb6099e79d5aa.png](img/c7cfb6099e79d5aa.png)

No __Status__ há um novo service worker esperando para ativar. Este deve ser o novo service worker que inclui as alterações que acabamos de fazer. Então, por algum motivo, o antigo service worker que instalamos (que era apenas um arquivo em branco) ainda está controlando a página. Se clicar no link `sw.js` ao lado de __Source__ você pode verificar que o antigo service worker ainda está em execução.

Para corrigir esse inconveniente, ative a caixa de seleção __Update on reload__.

![26f2ae9a805bc69b.png](img/26f2ae9a805bc69b.png)

Quando esta caixa de seleção está ativada, DevTools sempre atualiza o service worker a cada atualização da página. Isso é muito útil ao se desenvolver um service worker ativamente.

Atualize a página agora e você pode ver que um novo service worker está instalado e que os URLs de solicitação estão sendo registrados no Console, como esperado.

![53c23650b131143a.png](img/53c23650b131143a.png)

Agora você precisa decidir o que fazer com todas essas solicitações. Por padrão, se você não fizer nada, a solicitação é transmitida para a rede e a resposta é retornada para a página da Web.

Para que seu aplicativo funcione off-line, você precisa coletar a solicitação do cache se ela estiver disponível.

Atualize seu ouvinte de evento de busca para coincidir com o código abaixo.

O método `event.respondWith()` informa ao navegador para avaliar o resultado do evento no futuro. `caches.match(event.request)` leva a atual solicitação da web que ativou o evento de busca e procura no cache por um recurso que corresponda. A correspondência é realizada verificando a string do URL. O método `match` retorna uma promessa que resolve, mesmo se o arquivo não for encontrado no cache. Isso significa que você tem uma escolha sobre o que fazer. Em nosso caso simples, quando o arquivo não é encontrado, você deve `fetch` o mesmo da rede e retorná-lo ao navegador.

Este é o caso mais simples; existem muitos outros cenários de armazenamento em cache. Por exemplo, é possível armazenar em cache de forma incremental todas as respostas de solicitações que anteriormente não estavam armazenadas para que, no futuro, todas sejam retornadas do cache.

## Parabéns!

Agora você tem suporte off-line. Atualize a página enquanto ainda está online para atualizar o service worker para a última versão, e depois use DevTools para entrar em modo off-line. Atualizar a página novamente, e você deve ter uma buzina de ar off-line totalmente funcional!

#### Tópicos abordados

* Como adicionar um service worker básico a um projeto existente
* Como usar Chrome DevTools para simular o modo off-line e para inspecionar e depurar service workers.
* Uma estratégia simples para o armazenamento em cache off-line.

#### Próximas etapas

* Saiba como adicionar facilmente  [suporte off-line com elementos Polymer off-line](https://codelabs.developers.google.com/codelabs/sw-precache/index.html?index=..%2F..%2Findex#0) robusto
* Explore mais [técnicas avançadas de armazenamento em cache](https://jakearchibald.com/2014/offline-cookbook/)

#### Saiba mais

*  [Introdução ao service worker](/web/fundamentals/primers/service-worker/?hl=en)

## Encontrou um problema ou tem feedback? {: .hide-from-toc }
Ajude-nos a melhorar nossos codelabs reportando um
[problema](https://github.com/googlesamples/io2015-codelabs/issues) hoje. E obrigado!

{# wf_devsite_translation #}


text:
.class public interface abstract Lcom/samsung/context/sdk/samsunganalytics/a/d/c;
.super Ljava/lang/Object;

# virtual methods
.method public abstract a(Lcom/samsung/context/sdk/samsunganalytics/a/d/b;)V
.end method


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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical"
              android:paddingBottom="@dimen/activity_vertical_margin"
              android:paddingLeft="@dimen/activity_horizontal_margin"
              android:paddingRight="@dimen/activity_horizontal_margin"
              android:paddingTop="@dimen/activity_vertical_margin"
              android:weightSum="10"
    >

    <ScrollView

        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="7"
        >

        <RelativeLayout
            android:id="@+id/activity_main"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            >

            <Button
                android:id="@+id/btn_insert"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="INSERT"
                />

            <Button
                android:id="@+id/btn_delete"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/btn_insert"
                android:layout_centerHorizontal="true"
                android:text="DELETE"
                />

            <Button
                android:id="@+id/btn_update"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/btn_delete"
                android:layout_centerHorizontal="true"
                android:text="UPDATE"
                />

            <Button
                android:id="@+id/btn_query"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/btn_update"
                android:layout_centerHorizontal="true"
                android:text="QUERY"
                />
        </RelativeLayout>
    </ScrollView>

    <ScrollView
        android:id="@+id/sv_text"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="3"
        >

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/tv_title_result"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Result:"
                />

            <TextView
                android:id="@+id/tv_value_result"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/tv_title_result"
                android:layout_marginTop="10dp"
                android:text="result value"
                />
        </RelativeLayout>
    </ScrollView>
</LinearLayout>


text:
/**
 * View Models used by Spring MVC REST controllers.
 */
package br.com.rafael.webhipster.web.rest.vm;