问:
put array value of one file php into an other array of an other file
I know there are a lot of similar question but I didn't find how to do that.  I have one array in test.php

```<code>[
{
    "_id": "89",
    "name": "rfg",
    "author": "toto",
    "description": "",
    "status": "draft",
    "skills": [],
    "creationDate": "2008-07-17T07:49:05.000Z",
    "modificationDate": "2010-09-17T07:49:05.179Z"
}, ...
</code>```

And I want to put all these values in an array "modules" which is in final.php

```<code>[
{
    "_id": "89446259",
    "name": "something",
    "description": "coco",
    "programTemplate": "895",
    "author": "tutu",
    "tutors": [
        "titi"
    ],
    "startDate": "2018-10-05T13:49:00.000Z",
    "endDate": "2019-10-05T13:49:00.000Z",
    "skills": [],
    "modules": [
        {
            "_id": "89",
            "type": "course"
        },
        {
            "_id": "102",
            "type": "course"
        },
        {
            "type": "something",
            "name": "choose"
        }
    ]
}, ...
</code>```

The result as I want is if Id is the same in final.php and in test.php so I put the value.
For example, if the value '_id' in final.php is the same of the value '_id' of test.php so 'name', 'author', 'description', etc. will come in final.php.

Result I want:

```<code>[
{
    "_id": "89446259",
    "name": "something",
    "description": "coco",
    "programTemplate": "895",
    "author": "tutu",
    "tutors": [
        "titi"
    ],
    "startDate": "2018-10-05T13:49:00.000Z",
    "endDate": "2019-10-05T13:49:00.000Z",
    "skills": [],
    "modules": [
        {
            "_id": "89",
            "type": "course",
            "name": "rfg",
            "author": "toto",
            "description": "",
            "status": "draft",
            "skills": [],
            "creationDate": "2008-07-17T07:49:05.000Z",
            "modificationDate": "2010-09-17T07:49:05.179Z"
        },
        {
            "_id": "102",
            "type": "course"
        },
        {
            "type": "something",
            "name": "choose"
        }
    ]
}, ...
</code>```

My PHP code in final.php

```<code>require_once('courses.php');

// initialisation
$results = curl_init( );

// configuration
//session
curl_setopt( $results, CURLOPT_URL, "https://ex.myapi.com/call_api" );
curl_setopt( $results, CURLOPT_RETURNTRANSFER, true );

// récupération du fichier
$result = curl_exec( $results );
$toto=json_decode($result);

//$objArray = json_decode($rows);

$newarray = array();
foreach ($toto as &$t){

    $modules=$t->modules;
    foreach ($modules as $m){
        $coco='787';

        $m->testId= $val;
        if ($m->testId == $m->_id){
            $m->names = $name;
        $m->description = $desc;
        $m->author = $author;
        $m->status = $status;
        $m->creaDate = $creaDate;
        $m->modifDate = $modifDate;

        // $m->toto = $coco;
        $newarray[] = $m;
    }

}
print_r($toto);
echo json_encode($toto);

curl_close( $results );
</code>```

How can I do this?

答:
test.php:

```<code>$test1 = $decoded_json_object; // YOUR **DECODED** JSON OBJECT FROM test.php
</code>```

final.php:

```<code>require_once( 'test.php' );

$test2 = $decoded_json_object_2 // YOUR **DECODED** JSON OBJECT FROM final.php

foreach( $test1 as &$course )  {
  foreach( $test2 as &$program )  {
    foreach( $program->modules as &$module ) {
      if( $module->_id == $course->_id ) {
        $module = (object) array_merge( (array) $module, (array) $course);
      }
    }
  }
}

$test2 = json_encode( $test2 );
</code>```

Body:
I know there are a lot of similar question but I didn't find how to do that.  I have one array in test.php

[
{
    "_id": "89",
    "name": "rfg",
    "author": "toto",
    "description": "",
    "status": "draft",
    "skills": [],
    "creationDate": "2008-07-17T07:49:05.000Z",
    "modificationDate": "2010-09-17T07:49:05.179Z"
}, ...

And I want to put all these values in an array "modules" which is in final.php

[
{
    "_id": "89446259",
    "name": "something",
    "description": "coco",
    "programTemplate": "895",
    "author": "tutu",
    "tutors": [
        "titi"
    ],
    "startDate": "2018-10-05T13:49:00.000Z",
    "endDate": "2019-10-05T13:49:00.000Z",
    "skills": [],
    "modules": [
        {
            "_id": "89",
            "type": "course"
        },
        {
            "_id": "102",
            "type": "course"
        },
        {
            "type": "something",
            "name": "choose"
        }
    ]
}, ...

The result as I want is if Id is the same in final.php and in test.php so I put the value.
For example, if the value '_id' in final.php is the same of the value '_id' of test.php so 'name', 'author', 'description', etc. will come in final.php.

Result I want:

[
{
    "_id": "89446259",
    "name": "something",
    "description": "coco",
    "programTemplate": "895",
    "author": "tutu",
    "tutors": [
        "titi"
    ],
    "startDate": "2018-10-05T13:49:00.000Z",
    "endDate": "2019-10-05T13:49:00.000Z",
    "skills": [],
    "modules": [
        {
            "_id": "89",
            "type": "course",
            "name": "rfg",
            "author": "toto",
            "description": "",
            "status": "draft",
            "skills": [],
            "creationDate": "2008-07-17T07:49:05.000Z",
            "modificationDate": "2010-09-17T07:49:05.179Z"
        },
        {
            "_id": "102",
            "type": "course"
        },
        {
            "type": "something",
            "name": "choose"
        }
    ]
}, ...

My PHP code in final.php

require_once('courses.php');

// initialisation
$results = curl_init( );

// configuration
//session
curl_setopt( $results, CURLOPT_URL, "https://ex.myapi.com/call_api" );
curl_setopt( $results, CURLOPT_RETURNTRANSFER, true );

// récupération du fichier
$result = curl_exec( $results );
$toto=json_decode($result);

//$objArray = json_decode($rows);

$newarray = array();
foreach ($toto as &$t){

    $modules=$t->modules;
    foreach ($modules as $m){
        $coco='787';

        $m->testId= $val;
        if ($m->testId == $m->_id){
            $m->names = $name;
        $m->description = $desc;
        $m->author = $author;
        $m->status = $status;
        $m->creaDate = $creaDate;
        $m->modifDate = $modifDate;

        // $m->toto = $coco;
        $newarray[] = $m;
    }

}
print_r($toto);
echo json_encode($toto);

curl_close( $results );

How can I do this?

Body:
test.php:

$test1 = $decoded_json_object; // YOUR **DECODED** JSON OBJECT FROM test.php

final.php:

require_once( 'test.php' );

$test2 = $decoded_json_object_2 // YOUR **DECODED** JSON OBJECT FROM final.php

foreach( $test1 as &$course )  {
  foreach( $test2 as &$program )  {
    foreach( $program->modules as &$module ) {
      if( $module->_id == $course->_id ) {
        $module = (object) array_merge( (array) $module, (array) $course);
      }
    }
  }
}

$test2 = json_encode( $test2 );


来源: stackexchange

问:
Convert object of objects to array
I work on a Angular Project and I have a little issue with an object..

I have an object with objects inside :

```<code>P3E051V:{
    lot: "P3E051V"
    quantite: 5400
},
P3E052V:{
    lot: "P3E052V"
    quantite: 5400
},
P3E054V:{
    lot: "P3E054V"
    quantite: 10800
}
</code>```

What I would like to do is to display a table like this :
image of the table

But I can't loop on an object with *ngFor.
I tried to use Object.entries(myObject) but it doesn't work.

Anyone have an idea to solve this ?

Thanks

答:
Just put this object into an array
like array.push(object)</p>

ContentLicense: CC BY-SA 4.0

Title: Convert object of objects to array

Body:
I work on a Angular Project and I have a little issue with an object..

I have an object with objects inside :

P3E051V:{
    lot: "P3E051V"
    quantite: 5400
},
P3E052V:{
    lot: "P3E052V"
    quantite: 5400
},
P3E054V:{
    lot: "P3E054V"
    quantite: 10800
}

What I would like to do is to display a table like this :
image of the table

But I can't loop on an object with *ngFor.
I tried to use Object.entries(myObject) but it doesn't work.

Anyone have an idea to solve this ?

Thanks


问:
Compare two arrays and add matching strings to another array
So I have two arrays. One of them is 1D (AllAssigneesUnique) and the other is 2D (DB_Array). I want to compare (AllAssigneesUnique) with the first column of (DB_Array) and when there is an exact match, store the string from the first and second column of (DB_Array) to a third 3D Array called (NewAssigneesArray). Additionally, the third column of (NewAssigneesArray) should have the string "New". Below is my code so far.
P.S. How can I re-dimension the new array automatically since the number of matching strings will not always be the same? At the moment, I am using a previously made dictionary to get the exact number of matching strings. </p>

```<code>Dim NewAssigneesArray() As Variant
ReDim NewAssigneesArray(1 To NewAssigneesList.count, 1 To 3)

For a = LBound(AllAssigneesUnique) To UBound(AllAssigneesUnique)
    For b = LBound(DB_Array, 1) To UBound(DB_Array, 1)
        If AllAssigneesUnique(a) = DB_Array(b, 1) Then
            For i = LBound(NewAssigneesArray) To UBound(NewAssigneesArray)
                NewAssigneesArray(i, 1) = DB_Array(b, 1)
                NewAssigneesArray(i, 2) = DB_Array(b, 2)
                NewAssigneesArray(i, 3) = "New"
            Next i
        End If
    Next b
Next a
</code>```

答:
The code below is untested for obvious reasons and might contain typos or small errors. I believe you will be able to correct them. Note that it's more efficient to dimension an array larger than required and give it its final size at the end. The large UBound doesn't require RAM space.</p>

```<code>Sub CreateNewArray()

    Dim NewAssigneesArray() As Variant
    Dim i As Long
    Dim a As Long, b As Long

    ' set a (UBound, 2) a lot higher than what you will ever need.
    ' note that you can't Redim (UBound, 1), only (UBound, 2)
    ReDim NewAssigneesArray(1 To 3, 1 To 5000)

    For a = LBound(AllAssigneesUnique) To UBound(AllAssigneesUnique)
        For b = LBound(DB_Array, 1) To UBound(DB_Array, 1)
            ' Use VbBinaryCompare for a case sensitive comparison
            If StrComp(AllAssigneesUnique(a), DB_Array(b, 1), vbTextCompare) = 0 Then
                i = i + 1
                NewAssigneesArray(1, i) = DB_Array(b, 1)
                NewAssigneesArray(2, i) = DB_Array(b, 2)
                NewAssigneesArray(3, i) = "New"
                Exit For
            End If
        Next b
    Next a
    ReDim Preserve NewAssigneesArray(1 To 3, 1 To i)
End Sub
</code>```

Body:
So I have two arrays. One of them is 1D (AllAssigneesUnique) and the other is 2D (DB_Array). I want to compare (AllAssigneesUnique) with the first column of (DB_Array) and when there is an exact match, store the string from the first and second column of (DB_Array) to a third 3D Array called (NewAssigneesArray). Additionally, the third column of (NewAssigneesArray) should have the string "New". Below is my code so far.
P.S. How can I re-dimension the new array automatically since the number of matching strings will not always be the same? At the moment, I am using a previously made dictionary to get the exact number of matching strings.

Dim NewAssigneesArray() As Variant
ReDim NewAssigneesArray(1 To NewAssigneesList.count, 1 To 3)

For a = LBound(AllAssigneesUnique) To UBound(AllAssigneesUnique)
    For b = LBound(DB_Array, 1) To UBound(DB_Array, 1)
        If AllAssigneesUnique(a) = DB_Array(b, 1) Then
            For i = LBound(NewAssigneesArray) To UBound(NewAssigneesArray)
                NewAssigneesArray(i, 1) = DB_Array(b, 1)
                NewAssigneesArray(i, 2) = DB_Array(b, 2)
                NewAssigneesArray(i, 3) = "New"
            Next i
        End If
    Next b
Next a

Body:
The code below is untested for obvious reasons and might contain typos or small errors. I believe you will be able to correct them. Note that it's more efficient to dimension an array larger than required and give it its final size at the end. The large UBound doesn't require RAM space.

Sub CreateNewArray()

    Dim NewAssigneesArray() As Variant
    Dim i As Long
    Dim a As Long, b As Long

    ' set a (UBound, 2) a lot higher than what you will ever need.
    ' note that you can't Redim (UBound, 1), only (UBound, 2)
    ReDim NewAssigneesArray(1 To 3, 1 To 5000)

    For a = LBound(AllAssigneesUnique) To UBound(AllAssigneesUnique)
        For b = LBound(DB_Array, 1) To UBound(DB_Array, 1)
            ' Use VbBinaryCompare for a case sensitive comparison
            If StrComp(AllAssigneesUnique(a), DB_Array(b, 1), vbTextCompare) = 0 Then
                i = i + 1
                NewAssigneesArray(1, i) = DB_Array(b, 1)
                NewAssigneesArray(2, i) = DB_Array(b, 2)
                NewAssigneesArray(3, i) = "New"
                Exit For
            End If
        Next b
    Next a
    ReDim Preserve NewAssigneesArray(1 To 3, 1 To i)
End Sub


问:
Android seekbar textView
I have 3 seekbar to change the background color. Each seekbar har a textView from 0-255 to show the colorcode in RGB. When I slide one of the seekbar, the RGB textView change on all. How can I specify, so only the textView that belong to the seekbar, that I slide will change?</p>

```<code>  private SeekBar.OnSeekBarChangeListener seekBarChangeListener
        = new SeekBar.OnSeekBarChangeListener()
{

    TextView seekBar1Progress;
    TextView seekBar2Progress;
    TextView seekBar3Progress;

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress,
                                  boolean fromUser) {

        updateBackground();
        seekBar1Progress = (TextView) findViewById(R.id.viewSlider1);
        seekBar1Progress.setText(" " + progress);
        seekBar2Progress = (TextView) findViewById(R.id.viewSlider2);
        seekBar2Progress.setText(" " + progress);
        seekBar3Progress = (TextView) findViewById(R.id.viewSlider3);
        seekBar3Progress.setText(" " + progress);
    }
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
    }
};
</code>```

答:
You are getting SeekBar object in OnProgressChanged method, you can compare its id to your individual SeekBar. Try below code:

```<code>@Override
        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
            if(seekBar.getId()==R.id.seekBar1){
                seekBar1Progress = (TextView) findViewById(R.id.viewSlider1);
                seekBar1Progress.setText(" " + progress);
            }else if(seekBar.getId()==R.id.seekBar2){
                seekBar2Progress = (TextView) findViewById(R.id.viewSlider2);
                seekBar2Progress.setText(" " + progress);
            }else{
                seekBar3Progress = (TextView) findViewById(R.id.viewSlider3);
                seekBar3Progress.setText(" " + progress);
            }

        }
</code>```

Hope this will help!!

Title: Android seekbar textView

Body:
I have 3 seekbar to change the background color. Each seekbar har a textView from 0-255 to show the colorcode in RGB. When I slide one of the seekbar, the RGB textView change on all. How can I specify, so only the textView that belong to the seekbar, that I slide will change?

  private SeekBar.OnSeekBarChangeListener seekBarChangeListener
        = new SeekBar.OnSeekBarChangeListener()
{

    TextView seekBar1Progress;
    TextView seekBar2Progress;
    TextView seekBar3Progress;

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress,
                                  boolean fromUser) {

        updateBackground();
        seekBar1Progress = (TextView) findViewById(R.id.viewSlider1);
        seekBar1Progress.setText(" " + progress);
        seekBar2Progress = (TextView) findViewById(R.id.viewSlider2);
        seekBar2Progress.setText(" " + progress);
        seekBar3Progress = (TextView) findViewById(R.id.viewSlider3);
        seekBar3Progress.setText(" " + progress);
    }
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
    }
};

Body:
You are getting SeekBar object in OnProgressChanged method, you can compare its id to your individual SeekBar. Try below code:

@Override
        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
            if(seekBar.getId()==R.id.seekBar1){
                seekBar1Progress = (TextView) findViewById(R.id.viewSlider1);
                seekBar1Progress.setText(" " + progress);
            }else if(seekBar.getId()==R.id.seekBar2){
                seekBar2Progress = (TextView) findViewById(R.id.viewSlider2);
                seekBar2Progress.setText(" " + progress);
            }else{
                seekBar3Progress = (TextView) findViewById(R.id.viewSlider3);
                seekBar3Progress.setText(" " + progress);
            }

        }

Hope this will help!!


问:
Chart.js: passing objects instead of int values as data
Is it possible to pass an array of objects instead of an array of integers? The following code works but results in a flat zero line:</p>

```<code>var ctx = document.getElementById("a").getContext("2d");
var data = {
    labels: ["Fri", "Sat", "Sun"],
    datasets: [{
    label: "Chart B",
    fillColor: "rgba(220,220,220,0.2)",
    strokeColor: "rgba(150,150,150,1)",
    pointColor: "rgba(150,150,150,1)",
    pointStrokeColor: "#fff",
    pointHighlightFill: "#fff",
    pointHighlightStroke: "rgba(220,220,220,1)",
    data: [{
                y: 48,
                name: "Value one",
                date: "2015-04-30"
            }, {
                y: 40,
                name: "Value two",
                date: "2016-05-30"
            }, {
                y: 19,
                name: "Value three",
                date: "2016-06-30"
            } ]
    }]
};

var Chart = new Chart(ctx).Line(data);
</code>```

答:
I can confirm that answer @rinogo gave works on latests version. You can add custom properties to dataset and use 'em in tooltip or elsewhere afterwards.

First add data to dataset. On my case I only have one set, so I'm just pushing points.

```<code>chartData.datasets[0].data.push({
    y: groupedBooking.distinctCount,
    distinctUsers: distinctUsers
});
</code>```

... and finally override callback with chartOptions:

```<code>options: {
    tooltips: {
        callbacks: {
            label(tooltipItem, data) {
                console.log(data);
                return data.datasets[0].data[tooltipItem.index].distinctUsers;
            }
        }
    }
}
</code>```

If you would happen to have multiple datasets you get datasetIndex from tooltipItem as well... so to confirm, X can be omitted from datapoint and customer properties are preserved within object.

ContentLicense: CC BY-SA 3.0

Body:
Is it possible to pass an array of objects instead of an array of integers? The following code works but results in a flat zero line:

var ctx = document.getElementById("a").getContext("2d");
var data = {
    labels: ["Fri", "Sat", "Sun"],
    datasets: [{
    label: "Chart B",
    fillColor: "rgba(220,220,220,0.2)",
    strokeColor: "rgba(150,150,150,1)",
    pointColor: "rgba(150,150,150,1)",
    pointStrokeColor: "#fff",
    pointHighlightFill: "#fff",
    pointHighlightStroke: "rgba(220,220,220,1)",
    data: [{
                y: 48,
                name: "Value one",
                date: "2015-04-30"
            }, {
                y: 40,
                name: "Value two",
                date: "2016-05-30"
            }, {
                y: 19,
                name: "Value three",
                date: "2016-06-30"
            } ]
    }]
};

var Chart = new Chart(ctx).Line(data);

Body:
I can confirm that answer @rinogo gave works on latests version. You can add custom properties to dataset and use 'em in tooltip or elsewhere afterwards.

First add data to dataset. On my case I only have one set, so I'm just pushing points.

chartData.datasets[0].data.push({
    y: groupedBooking.distinctCount,
    distinctUsers: distinctUsers
});

... and finally override callback with chartOptions:

options: {
    tooltips: {
        callbacks: {
            label(tooltipItem, data) {
                console.log(data);
                return data.datasets[0].data[tooltipItem.index].distinctUsers;
            }
        }
    }
}

If you would happen to have multiple datasets you get datasetIndex from tooltipItem as well... so to confirm, X can be omitted from datapoint and customer properties are preserved within object.


问:
Removing an object from array in Vue.js - throws Property of method is not defined
I have 3 files: App, BlogList, BlogItem.
I want to allow the user to delete the post if she/he wants to. I am using splice but for some reason, I get this error:

Property or method "removePost" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

Here are the code snippets(BlogList is included in the App and also consists of many BlogItems):

App:

```<code><template>
  <div id="app">
    <Header />
    <PostList v-bind:posts="posts" />
  </div>
</template>

<script>
import axios from "axios";
import Header from ...
import PostList from ...

export default {
  name: "App",
  components: {
    Header,
    PostList,
  },
data() {
    return {
      posts: []
    };
  }
};
</script>
</code>```

BlogList:

```<code><template>
<div class="blog-list">
    <div v-for="(post,index) in posts" v-bind:key="post.id">
      <PostItem v-bind:post="[post,index]" />
    </div>
</div>
</template>

<script>
import PostItem from ...

export default {
  name: "PostList",
  components: {
    PostItem
  },
  props: ["posts"],
  methods: {
    removePost: function(index) {
      this.$delete(this.posts, index);
    }
  }
};
</script>
</code>```

BlogItem:

```<code><template>
  <div class="wrapper">
    <div class="post-text">{{post.data.title}}</div>
      <button class="btn-remove" @click="removePost(index)">Remove</button>
    </div>
  </div>
</template>

<script>
export default {
  name: "PostItem",
  props: ["post"]
};
</script>
</code>```

I am still fairly new to Vue and passing the data between the components seems is a challenge. I tried declaring the function in BlogList as it is where I put my v-for but I cannot fetch the index of the blog post's clicked(and I believe that is what causes issues). I'm including only the necessary bits of code and I am aware that a similar question has been asked already (How to remove an item from an array in Vue.js) but in my case, I want to use 3 separate components instead of just one.

答:
You have defined removePost in the BlogList, but not in the BlogItem component, that is why it throws an error. Also, there is no index within the BlogItem component's scope. In your scenario, it would be best to either emit the event or use the <slot>.

```<code><template>
  <div class="wrapper">
    <div class="post-text">{{this.post.data.title}}</div>
      <button class="btn-remove" @click="removePost(this.index)">Remove</button>
    </div>
  </div>
</template>

<script>
export default {
  name: "PostItem",
  props: ["post", "index"],
  methods: {
    removePost(index){
     this.$emit('remove-post', index);

    }

  }
};
</script>
</code>```

And then in the PostList component, catch the event within created() and call the parent's removePost:

```<code><template>
<div class="blog-list">
    <div v-for="(post,index) in posts" v-bind:key="post.id">
      <PostItem v-bind:post="[post,index]" />
    </div>
</div>
</template>

<script>
import PostItem from ...

export default {
  name: "PostList",
  components: {
    PostItem
  },
  props: ["posts"],
  created(){
    this.$root.$on('remove-post', function(index){
      this.removePost(index);
    });
  },
  methods: {
    removePost: function(index) {
      this.$delete(this.posts, index);
    }
  }
};
</script>
</code>```

Body:
I have 3 files: App, BlogList, BlogItem.
I want to allow the user to delete the post if she/he wants to. I am using splice but for some reason, I get this error:

Property or method "removePost" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

Here are the code snippets(BlogList is included in the App and also consists of many BlogItems):

App:

<template>

    <PostList v-bind:posts="posts" />

</template>

BlogList:

<template>

      <PostItem v-bind:post="[post,index]" />

</template>

BlogItem:

<template>

{{post.data.title}}

      <button class="btn-remove" @click="removePost(index)">Remove</button>

</template>

I am still fairly new to Vue and passing the data between the components seems is a challenge. I tried declaring the function in BlogList as it is where I put my v-for but I cannot fetch the index of the blog post's clicked(and I believe that is what causes issues). I'm including only the necessary bits of code and I am aware that a similar question has been asked already (How to remove an item from an array in Vue.js) but in my case, I want to use 3 separate components instead of just one.

Body:
You have defined removePost in the BlogList, but not in the BlogItem component, that is why it throws an error. Also, there is no index within the BlogItem component's scope. In your scenario, it would be best to either emit the event or use the <slot>.

<template>
  <div class="wrapper">
    <div class="post-text">{{this.post.data.title}}</div>
      <button class="btn-remove" @click="removePost(this.index)">Remove</button>
    </div>
  </div>
</template>

<script>
export default {
  name: "PostItem",
  props: ["post", "index"],
  methods: {
    removePost(index){
     this.$emit('remove-post', index);

    }

  }
};
</script>

And then in the PostList component, catch the event within created() and call the parent's removePost:

<template>
<div class="blog-list">
    <div v-for="(post,index) in posts" v-bind:key="post.id">
      <PostItem v-bind:post="[post,index]" />
    </div>
</div>
</template>

<script>
import PostItem from ...

export default {
  name: "PostList",
  components: {
    PostItem
  },
  props: ["posts"],
  created(){
    this.$root.$on('remove-post', function(index){
      this.removePost(index);
    });
  },
  methods: {
    removePost: function(index) {
      this.$delete(this.posts, index);
    }
  }
};
</script>


问:
Tradingview's auto fit scale function: exclude drawings of an indicator
I've got an indicator which automatically compresses the whole price chart on the y-scale, so I have to leave it invisible most of the time.
Even a doubleclick on the y-scale (chart auto fit function) includes all visible indicators.
Is there any way to prevent one or all indicators from doing that?</p>

答: ohhh... I've just found the answer ... a simple right click on the y-scale brings ups the context menu with an "scale price chart only" option!! Hope this also helps someone else :-)</p>


问:
Angular subscribe elegant
I'd like to ask about my subscribe method. I want to get my objects(employees) from firebase and do a loot of operations on my objects, like avg salaries, avg missed days... In my opinion it looks so horrible. My service void:

```<code> getEmployees(): Observable<Employee[]> {
    return this.db.list<Employee>(this.Api_url).snapshotChanges()
      .pipe(map(response => response.map(car => this.assignKey(car))));
  }
</code>```

And my ngOnInit:

```<code>  ngOnInit() {

    this.subscribtion = this.mainservice.getEmployees().subscribe((emps)=> {
      this.employees = emps;
      this.workersdatas = [];
      this.educationdatas = [];
      this.checkavaragesalaries(emps);
      this.countMonthAbsences(emps, 1);
      this.countMonthSalaries(emps, 1);
      this.departments.forEach((one)=> {
        const dep = emps.filter(on => on.department.includes(one) && this.FilterEmployees(on)).length;
        this.workersdatas.push({name: one, value: dep});
      });

      this.educations.forEach((one)=> {
        const edu = emps.filter(on => on.education.includes(one)).length;
        this.educationdatas.push({name: one, value: edu});
      });

      const mynumb =this.educationdatas.map(on => on.value);
      this.mosteducation = this.educationdatas.filter(one => one.value === Math.max(...mynumb))[0].name;
    }); }
</code>```

Should I unsubscribe() it on ngOnDestroy or that's not necessary? Is that allowed to write it like that?

答:
My favourite unsubscribe pattern is to use takeUntil. takeUntil() accepts an observable, and will stop the subscription when that observable emits a value.

The long-winded way to do this is emit a value in ngOnDestroy().

```<code>destroyed = new Subject<void>();

ngOnInit(): void {
  myService.getData().pipe(
    takeUntil(this.destroyed)
  ).subscribe(data => {
    // process data
  });
}

ngOnDestroy(): void {
  this.destroyed.next();
  this.destroyed.complete();
}
</code>```

This gets quite tedious once you've done this a few times. The best solution I've seen for this (and currently use) is to set up a shared function that emits the destroyed value for you. Source Credit

```<code>import { OnDestroy } from '@angular/core';

import { ReplaySubject, Subject, Observable } from 'rxjs';

export function componentDestroyed(component: OnDestroy): Observable<void> {
  const oldNgOnDestroy: () => void = component.ngOnDestroy;
  const destroyed: Subject<void> = new ReplaySubject<void>(1);
  component.ngOnDestroy = () => {
    oldNgOnDestroy.apply(component);
    destroyed.next(undefined);
    destroyed.complete();
  };
  return destroyed.asObservable();
}
</code>```

It is then almost trivial to use in your component:

```<code>ngOnInit(): void {
  myService.getData().pipe(
    takeUntil(componentDestroyed(this))
  ).subscribe(data => {
    // process data
  });
}

ngOnDestroy(): void {}

</code>```

All you have to do is implement ngOnDestroy in your component and add takeUntil(componentDestroyed(this)) to your pipe.

Title: Angular subscribe elegant

Body:
I'd like to ask about my subscribe method. I want to get my objects(employees) from firebase and do a loot of operations on my objects, like avg salaries, avg missed days... In my opinion it looks so horrible. My service void:

 getEmployees(): Observable<Employee[]> {
    return this.db.list<Employee>(this.Api_url).snapshotChanges()
      .pipe(map(response => response.map(car => this.assignKey(car))));
  }

And my ngOnInit:

  ngOnInit() {

    this.subscribtion = this.mainservice.getEmployees().subscribe((emps)=> {
      this.employees = emps;
      this.workersdatas = [];
      this.educationdatas = [];
      this.checkavaragesalaries(emps);
      this.countMonthAbsences(emps, 1);
      this.countMonthSalaries(emps, 1);
      this.departments.forEach((one)=> {
        const dep = emps.filter(on => on.department.includes(one) && this.FilterEmployees(on)).length;
        this.workersdatas.push({name: one, value: dep});
      });

      this.educations.forEach((one)=> {
        const edu = emps.filter(on => on.education.includes(one)).length;
        this.educationdatas.push({name: one, value: edu});
      });

      const mynumb =this.educationdatas.map(on => on.value);
      this.mosteducation = this.educationdatas.filter(one => one.value === Math.max(...mynumb))[0].name;
    }); }

Should I unsubscribe() it on ngOnDestroy or that's not necessary? Is that allowed to write it like that?

Body:
My favourite unsubscribe pattern is to use takeUntil. takeUntil() accepts an observable, and will stop the subscription when that observable emits a value.

The long-winded way to do this is emit a value in ngOnDestroy().

destroyed = new Subject<void>();

ngOnInit(): void {
  myService.getData().pipe(
    takeUntil(this.destroyed)
  ).subscribe(data => {
    // process data
  });
}

ngOnDestroy(): void {
  this.destroyed.next();
  this.destroyed.complete();
}

This gets quite tedious once you've done this a few times. The best solution I've seen for this (and currently use) is to set up a shared function that emits the destroyed value for you. Source Credit

import { OnDestroy } from '@angular/core';

import { ReplaySubject, Subject, Observable } from 'rxjs';

export function componentDestroyed(component: OnDestroy): Observable<void> {
  const oldNgOnDestroy: () => void = component.ngOnDestroy;
  const destroyed: Subject<void> = new ReplaySubject<void>(1);
  component.ngOnDestroy = () => {
    oldNgOnDestroy.apply(component);
    destroyed.next(undefined);
    destroyed.complete();
  };
  return destroyed.asObservable();
}

It is then almost trivial to use in your component:

ngOnInit(): void {
  myService.getData().pipe(
    takeUntil(componentDestroyed(this))
  ).subscribe(data => {
    // process data
  });
}

ngOnDestroy(): void {}

All you have to do is implement ngOnDestroy in your component and add takeUntil(componentDestroyed(this)) to your pipe.


问:
oracle pl-sql find the 3rd wednesday of a given date
Currently I have a process which takes a date variable EG: '01-MAR-2026', it then iterates over this date checking if the day is wednesday. If so then increment a counter else add 1 day and check again.
This exits when the wednesday count is = 3.

```<code>IF (to_char(v_Date,'dy') = 'wed') THEN
        v_NumWed := v_NumWed + 1;
END IF;

WHILE (v_NumWed != 3) LOOP
    v_Date := v_Date + interval '1' day;
    IF (to_char(v_Date, 'dy') = 'wed') THEN
        v_NumWed := v_NumWed + 1;
    END IF;
END LOOP;
</code>```

However I have a feeling there is a simpler way to achieve this maybe via a query or something not using a loop EG: use an input date and query to find the first wednesday then + 14 days?

Any suggestions would be great, thanks in advance :)

EDIT: I have something like this which appears to work, also considers if the first day is a wednesday itself.

```<code>select next_day(trunc(v_date, 'MM') - 1, 'WED'), next_day(trunc(v_date, 'MM') - 1, 'WED') + 14 into v_first, v_third from dual;
</code>```

SOLVED: thanks for the help folks, got a few possible solutions now in the comments!

Body:
Currently I have a process which takes a date variable EG: '01-MAR-2026', it then iterates over this date checking if the day is wednesday. If so then increment a counter else add 1 day and check again.
This exits when the wednesday count is = 3.

IF (to_char(v_Date,'dy') = 'wed') THEN
        v_NumWed := v_NumWed + 1;
END IF;

WHILE (v_NumWed != 3) LOOP
    v_Date := v_Date + interval '1' day;
    IF (to_char(v_Date, 'dy') = 'wed') THEN
        v_NumWed := v_NumWed + 1;
    END IF;
END LOOP;

However I have a feeling there is a simpler way to achieve this maybe via a query or something not using a loop EG: use an input date and query to find the first wednesday then + 14 days?

Any suggestions would be great, thanks in advance :)

EDIT: I have something like this which appears to work, also considers if the first day is a wednesday itself.

select next_day(trunc(v_date, 'MM') - 1, 'WED'), next_day(trunc(v_date, 'MM') - 1, 'WED') + 14 into v_first, v_third from dual;

SOLVED: thanks for the help folks, got a few possible solutions now in the comments!

Body:
TO get the third Wednesday from a date, including that date if ti is itself a Wednesday, you can do:

select next_day(date '2026-03-01' + 13, 'Wednesday') from dual;

NEXT_DAY(D
----------
2026-03-18

The next_day function is a bit awkward because it is NLS-sensitive, and doesn't have an override (like to_char() does) - so the NLS session language and the day name/abbreviation have to be in the same language. If you can't control then then you can work around it by getting the current-language day-name from a known fixed date:

alter session set nls_date_language = 'French';

select to_char(date '2026-03-01', 'Day'),
  next_day(date '2026-03-01' + 13, to_char(date '1999-12-29', 'Day'))
from dual;

TO_CHAR( NEXT_DAY(D
-------- ----------
Dimanche 2026-03-18

Demo with some sample dates:

with t (sample_date) as (
  select date '2026-02-15' + level
  from dual
  connect by level <= 31
)
select sample_date, next_day(sample_date + 13, 'Wednesday') as third_wed
from t
order by sample_date;

SAMPLE_DAT THIRD_WED
---------- ----------
2026-02-16 2026-03-04
2026-02-17 2026-03-04
2026-02-18 2026-03-04
2026-02-19 2026-03-11
2026-02-20 2026-03-11
2026-02-21 2026-03-11
2026-02-22 2026-03-11
2026-02-23 2026-03-11
2026-02-24 2026-03-11
2026-02-25 2026-03-11
2026-02-26 2026-03-18
2026-02-27 2026-03-18
2026-02-28 2026-03-18
2026-03-01 2026-03-18
2026-03-02 2026-03-18
2026-03-03 2026-03-18
2026-03-04 2026-03-18
2026-03-05 2026-03-25
2026-03-06 2026-03-25
2026-03-07 2026-03-25
2026-03-08 2026-03-25
2026-03-09 2026-03-25
2026-03-10 2026-03-25
2026-03-11 2026-03-25
2026-03-12 2026-04-01
2026-03-13 2026-04-01
2026-03-14 2026-04-01
2026-03-15 2026-04-01
2026-03-16 2026-04-01
2026-03-17 2026-04-01
2026-03-18 2026-04-01


问:
Is there any C++ function to sort a Map?
I want to know that how can I sort an ordered_map in C++ on the basis of values. Is there any function to do it?

答:
No. A std::map is designed to store elements formed by a combination of a key value and a mapped value, where the key values are used to sort and identify the elements.

To sort by values, you could simply create an inverted map:

```<code>template <typename T1, typename T2>
std::map<T2, T1> invert(const std::map<T1, T2> & m)
{
    std::map<T2, T1> ret;
    for (const auto& e : m)
        ret[e.second] = e.first;
    return ret;
}
</code>```

There are many solutions to this problem, and you might prefer one over the other in function of your needs.

Body:
No. A std::map is designed to store elements formed by a combination of a key value and a mapped value, where the key values are used to sort and identify the elements.

To sort by values, you could simply create an inverted map:

template <typename T1, typename T2>
std::map<T2, T1> invert(const std::map<T1, T2> & m)
{
    std::map<T2, T1> ret;
    for (const auto& e : m)
        ret[e.second] = e.first;
    return ret;
}

There are many solutions to this problem, and you might prefer one over the other in function of your needs.


问:
How to fix Google Script Error "TypeError: Cannot read property 'length' of undefined (line 59, file "Code")"?
I have this code that works fine. The code is supposed to copy and filter data from one spreadsheet to another using values in Column E. When I enter certain values like "Business 2", it runs fine. But if I enter other values like "Business 1", I get this error - "TypeError: Cannot read property 'length' of undefined (line 59, file "Code")"

I have cleaned and trimmed the cell contents with =CLEAN(TRIM())

Here is the code

```<code>function copySheetValuesV2(){
  var source = SpreadsheetApp.getActiveSheet();
  var sourceName = source.getSheetName();
  var sValues = source.getDataRange().getValues();

  //var rawData = range.getValues()     // get value from spreadsheet 1
var data = []                       // Filtered Data will be stored in this array
for (var i = 0; i< sValues.length ; i++){
if(sValues[i][4] == "Business 1")            // Check to see if column E says "Business 1" if not skip it
{
data.push(sValues[i])
}
}

  var destination = SpreadsheetApp.openById('idvalue');
  var shttoDelete = destination.getSheetByName('Copy of Dashboard');

  source.copyTo(destination);
  var destinationSheet = destination.getSheetByName('Copy of '+sourceName);
  destinationSheet.getRange(2,1,data.length,data[0].length).setValues(data);// overwrite all formulas that the copyTo preserved
  destinationSheet.getRange(data.length + 1,1,destinationSheet.getLastRow(),destinationSheet.getLastColumn()).clearContent();

}
</code>```

I need help with finding why the script isn't reading certain values from the column.

答: I typed the text "Business 1" in another cell. Then I copied it to replace the existing text in the column.</p>

Body:
I have this code that works fine. The code is supposed to copy and filter data from one spreadsheet to another using values in Column E. When I enter certain values like "Business 2", it runs fine. But if I enter other values like "Business 1", I get this error - "TypeError: Cannot read property 'length' of undefined (line 59, file "Code")"

I have cleaned and trimmed the cell contents with =CLEAN(TRIM())

Here is the code

function copySheetValuesV2(){
  var source = SpreadsheetApp.getActiveSheet();
  var sourceName = source.getSheetName();
  var sValues = source.getDataRange().getValues();

  //var rawData = range.getValues()     // get value from spreadsheet 1
var data = []                       // Filtered Data will be stored in this array
for (var i = 0; i< sValues.length ; i++){
if(sValues[i][4] == "Business 1")            // Check to see if column E says "Business 1" if not skip it
{
data.push(sValues[i])
}
}

  var destination = SpreadsheetApp.openById('idvalue');
  var shttoDelete = destination.getSheetByName('Copy of Dashboard');

  source.copyTo(destination);
  var destinationSheet = destination.getSheetByName('Copy of '+sourceName);
  destinationSheet.getRange(2,1,data.length,data[0].length).setValues(data);// overwrite all formulas that the copyTo preserved
  destinationSheet.getRange(data.length + 1,1,destinationSheet.getLastRow(),destinationSheet.getLastColumn()).clearContent();

}

I need help with finding why the script isn't reading certain values from the column.


问:
Can I mix Ktor with Exposed?
I am writing a service using Ktor and Exposed ORM which apparently isn't async. I am coming from the Python world and back there using a blocking ORM with a async IO library is a sin as it may block all users in thread.
Does the same rule apply in Kotlin? Am I creating a bad architecture?</p>

答:
There is coroutine support in Exposed.

Please read the documentation:

https://github.com/JetBrains/Exposed/wiki/Transactions#working-with-coroutines

Title: Can I mix Ktor with Exposed?


问:
How do I grab an element with jQuery without a way to reference it via class, ID, etc
I have a table like so:

```<code><table>
<thead>
    <tr>
        <th>Hostname</th>
        <th>Action</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>127.0.0.1</td>
        <td><a name="delete" onclick="remove_host('127.0.0.1')">Remove</a></td>
    </tr>
    <tr>
        <td>127.0.0.2</td>
        <td><a name="delete" onclick="remove_host('127.0.0.2')">Remove</a></td>
    </tr>
    <tr>
        <td>127.0.0.3</td>
        <td><a name="delete" onclick="remove_host('127.0.0.3')">Remove</a></td>
    </tr>
</tbody>
</code>```

What I'm trying to do is, when a user clicks on Remove, that the link is replaced with one of those loading images so the user can't repeatedly hit the link.

How do I get the a element, so to speak, so I can set the HTML accordingly with jQuery?

On other parts of the site, I'm able to attach a rel="host-1" (or similar) to the link, so I can easily reference it to change out the HTML.

答:
You can use the attribute selector to select based upon name of the

Also, you can use one() so the handler only fires once.

```<code>$("a[name='delete']").one("click", function(){
   $(this).html("Doing something...")
});
</code>```

Example on jsfiddle

side note, just replacing with.html() will not remove the inline js, you could use .replaceWith() to completely remove the

```<code>$("a[name='delete']").one("click", function() {
    $(this).replaceWith($("<img/>").attr({src: "http://placekitten.com/g/50/50"}))
});
</code>```

Example on jsfiddle

Body:
I have a table like so:

        Hostname
        Action

        127.0.0.1
        Remove

        127.0.0.2
        Remove

        127.0.0.3
        Remove

What I'm trying to do is, when a user clicks on Remove, that the link is replaced with one of those loading images so the user can't repeatedly hit the link.

How do I get the a element, so to speak, so I can set the HTML accordingly with jQuery?

On other parts of the site, I'm able to attach a rel="host-1" (or similar) to the link, so I can easily reference it to change out the HTML.

Body:
You can use the attribute selector to select based upon name of the <a/>

Also, you can use one() so the handler only fires once.

$("a[name='delete']").one("click", function(){
   $(this).html("Doing something...")
});

Example on jsfiddle

side note, just replacing with.html() will not remove the inline js, you could use .replaceWith() to completely remove the <a/>

$("a[name='delete']").one("click", function() {
    $(this).replaceWith($("<img/>").attr({src: "http://placekitten.com/g/50/50"}))
});

Example on jsfiddle


问:
Android Studio does not resolve androidTestImplementation dependencies in custom project layout
I have a project which uses a non-standard source folder layout like this:

```<code>sourceSets {
    androidTest {
        manifest.srcFile "/myproject/androidTest/AndroidManifest.xml"

        java {
            srcDirs = [
                "/myproject/androidTest/java"
            ]
        }
    }
}
</code>```

Android studio shows the above source folder just fine and also tags it as "androidTest" in the tree. The problem now starts with dependencies like espresso not resolving in any of the tests (class not found in AS) - although they have been properly declared like this:

```<code> androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
</code>```

If I change 'androidTestImplementation' to just 'implementation' Android Studio recovers and is able to resolve the dependencies (but I do not want to add test dependencies to my implementation scope!)

Is this just a bug in Android Studio 3.2.1 or is there a bug in my setup?

答:
Had the same problem. And accidentally found solution...

Just use brackets... so in your case it is:

```<code>androidTestImplementation('com.android.support.test.espresso:espresso-core:3.0.2')
</code>```

Body:
I have a project which uses a non-standard source folder layout like this:

sourceSets {
    androidTest {
        manifest.srcFile "/myproject/androidTest/AndroidManifest.xml"

        java {
            srcDirs = [
                "/myproject/androidTest/java"
            ]
        }
    }
}

Android studio shows the above source folder just fine and also tags it as "androidTest" in the tree. The problem now starts with dependencies like espresso not resolving in any of the tests (class not found in AS) - although they have been properly declared like this:

 androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

If I change 'androidTestImplementation' to just 'implementation' Android Studio recovers and is able to resolve the dependencies (but I do not want to add test dependencies to my implementation scope!)

Is this just a bug in Android Studio 3.2.1 or is there a bug in my setup?

Body:
Had the same problem. And accidentally found solution...

Just use brackets... so in your case it is:

androidTestImplementation('com.android.support.test.espresso:espresso-core:3.0.2')


问:
How to search records in text box after triggering enter button in Angularjs?
In this code, when I type the record name it is searching in text box, I need to search the record when I type and click the enter button it should search the record name.</p>

```<code><input type="text" class="form-control" name="search" placeholder="Enter keyword to search" ng-model="Google" style="background-color:#5b2c2c;color:white;">
<table  class="table" border="1" style="margin:0;margin-left:90px;background-color:white;width:80%;border:5px solid green">
   <thead>
      <tr>
         <th><a>Google</a></th>
         <th><a>Facebook</a></th>
         <th><a>Twitter</a></th>
         <th><a>Yahoo</a></th>
      </tr>
   </thead>
   <tbody>
      <tr ng-repeat="record in collection | filter:Google" ng-class-even="'stripped'">
         <td>{{record.Google}}</td>
         <td>{{record.Facebook}}</td>
         <td>{{record.Twitter}}</td>
         <td>{{record.Yahoo}}</td>
      </tr>
   </tbody>
</table>

<script>
 var app = angular.module('myapp', []);
 app.controller('myctrl', function($scope) {
     $scope.collection = [{
             Google: 'Dhoni',
             Facebook: 'Simla',
             Twitter: '5000'
         },
         {
             Google: 'Kohli',
             Facebook: 'Manali',
             Twitter: '15000'
         },
         {
             Google: 'Virat',
             Facebook: 'Rajasthan',
             Twitter: '35000'
         },
         {
             Google: 'Yuvraj',
             Facebook: 'Kerala',
             Twitter: '35000'
         },
         {
             Google: 'Singh',
             Facebook: 'Mysore',
             Twitter: '35000'
         },
         {
             Google: 'Murali',
             Facebook: 'OOTY',
             Twitter: '20000'
         },
         {
             Google: 'Vijay',
             Facebook: 'Goa',
             Twitter: '20000'
         }
     ];
 });
</script>
</code>```

答:
```<code><input type="text" ng-model="searchText" ng-keyPress="filterbyKeyword($event)" placeholder="Enter keyword to search" />

$scope.filterbyKeyword=function(event)
{
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if(keycode=='13')
    {
        //your code
    }
}
</code>```

Body:
In this code, when I type the record name it is searching in text box, I need to search the record when I type and click the enter button it should search the record name.

<input type="text" class="form-control" name="search" placeholder="Enter keyword to search" ng-model="Google" style="background-color:#5b2c2c;color:white;">

         Google
         Facebook
         Twitter
         Yahoo

         {{record.Google}}
         {{record.Facebook}}
         {{record.Twitter}}
         {{record.Yahoo}}


问:
Removing fields from struct or hiding them in JSON Response
I've created an API in Go that, upon being called, performs a query, creates an instance of a struct, and then encodes that struct as JSON before sending back to the caller.  I'd now like to allow the caller to be able to select the specific fields they would like returned by passing in a "fields" GET parameter.

This means depending on the fields value(s), my struct would change.  Is there any way to remove fields from a struct?  Or at least hide them in the JSON response dynamically?  (Note: Sometimes I have empty values so the JSON omitEmpty tag will not work here)  If neither of these are possible, is there a suggestion on a better way to handle this?

A smaller version of the structs I'm using are below:

```<code>type SearchResult struct {
    Date        string      `json:"date"`
    IdCompany   int         `json:"idCompany"`
    Company     string      `json:"company"`
    IdIndustry  interface{} `json:"idIndustry"`
    Industry    string      `json:"industry"`
    IdContinent interface{} `json:"idContinent"`
    Continent   string      `json:"continent"`
    IdCountry   interface{} `json:"idCountry"`
    Country     string      `json:"country"`
    IdState     interface{} `json:"idState"`
    State       string      `json:"state"`
    IdCity      interface{} `json:"idCity"`
    City        string      `json:"city"`
} //SearchResult

type SearchResults struct {
    NumberResults int            `json:"numberResults"`
    Results       []SearchResult `json:"results"`
} //type SearchResults
</code>```

I then encode and output the response like so:

```<code>err := json.NewEncoder(c.ResponseWriter).Encode(&msg)
</code>```

答:
I created this function to convert struct to JSON string by ignoring some fields. Hope it will help.

```<code>func GetJSONString(obj interface{}, ignoreFields ...string) (string, error) {
    toJson, err := json.Marshal(obj)
    if err != nil {
        return "", err
    }

    if len(ignoreFields) == 0 {
        return string(toJson), nil
    }

    toMap := map[string]interface{}{}
    json.Unmarshal([]byte(string(toJson)), &toMap)

    for _, field := range ignoreFields {
        delete(toMap, field)
    }

    toJson, err = json.Marshal(toMap)
    if err != nil {
        return "", err
    }
    return string(toJson), nil
}
</code>```

Example: https://play.golang.org/p/nmq7MFF47Gp

Body:
I've created an API in Go that, upon being called, performs a query, creates an instance of a struct, and then encodes that struct as JSON before sending back to the caller.  I'd now like to allow the caller to be able to select the specific fields they would like returned by passing in a "fields" GET parameter.

This means depending on the fields value(s), my struct would change.  Is there any way to remove fields from a struct?  Or at least hide them in the JSON response dynamically?  (Note: Sometimes I have empty values so the JSON omitEmpty tag will not work here)  If neither of these are possible, is there a suggestion on a better way to handle this?

A smaller version of the structs I'm using are below:

type SearchResult struct {
    Date        string      `json:"date"`
    IdCompany   int         `json:"idCompany"`
    Company     string      `json:"company"`
    IdIndustry  interface{} `json:"idIndustry"`
    Industry    string      `json:"industry"`
    IdContinent interface{} `json:"idContinent"`
    Continent   string      `json:"continent"`
    IdCountry   interface{} `json:"idCountry"`
    Country     string      `json:"country"`
    IdState     interface{} `json:"idState"`
    State       string      `json:"state"`
    IdCity      interface{} `json:"idCity"`
    City        string      `json:"city"`
} //SearchResult

type SearchResults struct {
    NumberResults int            `json:"numberResults"`
    Results       []SearchResult `json:"results"`
} //type SearchResults

I then encode and output the response like so:

err := json.NewEncoder(c.ResponseWriter).Encode(&msg)

Body:
I created this function to convert struct to JSON string by ignoring some fields. Hope it will help.

func GetJSONString(obj interface{}, ignoreFields ...string) (string, error) {
    toJson, err := json.Marshal(obj)
    if err != nil {
        return "", err
    }

    if len(ignoreFields) == 0 {
        return string(toJson), nil
    }

    toMap := map[string]interface{}{}
    json.Unmarshal([]byte(string(toJson)), &toMap)

    for _, field := range ignoreFields {
        delete(toMap, field)
    }

    toJson, err = json.Marshal(toMap)
    if err != nil {
        return "", err
    }
    return string(toJson), nil
}

Example: https://play.golang.org/p/nmq7MFF47Gp


问:
How to treat same component as two different components inside same parent [Angular]
I've recently started working on Angular. I'm sorry if I'm asking a wrong question. I've created a stackblitz also. But please let me explain. I've created two custom components from the scratch. One is Timeselector and the other is Monthpicker. Inside Timeselector I'm calling Monthpicker twice. Where Monthpicker is just a collection of 3 input fields (one for arrow symbol in between and two for entering values) which will accept startRange and endRange as input in MM-DD-YYYY format only. Validation being handled by moment.

timeselector.component.html

```<code>Primary range:
<app-monthpicker></app-monthpicker>

Reference range:
<app-monthpicker></app-monthpicker>

<button (click)="onSubmit()">Submit</button>
</code>```

monthpicker.component.html

```<code><div class="wrapper">
  <input type="text" [(ngModel)]="startRange" placeholder="MM-DD-YYYY">
  <input type="text" value="{{arrowSymbol}}" readonly>
  <input type="text" [(ngModel)]="endRange" placeholder="MM-DD-YYYY">
</div>
</code>```

monthpicker.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import moment from 'moment';

@Component({
  ...
})
export class MonthpickerComponent implements OnInit {

  arrowSymbol = String.fromCharCode(parseInt('2794', 16));

  startRange: string;
  endRange: string;

  isRangeValid: boolean;

  dateErrors: Set<string>;

  constructor() { }

  ngOnInit() {
  }

  triggerValidate() {
    this.validate(this.startRange, this.endRange);
  }

  validate(sDate: string, eDate: string) {
    this.isRangeValid=true;
    this.dateErrors = new Set<string>();
    const fromDate = moment(sDate, 'MM-DD-YYYY', true);
    const toDate = moment(eDate, 'MM-DD-YYYY', true);
    if (!fromDate.isValid() || !toDate.isValid()) {
      this.dateErrors.add('Errors.DateIsNotValid');
      this.isRangeValid = false;
    }
    if (fromDate.isAfter(toDate)) {
      this.dateErrors.add('Errors.StartDateMoreThanEndDate');
      this.isRangeValid = false;
    }
    if (this.isRangeValid) {
      console.log("All good!");
      console.log("Primary range: "+this.startRange+" to "+this.endRange);
      console.log("Secondary range: "+this.startRange+" to "+this.endRange)
    }
    console.log(this.dateErrors);
  }
}
</code>```

You can see I've bound the properties to startRange and endRange. I can bind only these two properties because Monthpicker component is one component being called twice. But I want all four values to be validated and printed on console viz. Primary range start and end dates and also for reference range start and end dates. How to create two instances of same component. I've checked this also:

How to inject new instance of same component in Angular2

But I didn't understand that very well. Hope I was able to explain the problem statement. I'm afraid my entire implementation is wrong. Please help me.

答:
Instead of ViewChild, ViewChildren can be used for accessing multiple child components.

Then each child component in the parent component can be validated.

monthpicker.component.ts

Instead of using ViewChild:

```<code>@ViewChildren(MonthpickerComponent)
monthpicker: MonthpickerComponent[];
</code>```

Then on the onSubmit method:

```<code>onSubmit() {
  this.monthpicker.forEach(picker => {
    picker.triggerValidate();
  });
}
</code>```

StackBlitz: https://stackblitz.com/edit/angular-zdt48j?file=src%2Fapp%2Ftimeselector%2Ftimeselector.component.ts

Body:
I've recently started working on Angular. I'm sorry if I'm asking a wrong question. I've created a stackblitz also. But please let me explain. I've created two custom components from the scratch. One is Timeselector and the other is Monthpicker. Inside Timeselector I'm calling Monthpicker twice. Where Monthpicker is just a collection of 3 input fields (one for arrow symbol in between and two for entering values) which will accept startRange and endRange as input in MM-DD-YYYY format only. Validation being handled by moment.

timeselector.component.html

Primary range:
<app-monthpicker></app-monthpicker>

Reference range:
<app-monthpicker></app-monthpicker>

<button (click)="onSubmit()">Submit</button>

monthpicker.component.html

  <input type="text" [(ngModel)]="startRange" placeholder="MM-DD-YYYY">
  <input type="text" value="{{arrowSymbol}}" readonly>
  <input type="text" [(ngModel)]="endRange" placeholder="MM-DD-YYYY">

monthpicker.component.ts

import { Component, OnInit } from '@angular/core';
import moment from 'moment';

@Component({
  ...
})
export class MonthpickerComponent implements OnInit {

  arrowSymbol = String.fromCharCode(parseInt('2794', 16));

  startRange: string;
  endRange: string;

  isRangeValid: boolean;

  dateErrors: Set<string>;

  constructor() { }

  ngOnInit() {
  }

  triggerValidate() {
    this.validate(this.startRange, this.endRange);
  }

  validate(sDate: string, eDate: string) {
    this.isRangeValid=true;
    this.dateErrors = new Set<string>();
    const fromDate = moment(sDate, 'MM-DD-YYYY', true);
    const toDate = moment(eDate, 'MM-DD-YYYY', true);
    if (!fromDate.isValid() || !toDate.isValid()) {
      this.dateErrors.add('Errors.DateIsNotValid');
      this.isRangeValid = false;
    }
    if (fromDate.isAfter(toDate)) {
      this.dateErrors.add('Errors.StartDateMoreThanEndDate');
      this.isRangeValid = false;
    }
    if (this.isRangeValid) {
      console.log("All good!");
      console.log("Primary range: "+this.startRange+" to "+this.endRange);
      console.log("Secondary range: "+this.startRange+" to "+this.endRange)
    }
    console.log(this.dateErrors);
  }
}

You can see I've bound the properties to startRange and endRange. I can bind only these two properties because Monthpicker component is one component being called twice. But I want all four values to be validated and printed on console viz. Primary range start and end dates and also for reference range start and end dates. How to create two instances of same component. I've checked this also:

How to inject new instance of same component in Angular2

But I didn't understand that very well. Hope I was able to explain the problem statement. I'm afraid my entire implementation is wrong. Please help me.

Body:
Instead of ViewChild, ViewChildren can be used for accessing multiple child components.

Then each child component in the parent component can be validated.

monthpicker.component.ts

Instead of using ViewChild:

@ViewChildren(MonthpickerComponent)
monthpicker: MonthpickerComponent[];

Then on the onSubmit method:

onSubmit() {
  this.monthpicker.forEach(picker => {
    picker.triggerValidate();
  });
}

StackBlitz: https://stackblitz.com/edit/angular-zdt48j?file=src%2Fapp%2Ftimeselector%2Ftimeselector.component.ts


问:
Detecting when ListView scrollbar reaches the bottom
How do I know when the WinForms ListView scrollbar reaches it's bottom?

When this happens, I want the listview to be populated with more data (which is endless in theory in my case).

The OnScroll event gives me the scroll value from the top, but I have no way of knowing if the user can scroll any further or not.

答:
I'm not able to answer your question directly, but from your description, it sounds like you really want to look into using the virtual mode of a list view for managing a large dataset.

http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.virtualmode.aspx


问:
Global CONSTANTS. Any problem using them?
I've been programming for over 6 years now and i've always avoided using global variables because there is always another way around the problems.

Today, i work on a (big) project, we want to use a dictionnary of mathematical CONSTANTS what will never be modified anywhere. The only problem i seem to find with globals on internet is the fact that if someone overwrites one it could bug out the whole project. But as mine are constants this problem doesnt apply.

(as a second security to avoid people creating a variable with the same name as one of the constants i will probably pack them all in a single global struct)

Does anyone know of problems that still happend using global constants?

Thanks for your answers! :)

答:
In MATLAB, your best bet for mathematical constants is to define a class with properties that have the Constant attribute. This is described in the doc here, and here's the leading example from that page:

```<code>classdef NamedConst
   properties (Constant)
      R = pi/180
      D = 1/NamedConst.R
      AccCode = '0145968740001110202NPQ'
      RN = rand(5)
   end
end
</code>```

This way, the values cannot be overridden. (Note that there's something a little perhaps unexpected in this example - the value of the property RN changes each time the class is loaded! I personally wouldn't write code like that...)

Body:
In MATLAB, your best bet for mathematical constants is to define a class with properties that have the Constant attribute. This is described in the doc here, and here's the leading example from that page:

classdef NamedConst
   properties (Constant)
      R = pi/180
      D = 1/NamedConst.R
      AccCode = '0145968740001110202NPQ'
      RN = rand(5)
   end
end

This way, the values cannot be overridden. (Note that there's something a little perhaps unexpected in this example - the value of the property RN changes each time the class is loaded! I personally wouldn't write code like that...)


问:
Adding TouchableHighlight or Touchableopacity to table row with dynamically generated cells
I'm trying to add TouchableHighlight to my table so that I can select a row and thereafter edit the row data elsewhere. I have a button to delete the row and have adapted the example 4 in the table component Readme React Native Table - This, however, is moving all my row data to the first col.</p>

```<code>import React, { Component } from 'react';
import { StyleSheet, View, Text, TouchableOpacity, Alert } from 'react-native';
import { Table, TableWrapper, Row, Cell } from 'react-native-table-component';

export default class ExampleFour extends Component {
  constructor(props) {
    super(props);
    this.state = {
      tableHead: ['Head', 'Head2', 'Head3', 'Head4'],
      tableData: [
        ['1', '2', '3', '4'],
        ['a', 'b', 'c', 'd'],
        ['1', '2', '3', '4'],
        ['a', 'b', 'c', 'd']
      ]
    }
  }

  _alertIndex(index) {
    Alert.alert(`This is row ${index + 1}`);
  }

selectCartItem(item) {
    console.log('Select Cart Item');
     console.log(item);
}

  render() {
    const state = this.state;
    const element = (data, index) => (
      <TouchableOpacity onPress={() => this._alertIndex(index)}>
        <View style={styles.btn}>
          <Text style={styles.btnText}>button</Text>
        </View>
      </TouchableOpacity>
    );

    return (
      <View style={styles.container}>
        <Table borderStyle={{borderColor: 'transparent'}}>
          <Row data={state.tableHead} style={styles.head} textStyle={styles.text}/>
          {
            state.tableData.map((rowData, index) => (
              <TableWrapper key={index} style={styles.row}>
 <TouchableOpacity onPress={this.selectCartItem.bind(this, this.index)}>
                {
                  rowData.map((cellData, cellIndex) => (
                    <Cell key={cellIndex} data={cellIndex === 3 ? element(cellData, index) :       cellData} textStyle={styles.text}/>
                  ))
                }
</TouchableOpacity>
              </TableWrapper>
            ))
          }
        </Table>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 16, paddingTop: 30, backgroundColor: '#fff' },
  head: { height: 40, backgroundColor: '#808B97' },
  text: { margin: 6 },
  row: { flexDirection: 'row', backgroundColor: '#FFF1C1' },
  btn: { width: 58, height: 18, backgroundColor: '#78B7BB',  borderRadius: 2 },
  btnText: { textAlign: 'center', color: '#fff' }
});
</code>```

答:
For anyone with a similar issue, I moved the TouchableOpacity to within the row data mapping and added the key value. Also added different stying to show which row is selected.</p>

```<code>rowData.map((cellData, cellIndex) => (
     <TouchableOpacity key={cellIndex} style={this.rowStyle(index)} onPress={() => this.selectCartItem(cellData, index)}>
         <Cell key={cellIndex} data={cellIndex === 4 ? this.voidElement(cellData, index) : cellData} textStyle={styles.text} />
     </TouchableOpacity>
 ))

selectCartItem(item, index) {
    this.setState({selectedTableItem : index })
}

rowStyle(selected) {

    if (selected == this.state.selectedTableItem) {
        return {
            flex: 1,
            backgroundColor: '#ff0000',
        }
    } else {
        return {
            flex: 1,
        }
    }

}
</code>```

Body:
I'm trying to add TouchableHighlight to my table so that I can select a row and thereafter edit the row data elsewhere. I have a button to delete the row and have adapted the example 4 in the table component Readme React Native Table - This, however, is moving all my row data to the first col.

import React, { Component } from 'react';
import { StyleSheet, View, Text, TouchableOpacity, Alert } from 'react-native';
import { Table, TableWrapper, Row, Cell } from 'react-native-table-component';

export default class ExampleFour extends Component {
  constructor(props) {
    super(props);
    this.state = {
      tableHead: ['Head', 'Head2', 'Head3', 'Head4'],
      tableData: [
        ['1', '2', '3', '4'],
        ['a', 'b', 'c', 'd'],
        ['1', '2', '3', '4'],
        ['a', 'b', 'c', 'd']
      ]
    }
  }

  _alertIndex(index) {
    Alert.alert(`This is row ${index + 1}`);
  }

selectCartItem(item) {
    console.log('Select Cart Item');
     console.log(item);
}

  render() {
    const state = this.state;
    const element = (data, index) => (
      <TouchableOpacity onPress={() => this._alertIndex(index)}>
        <View style={styles.btn}>
          <Text style={styles.btnText}>button</Text>
        </View>
      </TouchableOpacity>
    );

    return (
      <View style={styles.container}>

          <Row data={state.tableHead} style={styles.head} textStyle={styles.text}/>
          {
            state.tableData.map((rowData, index) => (
              <TableWrapper key={index} style={styles.row}>
 <TouchableOpacity onPress={this.selectCartItem.bind(this, this.index)}>
                {
                  rowData.map((cellData, cellIndex) => (
                    <Cell key={cellIndex} data={cellIndex === 3 ? element(cellData, index) :       cellData} textStyle={styles.text}/>
                  ))
                }
</TouchableOpacity>
              </TableWrapper>
            ))
          }

      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 16, paddingTop: 30, backgroundColor: '#fff' },
  head: { height: 40, backgroundColor: '#808B97' },
  text: { margin: 6 },
  row: { flexDirection: 'row', backgroundColor: '#FFF1C1' },
  btn: { width: 58, height: 18, backgroundColor: '#78B7BB',  borderRadius: 2 },
  btnText: { textAlign: 'center', color: '#fff' }
});

Body:
For anyone with a similar issue, I moved the TouchableOpacity to within the row data mapping and added the key value. Also added different stying to show which row is selected.

rowData.map((cellData, cellIndex) => (
     <TouchableOpacity key={cellIndex} style={this.rowStyle(index)} onPress={() => this.selectCartItem(cellData, index)}>
         <Cell key={cellIndex} data={cellIndex === 4 ? this.voidElement(cellData, index) : cellData} textStyle={styles.text} />
     </TouchableOpacity>
 ))

selectCartItem(item, index) {
    this.setState({selectedTableItem : index })
}

rowStyle(selected) {

    if (selected == this.state.selectedTableItem) {
        return {
            flex: 1,
            backgroundColor: '#ff0000',
        }
    } else {
        return {
            flex: 1,
        }
    }

}


问:
Exporting Matrixes from Ruby Arrays and Visualizing
So, if you've ever stumbled upon the idea of visualizing an matrix, and you're in Ruby, I'm not really sure how you would go about doing this.

There are a few libraries that allow arrays of data to be ploted. But I'm looking into something rather different than what I've ever done before. If you look closely on the image I have an extremely large matrix of data that I wish to see on a different program. There is roughly 1 thousand rows and about a hundred columns.

I believe the reason why I've been having such a problem with this is not necessarily for anything that I can't do but because of what I lack and what I don't know.

I'm writing because there should be an easier solution to visualizing this. I've tried spreadsheets in CSV files and in OpenOffice .ods files. But they are inadequate for this despite being great for organizing multiple data sets.

Now, concerning the matrix. For each row, there are time periods represented by letters. For each of these time periods the first element in these arrays there are prices where time has been before.

```<code>prices = [[9234.5, ['k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's']], [9234.0, ['a', 'b', 'c', 'd']], (...) ]
</code>```

I appreciate any input you might have on this. I hope to find anyone experienced on this matter because I am  definitely pretty bad at front-end and data visualization.

https://i.stack.imgur.com/5UIWa.png

答:
If my right brain is serving me well, you want to approximate the image layout you have provided with the data in the array you have provided. If so, it could be as simple as this:

```<code> prices.each { |row| print "#{row}\n" }
</code>```

All this is doing is taking each outer array element and printing it on its own row.

The result of the above looks like this:

[9234.5, ["k", "l", "m", "n", "o", "p", "q", "r", "s"]]

  [9234.0, ["a", "b", "c", "d"]]

Now, you can (and may very well want to) spend some time writing up something more sophisticated for each row, for example using an inner #each to go through each of the inner elements and print them in some sort of format (such as centered in five spaces, with a vertical bar on the right). But the basic idea is to print each of the outer elements on its own line. Each one of those is a row in your image.

Body:
So, if you've ever stumbled upon the idea of visualizing an matrix, and you're in Ruby, I'm not really sure how you would go about doing this.

There are a few libraries that allow arrays of data to be ploted. But I'm looking into something rather different than what I've ever done before. If you look closely on the image I have an extremely large matrix of data that I wish to see on a different program. There is roughly 1 thousand rows and about a hundred columns.

I believe the reason why I've been having such a problem with this is not necessarily for anything that I can't do but because of what I lack and what I don't know.

I'm writing because there should be an easier solution to visualizing this. I've tried spreadsheets in CSV files and in OpenOffice .ods files. But they are inadequate for this despite being great for organizing multiple data sets.

Now, concerning the matrix. For each row, there are time periods represented by letters. For each of these time periods the first element in these arrays there are prices where time has been before.

prices = [[9234.5, ['k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's']], [9234.0, ['a', 'b', 'c', 'd']], (...) ]

I appreciate any input you might have on this. I hope to find anyone experienced on this matter because I am  definitely pretty bad at front-end and data visualization.

https://i.stack.imgur.com/5UIWa.png

Body:
If my right brain is serving me well, you want to approximate the image layout you have provided with the data in the array you have provided. If so, it could be as simple as this:

 prices.each { |row| print "#{row}\n" }

All this is doing is taking each outer array element and printing it on its own row.

The result of the above looks like this:

[9234.5, ["k", "l", "m", "n", "o", "p", "q", "r", "s"]]

  [9234.0, ["a", "b", "c", "d"]]

Now, you can (and may very well want to) spend some time writing up something more sophisticated for each row, for example using an inner #each to go through each of the inner elements and print them in some sort of format (such as centered in five spaces, with a vertical bar on the right). But the basic idea is to print each of the outer elements on its own line. Each one of those is a row in your image.


问:
Making Model class from JSON
Here I am trying to make the model class of this JSON

```<code>{
  "debit": 1,
  "train": {
    "number": "14207",
    "name": "PADMAVAT EXP",
    "days": [
      {
        "code": "MON",
        "runs": "Y"
      },
      {
        "code": "TUE",
        "runs": "Y"
      },
      {
        "code": "WED",
        "runs": "Y"
      },
      {
        "code": "THU",
        "runs": "Y"
      },
      {
        "code": "FRI",
        "runs": "Y"
      },
      {
        "code": "SAT",
        "runs": "Y"
      },
      {
        "code": "SUN",
        "runs": "Y"
      }
    ],
    "classes": [
      {
        "code": "2A",
        "available": "Y",
        "name": "SECOND AC"
      },
      {
        "code": "3E",
        "available": "N",
        "name": "3rd AC ECONOMY"
      },
      {
        "code": "3A",
        "available": "Y",
        "name": "THIRD AC"
      },
      {
        "code": "2S",
        "available": "N",
        "name": "SECOND SEATING"
      },
      {
        "code": "CC",
        "available": "N",
        "name": "AC CHAIR CAR"
      },
      {
        "code": "SL",
        "available": "Y",
        "name": "SLEEPER CLASS"
      },
      {
        "code": "FC",
        "available": "N",
        "name": "FIRST CLASS"
      },
      {
        "code": "1A",
        "available": "Y",
        "name": "FIRST AC"
      }
    ]
  },
  "response_code": 200
}
</code>```

And I try this
First I create two Integer variable name response_code and debit(because inside "{" and "}" are key and value pairs)
Then I create on array List and one List named as train and classes which represents train list and classes array in json. Still Not Working

```<code>public class NewTrain {
    @SerializedName("response_code")
    private int response_code;
    @SerializedName("debit")
    private int debit;
    @SerializedName("train")
    private List<TrainClass> train= null;
   @SerializedName("classes")
    private ArrayList<classes> arrayList = null;

    public int getResponse_code() {
        return response_code;
    }

    public void setResponse_code(int response_code) {
        this.response_code = response_code;
    }

    public int getDebit() {
        return debit;
    }

    public void setDebit(int debit) {
        this.debit = debit;
    }

    public List<TrainClass> getTrain() {
        return train;
    }

    public void setTrain(List<TrainClass> train) {
        this.train = train;
    }

    public ArrayList<classes> getArrayList() {
        return arrayList;
    }

    public void setArrayList(ArrayList<classes> arrayList) {
        this.arrayList = arrayList;
    }
}

public class TrainClass
 @SerializedName("number")
    private int number;
    @SerializedName("name")
    private String name;
    @SerializedName("days")
    private List<Day> dayList = null;

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Day> getDayList() {
        return dayList;
    }

    public void setDayList(List<Day> dayList) {
        this.dayList = dayList;
    }
}
public class Day {
    @SerializedName("code")
    private String code;
    @SerializedName("runs")
    private String runs;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getRuns() {
        return runs;
    }

    public void setRuns(String runs) {
        this.runs = runs;
    }

}
public class classes {
    @SerializedName("code")
    private String code;

    @SerializedName("available")
    private String available;

    @SerializedName("name")
    private String name;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getAvailable() {
        return available;
    }

    public void setAvailable(String available) {
        this.available = available;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
</code>```

But instead it is giving Begin Array but was Begin Object at line 1 column 2!!!
Calling API data from server method

```<code> public void Show(View view) {

        MyWebService myWebService = MyWebService.retrofitfortrain.create(MyWebService.class);
        Call<List<NewTrain>>  call = myWebService.getTrainList();
      call.enqueue(new Callback<List<NewTrain>>() {
          @Override
          public void onResponse(Call<List<NewTrain>> call, Response<List<NewTrain>> response) {
              if(response.isSuccessful())
              {
                  for(NewTrain newTrain: response.body()) {
                      t.append(String.valueOf(newTrain.getResponse_code()));
                  }
              }
          }

          @Override
          public void onFailure(Call<List<NewTrain>> call, Throwable t) {
              Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_LONG).show();

          }
      });

    }
</code>```

答:
try this

```<code> export class RootObject {
    debit: number;
    train: Train;
    response_code: number;
}

export interface Train {
    number: string;
    name: string;
    days: Day[];
    classes: ClassModel[];
}
export interface Day {
    code: string;
    runs: string;
}

export interface ClassModel {
    code: string;
    available: string;
    name: string;
}
</code>```

Title: Making Model class from JSON

Body:
Here I am trying to make the model class of this JSON

{
  "debit": 1,
  "train": {
    "number": "14207",
    "name": "PADMAVAT EXP",
    "days": [
      {
        "code": "MON",
        "runs": "Y"
      },
      {
        "code": "TUE",
        "runs": "Y"
      },
      {
        "code": "WED",
        "runs": "Y"
      },
      {
        "code": "THU",
        "runs": "Y"
      },
      {
        "code": "FRI",
        "runs": "Y"
      },
      {
        "code": "SAT",
        "runs": "Y"
      },
      {
        "code": "SUN",
        "runs": "Y"
      }
    ],
    "classes": [
      {
        "code": "2A",
        "available": "Y",
        "name": "SECOND AC"
      },
      {
        "code": "3E",
        "available": "N",
        "name": "3rd AC ECONOMY"
      },
      {
        "code": "3A",
        "available": "Y",
        "name": "THIRD AC"
      },
      {
        "code": "2S",
        "available": "N",
        "name": "SECOND SEATING"
      },
      {
        "code": "CC",
        "available": "N",
        "name": "AC CHAIR CAR"
      },
      {
        "code": "SL",
        "available": "Y",
        "name": "SLEEPER CLASS"
      },
      {
        "code": "FC",
        "available": "N",
        "name": "FIRST CLASS"
      },
      {
        "code": "1A",
        "available": "Y",
        "name": "FIRST AC"
      }
    ]
  },
  "response_code": 200
}

And I try this
First I create two Integer variable name response_code and debit(because inside "{" and "}" are key and value pairs)
Then I create on array List and one List named as train and classes which represents train list and classes array in json. Still Not Working

public class NewTrain {
    @SerializedName("response_code")
    private int response_code;
    @SerializedName("debit")
    private int debit;
    @SerializedName("train")
    private List<TrainClass> train= null;
   @SerializedName("classes")
    private ArrayList<classes> arrayList = null;

    public int getResponse_code() {
        return response_code;
    }

    public void setResponse_code(int response_code) {
        this.response_code = response_code;
    }

    public int getDebit() {
        return debit;
    }

    public void setDebit(int debit) {
        this.debit = debit;
    }

    public List<TrainClass> getTrain() {
        return train;
    }

    public void setTrain(List<TrainClass> train) {
        this.train = train;
    }

    public ArrayList<classes> getArrayList() {
        return arrayList;
    }

    public void setArrayList(ArrayList<classes> arrayList) {
        this.arrayList = arrayList;
    }
}

public class TrainClass
 @SerializedName("number")
    private int number;
    @SerializedName("name")
    private String name;
    @SerializedName("days")
    private List<Day> dayList = null;

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Day> getDayList() {
        return dayList;
    }

    public void setDayList(List<Day> dayList) {
        this.dayList = dayList;
    }
}
public class Day {
    @SerializedName("code")
    private String code;
    @SerializedName("runs")
    private String runs;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getRuns() {
        return runs;
    }

    public void setRuns(String runs) {
        this.runs = runs;
    }

}
public class classes {
    @SerializedName("code")
    private String code;

    @SerializedName("available")
    private String available;

    @SerializedName("name")
    private String name;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getAvailable() {
        return available;
    }

    public void setAvailable(String available) {
        this.available = available;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

But instead it is giving Begin Array but was Begin Object at line 1 column 2!!!
Calling API data from server method

 public void Show(View view) {

        MyWebService myWebService = MyWebService.retrofitfortrain.create(MyWebService.class);
        Call<List<NewTrain>>  call = myWebService.getTrainList();
      call.enqueue(new Callback<List<NewTrain>>() {
          @Override
          public void onResponse(Call<List<NewTrain>> call, Response<List<NewTrain>> response) {
              if(response.isSuccessful())
              {
                  for(NewTrain newTrain: response.body()) {
                      t.append(String.valueOf(newTrain.getResponse_code()));
                  }
              }
          }

          @Override
          public void onFailure(Call<List<NewTrain>> call, Throwable t) {
              Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_LONG).show();

          }
      });

    }

Body:
try this

 export class RootObject {
    debit: number;
    train: Train;
    response_code: number;
}

export interface Train {
    number: string;
    name: string;
    days: Day[];
    classes: ClassModel[];
}
export interface Day {
    code: string;
    runs: string;
}

export interface ClassModel {
    code: string;
    available: string;
    name: string;
}


问:
Newbie trying to use external harddrive to move between devices
Changing MacDevices seems to confuse the RStudio. I want to always have the working directory be a folder on my external hard drive. Any tips?</p>

答:
I think you need to read a bit about .Rproj and how to use them.
R projects are a way to define your working directory and save memory depending on the project you openned. It allow to make different project without getting files together. Another advantage is that if all your data and script are within a directory linked to a Rproject, you can move it around and share it easily.

Here are some information on how to use them.

An other way of thinking could be modification of your .Rprofile so it setwd('where/you/work') at every R session. Some info on how to customize your .Rprofile. Note that there is drawbacks in this options, because your code may become not reproductible when you give it to someone else.


问:
JSF: Absolutely need to put expensive Business Logic inside accessor method. How to avoid calling this expensive BL multiples time
Here is my dilemma, I know in JSF the accessor method will get call mutilple times, therefore I know not to put expensive business logic (like DB access) in accessor method. What if I absolutely have to put business logic into my accessor. What should I do in this case? Below are a high level layout of my dilemma. (Mojarra 2.1, GF 3.1)

```<code><h:dataTable value="#{myBean.comments}" var="item1">
    <h:column>
          #{item1.name} says: #{item1.comment}
          <h:dataTable value="#{myBean.handleReplies(item1)}" var="item2">
               <h:column>
                   #{item2.name} replies: #{item2.comment}
               </h:column>
          </h:dataTable>
    </h:column>
</h:dataTable>

@ManagedBean
@ViewScoped
public void myBean(){
    private List<Comment> comments;

    @EJB
    private MyEJB myEJB;

    @PostConstruct
    public void init(){
        comments = myEJB.getAllComments();
    }

    //getters and setters for List<Comment> comments

    public List<Comment> handleReplies(Comment comment){
         //Return a List of replies of the comment
         return myEJB.getRepliesFromComment(comment);
    }
}
</code>```

As you can see, the inner dataTable take in the item of the outer dataTable to generate its List. Is there a way for somehow stop handleReplies() to be called multiple times, since this accessor method access DB.

答:
How about using a HashMap to create a view-scoped cache?

Something like:

```<code>private Map<Comment, List<Comment>> replies = new HashMap<Comment, List<Comment>>();

public List<Comment> handleReplies(Comment comment){
    if (!replies.containsKey(comment)) {
        replies.put(comment, myEJB.getRepliesFromComment(comment));
    }

    return replies.get(comment);
}
</code>```

This way, your view-scoped bean store previous request results, and returns them if the request has already been done. If it hasn't, the request is made. In the end, no duplicate request!

Body:
Here is my dilemma, I know in JSF the accessor method will get call mutilple times, therefore I know not to put expensive business logic (like DB access) in accessor method. What if I absolutely have to put business logic into my accessor. What should I do in this case? Below are a high level layout of my dilemma. (Mojarra 2.1, GF 3.1)

<h:dataTable value="#{myBean.comments}" var="item1">
    <h:column>
          #{item1.name} says: #{item1.comment}
          <h:dataTable value="#{myBean.handleReplies(item1)}" var="item2">
               <h:column>
                   #{item2.name} replies: #{item2.comment}
               </h:column>
          </h:dataTable>
    </h:column>
</h:dataTable>

@ManagedBean
@ViewScoped
public void myBean(){
    private List<Comment> comments;

    @EJB
    private MyEJB myEJB;

    @PostConstruct
    public void init(){
        comments = myEJB.getAllComments();
    }

    //getters and setters for List<Comment> comments

    public List<Comment> handleReplies(Comment comment){
         //Return a List of replies of the comment
         return myEJB.getRepliesFromComment(comment);
    }
}

As you can see, the inner dataTable take in the item of the outer dataTable to generate its List. Is there a way for somehow stop handleReplies() to be called multiple times, since this accessor method access DB.

Body:
How about using a HashMap to create a view-scoped cache?

Something like:

private Map<Comment, List<Comment>> replies = new HashMap<Comment, List<Comment>>();

public List<Comment> handleReplies(Comment comment){
    if (!replies.containsKey(comment)) {
        replies.put(comment, myEJB.getRepliesFromComment(comment));
    }

    return replies.get(comment);
}

This way, your view-scoped bean store previous request results, and returns them if the request has already been done. If it hasn't, the request is made. In the end, no duplicate request!


问:
Convert object of objects to array
I work on a Angular Project and I have a little issue with an object..

I have an object with objects inside :

```<code>P3E051V:{
    lot: "P3E051V"
    quantite: 5400
},
P3E052V:{
    lot: "P3E052V"
    quantite: 5400
},
P3E054V:{
    lot: "P3E054V"
    quantite: 10800
}
</code>```

What I would like to do is to display a table like this :
image of the table

But I can't loop on an object with *ngFor.
I tried to use Object.entries(myObject) but it doesn't work.

Anyone have an idea to solve this ?

Thanks

答:
```<code>const inputObject = {
  P3E051V:{
    lot: "P3E051V",
    quantite: 5400
  },
  P3E052V:{
    lot: "P3E052V",
    quantite: 5400
  },
  P3E054V:{
    lot: "P3E054V",
    quantite: 10800
  }
}

const outputObjectArray = Object.entries(inputObject).map(entry=>{ return entry[1]});
console.log(outputObjectArray);
</code>```

Title: Convert object of objects to array

Body:
I work on a Angular Project and I have a little issue with an object..

I have an object with objects inside :

P3E051V:{
    lot: "P3E051V"
    quantite: 5400
},
P3E052V:{
    lot: "P3E052V"
    quantite: 5400
},
P3E054V:{
    lot: "P3E054V"
    quantite: 10800
}

What I would like to do is to display a table like this :
image of the table

But I can't loop on an object with *ngFor.
I tried to use Object.entries(myObject) but it doesn't work.

Anyone have an idea to solve this ?

Thanks


问:
Is the values in a capacity declared arrayList null?
String[] arr = new String[10];
This creates an array with 10 elements all set to null. The first null element can be accessed with arr[0]

ArrayList<String> arr2 = new ArrayList<String>[10];
This creates an array with capacity of 10 but apparently no elements. Is this why you cannot use arr2.get(0) which returns an error? Because there are no elements present?

答:
An ArrayList is a class and an object to the class should be created using a constructor

ArrayList<String>[10] produces an error: cannot create array with '<>' error

Using constructor, the ArrayList is constructed as ArrayList<String>(10);

It is to be noted that this statement creates an Empty ArrayList of initial size 10.

The ArrayList only gets populated when you push values into it.

Refer the following for more understanding:

[1] [2] [3]


问:
Counter in double loop with counting in both internal and external for
I would like to know if there is a well-known formula for the following way of counting:

```<code>count = 0
for i in range(n):
   for j in range(m):
      count = count + 1
   count = count + 10
</code>```

Many thanks in advance,

Cayo

EDIT 1:

Thanks Ernest, you are right, but that is not really the problem. Sorry, I was not clear enough, let me explain better my problem. I don't just want to count, I need use this counter inside the inner loop. I have a 2D flatten array and I want to access just a sub-2D-region of this array. So, actually, what I am doing is:

```<code>count = 0
for i in range(n):
   for j in range(m):
      big_flatten_array(count) = value
      count = count + 1
   count = count + 10
</code>```

EDIT 2:
It doesn't work just using

```<code>count = i * 10 + j
</code>```

Try checking the values:

```<code>count = 0
for i in range(3):
   for j in range():
      k = i * 2 + j
      vec[k] = count
      vec2[k] = i * 10 + j
      count = count + 1
   count = count + 10
</code>```

And you will see the vec and vec2 are not the same...

答:
Let me try. If I understand correctly you just need current (not final) value of count inside the loop. So this should do:

# In the inner loop
count = i * 10 + j
```

Body:
I would like to know if there is a well-known formula for the following way of counting:

count = 0
for i in range(n):
   for j in range(m):
      count = count + 1
   count = count + 10

Many thanks in advance,

Cayo

EDIT 1:

Thanks Ernest, you are right, but that is not really the problem. Sorry, I was not clear enough, let me explain better my problem. I don't just want to count, I need use this counter inside the inner loop. I have a 2D flatten array and I want to access just a sub-2D-region of this array. So, actually, what I am doing is:

count = 0
for i in range(n):
   for j in range(m):
      big_flatten_array(count) = value
      count = count + 1
   count = count + 10

EDIT 2:
It doesn't work just using

count = i * 10 + j

Try checking the values:

count = 0
for i in range(3):
   for j in range():
      k = i * 2 + j
      vec[k] = count
      vec2[k] = i * 10 + j
      count = count + 1
   count = count + 10

And you will see the vec and vec2 are not the same...


问:
Regular expression to extract first word + first character of all following words
I am (newbie) using R and regular Regular expression to write the regex for manipulating strings in a data.frame column. My data look like this in R:

```<code>c1
Peter Parker
Hawk & Dove
J Jonah Jameson
3JPX spo
Bruce Wayne
</code>```

What I am trying to get is 2nd column "c2" that consists of the following strings:

```<code>c2
PeterP
Hawk&D
JJJ
3JPXs
BruceW
</code>```

Basically I want the entire first word of the string (regardless of length) and the first alphanumeric element of every word after. I have not been able to find any function or logic for this. Is it possible to do so with regex?

Thanks in Advance

答:
Though not particularly a regex solution but a different approach could be to get bring data in long format by separating each word, get first word as it is and take only first character from remaining of the words and paste them.

```<code>library(dplyr)

df %>%
  group_by(row = row_number()) %>%
  tidyr::separate_rows(c1, sep = "\\s+") %>%
  summarise(c2 = paste0(first(c1) , paste0(substr(c1[-1], 1, 1), collapse = "")),
            c1 = paste(c1, collapse = " ")) %>%
  select(c1, c2, -row)

#   c1              c2
#  <chr>           <chr>
#1 Peter Parker    PeterP
#2 Hawk & Dove     Hawk&D
#3 J Jonah Jameson JJJ
#4 3JPX spo        3JPXs
#5 Bruce Wayne     BruceW
</code>```

data

```<code>df <- structure(list(c1 = c("Peter Parker", "Hawk & Dove", "J Jonah Jameson",
"3JPX spo", "Bruce Wayne")), row.names = c(NA, -5L), class = "data.frame")
</code>```

Body:
I am (newbie) using R and regular Regular expression to write the regex for manipulating strings in a data.frame column. My data look like this in R:

c1
Peter Parker
Hawk & Dove
J Jonah Jameson
3JPX spo
Bruce Wayne

What I am trying to get is 2nd column "c2" that consists of the following strings:

c2
PeterP
Hawk&D
JJJ
3JPXs
BruceW

Basically I want the entire first word of the string (regardless of length) and the first alphanumeric element of every word after. I have not been able to find any function or logic for this. Is it possible to do so with regex?

Thanks in Advance

Body:
Though not particularly a regex solution but a different approach could be to get bring data in long format by separating each word, get first word as it is and take only first character from remaining of the words and paste them.

library(dplyr)

df %>%
  group_by(row = row_number()) %>%
  tidyr::separate_rows(c1, sep = "\\s+") %>%
  summarise(c2 = paste0(first(c1) , paste0(substr(c1[-1], 1, 1), collapse = "")),
            c1 = paste(c1, collapse = " ")) %>%
  select(c1, c2, -row)

#   c1              c2
#  <chr>           <chr>
#1 Peter Parker    PeterP
#2 Hawk & Dove     Hawk&D
#3 J Jonah Jameson JJJ
#4 3JPX spo        3JPXs
#5 Bruce Wayne     BruceW

data

df <- structure(list(c1 = c("Peter Parker", "Hawk & Dove", "J Jonah Jameson",
"3JPX spo", "Bruce Wayne")), row.names = c(NA, -5L), class = "data.frame")