Why is JavaScript randomly adding '/1' to the end of URL bar? - javascript

So, me and a few friends are making a video game (text adventure) in JavaScript. In this game, you go around fighting monsters. It opens with a fight, but when you win, it randomly adds '/1' to the end of the URL. This is strange because window.location never appears in the program. Here is the code that is executed at the time of the problem:
function Places() {
location = 1
answer = prompt('Where do you go now? You have ' + totalGold + ' gold, and ' + hitPoints + ' health.', 'Town, Plains, Swamp, Menu').toUpperCase()
switch (answer) {
case 'TOWN':
if (aabeaDestroysTown === 0) {
alert('You walk into town, where there is a marketplace and an inn.')
InTown()
} else {
alert('As you near the outskirts of town, you notice the stream of people leaving town. Then you notice that the entire place is now just a gigantic blast crater. Somebody blew it up!!! You decide to investigate, and walk over to the stream of people.')
alert('When you reach the people, they all say this person named A\'Abea had just come to town and started fires all over, and then used some weird, magical powers to blow up Smatino.')
alert('You are sure this A\'Abea is the same as the one who you met in the swamp, and wish you had used some \'weird, magical powers\' to blow him up')
alert('You race back to the swamp, and see him from a distance. You can\'t, however, blow him up. There are too many vines in the way. So, you follow him. You see a large tower in the distance, and finally, after a few hours, reach it at night. You see A\'Abea enter, and then, as the gate is clanging down above him, you slide under it and manage to get in.')
inTower()
}
break;
etc. You only see the prompt() box for a split second, then it does the random addition.
Error Message:
/*
Exception: out of memory
*/
What is even stranger about this is that it seems to only do it when testing in Firefox.

It's because you're setting window.location to 1. Don't do that unless you want to update the page URL.
By default, variables are set on the global window object. If you'd like to set a local variable named location inside your function, use var location = 1.

Related

Frame rate independent exponential interpolation

I am creating a game.
I usually start with quick-and-dirty get-the-job-done code, and improve it later.
And precisely, I am trying to improve that.
Let's present the problem: the player controls an aircraft. When pressing a key, the aircraft rotates (a "pitch") and goes down (or up, depending on the key pressed).
When the player releases the key, the aircraft goes back to horizontal.
The maximum angle for the aircraft should be reached quickly, it's not a simulation. Think of Starfox.
The quick and dirty approach is as follows: each frame, I check if a relevant key is pressed.
The output of this step is a variable that contains either 0, -1 or +1 whether the aircraft should be horizontal, going down or going up.
Now, I do the following formula:
pitch = pitch*0.9 + maxAngle * turn * 0.1
turn is the variable obtained containing 0, -1 or +1.
This produces a nice effect. It's an interpolation, but not a linear one, which makes it more "fun" to watch.
Here is the problem: this formula doesn't contain the length of a frame. It's frame rate dependent.
I tried to extract the general formula. First, 0.9 and 0.1 are obviously what they are because they sum up to 1 (I didn't try to have one of them lesser than 0 and or one bigger than 2).
If I put that
a1=a0*x + b*(1-x)
I arrive at the general formula of
an = a0*(x^n) + b*(1-x)*(x^(n-1) + x^(n-2) + x^(n-3) + ... + 1 )
By assuming a certain frame length I could inject it into that, maybe, somehow, but I still don't know how to properly turn that into a function (especially this sum of x^n, I don't know how to factorize it).
The second problem is that, currently, the user can press and release the key as they like. By that, I mean by that the b in the equation can change (and the resolution I attempted does not take that into account).
So, this is the problem. In short, how to reverse engineer my own solution to inject the frame length in it so it becomes frame rate independent?
Please note that you can assume that the frame rate in the current program IS stable.
I am quite sure I am not the first one encountering such a problem. If you don't have a solution, hints are also welcome, of course.
Thanks

Infinite scroll make page number auto increase after first scroll

I am working in infinite load, when i am first scroll to the bottom, the next data load to page. But after the next data load to page, it makes another data to be load and it load when I'm not continue to scroll again.
for example, when i first scroll to bottom the URL change to tes.html?page=1, but after a few seconds it will change to tes.html?page=2, tes.html?page=3 and so on. How to make page number change in URL and load data based on page number when scroll again?
Heres' the code
$(document).ready(function () {
let articleText = document.querySelector(".article_ct .text");
let currentPage = 1;
let totalPage = 5;
function loadData(currentPage) {
fetch("index.json")
.then((response) => response.json())
.then((result) => {
let text = document.createElement("p");
text.style.marginBottom = "100px";
text.innerText = result[currentPage].text;
articleText.append(text);
history.pushState(null, null, `tes.html?page=${currentPage}`);
})
.catch((error) => console.log(error));
return true;
}
// LOAD DATA PERTAMA
fetch("index.json")
.then((response) => response.json())
.then((result) => {
let text = document.createElement("p");
text.style.marginBottom = "100px";
text.innerText = result[0].text;
articleText.append(text);
})
.catch((error) => console.log(error));
$(window).scroll(function () {
if (
$(this).scrollTop() >
articleText.offsetHeight + articleText.offsetTop + 100
) {
if (currentPage <= totalPage) {
$(".loader").css("display", "block");
loadData(currentPage);
currentPage++;
} else {
$(".loader").css("display", "none");
}
}
// if($(this).scrollTop() > (articleText.offsetTop + articleText.offsetHeight)) {
// console.log('tes')
// }
});
});
Heres the json data file
[
{
"text": "The box sat on the desk next to the computer. It had arrived earlier in the day and business had interrupted her opening it earlier. She didn't who had sent it and briefly wondered who it might have been. As she began to unwrap it, she had no idea that opening it would completely change her life. If you can imagine a furry humanoid seven feet tall, with the face of an intelligent gorilla and the braincase of a man, you'll have a rough idea of what they looked like -- except for their teeth. The canines would have fitted better in the face of a tiger, and showed at the corners of their wide, thin-lipped mouths, giving them an expression of ferocity. There were only two ways to get out of this mess if they all worked together. The problem was that neither was all that appealing. One would likely cause everyone a huge amount of physical pain while the other would likely end up with everyone in jail. In Sam's mind, there was only one thing to do. He threw everyone else under the bus and he secretly sprinted away leaving the others to take the fall without him."
},
{
"text": "April seriously wondered about her sleeping partner choices. She looked at her bed and what a mess it had become. How did she get to the point in her life where she had two dogs, three cats, and a raccoon sleeping with her every night? She patiently waited for his number to be called. She had no desire to be there, but her mom had insisted that she go. She's resisted at first, but over time she realized it was simply easier to appease her and go. Mom tended to be that way. She would keep insisting until you wore down and did what she wanted. So, here she sat, patiently waiting for her number to be called. Stranded. Yes, she was now the first person ever to land on Venus, but that was of little consequence. Her name would be read by millions in school as the first to land here, but that celebrity would never actually be seen by her. She looked at the control panel and knew there was nothing that would ever get it back into working order. She was the first and it was not clear th is would also be her last."
},
{
"text": "Should he write it down? That was the question running through his mind. He couldn't believe what had just happened and he knew nobody else would believe him as well. Even if he documented what had happened by writing it down, he still didn't believe anyone would still believe it. So the question remained. Was it be worth it to actually write it down? I inadvertently went to See's Candy last week (I was in the mall looking for phone repair), and as it turns out, See's Candy now charges a dollar -- a full dollar -- for even the simplest of their wee confection offerings. I bought two chocolate lollipops and two chocolate-caramel-almond things. The total cost was four-something. I mean, the candies were tasty and all, but let's be real: A Snickers bar is fifty cents. After this dollar-per-candy revelation, I may not find myself wandering dreamily back into a See's Candy any time soon."
},
{
"text": "It was a scrape that he hardly noticed. Sure, there was a bit of blood but it was minor compared to most of the other cuts and bruises he acquired on his adventures. There was no way he could know that the rock that produced the cut had alien genetic material on it that was now racing through his bloodstream. He felt perfectly normal and continued his adventure with no knowledge of what was about to happen to him. He sat across from her trying to imagine it was the first time. It wasn't. Had it been a hundred? It quite possibly could have been. Two hundred? Probably not. His mind wandered until he caught himself and again tried to imagine it was the first time. Benny was tired. Not the normal every day tired from a hard day o work. The exhausted type of tired where you're surprised your body can even move. All he wanted to do was sit in front of the TV, put his feet up on the coffee table, and drink a beer. The only issue was that he had forgotten where he lived."
},
{
"text": "It was a simple tip of the hat. Grace didn't think that anyone else besides her had even noticed it. It wasn't anything that the average person would notice, let alone remember at the end of the day. That's why it seemed so unbelievable that this little gesture would ultimately change the course of the world. She was aware that things could go wrong. In fact, she had trained her entire life in anticipation that things would go wrong one day. She had quiet confidence as she started to see that this was the day that all her training would be worthwhile and useful. At this point, she had no idea just how wrong everything would go that day. I checked in for the night at Out O The Way motel. What a bad choice that was. First I took a shower and a spider crawled out of the drain. Next, the towel rack fell down when I reached for the one small bath towel. This allowed the towel to fall halfway into the toilet. I tried to watch a movie, but the remote control was sticky and wouldn’t stop scrolling through the channels. I gave up for the night and crawled into bed. I stretched out my leg and felt something furry by my foot. Filled with fear, I reached down and to my surprise, I pulled out a raccoon skin pair of underwear. After my initial relief that it wasn’t alive, the image of a fat, ugly businessman wearing raccoon skin briefs filled my brain. I jumped out of the bed, threw my t"
}
]

Why does Google +1 record my mouse movements? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
This is only on pages with a Google +1 box on my website:
It seems to be firing off an event on every mouse move. Anyone know what it is doing? I searched on Google (perhaps I should try Bing for once on this one!) but no one seems to have written about it. Is it recording information about my visitors browsing habits? Is it some sort of CAPTCHA to detect human like behviour?
Example URL, press F12 in chrome, go to timeline and press record, then move your mouse around this page (it plus ones this question, don't worry):
https://plusone.google.com/u/0/_/+1/button?hl=en-US&jsh=r%3Bgc%2F22224365-adc8a19e#url=https://stackoverflow.com/questions/6667544/google-1-recording-mouse-move&size=tall&count=true&id=I1_1310488711647&parent=https://plusone.google.com/u/0/_/+1/button?hl=en-US&jsh=r%3Bgc%2F22224365-adc8a19e#url=https://stackoverflow.com/questions/6667544/google-1-recording-mouse-move&size=tall&count=true&id=I1_1310488711647
For what it's worth (I can see this is going to be a popular question), I don't think there is anything sinister behind it, it might even be a useless artifact/bug, but if it is doing some sort of tracking, well, it seems a little deceptive to me.
Google +1 privacy policy
http://www.google.com/intl/en/privacy/plusone/
Google +1 Button Privacy Policy
June 28, 2011
The Google Privacy Policy describes how we treat personal information
when you use Google’s products and services, including information
provided when you use the Google +1 button. In addition, the following
describes our additional privacy practices specific to your use of the
+1 button.
Information we collect and how it is shared
The Google +1 button is a way for you to share information publicly
with the world. The Google +1 button helps you and others receive
personalized content from Google and our partners. The fact that you
+1’d something will be recorded by Google, along with information about the page you were viewing when you clicked on the +1 button.
Your +1’s may appear to others as an annotation with your profile name
and photo in Google services (such as in search results or on your
Google Profile) or elsewhere on websites and ads on the Internet.
We will record information about your +1 activity in order to provide
you and other users with a better experience on Google services.
In order to use the Google +1 button, you need to have a public Google
Profile visible to the world, which at a minimum includes the name you
chose for the profile. That name will be used across Google services
and in some cases it may replace another name you’ve used when sharing
content under your Google Account. We may display your Google Profile
identity to people who have your email address or other identifying
information.
Use of the collected information
In addition to the above-described uses, the information you provide
to us is used subject to our main Google Privacy Policy.
We may share aggregate statistics related to users’ +1 activity with
the public, our users, and partners, such as publishers, advertisers,
or connected sites. For example, we may tell a publisher that “10% of
the people who +1’d this page are in Tacoma, Washington.”
Your choices
You may view the list of items you have +1’d on the +1 tab on your
Profile. You can remove individual items from that list.
You may opt out of seeing +1 recommendations on third-party websites
(including on ads on third-party sites) from people you know.
We will store data (such as your recent +1’s) locally in your browser.
You may be able to access and clear this information in your browser
settings.
More information
Google adheres to the U.S. Safe Harbor privacy principles. For more
information about the Safe Harbor framework or our registration, see
the Department of Commerce’s website.
It appears to be seeding a random number generator with your mouse movements.
The mouse move handler itself does something along the lines of the following:
var b = ((event.X << 16) + event.Y) * (new Date().getTime() % 1000000);
c = c * b % d;
if (previousMouseMoveHandler) previousMouseMoveHandler.call(arguments);
d is (screen.width * screen.width + screen.height) * 1000000, and c is a variable that starts out as 1.
All of this is wrapped in the scope of an anonymous function, which itself is immediately evaluated to return a function that is assigned to a property named "random". That returned function looks something like this:
var b = c;
b += parseInt(hash.substr(0,20), 16);
hash = MD5(hash);
return b / (d + Math.pow(16, 20));
hash, BTW, is a variable that starts out as the MD5 hash of the page's cookies, location, the new Date().getTime(), and Math.random().
(Note, of course, that Google may change the script returned at any time and hence invalidate this analysis)
The actual code that is being executed is derived from the Shindig code found here:
http://svn.apache.org/repos/asf/shindig/trunk/features/src/main/javascript/features/shindig.random/random.js
A secure random number is needed to ensure that the secure postMessage channel created here cannot be compromised by scripts on the page to execute arbitrary actions.
Here's an article that explains why using Math.random() is bad:
http://baagoe.com/en/RandomMusings/javascript/
If you can get your script loaded first, you could hook addEventListener and log everyone who is setting addEventListener and see who's doing it and then, by looking at the relevant code, see what they're doing.
Put this in place before the Google code loads:
var oldListener = document.addEventListener;
document.addEventListener = function(type, listener, capture) {
if (type == "mousedown" || type == "mouseup" || type == "mousemove") {
console.log("type=" + type + " listener=" + listener.toString().slice(0, 80));
}
return (oldListener.apply(this, arguments));
}
To see what was listening to window.onmousemove, you'd have to do it afterwards because it's just a variable assignment, not a function that you can intercept. So sometimes after the initialization code of the page runs, you would do this to log what was hooked up to it:
if (window.onmousemove) {
console.log(window.onmousemove.toString().slice(0,80));
}
In the uncluttered code as of Jul 22, you'll notice the onmousemove is part of the Gb.random class:
Gb.random = function () {
function a(a) {
var b = Jb();
b.update(a);
return b.ib()
}
var b = la.random(),
c = 1,
d = (screen[za] * screen[za] + screen[J]) * 1E6,
e = i.onmousemove || Db();
i.onmousemove = function (a) {
if (i.event) a = i.event;
var b = a.screenX + a.clientX << 16;
b += a.screenY + a.clientY;
b *= (new Date)[Ta]() % 1E6;
c = c * b % d;
return e[G](i, ka[x][Aa][G](arguments))
};
var f = a(k.cookie + "|" + k[B] + "|" + (new Date)[Ta]() + "|" + b);
return function () {
var b = c;
b += ia(f[cb](0, 20), 16);
f = a(f);
return b / (d + la.pow(16, 20))
}
}();
It's multiplying sum of x and y by 2^16 using bitshift, then adding some other dimensions and multiplying all this by time in milliseconds mod 1000000. This definitely looks like a randomizing algorithm.
I'm not sure why the page would need something like this, perhaps it's using a cookie, preventing automated +1 clicking? When you click the "+1" the login screen that pops up appears to have a random number appended as the hash, the url ends with "&hl=en-US#RANDOMNUMBER"
I bet you its "In-Page Analytics" Beta. Making a cursor and click heat-map.
I think that the paper by Guo and Agichtein from CHI 2010 http://www.mathcs.emory.edu/~qguo3/wip287-guo11.pdf can provide further ideas on why Google is doing that.
Apparently mouse movements is a rough proxy for eye movement and allows people to approximate eye tracking results.
They probably use it to measure how quickly users move from one UI item to another, how often clicks miss etc.
I normally have a deeply cynical view of invasive features but I don't think this is a privacy risk. It's shocking because it's so unusually fine-grained, but it's not very revealing. Does your mouse movement encode bank details? Porn?
Google and the like have plenty of high-quality data to track you with. Mouse coordinates have very limited application.
To go off-topic a bit:
To an extent, the more data you collect about people the more problems you have. I hear (from Schneier and the like) that intelligence agencies are suffering from the huge numbers of false positives triggered by their ever-accelerating data aquisition -- the signal-to-noise ratio is abysmal. I find this somewhat amusing.
It's impossible to tell for certain, what Google does with this mouse movement data. As you can see yourself, it's not returning loads and loads of information back to the server, therefore, nothing to worry about.
The first is probably a generic event handler. Reason why I think that is if you read the source, you can see that on the line before there is throw Error("Invalid listener argument"); and next or one after the next there's throw Error("Invalid event type"). Since the fired line is in between these two (event related) exceptions, I'm pretty sure that it's some kind of an event handler. Using debugger, it doesn't do anything really (doesn't jump to some other function) so it seems that it's there for future implementation.
The second function is identical to the first one. Since it's gTalk's I suppose it updates your status (away, online etc).
The third seems to be content updater or something similar, since you can see strings like cacheTimeout etc scattered around it.
My 2 cents.
this is really beyond from far fetched, but here it goes anyway ...
it revolves around the type of trajectory & curvature of a mousemovement from a start point towards different attractors take i.e. 2 items/links on a page.
http://sciencestage.com/v/26698/dynamics-and-embodiment-in-language-comprehension.html
in short, if you put two competing links/buttons and analyze the trajectory towards one of those links, you can deduce a pattern or how you reached the decision to click only 1 of those links (see vid around 13:00)

Detect loops in computer player in a cardgame

A while ago I created a small cardgame web app for fun. The player plays against the computer and mostly it works fine. Sometimes though the computer player gets into a loop, the point of the game is to lose all your cards and if you don't have a card to play you take the pile. Sometimes the computer plays x,y,z, takes the pile, plays x,yz, takes the pile etc.
I keep track of the moves I've made, so at any point I have an array that looks something like : [C2,D5,H2,S4,C5,H2,S4,C5,H2,S4,C5]
In this case I can see that I've gotten into a loop of playing H2,S4,C5, then taking the pile and then repeating.
So, the generalized problem is, what's the best way to detect repeating patterns in a list? I could probably whip something up using a simple for loop, trying to find the card I'm about to play and if I find that in position x then I could check whether the pattern from x to n repeats at position x-(n-x) to x, but this seems like the kind of problem that could have a nice algorithm for it. How would you code this given the following function signature:
function findLoops(previousMoves, nextMove, maxPatternLength) {
//Return [loopLength, loopCount] or null if there are no loops
}
p.s. this is not a homework assignment, the game exists and is at http://www.idiot-cardgame.com if anyone is interested :)
First the general question: Your suggested method
trying to find the card I'm about to play and if I find that in position x then I could check whether the pattern from x to n repeats at position x-(n-x) to x,
looks really good. I would suggest basically the same. It is O(n) and needs a fixed amount of storage, and is simple: what else would you wish for?
Second: You can check for repetition in games generally if you keep a hash table of all previous game states (complete state, nothing left out). Everytime you reach a new state look up if it is in the hashtable, if its in it: you game state is looping.
In Javascript you have builtin hastables so this is very easy to do with something similar like this:
new_state = next_move(old_state);
new_encoded_state = encode(new_state); // make it into a string
if (allstates[new_encoded_state]) {
// we are looping!
} else {
allstates[new_encoded_state] = 1;
// no looping
}
The variable allstates is not an Array but of type Object. You can have array like access with strings and this uses the Object as hastable.

How can I make my counter look less fake?

I'm using this bit of code to display the number of users on a site.
My customer is complaining it looks fake. Any suggestions?
var visitors = 187584;
var updateVisitors = function()
{
visitors++;
var vs = visitors.toString(),
i = Math.floor(vs.length / 3),
l = vs.length % 3;
while (i-->0) if (!(l==0&&i==0))
vs = vs.slice(0,i*3+l)
+ ','
+ vs.slice(i*3+l);
$('#count').text(vs);
setTimeout(updateVisitors, Math.random()*2000);
};
setTimeout(updateVisitors, Math.random()*2000);
Edited:
alt text http://img695.imageshack.us/img695/4268/reachdevs2.png
Screenshot-Advertise - Stack Overflow - Chromium http://img130.imageshack.us/img130/8083/screenshotadvertisestac.png
http://inedomedia.com/stackoverflow.aspx
Everyone knows JS counters are fake, don't bother trying to make it look "less fake", bother making a real one.
If you don't have enough visitors to show around, just don't use a counter, they're so 90's.
Warning: Attempted Humour
Did he ask for a giant splash page to go along with the fake real-time visitor counter? How about some nice "Netscape Now!" button logos and blinking text? Here are some really cool "under construction" animated gifs you can use too.
http://www.animatedgif.net/underconstruction/construction.shtml
-Oisin
I'm guessing it looks fake because every time you load the page it starts at the same number and counts upwards?
Take a look at the javascript that tells you how many megabytes of email storage you get with a Gmail account. I think it bases the starting number on the date/time, so that if you load a page, watch it count up, and then load it again, it won't reload with a smaller number.
Be honest though... it is fake right? You aren't showing precisely how many users there are and updating it live as new users create accounts. The goal then is to make sure it is somewhat close to reality. Hopefully the rate at which the number increases in your script is based on past new-user subscription rates.
make the interval parameter of the setInterval random as well ... it will look more real as it will randomly increment the random numbers :)

Categories

Resources