How to test if an array of objects contains a string? - intersystems-cache

In C# I can do this:
public string[] MyStrings;
...
...
if(MyStrings.Contains("bob")) ...
In ObjectScript how is this done?
With %ArrayOfObjects type I don't see exactly what I am looking for here
What I have tried:
#Dim MyStrings As %ArrayOfDataTypes
do MyStrings.SetAt("User","User")
do MyStrings.SetAt("Users","Users")
do MyStrings.SetAt("Group","Group")
do MyStrings.SetAt("Groups","Groups")
// if MyStrings contains Groups
if MyStrings.GetAt("Groups") '= ""
{
}

It sounds like you want the .IsDefined() method. For example:
#Dim MyStrings As %ArrayOfDataTypes
do MyStrings.SetAt("User","User")
do MyStrings.SetAt("Users","Users")
do MyStrings.SetAt("Group","Group")
do MyStrings.SetAt("Groups","Groups")
// if MyStrings contains Groups
if MyStrings.IsDefined("Groups")
{
// code to execute if MyStrings contained "Groups"
}

You've got it right. I would suggest making a subclass of %Library.ArrayOfDataTypes with your own methods on it, such as "contains".
It's probably a little safer to use your own classes that you do control than library classes that you don't anyway (though in a pinch you could always use %Dictionary package methods to switch all references to a library class to a new class of your design, so it's not really that big a deal).

I am not familiar with that language, but could you try something like:
//declare myString to hold a string
set myString = MyStrings.GetNext("")
While myString '= ""
{
if MyStrings.GetAt(myString) '= "" //Or should it be something like myString.value? Is there a way to check the type of an object to see if it is a string?
{
//Do something here. Exit loop if you are trying to find just a match.
}
}
I am assuming '= is equivalent to != in C#.

Related

Rescript Record: Key as Array

In Rescript, one can define a Record in this format:
type record1 = {
a : String
}
but NOT:
type record2 = {
[a] : String
}
I am looking to write a record that compiles to JS like:
{
[Op.or]: [12,13]
}
The use case above comes from Sequelize, and the reference is here.
My current solution:
%raw(`{[Op.or]:[12,13]}`)
It's not entirely clear how you intend to interface with the Op construct, whether you can bind to it or not, but here's an example that does, and along with Js.Dict.t effectively produces the same output:
module Op = {
#val external or: string = "Op.or"
}
Js.Dict.fromList(list{
(Op.or, [12, 23])
})
It does not directly compile to the JS you want, however, which might be a problem if you rely on something that actually parses the source code. But short of that, I believe this should do what you ask for.

How to initialize an array of classes in kotlin?

I get an error when I put the type and size of an array of classes
I have tried:
fun main(args :Array<String>) {
class modul() {
var nommodul: String? = null
var coeff: Int? = null
var note: Int? = null
}
var releve
class notes() {
var releve: array<modul>(10){""} here the erreur
}
}
First of all, your code has several errors. This might be an MCVE and/or copy-paste issue, but I need to address these before I get started on the arrays.
var releve before the notes class isn't allowed. You don't assign it, you don't declare a type, and the compiler will complain if you copy-paste the code from your question.
Second, the array var itself: Array is upper-case, and initialization is separate. This would be more valid (note that this still does not work - the solution for that comes later in this answer):
var releve: Array<modul> = Array(10) {...}
// or
var releve = Array<modul>(10) {...}
And the last thing before I start on the array itself: please read the language conventions, especially the naming ones. Your classes should all start with an upper-case letter.
Kotlin arrays are quite different from Java arrays in many ways, but the most notable one being that direct array initialization also requires an initializer.
The brackets are expected to create a new instance, which you don't. You create a String, which isn't, in your case, a modul.
There are several ways to fix this depending on how you want to do this.
If you have instances you want to add to the array, you can use arrayOf:
arrayOf(modulInstance, modulInstance2, ...)
If you want to create them directly, you can use your approach:
var releve = Array(10) { modul() }
A note about both of these: because of the initialization, you get automatic type inference and don't need to explicitly declare <modul>
If you want Java-style arrays, you need an array of nulls.
There's two ways to do this:
var releve = arrayOfNulls<modul>(10)
// or
var releve = Array<modul?>(10) { null }
I highly recommend the first one, because it's cleaner. I'm not sure if there's a difference performance-wise though.
Note that this does infer a nullable type to the array, but it lets you work with arrays in a similar way to Java. Initialization from this point is just like Java: releve[i] = modul(). This approach is mostly useful if you have arguments you want to add to each of the classes and you need to do so manually. Using the manual initializers also provides you with an index (see the documentation) which you can use while initializing.
Note that if you're using a for loop to initialize, you can use Array(10) { YourClass() } as well, and use the supplied index if you need any index-sensitive information, such as function arguments. There's of course nothing wrong with using a for loop, but it can be cleaner.
Further reading
Array
Lambdas
here some example of kotlin array initialization:
array of Library Method
val strings = arrayOf("January", "February", "March")
Primitive Arrays
val numbers: IntArray = intArrayOf(10, 20, 30, 40, 50)
Late Initialization with Indices
val array = arrayOfNulls<Number>(5)
for (i in array.indices) {
array[i] = i * i
}
See Kotlin - Basic Types for details

NTriplesParser extract textual value from string

I am using dotnetrdf and trying to parse some triples with NTriplesParser. I have my own handler RobHandler in which I process each triple in turn.
public class RobHandler : BaseRdfHandler
{
protected override bool HandleTripleInternal(Triple t)
{
string predicateUrl = ((BaseUriNode)(t.Predicate)).Uri.AbsoluteUri;
string value = t.Object.ToString();
}
}
This works fine but I want to get the object minus the language. My objects look like "Lincoln"#en. I could obviously write some code to remove the #en bit, but I'd rather use some library code rather than my own that hard-coded strings like #en. To do this I think I need to create a LiteralNode but there doesn't seem to be a way to get from a string which is what I have (my variable value) to a LiteralNode.
How can I extract just the textual value from an object string?
Actually I think I have the answer myself:
if (t.Object.NodeType == NodeType.Literal)
{
var node = (ILiteralNode)t.Object;
}

Concatenate characters for the name of a struct in Matlab

I want program a struct in Matlab for saving some parameters.
The struct's name has to change every iteration in a loop, thus in each iteration I make a new struct. Therefore I want something like this:
index={'01','02','03'};
letter={'aa','bb','cc'};
names={'Peter','John','Michael'};
for(i=1:numel(index)){
......
strcat(str, index{i}, letter{i})(i).name = names{i};
}
Then, when the loop has finished I have 3 structs with the next names:
- str01aa{
name = 'Peter'
}
- str02bb{
name = 'John'
}
- str03cc{
name = 'Michael'
}
My problem is that the strcat function with the bracket (i) is not good defined, and the structs are not created.
I hope you can help me.
Thanks.
strcat(str, index{i}, letter{i})(i).name isn't a valid operation, because strcat returns a sting object, which can't possess fields. You need to make that string into a variable name using genvarname (documentation), like so:
index={'01','02','03'};
letter={'aa','bb','cc'};
names={'Peter','John','Michael'};
for(i = 1:numel(index))
{
......
genvarname(strcat('str', index{i}, letter{i}))(i).name = names{i};
}
Note that I changed str to 'str' for consistency with your example. As a general rule, dynamically constructed variable names are bad practice because they make debugging a nightmare.
Let me make a suggestion; instead of having a bunch of structs with different, seemingly arbitrary names, why not try something like this:
index={'01','02','03'};
letter={'aa','bb','cc'};
names={'Peter','John','Michael'};
for(i = 1:numel(index))
{
......
yourStruct(i).id = strcat('str', index{i}, letter{i});
yourStruct(i).name = names{i};
}
Either way, good luck!

How to create GWT JsArray?

I need to convert values of type T into JsArray.
For example, I have String1, String2 .... Stringn. I need to convert these Strings into JsArray string.
How can I implement this?
You don't have much choices: creating a JsArrayString and adding to it, or using JSNI.
JsArrayString arr = JavaScriptObject.createArray().cast();
arr.push(str1);
arr.push(str2);
arr.push(str3);
or
static native JsArrayString asJsArray(String str1, String str2, String str3) /*-{
return [str1, str2, str3];
}-*/;
Obviously, the latter doesn't scale, while being faster.
It really depends what exactly you need to do.
Use JsArrayUtils like this:
JsArray<String> arr = JsArrayUtils.readOnlyJsArray(new String[] { string1, string2 });
Take a look at the javadoc:
com.google.gwt.core.client.JsArrayUtils
Utility class for manipulating JS arrays. These methods are not on
other JavaScriptObject subclasses, such as JsArray, because adding new
methods might break existing subtypes.
Using generics, could do it like this:
public <T extends JavaScriptObject> JsArray<T> createGenericArray(T... objects) {
JsArray<T> array = JavaScriptObject.createArray().cast();
for (T object : objects) {
array.push(object);
}
return array;
}
Obviously, String doesn't extend JavaScriptObject. You'd need to have overloads to account for primitive types. (Or, less safely, you could remove the bounds of T to allow for arbitrary types. You'd need to be much more careful if you were to do so.)