I have a proto message:
syntax = "proto3";
import "google/protobuf/any.proto";
message Task {
repeated google.protobuf.Any targets = 1;
// ...
}
message Target {
string name = 1;
// ...
}
How should I add Target messages into Task.targets?
In official docs I've found info about how to assign value to a single Any type value, however in my case I have repeated Any field type.
Edit: Task.targets may contain different types of targets, that's why Any type is used. A single Target message is just for minimal reproducible example.
Thanks #Justin Schoen. According to https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/Any, you need to first create an Any object, then Pack a Target (or any other object type) before appending it to the repeated list.
from google.protobuf.any_pb2 import Any
task = Task()
target = Any()
target.Pack(Target())
task.targets.append(any)
I have limited knowledge of the any type, but I would think it could be treated as if it were a repeated list of Target messages.
Python Code:
task_targets = []
task_targets.append(<insert_pb2_import>.Target(name='test'))
return <insert_pb2_import>.Task(targets=task_targets)
After searching for an answer myself, I found this thread to be the most relevant so I'll post my solution here if it helps anyone (but in Java/Scala).
If you want
repeated google.protobuf.Any targets = 1;
and targets can be any value such as (string, bool, int, etc). This is how I did it in scala/java:
val task = Task.newBuilder()
.addTargets(Any.pack(StringValue.of("iss")))
.addTargets(Any.pack(Int32Value.of(25544)))
.addTargets(Any.pack(DoubleValue.of(1004.882447947814)))
.addTargets(Any.pack(DoubleValue.of(84.90917890132)))
.addTargets(Any.pack(DoubleValue.of(14.620929684)))
.addTargets(Any.pack(StringValue.of("kilometers")))
.build()
After playing around some time I have decided to revise the solution that uses repeating Any. And here is an advice for those who got stuck in this same place:
try to use specific types instead of Any.
A workaround for my situation is to create messages of types SpecificTargetSet1, SpecificTargetSet2, etc., that contain specific targets. The Task proto file would look like:
message Task {
google.protobuf.Any target_set = 1;
}
Target set proto file:
message SpecificTargetSet1 {
repeated SpecificTarget1 targets = 1;
}
And now a task could be created in such a way:
target = Target()
target.name = "Some name"
target_set = SpecificTargetSet1()
target_set.targets.append(target)
task = Task()
task.target_set.Pack(target_set)
I do not mark my answer as correct, as it is just a workaround.
Related
This is in reference to this question. I checked our test interface and we are only passing the V93k primary params to the test_suites.add method.
V93K_PRIMARIES = [:lev_equ_set, :lev_spec_set, :timset, :tim_equ_set, :tim_spec_set, :seqlbl, :levset]
primary_tm_params = {}.tap do |primary_hash|
V93K_PRIMARIES.each do |param|
primary_hash[param] = tm_params.delete(param) unless tm_params[param].nil?
end
end
# Create the test suite
t = test_suites.add(test_name, primary_tm_params)
t.test_method = test_methods.amd93k.send(options[:tm].to_sym, tm_params)
V93K_PRIMARIES.each do |primary|
t.send("#{primary}=", primary_tm_params[primary]) unless primary_tm_params[primary].nil?
end
# Insert the test into the flow
test(t, tm_params)
When I set a breakpoint, I do see they were missing. Here they are after updating the code:
:ip=>:L2,
:testmode=>:speed,
:cond=>:pmax,
:if_failed=>:cpu_pmin,
:testtype=>:cpu,
:test_ip=>:bist,
:tm=>"Bist"}
And here is the .tf file generated from the original two tests in the original question:
run_and_branch(cpu_L2_speed_pmin_965EA18)
then
{
}
else
{
#CPU_PMIN_965EA18_FAILED = 1;
}
if #CPU_PMIN_965EA18_FAILED == 1 then
{
run(cpu_L2_speed_pmax_965EA18);
}
else
{
}
I think we have it figured out, thx very much!
The normal approach to this is just to pass everything to flow.test, rather than a subset of the options passed from the flow.
It will only act on the options it recognizes, which are basically the flow control parameters (:id, :if_failed, :unless_enabled, etc) and the test and bin number parameters, and it will just ignore the rest.
My task is to open multiple files after a button clicked, and read all those selected files.
I have found an example of foreach function in c#, but I would like to write it in C++. How should I actually to convert that?
It shows the error that System::String, cannot use this type here without top level '^'.
I'm still new with that. Does anyone can give suggestion?
Thank you very much.
Below is my written codes
Stream^ myStream;
OpenFileDialog^ openFileDialog1 = gcnew OpenFileDialog;
openFileDialog1->InitialDirectory = "c:\\";
openFileDialog1->Title = "open captured file";
openFileDialog1->Filter = "CP files (*.cp)|*.cp|All files (*.*)|*.*|txt files (*.txt)|*.txt";
openFileDialog1->FilterIndex = 2;
//openFileDialog1->RestoreDirectory = true;
openFileDialog1->Multiselect = true;
if ( openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK )
{
**for each (String line in openFileDialog1->FileName)**
System::Diagnostics::Debug::WriteLine("{0}",line);
myStream->Close();
}
Depending on the Container type returned, there is a std::for_each defined in <algorithm>-header.
The function Looks like this:
#include <algorithm>
std::for_each(InputIterator first, InputIterator last, Function fn);
You need to provide two iterators, one for the beginning of the Container and one for the end of the iterator. As a third Argument you can provide a function (function-object) and operate on the current argument.
See here for further reference.
As I got it from MSDN, the property SafeFileNames returns an array<String^>.
System::Array provides a static method called Array::ForEach. You would need to call it like
System::Action<T> myAction; // You will Need to provide a function here to be used on every filename.
System::Array::ForEach(openFileDialog1->SafeFileNames, myAction);
This comes closest to foreach from C#.
Look here for System::Array::ForEach and here for OpenFileDialog::SafeFileNames.
I have the following c# code:
private XElement BuildXmlBlob(string id, Part part, out int counter)
{
// return some unique xml particular to the parameters passed
// remember to increment the counter also before returning.
}
Which is called by:
var counter = 0;
result.AddRange(from rec in listOfRecordings
from par in rec.Parts
let id = GetId("mods", rec.CKey + par.UniqueId)
select BuildXmlBlob(id, par, counter));
Above code samples are symbolic of what I am trying to achieve.
According to the Eric Lippert, the out keyword and linq does not mix. OK fair enough but can someone help me refactor the above so it does work? A colleague at work mentioned accumulator and aggregate functions but I am novice to Linq and my google searches were bearing any real fruit so I thought I would ask here :).
To Clarify:
I am counting the number of parts I might have which could be any number of them each time the code is called. So every time the BuildXmlBlob() method is called, the resulting xml produced will have a unique element in there denoting the 'partNumber'.
So if the counter is currently on 7, that means we are processing 7th part so far!! That means XML returned from BuildXmlBlob() will have the counter value embedded in there somewhere. That's why I need it somehow to be passed and incremented every time the BuildXmlBlob() is called per run through.
If you want to keep this purely in LINQ and you need to maintain a running count for use within your queries, the cleanest way to do so would be to make use of the Select() overloads that includes the index in the query to get the current index.
In this case, it would be cleaner to do a query which collects the inputs first, then use the overload to do the projection.
var inputs =
from recording in listOfRecordings
from part in recording.Parts
select new
{
Id = GetId("mods", recording.CKey + part.UniqueId),
Part = part,
};
result.AddRange(inputs.Select((x, i) => BuildXmlBlob(x.Id, x.Part, i)));
Then you wouldn't need to use the out/ref parameter.
XElement BuildXmlBlob(string id, Part part, int counter)
{
// implementation
}
Below is what I managed to figure out on my own:.
result.AddRange(listOfRecordings.SelectMany(rec => rec.Parts, (rec, par) => new {rec, par})
.Select(#t => new
{
#t,
Id = GetStructMapItemId("mods", #t.rec.CKey + #t.par.UniqueId)
})
.Select((#t, i) => BuildPartsDmdSec(#t.Id, #t.#t.par, i)));
I used resharper to convert it into a method chain which constructed the basics for what I needed and then i simply tacked on the select statement right at the end.
I have a list AllIDs:
List<IAddress> AllIDs = new List<IAddress>();
I want to do substring operation on a member field AddressId based on a character "_".
I am using below LINQ query but getting compilation error:
AllIDs= AllIDs.Where(s => s.AddressId.Length >= s.AddressId.IndexOf("_"))
.Select(s => s.AddressId.Substring(s.AddressId.IndexOf("_")))
.ToList();
Error:
Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'System.Collections.Generic.List<MyCompany.Common.Users.IAddress>'
AllIDs is a list of IAddress but you are selecting a string. The compiler is complaining it cannot convert a List<string> to a List<IAddress>. Did you mean the following instead?
var substrings = AllIDs.Where(...).Select(...).ToList();
If you want to put them back into Address objects (assuming you have an Address class in addition to your IAddress interface), you can do something like this (assuming the constructor for Address is in place):
AllIDs = AllIDs.Where(...).Select(new Address(s.AddressID.Substring(s.AddressID.IndexOf("_")))).ToList();
You should also look at using query syntax for LINQ instead of method syntax, it can clean up and improve the readability of a lot of queries like this. Your original (unmodified) query is roughly equivalent to this:
var substrings = from a in AllIDs
let id = a.AddressId
let idx = id.IndexOf("_")
where id.Length >= idx
select id.Substring(idx);
Though this is really just a style thing, and this compiles to the same thing as the original. One slight difference is that you only have to call String.IndexOf() one per entry, instead of twice per entry. let is your friend.
Maybe this?
var boundable =
from s id in AllIDs
where s.AddressId.Length >= s.AddressId.IndexOf("_")
select new { AddressId = s.AddressId.Substring(s.AddressId.IndexOf("_")) };
boundable = boundable.ToList();
I'm getting a text which contains ${somethingElse} inside, but it's just a normal String.
I've got a class:
class Whatever {
def somethingElse = 5
void action(String sth) {
def test = []
test.testing = sth
assert test.testing == 5
}
}
Is it possible with groovy?
EDIT:
my scenario is: load xml file, which contains nodes with values pointing to some other values in my application. So let's say I've got shell.setVariable("current", myClass). And now, in my xml I want to be able to put ${current.someField} as a value.
The trouble is, that the value from xml is a string and I can't evaluate it easily.
I can't predict how these "values" will be created by user, I just give them ability to use few classes.
I cannot convert it when the xml file is loaded, it has to be "on demand", since I use it in specific cases and I want them to be able to use values at that moment in time, and not when xml file is loaded.
Any tips?
One thing you could do is:
class Whatever {
def somethingElse = 5
void action( String sth ) {
def result = new groovy.text.GStringTemplateEngine().with {
createTemplate( sth ).make( this.properties ).toString()
}
assert result == "Number 5"
}
}
// Pass it a String
new Whatever().action( 'Number ${somethingElse}' )
At first, what we did, was used this format in xml:
normalText#codeToExecuteOrEvaluate#normalText
and used replace closure to regexp and groovyShell.evaluate() the code.
Insane. It took a lot of time and a lot of memory.
In the end we changed the format to the original one and crated scripts for each string we wanted to be able to evaluate:
Script script = shell.parse("\""+stringToParse+"\"")
where
stringToParse = "Hello world # ${System.currentTimeMillis()}!!"
Then we were able to call script.run() as many times as we wanted and everything performed well.
It actually still does.