Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

v1nce posted:

it's probably not that hard to make this native java script:
code:
var elements = {}; 
$('*').each(function() { 
	elements[this.tagName] = elements[this.tagName]+1 || 1; 
}); 
console.log(elements);

JavaScript code:
var elements = {}; 
Array.prototype.forEach.call(document.querySelectorAll('*'), function (elem) {
	elements[elem.tagName] = elements[elem.tagName]+1 || 1;
});
console.log(elements);

Adbot
ADBOT LOVES YOU

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

huhu posted:

Just looked up what a parser was... don't think that's what I'm doing.

My goal was to take this:

code:
<html>
     <head>
          <title>ss</title>
     </head>
     <body>
          <h1>sdfsdf</h1>
          <p>sdfsdf</p>
     </body>
</html>
Turn it into an
code:
array = [body,h1,head,html] 
Compare that array to an array with all html elements.

The end result would be a webapp that interacted with the Mozilla Developer Network that kept track of which HTML tags you've used before, which you haven't used yet, and stats about usage of each. I was going to add support for attributes and maybe some other tools. Its goal was to help as a sort of reference for me, and maybe others, as I learn HTML.

Just to be explicit, read this (http://stackoverflow.com/questions/8227612/how-to-create-document-objects-with-javascript), look at the response than mentions var doc = (new DOMParser).parseFromString(markup, mime_type), and then use vince/wheany's JQuery stuff to populate the array, rather than looking at the HTML input as a string yourself. Make the browser do the work.

Bruegels Fuckbooks fucked around with this message at 13:20 on May 11, 2015

v1nce
Sep 19, 2004

Plant your brassicas in may and cover them in mulch.

Wheany posted:

code and stuff
:allears:

You know that thing I told you not to do? Here's how to do it:
code:
var markup = document.documentElement.innerHTML; 
var reg = new RegExp(/<(?!!)\s*([\w]+)[^>]*\/?\s*>/g); 
var usages = {}; 
while(result = reg.exec(markup)) { 
	usages[result[1]] = usages[result[1]]+1 || 1; 
}
The main difference is the regex method ignores HTML comments and picks up everything that even looks remotely like an element.

I am an enabler :eng99:

Bruegels Fuckbooks posted:

Much better advice
Yes do that. I only did the regex because I thought it would be a fun exercise.

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

v1nce posted:

The main difference is the regex method ignores HTML comments and picks up everything that even looks remotely like an element.

I am an enabler :eng99:
Looked at that quickly and was like:

RobertKerans
Aug 25, 2006

There is a heppy lend
Fur, fur aw-a-a-ay.
could do
JavaScript code:
function mapNodes(startContext = document.body) {
  return Array.from(startContext.getElementsByTagName("*"))
              .map(v => v.tagName)
}
and also could get a tree representation
JavaScript code:
function mapNodeTree(startContext = document.body) {
  return Array.from(startContext.children)
              .map(function(v) {
                   return { node: v.tagName,
                            children: v.hasChildNodes() ? mapNodeTree(v) : [] }
              })
}
so
JavaScript code:
// given document:
// <!DOCTYPE html>
// <html>
//   <head>
//     <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
//     <title>Test Page</title>
//   </head>
//   <body>
//     <header>
//       <h1>Test Page</h1>
//     </header>
//     <main>
//       <ul>
//         <li>List item 1.</li>
//         <li>List item 2.</li>
//         <li>List item 3.</li>
//       </ul>
//     </main>
//     <footer>
//       <p>Some footer info.</p>
//     </footer>
//   </body>
// </html>

// probably should just be a class with methods, but this is just rough, so:

// all unique node names in defined context:
$ mapNodes().filter((node, index, arr) => arr.indexOf(node) == index );
// #=> [ "HEADER", "H1", "MAIN", "UL", "LI", "FOOTER", "P" ]

// set of { nodeName: numberOfNodesPresentInContext, ... }:
$ mapNodes().reduce(function(map, node) {  map[node] = ++map[node] || 1;  return map;  }, {});
// #=> { HEADER: 1, H1: 1, MAIN: 1, UL: 1, LI: 3, FOOTER: 1, P: 1 }

// tree in context:
$ mapNodeTree(document.body.children[1]);
// #=> [{node:"UL",children:[{node:"LI",children:[]},
//			     {node:"LI",children:[]},
//			     {node:"LI",children:[]}]
//     }]
XPath works ok as well if you're in a position to ignore IE

RobertKerans fucked around with this message at 15:26 on May 11, 2015

huhu
Feb 24, 2006
...at least I know a bit more about strings. Only spent like 7 hours in the wrong direction but what do you really learn if you get it right the first time? Thanks for the suggestions. They do seem much better uses.

fuf
Sep 12, 2004

haha
What's a good parallax scrolling plugin?

I've tried
https://github.com/Prinzhorn/skrollr (couldn't get scrolling to work on mobile)
and
https://github.com/markdalgleish/stellar.js (looks bad on mobile and is buggy)

Kobayashi
Aug 13, 2004

by Nyc_Tattoo
"Looks bad and is buggy" should be the warning label on any library that tries to hijack scroll behavior. Just say no.

fuf
Sep 12, 2004

haha
Do parallax background images really count as hijacking scroll behaviour?

They are kind of a design necessity at this point so I definitely need to come up with something.

necrotic
Aug 2, 2005
I owe my brother big time for this!
If they are just animated constantly its not scroll hijacking. That crap people do with parallax backgrounds on scroll is janky as gently caress.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

huhu posted:

...at least I know a bit more about strings. Only spent like 7 hours in the wrong direction but what do you really learn if you get it right the first time? Thanks for the suggestions. They do seem much better uses.

Better 7 hours than 7 months, right?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

fuf posted:

Do parallax background images really count as hijacking scroll behaviour?

They are kind of a design necessity at this point so I definitely need to come up with something.

Legible type is a "design necessity". Faux parallax stuff is distinctly not.

kedo
Nov 27, 2007

Does attaching crap like parallax to scroll events actually work on mobile these days? Last time I tried to do something similar it was a mess because iOS wouldn't fire scroll events until after the user completed a scroll.

Kobayashi
Aug 13, 2004

by Nyc_Tattoo
As of iOS 7 or iOS 8, scroll events actually work. It's been a huge boon for mobile prototyping.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
Scroll events work but gently caress that noise, because they don't work on momentum (and they're a poo poo show in general on mobile). Use CSS and degrade gracefully: http://keithclark.co.uk/articles/pure-css-parallax-websites/

Maluco Marinero fucked around with this message at 23:37 on May 11, 2015

WrathOfBlade
May 30, 2011

Let's say I have a conditional that I'm parsing from a string, such as -

code:
(inventory.sword.owned && inventory.sword.sharpened) || quests.sword == 'complete'
- and what I want to do is, as part of a gulp operation, convert this statement into a data structure that I can store in JSON and evaluate later. Any existing libraries that could help me here? Even just algorithms? This seems like a problem I shouldn't waste too much original thought on but I kinda can't describe it well enough to look up a solution.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
So you're basically just wanting to store the string in some form that you can evaluate later? Is there a reason you have to parse it now instead of just storing it as a string and then evaluating the string later?

WrathOfBlade
May 30, 2011

Not particularly, but I'll still need to parse it and evaluate it at some point. Preferably without the use of eval.

(E. Also don't take the object paths literally here, I'll have logic to fetch those values, the issue is parsing the Boolean logic to perform on them)

WrathOfBlade fucked around with this message at 17:03 on May 13, 2015

necrotic
Aug 2, 2005
I owe my brother big time for this!

WrathOfBlade posted:

Not particularly, but I'll still need to parse it and evaluate it at some point. Preferably without the use of eval.

(E. Also don't take the object paths literally here, I'll have logic to fetch those values, the issue is parsing the Boolean logic to perform on them)

Is it always going to be groups of AND separated by OR conditions? So (first) || (second) || (third)...? If that's the case it could be pretty straightforward:

code:
{
  "sword_get": [
    {"inventory.sword.owned": true, "inventory.sword.sharpened": true},
    {"quests.sword": "complete"}
  ]
}
You'd likely want to cache the "parsing" somehow.

Alternatively, while this is not a good solution, if you need more complex conditions you could simply store them as strings and eval them :)

darthbob88
Oct 13, 2011

YOSPOS
Goddammit. I've got a problem that should be impossible. When I try to set a breakpoint in 4TellBoost.js on http://www.eabco.net/Ruger-1022-Scope-Mount--Precision-Machined-Weaver-Style-Base_p_14362.html, viewing in Firefox, the breakpoint just jumps to the bottom of the script. I've tested it on other scripts, and it appears to be a problem only with certain scripts, but I can't find any pattern. jQuery.min.js comes from their servers and will let me place a breakpoint anywhere, analytics.js just sends breakpoints to the bottom of the script, but all the Facebook scripts work fine. My boss thought it might be because of this, but that doesn't explain the issues with analytics.js, which has no comments. Is there any better explanation, or should I get my computer exorcised?

Anony Mouse
Jan 30, 2005

A name means nothing on the battlefield. After a week, no one has a name.
Lipstick Apathy
I'm trying to create a page where users can log in with their tumblr account and fill out a form to post to their blog.

I'm using hello.js with the tumblr module.

I've modified the tumblr module demo and everything seems to be working in terms of logging in and authenticating. However, I'm unable to convince the API to let me use any OAUTH-restricted POST commands. GET commands, such as retrieving a user's followed blogs, work fine. But if I try something simple such as user/follow to follow a new blog, I get a "401 Not Authorized" response.

What could be causing OAUTH restricted GET commands to be working fine, but POST does not?

You can see my testing code live at http://www.jereddanielson.com/testing/tumblr/hello.js-master/demos/tumblr.html

Below is the pertinent javascript. I'm using the OAUTH proxy at https://auth-server.herokuapp.com/

code:
function login(network){
	hello( network ).login({scope: 'publish_actions, publish, post, post_actions, follow, follow_actions'}).then( function(r){
		// Get followed blogs
		hello(network).api({path: '/user/following', method: "get"}).then(function(p){
			console.log(p);
			console.log("Tried to retrieve followed blogs. Response status: " + p.meta.status + " " + p.meta.msg);
		});
		// Try to follow a blog
		hello(network).api({path: '/user/follow', method: "post", data: {url: "daily-fractal.tumblr.com"}}).then(function(p){
			console.log(p);
			console.log("Tried to follow a blog. Response status: " + p.meta.status + " " + p.meta.msg);
		});
	}, function(e){
		console.error(e);
	});
}

hello.init({
	'tumblr' : "bQpjOrKgIu9pWVann1HVOAoW6gOGNoSpcMXIpwjNqghUmkwvgt"
},
{
	redirect_uri:'../redirect.html',
	oauth_proxy: "https://auth-server.herokuapp.com/proxy"
});
Any ideas?

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
I asked a similar question before, but how are you supposed to develop/debug a user script in the year 2015?

As far as I can tell, Greasemonkey does not expose the source to at least Firefox's native developer tools in any way, so you can't set breakpoints and step through the code.

I tried doing it in Chrome and it wouldn't even let me run the file because it was not installed from the web store. I couldn't find the source file anywhere in the developer tools even when using Tampermonkey.

So back to Opera 12 I went and it highlighted exactly where a syntax error that was preventing the file from running was.

lunar detritus
May 6, 2009


I'm stuck in something that's probably easy but my brain is broken and doesn't like recursion.

I need to convert an array of objects to an nested object, like this:

JavaScript code:
var array = [
	{'title': 'Title 1', property: 1 },
	{'title': 'Title 2', property: 2 },
	{'title': 'Title 3', property: 3 }
];
JavaScript code:
var objectNeeded = {
	"Title 1": {
		property: 1,
		children: {
			"Title 2" : {
				property: 2,
				children: {
					"Title 3" : {
						property: 3,
					}
				}				
			}
		}
	}
};
Any ideas?

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.

gmq posted:

I'm stuck in something that's probably easy but my brain is broken and doesn't like recursion.

I need to convert an array of objects to an nested object, like this:

JavaScript code:
var array = [
	{'title': 'Title 1', property: 1 },
	{'title': 'Title 2', property: 2 },
	{'title': 'Title 3', property: 3 }
];
JavaScript code:
var objectNeeded = {
	"Title 1": {
		property: 1,
		children: {
			"Title 2" : {
				property: 2,
				children: {
					"Title 3" : {
						property: 3,
					}
				}				
			}
		}
	}
};
Any ideas?

Does you have to read properties dynamically or will there be a 'defined type'?

lunar detritus
May 6, 2009


Newf posted:

Does you have to read properties dynamically or will there be a 'defined type'?

In the future it'll be dynamic but right now they all use the same.

Kobayashi
Aug 13, 2004

by Nyc_Tattoo
It bothers me that superscript-2 (²) is not a valid Javascript character. I'm doing some basic statistics and want to provide an API with correct notation such as σ/s for standard deviation (ok!) and and σ²/s² for variance (not ok). :sigh:

necrotic
Aug 2, 2005
I owe my brother big time for this!
Something like this should work with a fixed schema:

JavaScript code:
function createTree(arr) {
    var root;

    arr.reduce(function(prev, el, i) {
        var cont = {},
            node = {property: el.property};

        cont[el.title] = node;
        if (i > 0) prev.children = cont;
        else root = cont;
        
        return node;
    }, {});
    
    return root;
}
Making it work with an arbitrary list of objects would simply require looping through el's keys and skipping the title.

lunar detritus
May 6, 2009


necrotic posted:

Something like this should work with a fixed schema:

JavaScript code:
function createTree(arr) {
    var root;

    arr.reduce(function(prev, el, i) {
        var cont = {},
            node = {property: el.property};

        cont[el.title] = node;
        if (i > 0) prev.children = cont;
        else root = cont;
        
        return node;
    }, {});
    
    return root;
}
Making it work with an arbitrary list of objects would simply require looping through el's keys and skipping the title.

You're my hero, I knew reduce would work but I kept hitting a brick wall while trying to do it.

huhu
Feb 24, 2006
Anyone have any suggestions for a good tool to learn regular expressions? Everything I've found so far just seems to throw it all at you at once and it's a bit overwhelming. Maybe a bunch of small steps where there are exercises and such?

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Friedl's book is still what I recommend.

WrathOfBlade
May 30, 2011

huhu posted:

Anyone have any suggestions for a good tool to learn regular expressions? Everything I've found so far just seems to throw it all at you at once and it's a bit overwhelming. Maybe a bunch of small steps where there are exercises and such?
Not sure if it's what you're looking for, but I learned a lot by screwing around in rubular and seeing what worked.

(Also for the record, the solution I turned out to be looking for earlier was a variation of Shunting-yard algorithm.)

v1nce
Sep 19, 2004

Plant your brassicas in may and cover them in mulch.

huhu posted:

Anyone have any suggestions for a good tool to learn regular expressions? Everything I've found so far just seems to throw it all at you at once and it's a bit overwhelming. Maybe a bunch of small steps where there are exercises and such?

This guide seems fairly direct, and doesn't miss out a ton of useful stuff like lookaheads:
http://okeschool.com/tutorial/2392/regex/regex-basics/introduction.html

regex101 is a great tool for explaining what's going on. I suggest you combine it with the above tutorials:
https://regex101.com/

Be aware that you can only learn regex syntax like you can learn a programming language. Actually parsing complex regex in your head isn't something you should expect to be able to do, and don't be surprised if you have to re-learn the regex syntax the first few times you use it.

Also, regular-expressions.info is an example of how make documentation more complicated and misleading than the thing you're explaining. Avoid this massive piece of poo poo.

huhu
Feb 24, 2006

WrathOfBlade posted:

Not sure if it's what you're looking for, but I learned a lot by screwing around in rubular and seeing what worked.

(Also for the record, the solution I turned out to be looking for earlier was a variation of Shunting-yard algorithm.)

That looks pretty interesting, thanks.I decided to play around with it and within 5 minutes I managed to figure this out:
code:
           $("#removeQuotesCleanArray").click(function(event){
               var htmlInput = $('#htmlInput').val();
               var myArray = htmlInput.match(/[<][!a-zA-z-]+/g);
               console.log(myArray);
          });
While not perfect I can't believe how much more quickly I was able to type that out than my previous code. :suicide: I'll probably end up using that JS mentioned earlier, except I still don't fully understand it... one day.

Edit:

v1nce posted:

This guide seems fairly direct, and doesn't miss out a ton of useful stuff like lookaheads:
http://okeschool.com/tutorial/2392/regex/regex-basics/introduction.html

regex101 is a great tool for explaining what's going on. I suggest you combine it with the above tutorials:
https://regex101.com/

Be aware that you can only learn regex syntax like you can learn a programming language. Actually parsing complex regex in your head isn't something you should expect to be able to do, and don't be surprised if you have to re-learn the regex syntax the first few times you use it.

Also, regular-expressions.info is an example of how make documentation more complicated and misleading than the thing you're explaining. Avoid this massive piece of poo poo.
I'll take a look at this as well, thanks.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

huhu posted:

Anyone have any suggestions for a good tool to learn regular expressions?

http://www.weitz.de/regex-coach/

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Wheany posted:

I asked a similar question before, but how are you supposed to develop/debug a user script in the year 2015?

As far as I can tell, Greasemonkey does not expose the source to at least Firefox's native developer tools in any way, so you can't set breakpoints and step through the code.

I tried doing it in Chrome and it wouldn't even let me run the file because it was not installed from the web store. I couldn't find the source file anywhere in the developer tools even when using Tampermonkey.

So back to Opera 12 I went and it highlighted exactly where a syntax error that was preventing the file from running was.

Did you have Chrome in developer mode? https://developer.chrome.com/extensions/faq#faq-dev-01 I thought it was supposed to let you install/enable and debug user extensions in that mode. Dunno if that'll enable Tampermonkey debugging, but it might be worth a shot.

also Opera 12 supremacy

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Munkeymon posted:

also Opera 12 supremacy
Sure, but it doesn't support poo poo like Array.from, requestAnimationFrame and MutationObserver, all of which I used in this script. The first two I could circumvent with Array.prototype.whatever.call() and setTimeout(,0), but the last bit I just had to comment out. :(

It's so loving dumb that Chrome says that "you might have been tricked into installing this", or whatever, but there is no "no I was not, I just wrote the drat thing myself" button. Well except maybe the developer mode, maybe.

e: The developer mode lets you open a directory that has the same structure as a Chrome extension. It does not enable you to just pick a .user.js file.

Wheany fucked around with this message at 16:00 on May 15, 2015

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Wheany posted:

It's so loving dumb that Chrome says that "you might have been tricked into installing this", or whatever, but there is no "no I was not, I just wrote the drat thing myself" button. Well except maybe the developer mode, maybe.

e: The developer mode lets you open a directory that has the same structure as a Chrome extension. It does not enable you to just pick a .user.js file.

Will it let you debug a script loaded via Tampermonkey, though? Seems like a not-unlikely side effect.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Munkeymon posted:

Will it let you debug a script loaded via Tampermonkey, though? Seems like a not-unlikely side effect.

Not in a way I can figure out. I tried putting a debugger statement in the script and it did nothing.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Wheany posted:

Not in a way I can figure out. I tried putting a debugger statement in the script and it did nothing.

I've debugged tampermonkey scripts. I think I had to turn on some setting in tampermonkey that inserted a breakpoint at script start, and then activate breakpoints from there.

Adbot
ADBOT LOVES YOU

Depressing Box
Jun 27, 2010

Half-price sideshow.

Subjunctive posted:

I've debugged tampermonkey scripts. I think I had to turn on some setting in tampermonkey that inserted a breakpoint at script start, and then activate breakpoints from there.

Is this it?

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply