<commit_before>/* Copyright 2018 Google LLC

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

    https://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 { google } = require('googleapis');
const { OAuth2Client } = require('google-auth-library');
const async = require('async');
const BigQuery = require('@google-cloud/bigquery');

const bigquery = new BigQuery();

var config = require('./config');
const Permission = require('../models/permission');
const User = require('../models/user');
const Organization = require('../models/organization');
const Report = require('../models/report');
var config = require('../utilities/config');

module.exports = {
  buildPermissionsQuery: function(bq_instance, bq_dataset, bq_client_data_perms, organization_id_list, identifier, identifierType, condition, token) {
    var updateRow = 'UPDATE `' + bq_instance + '.' + bq_dataset + '.' + bq_client_data_perms + '` SET Permissions = [';

    for (var i = 0; i < organization_id_list.length - 1; i++) {
      updateRow += '"' + organization_id_list[i] + '",';
    }

    updateRow += '"' + organization_id_list[organization_id_list.length - 1] + '"] WHERE ' + identifier + ' ';

    if (condition === 'contains') {
      updateRow += 'like "%' + token + '%"';
    } else if (condition === 'equals') {
      if (identifierType === 'STRING') {
        updateRow += '= "' + token + '"';
      } else {
        updateRow += '= ' + token;
      }
    } else if (condition === 'excludes') {
      if (identifierType === 'STRING') {
        updateRow += '<> "' + token + '"';
      } else {
        updateRow += '<> ' + token;
      }
    }

    return updateRow;
  },

  shareReport: function(file_id, permissions, revoke, callback) {
    const oAuth2Client = new OAuth2Client();

    oAuth2Client.credentials = {
      access_token: config.access_token
    };

    const drive = google.drive({ version: 'v3', auth: oAuth2Client });

    if (revoke == 0) {
      console.log('Sharing report...');

      async.eachSeries(
        permissions,
        function(permission, callback) {
          drive.permissions.create(
            {
              resource: permission,
              fileId: file_id,
              fields: 'id',
              sendNotificationEmail: false
            },
            function(err, res) {
              if (err) {
                // Handle error...
                console.log(err);
                callback(1);
              } else {
                console.log(res.status);
                console.log('Saving permissions...');

                var permObj = { fileId: file_id, googleID: permission.emailAddress, drivePermId: res.data.id };
                Permission.create(permObj, function(err3, res3) {
                  if (err3) {
                    console.log(err3);
                    callback(1);
                  }
                });

                if (res.status == 200) {
                  console.log('Sharing report finished...');
                  callback(0);
                } else {
                  callback(1);
                }
              }
            }
          );
        },
        function(err) {
          if (err) {
            // Handle error
            console.error(err);
            callback(1);
          } else {
            // All permissions inserted
          }
        }
      );
    } else {
      console.log('Revoking shared report...');
      async.eachSeries(permissions, function(permission, callback) {
        drive.permissions.delete(
          {
            fileId: permission.fileId,
            permissionId: permission.drivePermId
          },
          function(err, res) {
            if (err) {
              // Handle error...
              console.log(err);
              callback(1);
            } else {
              console.log(res.status);
              console.log('Removing permissions...');

              if (res.status == 204) {
                Permission.deleteOne({ drivePermId: permission.drivePermId }, function(err4, docs1) {
                  if (err4) {
                    callback(1);
                  }
                  callback(0);
                });
              }
            }
          }
        );
      });
    }
  },

  regenerateTables: function(callback) {
    Organization.find(function(err1, docs1) {
      if (err1) {
        callback(1);
      }

      var deleteAllOrgs =
        'DELETE FROM `' +
        config.bq_instance +
        '.' +
        config.bq_dataset +
        '.vendors_2` WHERE organization_id IN (SELECT organization_id FROM `' +
        config.bq_instance +
        '.' +
        config.bq_dataset +
        '.vendors_2`)';
      console.log('******** deleteAllOrgs');
      console.log(deleteAllOrgs);
      bigquery
        .createQueryStream(deleteAllOrgs)
        .on('error', function(err) {
          callback(1);
          console.log('##### ERROR : deleteAllOrgs');
          console.log(err);
        })
        .on('data', function(data) {})
        .on('end', function() {
          var deleteAllUsers =
            'DELETE FROM `' +
            config.bq_instance +
            '.' +
            config.bq_dataset +
            '.users_2` WHERE user_id in (SELECT user_id FROM `' +
            config.bq_instance +
            '.' +
            config.bq_dataset +
            '.users_2`)';
          console.log('******** deleteAllUsers');
          console.log(deleteAllUsers);
          bigquery
            .createQueryStream(deleteAllUsers)
            .on('error', function(err) {
              callback(1);
              console.log('##### ERROR : deleteAllUsers');
              console.log(err);
            })
            .on('data', function(data) {})
            .on('end', function() {
              var deleteAllUserVendorRoles =
                'DELETE FROM `' +
                config.bq_instance +
                '.' +
                config.bq_dataset +
                '.user_vendor_roles_2` WHERE user_id in (SELECT user_id FROM `' +
                config.bq_instance +
                '.' +
                config.bq_dataset +
                '.user_vendor_roles_2`)';
              console.log('******  deleteAllUserVendorRoles ');
              console.log(deleteAllUserVendorRoles);
              bigquery
                .createQueryStream(deleteAllUserVendorRoles)
                .on('error', function(err) {
                  callback(1);
                  console.log('##### ERROR : deleteAllUserVendorRoles');
                  console.log(err);
                })
                .on('data', function(data) {})
                .on('end', function() {
                  var deleteAllCurrentRoles =
                    'DELETE FROM `' +
                    config.bq_instance +
                    '.' +
                    config.bq_dataset +
                    '.user_current_vendor_2` WHERE user_id in (SELECT user_id FROM `' +
                    config.bq_instance +
                    '.' +
                    config.bq_dataset +
                    '.user_current_vendor_2`)';
                  console.log('******* deleteAllCurrentRoles ');
                  console.log(deleteAllCurrentRoles);
                  bigquery
                    .createQueryStream(deleteAllCurrentRoles)
                    .on('error', function(err) {
                      callback(1);
                      console.log('##### ERROR : deleteAllCurrentRoles');
                      console.log(err);
                    })
                    .on('data', function(data) {})
                    .on('end', function() {
                        var flag = 0;
                        for (var i = 0; i < docs1.length; i++) {
                          var createOrgRow = 'INSERT INTO `' + config.bq_instance + '.' + config.bq_dataset + '.vendors_2` (organization_id, organization) VALUES ("' + docs1[i]._id + '","' + docs1[i].name + '")';

                          bigquery
                            .createQueryStream(createOrgRow)
                            .on('error', function(err) {
                              callback(1);
                            })
                            .on('data', function(data) {})
                            .on('end', function() {
                              console.log('!!!! Printing i: ' + i);
                              if (flag == 0) {
                                flag = 1;

                                User.find(function(err2, docs2) {
                                  if (err2) {
                                    callback(1);
                                    console.log('##### ERROR : createOrgRow');
                                    console.log(err);
                                  }

                                  for (var j = 0; j < docs2.length; j++) {
                                      var currentUser = docs2[j];
                                      var createUserRow =
                                            'INSERT INTO `' +
                                            config.bq_instance +
                                            '.' +
                                            config.bq_dataset +
                                            '.users_2` (user_id, googleID, role) VALUES ("' +
                                            docs2[j]._id +
                                            '","' +
                                            docs2[j].googleID +
                                            '","' +
                                            docs2[j].role +
                                            '")';
                                            console.log('*********** createUserRow ');
                                            console.log(createUserRow);

                                            bigquery
                                              .createQueryStream(createUserRow)
                                              .on('error', function(err) {
                                                 callback(1);
                                                 console.log('##### ERROR : createUserRow');
                                                 console.log(err);
                                              })
                                              .on('data', function(data) {})
                                              .on('end', function() {
                                                   var user_orgs = currentUser.organizations;

                                                    for (var k = 0; k < user_orgs.length; k++) {
                                                      var createUserVendorRow =
                                                        'INSERT INTO `' +
                                                        config.bq_instance +
                                                        '.' +
                                                        config.bq_dataset +
                                                        '.user_vendor_roles_2` (user_id, organization_id) VALUES ("' +
                                                        currentUser._id +
                                                        '","' +
                                                        currentUser.organizations[k]._id +
                                                        '")';
                                                      console.log('******* createUserVendorRow  ');
                                                      console.log(createUserVendorRow);
                                                      bigquery
                                                        .createQueryStream(createUserVendorRow)
                                                        .on('error', function(err) {
                                                          callback(1);
                                                          console.log('##### ERROR : createUserVendorRow');
                                                          console.log(err);
                                                        })
                                                        .on('data', function(data) {})
                                                        .on('end', function() {
                                                          if (j == docs2.length && k == user_orgs.length) {
                                                            callback(0);
                                                          }
                                                        });
                                  }
                               });
                             }
                          });
                        }
                      });
                    }
                  });
              });
            });
        });
    });
  }

};
<commit_msg>changing order of loops<commit_after>/* Copyright 2018 Google LLC

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

    https://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 { google } = require('googleapis');
const { OAuth2Client } = require('google-auth-library');
const async = require('async');
const BigQuery = require('@google-cloud/bigquery');

const bigquery = new BigQuery();

var config = require('./config');
const Permission = require('../models/permission');
const User = require('../models/user');
const Organization = require('../models/organization');
const Report = require('../models/report');
var config = require('../utilities/config');

module.exports = {
  buildPermissionsQuery: function(bq_instance, bq_dataset, bq_client_data_perms, organization_id_list, identifier, identifierType, condition, token) {
    var updateRow = 'UPDATE `' + bq_instance + '.' + bq_dataset + '.' + bq_client_data_perms + '` SET Permissions = [';

    for (var i = 0; i < organization_id_list.length - 1; i++) {
      updateRow += '"' + organization_id_list[i] + '",';
    }

    updateRow += '"' + organization_id_list[organization_id_list.length - 1] + '"] WHERE ' + identifier + ' ';

    if (condition === 'contains') {
      updateRow += 'like "%' + token + '%"';
    } else if (condition === 'equals') {
      if (identifierType === 'STRING') {
        updateRow += '= "' + token + '"';
      } else {
        updateRow += '= ' + token;
      }
    } else if (condition === 'excludes') {
      if (identifierType === 'STRING') {
        updateRow += '<> "' + token + '"';
      } else {
        updateRow += '<> ' + token;
      }
    }

    return updateRow;
  },

  shareReport: function(file_id, permissions, revoke, callback) {
    const oAuth2Client = new OAuth2Client();

    oAuth2Client.credentials = {
      access_token: config.access_token
    };

    const drive = google.drive({ version: 'v3', auth: oAuth2Client });

    if (revoke == 0) {
      console.log('Sharing report...');

      async.eachSeries(
        permissions,
        function(permission, callback) {
          drive.permissions.create(
            {
              resource: permission,
              fileId: file_id,
              fields: 'id',
              sendNotificationEmail: false
            },
            function(err, res) {
              if (err) {
                // Handle error...
                console.log(err);
                callback(1);
              } else {
                console.log(res.status);
                console.log('Saving permissions...');

                var permObj = { fileId: file_id, googleID: permission.emailAddress, drivePermId: res.data.id };
                Permission.create(permObj, function(err3, res3) {
                  if (err3) {
                    console.log(err3);
                    callback(1);
                  }
                });

                if (res.status == 200) {
                  console.log('Sharing report finished...');
                  callback(0);
                } else {
                  callback(1);
                }
              }
            }
          );
        },
        function(err) {
          if (err) {
            // Handle error
            console.error(err);
            callback(1);
          } else {
            // All permissions inserted
          }
        }
      );
    } else {
      console.log('Revoking shared report...');
      async.eachSeries(permissions, function(permission, callback) {
        drive.permissions.delete(
          {
            fileId: permission.fileId,
            permissionId: permission.drivePermId
          },
          function(err, res) {
            if (err) {
              // Handle error...
              console.log(err);
              callback(1);
            } else {
              console.log(res.status);
              console.log('Removing permissions...');

              if (res.status == 204) {
                Permission.deleteOne({ drivePermId: permission.drivePermId }, function(err4, docs1) {
                  if (err4) {
                    callback(1);
                  }
                  callback(0);
                });
              }
            }
          }
        );
      });
    }
  },

  regenerateTables: function(callback) {
    Organization.find(function(err1, docs1) {
      if (err1) {
        callback(1);
      }

      var deleteAllOrgs =
        'DELETE FROM `' +
        config.bq_instance +
        '.' +
        config.bq_dataset +
        '.vendors_2` WHERE organization_id IN (SELECT organization_id FROM `' +
        config.bq_instance +
        '.' +
        config.bq_dataset +
        '.vendors_2`)';
      console.log('******** deleteAllOrgs');
      console.log(deleteAllOrgs);
      bigquery
        .createQueryStream(deleteAllOrgs)
        .on('error', function(err) {
          callback(1);
          console.log('##### ERROR : deleteAllOrgs');
          console.log(err);
        })
        .on('data', function(data) {})
        .on('end', function() {
          var deleteAllUsers =
            'DELETE FROM `' +
            config.bq_instance +
            '.' +
            config.bq_dataset +
            '.users_2` WHERE user_id in (SELECT user_id FROM `' +
            config.bq_instance +
            '.' +
            config.bq_dataset +
            '.users_2`)';
          console.log('******** deleteAllUsers');
          console.log(deleteAllUsers);
          bigquery
            .createQueryStream(deleteAllUsers)
            .on('error', function(err) {
              callback(1);
              console.log('##### ERROR : deleteAllUsers');
              console.log(err);
            })
            .on('data', function(data) {})
            .on('end', function() {
              var deleteAllUserVendorRoles =
                'DELETE FROM `' +
                config.bq_instance +
                '.' +
                config.bq_dataset +
                '.user_vendor_roles_2` WHERE user_id in (SELECT user_id FROM `' +
                config.bq_instance +
                '.' +
                config.bq_dataset +
                '.user_vendor_roles_2`)';
              console.log('******  deleteAllUserVendorRoles ');
              console.log(deleteAllUserVendorRoles);
              bigquery
                .createQueryStream(deleteAllUserVendorRoles)
                .on('error', function(err) {
                  callback(1);
                  console.log('##### ERROR : deleteAllUserVendorRoles');
                  console.log(err);
                })
                .on('data', function(data) {})
                .on('end', function() {
                  var deleteAllCurrentRoles =
                    'DELETE FROM `' +
                    config.bq_instance +
                    '.' +
                    config.bq_dataset +
                    '.user_current_vendor_2` WHERE user_id in (SELECT user_id FROM `' +
                    config.bq_instance +
                    '.' +
                    config.bq_dataset +
                    '.user_current_vendor_2`)';
                  console.log('******* deleteAllCurrentRoles ');
                  console.log(deleteAllCurrentRoles);
                  bigquery
                    .createQueryStream(deleteAllCurrentRoles)
                    .on('error', function(err) {
                      callback(1);
                      console.log('##### ERROR : deleteAllCurrentRoles');
                      console.log(err);
                    })
                    .on('data', function(data) {})
                    .on('end', function() {
                        var flag = 0;
                        for (var i = 0; i < docs1.length; i++) {
                          var createOrgRow = 'INSERT INTO `' + config.bq_instance + '.' + config.bq_dataset + '.vendors_2` (organization_id, organization) VALUES ("' + docs1[i]._id + '","' + docs1[i].name + '")';

                          bigquery
                            .createQueryStream(createOrgRow)
                            .on('error', function(err) {
                              callback(1);
                            })
                            .on('data', function(data) {})
                            .on('end', function() {
                              console.log('!!!! Printing i: ' + i);
                              if (flag == 0) {
                                flag = 1;

                                User.find(function(err2, docs2) {
                                  if (err2) {
                                    callback(1);
                                    console.log('##### ERROR : createOrgRow');
                                    console.log(err);
                                  }

                                  var queryList = [];
                                  for (var j = 0; j < docs2.length; j++) {
                                      var currentUser = docs2[j];
                                      var createUserRow =
                                            'INSERT INTO `' +
                                            config.bq_instance +
                                            '.' +
                                            config.bq_dataset +
                                            '.users_2` (user_id, googleID, role) VALUES ("' +
                                            docs2[j]._id +
                                            '","' +
                                            docs2[j].googleID +
                                            '","' +
                                            docs2[j].role +
                                            '")';
                                            console.log('*********** createUserRow ');
                                            console.log(createUserRow);

                                      queryList.push(createUserRow);

                                      var user_orgs = currentUser.organizations;

                                       for (var k = 0; k < user_orgs.length; k++) {
                                         var createUserVendorRow =
                                           'INSERT INTO `' +
                                           config.bq_instance +
                                           '.' +
                                           config.bq_dataset +
                                           '.user_vendor_roles_2` (user_id, organization_id) VALUES ("' +
                                           currentUser._id +
                                           '","' +
                                           currentUser.organizations[k]._id +
                                           '")';

                                          queryList.push(createUserVendorRow);
                                         }
                                    }

                                    for (var k = 0; k < queryList.length; k++) {
                                      bigquery
                                        .createQueryStream(queryList[k])
                                        .on('error', function(err) {
                                          callback(1);
                                        })
                                        .on('data', function(data) {})
                                        .on('end', function() {
                                          if (k == queryList.length) {
                                            return(1);
                                          }
                                        });
                                    }
                                  });
                                }
                              });
                            }
                          });
                        });
                      });
                    });
                  });
                }
};
<|endoftext|>


<commit_before>'use strict';

// Spreadsheet view, 2019. Inserts button next to to the task name.
togglbutton.render('.SpreadsheetRow .SpreadsheetTaskName:not(.toggl)', { observe: true },
  function (taskNameCell) {
    const container = taskNameCell.closest('.SpreadsheetRow');

    if (container.querySelector('.toggl-button')) {
      // Due to the way this UI is rendered, we must check for existence of old buttons manually.
      return;
    }

    const descriptionSelector = () => taskNameCell.querySelector('textarea').textContent.trim();
    const projectHeaderSelector = () => {
      // Try to look for for page project title instead.
      const projectHeader = document.querySelector('.TopbarPageHeaderStructure.ProjectPageHeader .TopbarPageHeaderStructure-title');
      if (!projectHeader) {
        return '';
      }
      return projectHeader.textContent.trim();
    };
    const projectSelector = () => {
      const projectCell = container.querySelector('.SpreadsheetTaskRow-projectsCell');
      if (!projectCell) {
        // Try to look for for page project title instead.
        return projectHeaderSelector();
      }

      // There can be multiple projects, but we can't support trying to match multiple yet.
      const firstProject = projectCell.querySelector('.Pill');
      return firstProject ? firstProject.textContent.trim() : projectHeaderSelector();
    };

    const link = togglbutton.createTimerLink({
      className: 'asana-spreadsheet',
      description: descriptionSelector,
      projectName: projectSelector,
      buttonType: 'minimal'
    });

    taskNameCell.insertAdjacentElement('afterend', link);
  }
);

// 2019 My Tasks view, possibly other similar views.
togglbutton.render('.MyTasksTaskRow:not(.toggl)', { observe: true },
  function (elem) {
    if (elem.querySelector('.toggl-button')) {
      // Due to the way this UI is rendered, we must check for existence of old buttons manually.
      return;
    }
    const container = elem.querySelector('.ItemRowTwoColumnStructure-left');
    const description = elem.querySelector('.TaskName textarea').textContent;

    const projectSelector = () => {
      const projectElement = elem.querySelector('.TaskRow-pots .Pill');

      return projectElement ? projectElement.textContent : '';
    };

    const link = togglbutton.createTimerLink({
      className: 'asana-new-ui',
      description: description,
      projectName: projectSelector,
      buttonType: 'minimal'
    });

    container.appendChild(link);
  }
);

// Dec 2019 detail view
togglbutton.render(
  '.SingleTaskPaneSpreadsheet:not(.toggl)',
  { observe: true },
  function (elem) {
    if ($('.toggl-button', elem)) {
      return;
    }

    const descriptionSelector = () => {
      return $('.SingleTaskTitleInput-taskName textarea', elem).textContent.trim();
    };

    const projectSelector = () => {
      const projectEl = $('.TaskProjectToken-potTokenizerPill', elem);
      return projectEl ? projectEl.textContent.trim() : '';
    };

    const link = togglbutton.createTimerLink({
      className: 'asana-board',
      description: descriptionSelector,
      projectName: projectSelector,
      buttonType: 'minimal'
    });

    link.style.margin = '0 5px';

    const firstButton = elem.querySelector('.SingleTaskPaneToolbar-button');
    firstButton.parentNode.insertBefore(link, firstButton);
  }
);

// Old and Beta UI - detail view
togglbutton.render(
  '.SingleTaskPane-titleRow:not(.toggl)',
  { observe: true },
  function (elem) {
    if ($('.toggl-button', elem)) {
      return;
    }
    const container = $('.SingleTaskPaneToolbar');

    const descriptionSelector = () => {
      return $(
        '.SingleTaskPane-titleRow .simpleTextarea',
        elem.parentNode
      ).textContent;
    };

    const projectSelector = () => {
      const projectElement = $(
        '.SingleTaskPane-projects .TaskProjectPill-projectName',
        elem.parentNode
      );

      return projectElement ? projectElement.textContent : '';
    };

    const link = togglbutton.createTimerLink({
      className: 'asana-board',
      description: descriptionSelector,
      projectName: projectSelector,
      buttonType: 'minimal'
    });

    link.style.marginRight = '5px';

    if (container) {
      const closeButton = container.lastElementChild;
      container.insertBefore(link, closeButton);
    }
  }
);
<commit_msg>fix(asana): Get task description when button is clicked Closes #1646<commit_after>'use strict';

// Spreadsheet view, 2019. Inserts button next to to the task name.
togglbutton.render('.SpreadsheetRow .SpreadsheetTaskName:not(.toggl)', { observe: true },
  function (taskNameCell) {
    const container = taskNameCell.closest('.SpreadsheetRow');

    if (container.querySelector('.toggl-button')) {
      // Due to the way this UI is rendered, we must check for existence of old buttons manually.
      return;
    }

    const descriptionSelector = () => taskNameCell.querySelector('textarea').textContent.trim();
    const projectHeaderSelector = () => {
      // Try to look for for page project title instead.
      const projectHeader = document.querySelector('.TopbarPageHeaderStructure.ProjectPageHeader .TopbarPageHeaderStructure-title');
      if (!projectHeader) {
        return '';
      }
      return projectHeader.textContent.trim();
    };
    const projectSelector = () => {
      const projectCell = container.querySelector('.SpreadsheetTaskRow-projectsCell');
      if (!projectCell) {
        // Try to look for for page project title instead.
        return projectHeaderSelector();
      }

      // There can be multiple projects, but we can't support trying to match multiple yet.
      const firstProject = projectCell.querySelector('.Pill');
      return firstProject ? firstProject.textContent.trim() : projectHeaderSelector();
    };

    const link = togglbutton.createTimerLink({
      className: 'asana-spreadsheet',
      description: descriptionSelector,
      projectName: projectSelector,
      buttonType: 'minimal'
    });

    taskNameCell.insertAdjacentElement('afterend', link);
  }
);

// 2019 My Tasks view, possibly other similar views.
togglbutton.render('.MyTasksTaskRow:not(.toggl)', { observe: true },
  function (elem) {
    if (elem.querySelector('.toggl-button')) {
      // Due to the way this UI is rendered, we must check for existence of old buttons manually.
      return;
    }
    const container = elem.querySelector('.ItemRowTwoColumnStructure-left');
    const descriptionSelector = () => elem.querySelector('.TaskName textarea').textContent;

    const projectSelector = () => {
      const projectElement = elem.querySelector('.TaskRow-pots .Pill');

      return projectElement ? projectElement.textContent : '';
    };

    const link = togglbutton.createTimerLink({
      className: 'asana-new-ui',
      description: descriptionSelector,
      projectName: projectSelector,
      buttonType: 'minimal'
    });

    container.appendChild(link);
  }
);

// Dec 2019 detail view
togglbutton.render(
  '.SingleTaskPaneSpreadsheet:not(.toggl)',
  { observe: true },
  function (elem) {
    if ($('.toggl-button', elem)) {
      return;
    }

    const descriptionSelector = () => {
      return $('.SingleTaskTitleInput-taskName textarea', elem).textContent.trim();
    };

    const projectSelector = () => {
      const projectEl = $('.TaskProjectToken-potTokenizerPill', elem);
      return projectEl ? projectEl.textContent.trim() : '';
    };

    const link = togglbutton.createTimerLink({
      className: 'asana-board',
      description: descriptionSelector,
      projectName: projectSelector,
      buttonType: 'minimal'
    });

    link.style.margin = '0 5px';

    const firstButton = elem.querySelector('.SingleTaskPaneToolbar-button');
    firstButton.parentNode.insertBefore(link, firstButton);
  }
);

// Old and Beta UI - detail view
togglbutton.render(
  '.SingleTaskPane-titleRow:not(.toggl)',
  { observe: true },
  function (elem) {
    if ($('.toggl-button', elem)) {
      return;
    }
    const container = $('.SingleTaskPaneToolbar');

    const descriptionSelector = () => {
      return $(
        '.SingleTaskPane-titleRow .simpleTextarea',
        elem.parentNode
      ).textContent;
    };

    const projectSelector = () => {
      const projectElement = $(
        '.SingleTaskPane-projects .TaskProjectPill-projectName',
        elem.parentNode
      );

      return projectElement ? projectElement.textContent : '';
    };

    const link = togglbutton.createTimerLink({
      className: 'asana-board',
      description: descriptionSelector,
      projectName: projectSelector,
      buttonType: 'minimal'
    });

    link.style.marginRight = '5px';

    if (container) {
      const closeButton = container.lastElementChild;
      container.insertBefore(link, closeButton);
    }
  }
);
<|endoftext|>


<commit_before>var gamestate = {};
gamestate.planetData = [];
gamestate.planetData[0] = {name:"Earth"  ,technology:1,minerals:1,fuel:1,food:0,antimatter:0,production:1,population:1,society:0};
gamestate.planetData[1] = {name:"Mars"   ,technology:1,minerals:1,fuel:1,food:0,antimatter:0,production:1,population:1,society:0};
gamestate.planetData[2] = {name:"Jupiter",technology:1,minerals:1,fuel:1,food:0,antimatter:0,production:1,population:1,society:0};
gamestate.planetData[3] = {name:"Saturn" ,technology:1,minerals:1,fuel:1,food:0,antimatter:0,production:1,population:1,society:0};
gamestate.planetData[4] = {name:"Uranus" ,technology:1,minerals:1,fuel:1,food:0,antimatter:0,production:1,population:1,society:0};
gamestate.planetData[5] = {name:"Neptune",technology:1,minerals:1,fuel:1,food:0,antimatter:0,production:1,population:1,society:0};
gamestate.currentPlanet = 0;
gamestate.costCache = [];
gamestate.supplyCache = [];

function onStart(){

  onArrive();
}

function newGame(){
  //random gen gamestate.planetData
  //gen player state
  onStart();
}

function loadGame(name){
  gamestate = JSON.parse(localStorage[name]);
  onStart();
}

function saveGame(name){
  localStorage.setItem(name,JSON.stringify(gamestate));
}

function onArrive(){
  timeStep();
  gamestate.costCache = generateCosts(gamestate.currentPlanet);

  var a = document.getElementById(gamestate.planetData[gamestate.currentPlanet].name);
  a.className = "track currentTrack";
  loadPlanetInterface(gamestate.currentPlanet);
}

function onLeave(to){
  var a = document.getElementById(gamestate.planetData[gamestate.currentPlanet].name);
  a.className = "track";
  clearPlanetInterface();
  hideInfo();
  updateInventory()
  gamestate.currentPlanet = to;
}

function generateWorlds(){

}

function timeStep(){

}

function generateCosts(planet){
  var temp;
  var out = {};
  var cache = {};
  for(var item in itemConfig){
    temp = itemConfig[item](gamestate.planetData[planet]); //returns [supply, demand]
    cache[item] = temp;
    temp = temp[1]/temp[0];
    if(isNaN(temp) || temp === 0 || temp > 1000000000){
      continue;
    }
    out[item] = temp;
  }
  gamestate.supplyCache = cache;
  return out;
}

var itemConfig =
{
  computers:function(traits){return [traits.production*traits.technology,traits.population/traits.minerals]},
  fuel:function(traits){return [traits.production*traits.fuel,traits.population/traits.technology]}
};

var worldConfig = {
  population:.1,
  technology:1.1,
  fuel:0.1,
  minerals:0.1,
  antimatter:0,
  food: 1,
  production: 1
};

gamestate.playerData = {reputation:[0,0,0,0,0,0]};
gamestate.playerData.inventory = {"credits":1000,"fuel":1000};
gamestate.playerData.ship = {engine:{},cargobay:{}};

function jump(to){
  var d = getDistance(to,gamestate.currentPlanet);
  var cost = ((d/30) | 0);
  if(gamestate.playerData.inventory.fuel - cost >= 0){
    gamestate.playerData.inventory.fuel -= cost;
    fly(to,gamestate.currentPlanet);
    onLeave(to);
  }else{
    showNotification('You do not have enough fuel to complete the journey');
  }
}

function transaction(itemName,itemQuantity) {
  // item quantity + inventory quantity >= 0 && player credits + (itemQuantity * item cost on planet) >= 0
  if (itemQuantity + (gamestate.playerData.inventory[itemName] || 0) >= 0 && gamestate.playerData.inventory.credits + (itemQuantity * gamestate.costCache[itemName]) >= 0 ) {
    gamestate.playerData.inventory[itemName] = itemQuantity + (gamestate.playerData.inventory[itemName]||0);
    gamestate.playerData.inventory.credits -= (itemQuantity * gamestate.costCache[itemName]);
    updateInventory();
  } else{
    showNotification("You cannot afford this transaction");
  };
  updateTransactionList()
}<commit_msg>Generate costCache on departure<commit_after>var gamestate = {};
gamestate.planetData = [];
gamestate.planetData[0] = {name:"Earth"  ,technology:1,minerals:1,fuel:1,food:0,antimatter:0,production:1,population:1,society:0};
gamestate.planetData[1] = {name:"Mars"   ,technology:1,minerals:1,fuel:1,food:0,antimatter:0,production:1,population:1,society:0};
gamestate.planetData[2] = {name:"Jupiter",technology:1,minerals:1,fuel:1,food:0,antimatter:0,production:1,population:1,society:0};
gamestate.planetData[3] = {name:"Saturn" ,technology:1,minerals:1,fuel:1,food:0,antimatter:0,production:1,population:1,society:0};
gamestate.planetData[4] = {name:"Uranus" ,technology:1,minerals:1,fuel:1,food:0,antimatter:0,production:1,population:1,society:0};
gamestate.planetData[5] = {name:"Neptune",technology:1,minerals:1,fuel:1,food:0,antimatter:0,production:1,population:1,society:0};
gamestate.currentPlanet = 0;
gamestate.costCache = [];
gamestate.supplyCache = [];

function onStart(){

  onArrive();
}

function newGame(){
  //random gen gamestate.planetData
  //gen player state
  onStart();
}

function loadGame(name){
  gamestate = JSON.parse(localStorage[name]);
  onStart();
}

function saveGame(name){
  localStorage.setItem(name,JSON.stringify(gamestate));
}

function onArrive(){
  var a = document.getElementById(gamestate.planetData[gamestate.currentPlanet].name);
  a.className = "track currentTrack";
  loadPlanetInterface(gamestate.currentPlanet);
}

function onLeave(to){
  var a = document.getElementById(gamestate.planetData[gamestate.currentPlanet].name);
  a.className = "track";
  clearPlanetInterface();
  hideInfo();
  updateInventory()
  gamestate.currentPlanet = to;
  timeStep();
  gamestate.costCache = generateCosts(gamestate.currentPlanet);
}

function generateWorlds(){

}

function timeStep(){

}

function generateCosts(planet){
  var temp;
  var out = {};
  var cache = {};
  for(var item in itemConfig){
    temp = itemConfig[item](gamestate.planetData[planet]); //returns [supply, demand]
    cache[item] = temp;
    temp = temp[1]/temp[0];
    if(isNaN(temp) || temp === 0 || temp > 1000000000){
      continue;
    }
    out[item] = temp;
  }
  gamestate.supplyCache = cache;
  return out;
}

var itemConfig =
{
  computers:function(traits){return [traits.production*traits.technology,traits.population/traits.minerals]},
  fuel:function(traits){return [traits.production*traits.fuel,traits.population/traits.technology]}
};

var worldConfig = {
  population:.1,
  technology:1.1,
  fuel:0.1,
  minerals:0.1,
  antimatter:0,
  food: 1,
  production: 1
};

gamestate.playerData = {reputation:[0,0,0,0,0,0]};
gamestate.playerData.inventory = {"credits":1000,"fuel":1000};
gamestate.playerData.ship = {engine:{},cargobay:{}};

function jump(to){
  var d = getDistance(to,gamestate.currentPlanet);
  var cost = ((d/30) | 0);
  if(gamestate.playerData.inventory.fuel - cost >= 0){
    gamestate.playerData.inventory.fuel -= cost;
    fly(to,gamestate.currentPlanet);
    onLeave(to);
  }else{
    showNotification('You do not have enough fuel to complete the journey');
  }
}

function transaction(itemName,itemQuantity) {
  // item quantity + inventory quantity >= 0 && player credits + (itemQuantity * item cost on planet) >= 0
  if (itemQuantity + (gamestate.playerData.inventory[itemName] || 0) >= 0 && gamestate.playerData.inventory.credits + (itemQuantity * gamestate.costCache[itemName]) >= 0 ) {
    gamestate.playerData.inventory[itemName] = itemQuantity + (gamestate.playerData.inventory[itemName]||0);
    gamestate.playerData.inventory.credits -= (itemQuantity * gamestate.costCache[itemName]);
    updateInventory();
  } else{
    showNotification("You cannot afford this transaction");
  };
  updateTransactionList()
}<|endoftext|>


<commit_before>import ext from "./utils/ext";

function getDepartureArrivalAirports() {
  var urlArray = (document.location.href).split(';');

  var from = urlArray[1].split('=')[1].split(',');
  var to = urlArray[2].split('=')[1].split(',');

  let departingAirport;
  let arrivingAirport;

  // TODO: handle 'all airports' selection
  from.length === 1 ? departingAirport = from[0] : departingAirport = 'undefined';
  to.length === 1 ? arrivingAirport = to[0] : arrivingAirport = 'undefined';

  return { from: departingAirport, to: arrivingAirport };
}

function checkIfResultsLoaded() {
  var flights = document.querySelectorAll('a.DQX2Q1B-d-X');

  // If flights results are not loaded in DOM, abort
  if(!flights.length || !flights) {
    console.log("Flights not yet loaded. Aborting...");
    return;
  }
  return flights;
  // // If results are loaded:
  // const destination = getDepartureArrivalAirports();
  // const flightResults = extractFlights(flights, destination);

  // return buildResultData(destination, flights.length, flightResults);
}

function buildResultData(flights) {
  // Final flightData response
  const flightData = {
    departingAirport: "",
    arrivingAirport: "",
    airports: [],
    allFlights: [],
    numFlights: null
  };

  const destination = getDepartureArrivalAirports();
  const flightResults = extractFlights(flights, destination);

  // Input departingAirport and arrivingAirport data
  if(destination && destination.from && destination.to) {
    flightData.departingAirport = destination.from;
    flightData.arrivingAirport = destination.to;
  }

  // Input numFlights
  if(flights && flights.length) {
    flightData.numFlights = flights.length;
  }

  if(flightResults) {
    flightData.allFlights = flightResults;
  }
  return flightData;
}

function processResultData(flightData) {
  const data = JSON.stringify(flightData);
  // Call get-airports in background.js
  ext.runtime.sendMessage({ action: "get-airports", data: data }, function(response) {
    if (response && response.action === "have-airports") {
      console.log("have-airport response:", response);

      // ext.tabs.query({active: true, currentWindow: true}, function(tabs) {
      //   var activeTab = tabs[0];
      //   // Output # of flights
      //   chrome.tabs.sendMessage(activeTab.id, { action: 'insert-content', data: response.data });
      // });
      for (var i=0; i < response.data.length; i++) {
        writeToScreen(response.data[i].id, response.data[i].emissions, response.data[i].distance);
      }
    } else {
      // renderMessage("Sorry, there was an error.");
      console.error("Sorry, there was an error.")
    }
  })
}

function extractFlights(flights, destination) {

  const flightResuts = [];
  // Get allFlights Array
  for (var i = 0; i < flights.length; i++) {
    var flight = flights[i];

    var flightInfo = {
      id: "",
      numLayovers: "",
      flightRoute: []
    };

    var flightId = flight.parentElement.getAttribute("iti");
    flightInfo.id = flightId;

    var numStopsElem = flight.getElementsByClassName("DQX2Q1B-d-Qb")[0];
    if (numStopsElem) {
      var numStopsSplit = numStopsElem.innerHTML.split(" ");;
      if (numStopsSplit[0] == 'Nonstop') {
        flightInfo.numLayovers = 0;
      } else {
        flightInfo.numLayovers = Number(numStopsSplit[0]);
      }
    }

    // Create flightRoute Array: init with departing Airport
    var flightroute = [destination.from];
    flightInfo.flightRoute = flightroute

    var layoversElem = flight.getElementsByClassName("DQX2Q1B-d-Z")[0];
    if (layoversElem) {
      var layoversArray;

      if (flightInfo.numLayovers == 1) { // ie. "2h 32m in YYZ"
        layoversArray = layoversElem.innerHTML.split(" ").slice(-1)
      } else { // ie. YVR, YYZ
        layoversArray = layoversElem.innerHTML.split(", ")
      }
      flightInfo.flightRoute = flightroute.concat(layoversArray);
    }

    // Add arriving Airport at the end
    flightInfo.flightRoute.push(destination.to);

    // Add flight info to allFlights array
    flightResuts.push(flightInfo);
  }

  return flightResuts;
};

var writeToScreen = function writeToScreen(iti, emissions,distance){
  if (iti) {
    var parentElem = document.querySelectorAll('[iti="'+iti+'"]')[0];
    var childElem = parentElem.getElementsByClassName("DQX2Q1B-d-Sb")[0];

    // Create new text node: Assing className 'co2-emission' and style
    var newDiv = document.createElement("DIV");
    newDiv.className = "co2-emission";
    newDiv.style.color = "rgb(18, 177, 74)";
    newDiv.appendChild(document.createTextNode(`co2e(kg): ${emissions}`));

    if(childElem) {
      let existingEmissionData = childElem.getElementsByClassName("co2-emission");
      if (existingEmissionData && existingEmissionData.length > 0) {
        childElem.removeChild(existingEmissionData);
      }
      childElem.appendChild(newDiv);
    }
  }
}

function onRequest(request, sender, sendResponse) {

  let flights;

  switch(request.action) {
    case 'query_flights':
      console.warn("querying flights...");
      // Check if flight info is already there
      flights = checkIfResultsLoaded();
      if(flights && flights.length > 0) {
        processResultData(buildResultData(flights));
        // sendResponse(buildResultData(flights));
      }
      break;
    case 'process-flights':
      console.warn("processing flights...");
      flights = checkIfResultsLoaded();
      if(flights && flights.length > 0) {
        sendResponse(buildResultData(flights));
      }
      break;
    case 'insert-content':
      for (var i=0; i<request.data.length; i++) {
        writeToScreen(request.data[i].id, request.data[i].emissions, request.data[i].distance);
      }
    break;
    default:
      console.log("action unknown");
  }
}

ext.runtime.onMessage.addListener(onRequest);
<commit_msg>Resolve removeChild error<commit_after>import ext from "./utils/ext";

function getDepartureArrivalAirports() {
  var urlArray = (document.location.href).split(';');

  var from = urlArray[1].split('=')[1].split(',');
  var to = urlArray[2].split('=')[1].split(',');

  let departingAirport;
  let arrivingAirport;

  // TODO: handle 'all airports' selection
  from.length === 1 ? departingAirport = from[0] : departingAirport = 'undefined';
  to.length === 1 ? arrivingAirport = to[0] : arrivingAirport = 'undefined';

  return { from: departingAirport, to: arrivingAirport };
}

function checkIfResultsLoaded() {
  var flights = document.querySelectorAll('a.DQX2Q1B-d-X');

  // If flights results are not loaded in DOM, abort
  if(!flights.length || !flights) {
    console.log("Flights not yet loaded. Aborting...");
    return;
  }
  return flights;
  // // If results are loaded:
  // const destination = getDepartureArrivalAirports();
  // const flightResults = extractFlights(flights, destination);

  // return buildResultData(destination, flights.length, flightResults);
}

function buildResultData(flights) {
  // Final flightData response
  const flightData = {
    departingAirport: "",
    arrivingAirport: "",
    airports: [],
    allFlights: [],
    numFlights: null
  };

  const destination = getDepartureArrivalAirports();
  const flightResults = extractFlights(flights, destination);

  // Input departingAirport and arrivingAirport data
  if(destination && destination.from && destination.to) {
    flightData.departingAirport = destination.from;
    flightData.arrivingAirport = destination.to;
  }

  // Input numFlights
  if(flights && flights.length) {
    flightData.numFlights = flights.length;
  }

  if(flightResults) {
    flightData.allFlights = flightResults;
  }
  return flightData;
}

function processResultData(flightData) {
  const data = JSON.stringify(flightData);
  // Call get-airports in background.js
  ext.runtime.sendMessage({ action: "get-airports", data: data }, function(response) {
    if (response && response.action === "have-airports") {
      console.log("have-airport response:", response);

      // ext.tabs.query({active: true, currentWindow: true}, function(tabs) {
      //   var activeTab = tabs[0];
      //   // Output # of flights
      //   chrome.tabs.sendMessage(activeTab.id, { action: 'insert-content', data: response.data });
      // });
      for (var i=0; i < response.data.length; i++) {
        writeToScreen(response.data[i].id, response.data[i].emissions, response.data[i].distance);
      }
    } else {
      // renderMessage("Sorry, there was an error.");
      console.error("Sorry, there was an error.")
    }
  })
}

function extractFlights(flights, destination) {

  const flightResuts = [];
  // Get allFlights Array
  for (var i = 0; i < flights.length; i++) {
    var flight = flights[i];

    var flightInfo = {
      id: "",
      numLayovers: "",
      flightRoute: []
    };

    var flightId = flight.parentElement.getAttribute("iti");
    flightInfo.id = flightId;

    var numStopsElem = flight.getElementsByClassName("DQX2Q1B-d-Qb")[0];
    if (numStopsElem) {
      var numStopsSplit = numStopsElem.innerHTML.split(" ");;
      if (numStopsSplit[0] == 'Nonstop') {
        flightInfo.numLayovers = 0;
      } else {
        flightInfo.numLayovers = Number(numStopsSplit[0]);
      }
    }

    // Create flightRoute Array: init with departing Airport
    var flightroute = [destination.from];
    flightInfo.flightRoute = flightroute

    var layoversElem = flight.getElementsByClassName("DQX2Q1B-d-Z")[0];
    if (layoversElem) {
      var layoversArray;

      if (flightInfo.numLayovers == 1) { // ie. "2h 32m in YYZ"
        layoversArray = layoversElem.innerHTML.split(" ").slice(-1)
      } else { // ie. YVR, YYZ
        layoversArray = layoversElem.innerHTML.split(", ")
      }
      flightInfo.flightRoute = flightroute.concat(layoversArray);
    }

    // Add arriving Airport at the end
    flightInfo.flightRoute.push(destination.to);

    // Add flight info to allFlights array
    flightResuts.push(flightInfo);
  }

  return flightResuts;
};

var writeToScreen = function writeToScreen(iti, emissions,distance){
  if (iti) {
    var flightEntry = document.querySelectorAll('[iti="'+iti+'"]')[0];
    var stopsColumn = flightEntry.getElementsByClassName("DQX2Q1B-d-Sb")[0];

    if(stopsColumn) {
      let existingEmissionData = stopsColumn.getElementsByClassName("co2-emission");

      if (existingEmissionData && existingEmissionData.length > 0) {
        // stopsColumn.removeChild(existingEmissionData);
        for (let i = 0, n = existingEmissionData.length; i < n; i++) {
          existingEmissionData[i].remove();
        }
      }
    }

    // Create new text node: Assing className 'co2-emission' and style
    var newDiv = document.createElement("DIV");
    newDiv.className = "co2-emission";
    newDiv.style.color = "rgb(18, 177, 74)";
    newDiv.appendChild(document.createTextNode(`co2e(kg): ${emissions}`));
    stopsColumn.appendChild(newDiv);
  }
}

function onRequest(request, sender, sendResponse) {

  let flights;

  switch(request.action) {
    case 'query_flights':
      console.warn("querying flights...");
      // Check if flight info is already there
      flights = checkIfResultsLoaded();
      if(flights && flights.length > 0) {
        processResultData(buildResultData(flights));
        // sendResponse(buildResultData(flights));
      }
      break;
    case 'process-flights':
      console.warn("processing flights...");
      flights = checkIfResultsLoaded();
      if(flights && flights.length > 0) {
        sendResponse(buildResultData(flights));
      }
      break;
    case 'insert-content':
      for (var i=0; i<request.data.length; i++) {
        writeToScreen(request.data[i].id, request.data[i].emissions, request.data[i].distance);
      }
    break;
    default:
      console.log("action unknown");
  }
}

ext.runtime.onMessage.addListener(onRequest);
<|endoftext|>


<commit_before>/**
 * @author Mat Groves http://matgroves.com/ @Doormat23
 */

/**
 * A set of functions used by the canvas renderer to draw the primitive graphics data
 *
 * @class CanvasGraphics
 */
PIXI.CanvasGraphics = function()
{
};

/*
 * Renders a PIXI.Graphics object to a canvas.
 *
 * @static
 * @method renderGraphics
 * @param graphics {Graphics} the actual graphics object to render
 * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas
 */
PIXI.CanvasGraphics.renderGraphics = function(graphics, context)
{
    var worldAlpha = graphics.worldAlpha;
    var color = '';

    for (var i = 0; i < graphics.graphicsData.length; i++)
    {
        var data = graphics.graphicsData[i];
        var shape = data.shape;

        context.strokeStyle = color = '#' + ('00000' + ( data.lineColor | 0).toString(16)).substr(-6);

        context.lineWidth = data.lineWidth;

        if(data.type === PIXI.Graphics.POLY)
        {
            context.beginPath();

            var points = shape.points;

            context.moveTo(points[0], points[1]);

            for (var j=1; j < points.length/2; j++)
            {
                context.lineTo(points[j * 2], points[j * 2 + 1]);
            }

            if(shape.closed)
            {
                context.lineTo(points[0], points[1]);
            }

            // if the first and last point are the same close the path - much neater :)
            if(points[0] === points[points.length-2] && points[1] === points[points.length-1])
            {
                context.closePath();
            }

            if(data.fill)
            {
                context.globalAlpha = data.fillAlpha * worldAlpha;
                context.fillStyle = color = '#' + ('00000' + ( data.fillColor | 0).toString(16)).substr(-6);
                context.fill();
            }
            if(data.lineWidth)
            {
                context.globalAlpha = data.lineAlpha * worldAlpha;
                context.stroke();
            }
        }
        else if(data.type === PIXI.Graphics.RECT)
        {

            if(data.fillColor || data.fillColor === 0)
            {
                context.globalAlpha = data.fillAlpha * worldAlpha;
                context.fillStyle = color = '#' + ('00000' + ( data.fillColor | 0).toString(16)).substr(-6);
                context.fillRect(shape.x, shape.y, shape.width, shape.height);

            }
            if(data.lineWidth)
            {
                context.globalAlpha = data.lineAlpha * worldAlpha;
                context.strokeRect(shape.x, shape.y, shape.width, shape.height);
            }
        }
        else if(data.type === PIXI.Graphics.CIRC)
        {
            // TODO - need to be Undefined!
            context.beginPath();
            context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI);
            context.closePath();

            if(data.fill)
            {
                context.globalAlpha = data.fillAlpha * worldAlpha;
                context.fillStyle = color = '#' + ('00000' + ( data.fillColor | 0).toString(16)).substr(-6);
                context.fill();
            }
            if(data.lineWidth)
            {
                context.globalAlpha = data.lineAlpha * worldAlpha;
                context.stroke();
            }
        }
        else if(data.type === PIXI.Graphics.ELIP)
        {
            // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas

            var w = shape.width * 2;
            var h = shape.height * 2;

            var x = shape.x - w/2;
            var y = shape.y - h/2;

            context.beginPath();

            var kappa = 0.5522848,
                ox = (w / 2) * kappa, // control point offset horizontal
                oy = (h / 2) * kappa, // control point offset vertical
                xe = x + w,           // x-end
                ye = y + h,           // y-end
                xm = x + w / 2,       // x-middle
                ym = y + h / 2;       // y-middle

            context.moveTo(x, ym);
            context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
            context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
            context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
            context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);

            context.closePath();

            if(data.fill)
            {
                context.globalAlpha = data.fillAlpha * worldAlpha;
                context.fillStyle = color = '#' + ('00000' + ( data.fillColor | 0).toString(16)).substr(-6);
                context.fill();
            }
            if(data.lineWidth)
            {
                context.globalAlpha = data.lineAlpha * worldAlpha;
                context.stroke();
            }
        }
            /*
        else if (data.type === PIXI.Graphics.RREC)
        {
            var rx = points[0];
            var ry = points[1];
            var width = points[2];
            var height = points[3];
            var radius = points[4];

            var maxRadius = Math.min(width, height) / 2 | 0;
            radius = radius > maxRadius ? maxRadius : radius;

            context.beginPath();
            context.moveTo(rx, ry + radius);
            context.lineTo(rx, ry + height - radius);
            context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height);
            context.lineTo(rx + width - radius, ry + height);
            context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius);
            context.lineTo(rx + width, ry + radius);
            context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry);
            context.lineTo(rx + radius, ry);
            context.quadraticCurveTo(rx, ry, rx, ry + radius);
            context.closePath();

            if(data.fillColor || data.fillColor === 0)
            {
                context.globalAlpha = data.fillAlpha * worldAlpha;
                context.fillStyle = color = '#' + ('00000' + ( data.fillColor | 0).toString(16)).substr(-6);
                context.fill();

            }
            if(data.lineWidth)
            {
                context.globalAlpha = data.lineAlpha * worldAlpha;
                context.stroke();
            }
        }
            */
    }
};

/*
 * Renders a graphics mask
 *
 * @static
 * @private
 * @method renderGraphicsMask
 * @param graphics {Graphics} the graphics which will be used as a mask
 * @param context {CanvasRenderingContext2D} the context 2d method of the canvas
 */
PIXI.CanvasGraphics.renderGraphicsMask = function(graphics, context)
{
    var len = graphics.graphicsData.length;

    if(len === 0) return;

    if(len > 1)
    {
        len = 1;
        window.console.log('Pixi.js warning: masks in canvas can only mask using the first path in the graphics object');
    }

    for (var i = 0; i < 1; i++)
    {
        var data = graphics.graphicsData[i];
        var shape = data.shape;

        if(data.type === PIXI.Graphics.POLY)
        {
            context.beginPath();

            var points = shape.points;

            context.moveTo(points[0], points[1]);

            for (var j=1; j < points.length/2; j++)
            {
                context.lineTo(points[j * 2], points[j * 2 + 1]);
            }

            // if the first and last point are the same close the path - much neater :)
            if(points[0] === points[points.length-2] && points[1] === points[points.length-1])
            {
                context.closePath();
            }

        }
        else if(data.type === PIXI.Graphics.RECT)
        {
            context.beginPath();
            context.rect(shape.x, shape.y, shape.width, shape.height);
            context.closePath();
        }
        else if(data.type === PIXI.Graphics.CIRC)
        {
            // TODO - need to be Undefined!
            context.beginPath();
            context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI);
            context.closePath();
        }
        else if(data.type === PIXI.Graphics.ELIP)
        {

            // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas

            var w = shape.width * 2;
            var h = shape.height * 2;

            var x = shape.x - w/2;
            var y = shape.y - h/2;

            context.beginPath();

            var kappa = 0.5522848,
                ox = (w / 2) * kappa, // control point offset horizontal
                oy = (h / 2) * kappa, // control point offset vertical
                xe = x + w,           // x-end
                ye = y + h,           // y-end
                xm = x + w / 2,       // x-middle
                ym = y + h / 2;       // y-middle

            context.moveTo(x, ym);
            context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
            context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
            context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
            context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
            context.closePath();
        }
        else if (data.type === PIXI.Graphics.RREC)
        {

            var points = shape.points;
            var rx = points[0];
            var ry = points[1];
            var width = points[2];
            var height = points[3];
            var radius = points[4];

            var maxRadius = Math.min(width, height) / 2 | 0;
            radius = radius > maxRadius ? maxRadius : radius;

            context.beginPath();
            context.moveTo(rx, ry + radius);
            context.lineTo(rx, ry + height - radius);
            context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height);
            context.lineTo(rx + width - radius, ry + height);
            context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius);
            context.lineTo(rx + width, ry + radius);
            context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry);
            context.lineTo(rx + radius, ry);
            context.quadraticCurveTo(rx, ry, rx, ry + radius);
            context.closePath();
        }
    }
};
<commit_msg>Update CanvasGraphics.js<commit_after>/**
 * @author Mat Groves http://matgroves.com/ @Doormat23
 */

/**
 * A set of functions used by the canvas renderer to draw the primitive graphics data
 *
 * @class CanvasGraphics
 */
PIXI.CanvasGraphics = function()
{
};

/*
 * Renders a PIXI.Graphics object to a canvas.
 *
 * @static
 * @method renderGraphics
 * @param graphics {Graphics} the actual graphics object to render
 * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas
 */
PIXI.CanvasGraphics.renderGraphics = function(graphics, context)
{
    var worldAlpha = graphics.worldAlpha;
    var color = '';

    for (var i = 0; i < graphics.graphicsData.length; i++)
    {
        var data = graphics.graphicsData[i];
        var shape = data.shape;

        context.strokeStyle = color = '#' + ('00000' + ( data.lineColor | 0).toString(16)).substr(-6);

        context.lineWidth = data.lineWidth;

        if(data.type === PIXI.Graphics.POLY)
        {
            context.beginPath();

            var points = shape.points;

            context.moveTo(points[0], points[1]);

            for (var j=1; j < points.length/2; j++)
            {
                context.lineTo(points[j * 2], points[j * 2 + 1]);
            }

            if(shape.closed)
            {
                context.lineTo(points[0], points[1]);
            }

            // if the first and last point are the same close the path - much neater :)
            if(points[0] === points[points.length-2] && points[1] === points[points.length-1])
            {
                context.closePath();
            }

            if(data.fill)
            {
                context.globalAlpha = data.fillAlpha * worldAlpha;
                context.fillStyle = color = '#' + ('00000' + ( data.fillColor | 0).toString(16)).substr(-6);
                context.fill();
            }
            if(data.lineWidth)
            {
                context.globalAlpha = data.lineAlpha * worldAlpha;
                context.stroke();
            }
        }
        else if(data.type === PIXI.Graphics.RECT)
        {

            if(data.fillColor || data.fillColor === 0)
            {
                context.globalAlpha = data.fillAlpha * worldAlpha;
                context.fillStyle = color = '#' + ('00000' + ( data.fillColor | 0).toString(16)).substr(-6);
                context.fillRect(shape.x, shape.y, shape.width, shape.height);

            }
            if(data.lineWidth)
            {
                context.globalAlpha = data.lineAlpha * worldAlpha;
                context.strokeRect(shape.x, shape.y, shape.width, shape.height);
            }
        }
        else if(data.type === PIXI.Graphics.CIRC)
        {
            // TODO - need to be Undefined!
            context.beginPath();
            context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI);
            context.closePath();

            if(data.fill)
            {
                context.globalAlpha = data.fillAlpha * worldAlpha;
                context.fillStyle = color = '#' + ('00000' + ( data.fillColor | 0).toString(16)).substr(-6);
                context.fill();
            }
            if(data.lineWidth)
            {
                context.globalAlpha = data.lineAlpha * worldAlpha;
                context.stroke();
            }
        }
        else if(data.type === PIXI.Graphics.ELIP)
        {
            // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas

            var w = shape.width * 2;
            var h = shape.height * 2;

            var x = shape.x - w/2;
            var y = shape.y - h/2;

            context.beginPath();

            var kappa = 0.5522848,
                ox = (w / 2) * kappa, // control point offset horizontal
                oy = (h / 2) * kappa, // control point offset vertical
                xe = x + w,           // x-end
                ye = y + h,           // y-end
                xm = x + w / 2,       // x-middle
                ym = y + h / 2;       // y-middle

            context.moveTo(x, ym);
            context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
            context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
            context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
            context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);

            context.closePath();

            if(data.fill)
            {
                context.globalAlpha = data.fillAlpha * worldAlpha;
                context.fillStyle = color = '#' + ('00000' + ( data.fillColor | 0).toString(16)).substr(-6);
                context.fill();
            }
            if(data.lineWidth)
            {
                context.globalAlpha = data.lineAlpha * worldAlpha;
                context.stroke();
            }
        }
            /*
        else if (data.type === PIXI.Graphics.RREC)
        {
            var rx = points[0];
            var ry = points[1];
            var width = points[2];
            var height = points[3];
            var radius = points[4];

            var maxRadius = Math.min(width, height) / 2 | 0;
            radius = radius > maxRadius ? maxRadius : radius;

            context.beginPath();
            context.moveTo(rx, ry + radius);
            context.lineTo(rx, ry + height - radius);
            context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height);
            context.lineTo(rx + width - radius, ry + height);
            context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius);
            context.lineTo(rx + width, ry + radius);
            context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry);
            context.lineTo(rx + radius, ry);
            context.quadraticCurveTo(rx, ry, rx, ry + radius);
            context.closePath();

            if(data.fillColor || data.fillColor === 0)
            {
                context.globalAlpha = data.fillAlpha * worldAlpha;
                context.fillStyle = color = '#' + ('00000' + ( data.fillColor | 0).toString(16)).substr(-6);
                context.fill();

            }
            if(data.lineWidth)
            {
                context.globalAlpha = data.lineAlpha * worldAlpha;
                context.stroke();
            }
        }
            */
    }
};

/*
 * Renders a graphics mask
 *
 * @static
 * @private
 * @method renderGraphicsMask
 * @param graphics {Graphics} the graphics which will be used as a mask
 * @param context {CanvasRenderingContext2D} the context 2d method of the canvas
 */
PIXI.CanvasGraphics.renderGraphicsMask = function(graphics, context)
{
    var len = graphics.graphicsData.length;

    if(len === 0) return;

    if(len > 1)
    {
        len = 1;
        window.console.log('Pixi.js warning: masks in canvas can only mask using the first path in the graphics object');
    }

    for (var i = 0; i < 1; i++)
    {
        var data = graphics.graphicsData[i];
        var shape = data.shape;

        if(data.type === PIXI.Graphics.POLY)
        {
            context.beginPath();

            var points = shape.points;

            context.moveTo(points[0], points[1]);

            for (var j=1; j < points.length/2; j++)
            {
                context.lineTo(points[j * 2], points[j * 2 + 1]);
            }

            // if the first and last point are the same close the path - much neater :)
            if(points[0] === points[points.length-2] && points[1] === points[points.length-1])
            {
                context.closePath();
            }

        }
        else if(data.type === PIXI.Graphics.RECT)
        {
            context.beginPath();
            context.rect(shape.x, shape.y, shape.width, shape.height);
            context.closePath();
        }
        else if(data.type === PIXI.Graphics.CIRC)
        {
            // TODO - need to be Undefined!
            context.beginPath();
            context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI);
            context.closePath();
        }
        else if(data.type === PIXI.Graphics.ELIP)
        {

            // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas

            var w = shape.width * 2;
            var h = shape.height * 2;

            var x = shape.x - w/2;
            var y = shape.y - h/2;

            context.beginPath();

            var kappa = 0.5522848,
                ox = (w / 2) * kappa, // control point offset horizontal
                oy = (h / 2) * kappa, // control point offset vertical
                xe = x + w,           // x-end
                ye = y + h,           // y-end
                xm = x + w / 2,       // x-middle
                ym = y + h / 2;       // y-middle

            context.moveTo(x, ym);
            context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
            context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
            context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
            context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
            context.closePath();
        }
        else if (data.type === PIXI.Graphics.RREC)
        {

            var pts = shape.points;
            var rx = pts[0];
            var ry = pts[1];
            var width = pts[2];
            var height = pts[3];
            var radius = pts[4];

            var maxRadius = Math.min(width, height) / 2 | 0;
            radius = radius > maxRadius ? maxRadius : radius;

            context.beginPath();
            context.moveTo(rx, ry + radius);
            context.lineTo(rx, ry + height - radius);
            context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height);
            context.lineTo(rx + width - radius, ry + height);
            context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius);
            context.lineTo(rx + width, ry + radius);
            context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry);
            context.lineTo(rx + radius, ry);
            context.quadraticCurveTo(rx, ry, rx, ry + radius);
            context.closePath();
        }
    }
};
<|endoftext|>


<commit_before>import en from '../i18n/dim_en.json';
import it from '../i18n/dim_it.json';
import de from '../i18n/dim_de.json';
import fr from '../i18n/dim_fr.json';
import es from '../i18n/dim_es.json';
import ja from '../i18n/dim_ja.json';
import ptBr from '../i18n/dim_pt_BR.json';

function config($compileProvider, $httpProvider, $translateProvider, $translateMessageFormatInterpolationProvider,
                hotkeysProvider, localStorageServiceProvider, ngHttpRateLimiterConfigProvider, ngDialogProvider) {
  'ngInject';

  // TODO: remove this depenency by fixing component bindings https://github.com/angular/angular.js/blob/master/CHANGELOG.md#breaking-changes-1
  $compileProvider.preAssignBindingsEnabled(true);
  // Allow chrome-extension: URLs in ng-src
  $compileProvider.imgSrcSanitizationWhitelist(/^\s*((https?|chrome-extension):|data:image\/)/);

  $httpProvider.interceptors.push('ngHttpRateLimiterInterceptor');
  $httpProvider.interceptors.push('http-refresh-token');
  $httpProvider.useApplyAsync(true);

  // See https://angular-translate.github.io/docs/#/guide
  $translateProvider.useSanitizeValueStrategy('escape');
  $translateProvider.useMessageFormatInterpolation();
  $translateProvider.preferredLanguage('en');

  $translateMessageFormatInterpolationProvider.messageFormatConfigurer(function(mf) {
    mf.setIntlSupport(true);
  });

  $translateProvider
    .translations('en', en)
    .translations('it', it)
    .translations('de', de)
    .translations('fr', fr)
    .translations('es', es)
    .translations('ja', ja)
    .translations('pt-br', ptBr)
    .fallbackLanguage('en');

  hotkeysProvider.includeCheatSheet = true;

  localStorageServiceProvider.setPrefix('');

  // Bungie's API will start throttling an API if it's called more than once per second. It does this
  // by making responses take 2s to return, not by sending an error code or throttling response. Choosing
  // our throttling limit to be 1 request every 1100ms lets us achieve best throughput while accounting for
  // what I assume is clock skew between Bungie's hosts when they calculate a global rate limit.
  ngHttpRateLimiterConfigProvider.addLimiter(/www\.bungie\.net\/Platform\/Destiny\/TransferItem/, 1, 1100);
  ngHttpRateLimiterConfigProvider.addLimiter(/www\.bungie\.net\/Platform\/Destiny\/EquipItem/, 1, 1100);
  ngHttpRateLimiterConfigProvider.addLimiter(/www\.bungie\.net\/d1\/Platform\/Destiny\/TransferItem/, 1, 1100);
  ngHttpRateLimiterConfigProvider.addLimiter(/www\.bungie\.net\/d1\/Platform\/Destiny\/EquipItem/, 1, 1100);

  // https://github.com/likeastore/ngDialog/issues/327
  ngDialogProvider.setDefaults({
    appendTo: '.app',
    disableAnimation: true,
    plain: true
  });
}

export default config;
<commit_msg>capitilization<commit_after>import en from '../i18n/dim_en.json';
import it from '../i18n/dim_it.json';
import de from '../i18n/dim_de.json';
import fr from '../i18n/dim_fr.json';
import es from '../i18n/dim_es.json';
import ja from '../i18n/dim_ja.json';
import ptBr from '../i18n/dim_pt_BR.json';

function config($compileProvider, $httpProvider, $translateProvider, $translateMessageFormatInterpolationProvider,
                hotkeysProvider, localStorageServiceProvider, ngHttpRateLimiterConfigProvider, ngDialogProvider) {
  'ngInject';

  // TODO: remove this depenency by fixing component bindings https://github.com/angular/angular.js/blob/master/CHANGELOG.md#breaking-changes-1
  $compileProvider.preAssignBindingsEnabled(true);
  // Allow chrome-extension: URLs in ng-src
  $compileProvider.imgSrcSanitizationWhitelist(/^\s*((https?|chrome-extension):|data:image\/)/);

  $httpProvider.interceptors.push('ngHttpRateLimiterInterceptor');
  $httpProvider.interceptors.push('http-refresh-token');
  $httpProvider.useApplyAsync(true);

  // See https://angular-translate.github.io/docs/#/guide
  $translateProvider.useSanitizeValueStrategy('escape');
  $translateProvider.useMessageFormatInterpolation();
  $translateProvider.preferredLanguage('en');

  $translateMessageFormatInterpolationProvider.messageFormatConfigurer(function(mf) {
    mf.setIntlSupport(true);
  });

  $translateProvider
    .translations('en', en)
    .translations('it', it)
    .translations('de', de)
    .translations('fr', fr)
    .translations('es', es)
    .translations('ja', ja)
    .translations('pt-br', ptBr)
    .fallbackLanguage('en');

  hotkeysProvider.includeCheatSheet = true;

  localStorageServiceProvider.setPrefix('');

  // Bungie's API will start throttling an API if it's called more than once per second. It does this
  // by making responses take 2s to return, not by sending an error code or throttling response. Choosing
  // our throttling limit to be 1 request every 1100ms lets us achieve best throughput while accounting for
  // what I assume is clock skew between Bungie's hosts when they calculate a global rate limit.
  ngHttpRateLimiterConfigProvider.addLimiter(/www\.bungie\.net\/Platform\/Destiny\/TransferItem/, 1, 1100);
  ngHttpRateLimiterConfigProvider.addLimiter(/www\.bungie\.net\/Platform\/Destiny\/EquipItem/, 1, 1100);
  ngHttpRateLimiterConfigProvider.addLimiter(/www\.bungie\.net\/D1\/Platform\/Destiny\/TransferItem/, 1, 1100);
  ngHttpRateLimiterConfigProvider.addLimiter(/www\.bungie\.net\/D1\/Platform\/Destiny\/EquipItem/, 1, 1100);

  // https://github.com/likeastore/ngDialog/issues/327
  ngDialogProvider.setDefaults({
    appendTo: '.app',
    disableAnimation: true,
    plain: true
  });
}

export default config;
<|endoftext|>


<commit_before>import moment from 'moment';

export default function isSameDay(a, b) {
  if (!moment.isMoment(a) || !moment.isMoment(b)) return false;
  return a.isSame(b, 'day');
}
<commit_msg>Speed up isSameDay<commit_after>import moment from 'moment';

export default function isSameDay(a, b) {
  if (!moment.isMoment(a) || !moment.isMoment(b)) return false;
  // Speeding up by comparing most likely to differ unit first
  return a.day() === b.day() &&
    a.month() === b.month() &&
    a.year() === b.year();
}
<|endoftext|>