Static class fields in Chapel - static

Does Chapel have the equivalent of the C++/Java static class field whose value is shared between class objects? If not, what should one do?

Chapel does not support an equivalent of static class fields. However, it does support an equivalent of static class methods, referred to as type methods in Chapel.
If one needed static class fields in Chapel, they could use a parentheses-less method returning a globally defined variable for a similar effect, e.g.
var globalValue = 42;
class C {
var a = 1;
proc b {
return globalValue;
}
}
var c1 = new owned C(1);
var c2 = new owned C(2);
writeln(c1.a);
writeln(c1.b);
writeln(c2.a);
writeln(c2.b);
globalValue += 1;
writeln(c1.a);
writeln(c1.b);
writeln(c2.a);
writeln(c2.b);
Output:
1
42
2
42
1
43
2
43

Related

Room Data Base Create Instance

I want to Create An Instance Of Room Data base in Composable
But
val db = Room.databaseBuilder(applicationContext, UserDatabase::class.java,"users.db").build()
is not working here not getting applicationContext
How to create an instance of context in composable
Have you tried getting the context with : val context = LocalContext.current and then adding this to get your applicationContext?
Like this: context.applicationContext or using simply val db = Room.databaseBuilder(context, UserDatabase::class.java,"users.db").build()
Room (and the underlying SQliteOpenHelper) only need the context to open the database (or more correctly to instantiate the underlying SQLiteOpenHelper).
Room/Android SQLiteOpenHelper uses the context to ascertain the Application's standard (recommended) location (data/data/<the_package_name>/databases). e.g. in the following demo (via Device Explorer):-
The database, as it is still open includes 3 files (the -wal and -shm are the Write Ahead Logging files that will at sometime be committed/written to the actual database (SQLite handles that)).
so roughly speaking Room only needs to have the context so that it can ascertain /data/data/a.a.so75008030kotlinroomgetinstancewithoutcontext/databases/testit.db (in the case of the demo).
So if you cannot use the applicationContext method then you can circumvent the need to provide the context, if using a singleton approach AND if after instantiating the singleton.
Perhaps consider this demo:-
First some pretty basic DB Stuff (table (#Entity annotated class), DAO functions and #Database annotated abstract class WITH singleton approach). BUT with some additional functions for accessing the instance without the context.
#Entity
data class TestIt(
#PrimaryKey
val testIt_id: Long?=null,
val testIt_name: String
)
#Dao
interface DAOs {
#Insert(onConflict = OnConflictStrategy.IGNORE)
fun insert(testIt: TestIt): Long
#Query("SELECT * FROM testit")
fun getAllTestItRows(): List<TestIt>
}
#Database(entities = [TestIt::class], exportSchema = false, version = 1)
abstract class TestItDatabase: RoomDatabase() {
abstract fun getDAOs(): DAOs
companion object {
private var instance: TestItDatabase?=null
/* Extra/not typical for without a context (if wanted)*/
fun isInstanceWithoutContextAvailable() : Boolean {
return instance != null
}
/******************************************************/
/* Extra/not typical for without a context */
/******************************************************/
fun getInstanceWithoutContext(): TestItDatabase? {
if (instance != null) {
return instance as TestItDatabase
}
return null
}
/* Typically the only function*/
fun getInstance(context: Context): TestItDatabase {
if (instance==null) {
instance = Room.databaseBuilder(context,TestItDatabase::class.java,"testit.db")
.allowMainThreadQueries() /* for convenience/brevity of demo */
.build()
}
return instance as TestItDatabase
}
}
}
And to demonstrate (within an activity for brevity) :-
class MainActivity : AppCompatActivity() {
lateinit var roomInstance: TestItDatabase
lateinit var dao: DAOs
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
roomInstance = TestItDatabase.getInstance(this) /* MUST be used before withoutContext functions but could be elsewhere shown here for brevity */
dao = roomInstance.getDAOs()
//dao.insert(TestIt(testIt_name = "New001")) /* Removed to test actually doing the database open with the without context */
logDataWithoutContext()
addRowWithoutContext()
addRowWithApplicationContext()
logDataWithoutContext()
}
private fun logDataWithoutContext() {
Log.d("${TAG}_LDWC","Room DB Instantiated = ${TestItDatabase.isInstanceWithoutContextAvailable()}")
for (t in TestItDatabase.getInstanceWithoutContext()!!.getDAOs().getAllTestItRows()) {
Log.d("${TAG}_LDWC_DATA","TestIt Name is ${t.testIt_name} ID is ${t.testIt_id}")
}
}
private fun addRowWithoutContext() {
Log.d("${TAG}_LDWC","Room DB Instantiated = ${TestItDatabase.isInstanceWithoutContextAvailable()}")
if (TestItDatabase.getInstanceWithoutContext()!!.getDAOs()
.insert(TestIt(System.currentTimeMillis(),"NEW AS PER ID (the time to millis) WITHOUT CONTEXT")) > 0) {
Log.d("${TAG}_ARWC_OK","Row successfully inserted.")
} else {
Log.d("${TAG}_ARWC_OUCH","Row was not successfully inserted (duplicate ID)")
}
}
private fun addRowWithApplicationContext() {
TestItDatabase.getInstance(applicationContext).getDAOs().insert(TestIt(System.currentTimeMillis() / 1000,"NEW AS PER ID (the time to seconds) WITH CONTEXT"))
}
}
The result output to the log showing that the database access, either way, worked:-
2023-01-05 12:45:39.020 D/DBINFO_LDWC: Room DB Instantiated = true
2023-01-05 12:45:39.074 D/DBINFO_LDWC: Room DB Instantiated = true
2023-01-05 12:45:39.077 D/DBINFO_ARWC_OK: Row successfully inserted.
2023-01-05 12:45:39.096 D/DBINFO_LDWC: Room DB Instantiated = true
2023-01-05 12:45:39.098 D/DBINFO_LDWC_DATA: TestIt Name is NEW AS PER ID (the time to seconds) WITH CONTEXT ID is 1672883139
2023-01-05 12:45:39.098 D/DBINFO_LDWC_DATA: TestIt Name is NEW AS PER ID (the time to millis) WITHOUT CONTEXT ID is 1672883139075
note that the shorter id was the last added but appears first due to it being selected first as it appears earlier in the index that the SQlite Query Optimiser would have used (aka the Primary Key).
basically the same date time second wise but the first insert included milliseconds whilst the insert via AddRowWithApplicationContext drops the milliseconds.

Need an alternate approach to get TestNG dataprovider arguments

I am reading data from excel using data provider, which has some 25 odd columns and 250 odd rows. I am reading and returning Object[][] from data provider.
In turn I have to declare so 25 arguments in my test method For example
#Test(groups = { "regressionTest" }, dataProvider = "testDP")
public void testDP(String statusResponse, String statusHeader, String reposnseID, String responseConetent ..... String lastElement)
And the value of arguments are different for different test methods of test class. All I want, is not to declare 25 arguments every time I am writing a seperate test method, rather a approach similar to passing an object of class would be great.
//like having a POJO Class
#Test(groups = { "regressionTest" }, dataProvider = "testDP")
public void testDP(Class obj ){
//accessing the variables with getter/setter methods.
obj.getstatusHeader();
obj.getstatusResponse();
etc...
}
Thanks,
Vinod Baradwaj

Retrieving every field of a database row as object in zend framework 2

I know we have result set to get a row as object But How can I get every field as a separate object ? consider of this database row :
user_id address_id product_id shop_id
5 3 134 2
I want to retrieve and save the row as follows :
userEntity AddressEntity ProductEntity ShopEntity
This is not how the TableDataGateway is supposed to be used, since what you are looking for are more complex features such as the ones of Doctrine 2 ORM and similar data-mappers.
Here is one possible solution to the problem, which involves using a custom hydrator (docs). My example is simplified, but I hope it clarifies how you are supposed to build your resultset.
First, define your entities (I'm simplifying the example assuming that UserEntity is the root of your hydration):
class UserEntity {
/* fields public for simplicity of the example */
public $address;
public $product;
public $shop;
}
class AddressEntity { /* add public fields here for simplicity */ }
class ProductEntity { /* add public fields here for simplicity */ }
class ShopEntity { /* add public fields here for simplicity */ }
Then, build hydrators specific for the single entities:
use Zend\Stdlib\Hydrator\HydratorInterface as Hydrator;
class AddressHydrator implements Hydrator {
// #TODO: implementation up to you
}
class ProductHydrator implements Hydrator {
// #TODO: implementation up to you
}
class ShopHydrator implements Hydrator {
// #TODO: implementation up to you
}
Then we aggregate these hydrators into one that is specifically built to hydrate a UserEntity:
class UserHydrator extends \Zend\Stdlib\Hydrator\ObjectProperty {
public function __construct(
Hydrator $addressHydrator,
Hydrator $productHydrator,
Hydrator $shopHydrator
) {
$this->addressHydrator = $addressHydrator;
$this->productHydrator = $productHydrator;
$this->shopHydrator = $shopHydrator;
}
public function hydrate(array $data, $object)
{
if (isset($data['address_id'])) {
$data['address'] = $this->addressHydrator->hydrate($data, new AddressEntity());
}
if (isset($data['product_id'])) {
$data['product'] = $this->productHydrator->hydrate($data, new ProductEntity());
}
if (isset($data['shop_id'])) {
$data['shop'] = $this->shopHydrator->hydrate($data, new ShopEntity());
}
return parent::hydrate($data, $object);
}
}
Now you can use it to work with your resultset. Let's define the service for your UserEntityTableGateway:
'UserEntityTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new UserHydrator());
return new TableGateway('user', $dbAdapter, null, $resultSetPrototype);
},
These are all simplified examples, but they should help you understanding how powerful hydrators can be, and how you can compose them to solve complex problems.
You may also check the chapters in the documentation about the Aggregate Hydrator and Hydration Strategies, which were designed specifically to solve your problem.

How to get the date when an entity was persisted

I want to sort a celltable by the last ones added on top, now , to do this, i need to sort them by the date they were added to the application. Is there a way to get this date? or i have to create a new attribute for each class?. Thanks!
You need to create your own attribute.
If I'm understanding well, you can use a comparator. For example, suppose you have some clas into gwt.shared.model package such as:
public class SomeClass implements IsSerializable {
private Date date;
// some stuff...
}
Then, implement a comparator for that class
import java.util.Comparator;
public class SomeClassComparator implements Comparator<SomeClass> {
#Override
public int compare(SomeClass someObject1, SomeClass someObject2) {
if (someObject1.getDate().getTimeInMillis() > someObject2.getDate().getTimeInMillis()) return 1
else if someObject1.getDate().getTimeInMillis() > someObject2.getDate().getTimeInMillis() return 0;
else return 0;
}
}
Before adding objects into the table you must do:
List<SomeClass> someObjects = ... // list of objects
Collection.sort(someObjects);
Then you can show them in the cell table.
Edit 1: the comparator must be included in gwt.shared.model

Entity, Entity Groups and List using Objectify 4

I'm having some difficulty to solve this kind of problem:
I Have some nested entities and I'm trying to persist them in the same transaction (HRD enable).
Entity A:
#Entity
public class A {
#Id Long id;
List<B> children;
}
Entity B:
#Entity
public class B {
#Id Long id;
}
When I try to persist 6 instances (just two Entity Groups, A e B) ...
public void testOfy() {
ofy.getFactory().register(A.class);
ofy.getFactory().register(B.class);
List<B> list = new ArrayList<B>();
final A a0 = new A();
final B b1 = new B();
final B b2 = new B();
final B b3 = new B();
final B b4 = new B();
final B b5 = new B();
Ofy o = ofy.transaction();
try {
o.save().entities(b1).now(); list.add(b1);
o.save().entities(b2).now(); list.add(b2);
o.save().entities(b3).now(); list.add(b3);
o.save().entities(b4).now(); list.add(b4);
o.save().entities(b5).now(); list.add(b5);
a0.children = list;
o.save(a0);
o.getTxn().commit();
}
finally {
if (o.getTxn().isActive())
o.getTxn().rollback();
}
}
I get the Exception:
java.lang.IllegalArgumentException: operating on too many entity groups in a single transaction.
at com.google.appengine.api.datastore.DatastoreApiHelper.translateError(DatastoreApiHelper.java:36)
However if I put just 5 instances everything works...
public void testOfy() {
ofy.getFactory().register(A.class);
ofy.getFactory().register(B.class);
List<B> list = new ArrayList<B>();
final A a0 = new A();
final B b1 = new B();
final B b2 = new B();
final B b3 = new B();
final B b4 = new B();
final B b5 = new B();
Ofy o = ofy.transaction();
try {
o.save().entities(b1).now(); list.add(b1);
o.save().entities(b2).now(); list.add(b2);
o.save().entities(b3).now(); list.add(b3);
o.save().entities(b4).now(); list.add(b4);
// o.save().entities(b5).now(); list.add(b5);
a0.children = list;
o.save(a0);
o.getTxn().commit();
}
finally {
if (o.getTxn().isActive())
o.getTxn().rollback();
}
}
I'm using Objectify 4.0b3, does anyone have any suggestion?
Thank you!
You have misunderstood what an entity group is. An entity group is not a class, it is an instance (or a group of instances).
Each of those entities represent a separate entity group. XG transactions allow a maximum of five EGs per transaction. The 6th produces the error you see.

Resources