<commit_before>var myFlashcards = [     {question:"for 101 just a threshold check",answer:"ultramercial, research corp"},
{question:"utility must be specific and substantial",answer:"fisher, harwood"},
{question:"101 can't be performed entirely in a human’s mind",answer:"CyberSource, Research Corp"},
{question:"application of abstract idea is patentable",answer:"ultramercial, gottschalk, parker and diamond2"},
{question:"101",answer:"mayo"},
{question:"for utility",answer:"langer, gaubert"},
{question:"mental processes not patentable and machine-transformation test not sole test",answer:"mayo, bilski"},
{question:"point of patents is to promote creation, nonnaturally occuring manufacture is patentable, isolated genes and information they encode not patentable",answer:"chakrabarty, hartranft, myriad"},
{question:"every issued patent presumed proper unless clear and convincing evidence to contrary",answer:"CLS"},
{question:"claims requiring programs to carry out functions are structural, not intended use",answer:"alappat, ultramercial"},
{question:"just add non-transitory to computer-readable medium to overcome 101",answer:"mewherter"},
{question:"Tests showing pharmacological activity may show a practical utility even though no specific therapeutic use.",answer:"nelson"},
{question:"tests evidencing pharmacological activity may manifest practical utility even tho no theraputic use because will marshall resources",answer:"cross, nelson"},
{question:"except process claims, eligible subject matter must exist in some physical or tangible form",answer:"burr, diamond, digitech"},
{question:"in § 101 analyses machine-or-transformation test provides a ‘useful clue’ in Alice framework 2nd step",answer:"ultramercial"},
{question:"claims squarely about creating a contractual relationship are an abstract idea",answer:"buysafe"},
{question:"claim rooted in computer tech to overcome problem specifically arising in networks not abstract idea",answer:"DDR Holdings"},
{question:"The machine-or-transformation test is not sole test for deciding if invention is patent-eligible process",answer:"bilski"},
{question:"claim elements individually or ordered combination transform nature of claim into patent-eligiblility",answer:"alice, mayo"},
{question:"new combination of steps in process may be patentable even though all constituents were well known",answer:"mayo, diamond1"},
{question:"If operation conflicts with science clear evidence req to overcome strong presumption of inoperativeness",answer:"chilowski"},
{question:"at some level, all inventions . . . embody, use, reflect, rest upon, or apply laws of nature, natural phenomena, or abstract ideas",answer:"alice, mayo, amdocs"},
{question:"chemical intermediates are patentable compositions of matter under 101 even if they are “transitory, unstable, and non-isolatable",answer:"breslow"},
{question:"computer implemented method must be more than just computer aided",answer:"cybersource, dealertrack"},
{question:"101",answer:"Dealertrack"},
{question:"recent S.Ct. 101 case",answer:"mayo"},
{question:"[L]aws of nature, natural phenomena, and abstract ideas' are not patentable",answer:"mayo"},
{question:"101",answer:"mayo, fort properties"},
{question:"101 computer readable medium non-statutory because could even be paper",answer:"shealy"},
{question:"self-evident thought is not patentable",answer:"Abrams"},
{question:"simply adding computer limitations to mental processes not enough",answer:"cybersource and dealertrack"},
{question:"to overcome 101 needs more than computer aided or computer implemented steps",answer:"dealertrack and cybersource"},
{question:"Justice Ginsberg for software not patentable",answer:"microsoft"},
{question:"claim directed to subjective mental process is nothing more than fundamental truth",answer:"CLS"},
{question:"S.Ct.s new 101 analysis",answer:"mayo"},
{question:"101",answer:"mayo, bancorp"},
{question:"abstract idea non-statutory",answer:"cybersource"},
{question:"mental process not patentable",answer:"comiskey"},
{question:"transmission media = wireless = signal unpatentable under 101",answer:"nuijten"},
{question:"tangible computer readable medium encompasses transitory signal",answer:"nuijten"},
{question:"MOT test machine must impose meaningful limit on scope of claim",answer:"SiRF"},
{question:"for mere data-gathering step can't make nonstatutory claim statutory",answer:"grams, myers"},
{question:"a claim is unpatentable if it encompasses unpatentable embodiment or reads on unpatentable subject matter",answer:"landgraf, muchmore"},
{question:"utility can't be meaningless",answer:"fisher"},
{question:"method that can be performed by human thought alone not patentable",answer:"cybersource, research corp, claussen"},
{question:"well-understood, routine activity not enough to turn abstract idea into patent-eligible concept",answer:"mayo collaborative, perkinelmer"},
{question:"machine or transformation test still useful",answer:"dealertrack"},
{question:"computer aided limitation to method claim not enough unless claim says how and extent computer is integrated and aids the method",answer:"dealertrack, cybersource"},
{question:"no matter what statuatory category look to underlying invention to determine patent-eligibility",answer:"cybersource"},
{question:"examples of claims not directed to 101 statutory category",answer:"nuijten, chakrabarty, ferguson, gottschalk, miller"},
{question:"patent eligiility under 101 reviewed de novo",answer:"bancorp"},
{question:"computer-readable storage medium that encomopasses transitory media uneligible under 101",answer:"mewherter"},
{question:"nothing in CLS except judgment has precedent swanson - in reexam burden of proof is preponderance of the evidence",answer:"CLS"},
{question:"programming a computer creates a new machine",answer:"ultramercial, alappat"},
{question:"claim has to be drawn to a specific computer readable medium, rather than to the underlying method",answer:"CyberSource, CLS, Dealertrack, Fort Properties"},
{question:"Patent eligibility under section 101 is an issue of law.",answer:"bancorp"},
{question:"Abstract software code is an idea without physical embodiment. http://t.co/QyYivpGBdu",answer:"microsoft"},
{question:"fundamental concepts, by themselves, are ineligible abstract ideas",answer:"alice"},
{question:"computing, monitoring, signaling, notifying do not confer patent eligibility to claims",answer:"bancorp"},
{question:"fundamental concepts, by themselves, are ineligible abstract ideas.",answer:"alice"},
{question:"A claim reciting an abstract idea does not become eligible merely by adding the words apply it.",answer:"bancorp"},
{question:"except process claims, all eligible subject matter categories must exist in some physical or tangible form",answer:"digitech"},
{question:"if abstract idea present in claim do limitations include significantly more when recited with abstract idea",answer:"alice"},
{question:"for 101 if claims directed to abstract idea, need more than simply add words 'apply it'",answer:"alice, mayo, ultramercial"},
{question:"invalid under 101 even though required a computer cpu memory terminal printer and video screen",answer:"planet bingo"},
{question:"The presence of a physical step in the claim to derive data for the algorithm will not render the claim statutory.",answer:"grams"},
{question:"The incorporation of algorithms and formulas does not prevent patent eligibility",answer:"research corp"},
{question:"is claim directed to patent-ineligible abstract idea, do elements of claim transform nature into patent-eligible application",answer:"alice, mayo"},
{question:"data in ethereal, non-physical form doesn't fall under any of the eligible subject matter categories under 101",answer:"digitech"},
{question:"To qualify as a manufacture, must be tangible article given new form, quality, property, or comb.",answer:"diamond, digitech"},
{question:"printed matter non-statutory under 101 but no reason to ignore when claim directed to a combination",answer:"russell, miller"},
{question:"simply appending general steps to abstract ideas performed by a computer not patent-eligible",answer:"alice, mayo"},
{question:"a statutory double patenting rejection under 35 U.S.C. § 101 cannot be cured by terminal disclaimer",answer:"vogel"},
{question:"because steps are mental processes, disembodied thoughts not subject to patenting",answer:"sarker"},
{question:"[a] machine is a concrete thing, consisting of parts, or of certain devices and combination of devices.",answer:"burr"},
{question:"recitation of generic computer elements doesn't make claim directed to abstract idea patent-eligible",answer:"DDR Holdings"},
{question:"if spec doesn't limit machine readable storage medium to exclude transitory media includes transitory",answer:"mewherter"},
{question:"utility in doubt if written desc suggests unbelievable undertaking or implausible scientific prin",answer:"cortright, brana"},
{question:"Using organizational and product group hierarchies to determine a price an abstract idea, no tangible form",answer:"versata"},
{question:"substantial evidence POSITA would 'reasonably doubt' asserted utility and operability of cold fusion",answer:"swartz"},
{question:"Appending purely conventional steps to an abstract idea (wagering game) not sufficiently inventive concept",answer:"smith2"},
{question:"humans have always performed the functions of data collection, recognition, and storage",answer:"content extraction"},
{question:"unpatentable under 101 where novelty adds little more than restatement of the natural law itself",answer:"genetic techs"},
{question:"preemption so patent ineligible, but absence of complete preemption doesn't demonstrate patent eligibility",answer:"ariosa"},
     ];
myFlashcards = document.getElementByClass("answer"), i, len = linkArray.length; for (i=0; i<len; i++){ myFlashcards.innerHTML += linkArray[i]; }
<commit_msg>Update questions101.js<commit_after>var myFlashcards = [     {question:"for 101 just a threshold check",answer:"ultramercial, research corp"},{question:"utility must be specific and substantial",answer:"fisher, harwood"},{question:"101 can't be performed entirely in a human’s mind",answer:"CyberSource, Research Corp"},{question:"application of abstract idea is patentable",answer:"ultramercial, gottschalk, parker and diamond2"},{question:"101",answer:"mayo"},{question:"for utility",answer:"langer, gaubert"},{question:"mental processes not patentable and machine-transformation test not sole test",answer:"mayo, bilski"},{question:"point of patents is to promote creation, nonnaturally occuring manufacture is patentable, isolated genes and information they encode not patentable",answer:"chakrabarty, hartranft, myriad"},{question:"every issued patent presumed proper unless clear and convincing evidence to contrary",answer:"CLS"},{question:"claims requiring programs to carry out functions are structural, not intended use",answer:"alappat, ultramercial"},{question:"just add non-transitory to computer-readable medium to overcome 101",answer:"mewherter"},{question:"Tests showing pharmacological activity may show a practical utility even though no specific therapeutic use.",answer:"nelson"},{question:"tests evidencing pharmacological activity may manifest practical utility even tho no theraputic use because will marshall resources",answer:"cross, nelson"},{question:"except process claims, eligible subject matter must exist in some physical or tangible form",answer:"burr, diamond, digitech"},{question:"in § 101 analyses machine-or-transformation test provides a ‘useful clue’ in Alice framework 2nd step",answer:"ultramercial"},{question:"claims squarely about creating a contractual relationship are an abstract idea",answer:"buysafe"},{question:"claim rooted in computer tech to overcome problem specifically arising in networks not abstract idea",answer:"DDR Holdings"},{question:"The machine-or-transformation test is not sole test for deciding if invention is patent-eligible process",answer:"bilski"},{question:"claim elements individually or ordered combination transform nature of claim into patent-eligiblility",answer:"alice, mayo"},{question:"new combination of steps in process may be patentable even though all constituents were well known",answer:"mayo, diamond1"},{question:"If operation conflicts with science clear evidence req to overcome strong presumption of inoperativeness",answer:"chilowski"},{question:"at some level, all inventions . . . embody, use, reflect, rest upon, or apply laws of nature, natural phenomena, or abstract ideas",answer:"alice, mayo, amdocs"},{question:"chemical intermediates are patentable compositions of matter under 101 even if they are “transitory, unstable, and non-isolatable",answer:"breslow"},{question:"computer implemented method must be more than just computer aided",answer:"cybersource, dealertrack"},{question:"101",answer:"Dealertrack"},{question:"recent S.Ct. 101 case",answer:"mayo"},{question:"[L]aws of nature, natural phenomena, and abstract ideas' are not patentable",answer:"mayo"},{question:"101",answer:"mayo, fort properties"},{question:"101 computer readable medium non-statutory because could even be paper",answer:"shealy"},{question:"self-evident thought is not patentable",answer:"Abrams"},{question:"simply adding computer limitations to mental processes not enough",answer:"cybersource and dealertrack"},{question:"to overcome 101 needs more than computer aided or computer implemented steps",answer:"dealertrack and cybersource"},{question:"Justice Ginsberg for software not patentable",answer:"microsoft"},{question:"claim directed to subjective mental process is nothing more than fundamental truth",answer:"CLS"},{question:"S.Ct.s new 101 analysis",answer:"mayo"},{question:"101",answer:"mayo, bancorp"},{question:"abstract idea non-statutory",answer:"cybersource"},{question:"mental process not patentable",answer:"comiskey"},{question:"transmission media = wireless = signal unpatentable under 101",answer:"nuijten"},{question:"tangible computer readable medium encompasses transitory signal",answer:"nuijten"},{question:"MOT test machine must impose meaningful limit on scope of claim",answer:"SiRF"},{question:"for mere data-gathering step can't make nonstatutory claim statutory",answer:"grams, myers"},{question:"a claim is unpatentable if it encompasses unpatentable embodiment or reads on unpatentable subject matter",answer:"landgraf, muchmore"},{question:"utility can't be meaningless",answer:"fisher"},{question:"method that can be performed by human thought alone not patentable",answer:"cybersource, research corp, claussen"},{question:"well-understood, routine activity not enough to turn abstract idea into patent-eligible concept",answer:"mayo collaborative, perkinelmer"},{question:"machine or transformation test still useful",answer:"dealertrack"},{question:"computer aided limitation to method claim not enough unless claim says how and extent computer is integrated and aids the method",answer:"dealertrack, cybersource"},{question:"no matter what statuatory category look to underlying invention to determine patent-eligibility",answer:"cybersource"},{question:"examples of claims not directed to 101 statutory category",answer:"nuijten, chakrabarty, ferguson, gottschalk, miller"},{question:"patent eligiility under 101 reviewed de novo",answer:"bancorp"},{question:"computer-readable storage medium that encomopasses transitory media uneligible under 101",answer:"mewherter"},{question:"nothing in CLS except judgment has precedent swanson - in reexam burden of proof is preponderance of the evidence",answer:"CLS"},{question:"programming a computer creates a new machine",answer:"ultramercial, alappat"},{question:"claim has to be drawn to a specific computer readable medium, rather than to the underlying method",answer:"CyberSource, CLS, Dealertrack, Fort Properties"},{question:"Patent eligibility under section 101 is an issue of law.",answer:"bancorp"},{question:"Abstract software code is an idea without physical embodiment. http://t.co/QyYivpGBdu",answer:"microsoft"},{question:"fundamental concepts, by themselves, are ineligible abstract ideas",answer:"alice"},{question:"computing, monitoring, signaling, notifying do not confer patent eligibility to claims",answer:"bancorp"},{question:"fundamental concepts, by themselves, are ineligible abstract ideas.",answer:"alice"},{question:"A claim reciting an abstract idea does not become eligible merely by adding the words apply it.",answer:"bancorp"},{question:"except process claims, all eligible subject matter categories must exist in some physical or tangible form",answer:"digitech"},{question:"if abstract idea present in claim do limitations include significantly more when recited with abstract idea",answer:"alice"},{question:"for 101 if claims directed to abstract idea, need more than simply add words 'apply it'",answer:"alice, mayo, ultramercial"},{question:"invalid under 101 even though required a computer cpu memory terminal printer and video screen",answer:"planet bingo"},{question:"The presence of a physical step in the claim to derive data for the algorithm will not render the claim statutory.",answer:"grams"},{question:"The incorporation of algorithms and formulas does not prevent patent eligibility",answer:"research corp"},{question:"is claim directed to patent-ineligible abstract idea, do elements of claim transform nature into patent-eligible application",answer:"alice, mayo"},{question:"data in ethereal, non-physical form doesn't fall under any of the eligible subject matter categories under 101",answer:"digitech"},{question:"To qualify as a manufacture, must be tangible article given new form, quality, property, or comb.",answer:"diamond, digitech"},{question:"printed matter non-statutory under 101 but no reason to ignore when claim directed to a combination",answer:"russell, miller"},{question:"simply appending general steps to abstract ideas performed by a computer not patent-eligible",answer:"alice, mayo"},{question:"a statutory double patenting rejection under 35 U.S.C. § 101 cannot be cured by terminal disclaimer",answer:"vogel"},{question:"because steps are mental processes, disembodied thoughts not subject to patenting",answer:"sarker"},{question:"[a] machine is a concrete thing, consisting of parts, or of certain devices and combination of devices.",answer:"burr"},{question:"recitation of generic computer elements doesn't make claim directed to abstract idea patent-eligible",answer:"DDR Holdings"},{question:"if spec doesn't limit machine readable storage medium to exclude transitory media includes transitory",answer:"mewherter"},{question:"utility in doubt if written desc suggests unbelievable undertaking or implausible scientific prin",answer:"cortright, brana"},{question:"Using organizational and product group hierarchies to determine a price an abstract idea, no tangible form",answer:"versata"},{question:"substantial evidence POSITA would 'reasonably doubt' asserted utility and operability of cold fusion",answer:"swartz"},{question:"Appending purely conventional steps to an abstract idea (wagering game) not sufficiently inventive concept",answer:"smith2"},{question:"humans have always performed the functions of data collection, recognition, and storage",answer:"content extraction"},{question:"unpatentable under 101 where novelty adds little more than restatement of the natural law itself",answer:"genetic techs"},{question:"preemption so patent ineligible, but absence of complete preemption doesn't demonstrate patent eligibility",answer:"ariosa"},
     ];
myFlashcards = document.getElementByClass("answer"), i, len = linkArray.length; for (i=0; i<len; i++){ myFlashcards.innerHTML += linkArray[i]; }
<|endoftext|>


<commit_before>var application = require("application");
var utils = require("utils/utils");
var LocalNotifications = require("./local-notifications-common");

LocalNotifications.addOnMessageReceivedCallback = function (callback) {
  return new Promise(function (resolve, reject) {
    try {
      // note that this is ONLY triggered when the user clicked the notification in the statusbar
      com.telerik.localnotifications.LocalNotificationsPlugin.setOnMessageReceivedCallback(
          new com.telerik.localnotifications.LocalNotificationsPluginListener({
            success: callback
          })
      );
      resolve();
    } catch (ex) {
      console.log("Error in LocalNotifications.addOnMessageReceivedCallback: " + ex);
      reject(ex);
    }
  });
};

LocalNotifications.schedule = function (arg) {
  return new Promise(function (resolve, reject) {
    try {
      var context = application.android.foregroundActivity;

      for (var n in arg) {
        var options = LocalNotifications.merge(arg[n], LocalNotifications.defaults);
        options.icon = application.android.nativeApp.getApplicationInfo().icon;
        options.atTime = options.at ? options.at.getTime() : new Date().getTime();

        // note that setting options.sound to explicitly to null will not add the default sound
        if (options.sound === undefined) {
          options.sound = android.media.RingtoneManager.getDefaultUri(android.media.RingtoneManager.TYPE_NOTIFICATION).toString();
        }

        // TODO best move this to native lib so we can reuse it in the restorereceiver (dupl for now)
        var builder = new android.support.v4.app.NotificationCompat.Builder(context)
            .setDefaults(0)
            .setContentTitle(options.title)
            .setContentText(options.body)
            .setSmallIcon(options.icon)
            .setAutoCancel(true) // removes the notification from the statusbar once tapped
            .setSound(options.sound == null ? null : android.net.Uri.parse(options.sound))
            .setNumber(options.badge)
            .setTicker(options.ticker || options.body);

        // add the intent that handles the event when the notification is clicked (which should launch the app)
        var reqCode = new java.util.Random().nextInt();
        var clickIntent = new android.content.Intent(context, com.telerik.localnotifications.NotificationClickedActivity.class)
            .putExtra("pushBundle", JSON.stringify(options))
            .setFlags(android.content.Intent.FLAG_ACTIVITY_NO_HISTORY);

        var pendingContentIntent = android.app.PendingIntent.getActivity(context, reqCode, clickIntent, android.app.PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pendingContentIntent);

        // NOTE this expanded mode works and is pretty awesome.. add properties one day
        /*
         var inboxStyle = new android.support.v4.app.NotificationCompat.InboxStyle();
         var events = ["a", "b", "c"];
         // Sets a title for the Inbox in expanded layout
         inboxStyle.setBigContentTitle("Event tracker details:");
         for (var i=0; i < events.length; i++) {
         inboxStyle.addLine(events[i]);
         }
         builder.setStyle(inboxStyle);
         */

        var not = builder.build();

        // add the intent which schedules the notification
        var notificationIntent = new android.content.Intent(context, com.telerik.localnotifications.NotificationPublisher.class)
            .setAction("" + options.id)
            .putExtra(com.telerik.localnotifications.NotificationPublisher.NOTIFICATION_ID, options.id)
            .putExtra(com.telerik.localnotifications.NotificationPublisher.NOTIFICATION, not);

        var pendingIntent = android.app.PendingIntent.getBroadcast(context, 0, notificationIntent, android.app.PendingIntent.FLAG_CANCEL_CURRENT);

        // configure when we'll show the event
        var alarmManager = utils.ad.getApplicationContext().getSystemService(android.content.Context.ALARM_SERVICE);
        alarmManager.set(android.app.AlarmManager.RTC_WAKEUP, options.atTime, pendingIntent);

        LocalNotifications._persist(options);
      }

      resolve();
    } catch (ex) {
      console.log("Error in LocalNotifications.schedule: " + ex);
      reject(ex);
    }
  });
};

/**
 * Persist notification info to the Android Shared Preferences.
 * This way we can later retrieve it to cancel it, or restore upon reboot.
 */
LocalNotifications._persist = function (options) {
  var sharedPreferences = LocalNotifications._getSharedPreferences();
  var sharedPreferencesEditor = sharedPreferences.edit();
  sharedPreferencesEditor.putString("" + options.id, JSON.stringify(options));
  sharedPreferencesEditor.apply();
};

LocalNotifications._unpersist = function (id) {
  var sharedPreferences = LocalNotifications._getSharedPreferences();
  var sharedPreferencesEditor = sharedPreferences.edit();
  sharedPreferencesEditor.remove("" + id);
  sharedPreferencesEditor.apply();
};

LocalNotifications._cancelById = function (id) {
  var context = application.android.foregroundActivity;

  var notificationIntent = new android.content.Intent(context, com.telerik.localnotifications.NotificationPublisher.class)
      .setAction("" + id);

  var pendingIntent = android.app.PendingIntent.getBroadcast(context, 0, notificationIntent, 0);

  var alarmManager = utils.ad.getApplicationContext().getSystemService(android.content.Context.ALARM_SERVICE);
  alarmManager.cancel(pendingIntent);

  var notificationManager = utils.ad.getApplicationContext().getSystemService(android.content.Context.NOTIFICATION_SERVICE);
  notificationManager.cancel(id);

  LocalNotifications._unpersist(id);
};

LocalNotifications.cancel = function (id) {
  return new Promise(function (resolve, reject) {
    try {
      LocalNotifications._cancelById(id);
      resolve(true);
    } catch (ex) {
      console.log("Error in LocalNotifications.cancel: " + ex);
      reject(ex);
    }
  });
};

LocalNotifications.cancelAll = function () {
  return new Promise(function (resolve, reject) {
    try {
      var sharedPreferences = LocalNotifications._getSharedPreferences();
      var keys = sharedPreferences.getAll().keySet();

      console.log("-----will cancel " + keys.size() + " notification(s): " + keys);

      var iterator = keys.iterator();
      while (iterator.hasNext()) {
        LocalNotifications._cancelById(iterator.next());
      }

      resolve();
    } catch (ex) {
      console.log("Error in LocalNotifications.cancelAll: " + ex);
      reject(ex);
    }
  });
};

LocalNotifications.getScheduledIds = function () {
  return new Promise(function (resolve, reject) {
    try {
      var scheduledIds = [];

      var sharedPreferences = LocalNotifications._getSharedPreferences();
      var keys = sharedPreferences.getAll().keySet();

      var iterator = keys.iterator();
      while (iterator.hasNext()) {
        scheduledIds.push(iterator.next());
      }

      resolve(scheduledIds);
    } catch (ex) {
      console.log("Error in LocalNotifications.getScheduledIds: " + ex);
      reject(ex);
    }
  });
};

LocalNotifications._getSharedPreferences = function () {
  var context = application.android.foregroundActivity;
  var PREF_KEY = "LocalNotificationsPlugin"; // TODO get constant from native, as the restorereceiver needs it as well
  return context.getSharedPreferences(PREF_KEY, android.content.Context.MODE_PRIVATE);
};

module.exports = LocalNotifications;

/*
 module.exports = (function () {
 var app = require('application');
 var context = app.android.context;

 (function() {
 //debugger;
 // Hook on the application events
 com.telerik.pushplugin.PushLifecycleCallbacks.registerCallbacks(app.android.nativeApp);
 })();

 var pluginObject = {
 register: function (options, successCallback, errorCallback) {
 com.telerik.pushplugin.PushPlugin.register(context, options.senderID,
 //Success
 new com.telerik.pushplugin.PushPluginListener(
 {
 success: successCallback,
 error: errorCallback
 })
 );
 },
 unregister: function (onSuccessCallback, onErrorCallback, options) {
 com.telerik.pushplugin.PushPlugin.unregister(context, options.senderID, new com.telerik.pushplugin.PushPluginListener(
 {
 success: onSuccessCallback
 }
 ));
 },
 onMessageReceived: function (callback) {
 com.telerik.pushplugin.PushPlugin.setOnMessageReceivedCallback(
 new com.telerik.pushplugin.PushPluginListener(
 {
 success: callback
 })
 );
 },
 onTokenRefresh : function (callback) {
 com.telerik.pushplugin.PushPlugin.setOnTokenRefreshCallback(
 new com.telerik.pushplugin.PushPluginListener(
 {
 success: callback
 })
 );
 },
 areNotificationsEnabled : function (callback) {
 var bool = com.telerik.pushplugin.PushPlugin.areNotificationsEnabled();
 callback(bool);
 }
 };
 return pluginObject;
 })();
 */<commit_msg>- Added empty impls for Android permission stuff (not needed on this platform) - Cleanup<commit_after>var application = require("application");
var utils = require("utils/utils");
var LocalNotifications = require("./local-notifications-common");

LocalNotifications.addOnMessageReceivedCallback = function (callback) {
  return new Promise(function (resolve, reject) {
    try {
      // note that this is ONLY triggered when the user clicked the notification in the statusbar
      com.telerik.localnotifications.LocalNotificationsPlugin.setOnMessageReceivedCallback(
          new com.telerik.localnotifications.LocalNotificationsPluginListener({
            success: callback
          })
      );
      resolve();
    } catch (ex) {
      console.log("Error in LocalNotifications.addOnMessageReceivedCallback: " + ex);
      reject(ex);
    }
  });
};

LocalNotifications.schedule = function (arg) {
  return new Promise(function (resolve, reject) {
    try {
      var context = application.android.foregroundActivity;

      for (var n in arg) {
        var options = LocalNotifications.merge(arg[n], LocalNotifications.defaults);
        options.icon = application.android.nativeApp.getApplicationInfo().icon;
        options.atTime = options.at ? options.at.getTime() : new Date().getTime();

        // note that setting options.sound to explicitly to null will not add the default sound
        if (options.sound === undefined) {
          options.sound = android.media.RingtoneManager.getDefaultUri(android.media.RingtoneManager.TYPE_NOTIFICATION).toString();
        }

        // TODO best move this to native lib so we can reuse it in the restorereceiver (dupl for now)
        var builder = new android.support.v4.app.NotificationCompat.Builder(context)
            .setDefaults(0)
            .setContentTitle(options.title)
            .setContentText(options.body)
            .setSmallIcon(options.icon)
            .setAutoCancel(true) // removes the notification from the statusbar once tapped
            .setSound(options.sound == null ? null : android.net.Uri.parse(options.sound))
            .setNumber(options.badge)
            .setTicker(options.ticker || options.body);

        // add the intent that handles the event when the notification is clicked (which should launch the app)
        var reqCode = new java.util.Random().nextInt();
        var clickIntent = new android.content.Intent(context, com.telerik.localnotifications.NotificationClickedActivity.class)
            .putExtra("pushBundle", JSON.stringify(options))
            .setFlags(android.content.Intent.FLAG_ACTIVITY_NO_HISTORY);

        var pendingContentIntent = android.app.PendingIntent.getActivity(context, reqCode, clickIntent, android.app.PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pendingContentIntent);

        // NOTE this expanded mode works and is pretty awesome.. add properties one day
        /*
         var inboxStyle = new android.support.v4.app.NotificationCompat.InboxStyle();
         var events = ["a", "b", "c"];
         // Sets a title for the Inbox in expanded layout
         inboxStyle.setBigContentTitle("Event tracker details:");
         for (var i=0; i < events.length; i++) {
         inboxStyle.addLine(events[i]);
         }
         builder.setStyle(inboxStyle);
         */

        var not = builder.build();

        // add the intent which schedules the notification
        var notificationIntent = new android.content.Intent(context, com.telerik.localnotifications.NotificationPublisher.class)
            .setAction("" + options.id)
            .putExtra(com.telerik.localnotifications.NotificationPublisher.NOTIFICATION_ID, options.id)
            .putExtra(com.telerik.localnotifications.NotificationPublisher.NOTIFICATION, not);

        var pendingIntent = android.app.PendingIntent.getBroadcast(context, 0, notificationIntent, android.app.PendingIntent.FLAG_CANCEL_CURRENT);

        // configure when we'll show the event
        var alarmManager = utils.ad.getApplicationContext().getSystemService(android.content.Context.ALARM_SERVICE);
        alarmManager.set(android.app.AlarmManager.RTC_WAKEUP, options.atTime, pendingIntent);

        LocalNotifications._persist(options);
      }

      resolve();
    } catch (ex) {
      console.log("Error in LocalNotifications.schedule: " + ex);
      reject(ex);
    }
  });
};

/**
 * Persist notification info to the Android Shared Preferences.
 * This way we can later retrieve it to cancel it, or restore upon reboot.
 */
LocalNotifications._persist = function (options) {
  var sharedPreferences = LocalNotifications._getSharedPreferences();
  var sharedPreferencesEditor = sharedPreferences.edit();
  sharedPreferencesEditor.putString("" + options.id, JSON.stringify(options));
  sharedPreferencesEditor.apply();
};

LocalNotifications._unpersist = function (id) {
  var sharedPreferences = LocalNotifications._getSharedPreferences();
  var sharedPreferencesEditor = sharedPreferences.edit();
  sharedPreferencesEditor.remove("" + id);
  sharedPreferencesEditor.apply();
};

LocalNotifications._cancelById = function (id) {
  var context = application.android.foregroundActivity;

  var notificationIntent = new android.content.Intent(context, com.telerik.localnotifications.NotificationPublisher.class)
      .setAction("" + id);

  var pendingIntent = android.app.PendingIntent.getBroadcast(context, 0, notificationIntent, 0);

  var alarmManager = utils.ad.getApplicationContext().getSystemService(android.content.Context.ALARM_SERVICE);
  alarmManager.cancel(pendingIntent);

  var notificationManager = utils.ad.getApplicationContext().getSystemService(android.content.Context.NOTIFICATION_SERVICE);
  notificationManager.cancel(id);

  LocalNotifications._unpersist(id);
};

LocalNotifications.cancel = function (id) {
  return new Promise(function (resolve, reject) {
    try {
      LocalNotifications._cancelById(id);
      resolve(true);
    } catch (ex) {
      console.log("Error in LocalNotifications.cancel: " + ex);
      reject(ex);
    }
  });
};

LocalNotifications.cancelAll = function () {
  return new Promise(function (resolve, reject) {
    try {
      var sharedPreferences = LocalNotifications._getSharedPreferences();
      var keys = sharedPreferences.getAll().keySet();

      console.log("-----will cancel " + keys.size() + " notification(s): " + keys);

      var iterator = keys.iterator();
      while (iterator.hasNext()) {
        LocalNotifications._cancelById(iterator.next());
      }

      resolve();
    } catch (ex) {
      console.log("Error in LocalNotifications.cancelAll: " + ex);
      reject(ex);
    }
  });
};

LocalNotifications.getScheduledIds = function () {
  return new Promise(function (resolve, reject) {
    try {
      var scheduledIds = [];

      var sharedPreferences = LocalNotifications._getSharedPreferences();
      var keys = sharedPreferences.getAll().keySet();

      var iterator = keys.iterator();
      while (iterator.hasNext()) {
        scheduledIds.push(iterator.next());
      }

      resolve(scheduledIds);
    } catch (ex) {
      console.log("Error in LocalNotifications.getScheduledIds: " + ex);
      reject(ex);
    }
  });
};

LocalNotifications.hasPermission = function (arg) {
  return new Promise(function (resolve, reject) {
    try {
      // nothing to do on this platform
      resolve(true);
    } catch (ex) {
      console.log("Error in LocalNotifications.hasPermission: " + ex);
      reject(ex);
    }
  });
};

LocalNotifications.requestPermission = function (arg) {
  return new Promise(function (resolve, reject) {
    try {
      // nothing to do on this platform
      resolve(true);
    } catch (ex) {
      console.log("Error in LocalNotifications.requestPermission: " + ex);
      reject(ex);
    }
  });
};

LocalNotifications._getSharedPreferences = function () {
  var context = application.android.foregroundActivity;
  var PREF_KEY = "LocalNotificationsPlugin"; // TODO get constant from native, as the restorereceiver needs it as well
  return context.getSharedPreferences(PREF_KEY, android.content.Context.MODE_PRIVATE);
};

module.exports = LocalNotifications;<|endoftext|>


<commit_before>import React from "react";

import { text } from "@storybook/addon-knobs/react";
import { Button } from "hig-react";
import { translate as t } from "@hig/storybook/utils";

import Banner from "../Banner";
import * as languages from "./i18n";

/**
 * @typedef {Object} BannerStory
 * @property {string} description
 * @property {function({ language: string; }): JSX.Element} getProps
 */

/** @type {BannerStory[]} */
export default [
  {
    description: "default",
    getProps: () => ({})
  },
  {
    description: "verbose, with interactions",
    getProps: ({ language }) => ({
      type: Banner.types.WARNING,
      children:
        // eslint-disable-next-line max-len
        "PROCESS COMPLETE: Changes have been made to you document. Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam.",
      // eslint-disable-next-line react/prop-types
      actions: ({ isWrappingActions }) => (
        <Banner.Interactions isWrappingActions={isWrappingActions}>
          <Banner.Action>
            <Button
              type="secondary"
              size="small"
              width={isWrappingActions ? "grow" : "shrink"}
              title={text(
                "Resolve text",
                t(languages, language, "BANNER_RESOLVE_BUTTON_TEXT")
              )}
            />
          </Banner.Action>
          <Banner.Action>
            <Button
              type="secondary"
              size="small"
              width={isWrappingActions ? "grow" : "shrink"}
              title={text(
                "Reject text",
                t(languages, language, "BANNER_REJECT_BUTTON_TEXT")
              )}
            />
          </Banner.Action>
        </Banner.Interactions>
      )
    })
  }
];
<commit_msg>chore(banner): Fix language knob on banner stories<commit_after>import React from "react";

import { text } from "@storybook/addon-knobs/react";
import { Button } from "hig-react";
import { translate as t } from "@hig/storybook/utils";

import Banner from "../Banner";
import * as languages from "./i18n";

/**
 * @param {string} language
 * @returns {string} The message pulled from translations
 */
export function getMessage(language) {
  return text("Message", t(languages, language, "BANNER_MESSAGE"));
}

/**
 * @typedef {Object} BannerStory
 * @property {string} description
 * @property {function({ language: string; }): JSX.Element} getProps
 */

/** @type {BannerStory[]} */
export default [
  {
    description: "default",
    getProps: ({ language }) => ({
      children: getMessage(language)
    })
  },
  {
    description: "verbose, with interactions",
    getProps: ({ language }) => ({
      type: Banner.types.WARNING,
      children: getMessage(language),
      // eslint-disable-next-line react/prop-types
      actions: ({ isWrappingActions }) => (
        <Banner.Interactions isWrappingActions={isWrappingActions}>
          <Banner.Action>
            <Button
              type="secondary"
              size="small"
              width={isWrappingActions ? "grow" : "shrink"}
              title={text(
                "Resolve text",
                t(languages, language, "BANNER_RESOLVE_BUTTON_TEXT")
              )}
            />
          </Banner.Action>
          <Banner.Action>
            <Button
              type="secondary"
              size="small"
              width={isWrappingActions ? "grow" : "shrink"}
              title={text(
                "Reject text",
                t(languages, language, "BANNER_REJECT_BUTTON_TEXT")
              )}
            />
          </Banner.Action>
        </Banner.Interactions>
      )
    })
  }
];
<|endoftext|>


<commit_before>/**
 * Returns whether both dates are for the same day
 *
 * @param {Date} date
 * @param {Date} otherDate
 * @returns {boolean}
 */
export function isSameDay (date, otherDate)
{
    if (!(date instanceof Date))
    {
        return false;
    }

    if (!(otherDate instanceof Date))
    {
        return false;
    }

    return 0 === compareDate(date, otherDate);
}

/**
 * Returns whether both dates are for the same day and the same hour
 *
 * @param {Date} date
 * @param {Date} otherDate
 * @returns {boolean}
 */
export function isSameTimestamp (date, otherDate)
{
    return 0 === compareTimestamp(date, otherDate);
}

/**
 * Checks whether the `date` is before the `otherDate`
 *
 * @param {Date} date
 * @param {Date} otherDate
 * @returns {boolean}
 */
export function isBeforeDate (date, otherDate)
{
    return -1 === compareDate(date, otherDate);
}

/**
 * Returns
 *      -1 if the `date` is before the `other date`,
 *       0 if the dates are equal and
 *      +1 if the `date` is after the `other date`.
 *
 * Only checks the date and ignores the time
 *
 * @param {Date} date
 * @param {Date} otherDate
 * @return {number}
 */
export function compareDate (date, otherDate)
{
    const compareYear = compare(date.getFullYear(), otherDate.getFullYear());

    if (0 !== compareYear)
    {
        return compareYear;
    }

    const compareMonth = compare(date.getMonth(), otherDate.getMonth());

    if (0 !== compareMonth)
    {
        return compareMonth;
    }

    return compare(date.getDate(), otherDate.getDate());
}

/**
 * Returns
 *      -1 if the `date` is before the `other date`,
 *       0 if the dates are equal and
 *      +1 if the `date` is after the `other date`.
 *
 * Includes time checks.
 *
 * @param {Date} date
 * @param {Date} otherDate
 * @return {number}
 */
export function compareTimestamp (date, otherDate)
{
    const compareDate = compareDate(date, otherDate);

    if (0 !== compareDate)
    {
        return compareDate;
    }

    const compareHour = compare(date.getHours(), otherDate.getHours());

    if (0 !== compareHour)
    {
        return compareHour;
    }

    const compareMinute = compare(date.getMinutes(), otherDate.getMinutes());

    if (0 !== compareMinute)
    {
        return compareMinute;
    }

    return compare(date.getSeconds(), otherDate.getSeconds());
}

/**
 * Compares two numbers
 *
 * @param {number} value
 * @param {number} otherValue
 * @return {number}
 */
function compare (value, otherValue)
{
    if (value === otherValue)
    {
        return 0;
    }

    return (value < otherValue) ? -1 : 1;
}
<commit_msg>Fix issue with duplicate variable name<commit_after>/**
 * Returns whether both dates are for the same day
 *
 * @param {Date} date
 * @param {Date} otherDate
 * @returns {boolean}
 */
export function isSameDay (date, otherDate)
{
    if (!(date instanceof Date))
    {
        return false;
    }

    if (!(otherDate instanceof Date))
    {
        return false;
    }

    return 0 === compareDate(date, otherDate);
}

/**
 * Returns whether both dates are for the same day and the same hour
 *
 * @param {Date} date
 * @param {Date} otherDate
 * @returns {boolean}
 */
export function isSameTimestamp (date, otherDate)
{
    return 0 === compareTimestamp(date, otherDate);
}

/**
 * Checks whether the `date` is before the `otherDate`
 *
 * @param {Date} date
 * @param {Date} otherDate
 * @returns {boolean}
 */
export function isBeforeDate (date, otherDate)
{
    return -1 === compareDate(date, otherDate);
}

/**
 * Returns
 *      -1 if the `date` is before the `other date`,
 *       0 if the dates are equal and
 *      +1 if the `date` is after the `other date`.
 *
 * Only checks the date and ignores the time
 *
 * @param {Date} date
 * @param {Date} otherDate
 * @return {number}
 */
export function compareDate (date, otherDate)
{
    const compareYear = compare(date.getFullYear(), otherDate.getFullYear());

    if (0 !== compareYear)
    {
        return compareYear;
    }

    const compareMonth = compare(date.getMonth(), otherDate.getMonth());

    if (0 !== compareMonth)
    {
        return compareMonth;
    }

    return compare(date.getDate(), otherDate.getDate());
}

/**
 * Returns
 *      -1 if the `date` is before the `other date`,
 *       0 if the dates are equal and
 *      +1 if the `date` is after the `other date`.
 *
 * Includes time checks.
 *
 * @param {Date} date
 * @param {Date} otherDate
 * @return {number}
 */
export function compareTimestamp (date, otherDate)
{
    const compareDateResult = compareDate(date, otherDate);

    if (0 !== compareDateResult)
    {
        return compareDateResult;
    }

    const compareHour = compare(date.getHours(), otherDate.getHours());

    if (0 !== compareHour)
    {
        return compareHour;
    }

    const compareMinute = compare(date.getMinutes(), otherDate.getMinutes());

    if (0 !== compareMinute)
    {
        return compareMinute;
    }

    return compare(date.getSeconds(), otherDate.getSeconds());
}

/**
 * Compares two numbers
 *
 * @param {number} value
 * @param {number} otherValue
 * @return {number}
 */
function compare (value, otherValue)
{
    if (value === otherValue)
    {
        return 0;
    }

    return (value < otherValue) ? -1 : 1;
}
<|endoftext|>


<commit_before>"use strict";

const Cu = Components.utils;
const Cc = Components.classes;
const Ci = Components.interfaces;

Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource://gre/modules/NetUtil.jsm");

function dumpln(s) { dump(s + "\n"); }

/*****************
 * API INJECTION *
 *****************/

// Based on:
// https://bug549539.bugzilla.mozilla.org/attachment.cgi?id=429661
// https://developer.mozilla.org/en/XPCOM/XPCOM_changes_in_Gecko_1.9.3
// http://mxr.mozilla.org/mozilla-central/source/toolkit/components/console/hudservice/HUDService.jsm#3240
// https://developer.mozilla.org/en/how_to_build_an_xpcom_component_in_javascript

function DOMFuzzHelper() {}

// Use runSoon to avoid false-positive leaks due to content JS on the stack (?)
function quitFromContent() { dumpln("Page called quitApplication."); runSoon(goQuitApplication); }
function quitApplicationSoon() { dumpln("Page called quitApplicationSoon."); runOnTimer(goQuitApplication); }

DOMFuzzHelper.prototype = {
  classDescription: "DOM fuzz helper",
  classID:          Components.ID("{59a52458-13e0-4d90-9d85-a637344f29a1}"),
  contractID:       "@squarefree.com/dom-fuzz-helper;1",

  QueryInterface:   XPCOMUtils.generateQI([Ci.nsIDOMGlobalPropertyInitializer]),

  init: function(aWindow)
  {
    // Using bind(this) to ensure web page gets a *copy* of the function (is this necessary?)

    var api = {
      quitApplication:     quitFromContent.bind(this),
      quitApplicationSoon: quitApplicationSoon.bind(this),
      closeTabThenQuit:    closeTabThenQuit(aWindow),
      quitWithLeakCheck:   quitWithLeakCheck.bind(this),
      setGCZeal:           setGCZeal.bind(this),
      runSoon:             runSoon.bind(this),
      enableAccessibility: enableAccessibility.bind(this),
      GC:                  function() { Components.utils.forceGC(); },
      MP:                  sendMemoryPressureNotification.bind(this),
      CC:                  cycleCollect(aWindow),
      fontList:            fontList.bind(this),
      // zoom:             setZoomLevel(aWindow), // bug 576927
      printToFile:         printToFile(aWindow),
      openAboutMemory:     openNewTab.bind(this, aWindow, "about:memory"),

      __exposedProps__: {
        quitApplication: "r",
        quitApplicationSoon: "r",
        closeTabThenQuit: "r",
        quitWithLeakCheck: "r",
        setGCZeal: "r",
        runSoon: "r",
        enableAccessibility: "r",
        GC: "r",
        MP: "r",
        CC: "r",
        fontList: "r",
        // zoom: "r",
        printToFile: "r",
        openAboutMemory: "r",
      }
    };

    return api;
  }
};

const NSGetFactory = XPCOMUtils.generateNSGetFactory([DOMFuzzHelper]);

/*****************************
 * MISC PRIVILEGED FUNCTIONS *
 *****************************/

function openNewTab(w, url)
{
  w.open(url);
}

function closeTabThenQuit(w)
{
  return function() {
    runOnTimer(goQuitApplication);
    w.close();
  }
}

function fontList()
{
  return Components.classes["@mozilla.org/gfx/fontenumerator;1"]
          .createInstance(Components.interfaces.nsIFontEnumerator)
          .EnumerateAllFonts({})
          .join("\n");
}

function runSoon(f)
{
  var tm = Components.classes["@mozilla.org/thread-manager;1"]
             .getService(Components.interfaces.nsIThreadManager);

  tm.mainThread.dispatch({
    run: function() {
      f();
    }
  }, Components.interfaces.nsIThread.DISPATCH_NORMAL);
}

function enableAccessibility()
{
  try {
    Components.classes["@mozilla.org/accessibilityService;1"]
      .getService(Components.interfaces.nsIAccessibleRetrieval);
    dump("Enabled accessibility!\n");
  } catch(e) {
    dump("Couldn't enable accessibility: " + e + "\n");
  }
}

function sendMemoryPressureNotification()
{
  var os = Components.classes["@mozilla.org/observer-service;1"]
           .getService(Components.interfaces.nsIObserverService);
  os.notifyObservers(null, "memory-pressure", "heap-minimize");
}

function cycleCollect(window)
{
  return function cycleCollectInner() {
    window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
          .getInterface(Components.interfaces.nsIDOMWindowUtils)
          .cycleCollect();
  }
}

function setZoomLevel(window)
{
  return function setZoomLevelInner(textOrFull, factor) {
    var viewer = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                       .getInterface(Components.interfaces.nsIWebNavigation)
                       .QueryInterface(Components.interfaces.nsIDocShell)
                       .contentViewer
                       .QueryInterface(Components.interfaces.nsIMarkupDocumentViewer);

    if (textOrFull == "text")
      viewer.textZoom = +factor;
    else if (textOrFull == "full")
      viewer.fullZoom = +factor;
  }
}

function printToFile(window)
{
  // Oddly asynchronous, at least on Linux.

  // Linux: works for PDF and PS.
  // Windows: works for PDF at least. Text may be invisible (bug 653336).
  // Mac: tested, printToFile is ignored and it goes to a printer! (bug 675709)
  var xulRuntime = Components.classes["@mozilla.org/xre/app-info;1"]
                             .getService(Components.interfaces.nsIXULRuntime);
  dumpln("xulRuntime.OS: " + xulRuntime.OS);
  if (xulRuntime.OS != "Linux" && xulRuntime.OS != "WINNT") return function() { };

  var fired = false;

  return function printToFileInner(showHeaders, showBGColor, showBGImages, ps) {
    runSoon(function() {
        // Don't print more than once, it gets messy fast.
        if (fired) { return false; }
        fired = true;

        // Based on https://addons.mozilla.org/en-US/firefox/addon/5971/ by pavlov (Stuart Parmenter) and bho

        var webBrowserPrint = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
        .getInterface(Components.interfaces.nsIWebBrowserPrint);

        var nsIPrintSettings = Components.interfaces.nsIPrintSettings;

        var PSSVC = Components.classes["@mozilla.org/gfx/printsettings-service;1"]
        .getService(Components.interfaces.nsIPrintSettingsService);

        var printSettings = PSSVC.newPrintSettings;

        var file = Components.classes["@mozilla.org/file/directory_service;1"].
                              getService(Components.interfaces.nsIProperties).
                              get("ProfD", Components.interfaces.nsIFile);
        file.append(ps ? "fuzzout.ps" : "fuzzout.pdf");
        dumpln("Printing to: " + file.path);

        printSettings.printToFile = true;
        printSettings.toFileName  = file.path;
        printSettings.printSilent = true;
        printSettings.outputFormat = ps ? nsIPrintSettings.kOutputFormatPS : nsIPrintSettings.kOutputFormatPDF;
        printSettings.printBGColors   = !!showBGColor;
        printSettings.printBGImages   = !!showBGImages;
        if (!showHeaders) {
            printSettings.footerStrCenter = '';
            printSettings.footerStrLeft   = '';
            printSettings.footerStrRight  = '';
            printSettings.headerStrCenter = '';
            printSettings.headerStrLeft   = '';
            printSettings.headerStrRight  = '';
        }

        webBrowserPrint.print(printSettings, null);
    });
  }
}

function setGCZeal(zeal)
{
  if (typeof(zeal) == "number") {
    Services.prefs.setIntPref("javascript.options.gczeal", zeal)
  }
}

/************************
 * QUIT WITH LEAK CHECK *
 ************************/

var quitting = false;

function quitWithLeakCheck(leaveWindowsOpen)
{
  leaveWindowsOpen = !!leaveWindowsOpen;

  // Magic string that rundomfuzz.py looks for
  var messagePrefix = "Leaked until " + (leaveWindowsOpen ? "tab close" : "shutdown");

  if (quitting)
    return;
  quitting = true;

  runSoon(a);
  function a() { dumpln("QA"); if (!leaveWindowsOpen) closeAllWindows(); runOnTimer(b); dumpln("QAA"); }
  function b() { dumpln("QB"); mpUntilDone(c); }
  function c() { dumpln("QC"); bloatStats(d); }
  function d(objectCounts) {
    dumpln("QD");

    // Mac normally has extra documents (due to the hidden window?)
    var isMac = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime).OS == "Darwin";

    var expected = {
      'nsGlobalWindow':          4 + 6*leaveWindowsOpen,
      'nsDocument':              4 + 4*isMac + 24*leaveWindowsOpen,
      'nsDocShell':              5,
      'BackstagePass':           1,
      'nsGenericElement':        1927,
      'nsHTMLDivElement':        4,
      'xpc::CompartmentPrivate': 3,
    }

    for (var p in expected) {
      if (objectCounts[p] > expected[p]) {
        dumpln(messagePrefix + ": " + p + "(" + objectCounts[p] + " > " + expected[p] + ")");
      } else if (objectCounts[p] < expected[p]) {
        dumpln("That's odd"  + ": " + p + "(" + objectCounts[p] + " < " + expected[p] + ")");
      }
    }

    runSoon(e);
  }
  function e() { dumpln("QE"); goQuitApplication(); }
}

var timerDeathGrip;
function runOnTimer(f)
{
    timerDeathGrip = Components.classes["@mozilla.org/timer;1"].createInstance(Components.interfaces.nsITimer);
    timerDeathGrip.initWithCallback({notify: function(){ timerDeathGrip=null; f(); }}, 2000, Components.interfaces.nsITimer.TYPE_ONE_SHOT);
}

function closeAllWindows()
{
  var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
                     .getService(Ci.nsIWindowWatcher);
  var enumerator = ww.getWindowEnumerator();

  var windowsToClose = [];

  while (enumerator.hasMoreElements()) {
    windowsToClose.push(enumerator.getNext().QueryInterface(Ci.nsIDOMWindow));
  }

  // if not mac...
  ww.openWindow(null, "about:blank", null, "width=200,height=200", null);

  for (var i = 0; i < windowsToClose.length; ++i) {
    windowsToClose[i].close();
  }

  dumpln("1");
}

function mpUntilDone(callback)
{
  function mpUntilDoneInner()
  {
    dumpln("MP " + j);
    sendMemoryPressureNotification();

    ++j;
    if (j > 9)
      runSoon(callback);
    else if (j % 2 == 1 && typeof Components.utils.schedulePreciseGC == "function")
      Components.utils.schedulePreciseGC(mpUntilDoneInner)
    else
      runSoon(mpUntilDoneInner);
  }

  var j = 0;
  mpUntilDoneInner();
}

/*
     |<----------------Class--------------->|<-----Bytes------>|<----------------Objects---------------->|<--------------References-------------->|
                                              Per-Inst   Leaked    Total      Rem      Mean       StdDev     Total      Rem      Mean       StdDev

*/
// Grab the class name and the number of remaining objects.
var bloatRex = /\s*\d+\s+(\S+)\s+\d+\s+\d+\s+\d+\s+(\d+)\s+.*/;
const SET_QUOTA = false;
const USE_QUOTA = false;

function bloatStats(callback)
{
  var objectCounts = {};

  try {
    //d.d.d;
    NetUtil.asyncFetch("about:bloat", fetched);
  } catch(e) {
    dumpln("Can't open about:bloat -- maybe you forgot to use XPCOM_MEM_LEAK_LOG");
    callback(objectCounts);
  }

  function fetched(aInputStream, aResult)
  {
    var r = NetUtil.readInputStreamToString(aInputStream, aInputStream.available());
    var lines = r.split("\n");
    for (var i = 0; i < lines.length; ++i)
    {
      var a = bloatRex.exec(lines[i]);
      if (a) {
        if (SET_QUOTA) {
          dumpln("'" + a[1] + "': " + a[2] + ",");
        } else if (USE_QUOTA) {
          var quotaA = QUOTA[a[1]] || 0;
          if (a[2] > quotaA) { dumpln("Leak? Too many " + a[1] + " (" + a[2] + " > " + quotaA + ")"); }
        }
        objectCounts[a[1]] = a[2];
      }
    }
    runSoon(callCallback);
  }

  function callCallback()
  {
    callback(objectCounts)
  }
}

/********
 * QUIT *
 ********/

// From quit.js, which Bob Clary extracted from mozilla/toolkit/content

function canQuitApplication()
{
  var os = Components.classes["@mozilla.org/observer-service;1"]
    .getService(Components.interfaces.nsIObserverService);
  if (!os)
  {
    return true;
  }

  try
 {
    var cancelQuit = Components.classes["@mozilla.org/supports-PRBool;1"]
      .createInstance(Components.interfaces.nsISupportsPRBool);
    os.notifyObservers(cancelQuit, "quit-application-requested", null);

    // Something aborted the quit process.
    if (cancelQuit.data)
    {
      return false;
    }
  }
  catch (ex)
  {
  }
  os.notifyObservers(null, "quit-application-granted", null);
  return true;
}

function goQuitApplication()
{
  dumpln("goQuitApplication (js component)");

  if (!canQuitApplication())
  {
    return false;
  }

  var kAppStartup = '@mozilla.org/toolkit/app-startup;1';
  var kAppShell   = '@mozilla.org/appshell/appShellService;1';
  var   appService;
  var   forceQuit;

  if (kAppStartup in Components.classes)
  {
    appService = Components.classes[kAppStartup].
      getService(Components.interfaces.nsIAppStartup);
    forceQuit  = Components.interfaces.nsIAppStartup.eForceQuit;

  }
  else if (kAppShell in Components.classes)
  {
    appService = Components.classes[kAppShell].
      getService(Components.interfaces.nsIAppShellService);
    forceQuit = Components.interfaces.nsIAppShellService.eForceQuit;
  }
  else
  {
    throw 'goQuitApplication: no AppStartup/appShell';
  }

  var windowManager = Components.
    classes['@mozilla.org/appshell/window-mediator;1'].getService();

  var windowManagerInterface = windowManager.
    QueryInterface(Components.interfaces.nsIWindowMediator);

  var enumerator = windowManagerInterface.getEnumerator(null);

  while (enumerator.hasMoreElements())
  {
    var domWindow = enumerator.getNext();
    if (("tryToClose" in domWindow) && !domWindow.tryToClose())
    {
      return false;
    }
    domWindow.close();
  }

  try
  {
    appService.quit(forceQuit);
  }
  catch(ex)
  {
    throw('goQuitApplication: ' + ex);
  }

  return true;
}

<commit_msg>Don't try to print to .ps on windows<commit_after>"use strict";

const Cu = Components.utils;
const Cc = Components.classes;
const Ci = Components.interfaces;

Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource://gre/modules/NetUtil.jsm");

function dumpln(s) { dump(s + "\n"); }

/*****************
 * API INJECTION *
 *****************/

// Based on:
// https://bug549539.bugzilla.mozilla.org/attachment.cgi?id=429661
// https://developer.mozilla.org/en/XPCOM/XPCOM_changes_in_Gecko_1.9.3
// http://mxr.mozilla.org/mozilla-central/source/toolkit/components/console/hudservice/HUDService.jsm#3240
// https://developer.mozilla.org/en/how_to_build_an_xpcom_component_in_javascript

function DOMFuzzHelper() {}

// Use runSoon to avoid false-positive leaks due to content JS on the stack (?)
function quitFromContent() { dumpln("Page called quitApplication."); runSoon(goQuitApplication); }
function quitApplicationSoon() { dumpln("Page called quitApplicationSoon."); runOnTimer(goQuitApplication); }

DOMFuzzHelper.prototype = {
  classDescription: "DOM fuzz helper",
  classID:          Components.ID("{59a52458-13e0-4d90-9d85-a637344f29a1}"),
  contractID:       "@squarefree.com/dom-fuzz-helper;1",

  QueryInterface:   XPCOMUtils.generateQI([Ci.nsIDOMGlobalPropertyInitializer]),

  init: function(aWindow)
  {
    // Using bind(this) to ensure web page gets a *copy* of the function (is this necessary?)

    var api = {
      quitApplication:     quitFromContent.bind(this),
      quitApplicationSoon: quitApplicationSoon.bind(this),
      closeTabThenQuit:    closeTabThenQuit(aWindow),
      quitWithLeakCheck:   quitWithLeakCheck.bind(this),
      setGCZeal:           setGCZeal.bind(this),
      runSoon:             runSoon.bind(this),
      enableAccessibility: enableAccessibility.bind(this),
      GC:                  function() { Components.utils.forceGC(); },
      MP:                  sendMemoryPressureNotification.bind(this),
      CC:                  cycleCollect(aWindow),
      fontList:            fontList.bind(this),
      // zoom:             setZoomLevel(aWindow), // bug 576927
      printToFile:         printToFile(aWindow),
      openAboutMemory:     openNewTab.bind(this, aWindow, "about:memory"),

      __exposedProps__: {
        quitApplication: "r",
        quitApplicationSoon: "r",
        closeTabThenQuit: "r",
        quitWithLeakCheck: "r",
        setGCZeal: "r",
        runSoon: "r",
        enableAccessibility: "r",
        GC: "r",
        MP: "r",
        CC: "r",
        fontList: "r",
        // zoom: "r",
        printToFile: "r",
        openAboutMemory: "r",
      }
    };

    return api;
  }
};

const NSGetFactory = XPCOMUtils.generateNSGetFactory([DOMFuzzHelper]);

/*****************************
 * MISC PRIVILEGED FUNCTIONS *
 *****************************/

function openNewTab(w, url)
{
  w.open(url);
}

function closeTabThenQuit(w)
{
  return function() {
    runOnTimer(goQuitApplication);
    w.close();
  }
}

function fontList()
{
  return Components.classes["@mozilla.org/gfx/fontenumerator;1"]
          .createInstance(Components.interfaces.nsIFontEnumerator)
          .EnumerateAllFonts({})
          .join("\n");
}

function runSoon(f)
{
  var tm = Components.classes["@mozilla.org/thread-manager;1"]
             .getService(Components.interfaces.nsIThreadManager);

  tm.mainThread.dispatch({
    run: function() {
      f();
    }
  }, Components.interfaces.nsIThread.DISPATCH_NORMAL);
}

function enableAccessibility()
{
  try {
    Components.classes["@mozilla.org/accessibilityService;1"]
      .getService(Components.interfaces.nsIAccessibleRetrieval);
    dump("Enabled accessibility!\n");
  } catch(e) {
    dump("Couldn't enable accessibility: " + e + "\n");
  }
}

function sendMemoryPressureNotification()
{
  var os = Components.classes["@mozilla.org/observer-service;1"]
           .getService(Components.interfaces.nsIObserverService);
  os.notifyObservers(null, "memory-pressure", "heap-minimize");
}

function cycleCollect(window)
{
  return function cycleCollectInner() {
    window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
          .getInterface(Components.interfaces.nsIDOMWindowUtils)
          .cycleCollect();
  }
}

function setZoomLevel(window)
{
  return function setZoomLevelInner(textOrFull, factor) {
    var viewer = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                       .getInterface(Components.interfaces.nsIWebNavigation)
                       .QueryInterface(Components.interfaces.nsIDocShell)
                       .contentViewer
                       .QueryInterface(Components.interfaces.nsIMarkupDocumentViewer);

    if (textOrFull == "text")
      viewer.textZoom = +factor;
    else if (textOrFull == "full")
      viewer.fullZoom = +factor;
  }
}

function printToFile(window)
{
  // Oddly asynchronous, at least on Linux.

  // Linux: works for PDF and PS.
  // Windows: works for PDF at least. Text may be invisible (bug 653336).
  // Mac: tested, printToFile is ignored and it goes to a printer! (bug 675709)
  var xulRuntime = Components.classes["@mozilla.org/xre/app-info;1"]
                             .getService(Components.interfaces.nsIXULRuntime);
  dumpln("xulRuntime.OS: " + xulRuntime.OS);
  if (xulRuntime.OS != "Linux" && xulRuntime.OS != "WINNT") return function() { };

  var fired = false;

  return function printToFileInner(showHeaders, showBGColor, showBGImages, ps) {
    runSoon(function() {
        // Don't print more than once, it gets messy fast.
        if (fired) { return false; }
        fired = true;

        ps = ps && xulRuntime.OS != "WINNT"; // Windows gets confused when trying to print to ps, and tosses up a *.xps filepicker outside the Firefox process!?

        // Based on https://addons.mozilla.org/en-US/firefox/addon/5971/ by pavlov (Stuart Parmenter) and bho

        var webBrowserPrint = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
        .getInterface(Components.interfaces.nsIWebBrowserPrint);

        var nsIPrintSettings = Components.interfaces.nsIPrintSettings;

        var PSSVC = Components.classes["@mozilla.org/gfx/printsettings-service;1"]
        .getService(Components.interfaces.nsIPrintSettingsService);

        var printSettings = PSSVC.newPrintSettings;

        var file = Components.classes["@mozilla.org/file/directory_service;1"].
                              getService(Components.interfaces.nsIProperties).
                              get("ProfD", Components.interfaces.nsIFile);
        file.append(ps ? "fuzzout.ps" : "fuzzout.pdf");
        dumpln("Printing to: " + file.path);

        printSettings.printToFile = true;
        printSettings.toFileName  = file.path;
        printSettings.printSilent = true;
        printSettings.outputFormat = ps ? nsIPrintSettings.kOutputFormatPS : nsIPrintSettings.kOutputFormatPDF;
        printSettings.printBGColors   = !!showBGColor;
        printSettings.printBGImages   = !!showBGImages;
        if (!showHeaders) {
            printSettings.footerStrCenter = '';
            printSettings.footerStrLeft   = '';
            printSettings.footerStrRight  = '';
            printSettings.headerStrCenter = '';
            printSettings.headerStrLeft   = '';
            printSettings.headerStrRight  = '';
        }

        webBrowserPrint.print(printSettings, null);
    });
  }
}

function setGCZeal(zeal)
{
  if (typeof(zeal) == "number") {
    Services.prefs.setIntPref("javascript.options.gczeal", zeal)
  }
}

/************************
 * QUIT WITH LEAK CHECK *
 ************************/

var quitting = false;

function quitWithLeakCheck(leaveWindowsOpen)
{
  leaveWindowsOpen = !!leaveWindowsOpen;

  // Magic string that rundomfuzz.py looks for
  var messagePrefix = "Leaked until " + (leaveWindowsOpen ? "tab close" : "shutdown");

  if (quitting)
    return;
  quitting = true;

  runSoon(a);
  function a() { dumpln("QA"); if (!leaveWindowsOpen) closeAllWindows(); runOnTimer(b); dumpln("QAA"); }
  function b() { dumpln("QB"); mpUntilDone(c); }
  function c() { dumpln("QC"); bloatStats(d); }
  function d(objectCounts) {
    dumpln("QD");

    // Mac normally has extra documents (due to the hidden window?)
    var isMac = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime).OS == "Darwin";

    var expected = {
      'nsGlobalWindow':          4 + 6*leaveWindowsOpen,
      'nsDocument':              4 + 4*isMac + 24*leaveWindowsOpen,
      'nsDocShell':              5,
      'BackstagePass':           1,
      'nsGenericElement':        1927,
      'nsHTMLDivElement':        4,
      'xpc::CompartmentPrivate': 3,
    }

    for (var p in expected) {
      if (objectCounts[p] > expected[p]) {
        dumpln(messagePrefix + ": " + p + "(" + objectCounts[p] + " > " + expected[p] + ")");
      } else if (objectCounts[p] < expected[p]) {
        dumpln("That's odd"  + ": " + p + "(" + objectCounts[p] + " < " + expected[p] + ")");
      }
    }

    runSoon(e);
  }
  function e() { dumpln("QE"); goQuitApplication(); }
}

var timerDeathGrip;
function runOnTimer(f)
{
    timerDeathGrip = Components.classes["@mozilla.org/timer;1"].createInstance(Components.interfaces.nsITimer);
    timerDeathGrip.initWithCallback({notify: function(){ timerDeathGrip=null; f(); }}, 2000, Components.interfaces.nsITimer.TYPE_ONE_SHOT);
}

function closeAllWindows()
{
  var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
                     .getService(Ci.nsIWindowWatcher);
  var enumerator = ww.getWindowEnumerator();

  var windowsToClose = [];

  while (enumerator.hasMoreElements()) {
    windowsToClose.push(enumerator.getNext().QueryInterface(Ci.nsIDOMWindow));
  }

  // if not mac...
  ww.openWindow(null, "about:blank", null, "width=200,height=200", null);

  for (var i = 0; i < windowsToClose.length; ++i) {
    windowsToClose[i].close();
  }

  dumpln("1");
}

function mpUntilDone(callback)
{
  function mpUntilDoneInner()
  {
    dumpln("MP " + j);
    sendMemoryPressureNotification();

    ++j;
    if (j > 9)
      runSoon(callback);
    else if (j % 2 == 1 && typeof Components.utils.schedulePreciseGC == "function")
      Components.utils.schedulePreciseGC(mpUntilDoneInner)
    else
      runSoon(mpUntilDoneInner);
  }

  var j = 0;
  mpUntilDoneInner();
}

/*
     |<----------------Class--------------->|<-----Bytes------>|<----------------Objects---------------->|<--------------References-------------->|
                                              Per-Inst   Leaked    Total      Rem      Mean       StdDev     Total      Rem      Mean       StdDev

*/
// Grab the class name and the number of remaining objects.
var bloatRex = /\s*\d+\s+(\S+)\s+\d+\s+\d+\s+\d+\s+(\d+)\s+.*/;
const SET_QUOTA = false;
const USE_QUOTA = false;

function bloatStats(callback)
{
  var objectCounts = {};

  try {
    //d.d.d;
    NetUtil.asyncFetch("about:bloat", fetched);
  } catch(e) {
    dumpln("Can't open about:bloat -- maybe you forgot to use XPCOM_MEM_LEAK_LOG");
    callback(objectCounts);
  }

  function fetched(aInputStream, aResult)
  {
    var r = NetUtil.readInputStreamToString(aInputStream, aInputStream.available());
    var lines = r.split("\n");
    for (var i = 0; i < lines.length; ++i)
    {
      var a = bloatRex.exec(lines[i]);
      if (a) {
        if (SET_QUOTA) {
          dumpln("'" + a[1] + "': " + a[2] + ",");
        } else if (USE_QUOTA) {
          var quotaA = QUOTA[a[1]] || 0;
          if (a[2] > quotaA) { dumpln("Leak? Too many " + a[1] + " (" + a[2] + " > " + quotaA + ")"); }
        }
        objectCounts[a[1]] = a[2];
      }
    }
    runSoon(callCallback);
  }

  function callCallback()
  {
    callback(objectCounts)
  }
}

/********
 * QUIT *
 ********/

// From quit.js, which Bob Clary extracted from mozilla/toolkit/content

function canQuitApplication()
{
  var os = Components.classes["@mozilla.org/observer-service;1"]
    .getService(Components.interfaces.nsIObserverService);
  if (!os)
  {
    return true;
  }

  try
 {
    var cancelQuit = Components.classes["@mozilla.org/supports-PRBool;1"]
      .createInstance(Components.interfaces.nsISupportsPRBool);
    os.notifyObservers(cancelQuit, "quit-application-requested", null);

    // Something aborted the quit process.
    if (cancelQuit.data)
    {
      return false;
    }
  }
  catch (ex)
  {
  }
  os.notifyObservers(null, "quit-application-granted", null);
  return true;
}

function goQuitApplication()
{
  dumpln("goQuitApplication (js component)");

  if (!canQuitApplication())
  {
    return false;
  }

  var kAppStartup = '@mozilla.org/toolkit/app-startup;1';
  var kAppShell   = '@mozilla.org/appshell/appShellService;1';
  var   appService;
  var   forceQuit;

  if (kAppStartup in Components.classes)
  {
    appService = Components.classes[kAppStartup].
      getService(Components.interfaces.nsIAppStartup);
    forceQuit  = Components.interfaces.nsIAppStartup.eForceQuit;

  }
  else if (kAppShell in Components.classes)
  {
    appService = Components.classes[kAppShell].
      getService(Components.interfaces.nsIAppShellService);
    forceQuit = Components.interfaces.nsIAppShellService.eForceQuit;
  }
  else
  {
    throw 'goQuitApplication: no AppStartup/appShell';
  }

  var windowManager = Components.
    classes['@mozilla.org/appshell/window-mediator;1'].getService();

  var windowManagerInterface = windowManager.
    QueryInterface(Components.interfaces.nsIWindowMediator);

  var enumerator = windowManagerInterface.getEnumerator(null);

  while (enumerator.hasMoreElements())
  {
    var domWindow = enumerator.getNext();
    if (("tryToClose" in domWindow) && !domWindow.tryToClose())
    {
      return false;
    }
    domWindow.close();
  }

  try
  {
    appService.quit(forceQuit);
  }
  catch(ex)
  {
    throw('goQuitApplication: ' + ex);
  }

  return true;
}

<|endoftext|>


<commit_before>(function () {
    'use strict';
    const userNameInput = document.getElementById('user-name');
    const assessmentButton = document.getElementById('assessment');
    const resultDivided = document.getElementById('result-area');
    const tweetDivided = document.getElementById('tweet-area');

    /**
    * 指定した要素の子どもを全て除去する
    * @param {HTMLElement} element HTMLの要素
    */
    function removeAllChildren(element) {
        while (element.firstChild) { // 子どもの要素があるかぎり除去
            element.removeChild(element.firstChild);
        }
    }

    assessmentButton.onclick = () => {
        const userName = userNameInput.value;
        if (userName.length === 0) { // 名前が空の時は処理を終了する
            return;
        }

        // 診断結果表示エリアの作成
        removeAllChildren(resultDivided);
        const header = document.createElement('h3');
        header.innerText = '診断結果';
        resultDivided.appendChild(header);

        const paragraph = document.createElement('p');
        const result = assessment(userName);
        paragraph.innerText = result;
        resultDivided.appendChild(paragraph);

        // ツイートエリアの作成
        removeAllChildren(tweetDivided);
        const anchor = document.createElement('a');
        const hrefValue = 'https://twitter.com/intent/tweet?button_hashtag='
            + encodeURIComponent('あなたのいいところ')
            + '&ref_src=twsrc%5Etfw';
        anchor.setAttribute('href', hrefValue);
        anchor.className = 'twitter-hashtag-button';
        anchor.setAttribute('data-text', result);
        anchor.innerText = 'Tweet #あなたのいいところ';
        tweetDivided.appendChild(anchor);

        twttr.widgets.load();
    };

    const answers = [
        '{userName}のいいところは声です。{userName}の特徴的な声はみなを惹きつけ、心に残ります。',
        '{userName}のいいところはまなざしです。{userName}に見つめられた人は、気になって仕方がないでしょう。',
        '{userName}のいいところは情熱です。{userName}の情熱に周りの人は感化されます。',
        '{userName}のいいところは厳しさです。{userName}の厳しさがものごとをいつも成功に導きます。',
        '{userName}のいいところは知識です。博識な{userName}を多くの人が頼りにしています。',
        '{userName}のいいところはユニークさです。{userName}だけのその特徴が皆を楽しくさせます。',
        '{userName}のいいところは用心深さです。{userName}の洞察に、多くの人が助けられます。',
        '{userName}のいいところは見た目です。内側から溢れ出る{userName}の良さに皆が気を惹かれます。',
        '{userName}のいいところは決断力です。{userName}がする決断にいつも助けられる人がいます。',
        '{userName}のいいところは思いやりです。{userName}に気をかけてもらった多くの人が感謝しています。',
        '{userName}のいいところは感受性です。{userName}が感じたことに皆が共感し、わかりあうことができます。',
        '{userName}のいいところは節度です。強引すぎない{userName}の考えに皆が感謝しています。',
        '{userName}のいいところは好奇心です。新しいことに向かっていく{userName}の心構えが多くの人に魅力的に映ります。',
        '{userName}のいいところは気配りです。{userName}の配慮が多くの人を救っています。',
        '{userName}のいいところはその全てです。ありのままの{userName}自身がいいところなのです。',
        '{userName}のいいところは自制心です。やばいと思ったときにしっかりと衝動を抑えられる{userName}が皆から評価されています。',
        '{userName}のいいところは優しさです。{userName}の優しい雰囲気や立ち振る舞いに多くの人が癒されています。'
    ];

    /**
    * 名前の文字列を渡すと診断結果を返す関数
    * @param {string} userName ユーザーの名前
    * @return {string} 診断結果
    */
    function assessment(userName) {
        // 全文字のコード番号を取得してそれを足し合わせる
        let sumOfcharCode = 0;
        for (let i = 0; i < userName.length; i++) {
            sumOfcharCode = sumOfcharCode + userName.charCodeAt(i);
        }

        // 文字のコード番号の合計を回答の数で割って添字の数値を求める
        const index = sumOfcharCode % answers.length;
        let result = answers[index];

        result = result.replace(/{userName}/g, userName);
        return result;
    }

    // テストコード
    console.assert(
        assessment('太郎') === '太郎のいいところは決断力です。太郎がする決断にいつも助けられる人がいます。',
        '診断結果の文言の特定の部分を名前に置き換える処理が正しくありません。'
    );
    console.assert(
        assessment('太郎') === assessment('太郎'),
        '入力が同じ名前なら同じ診断結果を出力する処理が正しくありません。'
    );
})();

<commit_msg>#1に対する対応を行いました。<commit_after>(function () {
    'use strict';
    const userNameInput = document.getElementById('user-name');
    const assessmentButton = document.getElementById('assessment');
    const resultDivided = document.getElementById('result-area');
    const tweetDivided = document.getElementById('tweet-area');

    /**
    * 指定した要素の子どもを全て除去する
    * @param {HTMLElement} element HTMLの要素
    */
    function removeAllChildren(element) {
        while (element.firstChild) { // 子どもの要素があるかぎり除去
            element.removeChild(element.firstChild);
        }
    }

    assessmentButton.onclick = () => {
        const userName = userNameInput.value;
        if (userName.length === 0) { // 名前が空の時は処理を終了する
            return;
        }

        // 診断結果表示エリアの作成
        removeAllChildren(resultDivided);
        const header = document.createElement('h3');
        header.innerText = '診断結果';
        resultDivided.appendChild(header);

        const paragraph = document.createElement('p');
        const result = assessment(userName);
        paragraph.innerText = result;
        resultDivided.appendChild(paragraph);

        // ツイートエリアの作成
        removeAllChildren(tweetDivided);
        const anchor = document.createElement('a');
        const hrefValue = 'https://twitter.com/intent/tweet?button_hashtag='
            + encodeURIComponent('あなたのいいところ')
            + '&ref_src=twsrc%5Etfw';
        anchor.setAttribute('href', hrefValue);
        anchor.className = 'twitter-hashtag-button';
        anchor.setAttribute('data-text', result);
        anchor.innerText = 'Tweet #あなたのいいところ';
        tweetDivided.appendChild(anchor);

        twttr.widgets.load();
    };

    const answers = [
        '{userName}のいいところは声です。{userName}の特徴的な声はみなを惹きつけ、心に残ります。',
        '{userName}のいいところはまなざしです。{userName}に見つめられた人は、気になって仕方がないでしょう。',
        '{userName}のいいところは情熱です。{userName}の情熱に周りの人は感化されます。',
        '{userName}のいいところは厳しさです。{userName}の厳しさがものごとをいつも成功に導きます。',
        '{userName}のいいところは知識です。博識な{userName}を多くの人が頼りにしています。',
        '{userName}のいいところはユニークさです。{userName}だけのその特徴が皆を楽しくさせます。',
        '{userName}のいいところは用心深さです。{userName}の洞察に、多くの人が助けられます。',
        '{userName}のいいところは見た目です。内側から溢れ出る{userName}の良さに皆が気を惹かれます。',
        '{userName}のいいところは決断力です。{userName}がする決断にいつも助けられる人がいます。',
        '{userName}のいいところは思いやりです。{userName}に気をかけてもらった多くの人が感謝しています。',
        '{userName}のいいところは感受性です。{userName}が感じたことに皆が共感し、わかりあうことができます。',
        '{userName}のいいところは節度です。強引すぎない{userName}の考えに皆が感謝しています。',
        '{userName}のいいところは好奇心です。新しいことに向かっていく{userName}の心構えが多くの人に魅力的に映ります。',
        '{userName}のいいところは気配りです。{userName}の配慮が多くの人を救っています。',
        '{userName}のいいところはその全てです。ありのままの{userName}自身がいいところなのです。',
        '{userName}のいいところは自制心です。やばいと思ったときにしっかりと衝動を抑えられる{userName}が皆から評価されています。',
        '{userName}のいいところは優しさです。{userName}の優しい雰囲気や立ち振る舞いに多くの人が癒されています。',
        '{userName}のいいところはばからしさです。{userName}のばからしい舞いに多くの人が癒されています。'
    ];

    /**
    * 名前の文字列を渡すと診断結果を返す関数
    * @param {string} userName ユーザーの名前
    * @return {string} 診断結果
    */
    function assessment(userName) {
        // 全文字のコード番号を取得してそれを足し合わせる
        let sumOfcharCode = 0;
        for (let i = 0; i < userName.length; i++) {
            sumOfcharCode = sumOfcharCode + userName.charCodeAt(i);
        }

        // 文字のコード番号の合計を回答の数で割って添字の数値を求める
        const index = sumOfcharCode % answers.length;
        let result = answers[index];

        result = result.replace(/{userName}/g, userName);
        return result;
    }

    // テストコード
    console.assert(
        assessment('太郎') === '太郎のいいところは決断力です。太郎がする決断にいつも助けられる人がいます。',
        '診断結果の文言の特定の部分を名前に置き換える処理が正しくありません。'
    );
    console.assert(
        assessment('太郎') === assessment('太郎'),
        '入力が同じ名前なら同じ診断結果を出力する処理が正しくありません。'
    );
})();

<|endoftext|>


<commit_before>var app = angular.module('viperdev', ['ngSanitize'])
app.controller('Data', ['$http', function($http , $scope){
    self = this;
    self.profile = [
        {
            "name" : "Lasse Schuirmann",
            "id" : "sils",
            "picture" : "https://avatars2.githubusercontent.com/u/5716520",
            "short_tagline": "Problem solver",
            "bio": "Founder of coala, GitMate and viperdev and conference speaker."
        },
        {
            "name" : "Mischa Krüger",
            "id" : "Makman2",
            "picture" : "https://avatars3.githubusercontent.com/u/6023916",
            "short_tagline": "Code & Review Junkie",
            "bio": "coala core developer and inventor of the open source CE3D terminal game engine."
        },
        {
            "name" : "Adhityaa Chandrasekar",
            "id" : "adtac",
            "picture" : "https://avatars2.githubusercontent.com/u/7521600",
            "short_tagline": "Hardcore hacker",
            "bio": "coala core developer and creator of climate and fssb."
        },
        {
            "name" : "Maximilian Scholz",
            "id" : "sims1253",
            "picture" : "https://avatars3.githubusercontent.com/u/6530123",
            "short_tagline": "Community evangelist",
            "bio": "Leader of the coala community team and creator of the LineSpots algorithm."
        },
        {
            "name" : "Sebastian Latacz",
            "id" : "seblat",
            "picture": "https://avatars0.githubusercontent.com/u/18051901",
            "short_tagline":"Business expert",
            "bio" : "Founder of GitMate and solver of the most complicated business problems."
        },
        {
            "name" : "Hemang Kumar",
            "id" : "hemangsk",
            "picture": "https://avatars1.githubusercontent.com/u/13018570",
            "short_tagline":"Frontend Enthusiast",
            "bio" : "coala developer. Frontend lover. Creates and designs web frontends with passion."
        }
    ]

    self.plans = [
        {
            "title" : "Monthly Quality Sessions",
            "subtitle": "Level up - one step every month",
            "benefits" : [
                "Build a better workflow incrementally",
                "Start learning, stop being dependent",
                "Get the right tools for your team",
            ],
            "features" : [
                "Talk through your problems monthly",
                "A monthly summary of your main issues",
                "3 recommendations on solutions",
                "Follow up at the end of the month",
                "Recurring ROI with every session"
            ],
            "price": "1000eur/mon",
            "form": `<a href="https://viperdev.typeform.com/to/fABj8j" target="_blank">Get Started</a>`
        },
        {
            "title" : "Boost Your Open Source Project",
            "subtitle": "Partner with us as a long term investment",
            "benefits" : [
                "Improve quality and save money",
                "Expand technology choices",
                "Give back and increase trust",
                "Strengthen your tech brand",
                "Attract uniquely motivated talent"
            ],
            "features" : [
                "Automated newcomer invitation and onboarding",
                "Social media promotion",
                "A dedicated community expert works with you in your channels",
                "Includes Monthly Quality Sessions",
            ],
            "price": "3500eur/mon/project
2000eur setup/project",
            "form": `<a href="https://viperdev.typeform.com/to/AKlsXq" target="_blank">Get Started</a>`
        },
        {
            "title" : "Custom",
            "subtitle": "You thought of something we're perfect for?",
            "benefits" : [
                "Improve code quality",
                "Improve workflows",
                "Develop faster",
            ],
            "features" : [
                "Workshops on premises",
                "Consulting on premises",
                "Limitless possibilities",
                "Create workflow automation"
            ],
            "price": "On Request",
            "form": "Mail us"
        }
    ]
}])
<commit_msg>Clarify and lower prices<commit_after>var app = angular.module('viperdev', ['ngSanitize'])
app.controller('Data', ['$http', function($http , $scope){
    self = this;
    self.profile = [
        {
            "name" : "Lasse Schuirmann",
            "id" : "sils",
            "picture" : "https://avatars2.githubusercontent.com/u/5716520",
            "short_tagline": "Problem solver",
            "bio": "Founder of coala, GitMate and viperdev and conference speaker."
        },
        {
            "name" : "Mischa Krüger",
            "id" : "Makman2",
            "picture" : "https://avatars3.githubusercontent.com/u/6023916",
            "short_tagline": "Code & Review Junkie",
            "bio": "coala core developer and inventor of the open source CE3D terminal game engine."
        },
        {
            "name" : "Adhityaa Chandrasekar",
            "id" : "adtac",
            "picture" : "https://avatars2.githubusercontent.com/u/7521600",
            "short_tagline": "Hardcore hacker",
            "bio": "coala core developer and creator of climate and fssb."
        },
        {
            "name" : "Maximilian Scholz",
            "id" : "sims1253",
            "picture" : "https://avatars3.githubusercontent.com/u/6530123",
            "short_tagline": "Community evangelist",
            "bio": "Leader of the coala community team and creator of the LineSpots algorithm."
        },
        {
            "name" : "Sebastian Latacz",
            "id" : "seblat",
            "picture": "https://avatars0.githubusercontent.com/u/18051901",
            "short_tagline":"Business expert",
            "bio" : "Founder of GitMate and solver of the most complicated business problems."
        },
        {
            "name" : "Hemang Kumar",
            "id" : "hemangsk",
            "picture": "https://avatars1.githubusercontent.com/u/13018570",
            "short_tagline":"Frontend Enthusiast",
            "bio" : "coala developer. Frontend lover. Creates and designs web frontends with passion."
        }
    ]

    self.plans = [
        {
            "title" : "Monthly Quality Sessions",
            "subtitle": "Level up - one step every month",
            "benefits" : [
                "Build a better workflow incrementally",
                "Start learning, stop being dependent",
                "Get the right tools for your team",
            ],
            "features" : [
                "Talk through your problems monthly",
                "A monthly summary of your main issues",
                "3 recommendations on solutions",
                "Follow up at the end of the month",
                "Recurring ROI with every session"
            ],
            "price": "500eur/mon",
            "form": `<a href="https://viperdev.typeform.com/to/fABj8j" target="_blank">Get Started</a>`
        },
        {
            "title" : "Boost Your Open Source Project",
            "subtitle": "Partner with us as a long term investment",
            "benefits" : [
                "Get great developers on your project",
                "Improve quality and save money",
                "Expand technology choices",
                "Give back and increase trust",
                "Strengthen your tech brand",
            ],
            "features" : [
                "Automated newcomer invitation and onboarding",
                "Social media promotion",
                "A dedicated community expert works with you in your channels",
                "Includes Monthly Quality Sessions",
            ],
            "price": "2000eur/mon/project
2000eur setup/project",
            "form": `<a href="https://viperdev.typeform.com/to/AKlsXq" target="_blank">Get Started</a>`
        },
        {
            "title" : "Custom",
            "subtitle": "You thought of something we're perfect for?",
            "benefits" : [
                "Improve code quality",
                "Improve workflows",
                "Develop faster",
            ],
            "features" : [
                "Workshops on premises",
                "Consulting on premises",
                "Limitless possibilities",
                "Create workflow automation"
            ],
            "price": "On Request",
            "form": "Mail us"
        }
    ]
}])
<|endoftext|>