问:
React Need help Syncfusion data grid
Iam new to react and I am trying to make the following.

I want to create a simple username and password form,
then add the data from username and password form and display it in a grid in the same page. Then update the grid every time I add a user (user name and password).

So here is my form where i get the user name only :

```<code>        <div >
              <form onSubmit={this.handleSubmit}>
                  <label htmlFor="username">Enter username</label>
                  <input id="username" name="username" type="text" />
                  <button>Send data!</button>
              </form>
            </div>
</code>```

I want to know how to do this exactly ?
Do i have to create a son file then map it and display it in a grid?
Or can i just save it in the state variable , then display every update ?
Or there is another solution for that?

Edit:  Following is my code,

```<code>    import React from "react";
    import {GridComponent, ColumnsDirective, Page , Inject} from '@syncfusion/ej2-react-grids';
    import productsApi from './getJson'
    import ddata from '../pages/source.json'

      export default class products extends React.Component  {
        constructor() {

          super();
          this.handleSubmit = this.handleSubmit.bind(this);
          this.state =
                  {
                    QrCode : '',
                    newProducts : []
                  }

              }

              // this one is not working at all
        componentDidMount(){
          productsApi.getAll().then( data => {
            this.setState({
              newProducts : data

            } )
           },
           )

        }

        handleSubmit(event) {
          event.preventDefault();
          this.setState({
            QrCode: event.target.elements.username.value}
            );
        }

        render() {

          return (
          <div >

            <div >
                  <form onSubmit={this.handleSubmit}>
                      <label htmlFor="username">Enter username</label>
                      <input id="username" name="username" type="text" />
                      <button>Send data!</button>
                  </form>
                </div>

                <div style={{margin: '10%', marginTop : '5%'}}>

                <GridComponent dataSource={ddata}  allowPaging={true} pageSettings= {{pageSize:100}}>

                    <Inject  services ={[Page]}/>
                </GridComponent>
                </div>

            </div>

          );
        }
      }
</code>```

Here is my sample json,

```<code>[
    {
        "id":0,
        "Qr":1234567891,
        "Stat":"A",
        "name":"Hello world"

    },
    {
        "id":0,
        "Qr":1234567891,
        "Stat":"A",
        "name":"Hello world"

    },
    {
        "id":0,
        "Qr":1234567891,
        "Stat":"A",
        "name":"Hello world"

    },
    {
        "id":0,
        "Qr":1234567891,
        "Stat":"A",
        "name":"Hello world"

    },
    {
        "id":0,
        "Qr":1234567891,
        "Stat":"A",
        "name":"Hello world"

    },
    {
        "id":0,
        "Qr":1234567891,
        "Stat":"A",
        "name":"Hello world"

    }

]
</code>```

I hope you can help me solve that problem .
Thank you

答:
Here is a working sample created on Code Sandbox,

Important things are,

Your class name should be Uppercase like Product.

Since you haven't published the getJson file, I created a one with the given function which basically loads the data from already resolved. Don't duplicate same data with a variable.

Then since you're using SyncFusion Grid, there is created event, don't use ComponentDidMount to bind the grid initially, use created event.

Grid doesn't automatically refreshed in this instance, you need to use SyncFusion way of doing it. That's by getting a ref and use it to access the instance and call refresh.

You can use controlled input for your text boxes instead of using event argument in onSubmit event.

When in onSubmit, you get the already bound items, push your new item with the information from textbox. Then update the state and update the ui.

```<code>import React from "react";
import {
  GridComponent,
  ColumnsDirective,
  Page,
  Inject
} from "@syncfusion/ej2-react-grids";
import productsApi from "./getJson";

export default class Products extends React.Component {
  constructor() {
    super();
    this.handleSubmit = this.handleSubmit.bind(this);
    this.userNameChanged = this.userNameChanged.bind(this);
    this.created = this.created.bind(this);
    this.grid = null;
    this.state = {
      QrCode: "",
      newProducts: [],
      userName: ""
    };
  }

  handleSubmit(event) {
    event.preventDefault();
    let products = this.state.newProducts;
    products.push({
      id: 0,
      Qr: 1234567891,
      Stat: "A",
      name: this.state.userName
    });
    this.setState({
      newProducts: products
    });
    this.grid.refresh();
  }

  userNameChanged(evt) {
    this.setState({
      userName: evt.target.value
    });
  }

  created(){
    productsApi.getAll().then(data => {
      console.log("x", data);
      this.setState({
        newProducts: data
      });

      this.grid.refresh();
    });
  }

  render() {
    console.log(this.state.newProducts);
    return (
      <div>
        <div>
          <form onSubmit={this.handleSubmit}>
            <label htmlFor="username">Enter username</label>
            <input
              onChange={this.userNameChanged}
              value={this.state.userName}
              id="username"
              name="username"
              type="text"
            />
            <button>Send data!</button>
          </form>
        </div>

        <div style={{ margin: "10%", marginTop: "5%" }}>
          <GridComponent
            ref={g => (this.grid = g)}
            dataSource={this.state.newProducts}
            created={this.created}
            allowPaging={true}
            pageSettings={{ pageSize: 100 }}
          >
            <Inject services={[Page]} />
          </GridComponent>
        </div>
      </div>
    );
  }
}
</code>```

getJson file,

```<code>const productsApi = {
  getAll: function() {
    //some ajax request
    return Promise.resolve([
      {
        id: 0,
        Qr: 1234567891,
        Stat: "A",
        name: "Hello world"
      },
      {
        id: 0,
        Qr: 1234567891,
        Stat: "A",
        name: "Hello world"
      },
      {
        id: 0,
        Qr: 1234567891,
        Stat: "A",
        name: "Hello world"
      },
      {
        id: 0,
        Qr: 1234567891,
        Stat: "A",
        name: "Hello world"
      },
      {
        id: 0,
        Qr: 1234567891,
        Stat: "A",
        name: "Hello world"
      },
      {
        id: 0,
        Qr: 1234567891,
        Stat: "A",
        name: "Hello world"
      }
    ]);
  }
};

export default productsApi;
</code>```

Updated codesandbox, https://codesandbox.io/s/magical-euclid-o7ire

Title: React Need help Syncfusion data grid

Body:
Iam new to react and I am trying to make the following.

I want to create a simple username and password form,
then add the data from username and password form and display it in a grid in the same page. Then update the grid every time I add a user (user name and password).

So here is my form where i get the user name only :

              <form onSubmit={this.handleSubmit}>
                  Enter username
                  <input id="username" name="username" type="text" />
                  <button>Send data!</button>
              </form>

I want to know how to do this exactly ?
Do i have to create a son file then map it and display it in a grid?
Or can i just save it in the state variable , then display every update ?
Or there is another solution for that?

Edit:  Following is my code,

    import React from "react";
    import {GridComponent, ColumnsDirective, Page , Inject} from '@syncfusion/ej2-react-grids';
    import productsApi from './getJson'
    import ddata from '../pages/source.json'

      export default class products extends React.Component  {
        constructor() {

          super();
          this.handleSubmit = this.handleSubmit.bind(this);
          this.state =
                  {
                    QrCode : '',
                    newProducts : []
                  }

              }

              // this one is not working at all
        componentDidMount(){
          productsApi.getAll().then( data => {
            this.setState({
              newProducts : data

            } )
           },
           )

        }

        handleSubmit(event) {
          event.preventDefault();
          this.setState({
            QrCode: event.target.elements.username.value}
            );
        }

        render() {

          return (

                  <form onSubmit={this.handleSubmit}>
                      Enter username
                      <input id="username" name="username" type="text" />
                      <button>Send data!</button>
                  </form>

                <GridComponent dataSource={ddata}  allowPaging={true} pageSettings= {{pageSize:100}}>

                    <Inject  services ={[Page]}/>
                </GridComponent>

          );
        }
      }

Here is my sample json,

[
    {
        "id":0,
        "Qr":1234567891,
        "Stat":"A",
        "name":"Hello world"

    },
    {
        "id":0,
        "Qr":1234567891,
        "Stat":"A",
        "name":"Hello world"

    },
    {
        "id":0,
        "Qr":1234567891,
        "Stat":"A",
        "name":"Hello world"

    },
    {
        "id":0,
        "Qr":1234567891,
        "Stat":"A",
        "name":"Hello world"

    },
    {
        "id":0,
        "Qr":1234567891,
        "Stat":"A",
        "name":"Hello world"

    },
    {
        "id":0,
        "Qr":1234567891,
        "Stat":"A",
        "name":"Hello world"

    }

]

I hope you can help me solve that problem .
Thank you

Body:
Here is a working sample created on Code Sandbox,

Important things are,

Your class name should be Uppercase like Product.

Since you haven't published the getJson file, I created a one with the given function which basically loads the data from already resolved. Don't duplicate same data with a variable.

Then since you're using SyncFusion Grid, there is created event, don't use ComponentDidMount to bind the grid initially, use created event.

Grid doesn't automatically refreshed in this instance, you need to use SyncFusion way of doing it. That's by getting a ref and use it to access the instance and call refresh.

You can use controlled input for your text boxes instead of using event argument in onSubmit event.

When in onSubmit, you get the already bound items, push your new item with the information from textbox. Then update the state and update the ui.

import React from "react";
import {
  GridComponent,
  ColumnsDirective,
  Page,
  Inject
} from "@syncfusion/ej2-react-grids";
import productsApi from "./getJson";

export default class Products extends React.Component {
  constructor() {
    super();
    this.handleSubmit = this.handleSubmit.bind(this);
    this.userNameChanged = this.userNameChanged.bind(this);
    this.created = this.created.bind(this);
    this.grid = null;
    this.state = {
      QrCode: "",
      newProducts: [],
      userName: ""
    };
  }

  handleSubmit(event) {
    event.preventDefault();
    let products = this.state.newProducts;
    products.push({
      id: 0,
      Qr: 1234567891,
      Stat: "A",
      name: this.state.userName
    });
    this.setState({
      newProducts: products
    });
    this.grid.refresh();
  }

  userNameChanged(evt) {
    this.setState({
      userName: evt.target.value
    });
  }

  created(){
    productsApi.getAll().then(data => {
      console.log("x", data);
      this.setState({
        newProducts: data
      });

      this.grid.refresh();
    });
  }

  render() {
    console.log(this.state.newProducts);
    return (
      <div>
        <div>
          <form onSubmit={this.handleSubmit}>
            <label htmlFor="username">Enter username</label>
            <input
              onChange={this.userNameChanged}
              value={this.state.userName}
              id="username"
              name="username"
              type="text"
            />
            <button>Send data!</button>
          </form>
        </div>

        <div style={{ margin: "10%", marginTop: "5%" }}>
          <GridComponent
            ref={g => (this.grid = g)}
            dataSource={this.state.newProducts}
            created={this.created}
            allowPaging={true}
            pageSettings={{ pageSize: 100 }}
          >
            <Inject services={[Page]} />
          </GridComponent>
        </div>
      </div>
    );
  }
}

getJson file,

const productsApi = {
  getAll: function() {
    //some ajax request
    return Promise.resolve([
      {
        id: 0,
        Qr: 1234567891,
        Stat: "A",
        name: "Hello world"
      },
      {
        id: 0,
        Qr: 1234567891,
        Stat: "A",
        name: "Hello world"
      },
      {
        id: 0,
        Qr: 1234567891,
        Stat: "A",
        name: "Hello world"
      },
      {
        id: 0,
        Qr: 1234567891,
        Stat: "A",
        name: "Hello world"
      },
      {
        id: 0,
        Qr: 1234567891,
        Stat: "A",
        name: "Hello world"
      },
      {
        id: 0,
        Qr: 1234567891,
        Stat: "A",
        name: "Hello world"
      }
    ]);
  }
};

export default productsApi;

Updated codesandbox, https://codesandbox.io/s/magical-euclid-o7ire


来源: stackexchange

问:
Facebook notification of Wordpress post
Is there a way of sending notification about new wordpress-based blog to facebook account?
Or maybe a plugin for wordpress?

Restriction is that user shouldn't be logged into facebook, just specify facebook credentials to the plugin.

答:
Not that I know of. From what I've researched, one of the ways to do this would be to create a Facebook Connect app (which is NOT a full facebook app). If user decides he/she wishes to grant your website/blog permission to connect to the FB account you will be able to post notifications to their wall, etc.

Resources:
http://developers.facebook.com/connect.php

If you're using ASP .NET:
http://www.codeplex.com/FacebookToolkit

OwnerDisplayName: Roman

LastEditorDisplayName: Roger Pate

ContentLicense: CC BY-SA 2.5

Title: Facebook notification of Wordpress post


问:
Element UI, passing id to table column with checkbox
Is there a way to pass id to el-table-column with selection type? I've tried passing a slot, but then checkbox is not rendering. Here is the code:

```<code><el-table-column>
    <template slot-scope="scope" v-if="scope.row">
      <div :id="`column-${scope.row.name}`">{{ `reports-${scope.row.name}` }}</div>
    </template>
  </el-table-column>
  <el-table-column prop="selected" align="center" type="selection" class-name="checkbox-column">
</el-table-column>
</code>```

First column getting id via scoped slot.

答:
Instead of ID if you are okay with class then use cell-class-name

In your template

```<code><el-table your-attrs ...  :cell-class-name="cellClassName">
</code>```

In your script

```<code>methods: {
  cellClassName({row, column, rowIndex, columnIndex}) {
    if (columnIndex === 1) return `checkbox-${rowIndex}`;
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Is there a way to pass id to el-table-column with selection type? I've tried passing a slot, but then checkbox is not rendering. Here is the code:

<el-table-column>
    <template slot-scope="scope" v-if="scope.row">
      <div :id="`column-${scope.row.name}`">{{ `reports-${scope.row.name}` }}

    </template>
  </el-table-column>
  <el-table-column prop="selected" align="center" type="selection" class-name="checkbox-column">
</el-table-column>

First column getting id via scoped slot.

Body:
Instead of ID if you are okay with class then use cell-class-name

In your template

<el-table your-attrs ...  :cell-class-name="cellClassName">

In your script

methods: {
  cellClassName({row, column, rowIndex, columnIndex}) {
    if (columnIndex === 1) return `checkbox-${rowIndex}`;
  }
}


问:
create a new array from array of arrays
I have this array of arrays:

```<code>let a = [

["i was sent", "i do"],
["i was sent", "i sent"],
["to protect you", "to find you"]

]
</code>```

And I want to return this single array from it:

```<code>b = ["i was sent = i do", "i was sent = i sent", "to protect you = to find you"]
</code>```

How can I do that?

I have tried to use a map like let b = a.map(s => s + ' = '); but it won't do the job?

答:
mine...

let a =
    [ [ "i was sent", "i do"]
    , [ "i was sent", "i sent"]
    , [ "to protect you", "to find you"]
    ]

const jojo=([x,y])=>x+' = '+y

let b = a.map(jojo)

console.log ( b )```

Title: create a new array from array of arrays

Body:
I have this array of arrays:

let a = [

["i was sent", "i do"],
["i was sent", "i sent"],
["to protect you", "to find you"]

]

And I want to return this single array from it:

b = ["i was sent = i do", "i was sent = i sent", "to protect you = to find you"]

How can I do that?

I have tried to use a map like let b = a.map(s => s + ' = '); but it won't do the job?


问:
Scaling down video conference software in Kubernetes
I'm planning to deploy a WebRTC custom videoconference software (based on NodeJS, using websockets) with Kubernetes, but I have some doubts about scaling down this environment.

Actually, I'm planning to use cloud hosted Kubernetes (GKE, EKS, AKS or any) to be able to auto-scale nodes in the cluster to attend the demand increase and decrease. But, scaling up is not the problem, but it's about scaling down.

The cluster will scale down based on some CPU average usage metrics across the cluster, as I understand, and if it tries to remove some node, it will start to drain connections and stop receiving new connections, right? But now, imagine that there's a videoconference still running in this "pending deletion" node. There are two problems:

1 - Stopping the node before the videoconference finishes (it will drop the meeting)

2 - With the draining behaviour when it starts to scale down, it will stop receiving new connections, so if someone tries to join in this running video conference, it will receive a timeout, right?

So, which is the best strategy to scale down nodes for a video conference solution? Any ideas?

Thanks

答:
I would say this is not a matter of resolving it on kubernetes level by some specific scaling strategy but rather application ability to handle such situations. It isn't even specific to kubernetes. Imagine that you deploy it directly on compute instances which are also subject to autoscale and you'll end up in exactly the same situation when the load decreases and one of the instances is removed from the set.

You should rather ask yourself if such application is suitable to be deployed as kubernetes workload. I can imagine that such videoconference session doesn't have to rely on the backend deployed on a single node only. You can even define some affinity or anti-affinity rules to prevent your Pods from being scheduled on the same node. So if the whole application cluster is still up and running (it's Pods are running on different nodes), eviction of a limited subset of Pods should not have a big impact.

You can actually face the same issue with any other application as vast majority of them base on some session which needs to be established between the client software and the server part. I would say it's application responsibility to be able to handle such scenarios. If some of the users unexpectedly loses the connection it should be possible to immediately redirect them to the running instance e.g. different Pod which is still able to accept new requests.

So basically if the application is designed to be highly available, scaling in (when we talk about horizontal scaling we actually talk about scaling in and scaling out) the underyling VMs, or more specifically kubernetes nodes, shouldn't affect it's high availability capabilities. From the other hand if it is not designed to be highly available, solution such as kubernetes probably won't help much.


问:
flutter has a problem with redux dependencies
i have a problem to run my flutter app, it seems flutter doesn't recognize it. i tried to connect to internet while running the project but the problem remains the same, here is the error message:

and here is the code where i inserted the dependency :

```<code>   dependencies:
    redux: ^4.0.0
    flutter_redux: ^0.6.0
</code>```

答: this error was caused by the fact that i named my app REDUX, i changed it and it works now. </p>

Body:
i have a problem to run my flutter app, it seems flutter doesn't recognize it. i tried to connect to internet while running the project but the problem remains the same, here is the error message:

and here is the code where i inserted the dependency :

   dependencies:
    redux: ^4.0.0
    flutter_redux: ^0.6.0


问:
i tried to add viewPager to my project but there is problem
The issue is caused by:

java.lang.ArrayIndexOutOfBoundsException:
      length=0; index=0

at com.example.proje.DetayActivity.onCreate(DetayActivity.java:78)

This page is where i add Viewpager to be shown on the activity. I think there is problem with the arraylist but it looks normal as i couldn't find any problem. Thank you for the help.

```<code>package com.example.proje;
 imports..

public class DetayActivity extends AppCompatActivity {

    ViewPager viewPager;
    LinearLayout sliderDotspanel;
    private int dotscount;
    private ImageView[] dots;
    private ArrayList<String> urls;
    String key;
    TextView txt1;
    TextView txt2;
    TextView txt3;
    TextView txt4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detay);
        setTitle("Detaylar");

        txt1 = findViewById(R.id.txttarih);
        txt2 = findViewById(R.id.txturunadi);
        txt3 = findViewById(R.id.txtfiyati);
        txt4 = findViewById(R.id.txtaciklama);

        Intent intent = getIntent();
        key = intent.getStringExtra("key");
        urls = new ArrayList<>();

        getdata();

        viewPager = findViewById(R.id.viewPager);

        sliderDotspanel = findViewById(R.id.SliderDots);

        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(this , urls);

        viewPager.setAdapter(viewPagerAdapter);

        dotscount = viewPagerAdapter.getCount();
        dots = new ImageView[dotscount];

        for (int i = 0; i < dotscount; i++) {

            dots[i] = new ImageView(this);
            dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.non_active_dot));

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

            params.setMargins(8, 0, 8, 0);

            sliderDotspanel.addView(dots[i], params);
        }

        dots[0].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.active_dot));

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < dotscount; i++) {
                    dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.non_active_dot));
                }
                dots[position].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.active_dot));
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

    }

    private void getdata() {

        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("urunler").child(key);

        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                Urun urun = dataSnapshot.getValue(Urun.class);
                txt1.setText(urun.getTarih());
                txt2.setText(urun.getUrunAdi());
                txt3.setText(Double.toString(urun.getFiyat()));
                txt4.setText(urun.getAciklama());
                urls.add(urun.getResim1());
                urls.add(urun.getResim2());
                urls.add(urun.getResim3());

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
}
}
</code>```

this page is the viewpager adapter

```<code>package com.example.proje;
imports..

public class ViewPagerAdapter extends PagerAdapter {

    private Context context;
    private LayoutInflater layoutInflater;
    private Integer [] images = {R.drawable.logo,R.drawable.doluredkalp,R.drawable.redheart};
    private ArrayList<String> urls = new ArrayList<>();

    public ViewPagerAdapter(Context context , ArrayList<String> urls) {
        this.context = context;
        this.urls = urls;

    }

    @Override
    public int getCount() {
        return urls.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {

        final String url = urls.get(position);

        layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.layoutpager, null);
        ImageView imageView = view.findViewById(R.id.imageView);
        Picasso.get().load(url).placeholder(R.drawable.logo).into(imageView);

        ViewPager vp = (ViewPager) container;
        vp.addView(view, 0);
        return view;
    }
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {

        ViewPager vp = (ViewPager) container;
        View view = (View) object;
        vp.removeView(view);

    }
}
</code>```

答:
Your problem is in line

```<code>dots[0].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.active_dot));
</code>```

dots array is empty and when you trying to get element at index 0 you get this error because there is no element at index 0.

Updated:

You can see that dots is an array with count equals dotscount.

dotscount variable is count of viewPagerAdapter items

You pass to viewPagerAdapter urls array which is empty.

That is the reason why you getting error ArrayIndexOutOfBoundsException

I think you should create dots array in onDataChange method after you populate urls array, this will fix this error

Body:
The issue is caused by:

java.lang.ArrayIndexOutOfBoundsException:
      length=0; index=0

at com.example.proje.DetayActivity.onCreate(DetayActivity.java:78)

This page is where i add Viewpager to be shown on the activity. I think there is problem with the arraylist but it looks normal as i couldn't find any problem. Thank you for the help.

package com.example.proje;
 imports..

public class DetayActivity extends AppCompatActivity {

    ViewPager viewPager;
    LinearLayout sliderDotspanel;
    private int dotscount;
    private ImageView[] dots;
    private ArrayList<String> urls;
    String key;
    TextView txt1;
    TextView txt2;
    TextView txt3;
    TextView txt4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detay);
        setTitle("Detaylar");

        txt1 = findViewById(R.id.txttarih);
        txt2 = findViewById(R.id.txturunadi);
        txt3 = findViewById(R.id.txtfiyati);
        txt4 = findViewById(R.id.txtaciklama);

        Intent intent = getIntent();
        key = intent.getStringExtra("key");
        urls = new ArrayList<>();

        getdata();

        viewPager = findViewById(R.id.viewPager);

        sliderDotspanel = findViewById(R.id.SliderDots);

        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(this , urls);

        viewPager.setAdapter(viewPagerAdapter);

        dotscount = viewPagerAdapter.getCount();
        dots = new ImageView[dotscount];

        for (int i = 0; i < dotscount; i++) {

            dots[i] = new ImageView(this);
            dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.non_active_dot));

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

            params.setMargins(8, 0, 8, 0);

            sliderDotspanel.addView(dots[i], params);
        }

        dots[0].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.active_dot));

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < dotscount; i++) {
                    dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.non_active_dot));
                }
                dots[position].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.active_dot));
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

    }

    private void getdata() {

        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("urunler").child(key);

        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                Urun urun = dataSnapshot.getValue(Urun.class);
                txt1.setText(urun.getTarih());
                txt2.setText(urun.getUrunAdi());
                txt3.setText(Double.toString(urun.getFiyat()));
                txt4.setText(urun.getAciklama());
                urls.add(urun.getResim1());
                urls.add(urun.getResim2());
                urls.add(urun.getResim3());

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
}
}

this page is the viewpager adapter

package com.example.proje;
imports..

public class ViewPagerAdapter extends PagerAdapter {

    private Context context;
    private LayoutInflater layoutInflater;
    private Integer [] images = {R.drawable.logo,R.drawable.doluredkalp,R.drawable.redheart};
    private ArrayList<String> urls = new ArrayList<>();

    public ViewPagerAdapter(Context context , ArrayList<String> urls) {
        this.context = context;
        this.urls = urls;

    }

    @Override
    public int getCount() {
        return urls.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {

        final String url = urls.get(position);

        layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.layoutpager, null);
        ImageView imageView = view.findViewById(R.id.imageView);
        Picasso.get().load(url).placeholder(R.drawable.logo).into(imageView);

        ViewPager vp = (ViewPager) container;
        vp.addView(view, 0);
        return view;
    }
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {

        ViewPager vp = (ViewPager) container;
        View view = (View) object;
        vp.removeView(view);

    }
}

Body:
Your problem is in line

dots[0].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.active_dot));

dots array is empty and when you trying to get element at index 0 you get this error because there is no element at index 0.

Updated:

You can see that dots is an array with count equals dotscount.

dotscount variable is count of viewPagerAdapter items

You pass to viewPagerAdapter urls array which is empty.

That is the reason why you getting error ArrayIndexOutOfBoundsException

I think you should create dots array in onDataChange method after you populate urls array, this will fix this error


问:
Flutter: Setting constraints for package versions in pubspec.yaml
I used share package, share pacakge document said add like this,

```<code> share: ">=0.6.y+x <2.0.0"
</code>```

Please set your constraint to share: '>=0.6.y+x <2.0.0'

after run pub get, I got this error,

```<code>Error on line 65, column 10 of pubspec.yaml: Invalid version constraint: Expected version number after ">=" in ">=0.6.y+x <2.0.0", got "0.6.y+x <2.0.0".

   ╷

65 │   share: ">=0.6.y+x <2.0.0"

   │          ^^^^^^^^^^^^^^^^^^

   ╵
pub get failed (65;    ╵)
</code>```

答:
You can go to the pub description of the package to get the exact versioning.

Or

Here's a short cut:

Try to give "any" instead of the version number in pubspec.yaml like:

```<code>share: any
</code>```

Then go to pubspec.lock, you will find the latest version that the framework has picked for you.

You might not want to leave it as "any" because if anything changes in the future update, maybe new feature or some deprecation. Your code might crash. It is advised to take the version number from .lock file and pass it in .yaml file (exactly as is it shown in .lock).

Setting constraints:

If you want a specific update of the plugin then you can set constraint for the version number as follows:

```<code>plugin_name: '>=1.0.0 <2.0.0' //change these values according to your specs
</code>```

For your specific requirement:

```<code>share: '>=0.6.4+3 <2.0.0'
</code>```

Body:
I used share package, share pacakge document said add like this,

 share: ">=0.6.y+x <2.0.0"

Please set your constraint to share: '>=0.6.y+x <2.0.0'

after run pub get, I got this error,

Error on line 65, column 10 of pubspec.yaml: Invalid version constraint: Expected version number after ">=" in ">=0.6.y+x <2.0.0", got "0.6.y+x <2.0.0".

   ╷

65 │   share: ">=0.6.y+x <2.0.0"

   │          ^^^^^^^^^^^^^^^^^^

   ╵
pub get failed (65;    ╵)

Body:
You can go to the pub description of the package to get the exact versioning.

Or

Here's a short cut:

Try to give "any" instead of the version number in pubspec.yaml like:

share: any

Then go to pubspec.lock, you will find the latest version that the framework has picked for you.

You might not want to leave it as "any" because if anything changes in the future update, maybe new feature or some deprecation. Your code might crash. It is advised to take the version number from .lock file and pass it in .yaml file (exactly as is it shown in .lock).

Setting constraints:

If you want a specific update of the plugin then you can set constraint for the version number as follows:

plugin_name: '>=1.0.0 <2.0.0' //change these values according to your specs

For your specific requirement:

share: '>=0.6.4+3 <2.0.0'


问:
How to clear UISearchBar background color in iOS10 Swift?
There are older version of this question for older versions of iOS no longer works due to the layout changes in UISearchBar.

I've tried the following to completely remove the background color of UISearchBar but it doesn't work. (I tried to look up the hierarchy views of it but xCode kept crashing for this option.)

```<code>private func clearBackgroundColor() {
    for view in self.subviews {
        view.backgroundColor = UIColor.clear
        for subview in view.subviews {
            subview.backgroundColor = UIColor.clear
        }
    }
}
</code>```

Any ideas or suggestions?

Thanks!!

答:
```<code>let searchBar = UISearchBar()
searchBar.backgroundImage = UIImage()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
There are older version of this question for older versions of iOS no longer works due to the layout changes in UISearchBar.

I've tried the following to completely remove the background color of UISearchBar but it doesn't work. (I tried to look up the hierarchy views of it but xCode kept crashing for this option.)

private func clearBackgroundColor() {
    for view in self.subviews {
        view.backgroundColor = UIColor.clear
        for subview in view.subviews {
            subview.backgroundColor = UIColor.clear
        }
    }
}

Any ideas or suggestions?

Thanks!!


问:
How Can A .dll File Read a .txt File?
I would like my Browser Helper Object which is simply a .dll, to be able to read a text file. I have tried using a pointer to a FILE, as well as ifstream in("file name goes here"). Before implementing these two methods of reading files into the BHO, I tested them individually, and made sure each example dealt with similar data types and locations. Both of them worked without a problem, yet testing the BHO reveals that the file cant even be opened. I have searched google for an alternative method, and after exhausting all other options, I'm hoping that someone would be able to provide me with some guidance/resource. Anything is appreciated; I will keep trying to find a solution and will post what I can in the event that someone else may have the same problem.</p>

答:
I think you might be a victim of the IE protected mode.

http://www.codeproject.com/KB/vista-security/PMSurvivalGuide.aspx

Under protected mode your addin might not have access to registry and file system as you might like.

Title: How Can A .dll File Read a .txt File?


问:
section not appearing below header
I'm trying to position my section below the header but it appears right below the nav. Also, the header only appears to be the nav and not the entire viewport of the page. I'm trying to figure out if I made a mistake on the CSS part of the code or if my HTML is structured wrong.
This is what I have so far:

```<code><body>

<header class="header-content">
    <nav>
        <div class="nav-wrapper">
            <div class="left-side">
                <div class="nav-link-wrapper active-nav-link">
                    <a href="index.html">Home</a>
                </div>
                <div class="nav-link-wrapper">
                    <a href="mailto:wrvn.co@gmail.com">Email</a>
                </div>
                <div class="nav-link-wrapper">
                    <a href="resume.html">Resume</a>
                </div>
            </div>

            <div class="right-side">
                <div class="name">
                    <a href="index.html">brand</a>
                </div>
            </div>
            </div>
            </nav>
    <div class="hero-text-box">
        <h2>Hello,<br>
            I'm a web designer and developer based in Florida. My main focus is to
            build minimalistic web sites that you can surf through as quickly and
            efficient as posible.
        </h2>
        <h2 class="typewriter">Take a look at my work!</h2>
    </div>
</header>

<section class="project-display">
    <h1>Projects</h1>

</section>
</code>```

```<code>    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
body, html {
    margin: 0;
}

.header-content{
    clear: both;
    top: 0;
    width: 100%;
    margin: 0;
    height: 100%;
    left: 0px;
    margin-left: 0;
    margin-bottom: 20px;
}

/* --- Nav Style --- */
.nav-wrapper {
    display: flex;
    justify-content: space-between;
    padding: 40px;
    color: transparent;
}

/* left side */
.left-side {
    display: flex;
}

.nav-wrapper > .left-side > div {
    margin-right: 20px;
    font-size: 0.9em;
    text-transform: uppercase;
}
.nav-link-wrapper {
    height: 22px;
    border-bottom: 1px solid transparent;
    transition: border-bottom 0.5s;
}

.nav-link-wrapper a {
    color: #8a8a8a;
    text-decoration: none;
    transition: color 0.5s;
}
.nav-link-wrapper:hover {
    border-bottom: 1px solid black;
}
.nav-link-wrapper a:hover {
    color: black;
}

.active-nav-link {
    border-bottom: 1px solid black;
}
.active-nav-link a {
    color: black !important;
}

/* right side */
.nav-wrapper > .right-side > div {
    margin-right: 20px;
    font-size: 100%;
    text-transform: uppercase;
}
.name a {
    color: black;
    text-decoration: none;
    transition: color 0.5s;
}

.hero-text-box {
    position: absolute;
    width: 800px;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
h2, .typewriter {
    margin-bottom: 0;
    margin-top: 0;
}

.hero-text-box h2, .typewriter {
    font-size: 30px;
    word-spacing: 2px;
    text-align: left;
    letter-spacing: 1px;
    color: rgb(83, 83, 83);
}

.typewriter {
    width: 44%;
    border-right: solid 2px black;
    white-space: nowrap;
    overflow: hidden;
    color: black;
}
/* Animation */
.typewriter {
    animation: animated-text 4s steps(29,end) 1s 1 normal both,
               animated-cursor 600ms steps(29,end) infinite;
}

  /* text animation */

  @keyframes animated-text{
    from{width: 0;}
    to{width: 44%;}
}

  /* cursor animations */

  @keyframes animated-cursor{
    from{border-right-color: black;}
    to{border-right-color: transparent;}
}

/* --- Project Styles --- */
.section {
    clear: both;
    padding: 0px;
    margin: 0px;
} ```

```

答:
Hi greetings for the day.

Here is the answer

Correction is : just add margin-top : 10% in section class.

body, html {
    margin: 0;
}

.header-content{
    clear: both;
    top: 0;
    width: 100%;
    margin: 0;
    height: 100%;
    left: 0px;
    margin-left: 0;
    margin-bottom: 20px;
}

/* --- Nav Style --- */
.nav-wrapper {
    display: flex;
    justify-content: space-between;
    padding: 40px;
    color: transparent;
}

/* left side */
.left-side {
    display: flex;
}

.nav-wrapper > .left-side > div {
    margin-right: 20px;
    font-size: 0.9em;
    text-transform: uppercase;
}
.nav-link-wrapper {
    height: 22px;
    border-bottom: 1px solid transparent;
    transition: border-bottom 0.5s;
}

.nav-link-wrapper a {
    color: #8a8a8a;
    text-decoration: none;
    transition: color 0.5s;
}
.nav-link-wrapper:hover {
    border-bottom: 1px solid black;
}
.nav-link-wrapper a:hover {
    color: black;
}

.active-nav-link {
    border-bottom: 1px solid black;
}
.active-nav-link a {
    color: black !important;
}

/* right side */
.nav-wrapper > .right-side > div {
    margin-right: 20px;
    font-size: 100%;
    text-transform: uppercase;
}
.name a {
    color: black;
    text-decoration: none;
    transition: color 0.5s;
}

.hero-text-box {
    position: absolute;
    width: 800px;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
h2, .typewriter {
    margin-bottom: 0;
    margin-top: 0;
}

.hero-text-box h2, .typewriter {
    font-size: 30px;
    word-spacing: 2px;
    text-align: left;
    letter-spacing: 1px;
    color: rgb(83, 83, 83);
}

.typewriter {
    width: 44%;
    border-right: solid 2px black;
    white-space: nowrap;
    overflow: hidden;
    color: black;
}
/* Animation */
.typewriter {
    animation: animated-text 4s steps(29,end) 1s 1 normal both,
               animated-cursor 600ms steps(29,end) infinite;
}

  /* text animation */

  @keyframes animated-text{
    from{width: 0;}
    to{width: 44%;}
}

  /* cursor animations */

  @keyframes animated-cursor{
    from{border-right-color: black;}
    to{border-right-color: transparent;}
}

/* --- Project Styles --- */
.section {
    clear: both;
    padding: 5px;
    margin-top:10%;
} ```</code>```

                    Home

                    Email

                    Resume

                    brand

Hello,

            I'm a web designer and developer based in Florida. My main focus is to
            build minimalistic web sites that you can surf through as quickly and
            efficient as posible.

Take a look at my work!

Projects

    ```

Title: section not appearing below header

Body:
I'm trying to position my section below the header but it appears right below the nav. Also, the header only appears to be the nav and not the entire viewport of the page. I'm trying to figure out if I made a mistake on the CSS part of the code or if my HTML is structured wrong.
This is what I have so far:

                    Home

                    Email

                    Resume

                    brand

Hello,

            I'm a web designer and developer based in Florida. My main focus is to
            build minimalistic web sites that you can surf through as quickly and
            efficient as posible.

Take a look at my work!

Projects

    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
body, html {
    margin: 0;
}

.header-content{
    clear: both;
    top: 0;
    width: 100%;
    margin: 0;
    height: 100%;
    left: 0px;
    margin-left: 0;
    margin-bottom: 20px;
}

/* --- Nav Style --- */
.nav-wrapper {
    display: flex;
    justify-content: space-between;
    padding: 40px;
    color: transparent;
}

/* left side */
.left-side {
    display: flex;
}

.nav-wrapper > .left-side > div {
    margin-right: 20px;
    font-size: 0.9em;
    text-transform: uppercase;
}
.nav-link-wrapper {
    height: 22px;
    border-bottom: 1px solid transparent;
    transition: border-bottom 0.5s;
}

.nav-link-wrapper a {
    color: #8a8a8a;
    text-decoration: none;
    transition: color 0.5s;
}
.nav-link-wrapper:hover {
    border-bottom: 1px solid black;
}
.nav-link-wrapper a:hover {
    color: black;
}

.active-nav-link {
    border-bottom: 1px solid black;
}
.active-nav-link a {
    color: black !important;
}

/* right side */
.nav-wrapper > .right-side > div {
    margin-right: 20px;
    font-size: 100%;
    text-transform: uppercase;
}
.name a {
    color: black;
    text-decoration: none;
    transition: color 0.5s;
}

.hero-text-box {
    position: absolute;
    width: 800px;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
h2, .typewriter {
    margin-bottom: 0;
    margin-top: 0;
}

.hero-text-box h2, .typewriter {
    font-size: 30px;
    word-spacing: 2px;
    text-align: left;
    letter-spacing: 1px;
    color: rgb(83, 83, 83);
}

.typewriter {
    width: 44%;
    border-right: solid 2px black;
    white-space: nowrap;
    overflow: hidden;
    color: black;
}
/* Animation */
.typewriter {
    animation: animated-text 4s steps(29,end) 1s 1 normal both,
               animated-cursor 600ms steps(29,end) infinite;
}

  /* text animation */

  @keyframes animated-text{
    from{width: 0;}
    to{width: 44%;}
}

  /* cursor animations */

  @keyframes animated-cursor{
    from{border-right-color: black;}
    to{border-right-color: transparent;}
}

/* --- Project Styles --- */
.section {
    clear: both;
    padding: 0px;
    margin: 0px;
} ```

Body:
Hi greetings for the day.

Here is the answer

Correction is : just add margin-top : 10% in section class.

body, html {
    margin: 0;
}

.header-content{
    clear: both;
    top: 0;
    width: 100%;
    margin: 0;
    height: 100%;
    left: 0px;
    margin-left: 0;
    margin-bottom: 20px;
}

/* --- Nav Style --- */
.nav-wrapper {
    display: flex;
    justify-content: space-between;
    padding: 40px;
    color: transparent;
}

/* left side */
.left-side {
    display: flex;
}

.nav-wrapper > .left-side > div {
    margin-right: 20px;
    font-size: 0.9em;
    text-transform: uppercase;
}
.nav-link-wrapper {
    height: 22px;
    border-bottom: 1px solid transparent;
    transition: border-bottom 0.5s;
}

.nav-link-wrapper a {
    color: #8a8a8a;
    text-decoration: none;
    transition: color 0.5s;
}
.nav-link-wrapper:hover {
    border-bottom: 1px solid black;
}
.nav-link-wrapper a:hover {
    color: black;
}

.active-nav-link {
    border-bottom: 1px solid black;
}
.active-nav-link a {
    color: black !important;
}

/* right side */
.nav-wrapper > .right-side > div {
    margin-right: 20px;
    font-size: 100%;
    text-transform: uppercase;
}
.name a {
    color: black;
    text-decoration: none;
    transition: color 0.5s;
}

.hero-text-box {
    position: absolute;
    width: 800px;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
h2, .typewriter {
    margin-bottom: 0;
    margin-top: 0;
}

.hero-text-box h2, .typewriter {
    font-size: 30px;
    word-spacing: 2px;
    text-align: left;
    letter-spacing: 1px;
    color: rgb(83, 83, 83);
}

.typewriter {
    width: 44%;
    border-right: solid 2px black;
    white-space: nowrap;
    overflow: hidden;
    color: black;
}
/* Animation */
.typewriter {
    animation: animated-text 4s steps(29,end) 1s 1 normal both,
               animated-cursor 600ms steps(29,end) infinite;
}

  /* text animation */

  @keyframes animated-text{
    from{width: 0;}
    to{width: 44%;}
}

  /* cursor animations */

  @keyframes animated-cursor{
    from{border-right-color: black;}
    to{border-right-color: transparent;}
}

/* --- Project Styles --- */
.section {
    clear: both;
    padding: 5px;
    margin-top:10%;
} ```

<body>

<header class="header-content">
    <nav>
        <div class="nav-wrapper">
            <div class="left-side">
                <div class="nav-link-wrapper active-nav-link">
                    <a href="index.html">Home</a>
                </div>
                <div class="nav-link-wrapper">
                    <a href="mailto:wrvn.co@gmail.com">Email</a>
                </div>
                <div class="nav-link-wrapper">
                    <a href="resume.html">Resume</a>
                </div>
            </div>

            <div class="right-side">
                <div class="name">
                    <a href="index.html">brand</a>
                </div>
            </div>
            </div>

    <div class="hero-text-box">
        <h2>Hello,<br>
            I'm a web designer and developer based in Florida. My main focus is to
            build minimalistic web sites that you can surf through as quickly and
            efficient as posible.
        </h2>
        <h2 class="typewriter">Take a look at my work!</h2>
    </div>
      </nav>
</header>
<div class="section">
      <h1>Projects</h1>
  </div>

  </body>


问:
Extract specific dictionaries from a list of nested dictionaries to a temp list
I have been struggling to extract sub dictionaries where the value is "0" from a list of dictionaries and add them to temporary dictionaries.

I tried this:

new_users = [{'user1':{'book1':'0', 'book2':'4', 'book3':'1'}},{'user2':{'book1':'5', 'book2':'1', 'book3':'0'}}]
    def approachA():
        for data in new_users:          # new_users is a list of nested dictionaries
            if data == '0':
                 print("found 0")
                 keys = data.keys()
                 for key in keys:
                     if key == '0':
                        key.pop() # tried to deleted delete the elements at first
```

<p>It did not work for some reason, and I have been trying to do it for 2 hours so please do not ask questions not related to the problem.</p>

<p>This is a simple version of what I am trying to do:</p>

<pre class="lang-py prettyprint-override"><code>[{'user1':{'book1':'0', 'book2':'4', 'book3':'1'}},{'user2':{'book1':'5', 'book2':'1', 'book3':'0'}}] -> [{'user1':{'book1':'0'}}, {'user2':{'book3':'0'}}]
</code>```

So basically the keys with value "0" get copied to a temp list of dictionaries.

答:
This should accomplish the "sample" snippet. Please give some additional details if this is not what you were trying. </p>

```<code>def solve_nested(nested_dict: list) -> list:
    result = list()
    for dictionary in nested_dict:
        for k, v in dictionary.items():
            for _k, _v in v.items():
                if _v == '0':
                    result.append({_k: _v})
    return result

if __name__ == '__main__':
    print(solve_nested([{"name": {"book1": "0", "book2": "1", "book3": "0"}}]))
</code>```

Body:
I have been struggling to extract sub dictionaries where the value is "0" from a list of dictionaries and add them to temporary dictionaries.

I tried this:

new_users = [{'user1':{'book1':'0', 'book2':'4', 'book3':'1'}},{'user2':{'book1':'5', 'book2':'1', 'book3':'0'}}]
    def approachA():
        for data in new_users:          # new_users is a list of nested dictionaries
            if data == '0':
                 print("found 0")
                 keys = data.keys()
                 for key in keys:
                     if key == '0':
                        key.pop() # tried to deleted delete the elements at first

It did not work for some reason, and I have been trying to do it for 2 hours so please do not ask questions not related to the problem.

This is a simple version of what I am trying to do:

[{'user1':{'book1':'0', 'book2':'4', 'book3':'1'}},{'user2':{'book1':'5', 'book2':'1', 'book3':'0'}}] -> [{'user1':{'book1':'0'}}, {'user2':{'book3':'0'}}]

So basically the keys with value "0" get copied to a temp list of dictionaries.

Body:
This should accomplish the "sample" snippet. Please give some additional details if this is not what you were trying.

def solve_nested(nested_dict: list) -> list:
    result = list()
    for dictionary in nested_dict:
        for k, v in dictionary.items():
            for _k, _v in v.items():
                if _v == '0':
                    result.append({_k: _v})
    return result

if __name__ == '__main__':
    print(solve_nested([{"name": {"book1": "0", "book2": "1", "book3": "0"}}]))


问:
How to change URL Query Parameters from a users Edit Text input?
The goal of the code is to query the google api for a list of books that the user has chosen. The app takes the text inputted in the editText field, and when the user clicks the search button, the query parameter in the query url should be changed to the inputted text then another network request is made using a loader. I can't seem to get this to function. Below is the code:

Query URLS

```<code>private static String queryUrl = "https://www.googleapis.com/books/v1/volumes?q=android&maxResults=20&orderBy=relevance";
private static String baseUrl = "https://www.googleapis.com/books/v1/volumes?";
</code>```

Search Button On Click

```<code>    //Method that takes the current URL and modifies it based on what the user searched
private void searchButtonOnClick() {
    Log.d(LOG_TAG, "searchButtonOnClick was called");

    //Get the user input
    if (TextUtils.isEmpty(editText.getText())) {
        Toast.makeText(this, "No Search Entered", Toast.LENGTH_SHORT).show();
    } else {

        Uri.Builder uriBuilder = new Uri.Builder();
        uriBuilder.scheme("https")
                .authority("www.googleapis.com")
                .appendPath("books")
                .appendPath("v1")
                .appendPath("volumes")
                .appendQueryParameter("q", editText.getText().toString())
                .appendQueryParameter("maxResults", "100")
                .appendQueryParameter("orderBy", "relevance");
        queryUrl = uriBuilder.build().toString();

        LoaderManager loaderManager = getSupportLoaderManager();
        booksListAdapter.clear();
        loaderManager.initLoader(BOOK_LOADER_ID, null, this);

    }
}
</code>```

Full MainActivity Class

```<code>package com.example.booksearch;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.Loader;

import android.net.Uri.Builder;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;

import java.lang.reflect.Array;
import java.net.NetworkInterface;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<Book>> {

    //Log tag for debugging purposes
    public static final String LOG_TAG = MainActivity.class.getSimpleName();

    //Getting title author and image, link book to where to buy when clicked
    private static String input = "";
    private static String queryUrl = "https://www.googleapis.com/books/v1/volumes?q=android&maxResults=20&orderBy=relevance";
    private static String baseUrl = "https://www.googleapis.com/books/v1/volumes?";
    private EditText editText;
    private List<Book> books = new ArrayList<>();
    private static BooksListAdapter booksListAdapter;
    private static int BOOK_LOADER_ID;
    private Button searchButton;
    private TextView emptyTextView;
    private ImageView imageView;
    private ProgressBar loadProgressIndicator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Hook up search button
        searchButton = findViewById(R.id.search_button);

        //Hook up editText
        editText = findViewById(R.id.search_edit_text);

        //setting up searchButtonOnclickListener
        searchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                searchButtonOnClick();
            }
        });

        //Get a connectivity Manager to monitor network state
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);

        //Get details about the devices network
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

        //Hook up the empty textView
        emptyTextView = findViewById(R.id.empty_text_view);

        //Hook up progress indicator
        loadProgressIndicator = findViewById(R.id.loading_data_progress_indicator);

        //If there is a network connection fetch data if not, set the text on the empty text view accordingly
        if (networkInfo != null && networkInfo.isConnected()) {
            LoaderManager loaderManager = getSupportLoaderManager();
            loaderManager.initLoader(BOOK_LOADER_ID, null, this);

        } else {
            //if no internet connection display error message
            loadProgressIndicator.setVisibility(View.GONE);
            emptyTextView.setText(R.string.no_internet);
        }
        // the Book objects are added to this array list off the main thread, thats why the adapter is set to an empty array list.
        //This line of code will always be executed before the asynchonous Load is done, because it's on the main thread.
        booksListAdapter = new BooksListAdapter(this, new ArrayList<Book>());

        ListView bookListView = findViewById(R.id.book_list_view);

        bookListView.setAdapter(booksListAdapter);
        bookListView.setEmptyView(emptyTextView);

        //Set onclick listener on the list to send the user to where to buy the book
        bookListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Book currentBook = booksListAdapter.getItem(position);

                //Check to see if there is a place to buy the book before sending the user off
                if (currentBook.getWhereToBuyBook().isEmpty()) {
                    Toast.makeText(MainActivity.this, "Cannot find where to purchase", Toast.LENGTH_SHORT).show();

                } else {
                    Uri bookURi = Uri.parse(currentBook.getWhereToBuyBook());
                    //Creating an intent to send the user to a website
                    Intent websiteIntent = new Intent(Intent.ACTION_VIEW, bookURi);

                    //send the intent to another app that can handle it
                    startActivity(websiteIntent);

                }

            }

        });
    }

    @NonNull
    @Override
    public Loader<List<Book>> onCreateLoader(int id, @Nullable Bundle args) {
        return new BookLoader(this, queryUrl);
    }

    @Override
    public void onLoadFinished(@NonNull Loader<List<Book>> loader, List<Book> data) {
        //After the first results load check for internet connectivity to avoid error message loading at app startup
        ConnectivityManager cm = (ConnectivityManager) this.getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        if (networkInfo == null) {
            emptyTextView.setText(R.string.no_internet);
        } else if (networkInfo != null && networkInfo.isConnected()) {
            //display when there is internet but there were no results
            emptyTextView.setText(R.string.no_books_found);
        }

        booksListAdapter.clear();

        //If there is a valid list of books, add them to the dataset, this will trigger the listview to update
        if (data != null && !data.isEmpty()) {
            booksListAdapter.addAll(data);
        } else {
            emptyTextView.setText(R.string.no_books_found);
        }

        loadProgressIndicator.setVisibility(View.GONE);

    }

    @Override
    public void onLoaderReset(@NonNull Loader<List<Book>> loader) {
        booksListAdapter.clear();
    }

    //Method that takes the current URL and modifies it based on what the user searched
    private void searchButtonOnClick() {
        Log.d(LOG_TAG, "searchButtonOnClick was called");

        //Get the user input
        if (TextUtils.isEmpty(editText.getText())) {
            Toast.makeText(this, "No Search Entered", Toast.LENGTH_SHORT).show();
        } else {
            Uri buildUri = Uri.parse(baseUrl);
            Uri.Builder uriBuilder = new Uri.Builder();
            buildUri.buildUpon();

            uriBuilder.scheme("https")
                    .authority("www.googleapis.com")
                    .appendPath("books")
                    .appendPath("v1")
                    .appendPath("volumes")
                    .appendQueryParameter("q", editText.getText().toString())
                    .appendQueryParameter("maxResults", "100")
                    .appendQueryParameter("orderBy", "relevance");
            queryUrl = uriBuilder.build().toString();

            booksListAdapter.clear();
            LoaderManager loaderManager = getSupportLoaderManager();
            loaderManager.restartLoader(BOOK_LOADER_ID, null, this);
            loaderManager.initLoader(BOOK_LOADER_ID, null, this).forceLoad();

        }
    }
</code>```

}

答:
As per the code snippet you have shared, .appendQueryParameter("q", editText.getText().toString()) is taking the query param already. Can you explain a bit more, what exactly is the issue you are facing?

Update:
Change your query to --

```<code>private static String baseUrl = "https://www.googleapis.com/books/v1/volumes?maxResults=20&orderBy=relevance&q=";
</code>```

Change your else block to this -

```<code>else {
        queryUrl = baseUrl + editText.getText().toString();
        LoaderManager loaderManager = getSupportLoaderManager();
        booksListAdapter.clear();
        loaderManager.initLoader(BOOK_LOADER_ID, null, this);
}
</code>```

Body:
The goal of the code is to query the google api for a list of books that the user has chosen. The app takes the text inputted in the editText field, and when the user clicks the search button, the query parameter in the query url should be changed to the inputted text then another network request is made using a loader. I can't seem to get this to function. Below is the code:

Query URLS

private static String queryUrl = "https://www.googleapis.com/books/v1/volumes?q=android&maxResults=20&orderBy=relevance";
private static String baseUrl = "https://www.googleapis.com/books/v1/volumes?";

Search Button On Click

    //Method that takes the current URL and modifies it based on what the user searched
private void searchButtonOnClick() {
    Log.d(LOG_TAG, "searchButtonOnClick was called");

    //Get the user input
    if (TextUtils.isEmpty(editText.getText())) {
        Toast.makeText(this, "No Search Entered", Toast.LENGTH_SHORT).show();
    } else {

        Uri.Builder uriBuilder = new Uri.Builder();
        uriBuilder.scheme("https")
                .authority("www.googleapis.com")
                .appendPath("books")
                .appendPath("v1")
                .appendPath("volumes")
                .appendQueryParameter("q", editText.getText().toString())
                .appendQueryParameter("maxResults", "100")
                .appendQueryParameter("orderBy", "relevance");
        queryUrl = uriBuilder.build().toString();

        LoaderManager loaderManager = getSupportLoaderManager();
        booksListAdapter.clear();
        loaderManager.initLoader(BOOK_LOADER_ID, null, this);

    }
}

Full MainActivity Class

package com.example.booksearch;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.Loader;

import android.net.Uri.Builder;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;

import java.lang.reflect.Array;
import java.net.NetworkInterface;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<Book>> {

    //Log tag for debugging purposes
    public static final String LOG_TAG = MainActivity.class.getSimpleName();

    //Getting title author and image, link book to where to buy when clicked
    private static String input = "";
    private static String queryUrl = "https://www.googleapis.com/books/v1/volumes?q=android&maxResults=20&orderBy=relevance";
    private static String baseUrl = "https://www.googleapis.com/books/v1/volumes?";
    private EditText editText;
    private List<Book> books = new ArrayList<>();
    private static BooksListAdapter booksListAdapter;
    private static int BOOK_LOADER_ID;
    private Button searchButton;
    private TextView emptyTextView;
    private ImageView imageView;
    private ProgressBar loadProgressIndicator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Hook up search button
        searchButton = findViewById(R.id.search_button);

        //Hook up editText
        editText = findViewById(R.id.search_edit_text);

        //setting up searchButtonOnclickListener
        searchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                searchButtonOnClick();
            }
        });

        //Get a connectivity Manager to monitor network state
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);

        //Get details about the devices network
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

        //Hook up the empty textView
        emptyTextView = findViewById(R.id.empty_text_view);

        //Hook up progress indicator
        loadProgressIndicator = findViewById(R.id.loading_data_progress_indicator);

        //If there is a network connection fetch data if not, set the text on the empty text view accordingly
        if (networkInfo != null && networkInfo.isConnected()) {
            LoaderManager loaderManager = getSupportLoaderManager();
            loaderManager.initLoader(BOOK_LOADER_ID, null, this);

        } else {
            //if no internet connection display error message
            loadProgressIndicator.setVisibility(View.GONE);
            emptyTextView.setText(R.string.no_internet);
        }
        // the Book objects are added to this array list off the main thread, thats why the adapter is set to an empty array list.
        //This line of code will always be executed before the asynchonous Load is done, because it's on the main thread.
        booksListAdapter = new BooksListAdapter(this, new ArrayList<Book>());

        ListView bookListView = findViewById(R.id.book_list_view);

        bookListView.setAdapter(booksListAdapter);
        bookListView.setEmptyView(emptyTextView);

        //Set onclick listener on the list to send the user to where to buy the book
        bookListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Book currentBook = booksListAdapter.getItem(position);

                //Check to see if there is a place to buy the book before sending the user off
                if (currentBook.getWhereToBuyBook().isEmpty()) {
                    Toast.makeText(MainActivity.this, "Cannot find where to purchase", Toast.LENGTH_SHORT).show();

                } else {
                    Uri bookURi = Uri.parse(currentBook.getWhereToBuyBook());
                    //Creating an intent to send the user to a website
                    Intent websiteIntent = new Intent(Intent.ACTION_VIEW, bookURi);

                    //send the intent to another app that can handle it
                    startActivity(websiteIntent);

                }

            }

        });
    }

    @NonNull
    @Override
    public Loader<List<Book>> onCreateLoader(int id, @Nullable Bundle args) {
        return new BookLoader(this, queryUrl);
    }

    @Override
    public void onLoadFinished(@NonNull Loader<List<Book>> loader, List<Book> data) {
        //After the first results load check for internet connectivity to avoid error message loading at app startup
        ConnectivityManager cm = (ConnectivityManager) this.getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        if (networkInfo == null) {
            emptyTextView.setText(R.string.no_internet);
        } else if (networkInfo != null && networkInfo.isConnected()) {
            //display when there is internet but there were no results
            emptyTextView.setText(R.string.no_books_found);
        }

        booksListAdapter.clear();

        //If there is a valid list of books, add them to the dataset, this will trigger the listview to update
        if (data != null && !data.isEmpty()) {
            booksListAdapter.addAll(data);
        } else {
            emptyTextView.setText(R.string.no_books_found);
        }

        loadProgressIndicator.setVisibility(View.GONE);

    }

    @Override
    public void onLoaderReset(@NonNull Loader<List<Book>> loader) {
        booksListAdapter.clear();
    }

    //Method that takes the current URL and modifies it based on what the user searched
    private void searchButtonOnClick() {
        Log.d(LOG_TAG, "searchButtonOnClick was called");

        //Get the user input
        if (TextUtils.isEmpty(editText.getText())) {
            Toast.makeText(this, "No Search Entered", Toast.LENGTH_SHORT).show();
        } else {
            Uri buildUri = Uri.parse(baseUrl);
            Uri.Builder uriBuilder = new Uri.Builder();
            buildUri.buildUpon();

            uriBuilder.scheme("https")
                    .authority("www.googleapis.com")
                    .appendPath("books")
                    .appendPath("v1")
                    .appendPath("volumes")
                    .appendQueryParameter("q", editText.getText().toString())
                    .appendQueryParameter("maxResults", "100")
                    .appendQueryParameter("orderBy", "relevance");
            queryUrl = uriBuilder.build().toString();

            booksListAdapter.clear();
            LoaderManager loaderManager = getSupportLoaderManager();
            loaderManager.restartLoader(BOOK_LOADER_ID, null, this);
            loaderManager.initLoader(BOOK_LOADER_ID, null, this).forceLoad();

        }
    }

}

Body:
As per the code snippet you have shared, .appendQueryParameter("q", editText.getText().toString()) is taking the query param already. Can you explain a bit more, what exactly is the issue you are facing?

Update:
Change your query to --

private static String baseUrl = "https://www.googleapis.com/books/v1/volumes?maxResults=20&orderBy=relevance&q=";

Change your else block to this -

else {
        queryUrl = baseUrl + editText.getText().toString();
        LoaderManager loaderManager = getSupportLoaderManager();
        booksListAdapter.clear();
        loaderManager.initLoader(BOOK_LOADER_ID, null, this);
}


问:
mongoDB project array element after filter
I have the following (simplified) aggregation:

```<code>Model.aggregate([
    {
      $lookup: {
        from: 'orders',
        localField: '_id',
        foreignField: 'customer',
        as: 'orders',
      },
    },
    {
      $project: {
        openOrders: {
          $filter: {
            input: '$orders',
            as: 'order',
            cond: { $eq: ['$$order.status', 'open'] },
          },
        },
      },
    },
  ])
</code>```

which returns the following:

```<code>{
  _id: ...,
  openOrders: [
    [Object], [Object]
  ],
}
</code>```

Those [Object]'s are simply the returned objects, persisted in the database, with all their fields.

I don't find a way to project/filter out those objects' fields and instead return only their _id's:

```<code>{
  _id: ...,
  openOrders: [
    _id: ...,
    _id: ....
  ],
}
</code>```

EDIT: I'd rather prefer the following expected output:

```<code>{
  _id: ...,
  openOrders: [
    { _id: ... },
    { _id: ... }
  ],
}
</code>```

I tried adding a new $project stage at various points of the aggregation with no success. Can someone help me?

答:
You should add a $project stage like below:

{
  $project: {
    openOrders: 'openOrders._id'
  }
}
```

<p>This will give the output like:</p>

```{
  _id: ...,
  openOrders: [
    _id1,
    _id2,
    ...
  ],
}
```

<p>instead of </p>

```{
  _id: ...,
  openOrders: [
    _id: ...,
    _id: ....
  ],
}
```

<p>I suggest this type of querying because, if you actually see <code>openOrders</code>, it's just the array of <code>_id</code>s, so adding only one <code>_id</code> field inside the array doesn't make sence.</p>

<p>If you still want the output to be like the array of object, then you can use the below:</p>

<pre class="lang-js prettyprint-override"><code>{
  $project: {
    'openOrders._id': 1
  }
}
</code>```

Body:
I have the following (simplified) aggregation:

Model.aggregate([
    {
      $lookup: {
        from: 'orders',
        localField: '_id',
        foreignField: 'customer',
        as: 'orders',
      },
    },
    {
      $project: {
        openOrders: {
          $filter: {
            input: '$orders',
            as: 'order',
            cond: { $eq: ['$$order.status', 'open'] },
          },
        },
      },
    },
  ])

which returns the following:

{
  _id: ...,
  openOrders: [
    [Object], [Object]
  ],
}

Those [Object]'s are simply the returned objects, persisted in the database, with all their fields.

I don't find a way to project/filter out those objects' fields and instead return only their _id's:

{
  _id: ...,
  openOrders: [
    _id: ...,
    _id: ....
  ],
}

EDIT: I'd rather prefer the following expected output:

{
  _id: ...,
  openOrders: [
    { _id: ... },
    { _id: ... }
  ],
}

I tried adding a new $project stage at various points of the aggregation with no success. Can someone help me?

Body:
You should add a $project stage like below:

{
  $project: {
    openOrders: 'openOrders._id'
  }
}

This will give the output like:

{
  _id: ...,
  openOrders: [
    _id1,
    _id2,
    ...
  ],
}

instead of

{
  _id: ...,
  openOrders: [
    _id: ...,
    _id: ....
  ],
}

I suggest this type of querying because, if you actually see openOrders, it's just the array of _ids, so adding only one _id field inside the array doesn't make sence.

If you still want the output to be like the array of object, then you can use the below:

{
  $project: {
    'openOrders._id': 1
  }
}


问:
how to handle nested objects in vuex-orm
i have this object:

userRights

{
  "admin": true,
  "rights": [
    {
      "id": 1,
      "value": true
    },
    {
      "id": 2,
      "value": true
    },
    {
      "id": 3,
      "value": true
    },
    {
      "id": 4,
      "value": true
    },
    {
      "id": 5,
      "value": true
    },
    {
      "id": 6,
      "value": true
    },
    {
      "id": 7,
      "value": true
    }
  ]
}
```

<p>the <code>value</code> should get mapped with the mapped <code>id</code> into this array of objects:</p>

<p><code>rights</code></p>

<pre class="lang-js prettyprint-override"><code>[
  {
    idModule: 1,
    name: 'admin.rights',
    caption: 'Rechte verwalten',
    default: false,
    id: 1,
  },
  {
    idModule: 1,
    name: 'reports',
    caption: 'Reports einsehen',
    default: false,
    id: 2,
  },
  {
    idModule: 1,
    name: 'admin.maintenance',
    caption: 'Wartungsarbeiten durchführen',
    default: false,
    id: 3,
  },
  {
    idModule: 2,
    name: 'users',
    caption: 'Benutzer einsehen',
    default: false,
    id: 4,
  },
  {
    idModule: 2,
    name: 'users.write',
    caption: 'Benutzer anlegen, ändern',
    default: false,
    id: 5,
  },
  {
    idModule: 2,
    name: 'users.passwords',
    caption: 'Benutzer-Passwörter ändern',
    default: false,
    id: 6,
  },
  {
    idModule: 2,
    name: 'users.delete',
    caption: 'Benutzer löschen',
    default: false,
    id: 7,
  },
];
</code>```

the id inside userRights.rights should mapped with the id of rights[0].id and then should create a new element as value: true/false inside the rights array of objects.

atm i do this but i am stuck:

rights.js

import { Model } from '@vuex-orm/core';
import userRights from './userRights';

export default class Right extends Model {
  static entity = 'right';

  static fields() {
    return {
      id: this.attr(null),
      idModule: this.attr(null),
      name: this.attr(''),
      caption: this.attr(''),
      default: this.attr(null),
      value: this.belongsTo(userRight, 'rights.value'),
    };
  }
}

-----------------------------------
userRights.js

import { Model } from '@vuex-orm/core';

export default class UserRight extends Model {
  static entity = 'userRight';

  static fields() {
    return {
      admin: this.attr(null),
      rights: this.attr([]),
    };
  }
}
```

how can i achieve this?

答:
You can make use of map to achieve that.

var userRights = { "admin": true, "rights": [ { "id": 1, "value": true }, { "id": 2, "value": true }, { "id": 3, "value": true }, { "id": 4, "value": true }, { "id": 5, "value": true }, { "id": 6, "value": false }, { "id": 7, "value": true } ]}

var rights = [ { idModule: 1, name: 'admin.rights', caption: 'Rechte verwalten', default: false, id: 1, }, { idModule: 1, name: 'reports', caption: 'Reports einsehen', default: false, id: 2, }, { idModule: 1, name: 'admin.maintenance', caption: 'Wartungsarbeiten durchführen', default: false, id: 3, }, { idModule: 2, name: 'users', caption: 'Benutzer einsehen', default: false, id: 4, }, { idModule: 2, name: 'users.write', caption: 'Benutzer anlegen, ändern', default: false, id: 5, }, { idModule: 2, name: 'users.passwords', caption: 'Benutzer-Passwörter ändern', default: false, id: 6, }, { idModule: 2, name: 'users.delete', caption: 'Benutzer löschen', default: false, id: 7}];

result = rights.map(val=>{
  val.value = userRights.rights.find(k=>k.id==val.id).value;
  return val;
});

console.log(result);```

Body:
i have this object:

userRights

{
  "admin": true,
  "rights": [
    {
      "id": 1,
      "value": true
    },
    {
      "id": 2,
      "value": true
    },
    {
      "id": 3,
      "value": true
    },
    {
      "id": 4,
      "value": true
    },
    {
      "id": 5,
      "value": true
    },
    {
      "id": 6,
      "value": true
    },
    {
      "id": 7,
      "value": true
    }
  ]
}

the value should get mapped with the mapped id into this array of objects:

rights

[
  {
    idModule: 1,
    name: 'admin.rights',
    caption: 'Rechte verwalten',
    default: false,
    id: 1,
  },
  {
    idModule: 1,
    name: 'reports',
    caption: 'Reports einsehen',
    default: false,
    id: 2,
  },
  {
    idModule: 1,
    name: 'admin.maintenance',
    caption: 'Wartungsarbeiten durchführen',
    default: false,
    id: 3,
  },
  {
    idModule: 2,
    name: 'users',
    caption: 'Benutzer einsehen',
    default: false,
    id: 4,
  },
  {
    idModule: 2,
    name: 'users.write',
    caption: 'Benutzer anlegen, ändern',
    default: false,
    id: 5,
  },
  {
    idModule: 2,
    name: 'users.passwords',
    caption: 'Benutzer-Passwörter ändern',
    default: false,
    id: 6,
  },
  {
    idModule: 2,
    name: 'users.delete',
    caption: 'Benutzer löschen',
    default: false,
    id: 7,
  },
];

the id inside userRights.rights should mapped with the id of rights[0].id and then should create a new element as value: true/false inside the rights array of objects.

atm i do this but i am stuck:

rights.js

import { Model } from '@vuex-orm/core';
import userRights from './userRights';

export default class Right extends Model {
  static entity = 'right';

  static fields() {
    return {
      id: this.attr(null),
      idModule: this.attr(null),
      name: this.attr(''),
      caption: this.attr(''),
      default: this.attr(null),
      value: this.belongsTo(userRight, 'rights.value'),
    };
  }
}

-----------------------------------
userRights.js

import { Model } from '@vuex-orm/core';

export default class UserRight extends Model {
  static entity = 'userRight';

  static fields() {
    return {
      admin: this.attr(null),
      rights: this.attr([]),
    };
  }
}

how can i achieve this?


问:
Will CLUSTER cluster the index in PostgreSQL?
Will CLUSTER in PostgreSQL also arrange the index itself in an efficient way on the disk? Or is this of little relevance? I mostly have index-only scans on queries where performance matter and I wonder if clustering is irrelevant then.</p>

答: CLUSTER rewrites the table using an index order but does not rewrite any index.</p>


问:
Conditional statement does not work correctly
Why I always have 'error' and none from 'if-else'?

```<code>DECLARE @Date DATE = '2015-01-01'

BEGIN TRY
    DECLARE @ROZNICA AS INT;
    SET @ROZNICA = DATEDIFF(day, @Date, getdate());

    IF @ROZNICA = 0
    BEGIN
        PRINT 'Data podana w parametrze jest datą bieżącą.';
    END;
    ELSE IF @ROZNICA > 0
    BEGIN
        PRINT 'Między datą obecną a datą ' + getdate() + ' jest ' + @ROZNICA + ' dni różnicy.';
    END;
    ELSE
    BEGIN
        PRINT 'Data podana w parametrze jest większa od bieżacej.';
    END;
END TRY
BEGIN CATCH
    PRINT 'Error';
END CATCH;
</code>```

I want something from the If Else statement to be displayed

答:
Just change

```<code>'Między datą obecną a datą ' + getdate() + ' jest ' + @ROZNICA + ' dni różnicy.';
</code>```

with

```<code>PRINT concat('Między datą obecną a datą ', getdate(), ' jest ', @ROZNICA, ' dni różnicy.');
</code>```

You get this because there is an error for casting datetime to varchar.
So your code will be

```<code>DECLARE @Date DATE = '2015-01-01'

BEGIN TRY
    DECLARE @ROZNICA AS INT;
    SET @ROZNICA = DATEDIFF(day, @Date, getdate());
    IF @ROZNICA = 0
      BEGIN
        PRINT 'Data podana w parametrze jest datą bieżącą.';
      END --Remove ; from here
    ELSE IF @ROZNICA >0
      BEGIN
        PRINT concat('Między datą obecną a datą ', getdate(), ' jest ', @ROZNICA, ' dni różnicy.');
      END -- Remove ; from here
    ELSE
      BEGIN
        PRINT 'Data podana w parametrze jest większa od bieżacej.';
      END;
END TRY
  BEGIN CATCH
    PRINT 'Error';
  END CATCH;
GO
</code>```

Body:
Why I always have 'error' and none from 'if-else'?

DECLARE @Date DATE = '2015-01-01'

BEGIN TRY
    DECLARE @ROZNICA AS INT;
    SET @ROZNICA = DATEDIFF(day, @Date, getdate());

    IF @ROZNICA = 0
    BEGIN
        PRINT 'Data podana w parametrze jest datą bieżącą.';
    END;
    ELSE IF @ROZNICA > 0
    BEGIN
        PRINT 'Między datą obecną a datą ' + getdate() + ' jest ' + @ROZNICA + ' dni różnicy.';
    END;
    ELSE
    BEGIN
        PRINT 'Data podana w parametrze jest większa od bieżacej.';
    END;
END TRY
BEGIN CATCH
    PRINT 'Error';
END CATCH;

I want something from the If Else statement to be displayed

Body:
Just change

'Między datą obecną a datą ' + getdate() + ' jest ' + @ROZNICA + ' dni różnicy.';

with

PRINT concat('Między datą obecną a datą ', getdate(), ' jest ', @ROZNICA, ' dni różnicy.');

You get this because there is an error for casting datetime to varchar.
So your code will be

DECLARE @Date DATE = '2015-01-01'

BEGIN TRY
    DECLARE @ROZNICA AS INT;
    SET @ROZNICA = DATEDIFF(day, @Date, getdate());
    IF @ROZNICA = 0
      BEGIN
        PRINT 'Data podana w parametrze jest datą bieżącą.';
      END --Remove ; from here
    ELSE IF @ROZNICA >0
      BEGIN
        PRINT concat('Między datą obecną a datą ', getdate(), ' jest ', @ROZNICA, ' dni różnicy.');
      END -- Remove ; from here
    ELSE
      BEGIN
        PRINT 'Data podana w parametrze jest większa od bieżacej.';
      END;
END TRY
  BEGIN CATCH
    PRINT 'Error';
  END CATCH;
GO


问:
How to properly handle client "Connection: close" request on HTTP file server?
How do I handle properly a client Connection: close request field? As of now if I get this particular field I close the socket and wait for a following request from the client than reply again and start serving the data.

I don't know why my client/server communication is not working as the Apache Server I tested with.

Thanks for any clarifications...

Client/Server comunication:

```<code>CLIENT:
HEAD /stream.mpeg HTTP/1.0
Host: 127.0.0.1
User-Agent: SuperPlayer
Connection: Close

SERVER:
HTTP/1.0 200 OK
Date: Wed, 1 Jun 2011 20:05:13 GMT
Server: HTTP Server
Last-Modified: Mon, 06 Aug 2009 01:02:23 GMT
Accept-Ranges: bytes
Connection: Close
Content-Type: audio/mpeg

CLIENT:
HEAD /stream.mpeg HTTP/1.0
Host: 127.0.0.1
User-Agent: SuperPlayer
Connection: Close

SERVER:
HTTP/1.0 200 OK
Date: Wed, 1 Jun 2011 20:05:13 GMT
Server: HTTP Server
Last-Modified: Mon, 06 Aug 2009 01:02:23 GMT
Accept-Ranges: bytes
Connection: Close
Content-Type: audio/mpeg

231489172304981723409817234981234acvass123412323
21312hjdfaoi8w34yorhadl4hi8rali45mhalo3i,wmotw
345fqw354aoicu43yocq2i3hr
</code>```

Client/ApacheServer Comunication:

```<code>CLIENT:
GET /test.mp3 HTTP/1.0
Host: 192.168.1.120
User-Agent: SuperPlayer
Connection: Close

SERVER:
HTTP/1.1 200 OK
Date: Wed, 01 Jun 2011 19:15:11 GMT
Server: Apache/2.2.16 (Win32)
Last-Modified: Thu, 29 Apr 2010 21:06:34 GMT
ETag: "14000000047049-4f75c8-4856680636a80"
Accept-Ranges: bytes
Content-Length: 5207496
Connection: close
Content-Type: audio/mpeg

...d.....<).0.. ..........<.@.. ( .h.$.J...1...i....A. ......c....a.9..!g.N...A. ........ ....>......|.......8....a......|..|N.............'>........?...C.....@..TJt.n .e...r.iL..#..IH...pR|.
</code>```

答: The Connection: close header just means that the client is expecting you to close the connection after sending the response. That also absolves you of having to send a Content-Length: header.

Body:
How do I handle properly a client Connection: close request field? As of now if I get this particular field I close the socket and wait for a following request from the client than reply again and start serving the data.

I don't know why my client/server communication is not working as the Apache Server I tested with.

Thanks for any clarifications...

Client/Server comunication:

CLIENT:
HEAD /stream.mpeg HTTP/1.0
Host: 127.0.0.1
User-Agent: SuperPlayer
Connection: Close

SERVER:
HTTP/1.0 200 OK
Date: Wed, 1 Jun 2011 20:05:13 GMT
Server: HTTP Server
Last-Modified: Mon, 06 Aug 2009 01:02:23 GMT
Accept-Ranges: bytes
Connection: Close
Content-Type: audio/mpeg

CLIENT:
HEAD /stream.mpeg HTTP/1.0
Host: 127.0.0.1
User-Agent: SuperPlayer
Connection: Close

SERVER:
HTTP/1.0 200 OK
Date: Wed, 1 Jun 2011 20:05:13 GMT
Server: HTTP Server
Last-Modified: Mon, 06 Aug 2009 01:02:23 GMT
Accept-Ranges: bytes
Connection: Close
Content-Type: audio/mpeg

231489172304981723409817234981234acvass123412323
21312hjdfaoi8w34yorhadl4hi8rali45mhalo3i,wmotw
345fqw354aoicu43yocq2i3hr

Client/ApacheServer Comunication:

CLIENT:
GET /test.mp3 HTTP/1.0
Host: 192.168.1.120
User-Agent: SuperPlayer
Connection: Close

SERVER:
HTTP/1.1 200 OK
Date: Wed, 01 Jun 2011 19:15:11 GMT
Server: Apache/2.2.16 (Win32)
Last-Modified: Thu, 29 Apr 2010 21:06:34 GMT
ETag: "14000000047049-4f75c8-4856680636a80"
Accept-Ranges: bytes
Content-Length: 5207496
Connection: close
Content-Type: audio/mpeg

...d.....<).0.. ..........<.@.. ( .h.$.J...1...i....A. ......c....a.9..!g.N...A. ........ ....>......|.......8....a......|..|N.............'>........?...C.....@..TJt.n .e...r.iL..#..IH...pR|.


答:
You cannot concatenate a date or an integer with a varchar without conversion, so you need:</p>

```<code> PRINT 'Między datą obecną a datą ' + cast(getdate() as varchar(10)) + ' jest ' + cast( @ROZNICA  as varchar(5))+ ' dni różnicy.';
</code>```

Title: Conditional statement does not work correctly

Body:
You cannot concatenate a date or an integer with a varchar without conversion, so you need:

 PRINT 'Między datą obecną a datą ' + cast(getdate() as varchar(10)) + ' jest ' + cast( @ROZNICA  as varchar(5))+ ' dni różnicy.';


问:
Is there a Union in Java Generics?
Can I contain two different types in a collection? For example, can I have List< String U Integer > ?</p>

答:
what you're decribing is the perfect use case for the Visitor pattern

100% statically type-checked

doesn't need Java 8 or above

usage:

```<code>List<UnionType> unionTypes = Arrays
    .asList(new StringContainer("hello"), new IntegerContainer(4));

for (UnionType unionType : unionTypes) {
    unionType.when(new UnionType.Cases<Integer>() {
        @Override
        public Integer is(StringContainer stringContainer) {
            // type-specific handling code
        }

        @Override
        public Integer is(IntegerContainer integerContainer) {
            // type-specific handling code
        }
    });
}
</code>```

boilerplate code:

interface UnionType {
    <R> R when(Cases<R> c);
    interface Cases<R> {
        R is(StringContainer stringContainer);
        R is(IntegerContainer integerContainer);
    }
}

class StringContainer implements UnionType {

    private final String value;
    public StringContainer(String value) { this.value = value; }
    public String getValue() { return value; }

    @Override
    public <R> R when(Cases<R> cases) {
        return cases.is(this);
    }
}

class IntegerContainer implements UnionType {

    private final Integer value;
    public IntegerContainer(Integer value) { this.value = value; }
    public Integer getValue() { return value; }

    @Override
    public <R> R when(Cases<R> cases) {
        return cases.is(this);
    }
}
```

Title: Is there a Union in Java Generics?

Body:
what you're decribing is the perfect use case for the Visitor pattern

100% statically type-checked

doesn't need Java 8 or above

usage:

List<UnionType> unionTypes = Arrays
    .asList(new StringContainer("hello"), new IntegerContainer(4));

for (UnionType unionType : unionTypes) {
    unionType.when(new UnionType.Cases<Integer>() {
        @Override
        public Integer is(StringContainer stringContainer) {
            // type-specific handling code
        }

        @Override
        public Integer is(IntegerContainer integerContainer) {
            // type-specific handling code
        }
    });
}

boilerplate code:

interface UnionType {
    <R> R when(Cases<R> c);
    interface Cases<R> {
        R is(StringContainer stringContainer);
        R is(IntegerContainer integerContainer);
    }
}

class StringContainer implements UnionType {

    private final String value;
    public StringContainer(String value) { this.value = value; }
    public String getValue() { return value; }

    @Override
    public <R> R when(Cases<R> cases) {
        return cases.is(this);
    }
}

class IntegerContainer implements UnionType {

    private final Integer value;
    public IntegerContainer(Integer value) { this.value = value; }
    public Integer getValue() { return value; }

    @Override
    public <R> R when(Cases<R> cases) {
        return cases.is(this);
    }
}