text:
## Golden rules

**Babylon.js** is built upon 3 golden rules:

1. You cannot add code that will break backward compatibility
2. You cannot add code that will slow down the rendering process
3. You cannot add code that will make things complex to use

### Backward compatibility

The first golden rule is a really important one because we want our users to trust Babylon.js. And when we need to introduce something that will break backward compatibility, we know that it will imply more work for our customers to switch to a new version. So even if something could be simpler to do by breaking the backward compatibility, we will not do it (exceptions may apply of course if there is a problem with performance or if this is related to a bug).

### Performance

Babylon.js is a 3D rendering engine. So every piece of code has to be scrutinized to look for potential bottlenecks or slow downs. Ultimately the goal is to render more with less resources.

### Simplicity

A developer should be able to quickly and easily learn to use the API.

Simplicity and a low barrier to entry are must-have features of every API. If you have any second thoughts about the complexity of a design, it is almost always much better to cut the feature from the current release and spend more time to get the design right for the next release.

You can always add to an API, you cannot ever remove anything from one. If the design does not feel right, and you ship it anyway, you are likely to regret having done so.

## Forum and Github issues

Since the very beginning, Babylon.js relies on a great forum and a tremendous community: [https://forum.babylonjs.com/](https://forum.babylonjs.com/). Please use the forum for **ANY questions you may have**.

Please use the Github issues (after discussing them on the forum) **only** for:

- Bugs
- Feature requests

We will try to enforce these rules as we consider the forum is a better place for discussions and learnings.

## Online one-click setup for Contributing

You can use Gitpod (A free online VS Code like IDE) for contributing online. With a single click it'll launch a workspace and automatically:

- clone the BabylonJS repo.
- install the dependencies.
- run `npm run start` in `Tools/Gulp`.

so that you can start straight away.

[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/BabylonJS/Babylon.js)

## Pull requests

We are not complicated people, but we still have some [coding guidelines](https://doc.babylonjs.com/how_to/approved_naming_conventions)
Before submitting your PR, just check that everything goes well by [creating the minified version](https://doc.babylonjs.com/resources/creating_the_mini-fied_version)

You should read the [how to contribute documentation](https://doc.babylonjs.com/how_to/how_to_start) before working on your PR.

To validate your PR, please follow these steps:

- Run "gulp" locally and make sure that no error is generated
- Make sure that all public functions and classes are commented using JSDoc syntax
- Make sure to add a line about your PR in the [what's new](https://github.com/BabylonJS/Babylon.js/blob/master/dist/preview%20release/what's%20new.md)

## What should go where

In order to not bloat the core engine with unwanted or unnecessary features (that we will need to maintain forever), here is a list of questions you could ask yourself before submitting a new feature (or feature request) for Babylon.js core engine:

- Does my feature belong to a framework library?
- Can my feature be used by multiple different applications?
- Is there a general use case for this feature?
- Does this feature already exist in a similar framework?

If your PR is does not fall into the core category you can consider using our [Extensions repo](https://github.com/BabylonJS/Extensions) for more high level features.


text:
/*CSS page shared by new_request.html, new_request_agency.html, new_request_user.html*/

#request-description {
    height: 15rem
}

.sideblock {
    padding-top: 33rem;
}

.example-title {
    padding: 1rem 1.5rem;
    background-color: #efefef;
}

.example-request {
    padding: 1rem 1.5rem;
    background-color: #efefef;
}

.top-padding {
    padding-top: 16rem;
}

.top-padding2 {
    padding-top: 5rem;
}

.parsley-errors-list {
    color: #e74c3c;
}

#state {
    height: 50px;
}

#zipcode {
    width: 45px;
}

#upload-control {
    padding-bottom: 3rem;
}

#filename {
    padding-top: 1rem;
}

.new-request-description-tooltip {
    padding-left: 300px;
    padding-right: 25px;
}

.new-request-description-tooltip {
    width: 300px;
}

.popover {
    max-width: 100%;
}

#request-form {
    width: 100%;
}

.no-padding-left {
    padding-left: 0;
}

.captcha {
    text-align: center;
    padding-bottom: 20px;
}

.g-recaptcha {
    display: inline-block;
}

.recaptcha-error {
    text-align: center;
    color: red;
}

#processing-submission img {
    display: block;
    margin-left: auto;
    margin-right: auto;
}

.modal-content {
    /* Bootstrap sets the size of the modal in the modal-dialog class, we need to inherit it */
    width:inherit;
    max-width:inherit;
    height:inherit;
    /* To center horizontally */
    margin: 0 auto;
    pointer-events: all;
}

.clear-file-button {
    background-color: #dc3545;
    border-color: #dc3545;
    margin-bottom: 10px;
    padding-top: 9px;
    padding-bottom: 9px;
    display: none;
}

.agency-instructions-title {
    text-align: center;
}

/* Styles for keyboard accessible upload section */
span[role=button] {
    display: table-cell;
    font-weight: normal;
    font-size: 14px;
    padding: 8px 8px;
    border-radius: 5px;
    border: 2px solid #265986;
    color: #ffffff;
    cursor: pointer;
    background-color: #265986;
    outline: none;
}

span[role=button]:hover,
span[role=button]:focus {
    box-shadow: 0 0 5px #595959;
    background-color: #183a57;
    border-color: #4D90FE;
    outline: 2px solid transparent;
}

.hide {
    position: absolute;
    width: 1px;
    height: 1px;
    padding: 0;
    margin: -1px;
    overflow: hidden;
    clip: rect(0, 0, 0, 0);
    border: 0;
}

input[type=text] .file-text-input {
    display: table-cell;
    margin-left: -5px;
    width: 20rem;
    font-size: 14px;
    font-weight: normal;
    padding: 8px 8px;
    border-top-right-radius: 5px;
    border-bottom-right-radius: 5px;
    border: 2px solid #265986;
    color: #000000;
    background-color: #ffffff;
}

.file-text-input:focus {
    box-shadow: 0 0 5px #595959;
    border-color: #4D90FE;
    outline: 2px solid transparent;
}

.help-text {
    margin-bottom: 0;
}

.parsley-maxFileSize {
    font-size: 14px;
    color: #df0000;
    padding-bottom: 10px;
}

redpajama_set_name: RedPajamaGithub


text:
// Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.

$(document).ready(function() {// Javascript object to store all map data

    console.log(introTrue);

    $("#mobile").hide();

    if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
     // You are in mobile browser
        $("#notinmobile").hide();
        $("#mobile").show();
        introTrue = false;
    }

    //Intro Js QuikMap creation introduction
    var createguide = introJs();
    createguide.setOptions({
      steps: [
          {
            intro: '
The QuikMap Create Page

 \
            Where concise direction giving QuikMaps are made'
          },
          {
            element:"#canvas",
            intro:"
The Map Canvas

You will be drawing your map here."
          },
          {
            element:"#toolbar",
            intro:"
The Toolbar

It contains all the tools you need to \
              create your own QuikMap. Click on them to know what they do"
          },
          {
            intro:"
Tips to draw a Good QuikMap
"
          },
          {
            element:"#nameMap",
            intro: "Firstly, name your map after its destination. \
              E.g. Pizzahut near Chinatown MRT \
              or E.g. John Tan's Wedding Reception "
          },
          {
            element:"#editpane",
            intro:"Secondly, draw the routes/paths \
              from your starting point to your endpoint using the draw tool:
\

\
              After which, add your start and end point.

\
              ",
          },
          {
            element:"#editpane",
            intro:"Next, add in the landmarks that\
              you can see as you travel along your route.\

\
              "
          },
          {
            element:"#tagsinput",
            intro:"Give your map some tags, such as coffee, bag shop, shoe shop"
          },
          {
            element:"#submitbutton",
            intro:"Lastly, submit your QuikMap, so that you can share it."
          }
      ],
      doneLabel: 'Done',
      tooltipPosition: 'auto',
      positionPrecedence: ['bottom','left', 'right', 'top'],
      disableInteraction: false
    });

    var maptips = introJs();
    maptips.setOptions({
      steps: [
          {
            intro:"
Tips to draw a Good QuikMap
"
          },
          {
            element:"#nameMap",
            intro: "Firstly, name your map after its destination. \
              E.g. Pizzahut near Chinatown MRT \
              or E.g. John Tan's Wedding Reception "
          },
          {
            element:"#editpane",
            intro:"Secondly, draw the routes/paths \
              from your starting point to your endpoint using the draw tool:
\

\
              After which, add your start and end point.

\
              ",
          },
          {
            element:"#editpane",
            intro:"Next, add in the landmarks that\
              you can see as you travel along your route.\

\
              "
          },
          {
            element:"#tagsinput",
            intro:"Give your map some tags, such as coffee, bag shop, shoe shop"
          },
          {
            element:"#submitbutton",
            intro:"Lastly, submit your QuikMap,\
            so that you can share it."
          }
      ],
      doneLabel: 'Done',
      tooltipPosition: 'auto',
      positionPrecedence: ['bottom','left', 'right', 'top'],
      disableInteraction: false
    });

    if(introTrue){
      createguide.start();
    }

    $('#howtousebutton').click(function(){
        maptips.start();
    });

    //bootstrapSwitch
    $('#isStraight').bootstrapSwitch('state',true);
    $('#isStraight').bootstrapSwitch("onText",'Straight');
    $('#isStraight').bootstrapSwitch("offText",'Curvy');
    $('#isStraight').bootstrapSwitch("onColor",'primary');
    $('#isStraight').bootstrapSwitch("offColor",'info');

    $('#isLandmark').bootstrapSwitch('state',false);
    $('#isLandmark').bootstrapSwitch("onText",'Landmark');
    $('#isLandmark').bootstrapSwitch("offText",'Points');
    $('#isLandmark').bootstrapSwitch("onColor",'primary');
    $('#isLandmark').bootstrapSwitch("offColor",'warning');

    //map_canvas properties

    var golden_ratio = 1.61803398875;

    var map_canvas = $('#canvas');
    var ctx = canvas.getContext("2d");
    var container = $("#app"); //container of map_canvas

    cwidth = container.width();
    cheight = cwidth / golden_ratio;

    map_canvas.attr("width",cwidth);
    map_canvas.attr("height",cheight);

    //canvas resizing on window resize
    $(window).resize(function(){
        cwidth = container.width();
        cheight = cwidth/golden_ratio;
        map_canvas.attr("width",cwidth);
        map_canvas.attr("height",cheight);
        update_canvas(map_data);
    });

    //map_data properties
    var map_data = {name:"Untitled", maxid: 0, lines:[], landmarks: []};
    var undo_stack = new Array();
    var redo_stack = new Array();
    var tochangeindex = null;

    /**
     *Toolbar controller.
     *controls all buttons in toolbar
     */
    var selected = 0;
    $('#selectdiv').hide();
    $('#drawdiv').hide();
    $('#landmarkdiv').hide();
    $('#removediv').hide();
    $('#undodiv').hide();
    $('#redodiv').hide();
    $('#undobutton').attr("disabled", true);
    $('#redobutton').attr("disabled", true);

    $('#selectbutton').click( function() {
        selected = 1;
      $('#blankdiv').hide();
    });

    $('#drawbutton').click( function() {
        selected = 2;
        $('#blankdiv').hide();
    });

    $('#landmarkbutton').click( function() {
        selected = 3;
        $('#blankdiv').hide();
    });

    $('#removebutton').click( function() {
        selected = 4;
        $('#blankdiv').hide();
    });

    $('#undobutton').click(function() {
        selected = 5;
        undo();
    });

    $('#redobutton').click(function(){
        selected = 6;
        redo();
    });

    $(document).keydown(function(e){
      if( e.which === 90 && e.ctrlKey ){
        if(!$('#undobutton').attr('disabled')) undo();
      }
      else if( e.which === 89 && e.ctrlKey ){
        if(!$('#redobutton').attr('disabled')) redo();
      }
    });

    var undo = function() {
        var actiontoundo = undo_stack.pop();
        if (actiontoundo.action == "line") {
            var line_data;
            var to_remove = 0;

            for (i = 0; i < map_data.lines.length; i++) {
                if (map_data.lines[i].id == actiontoundo.id) {
                    line_data = map_data.lines[i];
                    to_remove = i;
                    break;
                }
            }
            map_data.lines.splice(to_remove, 1);
            redo_stack.push({action: "line", data: line_data});
        }

        if (actiontoundo.action == "landmark") {
            var landmarkdata;
            var to_remove = 0;
            for (i = 0; i < map_data.landmarks.length; i++) {
                if (map_data.landmarks[i].id == actiontoundo.id) {
                    landmarkdata = map_data.landmarks[i];
                    to_remove = i;
                    break;
                }
            }
            map_data.landmarks.splice(to_remove, 1);
            redo_stack.push({action: "landmark", data: landmarkdata});
        }

        if (actiontoundo.action == "delete") {
            var datatoaddback = actiontoundo.data;
            if (datatoaddback.type == "line") {
                map_data.lines.push(datatoaddback);
            }
            else if (datatoaddback.type == "landmark") {
                map_data.landmarks.push(datatoaddback);
            }
            redo_stack.push({action:"delete",data: datatoaddback});
        }

        if (actiontoundo.action == "changelandmark") {
            for (i = 0; i < map_data.landmarks.length; i++) {
                if (map_data.landmarks[i].id == actiontoundo.id) {
                    var newlandmarkname = map_data.landmarks[i].landmarkname;
                    var newlandmarkimg = map_data.landmarks[i].img;
                    map_data.landmarks[i].landmarkname = actiontoundo.oldname;
                    map_data.landmarks[i].img = actiontoundo.oldimg;
                    redo_stack.push({action: "changelandmark", id: actiontoundo.id, newname: newlandmarkname, newimg: newlandmarkimg});
                    break;
                }
            }
        }
        update_canvas(map_data);
    }

    var redo = function() {
        var actiontoredo = redo_stack.pop();
        if (actiontoredo.action == "line") {
            var thisid = actiontoredo.data.id;
            undo_stack.push({action:"line", id:thisid});
            map_data.lines.push(actiontoredo.data);
        }
        if (actiontoredo.action == "landmark") {
            var thisid = actiontoredo.data.id;
            undo_stack.push({action:"landmark", id:thisid});
            map_data.landmarks.push(actiontoredo.data);
        }
        if (actiontoredo.action == "delete") {
            todelete = actiontoredo.data;
            undo_stack.push({action:"delete",data:todelete});
            if (todelete.type == "line") {
                map_data.lines.splice(map_data.lines.indexOf(todelete),1);
            }
            if (todelete.type == "landmark") {
                map_data.landmarks.splice(map_data.landmarks.indexOf(todelete),1);
            }
        }
        if (actiontoredo.action == "changelandmark") {
            for (i = 0; i < map_data.landmarks.length; i++) {
                if (map_data.landmarks[i].id == actiontoredo.id) {
                    var oldname = map_data.landmarks[i].landmarkname;
                    var oldimg = map_data.landmarks[i].img;
                    map_data.landmarks[i].landmarkname = actiontoredo.newname;
                    map_data.landmarks[i].img = actiontoredo.newimg;
                    undo_stack.push({action: "changelandmark", id: actiontoredo.id, oldname: oldname, oldimg: oldimg});
                    break;
                }
            }
        }
        update_canvas(map_data);
    }

    $('#isStraight').on('switchChange.bootstrapSwitch', function(event, state) {
      if (!state) {
        console.log("show");
        $("#curvydiv").show();
      } else {
        console.log("hide");
        $("#curvydiv").hide();
      }
    });

    $('#toolbar').click( function() {

        $('#selectbutton').attr("disabled", false);
        $('#drawbutton').attr("disabled", false);
        $('#landmarkbutton').attr("disabled", false);
        $('#removebutton').attr("disabled", false);
        $('#selectdiv').hide();
        $('#drawdiv').hide();
        $('#landmarkdiv').hide();
        $('#removediv').hide();
        $('#undodiv').hide();
        $('#redodiv').hide();
        $("#curvydiv").hide();

        switch (selected) {
        case 1:
            $('#selectbutton').attr("disabled", true);
            $('#selectdiv').show();
            break;
        case 2:
            $('#drawbutton').attr("disabled", true);
            if (!$('#isStraight').bootstrapSwitch("state")) {
              $("#curvydiv").show();
            }
            $('#drawdiv').show();
            break;
        case 3:
            $('#landmarkbutton').attr("disabled", true);
            $('#landmarkdiv').show();
            break;
        case 4:
            $('#removebutton').attr("disabled", true);
            $('#removediv').show();
            break;
        case 5:
            $('#undodiv').show();
            break;
        case 6:
            $('#redodiv').show();
        }
    });

    /**
     * Toolbar button code ends here
     */

    /**
     * Landmark popup code
     */
    $(document).click( function() {
        if (selected != 3 && selected != 1) {
            $("#pointpopover").hide();
            $("#landmarkpopover").hide();
        } else if (selected == 3){
            if (!$("#isLandmark").bootstrapSwitch("state")) {
                $("#landmarkpopover").hide();
            } else {
                $("#pointpopover").hide();
            }
        }
    });

    function createLandmark(img, name) {
        if (selected == 1) {
            // edit landmark
            var oldname = map_data.landmarks[tochangeindex].landmarkname;
            var oldimg = map_data.landmarks[tochangeindex].img;
            map_data.landmarks[tochangeindex].landmarkname = name;
            map_data.landmarks[tochangeindex].img = img;
            undo_stack.push({action: "changelandmark", id: map_data.landmarks[tochangeindex].id, oldname: oldname, oldimg: oldimg});
            redo_stack.splice(0, redo_stack.length);
            update_canvas(map_data);
        } else { // new landmark
            var thisid = map_data.maxid;
            map_data.maxid += 1;
            undo_stack.push({action: "landmark", id: thisid});
            redo_stack.splice(0, redo_stack.length);
            landmarkpos = {x: landmarkpos.x / cwidth*1.0, y: landmarkpos.y / cheight*1.0};
            addElement({type: "landmark", id: thisid, landmarkname: name, img: img, pos: landmarkpos});
        }
    }

    $("#startbutton").click( function() {
        name = $("#pointinput").val();
        if (name == "") {
            name = "Start";
        }
        createLandmark("startimg", name);
        $("#pointinput").val("");
        $("#pointpopover").hide();
    });

    $("#endbutton").click( function() {
        name = $("#pointinput").val();
        if (name == "") {
            name = "End";
        }
        createLandmark("endimg", name);
        $("#pointinput").val("");
        $("#pointpopover").hide();
    });

    $("#trainbutton").click( function() {
        name = $("#pointinput").val();
        if (name == "") {
            name = "Station";
        }
        createLandmark("trainimg", name);
        $("#pointinput").val("");
        $("#pointpopover").hide();
    });

    $("#busbutton").click( function() {
        name = $("#pointinput").val();
        if (name == "") {
            name = "Bus Stop";
        }
        createLandmark("busimg", name);
        $("#pointinput").val("");
        $("#pointpopover").hide();
    });

    $('#digitalbutton').click( function() {
        name = $("#landmarkinput").val();
        if (name == "") {
            name = "Digital";
        }
        createLandmark("digitalimg", name);
        $("#landmarkinput").val("");
        $("#landmarkpopover").hide();
    });

    $('#lifestylebutton').click( function() {
        name = $("#landmarkinput").val();
        if (name == "") {
            name = "Lifestyle";
        }
        createLandmark("lifestyleimg", name);
        $("#landmarkinput").val("");
        $("#landmarkpopover").hide();
    });

    $('#foodbutton').click( function() {
        name = $("#landmarkinput").val();
        if (name == "") {
            name = "F&B";
        }
        createLandmark("foodimg", name);
        $("#landmarkinput").val("");
        $("#landmarkpopover").hide();
    });

    $('#fashionbutton').click( function() {
        name = $("#landmarkinput").val();
        if (name == "") {
            name = "Fashion";
        }
        createLandmark("fashionimg", name);
        $("#landmarkinput").val("");
        $("#landmarkpopover").hide();
    });

    $('#servicesbutton').click( function() {
        name = $("#landmarkinput").val();
        if (name == "") {
            name = "Service";
        }
        createLandmark("servicesimg", name);
        $("#landmarkinput").val("");
        $("#landmarkpopover").hide();
    });

    $('#structuresbutton').click( function() {
        name = $("#landmarkinput").val();
        if (name == "") {
            name = "Structure";
        }
        createLandmark("structuresimg", name);
        $("#landmarkinput").val("");
        $("#landmarkpopover").hide();
    });

    /**
     * Landmark popup code ends here
     */

    // Canvas Manipulation

    var penDown = false;
    var startpos;
    var points = new Array();

    function getMousePos(e) {
        return {
            x: e.offsetX,
            y: e.offsetY
        };
    }

    function get_control_points(start,q1,q2,end){

      //Magic number, with golden ratio!
      extend_coefficient = 0.5*golden_ratio;

      function form_equation(q1,q2){

        function equation(x){
            var highvalue = 9999999999999;
            if(q1.x == q2.x) {
                gradient = highvalue;
            } else {
                  gradient = (q2.y - q1.y)/(q2.x - q1.x);
              }
          c = q1.y - gradient*q1.x;
          return gradient*x + c;
        }

        return equation;
      }

      var control1 = {x:0,y:0};
      var control2 = {x:0,y:0};

      control1.x = Math.floor(q1.x + extend_coefficient*(q1.x-start.x));
      control2.x = Math.floor(q2.x - extend_coefficient*(end.x-q2.x));
      control1.y = Math.floor(form_equation(start,q1)(control1.x));
      control2.y = Math.floor(form_equation(q2,end)(control2.x));

      return [control1,control2];
    }

    map_canvas.on('mousedown',function(e) {
        if (penDown === false && selected == 2) {
            penDown = true;
            var pos = getMousePos(e);
            startpos = pos;
            ctx.beginPath();
            ctx.moveTo(pos.x,pos.y);
        }
    });

    map_canvas.on('mousemove',function(e){
        if(penDown === true){
          var pos = getMousePos(e);
          ctx.lineTo(pos.x,pos.y);

          points.push(pos);
          console.log(pos);

          ctx.lineWidth= 7;
          ctx.lineCap ='round';
          ctx.linejoin ="round";
          ctx.strokeStyle = "rgba(0, 153, 255, 0.04)";
          ctx.shadowColor = 'rgba(224,255,255,0.1)';
          ctx.shadowBlur = 30;
          ctx.stroke();
        }
    });

    map_canvas.on('mouseup',function(e) {
        if (penDown === true && selected == 2) {
            ctx.closePath();
            penDown = false;
            var pos = getMousePos(e);
            var thisid = map_data.maxid;
            undo_stack.push({action: "line", id: thisid});
            redo_stack.splice(0, redo_stack.length);

            var controlpoints, quarter1, quarter2;
            if($('#isStraight').bootstrapSwitch("state")){
              controlpoints = [startpos,pos];
            }

            else{

                  quarter1 = points[Math.floor((points.length)/4)];
                  console.log("q1: " + quarter1.x + ", " + quarter1.y);
                  quarter2 = points[Math.floor((points.length)*3/4)];
                  console.log("q2: " + quarter2.x + ", " + quarter2.y);

                  controlpoints = get_control_points(startpos,quarter1,quarter2,pos);
            }

            addElement({type: "line", id: thisid,
                        start: {x: startpos.x / cwidth*1.0, y: startpos.y / cheight*1.0},
                        ctrl1: {x: controlpoints[0].x / cwidth*1.0, y:controlpoints[0].y / cheight*1.0},
                        ctrl2:{x:controlpoints[1].x / cwidth*1.0, y:controlpoints[1].y / cheight*1.0},
                        end:{x: pos.x / cwidth*1.0, y: pos.y / cheight*1.0}});

            points = new Array();
            map_data.maxid += 1;
        }
    });

    var landmarkpos;

    //Area formulas for triangle
    triAF = function(p1,p2,p3){
        return Math.abs(1/2*(p1.x*p2.y+p2.x*p3.y+p3.x*p1.y - p1.y*p2.x - p2.y*p3.x - p3.y*p1.x));
    }
    //Area formula for quadrilaterals
    quadAF = function(p1,p2,p3,p4){
        return Math.abs(1/2*(p1.x*p2.y+p2.x*p3.y+p3.x*p4.y+p4.x*p1.y- p1.y*p2.x - p2.y*p3.x - p3.y*p4.x -p4.y*p1.x));
    }
    //shortest distance to a point formula
    shrtD = function(p1,line){
        return Math.abs(((line.start.y-line.end.y)/(line.end.x-line.start.x))*p1.x+p1.y+((line.start.y-line.end.y)/(line.end.x-line.start.x))*p1.x-p1.y)/(Math.sqrt(Math.pow((line.start.y-line.end.y)/(line.end.x-line.start.x),2)+1));
    }

    map_canvas.click(function(e) {
        //Arbitrary number for rectangle approximation
        var rectApprox = 20;

        //Adding landmarks
        if (selected == 3) {
            var pos = {x: e.pageX, y: e.pageY};
            var adj;
            if ($("#isLandmark").bootstrapSwitch("state")) {
                adj = 300;
                popover = $("#landmarkpopover");
            } else {
                adj = 200;
                popover = $("#pointpopover");
            }
            popover.show();
            if (pos.y > 2 * cheight / 3) {
                popover.css('left', (pos.x + 5) + 'px');
                popover.css('top', (pos.y - adj) + 'px');
            } else {
                popover.css('left', (pos.x + 5) + 'px');
                popover.css('top', (pos.y) + 'px');
            }
            landmarkpos = getMousePos(e);
        }

        // Selecting landmarks
        if (selected == 1) {
            var pagepos = {x: e.pageX, y: e.pageY};
            var pos = getMousePos(e);
            tochangeindex = -1;
            for (var i = 0; i < map_data.landmarks.length; i++) {
                var tl, br;
                center = map_data.landmarks[i].pos;
                tl = {x: center.x * cwidth - 25, y: center.y * cheight - 25};
                br = {x: center.x * cwidth + 25, y: center.y * cheight + 38};

                if (pos.x
 tl.x) {
                    if (pos.y
 tl.y) {
                        tochangeindex = i;
                    }
                }
            }

            if (tochangeindex != -1) {
                $("#pointpopover").hide();
                $("#landmarkpopover").hide();
                var popover;
                if (map_data.landmarks[tochangeindex].img != "startimg" &&
                    map_data.landmarks[tochangeindex].img != "endimg" &&
                    map_data.landmarks[tochangeindex].img != "trainimg" &&
                    map_data.landmarks[tochangeindex].img != "busimg") {
                    popover = $("#landmarkpopover");
                } else {
                    popover = $("#pointpopover");
                }
                popover.show();
                popover.css('left', (pagepos.x + 5) + 'px');
                popover.css('top', (pagepos.y) + 'px');
            }
        }

        //Remove
        if (selected == 4) {
            var p = getMousePos(e);
            var todelete = null;
            for (var i = 0; i < map_data.landmarks.length; i++) {
                var center = map_data.landmarks[i].pos;
                var tl = {x: center.x * cwidth - 25, y: center.y * cheight - 25};
                var br = {x: center.x * cwidth + 25, y: center.y * cheight + 38};

                if (p.x
 tl.x) {
                    if (p.y
 tl.y) {
                        todelete = map_data.landmarks[i];
                    }
                }
            }

            //If there are no landmarks to be removed then look for closest line
            if (todelete == null) {

                var closest = 25;
                for (var i = 0; i < map_data.lines.length; i++) {
                    var line = map_data.lines[i];
                    var bez = new Bezier(line.start.x * cwidth, line.start.y * cheight,
                                        line.ctrl1.x * cwidth, line.ctrl1.y * cheight,
                                        line.ctrl2.x * cwidth, line.ctrl2.y * cheight,
                                        line.end.x * cwidth, line.end.y * cheight);
                    var points = bez.getLUT();
                    for (var j = 0; j < points.length; j++) {
                        var dist = Math.sqrt(Math.pow(p.x - points[j].x, 2) + Math.pow(p.y - points[j].y, 2));
                        if (dist < closest) {
                            closest = dist;
                            todelete = line;
                        }
                    }
                }

            }

            if (todelete != null) {
                undo_stack.push({action:"delete",data:todelete});
                if (todelete.type == "line") {
                    map_data.lines.splice(map_data.lines.indexOf(todelete),1)
                }
                if (todelete.type == "landmark") {
                    map_data.landmarks.splice(map_data.landmarks.indexOf(todelete),1)
                }
                update_canvas(map_data);
            }

        }
    });

    function addElement(elem) {
        if (elem.type == "line") {
            map_data.lines.push(elem);
        }
        if (elem.type == "landmark") {
            map_data.landmarks.push(elem);
        }
        update_canvas(map_data);
    }

    function clear_canvas(canvas, ctx) {
        ctx.clearRect(0, 0, canvas.width(), canvas.height());
    }

    function drawLine(line, ctx) {
        var scaling_factor = cwidth/1000;

        linestartx = line.start.x * cwidth;
        linestarty = line.start.y * cheight;
        linectrl1x = line.ctrl1.x * cwidth;
        linectrl1y = line.ctrl1.y * cheight;
        linectrl2x = line.ctrl2.x * cwidth;
        linectrl2y = line.ctrl2.y * cheight;
        lineendx = line.end.x * cwidth;
        lineendy = line.end.y * cheight;

        ctx.beginPath();
        ctx.moveTo(linestartx, linestarty);
        ctx.bezierCurveTo(linectrl1x,linectrl1y,
          linectrl2x,linectrl2y,lineendx,lineendy);

        ctx.lineWidth= 1 + 6 * scaling_factor;
        ctx.lineCap ='round';
        ctx.linejoin ="round";
        ctx.strokeStyle = "rgba(0, 153, 255, 0.5)";
        ctx.shadowColor = 'rgba(224,255,255,1)';
        ctx.shadowBlur = 10 + 20 * scaling_factor;
        ctx.stroke();
        ctx.closePath();
    }

    function drawLandmark(landmark, ctx) {
        var img = document.getElementById(landmark.img);
        var x = landmark.pos.x * cwidth;
        var y = landmark.pos.y * cheight;
        ctx.drawImage(img, x - 25, y - 25, 50, 50);
        y = y + 40;
        ctx.font = '' + (13) + 'pt Helvetica';
        ctx.textAlign = 'center';
        ctx.fillStyle = 'black';
        ctx.fillText(landmark.landmarkname, x, y);
    }

    function update_canvas(obj) {
        lines = obj.lines;
        landmarks = obj.landmarks;
        clear_canvas(map_canvas, ctx);

        for (var i = 0; i < lines.length; i++) {
            drawLine(lines[i], ctx);
        }
        for (var i = 0; i < landmarks.length; i++) {
            drawLandmark(landmarks[i], ctx);
        }

        if (redo_stack.length == 0) {
            $("#redobutton").attr("disabled", true);
        } else {
            $("#redobutton").attr("disabled", false);
        }
        if (undo_stack.length == 0) {
            $("#undobutton").attr("disabled", true);
        } else {
            $("#undobutton").attr("disabled", false);
        }
    }

    $("#submitbutton").click(function(e) {
        e.preventDefault();
        map_data.name = $("#titleinput").val();
        $("#mapdatainput").val(JSON.stringify(map_data));
        $('#titlehiddeninput').val(map_data.name);
        $("#submitform").submit();
    });

});


text:
/* $NetBSD: fuse.h,v 1.21 2008/08/01 15:54:09 dillo Exp $ */

/*
 * Copyright © 2007 Alistair Crooks.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote
 *    products derived from this software without specific prior written
 *    permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#ifndef FUSE_H_
#define FUSE_H_	20070123

/* set the default version to use for the fuse interface */
/* this value determines the API to be used */
#ifndef FUSE_USE_VERSION
#define FUSE_USE_VERSION	26
#endif

#include <sys/types.h>

#include <puffs.h>
#include <utime.h>

#ifdef __cplusplus
extern "C" {
#endif

struct fuse;
struct fuse_args; /* XXXsupportme */

struct fuse_file_info {
	int32_t		flags;
	uint32_t	fh_old;
	int32_t		writepage;
	uint32_t	direct_io:1;
	uint32_t	keep_cache:1;
	uint32_t	flush:1;
	uint32_t	padding:29;
	uint64_t	fh;
	uint64_t	lock_owner;
};

struct fuse_conn_info {
	uint32_t proto_major;
	uint32_t proto_minor;
	uint32_t async_read;
	uint32_t max_write;
	uint32_t max_readahead;
	uint32_t reserved[27];
};

/* equivalent'ish of puffs_cc */
struct fuse_context {
	struct fuse	*fuse;
	uid_t		uid;
	gid_t		gid;
	pid_t		pid;
	void		*private_data;
};

/**
 * Argument list
 */
struct fuse_args {
	int	argc;
	char	**argv;
	int	allocated;
};

/**
 * Initializer for 'struct fuse_args'
 */
#define FUSE_ARGS_INIT(argc, argv) { argc, argv, 0 }

typedef struct puffs_fuse_dirh *fuse_dirh_t;

typedef int (*fuse_fill_dir_t)(void *, const char *, const struct stat *, off_t);
typedef int (*fuse_dirfil_t)(fuse_dirh_t, const char *, int, ino_t);

#define FUSE_VERSION	26
#define FUSE_MAJOR_VERSION	2
#define FUSE_MINOR_VERSION	6

/*
 * These operations shadow those in puffs_usermount, and are used
 * as a table of callbacks to make when file system requests come
 * in.
 *
 * NOTE: keep same order as fuse
 */
struct fuse_operations {
	int	(*getattr)(const char *, struct stat *);
	int	(*readlink)(const char *, char *, size_t);
	int	(*getdir)(const char *, fuse_dirh_t, fuse_dirfil_t);
	int	(*mknod)(const char *, mode_t, dev_t);
	int	(*mkdir)(const char *, mode_t);
	int	(*unlink)(const char *);
	int	(*rmdir)(const char *);
	int	(*symlink)(const char *, const char *);
	int	(*rename)(const char *, const char *);
	int	(*link)(const char *, const char *);
	int	(*chmod)(const char *, mode_t);
	int	(*chown)(const char *, uid_t, gid_t);
	int	(*truncate)(const char *, off_t);
	int	(*utime)(const char *, struct utimbuf *);
	int	(*open)(const char *, struct fuse_file_info *);
	int	(*read)(const char *, char *, size_t, off_t, struct fuse_file_info *);
	int	(*write)(const char *, const char *, size_t, off_t, struct fuse_file_info *);
	int	(*statfs)(const char *, struct statvfs *);
	int	(*flush)(const char *, struct fuse_file_info *);
	int	(*release)(const char *, struct fuse_file_info *);
	int	(*fsync)(const char *, int, struct fuse_file_info *);
	int	(*setxattr)(const char *, const char *, const char *, size_t, int);
	int	(*getxattr)(const char *, const char *, char *, size_t);
	int	(*listxattr)(const char *, char *, size_t);
	int	(*removexattr)(const char *, const char *);
	int	(*opendir)(const char *, struct fuse_file_info *);
	int	(*readdir)(const char *, void *, fuse_fill_dir_t, off_t, struct fuse_file_info *);
	int	(*releasedir)(const char *, struct fuse_file_info *);
	int	(*fsyncdir)(const char *, int, struct fuse_file_info *);
	void	*(*init)(struct fuse_conn_info *);
	void	(*destroy)(void *);
	int	(*access)(const char *, int);
	int	(*create)(const char *, mode_t, struct fuse_file_info *);
	int	(*ftruncate)(const char *, off_t, struct fuse_file_info *);
	int	(*fgetattr)(const char *, struct stat *, struct fuse_file_info *);
	int	(*lock)(const char *, struct fuse_file_info *, int, struct flock *);
	int	(*utimens)(const char *, const struct timespec *);
	int	(*bmap)(const char *, size_t , uint64_t *);
};

struct fuse_chan *fuse_mount(const char *, struct fuse_args *);
struct fuse *fuse_new(struct fuse_chan *, struct fuse_args *,
	const struct fuse_operations *, size_t, void *);

int fuse_main_real(int, char **, const struct fuse_operations *, size_t, void *);
int fuse_loop(struct fuse *);
struct fuse_context *fuse_get_context(void);
void fuse_exit(struct fuse *);
void fuse_destroy(struct fuse *);

void fuse_unmount(const char *, struct fuse_chan *);

struct fuse *fuse_setup(int, char **, const struct fuse_operations *,
	size_t, char **, int *, int *);
void fuse_teardown(struct fuse *, char *);

#if FUSE_USE_VERSION == 22
#define fuse_unmount fuse_unmount_compat22
#endif

void fuse_unmount_compat22(const char *);

#if FUSE_USE_VERSION >= 26
#define fuse_main(argc, argv, op, arg) \
            fuse_main_real(argc, argv, op, sizeof(*(op)), arg)
#define fuse_setup	fuse_setup26
#else
#define fuse_main(argc, argv, op) \
            fuse_main_real(argc, argv, op, sizeof(*(op)), NULL)
#endif

struct fuse *fuse_setup26(int, char **, const struct fuse_operations *,
	size_t, char **, int *, void *);

#ifdef __cplusplus
}
#endif

#include <fuse_opt.h>

#endif


text:
export = detectIndent;

declare function detectIndent(str: string): detectIndent.IndentInfo;

declare namespace detectIndent {
    interface IndentInfo {
        amount: number;
        type: 'tab' | 'space' | null;
        indent: string;
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>:Done</title>
    <meta name="description" content="" />

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

    <link rel="shortcut icon" href="https://scriptindex.github.io/favicon.ico">

    <link rel="stylesheet" type="text/css" href="//scriptindex.github.io/themes/casper/assets/css/screen.css?v=1584662995032" />
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" />

    <link rel="canonical" href="https://scriptindex.github.io/2017/11/11/Done.html" />
    <meta name="referrer" content="origin" />

    <meta property="og:site_name" content="New Letters" />
    <meta property="og:type" content="article" />
    <meta property="og:title" content=":Done" />
    <meta property="og:description" content="Your lucky day. Bring me a bouquet of camomile so that I may delicately pluck its feathers tonight. -scriptindex, 11/11/17 sat" />
    <meta property="og:url" content="https://scriptindex.github.io/2017/11/11/Done.html" />
    <meta property="article:published_time" content="2017-11-11T00:00:00.000Z" />
    <meta property="article:tag" content="poetry" />

    <meta name="twitter:card" content="summary" />
    <meta name="twitter:title" content=":Done" />
    <meta name="twitter:description" content="Your lucky day. Bring me a bouquet of camomile so that I may delicately pluck its feathers tonight. -scriptindex, 11/11/17 sat" />
    <meta name="twitter:url" content="https://scriptindex.github.io/2017/11/11/Done.html" />

    <meta name="generator" content="HubPress" />
    <link rel="alternate" type="application/rss+xml" title="New Letters" href="https://scriptindex.github.io/rss/" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.10.0/styles/atom-one-dark.min.css">

:Done

                <time class="post-date" datetime="2017-11-11">11 November 2017</time>  on poetry

Your lucky day.

Bring me a bouquet of camomile

so that I may delicately pluck its feathers

tonight.

-scriptindex, 11/11/17 sat

                scriptindex's Picture

scriptindex

starting something new

Share this post

                    Twitter

                    Facebook

                    Google+

          Please enable JavaScript to view the comments powered by Disqus.
          comments powered by Disqus

New Letters © 2020

Proudly published with HubPress


text:
"""The image module provides basic functions for working with images in nipy.
Functions are provided to load, save and create image objects, along with
iterators to easily slice through volumes.

    load : load an image from a file

    save : save an image to a file

    fromarray : create an image from a numpy array

Examples
--------
See documentation for load and save functions for 'working' examples.

"""

import os

import numpy as np

import nipy.io.imageformats as formats

from nipy.core.api import Image, is_image
from nifti_ref import (coordmap_from_affine, coerce_coordmap,
                       ijk_from_fps, fps_from_ijk)

def load(filename):
    """Load an image from the given filename.

    Parameters
    ----------
    filename : string
        Should resolve to a complete filename path.

    Returns
    -------
    image : An `Image` object
        If successful, a new `Image` object is returned.

    See Also
    --------
    save_image : function for saving images
    fromarray : function for creating images from numpy arrays

    Examples
    --------

    >>> from nipy.io.api import load_image
    >>> from nipy.testing import anatfile
    >>> img = load_image(anatfile)
    >>> img.shape
    (33, 41, 25)
    """
    img = formats.load(filename)
    aff = img.get_affine()
    shape = img.get_shape()
    hdr = img.get_header()
    # Get info from NIFTI header, if present, to tell which axes are
    # which.  This is a NIFTI-specific kludge, that might be abstracted
    # out into the image backend in a general way.  Similarly for
    # getting zooms
    try:
        fps = hdr.get_dim_info()
    except (TypeError, AttributeError):
        fps = (None, None, None)
    ijk = ijk_from_fps(fps)
    try:
        zooms = hdr.get_zooms()
    except AttributeError:
        zooms = np.ones(len(shape))
    aff = _match_affine(aff, len(shape), zooms)
    coordmap = coordmap_from_affine(aff, ijk)
    img = Image(img.get_data(), coordmap)
    img.header = hdr
    return img

def _match_affine(aff, ndim, zooms=None):
    ''' Fill or prune affine to given number of dimensions

    >>> aff = np.arange(16).reshape(4,4)
    >>> _match_affine(aff, 3)
    array([[ 0,  1,  2,  3],
           [ 4,  5,  6,  7],
           [ 8,  9, 10, 11],
           [12, 13, 14, 15]])
    >>> _match_affine(aff, 2)
    array([[ 0.,  1.,  3.],
           [ 4.,  5.,  7.],
           [ 0.,  0.,  1.]])
    >>> _match_affine(aff, 4)
    array([[  0.,   1.,   2.,   0.,   3.],
           [  4.,   5.,   6.,   0.,   7.],
           [  8.,   9.,  10.,   0.,  11.],
           [  0.,   0.,   0.,   1.,   0.],
           [  0.,   0.,   0.,   0.,   1.]])
    >>> aff = np.arange(9).reshape(3,3)
    >>> _match_affine(aff, 2)
    array([[0, 1, 2],
           [3, 4, 5],
           [6, 7, 8]])
    '''
    if aff.shape[0] != aff.shape[1]:
        raise ValueError('Need square affine')
    aff_dim = aff.shape[0] - 1
    if ndim == aff_dim:
        return aff
    aff_diag = np.ones(ndim+1)
    if not zooms is None:
        n = min(len(zooms), ndim)
        aff_diag[:n] = zooms[:n]
    mod_aff = np.diag(aff_diag)
    n = min(ndim, aff_dim)
    # rotations zooms shears
    mod_aff[:n,:n] = aff[:n,:n]
    # translations
    mod_aff[:n,-1] = aff[:n,-1]
    return mod_aff

def save(img, filename, dtype=None):
    """Write the image to a file.

    Parameters
    ----------
    img : An `Image` object
    filename : string
        Should be a valid filename.

    Returns
    -------
    image : An `Image` object

    See Also
    --------
    load_image : function for loading images
    fromarray : function for creating images from numpy arrays

    Examples
    --------

    >>> import os
    >>> import numpy as np
    >>> from tempfile import mkstemp
    >>> from nipy.core.api import fromarray
    >>> from nipy.io.api import save_image
    >>> data = np.zeros((91,109,91), dtype=np.uint8)
    >>> img = fromarray(data, 'kji', 'zxy')
    >>> fd, fname = mkstemp(suffix='.nii.gz')
    >>> saved_img = save_image(img, fname)
    >>> saved_img.shape
    (91, 109, 91)
    >>> os.unlink(fname)
    >>> fd, fname = mkstemp(suffix='.img.gz')
    >>> saved_img = save_image(img, fname)
    >>> saved_img.shape
    (91, 109, 91)
    >>> os.unlink(fname)
    >>> fname = 'test.mnc'
    >>> saved_image = save_image(img, fname)
    Traceback (most recent call last):
       ...
    ValueError: Cannot save file type "minc"

    Notes
    -----
    Filetype is determined by the file extension in 'filename'.  Currently the
    following filetypes are supported:

    * Nifti single file : ['.nii', '.nii.gz']
    * Nifti file pair : ['.hdr', '.hdr.gz']
    * Analyze file pair : ['.img', 'img.gz']
    """
    # Get header from image
    try:
        original_hdr = img.header
    except AttributeError:
        original_hdr = None
    # Make NIFTI compatible version of image
    newcmap, order = coerce_coordmap(img.coordmap)
    Fimg = Image(np.transpose(np.asarray(img), order), newcmap)
    # Expand or contract affine to 4x4 (3 dimensions)
    rzs = Fimg.affine[:-1,:-1]
    zooms = np.sqrt(np.sum(rzs * rzs, axis=0))
    aff = _match_affine(Fimg.affine, 3, zooms)
    ftype = _type_from_filename(filename)
    if ftype.startswith('nifti1'):
        klass = formats.Nifti1Image
    elif ftype == 'analyze':
        klass = formats.Spm2AnalyzeImage
    else:
        raise ValueError('Cannot save file type "%s"' % ftype)
    # make new image
    out_img = klass(data=np.asarray(Fimg),
                    affine=aff,
                    header=original_hdr)
    hdr = out_img.get_header()
    # work out phase, freqency, slice from coordmap names
    ijk = newcmap.input_coords.coord_names
    fps = fps_from_ijk(ijk)
    # put fps into header if possible
    try:
        hdr.set_dim_info(*fps)
    except AttributeError:
        pass
    # Set zooms
    hdr.set_zooms(zooms)
    # save to disk
    out_img.to_filename(filename)
    return Fimg

def _type_from_filename(filename):
    ''' Return image type determined from filename

    Filetype is determined by the file extension in 'filename'.
    Currently the following filetypes are supported:

    * Nifti single file : ['.nii', '.nii.gz']
    * Nifti file pair : ['.hdr', '.hdr.gz']
    * Analyze file pair : ['.img', '.img.gz']

    >>> _type_from_filename('test.nii')
    'nifti1single'
    >>> _type_from_filename('test')
    'nifti1single'
    >>> _type_from_filename('test.hdr')
    'nifti1pair'
    >>> _type_from_filename('test.hdr.gz')
    'nifti1pair'
    >>> _type_from_filename('test.img.gz')
    'analyze'
    >>> _type_from_filename('test.mnc')
    'minc'
    '''
    if filename.endswith('.gz'):
        filename = filename[:-3]
    elif filename.endswith('.bz2'):
        filename = filename[:-4]
    _, ext = os.path.splitext(filename)
    if ext in ('', '.nii'):
        return 'nifti1single'
    if ext == '.hdr':
        return 'nifti1pair'
    if ext == '.img':
        return 'analyze'
    if ext == '.mnc':
        return 'minc'
    raise ValueError('Strange file extension "%s"' % ext)

def as_image(image_input):
    ''' Load image from filename or pass through image instance

    Parameters
    ----------
    image_input : str or Image instance
       image or string filename of image.  If a string, load image and
       return.  If an image, pass through without modification

    Returns
    -------
    img : Image or Image-like instance
       Input object if `image_input` seemed to be an image, loaded Image
       object if `image_input` was a string.

    Raises
    ------
    TypeError : if neither string nor image-like passed

    Examples
    --------
    >>> from nipy.testing import anatfile
    >>> from nipy.io.api import load_image
    >>> img = as_image(anatfile)
    >>> img2 = as_image(img)
    >>> img2 is img
    True
    '''
    if is_image(image_input):
        return image_input
    if isinstance(image_input, basestring):
        return load(image_input)
    raise TypeError('Expecting an image-like object or filename string')


text:
package xyz.brassgoggledcoders.steamagerevolution.multiblocks.furnace.blocks;

import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import xyz.brassgoggledcoders.steamagerevolution.machinesystem.multiblock.BlockMultiblockBase;
import xyz.brassgoggledcoders.steamagerevolution.multiblocks.furnace.tileentities.TileEntityFurnaceCasing;

public class BlockFurnaceCasing extends BlockMultiblockBase<TileEntityFurnaceCasing> {

    public BlockFurnaceCasing(Material material, String name) {
        super(material, name);
    }

    @Override
    public Class<? extends TileEntity> getTileEntityClass() {
        return TileEntityFurnaceCasing.class;
    }

    @Override
    public TileEntity createTileEntity(World world, IBlockState blockState) {
        return new TileEntityFurnaceCasing();
    }

}


text:
package sagemakerruntime

import (
	"github.com/aws/aws-sdk-go/private/protocol"
)

const (

	// ErrCodeInternalDependencyException for service response error code
	// "InternalDependencyException".
	//
	// Your request caused an exception with an internal dependency. Contact customer
	// support.
	ErrCodeInternalDependencyException = "InternalDependencyException"

	// ErrCodeInternalFailure for service response error code
	// "InternalFailure".
	//
	// An internal failure occurred.
	ErrCodeInternalFailure = "InternalFailure"

	// ErrCodeModelError for service response error code
	// "ModelError".
	//
	// Model (owned by the customer in the container) returned 4xx or 5xx error
	// code.
	ErrCodeModelError = "ModelError"

	// ErrCodeModelNotReadyException for service response error code
	// "ModelNotReadyException".
	//
	// Either a serverless endpoint variant's resources are still being provisioned,
	// or a multi-model endpoint is still downloading or loading the target model.
	// Wait and try your request again.
	ErrCodeModelNotReadyException = "ModelNotReadyException"

	// ErrCodeServiceUnavailable for service response error code
	// "ServiceUnavailable".
	//
	// The service is unavailable. Try your call again.
	ErrCodeServiceUnavailable = "ServiceUnavailable"

	// ErrCodeValidationError for service response error code
	// "ValidationError".
	//
	// Inspect your request and try again.
	ErrCodeValidationError = "ValidationError"
)

var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{
	"InternalDependencyException": newErrorInternalDependencyException,
	"InternalFailure":             newErrorInternalFailure,
	"ModelError":                  newErrorModelError,
	"ModelNotReadyException":      newErrorModelNotReadyException,
	"ServiceUnavailable":          newErrorServiceUnavailable,
	"ValidationError":             newErrorValidationError,
}


text:
namespace WebKit {
class WebData;
struct WebURLError;
class WebURLLoaderClient;
class WebURLRequest;
class WebURLResponse;
}

class WebURLLoaderMockFactory;

// A simple class for mocking WebURLLoader.
// If the WebURLLoaderMockFactory it is associated with has been configured to
// mock the request it gets, it serves the mocked resource.  Otherwise it just
// forwards it to the default loader.
class WebURLLoaderMock : public WebKit::WebURLLoader {
 public:
  // This object becomes the owner of |default_loader|.
  WebURLLoaderMock(WebURLLoaderMockFactory* factory,
                   WebKit::WebURLLoader* default_loader);
  virtual ~WebURLLoaderMock();

  // Simulates the asynchronous request being served.
  void ServeAsynchronousRequest(const WebKit::WebURLResponse& response,
                                const WebKit::WebData& data,
                                const WebKit::WebURLError& error);

  // Simulates the redirect being served.
  WebKit::WebURLRequest ServeRedirect(
      const WebKit::WebURLResponse& redirectResponse);

  // WebURLLoader methods:
  virtual void loadSynchronously(const WebKit::WebURLRequest& request,
                                 WebKit::WebURLResponse& response,
                                 WebKit::WebURLError& error,
                                 WebKit::WebData& data);
  virtual void loadAsynchronously(const WebKit::WebURLRequest& request,
                                  WebKit::WebURLLoaderClient* client);
  virtual void cancel();
  virtual void setDefersLoading(bool defer);

  bool isDeferred() { return is_deferred_; }

 private:
  WebURLLoaderMockFactory* factory_;
  WebKit::WebURLLoaderClient* client_;
  scoped_ptr<WebKit::WebURLLoader> default_loader_;
  bool using_default_loader_;
  bool is_deferred_;

  DISALLOW_COPY_AND_ASSIGN(WebURLLoaderMock);
};

#endif  // CONTENT_TEST_WEBURL_LOADER_MOCK_H_


text:
const router = require('express').Router();
const ensureRole = require('../auth/ensure-role');
const bodyParser = require('body-parser').json();
const List = require('../models/list-schema.js');

router
    .get('/', (req, res, next) => {
        List.find()
            .lean()
            .populate('item')
            .then(lists => res.send(lists))
            .catch(next);
    })

.get('/:id', (req, res, next) => {
    List.findById(req.params.id)
        .lean()
        .populate('item')
        .then(list => {
            if (!list) {
                res.status(404).send({ error: `Id ${req.params.id} Not Found` });
            } else {
                res.send(list);
            }
        })
        .catch(next);
})

.post('/', ensureRole('owner'), bodyParser, (req, res, next) => {
    new List(req.body).save()
        .then(list => res.send(list))
        .catch(next);
})

.post('/:id/additem', ensureRole('owner'), bodyParser, (req, res, next) => {
    return List.findById(req.params.id)
        .then(list => {
            list.item.push(req.body._id);
            return list.save();
        })
        .then(list => {
            res.send(list);
        })
        .catch(next);
})

.post('/:id/removeitem', ensureRole('owner'), bodyParser, (req, res, next) => {
    return List.findById(req.params.id)
        .then(list => {
            const newList = list.item.filter(x => {
                if (x != req.body.itemID) {
                    return x;
                } else {
                    return null;
                }
            });
            list.item = newList;
            return list.save();
        })
        .then(list => res.send(list))
        .catch(next);
})

.delete('/:id', ensureRole('owner'), (req, res, next) => {
    List.findByIdAndRemove(req.params.id)
        .then(deleted => res.send({ deleted: !!deleted }))
        .catch(next);
});

module.exports = router;


text:
# -*- encoding : utf-8 -*-
require 'spree_core'
require 'spree_safety_stock_hooks'

module SpreeSafetyStock
  class Engine < Rails::Engine

    config.autoload_paths += %W(#{config.root}/lib)

    def self.activate
      Dir.glob(File.join(File.dirname(__FILE__), "../app/**/*_decorator*.rb")) do |c|
        Rails.env.production? ? require(c) : load(c)
      end
    end

    config.to_prepare &method(:activate).to_proc
  end
end


text:
declare
  l_output_data       ut_varchar2_list;
  l_packages_executed integer := 0;
begin
  --act
  select * bulk collect into l_output_data
    from table(ut.run(ut_teamcity_reporter()));

  for i in 1 .. l_output_data.count loop
    if  l_output_data(i) like '%Finished %''test\_package\_1''%' escape '\'
    or l_output_data(i) like '%Finished %''test_package_2''%'
    or l_output_data(i) like '%Finished %''test_package_3''%' then
      l_packages_executed := l_packages_executed + 1;
    end if;
  end loop;

  if l_packages_executed = 3 then
    :test_result := ut_utils.tr_success;
  else
    for i in 1 .. l_output_data.count loop
      dbms_output.put_line(l_output_data(i));
    end loop;
    dbms_output.put_line('Failed: not all packages were found in the outputs. Expected 3, got '||l_packages_executed);
  end if;
end;
/


text:
<B>obj2bin.pl</B> is a PDP-11 object file translator / linker, transforming an .obj file as output from macro11 into an absolute binary load image file (.bin) or other useful formats (.hex).

If run with no options, it prints a usage screen:

```
obj2bin.pl v2.1 by Don North (perl 5.03)
Usage: ./obj2bin.pl [options...] arguments
       --help                  output manpage and exit
       --debug                 enable debug mode
       --verbose               verbose status reporting
       --boot                  M9312 boot prom .hex
       --console               M9312 console/diagnostic prom .hex
       --binary                binary program load image .bin [default]
       --ascii                 ascii m9312 program load image .txt
       --rt11                  read .obj files in RT11 format
       --rsx11                 read .obj files in RSX11 format [default]
       --bytes=N               bytes per block on output hex format
       --nocrc                 inhibit output of CRC-16 in hex format
       --logfile=LOGFILE       logging message file
       --outfile=OUTFILE       output .hex/.txt/.bin file
       OBJFILE...              macro11 object .obj file(s)
Aborted due to command line errors.
```

If run with the --help option it prints a longer manual page:

```
NAME
    obj2bin.pl - Convert a Macro-11 program image to PROM/load format

SYNOPSIS
    obj2bin.pl [--help] [--debug] [--verbose] [--boot] [--console] [--binary]
    [--ascii] [--rt11] [--rsx11] [--bytes=N] [--nocrc] [--logfile=LOGFILE]
    --outfile=BINFILE OBJFILE

DESCRIPTION
    Converts a Macro-11 object files to various output formats, including
    M9312 boot and console PROM, straight binary records, ASCII format for
    M9312 console load commands, and loadable absolute binary program images
    (.BIN) files.

    Multiple .psect/.asect ops are supported, as well as all local
    (non-global) relocation directory entries.

    Supports either RT-11 or RSX-11 format object files.

OPTIONS
    The following options are available:

    --help
        Output this manpage and exit the program.

    --debug
        Enable debug mode; print input file records as parsed.

    --verbose
        Verbose status; output status messages during processing.

    --boot
        Generate a hex PROM file image suitable for programming into an M9312
        boot prom (512x4 geometry, only low half used).

    --console
        Generate a hex PROM file image suitable for programming into an M9312
        console/diagnostic prom (1024x4 geometry).

    --ascii
        Generate a a sequence of 'L addr' / 'D data' commands for downloading
        a program via a terminal emulator thru the M9312 user command
        interface. Suitable only for really small test programs.

    --binary
        Generate binary format load records of the program image (paper tape
        format) for loading into SIMH or compatible simulators. These files
        can also be copied onto XXDP filesystems to generate runnable program
        images (used to write custom diaqnostics).

        Binary format is the default if no other option is specified. If more
        than one option is specified the last one takes effect.

    --rt11
        Read input object files in RT-11 format.

    --rsx11
        Read input object files in RSX-11 format.

        RSX-11 object file format is the default if no other option is
        specified. If more than one option is specified the last one takes
        effect.

    --bytes=N
        For hex format output files, output N bytes per line (default 16).

    --nocrc
        For hex format output files, don't automatically stuff the computed
        CRC-16 as the last word in the ROM.

    --logfile=FILENAME
        Generate debug output into this file.

    --outfile=FILENAME
        Output binary file in format selected by user option.

    OBJFILE...
        Input object file(s) in .obj format.

ERRORS
    The following diagnostic error messages can be produced on STDERR. The
    meaning should be fairly self explanatory.

    "Aborted due to command line errors" -- bad option or missing file(s)

    "Can't open input file '$file'" -- bad filename or unreadable file

    "Error: Improper object file format (1)" -- valid RT-11 record must start
    with 0x01

    "Error: Improper object file format (2)" -- second RT-11 byte must be 0x00

    "Error: Improper object file format (3)" -- third byte is low byte of
    record length

    "Error: Improper object file format (4)" -- fourth byte is high byte of
    record length

    "Error: Improper object file format (5)" -- bytes five thru end-1 are data
    bytes

    "Error: Improper object file format (6)" -- last RT-11 byte is checksum

    "Error: Bad checksum exp=0x%02X rcv=0x%02X" -- compare rcv'ed checksum vs
    exp'ed checksum

EXAMPLES
    Some examples of common usage:

      obj2bin.pl --help

      obj2bin.pl --verbose --boot --out 23-751A9.hex 23-751A9.obj

      obj2bin.pl --verbose --binary --rt11 --out memtest.bin memtest.obj

      obj2bin.pl --verbose --binary --rsx11 --out prftst.bin prftst.obj mac/printf.obj

AUTHOR
    Don North - donorth <ak6dn _at_ mindspring _dot_ com>

HISTORY
    Modification history:

      2005-05-05 v1.0  donorth - Initial version.
      2016-01-15 v1.1  donorth - Added RLD(IR) processing, moved sub's to end.
      2016-01-18 v1.2  donorth - Added GSD processing, improved debug output.
      2016-01-20 v1.3  donorth - Initial support for linking multiple PSECTs.
      2016-01-22 v1.4  donorth - Added objfile/outfile/logfile switches vs stdio.
      2016-01-28 v1.5  donorth - Added RLD processing, especially complex.
      2017-04-01 v1.9  donorth - Renamed from obj2hex.pl to obj2bin.pl
      2017-05-04 v1.95 donorth - Updated capability to read multiple input .obj files.
      2020-03-06 v2.0  donorth - Updated help documentation and README.md file.
      2020-03-10 v2.1  donorth - Broke down and added RSX-11 input format option.

```


text:
package com.plivo.api.models.number;

public enum NumberType {
  FIXED, MOBILE, ANY, LOCAL, TOLLFREE;
}


text:
ACCEPTED

#### According to
Interim Register of Marine and Nonmarine Genera

#### Published in
in [Hubei Province Bur. of Geol. Sanxia Stratigraphical Res. Gp] Xiadong diqu zhendanji zhi erdieji diceng gushengwu.

#### Original name
null

### Remarks
null


text:
package com.github.sandor_balazs.nosql_java.web.rest;

import com.github.sandor_balazs.nosql_java.AbstractCassandraTest;
import com.github.sandor_balazs.nosql_java.Application;
import com.github.sandor_balazs.nosql_java.domain.Milestone;
import com.github.sandor_balazs.nosql_java.repository.MilestoneRepository;
import com.github.sandor_balazs.nosql_java.service.MilestoneService;
import com.github.sandor_balazs.nosql_java.web.rest.dto.MilestoneDTO;
import com.github.sandor_balazs.nosql_java.web.rest.mapper.MilestoneMapper;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.hamcrest.Matchers.hasItem;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.util.List;
import java.util.UUID;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

/**
 * Test class for the MilestoneResource REST controller.
 *
 * @see MilestoneResource
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@IntegrationTest
public class MilestoneResourceIntTest extends AbstractCassandraTest {

    private static final String DEFAULT_NAME = "AAAAA";
    private static final String UPDATED_NAME = "BBBBB";

    private static final Integer DEFAULT_APP_ORDER = 1;
    private static final Integer UPDATED_APP_ORDER = 2;

    @Inject
    private MilestoneRepository milestoneRepository;

    @Inject
    private MilestoneMapper milestoneMapper;

    @Inject
    private MilestoneService milestoneService;

    @Inject
    private MappingJackson2HttpMessageConverter jacksonMessageConverter;

    @Inject
    private PageableHandlerMethodArgumentResolver pageableArgumentResolver;

    private MockMvc restMilestoneMockMvc;

    private Milestone milestone;

    @PostConstruct
    public void setup() {
        MockitoAnnotations.initMocks(this);
        MilestoneResource milestoneResource = new MilestoneResource();
        ReflectionTestUtils.setField(milestoneResource, "milestoneService", milestoneService);
        ReflectionTestUtils.setField(milestoneResource, "milestoneMapper", milestoneMapper);
        this.restMilestoneMockMvc = MockMvcBuilders.standaloneSetup(milestoneResource)
            .setCustomArgumentResolvers(pageableArgumentResolver)
            .setMessageConverters(jacksonMessageConverter).build();
    }

    @Before
    public void initTest() {
        milestoneRepository.deleteAll();
        milestone = new Milestone();
        milestone.setName(DEFAULT_NAME);
        milestone.setAppOrder(DEFAULT_APP_ORDER);
    }

    @Test
    public void createMilestone() throws Exception {
        int databaseSizeBeforeCreate = milestoneRepository.findAll().size();

        // Create the Milestone
        MilestoneDTO milestoneDTO = milestoneMapper.milestoneToMilestoneDTO(milestone);

        restMilestoneMockMvc.perform(post("/api/milestones")
                .contentType(TestUtil.APPLICATION_JSON_UTF8)
                .content(TestUtil.convertObjectToJsonBytes(milestoneDTO)))
                .andExpect(status().isCreated());

        // Validate the Milestone in the database
        List<Milestone> milestones = milestoneRepository.findAll();
        assertThat(milestones).hasSize(databaseSizeBeforeCreate + 1);
        Milestone testMilestone = milestones.get(milestones.size() - 1);
        assertThat(testMilestone.getName()).isEqualTo(DEFAULT_NAME);
        assertThat(testMilestone.getAppOrder()).isEqualTo(DEFAULT_APP_ORDER);
    }

    @Test
    public void getAllMilestones() throws Exception {
        // Initialize the database
        milestoneRepository.save(milestone);

        // Get all the milestones
        restMilestoneMockMvc.perform(get("/api/milestones?sort=id,desc"))
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON))
                .andExpect(jsonPath("$.[*].id").value(hasItem(milestone.getId().toString())))
                .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME.toString())))
                .andExpect(jsonPath("$.[*].appOrder").value(hasItem(DEFAULT_APP_ORDER)));
    }

    @Test
    public void getMilestone() throws Exception {
        // Initialize the database
        milestoneRepository.save(milestone);

        // Get the milestone
        restMilestoneMockMvc.perform(get("/api/milestones/{id}", milestone.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON))
            .andExpect(jsonPath("$.id").value(milestone.getId().toString()))
            .andExpect(jsonPath("$.name").value(DEFAULT_NAME.toString()))
            .andExpect(jsonPath("$.appOrder").value(DEFAULT_APP_ORDER));
    }

    @Test
    public void getNonExistingMilestone() throws Exception {
        // Get the milestone
        restMilestoneMockMvc.perform(get("/api/milestones/{id}", UUID.randomUUID().toString()))
                .andExpect(status().isNotFound());
    }

    @Test
    public void updateMilestone() throws Exception {
        // Initialize the database
        milestoneRepository.save(milestone);

		int databaseSizeBeforeUpdate = milestoneRepository.findAll().size();

        // Update the milestone
        milestone.setName(UPDATED_NAME);
        milestone.setAppOrder(UPDATED_APP_ORDER);
        MilestoneDTO milestoneDTO = milestoneMapper.milestoneToMilestoneDTO(milestone);

        restMilestoneMockMvc.perform(put("/api/milestones")
                .contentType(TestUtil.APPLICATION_JSON_UTF8)
                .content(TestUtil.convertObjectToJsonBytes(milestoneDTO)))
                .andExpect(status().isOk());

        // Validate the Milestone in the database
        List<Milestone> milestones = milestoneRepository.findAll();
        assertThat(milestones).hasSize(databaseSizeBeforeUpdate);
        Milestone testMilestone = milestones.get(milestones.size() - 1);
        assertThat(testMilestone.getName()).isEqualTo(UPDATED_NAME);
        assertThat(testMilestone.getAppOrder()).isEqualTo(UPDATED_APP_ORDER);
    }

    @Test
    public void deleteMilestone() throws Exception {
        // Initialize the database
        milestoneRepository.save(milestone);

		int databaseSizeBeforeDelete = milestoneRepository.findAll().size();

        // Get the milestone
        restMilestoneMockMvc.perform(delete("/api/milestones/{id}", milestone.getId())
                .accept(TestUtil.APPLICATION_JSON_UTF8))
                .andExpect(status().isOk());

        // Validate the database is empty
        List<Milestone> milestones = milestoneRepository.findAll();
        assertThat(milestones).hasSize(databaseSizeBeforeDelete - 1);
    }
}


text:
require 'js_regex'

class Regexp
  def as_json(*)
    JsRegex.new(self).to_h
  end

  def to_json(options = nil)
    as_json(options)
  end

  def encode_json(_encoder)
    inspect
  end
end


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2018] EMBL-European Bioinformatics Institute

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

package EnsEMBL::Users::Command::Account::Group::Delete;

### Command module to delete a group
### @author hr5

use strict;
use warnings;

use EnsEMBL::Users::Messages qw(MESSAGE_UNKNOWN_ERROR MESSAGE_GROUP_NOT_FOUND);

use parent qw(EnsEMBL::Users::Command::Account);

sub csrf_safe_process {
  my $self        = shift;
  my $object      = $self->object;
  my $hub         = $self->hub;
  my $user        = $hub->user;
  my $return_url;

  if (my $group_id = $hub->param('id')) {

    if (my $membership = $object->fetch_accessible_membership_for_user($user->rose_object, $group_id, {
      'with_objects'  => ['group', 'group.memberships', 'group.records'],
      'query'         => ['level' => 'administrator']
    })) {

      my $group = $membership->group;

      # do we need to notify anyone?
      my @curious_admins  = map {$_->user_id ne $user->user_id && $_->notify_edit && $_->user || ()} @{$group->admin_memberships};
      my $group_name      = $group->name;

      if ($group->delete('cascade' => 1)) {

        $self->mailer->send_group_deletion_notification_email(\@curious_admins, $group_name);
        $return_url = {'action' => 'Groups', 'function' => ''};

      } else {

        $return_url = {'action' => 'Groups', 'function' => 'View', 'id' => $group_id, 'err' => MESSAGE_UNKNOWN_ERROR};
      }
    }
  }

  return $self->ajax_redirect($hub->url($return_url || {'action' => 'Groups', 'function' => '', 'err' => MESSAGE_GROUP_NOT_FOUND}));
}

1;


text:
<?php

namespace OpenClassrooms\Bundle\DoctrineCacheExtensionBundle\Services\DataCollector;

use OpenClassrooms\DoctrineCacheExtension\CacheProviderDecoratorFactory;
use Symfony\Component\Stopwatch\Stopwatch;

/**
 * @author Romain Kuzniak <romain.kuzniak@openclassrooms.com>
 */
class DebugCacheProviderDecoratorFactory extends CacheProviderDecoratorFactory
{
    /**
     * @var Stopwatch
     */
    private static $stopwatch;

    /**
     * {@inheritdoc}
     */
    public static function create($type, ...$args)
    {
        return new DebugCacheProviderDecorator(parent::create($type, ...$args), self::$stopwatch);
    }

    public static function setStopwatch(Stopwatch $stopwatch)
    {
        self::$stopwatch = $stopwatch;
    }
}


text:
var path = require('path');

module.exports = {
  cache: false,
  entry: {
    bundle: './test'
  },
  output: {
    path: path.join(__dirname, 'test', 'dist'),
    publicPath: 'test/dist/',
    filename: '[name].js',
    chunkFilename: '[chunkhash].js'
  },
  module: {
    loaders: [
      { test: /\.json$/, loader: "json-loader" },
      { test: /_test\.js$/, loader: "webpack-espower-loader" }
    ],
    // to avoid warning by power-assert-formatter
    exprContextCritical: false
  }
};


text:
package org.tensorics.core.resolve.domain;

import static java.util.Objects.requireNonNull;

import java.util.Optional;

import org.tensorics.core.tree.domain.Expression;
import org.tensorics.core.tree.domain.ResolvingContext;

public class DetailedExpressionResult<R, E extends Expression<R>> {

    private final E rootExpression;
    private final R value;
    private final ResolvingContext context;

    protected DetailedExpressionResult(E rootExpression, R value, ResolvingContext context) {
        super();
        this.rootExpression = requireNonNull(rootExpression, "rootExpression must not be null");
        this.value = requireNonNull(value, "value must not be null");
        this.context = requireNonNull(context, "context must not be null");
    }

    public static final <R, E extends Expression<R>> DetailedExpressionResult<R, E> of(E rootExpression, R value,
            ResolvingContext context) {
        return new DetailedExpressionResult<>(rootExpression, value, context);
    }

    public R value() {
        return value;
    }

    public <T> Optional<T> resolvedValueOf(Expression<T> expression) {
        requireNonNull(expression, "expression must not be null.");
        if (context.resolves(expression)) {
            return Optional.of(context.resolvedValueOf(expression));
        }
        return Optional.empty();
    }

    public E rootExpression() {
        return this.rootExpression;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((context == null) ? 0 : context.hashCode());
        result = prime * result + ((rootExpression == null) ? 0 : rootExpression.hashCode());
        result = prime * result + ((value == null) ? 0 : value.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        DetailedExpressionResult<?, ?> other = (DetailedExpressionResult<?, ?>) obj;
        if (context == null) {
            if (other.context != null) {
                return false;
            }
        } else if (!context.equals(other.context)) {
            return false;
        }
        if (rootExpression == null) {
            if (other.rootExpression != null) {
                return false;
            }
        } else if (!rootExpression.equals(other.rootExpression)) {
            return false;
        }
        if (value == null) {
            if (other.value != null) {
                return false;
            }
        } else if (!value.equals(other.value)) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "DetailedExpressionResult [rootExpression=" + rootExpression + ", value=" + value + ", context="
                + context + "]";
    }

}


text:
package http

// Encoding to use for HTTP transport.
type Encoding int32

const (
	// Default
	Default Encoding = iota
	// BinaryV01 is Binary CloudEvents spec v0.1.
	BinaryV01
	// StructuredV01 is Structured CloudEvents spec v0.1.
	StructuredV01
	// BinaryV02 is Binary CloudEvents spec v0.2.
	BinaryV02
	// StructuredV02 is Structured CloudEvents spec v0.2.
	StructuredV02
	// BinaryV03 is Binary CloudEvents spec v0.3.
	BinaryV03
	// StructuredV03 is Structured CloudEvents spec v0.3.
	StructuredV03
	// BatchedV03 is Batched CloudEvents spec v0.3.
	BatchedV03
	// Unknown is unknown.
	Unknown
)

// String pretty-prints the encoding as a string.
func (e Encoding) String() string {
	switch e {
	case Default:
		return "Default Encoding " + e.Version()

	// Binary
	case BinaryV01:
		fallthrough
	case BinaryV02:
		fallthrough
	case BinaryV03:
		return "Binary Encoding " + e.Version()

	// Structured
	case StructuredV01:
		fallthrough
	case StructuredV02:
		fallthrough
	case StructuredV03:
		return "Structured Encoding " + e.Version()

	// Batched
	case BatchedV03:
		return "Batched Encoding " + e.Version()

	default:
		return "Unknown Encoding"
	}
}

// Version pretty-prints the encoding version as a string.
func (e Encoding) Version() string {
	switch e {
	case Default:
		return "Default"

	// Version 0.1
	case BinaryV01:
		fallthrough
	case StructuredV01:
		return "v0.1"

	// Version 0.2
	case BinaryV02:
		fallthrough
	case StructuredV02:
		return "v0.2"

	// Version 0.3
	case BinaryV03:
		fallthrough
	case StructuredV03:
		fallthrough
	case BatchedV03:
		return "v0.3"

	// Unknown
	default:
		return "Unknown"
	}
}

// Codec creates a structured string to represent the the codec version.
func (e Encoding) Codec() string {
	switch e {
	case Default:
		return "default"

	// Version 0.1
	case BinaryV01:
		return "binary/v0.1"
	case StructuredV01:
		return "structured/v0.1"

	// Version 0.2
	case BinaryV02:
		return "binary/v0.3"
	case StructuredV02:
		return "structured/v0.2"

	// Version 0.3
	case BinaryV03:
		return "binary/v0.3"
	case StructuredV03:
		return "structured/v0.3"
	case BatchedV03:
		return "batched/v0.3"

	// Unknown
	default:
		return "unknown"
	}
}


text:
var create = require('../src/plugman/create'),
    Q = require('q'),
    fs = require('fs'),
    shell = require('shelljs'),
    plugman = require('../src/plugman/plugman');

describe( 'create', function() {
    it( 'Test 001 : should call create', function() {
        var sCreate = spyOn( plugman, 'create' ).and.returnValue(Q());
        plugman.create();
        expect(sCreate).toHaveBeenCalled();
    });
});

describe( 'create plugin', function() {
    var done = false,
        existsSync,
        mkdir,
        writeFileSync;

    beforeEach( function() {
        existsSync = spyOn( fs, 'existsSync' ).and.returnValue( false );
        mkdir = spyOn( shell, 'mkdir' ).and.returnValue( true );
        writeFileSync = spyOn( fs, 'writeFileSync' );
        done = false;
    });

    it( 'Test 002 : should be successful', function(done) {
        create('name', 'org.plugin.id', '0.0.0', '.', [])
        .then(function(result) {
            expect( writeFileSync.calls.count() ).toEqual( 2 );
            done();
        }).fail(function err(errMsg) {
            expect(errMsg).toBeUndefined();
            done();
        });
    }, 6000);
});

describe( 'create plugin in existing plugin', function() {
    var done = false,
        existsSync;

    beforeEach( function() {
        existsSync = spyOn( fs, 'existsSync' ).and.returnValue( true );
        done = false;
    });

    it( 'Test 003 : should fail due to an existing plugin.xml', function(done) {
        create()
        .then(function(result) {
            expect(false).toBe(true);
            done();
        }).fail(function err(errMsg) {
            expect(errMsg.toString()).toContain( 'plugin.xml already exists. Are you already in a plugin?'  );
            done();
        });
    }, 6000);
});


text:
from django.conf import settings

# middleware use cache
CACHE_KEY = getattr(settings, 'SIMPLESPAMBLOCKER_CACHE_KEY',
                    'simplespamblocker/option/%(id)s')

# activate logger
LOGGER_NAME = getattr(settings, 'SIMPLESPAMBLOCKER_LOGGER_NAME', None)

# page on blocked spam
SPAM_TEMPLATE = getattr(settings, 'SIMPLESPAMBLOCKER_SPAM_TEMPLATE', None)


text:
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>

#include <algorithm>
#include <string>
#include <vector>

#include "native_client/src/include/nacl_assert.h"

void test_dirent(const char *test_directory) {
  // Create files: test00, test01, test02 ... and test29 into the directory.
  const int kNumTestFiles = 30;
  {
    char path[PATH_MAX];
    for (int i = 0; i < kNumTestFiles; ++i) {
      snprintf(path, PATH_MAX, "%s/test%02d", test_directory, i);
      fclose(fopen(path, "w"));
    }
  }

  int dirfd = open(test_directory, O_RDONLY);
  ASSERT_GE(dirfd, 0);
  DIR *dir = fdopendir(dirfd);  // Takes ownership of |dirfd|.

  // We expect '.', '..', 'test00', 'test01', ... and 'test29' as entries.
  std::vector<std::string> paths;
  for (int i = 0; i < kNumTestFiles + 2; ++i) {
    struct dirent entry;
    struct dirent *result;
    int rc = readdir_r(dir, &entry, &result);
    ASSERT_EQ(rc, 0);
    ASSERT_EQ(&entry, result);
    ASSERT_NE(result->d_ino, 0);
    ASSERT_GT(result->d_reclen, 0);
    paths.push_back(std::string(result->d_name));
  }

  std::sort(paths.begin(), paths.end());
  ASSERT(paths[0] == ".");
  ASSERT(paths[1] == "..");
  for (int i = 0; i < kNumTestFiles; ++i) {
    char name[PATH_MAX];
    snprintf(name, PATH_MAX, "test%02d", i);
    ASSERT_MSG(paths[i + 2] == name, name);
  }

  // Here DIR should hit end of entries.
  {
    struct dirent entry;
    struct dirent *result;
    int rc = readdir_r(dir, &entry, &result);
    ASSERT_EQ(rc, 0);
    ASSERT_EQ(result, NULL);
  }

  int rc = closedir(dir);
  ASSERT_EQ(rc, 0);

  // Test with bad file descriptor.
  dir = fdopendir(-1);
  ASSERT_EQ(dir, NULL);
  ASSERT_EQ(errno, EBADF);

  // Test with non-directory descriptor.
  char path[PATH_MAX];
  snprintf(path, PATH_MAX, "%s/test01", test_directory);
  int filefd = open(path, O_RDONLY);
  ASSERT_GE(filefd, 0);
  dir = fdopendir(filefd);
  ASSERT_EQ(dir, NULL);
  ASSERT_EQ(errno, ENOTDIR);

  rc = close(filefd);
  ASSERT_EQ(rc, 0);
}

int main(int argc, char *argv[]) {
  if (argc != 2) {
    printf("Please specify the test directory name.\n");
    exit(-1);
  }

  test_dirent(argv[1]);
  puts("PASSED");
  return 0;
}


text:
package com.salesforce.zsync.internal;

import static java.nio.file.StandardCopyOption.ATOMIC_MOVE;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.READ;
import static java.nio.file.StandardOpenOption.WRITE;
import static java.nio.file.attribute.FileTime.fromMillis;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ListMultimap;
import com.salesforce.zsync.http.ContentRange;
import com.salesforce.zsync.internal.util.ReadableByteBuffer;
import com.salesforce.zsync.internal.util.TransferListener;
import com.salesforce.zsync.internal.util.ZsyncUtil;
import com.salesforce.zsync.internal.util.HttpClient.RangeReceiver;
import com.salesforce.zsync.internal.util.TransferListener.ResourceTransferListener;

public class OutputFileWriter implements RangeReceiver, Closeable {

  // immutable state
  private final Path path;
  private final Path tempPath;

  private final int blockSize;
  private final int lastBlockSize;
  private final long length;
  private final String sha1;
  private final long mtime;
  private final List<BlockSum> blockSums;
  private final ListMultimap<BlockSum, Integer> positions;
  // mutable state
  private final FileChannel channel;
  private final boolean[] completed;
  private int blocksRemaining;
  private TransferListener listener;

  public OutputFileWriter(Path path, ControlFile controlFile, ResourceTransferListener<Path> listener)
      throws IOException {
    this.path = path;
    this.listener = listener;

    final Header header = controlFile.getHeader();
    this.blockSize = header.getBlocksize();
    this.length = header.getLength();
    this.lastBlockSize = (int) (this.length % this.blockSize == 0 ? this.blockSize : this.length % this.blockSize);
    this.sha1 = header.getSha1();
    this.mtime = header.getMtime().getTime();

    listener.start(this.path, this.length);

    final String tmpName = path.getFileName().toString() + ".part";
    final Path parent = path.getParent();
    if (parent != null) {
      if (!Files.isDirectory(parent)) {
        Files.createDirectories(parent);
      }
      this.tempPath = parent.resolve(tmpName);
    } else {
      this.tempPath = Paths.get(tmpName);
    }
    this.channel = FileChannel.open(this.tempPath, CREATE, WRITE, READ);

    this.blockSums = ImmutableList.copyOf(controlFile.getBlockSums());
    this.positions = indexPositions(this.blockSums);
    this.completed = new boolean[this.blockSums.size()];
    this.blocksRemaining = this.completed.length;
  }

  static ListMultimap<BlockSum, Integer> indexPositions(List<BlockSum> blockSums) {
    final ImmutableListMultimap.Builder<BlockSum, Integer> b = ImmutableListMultimap.builder();
    for (int i = 0; i < blockSums.size(); i++) {
      b.put(blockSums.get(i), i);
    }
    return b.build();
  }

  public int getNumBlocks() {
    return this.blockSums.size();
  }

  public BlockSum get(int index) {
    return this.blockSums.get(index);
  }

  public List<Integer> getPositions(BlockSum sum) {
    return this.positions.get(sum);
  }

  public boolean writeBlock(int position, ReadableByteBuffer data) {
    return this.writeBlock(position, data, 0);
  }

  public boolean writeBlock(int position, ReadableByteBuffer data, int offset) {
    if (this.completed[position]) {
      return false;
    }
    final int l = position == this.completed.length - 1 ? this.lastBlockSize : this.blockSize;
    try {
      this.channel.position(position * this.blockSize);
      data.write(this.channel, offset, l);
      this.listener.transferred(l);
    } catch (IOException e) {
      throw new RuntimeException("Failed to read block at position " + position, e);
    }
    this.blocksRemaining--;
    return this.completed[position] = true;
  }

  public List<ContentRange> getMissingRanges() {
    final ImmutableList.Builder<ContentRange> b = ImmutableList.builder();
    long start = -1;
    for (int i = 0; i < this.completed.length; i++) {
      if (this.completed[i]) {
        // if we're in a range, end it
        if (start != -1) {
          b.add(new ContentRange(start, i * this.blockSize - 1));
          start = -1;
        }
      } else {
        // if we're not in a range, start one
        if (start == -1) {
          start = i * this.blockSize;
        }
        // if this is the last block in the file map, we need to end the range
        if (i == this.completed.length - 1) {
          b.add(new ContentRange(start, this.length - 1));
        }
      }
    }
    return b.build();
  }

  public boolean isComplete() {
    return this.blocksRemaining == 0;
  }

  @Override
  public void receive(ContentRange range, InputStream in) throws IOException {
    if (range.first() % this.blockSize != 0) {
      throw new RuntimeException("Invalid range received: first byte not block aligned");
    }
    if ((range.last() + 1) % this.blockSize != 0 && range.last() + 1 != this.length) {
      throw new RuntimeException("Invalid range received: last byte not block aligned");
    }

    final ReadableByteChannel src = Channels.newChannel(in);
    final long length = range.length();
    long remaining = length;
    do {
      long transferred = this.channel.transferFrom(src, range.first(), length);
      remaining -= transferred;
      this.listener.transferred(transferred);
    } while (remaining > 0);

    final int first = (int) (range.first() / this.blockSize);
    final int last =
        (int) (range.last() + 1 == this.length ? this.completed.length - 1 : (range.last() + 1) / this.blockSize - 1);
    for (int i = first; i <= last; i++) {
      if (!this.completed[i]) {
        this.blocksRemaining--;
        this.completed[i] = true;
      }
    }
  }

  @Override
  public void close() throws IOException {
    try {
      this.channel.position(0); // reset channel to beginning to compute full SHA1
      String calculatedSha1 = ZsyncUtil.computeSha1(this.channel);
      if (!this.sha1.equals(calculatedSha1)) {
        throw new ChecksumValidationIOException(this.sha1, calculatedSha1);
      }
      try {
        Files.move(this.tempPath, this.path, REPLACE_EXISTING, ATOMIC_MOVE);
      } catch (AtomicMoveNotSupportedException e) {
        Files.move(this.tempPath, this.path, REPLACE_EXISTING);
      }
      Files.setLastModifiedTime(this.path, fromMillis(this.mtime));
    } finally {
      this.channel.close();
      this.listener.close();
    }
  }

}


text:
[![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/2166/badge)](https://bestpractices.coreinfrastructure.org/projects/2166)
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/a276a159c93f47768c59dc264750f9f5)](https://www.codacy.com/app/sgsaenger/vipster?utm_source=github.com&utm_medium=referral&utm_content=sgsaenger/vipster&utm_campaign=Badge_Grade)

Master:
[![Build Status](https://travis-ci.com/sgsaenger/vipster.svg?branch=master)](https://travis-ci.com/sgsaenger/vipster)
[![codecov](https://codecov.io/gh/sgsaenger/vipster/branch/master/graph/badge.svg)](https://codecov.io/gh/sgsaenger/vipster)

Testing:
[![Build Status](https://travis-ci.com/sgsaenger/vipster.svg?branch=testing)](https://travis-ci.com/sgsaenger/vipster)
[![codecov](https://codecov.io/gh/sgsaenger/vipster/branch/testing/graph/badge.svg)](https://codecov.io/gh/sgsaenger/vipster)

Visualization and editing framework for atomistic simulations.

For more information, please visit the [Homepage](https://sgsaenger.github.io/vipster),
installation instructions can be found [here](INSTALL.md).

Most importantly, [try it in your browser!](https://sgsaenger.github.io/vipster/emscripten/index.html)

      Libvipster

    C++17 based backbone: Powerful container-classes and I/O

    Fast and native GUI with OGL3.3 based rendering
    Portable browser-based GUI, shared render-code
    Scripting interface for batch-processing

## Dependencies:

- [JSON for Modern C++ >= 3.0](https://github.com/nlohmann/json) (included)
- [CLI11](https://github.com/CLIUtils/CLI11) (included)
- [tinyexpr](https://github.com/codeplea/tinyexpr) (included)
- [CMake >= 3.9](https://cmake.org)
- and a C++17-capable compiler (g++/mingw > 7 or clang > 4)
- optional:
    - [Qt5 >= 5.7](https://www.qt.io) (desktop application)
    - [emscripten](http://kripken.github.io/emscripten-site) (web interface)
    - [pybind11](https://github.com/pybind/pybind11) (script interface, included)
    - [Catch2](https://github.com/catchorg/Catch2) (testing, included)

## Supported file types:

- standard xyz
- PWscf input
- PWScf output
- Lammps data
- Lammps dump
- Empire-xyz
- CPMD input
- Gaussian cube
- XSF/AXSF
- ~~AIMALL output~~
- ~~Mol2~~
- ~~Turbomole~~