I have been working on a project that dynamically creates a javascript file using ASP.NET which is called from another site.
This jquery javascript file appends a div and fills it with a rather large HTML segment and in order to do that I need to turn the segment into a string like so:
$(document).ready(function(){
var html = "Giving this magazine such a lofty epithet may seem a bit presumptuous, but for a non scientifically trained outsider this magazine offers a fresh and challenging look at the fast paced world of science that doesn't shy away from humor and the use of terms and ideas that may require its readers to go online and define a term. And in some cases it may inspire the reader to pick up a book on science by such greats as Hawking and Greene in order to better grasp some of the concepts dealing with time, space and atoms. This magazine isn't dumbed down. It includes well placed and efficient illustrations to help explain some of the more abstract points. It is not designed in the way popular magazinea are, in so much as they only touch upon a topic in the simplest manner and then move on before the audience is lost. Yet this magazine keeps the attention of the reader by combining explanatory notes that help people with no background knowledge have some grasp of the topic and by using humor and well written articles to clearly make their points. <br />For a magazine with a serious and well researched list of topics having small cartoons the likes of the New Yorker shows how comfortable this magazine is with itself. From the moment I picked up this magazine for the first time I felt like every word I read mattered and was worth my time to read. (Not true of many other magazines) American Scientist may not have the audience of Discover or National Geographic, nor is it as accessible as said titles, but for those with a true interest in science willing to challenge themselves and commit to real learning this magazine may be a perfect fit. At $4.95 it is certainly worth it to pick a copy on the news stand and try it out."
$("#divname").append(html);
});
As you can see the segment will be pretty large and I have no way of knowing how big as it is generated dynamically from my database depending on the reviewID which is defined by the user in their request.
The html to be inserted into the div is a list of reviews and is generated using asp.net MVC by a repeater which loops through a list. (if that helps give you an idea of what I am doing).
Is there any way to turn this large segment into one string which can be inserted into the append script?
Thank You
Cross domain jquery json
http://docs.jquery.com/Release:jQuery_1.2/Ajax#Cross-Domain_getJSON_.28using_JSONP.29
Some ideas:
You can replace new lines with spaces and create a huge line. There shouldn't be a problem with it.
Use string concatenation. Split the string and lines and do:
var html = line1 +
line2 +
...
linen;
Make an Ajax call to fill the div:
$("#divname").load(service_url);
You need to create a service that will return the string.
In my opinion the 3rd option is better than the other ones.
Correct me if i'm wrong but i think everything between the starting and ending quotation marks would be considered part of that string no matter how many lines it has. Unless your string has got any quotation marks in itself, in which case it'll be better to do the equivalent of php's addslashes() function in ASP on your string, which should add a \ before all the " marks in the string.
Another idea can be to use Json to encode/decode the string.
i don't see what's wrong with just generating one big-ass long single-line string and appending it just like you are doing. period. done. Fancier isn't going to gain you anything.
Hide it else where on the page and populate the div with it when you need it?
Related
Hello,
I'm relatively new to the programming world and I was wondering how I would go about creating the following for a website I'm designing. I will use a random example as to not give my application away, but the process should be the same. I apologize ahead of time for the unrealistic values:
Say a civil engineer wants to come onto my website and figure out the mechanical stress at certain points on the Eiffel tower, lets say on the corner of the first/second observation deck (see Image). To make this more general, they want to vary values such as the height and base width of the tower to see how that affects the mechanical stress at those points.
Now, I can make the algorithm for calculating those stress values. My question is, how would a programmer go about creating this dynamic figure, such that the 'stress values' are shown on the image at distinct locations, and they change based off of the values of the user inputs + algorithm? My thoughts are the following:
Use HTML/CSS to place the images and design the webpage
Use JavaScript to take inputs, run the algorithm and calculate outputs. This would also make the dynamic changes on the image.
I have zero experience with JavaScript (I'm okay with HTML/CSS as I have built my own website before). I guess I'm hoping to be pointed in the right direction before I go off and start learning the wrong language for this application.
Bonus Challenge
While they're doing this, it would be nice to see a visual representation of the Eiffel tower change when the height and base area are changed. ie if you make the base way wider and the height much shorter, the bending in the midsection is going to be much more apparent. Obviously, this means I wouldn't be using a picture, but actually a vector-image model of the Eiffel tower that would change based off of the inputs. So what language and what libraries would one use to go about making this sort of things?
Thank you to anyone that can provide some insight on my issue. I really appreciate it!
Mike
Hello to integrate dynamic graph in a webpage there are two ways;
First you need to make your own graph library. For that you need to know SVG well to make a good looking graph.
Second, you can use any existing library. There are lot of open source libraries are there some of them are free to use also. To integrate graph using those libraries is not much difficult.
Some examples of graph generating library morris chart, c3.js etc. Google search 'll give you more detail idea.
As you said you have no idea about javascript so it will be a bit difficult at first for integrating graph. But 'll definitely much more easy to make your own graph library.
I'm sure this topic has been covered to bits, but I've spent hours trying to work something out and I can't find enough resources that explain the process. Please note, I am new to JS and still relying on tutorials and code snippets to write code. I'm still not confident enough to write code from complete scratch.
THE GOAL:
In JavaScript, 'draw' 5 random cards
Evaluate the cards' rank among all possible hands
Return a score from a Variable min/max, based on the rank of the card, unless it's less than a pair.
Lastly, be able to draw a RANDOM hand based on rank (less than, more than, or exactly) EG. Return a hand that is of rank 100 or smaller. (could bring back 100 different hands)
Eg. While Min-Max score is 10-30. If a royal flush comes out, return 30 (best hand means best score). If low Two Pair (6H 6D 2C 2H 5S) comes out return 13. If high Two Pair (AH AD QC QH 5S), return 14. Etc.
[Those are probably not accurate scores but you get the drift]
My Research results:
Random Draw: Many applications have achieved this. My favorite so far has been this tutorial:
http://www.informit.com/library/content.aspx?b=STY_JavaScript_24_hours&seqNum=229
it is quite simple and gets the result, however does not offer a full evaluation, only by category (pair, two pair, three of a kind etc). I need an evaluation that would be able to give a higher score to the superior of two hand that have two pairs.
Evaluators: This got a bit confusing. I found a very basic evaluator, that uses javascript: http://jsfiddle.net/subskybox/r4mSF/ but it was too basic. Doesn't give me a complete rank. I found this one too: https://github.com/chenosaurus/poker-evaluator which uses the Two Plus Two algorithm and a lookup table. Now, it sounds really good, but I'm terribly confused as to how to install it on into my website, or how to use it. It says: to install: npm install poker-evaluator, which I never heard of before.
Convert rating to score: Should be fairly easy maths. Perhaps: thisRank/maxRank*(MaxScore-MinScore)+MinScore
Draw hand by rank: Haven't seen any way of doing this anywhere. Wouldn't mind seeing some examples or ideas. I'm not sure this can be done with the Two Plus Two poker-evaluator. It's more like the reverse process.
Now, it feels like I'm getting close with all this, but I'm not a 100% sure how to compile this completely. I feel like I could use the code I found in section 1, and the Two Plus Two poker-evaluator to achieve what I need. I would love to it if you could shed a light on the 'npm install', if I'm going in the right direction, or if you know other methods I could achieve the same thing.
Please don't tell me I have to try doing it myself first, because I really don't know how to do this from scratch without a little guidance.
I will post another beginner's advice :
Write the algorithm of what you want to achieve in pseudo-code (e.g., words that are easy for you to read). If the algorithm is not clear in your head before you start coding it is not going to get clearer by itself. You are not able to write code : it is fine; you hope to write a program without having a detailed low-level vision of every one of its steps : it is not. At least that is how I see things.
Example of pseudo-code that I would write for this case:
1-
create card deck
loop on number of cards to be drawn
-generate random integer and remove corresponding card from card deck
-add drawn card to hand
end loop
2-
check if hand is highest figure and associate rating
else check if hand is 2nd highest and associate rating
else...
OR
get data with all possible hands and search for this hand to retrieve score...
(see github repo)
3-
I did not get 3-
4- If you have data with all hands and their value, you just have
to search this data by value instead of searching by hand like in 2-
Second, looking for code snippets on github is a good idea; read the javascript files in the projects which interest you and understand what they do. I think you will need to install node.js for that particular project, because it is used to import the lookup table. Just download the javascript files and include them in your project...do not forget to credit/thank the author.
Third, your question is not about a precise difficulty : it is a question about how to start programming stuff when you never did it before. I do not think stackoverflow is the right place for this, but I still answered your question because after all, this is also a help forum. My last advice would be to find a good book / tutorial; in every good book there is a sample project to follow in which you develop a complete program and will teach you the basics.
P.S.: if you are really interested, don't give up because programming can be hard but it is also very rewarding to see stuff work...
I'm reading "Javascript, The Good Parts" by Douglas Crockford, and having a difficulty understanding the use of all the railroad diagrams. He also doesn't elaborate much on this. He just says the following (on pg. 21):
The rules for interpreting these diagrams are simple:
You start on the left edge and follow the tracks to the right edge.
As you go, you will encounter literals in ovals, and rules or descriptions in rectangles.
Any sequence that can be made by following the tracks is legal.
Any sequence that cannot be made by following the tracks is not legal.
Railroad diagrams with one bar at each end allow whitespace to be inserted between any pair of tokens. Railroad diagrams with two bars at each end do not.
I am aware that this book is considered to be fundamental read for anyone who's really serious about Javascript, and I would very much like to understand the concepts he's addressing. But something just isn't clicking about the whole railroad diagram thing.
Could anyone explain his use of the railroad diagrams? Examples would be great.
This IBM page probably has the simplest explanation.
The Wikipedia page offers more info in how to construct them.
Railroad diagrams (Syntax diagrams, http://en.wikipedia.org/wiki/Syntax_diagram) are a graphical way to explain a grammar. If all you want to do is understand a railroad diagram, understand that you start at the left, and follow the line (track). And when you encounter a symbol/name, you go follow that track, until it is done, and then come back where you left off.
Also, reading about BNF and EBNF (Extended? Backus-Naur Formalism, http://en.wikipedia.org/wiki/Backus%E2%80%93Naur_Form) which is a formal way of describing a language grammar, using a set of productions, or rewrite rules. BNF/EBNF work the same as railroad diagrams, but using symbolic notation, the ::= production symbol, and a more formal/mathematical way to document a grammar.
I am also reading this book. It takes me a long time, but finally understand Railroad Diagrams.
First, as #ChuckCottrill mentioned, you should have a basic acknowledge about Syntax Diagrams and BNF/EBNF. But after reading that, it still confused me until I compare three graphs of different situation:
zero or more, zero or one, one or more
To understand their differences (as the following picture shows), the point is
"You start on the left edge and follow the tracks to the right edge."
So imagine you are the train, you just turn right, cannot turn left.
the above picture created by http://bottlecaps.de/rr/
In the "Edit Grammar" tab, input the following grammar:
zeroormore ::= element*
zeroorone ::= element?
oneormore ::= element+
I was wondering if anyone has any ideas, or has stumbled upon a script that will recognize portions of dates and times in any given field of text.
For instance, this sentence right here was being typed at 4:24pm and I suspect I will finish it at about 4:25 or so.. perhaps even later on the 19th.
I would like to be able to make a live listener that will pick out those times above (or guess) and surround them in a link to say... /calendar/events/create/TIMESTAMP
I expect regex could be used to find certain indicators like : or th, or anything like that and take a guess at the rest pending the current time..
Macs do this in mail and icalendar.. pretty cool. Thoughts or ideas would be greatly appreciated!
Have a look at date.js library which supports wide variety of formats.
Even with this library you will need to:
Preprocess the text (like removing dots at the end of sentences, removing whitespaces, ..)
Filter out false positives (it can parse th as thursday, say as saturday, etc).
Create algorithm for effective scanning of the text.
Map the found times/dates back to the text, etc.
So there is still a lot of work to do.
To see a very ineffective demonstration of the parsing have a look HERE.
For a while, I've been trying to find a way of intelligently extracting the "relevant" text from a URL by eliminating the text related to ads and all the other clutter.After several months of researching, I gave it up as a problem that cannot be accurately determined. (I've tried different ways but none were reliable)
A week back, I stumbled across Readability - a plugin that converts any URL into readable text. It looks pretty accurate to me. My guess is that they somehow have an algorithm that's smart enough to extract the relevant text.
Does anyone know how they do it? Or how I could do it reliably?
Readability mainly consists of heuristics that "just somehow work well" in many cases.
I have written some research papers about this topic and I would like to explain the background of why it is easy to come up with a solution that works well and when it gets hard to get close to 100% accuracy.
There seems to be a linguistic law underlying in human language that is also (but not exclusively) manifest in Web page content, which already quite clearly separates two types of text (full-text vs. non-full-text or, roughly, "main content" vs. "boilerplate").
To get the main content from HTML, it is in many cases sufficient to keep only the HTML text elements (i.e. blocks of text that are not interrupted by markup) which have more than about 10 words. It appears that humans choose from two types of text ("short" and "long", measured by the number of words they emit) for two different motivations of writing text. I would call them "navigational" and "informational" motivations.
If an author wants you to quickly get what is written, he/she uses "navigational" text, i.e. few words (like "STOP", "Read this", "Click here"). This is the mostly prominent type of text in navigational elements (menus etc.)
If an author wants you to deeply understand what he/she means, he/she uses many words. This way, ambiguity is removed at the cost of an increase in redundancy. Article-like content usually falls into this class as it has more than only a few words.
While this separation seems to work in a plethora of cases, it is getting tricky with headlines, short sentences, disclaimers, copyright footers etc.
There are more sophisticated strategies, and features, that help separating main content from boilerplate. For example the link density (number of words in a block that are linked versus the overall number of words in the block), the features of the previous/next blocks, the frequency of a particular block text in the "whole" Web, the DOM structure of HTML document, the visual image of the page etc.
You can read my latest article "Boilerplate Detection using Shallow Text Features" to get some insight from a theoretical perspective. You may also watch the video of my paper presentation on VideoLectures.net.
"Readability" uses some of these features. If you carefully watch the SVN changelog, you will see that the number of strategies varied over time, and so did the extraction quality of Readability. For example, the introduction of link density in December 2009 very much helped improving.
In my opinion, it therefore makes no sense in saying "Readability does it like that", without mentioning the exact version number.
I have published an Open Source HTML content extraction library called boilerpipe, which provides several different extraction strategies. Depending on the use case, one or the other extractor works better. You can try these extractors on pages on your choice using the companion boilerpipe-web app on Google AppEngine.
To let numbers speak, see the "Benchmarks" page on the boilerpipe wiki which compares some extraction strategies, including boilerpipe, Readability and Apple Safari.
I should mention that these algorithms assume that the main content is actually full text. There are cases where the "main content" is something else, e.g. an image, a table, a video etc. The algorithms won't work well for such cases.
readability is a javascript bookmarklet. meaning its client side code that manipulates the DOM. Look at the javascript and you should be able to see whats going on.
Readability's workflow and code:
/*
* 1. Prep the document by removing script tags, css, etc.
* 2. Build readability's DOM tree.
* 3. Grab the article content from the current dom tree.
* 4. Replace the current DOM tree with the new one.
* 5. Read peacefully.
*/
javascript: (function () {
readConvertLinksToFootnotes = false;
readStyle = 'style-newspaper';
readSize = 'size-medium';
readMargin = 'margin-wide';
_readability_script = document.createElement('script');
_readability_script.type = 'text/javascript';
_readability_script.src = 'http://lab.arc90.com/experiments/readability/js/readability.js?x=' + (Math.random());
document.documentElement.appendChild(_readability_script);
_readability_css = document.createElement('link');
_readability_css.rel = 'stylesheet';
_readability_css.href = 'http://lab.arc90.com/experiments/readability/css/readability.css';
_readability_css.type = 'text/css';
_readability_css.media = 'all';
document.documentElement.appendChild(_readability_css);
_readability_print_css = document.createElement('link');
_readability_print_css.rel = 'stylesheet';
_readability_print_css.href = 'http://lab.arc90.com/experiments/readability/css/readability-print.css';
_readability_print_css.media = 'print';
_readability_print_css.type = 'text/css';
document.getElementsByTagName('head')[0].appendChild(_readability_print_css);
})();
And if you follow the JS and CSS files that the above code pulls in you'll get the whole picture:
http://lab.arc90.com/experiments/readability/js/readability.js (this is pretty well commented, interesting reading)
http://lab.arc90.com/experiments/readability/css/readability.css
There's no 100% reliable way to do this, of course. You can have a look at the Readability source code here
Basically, what they're doing is trying to identify positive and negative blocks of text. Positive identifiers (i.e. div IDs) would be something like:
article
body
content
blog
story
Negative identifiers would be:
comment
discuss
And then they have unlikely and maybe candidates.
What they would do is determine what is most likely to be the main content of the site, see line 678 in the readability source. This is done by analyzing mostly the length of paragraphs, their identifiers (see above), the DOM tree (i.e. if the paragraph is a last child node), strip out everything unnecessary, remove formatting, etc.
The code has 1792 lines. It does seem like a non trivial problem, so maybe you can get your inspirations from there.
Interesting. I have developed a similar PHP script. It basically scans articles and attaches parts of speech to all text (Brill Tagger). Then, grammatically invalid sentences are instantly eliminated. Then, sudden shifts in pronouns or past tense indicate the article is over, or hasn't started yet. Repeated phrases are searched for and eliminated, like "Yahoo news sports finance" appears ten times in the page. You can also get statistics on the tone with a plethora of word banks relating to various emotions. Sudden changes in tone, from active/negative/financial, to passive/positive/political indicates a boundary. It's endless really, however dig you want to deep.
The major issues are links, embedded anomalies, scripting styles and updates.