Webbrowser, detect if there is a PDF reader installed? - pdf

Is there a way to check if the user has installed a PDF reader?
Maybe with a ActiveX component?
Could you please help me?

You can detect installed plugins with window.navigator.plugins
This will return an array with details of installed plugins, but this will not work for Internet Explorer. When running this code, IE only returns an array with embed tags in the page. Thanks IE, so useful?
Ok, let's try to work this out. The following function should work in all major browsers expect IE.
function hasPlugin(name) {
name = name.toLowerCase();
var plugins = window.navigator.plugins;
for (var i=0, len = plugins.length; i < len; i++) {
if (plugins[i].name.toLowerCase().indexOf(name) > -1) {
return true;
}
}
return false;
}
you can call this function and check the plugin status like this
hasPlugin('Flash');
hasPlugin('QuickTime');
For IE, we should try this
function hasPlugin(name) {
try {
new ActiveXObject(name);
return true;
} catch (e) {
return false;
}
}
you can call this function and check the plugin status for IE
hasPlugin('ShockwaveFlash.ShockwaveFlash');
You can made this function declaration cross browser like this
var hasPlugin;
if (navigator.userAgent.indexOf('MSIE')) {
hasPlugin = function(name) {
try {
new ActiveXObject(name);
return true;
} catch (e) {
return false;
}
}
}
else {
hasPlugin = function(name) {
name = name.toLowerCase();
var plugins = window.navigator.plugins;
for (var i=0, len = plugins.length; i < len; i++) {
if (plugins[i].name.toLowerCase().indexOf(name) > -1) {
return true;
}
}
return false;
}
}
Then you can call the function in a cross browser way. I am sorry, I don't installed any PDF plugin for my browsers, -Firefox, Chrome or IE- so I could tell you exact name the argument we should pass hasPlugin function.
I hope, this will help you. By the way, I did not tried the code in browsers, this is a therocial knowledge on me. But I guess this will help you -hope- :-)

No, I don't think so - but you could always direct your links through Google's PDF reader by default - which will work for everyone.
http://docs.google.com/viewer
Please be aware that this will channel your PDF files through Google's servers, so you will lose an element of security.

This was very useful for me:
Java script - Adobe plug-in detector
From comments area, get the corrections for Safari Browser too.

Related

how can I solve edittext recursion problem?

I was trying to implement live typeface change's in the edittextview
based on markdown syntax
and the first code I do was
my_edit_text_view.text = makeMDStyleSpannable(my_edit_text_view.text)//returns spannableString
but no luck since it is not invoking every time when text is changed
so I gave another try which is creating listener and testing things are working properly before I jump
my_edit_text_view.text = doOnTextChanged { it, start, count,after ->
if (it != null) {
if(it.isNotEmpty()){
Toast.makeText(this, (makeMDStyleSpannable(it)), Toast.LENGTH_SHORT).show()
}else if(it.isNullOrEmpty()){
}
}
}
as result it worked on another TOAST
However, here's the real recurring happened
my_edit_text_view.text = doOnTextChanged { it, start, count,after ->
if (it != null) {
if(it.isNotEmpty()){
my_edit_text_view.text = (makeMDStyleSpannable(it)
}else if(it.isNullOrEmpty()){
}
}
}
umm, what actually happening is while there is external text change(keyboard) on the edittext it calls makeMDStyleSpannable and this apply internal change then again and again it will call doOnTextChanged, Finally crashes.
How could I solve this problem?
keyboard(onText added[external]) => startThelistner => makeMDStyleSpannable[in]
/\ ||
||=====[infinite]=======
thanks
You can solve it by adding a boolean to check if text is changed by user or the code.
val shouldIgnoreChange = false
my_edit_text_view.text = doOnTextChanged { it, start, count,after ->
if (it != null) {
if(it.isNotEmpty()){
if(!shouldIgnoreChange){
shouldIgnoreChange = true
my_edit_text_view.text = (makeMDStyleSpannable(it)
shouldIgnoreChange = false
}
}else if(it.isNullOrEmpty()){
}
}
}

"Node is not writable" exception after a camera crash

I'm using the Spinnaker SDK for controlling FLIR cameras. If at any moment the application crashes with a camera being used, every next execution of the application throws an AccessException, like:
Spinnaker::GenApi::CommandNode::Execute: Message = GenICam::AccessException= Node is not writable. : AccessException thrown in node 'UserSetLoad' while calling 'UserSetLoad.Execute()'
The only solution I've found so far is to unplug and plug in the camera, but this is not an acceptable solution in some environments where the application is going to be used.
Here a sample code (not fully compilable since it is extracted from a larger codebase, but gives you an idea of the workflow):
// System instance is prepared before using the camera
Spinnaker::SystemPtr m_system = Spinnaker::System::GetInstance();
// Method in class that initializes the camera
bool initCamera(int index)
{
SmartCameraList cameras(m_system->GetCameras());
const auto cameras_count = cameras.GetSize();
if (cameras_count < 1) { return false; }
if (index >= (int)cameras_count) { return false; }
m_camera = cameras[index];
if (!m_camera) { return false; }
if (m_camera->IsInitialized()) { return false; } // passes
m_camera->DeInit(); // does nothing
m_camera->Init();
if (!m_camera->IsInitialized()) { return false; } // passes
// Default properties
try {
m_camera->UserSetSelector.SetValue(UserSetSelector_Default);
m_camera->UserSetDefault.SetValue(UserSetDefault_Default);
m_camera->UserSetLoad.Execute(); //< thrown here
m_camera->BalanceWhiteAuto.SetValue(BalanceWhiteAuto_Continuous);
m_camera->SensorShutterMode.SetValue(SensorShutterMode_Global);
} catch (Spinnaker::Exception e) {
std::cout << e.GetFullErrorMessage() << '\n';
return false;
}
return true;
}
// m_system->ReleaseInstance() is called when the application finishes using the camera
As you can see, camera is correctly initialized, but it seems that something else is holding the camera.
I've checked in official forums, looking for more generic GenICam related issues and nothing.
Is there any way to reset the camera before using it?
I solved this issue by connecting and disconnecting to the camera SW wise.
Starting capture by launching the following code in a separate thread:
void Cam::MainThread(){
m_cameraHandler->BeginAcquisition();
while(m_threadCtx.wait(ZERO_DURATION)){ //sleepwait
try {
ImagePtr pResultImage = m_cameraHandler->GetNextImage(1000);
const size_t width = pResultImage->GetWidth();
const size_t height = pResultImage->GetHeight();
cv::Mat_<uint16_t> img(height,width);
memcpy(img.data,pResultImage->GetData(),pResultImage->GetWidth()*pResultImage->GetHeight()*sizeof(uint16_t));
if (pResultImage->IsIncomplete())
cout << "Error";
else {
pResultImage->Release();
}
}
catch (Spinnaker::Exception& e)
{
CLerror << "Error: " << e.what();
}
}
}
Then stopping the camera
m_threadCtx.stop();
m_pMainThread->join();
m_cameraHandler->EndAcquisition();
m_cameraHandler->DeInit();
m_cameraHandler = nullptr;
m_spCameraList = nullptr;
delete(m_pMainThread);
After that you can open the camera and upload the file again and it should work.
worked for me

WebdriverIO function reusability pattern

I am transitioning from Selenium to WebdriverIO and I'm running into some difficulty regarding function reusability. Let me demonstrate with an example:
<nav>
<div><a>Clients</a></div>
<div><a>Accounts</a></div>
<div><a>Packages</a></div>
</nav>
lets say I have a navigation bar with 3 links above. When I land on this page, I want to check if each link exists. My function may look something like this:
class LoginPage extends Page {
get clientsLink() { return $('//a[contains(., "Clients")]'); }
isTabDisplayed() {
if (this.clientsLink.isDisplayed()) {
return true;
} else {
false
}
}
}
this is fine except I would have to write 2 more getters for Accounts and Packages and so my class would look like this:
class LoginPage extends Page {
get clientsLink() { return $('//a[contains(., "Clients")]'); }
get accountsLink() { return $('//a[contains(., "Accounts")]'); }
get packagesLink() { return $('//a[contains(., "Packages")]'); }
isClientTabDisplayed(tab) {
if (this.clientsLink.isDisplayed()) {
return true;
} else {
false
}
}
isAccountsTabDisplayed(tab) {
if (this.accountsLink.isDisplayed()) {
return true;
} else {
false
}
}
isPackagesTabDisplayed(tab) {
if (this.packagesLink.isDisplayed()) {
return true;
} else {
false
}
}
}
at this point, my anxiety kicks in and I start to think of ways I can reuse the isTabDisplayed function where I can pass a string to the getter with my tab name, or something along the lines of that.
Unfortunately, getters do not accept parameters and so far I have not found any resources on google that can help me to solve this issue (most common being Page Object Model which doesn't seem to address this problem)
Is my thought process out of line that I am striving for reusable code in UI testing or am I not googling for correct patterns?
Page Objects in WebdriverIO are just plain ES6 classes. Have a look through the documentation on ES6 classes to understand how you can create functions that you can pass arguments in to.
Now, that being said, what you're doing here isn't necessary. Instead of creating a function which references a getter, why not just reference that getter directly in your test?
const login = new LoginPage();
const isAccountsTabDisplayed = login.accountsLink.isDisplayed();
There's really no reason to create a wrapper function around this.

Copy Google Spreadsheet + Share with same users in script

I have searched the far reaches of the internet for a couple days now, but cannot seem to find a solution to my issue. I have limited knowledge of programming, but if I can get this to work, it is going to do wonderful things.
EXPLANATION: I need to make a copy of a template spreadsheet, using a script inside spreadsheet A and copy over all the permissions of the template into the copy (specifically the name and protected ranges). I am using SheetSpider.
As of right now, I can create the duplicate of the template, but SheetSpider seems to drop the permissions that the template has, and rewrites them with users that you define during the setup process. Instead, I would just like to copy the permissions of the template file. It seems to be tricky because a regular copy of the spreadsheet still does not bring over the permissions for the name and protected range settings like it would if you go to file > copy spreadsheet and check the box that says "and share with the same users" which DOES retain protected range settings.
Again, I have a very limited knowledge of programming, but I think I have pinpointed the lines that seem to drop and reset the permissions. I have tried playing with the below for days now to get it to leave the permissions alone, but to no avail.
Any help or guidance would be greatly appreciated!
Thanks!
function checkFixFileACLs(file, approvedViewers, approvedEditors) {
var viewers = file.getViewers().join(",");
viewers = viewers.split(",");
var editors = file.getEditors().join(",");
editors = editors.split(",");
viewers = arr_diff(editors, viewers);
var owner = file.getOwner().toString();
var fileKey = file.getId();
var driveFile = DriveApp.getFileById(fileKey);
var currViewers = [];
for (var k=0; k<viewers.length; k++) {
if ((viewers[k]!='')&&(approvedViewers.indexOf(viewers[k].toLowerCase())==-1)&&(approvedEditors.indexOf(viewers[k].toLowerCase())==-1)&&(viewers[k]!=owner)) {
try {
call(function() {driveFile.removeViewer(viewers[k].toLowerCase());});
} catch(err) {
Logger.log(err.message);
}
} else {
currViewers.push(viewers[k].toLowerCase());
}
}
for (var k=0; k<approvedViewers.length; k++) {
if ((approvedViewers[k]!='')&&(approvedViewers[k])) {
if (currViewers.indexOf(approvedViewers[k])==-1) {
try {
call(function() {driveFile.addViewer(approvedViewers[k].toLowerCase());});
} catch(err) {
Logger.log(err.message);
}
}
}
}
var currEditors = [];
for (var k=0; k<editors.length; k++) {
if ((editors[k]!='')&&(approvedEditors.indexOf(editors[k].toLowerCase())==-1)&&(editors[k]!=owner)) {
try {
call(function() {driveFile.removeEditor(editors[k].toLowerCase());});
} catch(err) {
Logger.log(err.message);
}
} else {
currEditors.push(editors[k].toLowerCase().replace(/\s+/g, ''));
}
}
for (var k=0; k<approvedEditors.length; k++) {
if ((approvedEditors[k]!='')&&(approvedEditors[k])) {
if (currEditors.indexOf(approvedEditors[k].toLowerCase())==-1) {
try {
call(function() {driveFile.addEditor(approvedEditors[k].toLowerCase().replace(/\s+/g, ''));});
} catch(err) {
Logger.log(err.message);
}
}
}
}
return;
}
Here a script that will copy the spreadsheet with permissions when run. However, it will turn commentators into viewers. This is avoidable with more code but is not very easy because there is no file method for getting commentators.
function myFunction() {
var file = DriveApp.getFileById(SpreadsheetApp.getActiveSpreadsheet().getId()).makeCopy();
var editors = DriveApp.getFileById(SpreadsheetApp.getActiveSpreadsheet().getId()).getEditors();
for (var i = 0; i<editors.length;i++) {
file.addEditor(editors[i])
}
var viewers = DriveApp.getFileById(SpreadsheetApp.getActiveSpreadsheet().getId()).getViewers();
for (var i = 0; i<viewers.length;i++) {
file.addViewer(viewers[i])
}
}

JavaScript - run once without booleans

Is there a way to run a piece of JavaScript code only ONCE, without using boolean flag variables to remember whether it has already been ran or not?
Specifically not something like:
var alreadyRan = false;
function runOnce() {
if (alreadyRan) {
return;
}
alreadyRan = true;
/* do stuff here */
}
I'm going to have a lot of these types of functions and keeping all booleans would be messy...
An alternative way that overwrites a function when executed so it will be executed only once.
function useThisFunctionOnce(){
// overwrite this function, so it will be executed only once
useThisFunctionOnce = Function("");
// real code below
alert("Hi!");
}
// displays "Hi!"
useThisFunctionOnce();
// does nothing
useThisFunctionOnce();
'Useful' example:
var preferences = {};
function read_preferences(){
// read preferences once
read_preferences = Function("");
// load preferences from storage and save it in 'preferences'
}
function readPreference(pref_name){
read_prefences();
return preferences.hasOwnProperty(pref_name) ? preferences[pref_name] : '';
}
if(readPreference('like_javascript') != 'yes'){
alert("What's wrong wth you?!");
}
alert(readPreference('is_stupid') ? "Stupid!" : ":)");
Edit: as CMS pointed out, just overwriting the old function with function(){} will create a closure in which old variables still exist. To work around that problem, function(){} is replaced by Function(""). This will create an empty function in the global scope, avoiding a closure.
I like Lekensteyn's implementation, but you could also just have one variable to store what functions have run. The code below should run "runOnce", and "runAgain" both one time. It's still booleans, but it sounds like you just don't want lots of variables.
var runFunctions = {};
function runOnce() {
if(!hasRun(arguments.callee)) {
/* do stuff here */
console.log("once");
}
}
function runAgain() {
if(!hasRun(arguments.callee)) {
/* do stuff here */
console.log("again");
}
}
function hasRun(functionName) {
functionName = functionName.toString();
functionName = functionName.substr('function '.length);
functionName = functionName.substr(0, functionName.indexOf('('));
if(runFunctions[functionName]) {
return true;
} else {
runFunctions[functionName] = true;
return false;
}
}
runOnce();
runAgain();
runAgain();
A problem with quite a few of these approaches is that they depend on function names to work: Mike's approach will fail if you create a function with "x = function() ..." and Lekensteyn's approach will fail if you set x = useThisFunctionOnce before useThisFunctionOnce is called.
I would recommend using Russ's closure approach if you want it run right away or the approach taken by Underscore.js if you want to delay execution:
function once(func) {
var ran = false, memo;
return function() {
if (ran) return memo;
ran = true;
return memo = func.apply(this, arguments);
};
}
var myFunction = once(function() {
return new Date().toString();
});
setInterval(function() {console.log(myFunction());}, 1000);
On the first execution, the inner function is executed and the results are returned. On subsequent runs, the original result object is returned.
What about an immediately invoked anonymous function?
(function () {
// code in here to run once
})();
the code will execute immediately and leave no trace in the global namespace.
If this code is going to need to be called from elsewhere, then a closure can be used to ensure that the contents of a function are run only once. Personally, I prefer this to a function that rewrites itself as I feel doing so can cause confusion, but to each their own :) This particular implementation takes advantage of the fact that 0 is a falsy value.
var once = (function() {
var hasRun = 0;
return function () {
if (!hasRun) {
hasRun++;
// body to run only once
// log to the console for a test
console.log("only ran once");
}
}
})();
// test that the body of the function executes only once
for (var i = 0; i < 5; i++)
once();
Elegant solution from Douglas Crockford, spent some time to understand how it works and stumbled upon this thread.
So the wrapper once return function which is just invokes parameter's function you passed. And taking advantage of closures this construction replaced passed function to empty function, or null in original source, after the first call, so all the next calls will be useless.
This is something very close to all other answers, but it is kinda self containing code and you could use it independently, which is good. I am still trying to grasp all the entire mechanism of replacement, but practically it just works perfectly.
function once (func) {
return function () {
var f = func;
func = null;
return f.apply(this, arguments);
};
}
function hi(name) {
console.log("Hi %s", name);
}
sayonce = once(hi);
sayonce("Vasya");
sayonce("Petya");
for those who are curious here is jsbin transformations
(function (){
var run = (function (){
var func, blank = function () {};
func = function () {
func = blank;
// following code executes only once
console.log('run once !');
};
return function(){
func.call();
};
})();
run();
run();
run();
run();
})();
I just ran into this problem, and ended up doing something like the following:
function runOnce () {
if (!this.alreadyRan) {
// put all your functionality here
console.log('running my function!');
// set a property on the function itself to prevent it being run again
this.alreadyRan = true;
}
}
This takes advantage of the fact that Javascript properties are undefined by default.
In addition, the nature of what happens in the "/* do stuff here */" may leave something around that, when present, must mean that the function has run e.g.
var counter = null;
function initCounter() {
if (counter === null) {
counter = 0;
}
}
If not bound to an event, code is usually ran once