modifying google-maps default directions title - google-maps

I'm using the Google maps V3 JavaScript API and I'm currently using the default directions formatting (because this is the easiest way to get the map pins and step icons integrated into the listing). I'm setting the text that is displayed for each 'address' for example:
var loc = 'The Old Ballpark Bar and Lounge';
var addr = '1234 Main st. Chicago, IL.';
...
route.legs[0].start_address = loc + ' - ' + addr;
I'd like to enhance the readability of this start_address in 2 ways:
I'd like to put the addr part on a separate line.
I'd like to highlight the loc part in bold
Since the text for this start_address is placed in a td (class="adp-text") within a table (class="adp-placemark"); I thought that putting a <br/> between the loc and addr would get me the newline I wanted; but it doesn't work, the api translates this into <br/>. Similarly, trying to put <b> before the loc part, gets translated into & lt;b& gt;.
I've tried escaping the markup code with quotes and backslashes, etc.; but can't find a way to do what I want. Is there any way to insert such mark up so as to get it past the Google code translators? Are there some lower-level CSS tags that might be used to accomplish this?

You must modify the elements after they have been inserted into the DOM.
assign the desired markup:
route.legs[0].start_address = '<div style="font-weight:bold">'+ loc + '</div>' + addr;
hide the panel(to avoid undesired effects)
//directionsDisplay is the google.maps.DirectionsRenderer-instance
directionsDisplay.getPanel().style.visibility='hidden';
set the direction:
directionsDisplay.setDirections(response);
wait a moment until you modify the elements:
setTimeout(function(){
//fetch the elements
var nodes=directionsDisplay.getPanel().querySelectorAll('td.adp-text');
for(var n=0;n<nodes.length;++n){
//assign the text-content of the element to the innerHTML-property
nodes[n].innerHTML=nodes[n].firstChild.data;
}
//show the panel
directionsDisplay.getPanel().style.visibility='visible';
},100);

Related

.text is scrambled with numbers and special keys in BeautifuSoup

Hello I am currently using Python 3, BeautifulSoup 4 and, requests to scrape some information from supremenewyork.com UK. I have implemented a proxy script (that I know works) into the script. The only problem is that this website does not like programs to scrape this information automatically and so they have decided to scramble this script which I think makes it unusable as text.
My question: is there a way to get the text without using the .text thing and/or is there a way to get the script to read the text? and when it sees a special character like # to skip over it or to read the text when it sees & skip until it sees ;?
because basically how this website scrambles the text is by doing this. Here is an example, the text shown when you inspect element is:
supremetshirt
Which is supposed to say "supreme t-shirt" and so on (you get the idea, they don't use letters to scramble only numbers and special keys)
this  is kind of highlighted in a box automatically when you inspect the element using a VPN on the UK supreme website, and is different than the text (which isn't highlighted at all). And whenever I run my script without the proxy code onto my local supremenewyork.com, It works fine (but only because of the code, not being scrambled on my local website and I want to pull this info from the UK website) any ideas? here is my code:
import requests
from bs4 import BeautifulSoup
categorys = ['jackets', 'shirts', 'tops_sweaters', 'sweatshirts', 'pants', 'shorts', 't-shirts', 'hats', 'bags', 'accessories', 'shoes', 'skate']
catNumb = 0
#use new proxy every so often for testing (will add something that pulls proxys and usses them for you.
UK_Proxy1 = '51.143.153.167:80'
proxies = {
'http': 'http://' + UK_Proxy1 + '',
'https': 'https://' + UK_Proxy1 + '',
}
for cat in categorys:
catStr = str(categorys[catNumb])
cUrl = 'http://www.supremenewyork.com/shop/all/' + catStr
proxy_script = requests.get(cUrl, proxies=proxies).text
bSoup = BeautifulSoup(proxy_script, 'lxml')
print('\n*******************"'+ catStr.upper() + '"*******************\n')
catNumb += 1
for item in bSoup.find_all('div', class_='inner-article'):
url = item.a['href']
alt = item.find('img')['alt']
req = requests.get('http://www.supremenewyork.com' + url)
item_soup = BeautifulSoup(req.text, 'lxml')
name = item_soup.find('h1', itemprop='name').text
#name = item_soup.find('h1', itemprop='name')
style = item_soup.find('p', itemprop='model').text
#style = item_soup.find('p', itemprop='model')
print (alt +(' --- ')+ name +(' --- ')+ style)
#print(alt)
#print(str(name))
#print (str(style))
When I run this script I get this error:
name = item_soup.find('h1', itemprop='name').text
AttributeError: 'NoneType' object has no attribute 'text'
And so what I did was I un-hash-tagged the stuff that is hash-tagged above, and hash-tagged the other stuff that is similar but different, and I get some kind of str error and so I tried the print(str(name)). I am able to print the alt fine (with every script, the alt is not scrambled), but when it comes to printing the name and style all it prints is a None under every alt code is printed.
I have been working on fixing this for days and have come up with no solutions. can anyone help me solve this?
I have solved my own answer using this solution:
thetable = soup5.find('div', class_='turbolink_scroller')
items = thetable.find_all('div', class_='inner-article')
for item in items:
alt = item.find('img')['alt']
name = item.h1.a.text
color = item.p.a.text
print(alt,' --- ', name, ' --- ',color)

Css 'const' chars in text input

Is there any way to set 'const' chars to text in css or html?
For Example user writes phone number 646830293 and in text (one input) this is 646-830-293 (so every fourth and eighth chars are '-').
jQuery Mask Plugin might the solution for you. It's very simple to use and has very good customization.
From the documentation, you'd write a simple mask with:
$(document).ready(function(){
$('.date').mask('00/00/0000');
$('.time').mask('00:00:00');
$('.date_time').mask('00/00/0000 00:00:00');
});
The whole page has a lot more examples!
Using your pastebin, here's the result:
I think you cannot do it with pure CSS but it is very simple only using Javascript.
var text = document.getElementById('text').innerHTML;
var output = text.substring(0, 3) + "-" + text.substring(3, 6) + "-" + text.substring(6);
document.getElementById('output').innerHTML = output;
<p id="text">646830293</p>
<p id="output"></p>

highlight words in html using regex & javascript - almost there

I am writing a jquery plugin that will do a browser-style find-on-page search. I need to improve the search, but don't want to get into parsing the html quite yet.
At the moment my approach is to take an entire DOM element and all nested elements and simply run a regex find/replace for a given term. In the replace I will simply wrap a span around the matched term and use that span as my anchor to do highlighting, scrolling, etc. It is vital that no characters inside any html tags are matched.
This is as close as I have gotten:
(?<=^|>)([^><].*?)(?=<|$)
It does a very good job of capturing all characters that are not in an html tag, but I'm having trouble figuring out how to insert my search term.
Input: Any html element (this could be quite large, eg <body>)
Search Term: 1 or more characters
Replace Txt: <span class='highlight'>$1</span>
UPDATE
The following regex does what I want when I'm testing with http://gskinner.com/RegExr/...
Regex: (?<=^|>)(.*?)(SEARCH_STRING)(?=.*?<|$)
Replacement: $1<span class='highlight'>$2</span>
However I am having some trouble using it in my javascript. With the following code chrome is giving me the error "Invalid regular expression: /(?<=^|>)(.?)(Mary)(?=.?<|$)/: Invalid group".
var origText = $('#'+opt.targetElements).data('origText');
var regx = new RegExp("(?<=^|>)(.*?)(" + $this.val() + ")(?=.*?<|$)", 'gi');
$('#'+opt.targetElements).each(function() {
var text = origText.replace(regx, '$1<span class="' + opt.resultClass + '">$2</span>');
$(this).html(text);
});
It's breaking on the group (?<=^|>) - is this something clumsy or a difference in the Regex engines?
UPDATE
The reason this regex is breaking on that group is because Javascript does not support regex lookbehinds. For reference & possible solutions: http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript.
Just use jQuerys built-in text() method. It will return all the characters in a selected DOM element.
For the DOM approach (docs for the Node interface): Run over all child nodes of an element. If the child is an element node, run recursively. If it's a text node, search in the text (node.data) and if you want to highlight/change something, shorten the text of the node until the found position, and insert a highligth-span with the matched text and another text node for the rest of the text.
Example code (adjusted, origin is here):
(function iterate_node(node) {
if (node.nodeType === 3) { // Node.TEXT_NODE
var text = node.data,
pos = text.search(/any regular expression/g), //indexOf also applicable
length = 5; // or whatever you found
if (pos > -1) {
node.data = text.substr(0, pos); // split into a part before...
var rest = document.createTextNode(text.substr(pos+length)); // a part after
var highlight = document.createElement("span"); // and a part between
highlight.className = "highlight";
highlight.appendChild(document.createTextNode(text.substr(pos, length)));
node.parentNode.insertBefore(rest, node.nextSibling); // insert after
node.parentNode.insertBefore(highlight, node.nextSibling);
iterate_node(rest); // maybe there are more matches
}
} else if (node.nodeType === 1) { // Node.ELEMENT_NODE
for (var i = 0; i < node.childNodes.length; i++) {
iterate_node(node.childNodes[i]); // run recursive on DOM
}
}
})(content); // any dom node
There's also highlight.js, which might be exactly what you want.

JSFL: convert text from a textfield to a HTML-format string

I've got a deceptively simple question: how can I get the text from a text field AND include the formatting? Going through the usual docs I found out it is possible to get the text only. It is also possible to get the text formatting, but this only works if the entire text field uses only one kind of formatting. I need the precise formatting so that I convert it to a string with html-tags.
Personally I need this so I can pass it to a custom-made text field component that uses HTML for formatting. But it could also be used to simply export the contents of any text field to any other format. This could be of interest to others out there, too.
Looking for a solution elsewhere I found this:
http://labs.thesedays.com/blog/2010/03/18/jsfl-rich-text/
Which seems to do the reverse of what I need, convert HTML to Flash Text. My own attempts to reverse this have not been successful thus far. Maybe someone else sees an easy way to reverse this that I’m missing? There might also be other solutions. One might be to get the EXACT data of the text field, which should include formatting tags of some kind(XML, when looking into the contents of the stored FLA file). Then remove/convert those tags. But I have no idea how to do this, if at all possible. Another option is to cycle through every character using start- and endIndex, and storing each formatting kind in an array. Then I could apply the formatting to each character. But this will result in excess tags. Especially for hyperlinks! So can anybody help me with this?
A bit late to the party but the following function takes a JSFL static text element as input and returns a HTML string (using the Flash-friendly <font> tag) based on the styles found it its TextRuns array. It's doing a bit of basic regex to clear up some tags and double spaces etc. and convert /r and /n to <br/> tags. It's probably not perfect but hopefully you can see what's going on easy enough to change or fix it.
function tfToHTML(p_tf)
{
var textRuns = p_tf.textRuns;
var html = "";
for ( var i=0; i<textRuns.length; i++ )
{
var textRun = textRuns[i];
var chars = textRun.characters;
chars = chars.replace(/\n/g,"<br/>");
chars = chars.replace(/\r/g,"<br/>");
chars = chars.replace(/ /g," ");
chars = chars.replace(/. <br\/>/g,".<br/>");
var attrs = textRun.textAttrs;
var font = attrs.face;
var size = attrs.size;
var bold = attrs.bold;
var italic = attrs.italic;
var colour = attrs.fillColor;
if ( bold )
{
chars = "<b>"+chars+"</b>";
}
if ( italic )
{
chars = "<i>"+chars+"</i>";
}
chars = "<font size=\""+size+"\" face=\""+font+"\" color=\""+colour+"\">"+chars+"</font>";
html += chars;
}
return html;
}

Are single quotes allowed in HTML?

I am a big time user of using double quotes in PHP so that I can interpolate variables rather than concatenating strings. As a result, when I am generating HTML I often use single quotes for setting tag fields. For example:
$html = "<input type='text' name='address' value='$address'>";
Now this is far more readable to me than either
$html = "<input type=\"text\" name=\"address\" value=\"$address\">";
or
$html = '<input type="text" name="address" values="' . $address . '">' ;
From brief searches I have heard people saying that single quotes for HTML fields is not recognized by EVERY browser. Thus I am wondering what browsers would have problems recognizing single quote HTML?
This is similar to When did single quotes in HTML become so popular?. Single quotes around attributes in HTML are and always have been permitted by the specification. I don't think any browsers wouldn't understand them.
As noted by PhiLho, although there is a widely spread belief that single quotes are not allowed for attribute values, that belief is wrong.
The XML standard permits both single and double quotes around attribute values.
The XHTML standard doesn't say anything to change this, but a related section which states that attribute values must be quoted uses double quotes in the example, which has probably lead to this confusion. This example is merely pointing out that attribute values in XHTML must meet the minimum standard for attribute values in XML, which means they must be quoted (as opposed to plain HTML which doesn't care), but does not restrict you to either single or double quotes.
Of course, it's always possible that you'll encounter a parser which isn't standards-compliant, but when that happens all bets are off anyway. So it's best to just stick to what the specification says. That's why we have specifications, after all.
I have heard people saying that single quotes for HTML fields is not recognized by EVERY browser
That person is wrong.
Don't believe everything you see on Internet...
Funnily, I just answered something similar to somebody declaring single quotes are not valid in XHTML...
Mmm, I look above while typing, and see that Adam N propagates the same belief. If he can back up his affirmation, I retract what I wrote... AFAIK, XML is agnostic and accepts both kinds of quote. I even tried and validated without problem an XHTML page with only single quotes.
As I was looking to find information on this in a much more recent version of the specification and it took me quite some time to find it, here it is:
From
HTML
Living Standard — Last Updated 17 September 2021
[...]
13.1.2.3 Attributes
Single-quoted attribute value syntax
The attribute name, followed by zero or more ASCII whitespace, followed by a single U+003D EQUALS SIGN character, followed by zero or more ASCII whitespace, followed by a single U+0027 APOSTROPHE character ('), followed by the attribute value, which, in addition to the requirements given above for attribute values, must not contain any literal U+0027 APOSTROPHE characters ('), and finally followed by a second single U+0027 APOSTROPHE character (').
In the following example, the type attribute is given with the single-quoted attribute value syntax:
<input type='checkbox'>
If an attribute using the single-quoted attribute syntax is to be followed by another attribute, then there must be ASCII whitespace separating the two.
https://html.spec.whatwg.org/#attributes-2
Only problem is data going into TEXT INPUT fields. Consider
<input value='it's gonna break'/>
Same with:
<input value="i say - "this is gonna be trouble" "/>
You can't escape that, you have to use htmlspecialchars.
I also tend to use single quotes in HTML and I have never experienced a problem.
I used single quotes in HTML pages and embedded JavaScripts into it and its works fine. Tested in IE9, Chrome and Firefox - seems working fine.
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<title>Bethanie Inc. data : geographically linked</title>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js'></script>
<script src='https://maps.googleapis.com/maps/api/js?v=3.11&sensor=false' type='text/javascript'></script>
<script type='text/javascript'>
// check DOM Ready
$(document).ready(function() {
// execute
(function() {
/////////////// Addresses ///////////////////
var locations = new Array();
var i = 0;
locations[i++] = 'L,Riversea: Comp Site1 at Riversea,1 Wallace Lane Mosman Park WA 6012'
locations[i++] = 'L,Wearne: Comp Site2 at Wearne,1 Gibney St Cottesloe WA 6011'
locations[i++] = 'L,Beachside:Comp Site3 Beachside,629 Two Rocks Rd Yanchep WA 6035'
/////// Addresses/////////
var total_locations = i;
i = 0;
console.log('About to look up ' + total_locations + ' locations');
// map options
var options = {
zoom: 10,
center: new google.maps.LatLng(-31.982484, 115.789329),//Bethanie
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true
};
// init map
console.log('Initialise map...');
var map = new google.maps.Map(document.getElementById('map_canvas'), options);
// use the Google API to translate addresses to GPS coordinates
//(See Limits: https://developers.google.com/maps/documentation/geocoding/#Limits)
var geocoder = new google.maps.Geocoder();
if (geocoder) {
console.log('Got a new instance of Google Geocoder object');
// Call function 'createNextMarker' every second
var myVar = window.setInterval(function(){createNextMarker()}, 700);
function createNextMarker() {
if (i < locations.length)
{
var customer = locations[i];
var parts = customer.split(','); // split line into parts (fields)
var type= parts.splice(0,1); // type from location line (remove)
var name = parts.splice(0,1); // name from location line(remove)
var address =parts.join(','); // combine remaining parts
console.log('Looking up ' + name + ' at address ' + address);
geocoder.geocode({ 'address': address }, makeCallback(name, type));
i++; // next location in list
updateProgressBar(i / total_locations);
} else
{
console.log('Ready looking up ' + i + ' addresses');
window.clearInterval(myVar);
}
}
function makeCallback(name,type)
{
var geocodeCallBack = function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var longitude = results[0].geometry.location.lng();
var latitude = results[0].geometry.location.lat();
console.log('Received result: lat:' + latitude + ' long:' + longitude);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(latitude, longitude),
map: map,
title: name + ' : ' + '\r\n' + results[0].formatted_address});// this is display in tool tip/ icon color
if (type=='E') {marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')};
Recently i've experienced a problem with Google Search optimization. If has a single quotes, it doesn't seem to crawl linked pages.
... or just use heredocs. Then you don't need to worry about escaping anything but END.
Single Quotes are fine for HTML, but they don't make valid XHTML, which might be problematic if anybody was using a browser which supported only XHTML, but not HTML. I don't believe any such browsers exist, though there are probably some User-Agents out there that do require strict XHTML.