Getting an error while deploying an agent in a node - unetstack

I have written an agent to calculate the distance between two nodes,but when deploying the agent on one of the nodes, following error occurred :
BUG! exception in phase 'semantic analysis' in source unit 'Script26.groovy' The lookup for node_agent caused a failed compilation. There should not have been any compilation from this call.
I have used the command container.add 'myagent' , new node_agent()
Following are the code snippets.
//! Simulation: Simple 3-node network
import org.arl.fjage.*
println '''
3-node network
--------------
'''
platform = RealTimePlatform
// run the simulation forever
simulate {
node '1', address: 101, location: [ 0.km, 0.km, -15.m], web:8081,api: 1101, shell: true, stack: "$home/etc/setup"
node '2', address: 102, location: [ 0.km, 1.km, -15.m], web:8082,api: 1102, shell: 5101, stack: "$home/etc/setup"
node '3', address: 103, location: [-1.km, 0.km, -15.m], web:8083,api: 1103, shell: 5102, stack: "$home/etc/setup"
node 'B', address: 104, location: [ 1.km, 0.km, -15.m], web:8084,api: 1104, shell: 5103, stack: "$home/etc/setup"
}
node_agent.groovy placed in the classes folder
import org.arl.fjage.Message
import org.arl.unet.*
import org.arl.unet.net.Router
import org.arl.unet.phy.*
import org.arl.unet.mac.*
import org.arl.fjage.RealTimePlatform
import org.arl.unet.nodeinfo.NodeInfo
import org.arl.fjage.*
import org.arl.unet.phy.Ranging.*
import org.arl.unet.phy.RangeNtf.*
import org.arl.unet.phy.RangeReq
class node_agent extends UnetAgent {
int addr;
float neighbor_distance;
void startup()
{
def phy = agentForService Services.PHYSICAL;
subscribe topic(phy);
def ranging = agentForService Services.RANGING;
subscribe topic(ranging);
def nodeInfo = agentForService Services.NODE_INFO;
addr = nodeInfo.address;
ranging<< new RangeReq(to: host('3'));
}
void processMessage(Message msg) {
if (msg instanceof RangeNtf )
{
float neighbor_distance = msg.getRange();
println " Distance between node "+addr + " and neighbor 3 is" + neighbor_distance;
}
}
}

In UnetStack 3.2.0, the RangeNtf class (and other ranging related classes) has moved to the org.arl.unet.localization package. See https://unetstack.net/javadoc/3.2/org/arl/unet/localization/RangeNtf.html. So your imports are incorrect.
In general, as described in this post (as pointed out by Jay Patel in the comment above), the way to find such problems is to manually compile the Groovy agent:
$ groovy -cp lib/unet-framework-3.2.0.jar:lib/fjage-1.8.0.jar:lib/unet-basic-3.2.0.jar classes/node_agent.groovy
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
unet/classes/node_agent.groovy: 11: unable to resolve class org.arl.unet.phy.RangeReq
# line 11, column 1.
import org.arl.unet.phy.RangeReq
^
/Users/mandar/Projects/unet/node_agent.groovy: 36: unable to resolve class RangeNtf
# line 36, column 24.
if (msg instanceof RangeNtf )
^
2 errors

Related

Flutter Floor Database from snapshot.data in Future Builder?

I can't able to store snapshot.data to database via floor in Flutter. I wrote entity, dao and database file, builded database and database.g.dart succesed to complete, but when I tried to insertUser function it turns below error;
What am I missing? Is there anything to do for record future snapshot.data which there isn't in [the guide]?1
Error:
════════ Exception caught by gesture ═══════════════════════════════════════════════════════════════
The following NoSuchMethodError was thrown while handling a gesture:
The method 'insertUser' was called on null.
Receiver: null
Tried calling: insertUser(Instance of 'UserF')
My entity:
import 'package:floor/floor.dart';
#entity
class UserF {
#PrimaryKey(autoGenerate: true)
final int id;
final String user;
final int overview;
UserF({this.id,
this.user,
this.overview,
#override
int get hashCode => id.hashCode ^ user.hashCode ^ overview.hashCode ;
#override
String toString() {
return 'UserF{id: $id, user: $user, overview: $overview}';
}
}
DAO:
import 'package:floor/floor.dart';
import 'entity.dart';
#dao
abstract class UserDao {
#Query('SELECT * FROM UserF')
Future<List<UserF>> findAllUsers();
#Query('SELECT * FROM UserF WHERE id = :id')
Stream<UserF> findUserById(int id);
#insert
Future<void> insertUser(UserF userF);
#delete
Future<int> deleteUser(UserF userF);
}
Database:
import 'dart:async';
import 'package:floor/floor.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart' as sqflite;
import 'user_dao.dart';
import 'entity.dart';
part 'database.g.dart'; // the generated code will be there
#Database(version: 1, entities: [UserF])
abstract class AppDatabase extends FloorDatabase {
UserDao get userDao;
}
Related Parts on my main.dart
Future<void> main() async{
WidgetsFlutterBinding.ensureInitialized();
final AppDatabase = await $FloorAppDatabase
.databaseBuilder('database.db')
.build();
runApp(MyApp());
}
....
floatingActionButton: FloatingActionButton(
onPressed: (){
final userf = UserF(user: snapshot.data.user, overview: snapshot.data.overview);
favoriteDao.insertUser(userf);
},
child: Icon(Icons.add),
....
If the code :
part 'database.g.dart';
is creating error that means you have to generate that file.
Add these dependencies if you haven't already:
Dependencies:
floor: ^0.14.0
sqflite: ^1.3.0
Dev Dependencies:
floor_generator: ^0.14.0
build_runner: ^1.8.1
In terminal run the following command:
flutter packages pub run build_runner build
And wait for some time. Flutter will generate the command.
Flutter will automatically generate the file.
REMEMBER: THE NAME OF THE DATABASE FILE AND NAME OF GENERATED FILE MUST BE SAME EXEPT FOR ADDING .g
For Example
if the database file name is mydatabase.dart
the generated file name must be mydatabase.g.dart

Error when passing audio file into watson websocket: [SSL: BAD_LENGTH] bad length (_ssl.c:2341)

I'm trying to identify uses of 'manager', 'warranty', and 'replace' in an audio file using the watson speech to text api. The error I get back is cryptic:
Error received: [SSL: BAD_LENGTH] bad length (_ssl.c:2341)
from __future__ import print_function
import json
from os.path import join, dirname
from ibm_watson import SpeechToTextV1
from ibm_watson.websocket import RecognizeCallback, AudioSource
speech_to_text = SpeechToTextV1(
iam_apikey="__nunya__",
url="__nunya__"
)
class MyRecognizeCallback(RecognizeCallback):
def __init__(self):
RecognizeCallback.__init__(self)
def on_data(self, data):
print(json.dumps(data, indent=2))
def on_error(self, error):
print('Error received: {}'.format(error))
def on_inactivity_timeout(self, error):
print('Inactivity timeout: {}'.format(error))
myRecognizeCallback = MyRecognizeCallback()
with open(join(dirname(__file__), './.', 'AudioRecordings/ComputerSupportCall.mp3'),
'rb') as audio_file:
audio_source = AudioSource(audio_file)
speech_to_text.recognize_using_websocket(
audio=audio_source,
content_type='audio/mp3',
recognize_callback=myRecognizeCallback,
model='en-US_BroadbandModel',
keywords=['manager', 'warranty', 'replace'],
keywords_threshold=0.5,
max_alternatives=3)
What I'm trying to get back is a response in this format:
"keywords_result": {
"manager": [
{
"normalized_text": "manager",
"start_time": 1.52,
"end_time": 2.15,
"confidence": 0.978
}
], (etc ...)
Of course I found the answer right after posting ... the file path was incorrect, should have been:
with open(join(dirname(__file__), 'AudioRecordings/ComputerSupportCall.mp3')
'rb') as audio_file:

how to configure a FileEntityStoreService

I'm trying to use a File EntityStore and I'm having an exception at activation because of slices being zero.
I assume it's an issue with configuration but I expected the default value to be 1.
I narrowed down to this assembly:
import org.apache.polygene.api.common.Visibility;
import org.apache.polygene.api.structure.Application;
import org.apache.polygene.bootstrap.Energy4Java;
import org.apache.polygene.entitystore.file.assembly.FileEntityStoreAssembler;
import org.apache.polygene.index.rdf.assembly.RdfNativeSesameStoreAssembler;
import org.apache.polygene.library.fileconfig.FileConfigurationAssembler;
public class FileStoreException {
public static void main(String[] args) throws Exception {
Energy4Java polygene = new Energy4Java();
Application application = polygene.newApplication(factory -> factory.newApplicationAssembly(
module -> {
new FileConfigurationAssembler()
.visibleIn(Visibility.application)
.assemble(module);
new FileEntityStoreAssembler()
.withConfig(module, Visibility.application)
.assemble(module);
new RdfNativeSesameStoreAssembler()
.withConfig(module, Visibility.application)
.assemble(module);
module.defaultServices();
})
);
application.activate();
}
}
The end of the stacktrace:
Caused by: java.lang.ArithmeticException: / by zero
at method "get" of FileEntityStoreService:FileEntityStoreService in module [Module 1] of layer [Layer 1].(:0)
at org.apache.polygene.entitystore.file.FileEntityStoreMixin.getDataFile(FileEntityStoreMixin.java:277)
at org.apache.polygene.entitystore.file.FileEntityStoreMixin.getDataFile(FileEntityStoreMixin.java:328)
at org.apache.polygene.entitystore.file.FileEntityStoreMixin.get(FileEntityStoreMixin.java:138)
at org.apache.polygene.spi.entitystore.helpers.JSONMapEntityStoreMixin.entityStateOf(JSONMapEntityStoreMixin.java:193)
... 14 more
I'm using version 3.0.0 and I'm on linux.
Adding FileConfigurationAssembler gave me the false impression that my config was done.
I struggled to find a working example of an assembly using a FileEntityStoreAssembler so here's one:
Application application = polygene.newApplication(factory -> factory.newApplicationAssembly(
module -> {
ModuleAssembly config = module.layer().module("Config");
config.defaultServices();
new MemoryEntityStoreAssembler().assemble(config);
config.entities(FileEntityStoreConfiguration.class);
new FileEntityStoreAssembler()
.withConfig(config, Visibility.application)
.assemble(module);
new RdfNativeSesameStoreAssembler()
.withConfig(config, Visibility.application)
.assemble(module);
module.defaultServices();
})
);
And to configure it:
config.forMixin(FileEntityStoreConfiguration.class)
.declareDefaults()
.directory().set("/home/user/appdata/");

Play-Reactivemongo 0.12.0 angular-seed

While refactoring from ReactiveMongo.0.11.1 to ReactiveMongo 0.12.0 in reference of https://github.com/AhmadMelegy/play-silhouette-reactivemongo-angular-seed compilation failed:
def configure() {
bind[DB].toInstance
{
import com.typesafe.config.ConfigFactory
import reactivemongo.api.DefaultDB
import scala.concurrent.ExecutionContext.Implicits.global
import scala.collection.JavaConversions._
import scala.concurrent.Future
val config = ConfigFactory.load
val driver = new MongoDriver
val connection = driver.connection(
config.getStringList("mongodb.servers"),
MongoConnectionOptions(),
Seq()
)
connection.database(config.getString("mongodb.db"))
}
How to resolve this issue?
required: reactivemongo.api.DB
found : scala.concurrent.Future[reactivemongo.api.DefaultDB]
Not recommended
You can use Await to receive result from the Future and bind it.
Recommended
Use "play.modules.reactivemongo.ReactiveMongoModule"
http://reactivemongo.org/releases/0.12/documentation/tutorial/play.html
Example of configuration:
# The default URI
mongodb.uri = "mongodb://someuser:somepasswd#localhost:27017/foo"
# Another one, named with 'bar'
mongodb.bar.uri = "mongodb://someuser:somepasswd#localhost:27017/lorem"
Example of code
class MyComponent #Inject() (
val defaultApi: ReactiveMongoApi, // corresponds to 'mongodb.uri'
#NamedDatabase("bar") val barApi: ReactiveMongoApi // 'mongodb.bar'
) {
}
If you need to do your own binding, then just look at this example:
https://github.com/ReactiveMongo/Play-ReactiveMongo/blob/master/src/main/scala/play/modules/reactivemongo/ReactiveMongoModule.scala

The package com.google.appengine.api.urlfetch cannot be found

We are trying to use a URL fetcher to retrieve get the response of an GAE API method, using the following code. As far as I'm aware this code is correct, but there seems to be a problem with the imports. Am I missing a dependency from the gradle build file perhaps? Have looked around on the internet but haven't got anywhere.
import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;
import java.io.IOException;
import java.net.URL;
import java.util.List;
…
URLFetchService fetcher = URLFetchServiceFactory.getURLFetchService();
try {
URL url = new URL("<URL we use is redacted>");
HTTPResponse response = fetcher.fetch(url);
byte[] content = response.getContent();
// if redirects are followed, this returns the final URL we are redirected to
URL finalUrl = response.getFinalUrl();
// 200, 404, 500, etc
int responseCode = response.getResponseCode();
List < HTTPHeader > headers = response.getHeaders();
for (HTTPHeader header: headers) {
String headerName = header.getName();
String headerValue = header.getValue();
System.out.println(headerName + " " + headerValue);
}
} catch (IOException e) {
// new URL throws MalformedUrlException, which is impossible for us here
}
We are getting the following error:
/Users/Michael/Documents/GradeMe/app/src/main/java/com/ip/grademe/Register.java
Error:(12, 41) error: package com.google.appengine.api.urlfetch does not exist
Error:(13, 41) error: package com.google.appengine.api.urlfetch does not exist
Error:(14, 41) error: package com.google.appengine.api.urlfetch does not exist
Error:(15, 41) error: package com.google.appengine.api.urlfetch does not exist
Error:(73, 17) error: cannot find symbol class URLFetchService
Error:(73, 43) error: cannot find symbol variable URLFetchServiceFactory
Error:(77, 21) error: cannot find symbol class HTTPResponse
Error:(85, 26) error: cannot find symbol class HTTPHeader
Error:(87, 25) error: cannot find symbol class HTTPHeader
EDIT: The gradle.build file
apply plugin: 'com.android.application'
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
defaultConfig {
applicationId "com.ip.grademe"
minSdkVersion 14
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.0.0'
compile project(path: ':backend', configuration: 'android-endpoints')
}

Resources