Cannot serialize a string object with Microsoft.Bond - bond

I am using Microsoft.Bond to serialize a class object which works perfectly fine. However, when I try to serialize a simple System.String object, the CompactBinaryWriter writes almost nothing to the output buffer. I am using this code:
string v = "test data";
var outputBuffer = new OutputBuffer();
var writer = new CompactBinaryWriter<OutputBuffer>(outputBuffer);
Serialize.To(writer, v);
var output = outputBuffer.Data;
output in this case is a one element array : {0}, irrespective of the value of v. Can someone point out why this doesn't work?

Bond requires a top-level Bond struct to perform serialization/deserialization.
If only one value needs to be passed/returned, the type bond.Box<T> can be used to quickly wrap a value in a Bond struct. (There's nothing special about bond.Box<T>, except that it ships with Bond.)
Try this:
Serialize.To(writer, Bond.Box.Create(v));
You'll need to deserialize into a bond.Box<string>.
There's an open issue about having better behavior in cases like this.

Related

Is it possible to cast a Tensor<TInt32> in Java to a double and other native Java variable types?

I'm new to TensorFlow and I cannot seem to find how to do this despite extensive searching online. I want to load the TensorFlow model I have built into Java to set some variable values, which in this case, is a double. Is there a good way of going about this?
I have looked at the TensorFlow copyTo() function but it doesn't seem relevant. I have found no relevant search results when trying to do this casting as well.
Here is the code snippet of what I am trying to do:
try(SavedModelBundle b = SavedModelBundle.load("/somePath", "serve")) {
Session s = b.session();
Tensor<TInt32> x = TInt32.scalarOf(1);
Tensor<TInt32> y = TInt32.scalarOf(2);
Tensor<TInt32> result = (Tensor<TInt32>) s.runner().feed("x", x).feed("y", y).fetch("ans").run().get(0);
// I know this won't work but do whatever is needed to convert to a double
this.ExampleDouble = result;
}
First you need to retrieve the output tensor(s) with their expected type.
If your model is returning an 32-bit integer (like it seems to do given your example), then you should do the following:
// Also note all resources that should be protected by a try-with-resource block...
try(SavedModelBundle model = SavedModelBundle.load("/somePath", "serve");
Tensor<TInt32> x = TInt32.scalarOf(1);
Tensor<TInt32> y = TInt32.scalarOf(2)) {
// Let's use the new functional API to instead of invoking the session directly
Map<String, Tensor<?>> inputTensors = new HashMap() {{
put("x", x);
put("y", y);
}};
try (Tensor<TInt32> result = model.call(inputTensors).get("ans").expect(TInt32.DTYPE)) {
this.ExampleDouble = (double)(result.data().getInt());
}
}
It is a bit surprising though that the datatype of the model output is a 32-bit integer if you know that it is returning a double floating value. Make sure to request the right datatype, as found in the model signature, or the cast will fail (if it is a double, then the expected datatype might be TFloat64.DTYPE).
You can look at the signatures of your model by calling model.signatures()

Google diff-match-patch : How to unpatch to get Original String?

I am using Google diff-match-patch JAVA plugin to create patch between two JSON strings and storing the patch to database.
diff_match_patch dmp = new diff_match_patch();
LinkedList<Patch> diffs = dmp.patch_make(latestString, originalString);
String patch = dmp.patch_toText(diffs); // Store patch to DB
Now is there any way to use this patch to re-create the originalString by passing the latestString?
I google about this and found this very old comment # Google diff-match-patch Wiki saying,
Unpatching can be done by just looping through the diff, swapping
DIFF_INSERT with DIFF_DELETE, then applying the patch.
But i did not find any useful code that demonstrates this. How could i achieve this with my existing code ? Any pointers or code reference would be appreciated.
Edit:
The problem i am facing is, in the front-end i am showing a revisions module that shows all the transactions of a particular fragment (take for example an employee details), like which user has updated what details etc. Now i am recreating the fragment JSON by reverse applying each patch to get the current transaction data and show it as a table (using http://marianoguerra.github.io/json.human.js/). But some JSON data are not valid JSON and I am getting JSON.parse error.
I was looking to do something similar (in C#) and what is working for me with a relatively simple object is the patch_apply method. This use case seems somewhat missing from the documentation, so I'm answering here. Code is C# but the API is cross language:
static void Main(string[] args)
{
var dmp = new diff_match_patch();
string v1 = "My Json Object;
string v2 = "My Mutated Json Object"
var v2ToV1Patch = dmp.patch_make(v2, v1);
var v2ToV1PatchText = dmp.patch_toText(v2ToV1Patch); // Persist text to db
string v3 = "Latest version of JSON object;
var v3ToV2Patch = dmp.patch_make(v3, v2);
var v3ToV2PatchTxt = dmp.patch_toText(v3ToV2Patch); // Persist text to db
// Time to re-hydrate the objects
var altV3ToV2Patch = dmp.patch_fromText(v3ToV2PatchTxt);
var altV2 = dmp.patch_apply(altV3ToV2Patch, v3)[0].ToString(); // .get(0) in Java I think
var altV2ToV1Patch = dmp.patch_fromText(v2ToV1PatchText);
var altV1 = dmp.patch_apply(altV2ToV1Patch, altV2)[0].ToString();
}
I am attempting to retrofit this as an audit log, where previously the entire JSON object was saved. As the audited objects have become more complex the storage requirements have increased dramatically. I haven't yet applied this to the complex large objects, but it is possible to check if the patch was successful by checking the second object in the array returned by the patch_apply method. This is an array of boolean values, all of which should be true if the patch worked correctly. You could write some code to check this, which would help check if the object can be successfully re-hydrated from the JSON rather than just getting a parsing error. My prototype C# method looks like this:
private static bool ValidatePatch(object[] patchResult, out string patchedString)
{
patchedString = patchResult[0] as string;
var successArray = patchResult[1] as bool[];
foreach (var b in successArray)
{
if (!b)
return false;
}
return true;
}

Copying a column of strings from 2D array to 1D in google-spreadsheet-api

I'm new to Javascript and the google-api and still struggling with casting and basic functionality.
I'm trying to copy a column of strings harvested from a sheet to another array for manipulation and running into various errors. So far I have tried the following ( that have not generated straight up syntax errors )...
// Character VALIDATION function
function validateCharacter(characterName) {
var sheetName = ("!" + characterName);
var characterSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
// characterData array will hold the values from the characters sheet
var dataRange=characterSheet.getDataRange();
var characterData = dataRange.getValues();
var Physicals;
Physicals.copyofrange(characterData,[14][0],[31][0]);
console.log(Physicals);
}
and
// Character VALIDATION function
function validateCharacter(characterName) {
var sheetName = ("!" + characterName);
var characterSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
// characterData array will hold the values from the characters sheet
var dataRange=characterSheet.getDataRange();
var characterData = dataRange.getValues();
var Physicals;
for (i=0;i<17;i++){
Physicals[i]=characterData[i+13][0];
}
console.log(Physicals);
}
I know that Java handles strings as pointers, but I'm not clear if Javascript does and I thought of the for loop first but I'm getting
TypeError: Cannot set property "0.0" of undefined to "Agile". (line 40).
when I do that. I'm assuming I'm missing something... dimensional? about the declaration of the array to be copied to but I can't figure out what. I've looked over various solutions involving Java declarations for arrays but none of those seem to apply or be allowed in the google-spreadsheets-api Javascript. It seemed to not even acknowledge the String declaration when I tried String[]=new String etc. Frankly I don't care how it's implemented just so it works. Efficiency isn't a big concern on this project. Thank you.
OK, figured it out. After seeing all the Java things that Javascript does not support, I found some documentation specifically on Javascript string handling and figured out I have to cast Physicals as an empty array then "push" the values into it in the loop rather than assigning them with = statements, as such.
// Character VALIDATION function
function validateCharacter(characterName) {
var sheetName = ("!" + characterName);
var characterSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
// characterData array will hold the values from the characters sheet
var dataRange=characterSheet.getDataRange();
var characterData = dataRange.getValues();
var Physicals=[];
for (i=0;i<17;i++){
Physicals.push(characterData[i+13][0]);
}
return(Physicals);
}
Knowing the distinction between Java, Javascript, and Guava actually helped a great deal since they seem to have wildly different function handling despite similar names and common ancestry.

Creating WCF service by determining type at runtime

I am trying to create a WCF service without knowing its type/interface at runtime. To do this, I use ChannelFactory. ChannelFactory is a generic class so I need to use Type.MakeGenericType. The type I pass to MakeGenericType is from a list of interfaces I previously gathered with reflection by searching some assemblies.
Ultimately, I call MethodInfo.Invoke to create the object. The object is created just fine, but I cannot cast it to the proper interface. Upon casting, I receive the following error:
"Unable to cast transparent proxy to type 'Tssc.Services.MyType.IMyType'"
After some experimenting, I have found that the interface/type passed to MakeGenericType seems to be the problem. If I substitute the interface in my list with the actual interface, then everything works fine. I have combed through the two objects and cannot see a difference. When I modify the code to produce both types, comparing them with Equals returns false. It is unclear to me whether Equals is just checking that they are referring to the same object (not) or thety are checking all properties, etc.
Could this have something to do with how I gathered my interfaces (Reflection, saving in a list...)? A comparison of the objects seems to indicate they are equivalent. I printed all properties for both objects and they are the same. Do I need to dig deeper? If so, into where?
// createService() method
//*** tried both of these interfaces, only 2nd works - but they seem to be identical
//Type t = interfaces[i]; // get type from list created above - doesn't work
Type t = typeof(Tssc.Services.MyType.IMyType); // actual type - works OK
// create ChannelFactory type with my type parameter (t)
Type factoryType = typeof(ChannelFactory<>);
factoryType = factoryType.MakeGenericType(new Type[] { t });
// create ChannelFactory<> object with two-param ctor
BasicHttpBinding binding = new BasicHttpBinding();
string address = "blah blah blah";
var factory = Activator.CreateInstance(factoryType, new object[] { binding, address });
// get overload of ChannelFactory<>.CreateChannel with no parameters
MethodInfo method = factoryType.GetMethod("CreateChannel", new Type[] { });
return method.Invoke(factory, null);
//--------------- code that calls code above and uses its return
object ob = createService();
//*** this cast fails
Tssc.Services.MyType.IMyType service = (Tssc.Services.MyType.IMyType)ob;
Ok, I understand whats happening here - the problem is relating to loading the same assembly being effectively loaded twice - once via a reference, and once via the assembly load command. What you need to do is change the place where you load your assembly, and check to see if it already exists in the current AppDomain, like this maybe:
Assembly assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.GetName().Name.Equals("ClassLibrary1Name"));
if (assembly == null)
{
assembly = System.Reflection.Assembly.LoadFile("path to your assembly");
}
//do your work here
This way if the assembly is already loaded into memory, it'll use that one.

Is it possible to pass a variable's name along with the value, when passing through functions?

I want to know if it's possible to retrieve the variables name from when it was passed into a certain function. For example, if I call parseId(myId) to a function with the signature parseId(id), i can obviously retrieve the value of 'id'. However, is there any way I can retrieve 'myId' as a string (without passing it as another value)?
Specifically in vb.net, but I'm interested in how it would work in any given language.
This is all just random thoughts.. feel free to dismiss or not ;-p
Re your comment about use with stored procedures... if you want to go that route, I wouldn't mess around with the local variable names; that is an implementation detail. However, you could expose those details on an interface method and use the names from there, since that is more formalised - for example (C#):
interface ICustomerRepository {
Customer GetById(int id); // perhaps an attribute to name the sproc
}
You can use similar expression-tree parsing (as discussed here) to get the name and value of the parameter, for example:
var repoWrapper = new Repo<ICustomerRepository>();
int custId = 12345;
var cust = repoWrapper.Execute(r => r.GetById(custId));
Here we'd want to resolve the argument to GetById as "id" (not "custId"), with value 12345. This is actually exactly what my protobuf-net RPC code does ;-p (just don't ask me to translate it to VB - it is hard enough to write it in a language you know well...)
No, you can't do that in the normal sense. What are you really trying to accomplish with this?
You can do this in .NET 3.5 and above using expression trees; I'll knock up a C# example, and try to run it through reflector for VB...
C#:
static void Main()
{
int i = 17;
WriteLine(() => i);
}
static void WriteLine<T>(Expression<Func<T>> expression)
{
string name;
switch (expression.Body.NodeType)
{
case ExpressionType.MemberAccess:
name = ((MemberExpression)expression.Body).Member.Name;
break;
default:
throw new NotSupportedException("Give me a chance!");
}
T val = expression.Compile()();
Console.WriteLine(name + "=" + val);
}
The VB is below, but note that the VB compiler seems to use different names (like $VB$Local_i, not i):
Sub Main()
Dim i As Integer = 17
WriteLine(Function() i)
End Sub
Private Sub WriteLine(Of T)(ByVal expression As Expression(Of Func(Of T)))
If (expression.Body.NodeType <> ExpressionType.MemberAccess) Then
Throw New NotSupportedException("Give me a chance!")
End If
Console.WriteLine((DirectCast(expression.Body, MemberExpression).Member.Name
& "=" & Convert.ToString(expression.Compile.Invoke)))
End Sub