问:
Angular model doesn't update after ng-click
the ng-repeat model doesn't update after a user clicks submit, it will only show on refresh, i reviewed a similar problem, but i couldn't connect the dots. A user recommended i do a ng-init, but i don't think im doing it right.

with ng-init it shows no data, without ng-init and removing the angular function it shows posts but doesn't update the model after click.

note:the angular brackets are replaced because laravel blade doesn't like it

html

```<code>    <div id="mypost" class="col-md-8 panel-default" ng-init="getPosts()" ng-repeat="post in myposts">
        <div id="eli-style-heading" class="panel-heading"><% post.title %></div>
            <div class="panel-body panel">
                <figure>
                    <p> <% post.body %></p>

                </figure>
            </div>

    </div>
</code>```

Main.js

```<code>// this doens't show posts when i use ng-init
$scope.getPosts = function(){

    $http.get('/auth/posts').then(function(data){
        $scope.myposts = data.data;
    });

};

// this shows posts without ng-init but doesn't update when a user adds data

$http.get('/auth/posts').then(function(data){
    $scope.myposts = data.data;
});
</code>```

Updated Again

network error

PostController.php

```<code>public function storePost(Request $request)
{
    $data = request()->validate([
     'title' => 'required|max:120',
     'body' => 'required|max:1000'
    ]);

    $data['user_id'] = auth()->user()->id;

    $post = Post::create($data);

    // return redirect('/home')->withMessage('A new post was created.');

    return Response::json(array('success' => true));
}
</code>```

答:
Don't use ng-init except in cases where you are aliasing a special property of ng-repeat like $last or $even for nested ng-repeats.  If you want a function to trigger immediately just call it in the controller or service/factory it is defined in.

https://jsfiddle.net/xf20j22u/1/

var app = angular.module('eli', []);

app.config(function($interpolateProvider) {
    $interpolateProvider.startSymbol('<%');
    $interpolateProvider.endSymbol('%>');
});

app.controller('mainCtrl', function($scope, $http, $timeout){
 $scope.posts = {};
  $scope.myposts = [{title:"titillating title",body:"Hot boddy"}]
 $scope.addPost = function(){

  $http.post('/auth/post', {
   title: $scope.post.title,
   body: $scope.post.body

  }).then(function(data, status, headers, config){
   $scope.posts.push(data);

  });

 };

 $scope.getPosts = function(){

  $timeout(function(){
          debugger;
          $scope.myposts = [{title:"something new",body:"It's my body"}]
        },3000)
  //$http.get('/auth/posts').then(function(data){
  // $scope.myposts = data.data;
  // $scope.$apply();
  //});
 };
  $scope.getPosts();

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.js"></script>
<div  ng-app="eli" ng-controller="mainCtrl">

  <div id="mypost" class="col-md-8 panel-default" ng-repeat="post in myposts">
    <div id="eli-style-heading" class="panel-heading">
      <% post.title %>
    </div>
    <div class="panel-body panel">
      <figure>
        <p>
          <% post.body %>
        </p>

      </figure>
    </div>
  </div>
</div></code>```

Working version above can replace $timeout with $http they both call $apply for you so don't call it again (only need to call $apply if you write your own things that async do work then update the model and you want to trigger a view refresh, angular event handlers and services do it for you)

Body:
the ng-repeat model doesn't update after a user clicks submit, it will only show on refresh, i reviewed a similar problem, but i couldn't connect the dots. A user recommended i do a ng-init, but i don't think im doing it right.

with ng-init it shows no data, without ng-init and removing the angular function it shows posts but doesn't update the model after click.

note:the angular brackets are replaced because laravel blade doesn't like it

html

<% post.title %>

 <% post.body %>

Main.js

// this doens't show posts when i use ng-init
$scope.getPosts = function(){

    $http.get('/auth/posts').then(function(data){
        $scope.myposts = data.data;
    });

};

// this shows posts without ng-init but doesn't update when a user adds data

$http.get('/auth/posts').then(function(data){
    $scope.myposts = data.data;
});

Updated Again

network error

PostController.php

public function storePost(Request $request)
{
    $data = request()->validate([
     'title' => 'required|max:120',
     'body' => 'required|max:1000'
    ]);

    $data['user_id'] = auth()->user()->id;

    $post = Post::create($data);

    // return redirect('/home')->withMessage('A new post was created.');

    return Response::json(array('success' => true));
}

Body:
Don't use ng-init except in cases where you are aliasing a special property of ng-repeat like $last or $even for nested ng-repeats.  If you want a function to trigger immediately just call it in the controller or service/factory it is defined in.

https://jsfiddle.net/xf20j22u/1/

var app = angular.module('eli', []);

app.config(function($interpolateProvider) {
    $interpolateProvider.startSymbol('<%');
    $interpolateProvider.endSymbol('%>');
});

app.controller('mainCtrl', function($scope, $http, $timeout){
 $scope.posts = {};
  $scope.myposts = [{title:"titillating title",body:"Hot boddy"}]
 $scope.addPost = function(){

  $http.post('/auth/post', {
   title: $scope.post.title,
   body: $scope.post.body

  }).then(function(data, status, headers, config){
   $scope.posts.push(data);

  });

 };

 $scope.getPosts = function(){

  $timeout(function(){
          debugger;
          $scope.myposts = [{title:"something new",body:"It's my body"}]
        },3000)
  //$http.get('/auth/posts').then(function(data){
  // $scope.myposts = data.data;
  // $scope.$apply();
  //});
 };
  $scope.getPosts();

});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.js"></script>
<div  ng-app="eli" ng-controller="mainCtrl">

  <div id="mypost" class="col-md-8 panel-default" ng-repeat="post in myposts">
    <div id="eli-style-heading" class="panel-heading">
      <% post.title %>
    </div>
    <div class="panel-body panel">
      <figure>
        <p>
          <% post.body %>
        </p>

      </figure>
    </div>
  </div>
</div>

Working version above can replace $timeout with $http they both call $apply for you so don't call it again (only need to call $apply if you write your own things that async do work then update the model and you want to trigger a view refresh, angular event handlers and services do it for you)


来源: stackexchange

问:
Best practice to reuse RecyclerView layout in other places
I have a Fragment which contains a RecyclerView to display a list of items in a feed. However, an individual item might be opened in another Fragment with the same layout it has in the RecyclerView.

What would be the best practice for this scenario? Could/should I create a separate Fragment for the item and use it somehow in the RecyclerView?

答:
Well, when you create RecyclerView in the first fragment, you also create layout for the item you want to display. In the other, fragment you can just include the layout of the item. I don't think it can get more simple than that.

My practice is, i try to identify items that repeat itself and i try to create general layouts, for example, layout with title and subtitle and the use this layout in RecyclerView or just include it. Good thing here is that RecyclerView allows you to have different layouts and instead of drawing views or including it (if there are more view in fragment that i have created), i just add it to one RecyclerView.

ContentLicense: CC BY-SA 3.0


问:
Parsing objects with several keys on the same index
I am struggeling to parse the following object, which I am getting from an input-form field:

```<code>const obj = { 'repeater-group[1][titel]': 'test1',
  'repeater-group[1][description]': 'test1',
  'repeater-group[3][titel]': 'test2',
  'repeater-group[3][description]': 'test2',
  'repeater-group[5][titel]': 'test3',
  'repeater-group[5][description]': 'test3' }

const desc = 'undefined'
const titel = 'undefined'
let i = 0
for (const k in obj) {
    const item = obj[k]

    if (k === `repeater-group[${i}][titel]`) {
        titel = item
    }
    if (k === `repeater-group[${i}][description]`) {
        desc = item
    }
    if (titel != 'undefined' && desc != 'undefined') {
        try {
            console.log(titel + ", " + desc)
        }
        catch (error) {
            console.log(error)
        }
    }

    i += 1
}
// Currently there is no output
</code>```

I would like to have the following output

```<code>//Expected output
// test1, test1
// test2, test2
// test3, test3
</code>```

Any suggestions what is wrong with my code?

Is there even a shorter way to do this object parsing?

I highly appreciate your replies!

答:
You could match the parts of the key you want to work with via a regular expression:

const obj = {
  'repeater-group[1][titel]': 'test1',
  'repeater-group[1][description]': 'test1',
  'repeater-group[3][titel]': 'test2',
  'repeater-group[3][description]': 'test2',
  'repeater-group[5][titel]': 'test3',
  'repeater-group[5][description]': 'test3'
}

const out = {}

for (const key in obj) {
  const value = obj[key]

  const match = /repeater-group\[([0-9])\]\[([a-z]+)\]/.exec(key)
  const index = match[1]
  const property = match[2]

  out[index] = {...out[index], [property]: value}
}

console.log(out)

/*
{
  "1": {
    "titel": "test1",
    "description": "test1"
  },
  "3": {
    "titel": "test2",
    "description": "test2"
  },
  "5": {
    "titel": "test3",
    "description": "test3"
  }
}
*/

Object.keys(out).forEach(i => console.log(`${out[i].titel}, ${out[i].description}`))

/*
test1, test1
test2, test2
test3, test3
*/```

Body:
I am struggeling to parse the following object, which I am getting from an input-form field:

const obj = { 'repeater-group[1][titel]': 'test1',
  'repeater-group[1][description]': 'test1',
  'repeater-group[3][titel]': 'test2',
  'repeater-group[3][description]': 'test2',
  'repeater-group[5][titel]': 'test3',
  'repeater-group[5][description]': 'test3' }

const desc = 'undefined'
const titel = 'undefined'
let i = 0
for (const k in obj) {
    const item = obj[k]

    if (k === `repeater-group[${i}][titel]`) {
        titel = item
    }
    if (k === `repeater-group[${i}][description]`) {
        desc = item
    }
    if (titel != 'undefined' && desc != 'undefined') {
        try {
            console.log(titel + ", " + desc)
        }
        catch (error) {
            console.log(error)
        }
    }

    i += 1
}
// Currently there is no output

I would like to have the following output

//Expected output
// test1, test1
// test2, test2
// test3, test3

Any suggestions what is wrong with my code?

Is there even a shorter way to do this object parsing?

I highly appreciate your replies!


问:
Automate the boring stuff with Python: Comma Code
Currently working my way through this beginners book and have completed one of the practice projects 'Comma Code' which asks the user to construct a program which:

takes a list value as an argument and returns
  a string with all the items separated by a comma and a space, with and
  inserted before the last item. For example, passing the below spam list to
  the function would return 'apples, bananas, tofu, and cats'. But your function
  should be able to work with any list value passed to it.

```<code>spam = ['apples', 'bananas', 'tofu', 'cats']
</code>```

My solution to the problem (Which works perfectly fine):

```<code>spam= ['apples', 'bananas', 'tofu', 'cats']
def list_thing(list):
    new_string = ''
    for i in list:
        new_string = new_string + str(i)
        if list.index(i) == (len(list)-2):
            new_string = new_string + ', and '
        elif list.index(i) == (len(list)-1):
            new_string = new_string
        else:
            new_string = new_string + ', '
    return new_string

print (list_thing(spam))
</code>```

My only question, is there any way I can shorten my code? or make it more 'pythonic'?

Here is my code.

```<code>def listTostring(someList):
    a = ''
    for i in range(len(someList)-1):
        a += str(someList[i])
    a += str('and ' + someList[len(someList)-1])
    print (a)

spam = ['apples', 'bananas', 'tofu', 'cats']
listTostring(spam)
</code>```

output: apples, bananas, tofu, and cats

答:
Here's my solution.  Once I found the join method and how it worked, the rest followed.</p>

```<code>spam = ['apples', 'bananas', 'tofu', 'cats']

def commas(h):
    s = ', '
    print(s.join(spam[0:len(spam)-1]) + s + 'and ' + spam[len(spam)-1])

commas(spam)
</code>```

Body:
Currently working my way through this beginners book and have completed one of the practice projects 'Comma Code' which asks the user to construct a program which:

takes a list value as an argument and returns
  a string with all the items separated by a comma and a space, with and
  inserted before the last item. For example, passing the below spam list to
  the function would return 'apples, bananas, tofu, and cats'. But your function
  should be able to work with any list value passed to it.

spam = ['apples', 'bananas', 'tofu', 'cats']

My solution to the problem (Which works perfectly fine):

spam= ['apples', 'bananas', 'tofu', 'cats']
def list_thing(list):
    new_string = ''
    for i in list:
        new_string = new_string + str(i)
        if list.index(i) == (len(list)-2):
            new_string = new_string + ', and '
        elif list.index(i) == (len(list)-1):
            new_string = new_string
        else:
            new_string = new_string + ', '
    return new_string

print (list_thing(spam))

My only question, is there any way I can shorten my code? or make it more 'pythonic'?

Here is my code.

def listTostring(someList):
    a = ''
    for i in range(len(someList)-1):
        a += str(someList[i])
    a += str('and ' + someList[len(someList)-1])
    print (a)

spam = ['apples', 'bananas', 'tofu', 'cats']
listTostring(spam)

output: apples, bananas, tofu, and cats

Body:
Here's my solution.  Once I found the join method and how it worked, the rest followed.

spam = ['apples', 'bananas', 'tofu', 'cats']

def commas(h):
    s = ', '
    print(s.join(spam[0:len(spam)-1]) + s + 'and ' + spam[len(spam)-1])

commas(spam)


问:
How to fold (all types of) comments in netbeans?
Netbeans seems inconsistent with folding comments in my Java code. Sometimes I can fold the comments, and sometimes I cannot. Any help? Thank you.</p>

答:
I have functions with very long lines, I usually do this

```<code>// <editor-fold defaultstate="collapsed" desc="Description (Example Execute)">
 /**
 *
 * Execute the query
 *
 * Accepts an SQL string as input and returns a result object upon
 * successful execution of a "read" type query. Returns boolean TRUE
 * upon successful execution of a "write" type query. Returns boolean
 * FALSE upon failure, and if the $db_debug variable is set to TRUE
 * will raise an error.
 *
 * @param   string  $sql
 * @param   array   $binds = FALSE      An array of binding data
 * @param   bool    $return_object = NULL
 * @return  mixed
 */

 public function query($sql, $binds = FALSE, $return_object = NULL){
 /* exmample code here */
 }

 // </editor-fold>
</code>```

I hope that will be useful :))

ContentLicense: CC BY-SA 2.5

Body:
I have functions with very long lines, I usually do this

// <editor-fold defaultstate="collapsed" desc="Description (Example Execute)">
 /**
 *
 * Execute the query
 *
 * Accepts an SQL string as input and returns a result object upon
 * successful execution of a "read" type query. Returns boolean TRUE
 * upon successful execution of a "write" type query. Returns boolean
 * FALSE upon failure, and if the $db_debug variable is set to TRUE
 * will raise an error.
 *
 * @param   string  $sql
 * @param   array   $binds = FALSE      An array of binding data
 * @param   bool    $return_object = NULL
 * @return  mixed
 */

 public function query($sql, $binds = FALSE, $return_object = NULL){
 /* exmample code here */
 }

 // </editor-fold>

I hope that will be useful :))


问:
SpringBoot/JHipster rest api configuration,transtyping issue
i've got a problem with my SpringBoot rest api generated by Jhipster version 4.2.2 when i try to get one of my object in JsonFormat .

```<code>    Request URL
    http://localhost:3000/api/models
    Response Body
    [
      {
        "id": 1,
        "name": "lenet",
        "lossWeights": null,
        "loss": "categorical_crossentropy",
        "sampleWeightMode": null,
        "isInput": false,
        "isOutput": false,
        "optimizer": {
          "id": 1,
          "optimizerType": {
        "id": 5,
        "name": "SGD"
          }
        },
        "coordinates": {
          "id": 1,
          "xpos": 0,
          "ypos": 0
        },
        "containedModels": [],
        "succeededByModels": [],
        "succeededByLayers": [],
        "containedLayers": [
          {
        "id": 1,
        "name": "input",
        "isInput": true,
        "isOutput": false,
        "isIntermediate": false,
        "coordinates": {
          "id": 2,
          "xpos": 78.376953125,
          "ypos": 108.01763916015625
        },
        "succeededByLayers": null,
        "succeededByModels": null,
        "layerType": {
          "id": 43,
          "name": "InputLayer"
        }
          },
          {
        "id": 2,
        "name": "conv2d_1",
        "isInput": false,
        "isOutput": false,
        "isIntermediate": false,
        "coordinates": {
          "id": 3,
          "xpos": 341.5582275390625,
          "ypos": 102.59124755859375
        },
        "succeededByLayers": null,
        "succeededByModels": null,
        "layerType": {
          "id": 63,
          "name": "Conv2D"
        }
          },
          {
        "id": 3,
        "name": "activation_1",
        "isInput": false,
        "isOutput": false,
        "isIntermediate": false,
        "coordinates": {
          "id": 4,
          "xpos": 623.73193359375,
          "ypos": 99.8780517578125
        },
        "succeededByLayers": null,
        "succeededByModels": null,
        "layerType": {
          "id": 15,
          "name": "Activation"
        }
          },
          {
        "id": 4,
        "name": "max_pooling2d_1",
        "isInput": false,
        "isOutput": false,
        "isIntermediate": false,
        "coordinates": {
          "id": 5,
          "xpos": 941.17724609375,
          "ypos": 102.59124755859375
        },
        "succeededByLayers": null,
        "succeededByModels": null,
        "layerType": {
          "id": 70,
          "name": "MaxPooling2D"
        }
          },
          {
        "id": 5,
        "name": "conv2d_2",
        "isInput": false,
        "isOutput": false,
        "isIntermediate": false,
        "coordinates": {
          "id": 6,
          "xpos": 1253.1962890625,
          "ypos": 99.8780517578125
        },
        "succeededByLayers": null,
        "succeededByModels": null,
        "layerType": {
          "id": 63,
          "name": "Conv2D"
        }
          },
          {
        "id": 6,
        "name": "max_pooling2d_2",
        "isInput": false,
        "isOutput": false,
        "isIntermediate": false,
        "coordinates": {
          "id": 7,
          "xpos": 1540.2081298828125,
          "ypos": 99.8780517578125
        },
        "succeededByLayers": null,
        "succeededByModels": null,
        "layerType": {
          "id": 70,
          "name": "MaxPooling2D"
        }
          },
          {
        "id": 7,
        "name": "activation_2",
        "isInput": false,
        "isOutput": false,
        "isIntermediate": false,
        "coordinates": {
          "id": 8,
          "xpos": 1861.44921875,
          "ypos": 99.8780517578125
        },
        "succeededByLayers": null,
        "succeededByModels": null,
        "layerType": {
          "id": 15,
          "name": "Activation"
        }
          },
          {
        "id": 8,
        "name": "flatten_1",
        "isInput": false,
        "isOutput": false,
        "isIntermediate": false,
        "coordinates": {
          "id": 9,
          "xpos": 2151.32373046875,
          "ypos": 99.8780517578125
        },
        "succeededByLayers": null,
        "succeededByModels": null,
        "layerType": {
          "id": 54,
          "name": "Flatten"
        }
          },
          {
        "id": 9,
        "name": "dense_1",
        "isInput": false,
        "isOutput": false,
        "isIntermediate": false,
        "coordinates": {
          "id": 10,
          "xpos": 2505.89208984375,
          "ypos": 98.57888793945312
        },
        "succeededByLayers": null,
        "succeededByModels": null,
        "layerType": {
          "id": 6,
          "name": "Dense"
        }
          },
          {
        "id": 10,
        "name": "dropout_1",
        "isInput": false,
        "isOutput": false,
        "isIntermediate": false,
        "coordinates": {
          "id": 11,
          "xpos": 2828.763671875,
          "ypos": 99.8780517578125
        },
        "succeededByLayers": null,
        "succeededByModels": null,
        "layerType": {
          "id": 44,
          "name": "Dropout"
        }
          },
          {
        "id": 11,
        "name": "dense_2",
        "isInput": false,
        "isOutput": false,
        "isIntermediate": false,
        "coordinates": {
          "id": 12,
          "xpos": 3121.79052734375,
          "ypos": 99.8780517578125
        },
        "succeededByLayers": null,
        "succeededByModels": null,
        "layerType": {
          "id": 6,
          "name": "Dense"
        }
          },
          {
        "id": 12,
        "name": "dropout_2",
        "isInput": false,
        "isOutput": false,
        "isIntermediate": false,
        "coordinates": {
          "id": 13,
          "xpos": 3452.8017578125,
          "ypos": 99.8780517578125
        },
        "succeededByLayers": null,
        "succeededByModels": null,
        "layerType": {
          "id": 44,
          "name": "Dropout"
        }
          },
          {
        "id": 13,
        "name": "dense_3",
        "isInput": false,
        "isOutput": false,
        "isIntermediate": false,
        "coordinates": {
          "id": 14,
          "xpos": 3784.675048828125,
          "ypos": 99.8780517578125
        },
        "succeededByLayers": null,
        "succeededByModels": null,
        "layerType": {
          "id": 6,
          "name": "Dense"
        }
          }
        ],
        "modelConfiguration": {
          "id": 1,
          "name": "ModÃ¨le LeNet5",
          "creationDate": "2017-05-11T00:00:00+02:00",
          "saveURI": "./tests/scripts/sequential/models/model.json",
          "project": {
        "id": 1,
        "name": "LeNet5",
        "creationDate": "2017-10-22T00:00:00+02:00",
        "updateDate": "2017-10-23T00:00:00+02:00"
          }
        }
      }
    ]
</code>```

Like you can see above this represent my model . You can acces to the list of  layers inside  thanks to the field containdLayers and each layers have a field suceededBylayers which is not  suppose to be null in that case(for the id 2 )

```<code>        @GetMapping("/models/{id}")
        @Timed
        public ResponseEntity<Model> getModel(@PathVariable Long id) {
        log.debug("REST request to get Model : {}", id);
        Model model = modelRepository.findOneWithEagerRelationships(id);
        System.out.println("======================================================");
        // Layer layer = (Layer)model.getContainedLayers().toArray()[0];
        // System.out.println(((Layer)layer.getSucceededByLayers().toArray()[0]).getSucceededByLayers());
        System.out.println("=====================================================");
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(model));
        }
</code>```

This is the portion of java spring code that enable to get this kind of Json File. And when i uncomment the line where i transtype,i get this kind of Json File

```<code>      {
                  "id": 1,
                  "name": "lenet",
                  "lossWeights": null,
                  "loss": "categorical_crossentropy",
                  "sampleWeightMode": null,
                  "isInput": false,
                  "isOutput": false,
                  "optimizer": {
                    "id": 1,
                    "optimizerType": {
                      "id": 5,
                      "name": "SGD"
                    }
                  },
                  "coordinates": {
                    "id": 1,
                    "xpos": 0,
                    "ypos": 0
                  },
                  "containedModels": [],
                  "succeededByModels": [],
                  "succeededByLayers": [],
                  "containedLayers": [
                    {
                      "id": 1,
                      "name": "input",
                      "isInput": true,
                      "isOutput": false,
                      "isIntermediate": false,
                      "coordinates": {
                    "id": 2,
                    "xpos": 78.376953125,
                    "ypos": 108.01763916015625
                      },
                      "succeededByLayers": [
                    {
                      "id": 2,
                      "name": "conv2d_1",
                      "isInput": false,
                      "isOutput": false,
                      "isIntermediate": false,
                      "coordinates": {
                        "id": 3,
                        "xpos": 341.5582275390625,
                        "ypos": 102.59124755859375
                      },
                      "succeededByLayers": [
                        {
                          "id": 3,
                          "name": "activation_1",
                          "isInput": false,
                          "isOutput": false,
                          "isIntermediate": false,
                          "coordinates": {
                        "id": 4,
                        "xpos": 623.73193359375,
                        "ypos": 99.8780517578125
                          },
                          "succeededByLayers": null,
                          "succeededByModels": null,
                          "layerType": {
                        "id": 15,
                        "name": "Activation"
                          }
                        }
                      ],
                      "succeededByModels": null,
                      "layerType": {
                        "id": 63,
                        "name": "Conv2D"
                      }
                    }
                      ],
                      "succeededByModels": null,
                      "layerType": {
                    "id": 43,
                    "name": "InputLayer"
                      }
                    },
                    {
                      "id": 2,
                      "name": "conv2d_1",
                      "isInput": false,
                      "isOutput": false,
                      "isIntermediate": false,
                      "coordinates": {
                    "id": 3,
                    "xpos": 341.5582275390625,
                    "ypos": 102.59124755859375
                      },
                      "succeededByLayers": null,
                      "succeededByModels": null,
                      "layerType": {
                    "id": 63,
                    "name": "Conv2D"
                      }
                    },
                    {
                      "id": 3,
                      "name": "activation_1",
                      "isInput": false,
                      "isOutput": false,
                      "isIntermediate": false,
                      "coordinates": {
                    "id": 4,
                    "xpos": 623.73193359375,
                    "ypos": 99.8780517578125
                      },
                      "succeededByLayers": null,
                      "succeededByModels": null,
                      "layerType": {
                    "id": 15,
                    "name": "Activation"
                      }
                    },
                    {
                      "id": 4,
                      "name": "max_pooling2d_1",
                      "isInput": false,
                      "isOutput": false,
                      "isIntermediate": false,
                      "coordinates": {
                    "id": 5,
                    "xpos": 941.17724609375,
                    "ypos": 102.59124755859375
                      },
                      "succeededByLayers": null,
                      "succeededByModels": null,
                      "layerType": {
                    "id": 70,
                    "name": "MaxPooling2D"
                      }
                    },
                    {
                      "id": 5,
                      "name": "conv2d_2",
                      "isInput": false,
                      "isOutput": false,
                      "isIntermediate": false,
                      "coordinates": {
                    "id": 6,
                    "xpos": 1253.1962890625,
                    "ypos": 99.8780517578125
                      },
                      "succeededByLayers": null,
                      "succeededByModels": null,
                      "layerType": {
                    "id": 63,
                    "name": "Conv2D"
                      }
                    },
                    {
                      "id": 6,
                      "name": "max_pooling2d_2",
                      "isInput": false,
                      "isOutput": false,
                      "isIntermediate": false,
                      "coordinates": {
                    "id": 7,
                    "xpos": 1540.2081298828125,
                    "ypos": 99.8780517578125
                      },
                      "succeededByLayers": null,
                      "succeededByModels": null,
                      "layerType": {
                    "id": 70,
                    "name": "MaxPooling2D"
                      }
                    },
                    {
                      "id": 7,
                      "name": "activation_2",
                      "isInput": false,
                      "isOutput": false,
                      "isIntermediate": false,
                      "coordinates": {
                    "id": 8,
                    "xpos": 1861.44921875,
                    "ypos": 99.8780517578125
                      },
                      "succeededByLayers": null,
                      "succeededByModels": null,
                      "layerType": {
                    "id": 15,
                    "name": "Activation"
                      }
                    },
                    {
                      "id": 8,
                      "name": "flatten_1",
                      "isInput": false,
                      "isOutput": false,
                      "isIntermediate": false,
                      "coordinates": {
                    "id": 9,
                    "xpos": 2151.32373046875,
                    "ypos": 99.8780517578125
                      },
                      "succeededByLayers": null,
                      "succeededByModels": null,
                      "layerType": {
                    "id": 54,
                    "name": "Flatten"
                      }
                    },
                    {
                      "id": 9,
                      "name": "dense_1",
                      "isInput": false,
                      "isOutput": false,
                      "isIntermediate": false,
                      "coordinates": {
                    "id": 10,
                    "xpos": 2505.89208984375,
                    "ypos": 98.57888793945312
                      },
                      "succeededByLayers": null,
                      "succeededByModels": null,
                      "layerType": {
                    "id": 6,
                    "name": "Dense"
                      }
                    },
                    {
                      "id": 10,
                      "name": "dropout_1",
                      "isInput": false,
                      "isOutput": false,
                      "isIntermediate": false,
                      "coordinates": {
                    "id": 11,
                    "xpos": 2828.763671875,
                    "ypos": 99.8780517578125
                      },
                      "succeededByLayers": null,
                      "succeededByModels": null,
                      "layerType": {
                    "id": 44,
                    "name": "Dropout"
                      }
                    },
                    {
                      "id": 11,
                      "name": "dense_2",
                      "isInput": false,
                      "isOutput": false,
                      "isIntermediate": false,
                      "coordinates": {
                    "id": 12,
                    "xpos": 3121.79052734375,
                    "ypos": 99.8780517578125
                      },
                      "succeededByLayers": null,
                      "succeededByModels": null,
                      "layerType": {
                    "id": 6,
                    "name": "Dense"
                      }
                    },
                    {
                      "id": 12,
                      "name": "dropout_2",
                      "isInput": false,
                      "isOutput": false,
                      "isIntermediate": false,
                      "coordinates": {
                    "id": 13,
                    "xpos": 3452.8017578125,
                    "ypos": 99.8780517578125
                      },
                      "succeededByLayers": null,
                      "succeededByModels": null,
                      "layerType": {
                    "id": 44,
                    "name": "Dropout"
                      }
                    },
                    {
                      "id": 13,
                      "name": "dense_3",
                      "isInput": false,
                      "isOutput": false,
                      "isIntermediate": false,
                      "coordinates": {
                    "id": 14,
                    "xpos": 3784.675048828125,
                    "ypos": 99.8780517578125
                      },
                      "succeededByLayers": null,
                      "succeededByModels": null,
                      "layerType": {
                    "id": 6,
                    "name": "Dense"
                      }
                    }
                  ],
                  "modelConfiguration": {
                    "id": 1,
                    "name": "ModÃ¨le LeNet5",
                    "creationDate": "2017-05-11T00:00:00+02:00",
                    "saveURI": "./tests/scripts/sequential/models/model.json",
                    "project": {
                      "id": 1,
                      "name": "LeNet5",
                      "creationDate": "2017-10-22T00:00:00+02:00",
                      "updateDate": "2017-10-23T00:00:00+02:00"
                    }
                  }
                }
</code>```

Here the field is not null .How am i suppose to configure the api so i don't get a null field .I would also be  intrested about getting only an array of layer id instead of the actual next layers.
I don't know if i'm clear enough that's my first post .Don't hesitate to ask me more info.

答:
You been caught by lazy-loaded relationships in JPA. By default all relationships in JHipster are lazy-loaded which means that the related entities are not fetched unless you access them. This is why values are null unless you access them in your System.out.println call which makes Hibernate to fetch the related objects.

To solve this, you should modify your repository and use @EntityGraph, have a look at the Spring Data JPA doc: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.entity-graph

Body:
i've got a problem with my SpringBoot rest api generated by Jhipster version 4.2.2 when i try to get one of my object in JsonFormat .

    Request URL
    http://localhost:3000/api/models
    Response Body
    [
      {
        "id": 1,
        "name": "lenet",
        "lossWeights": null,
        "loss": "categorical_crossentropy",
        "sampleWeightMode": null,
        "isInput": false,
        "isOutput": false,
        "optimizer": {
          "id": 1,
          "optimizerType": {
        "id": 5,
        "name": "SGD"
          }
        },
        "coordinates": {
          "id": 1,
          "xpos": 0,
          "ypos": 0
        },
        "containedModels": [],
        "succeededByModels": [],
        "succeededByLayers": [],
        "containedLayers": [
          {
        "id": 1,
        "name": "input",
        "isInput": true,
        "isOutput": false,
        "isIntermediate": false,
        "coordinates": {
          "id": 2,
          "xpos": 78.376953125,
          "ypos": 108.01763916015625
        },
        "succeededByLayers": null,
        "succeededByModels": null,
        "layerType": {
          "id": 43,
          "name": "InputLayer"
        }
          },
          {
        "id": 2,
        "name": "conv2d_1",
        "isInput": false,
        "isOutput": false,
        "isIntermediate": false,
        "coordinates": {
          "id": 3,
          "xpos": 341.5582275390625,
          "ypos": 102.59124755859375
        },
        "succeededByLayers": null,
        "succeededByModels": null,
        "layerType": {
          "id": 63,
          "name": "Conv2D"
        }
          },
          {
        "id": 3,
        "name": "activation_1",
        "isInput": false,
        "isOutput": false,
        "isIntermediate": false,
        "coordinates": {
          "id": 4,
          "xpos": 623.73193359375,
          "ypos": 99.8780517578125
        },
        "succeededByLayers": null,
        "succeededByModels": null,
        "layerType": {
          "id": 15,
          "name": "Activation"
        }
          },
          {
        "id": 4,
        "name": "max_pooling2d_1",
        "isInput": false,
        "isOutput": false,
        "isIntermediate": false,
        "coordinates": {
          "id": 5,
          "xpos": 941.17724609375,
          "ypos": 102.59124755859375
        },
        "succeededByLayers": null,
        "succeededByModels": null,
        "layerType": {
          "id": 70,
          "name": "MaxPooling2D"
        }
          },
          {
        "id": 5,
        "name": "conv2d_2",
        "isInput": false,
        "isOutput": false,
        "isIntermediate": false,
        "coordinates": {
          "id": 6,
          "xpos": 1253.1962890625,
          "ypos": 99.8780517578125
        },
        "succeededByLayers": null,
        "succeededByModels": null,
        "layerType": {
          "id": 63,
          "name": "Conv2D"
        }
          },
          {
        "id": 6,
        "name": "max_pooling2d_2",
        "isInput": false,
        "isOutput": false,
        "isIntermediate": false,
        "coordinates": {
          "id": 7,
          "xpos": 1540.2081298828125,
          "ypos": 99.8780517578125
        },
        "succeededByLayers": null,
        "succeededByModels": null,
        "layerType": {
          "id": 70,
          "name": "MaxPooling2D"
        }
          },
          {
        "id": 7,
        "name": "activation_2",
        "isInput": false,
        "isOutput": false,
        "isIntermediate": false,
        "coordinates": {
          "id": 8,
          "xpos": 1861.44921875,
          "ypos": 99.8780517578125
        },
        "succeededByLayers": null,
        "succeededByModels": null,
        "layerType": {
          "id": 15,
          "name": "Activation"
        }
          },
          {
        "id": 8,
        "name": "flatten_1",
        "isInput": false,
        "isOutput": false,
        "isIntermediate": false,
        "coordinates": {
          "id": 9,
          "xpos": 2151.32373046875,
          "ypos": 99.8780517578125
        },
        "succeededByLayers": null,
        "succeededByModels": null,
        "layerType": {
          "id": 54,
          "name": "Flatten"
        }
          },
          {
        "id": 9,
        "name": "dense_1",
        "isInput": false,
        "isOutput": false,
        "isIntermediate": false,
        "coordinates": {
          "id": 10,
          "xpos": 2505.89208984375,
          "ypos": 98.57888793945312
        },
        "succeededByLayers": null,
        "succeededByModels": null,
        "layerType": {
          "id": 6,
          "name": "Dense"
        }
          },
          {
        "id": 10,
        "name": "dropout_1",
        "isInput": false,
        "isOutput": false,
        "isIntermediate": false,
        "coordinates": {
          "id": 11,
          "xpos": 2828.763671875,
          "ypos": 99.8780517578125
        },
        "succeededByLayers": null,
        "succeededByModels": null,
        "layerType": {
          "id": 44,
          "name": "Dropout"
        }
          },
          {
        "id": 11,
        "name": "dense_2",
        "isInput": false,
        "isOutput": false,
        "isIntermediate": false,
        "coordinates": {
          "id": 12,
          "xpos": 3121.79052734375,
          "ypos": 99.8780517578125
        },
        "succeededByLayers": null,
        "succeededByModels": null,
        "layerType": {
          "id": 6,
          "name": "Dense"
        }
          },
          {
        "id": 12,
        "name": "dropout_2",
        "isInput": false,
        "isOutput": false,
        "isIntermediate": false,
        "coordinates": {
          "id": 13,
          "xpos": 3452.8017578125,
          "ypos": 99.8780517578125
        },
        "succeededByLayers": null,
        "succeededByModels": null,
        "layerType": {
          "id": 44,
          "name": "Dropout"
        }
          },
          {
        "id": 13,
        "name": "dense_3",
        "isInput": false,
        "isOutput": false,
        "isIntermediate": false,
        "coordinates": {
          "id": 14,
          "xpos": 3784.675048828125,
          "ypos": 99.8780517578125
        },
        "succeededByLayers": null,
        "succeededByModels": null,
        "layerType": {
          "id": 6,
          "name": "Dense"
        }
          }
        ],
        "modelConfiguration": {
          "id": 1,
          "name": "ModÃ¨le LeNet5",
          "creationDate": "2017-05-11T00:00:00+02:00",
          "saveURI": "./tests/scripts/sequential/models/model.json",
          "project": {
        "id": 1,
        "name": "LeNet5",
        "creationDate": "2017-10-22T00:00:00+02:00",
        "updateDate": "2017-10-23T00:00:00+02:00"
          }
        }
      }
    ]

Like you can see above this represent my model . You can acces to the list of  layers inside  thanks to the field containdLayers and each layers have a field suceededBylayers which is not  suppose to be null in that case(for the id 2 )

        @GetMapping("/models/{id}")
        @Timed
        public ResponseEntity<Model> getModel(@PathVariable Long id) {
        log.debug("REST request to get Model : {}", id);
        Model model = modelRepository.findOneWithEagerRelationships(id);
        System.out.println("======================================================");
        // Layer layer = (Layer)model.getContainedLayers().toArray()[0];
        // System.out.println(((Layer)layer.getSucceededByLayers().toArray()[0]).getSucceededByLayers());
        System.out.println("=====================================================");
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(model));
        }

This is the portion of java spring code that enable to get this kind of Json File. And when i uncomment the line where i transtype,i get this kind of Json File

      {
                  "id": 1,
                  "name": "lenet",
                  "lossWeights": null,
                  "loss": "categorical_crossentropy",
                  "sampleWeightMode": null,
                  "isInput": false,
                  "isOutput": false,
                  "optimizer": {
                    "id": 1,
                    "optimizerType": {
                      "id": 5,
                      "name": "SGD"
                    }
                  },
                  "coordinates": {
                    "id": 1,
                    "xpos": 0,
                    "ypos": 0
                  },
                  "containedModels": [],
                  "succeededByModels": [],
                  "succeededByLayers": [],
                  "containedLayers": [
                    {
                      "id": 1,
                      "name": "input",
                      "isInput": true,
                      "isOutput": false,
                      "isIntermediate": false,
                      "coordinates": {
                    "id": 2,
                    "xpos": 78.376953125,
                    "ypos": 108.01763916015625
                      },
                      "succeededByLayers": [
                    {
                      "id": 2,
                      "name": "conv2d_1",
                      "isInput": false,
                      "isOutput": false,
                      "isIntermediate": false,
                      "coordinates": {
                        "id": 3,
                        "xpos": 341.5582275390625,
                        "ypos": 102.59124755859375
                      },
                      "succeededByLayers": [
                        {
                          "id": 3,
                          "name": "activation_1",
                          "isInput": false,
                          "isOutput": false,
                          "isIntermediate": false,
                          "coordinates": {
                        "id": 4,
                        "xpos": 623.73193359375,
                        "ypos": 99.8780517578125
                          },
                          "succeededByLayers": null,
                          "succeededByModels": null,
                          "layerType": {
                        "id": 15,
                        "name": "Activation"
                          }
                        }
                      ],
                      "succeededByModels": null,
                      "layerType": {
                        "id": 63,
                        "name": "Conv2D"
                      }
                    }
                      ],
                      "succeededByModels": null,
                      "layerType": {
                    "id": 43,
                    "name": "InputLayer"
                      }
                    },
                    {
                      "id": 2,
                      "name": "conv2d_1",
                      "isInput": false,
                      "isOutput": false,
                      "isIntermediate": false,
                      "coordinates": {
                    "id": 3,
                    "xpos": 341.5582275390625,
                    "ypos": 102.59124755859375
                      },
                      "succeededByLayers": null,
                      "succeededByModels": null,
                      "layerType": {
                    "id": 63,
                    "name": "Conv2D"
                      }
                    },
                    {
                      "id": 3,
                      "name": "activation_1",
                      "isInput": false,
                      "isOutput": false,
                      "isIntermediate": false,
                      "coordinates": {
                    "id": 4,
                    "xpos": 623.73193359375,
                    "ypos": 99.8780517578125
                      },
                      "succeededByLayers": null,
                      "succeededByModels": null,
                      "layerType": {
                    "id": 15,
                    "name": "Activation"
                      }
                    },
                    {
                      "id": 4,
                      "name": "max_pooling2d_1",
                      "isInput": false,
                      "isOutput": false,
                      "isIntermediate": false,
                      "coordinates": {
                    "id": 5,
                    "xpos": 941.17724609375,
                    "ypos": 102.59124755859375
                      },
                      "succeededByLayers": null,
                      "succeededByModels": null,
                      "layerType": {
                    "id": 70,
                    "name": "MaxPooling2D"
                      }
                    },
                    {
                      "id": 5,
                      "name": "conv2d_2",
                      "isInput": false,
                      "isOutput": false,
                      "isIntermediate": false,
                      "coordinates": {
                    "id": 6,
                    "xpos": 1253.1962890625,
                    "ypos": 99.8780517578125
                      },
                      "succeededByLayers": null,
                      "succeededByModels": null,
                      "layerType": {
                    "id": 63,
                    "name": "Conv2D"
                      }
                    },
                    {
                      "id": 6,
                      "name": "max_pooling2d_2",
                      "isInput": false,
                      "isOutput": false,
                      "isIntermediate": false,
                      "coordinates": {
                    "id": 7,
                    "xpos": 1540.2081298828125,
                    "ypos": 99.8780517578125
                      },
                      "succeededByLayers": null,
                      "succeededByModels": null,
                      "layerType": {
                    "id": 70,
                    "name": "MaxPooling2D"
                      }
                    },
                    {
                      "id": 7,
                      "name": "activation_2",
                      "isInput": false,
                      "isOutput": false,
                      "isIntermediate": false,
                      "coordinates": {
                    "id": 8,
                    "xpos": 1861.44921875,
                    "ypos": 99.8780517578125
                      },
                      "succeededByLayers": null,
                      "succeededByModels": null,
                      "layerType": {
                    "id": 15,
                    "name": "Activation"
                      }
                    },
                    {
                      "id": 8,
                      "name": "flatten_1",
                      "isInput": false,
                      "isOutput": false,
                      "isIntermediate": false,
                      "coordinates": {
                    "id": 9,
                    "xpos": 2151.32373046875,
                    "ypos": 99.8780517578125
                      },
                      "succeededByLayers": null,
                      "succeededByModels": null,
                      "layerType": {
                    "id": 54,
                    "name": "Flatten"
                      }
                    },
                    {
                      "id": 9,
                      "name": "dense_1",
                      "isInput": false,
                      "isOutput": false,
                      "isIntermediate": false,
                      "coordinates": {
                    "id": 10,
                    "xpos": 2505.89208984375,
                    "ypos": 98.57888793945312
                      },
                      "succeededByLayers": null,
                      "succeededByModels": null,
                      "layerType": {
                    "id": 6,
                    "name": "Dense"
                      }
                    },
                    {
                      "id": 10,
                      "name": "dropout_1",
                      "isInput": false,
                      "isOutput": false,
                      "isIntermediate": false,
                      "coordinates": {
                    "id": 11,
                    "xpos": 2828.763671875,
                    "ypos": 99.8780517578125
                      },
                      "succeededByLayers": null,
                      "succeededByModels": null,
                      "layerType": {
                    "id": 44,
                    "name": "Dropout"
                      }
                    },
                    {
                      "id": 11,
                      "name": "dense_2",
                      "isInput": false,
                      "isOutput": false,
                      "isIntermediate": false,
                      "coordinates": {
                    "id": 12,
                    "xpos": 3121.79052734375,
                    "ypos": 99.8780517578125
                      },
                      "succeededByLayers": null,
                      "succeededByModels": null,
                      "layerType": {
                    "id": 6,
                    "name": "Dense"
                      }
                    },
                    {
                      "id": 12,
                      "name": "dropout_2",
                      "isInput": false,
                      "isOutput": false,
                      "isIntermediate": false,
                      "coordinates": {
                    "id": 13,
                    "xpos": 3452.8017578125,
                    "ypos": 99.8780517578125
                      },
                      "succeededByLayers": null,
                      "succeededByModels": null,
                      "layerType": {
                    "id": 44,
                    "name": "Dropout"
                      }
                    },
                    {
                      "id": 13,
                      "name": "dense_3",
                      "isInput": false,
                      "isOutput": false,
                      "isIntermediate": false,
                      "coordinates": {
                    "id": 14,
                    "xpos": 3784.675048828125,
                    "ypos": 99.8780517578125
                      },
                      "succeededByLayers": null,
                      "succeededByModels": null,
                      "layerType": {
                    "id": 6,
                    "name": "Dense"
                      }
                    }
                  ],
                  "modelConfiguration": {
                    "id": 1,
                    "name": "ModÃ¨le LeNet5",
                    "creationDate": "2017-05-11T00:00:00+02:00",
                    "saveURI": "./tests/scripts/sequential/models/model.json",
                    "project": {
                      "id": 1,
                      "name": "LeNet5",
                      "creationDate": "2017-10-22T00:00:00+02:00",
                      "updateDate": "2017-10-23T00:00:00+02:00"
                    }
                  }
                }

Here the field is not null .How am i suppose to configure the api so i don't get a null field .I would also be  intrested about getting only an array of layer id instead of the actual next layers.
I don't know if i'm clear enough that's my first post .Don't hesitate to ask me more info.


问:
Matrix in C: is that functions share local variables?
I defined as a global variable in int main() a matrix a[][], i didn't initialised the variable.

Then I used some function:

The first one: receives as argument the matrix a and then defines a[i][j] as a certain value (random), this for all i and j in the appropriate range. The function simply returns 1;

The second one: receives as argument the matrix a and simply prints it. Also this function simply returns 1;

The last one: receives as argument the matrix a and then determines the maximum of its values and return that values

I thought, naively, that writing plainly the code without defining some pointer to the matrix, to make the variable of the matrix global and sharable from all the functions, the code simply wouldn't have worked. But it worked.
I thought that it wouldn't have worked because i didn't defined the matrix in a global way, but it is defined only in a function and then (to me:)pretends to pass to the other functions.

So my question is: why it worked?

The code:

```<code>int matrix_definition(int a[][], int dim);
int matrix_print(int a[][], int dim);
int max_matrix(int a[][],int dim);

int main()
{
  int a[][], dim;

  matrix_definition(a,dim);
  matrix_print(a,dim);

  printf("%d", max_matrix(a,dim));
  return 0;
}
</code>```

The full code including main() and  matrix_definition is this:

```<code>#include<stdio.h>

#define SIZE 100

    int matrix_definition(int a[SIZE][SIZE], int dim);
    int matrix_print(int a[SIZE][SIZE], int dim);
    int max_matrix(int a[SIZE][SIZE],int dim);

    int main()
    {
      int a[SIZE][SIZE], dim;

      matrix_definition(a,dim);
      matrix_print(a,dim);

      printf("%d", max_matrix(a,dim));
      return 0;
    }

int matrix_definition(int a[SIZE][SIZE],int dim)
{
 int i,j;
srand(time(NULL));

for(i=0;i<dim;i++)
    {
        for(j=0;j<dim;j++)
            {
                a[i][j]=rand()%2;
            }
    }
return 1;
    }
</code>```

答:
The updated code you posted is very different from what you originally posted.   Yes, that code is valid with regard to how a is defined and how it is passed to various functions.

In each of your function declarations you declare a parameter:

```<code>int a[SIZE][SIZE]
</code>```

Since arrays as parameters are converted to pointers, this is equivalent to:

```<code>int (*a)[SIZE]
</code>```

This is compatible with the variable defined in main:

```<code>int a[SIZE][SIZE];
</code>```

When passing an array to a function, it decays to a pointer to the first element.  So this function call:

```<code>matrix_definition(a,dim);
</code>```

is the same as:

```<code>matrix_definition(&a[0],dim);
</code>```

The expression a[0] has type int [SIZE], so the expression &a[0] has type int (*)[SIZE].  This is the same as the function's parameter.

Body:
I defined as a global variable in int main() a matrix a[][], i didn't initialised the variable.

Then I used some function:

The first one: receives as argument the matrix a and then defines a[i][j] as a certain value (random), this for all i and j in the appropriate range. The function simply returns 1;

The second one: receives as argument the matrix a and simply prints it. Also this function simply returns 1;

The last one: receives as argument the matrix a and then determines the maximum of its values and return that values

I thought, naively, that writing plainly the code without defining some pointer to the matrix, to make the variable of the matrix global and sharable from all the functions, the code simply wouldn't have worked. But it worked.
I thought that it wouldn't have worked because i didn't defined the matrix in a global way, but it is defined only in a function and then (to me:)pretends to pass to the other functions.

So my question is: why it worked?

The code:

int matrix_definition(int a[][], int dim);
int matrix_print(int a[][], int dim);
int max_matrix(int a[][],int dim);

int main()
{
  int a[][], dim;

  matrix_definition(a,dim);
  matrix_print(a,dim);

  printf("%d", max_matrix(a,dim));
  return 0;
}

The full code including main() and  matrix_definition is this:

#include<stdio.h>

#define SIZE 100

    int matrix_definition(int a[SIZE][SIZE], int dim);
    int matrix_print(int a[SIZE][SIZE], int dim);
    int max_matrix(int a[SIZE][SIZE],int dim);

    int main()
    {
      int a[SIZE][SIZE], dim;

      matrix_definition(a,dim);
      matrix_print(a,dim);

      printf("%d", max_matrix(a,dim));
      return 0;
    }

int matrix_definition(int a[SIZE][SIZE],int dim)
{
 int i,j;
srand(time(NULL));

for(i=0;i<dim;i++)
    {
        for(j=0;j<dim;j++)
            {
                a[i][j]=rand()%2;
            }
    }
return 1;
    }

Body:
The updated code you posted is very different from what you originally posted.   Yes, that code is valid with regard to how a is defined and how it is passed to various functions.

In each of your function declarations you declare a parameter:

int a[SIZE][SIZE]

Since arrays as parameters are converted to pointers, this is equivalent to:

int (*a)[SIZE]

This is compatible with the variable defined in main:

int a[SIZE][SIZE];

When passing an array to a function, it decays to a pointer to the first element.  So this function call:

matrix_definition(a,dim);

is the same as:

matrix_definition(&a[0],dim);

The expression a[0] has type int [SIZE], so the expression &a[0] has type int (*)[SIZE].  This is the same as the function's parameter.


问:
R - Match based on minimum difference between column in data.frame
I have the following two dataframes:

```<code>df1 <- data.frame(Subject=c("S1","S1","S2","S2","S2","S3","S3"),
       SampleTime=c(1,2,1,2.1,3,0.9,2), Value=c(3,4,3,2,2,4,5))

df2 <- data.frame(Subject=c("S1","S1","S1","S2","S2","S2","S2","S3","S3"),
       SampleTime=c(0.99, 2.01,2.99, 0,1.01,2,3,1.2,2.02), Conc=c(4.7,5.2,8,5,2,1,3,4,6))
</code>```

My goal is to add the column df2$Conc to df1 where the difference between SampleTime in df1 and df2 is smallest per subject. In addition, I would like to add a column that shows the difference between SampleTime.

Desired output:

```<code>output <- data.frame(Subject=c("S1","S1","S2","S2","S2","S3","S3"),
                     SampleTime=c(1,2,1,2.1,3,0.9,2), Value=c(3,4,3,2,2,4,5),
                     SampleTime_df2=c(0.99,2.01,1.01,2,3,1.20,2.02), Conc=c(4.7,5.2,2,1,3,4,6))
</code>```

So far, I'm able to it per subject, like this for Subject S2:

```<code>     Indices <- sapply(df1$SampleTime[df1$Subject=="S2"], FUN=function(x,y) which.min(abs(y - x)), y=df2$SampleTime[df2$Subject=="S2"])
     df1$SampleTime_df2[df1$Subject=="S2"] <- df2$SampleTime[df2$Subject=="S2"][Indices]
     df1$Conc[df1$Subject=="S2"] <- df2$Conc[df2$Subject=="S2"][Indices]
</code>```

The code doesn't look very nice and I would like to do it for all subjects at once. In my real data, there aren't any ties (i.e. two sample times in df2 that are equally closest to one sample time in df1), but let's say that in that case I would like to keep the first.

I hope my question is clear. Thank you for your help!

答:
Would it work in general to merge dataframes (inner join) on Subject and  new columns filled with round(SampleTime)? This approach would work with the toy data that you supplied, i.e.</p>

```<code>df1$SampleTimeInt <- round(df1$SampleTime)
df2$SampleTimeInt <- round(df2$SampleTime)
combined <- merge(df1, df2, by=c("Subject", "SampleTimeInt"))
</code>```

Body:
I have the following two dataframes:

df1 <- data.frame(Subject=c("S1","S1","S2","S2","S2","S3","S3"),
       SampleTime=c(1,2,1,2.1,3,0.9,2), Value=c(3,4,3,2,2,4,5))

df2 <- data.frame(Subject=c("S1","S1","S1","S2","S2","S2","S2","S3","S3"),
       SampleTime=c(0.99, 2.01,2.99, 0,1.01,2,3,1.2,2.02), Conc=c(4.7,5.2,8,5,2,1,3,4,6))

My goal is to add the column df2$Conc to df1 where the difference between SampleTime in df1 and df2 is smallest per subject. In addition, I would like to add a column that shows the difference between SampleTime.

Desired output:

output <- data.frame(Subject=c("S1","S1","S2","S2","S2","S3","S3"),
                     SampleTime=c(1,2,1,2.1,3,0.9,2), Value=c(3,4,3,2,2,4,5),
                     SampleTime_df2=c(0.99,2.01,1.01,2,3,1.20,2.02), Conc=c(4.7,5.2,2,1,3,4,6))

So far, I'm able to it per subject, like this for Subject S2:

     Indices <- sapply(df1$SampleTime[df1$Subject=="S2"], FUN=function(x,y) which.min(abs(y - x)), y=df2$SampleTime[df2$Subject=="S2"])
     df1$SampleTime_df2[df1$Subject=="S2"] <- df2$SampleTime[df2$Subject=="S2"][Indices]
     df1$Conc[df1$Subject=="S2"] <- df2$Conc[df2$Subject=="S2"][Indices]

The code doesn't look very nice and I would like to do it for all subjects at once. In my real data, there aren't any ties (i.e. two sample times in df2 that are equally closest to one sample time in df1), but let's say that in that case I would like to keep the first.

I hope my question is clear. Thank you for your help!

Body:
Would it work in general to merge dataframes (inner join) on Subject and  new columns filled with round(SampleTime)? This approach would work with the toy data that you supplied, i.e.

df1$SampleTimeInt <- round(df1$SampleTime)
df2$SampleTimeInt <- round(df2$SampleTime)
combined <- merge(df1, df2, by=c("Subject", "SampleTimeInt"))


问:
exec("dir") produces Exception: Working Directory:null Environment:null
I Write simple application on AndroidStudio, run my it on a Galaxy Device.
when I am trying to execute the linux id command, like so -

```<code>Process proc = Runtime.getRuntime().exec("id");
</code>```

It works fine. But most other Linux commands, including dir,
produces

```<code>Exception: Working Directory:null Environment:null.
</code>```

I added those permissions to the AndroidManifest.xml:

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
</code>```

Do I miss permissions, or do I have to initialize some environment variables?
this is the method from mainActivity.java:

```<code>public void onButtonClick(View v) {
    TextView dataTextView = (TextView) findViewById(R.id.dataTextView);
    String st = "", st1 = "";
    try {
        Process proc = Runtime.getRuntime().exec("id");
        BufferedReader br = new BufferedReader(
                new InputStreamReader(proc.getInputStream()));
        while ((st1 = br.readLine()) != null) {
            st = "\r\nline: " + st1 + "\r\n";
            dataTextView.setText(st);
            System.out.println(st);
        }
        proc.waitFor();
        System.out.println("exit: " + proc.exitValue());
        dataTextView.setText(st + "exit: " + proc.exitValue());
        proc.destroy();
    }
    catch (Exception e) {
        if (e != null) {
            System.out.println("Exception: " + e.toString());
            dataTextView.setText("Exception: " + e.toString());
        }
    }
}
</code>```

答: Android has a very limited amount of Linux commands natively, use ls instead of dir. </p>

Body:
I Write simple application on AndroidStudio, run my it on a Galaxy Device.
when I am trying to execute the linux id command, like so -

Process proc = Runtime.getRuntime().exec("id");

It works fine. But most other Linux commands, including dir,
produces

Exception: Working Directory:null Environment:null.

I added those permissions to the AndroidManifest.xml:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />

Do I miss permissions, or do I have to initialize some environment variables?
this is the method from mainActivity.java:

public void onButtonClick(View v) {
    TextView dataTextView = (TextView) findViewById(R.id.dataTextView);
    String st = "", st1 = "";
    try {
        Process proc = Runtime.getRuntime().exec("id");
        BufferedReader br = new BufferedReader(
                new InputStreamReader(proc.getInputStream()));
        while ((st1 = br.readLine()) != null) {
            st = "\r\nline: " + st1 + "\r\n";
            dataTextView.setText(st);
            System.out.println(st);
        }
        proc.waitFor();
        System.out.println("exit: " + proc.exitValue());
        dataTextView.setText(st + "exit: " + proc.exitValue());
        proc.destroy();
    }
    catch (Exception e) {
        if (e != null) {
            System.out.println("Exception: " + e.toString());
            dataTextView.setText("Exception: " + e.toString());
        }
    }
}


问:
SQL Parameterized Query with DecryptByKey in WHERE clause (VB.Net front end)
I am using VB.Net to communicate with my SQL Server back end where I just added a Symmetric Key encrypted column.

When I do queries on this table without the DecryptByKey and therefore no opening/closing of the Key, it works fine.  Once I add it to the WHERE clause it bombs although my thought is that's probably related to the opening/closing of the Key.  Here's some code to look at...

VB.Net code that calls SQL Server

```<code>Dim _cn As New SqlClient.SqlConnection
Dim _dataset As New DataSet
Dim _dataapt As New SqlClient.SqlDataAdapter
Dim _command As New SqlClient.SqlCommand

_cn.ConnectionString = "fake connection string"
_cn.Open()

_command.CommandText = _SQL

If Not _parameters Is Nothing Then
    For _x As Integer = 0 To _parameters.Count - 1
        _command.Parameters.Add(_parameters(_x)._parameter, _parameters(_x)._type).Value = _parameters(_x)._value
        // _parameter = "@unencryptedValue", _type = SQLDbType.VarChar, _value = "12345"
    Next
End If

_command.CommandTimeout = 600
_command.Connection = _cn

If _cn.State = ConnectionState.Closed Then
    _cn.Open()
End If

_dataapt.SelectCommand = _command
_dataapt.Fill(_dataset)

_dataapt.Dispose()
_command.Dispose()
_cn.Close()
_cn.Dispose()
</code>```

SQL code being sent

```<code>OPEN SYMMETRIC KEY TestKey
DECRYPTION BY CERTIFICATE TestCertificate;
GO
SELECT 1
FROM TestTable
WHERE CONVERT(varchar, DecryptByKey(encryptedField)) = @unencryptedValue
CLOSE SYMMETRIC KEY TestKey;
GO
</code>```

If it wasn't noticeable above, @unencryptedValue is a varchar(50) with a value of "12345"

I get 2 errors back, both saying System.Data.SqlClient.SqlException: Incorrect syntax near 'GO'

When I run this query directly in an SSMS query window it works fine.

I know that GO has to be on it's own line so when I create the string that goes into _SQL I put ChrW(13) & ChrW(10) before and after it each time.

Also, I know doing DecryptByKey in the WHERE is slow and probably not a good idea, but the table will stay small so it shouldn't be an issue.

答:
GO is not part of the SQL language. It's a batch separator used by tools like Management Studio, but it's not something that's understood by Sql Server itself.

Instead, you can separate individual statements with a semi-colon (or often even with just a line break), and separate batches by sending separate calls to the database (distinct ExecuteNonQuery/ExecuteScalar/ExecuteDataReader/Fill function calls).

Body:
I am using VB.Net to communicate with my SQL Server back end where I just added a Symmetric Key encrypted column.

When I do queries on this table without the DecryptByKey and therefore no opening/closing of the Key, it works fine.  Once I add it to the WHERE clause it bombs although my thought is that's probably related to the opening/closing of the Key.  Here's some code to look at...

VB.Net code that calls SQL Server

Dim _cn As New SqlClient.SqlConnection
Dim _dataset As New DataSet
Dim _dataapt As New SqlClient.SqlDataAdapter
Dim _command As New SqlClient.SqlCommand

_cn.ConnectionString = "fake connection string"
_cn.Open()

_command.CommandText = _SQL

If Not _parameters Is Nothing Then
    For _x As Integer = 0 To _parameters.Count - 1
        _command.Parameters.Add(_parameters(_x)._parameter, _parameters(_x)._type).Value = _parameters(_x)._value
        // _parameter = "@unencryptedValue", _type = SQLDbType.VarChar, _value = "12345"
    Next
End If

_command.CommandTimeout = 600
_command.Connection = _cn

If _cn.State = ConnectionState.Closed Then
    _cn.Open()
End If

_dataapt.SelectCommand = _command
_dataapt.Fill(_dataset)

_dataapt.Dispose()
_command.Dispose()
_cn.Close()
_cn.Dispose()

SQL code being sent

OPEN SYMMETRIC KEY TestKey
DECRYPTION BY CERTIFICATE TestCertificate;
GO
SELECT 1
FROM TestTable
WHERE CONVERT(varchar, DecryptByKey(encryptedField)) = @unencryptedValue
CLOSE SYMMETRIC KEY TestKey;
GO

If it wasn't noticeable above, @unencryptedValue is a varchar(50) with a value of "12345"

I get 2 errors back, both saying System.Data.SqlClient.SqlException: Incorrect syntax near 'GO'

When I run this query directly in an SSMS query window it works fine.

I know that GO has to be on it's own line so when I create the string that goes into _SQL I put ChrW(13) & ChrW(10) before and after it each time.

Also, I know doing DecryptByKey in the WHERE is slow and probably not a good idea, but the table will stay small so it shouldn't be an issue.


问:
Passing props as unknown attributes to an element in React
Right now I'm working on an Input component which will represent a form input field. I want it to be universal (like for text, date and numbers). The problem so far is that I don't know how to pass unknown attributes directly to my input element Here's the code:

```<code>import React, { Component } from 'react'
import PropTypes from 'prop-types'

class Input extends Component {
    render () {
      let required = false
      if (this.props.required) {
        required = true
      }
      return (
        <div className='form-group'>
          <label>{ this.props.label }</label>
          <input
            type={this.props.type}
            name={this.props.name}
            value={this.props.value}
            placeholder={this.props.placeholder}
            className={this.props.className}
            onChange={this.props.handleChange}
            {this.props.attrs}  // error here
            required = {required}
          />
        </div>
      )
    }
}

Input.propTypes = {
  attrs: PropTypes.string,
  label: PropTypes.string.isRequired,
  type: PropTypes.string.isRequired,
  name: PropTypes.string.isRequired,
  value: PropTypes.string.isRequired,
  placeholder: PropTypes.string,
  className: PropTypes.string,
  handleChange: PropTypes.func.isRequired,
  required: PropTypes.bool
}

Input.defaultProps = {
  type: 'text',
  required: true
}

export default Input
</code>```

React rejects this.props.attrs when I insert it directly into the input element and I don't know what to do...

Why do I even need this.props.attrs?

I don't know what input type I may want to use in the future. Let's say I want to have a number input. In this case in this.props.attrs I could store min = '1' max = '100' string.

So when I pass this.props.attrs to a component I want to get an input like the following:

```<code><input ... min = '1' max = '100' ... />
</code>```

答:
Couple of things to mention here:

You need to spread rest of attributes

Set attr as object on PropTypes

If you want to make some props required then this implementation is fine but if you don't then you can eliminate PropTypes restriction and refactor the component to get only

{label, ...rest} = this.props;

let { PropTypes, Component } = React;

class Input extends Component {
 render () {
    let { required, label, handleChange, ...restOfattrs } = this.props;
    required = required ? required : false;

      return (

          {label}
          <input
          onChange={handleChange}
          {...restOfattrs}
          required={required} />

      )
    }
}

Input.propTypes = {
  attrs: PropTypes.object,
  label: PropTypes.string.isRequired,
  type: PropTypes.string.isRequired,
  name: PropTypes.string.isRequired,
  value: PropTypes.string.isRequired,
  placeholder: PropTypes.string,
  className: PropTypes.string,
  handleChange: PropTypes.func.isRequired,
  required: PropTypes.bool
}

Input.defaultProps = {
  type: 'text',
  required: true
}

ReactDOM.render(
  <Input label="Type password : " className="input" type="password" placeholder="Type Password" handleChange={() => console.log('change...')}  maxLength={4} />,
  document.getElementById("root")
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.input{
    border: 1px solid #a1a1a1;
    padding: 10px 40px;
    background: #e7e7e7;
    width: 100px;
    border-radius: 5px;
}</code>```

```

Body:
Right now I'm working on an Input component which will represent a form input field. I want it to be universal (like for text, date and numbers). The problem so far is that I don't know how to pass unknown attributes directly to my input element Here's the code:

import React, { Component } from 'react'
import PropTypes from 'prop-types'

class Input extends Component {
    render () {
      let required = false
      if (this.props.required) {
        required = true
      }
      return (

          { this.props.label }
          <input
            type={this.props.type}
            name={this.props.name}
            value={this.props.value}
            placeholder={this.props.placeholder}
            className={this.props.className}
            onChange={this.props.handleChange}
            {this.props.attrs}  // error here
            required = {required}
          />

      )
    }
}

Input.propTypes = {
  attrs: PropTypes.string,
  label: PropTypes.string.isRequired,
  type: PropTypes.string.isRequired,
  name: PropTypes.string.isRequired,
  value: PropTypes.string.isRequired,
  placeholder: PropTypes.string,
  className: PropTypes.string,
  handleChange: PropTypes.func.isRequired,
  required: PropTypes.bool
}

Input.defaultProps = {
  type: 'text',
  required: true
}

export default Input

React rejects this.props.attrs when I insert it directly into the input element and I don't know what to do...

Why do I even need this.props.attrs?

I don't know what input type I may want to use in the future. Let's say I want to have a number input. In this case in this.props.attrs I could store min = '1' max = '100' string.

So when I pass this.props.attrs to a component I want to get an input like the following:

<input ... min = '1' max = '100' ... />

Body:
Couple of things to mention here:

You need to spread rest of attributes

Set attr as object on PropTypes

If you want to make some props required then this implementation is fine but if you don't then you can eliminate PropTypes restriction and refactor the component to get only

{label, ...rest} = this.props;

let { PropTypes, Component } = React;

class Input extends Component {
 render () {
    let { required, label, handleChange, ...restOfattrs } = this.props;
    required = required ? required : false;

      return (
        <div className='form-group'>
          <label>{label}</label>
          <input
          onChange={handleChange}
          {...restOfattrs}
          required={required} />
        </div>
      )
    }
}

Input.propTypes = {
  attrs: PropTypes.object,
  label: PropTypes.string.isRequired,
  type: PropTypes.string.isRequired,
  name: PropTypes.string.isRequired,
  value: PropTypes.string.isRequired,
  placeholder: PropTypes.string,
  className: PropTypes.string,
  handleChange: PropTypes.func.isRequired,
  required: PropTypes.bool
}

Input.defaultProps = {
  type: 'text',
  required: true
}

ReactDOM.render(
  <Input label="Type password : " className="input" type="password" placeholder="Type Password" handleChange={() => console.log('change...')}  maxLength={4} />,
  document.getElementById("root")
);

.input{
    border: 1px solid #a1a1a1;
    padding: 10px 40px;
    background: #e7e7e7;
    width: 100px;
    border-radius: 5px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"> </div>


问:
Java - Stream - Collect every N elements
I am trying to learn java - stream. I am able to do simple iteration / filter / map / collection etc.

When I was kind of trying to collect every 3 elements and print as shown here in this example, [collect every 3 elements and print and so on...]

```<code>    List<String> list = Arrays.asList("a","b","c","d","e","f","g","h","i","j");

    int count=0;
    String append="";
    for(String l: list){
        if(count>2){
            System.out.println(append);
            System.out.println("-------------------");
            append="";
            count=0;
        }
        append = append + l;
        count++;
    }
    System.out.println(append);
</code>```

output:

```<code>abc
-------------------
def
-------------------
ghi
-------------------
j
</code>```

I am not getting any clue how to do this using stream. Should i implement my own collector to achieve this?

答:
I think the bets approach is using an amazing library StreamEx of Tagir Valeev. The solution fits in one line ))</p>

```<code>StreamEx.ofSubLists(list, 3).toList();
</code>```

Body:
I am trying to learn java - stream. I am able to do simple iteration / filter / map / collection etc.

When I was kind of trying to collect every 3 elements and print as shown here in this example, [collect every 3 elements and print and so on...]

    List<String> list = Arrays.asList("a","b","c","d","e","f","g","h","i","j");

    int count=0;
    String append="";
    for(String l: list){
        if(count>2){
            System.out.println(append);
            System.out.println("-------------------");
            append="";
            count=0;
        }
        append = append + l;
        count++;
    }
    System.out.println(append);

output:

abc
-------------------
def
-------------------
ghi
-------------------
j

I am not getting any clue how to do this using stream. Should i implement my own collector to achieve this?

Body:
I think the bets approach is using an amazing library StreamEx of Tagir Valeev. The solution fits in one line ))

StreamEx.ofSubLists(list, 3).toList();


问:
Complex query containing array tasks with number position in array in MongoDB
I need to know, can I make complex query which will return me result with array board but only with parameters Object inside :

board.name

_id

array with  (lists.list and index position in array)

length cards in array

I'm weak in mongodb so I ask if it is possible to do so, because I have order and I do not know whether to do it in the query or on the loop in the angularjs

Here is from db result with query db.getCollection('boards').find({}) (2results)

```<code>    /* 1 */
{
    "_id" : ObjectId("5a0b5c6da0502e2174fd849f"),
    "name" : "example 1",
    "users" : [
        ObjectId("59cd114cea98d9326ca1c421")
    ],
    "lists" : [
        {
            "list" : "example",
            "_id" : ObjectId("5a0b5c7ba0502e2174fd84ae"),
            "cards" : [
                {
                    "name" : "1",
                    "_id" : ObjectId("5a0b5c80a0502e2174fd84b4")
                },
                {
                    "name" : "2",
                    "_id" : ObjectId("5a0b5c80a0502e2174fd84b3")
                },
                {
                    "name" : "3",
                    "_id" : ObjectId("5a0b5c80a0502e2174fd84b2")
                }
            ]
        },
        {
            "list" : "example 1",
            "_id" : ObjectId("5a0b5c7ba0502e2174fd84ad"),
            "cards" : [
                {
                    "name" : "1",
                    "_id" : ObjectId("5a0b5c83a0502e2174fd84b5")
                }
            ]
        },
        {
            "list" : "example",
            "_id" : ObjectId("5a0b5c7ba0502e2174fd84ac"),
            "cards" : [
                {
                    "name" : "2",
                    "_id" : ObjectId("5a0b5c85a0502e2174fd84b6")
                }
            ]
        }
    ],
    "__v" : 0
}

/* 2 */
{
    "_id" : ObjectId("5a0b5c71a0502e2174fd84a4"),
    "name" : "example 2",
    "users" : [
        ObjectId("59cd114cea98d9326ca1c421")
    ],
    "lists" : [
        {
            "list" : "example next 1",
            "_id" : ObjectId("5a0b5c93a0502e2174fd84bc"),
            "cards" : [
                {
                    "name" : "1",
                    "_id" : ObjectId("5a0b5c95a0502e2174fd84c2")
                },
                {
                    "name" : "2",
                    "_id" : ObjectId("5a0b5c95a0502e2174fd84c1")
                },
                {
                    "name" : "3",
                    "_id" : ObjectId("5a0b5c95a0502e2174fd84c0")
                }
            ]
        },
        {
            "list" : "example next 2",
            "_id" : ObjectId("5a0b5c93a0502e2174fd84bb"),
            "cards" : [
                {
                    "name" : "1",
                    "_id" : ObjectId("5a0b5c98a0502e2174fd84c5")
                },
                {
                    "name" : "2",
                    "_id" : ObjectId("5a0b5c98a0502e2174fd84c4")
                }
            ]
        },
        {
            "list" : "example next 3",
            "_id" : ObjectId("5a0b5c93a0502e2174fd84ba"),
            "cards" : [
                {
                    "name" : "1",
                    "_id" : ObjectId("5a0b5c9aa0502e2174fd84c6")
                }
            ]
        }
    ],
    "__v" : 0
}
</code>```

答:
Yes,

You can structure your own response, with aggregation framework .

https://docs.mongodb.com/manual/aggregation/

The most useful stages in that framework I used are:

```<code>$project: Structure what I want.
$match: Very similiar to select in sql.
$group: to make groups
$sort: to sort :D
$unwind: to unwind arrays.
</code>```

There are more I think but depend on how you want structure, An excelent tutorial here:

https://www.tutorialspoint.com/mongodb/mongodb_aggregation.htm

Body:
I need to know, can I make complex query which will return me result with array board but only with parameters Object inside :

board.name

_id

array with  (lists.list and index position in array)

length cards in array

I'm weak in mongodb so I ask if it is possible to do so, because I have order and I do not know whether to do it in the query or on the loop in the angularjs

Here is from db result with query db.getCollection('boards').find({}) (2results)

    /* 1 */
{
    "_id" : ObjectId("5a0b5c6da0502e2174fd849f"),
    "name" : "example 1",
    "users" : [
        ObjectId("59cd114cea98d9326ca1c421")
    ],
    "lists" : [
        {
            "list" : "example",
            "_id" : ObjectId("5a0b5c7ba0502e2174fd84ae"),
            "cards" : [
                {
                    "name" : "1",
                    "_id" : ObjectId("5a0b5c80a0502e2174fd84b4")
                },
                {
                    "name" : "2",
                    "_id" : ObjectId("5a0b5c80a0502e2174fd84b3")
                },
                {
                    "name" : "3",
                    "_id" : ObjectId("5a0b5c80a0502e2174fd84b2")
                }
            ]
        },
        {
            "list" : "example 1",
            "_id" : ObjectId("5a0b5c7ba0502e2174fd84ad"),
            "cards" : [
                {
                    "name" : "1",
                    "_id" : ObjectId("5a0b5c83a0502e2174fd84b5")
                }
            ]
        },
        {
            "list" : "example",
            "_id" : ObjectId("5a0b5c7ba0502e2174fd84ac"),
            "cards" : [
                {
                    "name" : "2",
                    "_id" : ObjectId("5a0b5c85a0502e2174fd84b6")
                }
            ]
        }
    ],
    "__v" : 0
}

/* 2 */
{
    "_id" : ObjectId("5a0b5c71a0502e2174fd84a4"),
    "name" : "example 2",
    "users" : [
        ObjectId("59cd114cea98d9326ca1c421")
    ],
    "lists" : [
        {
            "list" : "example next 1",
            "_id" : ObjectId("5a0b5c93a0502e2174fd84bc"),
            "cards" : [
                {
                    "name" : "1",
                    "_id" : ObjectId("5a0b5c95a0502e2174fd84c2")
                },
                {
                    "name" : "2",
                    "_id" : ObjectId("5a0b5c95a0502e2174fd84c1")
                },
                {
                    "name" : "3",
                    "_id" : ObjectId("5a0b5c95a0502e2174fd84c0")
                }
            ]
        },
        {
            "list" : "example next 2",
            "_id" : ObjectId("5a0b5c93a0502e2174fd84bb"),
            "cards" : [
                {
                    "name" : "1",
                    "_id" : ObjectId("5a0b5c98a0502e2174fd84c5")
                },
                {
                    "name" : "2",
                    "_id" : ObjectId("5a0b5c98a0502e2174fd84c4")
                }
            ]
        },
        {
            "list" : "example next 3",
            "_id" : ObjectId("5a0b5c93a0502e2174fd84ba"),
            "cards" : [
                {
                    "name" : "1",
                    "_id" : ObjectId("5a0b5c9aa0502e2174fd84c6")
                }
            ]
        }
    ],
    "__v" : 0
}

Body:
Yes,

You can structure your own response, with aggregation framework .

https://docs.mongodb.com/manual/aggregation/

The most useful stages in that framework I used are:

$project: Structure what I want.
$match: Very similiar to select in sql.
$group: to make groups
$sort: to sort :D
$unwind: to unwind arrays.

There are more I think but depend on how you want structure, An excelent tutorial here:

https://www.tutorialspoint.com/mongodb/mongodb_aggregation.htm


问:
How can identify HTML class or specific cell in jsPDF autotable
sorry, my english is not so good. I have a question about jsPDF autotable.
After hours of frustrating my code run and create a PDF file.

Here is my code:

```<code>    $('#printBtn').on('click', function() {
    var pdf = new jsPDF('p', 'pt', 'a4');
    var res = pdf.autoTableHtmlToJson(document.getElementById("tablePrint"));

    pdf.autoTable(res.columns, res.data, {
        theme : 'plain',
        styles: {
            fontSize: 12
        },
        showHeader: 'never'
    });

    pdf.save("test.pdf");
});
</code>```

I have searched in the github repo and found a code snippet in the examples.js that can maybe help me but i dont know how i works right....

```<code>        parsedInput: function (cell, data) {
            if (data.column.dataKey === 'name') {
                cell.styles.fontStyle = 'bold';
            }
        }
</code>```

I have a table, for example

```<code><table>
<tbody>
<tr>
<td class="hrow">15.11.2016</td>
<td class="hrow">11:20</td>
<td class="hrow"></td>
</tr>
<tr>
<td></td>
<td>Musterfrau</td>
<td>Mustermann</td>
</tr>
<tr>
<td></td>
<td>Musterfrau XYZ</td>
<td>XXX</td>
</tr>
<tr>
<td class="hrow">15.11.2016</td>
<td class="hrow">11:20</td>
<td class="hrow"></td>
</tr>
<tr>
<td></td>
<td>Musterfrau</td>
<td>Mustermann</td>
</tr>
<tr>
<td></td>
<td>Musterfrau XYZ</td>
<td>XXX</td>
</tr>
<tr>
<td></td>
<td>Example cell</td>
<td>acusduhfsd</td>
</tr>
<tr>
<td class="hrow">15.11.2016</td>
<td class="hrow">11:20</td>
<td class="hrow"></td>
</tr>
<tr>
<td></td>
<td>Musterfrau dfg</td>
<td>Mustermann dfhgd</td>
</tr>
<tr>
</tbody>
</table>
</code>```

I want the rows respectively the cells with class "hrow" shows the text inside in bold.

How can i reach this?

Thanks for help.

答:
Try something like this:

```<code>pdf.autoTable(res.columns, res.data, {
    didParseCell: function(data) {
        var tdElement = data.cell.raw;
        if (tdElement.classList.contains('hrow')) {
            data.cell.styles.fontStyle = 'bold';
        }
    }
});
</code>```

Not tested, but should make cells that has the css class hrow bold.

Body:
sorry, my english is not so good. I have a question about jsPDF autotable.
After hours of frustrating my code run and create a PDF file.

Here is my code:

    $('#printBtn').on('click', function() {
    var pdf = new jsPDF('p', 'pt', 'a4');
    var res = pdf.autoTableHtmlToJson(document.getElementById("tablePrint"));

    pdf.autoTable(res.columns, res.data, {
        theme : 'plain',
        styles: {
            fontSize: 12
        },
        showHeader: 'never'
    });

    pdf.save("test.pdf");
});

I have searched in the github repo and found a code snippet in the examples.js that can maybe help me but i dont know how i works right....

        parsedInput: function (cell, data) {
            if (data.column.dataKey === 'name') {
                cell.styles.fontStyle = 'bold';
            }
        }

I have a table, for example

15.11.2016
11:20

Musterfrau
Mustermann

Musterfrau XYZ
XXX

15.11.2016
11:20

Musterfrau
Mustermann

Musterfrau XYZ
XXX

Example cell
acusduhfsd

15.11.2016
11:20

Musterfrau dfg
Mustermann dfhgd

I want the rows respectively the cells with class "hrow" shows the text inside in bold.

How can i reach this?

Thanks for help.

Body:
Try something like this:

pdf.autoTable(res.columns, res.data, {
    didParseCell: function(data) {
        var tdElement = data.cell.raw;
        if (tdElement.classList.contains('hrow')) {
            data.cell.styles.fontStyle = 'bold';
        }
    }
});

Not tested, but should make cells that has the css class hrow bold.

ContentLicense: CC BY-SA 4.0


问:
How to get sorted paged map by couple conditions using java 8 streams
I have some model object Account with list of fields, in simple case with two fields String name and double margin

And I need to get exact page of this accounts which is over some margin limit, sorted by margin & name. Each record should have margin as key, and Account as value.

I made this minimal example of code, but seems like sorting doesn't works well for me. So I wrap it in TreeMap, but it will cost extra memory and I hate it.
Probably should be wait to fix this inside of streams and add losted sort by name in case of equals margin

```<code>@Data
class Account {
    private final String name;
    private final double margin;

    private final static double MARGIN_LIMIT = 100;
    private final static int PAGE_SIZE = 3;

    private static Set<Account> accounts = new HashSet<>();

    public static void main(String[] args) {
        accounts.add(new Account("user1", 200));
        accounts.add(new Account("user2", 100));
        accounts.add(new Account("user3", 150));
        accounts.add(new Account("user4", 175));
        accounts.add(new Account("user5", 75));
        accounts.add(new Account("user6", 110));

        Map<Double,Account> val = new TreeMap<Double,Account>(Comparator.reverseOrder());
        val.putAll(getClientsForClosing(2));
        System.out.println(val);
    }

    private static Map<Double, Account> getClientsForClosing(int page) {
        return accounts.stream()
                .filter(account -> account.getMargin() >= MARGIN_LIMIT)
                .sorted(Comparator.comparingDouble(Account::getMargin).reversed())
                .skip(PAGE_SIZE * (page - 1))
                .limit(PAGE_SIZE)
                .collect(Collectors.toMap(Account::getMargin, o -> o));
    }
}
</code>```

答:
Seems like that fix exactly what you are looking for</p>

```<code>private static Map<Double, Account> getClientsForClosing(int page) {
    return accounts.stream()
            .filter(account -> account.getMargin() >= MARGIN_LIMIT)
            .sorted(Comparator.comparingDouble(Account::getMargin)
                    .reversed().thenComparing(Comparator.comparing(Account::getName)))
            .skip(PAGE_SIZE * (page - 1))
            .limit(PAGE_SIZE)
            .collect(Collectors.toMap(Account::getMargin, o -> o,
                    (oldVal, newVal) -> oldVal, LinkedHashMap::new));
}
</code>```

Body:
I have some model object Account with list of fields, in simple case with two fields String name and double margin

And I need to get exact page of this accounts which is over some margin limit, sorted by margin & name. Each record should have margin as key, and Account as value.

I made this minimal example of code, but seems like sorting doesn't works well for me. So I wrap it in TreeMap, but it will cost extra memory and I hate it.
Probably should be wait to fix this inside of streams and add losted sort by name in case of equals margin

@Data
class Account {
    private final String name;
    private final double margin;

    private final static double MARGIN_LIMIT = 100;
    private final static int PAGE_SIZE = 3;

    private static Set<Account> accounts = new HashSet<>();

    public static void main(String[] args) {
        accounts.add(new Account("user1", 200));
        accounts.add(new Account("user2", 100));
        accounts.add(new Account("user3", 150));
        accounts.add(new Account("user4", 175));
        accounts.add(new Account("user5", 75));
        accounts.add(new Account("user6", 110));

        Map<Double,Account> val = new TreeMap<Double,Account>(Comparator.reverseOrder());
        val.putAll(getClientsForClosing(2));
        System.out.println(val);
    }

    private static Map<Double, Account> getClientsForClosing(int page) {
        return accounts.stream()
                .filter(account -> account.getMargin() >= MARGIN_LIMIT)
                .sorted(Comparator.comparingDouble(Account::getMargin).reversed())
                .skip(PAGE_SIZE * (page - 1))
                .limit(PAGE_SIZE)
                .collect(Collectors.toMap(Account::getMargin, o -> o));
    }
}

Body:
Seems like that fix exactly what you are looking for

private static Map<Double, Account> getClientsForClosing(int page) {
    return accounts.stream()
            .filter(account -> account.getMargin() >= MARGIN_LIMIT)
            .sorted(Comparator.comparingDouble(Account::getMargin)
                    .reversed().thenComparing(Comparator.comparing(Account::getName)))
            .skip(PAGE_SIZE * (page - 1))
            .limit(PAGE_SIZE)
            .collect(Collectors.toMap(Account::getMargin, o -> o,
                    (oldVal, newVal) -> oldVal, LinkedHashMap::new));
}