Session makes the variable update data twice - angularjs

Every time I get a new price, the following is supposed to happen:
totalprice = totalprice + cart[i]
For example, if the totalprice was previously 500 and a new price is 800, the totalprice is supposed to be (500 + 800) whereas it's currently (500 + 500 + 800). Why does this happen?
exports.add = function(req, res) {
var cart = req.body.cart;
console.log('frome node..adding checkcart.js');
console.log("Session Initialized!!");
for(var i = 0 ; i < cart.length ; i++) {
totalprice = cart[i].price + totalprice;
console.log('Current Price: '+cart[i].price);
}
req.session.cart = cart;
console.log(cart);
console.log('total: ' + totalprice);
//req.session.totalprice = totalprice;
json_responses = {
"totalprice": req.session.totalprice
}
res.send(json_responses);
};

This is one of many answers. I would suggest creating a variable that will count the amount of items already added. Otherwise, your for loop will keep counting them all again and again. Bare in mind your question lacks a lot of code, so this will have me add two options.
Option 1
Every time a user adds an item the add function will be called. For this option all you have to do is add the last added item to the total price calculation. So in your code, instead of:
for(var i = 0 ; i < cart.length ; i++) {
totalprice = cart[i].price + totalprice;
console.log('Current Price: '+cart[i].price);
}
Use:
totalprice = cart[cart.length-1].price + totalprice;
Option 2
This option is for when a user can add many items, and the prices are calculated once the user clicks a button that calls the add method. This is just slightly more tricky. You need to add a counter that will count the items already calculated. So in code:
var counter = 0;
exports.add = function(req, res) {
var cart = req.body.cart;
var prevCounter = counter;
counter = req.body.cart.length - counter; // items added in the session
console.log('frome node..adding checkcart.js');
console.log("Session Initialized!!");
for(var i = prevCounter ; i < counter ; i++) {
totalprice = cart[i].price + totalprice;
console.log('Current Price: ' + cart[i].price);
}
req.session.cart = cart;
console.log(cart);
console.log('total: ' + totalprice);
//req.session.totalprice = totalprice;
json_responses = {
"totalprice": req.session.totalprice
}
res.send(json_responses);
};
Good luck !

Related

loop count number of consecutive cell containing specific word

I'm quite a beginner in JavaScript (well google app script) but now I can manage my work without it. My goal is to send an email to someone when the number of cell containing the word "alert" is equal to 3. I think that the structure of my program might be correct however the syntax may be wrong.
Let me show you what does my program look like for now (I want it to begin on row number 24 and on the 34th column of my sheet):
function onEdit(e) {
let sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
//EVENT VARIABLES
let range = e.range;
let row = e.range.getRow();
let col = e.range.getColumn();
let cellValue = sheet.getActiveCell().getValue();
let lastRow = sheet.getLastRow;
let projectName = sheet.getRange(row,1).getValue();
let user = Session.getActiveUser().getEmail();
let cellLocation = sheet.getActiveCell().getA1Notation();
let countAlerte = 0;
let url = "https://docs.google.com/spreadsheets/d/blablabla"
for (i=24;i<=lastRow;i++){
if ((col == 34 && cellValue == "alerte")){
countAlerte = 1;
}
else {
countAlerte = 0;
}
if (countAlerte == 3){
MailApp.sendEmail(
'surname.name#xxx.com',
user + projectName + ' alerte mol 1 ',
url + '&range=' + cellLocation
);
};
}
Is my syntax and variable definition correct?
Is there something wrong with my loop?
You should add 1 instead of assignment:
{
countAlerte = countAlerte + 1; /// or just countAlerte += 1;
}
else {
countAlerte = 0;
}
That is regarding the counting.
Another thing is how do you want to catch onEdit(e). It would be better to get values in the column 34
var valuesInColumn = sheet.getRange(24, 34, lastRow, 1).getValues();
and loop through all values in the valuesInColumn array
for example:
if (col == 34){
var valuesInColumn = sheet.getRange(24, 34, lastRow, 1).getValues();
valuesInColumn.forEach(function(item){
if (item == "alerte"){
countAlerte = countAlerte + 1;
if (countAlerte == 3){
MailApp.sendEmail(
'surname.name#xxx.com',
user + projectName + ' alerte mol 1 ',
url + '&range=' + cellLocation
);
countAlerte = 0;
}
}
else{
countAlerte = 0;
}
});
}

I'm trying to randomize 5 selections from a list of people

This might be less difficult than I'm making it out to be, but I'm trying to make a Discord.JS bot command, that will take however many arguments I have. For example: !randomize 1,2,3,4,5,6,7,8,9,10
And the bot would respond with something like: "I have chosen: 4,2,7,3,9!" Any help?
Current attempt: Not exactly sure what I'm doing.
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}`
`bot.on('message', async msg => {
if(msg.content === "!add") {
//message.member.user.tag
var msgArray = msg.content.split(" ");
var args = msgArray.slice(1);
var user = args[1];
//if(!args[1]) return msg.channel.send("Please specify an argument!");
if(nameList.includes(user)) {
msg.reply("You're already on the list.")
} else {
nameList.push(args[1]);
msg.channel.send(`${args[1]} has been added to the list!\n Current List:` + nameList);
}
}
if(msg.content === "!bonus") {
if(nameList.length === 0) {
msg.reply("Either the list is empty, or I'm not in the mood!");
} else {
shuffleArray(nameList);
var chosenOne = nameList.pop();
nameList = [];
msg.reply(chosenOne + ' has been chosen! Good luck!');
}
}
if(msg.content === "!list") {
if(nameList.length === 0) {
msg.channel.send("Either the list is empty, or I'm not in the mood!");
} else {
msg.channel.send('The current list:' + nameList);
}
});```
Here's some simple steps to select 5 random elements from an array...
Construct an array of possible selections. In this example I've used names for the first 10 letters of the alphabet. In your code, it'll be the command arguments or predefined nameList.
Make a new array to hold the elements picked.
At some point before #3, you should check to make sure the pool the user has provided is large enough to make 5 selections (Array.length).
Use a for loop to execute the next code multiple times.
Generate a random number representing the index of a selected element (Math.random(), Math.floor()/double NOT bitwise operator).
Push the selection into the array.
Remove the chosen element from the original pool (Array.splice()).
Return the results.
const pool = ['Albert', 'Bob', 'Charlie', 'David', 'Edward', 'Francis', 'George', 'Horacio', 'Ivan', 'Jim'];
const selected = [];
for (let i = 0; i < 5; i++) {
const num = ~~(Math.random() * pool.length);
selected.push(pool[num]);
pool.splice(num, 1);
}
console.log(`I have chosen: ${selected.join(', ')}`);
Take this example and manipulate it within your code to suit your purpose.

Can not save array in shared object as3

I have this code in my simple flash. I want to save name and score in my quiz. My code reference in this website http://www.mollyjameson.com/blog/local-flash-game-leaderboard-tutorial/
I want to make my code in just one actionscript. But I didn't success do it.
var m_FlashCookie = SharedObject.getLocal("LeaderboardExample");
var EntryName:String ="nama kamu";
var EntryScore:String ="nilai";
const NUM_SCORES_SAVED:int = 10;
inputBoxScore.text = EntryScore;
inputBoxName.text = EntryName
var latest_score_object:Object = {
name: EntryName,
score: EntryScore
};
var arr:Array;
arr = m_FlashCookie.data.storedArray
if ( arr == null)
{
arr = new Array();
}
arr.push( latest_score_object );
arr.sortOn("score", Array.NUMERIC | Array.DESCENDING);
if ( arr.length < NUM_SCORES_SAVED )
{
arr.pop();
}
btnSave.addEventListener(MouseEvent.CLICK, saveData);
function saveData(event:Event):void
{
m_FlashCookie.data.arr = arr;
m_FlashCookie.flush();
}
var myHTMLL:String = "";
var total_stored_scores:int = arr.length;
btnLoad.addEventListener(MouseEvent.CLICK, loadData);
function loadData(event:Event):void
{
for (var i:int = 0; i < total_stored_scores; ++i)
{
// loop through every entry, every entry has a "name" and "score" field as that's what we save.
var leaderboard_entry:Object = arr[i];
// is this the last score that was just entered last gamestate?
if ( leaderboard_entry == latest_score_object )
{
myHTMLL += (i+1) + ". <b><font color=\"#0002E5\">"+ leaderboard_entry.name + " " + leaderboard_entry.score +"</font></b><br>";
}
else
{
myHTMLL += (i+1) + ". "+ leaderboard_entry.name + " " + leaderboard_entry.score +"<br>";
}
}
myHTML.text = myHTMLL;
}
Can anybody help me?
You're saving the array as data.arr but reading the array as data.storedArray. You need to make them the same.
In other words, you've written this:
m_FlashCookie.data.arr = arr;
And when you load:
arr = m_FlashCookie.data.storedArray;
This clearly doesn't make sense: data.storedArray is never set, so it will never have a value, so you will always end up with a new empty array.
You need to use the same property on the shared object data. For example:
m_FlashCookie.data.storedArray = arr;
m_FlashCookie.flush();
Looking at your code, there's a number of other issues:
The latest score is immediately removed because arr.length < NUM_SAVED_SCORES is going to be true from the start, since arr starts out empty, and it then calls arr.pop() which will remove the latest entry that was just added. So the array is always empty.
It adds the score immediately with arr.push(latest_score_object) instead of waiting until the user clicks save, so the value of the input texts don't matter at all -- the saved values will always be "nama kamu" and "nilai".
The following fixes all the issues mentioned:
var leaderboard = SharedObject.getLocal("leaderboard");
const MAX_SAVED_SCORES:int = 10;
inputBoxName.text = "nama kamu";
inputBoxScore.text = "nilai";
var entries:Array = leaderboard.data.entries || [];
var latestEntry:Object;
displayScores();
btnLoad.addEventListener(MouseEvent.CLICK, loadClick);
btnSave.addEventListener(MouseEvent.CLICK, saveClick);
function loadClick(e:MouseEvent):void {
displayScores();
}
function saveClick(e:MouseEvent):void {
saveLatestScore();
displayScores();
}
function saveLatestScore():void {
// create the latest entry based on input texts
latestEntry = {
name: inputBoxName.text,
score: inputBoxScore.text
};
// add the entry and sort by score, highest to lowest
entries.push(latestEntry);
entries.sortOn("score", Array.NUMERIC | Array.DESCENDING);
// if reached the limit, remove lowest score
if (entries.length > MAX_SAVED_SCORES) {
entries.pop();
}
// store new sorted entries to shared object
leaderboard.data.entries = entries;
leaderboard.flush();
}
function displayScores():void {
var myHTMLL:String = "";
for (var i:int = 0; i < entries.length; ++i) {
// loop through every entry, every entry has a "name" and "score" field as that's what we save.
var entry:Object = entries[i];
// is this the last score that was just entered last gamestate?
if (entry == latestEntry)
myHTMLL += (i+1) + ". <b><font color=\"#0002E5\">"+ entry.name + " " + entry.score +"</font></b><br/>";
else
myHTMLL += (i+1) + ". "+ entry.name + " " + entry.score +"<br/>";
}
myHTML.htmlText = myHTMLL;
}

AS3 - Navigating through array elements

Hello and thank you for your time. I have an as3 code which randomly picks 5 frames out of 7, no repeats.
var mygroup1:RadioButtonGroup = new RadioButtonGroup("group1");
q1a1.group = q1a2.group = q1a3.group = q1a4.group = q1a5.group = mygroup1;
var number_array:Array = [8158,8159,8160,8161,8162,8163,8164];
var final_array:Array = [];
var count_selected:int = 5;
var i:int;
for(i = 0; i < count_selected; i++)
{
if(number_array.length == 0)
break;
else
final_array.push(number_array.splice(Math.floor(Math.random() * number_array.length), 1)[0]);
}
var index = 0;
var currentQuestion:int = final_array[index];
var answers:Object = {
8158: 'B) 12',
8159: 'F) All of the above',
8160: 'A) True',
8161: 'B) False',
8162: 'C) 4',
8163: 'F) D and E',
8164: 'B) B'
};
var getAnswer = mygroup1.selection.label; //Getting the selection from RadioButtonGroup
submitBtn.addEventListener(MouseEvent.CLICK, onSubmitClicked);
function onSubmitClicked(e:MouseEvent):void {
var answer:String = getAnswer();
if (answer === answers[currentQuestion])
awardScore(currentQuestion);
++index;
currentQuestion = final_array[index];
gotoAndStop(final_array[index]);
}
and when you click on the "startBtn", it takes you to the first randomly generated frame(final_array[0]) and it's all great to start the process randomly.
Each of the next 7 frames has a submit button(b1,b2...b7) which keeps track of the score and submits the answer and also should go to the next randomly picked frame but only 5 times, following the remaining generated frames....gotoAndStop(final_array[1])...(final_array[2])....(final_array[3])....(final_array[4]).
b1.addEventListener(MouseEvent.CLICK, quizHandler1)
function quizHandler1(event:MouseEvent):void{
if(mygroup1.selection.label=="B) 12") {
count = count + 20;
scoreresult.text = (count).toString();
gotoAndStop(final_array[1]);
}
else{
gotoAndStop(final_array[1]);
}
}
My problem is...Since the user will only go to 5 randomly picked frames out of 7, how can I make sure all the buttons in all 7 frames will listen and follow the gotoAndStop(final_array[]); statement in the order of 5? Because at the end, 2 frames will be left out, and those two frames will change randomly in every roll. I hope I could explain my dilemma. Thank you again.
To do a quiz like yours, I think that you don't need to duplicate all content on every frame. You can put your questions in MovieClips ( or one MovieClip with many frames ) and then you can add it to your stage, and for your check box you can create it once and every time you can change just their values and labels. For buttons, you need only one button which will validate and check the current question and the go to the next one.
Take a look on this example :
var score:int;
var max_score:int;
const default_score:int = 20;
// create our questions list (7 questions) :
var questions_list:Object = {
// index : to identify our question
// movie_clip : the class name used for AS linkage
1: { index : 1, movie_clip : Question1, good_answer : 'css3', first_answer : 'html5', second_answer : 'jquery', third_answer : 'css3', score : default_score },
2: { index : 2, movie_clip : Question2, good_answer : 'html5', first_answer : 'html5', second_answer : 'less', third_answer : 'ruby', score : 50 },
3: { index : 3, movie_clip : Question3, good_answer : 'jquery', first_answer : 'ruby', second_answer : 'jquery', third_answer : 'css3', score : default_score },
4: { index : 4, movie_clip : Question4, good_answer : 'less', first_answer : 'less', second_answer : 'html5', third_answer : 'css3', score : 15 },
5: { index : 5, movie_clip : Question5, good_answer : 'nodejs', first_answer : 'python', second_answer : 'nodejs', third_answer : 'jquery', score : 10 },
6: { index : 6, movie_clip : Question6, good_answer : 'python', first_answer : 'css3', second_answer : 'html5', third_answer : 'python', score : default_score },
7: { index : 7, movie_clip : Question7, good_answer : 'ruby', first_answer : 'ruby', second_answer : 'html5', third_answer : 'less', score : default_score }
};
var enabled_questions:Array = [1, 2, 3, 4, 5, 6, 7];
var current_question:int = 0;
//----------------------------------------------------------------------------------------------------
// sprite that shows our questions
var questions_container:Sprite = new Sprite();
questions_container.x = questions_container.y = 20;
questions_container.visible = false;
addChild(questions_container);
var checks_group:RadioButtonGroup = new RadioButtonGroup('checks_group');
// sprite that contains our 3 check box
var checks_container:Sprite = new Sprite();
checks_container.visible = false;
checks_container.x = int(stage.stageWidth / 2);
checks_container.y = 50;
addChild(checks_container);
// create our check box, 3 buttons in my case
// the 4th one is used only to uncheck every time all check box
for(var i:int = 0; i < 4; i++)
{
var btn_check:RadioButton = new RadioButton();
if(i != 3){
btn_check.y = i * 30;
} else {
// our 4th check box is hidden
btn_check.visible = false;
}
btn_check.group = checks_group;
btn_check.name = 'btn_check' + i;
checks_container.addChild(btn_check);
}
// start button
var btn_start:Button = new Button();
btn_start.label = 'Start ! ';
btn_start.width = 180;
btn_start.height = 60;
btn_start.x = int((stage.stageWidth - btn_start.width)/2);
btn_start.y = int((stage.stageHeight - btn_start.height)/2) - 20;
btn_start.addEventListener(MouseEvent.CLICK, startQuiz);
addChild(btn_start);
// next button, to go to the next question
var btn_next:Button = new Button()
btn_next.label = 'Next >> ';
btn_next.width = 90;
btn_next.height = 30;
btn_next.visible = false;
btn_next.x = stage.stageWidth - btn_next.width - 10;
btn_next.y = stage.stageHeight - btn_next.height - 10;
btn_next.addEventListener(MouseEvent.CLICK, checkAnswer);
addChild(btn_next);
// a text field which will show the score and the current question number
var txt_score:TextField = new TextField();
txt_score.width = 200;
txt_score.height = 30;
txt_score.x = stage.stageWidth - txt_score.width;
txt_score.y = 10;
txt_score.visible = false;
txt_score.selectable = false;
addChild(txt_score);
//----------------------------------------------------------------------------------------------------
function startQuiz(e:MouseEvent):void
{
// here we will get only 5 questions
// I used a method from http://stackoverflow.com/questions/11980657/as3-random-array-randomize-array-actionscript-3 to shuffle the array
// and then I remove the last 2 elements from the array
enabled_questions = enabled_questions.sort(function(i:*,j:*){return(Math.random()<.5)?-1:1;}).slice(0,enabled_questions.length-2);
for(var i:int = 0; i < enabled_questions.length; i++){
var q_i:int = enabled_questions[i];
var q:Object = questions_list[q_i];
max_score += q.score;
// create our questions instance and hide it
// every question is an instance of a movieclip in our library
// we can alse use only one movieclip and then we can use its timeline to go from a question to another
var question = new (q.movie_clip);
question.index = q_i;
question.visible = false;
questions_container.addChild(question);
}
// hide the start button
e.target.visible = false;
// show other elements
questions_container.visible = checks_container.visible = btn_next.visible = txt_score.visible = true
// load the first question
loadQuestion(current_question);
}
// check the answer and update score
function checkAnswer(e:MouseEvent):void
{
var question:Object = questions_list[enabled_questions[current_question]];
if(question.good_answer == checks_group.selectedData){
// update the score
setScore(question.score);
}
if(current_question < enabled_questions.length - 1){
current_question ++;
loadQuestion(current_question);
} else {
e.target.x = e.target.y = 0;
e.target.enabled = false;
e.target.width = stage.stageWidth;
e.target.height = stage.stageHeight;
e.target.label = 'You have finished the quiz, your score is : ' + score;
checks_container.visible = questions_container.visible = txt_score.visible = false;
}
}
// load question (show it) and update our check box
function loadQuestion(index:int):void
{
var question:Object = questions_list[enabled_questions[index]];
for(var i:int = 0; i < checks_container.numChildren; i++){
if(checks_container.getChildAt(i) is RadioButton){
var btn:RadioButton = RadioButton(checks_container.getChildAt(i));
switch (btn.name){
case 'btn_check0' : btn.value = btn.label = question.first_answer; break;
case 'btn_check1' : btn.value = btn.label = question.second_answer; break;
case 'btn_check2' : btn.value = btn.label = question.third_answer; break;
case 'btn_check3' : btn.selected = true; break;
}
}
}
for( i=0; i < questions_container.numChildren; i++){
if(questions_container.getChildAt(i) is MovieClip){
var mc:MovieClip = MovieClip(questions_container.getChildAt(i));
mc.visible = mc.index == question.index;
}
}
// setScore is used here just to update the question number in the score text field
setScore();
}
// show the score and current question
function setScore(new_score:int = 0){
score += new_score;
txt_score.text = 'Score : ' + score.toString() + ' / ' + max_score.toString() + ', Question : ' + (current_question+1) + ' / ' + enabled_questions.length;
}
// icons used in this example by Jozef Krajčovič : https://www.iconfinder.com/Jozef89
This code gives you something like this :
You can also see it working here.
Of course this is just a simple example, you can improve and adapt it to your needs.
Hope that can help.
Sounds like you just need a single submit button that goes to the next frame. That way you don't have to worry about the order.
Some sample code to give you an idea how it might work
var index = 0;
var currentQuestion:int = final_array[index];
var answers:Object = {
8158: '12',
8159: '13'
//...etc.
};
submitBtn.addEventListener(MouseEvent.CLICK, onSubmitClicked);
function onSubmitClicked(e:MouseEvent):void {
var answer:String = getAnswer(); //get the user's answer
if (answer === answers[currentQuestion]) {
awardScore(currentQuestion);
++index;
currentQuestion = final_array[index];
gotoAndStop(final_array[index]);
}
}
The idea is to have all that logic in a single click handler, once clicked it will grab the users answer and check if it is correct, if it is then it goes on to the next question.

Add cookie / no-repeat function to random page refresh

I have been using this java code to call a random html page from a list of 49 on a set timer (or upon page refresh). I would like to convert it so that a cookie - or something else - saves the pages that have already been shown so that upon refresh the user always receives a new page, until the list is finished, at which point the cookie is emptied/deleted.
I found this code for a cookie image array. Could I use it with this? A variant of this also appears here. Apologies, my coding is pretty poor. Any advice appreciated:
<script type="text/javascript">
var sites = [
"name1.html",
"name2.html",
"name3.html",
"name...etc.html",
"name49.html",
]
$(document).ready(function() {
newPage();
});
function newPage()
{
setTimeout(newPage, 60000);
var min = 0;
var max = 48;
var num = Math.floor(Math.random() * (max - min + 1)) + min;
$('#target').attr('src',sites[num]);
}
</script>
var numSites = 49;
var seen = new Array(numSites);
$(document).ready(function() {
var cookie = unescape(getCookie("seen"));
seen = cookie ? cookie.split(',') : seen;
setTimeout(gotoNext, 60000);
});
function gotoNext() {
var num = getRandom();
var count = 0;
while (seen[num] == 1) {
num++;
if (num >= numSites) {
num = 0;
count++;
if (count > 1) {
resetSeen();
num = getRandom();
}
}
}
seen[num] = 1;
setCookie("seen", escape(seen.join(',')), 365);
window.location = "name" + num + ".html";
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length, c.length);
}
return "";
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function resetSeen() {
for (var i=0; i<numSites; i++) {
seen[i] = "";
}
}
function getRandom() {
return Math.ceil(Math.random() * numSites);
}
It looks like you're using jQuery so I'll recommend using a jquery plugin for managing cookies much more neatly.
Copy & paste the contents of this URL to a new js file on your server and include it after the jquery file: https://raw.githubusercontent.com/carhartl/jquery-cookie/master/jquery.cookie.js
Or you could possibly use the get/set cookie functions from the other answer you mention.
The main thing to remember is that the cookie is stored as a string so you'll be join()ing and split()ing the array.
The other thing to note is that because we want a random item from the items we haven't visited yet it's more efficient to keep track of those rather than the ones we have visited.
What this means is we always choose a random item from what's left instead of looping over everything and checking each time if we've been there already as that would get very inefficient.
var sites = [ 'name1.html', 'name2.html', 'name3.html', ...etc... ],
unvisited = sites.slice(0); // .slice(0) clones the array
// if the cookie has a value then make it into the unvisited array
if ( $.cookie( 'unvisited' ) )
unvisited = $.cookie( 'unvisited' ).split( ',' );
$(document).ready(function() {
newPage();
});
function newPage() {
setTimeout( newPage, 60000 );
// check if the unvisited array needs resetting
if ( unvisited.length == 0 ) {
unvisited = sites.slice(0);
$.removeCookie( 'unvisited' );
}
// get a new index from the unvisited array
var num = Math.floor( Math.random() * unvisited.length );
// remove the item from the array and save the cookie
var site = unvisited.splice( num, 1 )[ 0 ];
// save the unvisited array minus the site we just spliced out
$.cookie( 'unvisited', unvisited.join( ',' ) );
$( '#target' ).attr( 'src', site );
}

Resources