exif_read_data suppressing IFD error - exif

Is there any way to suppress exif data 'Illegal IFD size' error? The following has not worked:
if (#exif_read_data($targetFile)) {
$exif = #exif_read_data($targetFile);
}
// this also failed
if ($exif = #exif_read_data($targetFile)) {
blah, blah
}
// as did this
$exif = #exif_read_data($targetFile);
if ($exif) {

My only resolve to this was via my error handler function, here it is should anyone need it:
function error_report ($e_num, $e_mes, $e_file, $e_line, $e_vars) {
if (strpos($e_mes, 'exif_read_data') === false) {
// report message
}
}
set_error_handler ('error_report');

You can use try-catch in this case:
try {
$exif = exif_read_data($filePath);
}
catch (Exception $exp) {
$exif = false;
}
if ($exif){
...
}

Related

define a constant instead of duplicating 5 times

I'm fairly new to Node.js and I am having some issues.
I received error in sonarqube as define a constant instead of duplicating 5 times for "-deleteFlag". how can i resolved this issue.
export class CCGuid {
"-deleteFlag": string;
"#text": string;
constructor(obj: any) {
if (typeof obj === "string") {
this["#text"] = obj;
this["-deleteFlag"] = "N";
} else {
try {
this["-deleteFlag"] = obj["-deleteFlag"];
} catch {
this["-deleteFlag"] = undefined;
}
try {
this["#text"] = obj["#text"];
} catch {
this["#text"] = undefined;
}
}
}
}
export class CCGuid {
"-deleteFlag": string;
"#text": string;
constructor(obj: any) {
const deleteFlag = "-deleteFlag";
if (typeof obj === "string") {
this["#text"] = obj;
this[deleteFlag] = "N";
} else {
try {
this[deleteFlag] = obj[deleteFlag];
} catch {
this[deleteFlag] = undefined;
}
try {
this["#text"] = obj["#text"];
} catch {
this["#text"] = undefined;
}
}
}
}
I think this should do the trick with SQ, at least when it comes to that particular variable. You can do the same with "#text" of course.
After edit: sorry my first answer was broken, I was in a rush and didn't realize what I was really writing down.
Given my updated snippet, you can do the following:
this[deleteFlag']: This will work.
this['-deleteFlag']: This will of course work but Sonar Qube will complain because your use of duplicated string literals.
this.deleteFlag: This won't work because would be looking for a deleteFlag key on the object. Such key doesn't exist, it's '-deleteFlag'.
this['deleteFlag']: this is functionally the same as the line above. Would look for a 'deletFlag' key on the object, which doesn't exist.
Sorry for the confusion! Hope this helps now

Issues with ActiveXObject in Angular 7

I am developing a small page/router component on a website using Angular 7 and its CLI. At one point I need to check if the user has allowed flash, I do this by doing so:
checkFlash() {
var hasFlash = false;
try {
hasFlash = Boolean(new ActiveXObject("ShockwaveFlash.ShockwaveFlash"));
} catch (exception) {
hasFlash = "undefined" != typeof navigator.mimeTypes["application/x-shockwave-flash"];
}
return hasFlash;
}
I found this off here, and it works great, but now as I am cleaning up my application I am noticing that Angular doesn't seem to like this, in fact, it says that ActiveXObject isn't defined, yet it still works.
Super confused...
I tried linking an actual flash object like so $('embed[type="application/x-shockwave-flash"]') or $('embed[type="application/x-shockwave-flash"]')[0] but had no luck, it always returned true.
I tried installing extra npm(s) including ones like activex-support and activex-data-support as well as their #types cousins. After setting them up I found out that they did nothing to help my case.
Here are the exact errors the CLI & VScode-Intellisense gave me:
VScode:
[ts] 'ActiveXObject' only refers to a type, but is being used as a value here. [2693]
any
CLI:
ERROR in src/app/games/games.component.ts(51,30): error TS2304: Cannot find name 'ActiveXObject'.
It doesn't throw this error when ran inside plain JS, but I've looked around and can't seem to figure out how to run pure JS inside Angular 2 (7). Also looked here with no luck.
Please help, completely lost here.
EDIT: Found the fix -->
The answer was here listed inside the comments (will need to make minor changes)(shown below)
change from:
checkFlash() {
var hasFlash = false;
try {
hasFlash = Boolean(new ActiveXObject("ShockwaveFlash.ShockwaveFlash"));
} catch (exception) {
hasFlash = "undefined" != typeof navigator.mimeTypes["application/x-
shockwave-flash"];
}
return hasFlash;
}
to:
function checkFlash() {
var hasFlash = false;
try {
var flash =
navigator.mimeTypes &&
navigator.mimeTypes["application/x-shockwave-flash"]
? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin
: 0;
if (flash) hasFlash = true;
} catch (e) {
if (navigator.mimeTypes["application/x-shockwave-flash"] != undefined)
hasFlash = true;
}
return hasFlash;
}
This issue with ActiveXObject can be solve as shown below:
Goto your tsconfig.json file and add the 'scripthost' library.
Then recompile your application.
"lib": [
"es2017",
"dom",
"scripthost"
]
The answer was here listed inside the comments (will need to make minor changes)(shown below)
change from:
checkFlash() {
var hasFlash = false;
try {
hasFlash = Boolean(new ActiveXObject("ShockwaveFlash.ShockwaveFlash"));
} catch (exception) {
hasFlash = "undefined" != typeof navigator.mimeTypes["application/x-
shockwave-flash"];
}
return hasFlash;
}
to:
function checkFlash() {
var hasFlash = false;
try {
var flash =
navigator.mimeTypes &&
navigator.mimeTypes["application/x-shockwave-flash"]
? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin
: 0;
if (flash) hasFlash = true;
} catch (e) {
if (navigator.mimeTypes["application/x-shockwave-flash"] != undefined)
hasFlash = true;
}
return hasFlash;
}

NodeJS Error Encapsulation

I am currently trying to handle exceptions and errors in a NodeJS app which will be used for critical information. I need a clean error management !
I've been wondering if there is something similar to Java Exceptions encapsulation.
I'm explaning.
In Java you can do something like that :
try {
// something that throws Exception
} catch (Throwable t) {
throw new Exception("My message", t);
}
That allows you to decide when to log your exception and you get the whole stack trace and call path !
I would like to know if there is a way to do the same in NodeJS because logging at every step seems not to be the right way of doing things.
Thank you.
You should look at this module :
https://www.npmjs.com/package/verror
Joyent quote it on his error management best pratices : https://www.joyent.com/developers/node/design/errors
At Joyent, we use the verror module to wrap errors since it's
syntactically concise. As of this writing, it doesn't quite do all of
this yet, but it will be extended to do so.
It allow you to get details on error message. And tracking the step of the error.
And also hide details to the client with wrapped error : WError() who returns only the last error message.
I answer my own question to explain what i finaly did to have the wanted encapsulation.
I used https://www.npmjs.com/package/verror as Sachacr suggested.
Then I extended it that way :
my_error.js :
var VError = require('verror');
var _ = require('lodash');
function MyError() {
var args = [];
var httpErrorCode;
var cause;
if (arguments.length > 0) {
var lastArgumentIndex = [arguments.length];
cause = manageCause(lastArgumentIndex, arguments);
httpErrorCode = manageHttpCode(lastArgumentIndex, arguments);
for (var i = 0; i < lastArgumentIndex; i++) {
args[i] = arguments[i];
}
}
this.__proto__.__proto__.constructor.apply(this, args);
if (cause) {
if (this.stack) {
this.stack += '\n' + cause.stack;
} else {
this.stack = cause.stack;
}
}
this.httpErrorCode = httpErrorCode;
}
MyError.prototype.__proto__ = VError.prototype;
function manageCause(lastArgumentIndex, arguments) {
if (lastArgumentIndex[0] > 0
&& arguments[lastArgumentIndex[0] - 1] instanceof Error) {
lastArgumentIndex[0]--;
return arguments[lastArgumentIndex[0]];
}
}
function manageHttpCode(lastArgumentIndex, arguments) {
if (lastArgumentIndex[0] > 0
&& _.isNumber(arguments[lastArgumentIndex[0] - 1])) {
lastArgumentIndex[0]--;
return arguments[lastArgumentIndex[0]];
}
}
module.exports = MyError;
It allows me to use it easily in my code :
var MyError = require('./my_error.js');
function withErrors() {
try {
// something with errors
} catch (err) {
// This is the same pattern as VError
return new MyError("My message", err, 401);
}
}
function somethingToDo(req, res) {
var result = withErrors();
if (result instanceof MyError) {
logger.warn(result);
res.status(result.httpErrorCode).send(result.message).end();
return
}
}
That way, i hace a nice stack trace with call path and every line involved in error/exception.
Hope it will help people, cause i searched a looooong time :)
EDIT : I modified my MyError class to add HTTP Error codes and clean arguments management.
You should be able to do something like:
funtion exception(message, error) {
this.message = message;
this.stacktrace = error.stack;
}
try {
if(someData == false)
throw new exception("something went wrong!", new Error());
}
catch(ex) {
console.log(ex.message);
console.log(ex.stacktrace);
}
You can then throw your own custom exception instance containing whatever debugging info you need.
EDIT: added stack trace to exception object

C++/CLI code doesn't enter .then part of the create_task function

This is the code that I have:
void MainPage::OnNavigatedTo(NavigationEventArgs^ e)
{
XTRACE(L"=========================================will start onNavigated ");
auto mediaCapture = ref new Windows::Media::Capture::MediaCapture();
m_mediaCaptureMgr = mediaCapture;
IAsyncAction ^asyncAction = m_mediaCaptureMgr->InitializeAsync();
try
{
create_task(asyncAction).then([this](task<void> initTask)
{
XTRACE(L"=========================================will start onNavigated 2");
try
{
initTask.get();
auto mediaCapture = m_mediaCaptureMgr.Get();
if (mediaCapture->MediaCaptureSettings->VideoDeviceId != nullptr && mediaCapture->MediaCaptureSettings->AudioDeviceId != nullptr)
{
String ^fileName;
fileName = VIDEO_FILE_NAME;
XTRACE(L"=================================Device initialized successful\n");
create_task(KnownFolders::VideosLibrary->CreateFileAsync(fileName, Windows::Storage::CreationCollisionOption::GenerateUniqueName))
.then([this](task<StorageFile^> fileTask)
{
XTRACE(L"=================================Create record file successful\n");
m_recordStorageFile = fileTask.get();
MediaEncodingProfile^ recordProfile = nullptr;
recordProfile = MediaEncodingProfile::CreateMp4(Windows::Media::MediaProperties::VideoEncodingQuality::Auto);
stream = ref new InMemoryRandomAccessStream();
return m_mediaCaptureMgr->StartRecordToStreamAsync(recordProfile, stream);
}).then([this](task<void> recordTask)
{
try
{
recordTask.get();
XTRACE(L"=================================Start Record successful\n");
}
catch (Exception ^e)
{
XTRACE(L"======ERRROR is : %d", e);
}
});
}
else
{
XTRACE(L"=================================No VideoDevice/AudioDevice Found\n");
}
XTRACE(L"=================================WILL EXIT \n");
}
catch (Exception ^ e)
{
XTRACE(L"============================================ERROR IS: %d\n", e);
}
}
);
}
catch (Exception ^ e)
{
XTRACE(L"============================================before create task ERROR IS: %d\n", e);
}
XTRACE(L"=================================SLEEP 20000====================================\n");
std::chrono::milliseconds dura(20000);
std::this_thread::sleep_for(dura);
XTRACE(L"=================================TIME ENDED====================================\n");
// stop device detection
try
{
XTRACE(L"=================================Stopping Record\n");
create_task(m_mediaCaptureMgr->StopRecordAsync())
.then([this](task<void> recordTask)
{
try
{
recordTask.get();
XTRACE(L"=================================Stop record successful: %d\n", stream->Size);
}
catch (Exception ^e)
{
XTRACE(L"=================================ERROR while stoping 2: %d\n", e);
}
});
}
catch (Exception ^e)
{
XTRACE(L"=================================ERROR try catch 3 stoping: %d\n", e);
}
CloseHandle(ghEvent);
// destruct the device manager
XTRACE(L"=====================================================================END\n");
}
In the log I see:
=========================================will start onNavigated
And then directly:
=====================================================================
=================================SLEEP 20000====================================
What is strange is that I had this code in a unittest and it worked, I created a new windows phone project with a UI and it doesn't work
Apparently it was because of the ThreadSleep:
std::chrono::milliseconds dura(20000);
std::this_thread::sleep_for(dura);
In the library project where I was working I was using a different sleep, provided by the library, and that would work. So this was the line that would cause the application to block itself.
I worked my way around this by including 2 buttons in the app, for the start and stop recording.

Monitoring chrome.storage throttle limits

I'm using chrome.storage in an extension and would like to avoid triggering runtime errors due to exceeding one of the documented throttles for either the sync or local stores. (things like QUOTA_BYTES, QUOTA_BYTES_PER_ITEM)
My first choice would be to intercept these errors prior to a runtime error being generated; alternatively I could track usage on the extension side and try to avoid triggering them.
This feels like an issue that someone must have addressed, but I can't seem to find any solutions - any suggestions appreciated.
Here's a sample of the solution I'm going with (using Angular, so there are promises in here), although having to regex the chrome.runtime.lastError value is pretty ugly IMO:
var service = {
error: function(lastError) {
if((lastError) && (lastError.message)) {
var errorString = lastError.message;
if(/QUOTA_BYTES/.test(errorString)) {
return true;
} else if(/QUOTA_BYTES_PER_ITEM/.test(errorString)) {
return true;
} else if(/MAX_ITEMS/.test(errorString)) {
return true;
} else if(/MAX_WRITE_OPERATIONS_PER_HOUR/.test(errorString)) {
return true;
} else if(/MAX_SUSTAINED_WRITE_OPERATIONS_PER_MINUTE/.test(errorString)) {
return true;
}
return false;
} else {
return false;
}
},
write: function(key, value) {
var deferred = $q.defer();
var data = {};
data[key] = value;
chrome.storage.sync.set(data, function() {
if(service.error(chrome.runtime.lastError)) {
deferred.reject('Write operation failed: '
+ chrome.runtime.lastError.message);
} else {
deferred.resolve();
}
});
return deferred.promise;
}
};
return service;

Resources