<commit_before>$(function() {
    $( 'input[name="date_pick_from"]' ).datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        numberOfMonths: 1,
        onClose: function( selectedDate ) {
            $( "#date_pick_to" ).datepicker( "option", "minDate", selectedDate );
        }
    });

    $( 'input[name="date_pick_to"]' ).datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        numberOfMonths: 1,
        onClose: function( selectedDate ) {
            $( "#date_pick_from" ).datepicker( "option", "maxDate", selectedDate );
        }
        });

    $('#dropdown_menu_biomimic_type').change( function () {
        biomimic_type = $("#dropdown_menu_biomimic_type option:selected").text();
        $.getJSON('/_parse_data', {
            select_type: "biomimic_type",
            select_value: biomimic_type
        })
        .done(function(data){
            $('#dropdown_menu_country_name').empty();
            $("#dropdown_menu_country_name").append('<option value="">Please select Country Name</option>')
            $.each(data, function(country){
                $("#dropdown_menu_country_name").append('<option value=\"'+country+'\">'+country+'</option>')
            });
        });
    });

    $('#dropdown_menu_country_name').change( function () {
        country_name = $("#dropdown_menu_country_name option:selected").text();
        $.getJSON('/_parse_data', {
            select_type: "country_name",
            select_value: country_name
        }).done(function(data) {
            $('#dropdown_menu_state_name').empty()
            $("#dropdown_menu_state_name").append('<option value="">Please select State Name</option>')
            $.each(data, function(state) {
                $("#dropdown_menu_state_name").append('<option value=\"'+state+'\">'+state+'</option>')
            });
        });
    });

    $('#dropdown_menu_state_name').change( function () {
        state_name = $("#dropdown_menu_state_name option:selected").text();
        $.getJSON('/_parse_data', {
            select_type: "state_name",
            select_value: state_name
            }).done(function(data) {
            $('#dropdown_menu_location_name').empty()
            $("#dropdown_menu_location_name").append('<option value="">Please select Location Name</option>')
            $.each(data, function(location) {
                $("#dropdown_menu_location_name").append('<option value=\"'+location+'\">'+location+'</option>')
            });
        });
    });

    $('#dropdown_menu_location_name').change( function () {
        //location_name = $("#dropdown_menu_location_name option:selected").text();
        $.getJSON('/_parse_data', {
            select_type: "lt_for_zone",
            select_value: biomimic_type
        }).done(function(data) {
            $('#dropdown_menu_zone_name').empty()
            $("#dropdown_menu_zone_name").append('<option value="">Please select Zone Name</option>')
            $("#dropdown_menu_zone_name").append('<option value="1">All</option>')
            $.each(data, function(zone) {
                $("#dropdown_menu_zone_name").append('<option value=\"'+zone+'\">'+zone+'</option>')
            });
        });
    });

    $('#dropdown_menu_zone_name').change( function () {
        $.getJSON('/_parse_data', {
            select_type: "lt_for_subzone",
            select_value: biomimic_type
            }).done(function(data) {
            $('#dropdown_menu_sub_zone_name').empty()
            $("#dropdown_menu_sub_zone_name").append('<option value="">Please select Sub Zone</option>')
            $("#dropdown_menu_sub_zone_name").append('<option value="1">All</option>')
            $.each(data, function(sub_zone) {
                $("#dropdown_menu_sub_zone_name").append('<option value=\"'+sub_zone+'\">'+sub_zone+'</option>')
            });
        });
    });

    $('#dropdown_menu_sub_zone_name').change( function () {
        $.getJSON('/_parse_data', {
            select_type: "lt_for_wave_exp",
            select_value: biomimic_type
            }).done(function(data) {
            $('#dropdown_menu_wave_exp_name').empty()
            $("#dropdown_menu_wave_exp_name").append('<option value="">Please select Wave Exposure</option>')
            $("#dropdown_menu_wave_exp_name").append('<option value="1">All</option>')
            $.each(data, function(wave_exp) {
                $("#dropdown_menu_wave_exp_name").append('<option value=\"'+wave_exp+'\">'+wave_exp+'</option>')
            });
        });
    });
    function fieldValidation(){
        var query_field1 = $("#dropdown_menu_biomimic_type option:selected").text()
        var query_field2 = $("#dropdown_menu_country_name option:selected").text()
        var query_field3 = $("#dropdown_menu_state_name option:selected").text()
        var query_field4 = $("#dropdown_menu_location_name option:selected").text()
        var query_field5 = $("#dropdown_menu_zone_name option:selected").text()
        var query_field6 = $("#dropdown_menu_zone_name option:selected")
        var query_field7 = $("#dropdown_menu_wave_exp_name option:selected").text()
        var query_field8 = $("#date_pick_from").val()
        var query_field9 = $("#date_pick_to").val()
        var valid = false
        if ((query_field1 != "Please select Biomimic Type") && (query_field2 != "Please select Country Name") && (query_field3 != "Please select State Name") && (query_field4 != "Please select Location Name") && (query_field5 != "Please select Zone Name") && (query_field6 != "Please select Sub zone") && (query_field7 != "Please select Wave Exposure") && (query_field8 != '') && (query_field9 != '')){
            valid = true
        }
        return valid
    }

    $('#button_submit_query').click(function () {
    if (fieldValidation())
        {
            $.getJSON('/_submit_query', {
                biomimic_type: $("#dropdown_menu_biomimic_type option:selected").text(),
                country: $("#dropdown_menu_country_name option:selected").text(),
                state_province: $("#dropdown_menu_state_name option:selected").text(),
                location: $("#dropdown_menu_location_name option:selected").text(),
                zone: $("#dropdown_menu_zone_name option:selected").text(),
                sub_zone: $("#dropdown_menu_sub_zone_name option:selected").text(),
                wave_exp: $("#dropdown_menu_wave_exp_name option:selected").text(),
                start_date: $("#date_pick_from").val(),
                end_date: $("#date_pick_to").val(),
            })
            .done(function(data){
                console.log(data.list_of_results)
                var values = (data.list_of_results)
                var options = $("#hidden-table");
                var button = $("#download-button");
                var title = $("#title")
                button.empty()
                options.empty()
                if (values == ''){
                    button.empty()
                    options.empty()
                    options.append("
  Search was unsucessfull, please try again with different select options
")
                }
                else {
                    options.empty()
                    title.append("
Data preview
")
                    options.append("

Timestamp	Temperature

")
                    $.each(data.list_of_results, function(key, value) {
                        options.append("
"+value[0]+"	"+value[1]+"
")
                    });
                    options.append("
")
                    options.append("
")
                    button.empty()
                    button.append(" Download All Data")
                }
            });
        }
    });

    $(document).ready(function(){
        $('[data-toggle="popover"]').popover();
    });
});<commit_msg>table header now deletes on submit<commit_after>$(function() {
    $( 'input[name="date_pick_from"]' ).datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        numberOfMonths: 1,
        onClose: function( selectedDate ) {
            $( "#date_pick_to" ).datepicker( "option", "minDate", selectedDate );
        }
    });

    $( 'input[name="date_pick_to"]' ).datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        numberOfMonths: 1,
        onClose: function( selectedDate ) {
            $( "#date_pick_from" ).datepicker( "option", "maxDate", selectedDate );
        }
        });

    $('#dropdown_menu_biomimic_type').change( function () {
        biomimic_type = $("#dropdown_menu_biomimic_type option:selected").text();
        $.getJSON('/_parse_data', {
            select_type: "biomimic_type",
            select_value: biomimic_type
        })
        .done(function(data){
            $('#dropdown_menu_country_name').empty();
            $("#dropdown_menu_country_name").append('<option value="">Please select Country Name</option>')
            $.each(data, function(country){
                $("#dropdown_menu_country_name").append('<option value=\"'+country+'\">'+country+'</option>')
            });
        });
    });

    $('#dropdown_menu_country_name').change( function () {
        country_name = $("#dropdown_menu_country_name option:selected").text();
        $.getJSON('/_parse_data', {
            select_type: "country_name",
            select_value: country_name
        }).done(function(data) {
            $('#dropdown_menu_state_name').empty()
            $("#dropdown_menu_state_name").append('<option value="">Please select State Name</option>')
            $.each(data, function(state) {
                $("#dropdown_menu_state_name").append('<option value=\"'+state+'\">'+state+'</option>')
            });
        });
    });

    $('#dropdown_menu_state_name').change( function () {
        state_name = $("#dropdown_menu_state_name option:selected").text();
        $.getJSON('/_parse_data', {
            select_type: "state_name",
            select_value: state_name
            }).done(function(data) {
            $('#dropdown_menu_location_name').empty()
            $("#dropdown_menu_location_name").append('<option value="">Please select Location Name</option>')
            $.each(data, function(location) {
                $("#dropdown_menu_location_name").append('<option value=\"'+location+'\">'+location+'</option>')
            });
        });
    });

    $('#dropdown_menu_location_name').change( function () {
        //location_name = $("#dropdown_menu_location_name option:selected").text();
        $.getJSON('/_parse_data', {
            select_type: "lt_for_zone",
            select_value: biomimic_type
        }).done(function(data) {
            $('#dropdown_menu_zone_name').empty()
            $("#dropdown_menu_zone_name").append('<option value="">Please select Zone Name</option>')
            $("#dropdown_menu_zone_name").append('<option value="1">All</option>')
            $.each(data, function(zone) {
                $("#dropdown_menu_zone_name").append('<option value=\"'+zone+'\">'+zone+'</option>')
            });
        });
    });

    $('#dropdown_menu_zone_name').change( function () {
        $.getJSON('/_parse_data', {
            select_type: "lt_for_subzone",
            select_value: biomimic_type
            }).done(function(data) {
            $('#dropdown_menu_sub_zone_name').empty()
            $("#dropdown_menu_sub_zone_name").append('<option value="">Please select Sub Zone</option>')
            $("#dropdown_menu_sub_zone_name").append('<option value="1">All</option>')
            $.each(data, function(sub_zone) {
                $("#dropdown_menu_sub_zone_name").append('<option value=\"'+sub_zone+'\">'+sub_zone+'</option>')
            });
        });
    });

    $('#dropdown_menu_sub_zone_name').change( function () {
        $.getJSON('/_parse_data', {
            select_type: "lt_for_wave_exp",
            select_value: biomimic_type
            }).done(function(data) {
            $('#dropdown_menu_wave_exp_name').empty()
            $("#dropdown_menu_wave_exp_name").append('<option value="">Please select Wave Exposure</option>')
            $("#dropdown_menu_wave_exp_name").append('<option value="1">All</option>')
            $.each(data, function(wave_exp) {
                $("#dropdown_menu_wave_exp_name").append('<option value=\"'+wave_exp+'\">'+wave_exp+'</option>')
            });
        });
    });
    function fieldValidation(){
        var query_field1 = $("#dropdown_menu_biomimic_type option:selected").text()
        var query_field2 = $("#dropdown_menu_country_name option:selected").text()
        var query_field3 = $("#dropdown_menu_state_name option:selected").text()
        var query_field4 = $("#dropdown_menu_location_name option:selected").text()
        var query_field5 = $("#dropdown_menu_zone_name option:selected").text()
        var query_field6 = $("#dropdown_menu_zone_name option:selected")
        var query_field7 = $("#dropdown_menu_wave_exp_name option:selected").text()
        var query_field8 = $("#date_pick_from").val()
        var query_field9 = $("#date_pick_to").val()
        var valid = false
        if ((query_field1 != "Please select Biomimic Type") && (query_field2 != "Please select Country Name") && (query_field3 != "Please select State Name") && (query_field4 != "Please select Location Name") && (query_field5 != "Please select Zone Name") && (query_field6 != "Please select Sub zone") && (query_field7 != "Please select Wave Exposure") && (query_field8 != '') && (query_field9 != '')){
            valid = true
        }
        return valid
    }

    $('#button_submit_query').click(function () {
    if (fieldValidation())
        {
            $.getJSON('/_submit_query', {
                biomimic_type: $("#dropdown_menu_biomimic_type option:selected").text(),
                country: $("#dropdown_menu_country_name option:selected").text(),
                state_province: $("#dropdown_menu_state_name option:selected").text(),
                location: $("#dropdown_menu_location_name option:selected").text(),
                zone: $("#dropdown_menu_zone_name option:selected").text(),
                sub_zone: $("#dropdown_menu_sub_zone_name option:selected").text(),
                wave_exp: $("#dropdown_menu_wave_exp_name option:selected").text(),
                start_date: $("#date_pick_from").val(),
                end_date: $("#date_pick_to").val(),
            })
            .done(function(data){
                console.log(data.list_of_results)
                var values = (data.list_of_results)
                var options = $("#hidden-table");
                var button = $("#download-button");
                var title = $("#title")
                if (values == ''){
                    button.empty()
                    title.empty()
                    options.empty()
                    options.append("
  Search was unsucessfull, please try again with different select options
")
                }
                else {
                    options.empty()
                    title.empty()
                    title.append("
Data preview
")
                    options.append("

Timestamp	Temperature

")
                    $.each(data.list_of_results, function(key, value) {
                        options.append("
"+value[0]+"	"+value[1]+"
")
                    });
                    options.append("
")
                    options.append("
")
                    button.empty()
                    button.append(" Download All Data")
                }
            });
        }
    });

    $(document).ready(function(){
        $('[data-toggle="popover"]').popover();
    });
});<|endoftext|>


<commit_before>import path from 'path';
import webpack from 'webpack';

export default {
  // devtools: 'eval-source-map',
  entry: [
    'webpack-hot-middleware/client',
    path.join(__dirname, './client/index.js'),
  ],
  output: {
    path: __dirname,
    filename: 'bundle.js',
    publicPath: '/',
  },
  plugins: [
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
  ],
  module: {
    loaders: [{
      test: /\.js$/,
      include: [
        path.join(__dirname, 'client'),
        path.join(__dirname, 'server/shared/'),
      ],
      loader: ['react-hot-loader', 'babel-loader'],
      exclude: /node_modules/,
    }],
  },
  resolve: {
    extensions: ['.js', '.jsx'],
  },
  node: {
    net: 'empty',
    dns: 'empty',
  },
};
<commit_msg>feature(webpack.config.dev.js) add scss loade, remove JsonWebToken dependencies<commit_after>import path from 'path';
import webpack from 'webpack';

export default {
  // devtools: 'eval-source-map',
  entry: [
    'webpack-hot-middleware/client',
    path.join(__dirname, './client/index.js'),
  ],
  output: {
    path: __dirname,
    filename: 'bundle.js',
    publicPath: '/',
  },
  plugins: [
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
  ],
  module: {
    loaders: [{
      test: /\.js$/,
      include: [
        path.join(__dirname, 'client'),
        path.join(__dirname, 'server/shared/'),
      ],
      loader: ['react-hot-loader', 'babel-loader'],
      exclude: /node_modules/,
    }, {
      test: /\.scss$/,
      include: path.join(__dirname, 'client'),
      loaders: ['style-loader', 'css-loader', 'sass-loader'],
    },
     { test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192' }],
  },
  resolve: {
    extensions: ['.js', '.jsx'],
  },
};
<|endoftext|>


<commit_before>const webpack = require("webpack");
const config = require("./webpack.base.config");

config.module.rules.push(
    {
        test: /\.jsx?$/,
        use: ["eslint-loader"],
        exclude: /node_modules/,
        enforce: "pre"
    },
    {
        test: /\.css$/,
        use: ["style-loader", "css-loader"]
    },
    {
        test: /\.less$/,
        use: ["style-loader", "css-loader", "less-loader"]
    }
);

config.plugins.push(
    new webpack.SourceMapDevToolPlugin({
        filename: "[file].map",
        exclude: ["vendor.js"]
    })
);

// HMR.
// config.module.loaders[0].loaders.unshift("react-hot");
// for (const key of Object.keys(config.entry))
// {
//     config.entry[key].push("webpack-hot-middleware/client?reload=true");
// }
// config.plugins.push(
//     new webpack.HotModuleReplacementPlugin()
// );

module.exports = config;
<commit_msg>update to webpack 2<commit_after>const webpack = require("webpack");
const config = require("./webpack.base.config");

config.module.rules.push(
    {
        enforce: "pre",
        test: /\.jsx?$/,
        use: ["eslint-loader"],
        exclude: /node_modules/
    },
    {
        test: /\.css$/,
        use: ["style-loader", "css-loader"]
    },
    {
        test: /\.less$/,
        use: ["style-loader", "css-loader", "less-loader"]
    }
);

config.plugins.push(
    new webpack.SourceMapDevToolPlugin({
        filename: "[file].map",
        exclude: ["vendor.js"]
    })
);

// HMR.
// config.module.loaders[0].loaders.unshift("react-hot");
// for (const key of Object.keys(config.entry))
// {
//     config.entry[key].push("webpack-hot-middleware/client?reload=true");
// }
// config.plugins.push(
//     new webpack.HotModuleReplacementPlugin()
// );

module.exports = config;
<|endoftext|>


<commit_before>require.paths.unshift('lib');
require.paths.unshift('deps/redis-node-client/lib');
require.paths.unshift('deps/node-smtp/lib');

var smtp = require('smtp');
var config = require('config');
var sys = require('sys');

if (!config.smtp.smarthost){
  sys.debug('Smarthost not configured. Cannot start');
  process.exit(1);
}
if (!config.smtp.bannerHostname){
  sys.debug('Banner Hostname not configured. Cannot start');
  process.exit(1);
}

var server = new smtp.Server();
server.port = config.smtp.port;
server.host = config.smtp.listen;
server.hostname = config.smtp.bannerHostname;

require('redis').client.stream.addListener("connect", function (){
  server.runServer();
});

server.addListener('ehlo', function(args){
  args[1].emitSuccess(['SIZE '+config.smtp.maxlength]);
});

server.addListener('end', function(args){
  var session = args[0];
  if (session.client){
    session.client.quit();
    delete(session.client);
  }
});

server.addListener('rcpt_to', function(args){
  var addr = args[0], promise = args[1], session = args[2];
  addr = 'pilif@gnegg.ch'; // let's simulate alias expansion here!

  var setRecipient = function(addr){
    session.client.rcpt(addr)
      .addErrback(function(e){args[1].emitError(['Upstream denied from: '+e.data[0], true, e.status])})
      .addCallback(function(){
        promise.emitSuccess(addr);
      });
  }

  if (session.client){
    if (session.client.socket.readyState != 'open'){
      promise.emitError(['Upstream connection failed', true]);
      return;
    }
    setRecipient();
  }else{
    var client = session.client = new smtp.Client();
    client.connect(25, config.smtp.smarthost)
        .addErrback(function(e){ args[1].emitError(['Failure to connect to upstream server: '+e, true]); })
        .addCallback(function(){
          client.mail(session.fromAddress)
            .addErrback(function(e){args[1].emitError(['Upstream denied from: '+e.data[0], true, e.status])})
            .addCallback(function(){
              setRecipient(addr);
            });
        });
  }
});

server.addListener('mail_from', function(args){
  var addrLine = args[0].split(/\s+/), promise = args[1], session = args[2];
  var i = 0;

  if (! addrLine[0].match(/^[^@]+@[^@.][^@]+\.[^@.]+$/)){
    promise.emitError(["keep address simpler. Please. We only support user@host.domain", true, 501]);
    return;
  }
  for (i = 1; i < addrLine.length; i++){
    var sz = addrLine[i].match(/^SIZE=(\d+)/i);
    if (!sz){
      promise.emitError(["invalid argument", false, 501]);
      return;
    }
    if (parseInt(sz[1], 10) > config.smtp.maxlength){
      promise.emitError(['message would exceed size limit', false, 552]);
      return;
    }
  }
  promise.emitSuccess(addrLine[0]);
});

server.addListener('data', function(args){
  var promise = args[1], session = args[2];

  if (!session.client || session.client.socket.readyState != 'open'){
    promise.emitError(['Upstream connection failed', true]);
    return;
  }

  session.client.beginData()
    .addErrback(function(e){ promise.emitError(["upstream denied data: " + e.data[0], true, e.status]); })
    .addCallback(function(){
      session.data_counter = 0;
      promise.emitSuccess();
    });
});

server.addListener('data_available', function(args){
  var data = args[0], promise = args[1], session = args[2];

  if (!session.client || session.client.socket.readyState != 'open'){
    promise.emitError(['Upstream connection failed', true]);
    return;
  }
  session.data_counter += data.length;
  if (session.data_counter > config.smtp.maxlength + 100){
    promise.emitError(['Data size exceeded', true, 552]);
    return;
  }
  if (!session.received_added){
    data = 'Received: from ' + session.socket.remoteAddress + "\n" +
           '        by ' + config.smtp.bannerHostname +
               ' with ' + (session.esmtp ? 'ESMTP' : 'SMTP') + " id;\n" +
           '        ' + new Date().toUTCString() + "\n" + data;
    session.received_added = true;
  }

  session.client.sendData(data)
    .addCallback(function(){
      promise.emitSuccess();
  });
});

server.addListener('data_end', function(args){
  var data = args[0], promise = args[1], session = args[2];

  if (!session.client || session.client.socket.readyState != 'open'){
    promise.emitError(['Upstream connection failed', true]);
    return;
  }
  session.client.endData()
    .addErrback(function(e){ promise.emitError(["upstream denied data: " + e.data[0], true, e.status]); })
    .addCallback(function(){
      promise.emitSuccess();
    });
});
<commit_msg>checking for aliases on RCPT TO<commit_after>require.paths.unshift('lib');
require.paths.unshift('deps/redis-node-client/lib');
require.paths.unshift('deps/node-smtp/lib');

var smtp = require('smtp');
var config = require('config');
var sys = require('sys');
var tempalias = require('tempalias');

var aliasProvider = tempalias.AliasProvider;

if (!config.smtp.smarthost){
  sys.debug('Smarthost not configured. Cannot start');
  process.exit(1);
}
if (!config.smtp.bannerHostname){
  sys.debug('Banner Hostname not configured. Cannot start');
  process.exit(1);
}

var server = new smtp.Server();
server.port = config.smtp.port;
server.host = config.smtp.listen;
server.hostname = config.smtp.bannerHostname;

require('redis').client.stream.addListener("connect", function (){
  server.runServer();
});

server.addListener('ehlo', function(args){
  args[1].emitSuccess(['SIZE '+config.smtp.maxlength]);
});

server.addListener('end', function(args){
  var session = args[0];
  if (session.client){
    session.client.quit();
    delete(session.client);
  }
});

server.addListener('rcpt_to', function(args){
  var addr = args[0], promise = args[1], session = args[2];

  addr = addr.split('@');
  if (config.smtp.domains.indexOf(addr[1]) == -1){
    promise.emitError(['Relaying denied', false, 553]);
    return;
  }

  aliasProvider.findById(addr[0], function(alias){
    if (!alias){
      promise.emitError(['User unknown', false, 550]);
      return;
    }
    var target = alias.target;

    var setRecipient = function(addr){
      session.client.rcpt(addr)
        .addErrback(function(e){args[1].emitError(['Upstream denied from: '+e.data[0], true, e.status])})
        .addCallback(function(){
          promise.emitSuccess(addr);
        });
    };

    if (session.client){
      if (session.client.socket.readyState != 'open'){
        promise.emitError(['Upstream connection failed', true]);
        return;
      }
      setRecipient(target);
    }else{
      var client = session.client = new smtp.Client();
      client.connect(25, config.smtp.smarthost)
          .addErrback(function(e){ args[1].emitError(['Failure to connect to upstream server: '+e, true]); })
          .addCallback(function(){
            client.mail(session.fromAddress)
              .addErrback(function(e){args[1].emitError(['Upstream denied from: '+e.data[0], true, e.status])})
              .addCallback(function(){
                setRecipient(target);
              });
          });
    }

  })
});

server.addListener('mail_from', function(args){
  var addrLine = args[0].split(/\s+/), promise = args[1], session = args[2];
  var i = 0;

  if (! addrLine[0].match(/^[^@]+@[^@.][^@]+\.[^@.]+$/)){
    promise.emitError(["keep address simpler. Please. We only support user@host.domain", true, 501]);
    return;
  }
  for (i = 1; i < addrLine.length; i++){
    var sz = addrLine[i].match(/^SIZE=(\d+)/i);
    if (!sz){
      promise.emitError(["invalid argument", false, 501]);
      return;
    }
    if (parseInt(sz[1], 10) > config.smtp.maxlength){
      promise.emitError(['message would exceed size limit', false, 552]);
      return;
    }
  }
  promise.emitSuccess(addrLine[0]);
});

server.addListener('data', function(args){
  var promise = args[1], session = args[2];

  if (!session.client || session.client.socket.readyState != 'open'){
    promise.emitError(['Upstream connection failed', true]);
    return;
  }

  session.client.beginData()
    .addErrback(function(e){ promise.emitError(["upstream denied data: " + e.data[0], true, e.status]); })
    .addCallback(function(){
      session.data_counter = 0;
      promise.emitSuccess();
    });
});

server.addListener('data_available', function(args){
  var data = args[0], promise = args[1], session = args[2];

  if (!session.client || session.client.socket.readyState != 'open'){
    promise.emitError(['Upstream connection failed', true]);
    return;
  }
  session.data_counter += data.length;
  if (session.data_counter > config.smtp.maxlength + 100){
    promise.emitError(['Data size exceeded', true, 552]);
    return;
  }
  if (!session.received_added){
    data = 'Received: from ' + session.socket.remoteAddress + "\n" +
           '        by ' + config.smtp.bannerHostname +
               ' with ' + (session.esmtp ? 'ESMTP' : 'SMTP') + " id;\n" +
           '        ' + new Date().toUTCString() + "\n" + data;
    session.received_added = true;
  }

  session.client.sendData(data)
    .addCallback(function(){
      promise.emitSuccess();
  });
});

server.addListener('data_end', function(args){
  var data = args[0], promise = args[1], session = args[2];

  if (!session.client || session.client.socket.readyState != 'open'){
    promise.emitError(['Upstream connection failed', true]);
    return;
  }
  session.client.endData()
    .addErrback(function(e){ promise.emitError(["upstream denied data: " + e.data[0], true, e.status]); })
    .addCallback(function(){
      promise.emitSuccess();
    });
});
<|endoftext|>


<commit_before>'use strict';

var validUrl = require('valid-url');
var Url = require('../models/url.js');

	function genId(len) {
		var i;
		var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
		var id = '';
		for (i=0;i<len;i++) {
			id += chars.charAt(Math.floor(Math.random() * chars.length));
		}
		return id;
	}

function ApiHandler () {

	this.getOriginalUrl = function (req, res) {
		Url
			.findByIdAndUpdate(req.params.id, { $inc: { 'counter': 1 } }, {select:{_id:0,}}, function(err, result) {
				if (err) { throw err; }

				if (result !== null) {
					res.redirect(result.original_url);
				}
				else {
					res.json({error: "This url is not in database."});
				}
			});
	};

	this.addUrl = function (req, res, next) {
		var fullUrl = req.params.protocol + '//' + req.params.url;
		if (validUrl.isWebUri(fullUrl)) {
		    //valid url
		    	Url.findOneAndUpdate({"original_url": fullUrl},
			{$setOnInsert:
				{
					"_id": genId(6),
					"original_url": fullUrl,
					"counter": 0
				}
			} ,
			{upsert: true, 'new': true},
			function(err, result){
				if (err) {
					if (err.name === 'MongoError' && err.code === 11000) {
			        // Duplicate username
			        // TODO Notify on key duplication - need to increment genId
			        // for more combinations
			        console.log("key duplication - need to increment genId for more combinations");
			        res.status(500).send({ error: 'Internal server error, try once again. If error persist contact support' });
			      }
					else {
						throw err;
					}
				}
				res.json({ "original_url":result.original_url, "short_url":req.protocol + '://' + req.get('host') + '/' + result._id});
			});
		  } else {
		  	//url invalid
		    res.json({error: "Wrong url format, make sure you have a valid protocol and real site."});
		  }

		// var url = new Url ({
		// 	"_id": genId(6),
		// 	"original_url": req.params.protocol + '//' + req.params.url
		// });

		// url.save(function(err, result){
		// 	if (err) {
		// 		if (err.name === 'MongoError' && err.code === 11000) {
		//         // Duplicate username
		//         // TODO Notify on key duplication - need to increment genId
		//         // for more combinations
		//         console.log("key duplication - need to increment genId for more combinations");
		//         res.status(500).send({ error: 'Internal server error, try once again. If error persist contact support' });
		//       }
		// 		else {
		// 			throw err;
		// 		}
		// 	}
		// 	res.json({ "original_url":result.original_url, "short_url":req.protocol + '://' + req.get('host') + '/' + result._id});
		// });
	};
}

module.exports = ApiHandler;
<commit_msg>Added -_ symbols to chars that generate unique ids<commit_after>'use strict';

var validUrl = require('valid-url');
var Url = require('../models/url.js');

	function genId(len) {
		var i;
		var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
		var id = '';
		for (i=0;i<len;i++) {
			id += chars.charAt(Math.floor(Math.random() * chars.length));
		}
		return id;
	}

function ApiHandler () {

	this.getOriginalUrl = function (req, res) {
		Url
			.findByIdAndUpdate(req.params.id, { $inc: { 'counter': 1 } }, {select:{_id:0,}}, function(err, result) {
				if (err) { throw err; }

				if (result !== null) {
					res.redirect(result.original_url);
				}
				else {
					res.json({error: "This url is not in database."});
				}
			});
	};

	this.addUrl = function (req, res, next) {
		var fullUrl = req.params.protocol + '//' + req.params.url;
		if (validUrl.isWebUri(fullUrl)) {
		    //valid url
		    	Url.findOneAndUpdate({"original_url": fullUrl},
			{$setOnInsert:
				{
					"_id": genId(6),
					"original_url": fullUrl,
					"counter": 0
				}
			} ,
			{upsert: true, 'new': true},
			function(err, result){
				if (err) {
					if (err.name === 'MongoError' && err.code === 11000) {
			        // Duplicate username
			        // TODO Notify on key duplication - need to increment genId
			        // for more combinations
			        console.log("key duplication - need to increment genId for more combinations");
			        res.status(500).send({ error: 'Internal server error, try once again. If error persist contact support' });
			      }
					else {
						throw err;
					}
				}
				res.json({ "original_url":result.original_url, "short_url":req.protocol + '://' + req.get('host') + '/' + result._id});
			});
		  } else {
		  	//url invalid
		    res.json({error: "Wrong url format, make sure you have a valid protocol and real site."});
		  }

		// var url = new Url ({
		// 	"_id": genId(6),
		// 	"original_url": req.params.protocol + '//' + req.params.url
		// });

		// url.save(function(err, result){
		// 	if (err) {
		// 		if (err.name === 'MongoError' && err.code === 11000) {
		//         // Duplicate username
		//         // TODO Notify on key duplication - need to increment genId
		//         // for more combinations
		//         console.log("key duplication - need to increment genId for more combinations");
		//         res.status(500).send({ error: 'Internal server error, try once again. If error persist contact support' });
		//       }
		// 		else {
		// 			throw err;
		// 		}
		// 	}
		// 	res.json({ "original_url":result.original_url, "short_url":req.protocol + '://' + req.get('host') + '/' + result._id});
		// });
	};
}

module.exports = ApiHandler;
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2017-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

// See https://docusaurus.io/docs/site-config for all the possible
// site configuration options.

const repoUrl = 'https://github.com/clay/clay';

// List of projects/orgs using your project for the users page.
const users = [];

const siteConfig = {
  title: 'Clay', // Title for your website.
  tagline: 'Organize, edit, and deliver the web, one component at a time.',
  url: 'https://clay.github.io/', // Your website URL
  baseUrl: '/clay/', // Base URL for your project */
  // For github.io type URLs, you would set the url and baseUrl like:
  //   url: 'https://facebook.github.io',
  //   baseUrl: '/test-site/',

  // Used for publishing and more
  projectName: 'Clay',
  organizationName: 'Clay Platform',
  // For top-level user or org sites, the organization is still the same.
  // e.g., for the https://JoelMarcey.github.io site, it would be set like...
  //   organizationName: 'JoelMarcey'

  // For no header links in the top nav bar -> headerLinks: [],
  headerLinks: [
    {doc: 'getting-started', label: 'Getting Started'},
    {href: repoUrl, label: 'GitHub'}
  ],

  // If you have users set above, you add it here:
  users,

  /* path to images for header/footer */
  headerIcon: 'img/logo.svg',
  footerIcon: '',
  favicon: '',

  /* Colors for website */
  colors: {
    primaryColor: '#607d8b',
    secondaryColor: '#1976d2',
  },

  /* Custom fonts for website */
  /*
  fonts: {
    myFont: [
      "Times New Roman",
      "Serif"
    ],
    myOtherFont: [
      "-apple-system",
      "system-ui"
    ]
  },
  */

  // This copyright info is used in /core/Footer.js and blog RSS/Atom feeds.
  copyright: `Copyright © ${new Date().getFullYear()} Your Name or Your Company Name`,

  highlight: {
    // Highlight.js theme to use for syntax highlighting in code blocks.
    theme: 'default',
  },

  // Add custom scripts here that would be placed in <script> tags.
  scripts: ['https://buttons.github.io/buttons.js'],

  docsSideNavCollapsible: true,
  // On page navigation for the current documentation page.
  onPageNav: 'separate',
  // No .html extensions for paths.
  cleanUrl: true,

  // Open Graph and Twitter card images.
  ogImage: '#99D3DF',
  twitterImage: '#99D3DF',

  // Show documentation's last contributor's name.
  // enableUpdateBy: true,

  // Show documentation's last update time.
  // enableUpdateTime: true,

  // You may provide arbitrary config keys to be used as needed by your
  // template. For example, if you need your repo's URL...
  //   repoUrl: 'https://github.com/facebook/test-site',
};

module.exports = siteConfig;
<commit_msg>updating config<commit_after>/**
 * Copyright (c) 2017-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

// See https://docusaurus.io/docs/site-config for all the possible
// site configuration options.

const repoUrl = 'https://github.com/clay';

// List of projects/orgs using your project for the users page.
const users = [];

const siteConfig = {
  title: 'Clay', // Title for your website.
  tagline: 'Organize, edit, and deliver the web, one component at a time.',
  url: 'https://clay.github.io', // Your website URL
  baseUrl: '/clay/', // Base URL for your project */
  // For github.io type URLs, you would set the url and baseUrl like:
  //   url: 'https://facebook.github.io',
  //   baseUrl: '/test-site/',

  // Used for publishing and more
  projectName: 'Clay',
  organizationName: 'clayplatform',
  // For top-level user or org sites, the organization is still the same.
  // e.g., for the https://JoelMarcey.github.io site, it would be set like...
  //   organizationName: 'JoelMarcey'

  // For no header links in the top nav bar -> headerLinks: [],
  headerLinks: [
    {doc: 'getting-started', label: 'Getting Started'},
    {href: repoUrl, label: 'G'}
  ],

  // If you have users set above, you add it here:
  users,

  /* path to images for header/footer */
  headerIcon: 'img/logo.svg',
  footerIcon: '',
  favicon: '',

  /* Colors for website */
  colors: {
    primaryColor: '#607d8b',
    secondaryColor: '#1976d2',
  },

  /* Custom fonts for website */
  /*
  fonts: {
    myFont: [
      "Times New Roman",
      "Serif"
    ],
    myOtherFont: [
      "-apple-system",
      "system-ui"
    ]
  },
  */

  // This copyright info is used in /core/Footer.js and blog RSS/Atom feeds.
  copyright: `Copyright © ${new Date().getFullYear()} Your Name or Your Company Name`,

  highlight: {
    // Highlight.js theme to use for syntax highlighting in code blocks.
    theme: 'default',
  },

  // Add custom scripts here that would be placed in <script> tags.
  scripts: ['https://buttons.github.io/buttons.js'],

  docsSideNavCollapsible: true,
  // On page navigation for the current documentation page.
  onPageNav: 'separate',
  // No .html extensions for paths.
  cleanUrl: true,

  // Open Graph and Twitter card images.
  ogImage: '#99D3DF',
  twitterImage: '#99D3DF',

  // Show documentation's last contributor's name.
  // enableUpdateBy: true,

  // Show documentation's last update time.
  // enableUpdateTime: true,

  // You may provide arbitrary config keys to be used as needed by your
  // template. For example, if you need your repo's URL...
  //   repoUrl: 'https://github.com/facebook/test-site',
};

module.exports = siteConfig;
<|endoftext|>


<commit_before>'use strict';

var db = require('mano').db,
	user = db.User.prototype,
	inventoryCaluculation = require('./_inventory'),
	reqRadio;

exports.step = function () {
	insert(inventoryCaluculation);
	section({ class: 'user-guide' },
			h1("1. Individual registration guide for companies"
			),
			form({ class: 'guide-form' },
				div({ class: 'guide-box' }, h2("Questions"),
					hr(),
					ul({ class: 'form-elements' },
					['businessActivity',
						'isOwner',
						'inventory',
						'inventoryCaluculation',
						'surfaceArea', 'members',
						'companyType',
						'isShoppingGallery'],
					function (name) {
						if (name === 'inventoryCaluculation') {
							li({ class: 'inventory-calculation' },
								a({ onclick: inventoryCaluculation.show },
									span({ class: 'fa fa-calculator' }, "Calculator"),
									span("Calculate the amount")
									)
								);
						} else {
							li(div({ class: 'dbjs-input-component' },
								label(user.getDescriptor(name).label, ":"),
								div({ class: 'control' }, input({ dbjs: user.getObservable(name) }))));
						}
					})),
				div({ class: 'guide-box' }, h2("Registrations"),
					hr(),
					ul(li(label({ class: 'input-aside' },
							input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
						span(user.getDescriptor('isARequested').label))),
						li(label({ class: 'input-aside' },
							input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
						span(user.getDescriptor('isBRequested').label))),
						li(label({ class: 'input-aside' },
							input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
						span(user.getDescriptor('isARequested').label)))
					),
					p("Lorem ipsum dolor sit amet, consectetur adipiscing elit." +
						" Etiam vestibulum dui mi, nec ultrices diam ultricies id. " +
						" Etiam vestibulum dui mi, nec ultrices diam ultricies id. "),
					p("Lorem ipsum dolor sit amet, consectetur adipiscing elit." +
						" Etiam vestibulum dui mi, nec ultrices diam ultricies id. " +
						" Etiam vestibulum dui mi, nec ultrices diam ultricies id. ")
				),
				div({ class: 'guide-box' }, h2("Requirements"),
					hr(),
					p("Lorem ipsum dolor sit amet, consectetur adipiscing elit." +
						" Etiam vestibulum dui mi, nec ultrices diam ultricies id. "),
					ul({ class: 'guide-requirements-list' },
						li("Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
						" Lorem ipsum dolor sit amet, consectetur adipiscing elit."),
						li("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum " +
							"dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet," +
							" consectetur adipiscing elit."),
						li("Lorem ipsum dolor sit amet, consectetur adipiscing elit."),
						li("Lorem ipsum dolor sit amet, consectetur adipiscing elit."),
						li("Lorem ipsum dolor sit amet, consectetur adipiscing elit."),
						li("Lorem ipsum dolor sit amet: ",
						ul(li(reqRadio = input({ dbjs: user._isType, type: 'radio',
							renderOption: function (labelTxt) {
								var data = {};
								data.dom = li(label({ class: 'input-aside' },
									span(data.input = input()),
									span(labelTxt)));
								return data;
							}  }), " "))),
						li(
						"Please choose x docs in the list: ",
						ul(
							li(label({ class: 'input-aside' },
								input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
								span(user.getDescriptor('isBRequested').label))),
							li(label({ class: 'input-aside' },
								input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
								span(user.getDescriptor('isBRequested').label))),
							li({ class: 'disabled' },
								label({ class: 'input-aside' }, input({ dbjs: user._isBRequested,
															type: 'checkbox',
															disabled: 'disabled',
															value: 'checked' }),
									" ",
									span(user.getDescriptor('isBRequested').label))),
							li(label({ class: 'input-aside' },
								input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
								span(user.getDescriptor('isARequested').label))),
							li(label({ class: 'input-aside' },
								input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
								span(user.getDescriptor('isBRequested').label)))
						)
					)
					)
				),
				div({ class: 'guide-box' }, h2("Costs"),
					hr(),
					p("Lorem ipsum dolor sit amet, consectetur adipiscing elit." +
						" Etiam vestibulum dui mi, nec ultrices diam ultricies id. "),
					ul({ class: 'guide-costs-list' },
						li(span("Registration fee"), " ",
							span("$50'000")
							),
						li(span("Stamp duty for registration"), " ",
							span("$10'000")),
						li(span("Filing fees for memorandum"), " ",
							span("$45'000")),
						li({ class: 'guide-total-costs' },
								span("Total Costs:"), " ",
								span("$105'000")
							)
						)
				),
				button({ class: 'save-step-one', type: 'submit' },
					"Save and continue"
				)
			)
		);
	reqRadio._dbjsInput.listItems[0].appendChild(
		div({ class: 'disabler-range' }, // add 'disabled' class to disable ul
			ul(
				li(label({ class: 'input-aside' },
					input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
					span(user.getDescriptor('isBRequested').label))),
				li(label({ class: 'input-aside' },
					input({ dbjs: user._isARequested,
						type: 'checkbox', value: 'checked' }), " ",
					span(user.getDescriptor('isBRequested').label)))
			),
			div({ class: 'disabler' })
			)
	);
};
<commit_msg>Moved inventory-calulation element from its own li into invetory li as div. #112<commit_after>'use strict';

var db = require('mano').db,
	user = db.User.prototype,
	inventoryCaluculation = require('./_inventory'),
	reqRadio;

exports.step = function () {
	insert(inventoryCaluculation);
	section({ class: 'user-guide' },
			h1("1. Individual registration guide for companies"
			),
			form({ class: 'guide-form' },
				div({ class: 'guide-box' }, h2("Questions"),
					hr(),
					ul({ class: 'form-elements' },
					['businessActivity',
						'isOwner',
						'inventory',
						'surfaceArea', 'members',
						'companyType',
						'isShoppingGallery'],
					function (name) {
						if (name === 'inventory') {
							li(div({ class: 'dbjs-input-component' },
								label(user.getDescriptor(name).label, ":"),
								div({ class: 'control' }, input({ dbjs: user.getObservable(name) }))));
							div({ class: 'inventory-calculation' },
								a({ onclick: inventoryCaluculation.show },
									span({ class: 'fa fa-calculator' }, "Calculator"),
									span("Calculate the amount")
									)
								);
						} else {
							li(div({ class: 'dbjs-input-component' },
								label(user.getDescriptor(name).label, ":"),
								div({ class: 'control' }, input({ dbjs: user.getObservable(name) }))));
						}
					})),
				div({ class: 'guide-box' }, h2("Registrations"),
					hr(),
					ul(li(label({ class: 'input-aside' },
							input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
						span(user.getDescriptor('isARequested').label))),
						li(label({ class: 'input-aside' },
							input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
						span(user.getDescriptor('isBRequested').label))),
						li(label({ class: 'input-aside' },
							input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
						span(user.getDescriptor('isARequested').label)))
					),
					p("Lorem ipsum dolor sit amet, consectetur adipiscing elit." +
						" Etiam vestibulum dui mi, nec ultrices diam ultricies id. " +
						" Etiam vestibulum dui mi, nec ultrices diam ultricies id. "),
					p("Lorem ipsum dolor sit amet, consectetur adipiscing elit." +
						" Etiam vestibulum dui mi, nec ultrices diam ultricies id. " +
						" Etiam vestibulum dui mi, nec ultrices diam ultricies id. ")
				),
				div({ class: 'guide-box' }, h2("Requirements"),
					hr(),
					p("Lorem ipsum dolor sit amet, consectetur adipiscing elit." +
						" Etiam vestibulum dui mi, nec ultrices diam ultricies id. "),
					ul({ class: 'guide-requirements-list' },
						li("Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
						" Lorem ipsum dolor sit amet, consectetur adipiscing elit."),
						li("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum " +
							"dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet," +
							" consectetur adipiscing elit."),
						li("Lorem ipsum dolor sit amet, consectetur adipiscing elit."),
						li("Lorem ipsum dolor sit amet, consectetur adipiscing elit."),
						li("Lorem ipsum dolor sit amet, consectetur adipiscing elit."),
						li("Lorem ipsum dolor sit amet: ",
						ul(li(reqRadio = input({ dbjs: user._isType, type: 'radio',
							renderOption: function (labelTxt) {
								var data = {};
								data.dom = li(label({ class: 'input-aside' },
									span(data.input = input()),
									span(labelTxt)));
								return data;
							}  }), " "))),
						li(
						"Please choose x docs in the list: ",
						ul(
							li(label({ class: 'input-aside' },
								input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
								span(user.getDescriptor('isBRequested').label))),
							li(label({ class: 'input-aside' },
								input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
								span(user.getDescriptor('isBRequested').label))),
							li({ class: 'disabled' },
								label({ class: 'input-aside' }, input({ dbjs: user._isBRequested,
															type: 'checkbox',
															disabled: 'disabled',
															value: 'checked' }),
									" ",
									span(user.getDescriptor('isBRequested').label))),
							li(label({ class: 'input-aside' },
								input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
								span(user.getDescriptor('isARequested').label))),
							li(label({ class: 'input-aside' },
								input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
								span(user.getDescriptor('isBRequested').label)))
						)
					)
					)
				),
				div({ class: 'guide-box' }, h2("Costs"),
					hr(),
					p("Lorem ipsum dolor sit amet, consectetur adipiscing elit." +
						" Etiam vestibulum dui mi, nec ultrices diam ultricies id. "),
					ul({ class: 'guide-costs-list' },
						li(span("Registration fee"), " ",
							span("$50'000")
							),
						li(span("Stamp duty for registration"), " ",
							span("$10'000")),
						li(span("Filing fees for memorandum"), " ",
							span("$45'000")),
						li({ class: 'guide-total-costs' },
								span("Total Costs:"), " ",
								span("$105'000")
							)
						)
				),
				button({ class: 'save-step-one', type: 'submit' },
					"Save and continue"
				)
			)
		);
	reqRadio._dbjsInput.listItems[0].appendChild(
		div({ class: 'disabler-range' }, // add 'disabled' class to disable ul
			ul(
				li(label({ class: 'input-aside' },
					input({ dbjs: user._isARequested, type: 'checkbox' }), " ",
					span(user.getDescriptor('isBRequested').label))),
				li(label({ class: 'input-aside' },
					input({ dbjs: user._isARequested,
						type: 'checkbox', value: 'checked' }), " ",
					span(user.getDescriptor('isBRequested').label)))
			),
			div({ class: 'disabler' })
			)
	);
};
<|endoftext|>


<commit_before>function circularIdenticonSVG(size, id, options){
	var idHash = string2ByteArray(md5(id));

	var fillColor = "#" + padFront(idHash[13].toString(16), 2) +
	                padFront(idHash[14].toString(16), 2) +
	                padFront(idHash[15].toString(16), 2);

	var shells = (options && options['shells']) || 4;
	var segments = (options && options['segments']) || Infinity;
	var innerRadius = Math.floor(size / ((shells * 2) + 1));
	var centerx = Math.floor(size / 2);
	var centery = Math.floor(size / 2);

	var svgNS = 'http://www.w3.org/2000/svg';
	var svg = document.createElementNS(svgNS, 'svg');

	svg.setAttribute('width', size);
	svg.setAttribute('height', size);
	svg.setAttribute('xmlns', svgNS);

	var innerCircle = document.createElementNS(svgNS, 'circle');

	innerCircle.setAttribute('cx', centerx);
	innerCircle.setAttribute('cy', centery);
	innerCircle.setAttribute('r', innerRadius + 1);
	innerCircle.setAttribute('fill', fillColor);

	svg.appendChild(innerCircle);

	for(var i = 1; i < shells; ++i){
		var theta1 = floorToMultiple(360 * (idHash[(i * 2) + 0] / 0xFF), 360 / segments);
		var theta2 = floorToMultiple(360 * (idHash[(i * 2) + 1] / 0xFF), 360 / segments)

		if(theta2 < theta1){
			var temp = theta1;
			theta1 = theta2;
			theta2 = temp;
		}

		var r1 = innerRadius * i;
		var r2 = innerRadius * (i + 1) + 1;

		var largeArcFlag = (theta2 - theta1) < 180 ? 0 : 1;

		var d = `M ${centerx + polar2CartesianX(r2, theta1)} ${centery + polar2CartesianY(r2, theta1)} ` +
		        `A ${r2} ${r2} 0 ${largeArcFlag} 1 ${centerx + polar2CartesianX(r2, theta2)} ${centery + polar2CartesianY(r2, theta2)} ` +
		        `L ${centerx + polar2CartesianX(r1, theta2)} ${centery + polar2CartesianY(r1, theta2)} ` +
		        `A ${r1} ${r1} 0 ${largeArcFlag} 0 ${centerx + polar2CartesianX(r1, theta1)} ${centery + polar2CartesianY(r1, theta1)} ` +
		        'Z';

		var arc = document.createElementNS(svgNS, 'path');

		arc.setAttribute('d', d);
		arc.setAttribute('fill', fillColor);

		svg.appendChild(arc);
	}

	return svg;
}

function string2ByteArray(string){
	var bytes = [];
	for(var i = 0; i < string.length; ++i){
		bytes[i] = parseInt(string.substr(i * 2, 2), 16);
	}
	return bytes;
}

function polar2CartesianX(r, theta){
	var radians = Math.PI * (theta - 90) / 180;
	return r * Math.cos(radians);
}

function polar2CartesianY(r, theta){
	var radians = Math.PI * (theta - 90) / 180;
	return r * Math.sin(radians);
}

function floorToMultiple(n, m){
	if(!m){
		return n;
	}
	n /= m;
	n = Math.floor(n);
	return n * m;
}
<commit_msg>Add vertical symmetry to circular<commit_after>function circularIdenticonSVG(size, id, options){
	var idHash = string2ByteArray(md5(id));

	var fillColor = "#" + padFront(idHash[13].toString(16), 2) +
	                padFront(idHash[14].toString(16), 2) +
	                padFront(idHash[15].toString(16), 2);

	var shells = (options && options['shells']) || 4;
	var segments = (options && options['segments']) || Infinity;
	var symmetric = (options && options['symmetric']) || false;
	var innerRadius = Math.floor(size / ((shells * 2) + 1));
	var centerx = Math.floor(size / 2);
	var centery = Math.floor(size / 2);

	var svgNS = 'http://www.w3.org/2000/svg';
	var svg = document.createElementNS(svgNS, 'svg');

	svg.setAttribute('width', size);
	svg.setAttribute('height', size);
	svg.setAttribute('xmlns', svgNS);

	var innerCircle = document.createElementNS(svgNS, 'circle');

	innerCircle.setAttribute('cx', centerx);
	innerCircle.setAttribute('cy', centery);
	innerCircle.setAttribute('r', innerRadius + 1);
	innerCircle.setAttribute('fill', fillColor);

	svg.appendChild(innerCircle);

	for(var i = 1; i < shells; ++i){
		var theta1 = floorToMultiple((symmetric ? 180 : 360) * (idHash[(i * 2) + 0] / 0xFF), 360 / segments);
		var theta2 = symmetric ? (360 - theta1) : floorToMultiple(360 * (idHash[(i * 2) + 1] / 0xFF), 360 / segments);

		console.log([theta1, i])

		if(theta2 < theta1){
			var temp = theta1;
			theta1 = theta2;
			theta2 = temp;
		}

		var r1 = innerRadius * i;
		var r2 = innerRadius * (i + 1) + 1;

		var largeArcFlag = (theta2 - theta1) < 180 ? 0 : 1;

		var d = `M ${centerx + polar2CartesianX(r2, theta1)} ${centery + polar2CartesianY(r2, theta1)} ` +
		        `A ${r2} ${r2} 0 ${largeArcFlag} 1 ${centerx + polar2CartesianX(r2, theta2)} ${centery + polar2CartesianY(r2, theta2)} ` +
		        `L ${centerx + polar2CartesianX(r1, theta2)} ${centery + polar2CartesianY(r1, theta2)} ` +
		        `A ${r1} ${r1} 0 ${largeArcFlag} 0 ${centerx + polar2CartesianX(r1, theta1)} ${centery + polar2CartesianY(r1, theta1)} ` +
		        'Z';

		var arc = document.createElementNS(svgNS, 'path');

		arc.setAttribute('d', d);
		arc.setAttribute('fill', fillColor);

		svg.appendChild(arc);
	}

	return svg;
}

function string2ByteArray(string){
	var bytes = [];
	for(var i = 0; i < string.length; ++i){
		bytes[i] = parseInt(string.substr(i * 2, 2), 16);
	}
	return bytes;
}

function polar2CartesianX(r, theta){
	var radians = Math.PI * (theta - 90) / 180;
	return r * Math.cos(radians);
}

function polar2CartesianY(r, theta){
	var radians = Math.PI * (theta - 90) / 180;
	return r * Math.sin(radians);
}

function floorToMultiple(n, m){
	if(!m){
		return n;
	}
	n /= m;
	n = Math.floor(n);
	return n * m;
}
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { compose } from 'redux';
import { reduxForm, Field, SubmissionError, propTypes as formPropTypes } from 'redux-form';

import {
  selectUsername,
  selectUserLevel,
  selectApiKey,
  selectApiKeyV2,
} from 'features/user/selectors';
import { doValuesMatch, numberValid } from 'common/validations';
import { WK_API_KEY_URL } from 'common/constants';

import H2 from 'common/components/H2';
import H4 from 'common/components/H4';
import Button from 'common/components/Button';
import settings from './actions';

import InputField from './InputField';
import RangeField from './RangeField';

import { Form, Section, SubSection, Block, ApiLink, Controls } from './styles';

const ResetProgress = ({ currentLevel, handleSubmit, submitting, submitSucceeded }) => {
  const tip = 'This action will reset all unlocked Vocab from higher levels; e.g. resetting to 19 resets Vocab from Levels 20 and up';

  return (
    <Form onSubmit={handleSubmit}>
      <Block>
        <Field
          name="resetLevel"
          label="Reset to level:"
          component={RangeField}
          note={tip}
          min={0}
          max={currentLevel}
          step={1}
        />
        <Field
          name="confirmation"
          label="Enter username to confirm:"
          placeholder="名前"
          component={InputField}
        />
      </Block>
      <Controls>
        <Button type="submit">
          {(submitting && 'Submitting') || (submitSucceeded && 'Reset!') || 'Reset Progress'}
        </Button>
      </Controls>
    </Form>
  );
};

ResetProgress.propTypes = {
  ...formPropTypes,
  currentLevel: PropTypes.number.isRequired,
};

const ResetProgressForm = compose(
  connect((state) => ({
    name: selectUsername(state),
    currentLevel: selectUserLevel(state),
    initialValues: { resetLevel: 0 },
  })),
  reduxForm({
    form: 'resetProgress',
    onSubmit: ({ confirmation, resetLevel }, dispatch, { name }) => {
      const errors = {
        confirmation: doValuesMatch(confirmation, name),
        resetLevel: numberValid(resetLevel),
      };
      if (Object.values(errors).some(Boolean)) {
        throw new SubmissionError(errors);
      } else {
        dispatch(settings.resetProgress.request({ level: resetLevel }));
      }
    },
  }),
)(ResetProgress);

const UpdateApiKey = ({ name, label, v2Exists, handleSubmit, submitting, submitSucceeded }) => {
  const isV1 = name === 'apiKey';
  // users that have added a v2 key shouldn't see v1 options anymore
  if (isV1 && v2Exists) {
    return null;
  }

  const icon = isV1 ? (
    undefined
  ) : (

      <ApiLink
        title="Find WK Access Token"
        name="HELP"
        color="black"
        href={WK_API_KEY_URL}
        external
      />

  );

  return (
    <Form onSubmit={handleSubmit}>
      <Field
        name={name}
        label={label}
        component={InputField}
        icon={icon}
        props={{ disabled: isV1, inputStyle: { flex: '0 1 360px', opacity: isV1 ? '0.5' : '1' } }}
      />

      {!isV1 && (
        <Controls>
          <Button type="submit">
            {(submitting && 'Updating') || (submitSucceeded && 'Updated!') || 'Update'}
          </Button>
        </Controls>
      )}
    </Form>
  );
};

UpdateApiKey.propTypes = formPropTypes;

const UpdateApiKeyForm = compose(
  connect((state) => ({
    name: 'apiKey',
    label: 'V1 Api Key (discontinued):',
    v2Exists: selectApiKeyV2(state) != null,
    initialValues: {
      apiKey: selectApiKey(state),
    },
  })),
  reduxForm({
    form: 'updateApiKey',
    enableReinitialize: true,
    onSubmit: (values, dispatch, props) => {
      dispatch(settings.save.request(values, { form: props }));
    },
  }),
)(UpdateApiKey);

const UpdateApiKeyV2Form = compose(
  connect((state) => ({
    name: 'apiKeyV2',
    label: 'Personal Access Token (V2 Api):',
    initialValues: {
      apiKeyV2: selectApiKeyV2(state),
    },
  })),
  reduxForm({
    form: 'updateApiKeyV2',
    enableReinitialize: true,
    onSubmit: (values, dispatch, props) => {
      dispatch(settings.save.request(values, { form: props }));
    },
  }),
)(UpdateApiKey);

function AccountForm() {
  return (

Account

      <UpdateApiKeyForm />
      <UpdateApiKeyV2Form />
      <SubSection>

Reset Kaniwani Progress

        <ResetProgressForm />
      </SubSection>

  );
}

export default AccountForm;
<commit_msg>feat: embelish settings note, relocate below field<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { compose } from 'redux';
import { reduxForm, Field, SubmissionError, propTypes as formPropTypes } from 'redux-form';

import {
  selectUsername,
  selectUserLevel,
  selectApiKey,
  selectApiKeyV2,
} from 'features/user/selectors';
import { doValuesMatch, numberValid } from 'common/validations';
import { WK_API_KEY_URL } from 'common/constants';

import H2 from 'common/components/H2';
import H4 from 'common/components/H4';
import Button from 'common/components/Button';
import settings from './actions';

import InputField from './InputField';
import RangeField from './RangeField';

import { Form, Section, SubSection, Block, ApiLink, Controls } from './styles';

const ResetProgress = ({ currentLevel, handleSubmit, submitting, submitSucceeded }) => {
  const tip = 'This action will reset all unlocked vocab above the selected level; e.g. resetting to 19 resets the SRS (and locks) Levels 20 and above. Visit the Vocabulary pages to unlock them when you are ready to begin reviewing again.';

  return (
    <Form onSubmit={handleSubmit}>
      <Block>
        <Field
          name="resetLevel"
          label="Reset to level:"
          component={RangeField}
          min={0}
          max={currentLevel}
          step={1}
        />
        <Field
          name="confirmation"
          label="Enter username to confirm:"
          placeholder="名前"
          note={tip}
          component={InputField}
        />
      </Block>
      <Controls>
        <Button type="submit">
          {(submitting && 'Submitting') || (submitSucceeded && 'Reset!') || 'Reset Progress'}
        </Button>
      </Controls>
    </Form>
  );
};

ResetProgress.propTypes = {
  ...formPropTypes,
  currentLevel: PropTypes.number.isRequired,
};

const ResetProgressForm = compose(
  connect((state) => ({
    name: selectUsername(state),
    currentLevel: selectUserLevel(state),
    initialValues: { resetLevel: 0 },
  })),
  reduxForm({
    form: 'resetProgress',
    onSubmit: ({ confirmation, resetLevel }, dispatch, { name }) => {
      const errors = {
        confirmation: doValuesMatch(confirmation, name),
        resetLevel: numberValid(resetLevel),
      };
      if (Object.values(errors).some(Boolean)) {
        throw new SubmissionError(errors);
      } else {
        dispatch(settings.resetProgress.request({ level: resetLevel }));
      }
    },
  }),
)(ResetProgress);

const UpdateApiKey = ({ name, label, v2Exists, handleSubmit, submitting, submitSucceeded }) => {
  const isV1 = name === 'apiKey';
  // users that have added a v2 key shouldn't see v1 options anymore
  if (isV1 && v2Exists) {
    return null;
  }

  const icon = isV1 ? (
    undefined
  ) : (

      <ApiLink
        title="Find WK Access Token"
        name="HELP"
        color="black"
        href={WK_API_KEY_URL}
        external
      />

  );

  return (
    <Form onSubmit={handleSubmit}>
      <Field
        name={name}
        label={label}
        component={InputField}
        icon={icon}
        props={{ disabled: isV1, inputStyle: { flex: '0 1 360px', opacity: isV1 ? '0.5' : '1' } }}
      />

      {!isV1 && (
        <Controls>
          <Button type="submit">
            {(submitting && 'Updating') || (submitSucceeded && 'Updated!') || 'Update'}
          </Button>
        </Controls>
      )}
    </Form>
  );
};

UpdateApiKey.propTypes = formPropTypes;

const UpdateApiKeyForm = compose(
  connect((state) => ({
    name: 'apiKey',
    label: 'V1 Api Key (discontinued):',
    v2Exists: selectApiKeyV2(state) != null,
    initialValues: {
      apiKey: selectApiKey(state),
    },
  })),
  reduxForm({
    form: 'updateApiKey',
    enableReinitialize: true,
    onSubmit: (values, dispatch, props) => {
      dispatch(settings.save.request(values, { form: props }));
    },
  }),
)(UpdateApiKey);

const UpdateApiKeyV2Form = compose(
  connect((state) => ({
    name: 'apiKeyV2',
    label: 'Personal Access Token (V2 Api):',
    initialValues: {
      apiKeyV2: selectApiKeyV2(state),
    },
  })),
  reduxForm({
    form: 'updateApiKeyV2',
    enableReinitialize: true,
    onSubmit: (values, dispatch, props) => {
      dispatch(settings.save.request(values, { form: props }));
    },
  }),
)(UpdateApiKey);

function AccountForm() {
  return (

Account

      <UpdateApiKeyForm />
      <UpdateApiKeyV2Form />
      <SubSection>

Reset Kaniwani Progress

        <ResetProgressForm />
      </SubSection>

  );
}

export default AccountForm;
<|endoftext|>


<commit_before>/* --------------------------------------------------------------------------- */
window.DEBUG = (function() {
    //--------------------------------------------------
    var debug_enable = false;
    //----------
    var colors = {'Г':'blue', 'ПР':'gray', 'С':'red', 'Н':'green', 'М':'black'};
    //----------
    var preparsing = {
        panel:      '',
    };
    //----------
    var objects = {
        panel:      'debug-objects-list',
    };
    //----------
    var preparsing = {
        panel:      'debug-preparsing-objects',
    };
    //----------
    var words = {
        full_list:  {panel:     'debug-words-list-full'},
        short_list: {panel:     'debug-words-list-short'}
    };
    //--------------------------------------------------
    return {
        //--------------------------------------------------
        Enable: function () {
            debug_enable = true;
        },
        //--------------------------------------------------
        Disable: function () {
            debug_enable = false;
        },
        //--------------------------------------------------
        isEnable: function () {
            return debug_enable;
        },
        //--------------------------------------------------
        setPanelForPreparsing: function (_name) {
            _name = _name.trim();
            //----------
            preparsing.panel = _name;
            //----------
            if (debug_enable == false) {return;} // end if
            //----------
            if (_name == '') {

            } else {

            }// end if
        },
        //--------------------------------------------------
        setPanelForObjects: function (_name) {
            _name = _name.trim();
            //----------
            objects.panel = _name;
            //----------
            if (debug_enable == false) {return;} // end if
            //----------
            if (_name == '') {
                SCREEN.Clear('debug-objects-list');
            } else {

            }// end if
        },
        //--------------------------------------------------
        updatePanelForObjects: function () {
            if (debug_enable == false || objects.panel == '') {return;} // end if
            //----------
            var txt_objects = AZ.available_objects(true);
            //----------
            SCREEN.Clear('debug-objects-list');
            //----------
            if (txt_objects.length > 0) {
                SCREEN.Out(txt_objects.join('
'), 'debug-objects-list');
            } // end if
            //----------
        },
        //--------------------------------------------------
        updateWordsFullList: function () {
            if (debug_enable == false || words.full_list.panel == '') {return;} // end if
            //----------
            AUTOCOMPLETE.start(0);
            //----------
            var output = '';
            //----------
            if (AUTOCOMPLETE.getActionFlag() == true) {
                output += '<ввод>
';
            } // end if
            //----------
            while (AUTOCOMPLETE.next(0) != false) {
                var word    = AUTOCOMPLETE.word(0);
                var morph   = AUTOCOMPLETE.morph(0);
                //----------
                output += ''+word+'
';
            } // end for
            //----------
            SCREEN.Clear(words.full_list.panel);
            SCREEN.Out(output, words.full_list.panel);
            //----------
        },
        //--------------------------------------------------
        updateWordsShortList: function () {
            if (debug_enable == false || words.short_list.panel == '') {return;} // end if
            //----------
            AUTOCOMPLETE.start(1);
            //----------
            var output = '';
            //----------
            while (AUTOCOMPLETE.next(1) != false) {
                var word    = AUTOCOMPLETE.word(1);
                var morph   = AUTOCOMPLETE.morph(1);
                //----------
                output += '
'+word+'
';
            } // end for
            //----------
            if (AUTOCOMPLETE.getActionFlag() == true) {
                output += '<ввод>';
            } // end if
            //----------
            SCREEN.Clear(words.short_list.panel);
            SCREEN.Out(output,words.short_list.panel);
            //----------
        },
        //--------------------------------------------------
        updatePreparsingData: function (CMD) {
            if (debug_enable == false || preparsing.panel == '') {return;} // end if
            //----------
            var br      = '
';
            var output  = '';
            //----------
            output += 'Команда: "'+CMD.phrase+'"'+br;
            output += 'глагол: '+(CMD.verb == null ? '-' : DICTIONARY.getBase(CMD.verb.bid).base+' ('+CMD.verb.bid+')')+'
';
            //----------
            for (var priority=1; priority<=3; priority++) {
                output += '#'+priority+': '+(CMD.params[priority] == null ? '-' : '');
                if (CMD.params[priority] != null) {
                    output += 'п: ' + (CMD.params[priority].prep == null ? '-' : DICTIONARY.getBase(CMD.params[priority].prep.bid).base+' ('+CMD.params[priority].prep.bid+')');
                    //----------
                    output += ', с: '+DICTIONARY.getBase(CMD.params[priority].bid).base+' ('+CMD.params[priority].bid+')';
                } // end if
                //----------
                output += ', о: '+(CMD.objects[priority] == null ? '-' : CMD.objects[priority].ID);
                //----------
                if (CMD.objects[priority] != null) {
                    var action_id = CMD.actions[priority];
                    //----------
                    if (action_id != null) {
                        output += ', a: #'+action_id;
                    } // end if
                } // end if
                //----------
                output += '
';
            } // end for priority
            //----------
            SCREEN.Clear(preparsing.panel);
            SCREEN.Out(output,preparsing.panel);
            //----------
        },
        //--------------------------------------------------
    };
})(); // end object "DEBUG"
/* --------------------------------------------------------------------------- */
<commit_msg>Перенесена функция дополнения слова в команде игрока<commit_after>/* --------------------------------------------------------------------------- */
window.DEBUG = (function() {
    //--------------------------------------------------
    var debug_enable = false;
    //----------
    var colors = {'Г':'blue', 'ПР':'gray', 'С':'red', 'Н':'green', 'М':'black'};
    //----------
    var preparsing = {
        panel:      '',
    };
    //----------
    var objects = {
        panel:      'debug-objects-list',
    };
    //----------
    var preparsing = {
        panel:      'debug-preparsing-objects',
    };
    //----------
    var words = {
        full_list:  {panel:     'debug-words-list-full'},
        short_list: {panel:     'debug-words-list-short'}
    };
    //--------------------------------------------------
    return {
        //--------------------------------------------------
        Enable: function () {
            debug_enable = true;
        },
        //--------------------------------------------------
        Disable: function () {
            debug_enable = false;
        },
        //--------------------------------------------------
        isEnable: function () {
            return debug_enable;
        },
        //--------------------------------------------------
        setPanelForPreparsing: function (_name) {
            _name = _name.trim();
            //----------
            preparsing.panel = _name;
            //----------
            if (debug_enable == false) {return;} // end if
            //----------
            if (_name == '') {

            } else {

            }// end if
        },
        //--------------------------------------------------
        setPanelForObjects: function (_name) {
            _name = _name.trim();
            //----------
            objects.panel = _name;
            //----------
            if (debug_enable == false) {return;} // end if
            //----------
            if (_name == '') {
                SCREEN.Clear('debug-objects-list');
            } else {

            }// end if
        },
        //--------------------------------------------------
        updatePanelForObjects: function () {
            if (debug_enable == false || objects.panel == '') {return;} // end if
            //----------
            var txt_objects = AZ.available_objects(true);
            //----------
            SCREEN.Clear('debug-objects-list');
            //----------
            if (txt_objects.length > 0) {
                SCREEN.Out(txt_objects.join('
'), 'debug-objects-list');
            } // end if
            //----------
        },
        //--------------------------------------------------
        updateWordsFullList: function () {
            if (debug_enable == false || words.full_list.panel == '') {return;} // end if
            //----------
            AUTOCOMPLETE.start(0);
            //----------
            var output = '';
            //----------
            if (AUTOCOMPLETE.getActionFlag() == true) {
                output += '<ввод>
';
            } // end if
            //----------
            while (AUTOCOMPLETE.next(0) != false) {
                var word    = AUTOCOMPLETE.word(0);
                var morph   = AUTOCOMPLETE.morph(0);
                //----------
                output += ''+word+'
';
            } // end for
            //----------
            SCREEN.Clear(words.full_list.panel);
            SCREEN.Out(output, words.full_list.panel);
            //----------
        },
        //--------------------------------------------------
        updateWordsShortList: function () {
            if (debug_enable == false || words.short_list.panel == '') {return;} // end if
            //----------
            AUTOCOMPLETE.start(1);
            //----------
            var output = '';
            //----------
            while (AUTOCOMPLETE.next(1) != false) {
                var word    = AUTOCOMPLETE.word(1);
                var morph   = AUTOCOMPLETE.morph(1);
                //----------
                output += '
'+word+'
';
            } // end for
            //----------
            /*if (AUTOCOMPLETE.getActionFlag() == true) {
                output += '<ввод>';
            } // end if*/
            //----------
            SCREEN.Clear(words.short_list.panel);
            SCREEN.Out(output,words.short_list.panel);
            //----------
        },
        //--------------------------------------------------
        updatePreparsingData: function (CMD) {
            if (debug_enable == false || preparsing.panel == '') {return;} // end if
            //----------
            var br      = '
';
            var output  = '';
            //----------
            output += 'Команда: "'+CMD.phrase+'"'+br;
            output += 'глагол: '+(CMD.verb == null ? '-' : DICTIONARY.getBase(CMD.verb.bid).base+' ('+CMD.verb.bid+')')+'
';
            //----------
            for (var priority=1; priority<=3; priority++) {
                output += '#'+priority+': '+(CMD.params[priority] == null ? '-' : '');
                if (CMD.params[priority] != null) {
                    output += 'п: ' + (CMD.params[priority].prep == null ? '-' : DICTIONARY.getBase(CMD.params[priority].prep.bid).base+' ('+CMD.params[priority].prep.bid+')');
                    //----------
                    output += ', с: '+DICTIONARY.getBase(CMD.params[priority].bid).base+' ('+CMD.params[priority].bid+')';
                } // end if
                //----------
                output += ', о: '+(CMD.objects[priority] == null ? '-' : CMD.objects[priority].ID);
                //----------
                if (CMD.objects[priority] != null) {
                    var action_id = CMD.actions[priority];
                    //----------
                    if (action_id != null) {
                        output += ', a: #'+action_id;
                    } // end if
                } // end if
                //----------
                output += '
';
            } // end for priority
            //----------
            SCREEN.Clear(preparsing.panel);
            SCREEN.Out(output,preparsing.panel);
            //----------
        },
        //--------------------------------------------------
    };
})(); // end object "DEBUG"
/* --------------------------------------------------------------------------- */
<|endoftext|>


<commit_before>// ==UserScript==
// @name        Scratchy Stuff
// @namespace   http://scratch.cf
// @include     http://scratch.mit.edu/*
// @version     0.2.1
// @grant       none
// ==/UserScript==

var queryString = {};
window.location.search.replace(/([^?=&]+)(=([^&]*))?/g, function($0, $1, $2, $3) { queryString[$1] = $3; });

var username = Scratch.INIT_DATA.LOGGED_IN_USER.model ? Scratch.INIT_DATA.LOGGED_IN_USER.model.username : null;

var extPresets = {
  'Mesh': {url: 'https://raw.githubusercontent.com/bobbybee/mesh-2.0/master/ext.js', author: 'bobbybee'},
  'Scratch Cloud': {url: 'https://dl.dropboxusercontent.com/u/6274273/web/scratchcloud/icon.js', author: 'MathWizz'},
  'Image Stuff': {url: 'http://scratch.cf/extensions/imagestuff.js', author: 'djdolphin'},
  'Cool helpful things extension': {url: 'http://textuploader.com/07bg/raw', author: 'PullJosh'},
  'More Math': {url: 'http://savakamyimages00000.weebly.com/uploads/6/4/5/3/6453739/more_math.js', author: 'savaka'},
  'Debugging': {url: 'http://savakamyimages00000.weebly.com/uploads/6/4/5/3/6453739/javascript_dialogs.js', author: 'savaka'},
  'Javascript Dialogs': {url: 'http://savakamyimages00000.weebly.com/uploads/6/4/5/3/6453739/javascript_dialogs.js', author: 'savaka'},
  'Link Opener': {url: 'http://savakamyimages00000.weebly.com/uploads/6/4/5/3/6453739/link_opener.js', author: 'savaka'},
  'littleBits': {url: 'https://raw.githubusercontent.com/khanning/scratch-littlebits-extension/master/littlebits_extension.js', author: 'khanning'},
  'Data Blocks': {url: 'https://raw.githubusercontent.com/Thepuzzlegame/My-Scratch-Extensions/master/data_extension.js', author: 'Thepuzzlegame'},
  'Infinity Reporter': {url: 'https://raw.githubusercontent.com/Thepuzzlegame/My-Scratch-Extensions/master/infinity_reporter.js', author: 'Thepuzzlegame'},
  'Extension Loader': {url: 'https://raw.githubusercontent.com/Thepuzzlegame/My-Scratch-Extensions/master/extension_loader.js', author: 'Thepuzzlegame'},
  'Alarm extension': {url: 'https://raw.githubusercontent.com/LLK/scratch-extension-docs/master/alarm_extension.js', author: 'sdg1'},
  'Browser Stuff': {url: 'https://raw.githubusercontent.com/LLK/scratch-extension-docs/master/browser_extension.js', author: 'grokblah'},
  'Joystick': {url: 'https://raw.githubusercontent.com/LLK/scratch-extension-docs/master/joystickExtension.js', author: 'sdg1'},
  'Local Storage': {url: 'https://raw.githubusercontent.com/LLK/scratch-extension-docs/master/localstorage_extension.js', author: 'sdg1'},
  'PicoBoard': {url: 'https://raw.githubusercontent.com/LLK/scratch-extension-docs/master/picoExtension.js', author: 'grokblah'},
  'PicoBoard Fixed': {url: 'http://www.picaxe.com/downloads/scratch/scraxepicoextension.js', 'author': 'SCRAXE'},
  'Power Extension': {url: 'https://raw.githubusercontent.com/LLK/scratch-extension-docs/master/power_extension.js', author: 'sdg1'},
  'Random wait extension': {url: 'https://raw.githubusercontent.com/LLK/scratch-extension-docs/master/random_wait_extension.js', author: 'sdg1'},
  'Speech to Text': {url: 'https://raw.githubusercontent.com/LLK/scratch-extension-docs/master/speech_to_text_extension.js', author: 'sdg1'},
  'Text to Speech': {url: 'https://raw.githubusercontent.com/LLK/scratch-extension-docs/master/text_to_speech_extension.js', author: 'sdg1'},
  'Text to Speech Simple': {url: 'https://raw.githubusercontent.com/LLK/scratch-extension-docs/master/text_to_speech_simple_extension.js', author: 'sdg1'},
  'Weather Extension': {url: 'https://raw.githubusercontent.com/LLK/scratch-extension-docs/master/weather_extension.js', author: 'sdg1'},
  'ScratchExt': {url: 'http://stefanbates.com/library/import.js', author: 'GrannyCookies, Yoda3D, Thistleeverfreen'}
};
//Thanks, Thepuzzlegame!

function createButton() {
  $('head').append('');

  //Scratchy Stuff Extension Library
  var extLibrary = $('

Extension	Author

'), extTable = $(''),
      extMenu = extLibrary.find('#scratchystuffextmenu');
  $.each(extPresets, function(extName, ext) {
    extMenu.append($('

')
      .append($('	').append($('').text(extName).attr('data-extension', ext.url).click(function() {
        ScratchExtensions.loadExternalJS($(this).attr('data-extension'));
      })))
      .append($('	').append($('').text(ext.author).attr('href', '/users/' + ext.author + '/')))
    );
  });
  extLibrary.dialog({
    autoOpen: false,
    dialogClass: 'scratchystuffextlib',
    title: 'Scratchy Stuff Extension Library',
    width: 365,
    minWidth: 365,
    maxWidth: 365
  });

  //Menu
  $('body').append('

Scratchy Stuff

');
  //Load extension from URL
  var menu = $('#scratchystuffmenu');
  menu.append($('
Load extension from URL
').click(function() {
    var extensionURL = prompt('What URL?');
    if (!extensionURL) return;
    ScratchExtensions.loadExternalJS(extensionURL);
  }));
  //Load asset from URL
  menu.append($('
Load asset from URL
').click(function() {
    var assetURL = prompt('What URL?');
    if (!assetURL) return;
    var fileName = assetURL.slice(assetURL.lastIndexOf('/') + 1);
    assetURL = 'http://www.corsproxy.com/' + assetURL.replace(/^https?:\/\//, '');
    var xhr = new XMLHttpRequest();
    xhr.onload = function() {
      var scratchData = ',' + btoa(String.fromCharCode.apply(null, new Uint8Array(this.response)));
      Scratch.FlashApp.ASobj.ASdropFile(fileName, scratchData, 0, 0);
    };
    xhr.open('GET', assetURL);
    xhr.responseType = 'arraybuffer';
    xhr.send();
  }));
  //Load extension from library
  menu.append($('
SS Extension Library
').click(function() {
    extLibrary.dialog('open');
  }));
  //Self-remix
  if (data.project.creator == username) menu.append($('
Remix project
').click(JSremixProject));
}

function showSettings() {
  $('.tabs-index > ul > li').removeClass('active');
  $('.scratchystuffsettings').addClass('active');
  $('#main-content').text('Coming soon!');
}

if (username) {
  if (/^\/projects\/\d+\/$/.test(location.pathname)) {
    createButton();
    //Download
    $('#see-inside').parent().before($('
Download
').click(JSdownloadProject));
    $('#see-inside').parent().css('display', 'inline-block');
  }
  if (/^\/accounts\/(password_change|email_change|change_country)\/$/.test(location.pathname)) {
  	$('.tabs-index > ul').append('
Scratchy Stuff
');
    if (location.hash == '#scratchystuff') showSettings();
  	else $(window).on('hashchange', function() { if (location.hash == '#scratchystuff') showSettings(); });
  }
}
<commit_msg>URLs Clean Up<commit_after>// ==UserScript==
// @name        Scratchy Stuff
// @namespace   http://scratch.cf
// @include     http://scratch.mit.edu/*
// @version     0.2.1
// @grant       none
// ==/UserScript==

var queryString = {};
window.location.search.replace(/([^?=&]+)(=([^&]*))?/g, function($0, $1, $2, $3) { queryString[$1] = $3; });

var username = Scratch.INIT_DATA.LOGGED_IN_USER.model ? Scratch.INIT_DATA.LOGGED_IN_USER.model.username : null;

var extPresets = {
  'Mesh': {url: 'https://cdn.rawgit.com/bobbybee/mesh-2.0/master/ext.js', author: 'bobbybee'},
  'Scratch Cloud': {url: 'https://dl.dropboxusercontent.com/u/6274273/web/scratchcloud/icon.js', author: 'MathWizz'},
  //'Image Stuff': {url: 'http://scratch.cf/extensions/imagestuff.js', author: 'djdolphin'},
  'Cool helpful things extension': {url: 'http://textuploader.com/07bg/raw', author: 'PullJosh'},
  'More Math': {url: 'http://savakamyimages00000.weebly.com/uploads/6/4/5/3/6453739/more_math.js', author: 'savaka'},
  'Javascript Dialogs': {url: 'http://savakamyimages00000.weebly.com/uploads/6/4/5/3/6453739/javascript_dialogs.js', author: 'savaka'},
  'Link Opener': {url: 'http://savakamyimages00000.weebly.com/uploads/6/4/5/3/6453739/link_opener.js', author: 'savaka'},
  'littleBits': {url: 'https://cdn.rawgit.com/khanning/scratch-littlebits-extension/master/littlebits_extension.js', author: 'khanning'},
  //'Data Blocks': {url: 'https://raw.githubusercontent.com/Thepuzzlegame/My-Scratch-Extensions/master/data_extension.js', author: 'Thepuzzlegame'},
  //'Infinity Reporter': {url: 'https://raw.githubusercontent.com/Thepuzzlegame/My-Scratch-Extensions/master/infinity_reporter.js', author: 'Thepuzzlegame'},
  //'Extension Loader': {url: 'https://raw.githubusercontent.com/Thepuzzlegame/My-Scratch-Extensions/master/extension_loader.js', author: 'Thepuzzlegame'},
  'Alarm extension': {url: 'https://cdn.rawgit.com/LLK/scratch-extension-docs/master/alarm_extension.js', author: 'sdg1'},
  'Browser Stuff': {url: 'https://cdn.rawgit.com/LLK/scratch-extension-docs/master/browser_extension.js', author: 'grokblah'},
  'Joystick': {url: 'https://cdn.rawgit.com/LLK/scratch-extension-docs/master/joystickExtension.js', author: 'sdg1'},
  'Local Storage': {url: 'https://cdn.rawgit.com/LLK/scratch-extension-docs/master/localstorage_extension.js', author: 'sdg1'},
  'PicoBoard': {url: 'https://cdn.rawgit.com/LLK/scratch-extension-docs/master/picoExtension.js', author: 'grokblah'},
  'PicoBoard Fixed': {url: 'http://www.picaxe.com/downloads/scratch/scraxepicoextension.js', 'author': 'SCRAXE'},
  'Power Extension': {url: 'https://cdn.rawgit.com/LLK/scratch-extension-docs/master/power_extension.js', author: 'sdg1'},
  'Random wait extension': {url: 'https://cdn.rawgit.com/LLK/scratch-extension-docs/master/random_wait_extension.js', author: 'sdg1'},
  'Speech to Text': {url: 'https://cdn.rawgit.com/LLK/scratch-extension-docs/master/speech_to_text_extension.js', author: 'sdg1'},
  'Text to Speech': {url: 'https://cdn.rawgit.com/LLK/scratch-extension-docs/master/text_to_speech_extension.js', author: 'sdg1'},
  'Text to Speech Simple': {url: 'https://cdn.rawgit.com/LLK/scratch-extension-docs/master/text_to_speech_simple_extension.js', author: 'sdg1'},
  'Weather Extension': {url: 'https://cdn.rawgit.com/LLK/scratch-extension-docs/master/weather_extension.js', author: 'sdg1'},
  'ScratchExt': {url: 'http://stefanbates.com/library/install.js', author: 'GrannyCookies, Yoda3D, Thistleeverfreen'}
};
//Thanks, Thepuzzlegame!

function createButton() {
  $('head').append('');

  //Scratchy Stuff Extension Library
  var extLibrary = $('

Extension	Author

'), extTable = $(''),
      extMenu = extLibrary.find('#scratchystuffextmenu');
  $.each(extPresets, function(extName, ext) {
    extMenu.append($('

')
      .append($('	').append($('').text(extName).attr('data-extension', ext.url).click(function() {
        ScratchExtensions.loadExternalJS($(this).attr('data-extension'));
      })))
      .append($('	').append($('').text(ext.author).attr('href', '/users/' + ext.author + '/')))
    );
  });
  extLibrary.dialog({
    autoOpen: false,
    dialogClass: 'scratchystuffextlib',
    title: 'Scratchy Stuff Extension Library',
    width: 365,
    minWidth: 365,
    maxWidth: 365
  });

  //Menu
  $('body').append('

Scratchy Stuff

');
  //Load extension from URL
  var menu = $('#scratchystuffmenu');
  menu.append($('
Load extension from URL
').click(function() {
    var extensionURL = prompt('What URL?');
    if (!extensionURL) return;
    ScratchExtensions.loadExternalJS(extensionURL);
  }));
  //Load asset from URL
  menu.append($('
Load asset from URL
').click(function() {
    var assetURL = prompt('What URL?');
    if (!assetURL) return;
    var fileName = assetURL.slice(assetURL.lastIndexOf('/') + 1);
    assetURL = 'http://www.corsproxy.com/' + assetURL.replace(/^https?:\/\//, '');
    var xhr = new XMLHttpRequest();
    xhr.onload = function() {
      var scratchData = ',' + btoa(String.fromCharCode.apply(null, new Uint8Array(this.response)));
      Scratch.FlashApp.ASobj.ASdropFile(fileName, scratchData, 0, 0);
    };
    xhr.open('GET', assetURL);
    xhr.responseType = 'arraybuffer';
    xhr.send();
  }));
  //Load extension from library
  menu.append($('
SS Extension Library
').click(function() {
    extLibrary.dialog('open');
  }));
  //Self-remix
  if (data.project.creator == username) menu.append($('
Remix project
').click(JSremixProject));
}

function showSettings() {
  $('.tabs-index > ul > li').removeClass('active');
  $('.scratchystuffsettings').addClass('active');
  $('#main-content').text('Coming soon!');
}

if (username) {
  if (/^\/projects\/\d+\/$/.test(location.pathname)) {
    createButton();
    //Download
    $('#see-inside').parent().before($('
Download
').click(JSdownloadProject));
    $('#see-inside').parent().css('display', 'inline-block');
  }
  if (/^\/accounts\/(password_change|email_change|change_country)\/$/.test(location.pathname)) {
  	$('.tabs-index > ul').append('
Scratchy Stuff
');
    if (location.hash == '#scratchystuff') showSettings();
  	else $(window).on('hashchange', function() { if (location.hash == '#scratchystuff') showSettings(); });
  }
}
<|endoftext|>