问:
Does setting a virtual column as an index in MySQL improve query speed?
I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this.

database version MySQL 5.7.37
server version windows server 2016 datacenter

I have two tables: rep_order, tb_user.

```<code>create table rep_order
(
    id            bigint auto_increment
        primary key,
    code          varchar(32)                         null,
    equ_id        bigint(32)                          not null ,
    mileage       varchar(10)                         null,
    order_type    varchar(5)                          null ,
    report_name   varchar(10)                         null ,
    report_phone  varchar(15)                         null ,
    contact_name  varchar(10)                         null ,
    contact_phone varchar(15)                         null ,
    address       varchar(100)                        null ,
    lng           varchar(20)                         null ,
    lat           varchar(20)                         null ,
    order_level   int(1)                              null ,
    des           varchar(50)                         null ,
    user_ids      json                                null ,
    oper_date     timestamp default CURRENT_TIMESTAMP not null,
    v_user_ids    varchar(500) as (json_unquote(json_extract(`user_ids`, '$[*]')))
);

create index rep_order_equ_id_index
    on rep_order (equ_id);

create index v_user_ids
    on rep_order (v_user_ids);
</code>```
```<code>create table tb_user
(
    user_id       bigint           not null
        primary key,
    openid        varchar(50)      null ,
    name          varchar(32)      null ,
    type          varchar(10)      null ,
    mobile        varchar(20)      null ,
    username      varchar(50)      null ,
    wage_id       bigint           null ,
    resign_date   date             null ,
    entry_date    date             null ,
    identity      varchar(25)      null ,
    create_time   datetime         null ,
    password      varchar(64)      null ,
    dept_id       bigint           null ,
    sex           enum ('男', '女')  null,
    client_leader int(1) default 0 not null,
    constraint tb_user_identity_uindex
        unique (identity),
    constraint tb_user_mobile_uindex
        unique (mobile),
    constraint tb_user_username_uindex
        unique (username)
)
    comment '用户' charset = utf8;

create index tb_user_name_mobile_index
    on tb_user (name, mobile);

create index tb_user_rep_wage_config_id_fk
    on tb_user (wage_id);

create index tb_user_sys_dept_dept_id_fk
    on tb_user (dept_id);

create index tb_user_type_index
    on tb_user (type);
</code>```

A user_ids field is defined in rep_order, which is a json array type.

Then I created a virtual column v_user_ids for user_ids in rep_order, and set v_user_ids as an index column, the execution of the following statement is also very fast

```<code>select o.id, u.user_id
from rep_order o, tb_user u
where locate(concat(u.user_id), o.v_user_ids) > 0
</code>```

Screenshot of explain execution result

But the execution of the following statement is very slow

```<code>select o.id, u.user_id
from rep_order o, tb_user u
where locate(concat(u.user_id), o.v_user_ids) > 0
group by o.id, u.user_id;
</code>```

Screenshot of explain execution result

It seems that setting the virtual column as an index does not improve the execution speed of the query. Why is this? What can I do to improve the query speed?

Thanks in advance.

答:
Both queries contain this

```<code>where locate(concat(u.user_id), o.v_user_ids) > 0
</code>```

It isn't sargable. That means it can't use random access on the index you created on your virtual column. MySQL must scan the index: examine every entry in it to see if it contains the substring for the user_id you want.

RDBMS indexes work best when there's one value in each column. Your virtual column definition puts multiple values in that column.

Body:
I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this.

database version MySQL 5.7.37
server version windows server 2016 datacenter

I have two tables: rep_order, tb_user.

create table rep_order
(
    id            bigint auto_increment
        primary key,
    code          varchar(32)                         null,
    equ_id        bigint(32)                          not null ,
    mileage       varchar(10)                         null,
    order_type    varchar(5)                          null ,
    report_name   varchar(10)                         null ,
    report_phone  varchar(15)                         null ,
    contact_name  varchar(10)                         null ,
    contact_phone varchar(15)                         null ,
    address       varchar(100)                        null ,
    lng           varchar(20)                         null ,
    lat           varchar(20)                         null ,
    order_level   int(1)                              null ,
    des           varchar(50)                         null ,
    user_ids      json                                null ,
    oper_date     timestamp default CURRENT_TIMESTAMP not null,
    v_user_ids    varchar(500) as (json_unquote(json_extract(`user_ids`, '$[*]')))
);

create index rep_order_equ_id_index
    on rep_order (equ_id);

create index v_user_ids
    on rep_order (v_user_ids);

create table tb_user
(
    user_id       bigint           not null
        primary key,
    openid        varchar(50)      null ,
    name          varchar(32)      null ,
    type          varchar(10)      null ,
    mobile        varchar(20)      null ,
    username      varchar(50)      null ,
    wage_id       bigint           null ,
    resign_date   date             null ,
    entry_date    date             null ,
    identity      varchar(25)      null ,
    create_time   datetime         null ,
    password      varchar(64)      null ,
    dept_id       bigint           null ,
    sex           enum ('男', '女')  null,
    client_leader int(1) default 0 not null,
    constraint tb_user_identity_uindex
        unique (identity),
    constraint tb_user_mobile_uindex
        unique (mobile),
    constraint tb_user_username_uindex
        unique (username)
)
    comment '用户' charset = utf8;

create index tb_user_name_mobile_index
    on tb_user (name, mobile);

create index tb_user_rep_wage_config_id_fk
    on tb_user (wage_id);

create index tb_user_sys_dept_dept_id_fk
    on tb_user (dept_id);

create index tb_user_type_index
    on tb_user (type);

A user_ids field is defined in rep_order, which is a json array type.

Then I created a virtual column v_user_ids for user_ids in rep_order, and set v_user_ids as an index column, the execution of the following statement is also very fast

select o.id, u.user_id
from rep_order o, tb_user u
where locate(concat(u.user_id), o.v_user_ids) > 0

Screenshot of explain execution result

But the execution of the following statement is very slow

select o.id, u.user_id
from rep_order o, tb_user u
where locate(concat(u.user_id), o.v_user_ids) > 0
group by o.id, u.user_id;

Screenshot of explain execution result

It seems that setting the virtual column as an index does not improve the execution speed of the query. Why is this? What can I do to improve the query speed?

Thanks in advance.

Body:
Both queries contain this

where locate(concat(u.user_id), o.v_user_ids) > 0

It isn't sargable. That means it can't use random access on the index you created on your virtual column. MySQL must scan the index: examine every entry in it to see if it contains the substring for the user_id you want.

RDBMS indexes work best when there's one value in each column. Your virtual column definition puts multiple values in that column.


来源: stackexchange

问:
Test if getJSONArray is null or not
My code extract results of JSONObject, but, sometimes, the i value don't begin to 1, and i have an error like that :

```<code>org.json.JSONException: No value for 1
</code>```

My code :

```<code>JSONObject obj = new JSONObject(result);
       for(int i=1;i<=14;i++) {

            JSONArray arr = obj.getJSONArray(""+i);
        extraction(arr, i);
       }
</code>```

I want to test before the extraction if the object code (i) exists or not. How i can do this ?

答:
use obj.optJSONArray(name) the response will be null if the name does not exists.

```<code>JSONObject obj = new JSONObject(result);
   for(int i=1;i<=14;i++) {

        JSONArray arr = obj.optJSONArray(""+i);
        if(arr != null) {
              extraction(arr, i);
        }
   }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Test if getJSONArray is null or not

Body:
My code extract results of JSONObject, but, sometimes, the i value don't begin to 1, and i have an error like that :

org.json.JSONException: No value for 1

My code :

JSONObject obj = new JSONObject(result);
       for(int i=1;i<=14;i++) {

            JSONArray arr = obj.getJSONArray(""+i);
        extraction(arr, i);
       }

I want to test before the extraction if the object code (i) exists or not. How i can do this ?

Body:
use obj.optJSONArray(name) the response will be null if the name does not exists.

JSONObject obj = new JSONObject(result);
   for(int i=1;i<=14;i++) {

        JSONArray arr = obj.optJSONArray(""+i);
        if(arr != null) {
              extraction(arr, i);
        }
   }


问:
How to convert binary array to decimal in C
I am trying to convert a binary array to decimal
Here is what i have to convert, binTodec[8] = {1,1,1,1,0,0,1,1}

I have started with
for(int i=0; i<8; i++)

Is there anybody that can help me

答:
One method is to calculate from the most significant bit to the least significant bit.

If binTodec[0] is the most significant bit in binary number :
The decimal number is

1 * 2^7 + 1 * 2^6 + 1 * 2^5 + 1 * 2^4 + 0 * 2^3 + 0 * 2^2 + 1 * 2^1 + 1 * 2^0

= 243

The implemented code would be

int binTodec[8] = {1,1,1,1,0,0,1,1};
int result = 0;

for (int i = 0; i < 8; i++) {
    result *= 2;
    result += binTodec[i];
}
printf("%d\n", result);
```
<p>On the other hand, if binTodec[0] is the least significant bit in binary number :<br />
The decimal number is<br />
<code>1</code> * 2^0 + <code>1</code> * 2^1 + <code>1</code> * 2^2 + <code>1</code> * 2^3 + <code>0</code> * 2^4 + <code>0</code> * 2^5 + <code>1</code> * 2^6 + <code>1</code> * 2^7<br />
= 207</p>
<p>The implemented code would be</p>
<pre class="lang-c prettyprint-override"><code>int binTodec[8] = {1,1,1,1,0,0,1,1};
int result = 0;

for (int i = 7; i >= 0; i--) {
    result *= 2;
    result += binTodec[i];
}
printf("%d\n", result);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
One method is to calculate from the most significant bit to the least significant bit.

If binTodec[0] is the most significant bit in binary number :
The decimal number is

1 * 2^7 + 1 * 2^6 + 1 * 2^5 + 1 * 2^4 + 0 * 2^3 + 0 * 2^2 + 1 * 2^1 + 1 * 2^0

= 243

The implemented code would be

int binTodec[8] = {1,1,1,1,0,0,1,1};
int result = 0;

for (int i = 0; i < 8; i++) {
    result *= 2;
    result += binTodec[i];
}
printf("%d\n", result);

On the other hand, if binTodec[0] is the least significant bit in binary number :

The decimal number is

1 * 2^0 + 1 * 2^1 + 1 * 2^2 + 1 * 2^3 + 0 * 2^4 + 0 * 2^5 + 1 * 2^6 + 1 * 2^7

= 207

The implemented code would be

int binTodec[8] = {1,1,1,1,0,0,1,1};
int result = 0;

for (int i = 7; i >= 0; i--) {
    result *= 2;
    result += binTodec[i];
}
printf("%d\n", result);


问:
Items in a RecyclerView are getting the data of previous items
The application has a database with items that have columns of locations marked as integers which are displayed in a RecyclerView.

If any of the integers in the database columns is a zero, then the integer should not be displayed and to accomplish that I added if statements to check through each of the received integers and if the received integer is a zero, then it shouldn't be displayed.

```<code>private int journeyPosition;
...

  @Override
    public void onBindViewHolder(@NonNull JourneyAdapter.JourneyViewHolder holder, int position) {
        journeyPosition = holder.getAdapterPosition();
        JourneyObject journeyObject = journeyObjectList.get(holder.getAdapterPosition());

        if (journeyObject.getLocation1() != 0){
            holder.location1.setText(Integer.toString(journeyObject.getLocation1()));
        }
        if (journeyObject.getLocation2() != 0) {
            holder.location2.setText(Integer.toString(journeyObject.getLocation2()));
        }
        if (journeyObject.getLocation3() != 0) {
            holder.location3.setText(Integer.toString(journeyObject.getLocation3()));
        }
        if (journeyObject.getLocation4() != 0) {
            holder.location4.setText(Integer.toString(journeyObject.getLocation4()));
        }
        if (journeyObject.getLocation5() != 0) {
            holder.location5.setText(Integer.toString(journeyObject.getLocation5()));
        }
</code>```

At the moment the code works correctly if all the locations are anything bigger than a zero, but since some of the locations in some items are a zero, then those integers are gotten from the RecyclerView's other items that have a number bigger than zero present in the field.

I have not yet figured out why the data is received from the previous adapter positions.
If anything is unclear, then please specify what.

Thanks

答:
Remember that it’s a recycler view. The views scrolling onto the screen may have already been used. When you bind the view, don’t just use if statements. Use if/else statements so you can clear old data if you want to show nothing.

And a tip, when you find yourself writing a bunch of code that looks copy-pasted like that, find a way to do it by iteration instead. Your code will be cleaner, more concise, easier to read, and less error prone.

Body:
The application has a database with items that have columns of locations marked as integers which are displayed in a RecyclerView.

If any of the integers in the database columns is a zero, then the integer should not be displayed and to accomplish that I added if statements to check through each of the received integers and if the received integer is a zero, then it shouldn't be displayed.

private int journeyPosition;
...

  @Override
    public void onBindViewHolder(@NonNull JourneyAdapter.JourneyViewHolder holder, int position) {
        journeyPosition = holder.getAdapterPosition();
        JourneyObject journeyObject = journeyObjectList.get(holder.getAdapterPosition());

        if (journeyObject.getLocation1() != 0){
            holder.location1.setText(Integer.toString(journeyObject.getLocation1()));
        }
        if (journeyObject.getLocation2() != 0) {
            holder.location2.setText(Integer.toString(journeyObject.getLocation2()));
        }
        if (journeyObject.getLocation3() != 0) {
            holder.location3.setText(Integer.toString(journeyObject.getLocation3()));
        }
        if (journeyObject.getLocation4() != 0) {
            holder.location4.setText(Integer.toString(journeyObject.getLocation4()));
        }
        if (journeyObject.getLocation5() != 0) {
            holder.location5.setText(Integer.toString(journeyObject.getLocation5()));
        }

At the moment the code works correctly if all the locations are anything bigger than a zero, but since some of the locations in some items are a zero, then those integers are gotten from the RecyclerView's other items that have a number bigger than zero present in the field.

I have not yet figured out why the data is received from the previous adapter positions.
If anything is unclear, then please specify what.

Thanks


问:
hasManyThrough with morph
I have a projects table that either can be assigned to a user or a team, this is the structure:

```<code>id
assignable_id
assignable_type

class Project extends Model {
    public function assignable(): MorphTo
    {
        return $this->morphTo();
    }
}
</code>```

and my team table contains members with a pivot table:

```<code>id

class Team extends Model {

    public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class);
    }

    public function projects(): MorphMany
    {
        return $this->morphMany(Project::class, 'assignable');
    }
}

// team_user table
team_id
user_id
</code>```

and finally my user table:

```<code>id

class User extends Model {

    public function teams(): BelongsToMany
    {
        return $this->belongsToMany(Team::class);
    }

    public function projects(): MorphMany
    {
        return $this->morphMany(Project::class, 'assignable');
    }
}
</code>```

Now the problem is I want to get all projects that have been assigned to a user either directly or through a team, as expected $user()->projects return the ones that directly have been assigned to the user.

I tried many solutions but none has worked for me yet.

答:
Use whereHasMorph:

```<code>$user = ...

$projects = Project::whereHasMorph(
    'assignable',
    [Team::class, User::class],
    function ($query, $type) use($user) {
        if($type === Team::class){
            $query->whereRelation('users', 'id', $user->id);
        }else{
            $query->where('id', $user->id);
        }
    }
)->get();
</code>```

Or split into 2 queries and merge together:

```<code>$projects = $user->projects;
$teams = $user->teams()->with('projects')->get();
$teams_projects = $teams->pluck('projects')->collapse();
$projects = $projects->merge($teams_projects);
</code>```

Title: hasManyThrough with morph

Body:
I have a projects table that either can be assigned to a user or a team, this is the structure:

id
assignable_id
assignable_type

class Project extends Model {
    public function assignable(): MorphTo
    {
        return $this->morphTo();
    }
}

and my team table contains members with a pivot table:

id

class Team extends Model {

    public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class);
    }

    public function projects(): MorphMany
    {
        return $this->morphMany(Project::class, 'assignable');
    }
}

// team_user table
team_id
user_id

and finally my user table:

id

class User extends Model {

    public function teams(): BelongsToMany
    {
        return $this->belongsToMany(Team::class);
    }

    public function projects(): MorphMany
    {
        return $this->morphMany(Project::class, 'assignable');
    }
}

Now the problem is I want to get all projects that have been assigned to a user either directly or through a team, as expected $user()->projects return the ones that directly have been assigned to the user.

I tried many solutions but none has worked for me yet.

Body:
Use whereHasMorph:

$user = ...

$projects = Project::whereHasMorph(
    'assignable',
    [Team::class, User::class],
    function ($query, $type) use($user) {
        if($type === Team::class){
            $query->whereRelation('users', 'id', $user->id);
        }else{
            $query->where('id', $user->id);
        }
    }
)->get();

Or split into 2 queries and merge together:

$projects = $user->projects;
$teams = $user->teams()->with('projects')->get();
$teams_projects = $teams->pluck('projects')->collapse();
$projects = $projects->merge($teams_projects);


问:
PGraphics with background(); in Processing
I am trying to draw ellipses from an array list onto a PGraphics layer. This works so far. However, I need to give the PGraphics layer a white background. The moment I add the background, I can't add any more ellipses by mouse click. I have already tried to draw the ellipses without background on a PGraphics layer, and this again on a second PGraphics layer with background. But this still leads to the problem that the ellipses become pixelated as they are drawn over and over again. How can I make it so that the ellipses are gradually added from the array list to the one and only PGrpahics layer?

```<code>PGraphics pg;
ArrayList<Circle> circles;
void setup () {
  size(500, 500);
  circles = new ArrayList<Circle>();
  circles.add(new Circle());
  pg = createGraphics(width, height);
}

void draw() {
  background(255);
  image(pg, 0, 0);
  for (int i = circles.size()-1; i >= 0; i--) {
    Circle circle = circles.get(i);
    circle.display();
  }
}
void mousePressed() {
  circles.add(new Circle());
}
</code>```

And this part… I commented the background function out…

```<code>  class Circle {
  int x = int(random(width));
  int y = int(random(height));
  int size;

  Circle() {
  }
  void display() {
    pg.beginDraw();
    //pg.background(255);
    pg.ellipse(x, y, 20, 20);
    pg.endDraw();
  }
}
</code>```

答: Maybe try putting the background in the setup, so the background doesn't overwrite all the ellipses. Hope it works</p>

Body:
I am trying to draw ellipses from an array list onto a PGraphics layer. This works so far. However, I need to give the PGraphics layer a white background. The moment I add the background, I can't add any more ellipses by mouse click. I have already tried to draw the ellipses without background on a PGraphics layer, and this again on a second PGraphics layer with background. But this still leads to the problem that the ellipses become pixelated as they are drawn over and over again. How can I make it so that the ellipses are gradually added from the array list to the one and only PGrpahics layer?

PGraphics pg;
ArrayList<Circle> circles;
void setup () {
  size(500, 500);
  circles = new ArrayList<Circle>();
  circles.add(new Circle());
  pg = createGraphics(width, height);
}

void draw() {
  background(255);
  image(pg, 0, 0);
  for (int i = circles.size()-1; i >= 0; i--) {
    Circle circle = circles.get(i);
    circle.display();
  }
}
void mousePressed() {
  circles.add(new Circle());
}

And this part… I commented the background function out…

  class Circle {
  int x = int(random(width));
  int y = int(random(height));
  int size;

  Circle() {
  }
  void display() {
    pg.beginDraw();
    //pg.background(255);
    pg.ellipse(x, y, 20, 20);
    pg.endDraw();
  }
}


问:
How to require child class method to call parent class method?
Let's say I have a parent class A.

```<code>class A
{
    public:
        A() {}

        void MyMethod()
        {
            printf( "A\n" );
        }
};
</code>```

And I have a child class B.

```<code>class B : public A
{
    public:
        B() {}

        void MyMethod()
        {
            printf( "B\n" );
        }
};
</code>```

Now, I would like to require class B to call A::MyMethod(), without explicitly calling it, as shown above. Resulting in:

```<code>A
B
</code>```

Or

```<code>B
A
</code>```

Would that be possible?

Right now B->MyMethod() only calls the child method.

答:
Non-Virtual Interface idiom has the base class define a public
non-virtual member function, and a private virtual member function that
is an override point for derived classes.

The public non-virtual member function acts as a public facing API.

The private virtual member function acts as a class hierarchy
facing API.

Separating those two concerns can be a handy technique especially
for larger projects, and for debugging purposes, and for ensuring
pre- and post- operations in the base class's public non-virtual
member function.

```<code>#include <iostream>

using std::cout;

namespace {

class A {
    virtual void MyMethodImpl() const {
        // Derived classes should override this virtual member function
        // and add their extra steps there.
    }
public:
    virtual ~A() = default;
    A() {}

    void MyMethod() const {
        cout << "A::MyMethod before steps.\n";
        MyMethodImpl();
        cout << "A::MyMethod after steps.\n";
    }
};

class B : public A {
    void MyMethodImpl() const override {
        cout << "B::MyMethodImpl extra steps.\n";
    }
public:
    B() {}
};

} // anon

int main() {
    B b;
    b.MyMethod();
}
</code>```

Body:
Let's say I have a parent class A.

class A
{
    public:
        A() {}

        void MyMethod()
        {
            printf( "A\n" );
        }
};

And I have a child class B.

class B : public A
{
    public:
        B() {}

        void MyMethod()
        {
            printf( "B\n" );
        }
};

Now, I would like to require class B to call A::MyMethod(), without explicitly calling it, as shown above. Resulting in:

A
B

Or

B
A

Would that be possible?

Right now B->MyMethod() only calls the child method.

Body:
Non-Virtual Interface idiom has the base class define a public
non-virtual member function, and a private virtual member function that
is an override point for derived classes.

The public non-virtual member function acts as a public facing API.

The private virtual member function acts as a class hierarchy
facing API.

Separating those two concerns can be a handy technique especially
for larger projects, and for debugging purposes, and for ensuring
pre- and post- operations in the base class's public non-virtual
member function.

#include <iostream>

using std::cout;

namespace {

class A {
    virtual void MyMethodImpl() const {
        // Derived classes should override this virtual member function
        // and add their extra steps there.
    }
public:
    virtual ~A() = default;
    A() {}

    void MyMethod() const {
        cout << "A::MyMethod before steps.\n";
        MyMethodImpl();
        cout << "A::MyMethod after steps.\n";
    }
};

class B : public A {
    void MyMethodImpl() const override {
        cout << "B::MyMethodImpl extra steps.\n";
    }
public:
    B() {}
};

} // anon

int main() {
    B b;
    b.MyMethod();
}


问:
Using where clause or similar way with JSON
I am trying to pass an input value using a post request and retrieving on another file with isset() set value and trying to get the outcome where the value is in in the JSON as below.

A.php - where I make the API calls and retrieve JSON

```<code>global $decoded_result;
$decoded_result = array();
$decoded_result = json_decode($result, true);
</code>```

B.php - where the input is sent

```<code>    $("#_inputDropdown").change(function(e){
        e.preventDefault();
        var _zid = $(this).find(':selected').attr('data-id');
         $.ajax({
            url:'c.php',
            method: 'POST',
            dataType: 'json',
            data: {_zid:_zid},
            success:function(data){
                $('#_eid').val(data[0].invoice_number);
                $('#_customerName').val(data[0].customer_name);
            }
        });
    });
</code>```

C.php - when the input id is sent to C.php, that's where the JSON set for the particular input will be returned.

```<code>if(isset($_POST['_zid'])){
    $rows = array();
    global $decoded_result;
    global $result;
    $row = echo json_encode($decoded_result['invoices']);
    foreach($decoded_result['invoices'] as $result) {
        //HOW WOULD THE JSON WILL BE RETURNED WHERE THE id = _zid
    }
    $json = json_encode($rows);
    echo $json;
}
</code>```

How should I approach since I am trying to retrieve from JSON nodes. finding a similar way as MySql.

答:
I was searching for associative arrays in order to complete this task. as per it is</p>
```<code>if(isset($_POST['_zid'])){
    $zid = $_POST['_zid'];
    global $decoded_result;
    global $result;
    $newArr = array_filter($decoded_result['invoices'], function($result){
        return $result['invoice_number'] == $_POST['_zid'];
    });
    $json = json_encode($newArr);
    echo $json;
}
</code>```

Body:
I am trying to pass an input value using a post request and retrieving on another file with isset() set value and trying to get the outcome where the value is in in the JSON as below.

A.php - where I make the API calls and retrieve JSON

global $decoded_result;
$decoded_result = array();
$decoded_result = json_decode($result, true);

B.php - where the input is sent

    $("#_inputDropdown").change(function(e){
        e.preventDefault();
        var _zid = $(this).find(':selected').attr('data-id');
         $.ajax({
            url:'c.php',
            method: 'POST',
            dataType: 'json',
            data: {_zid:_zid},
            success:function(data){
                $('#_eid').val(data[0].invoice_number);
                $('#_customerName').val(data[0].customer_name);
            }
        });
    });

C.php - when the input id is sent to C.php, that's where the JSON set for the particular input will be returned.

if(isset($_POST['_zid'])){
    $rows = array();
    global $decoded_result;
    global $result;
    $row = echo json_encode($decoded_result['invoices']);
    foreach($decoded_result['invoices'] as $result) {
        //HOW WOULD THE JSON WILL BE RETURNED WHERE THE id = _zid
    }
    $json = json_encode($rows);
    echo $json;
}

How should I approach since I am trying to retrieve from JSON nodes. finding a similar way as MySql.

Body:
I was searching for associative arrays in order to complete this task. as per it is

if(isset($_POST['_zid'])){
    $zid = $_POST['_zid'];
    global $decoded_result;
    global $result;
    $newArr = array_filter($decoded_result['invoices'], function($result){
        return $result['invoice_number'] == $_POST['_zid'];
    });
    $json = json_encode($newArr);
    echo $json;
}


问:
invalid SQL statement while declaring a rowtype record in oracle
i am trying to display a record rowtype in oracle, i am getting

SQL Error [900] [42000]: ORA-00900: invalid SQL statement at line 7

here :

```<code>intraftrecord xyz%rowtype;
</code>```

i can't seem to figure it out.

```<code>CREATE OR REPLACE PROCEDURE intraftresponseprocedure
IS
CURSOR xyz IS
select REGEXP_REPLACE(RESPONSE_PARAM , '-', '') from (
    select RESPONSE_PARAM from AUDIT_LOG WHERE ACTIVITY ='Intra Bank Funds Transfer' order by id asc
);
intraftrecord xyz%rowtype;
BEGIN
    OPEN xyz;
LOOP
FETCH xyz INTO intraftrecord;
EXIT WHEN intraftrecord%notfound;
dbms_output.put_line(intraftrecord);
END LOOP;
END;
</code>```

答:
Three issues -

It's the cursor that has a %found attribute, not the record.

dbms_output.put_line() takes a single varchar2 as argument, not xyz%rowtype

You'll need to refer to the specific attribute of intraftrecord that you want to display, so the cursor needs to give it a name.

Fixed version:

```<code>create or replace procedure intraftresponseprocedure
as
    cursor xyz is
        select regexp_replace(response_param, '-', '') as response
        from   ( select response_param
                 from   audit_log
                 where  activity = 'Intra Bank Funds Transfer'
                 order by id asc );

    intraftrecord xyz%rowtype;
begin
    open xyz;

    loop
        fetch xyz into intraftrecord;
        exit when xyz%notfound;
        dbms_output.put_line(intraftrecord.response);
    end loop;
end;
</code>```

The cursor could also be simplified, and there's no need for an explicitly declared and fetched cursor and record. Simplified version:

```<code>create or replace procedure intraftresponseprocedure
as
begin
    for r in (
        select regexp_replace(response_param, '-', '') as response
        from   audit_log
        where  activity = 'Intra Bank Funds Transfer'
        order by id asc
    )
    loop
        dbms_output.put_line(r.response);
    end loop;
end;
</code>```

Body:
i am trying to display a record rowtype in oracle, i am getting

SQL Error [900] [42000]: ORA-00900: invalid SQL statement at line 7

here :

intraftrecord xyz%rowtype;

i can't seem to figure it out.

CREATE OR REPLACE PROCEDURE intraftresponseprocedure
IS
CURSOR xyz IS
select REGEXP_REPLACE(RESPONSE_PARAM , '-', '') from (
    select RESPONSE_PARAM from AUDIT_LOG WHERE ACTIVITY ='Intra Bank Funds Transfer' order by id asc
);
intraftrecord xyz%rowtype;
BEGIN
    OPEN xyz;
LOOP
FETCH xyz INTO intraftrecord;
EXIT WHEN intraftrecord%notfound;
dbms_output.put_line(intraftrecord);
END LOOP;
END;

Body:
Three issues -

It's the cursor that has a %found attribute, not the record.

dbms_output.put_line() takes a single varchar2 as argument, not xyz%rowtype

You'll need to refer to the specific attribute of intraftrecord that you want to display, so the cursor needs to give it a name.

Fixed version:

create or replace procedure intraftresponseprocedure
as
    cursor xyz is
        select regexp_replace(response_param, '-', '') as response
        from   ( select response_param
                 from   audit_log
                 where  activity = 'Intra Bank Funds Transfer'
                 order by id asc );

    intraftrecord xyz%rowtype;
begin
    open xyz;

    loop
        fetch xyz into intraftrecord;
        exit when xyz%notfound;
        dbms_output.put_line(intraftrecord.response);
    end loop;
end;

The cursor could also be simplified, and there's no need for an explicitly declared and fetched cursor and record. Simplified version:

create or replace procedure intraftresponseprocedure
as
begin
    for r in (
        select regexp_replace(response_param, '-', '') as response
        from   audit_log
        where  activity = 'Intra Bank Funds Transfer'
        order by id asc
    )
    loop
        dbms_output.put_line(r.response);
    end loop;
end;


问:
Creating a temporal train test split for customer item interactions
I'm looking for a more pythonic/faster way to do this. The data consist of 6 million rows and there are around 8 columns. Any help much appriciated.

data.sort_values(by=['user_id', 'event_time'], inplace=True)
data.reset_index(inplace=True)

unique_users_df = data['user_id'].unique()

train = pd.DataFrame()
test = pd.DataFrame()

for i, user in enumerate(unique_users_df):
    df = data[data['user_id'] == user]
    number = len(df)
    if number <= 5:
        pass
else:
    train_split = int(number * 0.80)
    test_split = int(number * 0.20)
    train_items = df.iloc[:train_split, :]
    test_items = df.iloc[-test_split:, :]
    train = pd.concat([train, train_items])
    test = pd.concat([test, test_items])
```

答:
Use:

```<code>df = pd.DataFrame({'user':['ali', 'ali', 'ali', 'reza', 'reza'], 'feat':[1,2,3,1,2]})
train = df.groupby('user')['feat'].apply(list).apply(lambda x: x[:int(.8*len(x))])
test = df.groupby('user')['feat'].apply(list).apply(lambda x: x[int(.8*len(x)):])
</code>```

Output:

Or, more simple:

```<code>train = df.groupby('user')['feat'].apply(lambda x: list(x)[:int(.8*len(x))])
</code>```

Body:
Use:

df = pd.DataFrame({'user':['ali', 'ali', 'ali', 'reza', 'reza'], 'feat':[1,2,3,1,2]})
train = df.groupby('user')['feat'].apply(list).apply(lambda x: x[:int(.8*len(x))])
test = df.groupby('user')['feat'].apply(list).apply(lambda x: x[int(.8*len(x)):])

Output:

Or, more simple:

train = df.groupby('user')['feat'].apply(lambda x: list(x)[:int(.8*len(x))])


问:
Labeling stack local variables (asm)
In an ASM function, one can use the stack to create a local workspace for variables.

What I am wondering is, can you create labels to reference them vs using an explicit numeric offset from the stack pointer?

Ex: one wants to ldr r0, sp+4 but use a symbol name instead? What is the correct way to do this? I can't imagine people remembering numeric offsets for everything.

答:
This really depends on the assembler. For the GNU toolchain (GCC with GAS), you can use an .S file (instead of an .s), and the gcc compiler driver will preprocess it like a C source file. So you could write

#define VAR sp+4
```
<p>and then use</p>
```        ldr r0, VAR
```

Note that macros are not properly scoped (restricted to the current function), so this can be quite confusing.

Title: Labeling stack local variables (asm)

Body:
This really depends on the assembler. For the GNU toolchain (GCC with GAS), you can use an .S file (instead of an .s), and the gcc compiler driver will preprocess it like a C source file. So you could write

#define VAR sp+4

and then use

        ldr r0, VAR

Note that macros are not properly scoped (restricted to the current function), so this can be quite confusing.


问:
Typedef in C, but a different way
I am aware of the standard way to define a structure in C. But, in analogy with this:

// <typedef structureName alias>
typedef unsigned long int u_int32
```
<p>I was expecting this to work too:</p>
<pre class="lang-c prettyprint-override"><code>struct myStr {char name[100]; float avgProb; int severity;};
typedef myStr ms;
myStr ms = {name:"hell", avgProb:50.0, severity:5,};
printf("myR %f", ms.avgProb);
</code>```

Is it just not possible to do it or I am missing something?

答:
I was expecting this to work also:

    typedef myStr ms;

Is it just not possible to do it or I am missing something?

It's possible, but what you're doing there isn't it.  (In a sense you're begging the question.)

Your attempt

```<code>typedef myStr ms;
</code>```

would work if myStr were already a typedef name.  But of course it's not, yet.

When you declare a structure like

```<code>struct myStr {char name[100]; float avgProb; int severity;};
</code>```

its full, official name (the name on its birth certificate, so to speak) is struct myStr.

A lot of programmers (especially if they've seen how "easy" it is in C++) wish that their structures had single names, wish that they didn't have to keep slinging that struct keyword around.  And you can certainly do that, by declaring a typedef.  But, when you declare this typedef, it has to be in terms of the full, official, existing name of the type.  So it's

```<code>typedef struct myStr ms;
</code>```

where we can break that down as

```<code>typedef struct myStr ms;
\_____/ \__________/ \/
keyword   old name   new
                     name
</code>```

You asked about C, but I suspect your thinking here has been influenced by something you may have heard abut C++.
Things are a little different in C++, and when you say

```<code>struct myStr {char name[100]; float avgProb; int severity;};
</code>```

it not only declares a structure struct myStr, it also implicitly creates a typedef at the same time.  It's as if you had also said

```<code>typedef struct myStr myStr;
</code>```

So now (in C++) you can either say

```<code>struct myStr struct1 = { "Fred", 1.2, 3 };
</code>```

or

```<code>myStr struct1 = { "Barney", 4.5, 6 };
</code>```

(And, in case you're wondering, yes: the typedef name is exactly the same as the structure name, but it turns out that's okay, and not ambiguous.)

So, in C++, you could say

```<code>typedef myStr ms;
</code>```

if you wanted to give your structure a second, shorter name.  Although, in C++, you wouldn't really need to do that, either, because you could just give it that shorter name to begin with:

```<code>struct ms {char name[100]; float avgProb; int severity;};
</code>```

Title: Typedef in C, but a different way

Body:
I am aware of the standard way to define a structure in C. But, in analogy with this:

// <typedef structureName alias>
typedef unsigned long int u_int32

I was expecting this to work too:

struct myStr {char name[100]; float avgProb; int severity;};
typedef myStr ms;
myStr ms = {name:"hell", avgProb:50.0, severity:5,};
printf("myR %f", ms.avgProb);

Is it just not possible to do it or I am missing something?

Body:
I was expecting this to work also:

    typedef myStr ms;

Is it just not possible to do it or I am missing something?

It's possible, but what you're doing there isn't it.  (In a sense you're begging the question.)

Your attempt

typedef myStr ms;

would work if myStr were already a typedef name.  But of course it's not, yet.

When you declare a structure like

struct myStr {char name[100]; float avgProb; int severity;};

its full, official name (the name on its birth certificate, so to speak) is struct myStr.

A lot of programmers (especially if they've seen how "easy" it is in C++) wish that their structures had single names, wish that they didn't have to keep slinging that struct keyword around.  And you can certainly do that, by declaring a typedef.  But, when you declare this typedef, it has to be in terms of the full, official, existing name of the type.  So it's

typedef struct myStr ms;

where we can break that down as

typedef struct myStr ms;
\_____/ \__________/ \/
keyword   old name   new
                     name

You asked about C, but I suspect your thinking here has been influenced by something you may have heard abut C++.
Things are a little different in C++, and when you say

struct myStr {char name[100]; float avgProb; int severity;};

it not only declares a structure struct myStr, it also implicitly creates a typedef at the same time.  It's as if you had also said

typedef struct myStr myStr;

So now (in C++) you can either say

struct myStr struct1 = { "Fred", 1.2, 3 };

or

myStr struct1 = { "Barney", 4.5, 6 };

(And, in case you're wondering, yes: the typedef name is exactly the same as the structure name, but it turns out that's okay, and not ambiguous.)

So, in C++, you could say

typedef myStr ms;

if you wanted to give your structure a second, shorter name.  Although, in C++, you wouldn't really need to do that, either, because you could just give it that shorter name to begin with:

struct ms {char name[100]; float avgProb; int severity;};


问:
How can I order these bars using ggplot? Why is the forcat method not working?
I'm trying to reorder the bars on my bargraph so they are biggest to smallest, ordered by log(Max_N) rather than alphabetically. I've tried using forcats but it brings up an error message. This is my code so far, whats going wrong? I'm trying to teach myself how to use ggplot, so please do point out any errors I've made, because I am self-taught!

```<code>library("ggplot2")
library (forcats)
test<-ggplot(all, aes(x=all$Species, y=log(all$Max_N+1))) +
geom_bar(stat = "identity") +
coord_flip()

test <- test + labs(title = "",
              subtitle = "",
              caption = "",
              y = "Log(MaxN)", x = "Species",
              tag = "")
test %>%
  mutate(name = fct_reorder(Species, log(Max_N+1)) %>%
</code>```

Original plot

a) Here's the reproducible example requested (I hope that's what you mean?)

```<code> structure(list(Site = c("Mylor", "Mylor", "Mylor", "Mylor", "Mylor",
 "Mylor", "Mylor", "Mylor", "Mylor", "Mylor"), Trial = c(1L, 1L,
 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L), Location = c("centre", "edge",
 "edge", "edge", "edge", "edge", "edge", "centre", "centre", "centre"
 ), Bait = c("whitefish", "whitefish", "whitefish", "whitefish",
 "whitefish", "whitefish", "whitefish", "whitefish", "whitefish",
 "whitefish"), ECP = c("yes", "yes", "yes", "yes", "yes", "yes",
 "yes", "no", "no", "no"), SSP = c("no", "no", "no", "no", "no",
 "no", "no", "no", "no", "no"), KP = c("no", "no", "no", "no",
 "no", "no", "no", "no", "no", "no"), OSP = c("no", "no", "no",
 "no", "no", "no", "no", "no", "no", "no"), Density =
 c("dense_seagrass",
  "dense_seagrass", "dense_seagrass", "dense_seagrass",
 "dense_seagrass",
 "dense_seagrass", "dense_seagrass", "dense_seagrass",
 "dense_seagrass",
 "dense_seagrass"), Viz = c(1.75, 1.75, 1.75, 1.75, 1.75, 1.75,
 1.75, 4.5, 4.5, 4.5), Species = c("sea_sprat", "corkwing_wrasse",
 "pollack", "sand_smelt", "unknown_wrasse", "two_spotted_goby",
 "unknown_wrasse", "mackerel", "sand_smelt", "mullet"), AJ = c("juv",
 "juv", "juv", "adu", "adu", "adu", "adu", "adu", "adu", "adu"
 ), FG = c("pelagic_neritic", "reef_associated", "pelagic_neritic",
 "pelagic_neritic", "reef_associated", "reef_associated",
 "reef_associated",
 "pelagic_neritic", "pelagic_neritic", "pelagic_neritic"), Max_N =
 c(1L,
 1L, 2L, 2L, 2L, 2L, 1L, 1L, 26L, 1L)), row.names = c(NA, 10L), class
 = "data.frame")
</code>```

b) so I changed the Species to name as suggested, and it has order some but not others? Changed code to this.

```<code> test<-ggplot(all2, aes(x=name, y=log(Max_N+1))) +
  geom_bar(stat = "identity") +
  coord_flip()
</code>```

plot after changing code to above

答:
Acutally if I were you, I will just have a reorder inside ggplot(aes()), then you don't need to change anything in your data.

If you want to plot this bar chart that sum up all Max_N within a species, you can do a group_by and summarise before piping into ggplot. This will NOT change your original all dataframe.

```<code>library(tidyverse)

all %>% group_by(Species) %>% summarize(Max_N = sum(Max_N)) %>%
  ggplot(all, aes(x = reorder(Species, Max_N), y =log(Max_N+1))) +
  geom_bar(stat = "identity") +
  coord_flip() + labs(x = "Species", y = "Log(MaxN)")
</code>```

Body:
I'm trying to reorder the bars on my bargraph so they are biggest to smallest, ordered by log(Max_N) rather than alphabetically. I've tried using forcats but it brings up an error message. This is my code so far, whats going wrong? I'm trying to teach myself how to use ggplot, so please do point out any errors I've made, because I am self-taught!

library("ggplot2")
library (forcats)
test<-ggplot(all, aes(x=all$Species, y=log(all$Max_N+1))) +
geom_bar(stat = "identity") +
coord_flip()

test <- test + labs(title = "",
              subtitle = "",
              caption = "",
              y = "Log(MaxN)", x = "Species",
              tag = "")
test %>%
  mutate(name = fct_reorder(Species, log(Max_N+1)) %>%

Original plot

a) Here's the reproducible example requested (I hope that's what you mean?)

 structure(list(Site = c("Mylor", "Mylor", "Mylor", "Mylor", "Mylor",
 "Mylor", "Mylor", "Mylor", "Mylor", "Mylor"), Trial = c(1L, 1L,
 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L), Location = c("centre", "edge",
 "edge", "edge", "edge", "edge", "edge", "centre", "centre", "centre"
 ), Bait = c("whitefish", "whitefish", "whitefish", "whitefish",
 "whitefish", "whitefish", "whitefish", "whitefish", "whitefish",
 "whitefish"), ECP = c("yes", "yes", "yes", "yes", "yes", "yes",
 "yes", "no", "no", "no"), SSP = c("no", "no", "no", "no", "no",
 "no", "no", "no", "no", "no"), KP = c("no", "no", "no", "no",
 "no", "no", "no", "no", "no", "no"), OSP = c("no", "no", "no",
 "no", "no", "no", "no", "no", "no", "no"), Density =
 c("dense_seagrass",
  "dense_seagrass", "dense_seagrass", "dense_seagrass",
 "dense_seagrass",
 "dense_seagrass", "dense_seagrass", "dense_seagrass",
 "dense_seagrass",
 "dense_seagrass"), Viz = c(1.75, 1.75, 1.75, 1.75, 1.75, 1.75,
 1.75, 4.5, 4.5, 4.5), Species = c("sea_sprat", "corkwing_wrasse",
 "pollack", "sand_smelt", "unknown_wrasse", "two_spotted_goby",
 "unknown_wrasse", "mackerel", "sand_smelt", "mullet"), AJ = c("juv",
 "juv", "juv", "adu", "adu", "adu", "adu", "adu", "adu", "adu"
 ), FG = c("pelagic_neritic", "reef_associated", "pelagic_neritic",
 "pelagic_neritic", "reef_associated", "reef_associated",
 "reef_associated",
 "pelagic_neritic", "pelagic_neritic", "pelagic_neritic"), Max_N =
 c(1L,
 1L, 2L, 2L, 2L, 2L, 1L, 1L, 26L, 1L)), row.names = c(NA, 10L), class
 = "data.frame")

b) so I changed the Species to name as suggested, and it has order some but not others? Changed code to this.

 test<-ggplot(all2, aes(x=name, y=log(Max_N+1))) +
  geom_bar(stat = "identity") +
  coord_flip()

plot after changing code to above

Body:
Acutally if I were you, I will just have a reorder inside ggplot(aes()), then you don't need to change anything in your data.

If you want to plot this bar chart that sum up all Max_N within a species, you can do a group_by and summarise before piping into ggplot. This will NOT change your original all dataframe.

library(tidyverse)

all %>% group_by(Species) %>% summarize(Max_N = sum(Max_N)) %>%
  ggplot(all, aes(x = reorder(Species, Max_N), y =log(Max_N+1))) +
  geom_bar(stat = "identity") +
  coord_flip() + labs(x = "Species", y = "Log(MaxN)")


问:
Entity Framework with multiple data sources
Is it possible to have an EDM that retrieves data from two data sources at the same time ? Say, it retrieves 3 tables from an SQL Server database and some other data from a binary file ?</p>

答: No, you'd need one EDMX per data source then use a repository to merge the results in memory.</p>


问:
Android Studio error "Installed Build Tools revision 31.0.0 is corrupted"
I'm on Android Studio 4.2.2. I created a new project and haven't added anything to the starter code and whenever I click build or run, I get this error:

Installed Build Tools revision 31.0.0 is corrupted. Remove and install again using the SDK Manager.

I've looked at other posts' suggestions, but neither of those solutions worked. Here's what I've tried:

SDK Manager → SDK Tools → check "Show package details", uncheck 31.0.0, and click "Apply" → Uninstall 31.0.0 → check 31.0.0 and reinstall it

In SDK Manager, deselect 31.0.0 and try installing an older version (e.g., I've tried 30.0.3) and update "buildToolsVersion" in build.gradle to the installed version

Went to Project Structure → Properties and verified that 31.0.0 is selected for "Build Tools Version" and "Compiled SDK Version"

Manually remove the stuff in the build-tools folder; i.e., rm -rf /path/to/android/sdk/build-tools/31.0.0 (it doesn't end in "-rc" like some other posts have described)

Restart Android Studio

Reinstall Android Studio

I'm an Android noob just trying to set up a Hello, World! project, and it really shouldn't be this hard.

答:
Change your Gradle build from:

```<code>android {
    compileSdkVersion 31
    buildToolsVersion '31.0.0'

    defaultConfig {
        applicationId "com.example.eg"
        minSdkVersion 23
        targetSdkVersion 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
</code>```

to:

```<code>android {
    compileSdk 31

    defaultConfig {
        applicationId "com.example.eg"
        minSdk 23
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
</code>```

This will work.

Body:
Change your Gradle build from:

android {
    compileSdkVersion 31
    buildToolsVersion '31.0.0'

    defaultConfig {
        applicationId "com.example.eg"
        minSdkVersion 23
        targetSdkVersion 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

to:

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.example.eg"
        minSdk 23
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

This will work.


问:
Compile GLobjects
I'm new to GLobjects and I have difficulties when compiling it.

my document structure:

In the main.cpp, I just use a simple #include<iostream> int main(){return 0;} as example.

In CMakeLists.txt, I wrote :

```<code>cmake_minimum_required(VERSION 3.2.0)
project(globject)
add_subdirectory(glm)
add_subdirectory(globjects)
add_executable(globject main.cpp)
target_link_libraries(globject glm globjects)
</code>```

The glm and globjects files contains the two libraries.
When I run cmake. in build, I got this error:

```<code>Could not find a package configuration file provided by "glm" with any of
  the following names:
    glmConfig.cmake
    glm-config.cmake
Add the installation prefix of "glm" to CMAKE_PREFIX_PATH or set "glm_DIR"
  to a directory containing one of the above files.
</code>```

I tried a lot of ways to fix the problem but I got nowhere. what is wrong here?

答:
We only have to include the proper header files  , no linking and compiling necessary.
GLM can be downloaded from their website.
Copy the root directory of the header files into your includes folder .

https://glm.g-truc.net/0.9.8/index.html

Title: Compile GLobjects

Body:
I'm new to GLobjects and I have difficulties when compiling it.

my document structure:

In the main.cpp, I just use a simple #include<iostream> int main(){return 0;} as example.

In CMakeLists.txt, I wrote :

cmake_minimum_required(VERSION 3.2.0)
project(globject)
add_subdirectory(glm)
add_subdirectory(globjects)
add_executable(globject main.cpp)
target_link_libraries(globject glm globjects)

The glm and globjects files contains the two libraries.
When I run cmake. in build, I got this error:

Could not find a package configuration file provided by "glm" with any of
  the following names:
    glmConfig.cmake
    glm-config.cmake
Add the installation prefix of "glm" to CMAKE_PREFIX_PATH or set "glm_DIR"
  to a directory containing one of the above files.

I tried a lot of ways to fix the problem but I got nowhere. what is wrong here?


问:
Cloud Run Web Hosting limitation
I'm considering a cloud run for web hosting rather than a complex compute engine.

I just want to make an api with node.js. I heard that automatic load balancing is also available. If so, is there any problem with concurrent traffic of 1 million people without any configuration? (The database server is somewhere else (which is serverless like cockroachDB)

Or Do I have to configure various complicated settings like aws ec2 or gce?

答:
For such traffic, out of the box configuration must be fine tuned.

Firstly, the concurrency parameter on Cloud Run. This parameter indicate how many concurrent request can be handle per instance. It's 80 the default value, and you can set up to 1000 concurrent requests per instance.

Of course, if you handle 1000 concurrent request per instance (or less) you should require more CPU and Memory. You can also play with those parameters

You also have to change the max instance limit. By default, you are limited to 1000.

If you set 1000 concurrent requests and 1000 instances, you can handle 1 million of concurrent request.

However, you don't have a lot of margins, or your instance with 1000 concurrent requests can be struggle even with max CPU and memory.

You can request more than 1000 instances with a quota increase request.

You can also optimise differently, especially if your 1 million users aren't in the same country/Google Cloud Region. if so, you can deploy a HTTPS load balancer in front of your cloud run service and deploy it in all the region of your users. (The Cloud Run services deployed in different regions must have the same name).

Like that, it's not only one service that will have to absorb 1 million of users, but several, in different regions. In addition, the HTTPS load balancer route the request to the closest region and therefore your optimize the latency, and reduce the egress/cross region traffic.

Title: Cloud Run Web Hosting limitation


问:
can ranges split be used with a predicate?
Can this double loop be rewritten using ranges views split() ?

```<code>#include <vector>
#include <span>

struct MyPair
{
    int a;
    char b;
};

vector<MyPair> path = {{1,'a'},{1,'z'},{2,'b'},{2,'y'}};
vector<span<MyPair> > spans;

for (int i=0; i < path.size();)
{
    auto r = path | ranges::views::drop(i) | views::take_while([&](const MyPair& p){return p.a == path[i].a;});
    int size = ranges::distance(r);
    span<Range> ranges(&path[i], size);
    spans.push_back(ranges);
    i += size ;
}
</code>```

I want a view of views looking like

```<code>{{{1,'a'},{1,'z'}},{{2,'b'},{2,'y'}}}
</code>```

答:
In the absence of views::chunk_by, here is my code, using a good old for loop:</p>
```<code>#include <vector>
#include <span>

struct MyPair
{
    int a;
    char b;
};

vector<MyPair> path = {{1,'a'},{1,'z'},{2,'b'},{2,'y'}};

vector<span<MyPair> > spans;

int i_prev=0;
for (int i=0;i < path.size(); i++)
{
    if (path[i].a != path[i_prev].a)
    {
        spans.push_back(span<MyPair>(&path[i_prev], i - i_prev));
                i_prev=i ;
    }
}
spans.push_back(span<MyPair>(&path[i_prev], path.size() - i_prev));
</code>```

Body:
Can this double loop be rewritten using ranges views split() ?

#include <vector>
#include

struct MyPair
{
    int a;
    char b;
};

vector<MyPair> path = {{1,'a'},{1,'z'},{2,'b'},{2,'y'}};
vector<span<MyPair> > spans;

for (int i=0; i < path.size();)
{
    auto r = path | ranges::views::drop(i) | views::take_while([&](const MyPair& p){return p.a == path[i].a;});
    int size = ranges::distance(r);
    span<Range> ranges(&path[i], size);
    spans.push_back(ranges);
    i += size ;
}

I want a view of views looking like

{{{1,'a'},{1,'z'}},{{2,'b'},{2,'y'}}}

Body:
In the absence of views::chunk_by, here is my code, using a good old for loop:

#include <vector>
#include <span>

struct MyPair
{
    int a;
    char b;
};

vector<MyPair> path = {{1,'a'},{1,'z'},{2,'b'},{2,'y'}};

vector<span<MyPair> > spans;

int i_prev=0;
for (int i=0;i < path.size(); i++)
{
    if (path[i].a != path[i_prev].a)
    {
        spans.push_back(span<MyPair>(&path[i_prev], i - i_prev));
                i_prev=i ;
    }
}
spans.push_back(span<MyPair>(&path[i_prev], path.size() - i_prev));


问:
Your test suite must contain at least one test
I have updated some of the dependencies today in my project, but it went through really smoothly. Now, when I'm about to push it, I started my tests. And boom. All of them throw:

Your test suite must contain at least one test.

My packages:

```<code>"jest": "23.1.0",
"jest-enzyme": "^6.0.1",
"jest-webpack-alias": "^3.3.3",
"jsdom": "^11.2.0",
"jsdom-global": "^3.0.2",
"enzyme": "3.3.0",
"enzyme-adapter-react-16": "^1.1.0",
"enzyme-to-json": "3.3.4",
</code>```

And that is how my sample test file looks like:

/shared/components/App/MyRoute/__tests__/MyRoute.test.js

```<code>/* eslint-disable import/no-extraneous-dependencies */
import React from 'react';
import { shallow } from 'enzyme';
import { ContactsRoute } from '../Route';

describe('<ContactsRoute />', () => {
  test('renders', () => {
    const wrapper = shallow(<ContactsRoute t={key => key} />);
    expect(wrapper).toMatchSnapshot();
  });
});
</code>```

I have no idea why they stopped running so suddenly?

Edit - adding my jest config

```<code>  "jest": {
"collectCoverageFrom": [
  "shared/**/*.{js,jsx}"
],
"globals": {
  "JWT_SECRET": "local",
  "IS_TEST": "true"
},
"snapshotSerializers": [
  "<rootDir>/node_modules/enzyme-to-json/serializer"
],
"testPathIgnorePatterns": [
  "<rootDir>/(build|internal|node_modules|flow-typed|public|shared/services)/"
],
"moduleNameMapper": {
  "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/_test_config_/mocks/fileMock.js"
},
"testURL": "http://localhost:3005",
"transform": {
  ".": "<rootDir>/_test_config_/preprocessors/webpackAlias.js",
  "^.+\\.css$": "<rootDir>/_test_config_/preprocessors/cssTransform.js",
  "^(?!.*\\.(js|jsx|css|json)$)": "<rootDir>/_test_config_/preprocessors/fileTransform.js"
},
"setupFiles": [
  "<rootDir>/_test_config_/preprocessors/polyfills.js"
],
"setupTestFrameworkScriptFile": "./node_modules/jest-enzyme/lib/index.js"
},
</code>```

答:
another issue which raises this Error is when you have put some none-test files into your __test__ directory.

All files in your __test__ directory must include some tests to run.

Body:
I have updated some of the dependencies today in my project, but it went through really smoothly. Now, when I'm about to push it, I started my tests. And boom. All of them throw:

Your test suite must contain at least one test.

My packages:

"jest": "23.1.0",
"jest-enzyme": "^6.0.1",
"jest-webpack-alias": "^3.3.3",
"jsdom": "^11.2.0",
"jsdom-global": "^3.0.2",
"enzyme": "3.3.0",
"enzyme-adapter-react-16": "^1.1.0",
"enzyme-to-json": "3.3.4",

And that is how my sample test file looks like:

/shared/components/App/MyRoute/__tests__/MyRoute.test.js

/* eslint-disable import/no-extraneous-dependencies */
import React from 'react';
import { shallow } from 'enzyme';
import { ContactsRoute } from '../Route';

describe('<ContactsRoute />', () => {
  test('renders', () => {
    const wrapper = shallow(<ContactsRoute t={key => key} />);
    expect(wrapper).toMatchSnapshot();
  });
});

I have no idea why they stopped running so suddenly?

Edit - adding my jest config

  "jest": {
"collectCoverageFrom": [
  "shared/**/*.{js,jsx}"
],
"globals": {
  "JWT_SECRET": "local",
  "IS_TEST": "true"
},
"snapshotSerializers": [
  "<rootDir>/node_modules/enzyme-to-json/serializer"
],
"testPathIgnorePatterns": [
  "<rootDir>/(build|internal|node_modules|flow-typed|public|shared/services)/"
],
"moduleNameMapper": {
  "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/_test_config_/mocks/fileMock.js"
},
"testURL": "http://localhost:3005",
"transform": {
  ".": "<rootDir>/_test_config_/preprocessors/webpackAlias.js",
  "^.+\\.css$": "<rootDir>/_test_config_/preprocessors/cssTransform.js",
  "^(?!.*\\.(js|jsx|css|json)$)": "<rootDir>/_test_config_/preprocessors/fileTransform.js"
},
"setupFiles": [
  "<rootDir>/_test_config_/preprocessors/polyfills.js"
],
"setupTestFrameworkScriptFile": "./node_modules/jest-enzyme/lib/index.js"
},


问:
How TThreadedSelectorServer support saml ？
How to using SAML with TThreadedSelectorServer ? i really can not find any articals  for it.
In my understanding, TThreadedSelectorServer is an advanced server based on NIO, so I want to use SAML together</p>

答:
I think you're misunderstanding what Thrift does.. it's a way to create server side stubs.. but you still must write logic yourself.. including handling SAML

if you have a more specific question I think it'd be easier to offer advice how to get started


问:
collapsing all other menu when one is expanded
I'm working on react js and I make a dashboard with sidebar(sidenav) in my sidebar I have a menu with submenu's And I want the collapse menus automatically when I click on one of the menus to be opened

              {MenuItems.map((menuItem, key) => (
                <MenuItem
                  key={key}
                  name={menuItem.name}
                  iconName={menuItem.iconName}
                  subMenu={menuItem.subMenu || []}
                />
              ))}

  ```
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React, { useState } from "react";
import { Link } from "react-router-dom";

const MenuItem = (props) => {
  const { name, subMenu, iconName } = props;
  const [expand, setExpand] = useState(false);
  return (
    <li onClick={props.onClick}>
      <a
        href="#"
        onClick={() => {
          setExpand(!expand);
        }}
        className={`menu-item ${expand ? "active" : ""}`}
      >
        <div className="menu-icon">
          <span>{iconName}</span>
        </div>
        <span>{name}</span>
      </a>
      {subMenu && subMenu.length > -0 ? (
        <ul className={`sub-menu ${expand ? "active" : ""}`}>
          {subMenu.map((menu, index, to) => (
            <li key={index} className={`${expand ? "active" : ""}`}>
              <Link to={menu.to}>{menu.name}</Link>
            </li>
          ))}
        </ul>
      ) : null}
    </li>
  );
};
export default MenuItem;</code>```

答:
If the subMenu prop has an id or a unique value, you can add another variable which will be the opend subMenu id

something like:

```<code>  const [opendMenuId, setOpendMenuId] = useState(null); // no menu is open by default

</code>```

and for the className

```<code> {subMenu.map((menu, index, to) => (
 <li key={index} className={`${opendMenuId === menu.id ? "active" : ""}`}>
   <Link to={menu.to}>{menu.name}</Link>
 </li>
)}
</code>```

Body:
I'm working on react js and I make a dashboard with sidebar(sidenav) in my sidebar I have a menu with submenu's And I want the collapse menus automatically when I click on one of the menus to be opened

              {MenuItems.map((menuItem, key) => (
                <MenuItem
                  key={key}
                  name={menuItem.name}
                  iconName={menuItem.iconName}
                  subMenu={menuItem.subMenu || []}
                />
              ))}

import React, { useState } from "react";
import { Link } from "react-router-dom";

const MenuItem = (props) => {
  const { name, subMenu, iconName } = props;
  const [expand, setExpand] = useState(false);
  return (

       {
          setExpand(!expand);
        }}
        className={`menu-item ${expand ? "active" : ""}`}
      >

          {iconName}

        {name}

      {subMenu && subMenu.length > -0 ? (
        <ul className={`sub-menu ${expand ? "active" : ""}`}>
          {subMenu.map((menu, index, to) => (
            <li key={index} className={`${expand ? "active" : ""}`}>
              <Link to={menu.to}>{menu.name}</Link>

          ))}

      ) : null}

  );
};
export default MenuItem;

Body:
If the subMenu prop has an id or a unique value, you can add another variable which will be the opend subMenu id

something like:

  const [opendMenuId, setOpendMenuId] = useState(null); // no menu is open by default

and for the className

 {subMenu.map((menu, index, to) => (
 <li key={index} className={`${opendMenuId === menu.id ? "active" : ""}`}>
   <Link to={menu.to}>{menu.name}</Link>
 </li>
)}


问:
Linux bash weave two text files into one alternative line using all available lines
I am looking to merge two text files into one,
where all the lines from one text file become odd line numbers
and the other file becomes even line numbers
such as to weave the files together

input1.txt

```<code>1, 267, Note_on_c, 0, 67, 100
1, 758, Note_on_c, 0, 58, 100
1, 1248, Note_on_c, 0, 79, 100
1, 1739, Note_on_c, 0, 52, 100
</code>```

input2.txt

```<code>1, 368, Note_off_c, 0, 67, 127
1, 936, Note_off_c, 0, 58, 127
1, 1415, Note_off_c, 0, 79, 127
1, 1917, Note_off_c, 0, 52, 127
</code>```

and need to combine these text files to create the following output

```<code>1, 267, Note_on_c, 0, 67, 100
1, 368, Note_off_c, 0, 67, 127
1, 758, Note_on_c, 0, 58, 100
1, 936, Note_off_c, 0, 58, 127
1, 1248, Note_on_c, 0, 79, 100
1, 1415, Note_off_c, 0, 79, 127
1, 1739, Note_on_c, 0, 52, 100
1, 1917, Note_off_c, 0, 52, 127
</code>```

so I am looking to merge these files in the true since of the word weave

答:
Another alternative would be using paste with a newline as delimiter

paste -d '\n' input1.txt input2.txt
```
```1, 267, Note_on_c, 0, 67, 100
1, 368, Note_off_c, 0, 67, 127
1, 758, Note_on_c, 0, 58, 100
1, 936, Note_off_c, 0, 58, 127
1, 1248, Note_on_c, 0, 79, 100
1, 1415, Note_off_c, 0, 79, 127
1, 1739, Note_on_c, 0, 52, 100
1, 1917, Note_off_c, 0, 52, 127
```

From man paste:

Write lines consisting of the sequentially corresponding lines from each FILE

Body:
I am looking to merge two text files into one,
where all the lines from one text file become odd line numbers
and the other file becomes even line numbers
such as to weave the files together

input1.txt

1, 267, Note_on_c, 0, 67, 100
1, 758, Note_on_c, 0, 58, 100
1, 1248, Note_on_c, 0, 79, 100
1, 1739, Note_on_c, 0, 52, 100

input2.txt

1, 368, Note_off_c, 0, 67, 127
1, 936, Note_off_c, 0, 58, 127
1, 1415, Note_off_c, 0, 79, 127
1, 1917, Note_off_c, 0, 52, 127

and need to combine these text files to create the following output

1, 267, Note_on_c, 0, 67, 100
1, 368, Note_off_c, 0, 67, 127
1, 758, Note_on_c, 0, 58, 100
1, 936, Note_off_c, 0, 58, 127
1, 1248, Note_on_c, 0, 79, 100
1, 1415, Note_off_c, 0, 79, 127
1, 1739, Note_on_c, 0, 52, 100
1, 1917, Note_off_c, 0, 52, 127

so I am looking to merge these files in the true since of the word weave

Body:
Another alternative would be using paste with a newline as delimiter

paste -d '\n' input1.txt input2.txt

1, 267, Note_on_c, 0, 67, 100
1, 368, Note_off_c, 0, 67, 127
1, 758, Note_on_c, 0, 58, 100
1, 936, Note_off_c, 0, 58, 127
1, 1248, Note_on_c, 0, 79, 100
1, 1415, Note_off_c, 0, 79, 127
1, 1739, Note_on_c, 0, 52, 100
1, 1917, Note_off_c, 0, 52, 127

From man paste:

Write lines consisting of the sequentially corresponding lines from each FILE


问:
Get id of tag using querySelector in Pug
I'm new to stackoverflow.
My question consists of kml, and pug.
My kml file looks like this:

```<code><Document>
<Placemark id="LIB02">
  <name>Agincourt</name>
  <description>Address: 155 Bonis Ave., Toronto, ON, M1T 3W6<br/>Link: https://www.torontopubliclibrary.ca/detail.jsp?R=LIB02</description>
  <address>155 Bonis Ave., Toronto, ON, M1T 3W6</address>
  <phoneNumber>416-396-8943</phoneNumber>
  <Point>
    <coordinates>-79.29342962962961,43.78516666666665</coordinates>
  </Point>
</Placemark>
</Document>
</code>```

I need to access the id of the placemark using pug and pass it to my libraries javascript function. My pug file is as follows:

```<code>li
- var id = library.querySelector("Document.Placemark/{id}").; //THE ERROR LIES HERE
- var p = library.querySelector("name").textContent;
a(href=`/libraries/${p}`) #{p}
</code>```

How do I get the id of my Placemark?

答:
How is used the pug?

render pug into static HTML via HtmlWebpackPlugin

load pug in JavaScript, like const tmpl = require('template.pug')

webpack.config.js

which pug loader is used

serverside render?

You should pass concrete data into pug.
For example, if you load pug in JavaScript:

const tmpl = require('template.pug');

const name = library.querySelector("name").textContent;
const renderedHtml = tmpl({
  name,
  // ... pass other data
});

```
<p>pug</p>
```li
  a(href=`/libraries/${name}`) #{name}
```

The renderedHtml contains the HTML string what can de inserted in DOM.

Body:
I'm new to stackoverflow.
My question consists of kml, and pug.
My kml file looks like this:

<Document>
<Placemark id="LIB02">
  <name>Agincourt</name>
  <description>Address: 155 Bonis Ave., Toronto, ON, M1T 3W6
Link: https://www.torontopubliclibrary.ca/detail.jsp?R=LIB02</description>
  <address>155 Bonis Ave., Toronto, ON, M1T 3W6</address>
  <phoneNumber>416-396-8943</phoneNumber>
  <Point>
    <coordinates>-79.29342962962961,43.78516666666665</coordinates>
  </Point>
</Placemark>
</Document>

I need to access the id of the placemark using pug and pass it to my libraries javascript function. My pug file is as follows:

li
- var id = library.querySelector("Document.Placemark/{id}").; //THE ERROR LIES HERE
- var p = library.querySelector("name").textContent;
a(href=`/libraries/${p}`) #{p}

How do I get the id of my Placemark?

Body:
How is used the pug?

render pug into static HTML via HtmlWebpackPlugin

load pug in JavaScript, like const tmpl = require('template.pug')

webpack.config.js

which pug loader is used

serverside render?

You should pass concrete data into pug.
For example, if you load pug in JavaScript:

const tmpl = require('template.pug');

const name = library.querySelector("name").textContent;
const renderedHtml = tmpl({
  name,
  // ... pass other data
});

pug

li
  a(href=`/libraries/${name}`) #{name}

The renderedHtml contains the HTML string what can de inserted in DOM.


问:
Throw an error "inside" an observable in angular
I want the same behavior as ReplaySubject.next(), but for errors (ReplaySubject.nextError())

Something that will make the error part of the subscription execute

I know about the ThrowError operator, but it doesn't work for me because it is creating a new observable that will throw an error, while I want an existing observable (ReplaySubject) to throw an error upon subscription.

```<code>obs = ReplaySubject(1);
obs.nextError('some error');
obs.subscribe(res=> {'this should not execute')} err=>{console.log('this should execute')})
</code>```

答:
Just throw use throwError in a switchMap.

```<code>of('some value')
  .pipe(
    switchMap((ms) => {
      return throwError(() => new Error(`Errory McErrorFace`));
    })
  )
  .subscribe({
    next: console.log, // not called
    error: console.error, // called
  });
</code>```

Body:
I want the same behavior as ReplaySubject.next(), but for errors (ReplaySubject.nextError())

Something that will make the error part of the subscription execute

I know about the ThrowError operator, but it doesn't work for me because it is creating a new observable that will throw an error, while I want an existing observable (ReplaySubject) to throw an error upon subscription.

obs = ReplaySubject(1);
obs.nextError('some error');
obs.subscribe(res=> {'this should not execute')} err=>{console.log('this should execute')})

Body:
Just throw use throwError in a switchMap.

of('some value')
  .pipe(
    switchMap((ms) => {
      return throwError(() => new Error(`Errory McErrorFace`));
    })
  )
  .subscribe({
    next: console.log, // not called
    error: console.error, // called
  });


问:
How Can I get Attribute value against each attribute name from a json response in .net after consuming it and deserialized it
```<code>    public class walletcustinfo
    {
        public int ID { get; set; }
        public string ATTRIBUTECODE { get; set; }
        public string ATTRIBUTENAME { get; set; }
        public string ATTRIBUTEVALUE { get; set; }
        public int ISMANDATORY { get; set; }
        public int ISUNIQUE { get; set; }
        public int ACCOUNTHOLDERID { get; set; }
    }

    public class Rootwalletinfo
    {
        public string code { get; set; }
        public string description { get; set; }
        public List<walletcustinfo> data { get; set; }
    }

    public Rootwalletinfo GetWalletCustomerInfo(string cnic, string IP)
    {
        Rootwalletinfo _response = new Rootwalletinfo()
        {
            code = "99",
            description = "Transaction Failed"
        };
        try
        {
            string url = "http://99.99.99.99:7777/Wallet-ggg-iurytrr/services/wallet/CustomerInfo/";
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(url);
            client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

            Log.WriteOnboardWalletLogEntry("\n\nInfo", IP, "Getting Response: ");

            HttpResponseMessage response = client.GetAsync(cnic).Result;

            var resp = response.Content.ReadAsStringAsync().Result;

            _response = JsonConvert.DeserializeObject<Rootwalletinfo>(resp);

            return _response;
        }
        catch (Exception e)
        {
            return _response;
        }
    }
</code>```

Json Response:
{
"code": "00",
"description": "SUCCESS",
"data": [
{
"ID": 6547362,
"ATTRIBUTECODE": "Company Name",
"ATTRIBUTENAME": "Company Name",
"ATTRIBUTEVALUE": "Jerry",
"ISMANDATORY": 0,
"ISUNIQUE": 0,
"ACCOUNTHOLDERID": 6454647
},
{
"ID": 10540617,
"ATTRIBUTECODE": "Product Name",
"ATTRIBUTENAME": "Product Name",
"ATTRIBUTEVALUE": "Pay Level 0",
"ISMANDATORY": 0,
"ISUNIQUE": 0,
"ACCOUNTHOLDERID": 4353647
}
]
}

答:
try this code

```<code>    var rootWalletInfo = GetWalletCustomerInfo(..);

    var values = rootWalletInfo.Data.Select(d => new {AttributeName= d.Attributename, AttributeValue=d.Attributevalue} );

    // or search

    var value= rootWalletInfo.Data.Where( i=> i.Attributename=="Company Name")
               .Select(d => d.Attributevalue ).FirstOrDefault(); // Jerry
</code>```

and to comply with c# name conventions , it is better to use these classes

```<code>public partial class RootWalletInfo
    {
        [JsonProperty("code")]
        public string Code { get; set; }

        [JsonProperty("description")]
        public string Description { get; set; }

        [JsonProperty("data")]
        public List<WalletCustInfo> data { get; set; }
    }

    public partial class WalletCustInfo
    {
        [JsonProperty("ID")]
        public long Id { get; set; }

        [JsonProperty("ATTRIBUTECODE")]
        public string Attributecode { get; set; }

        [JsonProperty("ATTRIBUTENAME")]
        public string Attributename { get; set; }

        [JsonProperty("ATTRIBUTEVALUE")]
        public string Attributevalue { get; set; }

        [JsonProperty("ISMANDATORY")]
        public long Ismandatory { get; set; }

        [JsonProperty("ISUNIQUE")]
        public long Isunique { get; set; }

        [JsonProperty("ACCOUNTHOLDERID")]
        public long Accountholderid { get; set; }
    }
</code>```

Body:
    public class walletcustinfo
    {
        public int ID { get; set; }
        public string ATTRIBUTECODE { get; set; }
        public string ATTRIBUTENAME { get; set; }
        public string ATTRIBUTEVALUE { get; set; }
        public int ISMANDATORY { get; set; }
        public int ISUNIQUE { get; set; }
        public int ACCOUNTHOLDERID { get; set; }
    }

    public class Rootwalletinfo
    {
        public string code { get; set; }
        public string description { get; set; }
        public List<walletcustinfo> data { get; set; }
    }

    public Rootwalletinfo GetWalletCustomerInfo(string cnic, string IP)
    {
        Rootwalletinfo _response = new Rootwalletinfo()
        {
            code = "99",
            description = "Transaction Failed"
        };
        try
        {
            string url = "http://99.99.99.99:7777/Wallet-ggg-iurytrr/services/wallet/CustomerInfo/";
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(url);
            client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

            Log.WriteOnboardWalletLogEntry("\n\nInfo", IP, "Getting Response: ");

            HttpResponseMessage response = client.GetAsync(cnic).Result;

            var resp = response.Content.ReadAsStringAsync().Result;

            _response = JsonConvert.DeserializeObject<Rootwalletinfo>(resp);

            return _response;
        }
        catch (Exception e)
        {
            return _response;
        }
    }

Json Response:
{
"code": "00",
"description": "SUCCESS",
"data": [
{
"ID": 6547362,
"ATTRIBUTECODE": "Company Name",
"ATTRIBUTENAME": "Company Name",
"ATTRIBUTEVALUE": "Jerry",
"ISMANDATORY": 0,
"ISUNIQUE": 0,
"ACCOUNTHOLDERID": 6454647
},
{
"ID": 10540617,
"ATTRIBUTECODE": "Product Name",
"ATTRIBUTENAME": "Product Name",
"ATTRIBUTEVALUE": "Pay Level 0",
"ISMANDATORY": 0,
"ISUNIQUE": 0,
"ACCOUNTHOLDERID": 4353647
}
]
}

Body:
try this code

    var rootWalletInfo = GetWalletCustomerInfo(..);

    var values = rootWalletInfo.Data.Select(d => new {AttributeName= d.Attributename, AttributeValue=d.Attributevalue} );

    // or search

    var value= rootWalletInfo.Data.Where( i=> i.Attributename=="Company Name")
               .Select(d => d.Attributevalue ).FirstOrDefault(); // Jerry

and to comply with c# name conventions , it is better to use these classes

public partial class RootWalletInfo
    {
        [JsonProperty("code")]
        public string Code { get; set; }

        [JsonProperty("description")]
        public string Description { get; set; }

        [JsonProperty("data")]
        public List<WalletCustInfo> data { get; set; }
    }

    public partial class WalletCustInfo
    {
        [JsonProperty("ID")]
        public long Id { get; set; }

        [JsonProperty("ATTRIBUTECODE")]
        public string Attributecode { get; set; }

        [JsonProperty("ATTRIBUTENAME")]
        public string Attributename { get; set; }

        [JsonProperty("ATTRIBUTEVALUE")]
        public string Attributevalue { get; set; }

        [JsonProperty("ISMANDATORY")]
        public long Ismandatory { get; set; }

        [JsonProperty("ISUNIQUE")]
        public long Isunique { get; set; }

        [JsonProperty("ACCOUNTHOLDERID")]
        public long Accountholderid { get; set; }
    }


问:
bash or zsh: how to pass multiple inputs to interactive piped parameters?
I have 3 different files that I want to compare

words_freq
words_freq_deduped
words_freq_alpha

For each file, I run a command like so, which I iterate on constantly to compare the results.

For example, I would do this:

```<code>$ cat words_freq | grep -v '[soe]'
$ cat words_freq_deduped | grep -v '[soe]'
$ cat words_freq_alpha | grep -v '[soe]'
</code>```

and then review the results, and then do it again, with an additional filter

```<code>$ cat words_freq | grep -v '[soe]' | grep a | grep r | head -n20
a

$ cat words_freq_deduped | grep -v '[soe]' | grep a | grep r | head -n20
b

$ cat words_freq_alpha | grep -v '[soe]' | grep a | grep r | head -n20
c
</code>```

This continues on until I've analyzed my data.

I would like to write a script that could take the piped portions, and pass it to each of these files, as I iterate on the grep/head portions of the command.

e.g. The following would dump the results of running the 3 commands above AND also compare the 3 results, and dump additional calculations on them

```<code>$ myScript | grep -v '[soe]' | grep a | grep r | head -n20
the letters were in all 3 runs, and it took 5 seconds
a
b
c
</code>```

How can I do this using bash/python or zsh for the myScript part?

EDIT: After asking the question, it occurred to me that I could use eval to do it, like so, which I've added as an answer as well

The following approach allows me to process multiple files by using eval, which I know is frowned upon - any other suggestions are greatly appreciated!

```<code>$ myScript "grep -v '[soe]' | grep a | grep r | head -n20"
</code>```

myScript

```<code>#!/usr/bin/env bash
function doIt(){
  FILE=$1
  CMD="cat $1 | $2"
  echo processing file "$FILE"
  eval "$CMD"
  echo
}

doIt words_freq "$@"
doIt words_freq_deduped "$@"
doIt words_freq_alpha "$@"
</code>```

答:
Not fully understood problem correctly.

I understood you want to write a script without pipes, by including the filtering logic into the script.
And feeding the filtering patterns as arguments.

Here is a gawk script (standard Linux awk).

With one sweep on 3 input files, without piping.

script.awk

```<code>BEGIN {
  RS="!@!@!@!@!@!@!@";
  # set record separator to something unlikely matched, causing each file to be read entirely as a single record
}
$0 !~ excludeRegEx      # if file does not match excludeRegEx
&& $0 ~ includeRegEx1   # and match includeRegEx1
&& $0 ~ includeRegEx2 { # and match includeRegEx2
  system "head -n20 "FILENAME; # call shell command "head -n20 " on current filename
}
</code>```

Running script.awk

```<code>   awk -v excludeRegEx='[soe]' \
       -v includeRegEx1='a' \
       -v includeRegEx2='r' \
       -f script.awk words_freq words_freq_deduped words_freq_alpha
</code>```

Body:
I have 3 different files that I want to compare

words_freq
words_freq_deduped
words_freq_alpha

For each file, I run a command like so, which I iterate on constantly to compare the results.

For example, I would do this:

$ cat words_freq | grep -v '[soe]'
$ cat words_freq_deduped | grep -v '[soe]'
$ cat words_freq_alpha | grep -v '[soe]'

and then review the results, and then do it again, with an additional filter

$ cat words_freq | grep -v '[soe]' | grep a | grep r | head -n20
a

$ cat words_freq_deduped | grep -v '[soe]' | grep a | grep r | head -n20
b

$ cat words_freq_alpha | grep -v '[soe]' | grep a | grep r | head -n20
c

This continues on until I've analyzed my data.

I would like to write a script that could take the piped portions, and pass it to each of these files, as I iterate on the grep/head portions of the command.

e.g. The following would dump the results of running the 3 commands above AND also compare the 3 results, and dump additional calculations on them

$ myScript | grep -v '[soe]' | grep a | grep r | head -n20
the letters were in all 3 runs, and it took 5 seconds
a
b
c

How can I do this using bash/python or zsh for the myScript part?

EDIT: After asking the question, it occurred to me that I could use eval to do it, like so, which I've added as an answer as well

The following approach allows me to process multiple files by using eval, which I know is frowned upon - any other suggestions are greatly appreciated!

$ myScript "grep -v '[soe]' | grep a | grep r | head -n20"

myScript

#!/usr/bin/env bash
function doIt(){
  FILE=$1
  CMD="cat $1 | $2"
  echo processing file "$FILE"
  eval "$CMD"
  echo
}

doIt words_freq "$@"
doIt words_freq_deduped "$@"
doIt words_freq_alpha "$@"

Body:
Not fully understood problem correctly.

I understood you want to write a script without pipes, by including the filtering logic into the script.
And feeding the filtering patterns as arguments.

Here is a gawk script (standard Linux awk).

With one sweep on 3 input files, without piping.

script.awk

BEGIN {
  RS="!@!@!@!@!@!@!@";
  # set record separator to something unlikely matched, causing each file to be read entirely as a single record
}
$0 !~ excludeRegEx      # if file does not match excludeRegEx
&& $0 ~ includeRegEx1   # and match includeRegEx1
&& $0 ~ includeRegEx2 { # and match includeRegEx2
  system "head -n20 "FILENAME; # call shell command "head -n20 " on current filename
}

Running script.awk

   awk -v excludeRegEx='[soe]' \
       -v includeRegEx1='a' \
       -v includeRegEx2='r' \
       -f script.awk words_freq words_freq_deduped words_freq_alpha


问:
Are there any compression and encryption libraries in C#?
I want to compress some files (into the ZIP format) and encrypt them if possible using C#. Is there some way to do this?

Can encryption be done as a part of the compression itself?

答:
Here is a useful topic:

Help in creating Zip files from .Net and reading them from Java

System.IO.Packaging namespace gives you useful classes to compress data in zip format and support rights management.

OwnerDisplayName: Niyaz

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: aku


问:
How should I set up run-time external resources in my project?
I'm creating a command line program that uses a defined set of external files (.txts and the like) at runtime. I need it to have these in its working directory when run. Currently, I have them in a folder in the solutiondir with an xcopy into the projectdir as a pre-build event. What's the "accepted" way to set up a situation like this?</p>

答:
If its a .net project then you can mark those files are copy to output directory.

in c++ land (vcproj) you need to use the Pre/Post build step and copy them into the $(TargetDir)/$(ProjectDir)

OwnerDisplayName: Stuart P. Bentley

LastEditorDisplayName: Stuart P. Bentley

OwnerDisplayName: Shay Erlichmen


问:
How to update 2 JCombo Boxs
I have 2 Jcombo Boxs: which is combo1 and combo2

I choose combo1 and I can get information for combo2 but The problem is I can get informatiob for combo2 but it is not updated. I also try to use updata.UI() but it doesn't help.

This is the code in side

```<code>public void actionPerformed(ActionEvent e) {
    JComboBox cb = (JComboBox)e.getSource();
    String uname1 = (String)cb.getSelectedItem();

        combo2 = update(uname1);
        combo2.updateUI();

}
</code>```

This is code inside update

```<code>protected JComboBox update(String name) {
    JComboBox tmp = new JComboBox();
    //Read Content from XML file (University is bigger than Year)
    NodeList nList = doc.getElementsByTagName("University");
    System.out.println("Inside Fn " + name);
    for(int i = 0 ; i < nList.getLength();i++) {
        Element el = (Element)nList.item(i);
        if(name.contentEquals(el.getAttributeNode("name").getNodeValue()))
        {
            NodeList tmpyList = el.getElementsByTagName("Year");
            for(int j = 0 ; j < tmpyList.getLength();j++)
            {
                Element yl = (Element)tmpyList.item(j);
                System.out.println(yl.getAttribute("yr"));
                tmp.addItem(yl.getAttribute("yr"));
            }
        }
    }
    return tmp; //Return ComboBox to combo2
}
</code>```

Thank you for your kindness, I try to use your code but it is not work (It still not update), please help me

This is my constructor

```<code>public JFrameExample() {
    String[] comboboxdefault = { "Select" };

    JComboBox combo1 = Universitylist();
    JComboBox combo2 = new JComboBox(comboboxdefault);
    JComboBox combo3 = new JComboBox(comboboxdefault);

    uList.addActionListener(this);
    yList.addActionListener(this);
    dList.addActionListener(this);

    JPanel student_information = new JPanel(new GridLayout(0,1));
    uList.setName("University List");
    yList.setName("Year List");

    // University List

    student_information.add(combo1);
    // Database Year List

    student_information.add(combo2);
    // Programme List

    student_information.add(combo3);
    //Add Components to this container, using the default FlowLayout.
    add(student_information);

}
</code>```

This is the combo2 Update it is return String Array

```<code>protected String[] updateyList(String name)
{
    String[] tmp = null;

           //Read from XML file
    for(int i = 0 ; i < nList.getLength();i++) {
        Element el = (Element)nList.item(i);
        if(name.contentEquals(el.getAttributeNode("name").getNodeValue()))
        {
            NodeList tmpyList = el.getElementsByTagName("Year");
            tmp = new String[tmpyList.getLength()];
            for(int j = 0 ; j < tmpyList.getLength();j++)
            {
                Element yl = (Element)tmpyList.item(j);
                //Add to String Array
                tmp[j] = yl.getAttribute("yr");
            }
        }
    }

    return tmp;
}
</code>```

In the Action Perform

```<code>public void actionPerformed(ActionEvent e) {
    JComboBox cb = (JComboBox)e.getSource();
    String uname1 = (String)cb.getSelectedItem();
    System.out.println(cb.getName()); // To make sure I got the combo1.
    try {
        //I change to the model method
        DefaultComboBoxModel model = new DefaultComboBoxModel(  updateyList(uname1) );
        System.out.println(model.getSize());
        combo2 = new JComboBox(); // If I don't have this line it will throw  error Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
        combo2.setModel(model);

    } catch (ParserConfigurationException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (SAXException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

}
</code>```

And this is for creating GUI function

```<code>private static void createAndShowLoginGUI() {

   //Create and set up the window.
    JFrame frame = new JFrame("Login");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Create and set up the content pane.
    JFrameExample newContentPane = new JFrameExample();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);

    //Display the window.
    frame.pack();
    frame.setVisible(true);
}
</code>```

This is main function

```<code>public static void main(String[] args)
{
    //Schedule a job for the event-dispatching thread:

    //creating and showing this application's GUI.

    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowLoginGUI();
        }
    });
}
</code>```

I think I did something wrong but I don't know where

答: As you do now, you recreate the combo box every time (by returning the tmp in update method). This as it seems is not reflecting in the UI and maybe others will post the reason. But if you can change to update the combo values (changing the model or deleting the current values and adding the new ones) instead of recreating, then the following post can help you Dynamically change JComboBox</p>

Title: How to update 2 JCombo Boxs

Body:
I have 2 Jcombo Boxs: which is combo1 and combo2

I choose combo1 and I can get information for combo2 but The problem is I can get informatiob for combo2 but it is not updated. I also try to use updata.UI() but it doesn't help.

This is the code in side

public void actionPerformed(ActionEvent e) {
    JComboBox cb = (JComboBox)e.getSource();
    String uname1 = (String)cb.getSelectedItem();

        combo2 = update(uname1);
        combo2.updateUI();

}

This is code inside update

protected JComboBox update(String name) {
    JComboBox tmp = new JComboBox();
    //Read Content from XML file (University is bigger than Year)
    NodeList nList = doc.getElementsByTagName("University");
    System.out.println("Inside Fn " + name);
    for(int i = 0 ; i < nList.getLength();i++) {
        Element el = (Element)nList.item(i);
        if(name.contentEquals(el.getAttributeNode("name").getNodeValue()))
        {
            NodeList tmpyList = el.getElementsByTagName("Year");
            for(int j = 0 ; j < tmpyList.getLength();j++)
            {
                Element yl = (Element)tmpyList.item(j);
                System.out.println(yl.getAttribute("yr"));
                tmp.addItem(yl.getAttribute("yr"));
            }
        }
    }
    return tmp; //Return ComboBox to combo2
}

Thank you for your kindness, I try to use your code but it is not work (It still not update), please help me

This is my constructor

public JFrameExample() {
    String[] comboboxdefault = { "Select" };

    JComboBox combo1 = Universitylist();
    JComboBox combo2 = new JComboBox(comboboxdefault);
    JComboBox combo3 = new JComboBox(comboboxdefault);

    uList.addActionListener(this);
    yList.addActionListener(this);
    dList.addActionListener(this);

    JPanel student_information = new JPanel(new GridLayout(0,1));
    uList.setName("University List");
    yList.setName("Year List");

    // University List

    student_information.add(combo1);
    // Database Year List

    student_information.add(combo2);
    // Programme List

    student_information.add(combo3);
    //Add Components to this container, using the default FlowLayout.
    add(student_information);

}

This is the combo2 Update it is return String Array

protected String[] updateyList(String name)
{
    String[] tmp = null;

           //Read from XML file
    for(int i = 0 ; i < nList.getLength();i++) {
        Element el = (Element)nList.item(i);
        if(name.contentEquals(el.getAttributeNode("name").getNodeValue()))
        {
            NodeList tmpyList = el.getElementsByTagName("Year");
            tmp = new String[tmpyList.getLength()];
            for(int j = 0 ; j < tmpyList.getLength();j++)
            {
                Element yl = (Element)tmpyList.item(j);
                //Add to String Array
                tmp[j] = yl.getAttribute("yr");
            }
        }
    }

    return tmp;
}

In the Action Perform

public void actionPerformed(ActionEvent e) {
    JComboBox cb = (JComboBox)e.getSource();
    String uname1 = (String)cb.getSelectedItem();
    System.out.println(cb.getName()); // To make sure I got the combo1.
    try {
        //I change to the model method
        DefaultComboBoxModel model = new DefaultComboBoxModel(  updateyList(uname1) );
        System.out.println(model.getSize());
        combo2 = new JComboBox(); // If I don't have this line it will throw  error Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
        combo2.setModel(model);

    } catch (ParserConfigurationException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (SAXException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

}

And this is for creating GUI function

private static void createAndShowLoginGUI() {

   //Create and set up the window.
    JFrame frame = new JFrame("Login");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Create and set up the content pane.
    JFrameExample newContentPane = new JFrameExample();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);

    //Display the window.
    frame.pack();
    frame.setVisible(true);
}

This is main function

public static void main(String[] args)
{
    //Schedule a job for the event-dispatching thread:

    //creating and showing this application's GUI.

    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowLoginGUI();
        }
    });
}

I think I did something wrong but I don't know where