average of counts with Laravel 5 - eloquent

We have two classes: Module and Resource, with a module having many resources:
class Module extends Model {
public function resources() {
return $this->hasMany('App\Models\Resource');
}
}
and a resource belonging to a Module:
class Resource extends Model {
public function module() {
return $this->belongsTo('App\Models\Module');
}
}
I need to show a list of all the modules with:
The number of resources for each each module
The average of resources per module
The first one is added to the Module model so it can be used with eager loading:
public function resourcesCount() {
return $this->hasMany('App\Models\Resource')
->selectRaw('module_id, count(*) AS aggregate')
->groupBy('module_id');
}
However, I can't find an efficient and elegant way to calculate the average of the counts calculated by resourcesCount. I know I could iterate through the results of
$modules = Module::with('resourcesCount')->get();
and do it manually, but I feel there's something better out there.
EDIT: forgot to say that I modified the accessor for the resourcesCountAttribute:
public function getResourcesCountAttribute() {
if (!$this->relationLoaded('resourcesCount'))
$this->load('resourcesCount');
$related = $this->getRelation('resourcesCount');
return ($related) ? (int) $related->aggregate : 0;
}
So I can use 'resourcesCount' (See my response), rather than having to use 'resourcesCount.aggregate'.

I found out an acceptable way to do so, using the collection's methods.
// Returns an elloquent collection
$modules = Module::with('resourcesCount')->get();
// counts sums divided by the number of
$avgResources = $modules->sum('resourcesCount') / $modules->count();

The only way would be to do it through iteration or in a separate DB::select() statement, relying on things like GROUP BY and AVERAGE().

Related

Yang Model recursive search for must condition

I have a problem with a restriction on my CLI. I've been investigating yang RFC7950 (https://www.rfc-editor.org/rfc/rfc7950) but I've found nothing.
Here is an example.
grouping httpGroup {
list http-list{
key "value";
leaf value {
status current { yexte:preliminary; }
description "value to match";
must "(not(../protocol)) and (not(../network-port)))" {
error-message "Not compatible with protocol or non-TCP ports";
}
type string { length "1..255"; }
}
}
}
This group will be included in several groups with the following structure:
list and {
leaf-list protocol { ..... }
uses A;
list or {
leaf-list protocol { ..... }
uses A;
}
}
grouping A {
status{}
leaf-list protocol { ..... }
leaf-list X { ..... }
uses httpGroup;
}
I need this must condition included in httpGroup to verify that protocol value has not been configured in any level of the hierarchy.
I've made this be adding more relatives paths to search for this node:
// same level
not(../protocol)
// next level
not(../and/protocol)
not(../or/protocol)
// previous level
not(../../protocol)
not(../../protocol)
//recursively down previous level
not(../../and/protocol)
not(../../or/protocol)
// third level
not(../and/or/protocol)
not(../and/and/protocol)
As you can see, this is not a clean solution at all.
Is there any way it can be done for a whole hierarchy like:
if protocol node exists and http-list exists then error.
Thank you in advance.
Groupings are meant to be reusable. It is a bad practice to attempt to create a grouping that may only be used in specific contexts. This is exactly what happens if you define an XPath expression within a grouping and this expression references nodes that are "outside" this grouping (a not yet known ancestor data node, for example, or even worse - an ancestor with a specific name).
The proper way for you to handle this situation would be to use a refine statement in each different context where this grouping is used. You target the value leaf with it, then refine it by adding a must statement, the expression of which of course depends on usage context. You do not define a must statement within grouping http-list.
Within grouping A:
grouping A {
status{}
leaf-list protocol { ..... }
leaf-list X { ..... }
uses httpGroup {refine "http-list/value" {must "not(../../protocol)";}}
}
As you can see, grouping A is now completely self-sufficient and may be used within any context - the must will not have any problems with it.

openscad drill into group created by for

I know that when I use for it creates a group of the generated children.
I created a module called grid like so:
module grid(x0,y0,dx,dy,nx,ny) {
for (x=[0:1:nx-1]) {
for(y=[0:1:ny-1]) {
i=x*nx+y;
echo(i);
translate([x0+x*dx,y0+y*dy,0]) children(i);
}
}
}
which when used like this:
grid(-50,-50,25,25,5,5) {
cube([10,10,10],center=true);
cube([10,10,10],center=true);
cube([10,10,10],center=true);
cube([10,10,10],center=true);
//.. continue to create 25 cubes total
}
arranges the cubes in a nice grid.
however my original hope and intention was to use it like this:
grid(-50,-50,25,25,5,5) {
for(i=[0:1:24]) {
cube([10,10,10],center=true);
}
}
Which fails because the for operator returns a group and not a set of children.
Why does the for add a group to begin with? (also leading to the need for intersection_for)
And is there a way for my Grid operator module to handle the children of the group?
I personally hope for the grouping/union for elements within a for() to become optional at some time.
If you don't mind compiling OpenSCAD from source, you could try it already today.
There is an ongoing issue Lazy union (aka. no implicit union)
and a patch here Make for() UNION optional
Just updated my knowledge of OpenSCAD, there is a better solution:
module nice_cube()
{
translate([0,0,$height/2]) cube([9,9,$height], center = true);
}
module nice_cylinder()
{
translate([0,0,$height/2]) cylinder(d=10,h=$height, center = true);
}
module nice_text()
{
linear_extrude(height=$height, center=false) text(str($height), size=5);
}
module nice_grid()
{
for(i=[0:9], j=[0:9])
{
$height=(i+1)*(j+1);
x=10*i;
y=10*j;
translate([x,y,0]) children();
/* let($height=(i+1)*(j+1)) {children();} */
}
}
nice_grid() nice_cube();
translate([0,-110,0]) nice_grid() nice_text();
translate([-110,0,0]) nice_grid() nice_cylinder();
The trick here is to control the shape produced by module by special variables (starting with $) those can be used like in example, commented line using let() requires development version of openscad.
I guess You want this:
for(x=[...], y=[...]) {
translate([x,y,0]) children();
}
Note, that you need only one for statement to loop through both x and y values.
What I have understood from your comment is, that you want your objects in the nodes of the grids to be parametric, and parameter depends on index. This requirement was not mentioned in the original question. In this case, solution depends on your problem context, I guess. The two possibilities I see are:
module grid_of_parametric_modules(other_param)
{
for(i=[0:24])
{
x=_x(i);
y=_y(i);
translate([x,y,0]) parametric_module(i_param(i), other_param);
}
}
However this may not be suitable, especially if You are going to add new shapes to your grid in future. Then you can probably do it like:
function grid_pos(i) = [_x(i), _y(i), 0];
....
for(i=[0:24])
translate(grid_pos(i)) parametric_module(i);

Spring Batch - Invoke read() method in Reader multiple times

I am trying to implement calling read() method in the itemReader multiple times.
For Eg:
I have a list of POJO in which I will have one string variable with values either A or B or C.
I have to sort this list based on alphabetical order and segment it into three list for each value. i.e., list for value A and list for value B
and list for value C.
I need to send each list to the read() method in the itemReader one by one.
Once List for A is processed and write, then I need to send List for B and so on..
Is this doable? Any help is appreciated.
Although I am not very clear on what you are trying to achieve, I don't see any reason it cannot be done.
I assume you mean either of this:
1. You want the "item" to be process to be a whole list of POJO with same ABC Type, or
2. You want the item to be the POJO itself, and you want them to be processed in order of ABC Type
2 is straight-forward. At the first read, prepare all the POJOs, sort it. I assume they are in some kind of
In psuedo code, it looks like this
class MyReader implements ItemReader<MyPojo> {
private List<MyPojo> values;
MyPojo read() {
if (values == null) {
values = getPojos();
sort values;
}
if (values.isEmpty()){
return null;
} else {
return values.popFront();
}
}
}
1 is nothing more complicated. You will need to group POJOs with same ABC type in same list, and return the lists one by one. It can be easily done by using a TreeMap<String, List<MyPojo>>
In psuedo code, it looks like this
class MyReader implements ItemReader<List<MyPojo>> { // note the item is List<MyPojo>
private NavigableMap<String, List<MyPojo>> values;
List<MyPojo> read() {
if (values == null) {
values = new TreeMap<>();
pojos = getPojos();
for (pojo : pojos) {
if (values do not contain pojo.abcType() ) {
values.put(pojo.abcType(), new ArrayList(pojo));
} else {
values.get(pojo.abcType()).add(pojo);
}
}
}
if (values.isEmpty()){
return null;
} else {
return values.popFirstEntry().value();
}
}
}
If your list of items is fully available (you have a List<Pojo> loaded with all items) you can:
use a ListItemReader and inject into the ordered list
use a custom ItemReader and sort items after first ItemReader.read()
About break the best way is to use a custom CompletionPolicy based on pojo 'string variable'; in this manner your writer will receive a list where POJO's 'string variable' has the same values for all list items (check How to read csv lines chunked by id-column with Spring-Batch? for sample code).

In Tritium, is there a way to assign an id based on child number?

I have a table with a series of rows. I want to change them into divs, but maintain (somehow) their positional information. At the moment, this is what I'm doing:
$("./tr[1]") {
add_class("mw_old_row_1")
}
$("./tr[2]") {
add_class("mw_old_row_2")
}
$("./tr") {
name("div")
}
But this isn't ideal because:
It's super-repetitive
I don't know how many rows there are
Is there a way to take the child number and include that in the class I'm assigning?
Yup, you want to make use of the index() function. Below is the example you wrote reworked using index():
$("./tr") {
add_class("mw_old_row_" + index())
name("div")
}
Below is a link with the following example in tritium tester: http://tester.tritium.io/775895b154e8e2ce99e100967299c10d73dbeb91

How to parametrize my exports?

I'd like to be able to parametrize my exports not only with types (as in, generic exports), but also with values.
Something like:
class Greeter
{
readonly string _format;
public Greeter( string format ) { _format = format; }
public string Greet( string name ) { return string.Format( _format, name ); }
}
// ...
var e = new ExportProvider();
e.ExportParametrized<Greeter>( args: new[] { "Hi, {0}!" } );
e.ExportParametrized<Greeter>( args: new[] { "¡Hola, {0}!" } );
// And then:
[ImportMany] IEnumerable<Greeter> Greeters { get; set; }
foreach( var g in Greeters ) Console.WriteLine( g.Greet( "John" ) );
// Should print out:
// Hello, John!
// ¡Hola, John!
One might ask: why don't I simply export the value new Greeter( "Hello, {0}!" ) using ComposablePartExportProvider and CompositionBatch?
While this approach would work in this particular case, it has an important flaw: if the Greeter class had any imports of its own, they would not be satisfied.
The usual way I would go about this is to declare two classes - EnglishGreeter and SpanishGreeter, inherit them both from Greeter, and then provide the appropriate arguments in the call to base constructor.
But this doesn't work for two reasons:
This is a lot of noise to write. Not only do I have to type the whole shebang, I also have to come up with names for those classes, and it doesn't always make sense to have names. Not to mention the DRY principle. But even besides the noise...
Sometimes I don't know the parameters upfront. Say, for example, my greeting formats were coming from some kind of config file.
Here is another thought, to somewhat clarify what I'm looking for.
This problem is almost solved in the TypeCatalog. See, the TypeCatalog knows about the type and it calls the type's constructor to create the part on demand.
One can think of this process from another standpoint: the catalog has a factory function; using that function, it creates the part, then satisfies its non-prerequisite imports, and then returns the part back to the requestor.
Now, in the particular case of TypeCatalog, the factory function just happens to be the type's own constructor. If only I could hook in and replace the factory function with my own, but still leverage the rest of the machinery, that would be exactly what I'm looking for.
You can achieve this by using property exports. You could define a class specifically for those kinds of exports, and it will look like this:
class MyParameterizedExports
{
[Export(typeof(Greeter))]
private Greeter EnglishGreeter
{
get
{
Greeter g = new Greeter("Hi, {0}!");
container.SatisfyImportsOnce(g);
return g;
}
}
[Export(typeof(Greeter))]
private Greeter SpanishGreeter
{
get
{
Greeter g = new Greeter("¡Hola, {0}!");
container.SatisfyImportsOnce(g);
return g;
}
}
}
Here you export two separate Greeter instances without having to define a new class for each type of Greeter.