Modify image format (from default jpg to another) - m2doc

I'm trying to change the format of an image I want to export in Word.
According to the PictureType.java class, it seems possible but after a few tests it doesn't seem to be working properly.
I used this line:
{m: '[PAB] A. SIEG.4_UP-CTB (LTTBI).jpg'.asImage('emf')} but the file is still in the jpg format.
Is it possible to have further information as to how the conversion method "totype" works?
I don't have any messages of error and the image is well exported but in jpg format, so I can only assume there is a possible Exception raised but caught and therefore no trace as there is no message in the "catch" exception :
try {
res = valueOf(extension.toUpperCase());
} catch (IllegalArgumentException ignored) {
// Simply ignore this exception. It means that the
// given extension is unknown.
// JPG type will be returned by default.
}
or more likely this one which appears further in the method :
try {
res = valueOf(type.substring(MIME_IMAGE_TYPE.length()).toUpperCase());
} catch (IllegalArgumentException ignored) {
// Simply ignore this exception. It means that the
// given extension is unknown.
// JPG type will be returned by default.
}
Thanks in advance for your answers.

The type passed to the asImage() service is used to tell M2Doc the format of the image if it can't be computed from the file extension. It's not used to convert the image format. To do that, you can create a Java service and use javax.imageio.ImageIO for instance.

Related

Setting up setCharging for Linea Pro device in Swift

I want to set up the Linea Pro to charge the phone if the phone's battery gets low and I'm having a tough time mainly because all the examples are shown in objective-C still and not in Swift.
The manual says:
#param enabled TRUE to enable charging, FALSE to disable/stop it
#param error pointer to NSError object, where error information is stored in case function fails. You can pass nil if you don't want that information
#return TRUE if function succeeded, FALSE otherwise
*/
and the code provided is the following:
-(BOOL)setCharging:(BOOL)enabled error:(NSError **)error;
So in Swift I first tried this:
self.scanner.setCharging = true
but that gives me the following error:
Cannot assign to property: 'setCharging' is a method
So I tried this:
self.scanner.setCharging(true)
which gives me this error:
Call can throw, but it is not marked with 'try' and the error is not handled
Interesting because apparently I have to build it in a function called "setCharging" I think, but I have no idea what and how it wants me to set up the try and catch to, and quite frankly where am I opposed to get this information from?
I think it should be along these lines or something, but I'm not clear on the specifics :
func setCharging(_ enabled: Bool) throws -> Bool {
do {
try
//something goes here I'm not sure what
} catch {
//and then maybe something here on that to do with error
print("some error")
}
}
The answer was provided to me by the manufacturer. It is unnecessary to create a function with the same name as the API, APIs can be called anywhere in the code with the exception of handling error. So in this case I just have this directly in my code not in a function and it just works. (Since I have my scanner.connect code inside a viewWillAppear block, the code to start charging was too early to be called in there, so I placed it inside of a viewDidAppear block).
The following is the code:
do{
try self.scanner.setCharging(true)
}catch let error as NSError{
NSLog("Operation \(error as Error)")
}

register ErrorCollector or intercept parse errors for wire format?

When It is possible to define a custom ErrorCollector class for handling google::protobuf parsing errors
struct ErrorCollector : ::google::protobuf::io::ErrorCollector
{
void AddError(int line, int column, const std::string& message) override
{
// log error
}
void AddWarning(int line, int column, const std::string& message) override
{
// log warning
}
};
When parsing from a text file, you can use the protobuf TextFormat class and register your custom ErrorCollector
::google::protobuf::io::IstreamInputStream input_stream(&file);
::google::protobuf::TextFormat::Parser parser;
ErrorCollector error_collector;
parser.RecordErrorsTo(&error_collector);
if (parser.Parse(&input_stream, &msg))
{
// handle msg
}
For parsing wire format, I currently use Message::ParseFromArray
if (msg.ParseFromArray(data, data_len))
{
// handle msg
}
This doesn't allow me to specify a custom ErrorCollector though.
I've searched through the source code, but as of yet have been unable to find if this is possible.
Is it possible to use an ErrorCollector when parsing wire format?
Is there another way to intercept parse errors and make them available to client code?
There are essentially two ways that parsing the wire format could fail:
The bytes are not a valid protobuf (e.g. they are corrupted, or in a totally different format).
A required field is missing.
For case 1, protobuf does not give you any more information than "it's invalid". This is partly for code simplicity (and speed), but it is also partly because any attempt to provide more information usually turns out more misleading than helpful. Detailed error reporting is useful for text format because text is often written by humans, but machines make very different kinds of errors. In some languages, protobuf actually reports specific errors like "end-group tag does not match start-group tag". In the vast majority of cases, this error really just means "the bytes are corrupted", but inevitably people think the error is trying to tell them something deeper which they do not understand. They then post questions to stack overflow like "How do I make sure my start-group and end-group tags match?" when they really should be comparing bytes between their source and destination to narrow down where they got corrupted. Even reporting the byte position where the parse error occurred is not very useful: protobuf is a dense encoding, which means that many random corrupt byte sequences will parse successfully, which means the parser may only notice a problem somewhere later down the line rather than at the point where things actually went wrong.
The one case that clearly is useful to distinguish is case 2 (missing required fields) -- at least, if you use required fields (I personally recommend avoiding them). There are a couple options here:
Normally, required field checks write errors to the console (on stderr). You can intercept these and record them your own way using SetLogHandler, but this doesn't give you structured information, only text messages.
To check required fields more programmatically, you can separate required field checking from parsing. Use MessageLite::ParsePartialFromArray() or one of the other Partial parsing methods to parse a message while ignoring the absence of required fields. You can then use the MessageLite::IsInitialized() to check if all required fields are set. If it returns false, use Message::FindInitializationErrors() to get a list of paths of all required fields that are missing.

Xerces: How to check the validity of an XML file using ErrorHandler

I am trying to determine if a given XML file is valid (has proper syntax and structure), and I am using Xerces. I have been able to succesfully read proper files but when I give it files with incorrect syntax, no errors are thrown.
I have been fishing around and found out that I might have to use an Error handler and user setErrorHandler to catch the errors instead of the traditional try-throw-catch exception handling.
The problem that I am having though is that I am very confused how to declare the proper handler, set it to my parser and then read the errors if there are any that show up.
Is there any chance somebody could shed some light on my situation?
// #input_parameter from function: const string & xmlConfigArg
xercesc::DOMDocument* doc = NULL;
string xmlConfig(xmlConfigArg);
Handler handler; // I'm not sure what type of handler to use
_parser->setErrorHandler(&handler);
try{
_parser->parse(xmlConfigArg.c_str());
doc = _parser-> getDocument();
}catch(...){
//Nothing is ever caught here
}
You need to derive a class from ErrorHandler (< xercesc/sax/ErrorHandler.hpp >)
then overwrite all the virtual methods there.
After doing so, You can get the error code from the class you created. No exceptions will be thrown in the parsing, so you can wave the try/cache block (or keep it for a different use).

Loading Image from Content to StorageFile^ in Metro C++

I am trying Share an Image in Windows 8 Metro C++ Application using Share Charm. To do so, I need to load image to StorageFile^ first. I assume it should looks like:
create_task(imageFile->GetFileFromPathAsync("Textures/title.png")).then([this](StorageFile^ storageFile)
{
imageFile = storageFile;
});
where imageFile is defined in header file
Windows::Storage::StorageFile^ imageFile;
This actual code would throw this exeption
An invalid parameter was passed to a function that considers invalid parameters fatal.
This seems to be very trivial, but there is a very little documentation about Sharing in Metro, and the only Microsoft example shows how to do sharing using FilePicker.
Would be very grateful if someone knows how to do it properly.
If "Textures" is coming from your application package, you should use StorageFile::GetFileFromApplicationUriAsync instead:
Uri^ uri = ref new Uri("ms-appx:///Assets/Logo.png");
create_task(StorageFile::GetFileFromApplicationUriAsync(uri)).then([](task<StorageFile^> t)
{
auto storageFile = t.get();
auto f = storageFile->FileType;
});
You can also use a task-based continuation (as I show above) in order to inspect the exception information more closely. In your case, the inner exception is: The specified path (Assets/Logo.png) contains one or more invalid characters.
This is due to the forward-slash, if you change it to a backslash you'll see: The specified path (Assets\Logo.png) is not an absolute path, and relative paths are not permitted.
If you want to use GetFileFromPathAsync I would recommend using
Windows::ApplicationModel::Package::Current->InstalledLocation
To figure out where your application is installed and building up your path from there.

Exception handling aware of execution flow

Edit:
For personn interested in a cleaner way to implemenent that, have a look to that answer.
In my job I often need to use third-made API to access remote system.
For instance to create a request and send it to the remote system:
#include "external_lib.h"
void SendRequest(UserRequest user_request)
{
try
{
external_lib::Request my_request;
my_request.SetPrice(user_request.price);
my_request.SetVolume(user_request.quantity);
my_request.SetVisibleVolume(user_request.quantity);
my_request.SetReference(user_request.instrument);
my_request.SetUserID(user_request.user_name);
my_request.SetUserPassword(user_request.user_name);
// Meny other member affectations ...
}
catch(external_lib::out_of_range_error& e)
{
// Price , volume ????
}
catch(external_lib::error_t& e)
{
// Here I need to tell the user what was going wrong
}
}
Each lib's setter do checks the values that the end user has provided, and may thow an exception when the user does not comply with remote system needs. For instance a specific user may be disallowed to send a too big volume. That's an example, and actually many times users tries does not comply: no long valid instrument, the prices is out of the limit, etc, etc.
Conseqently, our end user need an explicit error message to tell him what to modify in its request to get a second chance to compose a valid request. I have to provide hiim such hints
Whatever , external lib's exceptions (mostly) never specifies which field is the source
of aborting the request.
What is the best way, according to you, to handle those exceptions?
My first try at handling those exceptions was to "wrap" the Request class with mine. Each setters are then wrapped in a method which does only one thing : a try/catch block. The catch block then throws a new exceptions of mine : my_out_of_range_volume, or my_out_of_range_price depending on the setter. For instance SetVolume() will be wrapped this way:
My_Request::SetVolume(const int volume)
{
try
{
m_Request.SetVolume(volume);
}
catch(external_lib::out_range_error& e)
{
throw my_out_of_range_volume(volume, e);
}
}
What do you think of it? What do you think about the exception handling overhead it implies? ... :/
Well the question is open, I need new idea to get rid of that lib constraints!
If there really are a lot of methods you need to call, you could cut down on the code using a reflection library, by creating just one method to do the calling and exception handling, and passing in the name of the method/property to call/set as an argument. You'd still have the same amount of try/catch calls, but the code would be simpler and you'd already know the name of the method that failed.
Alternatively, depending on the type of exception object that they throw back, it may contain stack information or you could use another library to walk the stack trace to get the name of the last method that it failed on. This depends on the platform you're using.
I always prefer a wrapper whenever I'm using third party library.
It allows me to define my own exception handling mechanism avoiding users of my class to know about external library.
Also, if later the third party changes the exception handling to return codes then my users need not be affected.
But rather than throwing the exception back to my users I would implement the error codes. Something like this:
class MyRequest
{
enum RequestErrorCode
{
PRICE_OUT_OF_LIMIT,
VOLUME_OUT_OF_LIMIT,
...
...
...
};
bool SetPrice(const int price , RequestErrorCode& ErrorCode_out);
...
private:
external_lib::Request mRequest;
};
bool MyRequest::SetPrice(const int price , RequestErrorCode& ErrorCode_out)
{
bool bReturn = true;
try
{
bReturn = mRequest.SetPrice(price);
}
catch(external_lib::out_of_range_error& e)
{
ErrorCode_out = PRICE_OUT_OF_LIMIT;
bReturn = false;
}
return bReturn;
}
bool SendRequest(UserRequest user_request)
{
MyRequest my_request;
MyRequest::RequestErrorCode anErrorCode;
bool bReturn = my_request.SetPrice(user_request.price, anErrorCode);
if( false == bReturn)
{
//Get the error code and process
//ex:PRICE_OUT_OF_LIMIT
}
}
I think in this case I might dare a macro. Something like (not tested, backslashes omitted):
#define SET( ins, setfun, value, msg )
try {
ins.setfun( value );
}
catch( external::error & ) {
throw my_explanation( msg, value );
}
and in use:
Instrument i;
SET( i, SetExpiry, "01-01-2010", "Invalid expiry date" );
SET( i, SetPeriod, 6, "Period out of range" );
You get the idea.
Although this is not really the answer you are looking for, but i think that your external lib, or you usage of it, somehow abuses exceptions. An exception should not be used to alter the general process flow. If it is the general case, that the input does not match the specification, than it is up to your app to valid the parameter before passing it to the external lib. Exceptions should only be thrown if an "exceptional" case occurrs, and i think whenever it comes to doing something with user input, you usually have to deal with everything and not rely on 'the user has to provide the correct data, otherwise we handle it with exceptions'.
nevertheless, an alternative to Neil's suggestions could be using boost::lambda, if you want to avoid macros.
In your first version, you could report the number of operations that succeeded provided the SetXXX functions return some value. You could also keep a counter (which increases after every SetXXX call in that try block) to note what all calls succeeded and based on that counter value, return an appropriate error message.
The major problem with validating each and every step is, in a real-time system -- you are probably introducing too much latency.
Otherwise, your second option looks like the only way. Now, if you have to write a wrapper for every library function and why not add the validation logic, if you can, instead of making the actual call to the said library? This IMO, is more efficient.