I have some simple JavaScript that determines where a click happens within a browser here:
var clickDoc = (document.documentElement != undefined && document.documentElement.clientHeight != 0) ? document.documentElement : document.body;
var x = evt.clientX;
var y = evt.clientY;
var w = clickDoc.clientWidth != undefined ? clickDoc.clientWidth : window.innerWidth;
var h = clickDoc.clientHeight != undefined ? clickDoc.clientHeight : window.innerHeight;
var scrollx = window.pageXOffset == undefined ? clickDoc.scrollLeft : window.pageXOffset;
var scrolly = window.pageYOffset == undefined ? clickDoc.scrollTop : window.pageYOffset;
params = '&x=' + (x + scrollx) + '&y=' + (y + scrolly) + '&w=' + w + '&random=' + Date();
All of this data gets stored in a DB. Later I retrieve it and display where all the clicks happened on that page. This works fine if I do all my clicks in one resolution, and then display it back in the same resolution, but this, not the case. there can be large amounts of resolutions used.
In my test case, I was clicking on the screen with a screen resolution of 1260x1080. I retrieved all the data and displayed it in the same resolution. But when I use a different monitor (tried 1024x768 and 1920x1080. The marks shift to the incorrect spot.
My question is if I am storing the width and height of the client, and the x/y position of the click. If 3 different users all with different screen resolutions click on the same word, and a 4th user goes to view where all of those clicks happened, how can I plot the x/y position correctly to show that everyone clicked in the same space, no matter the resolution?
If this belongs in a better section, please let me know as well.
:::EDIT::: After applying brock's suggestions, I have attached two screenshots. I clicked on the word If at the beginning of each paragraph in different resolutions. When viewing in both those resolutions, the clicks that happened in the same resolution are directly on the word, when it's a higher or lower resolution, it shifts to the right or left, respectively.
http://img291.imageshack.us/img291/5682/1260x1080.png
http://img27.imageshack.us/img27/8950/1920x1080c.png%20
Update:
Additional issues to consider, the problem may not be perfectly solvable...
At different screen sizes, things like margins (for centered content) will be different. Need to adjust to where "screen size" really becomes the clientWidth after compensating for changing margins.
Also, despite everything, a page just might render differently at different screen resolutions (plus whatever size the user has his browser window at). If this causes lines to wrap differently, it will really throw off comparisons.
Original Answer:
"if I am storing the width and height of the client, and the x/y position of the click. If 3 different users all with different screen resolutions click on the same word, and a 4th user goes to view where all of those clicks happened, how can I plot the x/y position correctly"
This should just be a simple scaling problem.
Pseudo code:
Given:
CapturedMousePosition = {X and Y coordinates of logged machine, in pixels} //-- EG [42, 69]
CapturedScreenSize = {width and height of logged machine, in pixels} //-- EG [1260, 1080]
TargetScreenSize = {width and height of display machine, in pixels} //-- EG [1024, 768]
/*-- Note that client size and/or view-port size, are what we mean by "screen size" here.
This is because the browser will use some unknown fraction of the PC's display resolution.
*/
Then:
TargetMousePosition = CapturedMousePosition * TargetScreenSize / CapturedScreenSize
EG: [42 * 1024 / 1260, 69 * 768 / 1080] -- Be sure to round to *nearest* integer.
If you need to store the place in the document where the user clicked, what you are doing now should be ok.
If you need to store the place in the browser window (why?), you'd have to also store the browser resolution, or a normalized value based on the resolution.
Related
My PHPExcel generated excel contains a barchart and a pie chart and is automatically fired to an email. When the email attachment is downloaded and opened (you have to click enable editing) it displays this alert box:
When the email attachment is downloaded and opened (you have to click enable editing) it displays this alert box:
and behind this you can see the expected data in their cells and a blank canvas for the charts.
I close the excel document and open it again, this time I get the expected chart displayed along with data sets overlayed by this alert box:
I close the excel document and open it again, this time I get the expected chart displayed along with data sets overlayed by this alert box:
Clicking on the update link in the second alert box resolves to launching the first alert box. Clicking continue in that resolves to the chart going blank, only showing a blank canvas with axis.
My code uses extensive variables to determine the cell location for each data field. I tried using EXIT at the end of the script as advise by one of the answers around here. That didn;t work.
Code Sample:
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.$StartRow, 'Date')
->setCellValue('B'.$StartRow, $ndate)
->setCellValue('C'.$ParticipantStartLabel, 'Enrolled')
->setCellValue('D'.$ParticipantStartLabel, 'Logged In')
->setCellValue('E'.$ParticipantStartLabel, 'Yet to Log In')
->setCellValue('F'.$ParticipantStartLabel, 'Monitors (BOI, EDC and AMI)')
->setCellValue('B'.$ParticipantStartDetails, 'Participants on the program')
->setCellValue('C'.$ParticipantStartDetails, $ParticipantEnrolled)
->setCellValue('D'.$ParticipantStartDetails, $ParticipantLoggin)
->setCellValue('E'.$ParticipantStartDetails, $ParticipantYettoLog)
->setCellValue('F'.$ParticipantStartDetails, $Monitors) //$Monitors
->setCellValue('A'.$CoursesStartRow, 'S/N')
->setCellValue('B'.$CoursesStartRow, 'Course')
->setCellValue('C'.$CoursesStartRow, 'Enrolled')
->setCellValue('D'.$CoursesStartRow, 'Completed')
->setCellValue('E'.$CoursesStartRow, 'Incomplete');
//print courses for single dataset
for( $i = 0 ; $i < $NumCourses; $i++ ){
$newi = $i + 1;
$newCoursesStartRow = $CoursesStartRow + $newi;
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.$newCoursesStartRow, $newi)
->setCellValue('B'.$newCoursesStartRow, $Courses[$i]) // continue to Add some data on courses
->setCellValue('C'.$newCoursesStartRow, $CoursesEnrolled[$i])
->setCellValue('D'.$newCoursesStartRow, $CoursesCompleted[$i])
->setCellValue('E'.$newCoursesStartRow, $CoursesIncompleted[$i]);
}
Any help to decipher why the document would not just open with displaying this distracting alert boxes is appreciated.
It's called security, and Microsoft have applied it in all recent versions of MS Excel. The purpose is to prevent any malicious excel files from executing arbitrary code. Unfortunately, because some people have chosen to use Excel spreadsheets for malware, Microsoft have chosen to provide these warnings to indicate that they can't guarantee that this spreadsheet may contain dangerous content, and that the user opening it must make a conscious decision to accept the risks.
Generally, you would only get this error if the spreadsheet references other spreadsheet files, or if it tries to access remote data. Are you building your file froma template that may contain these?
I have a JQuery-Code like this:
var number_images = 5;
var ct = 1;
// Goto previous Picture
$('#changeImageMinus').on('click', function()
{
if(ct-1>=1 && ct-1<=number_images)
{
ct = ct - 1;
$('.container-bg').css("background-image","url('images/" + ct + ".png')");
}
})
// Goto next Picture
$('#changeImagePlus').on('click', function()
{
if(ct+1>=1 && ct+1<=number_images)
{
ct = ct + 1;
$('.container-bg').css("background-image","url('images/" + ct + ".png')");
}
})
I have images named like 1.png, 2.png ... in the folder images/, so i simply load the images back/forward by pressing a "+" or a "-" button. The problem ist that the loading takes really long and i would like to know if there is a possible way to preload all images into a buffer or something like that. I basically want to load the images all before the site openes so that it will show off faster when i switch them. Thank you very much in advance!
You can do it with JS by using Image class. Create new Image object and set it's src property with path to your picture. Do it for all images before printing page and you should have them preloaded. In this article they describe it (second way).
Just be careful because if you have a lot of pictures it can negatively affect the user experience, especially for the users with slower connection (yes they exist, me for example :D). Imagine that you need to wait few (like 10 or more) seconds for a page to load. The best method in such cases would be preloading the specified amount of images and then loading the rest if needed. The problem of waiting may occure again then but at least user will see your page and not search for some other one :)
Good Morning Justice League of Stackoverflow,
I have here a problem that may stump the panel.
I am creating an interactive post-it for an upcoming event that allows for us to tap into a sql database and post tweets, survey answers and images. We've already tapped into the Twitter API and the survey, so those are A-OK.
The problem lies within loading the images from a location other than the local interactive board's server.
If the image itself is locally hosted, it loads just fine.
If the image is hosted elsewhere, the image will not load, even though I have a trace on the URL of said image.
I'm loading all tweets, surveys and images through an XML load and all the data is loading properly.
I AM loading the image through a smoothing filter so that when the "post-its" are slightly rotated, they are not jagged. Here is THAT code:
import flash.display.*;
var srcImg = _parent._parent.varContent;
urlText.text = srcImg;
var mainHolder = this.createEmptyMovieClip("main", this.getNextHighestDepth());
var original = mainHolder.createEmptyMovieClip("original", mainHolder.getNextHighestDepth());
var smooth = mainHolder.createEmptyMovieClip("smooth", mainHolder.getNextHighestDepth());
var mclListener:Object = new Object();
mclListener.onLoadInit = function() {
var w = original._width;
var h = original._height;
var bmpData1:BitmapData = new BitmapData(w, h, true, 0x000000);//true and 0 color allows for transparency
bmpData1.draw(original);
smooth.attachBitmap(bmpData1,2,"auto",true);//true for SMOOTHING, ;)
reSize(smooth);
original.removeMovieClip();
mainHolder._x = -(smooth._width / 2);
mainHolder._y = -(smooth._height / 2);
};
var image_mcl:MovieClipLoader = new MovieClipLoader();
image_mcl.addListener(mclListener);
image_mcl.loadClip(srcImg,original);
function reSize(target) {
if (target._width > target._height) {
s = Math.floor((300.85 / target._height) * 100);
}
if (target._width < target._height) {
s = Math.floor((320.90 / target._width) * 100);
}
target._xscale = s;
target._yscale = s;
}
This is a two part script where the bulk loads in the image and places it into an empty movieclip, then adds the smoothing filter. The second part is a resizer that automatically resizes the image and keeps the aspect ratio
Here's the kicker. When I test the flash piece (not embedded in HTML) the thing works 100%.
As soon as I put the swf into an html and view it on a web page, the remote images will not load.
I'm a bit stumped on why this is, could this be a firewall or security issue? Because I work in a high security firewall environment.
Any guidance in this would be most appreciated.
Thank you for your time.
by default flash does not allow cross domain loading of data as a security feature, but it can be overridden.
this may help:
allowDomain (security.allowDomain method) if you can get a swf running on the image server
http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00002104.html
A cross domain policy file may also be used on the server to grant access to the swf:
http://help.adobe.com/en_US/AS2LCR/Flash_10.0/help.html?content=00000470.html
I have a site that I want to display ads to 10% of my traffic. I am getting on average around 30,000 hits a day and want 10% of those users to see an ad from one of my advertisers.
What's the best way to go about implementing this?
I was thinking about counting the visitors in a database, and then every 10 people that visit 1 user gets an ad. Or is there a better way of going about it?
I'm no good with math, so I'm not sure what's the best approach.
Generate a random number between 1 and 10, and compare it to a fixed number, and your code will run on average 10% of the time:
if (rand(1,10) == 1) {
echo 'ad code';
}
You can make this per-user instead of per-pageview by storing whether that user was 'chosen' in their session.
session_start();
if (isset($_SESSION['show_me_ads']) || rand(1,10) == 1)
$_SESSION['show_me_ads'] = true;
echo 'ad code';
}
I use Google's DFP (Doubleclick for Publishers) to serve ads on my site. It's pretty robust. You have to have an AdSense account, but that's not very hard to obtain, it's just annoying to wait to be approved.
Once you have it set up and your ads loaded in, you can control how many people see your ad by percentage (such as the 10% you were talking about), total pageviews, etc.
Look into it: http://google.com/dfp
If you'd rather not use 3rd party software, I'd think the simplest way would be to randomize it so 1/10 visitors see your ad. The simple way would be:
if (rand(1,10) == 1) {
echo 'YOUR AD CODE HERE';
}
You said you're not good at math, and I understand that, I'm pretty horrible at it too, but basically, every time the page is loaded, it's "rolling" a 10-sided "dice". Every time it "rolls" a 1 (which would be 1 out of 10 times, or 10%), it'll display the ad. Otherwise, it'll be ignored.
The reason this is better than relying on counting the number of users (aside from simplicity) is that it will still roll 1 10% of the time whether you have 30,000 visitors or 3,000,000.
In its simplest form:
if (rand(1,10) == 1) {
echo $ad_content;
}
if(rand ( 1,10) == 1)
display_ads();
You can use
if(mt_rand(1,10)==10){
//show your code;
}
It will show ads to about 10% users
Why would you show ads to a few unlucky ones instead of randomly deciding per page impression (instead of per visitor)?
In php, you can just go ahead and write:
$adPercent = 10;
if (rand(0, 100) < $adPercent) {
echo '<div class="ads">Buy now!</div>';
}
if this was for google ads, then you would need to make the ad insertion optional (using the prob logic above), suggest something along the lines of Google Ads Async (asynchronous)
<script type="text/javascript"><!--
// dynamically Load Ads out-of-band
setTimeout((function ()
{
// placeholder for ads
var eleAds = document.createElement("ads");
// dynamic script element
var eleScript = document.createElement("script");
// remember the implementation of document.write function
w = document.write;
// override and replace with our version
document.write = (function(params)
{
// replace our placeholder with real ads
eleAds.innerHTML = params;
// put the old implementation back in place
document.write=w;
});
// setup the ads script element
eleScript.setAttribute("type", "text/javascript");
eleScript.setAttribute("src", "http://pagead2.googlesyndication.com/pagead/show_ads.js");
// add the two elements, causing the ads script to run
document.body.appendChild(eleAds);
document.body.appendChild(eleScript);
}), 1);
//-->
</script>
I want to fetch google images against any query. I have gone through the google image search api but unable to understand. i have also seen some methods, they fetch images but only of first page.i have used following method.
function getGoogleImg($k)
{
$url = "http://images.google.it/images?as_q=##query##&hl=it&imgtbs=z&btnG=Cerca+con+Google&as_epq=&as_oq=&as_eq=&imgtype=&imgsz=m&imgw=&imgh=&imgar=&as_filetype=&imgc=&as_sitesearch=&as_rights=&safe=images&as_st=y";
$web_page = file_get_contents( str_replace("##query##",urlencode($k), $url ));
$tieni = stristr($web_page,"dyn.setResults(");
$tieni = str_replace( "dyn.setResults(","", str_replace(stristr($tieni,");"),"",$tieni) );
$tieni = str_replace("[]","",$tieni);
$m = preg_split("/[\[\]]/",$tieni);
$x = array();
for($i=0;$i<count($m);$i++)
{
$m[$i] = str_replace("/imgres?imgurl\\x3d","",$m[$i]);
$m[$i] = str_replace(stristr($m[$i],"\\x26imgrefurl"),"",$m[$i]);
$m[$i] = preg_replace("/^\"/i","",$m[$i]);
$m[$i] = preg_replace("/^,/i","",$m[$i]);
if ($m[$i]!="")
array_push($x,$m[$i]);
}
return $x;
}
This function return only 21 images. i want all images against this query. i am doing this in php
Sadly the image API is being closed down, so I wont suggest moving to that, but that would have been a nicer solution I think.
My best guess is that image 22 and forwards is being loaded using som ajax/javascript of some sort (if you search for say logo and scroll down you will see placeholders that gets loaded as you move down) and that you need to pass the page by a javascript engine and that is not something that I can find anyone who have done with php (yet).
Have you checked that $web_page contains more than 21 images (when I toy against google image search it uses javascript to load some of the images)?
When you access the link from your normal browser what happens then and what happens if you turn off javascript?
Is there perhaps a link to next page in the result you have?
In the now deprecated Image API there were ways to limit the number of results per page and ways to step to the next page https://developers.google.com/image-search/v1/jsondevguide#json_snippets_php
If you wish to keep on doing searches and fetching images from the search result then for later http://simplehtmldom.sourceforge.net/ might be a nice alternative to look at.
It fetches a html DOM and allows you to easily find nodes and makes it easy to work with them. But it still uses file_get_contents or curl libraries to fetch the data so it might need some fiddling to get javascript working.
I wrote a script to download images form google Image search which I currently downloading 100 original images
The original script I wrote on stackoverflow answer
Python - Download Images from google Image search?
which I will explain in detail how I am scraping url’s of original Images from Google Image search using urllib2 and BeautifulSoup
For example if u want to scrape images of movie terminator 3 from google image search
query= "Terminator 3"
query= '+'.join(query.split()) #this will make the query terminator+3
url="https://www.google.co.in/search?q="+query+"&source=lnms&tbm=isch"
header={'User-Agent':"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36"
}
req = urllib2.Request(url,headers=header)
soup= urllib2.urlopen(req)
soup = BeautifulSoup(soup)
variable soup above contains the html code of the page that is requested now we need to extract the images for that u have to open the web page in your browser and and do inspect element on the image
here you will find the the tags containing the image of the url
for example for google image i found "div",{"class":"rg_meta"} containing the link to image
You can search up the BeautifulSoup documentation
print soup.find_all("div",{"class":"rg_meta"})
You will get a list of results as
<div class="rg_meta">{"cl":3,"cr":3,"ct":12,"id":"C0s-rtOZqcJOvM:","isu":"emuparadise.me","itg":false,"ity":"jpg","oh":540,"ou":"http://199.101.98.242/media/images/66433-Terminator_3_The_Redemption-1.jpg","ow":960,"pt":"Terminator 3 The Redemption ISO \\u0026lt; GCN ISOs | Emuparadise","rid":"VJSwsesuO1s1UM","ru":"http://www.emuparadise.me/Nintendo_Gamecube_ISOs/Terminator_3_The_Redemption/66433","s":"Screenshot Thumbnail / Media File 1 for Terminator 3 The Redemption","th":168,"tu":"https://encrypted-tbn2.gstatic.com/images?q\\u003dtbn:ANd9GcRs8dp-ojc4BmP1PONsXlvscfIl58k9hpu6aWlGV_WwJ33A26jaIw","tw":300}</div>
the result above contains link to our image url
http://199.101.98.242/media/images/66433-Terminator_3_The_Redemption-1.jpg
You can extract these links and images as follows
ActualImages=[]# contains the link for Large original images, type of image
for a in soup.find_all("div",{"class":"rg_meta"}):
link , Type =json.loads(a.text)["ou"] ,json.loads(a.text)["ity"]
ActualImages.append((link,Type))
for i , (img , Type) in enumerate( ActualImages):
try:
req = urllib2.Request(img, headers={'User-Agent' : header})
raw_img = urllib2.urlopen(req).read()
if not os.path.exists(DIR):
os.mkdir(DIR)
cntr = len([i for i in os.listdir(DIR) if image_type in i]) + 1
print cntr
if len(Type)==0:
f = open(DIR + image_type + "_"+ str(cntr)+".jpg", 'wb')
else :
f = open(DIR + image_type + "_"+ str(cntr)+"."+Type, 'wb')
f.write(raw_img)
f.close()
except Exception as e:
print "could not load : "+img
print e
Voila now u can use this script to download images from google search. Or for collecting training images
For the fully working script you can get it here
https://gist.github.com/rishabhsixfeet/8ff479de9d19549d5c2d8bfc14af9b88