jeudi 13 août 2015

If argument is blank do not append to string

I want to write a simple javascript function to append to a string of values given arguments, but only if the arguments have values. Here is an example:

function foo(bar){
  return "hello" + bar;  
}

If I run foo() I will get "helloundefined" I want it to just return "hello" and if i run foo('world') that works right now with "helloworld"

I was thinking I could do something like:

return "hello" + null || bar but i would just get "hellonull"

or

return "hello" + if(bar){bar} is invalid syntax.



via Chebli Mohamed

Blanket.js code is instrumented, but will not display when running with Mocha and chai and AMD RequireJS

I've google and SO'd extensively for the answer, and have a found a number of repositories and tutorials with something that wasn't quite what I was looking for, but I attempted to adapt anyway.

According to earlier issues I've looked through, the key to Blanket.js' coverage working is that window._$blanket is defined, and mine is, along with the instrumentations of my source.

However, when my testrunner.html loads, it tends to alternate between a full fledged blanket.js report, or the actual mocha tests (with checkmarks and css and whatnot). I'm inclined to think it has to do with the source being asynchronously loaded with RequireJS.

Here's my testRunner.html:

<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="/js/vendor/npm/mocha/mocha.css" />
    <script type="text/javascript" src="js/vendor/mocha/mocha.js"></script>
    <script type="text/javascript" src="js/vendor/require.js"></script>
    <script type="text/javascript" src="/js/test/unit/config.js"></script>
    <script type="text/javascript" src="/js/main.js"></script>
</head>
<body>
<script type="text/javascript" data-cover-only="/js/test/unit/js/some/path/to/"
        src="http://ift.tt/1Wnooca">
</script>
<script type="text/javascript" src="/js/vendor/blanket/src/adapters/mocha-blanket.js"></script>
<script>

    require(['mocha', 'chai', 'chai-jquery', 'sinon'], function(mocha, chai, chaiJquery, sinon) {

        // Init Chai
        chai.should(); //initializes chai.should()
        chai.use(chaiJquery);
        expect = chai.expect;

        mocha.setup({
            ui: 'bdd',
            ignoreLeaks: true
        });

        require([
            '../js/test/unit/js/some/path/to/AModel.test.js',
            '../js/test/unit/js/some/path/to/SModel.test.js',
        ], function(require) {
            mocha.run();
        });
    });
</script>
<div id="mocha"></div>
</body>
</html>

and here's the somemodel.test.js file:

define([
        "app",
        "moment",
        "util/utils",
    ],
    function(app) {

        describe('AModel', function() {

            beforeEach(function () {
                this.AModel = new AModel ({
                    type: undefined,
                    name: undefined, 
                });

                sinon.stub(this.AModel, 'fetch').yieldsTo('success', {
                    fun: "funk"
                });
            });

            afterEach(function () {
                this.AModel = null;
            });




            it('should get a node returned from a given ID', function() {
                var that = this;
                var nodeModel = this.AModel.getNode("node1");
                expect(nodeModel instanceof SModel).to.be.true;
            });

            it('should get the peer nodes of an object', function() {
                var temp = this.AModel.getPeerNodes("node1", "fakeType" );
                expect(temp).to.have.length(10);
            });


        });
    }
);



via Chebli Mohamed

wait for css_parser.getCSSFiles()

I want to render page when CSS will be loaded. Function css_parser.getCSSFiles() reads file asynchronously and sends CSS content to variable css.cssFile . How I can force res.render to wait for end of file reading?

router.get('/main', function(req, res) {

    css_parser.getCSSFiles();
    app.locals.css = css.cssFile;

    res.render('ua', {
        css: app.locals.css,
    });

});

UPDATE: So basically, I want to read also other kind of files. getJSFile is similar to getCSSFiles and I also initialize it before res.render

getJSFile: function(directory, file, variable) {
    fs.readFile(directory + file, 'utf8', function(err, data) {
        if (err) {
            return console.log(err);
        }
        variable.push(data);
});



via Chebli Mohamed

How to pass Javascript date object (formatted datetime) from Laravel API

My Laravel 5 API pulls regular datetime columns from my MySQL db. My JSON datetime output looks like this:

2015-08-13 13:45:00

but the widget reading my JSON expects a JavaScript Date Object? What would be the syntax to pass my datetime as a JavaScript Date Object?

My current Laravel method looks like so:

public function transform($events)
{
    return [
        'startdt' => $events['event_start'],
        'enddt'   => $events['event_end'],
    ];
}

This is the code I have in my widget JS file:

'use strict';

angular
  .module('demo', ['mwl.calendar', 'ui.bootstrap', 'ngTouch', 'ngAnimate'])
  .controller('MainCtrl', function ($modal, moment, $http) {

var vm = this;
vm.calendarView = 'month';
vm.calendarDay = new Date();

$http.get('http://ift.tt/1Wnooc0').success(function(events) {    
    vm.events = events.events;
}); 



via Chebli Mohamed

Handsontable dropdowns with multiple selections

I am trying to extend the handsontable plugin to support multiple selections in its dropdown list. I have already tried extending the base Editor built into the library by modifying the 'dropdownEditor' as suggested http://ift.tt/1IPeF4Y. I spent hours reading and searching through the source for keywords but I am not coming up with anything of real use.

I do not mind if this is answered using the Angular extension or another native ECMA5 or 6 way of extending the http://ift.tt/1FAcz8U plugin.

So far my only thoughts were to actually extend the framework with this bit of code following the patterns that exist. I added all LOC below that are pointing to: multiselect or Handsontable.MultiselectDropdownCell copied the dropdown method, called the new name and everything works, however still cannot see where I could begin to find what I am looking for.

Handsontable.MultiselectDropdownCell ={
  editor: getEditorConstructor('multiselectdropdown'),
  renderer: getRenderer('autocomplete')
};

Handsontable.cellTypes = {
  text: Handsontable.TextCell,
  date: Handsontable.DateCell,
  numeric: Handsontable.NumericCell,
  checkbox: Handsontable.CheckboxCell,
  autocomplete: Handsontable.AutocompleteCell,
  handsontable: Handsontable.HandsontableCell,
  password: Handsontable.PasswordCell,
  dropdown: Handsontable.DropdownCell,
  multiselect: Handsontable.MultiselectDropdownCell
};

Handsontable.cellLookup = { validator: {
    numeric: Handsontable.NumericValidator,
    autocomplete: Handsontable.AutocompleteValidator
}};

I have at a modified version of dropdown editor in place that looks like:

import {getEditor, registerEditor} from './../editors.js';
import {AutocompleteEditor} from './autocompleteEditor.js';

/**
 * @private
 * @editor MultiSelectDropdownEditor
 * @class MultiSelectDropdownEditor
 * @dependencies AutocompleteEditor
 */
class MultiSelectDropdownEditor extends AutocompleteEditor {
  prepare(row, col, prop, td, originalValue, cellProperties) {
    super.prepare(row, col, prop, td, originalValue, cellProperties);
    this.cellProperties.filter = false;
    this.cellProperties.strict = true;
  }
}

export {MultiSelectDropdownEditor};

registerEditor('multiselectdropdown', MultiSelectDropdownEditor);

At this point I have no clue where the click event is happening when the user selects an item from the dropdown list. Debugging has been painful for me because it is through Traceur. I tried setting a click event after the module is ready and the DOM is as well however I cannot get even an alert to fire based off of a click on one of the select dropdown cells. The 'normal' cells I can get a click with a simple:

$('body').on('click','#handsontable td', someAlert)

However not so for the menu contents. Right clicking to inspect the dropdown menu means first disabling the context menu like the one on http://ift.tt/WWRahK. Then you will notice that right clicking to inspect anything will fire an event that closes the dropdown menu you are trying to inspect.

I've put breakpoints all through the libraries source code, I cannot figure this one out.

The only thing I want to do is figure out where the part of the code that highlights the menu item and sets it to an active selection, turn that into a method that accepts multiple selections (up to the entire array of options available, clicking an active item will disable it lets just say).

Then ensuring that those selections are actually in the Handsontable 'data scope'.

Thats it, I don't need it to even render in the cell what things have been chosen, although any help there would be great because unfortunately, I am yet to find the spot when the options in the dropdown are rendered either.

I have also tried using the Select2Editor made for handsontable as seen http://ift.tt/1WnonVE and http://ift.tt/1IPeGWt , however it does not help my cause much. Here is what the dropdown cell in handsontable looks like:

http://ift.tt/1WnoobS

Finally, heres a fiddle: http://ift.tt/1IPeF54

I would be super appreciative if someone could help me out here. Thanks SO!

UPDATE

I have managed to parse the values in the cell and turn the type into an array containing the values (so typing red blue will turn an array containing ['red','blue']) . I have run this array through the internal sort algorithm which parses the options and returns an index of a matching item. I get this working fine and I now am passing the array into the highlight method. This method passes the values the the core library WalkOnTable. I do not see where I can alter the logic to select more than one value instead of unhighlighting the first option.

 this.selectCell = function(row, col, endRow, endCol, scrollToCell, changeListener) {
var coords;
changeListener = typeof changeListener === 'undefined' || changeListener === true;
if (typeof row !== 'number' && !Array.isArray(row) || row < 0 || row >= instance.countRows()) {
  return false;
}
if (typeof col !== 'number' || col < 0 || col >= instance.countCols()) {
  return false;
}
if (typeof endRow !== 'undefined') {
  if (typeof endRow !== 'number' || endRow < 0 || endRow >= instance.countRows()) {
    return false;
  }
  if (typeof endCol !== 'number' || endCol < 0 || endCol >= instance.countCols()) {
    return false;
  }
}
// Normal number value, one item typed in
if (!Array.isArray(row) && typeof row === 'number'){
  coords = new WalkontableCellCoords(row, col);

  walkSelection(coords);
}

This is the spot where I think I need WalkontableCellCoords to be modified to accept an array and then highlight and select both values when the dropdown is opened and closed. I also need to be able to select multiple options via touch or click event.

else {
  // Array found, apply to each value
  new WalkontableCellCoords(row[0], col);
  new WalkontableCellCoords(row[1], col);
}

function walkSelection(coords){
  priv.selRange = new WalkontableCellRange(coords, coords, coords);
  if (document.activeElement && document.activeElement !== document.documentElement && document.activeElement !== document.body) {
    document.activeElement.blur();
  }
  if (changeListener) {
    instance.listen();
  }
  if (typeof endRow === 'undefined') {
    selection.setRangeEnd(priv.selRange.from, scrollToCell);
  } else {
    selection.setRangeEnd(new WalkontableCellCoords(endRow, endCol), scrollToCell);
  }
  instance.selection.finish();
}

return true;

};



via Chebli Mohamed

Nodejs - close socket event reason

Based on the documentation for net module it says that:

Emitted once the socket is fully closed. The argument had_error is a boolean which says if the socket was closed due to a transmission error.

Also, we know that close event will be triggered after error event always:

Emitted when an error occurs. The 'close' event will be called directly following this event.

I have a few doubts regarding how closing of socket works (more precisely when it can happen). I would like to conclude within the script when "close" event is triggered, which side closed the socket. So if "close" event is triggered on client side does this 100% means that socket is closed by other side (and vice versa)? Or I am missing something?

Is it possible for socket to encounter some kind of error which will trigger "close" event even other side is still running? If that is the case how can i conclude from where (and because of what kind of reason) socket is closed? Is it possible to conclude which one of two sides closed the socket (server or client)?



via Chebli Mohamed

Sequelize.js One-to-Many relationship foreign key

I am creating a survey app using Node.js/Express and MySQL with Sequelize.js ORM.

I am having trouble setting the relationship between the 2 models correctly. I'd like to have the Questions' qId foreign key in the Answers Table.

// define the Questions table
var Questions = sequelize.define('Questions', {
  qId: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true},
  question: Sequelize.STRING
}, {
  timestamps: false
});

// define the Answers table
var Answers = sequelize.define('Answers', {
  aId: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true},
  answer: Sequelize.STRING,
  answer_count: { type: Sequelize.INTEGER, defaultValue: 0}
}, {
  timestamps: false
});

// define one-to-many relationship
Questions.hasMany(Answers, {as: 'Answers', foreignKey: 'qId'});

Questions.sync({force: true}).then(function() {
  // OPTIONAL: create a new question upon instantiating the db using sequelize
  Questions.create({question: 'what is your language?'});
  Questions.create({question: 'what is your drink?'});
  console.log('created Questions table');
  }).catch(function(error) {
    console.log('error creating Questions table');
  });

Answers.sync({force: true}).then(function() {
  Answers.create({answer: 'python', qId: 1});
  Answers.create({answer: 'javascript', qId: 1});
  Answers.create({answer: 'ruby', qId: 1});
  Answers.create({answer: 'c++', qId: 1});
  Answers.create({answer: 'manhattan', qId: 2});
  Answers.create({answer: 'cosmopolitan', qId: 2});
  console.log('created Answers table');
}).catch(function(error) {
  console.log('error creating Answers table');
});

But when I do MySQL queries:

select * from Questions, Answers where Answers.qId=2;

it's showing the following:

mysql> select * from Answers;
+-----+--------------+--------------+------+
| aId | answer       | answer_count | qId  |
+-----+--------------+--------------+------+
|   1 | python       |            0 |    1 |
|   2 | javascript   |            0 |    1 |
|   3 | ruby         |            0 |    1 |
|   4 | c++          |            0 |    1 |
|   5 | manhattan    |            0 |    2 |
|   6 | cosmopolitan |            0 |    2 |
+-----+--------------+--------------+------+
6 rows in set (0.00 sec)

mysql> select * from Questions;
+-----+------------------------+
| qId | question               |
+-----+------------------------+
|   1 | what is your language? |
|   2 | what is your drink?    |
+-----+------------------------+
2 rows in set (0.00 sec)

mysql> select * from Questions, Answers where Answers.qId=2;
+-----+------------------------+-----+--------------+--------------+------+
| qId | question               | aId | answer       | answer_count | qId  |
+-----+------------------------+-----+--------------+--------------+------+
|   1 | what is your language? |   5 | manhattan    |            0 |    2 |
|   1 | what is your language? |   6 | cosmopolitan |            0 |    2 |
|   2 | what is your drink?    |   5 | manhattan    |            0 |    2 |
|   2 | what is your drink?    |   6 | cosmopolitan |            0 |    2 |
+-----+------------------------+-----+--------------+--------------+------+

When I'd like it to show

mysql> select * from Questions, Answers where Answers.qId=2;
+-----+------------------------+-----+--------------+--------------+------+
| qId | question               | aId | answer       | answer_count | qId  |
+-----+------------------------+-----+--------------+--------------+------+ 
|   2 | what is your drink?    |   5 | manhattan    |            0 |    2 |
|   2 | what is your drink?    |   6 | cosmopolitan |            0 |    2 |
+-----+------------------------+-----+--------------+--------------+------+

I've been looking at the documentation for a few hours now and any help would be much appreciated :) Thank you.



via Chebli Mohamed