unetstack : Could not find matching constructor - unetstack

I tried simulating the AbstractAcousticChannel example given in the documentation(https://www.unetstack.net/channels.html#extending-the-abstractacousticchannel) I have encountered the following error,
groovy.lang.GroovyRuntimeException: Could not find matching constructor for: MyAcousticModel(MyAcousticChannel)
channel
import org.arl.unet.sim.channels.*
import org.arl.unet.sim.channels.UrickAcousticModel
class MyAcousticChannel extends AbstractAcousticChannel{
#Delegate UrickAcousticModel acoustics = new MyAcousticModel(this)
#Delegate BPSKFadingModel comms = new BPSKFadingModel(this)
}
model
import org.arl.unet.sim.channels.UrickAcousticModel
class MyAcousticModel extends UrickAcousticModel {
private final def noiseLevel = [ 0: 20, 1: 30, 2: 35, 3: 40, 4: 42, 5: 44, 6: 46 ]
float seaState = 2
double getNoisePower() {
return Math.pow(10, noiseLevel[seaState]/10) * model.bandwidth
}
}
and in simulation
channel = [ model: MyAcousticChannel ]

The MyAcousticModel needs the correct constructor. You can add this to your clas s definition, something like:
import org.arl.unet.sim.channels.AbstractAcousticChannel
class MyAcousticModel extends UrickAcousticModel {
MyAcousticModel(AbstractAcousticChannel parent) {
super(parent)
}
:
:
}

Related

Merge new object in firebase database inside document

I have stored my data into firebase database by getting data from google sheet. The problem I am getting is every time I run the application It sets with new document Id. I want only one document in the firebase database collection.
My question is How do I merge data when I get new data object as response?
Example:
I have got following response :
0: {Id: 202, Name: 'word', Major: 'comp'}
1: {Id: 203, Name: 'John', Major: 'science'}
2: {Id: 204, Name: 'nsia', Major: 'cmpi'}
and It is stored in database.
Now when I run application again then It creates new document instead of merging new data to old document.
Example:
new data is
0: {Id: 205, Name: 'hello', Major: 'sci'}
and I want to merge object and get as
0: {Id: 202, Name: 'word', Major: 'comp'}
1: {Id: 203, Name: 'John', Major: 'science'}
2: {Id: 204, Name: 'nsia', Major: 'cmpi'}
3: {Id: 205, Name: 'hello', Major: 'sci'}
How do we do merge?
Here is my code to get data and post data
import { HttpClient } from '#angular/common/http';
import { Component, OnInit } from '#angular/core';
import { AngularFirestore, AngularFirestoreCollection } from '#angular/fire/compat/firestore';
import { Router } from '#angular/router';
import { AuthService } from '../shared/auth.service';
import { Field } from '../model/field';
#Component({
selector: 'app-landing-page',
templateUrl: './landing-page.page.html',
styleUrls: ['./landing-page.page.scss'],
})
export class LandingPagePage implements OnInit {
Object = Object;
myArray: Field[] = [];
private collection: AngularFirestoreCollection<Field>;
myCollection: any;
constructor(private auth: AuthService, private router:Router, private http :HttpClient,private afs: AngularFirestore) {
this.collection = this.afs.collection<Field>("Exceldata");
this.myCollection = this.collection.snapshotChanges();
}
ngOnInit() {
this.excelData();
this.auth.getDataFromFirebase().subscribe(myArray => {
this.myArray = myArray;
});
}
logout()
{
this.auth.signOut();
}
excelData(){
var sf = "https://docs.google.com/spreadsheets/d/1qeCEUlVt_hnuyhnoT1wxMMSv7kZW1s4cUIRLynJ0TxQ/gviz/tq?tqx=out:json";
this.http.get(sf,{responseType: 'text'}).subscribe(res=>{
const data =res.toString().match(/google\.visualization\.Query\.setResponse\(([\s\S\w]+)\)/);
if(data && data.length==2){
const obj=JSON.parse(data[1]);
const table=obj.table;
const header = table.cols.map(({label}) => label);
const rows = table.rows.map(({c}) => c.map(({v}) => v));
const values = rows.map(e => header.reduce((o, f, j) => Object.assign(o, {[f]: e[j]}), {}));
console.log(values);
if(!this.collection.doc){
this.collection.doc().set(Object.assign({}, values));
}else{
this.collection.doc().set((values),{merge: true});
}
}
});
}
I'm not sure if there's a better way of doing it but I've survived by storing my items locally eg as an array, appending new item and then saving as a new item.

Read JSON questions file - JAVA game

I have the following JSON file with questions and answer options.
And the code I used trying to print the questions.
{
"GameName": "millionaire game",
"level": 1,
"questions": [
{
"question1": "What is the minimum of players in a footbal game?",
"options1": [
8,
10,
9,
7
],
"answer1": "7"
},
{
"question2": "Who scored maximum goal footbal game?",
"options2": [
"Jhon",
"Pitty",
"Richard",
"Mike"
],
"answer2": "Mike"
},
{
"question3": "What is the maximum of players in a footbal game?",
"options3": [
8,
10,
9,
7
],
"answer3": "7"
}
]
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Random;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.json.*;
public class readJson {
public static void main(String[] args) throws JSONException {
String first = "jsonPerguntas2.json";
try {
String content = new String((Files.readAllBytes(Paths.get(first))));
JSONObject o = new JSONObject(content);
JSONArray firstQuestion = o.getJSONArray("question1");
//System.out.println(conteudo);
for (int i=0; i<firstQuestion.length(); i++){
System.out.println(firstQuestion.get(i));
}
} catch (IOException e) {
}
}
}
I have this code to read the file. But it always return the same error:
Exception in thread "main" org.json.JSONException: JSONObject["question1"] not found.
at org.json.JSONObject.get(JSONObject.java:454)
at org.json.JSONObject.getJSONArray(JSONObject.java:535)
at TrabPraticoJava.TesteLerJson.main(TesteLerJson.java:37)
C:\Users\José Dias\Documents\NetBeansProjects\TrabPraticoJava\nbproject\build-impl.xml:1341: The following error occurred while executing this line:
C:\Users\José Dias\Documents\NetBeansProjects\TrabPraticoJava\nbproject\build-impl.xml:936: Java returned: 1
BUILD FAILED (total time: 0 seconds)
If I change the line JSONArray firstQuestion = o.getJSONArray("question1"); to JSONArray firstQuestion = o.getJSONArray("questions"); it actually prints the all file but I want to print the questions separately.
Can someone help me out?
Thanks in advance
Try this:
JSONArray questions = o.getJSONArray("questions");
for (int i = 0; i < questions.length(); i++) {
JSONObject question = recs.getJSONObject(i);
System.out.println(question.getInt("question"+i+1));
}

How can I access/call array(list) data from another class in Flutter?

Example i have three dart class.
main.dart, firstdata.dart, and seconddata.dart.
then in firstdata.dart and seconddata.dart i have list/array data
firstdata.dart:
class firstdata{
static logo = [ assets/pic1.png, assets/pic2.png];
static name = [ 'dani', 'lict'];}
seconddata.dart:
class seconddata{
static logo = [ 'assets/image1.png', 'assets/image2.png'];
static name = [ 'rose', 'fanny'];}
Question: How can i call/access array/list value from firstdata.dart and seconddata.dart to main.dart?
//Custom class in project directory
class FirstData {
FirstData._();
static logo = [ assets/pic1.png, assets/pic2.png];
static name = [ 'dani', 'lict'];
}
class SecondData {
SecondData._();
static logo = [ assets/image1.png, assets/image2.png];
static name = [ 'rose', 'fanny'];
}
And Now Call Like this any class like:
class MainClass {
// From Class Second
FirstData.logo;
FirstData.name;
// From Class Second
SecondData.logo;
SecondData.name;
}
You can directly access all the static variable using class name only.
void main() {
print(Firstdata.logo);
}
class Firstdata{
static var logo = ['logo'];
static var name = [ 'dani', 'lict'];}
class Seconddata{
static var logo = [ 'assets/image1.png, assets/image2.png'];
static var name = [ 'rose', 'fanny'];}

Data Class Either Object or Array

I have a Kotlin data class that has an arg that can either be an Object or Array. Is there a way to de-serialize a string into this class and not care if not an Array but somehow get it into an array of one?
data class Game(var name:List<NameItem>)
data class NameItem(var title: String, var id: Int)
data can come back as both ways a single object or an array of objects( I have no control over the data as it is 3rd party data.
jsonString = "{"game":{"name":{"title":"GameName","id":22}}}"
jsonString = "{"game":{"name":[{"title":"GameName","id":22},{"title":"GameName2","id":23}]}}"
game: Game? = Gson().fromJson(jsonString Game::class.java)
You have to write a custom JsonDeserializer. Both or your class should have the same parent class. Then, write a custom JsonDeserializer for this specific type.
For example:
sealed class GameParent() {
data class Game(val name: String): GameParent()
data class GameList(val games: List<Game>): GameParent()
}
class GameDeserializer : JsonDeserializer<GameParent> {
override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): GameParent {
with(json) {
if(isJsonObject) {
// parse as Game
}
if(isJsonArray) {
// parse as GameList
}
}
}
}
Then, in your GsonBuilder you have to register this custom JsonDeserializer:
gsonBuilder.registerTypeAdapter(GameParent::class.java, GameDeserializer());
Now, whenever your Gson expect GameParent will use registered deserializer.
my suggestions for solving your task
my solution if name is object, replace it with arrays
data class Game(var name:List<NameItem> )
data class NameItem(var title: String, var id: Int)
fun main(args: Array<String>) {
var json = "{\"game\":{\"name\":[{\"title\":\"game 1\",\"id\":1},{\"title\":\"game 2\",\"id\":2}]}}"
println(useJsonParser(json)) //Game(name=[NameItem(title=game 1, id=1), NameItem(title=game 2, id=2)])
json = "{\"game\":{\"name\":[{\"title\":\"game 1\",\"id\":1}]}}"
println(useJsonParser(json)) //Game(name=[NameItem(title=game 1, id=1), NameItem(title=game 2, id=2)])
json = "{\"game\":{\"name\":{\"title\":\"game 1\",\"id\":1}}}" // not array
println(useJsonParser(json)) //Game(name=[NameItem(title=game 1, id=1)])
}
version 1 -- created and registry adapter link #Cililing
fun useJsonParser(json: String): Game? {
val gson = GsonBuilder().registerTypeAdapter(Game::class.java, GameDeserializer()).create()
return gson.fromJson(json, Game::class.java)
}
class GameDeserializer : JsonDeserializer<Game?> {
override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): Game? {
val gameJson = json!!.asJsonObject.get("game")
if (gameJson.isJsonObject) {
val jsonName = gameJson.asJsonObject["name"]
val list = if (jsonName.isJsonObject) {
arrayOf(Gson().fromJson(jsonName, NameItem::class.java))
} else {
val fromJson = Gson().fromJson(jsonName, Array<NameItem>::class.java)
fromJson
}.toList()
return Game(list)
}
return null
}
}
version 2 -- manipulating the response
fun useJsonParser(json:String):Game?{
val jsonObject = JsonParser().parse(json).asJsonObject.get("game")
if(jsonObject.asJsonObject["name"].isJsonObject){
val jsonName = jsonObject.asJsonObject["name"].asJsonObject
val array = JsonArray()
array.add(jsonName)
jsonObject.asJsonObject.add("name", array) // rewrite origin JSON
}
return Gson().fromJson(jsonObject, Game::class.java)
}
vesrion 3 -- add adapter TypeToken>()
fun useJsonParser(json: String): Game? {
val type = object : TypeToken<MutableList<NameItem>>() {}.type
val gson = GsonBuilder().registerTypeAdapter(type, NameItemDeserializer()).create()
return gson.fromJson(JsonParser().parse(json).asJsonObject.get("game"), Game::class.java)
}
class NameItemDeserializer : JsonDeserializer<List<NameItem>?> {
override fun deserialize(json: JsonElement, type: Type, context: JsonDeserializationContext?): List<NameItem>? {
with(json){
return if(isJsonObject){
arrayListOf(Gson().fromJson(this,NameItem::class.java))
}else{
Gson().fromJson(this,Array<NameItem>::class.java).toList()
}
}
}
}

Angular 2 accessing value in an array

Component:
import { Component, OnInit } from '#angular/core';
import * as _ from "lodash";
import { AF } from '../angularfire.service';
#Component({
selector: 'app-record-chart',
templateUrl: './record-chart.component.html',
styleUrls: ['./record-chart.component.less']
})
export class RecordChartComponent implements OnInit {
currentUser = [];
userRecords = [];
topRecords = [];
topRecordLabels = [];
movements = [
"Back Squat",
"Bench Press",
"Clean",
"Clean & Jerk",
"Deadlift",
"Front Squat",
"Jerk",
"Power Clean",
"Power Snatch",
"Push Press",
"Snatch",
"Strict Press"
];
public barChartOptions:any = {
scaleShowVerticalLines: false,
responsive: true
};
public barChartLabels = this.topRecords[0];
public barChartType:string = 'bar';
public barChartLegend:boolean = true;
public barChartData:any[] = [
{data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A'},
{data: [28, 48, 40, 19, 86, 27, 90], label: 'Series B'}
];
// events
public chartClicked(e:any):void {
console.log(e);
}
public chartHovered(e:any):void {
console.log(e);
}
constructor(private afService: AF) {
// Get current user details.
afService.getCurrentUserInfo().then(currentUserDetails => {
this.currentUser.push(currentUserDetails);
}).then(() => {
// Populate lifts array
for(let movement of this.movements) {
this.afService.getRecords(movement, this.currentUser[0].userID).subscribe((data) => {
var sortedArray = _.orderBy(data, ['weight']);
var sortedArray2 = _.uniqBy(sortedArray,'weight');
// console.log(sortedArray2);
this.userRecords.push(sortedArray);
var newRecords = sortedArray
.filter(function(record) {
return sortedArray.find(function(innerRecord) {
return innerRecord.name === record.name && innerRecord.weight > record.weight; }) === undefined;
});
for (let record of newRecords) {
this.topRecords.push(record);
}
});
}
}).then(() => {
// console.log(this.topRecords);
for (item in this.topRecords) {
this.topRecordLabels.push(item.movement);
}
console.log(this.topRecords);
})
}
ngOnInit() {
}
}
this.topRecords Array output:
How do I iterate through every object in this array and push all of the movement values into their own array? I thought I would be able to access them individually with this.topRecords[0] in a for loop, but it always returns a length of 0.
This is what I thought would work:
for (item in this.topRecords) {
this.topRecordLabels.push(item.movement);
}
But it makes 0 iterations. I'm stuck on figuring out how to access and cycle through the objects of this array.
You can iterate through the array with the map operator and then return another array for your field like this:
this.topRecordLabels = this.topRecords.map((item)=> item.movement);
Example usage: https://jsfiddle.net/echonax/n0e0qxng/
Please remove this line first :
public barChartLabels = this.topRecords[0];
This doesn't make nay sense.
You need to read the differnce b/w for in and for of
Replace your code with :
for (let item of this.topRecords) {
this.topRecordLabels.push(item.movement);
}
For more information , please checkout the link :
What is the difference between ( for... in ) and ( for... of ) in javascript?
#echonax figured this out:
this.topRecordLabels = this.topRecords.map((item)=> item.movement)

Resources