问:
From JSON File: How to create one common angular ng2-charts (Bar chart) component which can be call from different components with different parameter
I am trying to create a common ng2-charts (Bar Stacked) component, where I can pass the data from other component and it will get update. Actually, I want to display multiple same stacked bar charts with different values in the same page while loading the page.

I have created one common component with ng-2 charts and created one service also. Now I am calling the common component from one more different component via shared service with different parameter and data source is coming from a json file which I am fetching via API.

Now, while fetching, when I am doing console.log()and in that, it is displaying my data.

1st Situation:

In my common component canvas html, if I write,
[datasets]="barChartData ? barChartData : []",
then the data is displaying in the chart but in console, there are errors like
ERROR TypeError: "this.datasets[0] is undefined"
and for this error, everything get freezes, no other things work.

2nd Situation,

In my common component canvas html, if I write,
[datasets]="barChartData", then the data is not displaying"

my common component (bar-chart.component.ts),

```<code>import { Component, OnInit, Input } from "@angular/core";
import { ChartOptions, ChartType, ChartDataSets } from "chart.js";
import * as pluginDataLabels from "chartjs-plugin-datalabels";
import { Label } from "ng2-charts";

@Component({
  selector: "app-common-barchart",
  templateUrl: "./common-barchart.component.html",
  styleUrls: ["./common-barchart.component.css"]
})
export class CommonBarchartComponent implements OnInit {
  constructor() {}

  public barChartOptions: ChartOptions = {
    responsive: true,
    // We use these empty structures as placeholders for dynamic theming.
    scales: {
      xAxes: [
        {
          stacked: true
        }
      ],
      yAxes: [{}]
    },
    plugins: {
      datalabels: {
        anchor: "center",
        align: "center"
      }
    }
  };

  @Input() barChartLabels: Label[];
  @Input() barChartData: ChartDataSets[];

  public barChartType: ChartType = "bar";
  public barChartLegend = true;
  public barChartPlugins = [pluginDataLabels];

  ngOnInit() {
    //console.log("barChartData", this.barChartData);
  }
}
</code>```

my common component's html:

```<code><div>
  <div>
    <div style="display: block">
      <canvas
        baseChart
        height="400"
        [datasets]="barChartData ? barChartData : []"
        [labels]="barChartLabels"
        [options]="barChartOptions"
        [plugins]="barChartPlugins"
        [legend]="barChartLegend"
        [chartType]="barChartType"
      >
      </canvas>
    </div>
  </div>
</div>
</code>```

the component, from which I am calling the common component, (department-wise-barchart.component.ts)

```<code>import { Component, OnInit } from "@angular/core";
import { ChartOptions, ChartType, ChartDataSets } from "chart.js";
import * as pluginDataLabels from "chartjs-plugin-datalabels";
import { Label } from "ng2-charts";
import { BarChartService } from "../../service/bar-chart.service";

@Component({
  selector: "app-department-wise-barchart",
  templateUrl: "./department-wise-barchart.component.html",
  styleUrls: ["./department-wise-barchart.component.css"]
})
export class DepartmentWiseBarchartComponent implements OnInit {
  public barChartData: ChartDataSets[];
  public parentChartData: ChartDataSets[];
  public myLabelsArray: Label[];
  public barChartLabels: Label[];
  public isDataAvailable: boolean = false;

  constructor(private barchartservice: BarChartService) {}

  ngOnInit() {
    this.barchartservice.getBarChartDataFromJSON("dept").subscribe(response => {
      this.parentChartData = response;
    });
  }
}
</code>```

the corresponding html (employee-band-wise-barchart.component.html),

```<code><app-common-barchart
  [barChartData]="parentChartData"
  [barChartLabels]="myLabelsArray"
></app-common-barchart>
</code>```

the service file, (bar-chart.service.ts),

```<code>import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";

@Injectable({
  providedIn: "root"
})
export class BarChartService {
  constructor(private http: HttpClient) {}

  private _url1: string = "../../assets/chart-dummy-data/emp-band.json";
  private _url2: string = "../../assets/chart-dummy-data/dept.json";

  getBarChartDataFromJSON(chartType): Observable<any> {
    if (chartType == "emp-band") {
      return this.http.get<any>(this._url1);
    } else if (chartType == "dept") {
      return this.http.get<any>(this._url2);
    } else {
      return this.http.get<any>(this._url2);
    }
  }
}
</code>```

my json file, (emp-band.json)

```<code>[
  {
    "data": [2, 5, 9],
    "label": "Male",
    "stack": "1"
  },
  {
    "data": [4, 1, 3],
    "label": "Female",
    "stack": "1"
  }
]
</code>```

Can anybody please help me on this above situation.

NB: There will be multiple same type of component (with different data set) which will call the common component at the same time to display different parameterized data.

答:
I have resolved the above issue with the help of this ng2-charts bar graph not displaying data/graph labels url.

Instead of using the ternary operator ([datasets]="barChartData ? barChartData : []") in the common component, if we use a flag (whether the data loaded or not, in my case, I have used a flag named "loaded") and using the flag in the calling componet's html like the below, then the above problem will get resolved.

```<code><app-common-barchart
  *ngIf="loaded"
  [barChartData]="parentChartData"
  [barChartLabels]="myLabelsArray"
></app-common-barchart>
</code>```

Body:
I am trying to create a common ng2-charts (Bar Stacked) component, where I can pass the data from other component and it will get update. Actually, I want to display multiple same stacked bar charts with different values in the same page while loading the page.

I have created one common component with ng-2 charts and created one service also. Now I am calling the common component from one more different component via shared service with different parameter and data source is coming from a json file which I am fetching via API.

Now, while fetching, when I am doing console.log()and in that, it is displaying my data.

1st Situation:

In my common component canvas html, if I write,
[datasets]="barChartData ? barChartData : []",
then the data is displaying in the chart but in console, there are errors like
ERROR TypeError: "this.datasets[0] is undefined"
and for this error, everything get freezes, no other things work.

2nd Situation,

In my common component canvas html, if I write,
[datasets]="barChartData", then the data is not displaying"

my common component (bar-chart.component.ts),

import { Component, OnInit, Input } from "@angular/core";
import { ChartOptions, ChartType, ChartDataSets } from "chart.js";
import * as pluginDataLabels from "chartjs-plugin-datalabels";
import { Label } from "ng2-charts";

@Component({
  selector: "app-common-barchart",
  templateUrl: "./common-barchart.component.html",
  styleUrls: ["./common-barchart.component.css"]
})
export class CommonBarchartComponent implements OnInit {
  constructor() {}

  public barChartOptions: ChartOptions = {
    responsive: true,
    // We use these empty structures as placeholders for dynamic theming.
    scales: {
      xAxes: [
        {
          stacked: true
        }
      ],
      yAxes: [{}]
    },
    plugins: {
      datalabels: {
        anchor: "center",
        align: "center"
      }
    }
  };

  @Input() barChartLabels: Label[];
  @Input() barChartData: ChartDataSets[];

  public barChartType: ChartType = "bar";
  public barChartLegend = true;
  public barChartPlugins = [pluginDataLabels];

  ngOnInit() {
    //console.log("barChartData", this.barChartData);
  }
}

my common component's html:

      <canvas
        baseChart
        height="400"
        [datasets]="barChartData ? barChartData : []"
        [labels]="barChartLabels"
        [options]="barChartOptions"
        [plugins]="barChartPlugins"
        [legend]="barChartLegend"
        [chartType]="barChartType"
      >
      </canvas>

the component, from which I am calling the common component, (department-wise-barchart.component.ts)

import { Component, OnInit } from "@angular/core";
import { ChartOptions, ChartType, ChartDataSets } from "chart.js";
import * as pluginDataLabels from "chartjs-plugin-datalabels";
import { Label } from "ng2-charts";
import { BarChartService } from "../../service/bar-chart.service";

@Component({
  selector: "app-department-wise-barchart",
  templateUrl: "./department-wise-barchart.component.html",
  styleUrls: ["./department-wise-barchart.component.css"]
})
export class DepartmentWiseBarchartComponent implements OnInit {
  public barChartData: ChartDataSets[];
  public parentChartData: ChartDataSets[];
  public myLabelsArray: Label[];
  public barChartLabels: Label[];
  public isDataAvailable: boolean = false;

  constructor(private barchartservice: BarChartService) {}

  ngOnInit() {
    this.barchartservice.getBarChartDataFromJSON("dept").subscribe(response => {
      this.parentChartData = response;
    });
  }
}

the corresponding html (employee-band-wise-barchart.component.html),

<app-common-barchart
  [barChartData]="parentChartData"
  [barChartLabels]="myLabelsArray"
></app-common-barchart>

the service file, (bar-chart.service.ts),

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";

@Injectable({
  providedIn: "root"
})
export class BarChartService {
  constructor(private http: HttpClient) {}

  private _url1: string = "../../assets/chart-dummy-data/emp-band.json";
  private _url2: string = "../../assets/chart-dummy-data/dept.json";

  getBarChartDataFromJSON(chartType): Observable<any> {
    if (chartType == "emp-band") {
      return this.http.get<any>(this._url1);
    } else if (chartType == "dept") {
      return this.http.get<any>(this._url2);
    } else {
      return this.http.get<any>(this._url2);
    }
  }
}

my json file, (emp-band.json)

[
  {
    "data": [2, 5, 9],
    "label": "Male",
    "stack": "1"
  },
  {
    "data": [4, 1, 3],
    "label": "Female",
    "stack": "1"
  }
]

Can anybody please help me on this above situation.

NB: There will be multiple same type of component (with different data set) which will call the common component at the same time to display different parameterized data.

Body:
I have resolved the above issue with the help of this ng2-charts bar graph not displaying data/graph labels url.

Instead of using the ternary operator ([datasets]="barChartData ? barChartData : []") in the common component, if we use a flag (whether the data loaded or not, in my case, I have used a flag named "loaded") and using the flag in the calling componet's html like the below, then the above problem will get resolved.

<app-common-barchart
  *ngIf="loaded"
  [barChartData]="parentChartData"
  [barChartLabels]="myLabelsArray"
></app-common-barchart>


来源: stackexchange

问:
Serialization of struct with pointers
Having a struct heirarchy like:

type DomainStore struct {
    Domains []*Domain
    Users []*User
}

type Domain struct {
    Name    string
    Records []*Record
    Owner   *User
}

type User struct {
    Name      string
    Email     string
    Domains []*Domain
}

type Record struct {
    Name      string
    Host      string
}
```

<p>With a single DomainStore having a list of Domain and Users with pointer between Domain and User.</p>

<p>I'm looking for a way to serialize/deserialize to/from file. I have been trying to use gob, but the pointers is not (by design) serialized correct (its flattened).</p>

<p>Thinking about giving each object a unique id and making a func to serialize/deserialize each type, but it seems much work/boilerplate. Any suggestions for a strategy?</p>

<p>I would like to keep the whole DomainStore in memory, and just serialize to file on user request.</p>

<p><strong>The main problem: How to serialise/deserialize and keep the pointers pointing to the same object and not different copies of the same object</strong></p>

<p>Both gob and json seems to "just" copy the value of the object and afted deserializasion I end up with multiple independent copies of objects.</p>

<p>Using gob ang json this is what happens:</p>

<p>Before, A & C both points to B:</p>

```A -> B <- C
```

<p>After deserialization with json/gob:</p>

```A -> B1 , C -> B2
```

<p>A & C points to to different object, with the same values. But, if i change B1 it's not changed in B2.</p>

<p>--- Update ---</p>

<p>When marshalling i can obtain the memory location of the object and use it as an ID:</p>

```func (u *User) MarshalJSON() ([]byte, error) {
    return json.Marshal(&JsonUser{
        ID:       fmt.Sprintf("%p", u),
        Name:     u.Name,
        Email:    u.Email,
    })
}
```

<p>And when marshalling the Domain I can replace the </p>

```func (d *Domain) MarshalJSON() ([]byte, error) {
    return json.Marshal(&struct {
        ID       string `json:"id"`
        Name     string `json:"name"`
        User     string `json:"user"`
    }{
        ID:       fmt.Sprintf("%p", d),
        Name:     d.Name,
        User:     fmt.Sprintf("%p", d.User),
    })
}
```

<p>Now I <em>just</em> need to be able to unmarshal this which gives me a problem in the UnmarshalJSON need to access a map of id's and their respective objects.</p>

```func (u *User) UnmarshalJSON(data []byte) error {
  // need acces to a map shared by all UnmarshalJSON functions
}
```

答:
Use encoding/json package

to marshal:

```<code>// Marshal is a function that marshals the object into an
// io.Reader.
// By default, it uses the JSON marshaller.
var Marshal = func(v interface{}) (io.Reader, error) {
  b, err := json.MarshalIndent(v, "", "\t")
  if err != nil {
    return nil, err
  }
  return bytes.NewReader(b), nil
}
</code>```

to unmarshal:

```<code>// Unmarshal is a function that unmarshals the data from the
// reader into the specified value.
// By default, it uses the JSON unmarshaller.
var Unmarshal = func(r io.Reader, v interface{}) error {
  return json.NewDecoder(r).Decode(v)
}
</code>```

Not sure there's more to this,

Another thing you can do is, store all these as json formatted strings.

ContentLicense: CC BY-SA 4.0

Title: Serialization of struct with pointers

Body:
Having a struct heirarchy like:

type DomainStore struct {
    Domains []*Domain
    Users []*User
}

type Domain struct {
    Name    string
    Records []*Record
    Owner   *User
}

type User struct {
    Name      string
    Email     string
    Domains []*Domain
}

type Record struct {
    Name      string
    Host      string
}

With a single DomainStore having a list of Domain and Users with pointer between Domain and User.

I'm looking for a way to serialize/deserialize to/from file. I have been trying to use gob, but the pointers is not (by design) serialized correct (its flattened).

Thinking about giving each object a unique id and making a func to serialize/deserialize each type, but it seems much work/boilerplate. Any suggestions for a strategy?

I would like to keep the whole DomainStore in memory, and just serialize to file on user request.

The main problem: How to serialise/deserialize and keep the pointers pointing to the same object and not different copies of the same object

Both gob and json seems to "just" copy the value of the object and afted deserializasion I end up with multiple independent copies of objects.

Using gob ang json this is what happens:

Before, A & C both points to B:

A -> B <- C

After deserialization with json/gob:

A -> B1 , C -> B2

A & C points to to different object, with the same values. But, if i change B1 it's not changed in B2.

--- Update ---

When marshalling i can obtain the memory location of the object and use it as an ID:

func (u *User) MarshalJSON() ([]byte, error) {
    return json.Marshal(&JsonUser{
        ID:       fmt.Sprintf("%p", u),
        Name:     u.Name,
        Email:    u.Email,
    })
}

And when marshalling the Domain I can replace the

func (d *Domain) MarshalJSON() ([]byte, error) {
    return json.Marshal(&struct {
        ID       string `json:"id"`
        Name     string `json:"name"`
        User     string `json:"user"`
    }{
        ID:       fmt.Sprintf("%p", d),
        Name:     d.Name,
        User:     fmt.Sprintf("%p", d.User),
    })
}

Now I just need to be able to unmarshal this which gives me a problem in the UnmarshalJSON need to access a map of id's and their respective objects.

func (u *User) UnmarshalJSON(data []byte) error {
  // need acces to a map shared by all UnmarshalJSON functions
}

Body:
Use encoding/json package

to marshal:

// Marshal is a function that marshals the object into an
// io.Reader.
// By default, it uses the JSON marshaller.
var Marshal = func(v interface{}) (io.Reader, error) {
  b, err := json.MarshalIndent(v, "", "\t")
  if err != nil {
    return nil, err
  }
  return bytes.NewReader(b), nil
}

to unmarshal:

// Unmarshal is a function that unmarshals the data from the
// reader into the specified value.
// By default, it uses the JSON unmarshaller.
var Unmarshal = func(r io.Reader, v interface{}) error {
  return json.NewDecoder(r).Decode(v)
}

Not sure there's more to this,

Another thing you can do is, store all these as json formatted strings.


问:
How can I set an environmental variable in node.js?
How can I set an environmental variable in node.js?

I would prefer not to rely on anything platform specific, such as running export or cmd.exe's set.

答:
First you should install this package :-
https://github.com/motdotla/dotenv [npm install dotenv]

Then you need to create a .env file in your project's root directory, and there you can add variables like below:-

```<code>NODE_ENV=PRODUCTION
DATABASE_HOST=localhost
</code>```

Now you can easily access these variables in your code like below:-

```<code>require('dotenv').config()
console.log(process.env.NODE_ENV);
</code>```

It worked for me, hopefully that helps.

ContentLicense: CC BY-SA 3.0

Body:
First you should install this package :-
https://github.com/motdotla/dotenv [npm install dotenv]

Then you need to create a .env file in your project's root directory, and there you can add variables like below:-

NODE_ENV=PRODUCTION
DATABASE_HOST=localhost

Now you can easily access these variables in your code like below:-

require('dotenv').config()
console.log(process.env.NODE_ENV);

It worked for me, hopefully that helps.


问:
Mixing for each and lambdas in c++
I wanted to play a little bit with  lambdas and for each(Range-based for-loop, not STL for_each) in C++0x. So i went to wiki and tried to rewrite examples from wiki using lambdas:

```<code>    std::vector<int> some_list;
some_list.push_back(42);
some_list.push_back(37);
int total = 0;
int value = 5;
for(int& x:some_list)
{
    [](int x)
    {
        cout << "xL=" <<x <<endl;
    };
}

for(auto x:some_list)
    cout<< "x="<<x<<endl;

    return result;
}
</code>```

Problem is that I don't see any cout in the lambda version, for each version prints x nicely... I presume that it is impossible to mix for each and lambdas because lambdas can only be in the place of the "functions", and cannot act as loop body, but I'm not sure, so if somebody can confirm it would be cool

compiler: GCC 4.6

答:
You should do a call to operator() on the lambda itself.</p>

```<code>for(int& x:some_list)
{
    [](int x)
    {
        cout << "xL=" <<x <<endl;
    }(x);  //notice the "()"
}
</code>```

Title: Mixing for each and lambdas in c++

Body:
I wanted to play a little bit with  lambdas and for each(Range-based for-loop, not STL for_each) in C++0x. So i went to wiki and tried to rewrite examples from wiki using lambdas:

    std::vector<int> some_list;
some_list.push_back(42);
some_list.push_back(37);
int total = 0;
int value = 5;
for(int& x:some_list)
{
    [](int x)
    {
        cout << "xL=" <<x <<endl;
    };
}

for(auto x:some_list)
    cout<< "x="<<x<<endl;

    return result;
}

Problem is that I don't see any cout in the lambda version, for each version prints x nicely... I presume that it is impossible to mix for each and lambdas because lambdas can only be in the place of the "functions", and cannot act as loop body, but I'm not sure, so if somebody can confirm it would be cool

compiler: GCC 4.6

Body:
You should do a call to operator() on the lambda itself.

for(int& x:some_list)
{
    [](int x)
    {
        cout << "xL=" <<x <<endl;
    }(x);  //notice the "()"
}


问:
ArrayList is being initialised everytime the CustomDialogFragment is opened
I use Arraylist in CustomDialogFragment to store values each time when the user checks a checkbox. And removes the values when the user unchecks it. The issue is that each time the user dismisses the dialog, the values in the arraylist gets deleted. I think it's because of reinitialisation of the array  each time when the user  opens the dialog.

I was thinking to store the array in shared preferences, but not sure whether that is the right way to do it. Kindly suggest me how to do it effectively.

CarTypeDialogFragment.java

```<code>public class CarTypeDialogFragment extends DialogFragment {

public interface OnInputListener {
    void sendInput(String input);
}

public OnInputListener mOnInputListener;

CheckBox type1, type2, type4;
String SedanCheckBoxesVal, SUVCheckBoxesVal, HatchBackCheckBoxesVal;

ArrayList<String> myList = new ArrayList<String>();
View v;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
    if (getArguments() != null) {
        //totalCars = getArguments().getString("cars","");
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    if (v != null) {
        if ((ViewGroup) v.getParent() != null)
            ((ViewGroup) v.getParent()).removeView(v);
        return v;
    }
    v = inflater.inflate(R.layout.fragment_restype_dialog, container, false);

    type1 = (CheckBox) v.findViewById(R.id.checkBox);
    type1.setChecked(getFromSP("cb1"));

    type2 = (CheckBox) v.findViewById(R.id.checkBox2);
    type2.setChecked(getFromSP("cb2"));

    type4 = (CheckBox) v.findViewById(R.id.checkBox4);
    type4.setChecked(getFromSP("cb4"));

    type1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (((CheckBox) view).isChecked()) {
                SedanCheckBoxesVal = "'Accord','Avlon','Challenger'";
                saveInSp("cb1", true);
                myList.add(SedanCheckBoxesVal);
                mOnInputListener.sendInput(TextUtils.join("", myList));
                saveInSp("cb1enable", false);

            } else {
                myList.remove(SedanCheckBoxesVal);
                mOnInputListener.sendInput(TextUtils.join("", myList));
                saveInSp("cb1", false);
            }
         }
    });

    type2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //is chkIos checked?

            if (((CheckBox) view).isChecked()) {
                SUVCheckBoxesVal = "'GMC','BMW'";
                saveInSp("cb2", true);
                myList.add(SUVCheckBoxesVal);
                mOnInputListener.sendInput(TextUtils.join("", myList));
                saveInSp("cb2enable", false);

            } else {
                myList.remove(SUVCheckBoxesVal);
                mOnInputListener.sendInput(TextUtils.join("", myList));
                saveInSp("cb2", false);
            }
        }
    });

    type4.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //is chkIos checked?

            if (((CheckBox) view).isChecked()) {
                HatchBackCheckBoxesVal = "'Polo','Micra','MiniCooper'";
                saveInSp("cb4", true);
                myList.add(HatchBackCheckBoxesVal);
                mOnInputListener.sendInput(TextUtils.join("", myList));
                saveInSp("cb4enable", false);
                type4.setEnabled(false);

            } else {
                myList.remove(HatchBackCheckBoxesVal);
                mOnInputListener.sendInput(TextUtils.join("", myList));
                mOnInputListener.sendInput("");
                saveInSp("cb4", false);
            }
        }
    });
    return v;
}

private boolean getFromSP(String key) {
    SharedPreferences preferences = getContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
    return preferences.getBoolean(key, false);
}

private void saveInSp(String key, boolean value) {
    SharedPreferences preferences = getContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putBoolean(key, value);
    editor.commit();

}

@Override
public void onStart() {
    super.onStart();

    Window window = getDialog().getWindow();
    WindowManager.LayoutParams windowParams = window.getAttributes();
    windowParams.dimAmount = 0.00f;
    windowParams.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
    window.setAttributes(windowParams);
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try {
        mOnInputListener = (OnInputListener) getActivity();
    } catch (ClassCastException e) {
        Log.e(TAG, "onAttach: ClassCastException: " + e.getMessage());
    }
}

@Override
public void onDestroyView() {
    //workaround for this issue: https://code.google.com/p/android/issues/detail?id=17423 (unable to retain instance after configuration change)
    if (getDialog() != null && getRetainInstance())
        getDialog().setDismissMessage(null);
    super.onDestroyView();
}
}
</code>```

答:
You are correct that the ArrayList is re-initialized to be empty whenever you close and reopen the dialog. To retain that state when reopened, you would need to persist it before the dialog closes and load it when the dialog opens, like you are doing with the checked states of checkboxes currently. Using SharedPrefs for this is fine, since your list is not large.

However, from what I can see you are adding items to the list based on the checked states (which are already being stored). So you should be able to use them to construct the list without having to store the list too.

For example:

```<code>if (getFromSP("cb1")) {
    myList.add("'Accord','Avlon','Challenger'")
}
</code>```

and similar for the other checkboxes. This can be done in onCreateView just after you getFromSP and use it to setChecked.

Body:
I use Arraylist in CustomDialogFragment to store values each time when the user checks a checkbox. And removes the values when the user unchecks it. The issue is that each time the user dismisses the dialog, the values in the arraylist gets deleted. I think it's because of reinitialisation of the array  each time when the user  opens the dialog.

I was thinking to store the array in shared preferences, but not sure whether that is the right way to do it. Kindly suggest me how to do it effectively.

CarTypeDialogFragment.java

public class CarTypeDialogFragment extends DialogFragment {

public interface OnInputListener {
    void sendInput(String input);
}

public OnInputListener mOnInputListener;

CheckBox type1, type2, type4;
String SedanCheckBoxesVal, SUVCheckBoxesVal, HatchBackCheckBoxesVal;

ArrayList<String> myList = new ArrayList<String>();
View v;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
    if (getArguments() != null) {
        //totalCars = getArguments().getString("cars","");
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    if (v != null) {
        if ((ViewGroup) v.getParent() != null)
            ((ViewGroup) v.getParent()).removeView(v);
        return v;
    }
    v = inflater.inflate(R.layout.fragment_restype_dialog, container, false);

    type1 = (CheckBox) v.findViewById(R.id.checkBox);
    type1.setChecked(getFromSP("cb1"));

    type2 = (CheckBox) v.findViewById(R.id.checkBox2);
    type2.setChecked(getFromSP("cb2"));

    type4 = (CheckBox) v.findViewById(R.id.checkBox4);
    type4.setChecked(getFromSP("cb4"));

    type1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (((CheckBox) view).isChecked()) {
                SedanCheckBoxesVal = "'Accord','Avlon','Challenger'";
                saveInSp("cb1", true);
                myList.add(SedanCheckBoxesVal);
                mOnInputListener.sendInput(TextUtils.join("", myList));
                saveInSp("cb1enable", false);

            } else {
                myList.remove(SedanCheckBoxesVal);
                mOnInputListener.sendInput(TextUtils.join("", myList));
                saveInSp("cb1", false);
            }
         }
    });

    type2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //is chkIos checked?

            if (((CheckBox) view).isChecked()) {
                SUVCheckBoxesVal = "'GMC','BMW'";
                saveInSp("cb2", true);
                myList.add(SUVCheckBoxesVal);
                mOnInputListener.sendInput(TextUtils.join("", myList));
                saveInSp("cb2enable", false);

            } else {
                myList.remove(SUVCheckBoxesVal);
                mOnInputListener.sendInput(TextUtils.join("", myList));
                saveInSp("cb2", false);
            }
        }
    });

    type4.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //is chkIos checked?

            if (((CheckBox) view).isChecked()) {
                HatchBackCheckBoxesVal = "'Polo','Micra','MiniCooper'";
                saveInSp("cb4", true);
                myList.add(HatchBackCheckBoxesVal);
                mOnInputListener.sendInput(TextUtils.join("", myList));
                saveInSp("cb4enable", false);
                type4.setEnabled(false);

            } else {
                myList.remove(HatchBackCheckBoxesVal);
                mOnInputListener.sendInput(TextUtils.join("", myList));
                mOnInputListener.sendInput("");
                saveInSp("cb4", false);
            }
        }
    });
    return v;
}

private boolean getFromSP(String key) {
    SharedPreferences preferences = getContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
    return preferences.getBoolean(key, false);
}

private void saveInSp(String key, boolean value) {
    SharedPreferences preferences = getContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putBoolean(key, value);
    editor.commit();

}

@Override
public void onStart() {
    super.onStart();

    Window window = getDialog().getWindow();
    WindowManager.LayoutParams windowParams = window.getAttributes();
    windowParams.dimAmount = 0.00f;
    windowParams.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
    window.setAttributes(windowParams);
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try {
        mOnInputListener = (OnInputListener) getActivity();
    } catch (ClassCastException e) {
        Log.e(TAG, "onAttach: ClassCastException: " + e.getMessage());
    }
}

@Override
public void onDestroyView() {
    //workaround for this issue: https://code.google.com/p/android/issues/detail?id=17423 (unable to retain instance after configuration change)
    if (getDialog() != null && getRetainInstance())
        getDialog().setDismissMessage(null);
    super.onDestroyView();
}
}

Body:
You are correct that the ArrayList is re-initialized to be empty whenever you close and reopen the dialog. To retain that state when reopened, you would need to persist it before the dialog closes and load it when the dialog opens, like you are doing with the checked states of checkboxes currently. Using SharedPrefs for this is fine, since your list is not large.

However, from what I can see you are adding items to the list based on the checked states (which are already being stored). So you should be able to use them to construct the list without having to store the list too.

For example:

if (getFromSP("cb1")) {
    myList.add("'Accord','Avlon','Challenger'")
}

and similar for the other checkboxes. This can be done in onCreateView just after you getFromSP and use it to setChecked.


问:
If a bash command accepts a filename as the last arg, can piping be used to provide file content?
Say a command takes a filename as its last argument:

```<code>count-words "$word" file.txt
</code>```

Is there a way to use pipe in order to provide file content rather than writing to a temp file?

答:
As Gordon Davisson mentioned in the comment, you could use the special file /dev/stdin which represents standard input.

some-command | count-words "$word" /dev/stdin
```

Body:
Say a command takes a filename as its last argument:

count-words "$word" file.txt

Is there a way to use pipe in order to provide file content rather than writing to a temp file?


问:
Why NotifyCollectionChangedEventArgs has NewItems and OldItems as plural?
I'm new to C# and OOP, just a question on NotifyCollectionChangedEventArgs. I don't understand why it has NewItems and OldItems rather than NewItem and OldItem.
For example, we use ObservableCollection as:

```<code>ObservableCollection<Person> people = new ObservableCollection<Person>()
// Wire up the CollectionChanged event.
people.CollectionChanged += people_CollectionChanged;

static void people_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
   if (e.Action == NotifyCollectionChangedAction.Add)
   {
     foreach (Person p in e.NewItems)
     {
        Console.WriteLine(p.ToString());
     }
   }

}
</code>```

so each time we add a new Person in the collection as:

```<code>people.Add(new Person("John", "Smith", 32));
</code>```

CollectionChanged trigger people_CollectionChanged, so e.NewItems will only contain one person (the one I just added), so what's the point to assume e.NewItems could have more than one item as it always can only have one item?

答:
If you look at the official documentation, you will notice that the backing entity is an IList implementation. Given that it's a list, it's only natural that the property name is in plural.

For example, if I use AddRange, multiple items will be added at once, and NewItems (or OldItems, if you removed content) would be populated with more than one entry.

Body:
I'm new to C# and OOP, just a question on NotifyCollectionChangedEventArgs. I don't understand why it has NewItems and OldItems rather than NewItem and OldItem.
For example, we use ObservableCollection as:

ObservableCollection<Person> people = new ObservableCollection<Person>()
// Wire up the CollectionChanged event.
people.CollectionChanged += people_CollectionChanged;

static void people_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
   if (e.Action == NotifyCollectionChangedAction.Add)
   {
     foreach (Person p in e.NewItems)
     {
        Console.WriteLine(p.ToString());
     }
   }

}

so each time we add a new Person in the collection as:

people.Add(new Person("John", "Smith", 32));

CollectionChanged trigger people_CollectionChanged, so e.NewItems will only contain one person (the one I just added), so what's the point to assume e.NewItems could have more than one item as it always can only have one item?


问:
How do I dismiss a rootViewController before presenting a new UITabBarController?
I've set up a UIViewController as my rootViewController in AppDelegate, however, when a user logs in or skips it I am presenting a UITabBarController over the top.

I need to dismiss the LoginController, and set the UITabController as rootViewController instead after user logs in.

How can I go about reorganizing this?

AppDelegate()

```<code>window = UIWindow()
window?.makeKeyAndVisible()
window?.rootViewController = LoginController()
</code>```

LoginController()

```<code>self.present(MainTabBarController(), animated: true, completion: nil)
</code>```

答:
you can design your code like this.

This one

Body:
I've set up a UIViewController as my rootViewController in AppDelegate, however, when a user logs in or skips it I am presenting a UITabBarController over the top.

I need to dismiss the LoginController, and set the UITabController as rootViewController instead after user logs in.

How can I go about reorganizing this?

AppDelegate()

window = UIWindow()
window?.makeKeyAndVisible()
window?.rootViewController = LoginController()

LoginController()

self.present(MainTabBarController(), animated: true, completion: nil)


问:
Flex box rendering like a column when it should be a row
I am putting together what should be a simple nav bar and styling with flex box. For some reason, instead of displaying as a row (horizontal), it is showing as a column (vertical).

I can make the links go horizontal using float:left, but then they don't stretch evenly to fill the nav bar.

My understanding is that flex-grow:1 should make each item occupy an equal amount of space. But this is not happening.

There are four declarations that are not working as expected:

flex-direction The links within the nav bar are in a column instead of a row

padding Although the nav bar's padding is set to zero, it still appears to have padding

text-align The text within each
 is not getting horizontally centered

flex-grow The links are not spacing out evenly

I'm not sure if they are all stemming from to one problem, or each separate problems.

Here is a simplified snippet:

<!doctype html>

<meta charset="utf-8">
<title>Curse of the Nav Bar</title>

Once

Upon

A Time

There

Was

A Problematic

Nav Bar

```

I've used flex box plenty of times before, but never seen it behave like this.

答:
You take a simple change the

```<code>nav {
   display: flex;
   flex-direction: row; /* not working */
   background-color: #d2d6d6;
   padding: 0; /* not working */
}
</code>```

To

```<code>nav ul {
   display: flex;
   flex-direction: row; /* not working */
   background-color: #d2d6d6;
   padding: 0; /* not working */
}
</code>```

<!doctype html>

<meta charset="utf-8">
<title>Curse of the Nav Bar</title>

Once

Upon

A Time

There

Was

A Problematic

Nav Bar

```

Body:
I am putting together what should be a simple nav bar and styling with flex box. For some reason, instead of displaying as a row (horizontal), it is showing as a column (vertical).

I can make the links go horizontal using float:left, but then they don't stretch evenly to fill the nav bar.

My understanding is that flex-grow:1 should make each item occupy an equal amount of space. But this is not happening.

There are four declarations that are not working as expected:

flex-direction The links within the nav bar are in a column instead of a row

padding Although the nav bar's padding is set to zero, it still appears to have padding

text-align The text within each
 is not getting horizontally centered

flex-grow The links are not spacing out evenly

I'm not sure if they are all stemming from to one problem, or each separate problems.

Here is a simplified snippet:

<!doctype html>

<meta charset="utf-8">
<title>Curse of the Nav Bar</title>

Once

Upon

A Time

There

Was

A Problematic

Nav Bar

I've used flex box plenty of times before, but never seen it behave like this.

Body:
You take a simple change the

nav {
   display: flex;
   flex-direction: row; /* not working */
   background-color: #d2d6d6;
   padding: 0; /* not working */
}

To

nav ul {
   display: flex;
   flex-direction: row; /* not working */
   background-color: #d2d6d6;
   padding: 0; /* not working */
}

<!doctype html>
<html lang="en">

<head>
<meta charset="utf-8">
<title>Curse of the Nav Bar</title>
<style>
nav ul {
 display: flex;
 flex-direction: row; /* not working */
 background-color: #d2d6d6;
 padding: 0; /* not working */
}
nav a {
 display: flex;
 text-decoration: none;
 list-style: none;
 border: 2px solid #727171;
 color: #727171;
 background-color: #c4c4c4;
 padding: 4px;
 margin: 2px;
 text-align: center; /* not working */
 flex-grow: 1; /* not working */
}
nav a:hover,
nav a:active {
 background-color: #aaa;
}
</style>
</head>

<body>
<nav>
 <ul>
  <a href="#"><li>Once</li></a>
  <a href="#"><li>Upon</li></a>
  <a href="#"><li>A Time</li></a>
  <a href="#"><li>There</li></a>
  <a href="#"><li>Was</li></a>
  <a href="#"><li>A Problematic</li></a>
  <a href="#"><li>Nav Bar</li></a>
 </ul>
</nav>
</body>
</html>


问:
How to create a regular expression to find out repeated character in string?
Eg:

HelloWorld - repeated characters are 5 (l is repeating 3 times and o is repeating 2 times)

Smart2000,  repeated characters = 3?(0 is repeating 3 times)

Smart@200@12, repeated characters = 6

I tried with iterating over string

Here is my code with string iteration to find out the repeated character in string.

```<code>func countRepeatDigitsIn(keyword : String) -> Int
{
    // To keep track of processed symbols
    var uniqueCharacters = ""
    var repeatCharacterCount = 0

    for char in keyword.uppercased() {
        let alphabet = String(char)

        // If this is already counted, skip it
        if (uniqueCharacters.contains(alphabet))
        {
            repeatCharacterCount += 1
        }

        // Otherwise, add it to processed symbols
        uniqueCharacters += alphabet
    }

    return repeatCharacterCount
}
</code>```

答:
Group same characters in a dictionary using Dictionary(grouping:by:) and add the counts of values where the count is greater than 1</p>

```<code>extension String {
    func repeatCount() -> Int {
        return Dictionary(grouping: lowercased()) { $0 }.values.filter { $0.count > 1 }.reduce(0) { $0 + $1.count }
    }
}
print("HelloWorLd".repeatCount())//5
print("Smart2000".repeatCount())//3
print("Smart@200@12".repeatCount())//6
</code>```

Body:
Eg:

HelloWorld - repeated characters are 5 (l is repeating 3 times and o is repeating 2 times)

Smart2000,  repeated characters = 3?(0 is repeating 3 times)

Smart@200@12, repeated characters = 6

I tried with iterating over string

Here is my code with string iteration to find out the repeated character in string.

func countRepeatDigitsIn(keyword : String) -> Int
{
    // To keep track of processed symbols
    var uniqueCharacters = ""
    var repeatCharacterCount = 0

    for char in keyword.uppercased() {
        let alphabet = String(char)

        // If this is already counted, skip it
        if (uniqueCharacters.contains(alphabet))
        {
            repeatCharacterCount += 1
        }

        // Otherwise, add it to processed symbols
        uniqueCharacters += alphabet
    }

    return repeatCharacterCount
}

Body:
Group same characters in a dictionary using Dictionary(grouping:by:) and add the counts of values where the count is greater than 1

extension String {
    func repeatCount() -> Int {
        return Dictionary(grouping: lowercased()) { $0 }.values.filter { $0.count > 1 }.reduce(0) { $0 + $1.count }
    }
}
print("HelloWorLd".repeatCount())//5
print("Smart2000".repeatCount())//3
print("Smart@200@12".repeatCount())//6


问:
multithread handling in java
I have stuck in a serious problem. I am sending a request to server which contains some URL as its data.If I explain it , it is like I have a file which contains some URL in a sequential order I have to read those sequential data by using thread. Now the problem is there are one hundred thousand URL, I have to send each URL in the server in a particular time(say  suppose 30 seconds).So I have to create threads which will serve the task in the desired time. But I have to read the file in such a way if first thread serve first 100 URL then 2nd thread will serve the next 100 URL and in the same way the other threads also.And I am doing it in a socket programming,so there is only one port at a time that I can use. So how to solve this problem. Give me a nice and simple idea, and if possible give me an example also.

Thanks in Advance

答: Nice and simple idea (if I understand your question correctly): You can use a LinkedList as a queue. Read in the 1,000 urls from file and put them in the list. Spawn your threads, which then pull (and remove) the next 100 urls from the list. LinkedList is not thread-safe though, so you must synchronize access yourself.</p>

Title: multithread handling in java


问:
How to read a resource file in C#
I have added a resource file to my project (C#, windows service - TopShelp):

I have added a text file to the resource:

Now I want to read the test file, this is what I have tried:

```<code>ResourceManager rm = new ResourceManager("My.Project.Name.Resources", Assembly.GetExecutingAssembly());
</code>```

It does not find anything, ResourceSets count = 0.

Update

As suggested in the comments, I also tried adding the resource under:

Project > Properties > Resources

And tried the following code, which did not find anything:

```<code>ResourceManager rm = new ResourceManager("My.Project.Name.Resources", Assembly.GetExecutingAssembly());
</code>```

答:
You can always try:

```<code>var assembly = Assembly.GetExecutingAssembly();
var resourceName = "MyCompany.MyProduct.MyFile.txt";

using (Stream stream = assembly.GetManifestResourceStream(resourceName))
using (StreamReader reader = new StreamReader(stream))
{
    string result = reader.ReadToEnd();
}
</code>```

Check that your file exists through Assembly.GetManifestResourceNames method.

Title: How to read a resource file in C#

Body:
I have added a resource file to my project (C#, windows service - TopShelp):

I have added a text file to the resource:

Now I want to read the test file, this is what I have tried:

ResourceManager rm = new ResourceManager("My.Project.Name.Resources", Assembly.GetExecutingAssembly());

It does not find anything, ResourceSets count = 0.

Update

As suggested in the comments, I also tried adding the resource under:

Project > Properties > Resources

And tried the following code, which did not find anything:

ResourceManager rm = new ResourceManager("My.Project.Name.Resources", Assembly.GetExecutingAssembly());

Body:
You can always try:

var assembly = Assembly.GetExecutingAssembly();
var resourceName = "MyCompany.MyProduct.MyFile.txt";

using (Stream stream = assembly.GetManifestResourceStream(resourceName))
using (StreamReader reader = new StreamReader(stream))
{
    string result = reader.ReadToEnd();
}

Check that your file exists through Assembly.GetManifestResourceNames method.


问:
I want to plus the number form string datatype
I have the following input as string:

```<code>Num: 12345
</code>```

I would like to print out the sum of digits from the input (1+2+3+4+5 = 15):

```<code>total:15
</code>```

I tried, but there is a problem with atoi() in the for loop and I got an error:

[Error] invalid conversion from 'char' to 'const char*'

How can I fix that or how can I resolve it in an easier way?

```<code> #include <stdio.h>
 #include <ctype.h>
 #include <stdlib.h>
 #include <string.h>

 char numstr[100];
 int total = 0;

 main(){
     printf("Num:");
     scanf("%s", numstr);

     for(int i = 0; i < strlen(numstr); i++){
         total += atoi(numstr[i]);
     }
     printf("%d", total);
 }
</code>```

答:
You can subtract the numeric character (in ASCII) by 0x30 (i.e. ASCII character zero '0') to convert the ASCII numeric character to its decimal equivalent.

```<code> #include <stdio.h>
 #include <ctype.h>
 #include <stdlib.h>
 #include <string.h>
 char numstr[100];
 int total=0;
 main(){
 printf("Num:");
 scanf("%s",numstr);

 for(int i = 0;i<strlen(numstr);i++){
     total += numstr[i] - 0x30;
 }
 printf("%d",total);
 }
</code>```

The string "12345" will be

```<code>1 -> 0x31 - 0x30 = 1
2 -> 0x32 - 0x30 = 2
3 -> 0x33 - 0x30 = 3
4 -> 0x34 - 0x30 = 4
5 -> 0x35 - 0x30 = 5
</code>```

Body:
I have the following input as string:

Num: 12345

I would like to print out the sum of digits from the input (1+2+3+4+5 = 15):

total:15

I tried, but there is a problem with atoi() in the for loop and I got an error:

[Error] invalid conversion from 'char' to 'const char*'

How can I fix that or how can I resolve it in an easier way?

 #include <stdio.h>
 #include <ctype.h>
 #include <stdlib.h>
 #include <string.h>

 char numstr[100];
 int total = 0;

 main(){
     printf("Num:");
     scanf("%s", numstr);

     for(int i = 0; i < strlen(numstr); i++){
         total += atoi(numstr[i]);
     }
     printf("%d", total);
 }

Body:
You can subtract the numeric character (in ASCII) by 0x30 (i.e. ASCII character zero '0') to convert the ASCII numeric character to its decimal equivalent.

 #include <stdio.h>
 #include <ctype.h>
 #include <stdlib.h>
 #include <string.h>
 char numstr[100];
 int total=0;
 main(){
 printf("Num:");
 scanf("%s",numstr);

 for(int i = 0;i<strlen(numstr);i++){
     total += numstr[i] - 0x30;
 }
 printf("%d",total);
 }

The string "12345" will be

1 -> 0x31 - 0x30 = 1
2 -> 0x32 - 0x30 = 2
3 -> 0x33 - 0x30 = 3
4 -> 0x34 - 0x30 = 4
5 -> 0x35 - 0x30 = 5


问:
How to make an ImageView with rounded corners?
In Android, an ImageView is a rectangle by default. How can I make it a rounded rectangle (clip off all 4 corners of my Bitmap to be rounded rectangles) in the ImageView?

Note that from 2021 onwards, simply use ShapeableImageView

答:
For Glide 4.x.x

use this simple code

```<code>Glide
  .with(context)
  .load(uri)
  .apply(
      RequestOptions()
        .circleCrop())
  .into(imageView)
</code>```

Body:
For Glide 4.x.x

use this simple code

Glide
  .with(context)
  .load(uri)
  .apply(
      RequestOptions()
        .circleCrop())
  .into(imageView)


问:
Data insertion into the hierarchy format from one table to another
I have an issue in insertion of records from one table to another the tables schema is same

```<code>Table 1
Id  Parent Id   Text
11  Null          A
12  Null          B
13  11            C
14  11            D
15  13            E
</code>```

The record should be inserted in this format, I have to copy the foreign key relation not the identities of it.

```<code>Table 2
Id  Parent Id   Text
31  Null         A
32  Null         B
33  31           C
34  31           D
35  33           E
</code>```

答:
What you want could be achieved easily in the Database side.
But since you are looking for a linq approach. Here is how it can be achieved.

The Process is divided into two parts:

Hoping that you would have the model for the Table1 and Table2 something like(use the order you think is helpful. For my thinking the Table1 is the temp table):

```<code>Public class myEntity
{
  public int Id{get; set;}
  public int? ParentId{get; set;}
  public string Text{get; set;}
}
</code>```

1st: Copying all the Text Properties from Table A and inserting them into Table B with incrementing the IDs

```<code>var Table2 = new List<myEntity>();

Table1.Select(s=>s.Text).OrderBy(o=>o).ToList().ForEach(f=>
{
    //now append the texts to
    Table2.Add(new tablesTest { Id = (Table2.Count + 1), Text = f });//remove the Id property manupulation or set it to 0 if you are inserting directly in the database and use the context.SaveChanges();(*if entity-framework*) once the insertion is complete.
}}
</code>```

2nd: Creating a mapping table using self-join to get the parent-child relationship between the entries from Table1 and then updating the entries in Table2

```<code>var parentChildListFromTb1 = from m in Table1
                      join ch in Table1 on m.Id equals ch.ParentId
                      select new
                      {
                         Id = ch.Id,
                         Parent = m.Text,
                         Text = ch.Text
                      };
</code>```

Which will give you an output:

```<code>----------------------------
|  Id  |  Parent  |  Text  |
----------------------------
|  13  |    A     |    C   |
----------------------------
|  14  |    A     |    D   |
----------------------------
|  15  |    C     |    E   |
----------------------------
</code>```

Now after we have the parent-child list now we create the child list by querying Table2 and updating its ParentId with their respected Ids:

```<code>parentChildListFromTb1.ForEach(f=>{
            var ChildEntity = Table2.Single(s => s.Text.Equals(f.Text));//fetching the child entity from Table2
            ChildEntity.ParentId = Table2.Single(s => s.Text.Equals(f.Parent)).Id;//updating the parentIds in Table2
});
</code>```

And the Table2 will look something like :

```<code>------------------------------
|  Id  |  ParentId  |  Text  |
------------------------------
|   1  |    null    |    A   |
------------------------------
|   2  |    null    |    B   |
------------------------------
|   3  |     1      |    C   |
------------------------------
|   4  |     1      |    D   |
------------------------------
|   5  |     3      |    E   |
------------------------------
</code>```

Body:
I have an issue in insertion of records from one table to another the tables schema is same

Table 1
Id  Parent Id   Text
11  Null          A
12  Null          B
13  11            C
14  11            D
15  13            E

The record should be inserted in this format, I have to copy the foreign key relation not the identities of it.

Table 2
Id  Parent Id   Text
31  Null         A
32  Null         B
33  31           C
34  31           D
35  33           E

Body:
What you want could be achieved easily in the Database side.
But since you are looking for a linq approach. Here is how it can be achieved.

The Process is divided into two parts:

Hoping that you would have the model for the Table1 and Table2 something like(use the order you think is helpful. For my thinking the Table1 is the temp table):

Public class myEntity
{
  public int Id{get; set;}
  public int? ParentId{get; set;}
  public string Text{get; set;}
}

1st: Copying all the Text Properties from Table A and inserting them into Table B with incrementing the IDs

var Table2 = new List<myEntity>();

Table1.Select(s=>s.Text).OrderBy(o=>o).ToList().ForEach(f=>
{
    //now append the texts to
    Table2.Add(new tablesTest { Id = (Table2.Count + 1), Text = f });//remove the Id property manupulation or set it to 0 if you are inserting directly in the database and use the context.SaveChanges();(*if entity-framework*) once the insertion is complete.
}}

2nd: Creating a mapping table using self-join to get the parent-child relationship between the entries from Table1 and then updating the entries in Table2

var parentChildListFromTb1 = from m in Table1
                      join ch in Table1 on m.Id equals ch.ParentId
                      select new
                      {
                         Id = ch.Id,
                         Parent = m.Text,
                         Text = ch.Text
                      };

Which will give you an output:

----------------------------
|  Id  |  Parent  |  Text  |
----------------------------
|  13  |    A     |    C   |
----------------------------
|  14  |    A     |    D   |
----------------------------
|  15  |    C     |    E   |
----------------------------

Now after we have the parent-child list now we create the child list by querying Table2 and updating its ParentId with their respected Ids:

parentChildListFromTb1.ForEach(f=>{
            var ChildEntity = Table2.Single(s => s.Text.Equals(f.Text));//fetching the child entity from Table2
            ChildEntity.ParentId = Table2.Single(s => s.Text.Equals(f.Parent)).Id;//updating the parentIds in Table2
});

And the Table2 will look something like :

------------------------------
|  Id  |  ParentId  |  Text  |
------------------------------
|   1  |    null    |    A   |
------------------------------
|   2  |    null    |    B   |
------------------------------
|   3  |     1      |    C   |
------------------------------
|   4  |     1      |    D   |
------------------------------
|   5  |     3      |    E   |
------------------------------


问:
Add item to specific position otherwise push zero in array in javascript
I have empty array in that I want to add specific items at specific position which are coming from web api and want to add zero(0) to remaining positions dynamically using javscript.
Here is my Code :-

```<code>let arraydata = [0, 0, 0, 0, 0,0,0,0,0,0,0,0]
arraydata.splice(5, 0, 4)
document.querySelector("#app").innerHTML = arraydata;
</code>```

My Code

Right now I have added zero manually,I want to add 0 upto 12 index and want to add 4 at 5th position synamicaaly.

答:
Use map:

let arraydata = Array(12).fill();
arraydata.splice(5, 0, 4);
arraydata = arraydata.map(e => e ? e : 0);
console.log(arraydata);```
</div>
</div>
</p>

<p>You can also add different values - just place them inside the <code>fill</code>:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let arraydata = Array(12).fill("Things");
arraydata.splice(5, 0, 4);
arraydata = arraydata.map(e => e ? e : 0);
console.log(arraydata);</code>```

Body:
I have empty array in that I want to add specific items at specific position which are coming from web api and want to add zero(0) to remaining positions dynamically using javscript.
Here is my Code :-

let arraydata = [0, 0, 0, 0, 0,0,0,0,0,0,0,0]
arraydata.splice(5, 0, 4)
document.querySelector("#app").innerHTML = arraydata;

My Code

Right now I have added zero manually,I want to add 0 upto 12 index and want to add 4 at 5th position synamicaaly.

Body:
Use map:

let arraydata = Array(12).fill();
arraydata.splice(5, 0, 4);
arraydata = arraydata.map(e => e ? e : 0);
console.log(arraydata);

You can also add different values - just place them inside the fill:

let arraydata = Array(12).fill("Things");
arraydata.splice(5, 0, 4);
arraydata = arraydata.map(e => e ? e : 0);
console.log(arraydata);


问:
How to save the list in to .txt?
I have to save 'Record' into text file. So I have tried to use name_error_record.write( record[0]+"   "+record[1]+"   "+record[2]+"   "+record[3]) but it doesn't work...

I have to align as 'No   Menu_name Num Total' and save it into text file. please help..

The list that I have to save is [['No.', 'Menu_name', 'Num', 'Total'], ['4', 'Smoothie_queen', '4', '12000'], ['10', 'Amorparty', '2', '4000'], ['24', 'Plane_yougurt', '14', '49000'], ['36', 'Cofe_latte', '18', '45000'], ['51', 'Cofe_latte', '16', '40000'], ['53', 'Berry_smudie', '17', '51000'], ['54', 'American_air', '4', '8000']]

and also it has to be aligned by columns as 'No    Menu name    Num   Total'.
I think I am missing something but I can't find them.. help T.T

```<code>def error_check(date):
    #========= STEP 3 ==========
    Record = []
    errormenu = []
    recordfile = open("ledger_"+date+".txt","r")
    errormenufile = open("menu.txt", "r")

    for error in errormenufile:
        menu = error.split()
        errormenu.append(menu[0])

    errormenufile.close()

    for line in recordfile:
        record = line.split()
        Record.append(record)

        Record = [x for x in Record if errormenu[0] not in x]
        Record = [x for x in Record if errormenu[1] not in x]
        Record = [x for x in Record if errormenu[2] not in x]
        Record = [x for x in Record if errormenu[3] not in x]
        Record = [x for x in Record if errormenu[4] not in x]

    name_error_record = open("ledger_"+date+"_name_error.txt","r")

    for record in Record:
        name_error_record.write( record[0]+"   "+record[1]+"   "+record[2]+"   "+record[3])

    name_error_record.close()
    #========= STEP 3 ==========
</code>```

答:
Simply change 'r' to 'w' in:

```<code>open("ledger_"+date+"_name_error.txt","r")
open("ledger_"+date+"_name_error.txt","w")
</code>```

by setting 'w' you open file for writing

you can add '\n' at the end of saved line in:

```<code>name_error_record.write( record[0]+"   "+record[1]+"   "+record[2]+"   "+record[3]+'\n')
</code>```

to save data line by line

Title: How to save the list in to .txt?

Body:
I have to save 'Record' into text file. So I have tried to use name_error_record.write( record[0]+"   "+record[1]+"   "+record[2]+"   "+record[3]) but it doesn't work...

I have to align as 'No   Menu_name Num Total' and save it into text file. please help..

The list that I have to save is [['No.', 'Menu_name', 'Num', 'Total'], ['4', 'Smoothie_queen', '4', '12000'], ['10', 'Amorparty', '2', '4000'], ['24', 'Plane_yougurt', '14', '49000'], ['36', 'Cofe_latte', '18', '45000'], ['51', 'Cofe_latte', '16', '40000'], ['53', 'Berry_smudie', '17', '51000'], ['54', 'American_air', '4', '8000']]

and also it has to be aligned by columns as 'No    Menu name    Num   Total'.
I think I am missing something but I can't find them.. help T.T

def error_check(date):
    #========= STEP 3 ==========
    Record = []
    errormenu = []
    recordfile = open("ledger_"+date+".txt","r")
    errormenufile = open("menu.txt", "r")

    for error in errormenufile:
        menu = error.split()
        errormenu.append(menu[0])

    errormenufile.close()

    for line in recordfile:
        record = line.split()
        Record.append(record)

        Record = [x for x in Record if errormenu[0] not in x]
        Record = [x for x in Record if errormenu[1] not in x]
        Record = [x for x in Record if errormenu[2] not in x]
        Record = [x for x in Record if errormenu[3] not in x]
        Record = [x for x in Record if errormenu[4] not in x]

    name_error_record = open("ledger_"+date+"_name_error.txt","r")

    for record in Record:
        name_error_record.write( record[0]+"   "+record[1]+"   "+record[2]+"   "+record[3])

    name_error_record.close()
    #========= STEP 3 ==========

Body:
Simply change 'r' to 'w' in:

open("ledger_"+date+"_name_error.txt","r")
open("ledger_"+date+"_name_error.txt","w")

by setting 'w' you open file for writing

you can add '\n' at the end of saved line in:

name_error_record.write( record[0]+"   "+record[1]+"   "+record[2]+"   "+record[3]+'\n')

to save data line by line


问:
Spring MVC Annotated Controller
I have a controller which has a few actions, which are triggered by hitting various buttons on the page.  I would like to have a default action, but am unsure how to annotate the method.  Here is an example:

```<code>@Controller
@RequestMapping("/view.jsp")
public class ExampleController {

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView displayResults() {
        ModelAndView mav = new ModelAndView("view");
        mav.addObject("queryResults", methodToQueryDBForListing());
        return mav;
    }

    @RequestMapping(method = RequestMethod.POST, params="submit=Action 1")
    public ModelAndView action1(@RequestParam("selectedItemKey") String key) {
        ModelAndView mav = new ModelAndView("action1");
        //Business logic
        return mav;
    }

    @RequestMapping(method = RequestMethod.POST, params="submit=Action 2")
    public ModelAndView action2(@RequestParam("selectedItemKey") String key) {
        ModelAndView mav = new ModelAndView("action2");
        //Business logic
        return mav;
    }

    //A few more methods which basically do what action1 and action2 do
}
</code>```

How can I annotate a method which will act on a POST with any submit button pressed with no key selected?

I have tried:

```<code>@RequestMethod(method = RequestMethod.POST, params="!selectedItemKey")
@RequestMethod(method = RequestMethod.POST)
</code>```

I'd really hate it if I had to set required = false on each of the methods which take RequestParams and then conditionally check to see if one comes in or not...  Is there a way to annotate this to work properly?

答:
I would make this a path variable rather than a parameter, and would get rid of the .jsp:

```<code>@RequestMapping("/view")
...

@RequestMapping("/action1")
@RequestMapping("/action2")
@RequestMapping("/{action}")
</code>```

It is more "restful".

Title: Spring MVC Annotated Controller

Body:
I have a controller which has a few actions, which are triggered by hitting various buttons on the page.  I would like to have a default action, but am unsure how to annotate the method.  Here is an example:

@Controller
@RequestMapping("/view.jsp")
public class ExampleController {

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView displayResults() {
        ModelAndView mav = new ModelAndView("view");
        mav.addObject("queryResults", methodToQueryDBForListing());
        return mav;
    }

    @RequestMapping(method = RequestMethod.POST, params="submit=Action 1")
    public ModelAndView action1(@RequestParam("selectedItemKey") String key) {
        ModelAndView mav = new ModelAndView("action1");
        //Business logic
        return mav;
    }

    @RequestMapping(method = RequestMethod.POST, params="submit=Action 2")
    public ModelAndView action2(@RequestParam("selectedItemKey") String key) {
        ModelAndView mav = new ModelAndView("action2");
        //Business logic
        return mav;
    }

    //A few more methods which basically do what action1 and action2 do
}

How can I annotate a method which will act on a POST with any submit button pressed with no key selected?

I have tried:

@RequestMethod(method = RequestMethod.POST, params="!selectedItemKey")
@RequestMethod(method = RequestMethod.POST)

I'd really hate it if I had to set required = false on each of the methods which take RequestParams and then conditionally check to see if one comes in or not...  Is there a way to annotate this to work properly?

Body:
I would make this a path variable rather than a parameter, and would get rid of the .jsp:

@RequestMapping("/view")
...

@RequestMapping("/action1")
@RequestMapping("/action2")
@RequestMapping("/{action}")

It is more "restful".


问:
How can I show an ampersand in XAML text string?
I am trying to add an ampersand like this:

```<code><Label Text="Phrase & Meaning Visible" />
</code>```

This doesn't work so I tried to delimit with a \ and that also does not work.  Does anyone have any suggestions on how I can do this?

答:
Taken this with thanks from the following blog post.
Special Symbols in XAML

```<code>For Ampersand sign <Label Text="&"/>
For less than sign <Label Text="<">
For greater than sign <Label Text=">"/>
For double quotes <Label Text="""/>
</code>```

Body:
I am trying to add an ampersand like this:

This doesn't work so I tried to delimit with a \ and that also does not work.  Does anyone have any suggestions on how I can do this?

Body:
Taken this with thanks from the following blog post.
Special Symbols in XAML

For Ampersand sign <Label Text="&amp;"/>
For less than sign <Label Text="&lt;">
For greater than sign <Label Text="&gt;"/>
For double quotes <Label Text="&quot;"/>


问:
modulepath environment variable in Java similar to CLASSPATH
In previous versions of Java if you had for example a user-defined package org.mypackage in windows with directory structure

```<code>D:\myprogram\
      |
      ---> org\
            |
            ---> mypackage\
                     |
                     ---> HelloWorld.class
                     ---> SupportClass.class
                     ---> UtilClass.class
</code>```

you make the JVM aware of the package by using the CLASSPATH environment variable.

For example:

```<code>set CLASSPATH=D:\myprogram
</code>```

Does set MODULEPATH command instead make the JVM aware of the location of user-defined modules in the latest versions of Java ?

If so why is classpath command still around and what purpose does it serve now?

答:
No, the jdk does not read any MODULEPATH environment variable or similar.

The MODULEPATH only exists as a command-line argument --module-path, but not as an environment variable.

See http://mail.openjdk.java.net/pipermail/jigsaw-dev/2016-September/009345.html

Unlike CLASSPATH, there is no equivalent MODULEPATH to get the option off of the command line.

Also see the linked question Is it possible to mix --class-path and --module-path in javac (JDK 9)? for more details on the differences between boths paths.

If you put a normal jar on the modulepath, it becomes an automatic module, exporting its packages (and reserving those packages for itself).

While you can put any normal jar file into the MODULEPATH, there is a restriction: If 2 jar files contain the same package, then java will not allow both of them in the modulepath. That's why Java still has the classpath, because several existing jar files still have overlapping packages, and it is not possible to put them all on the MODULEPATH. They have to be cleaned up first.

In the far future, when all libraries have been migrated to modules (or cleaned up), maybe classpath can be removed.

Body:
In previous versions of Java if you had for example a user-defined package org.mypackage in windows with directory structure

D:\myprogram\
      |
      ---> org\
            |
            ---> mypackage\
                     |
                     ---> HelloWorld.class
                     ---> SupportClass.class
                     ---> UtilClass.class

you make the JVM aware of the package by using the CLASSPATH environment variable.

For example:

set CLASSPATH=D:\myprogram

Does set MODULEPATH command instead make the JVM aware of the location of user-defined modules in the latest versions of Java ?

If so why is classpath command still around and what purpose does it serve now?


问:
Java heap dump & shut down - what order?
I would like to detect an OutOfMemoryError, take a heap dump, and automatically exit the Java program. Say I have the following command-line arguments for my JVM:

```<code>-XX:OnOutOfMemoryError="kill -9 %p"
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/usr/tmp
</code>```

Which happens first? Does the process dump memory and then quit, or the other way around?

答:
You shall use

ExitOnOutOfMemoryError or
  CrashOnOutOfMemoryError

and

HeapDumpOnOutOfMemoryError

OpenJDK JVM (Hotspot) at first takes the heap dump and then crashes out or exits as opted for.

To get a clearer understanding you may refer to JVM source file taking care of this particular logic.

https://hg.openjdk.java.net/jdk8u/jdk8u/hotspot/file/8641949eb21f/src/share/vm/utilities/debug.cpp

Body:
I would like to detect an OutOfMemoryError, take a heap dump, and automatically exit the Java program. Say I have the following command-line arguments for my JVM:

-XX:OnOutOfMemoryError="kill -9 %p"
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/usr/tmp

Which happens first? Does the process dump memory and then quit, or the other way around?