<commit_before>// stream-test.js
//
// Test the stream module
//
// Copyright 2012, StatusNet Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var assert = require("assert"),
    vows = require("vows"),
    databank = require("databank"),
    Step = require("step"),
    URLMaker = require("../lib/urlmaker").URLMaker,
    schema = require("../lib/schema").schema,
    Databank = databank.Databank,
    DatabankObject = databank.DatabankObject;

var suite = vows.describe("stream objects interface");

// Test the object methods

suite.addBatch({

    "When we get the Stream class": {

        topic: function() {
            var cb = this.callback;
            // Need this to make IDs

            URLMaker.hostname = "example.net";

            // Dummy databank

            var params = {schema: schema};

            var db = Databank.get("memory", params);

            db.connect({}, function(err) {

                var Stream, mod;

                if (err) {
                    cb(err, null);
                    return;
                }

                DatabankObject.bank = db;

                mod = require("../lib/model/stream");

                if (!mod) {
                    cb(new Error("No module"), null);
                    return;
                }

                Stream = mod.Stream;

                if (!Stream) {
                    cb(new Error("No class"), null);
                    return;
                }

                cb(null, Stream);
            });
        },
        "it works": function(err, Stream) {
            assert.ifError(err);
            assert.isFunction(Stream);
        },
        "and we create a stream object": {
            topic: function(Stream) {
                Stream.create({name: "object-test-1"}, this.callback);
            },
            "it has a getObjects() method": function(err, stream) {
                assert.ifError(err);
                assert.isFunction(stream.getObjects);
            },
            "it has a getObjectsGreaterThan() method": function(err, stream) {
                assert.ifError(err);
                assert.isFunction(stream.getObjectsGreaterThan);
            },
            "it has a getObjectsLessThan() method": function(err, stream) {
                assert.ifError(err);
                assert.isFunction(stream.getObjectsLessThan);
            },
            "it has a deliverObject() method": function(err, stream) {
                assert.ifError(err);
                assert.isFunction(stream.deliverObject);
            },
            "it has a removeObject() method": function(err, stream) {
                assert.ifError(err);
                assert.isFunction(stream.removeObject);
            },
            "and we get some objects": {
                topic: function(stream) {
                    stream.getObjects(0, 20, this.callback);
                },
                "it works": function(err, objects) {
                    assert.ifError(err);
                },
                "it is an empty array": function(err, objects) {
                    assert.isArray(objects);
                    assert.lengthOf(objects, 0);
                }
            },
            "and we get objects with indexes greater than some object": {
                topic: function(stream) {
                    var cb = this.callback,
                        NotInStreamError = require('../lib/model/stream').NotInStreamError;

                    stream.getObjectsGreaterThan({a: "b"}, 10, function(err, objects) {
                        if (err && err instanceof NotInStreamError) {
                            cb(null);
                        } else if (err) {
                            cb(err);
                        } else {
                            cb(new Error("Unexpected success"));
                        }
                    });
                },
                "it fails correctly": function(err) {
                    assert.ifError(err);
                }
            },
            "and we get objects with indexes less than some object": {
                topic: function(stream) {
                    var cb = this.callback,
                        NotInStreamError = require('../lib/model/stream').NotInStreamError;

                    stream.getObjectsLessThan({a: "b"}, 10, function(err, objects) {
                        if (err && err instanceof NotInStreamError) {
                            cb(null);
                        } else if (err) {
                            cb(err);
                        } else {
                            cb(new Error("Unexpected success"));
                        }
                    });
                },
                "it fails correctly": function(err) {
                    assert.ifError(err);
                }
            },
            "and we remove an object that doesn't exist": {
                topic: function(stream) {
                    var cb = this.callback,
                        NotInStreamError = require('../lib/model/stream').NotInStreamError;

                    stream.removeObject({a: "b"}, function(err) {
                        if (err && err instanceof NotInStreamError) {
                            cb(null);
                        } else if (err) {
                            cb(err);
                        } else {
                            cb(new Error("Unexpected success"));
                        }
                    });
                },
                "it fails correctly": function(err) {
                    assert.ifError(err);
                }
            }
        },
        "and we create another stream": {
            topic: function(Stream) {
                Stream.create({name: "object-test-2"}, this.callback);
            },
            "it works": function(err, stream) {
                assert.ifError(err);
                assert.isObject(stream);
            },
            "and we deliver an object to it": {
                topic: function(stream) {
                    var cb = this.callback,
                        obj = {
                            objectType: "person",
                            id: "acct:evan@status.net"
                        };

                    stream.deliverObject(obj, cb);
                },
                "it works": function(err) {
                    assert.ifError(err);
                },
                "and we get the stream's objects": {
                    topic: function(stream) {
                        stream.getObjects(0, 20, this.callback);
                    },
                    "it works": function(err, objects) {
                        assert.ifError(err);
                    },
                    "results look right": function(err, objects) {
                        assert.ifError(err);
                        assert.isArray(objects);
                        assert.lengthOf(objects, 1);
                        assert.isObject(objects[0]);
                        assert.include(objects[0], "objectType");
                        assert.equal(objects[0].objectType, "person");
                        assert.include(objects[0], "id");
                        assert.equal(objects[0].id, "acct:evan@status.net");
                    }
                }
            }
        },
        "and we create a stream and deliver many objects to it": {
            topic: function(Stream) {
                var cb = this.callback,
                    stream;

                Step(
                    function() {
                        Stream.create({name: "object-test-3"}, this);
                    },
                    function(err, results) {
                        var i, group = this.group();
                        if (err) throw err;
                        stream = results;
                        for (i = 0; i < 50; i++) {
                            stream.deliverObject({id: "http://example.com/person" + i, objectType: "person"}, group());
                        }
                    },
                    function(err) {
                        if (err) {
                            cb(err, null);
                        } else {
                            cb(null, stream);
                        }
                    }
                );
            },
            "it works": function(err, stream) {
                assert.ifError(err);
                assert.isObject(stream);
            },
            "and we get the stream's objects": {
                topic: function(stream) {
                    stream.getObjects(0, 100, this.callback);
                },
                "it works": function(err, objects) {
                    assert.ifError(err);
                },
                "results look right": function(err, objects) {
                    var i, obj, seen = {};
                    assert.ifError(err);
                    assert.isArray(objects);
                    assert.lengthOf(objects, 50);
                    for (i = 0; i < objects.length; i++) {
                        obj = objects[i];
                        assert.isObject(obj);
                        assert.include(obj, "objectType");
                        assert.equal(obj.objectType, "person");
                        assert.include(obj, "id");
                        assert.match(obj.id, /http:\/\/example.com\/[0-9]+/);
                        assert.isUndefined(seen[obj.id]);
                        seen[obj.id] = obj;
                    }
                }
            }
        }
    }
});

suite["export"](module);<commit_msg>Bad fake ID<commit_after>// stream-test.js
//
// Test the stream module
//
// Copyright 2012, StatusNet Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var assert = require("assert"),
    vows = require("vows"),
    databank = require("databank"),
    Step = require("step"),
    URLMaker = require("../lib/urlmaker").URLMaker,
    schema = require("../lib/schema").schema,
    Databank = databank.Databank,
    DatabankObject = databank.DatabankObject;

var suite = vows.describe("stream objects interface");

// Test the object methods

suite.addBatch({

    "When we get the Stream class": {

        topic: function() {
            var cb = this.callback;
            // Need this to make IDs

            URLMaker.hostname = "example.net";

            // Dummy databank

            var params = {schema: schema};

            var db = Databank.get("memory", params);

            db.connect({}, function(err) {

                var Stream, mod;

                if (err) {
                    cb(err, null);
                    return;
                }

                DatabankObject.bank = db;

                mod = require("../lib/model/stream");

                if (!mod) {
                    cb(new Error("No module"), null);
                    return;
                }

                Stream = mod.Stream;

                if (!Stream) {
                    cb(new Error("No class"), null);
                    return;
                }

                cb(null, Stream);
            });
        },
        "it works": function(err, Stream) {
            assert.ifError(err);
            assert.isFunction(Stream);
        },
        "and we create a stream object": {
            topic: function(Stream) {
                Stream.create({name: "object-test-1"}, this.callback);
            },
            "it has a getObjects() method": function(err, stream) {
                assert.ifError(err);
                assert.isFunction(stream.getObjects);
            },
            "it has a getObjectsGreaterThan() method": function(err, stream) {
                assert.ifError(err);
                assert.isFunction(stream.getObjectsGreaterThan);
            },
            "it has a getObjectsLessThan() method": function(err, stream) {
                assert.ifError(err);
                assert.isFunction(stream.getObjectsLessThan);
            },
            "it has a deliverObject() method": function(err, stream) {
                assert.ifError(err);
                assert.isFunction(stream.deliverObject);
            },
            "it has a removeObject() method": function(err, stream) {
                assert.ifError(err);
                assert.isFunction(stream.removeObject);
            },
            "and we get some objects": {
                topic: function(stream) {
                    stream.getObjects(0, 20, this.callback);
                },
                "it works": function(err, objects) {
                    assert.ifError(err);
                },
                "it is an empty array": function(err, objects) {
                    assert.isArray(objects);
                    assert.lengthOf(objects, 0);
                }
            },
            "and we get objects with indexes greater than some object": {
                topic: function(stream) {
                    var cb = this.callback,
                        NotInStreamError = require('../lib/model/stream').NotInStreamError;

                    stream.getObjectsGreaterThan({a: "b"}, 10, function(err, objects) {
                        if (err && err instanceof NotInStreamError) {
                            cb(null);
                        } else if (err) {
                            cb(err);
                        } else {
                            cb(new Error("Unexpected success"));
                        }
                    });
                },
                "it fails correctly": function(err) {
                    assert.ifError(err);
                }
            },
            "and we get objects with indexes less than some object": {
                topic: function(stream) {
                    var cb = this.callback,
                        NotInStreamError = require('../lib/model/stream').NotInStreamError;

                    stream.getObjectsLessThan({a: "b"}, 10, function(err, objects) {
                        if (err && err instanceof NotInStreamError) {
                            cb(null);
                        } else if (err) {
                            cb(err);
                        } else {
                            cb(new Error("Unexpected success"));
                        }
                    });
                },
                "it fails correctly": function(err) {
                    assert.ifError(err);
                }
            },
            "and we remove an object that doesn't exist": {
                topic: function(stream) {
                    var cb = this.callback,
                        NotInStreamError = require('../lib/model/stream').NotInStreamError;

                    stream.removeObject({a: "b"}, function(err) {
                        if (err && err instanceof NotInStreamError) {
                            cb(null);
                        } else if (err) {
                            cb(err);
                        } else {
                            cb(new Error("Unexpected success"));
                        }
                    });
                },
                "it fails correctly": function(err) {
                    assert.ifError(err);
                }
            }
        },
        "and we create another stream": {
            topic: function(Stream) {
                Stream.create({name: "object-test-2"}, this.callback);
            },
            "it works": function(err, stream) {
                assert.ifError(err);
                assert.isObject(stream);
            },
            "and we deliver an object to it": {
                topic: function(stream) {
                    var cb = this.callback,
                        obj = {
                            objectType: "person",
                            id: "acct:evan@status.net"
                        };

                    stream.deliverObject(obj, cb);
                },
                "it works": function(err) {
                    assert.ifError(err);
                },
                "and we get the stream's objects": {
                    topic: function(stream) {
                        stream.getObjects(0, 20, this.callback);
                    },
                    "it works": function(err, objects) {
                        assert.ifError(err);
                    },
                    "results look right": function(err, objects) {
                        assert.ifError(err);
                        assert.isArray(objects);
                        assert.lengthOf(objects, 1);
                        assert.isObject(objects[0]);
                        assert.include(objects[0], "objectType");
                        assert.equal(objects[0].objectType, "person");
                        assert.include(objects[0], "id");
                        assert.equal(objects[0].id, "acct:evan@status.net");
                    }
                }
            }
        },
        "and we create a stream and deliver many objects to it": {
            topic: function(Stream) {
                var cb = this.callback,
                    stream;

                Step(
                    function() {
                        Stream.create({name: "object-test-3"}, this);
                    },
                    function(err, results) {
                        var i, group = this.group();
                        if (err) throw err;
                        stream = results;
                        for (i = 0; i < 50; i++) {
                            stream.deliverObject({id: "http://example.com/person" + i, objectType: "person"}, group());
                        }
                    },
                    function(err) {
                        if (err) {
                            cb(err, null);
                        } else {
                            cb(null, stream);
                        }
                    }
                );
            },
            "it works": function(err, stream) {
                assert.ifError(err);
                assert.isObject(stream);
            },
            "and we get the stream's objects": {
                topic: function(stream) {
                    stream.getObjects(0, 100, this.callback);
                },
                "it works": function(err, objects) {
                    assert.ifError(err);
                },
                "results look right": function(err, objects) {
                    var i, obj, seen = {};
                    assert.ifError(err);
                    assert.isArray(objects);
                    assert.lengthOf(objects, 50);
                    for (i = 0; i < objects.length; i++) {
                        obj = objects[i];
                        assert.isObject(obj);
                        assert.include(obj, "objectType");
                        assert.equal(obj.objectType, "person");
                        assert.include(obj, "id");
                        assert.match(obj.id, /http:\/\/example.com\/person[0-9]+/);
                        assert.isUndefined(seen[obj.id]);
                        seen[obj.id] = obj;
                    }
                }
            }
        }
    }
});

suite["export"](module);<|endoftext|>


<commit_before>/*jslint indent: 2 */
/*global window: false, document: false, chrome: false, $: false, createTag: false, createLink: false*/
(function () {
  "use strict";
  function createTimerLink(task, moreClass, tag) {
    var link;
    if (!tag) {
      link = createLink('jira ' + moreClass);
    } else {
      link = createTag(tag, 'jira ' + moreClass);
      link.appendChild(document.createTextNode('Start timer'));
    }
    link.addEventListener("click", function (e) {
      e.preventDefault();
      chrome.extension.sendMessage({
        type: 'timeEntry',
        description: task
      });
      $('span', link).innerHTML = "Started...";
    });
    return link;
  }

  function observeBoard() {
    var target = document.querySelector('#ghx-detail-view');
    var observer = new WebKitMutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
        if ($('.toggl-button')) {
          return;
        }

        var titleElem = $('dd.ghx-fieldname-summary'), numElem, title,wrapSpan, button;
        if (titleElem === null) {
          return;
        }

        numElem = $('.ghx-fieldname-issuekey a');
        title = titleElem.textContent;
        if (numElem !== null) {
          title = numElem.textContent + " " + title;
        }

        button = createTimerLink(title, 'aui-button ghx-actions aui-button-compact', 'button');
        wrapSpan = createTag('span', 'toggl-button', button.textContent);
        button.innerHTML = wrapSpan.outerHTML;
        $(".ghx-controls").insertBefore(button, $(".ghx-controls").childNodes[0]);
      });
    });
    var config = {childList: true, subtree: true};
    observer.observe(target, config);
  }

  function addLinkToDiscussion() {
    var titleElem = $('#summary-val'), numElem, title, wrapUl, wrapLi, wrapSpan, a;
    if (titleElem === null) {
      return;
    }

    numElem = $('.issue-link');
    title = titleElem.textContent;
    if (numElem !== null) {
      title = numElem.getAttribute('data-issue-key') + " " + title;
    }

    wrapUl = createTag('ul', 'toggl toolbar-group');
    wrapLi = createTag('li', 'toolbar-item');
    wrapUl.appendChild(wrapLi);

    a = createTimerLink(title, 'button toolbar-trigger');
    wrapSpan = createTag('span', 'toggl-button', a.textContent);
    a.innerHTML = wrapSpan.outerHTML;
    wrapLi.appendChild(a);
    $(".command-bar .toolbar-split-left").appendChild(wrapUl);
  }

  chrome.extension.sendMessage({type: 'activate'}, function (response) {
    if (response.success) {
      if ($('#gh')) {
        observeBoard();
      } else {
        addLinkToDiscussion();
      }
    }
  });

}());
<commit_msg>Jira: reset isStarted flag on issue reload<commit_after>/*jslint indent: 2 */
/*global window: false, document: false, chrome: false, $: false, createTag: false, createLink: false*/
(function () {
  "use strict";
  function createTimerLink(task, moreClass, tag) {
    var link;
    if (!tag) {
      link = createLink('jira ' + moreClass);
    } else {
      link = createTag(tag, 'jira ' + moreClass);
      link.appendChild(document.createTextNode('Start timer'));
    }
    link.addEventListener("click", function (e) {
      e.preventDefault();
      chrome.extension.sendMessage({
        type: 'timeEntry',
        description: task
      });
      $('span', link).innerHTML = "Started...";
    });
    return link;
  }

  function observeBoard() {
    var target = document.querySelector('#ghx-detail-view');
    var observer = new WebKitMutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
        if ($('.toggl-button')) {
          return;
        }

        var titleElem = $('dd.ghx-fieldname-summary'), numElem, title,wrapSpan, button;
        if (titleElem === null) {
          return;
        }

        numElem = $('.ghx-fieldname-issuekey a');
        title = titleElem.textContent;
        if (numElem !== null) {
          title = numElem.textContent + " " + title;
        }

        button = createTimerLink(title, 'aui-button ghx-actions aui-button-compact', 'button');
        wrapSpan = createTag('span', 'toggl-button', button.textContent);
        button.innerHTML = wrapSpan.outerHTML;
        $(".ghx-controls").insertBefore(button, $(".ghx-controls").childNodes[0]);
        isStarted = false;
      });
    });
    var config = {childList: true, subtree: true};
    observer.observe(target, config);
  }

  function addLinkToDiscussion() {
    var titleElem = $('#summary-val'), numElem, title, wrapUl, wrapLi, wrapSpan, a;
    if (titleElem === null) {
      return;
    }

    numElem = $('.issue-link');
    title = titleElem.textContent;
    if (numElem !== null) {
      title = numElem.getAttribute('data-issue-key') + " " + title;
    }

    wrapUl = createTag('ul', 'toggl toolbar-group');
    wrapLi = createTag('li', 'toolbar-item');
    wrapUl.appendChild(wrapLi);

    a = createTimerLink(title, 'button toolbar-trigger');
    wrapSpan = createTag('span', 'toggl-button', a.textContent);
    a.innerHTML = wrapSpan.outerHTML;
    wrapLi.appendChild(a);
    $(".command-bar .toolbar-split-left").appendChild(wrapUl);
  }

  chrome.extension.sendMessage({type: 'activate'}, function (response) {
    if (response.success) {
      if ($('#gh')) {
        observeBoard();
      } else {
        addLinkToDiscussion();
      }
    }
  });

}());
<|endoftext|>


<commit_before>/**
 * Little helper to fetch schema.json (used by the Relayjs compiler) from indexd,
 * and dataDictionary.json from the gdc api (used by data/gqlSetup.js to customize gql queries
 * based on the active dictionary before Relay compile).
 *
 * Ex: https://dev.bionimbus.org/api/v0/submission/getschema
 *     https://dev.bionimbus.org/api/v0/submission/_dictionary/_all
 */
const fetch = require('node-fetch');
const fs = require('fs');
const {
  buildClientSchema,
  printSchema,
} = require('graphql/utilities/index');

const { gdcSubPath } = (function () {
  function addSlash(path) { return (`${path}/`).replace(/\/+$/, '/'); }

  if (process.argv.length < 3) {
    let gdcDefaultPath = process.env.HOSTNAME ? `https://${process.env.HOSTNAME}/api/v0/submission/` : 'http://localhost:5000/v0/submission/';
    if (gdcDefaultPath.startsWith('revproxy')) {
      gdcDefaultPath = `http://${process.env.HOSTNAME}/api/v0/submission/`
    }
    return { status: 'ok', gdcSubPath: addSlash(process.env.GDC_SUBPATH || gdcDefaultPath) };
  }
  const arg1 = process.argv[2];
  if (!arg1.match(/^https?:\/\//)) {
    console.log(`
    getSchema downloads data/schema.json and data/dictionary.json from the environment's
    gdc-api for later use configuring gql queries for the portal environment, and
    running the relayjs gql compiler.

    Use: node getSchema.js [gdcSubmissionApiPath]
        - where gdcSubmissionApiPath defaults to: process.env.GDC_SUBPATH || 'http://localhost:5000/v0/submission/'
        - example - if gdcSubmissionApiPath = https://dev.bionimbus.org/api/vo/submission/,
            then the script loads:
            * https://dev.bionimbus.org/api/v0/submission/_dictionary/_all
            * https://dev.bionimbus.org/api/v0/submission/getschema
    `);
    return { status: 'exit' };
  }
  return { status: 'ok', gdcSubPath: addSlash(arg1) };
}());

if (!gdcSubPath) {
  process.exit(1);
}

const schemaUrl = `${gdcSubPath}getschema`;
const schemaPath = `${__dirname}/schema.json`;
const dictUrl = `${gdcSubPath}_dictionary/_all`;
const dictPath = `${__dirname}/dictionary.json`;

async function fetchJson(url) {
  console.log(`Fetching ${url}`);
  return fetch(url, {
    method: 'GET',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
  }).then(res => res.json(),
  ).catch((err) => {
    console.error(`Error processing ${url}`, err);
    return Promise.reject(err);
  });
}

const actionList = [];

actionList.push(
  // Save JSON of full schema introspection for Babel Relay Plugin to use
  fetchJson(schemaUrl).then((schema) => {
    fs.writeFileSync(schemaPath, JSON.stringify(schema, null, 2));

    // Save user readable type system shorthand of schema
    const graphQLSchema = buildClientSchema(schema.data);
    fs.writeFileSync(`${__dirname}/schema.graphql`, printSchema(graphQLSchema));
  }),
);

actionList.push(
  fetchJson(dictUrl).then(
    (dict) => {
      fs.writeFileSync(dictPath, JSON.stringify(dict, null, 2));
    },
  ),
);

Promise.all(actionList).then(
  () => {
    console.log('All done!');
    process.exit(0);
  },
  (err) => {
    console.error('Error: ', err);
    process.exit(2);
  },
);
<commit_msg>fix(hostname): internal useage for openstack<commit_after>/**
 * Little helper to fetch schema.json (used by the Relayjs compiler) from indexd,
 * and dataDictionary.json from the gdc api (used by data/gqlSetup.js to customize gql queries
 * based on the active dictionary before Relay compile).
 *
 * Ex: https://dev.bionimbus.org/api/v0/submission/getschema
 *     https://dev.bionimbus.org/api/v0/submission/_dictionary/_all
 */
const fetch = require('node-fetch');
const fs = require('fs');
const {
  buildClientSchema,
  printSchema,
} = require('graphql/utilities/index');

const { gdcSubPath } = (function () {
  function addSlash(path) { return (`${path}/`).replace(/\/+$/, '/'); }

  if (process.argv.length < 3) {
    let gdcDefaultPath = process.env.HOSTNAME ? `https://${process.env.HOSTNAME}/api/v0/submission/` : 'http://localhost:5000/v0/submission/';
    if (process.env.HOSTNAME.startsWith('revproxy')) {
      gdcDefaultPath = `http://${process.env.HOSTNAME}/api/v0/submission/`
    }
    return { status: 'ok', gdcSubPath: addSlash(process.env.GDC_SUBPATH || gdcDefaultPath) };
  }
  const arg1 = process.argv[2];
  if (!arg1.match(/^https?:\/\//)) {
    console.log(`
    getSchema downloads data/schema.json and data/dictionary.json from the environment's
    gdc-api for later use configuring gql queries for the portal environment, and
    running the relayjs gql compiler.

    Use: node getSchema.js [gdcSubmissionApiPath]
        - where gdcSubmissionApiPath defaults to: process.env.GDC_SUBPATH || 'http://localhost:5000/v0/submission/'
        - example - if gdcSubmissionApiPath = https://dev.bionimbus.org/api/vo/submission/,
            then the script loads:
            * https://dev.bionimbus.org/api/v0/submission/_dictionary/_all
            * https://dev.bionimbus.org/api/v0/submission/getschema
    `);
    return { status: 'exit' };
  }
  return { status: 'ok', gdcSubPath: addSlash(arg1) };
}());

if (!gdcSubPath) {
  process.exit(1);
}

const schemaUrl = `${gdcSubPath}getschema`;
const schemaPath = `${__dirname}/schema.json`;
const dictUrl = `${gdcSubPath}_dictionary/_all`;
const dictPath = `${__dirname}/dictionary.json`;

async function fetchJson(url) {
  console.log(`Fetching ${url}`);
  return fetch(url, {
    method: 'GET',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
  }).then(res => res.json(),
  ).catch((err) => {
    console.error(`Error processing ${url}`, err);
    return Promise.reject(err);
  });
}

const actionList = [];

actionList.push(
  // Save JSON of full schema introspection for Babel Relay Plugin to use
  fetchJson(schemaUrl).then((schema) => {
    fs.writeFileSync(schemaPath, JSON.stringify(schema, null, 2));

    // Save user readable type system shorthand of schema
    const graphQLSchema = buildClientSchema(schema.data);
    fs.writeFileSync(`${__dirname}/schema.graphql`, printSchema(graphQLSchema));
  }),
);

actionList.push(
  fetchJson(dictUrl).then(
    (dict) => {
      fs.writeFileSync(dictPath, JSON.stringify(dict, null, 2));
    },
  ),
);

Promise.all(actionList).then(
  () => {
    console.log('All done!');
    process.exit(0);
  },
  (err) => {
    console.error('Error: ', err);
    process.exit(2);
  },
);
<|endoftext|>


<commit_before>var data_array={
"20160427":7,
"20160426":6,
"20160425":6,
"20160424":1.5,
"20160423":0.5,
"20160422":3,
"20160421":7,
"20160420":7,
"20160419":3,
"20160418":7,
"20160417":7,
"20160416":0,
"20160415":5.5,
"20160414":7,
"20160413":7,
"20160412":3,
"20160411":7,
"20160410":5,
"20160409":2,
"20160408":7,
"20160407":7,
"20160406":7,
"20160405":7,
"20160404":7,
"20160403":0,
"20160402":2.5,
"20160401":7,
"20160331":7,
"20160330":7,
"20160329":7,
"20160328":7,
"20160327":4.5,
"20160326":2,
"20160325":5.5,
"20160324":5,
"20160323":4,
"20160322":2.5,
"20160321":5.5,
"20160320":2,
"20160319":0.5,
"20160318":6,
"20160317":0,
"20160316":0,
"20160315":1.5,
"20160314":0,
"20160313":2,
"20160312":2,
"20160311":0,
"20160310":5,
"20160309":1,
"20160308":0,
"20160307":5,
"20160306":7,
"20160305":3,
"20160304":6,
"20160303":3,
"20160302":6,
"20160301":7,
"20160229":7,
"20160228":7,
"20160227":3,
"20160226":2,
"20160225":2.5,
"20160224":5.5,
"20160223":5,
"20160222":7,
"20160221":3.5,
"20160220":3,
"20160219":7,
"20160218":7,
"20160217":6,
"20160216":5.5,
"20160215":6,
"20160214":3.5,
"20160213":0,
"20160212":4,
"20160211":5,
"20160210":7,
"20160209":6,
"20160208":5,
"20160207":0,
"20160206":0,
"20160205":3,
"20160204":5,
"20160203":5,
"20160202":4,
"20160201":6,
"20160131":3,
"20160130":0,
"20160129":7,
"20160128":7,
"20160127":6.5,
"20160126":5,
"20160125":7,
"20160124":3,
"20160123":0,
"20160122":7,
"20160121":7,
"20160120":7,
"20160119":6,
"20160118":5,
"20160117":0,
"20160116":1,
"20160115":4,
"20160114":5,
"20160113":5,
"20160112":5,
"20160111":5,
"20160110":3,
"20160109":0,
"20160108":5.5,
"20160107":5,
"20160106":5,
"20160105":5,
"20160104":4.5,
"20160103":0,
"20160102":2,
"20160101":0,
"20151231":0,
"20151230":1.5,
"20151229":2,
"20151228":2,
"20151227":3.5,
"20151226":1.5,
"20151225":0,
"20151224":0,
"20151223":2.5,
"20151222":3,
"20151221":2,
"20151220":4,
"20151219":2,
"20151218":4,
"20151217":4.5,
"20151216":4,
"20151215":4,
"20151214":5,
"20151213":4,
"20151212":4,
"20151211":4.5,
"20151210":7,
"20151209":6,
"20151208":5,
"20151207":7,
"20151206":4,
"20151205":7,
"20151204":4,
"20151203":5.5,
"20151202":6,
"20151201":4.5,
"20151130":5,
"20151129":4,
"20151128":4
};

var width = 900,
    height = 120,
    cellSize = 15; // cell size
    month = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
    color = ["#eee","#d6e685","#8cc665","#44a340","#1e6823"];
    range = [0,2,4,7];

var day = d3.time.format("%w"),
    week = d3.time.format("%U"),
    percent = d3.format(".1%"),
	format = d3.time.format("%Y%m%d");
	parseDate = d3.time.format("%Y%m%d").parse;

var svg = d3.select(".calender-map").selectAll("svg")
    .data(d3.range(2015, 2017))
  .enter().append("svg")
    .attr("width", '100%')
    .attr("data-height", '0.5678')
    .attr("viewBox",'0 0 ' + width + ' ' + height)
  .append("g")
    .attr("transform", "translate(" + ((width - cellSize * 53) / 2) + "," + (height - cellSize * 7 - 1) + ")");

svg.append("text")
    .attr("transform", "translate(-10," + cellSize * 3.5 + ")rotate(-90)")
    .style("text-anchor", "middle")
    .text(function(d) { return d; });

var rect = svg.selectAll(".day")
    .data(function(d) { return d3.time.days(new Date(d, 0, 1), new Date(d + 1, 0, 1)); })
  .enter()
	.append("rect")
    .attr("class", "day")
    .attr("width", cellSize)
    .attr("height", cellSize)
    .attr("x", function(d) { return week(d) * cellSize; })
    .attr("y", function(d) { return day(d) * cellSize; })
    .attr("fill",'#fff')
    .datum(format);

var legend = svg.selectAll(".legend")
      .data(month)
    .enter().append("g")
      .attr("class", "legend")
      .attr("transform", function(d, i) { return "translate(" + (((i+1) * 50)+8) + ",0)"; });

svg.selectAll(".month")
    .data(function(d) { return d3.time.months(new Date(d, 0, 1), new Date(d + 1, 0, 1)); })
  .enter().append("path")
    .attr("class", "month")
    .attr("d", monthPath);

function getRange(d) {
  for (i = 1; i < range.length; i++) {
    if (d < range[i])
      return i;
  }
  return -1;
}

function getColor(d) {
  if (d == 0)
    return color[0];
  if (d >= range[range.length - 1])
    return color[range.length];
  index = getRange(d);
  change = d3.scale.linear().range([color[index - 1], color[index]])
    .domain([range[index - 1], range[index]])
  return change(d)
}

  rect
      .attr("fill", function(d) {if (isNaN(data_array[d])) return color[0];  return getColor(data_array[d]); })
	  .attr("data-title", function(d) { if (isNaN(data_array[d])) ret = "No record on "; else ret = data_array[d] + " hours on "; return ret + month[parseDate(d).getMonth()] + ". " + parseDate(d).getDate()});

d3.csv("",function() {
	$("rect").tooltip({container: 'body'});

});

function numberWithCommas(x) {
    x = x.toString();
    var pattern = /(-?\d+)(\d{3})/;
    while (pattern.test(x))
        x = x.replace(pattern, "$1,$2");
    return x;
}

function monthPath(t0) {
  var t1 = new Date(t0.getFullYear(), t0.getMonth() + 1, 0),
      d0 = +day(t0), w0 = +week(t0),
      d1 = +day(t1), w1 = +week(t1);
  return "M" + (w0 + 1) * cellSize + "," + d0 * cellSize
      + "H" + w0 * cellSize + "V" + 7 * cellSize
      + "H" + w1 * cellSize + "V" + (d1 + 1) * cellSize
      + "H" + (w1 + 1) * cellSize + "V" + 0
      + "H" + (w0 + 1) * cellSize + "Z";
}

<commit_msg>tracker<commit_after>var data_array={
"20160428":7,
"20160427":7,
"20160426":6,
"20160425":6,
"20160424":1.5,
"20160423":0.5,
"20160422":3,
"20160421":7,
"20160420":7,
"20160419":3,
"20160418":7,
"20160417":7,
"20160416":0,
"20160415":5.5,
"20160414":7,
"20160413":7,
"20160412":3,
"20160411":7,
"20160410":5,
"20160409":2,
"20160408":7,
"20160407":7,
"20160406":7,
"20160405":7,
"20160404":7,
"20160403":0,
"20160402":2.5,
"20160401":7,
"20160331":7,
"20160330":7,
"20160329":7,
"20160328":7,
"20160327":4.5,
"20160326":2,
"20160325":5.5,
"20160324":5,
"20160323":4,
"20160322":2.5,
"20160321":5.5,
"20160320":2,
"20160319":0.5,
"20160318":6,
"20160317":0,
"20160316":0,
"20160315":1.5,
"20160314":0,
"20160313":2,
"20160312":2,
"20160311":0,
"20160310":5,
"20160309":1,
"20160308":0,
"20160307":5,
"20160306":7,
"20160305":3,
"20160304":6,
"20160303":3,
"20160302":6,
"20160301":7,
"20160229":7,
"20160228":7,
"20160227":3,
"20160226":2,
"20160225":2.5,
"20160224":5.5,
"20160223":5,
"20160222":7,
"20160221":3.5,
"20160220":3,
"20160219":7,
"20160218":7,
"20160217":6,
"20160216":5.5,
"20160215":6,
"20160214":3.5,
"20160213":0,
"20160212":4,
"20160211":5,
"20160210":7,
"20160209":6,
"20160208":5,
"20160207":0,
"20160206":0,
"20160205":3,
"20160204":5,
"20160203":5,
"20160202":4,
"20160201":6,
"20160131":3,
"20160130":0,
"20160129":7,
"20160128":7,
"20160127":6.5,
"20160126":5,
"20160125":7,
"20160124":3,
"20160123":0,
"20160122":7,
"20160121":7,
"20160120":7,
"20160119":6,
"20160118":5,
"20160117":0,
"20160116":1,
"20160115":4,
"20160114":5,
"20160113":5,
"20160112":5,
"20160111":5,
"20160110":3,
"20160109":0,
"20160108":5.5,
"20160107":5,
"20160106":5,
"20160105":5,
"20160104":4.5,
"20160103":0,
"20160102":2,
"20160101":0,
"20151231":0,
"20151230":1.5,
"20151229":2,
"20151228":2,
"20151227":3.5,
"20151226":1.5,
"20151225":0,
"20151224":0,
"20151223":2.5,
"20151222":3,
"20151221":2,
"20151220":4,
"20151219":2,
"20151218":4,
"20151217":4.5,
"20151216":4,
"20151215":4,
"20151214":5,
"20151213":4,
"20151212":4,
"20151211":4.5,
"20151210":7,
"20151209":6,
"20151208":5,
"20151207":7,
"20151206":4,
"20151205":7,
"20151204":4,
"20151203":5.5,
"20151202":6,
"20151201":4.5,
"20151130":5,
"20151129":4,
"20151128":4
};

var width = 900,
    height = 120,
    cellSize = 15; // cell size
    month = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
    color = ["#eee","#d6e685","#8cc665","#44a340","#1e6823"];
    range = [0,2,4,7];

var day = d3.time.format("%w"),
    week = d3.time.format("%U"),
    percent = d3.format(".1%"),
	format = d3.time.format("%Y%m%d");
	parseDate = d3.time.format("%Y%m%d").parse;

var svg = d3.select(".calender-map").selectAll("svg")
    .data(d3.range(2015, 2017))
  .enter().append("svg")
    .attr("width", '100%')
    .attr("data-height", '0.5678')
    .attr("viewBox",'0 0 ' + width + ' ' + height)
  .append("g")
    .attr("transform", "translate(" + ((width - cellSize * 53) / 2) + "," + (height - cellSize * 7 - 1) + ")");

svg.append("text")
    .attr("transform", "translate(-10," + cellSize * 3.5 + ")rotate(-90)")
    .style("text-anchor", "middle")
    .text(function(d) { return d; });

var rect = svg.selectAll(".day")
    .data(function(d) { return d3.time.days(new Date(d, 0, 1), new Date(d + 1, 0, 1)); })
  .enter()
	.append("rect")
    .attr("class", "day")
    .attr("width", cellSize)
    .attr("height", cellSize)
    .attr("x", function(d) { return week(d) * cellSize; })
    .attr("y", function(d) { return day(d) * cellSize; })
    .attr("fill",'#fff')
    .datum(format);

var legend = svg.selectAll(".legend")
      .data(month)
    .enter().append("g")
      .attr("class", "legend")
      .attr("transform", function(d, i) { return "translate(" + (((i+1) * 50)+8) + ",0)"; });

svg.selectAll(".month")
    .data(function(d) { return d3.time.months(new Date(d, 0, 1), new Date(d + 1, 0, 1)); })
  .enter().append("path")
    .attr("class", "month")
    .attr("d", monthPath);

function getRange(d) {
  for (i = 1; i < range.length; i++) {
    if (d < range[i])
      return i;
  }
  return -1;
}

function getColor(d) {
  if (d == 0)
    return color[0];
  if (d >= range[range.length - 1])
    return color[range.length];
  index = getRange(d);
  change = d3.scale.linear().range([color[index - 1], color[index]])
    .domain([range[index - 1], range[index]])
  return change(d)
}

  rect
      .attr("fill", function(d) {if (isNaN(data_array[d])) return color[0];  return getColor(data_array[d]); })
	  .attr("data-title", function(d) { if (isNaN(data_array[d])) ret = "No record on "; else ret = data_array[d] + " hours on "; return ret + month[parseDate(d).getMonth()] + ". " + parseDate(d).getDate()});

d3.csv("",function() {
	$("rect").tooltip({container: 'body'});

});

function numberWithCommas(x) {
    x = x.toString();
    var pattern = /(-?\d+)(\d{3})/;
    while (pattern.test(x))
        x = x.replace(pattern, "$1,$2");
    return x;
}

function monthPath(t0) {
  var t1 = new Date(t0.getFullYear(), t0.getMonth() + 1, 0),
      d0 = +day(t0), w0 = +week(t0),
      d1 = +day(t1), w1 = +week(t1);
  return "M" + (w0 + 1) * cellSize + "," + d0 * cellSize
      + "H" + w0 * cellSize + "V" + 7 * cellSize
      + "H" + w1 * cellSize + "V" + (d1 + 1) * cellSize
      + "H" + (w1 + 1) * cellSize + "V" + 0
      + "H" + (w0 + 1) * cellSize + "Z";
}

<|endoftext|>


<commit_before>var assert = require('assert'),
    path = require('path'),
    vows = require('../lib/vows'),
    exec = require('child_process').exec;

function generateTopic(supress) {
    return function () {
        var cmd = './bin/vows ' + (supress ? '--supress-stdout ' : '') +
                  './test/fixtures/supress-stdout/output.js',
            options = {cwd: path.resolve(__dirname + '/../')},
            callback = this.callback;

        exec(cmd, options, function (err, stdout) {
            callback(null, {err: err, stdout: stdout});
        });
    };
}

vows.describe('vows/supress-stdout').addBatch({
    'Running vows for test/fixtures/supress-stdout/output.js': {
        'with --supress-stdout flag': {
            topic: generateTopic(true),
            'should be ok': function (result) {
                assert.isNull(result.err);
            },
            'should not contain output from stdout': function (result) {
                assert.equal(result.stdout.toString().indexOf('goo'), -1);
                // console.log output?
                // nope, just Chuck Testa!
            }
        },
        'without --supress-stdout flag': {
            topic: generateTopic(),
            'should be ok': function (result) {
                assert.isNull(result.err);
            },
            'should contain output from stdout': function (result) {
                assert.notEqual(result.stdout.toString().indexOf('goo'), -1);
            }
        }
    }
}).export(module);

<commit_msg>use process.execPath and not ./bin/vows in for cmd in call to exec(). Fix for windows<commit_after>var assert = require('assert'),
    path = require('path'),
    vows = require('../lib/vows'),
    exec = require('child_process').exec;

function generateTopic(supress) {
    return function () {
        var cmd = '"' + process.execPath + '"' +  ' ./bin/vows ' + (supress ? '--supress-stdout ' : '') +
                  './test/fixtures/supress-stdout/output.js',
            options = {cwd: path.resolve(__dirname + '/../')},
            callback = this.callback;

        exec(cmd, options, function (err, stdout) {
            callback(null, {err: err, stdout: stdout});
        });
    };
}

vows.describe('vows/supress-stdout').addBatch({
    'Running vows for test/fixtures/supress-stdout/output.js': {
        'with --supress-stdout flag': {
            topic: generateTopic(true),
            'should be ok': function (result) {
                assert.isNull(result.err);
            },
            'should not contain output from stdout': function (result) {
                assert.equal(result.stdout.toString().indexOf('goo'), -1);
                // console.log output?
                // nope, just Chuck Testa!
            }
        },
        'without --supress-stdout flag': {
            topic: generateTopic(),
            'should be ok': function (result) {
                assert.isNull(result.err);
            },
            'should contain output from stdout': function (result) {
                assert.notEqual(result.stdout.toString().indexOf('goo'), -1);
            }
        }
    }
}).export(module);

<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Route.extend({
  beforeModel: function() {
    this.transitionTo('environments');
  }
});
<commit_msg>Transition should go through the welcome route<commit_after>import Ember from 'ember';

export default Ember.Route.extend({
  beforeModel: function() {
    this.transitionTo('services');
  }
});
<|endoftext|>


<commit_before>"use strict";

const { computed, observable, dom } = require('../..');

function toCelsius(fahrenheit) {
  return (fahrenheit - 32) * 5 / 9;
}

function toFahrenheit(celsius) {
  return (celsius * 9 / 5) + 32;
}

function tryConvert(temperature, convert) {
  const input = parseFloat(temperature);
  if (Number.isNaN(input)) {
    return '';
  }
  const output = convert(input);
  const rounded = Math.round(output * 1000) / 1000;
  return rounded.toString();
}

function BoilingVerdict(celsius) {
  return dom('p',
    dom.text(use => use(celsius) >= 100 ? 'The water would boil.' : 'The water would not boil.'));
}

function TemperatureInput(temperature, scaleName) {
  return dom('fieldset',
    dom('legend', `Enter temperature in ${scaleName}:`),
    dom('input', dom.prop('value', temperature),
      dom.on('input', e => temperature.set(e.target.value)))
  );
}

class Calculator extends dom.Component {
  constructor() {
    super();
    this._temp = observable('');
    this._scale = observable('c');

    const celsius = this.autoDispose(this._makeScaleTemp('c', toCelsius));
    const fahrenheit = this.autoDispose(this._makeScaleTemp('f', toFahrenheit));
    const celsiusValue = this.autoDispose(computed(use => parseFloat(use(celsius))));

    this.setContent(dom('div',
      TemperatureInput(celsius, 'Celsius'),
      TemperatureInput(fahrenheit, 'Fahrenheit'),
      BoilingVerdict(celsiusValue)
    ));
  }

  _makeScaleTemp(toScale, converter) {
    return computed(this._temp, this._scale,
      (use, temp, scale) => (scale === toScale ? temp : tryConvert(temp, converter)))
    .onWrite(val => { this._scale.set(toScale); this._temp.set(val); });
  }
}

dom.update(dom.find('#root'), dom.create(Calculator));
<commit_msg>Fix the demo file for grainjs<commit_after>"use strict";

const { computed, Disposable, observable, dom } = require('../..');

function toCelsius(fahrenheit) {
  return (fahrenheit - 32) * 5 / 9;
}

function toFahrenheit(celsius) {
  return (celsius * 9 / 5) + 32;
}

function tryConvert(temperature, convert) {
  const input = parseFloat(temperature);
  if (Number.isNaN(input)) {
    return '';
  }
  const output = convert(input);
  const rounded = Math.round(output * 1000) / 1000;
  return rounded.toString();
}

function BoilingVerdict(celsius) {
  return dom('p',
    dom.text(use => use(celsius) >= 100 ? 'The water would boil.' : 'The water would not boil.'));
}

function TemperatureInput(temperature, scaleName) {
  return dom('fieldset',
    dom('legend', `Enter temperature in ${scaleName}:`),
    dom('input', dom.prop('value', temperature),
      dom.on('input', e => temperature.set(e.target.value)))
  );
}

class Calculator extends Disposable {
  constructor() {
    super();
    this._temp = observable('');
    this._scale = observable('c');
  }

  buildDom() {
    const celsius = this.autoDispose(this._makeScaleTemp('c', toCelsius));
    const fahrenheit = this.autoDispose(this._makeScaleTemp('f', toFahrenheit));
    const celsiusValue = this.autoDispose(computed(use => parseFloat(use(celsius))));
    return dom('div',
      TemperatureInput(celsius, 'Celsius'),
      TemperatureInput(fahrenheit, 'Fahrenheit'),
      BoilingVerdict(celsiusValue)
    );
  }

  _makeScaleTemp(toScale, converter) {
    return computed(this._temp, this._scale,
      (use, temp, scale) => (scale === toScale ? temp : tryConvert(temp, converter)))
    .onWrite(val => { this._scale.set(toScale); this._temp.set(val); });
  }
}

dom.update(dom.find('#root'), dom.create(Calculator));
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import {
   Button,
   ButtonGroup,
   Grid,
   GridCell,
   Spacer,

   Text,
   Title,
   TitleBar,
   View
} from '../../src'
import style from '../style.less'

export default class DemoContentButtonGroup extends Component {
   static propTypes = {
      contents: React.PropTypes.array
   }

   render() {
      return (
         <View width="100%" className={style.docs}>
            <TitleBar title="ButtonGroup" flush />
            <Spacer size="9" />
            <Grid columns="1[a] 2[b] 4[c-e]" gutter="60px">
               <GridCell>
                  <Title>ButtonGroup Modes</Title>
                  <Text size="2" color="gray50">
                     ButtonGroup modes are different ways to visually present a set of
                     buttons. Often it is useful to present them as a vertical list
                     or grouped more tightly together like a segmented control.
                  </Text>
               </GridCell>
               <GridCell colspan="3">
                  <View width="100%">
                     <Grid gutter="30px" width="100%" columns="1">
                        <GridCell>
                           <Text weight="semibold" size="3">Normal</Text>
                           <Spacer size="3" />
                           <View width="100%">
                              <ButtonGroup>
                                 <Button name="Button One" />
                                 <Button name="Button Two" outline />
                                 <Button name="Button Three" outline />
                              </ButtonGroup>
                           </View>
                        </GridCell>
                        <GridCell>
                           <Text weight="semibold" size="3">List</Text>
                           <Spacer size="3" />
                           <View width="150px" height="180px" className={style.docsWindow}>
                              <ButtonGroup mode="list">
                                 <Button size="small" name="Button One" />
                                 <Button size="small" name="Button Two" />
                                 <Button size="small" name="Button Three" />
                              </ButtonGroup>
                           </View>
                        </GridCell>
                        <GridCell>
                           <Text weight="semibold" size="3">Segmented Control</Text>
                           <Spacer size="3" />
                           <View width="100%">
                              <ButtonGroup mode="segmented">
                                 <Button link="/button-group" indexLink size="small" name="Button One" />
                                 <Button size="small" name="Button Two" />
                                 <Button size="small" name="Button Three" />
                              </ButtonGroup>
                           </View>
                        </GridCell>
                     </Grid>
                  </View>
               </GridCell>
               <GridCell>
                  <Title>ButtonGroup Configurations</Title>
                  <Text size="2" color="gray50">
                     Props for using the Modal component
                  </Text>
               </GridCell>
               <GridCell colspan="3">

                           Prop
                           Prop Type
                           Default Value
                           Description/Options

                           align
                           String
                           left

                                 left
                                 center
                                 right

                                 This prop only applies
                                 when ButtonGroup is in the normal mode.

                           mode
                           String
                           normal

                              normal
                              segmented
                              list

                           spacing
                           String
                           6px

                                 Pass a number with pixel-based unit.

                                 This prop only applies
                                 when ButtonGroup is in the normal mode.

               </GridCell>
            </Grid>
         </View>
      )
   }
}
<commit_msg>whoops. minor code fix.<commit_after>import React, { Component } from 'react'
import {
   Button,
   ButtonGroup,
   Grid,
   GridCell,
   Spacer,
   Text,
   Title,
   TitleBar,
   View
} from '../../src'
import style from '../style.less'

export default class DemoContentButtonGroup extends Component {
   static propTypes = {
      contents: React.PropTypes.array
   }

   render() {
      return (
         <View width="100%" className={style.docs}>
            <TitleBar title="ButtonGroup" flush />
            <Spacer size="9" />
            <Grid columns="1[a] 2[b] 4[c-e]" gutter="60px">
               <GridCell>
                  <Title>ButtonGroup Modes</Title>
                  <Text size="2" color="gray50">
                     ButtonGroup modes are different ways to visually present a set of
                     buttons. Often it is useful to present them as a vertical list
                     or grouped more tightly together like a segmented control.
                  </Text>
               </GridCell>
               <GridCell colspan="3">
                  <View width="100%">
                     <Grid gutter="30px" width="100%" columns="1">
                        <GridCell>
                           <Text weight="semibold" size="3">Normal</Text>
                           <Spacer size="3" />
                           <View width="100%">
                              <ButtonGroup>
                                 <Button name="Button One" />
                                 <Button name="Button Two" outline />
                                 <Button name="Button Three" outline />
                              </ButtonGroup>
                           </View>
                        </GridCell>
                        <GridCell>
                           <Text weight="semibold" size="3">List</Text>
                           <Spacer size="3" />
                           <View width="150px" height="180px" className={style.docsWindow}>
                              <ButtonGroup mode="list">
                                 <Button size="small" name="Button One" />
                                 <Button size="small" name="Button Two" />
                                 <Button size="small" name="Button Three" />
                              </ButtonGroup>
                           </View>
                        </GridCell>
                        <GridCell>
                           <Text weight="semibold" size="3">Segmented Control</Text>
                           <Spacer size="3" />
                           <View width="100%">
                              <ButtonGroup mode="segmented">
                                 <Button link="/button-group" indexLink size="small" name="Button One" />
                                 <Button size="small" name="Button Two" />
                                 <Button size="small" name="Button Three" />
                              </ButtonGroup>
                           </View>
                        </GridCell>
                     </Grid>
                  </View>
               </GridCell>
               <GridCell>
                  <Title>ButtonGroup Configurations</Title>
                  <Text size="2" color="gray50">
                     Props for using the Modal component
                  </Text>
               </GridCell>
               <GridCell colspan="3">

                           Prop
                           Prop Type
                           Default Value
                           Description/Options

                           align
                           String
                           left

                                 left
                                 center
                                 right

                                 This prop only applies
                                 when ButtonGroup is in the normal mode.

                           mode
                           String
                           normal

                              normal
                              segmented
                              list

                           spacing
                           String
                           6px

                                 Pass a number with pixel-based unit.

                                 This prop only applies
                                 when ButtonGroup is in the normal mode.

               </GridCell>
            </Grid>
         </View>
      )
   }
}
<|endoftext|>


<commit_before>/**
 *  weather.js
 *  -----
 *  Impact Weather Add-on for the Impact Day/Night Cycle Plugin
 *  https://github.com/chessmasterhong/impact-day-night
 *
 *  Kevin Chan (chessmasterhong)
 *
 *  An add-on for the Impact Day/Night Cycle Plugin for the Impact game engine
 *  that simulates weather conditions.
 */

ig.module(
    'plugins.weather'
)
.requires(
    'impact.game'
)
.defines(function() {
    "use strict";

    ig.Weather = ig.Game.extend({
        condition: 0, // 0 = clear, 1 = rain, 2 = snow

        count: 100,

        //---------------------------------------------------------------------
        // Init
        init: function() {
            this.nextParticle = new ig.Timer();
        }, // End init
        //---------------------------------------------------------------------

        //---------------------------------------------------------------------
        // Update
        update: function() {
            if(this.nextParticle.delta() >= 0 && this.count > 0) {
                this.count--;
                this.nextParticle.set(1 / this.count);
                ig.game.spawnEntity(
                    EntitySnow,
                    Math.random() * (ig.game.screen.x + ig.system.width - ig.game.screen.x) + ig.game.screen.x,
                    ig.game.screen.y
                );
            }
        }, // End update
        //---------------------------------------------------------------------

        //---------------------------------------------------------------------
        // Draw
        draw: function() {
            // TODO
        } // End draw
        //---------------------------------------------------------------------
    });

    var EntitySnow = ig.Entity.extend({
        size: {x: 3, y: 3},
        vel: {x: 60, y: 80},
        //maxVel: {x: 100, y: 100},

        init: function(x, y, settings) {
            this.parent(x, y, settings);

            // Randomize initial velocity
            this.vel.x *= Math.random() * 2 - 1;
            this.vel.y *= Math.abs(Math.random() * 2 - 1); // Snow should not "fall" upwards...
        },

        update: function() {
            this.parent();

            // Handle entity moving out of screen bounds
            // Wraparound to opposite side of screen
            if(this.pos.y > ig.game.screen.y + ig.system.height)
               this.pos.y = ig.game.screen.y;
            else if(this.pos.x > ig.game.screen.x + ig.system.width)
                this.pos.x = ig.game.screen.x;
            else if(this.pos.x < ig.game.screen.x)
                this.pos.x = ig.game.screen.x + ig.system.width;
        },

        draw: function() {
            // No this.parent(); draw once and leave it alone

            // Draw snow
            ig.system.context.fillStyle = 'rgba(255, 255, 255, 0.8)';
            ig.system.context.beginPath();
            ig.system.context.arc(
                this.pos.x + this.size.x / 2,
                this.pos.y + this.size.y / 2,
                this.size.x / 2,
                0,
                2 * Math.PI
            );
            ig.system.context.fill();
        },

        handleMovementTrace: function(res) {
            this.pos.x += this.vel.x * ig.system.tick;
            this.pos.y += this.vel.y * ig.system.tick;
        }
    });
});
<commit_msg>Added condition trigger (user set) to snow.<commit_after>/**
 *  weather.js
 *  -----
 *  Impact Weather Add-on for the Impact Day/Night Cycle Plugin
 *  https://github.com/chessmasterhong/impact-day-night
 *
 *  Kevin Chan (chessmasterhong)
 *
 *  An add-on for the Impact Day/Night Cycle Plugin for the Impact game engine
 *  that simulates weather conditions.
 */

ig.module(
    'plugins.weather'
)
.requires(
    'impact.game'
)
.defines(function() {
    "use strict";

    ig.Weather = ig.Game.extend({
        condition: 2, // 0 = clear, 1 = rain, 2 = snow

        max_particles: 100,

        //---------------------------------------------------------------------
        // Init
        init: function() {
            if(this.condition)
                this.nextParticle = new ig.Timer();
        }, // End init
        //---------------------------------------------------------------------

        //---------------------------------------------------------------------
        // Update
        update: function() {
            if(this.condition === 1) {

            } else if(this.condition === 2) {
                if(this.nextParticle.delta() >= 0 && this.max_particles > 0) {
                    this.max_particles--;
                    this.nextParticle.set(1 / this.max_particles);
                    ig.game.spawnEntity(
                        EntitySnow,
                        Math.random() * (ig.game.screen.x + ig.system.width - ig.game.screen.x) + ig.game.screen.x,
                        ig.game.screen.y
                    );
                }
            }
        }, // End update
        //---------------------------------------------------------------------

        //---------------------------------------------------------------------
        // Draw
        draw: function() {
            // TODO
        } // End draw
        //---------------------------------------------------------------------
    });

    var EntitySnow = ig.Entity.extend({
        size: {x: 3, y: 3},
        vel: {x: 60, y: 80},
        //maxVel: {x: 100, y: 100},

        init: function(x, y, settings) {
            this.parent(x, y, settings);

            // Randomize initial velocity
            this.vel.x *= Math.random() * 2 - 1;
            this.vel.y *= Math.abs(Math.random() * 2 - 1); // Snow should not "fall" upwards...
        },

        update: function() {
            this.parent();

            // Handle entity moving out of screen bounds
            // Wraparound to opposite side of screen
            if(this.pos.y > ig.game.screen.y + ig.system.height)
               this.pos.y = ig.game.screen.y;
            else if(this.pos.x > ig.game.screen.x + ig.system.width)
                this.pos.x = ig.game.screen.x;
            else if(this.pos.x < ig.game.screen.x)
                this.pos.x = ig.game.screen.x + ig.system.width;
        },

        draw: function() {
            // No this.parent(); draw once and leave it alone

            // Draw snow
            ig.system.context.fillStyle = 'rgba(255, 255, 255, 0.8)';
            ig.system.context.beginPath();
            ig.system.context.arc(
                this.pos.x + this.size.x / 2,
                this.pos.y + this.size.y / 2,
                this.size.x / 2,
                0,
                2 * Math.PI
            );
            ig.system.context.fill();
        },

        handleMovementTrace: function(res) {
            this.pos.x += this.vel.x * ig.system.tick;
            this.pos.y += this.vel.y * ig.system.tick;
        }
    });
});
<|endoftext|>


<commit_before>var request = window.server.request,
    Q = require("q"),
    moment = require('moment'),
    _ = require("lodash"),
    sprintf = require("sprintf-js").sprintf,
    db = require("data/db/finchartsdb");

var PriceDataApi = {
    /**
     *  chartKeys: {
     *      ticker: "MSFT",
     *      timeframe: {
     *          from: <Date>,
     *          to: <Date>
     *      },
     *      duration: 'daily'
     *  }
     */
    getTickerDataAsync: function (chartKeys) {
        return getCookieCrumb()
                 .then(function (crumb) {
                    return fetchData(crumb, chartKeys);
                  })
                 .then(parseData);
    }
};

function getCookieCrumb() {
     var re = /CrumbStore\":{\"crumb\":\"(.*?)\"}/gi;
     return getResponseFromServer("https://finance.yahoo.com/quote/MSFT/history")
                .then((data) => {
                  var matches = re.exec(data.body);
                  return {
                    cookie: data.response.headers['set-cookie'][0] || "",
                    crumb: matches[1] || ""
                  };
                });
   }

function fetchData(cookieData, chartKeys) {
    var fetchDeferred = Q.defer(), ticker = chartKeys.ticker;

    var toDate = chartKeys.timeframe.to;
    var fromDate = chartKeys.timeframe.from;
    // var toDate = moment().toDate();
    // var fromDate = moment(toDate).subtract(chartKeys.timeframe.from, 'months').toDate();
    var duration = chartKeys.duration === "daily" ? "d" : (chartKeys.duration === "weekly" ? "w" : "m");

    var interval = (function (period) {
          switch (period) {
            case "daily": return "1d";
            case "weekly": return "1wk";
            case "monthly": return "1mo";
            default: return "1d";
          }
        })(chartKeys.duration);

    //https://query1.finance.yahoo.com/v7/finance/download/MSFT?period1=1466191294&period2=1497727294&interval=1mo&events=history&crumb=wQMXQHsHwRC

    var dataUrl = sprintf("https://query1.finance.yahoo.com/v7/finance/download/%s?period1=%s&period2=%s&interval=%s&events=history&crumb=%s",
                                        ticker,
                                        Math.floor((fromDate.getTime()) / 1000),
                                        Math.floor((toDate.getTime()) / 1000),
                                        interval,
                                        cookieData.crumb);

    var cacheKey = sprintf("%s_%s_%s_%s", ticker.toLowerCase(), duration, moment(toDate).format('YYYYMMDD'), moment(fromDate).format('YYYYMMDD'));

    getFromCache(cacheKey)
      .then(function (rowData /* {key: "", data: ""} */) {
        if (rowData) {
          fetchDeferred.resolve({priceData: rowData.data, ticker: ticker});
        } else {
          getDataFromServer(dataUrl, { cookie: cookieData.cookie })
            .then(function (priceData) {
              addToCache(cacheKey, priceData)
                .then(function () {
                  fetchDeferred.resolve({priceData: priceData, ticker: ticker});
                });
            });
        }
      });

    return fetchDeferred.promise;
}

function getFromCache(cacheKey) {
  return db.pricetable
          .where('key')
          .equals(cacheKey)
          .first()
          .then(function (priceData) {
            console.log("data loaded from indexDb", priceData);
            return priceData;
          }).catch(function (error) {
            console.log("IndexDb error:", error);
            return "";
          });
}

function getDataFromServer(dataUrl, headers) {
  console.log("loading data from", dataUrl, headers);
  var serverDataDeferred = Q.defer();
  request({
    url: dataUrl,
    headers: headers
    }, function (error, response, body) {
      if (!error && response.statusCode === 200) {
        console.log("data downloaded");
        serverDataDeferred.resolve(body);
      }
    });
  return serverDataDeferred.promise;
}

function getResponseFromServer(dataUrl) {
  console.log("loading data from", dataUrl);
  var serverDataDeferred = Q.defer();
  request(dataUrl, function (error, response, body) {
    if (!error && response.statusCode === 200) {
      console.log("data downloaded");
      serverDataDeferred.resolve({
        response: response,
        body: body
      });
    }
  });
  return serverDataDeferred.promise;
}

function addToCache(cacheKey, priceData) {
  console.log("adding data to indexdb", cacheKey);
  return db.pricetable
          .add({key: cacheKey, data: priceData})
          .catch(function (error) {
            console.log("IndexDb add error:", error, cacheKey);
            return "";
          });
}

// Jan12 - Jan7 - daily - http://finance.yahoo.com/q/hp?s=YHOO&a=00&b=12&c=1996&d=00&e=7&f=2014&g=d
// Dec12 - Dec7 - daily - http://finance.yahoo.com/q/hp?s=YHOO&a=11&b=12&c=1996&d=11&e=7&f=2014&g=d
// Dec12 - Dec7 - weekly - http://finance.yahoo.com/q/hp?s=YHOO&a=11&b=12&c=1996&d=11&e=7&f=2014&g=w
// Dec12 - Dec7 - montly - http://finance.yahoo.com/q/hp?s=YHOO&a=11&b=12&c=1996&d=11&e=7&f=2014&g=m

// data - {priceData: "string", ticker: "ticker"}

function parseData(data) {
    var returnData = {
        status: 'loaded',
        series: [],
        min: Infinity,
        max: -Infinity,
        minVolume: Infinity,
        maxVolume: -Infinity
    };

    var parseDeferred = Q.defer();

    var dateRecords = data.priceData.split('\n');

    _.each(dateRecords, function (dataRow) {
        var record = (dataRow || "").split(',');

        if (record.length !== 7 || isNaN(record[1]) || isNaN(record[2]) ||
            isNaN(record[3]) || isNaN(record[4]) || isNaN(record[5]) ||
            isNaN(record[6])) {
            return;
          }

        var data = {
            date: Date.parse(record[0]),
            open: +parseFloat(record[1]).toFixed(2),
            high: +parseFloat(record[2]).toFixed(2),
            low: +parseFloat(record[3]).toFixed(2),
            close: +parseFloat(record[5]).toFixed(2),
            volume: +parseFloat(record[6]).toFixed(2),
            adjClose: +parseFloat(record[5]).toFixed(2)
        };

        // adjust prices for splits (unfortunately yahoo includes dividends in adjClose)
        // the prices displayed in this tool will be off by a bit
        /*var adjRatio = data.adjClose / data.close;
        data.open = formatNumber(data.open * adjRatio);
        data.high = formatNumber(data.high * adjRatio);
        data.low = formatNumber(data.low * adjRatio);
        data.close = formatNumber(data.close * adjRatio);*/

        returnData.series.push(data);

        if (data.low < returnData.min)
            returnData.min = data.low;

        if (data.high > returnData.max)
            returnData.max = data.high;

        if (data.volume < returnData.minVolume)
            returnData.minVolume = data.volume;

        if (data.volume > returnData.maxVolume)
            returnData.maxVolume = data.volume;
      });

      parseDeferred.resolve(returnData);

      return parseDeferred.promise;
}

/*function formatNumber(number) {
      return +number.toFixed(3);
}*/

module.exports = PriceDataApi;
<commit_msg>patch data issues<commit_after>var request = window.server.request,
    Q = require("q"),
    moment = require('moment'),
    _ = require("lodash"),
    sprintf = require("sprintf-js").sprintf,
    db = require("data/db/finchartsdb");

var PriceDataApi = {
    /**
     *  chartKeys: {
     *      ticker: "MSFT",
     *      timeframe: {
     *          from: <Date>,
     *          to: <Date>
     *      },
     *      duration: 'daily'
     *  }
     */
    getTickerDataAsync: function (chartKeys) {
        return getCookieCrumb()
                 .then(function (crumb) {
                    return fetchData(crumb, chartKeys);
                  })
                 .then(parseData);
    }
};

var yahooSessionCache;

function getCookieCrumb() {
     if (yahooSessionCache) {
        return Q.resolve(yahooSessionCache);
     } else {
       var re = /CrumbStore\":{\"crumb\":\"(.*?)\"}/gi;
       return getResponseFromServer("https://finance.yahoo.com/quote/MSFT/history")
                  .then((data) => {
                    var matches = re.exec(data.body);

                    // cache session data
                    yahooSessionCache = {
                      cookie: data.response.headers['set-cookie'][0] || "",
                      crumb: matches[1] || ""
                    };

                    // clear the cache after an hour
                    setTimeout(function () {
                      yahooSessionCache = null;
                    }, 1000 * 60 * 60);

                    return yahooSessionCache;
                  });
      }
   }

function fetchData(cookieData, chartKeys) {
    var fetchDeferred = Q.defer(), ticker = chartKeys.ticker;

    var toDate = chartKeys.timeframe.to;
    var fromDate = chartKeys.timeframe.from;
    // var toDate = moment().toDate();
    // var fromDate = moment(toDate).subtract(chartKeys.timeframe.from, 'months').toDate();
    var duration = chartKeys.duration === "daily" ? "d" : (chartKeys.duration === "weekly" ? "w" : "m");

    var interval = (function (period) {
          switch (period) {
            case "daily": return "1d";
            case "weekly": return "1wk";
            case "monthly": return "1mo";
            default: return "1d";
          }
        })(chartKeys.duration);

    //https://query1.finance.yahoo.com/v7/finance/download/MSFT?period1=1466191294&period2=1497727294&interval=1mo&events=history&crumb=wQMXQHsHwRC

    var dataUrl = sprintf("https://query1.finance.yahoo.com/v7/finance/download/%s?period1=%s&period2=%s&interval=%s&events=history&crumb=%s",
                                        ticker,
                                        Math.floor((fromDate.getTime()) / 1000),
                                        Math.floor((toDate.getTime()) / 1000),
                                        interval,
                                        cookieData.crumb);

    var cacheKey = sprintf("%s_%s_%s_%s", ticker.toLowerCase(), duration, moment(toDate).format('YYYYMMDD'), moment(fromDate).format('YYYYMMDD'));

    getFromCache(cacheKey)
      .then(function (rowData /* {key: "", data: ""} */) {
        if (rowData) {
          fetchDeferred.resolve({priceData: rowData.data, ticker: ticker});
        } else {
          getDataFromServer(dataUrl, { cookie: cookieData.cookie })
            .then(function (priceData) {
              addToCache(cacheKey, priceData)
                .then(function () {
                  fetchDeferred.resolve({priceData: priceData, ticker: ticker});
                });
            });
        }
      });

    return fetchDeferred.promise;
}

function getFromCache(cacheKey) {
  return db.pricetable
          .where('key')
          .equals(cacheKey)
          .first()
          .then(function (priceData) {
            console.log("data loaded from indexDb", priceData);
            return priceData;
          }).catch(function (error) {
            console.log("IndexDb error:", error);
            return "";
          });
}

function getDataFromServer(dataUrl, headers) {
  console.log("loading data from", dataUrl, headers);
  var serverDataDeferred = Q.defer();
  request({
    url: dataUrl,
    headers: headers
    }, function (error, response, body) {
      if (!error && response.statusCode === 200) {
        console.log("data downloaded");
        serverDataDeferred.resolve(body);
      }
    });
  return serverDataDeferred.promise;
}

function getResponseFromServer(dataUrl) {
  console.log("loading data from", dataUrl);
  var serverDataDeferred = Q.defer();
  request(dataUrl, function (error, response, body) {
    if (!error && response.statusCode === 200) {
      console.log("data downloaded");
      serverDataDeferred.resolve({
        response: response,
        body: body
      });
    }
  });
  return serverDataDeferred.promise;
}

function addToCache(cacheKey, priceData) {
  console.log("adding data to indexdb", cacheKey);
  return db.pricetable
          .add({key: cacheKey, data: priceData})
          .catch(function (error) {
            console.log("IndexDb add error:", error, cacheKey);
            return "";
          });
}

// Jan12 - Jan7 - daily - http://finance.yahoo.com/q/hp?s=YHOO&a=00&b=12&c=1996&d=00&e=7&f=2014&g=d
// Dec12 - Dec7 - daily - http://finance.yahoo.com/q/hp?s=YHOO&a=11&b=12&c=1996&d=11&e=7&f=2014&g=d
// Dec12 - Dec7 - weekly - http://finance.yahoo.com/q/hp?s=YHOO&a=11&b=12&c=1996&d=11&e=7&f=2014&g=w
// Dec12 - Dec7 - montly - http://finance.yahoo.com/q/hp?s=YHOO&a=11&b=12&c=1996&d=11&e=7&f=2014&g=m

// data - {priceData: "string", ticker: "ticker"}

function parseData(data) {
    var returnData = {
        status: 'loaded',
        series: [],
        min: Infinity,
        max: -Infinity,
        minVolume: Infinity,
        maxVolume: -Infinity
    };

    var parseDeferred = Q.defer();

    var dateRecords = data.priceData.split('\n');
    // console.log(dateRecords);

    _.each(dateRecords, function (dataRow) {
        var record = (dataRow || "").split(',');

        if (record.length !== 7 || isNaN(record[1]) || isNaN(record[2]) ||
            isNaN(record[3]) || isNaN(record[4]) || isNaN(record[5]) ||
            isNaN(record[6])) {
            return;
          }

        var data = {
            date: Date.parse(record[0]),
            open: +parseFloat(record[1]).toFixed(2),
            high: +parseFloat(record[2]).toFixed(2),
            low: +parseFloat(record[3]).toFixed(2),
            close: +parseFloat(record[4]).toFixed(2),
            volume: +parseFloat(record[6]).toFixed(2),
            adjClose: +parseFloat(record[5]).toFixed(2)
        };

        // Patch the data issues
        if (data.close < data.low) {
          data.close = data.adjClose;
        }

        // adjust prices for splits (unfortunately yahoo includes dividends in adjClose)
        // the prices displayed in this tool will be off by a bit
        /*var adjRatio = data.adjClose / data.close;
        data.open = formatNumber(data.open * adjRatio);
        data.high = formatNumber(data.high * adjRatio);
        data.low = formatNumber(data.low * adjRatio);
        data.close = formatNumber(data.close * adjRatio);*/

        returnData.series.push(data);

        if (data.low < returnData.min)
            returnData.min = data.low;

        if (data.high > returnData.max)
            returnData.max = data.high;

        if (data.volume < returnData.minVolume)
            returnData.minVolume = data.volume;

        if (data.volume > returnData.maxVolume)
            returnData.maxVolume = data.volume;
      });

      parseDeferred.resolve(returnData);

      return parseDeferred.promise;
}

/*function formatNumber(number) {
      return +number.toFixed(3);
}*/

module.exports = PriceDataApi;
<|endoftext|>


<commit_before>var React = require('react');
var PropTypes = React.PropTypes;

var MapLayerToggle = React.createClass({

  propTypes: {
    toggleText: PropTypes.string,
  },
  handleLayerClick: function(e){

    const leafletMap = this.props.leafletMap;
    const leafletLayer = this.props.layer;
    const isLayerVis = leafletMap.hasLayer(leafletLayer);
    isLayerVis ? leafletMap.removeLayer(leafletLayer) : leafletMap.addLayer(leafletLayer);
    //console.log(isLayerVis)

  },
  getDefaultProps: function() {
    return {
      toggleText:'Layer Toggle'
    };
  },
  getInitialState: function() {
    this.toggleText = this.props.toggleText;
    return {
      toggleText: this.toggleText
    };
  },
  render: function() {
    return (

          <input type="checkbox"  defaultChecked  onClick={this.handleLayerClick} />
          {this.state.toggleText}

    );
  }

});

module.exports = MapLayerToggle;
<commit_msg>some comments<commit_after>var React = require('react');
var PropTypes = React.PropTypes;

var MapLayerToggle = React.createClass({

  propTypes: {
    toggleText: PropTypes.string,
  },
  handleLayerClick: function(e){

    //get map object.  saved in redux store
    const leafletMap = this.props.leafletMap;

    //get the current layer object.
    const leafletLayer = this.props.layer;

    //check if the layer is vissible
    const isLayerVis = leafletMap.hasLayer(leafletLayer);

    //if vissible remove (turn off) layer otherwise add (turn on)
    isLayerVis ? leafletMap.removeLayer(leafletLayer) : leafletMap.addLayer(leafletLayer);

  },
  getDefaultProps: function() {
    return {
      toggleText:'Layer Toggle'
    };
  },
  getInitialState: function() {
    this.toggleText = this.props.toggleText;
    return {
      toggleText: this.toggleText
    };
  },
  render: function() {
    return (

          <input type="checkbox"  defaultChecked  onClick={this.handleLayerClick} />
          {this.state.toggleText}

    );
  }

});

module.exports = MapLayerToggle;
<|endoftext|>