ImageResizer: how do you use Instructions? - imageresizer

The documentation for ResizeSettings says:
"Replaced by the Instructions class"
http://documentation.imageresizing.net/docu/ImageResizer/ResizeSettings.htm
The documentation for Instructions says:
"The successor to ResizeSettings."
http://documentation.imageresizing.net/docu/ImageResizer/Instructions.htm
However, I cannot figure out how to use Instructions instead of ResizeSettings. I've tried
Google
Documentation (documentation.imageresizing.net)
Looking through the Object Browser for uses of Instructions
Searching ImageResizer.dll in .net Reflector for uses of Instructions
Decompiling all of ImageResizer.dll and searching for through the resulting code.
If Instructions replaces ResizeSettings, then how do I use it instead of ResizeSettings?
=== Edit - more detail:
This a way to use ResizeSettings:
public static Bitmap Resize(Bitmap bitmap, int maxHeight, int maxWidth)
{
var setting = new ResizeSettings
{
MaxHeight = maxHeight,
MaxWidth = maxWidth,
};
return ImageBuilder.Current.Build(bitmap, setting);
}
Reading that Instructions was a replacement for ResizeSettings, one of the first things I tried was this: (I was hoping ImageBuilder might have an overloaded Build method)
public static Bitmap Resize(Bitmap bitmap, int maxHeight, int maxWidth)
{
var instructions = new Instructions
{
Width = maxWidth,
Height = maxHeight,
Mode = FitMode.Max
};
return ImageBuilder.Current.Build(bitmap, instructions);
}

In an unexpected turn of events, the documentation is ahead of reality.
You can use the Instructions class, but for now you must convert it to a ResizeSettings instance first like so:
.Build(source, dest, new ResizeSettings(new Instructions("width=20")));
In the next major release, this will accept an Instructions class directly.

Related

Using Camera by C++/WinRT

I want to use Camera(CameraCaptureUI or MediaCapture class) in C++/WinRT.
Microsoft document sample code is written by C# and JavaScript.
https://learn.microsoft.com/en-us/uwp/api/Windows.Media.Capture.CameraCaptureUI#code-snippet-1
MFC + C++/WinRT
void CWinRTtestDlg::OnBnClickedButtonToast()
{
// show toast
auto notificationManager = ToastNotificationManager::GetDefault();
auto toastXml = ToastNotificationManager::GetTemplateContent(ToastTemplateType::ToastText01);
auto textNode = toastXml.GetElementsByTagName(L"text").Item(0);
textNode.AppendChild(toastXml.CreateTextNode(L"Hello C++/WinRT!"));
auto toast = ToastNotification(toastXml);
toast.ExpirationTime(winrt::clock::now() + std::chrono::hours() * 2);
notificationManager.CreateToastNotifier().Show(toast);
}
this code is working.
IAsyncAction Camera()
{
auto cameraManager = CameraCaptureUI();
cameraManager.PhotoSettings().CroppedAspectRatio(Size(4, 3));
cameraManager.PhotoSettings().Format(CameraCaptureUIPhotoFormat::Jpeg);
auto file{ co_await cameraManager.CaptureFileAsync(CameraCaptureUIMode::Photo) };
}
void CWinRTtestDlg::OnBnClickedButtonCamera()
{
winrt::init_apartment();
auto image = Camera();
}
but this code is NOT working...
C++ project setting
Additional Option /await
C++ Language Standard C++17
Conformance mode No
Teams are slowly adding C++ samples, but it's going to take time. For the most part, a transliteration shouldn't be too hard. If it's a C# constructor, replace it with a C++ constructor. For example:
Widget widget = new Widget(123);
Becomes:
Widget widget(123);
Properties don't exist in C++ so you can just add parentheses and treat it as a method. You can also use coroutines, so an await in C# becomes a co_await in C++.

Equivalent of CGRectInfinite & CGRectIsInfinite in MonoTouch/Xamarin

I am trying to convert an open source flyout menu from Objective-C to Xamarin. The current issue I have is that the Obj-C code creates a frame using CGRectInfinite. This does not appear to be available under MonoTouch, via the usual RectangleF class. Is there an alternative?
Similarly, there does not appear to be a CGRectIsInfinite equivalent in RectangleF. What, if any, is the alternative?
Add this using statement first:
using MonoTouch.CoreGraphics;
Then you can test it with this:
public static RectangleF GetInfinite()
{
var image = CIImage.EmptyImage;
if (image.Extent.IsInfinite ())
{
return image.Extent;
}
throw new Exception ("Unable to create infinite rect");
}

Accessing a C/C++ structure of callbacks through a DLL's exported function using JNA

I have a vendor supplied .DLL and an online API that I am using to interact with a piece of radio hardware; I am using JNA to access the exported functions through Java (because I don't know C/C++). I can call basic methods and use some API structures successfully, but I am having trouble with the callback structure. I've followed the TutorTutor guide here and also tried Mr. Wall's authoritative guide here, but I haven't been able to formulate the Java side syntax for callbacks set in a structure correctly.
I need to use this exported function:
BOOL __stdcall SetCallbacks(INT32 hDevice,
CONST G39DDC_CALLBACKS *Callbacks, DWORD_PTR UserData);
This function references the C/C++ Structure:
typedef struct{
G39DDC_IF_CALLBACK IFCallback;
//more omitted
} G39DDC_CALLBACKS;
...which according to the API has these Members (Note this is not an exported function):
VOID __stdcall IFCallback(CONST SHORT *Buffer, UINT32 NumberOfSamples,
UINT32 CenterFrequency, WORD Amplitude,
UINT32 ADCSampleRate, DWORD_PTR UserData);
//more omitted
I have a G39DDCAPI.java where I have loaded the DLL library and reproduced the API exported functions in Java, with the help of JNA. Simple calls to that work well.
I also have a G39DDC_CALLBACKS.java where I have implemented the above C/C++ structure in a format works for other API structures. This callback structure is where I am unsure of the syntax:
import java.util.Arrays;
import java.util.List;
import java.nio.ShortBuffer;
import com.sun.jna.Structure;
import com.sun.jna.platform.win32.BaseTSD.DWORD_PTR;
import com.sun.jna.win32.StdCallLibrary.StdCallCallback;
public class G39DDC_CALLBACKS extends Structure {
public G39DDC_IF_CALLBACK IFCallback;
//more omitted
protected List getFieldOrder() {
return Arrays.asList(new String[] {
"IFCallback","DDC1StreamCallback" //more omitted
});
}
public static interface G39DDC_IF_CALLBACK extends StdCallCallback{
public void invoke(ShortBuffer _Buffer,int NumberOfSamples,
int CenterFrequency, short Amplitude,
int ADCSampleRate, DWORD_PTR UserData);
}
}
Edit: I made my arguments more type safe as Technomage suggested. I am still getting a null pointer exception with several attempts to call the callback. Since I'm not sure of my syntax regarding the callback structure above, I can't pinpoint my problem in the main below. Right now the relevant section looks like this:
int NumberOfSamples=65536;//This is usually 65536.
ShortBuffer _Buffer = ShortBuffer.allocate(NumberOfSamples);
int CenterFrequency=10000000;//Specifies center frequency (in Hz) of the useful band
//in received 50 MHz wide snapshot.
short Amplitude=0;//The possible value is 0 to 32767.
int ADCSampleRate=100;//Specifies sample rate of the ADC in Hz.
DWORD_PTR UserData = null;
G39DDC_CALLBACKS callbackStruct= new G39DDC_CALLBACKS();
lib.SetCallbacks(hDevice,callbackStruct,UserData);
//hDevice is a handle for the hardware device used-- works in other uses
//lib is a reference to the library in G39DDCAPI.java-- works in other uses
//The UserData is a big unknown-- I don't know what to do with this variable
//as a DWORD_PTR
callbackStruct.IFCallback.invoke(_Buffer, NumberOfSamples, CenterFrequency,
Amplitude, ADCSampleRate, UserData);
EDIT NO 2:
I have one callback working somewhat, but I don't have control over the buffers. More frustratingly, a single call to invoke the method will result in several runs of the custom callback, usually with multiple output files (results vary drastically from run to run). I don't know if it is because I am not allocating memory correctly on the Java side, because I cannot free the memory on the C/C++ side, or because I have no cue on which to tell Java to access the buffer, etc. Relevant code looks like:
//before this, main method sets library, starts DDCs, initializes some variables...
//API call to start IF
System.out.print("Starting IF... "+lib.StartIF(hDevice, Period)+"\n")
G39DDC_CALLBACKS callbackStructure = new G39DDC_CALLBACKS();
callbackStructure.IFCallback = new G39DDC_IF_CALLBACK(){
#Override
public void invoke(Pointer _Buffer, int NumberOfSamples, int CenterFrequency,
short Amplitude, int ADCSampleRate, DWORD_PTR UserData ) {
//notification
System.out.println("Invoked IFCallback!!");
try {
//ready file and writers
File filePath = new File("/users/user/G39DDC_Scans/");
if (!filePath.exists()){
System.out.println("Making new directory...");
filePath.mkdir();
}
String filename="Scan_"+System.currentTimeMillis();
File fille= new File("/users/user/G39DDC_Scans/"+filename+".txt");
if (!fille.exists()) {
System.out.println("Making new file...");
fille.createNewFile();
}
FileWriter fw = new FileWriter(fille.getAbsoluteFile());
//callback body
short[] deBuff=new short[NumberOfSamples];
int offset=0;
int arraySize=NumberOfSamples;
deBuff=_Buffer.getShortArray(offset,arraySize);
for (int i=0; i<NumberOfSamples; i++){
String str=deBuff[i]+",";
fw.write(str);
}
fw.close();
} catch (IOException e1) {
System.out.println("IOException: "+e1);
}
}
};
lib.SetCallbacks(hDevice, callbackStructure,UserData);
System.out.println("Main, before callback invocation");
callbackStructure.IFCallback.invoke(s_Pointer, NumberOfSamples, CenterFrequency, Amplitude, ADCSampleRate, UserData);
System.out.println("Main, after callback invocation");
//suddenly having trouble stopping DDCs or powering off device; assume it has to do with dll using the functions above
//System.out.println("StopIF: " + lib.StopIF(hDevice));//API function returns boolean value
//System.out.println("StopDDC2: " + lib.StopDDC2( hDevice, Channel));
//System.out.println("StopDDC1: " + lib.StopDDC1( hDevice, Channel ));
//System.out.println("test_finishDevice: " + test_finishDevice( hDevice, lib));
System.out.println("Program Exit");
//END MAIN METHOD
You need to extend StdCallCallback, for one, otherwise you'll likely crash when the native code tries to call the Java code.
Any place you see a Windows type with _PTR, you should use a PointerType - the platform package with JNA includes definitions for DWORD_PTR and friends.
Finally, you can't have a primitive array argument in your G39DDC_IF_CALLBACK. You'll need to use Pointer or an NIO buffer; Pointer.getShortArray() may then be used to extract the short[] by providing the desired length of the array.
EDIT
Yes, you need to initialize your callback field in the callbacks structure before passing it into your native function, otherwise you're just passing a NULL pointer, which will cause complaints on the Java or native side or both.
This is what it takes to create a callback, using an anonymous instance of the declared callback function interface:
myStruct.callbackField = new MyCallback() {
public void invoke(int arg) {
// do your stuff here
}
};

How do I execute Dynamically (like Eval) in Dart?

Since getting started in Dart I've been watching for a way to execute Dart (Text) Source (that the same program may well be generating dynamically) as Code. Like the infamous "eval()" function.
Recently I have caught a few hints that the communication port between Isolates support some sort of "Spawn" that seems like it could allow this "trick". In Ruby there is also the possibility to load a module dynamically as a language feature, perhaps there is some way to do this in Dart?
Any clues or a simple example will be greatly appreciated.
Thanks in advance!
Ladislav Thon provided this answer on the Dart forum:
I believe it's very safe to say that Dart will never have eval. But it will have other, more structured ways of dynamically generating code (code name mirror builders). There is nothing like that right now, though.
There are two ways of spawning an isolate: spawnFunction, which runs an existing function from the existing code in a new isolate, so nothing you are looking for, and spawnUri, which downloads code from given URI and runs it in new isolate. That is essentially dynamic code loading -- but the dynamically loaded code is isolated from the existing code. It runs in a new isolate, so the only means of communicating with it is via message passing (through ports).
You can run a string as Dart code by first constructing a data URI from it and then passing it into Isolate.spawnUri.
import 'dart:isolate';
void main() async {
final uri = Uri.dataFromString(
'''
void main() {
print("Hellooooooo from the other side!");
}
''',
mimeType: 'application/dart',
);
await Isolate.spawnUri(uri, [], null);
}
Note that you can only do this in JIT mode, which means that the only place you might benefit from it is Dart VM command line apps / package:build scripts. It will not work in Flutter release builds.
To get a result back from it, you can use ports:
import 'dart:isolate';
void main() async {
final name = 'Eval Knievel';
final uri = Uri.dataFromString(
'''
import "dart:isolate";
void main(_, SendPort port) {
port.send("Nice to meet you, $name!");
}
''',
mimeType: 'application/dart',
);
final port = ReceivePort();
await Isolate.spawnUri(uri, [], port.sendPort);
final String response = await port.first;
print(response);
}
I wrote about it on my blog.
Eval(), in Ruby at least, can execute anything from a single statement (like an assignment) to complete involved programs. There is a substantial time penalty for executing many small snippets over most any other form of execution that is possible.
Looking at the problem closer, there are at least three different functions that were at the base of the various schemes where eval might be used. Dart handles at least 2 of these in at least minimal ways.
Dart does not, nor does it look like there is any plan to support "general" script execution.
However, the NoSuchMethod method can be used to effectively implement the dynamic "injection" of variables into your local class environment. It replaces an eval() with a string that would look like this: eval( "String text = 'your first name here';" );
The second function that Dart readily supports now is the invocation of a method, that would look like this: eval( "Map map = SomeClass.some_method()" );
After messing about with this it finally dawned on me that a single simple class can be used to store the information needed to invoke a method, for a class, as a string which seems to have general utility. I can replace a big maintenance prone switch statement that might otherwise be necessary to invoke a series of methods. In Ruby this was almost trivial, however in Dart there are some fairly less than intuitive calls so I wanted to get this "trick" in one place, which fits will with doing ordering and filtering on the strings such as you may need.
Here's the code to "accumulate" as many classes (a whole library?) into a map using reflection such that the class.methodName() can be called with nothing more than a key (as a string).
Note: I used a few "helper methods" to do Map & List functions, you will probably want to replace them with straight Dart. However this code is used and tested only using the functions..
Here's the code:
//The used "Helpers" here..
MAP_add(var map, var key, var value){ if(key != null){map[key] = value;}return(map);}
Object MAP_fetch(var map, var key, [var dflt = null]) {var value = map[key];if (value==null) {value = dflt;}return( value );}
class ClassMethodMapper {
Map _helperMirrorsMap, _methodMap;
void accum_class_map(Object myClass){
InstanceMirror helperMirror = reflect(myClass);
List methodsAr = helperMirror.type.methods.values;
String classNm = myClass.toString().split("'")[1]; ///#FRAGILE
MAP_add(_helperMirrorsMap, classNm, helperMirror);
methodsAr.forEach(( method) {
String key = method.simpleName;
if (key.charCodeAt(0) != 95) { //Ignore private methods
MAP_add(_methodMap, "${classNm}.${key}()", method);
}
});
}
Map invoker( String methodNm ) {
var method = MAP_fetch(_methodMap, methodNm, null);
if (method != null) {
String classNm = methodNm.split('.')[0];
InstanceMirror helperMirror = MAP_fetch(_helperMirrorsMap, classNm);
helperMirror.invoke(method.simpleName, []);
}
}
ClassMethodMapper() {
_methodMap = {};
_helperMirrorsMap = {};
}
}//END_OF_CLASS( ClassMethodMapper );
============
main() {
ClassMethodMapper cMM = new ClassMethodMapper();
cMM.accum_class_map(MyFirstExampleClass);
cMM.accum_class_map(MySecondExampleClass);
//Now you're ready to execute any method (not private as per a special line of code above)
//by simply doing this:
cMM.invoker( MyFirstExampleClass.my_example_method() );
}
Actually there some libraries in pub.dev/packages but has some limitations because are young versions, so that I can recommend you this library expressions to dart and flutter.
A library to parse and evaluate simple expressions.
This library can handle simple expressions, but no blocks of code, control flow statements and so on. It supports a syntax that is common to most programming languages.
There I create an example of code to evaluate arithmetic operations and comparations of data.
import 'package:expressions/expressions.dart';
import 'dart:math';
#override
Widget build(BuildContext context) {
final parsing = FormulaMath();
// Expression example
String condition = "(cos(x)*cos(x)+sin(x)*sin(x)==1) && respuesta_texto == 'si'";
Expression expression = Expression.parse(condition);
var context = {
"x": pi / 5,
"cos": cos,
"sin": sin,
"respuesta_texto" : 'si'
};
// Evaluate expression
final evaluator = const ExpressionEvaluator();
var r = evaluator.eval(expression, context);
print(r);
return Scaffold(
body: Container(
margin: EdgeInsets.only(top: 50.0),
child: Column(
children: [
Text(condition),
Text(r.toString())
],
),
),
);
}
I/flutter (27188): true

Computing the union 2 MKPolygons

I am working on map applications with polygon MKOverlays. I have a requirement to merge (union) overlapping polygons.
Is there a well known algorithm to do this? Are there any free existing libraries/implementations that help with such geometry operations?
I have found the GEOS library, but apparently its licensing terms disallow use without distributing your source code. Is anyone else using this library. If yes, where can I find the way to include this in my Xcode project.
The only free libraries I'm aware of are -
Clipper:
http://angusj.com/delphi/clipper.php
Boost Polygon:
http://www.boost.org/doc/libs/1_47_0/libs/polygon/doc/index.htm
Boost Geometry:
http://trac.osgeo.org/ggl/
Try gpc. They have several licences. Also there are similar libraries listed on their page.
There is a great library RSClipperWrapper which is basically a wrapper for Clipper. There is even a great library comparison inside their website:
TL;DR, free library, error free and fast.
A few notes:
RSClipperWrapper takes CGPoint but fear not, you can pass lat/long into it and it will get the job done (tested and verified).
For convinice I've written an extension so we can just pass a custom Polygon array and get the merged polygons - if you're using MKPolygon or other type then don't forget adjust your type:
extension Clipper {
static func union(polygons: [Polygon]) -> [Polygon] {
let pointsPolygons = convert(polygons: polygons)
let unionfied = Clipper.unionPolygons(pointsPolygons, withPolygons: pointsPolygons)
return convert(pointsPolygons: unionfied)
}
static func convert(polygons: [Polygon]) -> [[CGPoint]] {
var polygonsPoints: [[CGPoint]] = []
for polygon in polygons {
var points: [CGPoint] = []
for location in polygon.locations {
points.append(CGPoint(x: location.coordinate.latitude, y: location.coordinate.longitude))
}
polygonsPoints.append(points)
}
return polygonsPoints
}
static func convert(pointsPolygons: [[CGPoint]]) -> [Polygon] {
var polygons: [Polygon] = []
for pointsPolygon in pointsPolygons {
var locations: [CLLocation] = []
for point in pointsPolygon {
locations.append(CLLocation(latitude: CLLocationDegrees(point.x), longitude: CLLocationDegrees(point.y)))
}
let polygon = Polygon(locations: locations)
polygons.append(polygon)
}
return polygons
}
}