问:
Function of two cells
What is wrong about:

```<code>Function Muh(a As Double, b As Double) As Double
   Muh = a + b
End Function
</code>```

and table with say A1=2 and B1=3 an defining C1=Muh(A1,B1)?
And how can I fix it?

答:
Replace the comma with a semicolon</p>

```<code>C1=Muh(A1;B1)
</code>```

Title: Function of two cells

Body:
What is wrong about:

Function Muh(a As Double, b As Double) As Double
   Muh = a + b
End Function

and table with say A1=2 and B1=3 an defining C1=Muh(A1,B1)?
And how can I fix it?

Body:
Replace the comma with a semicolon

C1=Muh(A1;B1)


来源: stackexchange

问:
c++ two functions do the same except one line
I dont want to duplicate my code, but I have 2 functions which do the same except 1 line.
I do want separate functions that will call a private function, that might be a template and will solve my duplicate code problem.

```<code>double EuclideanDistance::calculateDistance(const Point &p1, const Point &p2) const
{
    if (p1.getDimension()!=p2.getDimension())
        return 0;
    double sum = 0.0;
    for( size_t i = 0; i < p1.getDimension(); i++)
    {
        sum += pow( p1[i] - p2[i], 2.0);
    }
    return sqrt(sum);
}

double EuclideanDistance::calculateWeightedDistance(const Point &p1, const Point &p2, const double *weights) const
{
    if (p1.getDimension()!=p2.getDimension())
        return 0;
    double sum = 0.0;
    for( size_t i = 0; i < p1.getDimension(); i++)
    {
        sum += pow( ((p1[i] - p2[i])*weights[i]), 2.0);//here is the difference
    }
    return sqrt(sum);
}
</code>```

what do you suggest?

答:
What about the following?
If you invoke the function with the third parameter nullptr, then the behaviour of the first version is executed.

```<code>double EuclideanDistance::calculateWeightedDistance(const Point& p1, const Point& p2, const double* weights) const {
    if (p1.getDimension()!=p2.getDimension())
        return 0;

    double sum = 0.0;
    for( size_t i = 0; i < p1.getDimension(); i++)
    {
        const auto distance_d = (p1[i] - p2[i]) *
                                (weights != nullptr ? weights[i] : 1.0);
        sum += pow(distance_d, 2.0);
    }
    return sqrt(sum);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I dont want to duplicate my code, but I have 2 functions which do the same except 1 line.
I do want separate functions that will call a private function, that might be a template and will solve my duplicate code problem.

double EuclideanDistance::calculateDistance(const Point &p1, const Point &p2) const
{
    if (p1.getDimension()!=p2.getDimension())
        return 0;
    double sum = 0.0;
    for( size_t i = 0; i < p1.getDimension(); i++)
    {
        sum += pow( p1[i] - p2[i], 2.0);
    }
    return sqrt(sum);
}

double EuclideanDistance::calculateWeightedDistance(const Point &p1, const Point &p2, const double *weights) const
{
    if (p1.getDimension()!=p2.getDimension())
        return 0;
    double sum = 0.0;
    for( size_t i = 0; i < p1.getDimension(); i++)
    {
        sum += pow( ((p1[i] - p2[i])*weights[i]), 2.0);//here is the difference
    }
    return sqrt(sum);
}

what do you suggest?

Body:
What about the following?
If you invoke the function with the third parameter nullptr, then the behaviour of the first version is executed.

double EuclideanDistance::calculateWeightedDistance(const Point& p1, const Point& p2, const double* weights) const {
    if (p1.getDimension()!=p2.getDimension())
        return 0;

    double sum = 0.0;
    for( size_t i = 0; i < p1.getDimension(); i++)
    {
        const auto distance_d = (p1[i] - p2[i]) *
                                (weights != nullptr ? weights[i] : 1.0);
        sum += pow(distance_d, 2.0);
    }
    return sqrt(sum);
}


问:
How to put json array in json object
This is code which I'm using:

```<code>@Override
protected String doInBackground(String... arg0) {
    String yourJsonStringUrl = "GetCalender_Events";
    JsonParser jParser = new JsonParser();
    json = jParser.getJSONFromUrlArray(yourJsonStringUrl);
    return null;
}

@Override
protected void onPostExecute(String strFromDoInBg) {
    for (int i = 0; i < json.length(); i++) {
        try {
            JSONObject c = json.getJSONObject(i);
            ldatosAgenda.add(new DatosAgenda(c.getString("Event_Name"), c.getString("Event_Name"),
                    sdf5.format(sdf1.parse(c.getString("Column1"))), sdf6.format(sdf1.parse(c.getString("Column1"))),
                    c.getString("Description")));
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

}
</code>```

How to put my JSON Array into JSON object? Can anyone please help me, this is my first try with JSON Array.

My array looks like this:

```<code>{
  "ContactList": [
    {
      "Column1": "22-05-2017",
      "Event_Name": "Garba Compition",
      "Description": "School organized garba compition"
    },
    {
      "Column1": "24-05-2017",
      "Event_Name": "Mahendi Compition",
      "Description": "Mahendi compition"
    }
  ]
}
</code>```

答:
#. Seems you are getting JSONObject as response. So you have to parse JSONObject first from sever response:

```<code>JSONObject json = jParser.getJSONFromUrlObject(yourJsonStringUrl);
</code>```

#. Then parse ContactList and its item as below:

```<code>@Override
protected void onPostExecute(String strFromDoInBg) {

    JSONArray jsonArray = json.getJSONArray("ContactList");

    for (int i = 0; i < jsonArray.length(); i++) {
        try
        {
            JSONObject c = jsonArray.getJSONObject(i);
            ldatosAgenda.add(new DatosAgenda(c.getString("Event_Name"),c.getString("Event_Name"), sdf5.format(sdf1.parse(c.getString("Column1"))), sdf6.format(sdf1.parse(c.getString("Column1"))),c.getString("Description")));
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
</code>```

Title: How to put json array in json object

Body:
This is code which I'm using:

@Override
protected String doInBackground(String... arg0) {
    String yourJsonStringUrl = "GetCalender_Events";
    JsonParser jParser = new JsonParser();
    json = jParser.getJSONFromUrlArray(yourJsonStringUrl);
    return null;
}

@Override
protected void onPostExecute(String strFromDoInBg) {
    for (int i = 0; i < json.length(); i++) {
        try {
            JSONObject c = json.getJSONObject(i);
            ldatosAgenda.add(new DatosAgenda(c.getString("Event_Name"), c.getString("Event_Name"),
                    sdf5.format(sdf1.parse(c.getString("Column1"))), sdf6.format(sdf1.parse(c.getString("Column1"))),
                    c.getString("Description")));
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

}

How to put my JSON Array into JSON object? Can anyone please help me, this is my first try with JSON Array.

My array looks like this:

{
  "ContactList": [
    {
      "Column1": "22-05-2017",
      "Event_Name": "Garba Compition",
      "Description": "School organized garba compition"
    },
    {
      "Column1": "24-05-2017",
      "Event_Name": "Mahendi Compition",
      "Description": "Mahendi compition"
    }
  ]
}

Body:
#. Seems you are getting JSONObject as response. So you have to parse JSONObject first from sever response:

JSONObject json = jParser.getJSONFromUrlObject(yourJsonStringUrl);

#. Then parse ContactList and its item as below:

@Override
protected void onPostExecute(String strFromDoInBg) {

    JSONArray jsonArray = json.getJSONArray("ContactList");

    for (int i = 0; i < jsonArray.length(); i++) {
        try
        {
            JSONObject c = jsonArray.getJSONObject(i);
            ldatosAgenda.add(new DatosAgenda(c.getString("Event_Name"),c.getString("Event_Name"), sdf5.format(sdf1.parse(c.getString("Column1"))), sdf6.format(sdf1.parse(c.getString("Column1"))),c.getString("Description")));
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}


问:
angular2/javascript - NgFor looping through array inside of object
I have my own object with data which I loop through using ngFor. However there is an array part in the object, which I want to loop through as well in a

Currently it looks like this. However I don't want the complete string in one

 I just want one piece of the array there.

Relevant Code:

tier.model

```<code>export class Tier {
  constructor (
    public id: number,
    public title: string,
    public rewards: any[],
    public price: number
  )
  {}
}
</code>```

component:

```<code>export class PackagesComponent {  //will be renamed to TierComponent
  public tierToEdit: Tier;
  editMode = false;
  tiers: Tier[] = [
    new Tier(
      10,
      'First Tier',
      ['Server access - Simple', 'Win something small', 'and so on'],
      5.00),
    new Tier(
      11,
      'Second Tier',
      ['Server access - Standard', 'Win something medium', 'and so on and on'],
      10.00),
    new Tier(
      12,
      'Third Tier',
      ['Server access - Advanced', 'Win something big', 'and so on and on and on'],
      10.00)
  ]
</code>```

template:

```<code><div class="row">
  <div  class="col-md-4" *ngFor="let tier of tiers; let i=index;">
    <ul class="pricing-table">
      <li class="plan-name">
        {{ tier.title }}
      </li>
      <li *ngFor="let reward of tiers">
        {{ reward.rewards }}
      </li>
      <p class="plan-price">{{ tier.price }}</p>
      <li class="plan-action">
        <a class="btn btn-primary" (click)="onEdit(tier)">Edit</a>
        <a class="btn btn-success" (click)="this.clickSave()">SaveYes</a>
        <a class="btn btn-warning" >Get</a>
      </li>
    </ul>
</code>```

In the end it should look like this:

Something else I tried was this:

```<code><div  class="col-md-4" *ngFor="let tier of tiers; let i=index;">
    <!-- Show Mode -->
    <ul *ngIf="!editMode || tierToEdit != tier" class="pricing-table">
      <li class="plan-name">
        {{ tier.title }}
      </li>
      <li *ngFor="let reward of tiers; let i=index">
        {{ reward.rewards[i] }}
      </li>
</code>```

Which than gave me the first element of the first array, the second element of the second array and the third element of the third array:

Hope this is not to confusing, still very new to angular/javascript, sorry for possibly asking stupid question or using wrong terms :) Thank you very much!

答:
try this  </p>

```<code>   <li *ngFor="let reward of tier.rewards">
        {{ reward }}
   </li>
</code>```

Body:
I have my own object with data which I loop through using ngFor. However there is an array part in the object, which I want to loop through as well in a

Currently it looks like this. However I don't want the complete string in one

 I just want one piece of the array there.

Relevant Code:

tier.model

export class Tier {
  constructor (
    public id: number,
    public title: string,
    public rewards: any[],
    public price: number
  )
  {}
}

component:

export class PackagesComponent {  //will be renamed to TierComponent
  public tierToEdit: Tier;
  editMode = false;
  tiers: Tier[] = [
    new Tier(
      10,
      'First Tier',
      ['Server access - Simple', 'Win something small', 'and so on'],
      5.00),
    new Tier(
      11,
      'Second Tier',
      ['Server access - Standard', 'Win something medium', 'and so on and on'],
      10.00),
    new Tier(
      12,
      'Third Tier',
      ['Server access - Advanced', 'Win something big', 'and so on and on and on'],
      10.00)
  ]

template:

        {{ tier.title }}

        {{ reward.rewards }}

{{ tier.price }}

        Edit
        SaveYes
        Get

In the end it should look like this:

Something else I tried was this:

        {{ tier.title }}

        {{ reward.rewards[i] }}

Which than gave me the first element of the first array, the second element of the second array and the third element of the third array:

Hope this is not to confusing, still very new to angular/javascript, sorry for possibly asking stupid question or using wrong terms :) Thank you very much!

Body:
try this

   <li *ngFor="let reward of tier.rewards">
        {{ reward }}
   </li>


问:
Remove object in array using filter and splice which one is best approach in JavaScript?
Hi I delete an object in an array using two approaches:-
splice and filter.

splice code here:-

```<code>(this.myArray).splice((this.myArray).indexOf(myobject), 1);
</code>```

filter code here:-

```<code>(this.myArray).filter(obj => obj !== myobject);
</code>```

Please tell us differences between both and which one is the best approach?

答: In case you know the index using splice would be an O(1) operation while using filter is an O(n) operation.</p>

ContentLicense: CC BY-SA 4.0

Body:
Hi I delete an object in an array using two approaches:-
splice and filter.

splice code here:-

(this.myArray).splice((this.myArray).indexOf(myobject), 1);

filter code here:-

(this.myArray).filter(obj => obj !== myobject);

Please tell us differences between both and which one is the best approach?


问:
Jenkins Pipeline: How do I fetch (not pull) a different branch?
I'm trying to use Jenkins Pipelines and I would like to diff the current branch of the job to master. For that I need to have master checked out. Jenkins only checks out the branch I'm building.

I tried:

withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'GITHUB', usernameVariable:  'GIT_USERNAME', passwordVariable: 'GIT_PASSWORD']]) {
   sh 'git fetch origin master:master'
}

but that only binds the credentials to the ENV variables and git doesn't pick that up.

All the other approaches I've seen use checkout, but that would change my current branch. I only want to fetch the master so I can do a git diff later

答:
I found a workaround:

```<code>git branch: 'master', credentialsId: 'GITHUB', url: env.GIT_URL
git branch: env.BRANCH_NAME, credentialsId: 'GITHUB', url: env.GIT_URL
</code>```

First I check out the master branch and then check out my branch again. This is not ideal, since its changing the working tree instead of just fetching the master branch, but it works.

Body:
I found a workaround:

git branch: 'master', credentialsId: 'GITHUB', url: env.GIT_URL
git branch: env.BRANCH_NAME, credentialsId: 'GITHUB', url: env.GIT_URL

First I check out the master branch and then check out my branch again. This is not ideal, since its changing the working tree instead of just fetching the master branch, but it works.


问:
calling a synonym of a procedure where input parameter is user-defined table type
On DatabaseA I have User-Defined Data Type which is used as input parameter in a stored procedure. On another database (DatabaseB) I am creating synonym to this procedure and I am creating same data type there.

When I call the sysnonym I am reciving an error "Operand type clash: Ids is incompatible with Ids"

Any suggestion how to resolve this problem?

```<code>use DatabaseA
go

CREATE TYPE [dbo].[Ids] AS TABLE(
    [Id] [sql_variant] NULL
)
GO

create procedure dbo.proc1 @Ids [Ids] readonly
as
begin
    select *
    from @Ids;
end

declare @Ids  dbo.Ids;
insert into @Ids values (1),(2)
exec dbo.proc1
    @Ids = @Ids

use DatabaseB

CREATE TYPE [dbo].[Ids] AS TABLE(
    [Id] [sql_variant] NULL
)
go

CREATE SYNONYM [Admiral_CentralSystem01].[dbo_proc1] FOR [Admiral_CentralSystem01].[dbo].[proc1]
GO

declare @Ids  dbo.Ids;
insert into @Ids values (1),(2)
exec [Admiral_CentralSystem01].[dbo_proc1]
    @Ids = @Ids
</code>```

答:
You cannot pass Table variables as parameter in another db.
XML variable with XPath can solve your problem</p>

Body:
On DatabaseA I have User-Defined Data Type which is used as input parameter in a stored procedure. On another database (DatabaseB) I am creating synonym to this procedure and I am creating same data type there.

When I call the sysnonym I am reciving an error "Operand type clash: Ids is incompatible with Ids"

Any suggestion how to resolve this problem?

use DatabaseA
go

CREATE TYPE [dbo].[Ids] AS TABLE(
    [Id] [sql_variant] NULL
)
GO

create procedure dbo.proc1 @Ids [Ids] readonly
as
begin
    select *
    from @Ids;
end

declare @Ids  dbo.Ids;
insert into @Ids values (1),(2)
exec dbo.proc1
    @Ids = @Ids

use DatabaseB

CREATE TYPE [dbo].[Ids] AS TABLE(
    [Id] [sql_variant] NULL
)
go

CREATE SYNONYM [Admiral_CentralSystem01].[dbo_proc1] FOR [Admiral_CentralSystem01].[dbo].[proc1]
GO

declare @Ids  dbo.Ids;
insert into @Ids values (1),(2)
exec [Admiral_CentralSystem01].[dbo_proc1]
    @Ids = @Ids


问:
Unique pointer to vector and polymorphism
I have problem, I want to create unique pointer to vector of Base objects.
I want keep in this vector subclass of Base (SubClass), but i have problem with initialization, because Base class is virtual.

```<code>std::unique_ptr<std::vector<Base>> baseVector = std::make_unique<std::vector<Base>>();
SubClass newObject();
baseVector->push_back(newObject);
</code>```

答:
Short Version: You don't want a dynamic pointer to a collection of Base; you want a collection of dynamic pointer-to-Base.

You seem to be misunderstanding where to place std::unique_ptr in your polymorphic collection. It isn't the collection that needs to be pointers for polymorphism to work; it's the object held within.

For example:

```<code>#include <iostream>
#include <vector>
#include <memory>

struct Base
{
    virtual ~Base() {}

    virtual void foo() const = 0;
};

class DerivedOne : public Base
{
public:
    virtual void foo() const
    {
        std::cout << "DerivedOne\n";
    }
};

class DerivedTwo : public Base
{
public:
    virtual void foo() const
    {
        std::cout << "DerivedTwo\n";
    }
};

int main()
{
    std::vector< std::unique_ptr<Base> > objs;

    objs.emplace_back(std::make_unique<DerivedOne>());
    objs.emplace_back(std::make_unique<DerivedTwo>());

    // via operator[]
    objs[0]->foo();
    objs[1]->foo();

    // via range-for
    for (auto const& p : objs)
        p->foo();

    // via iterators
    for (auto it = objs.begin(); it !=objs.end(); ++it)
        (*it)->foo();
}
</code>```

Output

```<code>DerivedOne
DerivedTwo
DerivedOne
DerivedTwo
DerivedOne
DerivedTwo
</code>```

Whether you want the collection itself to be managed dynamically via a smart pointer is unrelated (and somewhat questionable) to this issue.

Body:
I have problem, I want to create unique pointer to vector of Base objects.
I want keep in this vector subclass of Base (SubClass), but i have problem with initialization, because Base class is virtual.

std::unique_ptr<std::vector<Base>> baseVector = std::make_unique<std::vector<Base>>();
SubClass newObject();
baseVector->push_back(newObject);

Body:
Short Version: You don't want a dynamic pointer to a collection of Base; you want a collection of dynamic pointer-to-Base.

You seem to be misunderstanding where to place std::unique_ptr in your polymorphic collection. It isn't the collection that needs to be pointers for polymorphism to work; it's the object held within.

For example:

#include <iostream>
#include <vector>
#include <memory>

struct Base
{
    virtual ~Base() {}

    virtual void foo() const = 0;
};

class DerivedOne : public Base
{
public:
    virtual void foo() const
    {
        std::cout << "DerivedOne\n";
    }
};

class DerivedTwo : public Base
{
public:
    virtual void foo() const
    {
        std::cout << "DerivedTwo\n";
    }
};

int main()
{
    std::vector< std::unique_ptr<Base> > objs;

    objs.emplace_back(std::make_unique<DerivedOne>());
    objs.emplace_back(std::make_unique<DerivedTwo>());

    // via operator[]
    objs[0]->foo();
    objs[1]->foo();

    // via range-for
    for (auto const& p : objs)
        p->foo();

    // via iterators
    for (auto it = objs.begin(); it !=objs.end(); ++it)
        (*it)->foo();
}

Output

DerivedOne
DerivedTwo
DerivedOne
DerivedTwo
DerivedOne
DerivedTwo

Whether you want the collection itself to be managed dynamically via a smart pointer is unrelated (and somewhat questionable) to this issue.


问:
Java: Algorithm to match a string with unknown characters
I have data stored in a database.
Database has 3 columns:
2 columns containing 6-character numeric strings (matching),
1 column contains the result

User can input 2 strings, I have to create an algorithm to match strings and get the result.

The allowed values are numbers from 0 to 9, *, X and Y

```<code>EXAMPLE:

match1    match2      RESULT

123456    123*56      A
1234X8    123*X8      b
1*4567    1*5435      c
345**7    ******      d
12454X    12X124      E
123X5Y    123Y12      F
</code>```

Represents any possible value
X and Y represent any value but different from themselves

if user insert:

```<code>123456 , 123756 ----> result are A

123498 , 123198 ----> result are B

123456 , 123412 ----> no results......because to obtain "F"....y
                      have to be equals from inputs and 6!=4
</code>```

答:
You can request the results directly with SQL.

The query is somewhat stupid, but it will do the job (inner query extracts the characters, outer query does the matching):

```<code>SELECT
   o.r
FROM (
   SELECT
      SUBSTR(t.match1, 1, 1) l1,
      SUBSTR(t.match1, 2, 1) l2,
      SUBSTR(t.match1, 3, 1) l3,
      SUBSTR(t.match1, 4, 1) l4,
      SUBSTR(t.match1, 5, 1) l5,
      SUBSTR(t.match1, 6, 1) l6,
      SUBSTR(t.match2, 1, 1) r1,
      SUBSTR(t.match2, 2, 1) r2,
      SUBSTR(t.match1, 3, 1) r3,
      SUBSTR(t.match1, 4, 1) r4,
      SUBSTR(t.match1, 5, 1) r5,
      SUBSTR(t.match1, 6, 1) r6,
      SUBSTR(:INPUT1, 1, 1) i11,
      SUBSTR(:INPUT1, 2, 1) i12,
      SUBSTR(:INPUT1, 3, 1) i13,
      SUBSTR(:INPUT1, 4, 1) i14,
      SUBSTR(:INPUT1, 5, 1) i15,
      SUBSTR(:INPUT1, 6, 1) i16,
      SUBSTR(:INPUT2, 1, 1) i21,
      SUBSTR(:INPUT2, 2, 1) i22,
      SUBSTR(:INPUT2, 3, 1) i23,
      SUBSTR(:INPUT2, 4, 1) i24,
      SUBSTR(:INPUT2, 5, 1) i25,
      SUBSTR(:INPUT2, 6, 1) i26,
      result r
   FROM
      table t
) o
WHERE
   (o.l1 = '*' OR o.l1 = o.i11) AND
   (o.l2 = '*' OR o.l2 = o.i12) AND
   (o.l3 = '*' OR o.l3 = o.i13) AND
   (o.l4 = '*' OR o.l4 = o.i14) AND
   (o.l5 = '*' OR o.l5 = o.i15) AND
   (o.l6 = '*' OR o.l6 = o.i16) AND
   (o.r1 = '*' OR o.r1 = o.i21) AND
   (o.r2 = '*' OR o.r2 = o.i22) AND
   (o.r3 = '*' OR o.r3 = o.i23) AND
   (o.r4 = '*' OR o.r4 = o.i24) AND
   (o.r5 = '*' OR o.r5 = o.i25) AND
   (o.r6 = '*' OR o.r6 = o.i26)
</code>```

Body:
I have data stored in a database.
Database has 3 columns:
2 columns containing 6-character numeric strings (matching),
1 column contains the result

User can input 2 strings, I have to create an algorithm to match strings and get the result.

The allowed values are numbers from 0 to 9, *, X and Y

EXAMPLE:

match1    match2      RESULT

123456    123*56      A
1234X8    123*X8      b
1*4567    1*5435      c
345**7    ******      d
12454X    12X124      E
123X5Y    123Y12      F

Represents any possible value
X and Y represent any value but different from themselves

if user insert:

123456 , 123756 ----> result are A

123498 , 123198 ----> result are B

123456 , 123412 ----> no results......because to obtain "F"....y
                      have to be equals from inputs and 6!=4

Body:
You can request the results directly with SQL.

The query is somewhat stupid, but it will do the job (inner query extracts the characters, outer query does the matching):

SELECT
   o.r
FROM (
   SELECT
      SUBSTR(t.match1, 1, 1) l1,
      SUBSTR(t.match1, 2, 1) l2,
      SUBSTR(t.match1, 3, 1) l3,
      SUBSTR(t.match1, 4, 1) l4,
      SUBSTR(t.match1, 5, 1) l5,
      SUBSTR(t.match1, 6, 1) l6,
      SUBSTR(t.match2, 1, 1) r1,
      SUBSTR(t.match2, 2, 1) r2,
      SUBSTR(t.match1, 3, 1) r3,
      SUBSTR(t.match1, 4, 1) r4,
      SUBSTR(t.match1, 5, 1) r5,
      SUBSTR(t.match1, 6, 1) r6,
      SUBSTR(:INPUT1, 1, 1) i11,
      SUBSTR(:INPUT1, 2, 1) i12,
      SUBSTR(:INPUT1, 3, 1) i13,
      SUBSTR(:INPUT1, 4, 1) i14,
      SUBSTR(:INPUT1, 5, 1) i15,
      SUBSTR(:INPUT1, 6, 1) i16,
      SUBSTR(:INPUT2, 1, 1) i21,
      SUBSTR(:INPUT2, 2, 1) i22,
      SUBSTR(:INPUT2, 3, 1) i23,
      SUBSTR(:INPUT2, 4, 1) i24,
      SUBSTR(:INPUT2, 5, 1) i25,
      SUBSTR(:INPUT2, 6, 1) i26,
      result r
   FROM
      table t
) o
WHERE
   (o.l1 = '*' OR o.l1 = o.i11) AND
   (o.l2 = '*' OR o.l2 = o.i12) AND
   (o.l3 = '*' OR o.l3 = o.i13) AND
   (o.l4 = '*' OR o.l4 = o.i14) AND
   (o.l5 = '*' OR o.l5 = o.i15) AND
   (o.l6 = '*' OR o.l6 = o.i16) AND
   (o.r1 = '*' OR o.r1 = o.i21) AND
   (o.r2 = '*' OR o.r2 = o.i22) AND
   (o.r3 = '*' OR o.r3 = o.i23) AND
   (o.r4 = '*' OR o.r4 = o.i24) AND
   (o.r5 = '*' OR o.r5 = o.i25) AND
   (o.r6 = '*' OR o.r6 = o.i26)


问:
Xamarin.Forms view for Wizard
Is there any View on Xamarin.Forms to use like wizard? I must use Xamarin.Forms (not Xamarin.Android). Any suggestions?
I have seen this post but it looks like a bit complicated to me (Xamarin step by step wizard android views)</p>

答:
Update 17.04.2019:

Beginning with Xamarin.Forms 4.0, there is a new CarouselView control! This makes my old answer obsolete.

Old answer (obsolete):

The closest to what you're looking for is a CarouselPage. It holds several pages and you can navigate between them by swiping the screen to the left or the right.

Unfortunately, CarouselPage doesn't contain indicators which show on which page you are right now. You will have to implement this on your own if you need it. Your best choise are Custom Renderers.

Title: Xamarin.Forms view for Wizard


问:
Need to create a package with a specific number in either the protocol header or payload
Unfortunately I'm not too familiar with Wireshark and in our recent homework we are supposed to create a pcap file which includes a specific number. In order to create that pcap file we are supposed to use the search function of Wireshark to find by string in packet bytes and export the result with the specified number in either the protocol header or the payload. How am I supposed to go about this? </p>

答: Well, this was way easier than I thought. All I needed to do was to create a connection to a FTP server, listen to that connection in Wireshark and then transfer a textfile with the number in it/named after it, in plain FTP in ASCII mode. </p>


问:
Not able to edit datasource in Sitecore content & experience editor in Sitecore 8.2
I am having a issue. The datasource editing seems to disabled for a particular role "Regional Content Author" but is enabled for another in sitecore content & experience editor.

I have analyzed that both the roles have read & write ability for the items (for which we want the datasource to be edited) in the Access Viewer.

Can someone suggest what may the issue?

PFB the screenshot:

答:
Hi I figured out what the issue was.

Adding the predefined role Sitecore/Designer gave the necessary permissions to edit Datasource.

I am currently looking how to assign the permissions without assigning any pre-existing roles


问:
Android custom notification sound
I have to change notification sound in my app. The sound is downloaded from the server so it is stored in my app storage. Unfortunately, the sound is not played.

```<code>File folder = new File(context.getFilesDir() + File.separator + "sounds");
File sound = new File(folder, "my-sound.mp3");

Notification notification = new Builder(context)
            .setContentText("test")
            .setContentTitle(context.getText(R.string.app_name))
            .setSmallIcon(R.drawable.notification_icon)
            .setSound(Uri.parse(sound.toString()))
            .build();
</code>```

I also tried to get this Uri differently:

```<code>.setSound(Uri.parse(sound.toString()))
</code>```

Or save it in MediaStore:

```<code>ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, sound.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "My Song title");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mpeg");
values.put(MediaStore.Audio.Media.ARTIST, "Some Artist");
values.put(MediaStore.Audio.Media.IS_RINGTONE, false);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, false);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
Uri uri = MediaStore.Audio.Media.getContentUriForPath(sound.getAbsolutePath());
Uri soundUri = context.getContentResolver().insert(uri, values);
</code>```

Sound Uri path is now equal content://media/external/audio/media/1265 and still its not working.

If I set default sound then it is working correctly. .setSound(RingtoneManager.getDefaultUri(TYPE_NOTIFICATION))

答:
For files stored in Internal Storage you can use FileProvider.

Add provider to AndroidManifest.xml

```<code><provider
    android:authorities="my.file.provider"
    android:name="android.support.v4.content.FileProvider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>
</code>```

then add new xml file with body

```<code><paths>
    <files-path name="sounds" path="sounds/"/>
</paths>
</code>```

before setSound  you have to grandUriPermission to Android System

```<code>Uri soundUri = FileProvider.getUriForFile(context, "my.file.provider", sound);
context.grantUriPermission("com.android.systemui", soundUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);

...

.setSound(soundUri)
</code>```

Title: Android custom notification sound

Body:
I have to change notification sound in my app. The sound is downloaded from the server so it is stored in my app storage. Unfortunately, the sound is not played.

File folder = new File(context.getFilesDir() + File.separator + "sounds");
File sound = new File(folder, "my-sound.mp3");

Notification notification = new Builder(context)
            .setContentText("test")
            .setContentTitle(context.getText(R.string.app_name))
            .setSmallIcon(R.drawable.notification_icon)
            .setSound(Uri.parse(sound.toString()))
            .build();

I also tried to get this Uri differently:

.setSound(Uri.parse(sound.toString()))

Or save it in MediaStore:

ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, sound.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "My Song title");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mpeg");
values.put(MediaStore.Audio.Media.ARTIST, "Some Artist");
values.put(MediaStore.Audio.Media.IS_RINGTONE, false);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, false);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
Uri uri = MediaStore.Audio.Media.getContentUriForPath(sound.getAbsolutePath());
Uri soundUri = context.getContentResolver().insert(uri, values);

Sound Uri path is now equal content://media/external/audio/media/1265 and still its not working.

If I set default sound then it is working correctly. .setSound(RingtoneManager.getDefaultUri(TYPE_NOTIFICATION))

Body:
For files stored in Internal Storage you can use FileProvider.

Add provider to AndroidManifest.xml

<provider
    android:authorities="my.file.provider"
    android:name="android.support.v4.content.FileProvider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

then add new xml file with body

<paths>
    <files-path name="sounds" path="sounds/"/>
</paths>

before setSound  you have to grandUriPermission to Android System

Uri soundUri = FileProvider.getUriForFile(context, "my.file.provider", sound);
context.grantUriPermission("com.android.systemui", soundUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);

...

.setSound(soundUri)


问:
How to Convert Hijri date to Gregorian and Hijri date to Gregorian vice versa using AngularJs
We have two [Hijiri and English ] datepicker text boxes when given date into hijiri it will convert to Gregorian</p>

答:
I would recommand you to use a robust solution tested for that.
I'd use moment.js (http://momentjs.com/docs/#/plugins/hijri/) in pair with a Hijiri plugin (https://github.com/xsoh/moment-hijri )

Once you have those plugin; manipulating a date from one side to other is very simple.
See documentation for more info of the hijri plugin : https://github.com/xsoh/moment-hijri


问:
Toolbar setOnScrollChangeListener() for api level 19
Is there any alternate listener which I can use to get scrolling amount in y axis?

I am using android.support.v7.widget.Toolbar but it doesn't have backward compatibility to API level 19.

答:
You can achieve that using ViewTreeObserver#addOnScrollChangedListener() API:

```
<code>
    toolbar.getViewTreeObserver().addOnScrollChangedListener(
        new ViewTreeObserver.OnScrollChangedListener() {
          @Override public void onScrollChanged() {
              int x = toolbar.getScrollX();
              int y = toolbar.getScrollY();
          }
        });
</code>
```

Body:
You can achieve that using ViewTreeObserver#addOnScrollChangedListener() API:

    toolbar.getViewTreeObserver().addOnScrollChangedListener(
        new ViewTreeObserver.OnScrollChangedListener() {
          @Override public void onScrollChanged() {
              int x = toolbar.getScrollX();
              int y = toolbar.getScrollY();
          }
        });


问:
With clause not working with union
My query result is a union of several queries. I am facing the below error when I use WITH clause within a union. Any ideas why?

```<code>select column1 from TABLE_A
union
with abcd as (select * from TABLE_B)
    select column2 from TABLE_A A, abcd
    where abcd.m_reference = A.m_reference
</code>```

ORA-32034: unsupported use of WITH clause

  32034. 00000 -  "unsupported use of WITH clause"

  *Cause:    Inproper use of WITH clause because one of the following two reasons

             1. nesting of WITH clause within WITH clause not supported yet

             2. For a set query, WITH clause can't be specified for a branch.

             3. WITH clause can't sepecified within parentheses.

  *Action:   correct query and retry

答:
Encapsulate your WITH statement in a dummy select.</p>

```<code>select column1 from TABLE_A
union
select * from (
  with abcd as (select * from TABLE_B)
    select column2 from TABLE_A A, abcd
    where abcd.m_reference = A.m_reference
)
</code>```

Title: With clause not working with union

Body:
My query result is a union of several queries. I am facing the below error when I use WITH clause within a union. Any ideas why?

select column1 from TABLE_A
union
with abcd as (select * from TABLE_B)
    select column2 from TABLE_A A, abcd
    where abcd.m_reference = A.m_reference

ORA-32034: unsupported use of WITH clause

  32034. 00000 -  "unsupported use of WITH clause"

  *Cause:    Inproper use of WITH clause because one of the following two reasons

             1. nesting of WITH clause within WITH clause not supported yet

             2. For a set query, WITH clause can't be specified for a branch.

             3. WITH clause can't sepecified within parentheses.

  *Action:   correct query and retry

Body:
Encapsulate your WITH statement in a dummy select.

select column1 from TABLE_A
union
select * from (
  with abcd as (select * from TABLE_B)
    select column2 from TABLE_A A, abcd
    where abcd.m_reference = A.m_reference
)


问:
Random string generator: Unicode out of range?
I'm trying to make a random string generator in C#, given a length of the string. My first attempt was this:

```<code>public static string RandomString(int characters)
{
    string s = "";
    for (int i = 0; i < characters; i++)
    {
        s += Convert.ToChar((97 + r.Next(26)));
    }
    return s;
}
</code>```

But the frequencies of the letters before k were very low, so I tried to change it by writing my own randomizer:

```<code>public static string RandomString(int characters)
{
    string s = "";
    for (int i = 0; i < characters; i++)
    {
        int randomLetter = 0;

        for (int bit = 0; i < 5; bit++)
        {
            if (r.Next(2) == 0)
                continue;
            randomLetter += 1 << bit;

            if (randomLetter + (1 << (bit + 1)) > 26)
                break;
        }
        s += Convert.ToChar(97 + randomLetter);
    }
    return s;
}
</code>```

But sometimes randomLetter will be greater than 26, sometimes way too great. I can't find the cause of this problem, can you?

答:
If you just want a simple random string, this approach should be much simpler:

```<code>private static Random random = new Random();

public static string GetRandomString(int length)
{
    var chars = new char[length];
    var possibleLetters = "abcdefghijklmnopqrstuvwxyz";

    for (int i = 0; i < length; i++)
    {
        chars[i] = possibleLetters[random.Next(0, possibleLetters.Length - 1)];
    }

    return new string(chars);
}
</code>```

I just made a console test with your code against mine:

```<code>System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
for (int i = 0; i < 1000; i++)
{
   string s = RandomString(10000);
}
sw.Stop();
Console.WriteLine(sw.Elapsed.TotalMilliseconds);
sw.Restart();

for (int i = 0; i < 1000; i++)
{
    string s = GetRandomString(10000);
}

sw.Stop();
Console.WriteLine(sw.Elapsed.TotalMilliseconds);
Console.Read();
</code>```

RESULTS:

```<code>RandomString => 18830,7537
GetRandomString => 321.098
</code>```

As you can see, your implementation is not only worse to read, but also performs much slower.

To justify curiosity, I recreated my method with a StringBuilder instead:

```<code>private static string GetRandomStringSB(int length)
{
   var stringBuilder = new StringBuilder(length);

   var possibleLetters = "abcdefghijklmnopqrstuvwxyz";

   for (int i = 0; i < length; i++)
   {
       stringBuilder.Append(possibleLetters[r.Next(0, possibleLetters.Length - 1)]);
   }

   return stringBuilder.ToString();
}
</code>```

Not surprisingly, the results didn't defer much:

```<code>RandomString (OP) => 13175
GetRandomString (char[]) => 213
GetRandomStringSB (StringBuilder) => 244
</code>```

Body:
I'm trying to make a random string generator in C#, given a length of the string. My first attempt was this:

public static string RandomString(int characters)
{
    string s = "";
    for (int i = 0; i < characters; i++)
    {
        s += Convert.ToChar((97 + r.Next(26)));
    }
    return s;
}

But the frequencies of the letters before k were very low, so I tried to change it by writing my own randomizer:

public static string RandomString(int characters)
{
    string s = "";
    for (int i = 0; i < characters; i++)
    {
        int randomLetter = 0;

        for (int bit = 0; i < 5; bit++)
        {
            if (r.Next(2) == 0)
                continue;
            randomLetter += 1 << bit;

            if (randomLetter + (1 << (bit + 1)) > 26)
                break;
        }
        s += Convert.ToChar(97 + randomLetter);
    }
    return s;
}

But sometimes randomLetter will be greater than 26, sometimes way too great. I can't find the cause of this problem, can you?

Body:
If you just want a simple random string, this approach should be much simpler:

private static Random random = new Random();

public static string GetRandomString(int length)
{
    var chars = new char[length];
    var possibleLetters = "abcdefghijklmnopqrstuvwxyz";

    for (int i = 0; i < length; i++)
    {
        chars[i] = possibleLetters[random.Next(0, possibleLetters.Length - 1)];
    }

    return new string(chars);
}

I just made a console test with your code against mine:

System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
for (int i = 0; i < 1000; i++)
{
   string s = RandomString(10000);
}
sw.Stop();
Console.WriteLine(sw.Elapsed.TotalMilliseconds);
sw.Restart();

for (int i = 0; i < 1000; i++)
{
    string s = GetRandomString(10000);
}

sw.Stop();
Console.WriteLine(sw.Elapsed.TotalMilliseconds);
Console.Read();

RESULTS:

RandomString => 18830,7537
GetRandomString => 321.098

As you can see, your implementation is not only worse to read, but also performs much slower.

To justify curiosity, I recreated my method with a StringBuilder instead:

private static string GetRandomStringSB(int length)
{
   var stringBuilder = new StringBuilder(length);

   var possibleLetters = "abcdefghijklmnopqrstuvwxyz";

   for (int i = 0; i < length; i++)
   {
       stringBuilder.Append(possibleLetters[r.Next(0, possibleLetters.Length - 1)]);
   }

   return stringBuilder.ToString();
}

Not surprisingly, the results didn't defer much:

RandomString (OP) => 13175
GetRandomString (char[]) => 213
GetRandomStringSB (StringBuilder) => 244


问:
PDOException could not find driver
im working with symfony and when i type in console this:

```<code>php app/console doctrine:schema:create
</code>```

i have the next errors

[Doctrine\DBAL\Exception\DriverException]

An exception occured in driver: could not find driver

[Doctrine\DBAL\Driver\PDOException]

could not find driver

[PDOException]

could not find driver

I've been following this  link in order to sort it out

PDOException “could not find driver” in php

this is what i get when i run php -m

```<code>root@asus-K53SD:/opt/lampp/htdocs/symfonycurso# php -m
[PHP Modules]
calendar
Core
ctype
date
dom
exif
fileinfo
filter
ftp
gettext
hash
iconv
json
libxml
openssl
pcntl
pcre
PDO
pdo_sqlite
Phar
posix
readline
Reflection
session
shmop
SimpleXML
sockets
SPL
sqlite3
standard
sysvmsg
sysvsem
sysvshm
tokenizer
wddx
xml
xmlr    eader
xmlwriter
xsl
Zend OPcache
zlib
Zend Modules
Zend OPcache
</code>```

i uncommented this and restart the server

extension=php_pdo_pgsql.dll

this is my parameter.yml

Added database_driver  : pdo_mysql and password removed (before was null) ``` # This file is auto-generated during the composer install
parameters:
database_driver  : pdo_mysql
database_host: 127.0.0.1
database_port:
database_name: blog
database_user: root
database_password:
mailer_transport: smtp
mailer_host: 127.0.0.1
mailer_user:
mailer_password:
secret: ThisTokenIsNotSoSecretChangeIt```

anyone know how can i fix this errors?? can be the problem that im working on PHP7

NOTE: Using lampp on linux

答: Check your php version and versions your modules for php. I had problem after php update from 7.0 to 7.1. PHP migrate should help you. For exmaple http://php.net/manual/en/migration71.php</p>

Title: PDOException could not find driver

Body:
im working with symfony and when i type in console this:

php app/console doctrine:schema:create

i have the next errors

[Doctrine\DBAL\Exception\DriverException]

An exception occured in driver: could not find driver

[Doctrine\DBAL\Driver\PDOException]

could not find driver

[PDOException]

could not find driver

I've been following this  link in order to sort it out

PDOException “could not find driver” in php

this is what i get when i run php -m

root@asus-K53SD:/opt/lampp/htdocs/symfonycurso# php -m
[PHP Modules]
calendar
Core
ctype
date
dom
exif
fileinfo
filter
ftp
gettext
hash
iconv
json
libxml
openssl
pcntl
pcre
PDO
pdo_sqlite
Phar
posix
readline
Reflection
session
shmop
SimpleXML
sockets
SPL
sqlite3
standard
sysvmsg
sysvsem
sysvshm
tokenizer
wddx
xml
xmlr    eader
xmlwriter
xsl
Zend OPcache
zlib
Zend Modules
Zend OPcache

i uncommented this and restart the server

extension=php_pdo_pgsql.dll

this is my parameter.yml

Added database_driver  : pdo_mysql and password removed (before was null)
 # This file is auto-generated during the composer install
parameters:
database_driver  : pdo_mysql
database_host: 127.0.0.1
database_port:
database_name: blog
database_user: root
database_password:
mailer_transport: smtp
mailer_host: 127.0.0.1
mailer_user:
mailer_password:
secret: ThisTokenIsNotSoSecretChangeIt

anyone know how can i fix this errors?? can be the problem that im working on PHP7

NOTE: Using lampp on linux


问:
How exactly works the Angular 2 property binding? What really happens in this example?
I am an absolute beginner with Angular 2 and I have the following doubt relate property binding.

This example works but I have doubt about what exactly happen under the hood.

I have a component view (the servers.component.html file) containing this button:

```<code><button [disabled]="!allowNewServer" class="btn btn-primary">Add Server</button>
</code>```

The related component is:

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

@Component({
  selector: 'app-servers',
  templateUrl: './servers.component.html',
  styleUrls: ['./servers.component.css']
})
export class ServersComponent implements OnInit {
  allowNewServer = false;

  constructor() {
    setTimeout(() => {
      this.allowNewServer = true;
    }, 8000);
  }

  ngOnInit() {
  }

}
</code>```

As you can see at the beginning the allowNewServer value is false, after 8 seconds it is setted to true by a function declared in the constructor.

On my button is setted this disabled attribute:

```<code> [disabled]="!allowNewServer"
</code>```

So at the beginning the button is disabled and after 8 seconds it will enabled.

Mu doubts are:

1) What exactly means the [...] Angular syntax?

2) I expected that was rendered something like disabled=true (at the beginning) and after 8 seconds something like disabled=dalse, but after 8 seconds simply the disable attribute is deleted. So I think that I am not understending what the [...] syntax mean.

答:
The [...] syntax is for property binding. More information here.

I recommend you to follow the Tour of Heroes tutorial, made by Google. It explains the basics about Angular (v2,v4) and help you to create your first cool application. You can find it here.

Body:
I am an absolute beginner with Angular 2 and I have the following doubt relate property binding.

This example works but I have doubt about what exactly happen under the hood.

I have a component view (the servers.component.html file) containing this button:

<button [disabled]="!allowNewServer" class="btn btn-primary">Add Server</button>

The related component is:

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

@Component({
  selector: 'app-servers',
  templateUrl: './servers.component.html',
  styleUrls: ['./servers.component.css']
})
export class ServersComponent implements OnInit {
  allowNewServer = false;

  constructor() {
    setTimeout(() => {
      this.allowNewServer = true;
    }, 8000);
  }

  ngOnInit() {
  }

}

As you can see at the beginning the allowNewServer value is false, after 8 seconds it is setted to true by a function declared in the constructor.

On my button is setted this disabled attribute:

 [disabled]="!allowNewServer"

So at the beginning the button is disabled and after 8 seconds it will enabled.

Mu doubts are:

1) What exactly means the [...] Angular syntax?

2) I expected that was rendered something like disabled=true (at the beginning) and after 8 seconds something like disabled=dalse, but after 8 seconds simply the disable attribute is deleted. So I think that I am not understending what the [...] syntax mean.


问:
dynamically change the json property name and serialize
i want to change the json property name dynamically and serialize the object.

here is my json for two different entities

For customer

```<code>{
  "userName": "66666",
  "password": "test1234",
  "customersList": [
    {
      "address": "Test Stree2",
      "customerNumber": "US01-000281",
      "city": ""

    }
  ]
}
</code>```

For contact

```<code>{
  "userName": "66666",
  "password": "test1234",
  "contactList": [
    {
      "address": "Test stree1",
      "contactNumber": "US01-000281",
      "city": ""

    }
  ]
}
</code>```

and the model that is holding this data is as follows

```<code>public class URequest<T>
    {

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string userName { get; set; }

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string password { get; set; }

       [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public IList<T> requestList { get; set; }

    }
</code>```

in above code requestList could contain list of contacts or customer but while sending i want to change the requestList json property name to respective entity name i.e. for customer it will be customerList and for contact it will be contactList after serializing.

答:
You can create a custom JsonConverter.

Using custom JsonConverter in order to alter the serialization of the portion of an object

Example

```<code>public class Customer
{
    public string Name { get; set; }
}

public class Client
{
    public string Name { get; set; }
}

public class URequest<T>
{

    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public string userName { get; set; }

    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public string password { get; set; }

    [JsonIgnore]
    public IList<T> requestList { get; set; }

}

public class URequestConverter<T> : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(URequest<T>));
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var objectType = value.GetType().GetGenericArguments()[0];
        URequest<T> typedValue = (URequest<T>) value;

        JObject containerObj = JObject.FromObject(value);

        containerObj.Add($"{objectType.Name.ToLower()}List", JToken.FromObject(typedValue.requestList));
        containerObj.WriteTo(writer);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}
</code>```

You can use it like this

```<code>    [TestMethod]
    public void TestMethod1()
    {
        URequest<Customer> request = new URequest<Customer>();
        request.password = "test";
        request.userName = "user";
        request.requestList = new List<Customer>();

        request.requestList.Add(new Customer() { Name = "customer" });

        JsonSerializerSettings settings = new JsonSerializerSettings();
        settings.Formatting = Formatting.Indented;
        settings.Converters.Add(new URequestConverter<Customer>());

        Console.WriteLine(JsonConvert.SerializeObject(request, settings));
    }
</code>```

Body:
i want to change the json property name dynamically and serialize the object.

here is my json for two different entities

For customer

{
  "userName": "66666",
  "password": "test1234",
  "customersList": [
    {
      "address": "Test Stree2",
      "customerNumber": "US01-000281",
      "city": ""

    }
  ]
}

For contact

{
  "userName": "66666",
  "password": "test1234",
  "contactList": [
    {
      "address": "Test stree1",
      "contactNumber": "US01-000281",
      "city": ""

    }
  ]
}

and the model that is holding this data is as follows

public class URequest<T>
    {

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string userName { get; set; }

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string password { get; set; }

       [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public IList<T> requestList { get; set; }

    }

in above code requestList could contain list of contacts or customer but while sending i want to change the requestList json property name to respective entity name i.e. for customer it will be customerList and for contact it will be contactList after serializing.

Body:
You can create a custom JsonConverter.

Using custom JsonConverter in order to alter the serialization of the portion of an object

Example

public class Customer
{
    public string Name { get; set; }
}

public class Client
{
    public string Name { get; set; }
}

public class URequest<T>
{

    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public string userName { get; set; }

    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public string password { get; set; }

    [JsonIgnore]
    public IList<T> requestList { get; set; }

}

public class URequestConverter<T> : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(URequest<T>));
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var objectType = value.GetType().GetGenericArguments()[0];
        URequest<T> typedValue = (URequest<T>) value;

        JObject containerObj = JObject.FromObject(value);

        containerObj.Add($"{objectType.Name.ToLower()}List", JToken.FromObject(typedValue.requestList));
        containerObj.WriteTo(writer);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

You can use it like this

    [TestMethod]
    public void TestMethod1()
    {
        URequest<Customer> request = new URequest<Customer>();
        request.password = "test";
        request.userName = "user";
        request.requestList = new List<Customer>();

        request.requestList.Add(new Customer() { Name = "customer" });

        JsonSerializerSettings settings = new JsonSerializerSettings();
        settings.Formatting = Formatting.Indented;
        settings.Converters.Add(new URequestConverter<Customer>());

        Console.WriteLine(JsonConvert.SerializeObject(request, settings));
    }


问:
ListBox only updates the first time its called? c#
I have a ListBox studentListBox in Form1 and it displays the members of studentList which is populated by Form2. There is a class Student which contains a few different properties regarding each student.

I also have a function BindData() in Form1 which sets studentListBox data source to studentList. It also sets studentListBox display member to Name which is a property in a class Student.

Form1

```<code>public void BindData()
        {
            if (studentListHome != null)
            {
                studentListBox.DataSource = studentListHome;
                foreach(Student s in studentListHome)
                {
                    studentListBox.DisplayMember = "Name";
                }

            }
        }
</code>```

BindData is called on Form1_Load and it can also be called by clicking the refresh button.

Form2 creates each student and adds it to studentList inside of Form1 It does this when the submit button is clicked

Form2

```<code>private void submitButton_Click(object sender, EventArgs e)
        {
            if (comparator(nameInput) &
               comparator(idInput) &
               comparator(bdayInput)){
                variable_assignment();
                var tempStudent = StudentCreation();
                if(tempStudent != null)
                {
                    studentListForm2.Add(tempStudent);
                }
                testList.Add(tim);
                testList.Add(john);
                testList.Add(tempStudent);

                foreach(Student s in testList)
                {
                    homeForm.StudentListHome.Add(s);
                }
                homeForm.BindData();
            }
        }
</code>```

comparator() is a function that makes sure the user input fields aren't empty.
variable_assignment() assigns the user input to the related variables.
StudentCreation() is a function that instatiates the Student

So like I mentioned in the title, the ListBox only updates the first time its called, after that, it remains exactly the same. I know that the Students are being added to the List<Student> that ListBox is bound to because I was Console.WriteLineing them and I could see the new Student being added to the studentList every time the submit button was clicked.

How do I fix this ?

答:
A few small things

```<code>if (studentListHome != null)
        {
            studentListBox.DataSource = studentListHome;
            foreach(Student s in studentListHome)
            {
                studentListBox.DisplayMember = "Name";
            }

        }
</code>```

the foreach is redundant since you need to set only once for the list box and not each item in the list box.

```<code>    if (studentListHome != null)
    {
        studentListBox.DataSource = studentListHome;
        studentListBox.DisplayMember = "Name";
    }
</code>```

Next to answer your question you must use a BindingList rather than any other type of collection and then for the comparison and sorting you can implement IComparable and INotifiyPropertyChanged on the Student class itself.

And then you do not to rebind again and just modify the BindingList instance to manipulate the list and the listbox would behave in sync with the list.

Body:
I have a ListBox studentListBox in Form1 and it displays the members of studentList which is populated by Form2. There is a class Student which contains a few different properties regarding each student.

I also have a function BindData() in Form1 which sets studentListBox data source to studentList. It also sets studentListBox display member to Name which is a property in a class Student.

Form1

public void BindData()
        {
            if (studentListHome != null)
            {
                studentListBox.DataSource = studentListHome;
                foreach(Student s in studentListHome)
                {
                    studentListBox.DisplayMember = "Name";
                }

            }
        }

BindData is called on Form1_Load and it can also be called by clicking the refresh button.

Form2 creates each student and adds it to studentList inside of Form1 It does this when the submit button is clicked

Form2

private void submitButton_Click(object sender, EventArgs e)
        {
            if (comparator(nameInput) &
               comparator(idInput) &
               comparator(bdayInput)){
                variable_assignment();
                var tempStudent = StudentCreation();
                if(tempStudent != null)
                {
                    studentListForm2.Add(tempStudent);
                }
                testList.Add(tim);
                testList.Add(john);
                testList.Add(tempStudent);

                foreach(Student s in testList)
                {
                    homeForm.StudentListHome.Add(s);
                }
                homeForm.BindData();
            }
        }

comparator() is a function that makes sure the user input fields aren't empty.
variable_assignment() assigns the user input to the related variables.
StudentCreation() is a function that instatiates the Student

So like I mentioned in the title, the ListBox only updates the first time its called, after that, it remains exactly the same. I know that the Students are being added to the List<Student> that ListBox is bound to because I was Console.WriteLineing them and I could see the new Student being added to the studentList every time the submit button was clicked.

How do I fix this ?

Body:
A few small things

if (studentListHome != null)
        {
            studentListBox.DataSource = studentListHome;
            foreach(Student s in studentListHome)
            {
                studentListBox.DisplayMember = "Name";
            }

        }

the foreach is redundant since you need to set only once for the list box and not each item in the list box.

    if (studentListHome != null)
    {
        studentListBox.DataSource = studentListHome;
        studentListBox.DisplayMember = "Name";
    }

Next to answer your question you must use a BindingList rather than any other type of collection and then for the comparison and sorting you can implement IComparable and INotifiyPropertyChanged on the Student class itself.

And then you do not to rebind again and just modify the BindingList instance to manipulate the list and the listbox would behave in sync with the list.


问:
Android Vector Drawables in Selector for CheckBox (Sdk < 21)
So, i've been adding vector resources to my project. And... they work fine on pre-Lollipop (sdk < 21) devices. I didn't add gradle:vectorDrawables.useSupportLibrary=true flag to build.gradle. Didn't add AppComaptDelegate.setCompatVectorFromResourcesEnabled(true) to java. Didn't use compat widget in layout. The related xml looks like this:

```<code><CheckBox
      ...
      android:background="@drawable/round_checkbox"
      android:button="@null"/>
</code>```

round_checkbox.xml:

```<code><selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:drawable="@drawable/round_check_green"/>
    <item android:drawable="@drawable/round_check_gray"/>
</selector>
</code>```

Relevant project info:

```<code>minSdkVersion 19
targetSdkVersion 24
compileSdkVersion 25
buildToolsVersion '25.0.2'
gradle Version 3.3
dependancies:
... [way too many, we are multidexing here]. General:
compile "com.android.support:appcompat-v7:25.3.1"
</code>```

Though, been pretty much happy, with my app working fine, I'm confused with why it doesn't crash.
This is a big project, so testing on user is not an option. Any thoughts/suggestions/info will be much appreciated.

答: After some empiric testing, I can confirm vsatkh's assumption, AS does generate raster graphics (in build/intermediates) from vector drawables, if according gradle flag is absent. So, to use vector drawable one need to follow this tutorial, otherwise it'll be simple raster autogeneration.</p>

Body:
So, i've been adding vector resources to my project. And... they work fine on pre-Lollipop (sdk < 21) devices. I didn't add gradle:vectorDrawables.useSupportLibrary=true flag to build.gradle. Didn't add AppComaptDelegate.setCompatVectorFromResourcesEnabled(true) to java. Didn't use compat widget in layout. The related xml looks like this:

<CheckBox
      ...
      android:background="@drawable/round_checkbox"
      android:button="@null"/>

round_checkbox.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:drawable="@drawable/round_check_green"/>
    <item android:drawable="@drawable/round_check_gray"/>
</selector>

Relevant project info:

minSdkVersion 19
targetSdkVersion 24
compileSdkVersion 25
buildToolsVersion '25.0.2'
gradle Version 3.3
dependancies:
... [way too many, we are multidexing here]. General:
compile "com.android.support:appcompat-v7:25.3.1"

Though, been pretty much happy, with my app working fine, I'm confused with why it doesn't crash.
This is a big project, so testing on user is not an option. Any thoughts/suggestions/info will be much appreciated.


问:
create a file on the project directory java
I want to create a file in the project directory so i tried this code and i created a temp directory on the project directory

```<code>try {

    File file = new File("temp/"+soCourrier.getHeaders().get("filename").get(0));
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(sCourrier.getBody());
    model.addAttribute("path", file.getAbsoluteFile());

} catch (IOException e) {
    e.printStackTrace();
}
</code>```

But this gives me an error

```<code>java.io.IOException: Le chemin d’accès spécifié est introuvable
    at java.io.WinNTFileSystem.createFileExclusively(Native Method)
    at java.io.File.createNewFile(Unknown Source)
    at controllers.UserController.showCourrierDetail(UserController.java:77)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
</code>```

can any one help me ?

答:
It seems like you are using / on a Windows machine, but in Windows a folder gets marked by a \.
Use the constant File.seperator to get the right seperator on every machine.

Body:
I want to create a file in the project directory so i tried this code and i created a temp directory on the project directory

try {

    File file = new File("temp/"+soCourrier.getHeaders().get("filename").get(0));
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(sCourrier.getBody());
    model.addAttribute("path", file.getAbsoluteFile());

} catch (IOException e) {
    e.printStackTrace();
}

But this gives me an error

java.io.IOException: Le chemin d’accès spécifié est introuvable
    at java.io.WinNTFileSystem.createFileExclusively(Native Method)
    at java.io.File.createNewFile(Unknown Source)
    at controllers.UserController.showCourrierDetail(UserController.java:77)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)

can any one help me ?


问:
How can I fix Grails error: "No domain class found for name PrivacyOptions. Please try again and enter a valid domain class name"
I'm just getting started with Groovy/Grails.

I added a new domain controller to my project, and generate-controller doesn't like it.

There are other indications something's wrong: If I run the app no table is actually created in the database for this.

I've reduced the DomainController to one String field and no constraints, just to make sure there wasn't something wrong with my specification. I also tried renaming it, just in case there was something about the original name (Privacy) that conflicted with something.

I'm sure I have the correct name, and that the file is called PrivacyOptions.groovy and inside the class is also called PrivacyOptions.

Here's the error:

```<code>Running script /opt/local/grails/scripts/GenerateController.groovy
Environment set to development
Domain class not found in grails-app/domain, trying hibernate mapped classes...
No domain class found for name PrivacyOptions. Please try again and enter a valid domain class name
</code>```

答:
Yep... worked for me too. I just prefixed the package name to the class I was trying to generate-all for and it worked. So ...

generate-all racetrack.User

Bit of a pants bug really since all other grails commands do not require a package name to be included :-))

ContentLicense: CC BY-SA 2.5

Body:
I'm just getting started with Groovy/Grails.

I added a new domain controller to my project, and generate-controller doesn't like it.

There are other indications something's wrong: If I run the app no table is actually created in the database for this.

I've reduced the DomainController to one String field and no constraints, just to make sure there wasn't something wrong with my specification. I also tried renaming it, just in case there was something about the original name (Privacy) that conflicted with something.

I'm sure I have the correct name, and that the file is called PrivacyOptions.groovy and inside the class is also called PrivacyOptions.

Here's the error:

Running script /opt/local/grails/scripts/GenerateController.groovy
Environment set to development
Domain class not found in grails-app/domain, trying hibernate mapped classes...
No domain class found for name PrivacyOptions. Please try again and enter a valid domain class name


问:
Remove object in array using filter and splice which one is best approach in JavaScript?
Hi I delete an object in an array using two approaches:-
splice and filter.

splice code here:-

```<code>(this.myArray).splice((this.myArray).indexOf(myobject), 1);
</code>```

filter code here:-

```<code>(this.myArray).filter(obj => obj !== myobject);
</code>```

Please tell us differences between both and which one is the best approach?

答:
I think that the main difference here is:

splice - lets you remove an element from this particular array

filter - won't touch the input array and will create and return new filttered array

angular has nothing to do here and when it comes to speed, splice will win

Body:
Hi I delete an object in an array using two approaches:-
splice and filter.

splice code here:-

(this.myArray).splice((this.myArray).indexOf(myobject), 1);

filter code here:-

(this.myArray).filter(obj => obj !== myobject);

Please tell us differences between both and which one is the best approach?


问:
How to upload images using wordpress REST api in python?
I think I've got this 90% working, but it ends up 'uploading' a blank transparent image. I get a 201 response after the upload. I think that's probably a proxy for when WP finds a missing image. I'm unsure if i'm passing the image incorrectly (ie it doesn't leave my computer) or if I'm not tagging it properly to WP's liking.

```<code>from base64 import b64encode
import json
import requests

def imgUploadREST(imgPath):
    url = 'https://www.XXXXXXXXXX.com/wp-json/wp/v2/media'
    auth = b64encode('{}:{}'.format('USERNAME','PASS'))
    payload = {
        'type': 'image/jpeg',  # mimetype
        'title': 'title',
        "Content":"content",
        "excerpt":"Excerpt",
    }
    headers = {
        'post_content':'post_content',
        'Content':'content',
        'Content-Disposition' : 'attachment; filename=image_20170510.jpg',
        'Authorization': 'Basic {}'.format(auth),
    }
    with open(imgPath, "rb") as image_file:
        files = {'field_name': image_file}
        r = requests.post(url, files=files, headers=headers, data=payload)
        print r
        response = json.loads(r.content)
        print response
    return response
</code>```

I've seen a fair number of answers in php or node.js, but I'm having trouble understanding the syntax in python. Thank you for any help!

答:
I've figured it out!

With this function I'm able to upload images via the WP REST api to my site (Photo Gear Hunter.) The function returns the ID of the image. You can then pass that id to a new post call and make it the featured image, or do whatever you wish with it.

```<code>def restImgUL(imgPath):
    url='http://xxxxxxxxxxxx.com/wp-json/wp/v2/media'
    data = open(imgPath, 'rb').read()
    fileName = os.path.basename(imgPath)
    res = requests.post(url='http://xxxxxxxxxxxxx.com/wp-json/wp/v2/media',
                        data=data,
                        headers={ 'Content-Type': 'image/jpg','Content-Disposition' : 'attachment; filename=%s'% fileName},
                        auth=('authname', 'authpass'))
    # pp = pprint.PrettyPrinter(indent=4) ## print it pretty.
    # pp.pprint(res.json()) #this is nice when you need it
    newDict=res.json()
    newID= newDict.get('id')
    link = newDict.get('guid').get("rendered")
    print newID, link
    return (newID, link)
</code>```

Body:
I think I've got this 90% working, but it ends up 'uploading' a blank transparent image. I get a 201 response after the upload. I think that's probably a proxy for when WP finds a missing image. I'm unsure if i'm passing the image incorrectly (ie it doesn't leave my computer) or if I'm not tagging it properly to WP's liking.

from base64 import b64encode
import json
import requests

def imgUploadREST(imgPath):
    url = 'https://www.XXXXXXXXXX.com/wp-json/wp/v2/media'
    auth = b64encode('{}:{}'.format('USERNAME','PASS'))
    payload = {
        'type': 'image/jpeg',  # mimetype
        'title': 'title',
        "Content":"content",
        "excerpt":"Excerpt",
    }
    headers = {
        'post_content':'post_content',
        'Content':'content',
        'Content-Disposition' : 'attachment; filename=image_20170510.jpg',
        'Authorization': 'Basic {}'.format(auth),
    }
    with open(imgPath, "rb") as image_file:
        files = {'field_name': image_file}
        r = requests.post(url, files=files, headers=headers, data=payload)
        print r
        response = json.loads(r.content)
        print response
    return response

I've seen a fair number of answers in php or node.js, but I'm having trouble understanding the syntax in python. Thank you for any help!

Body:
I've figured it out!

With this function I'm able to upload images via the WP REST api to my site (Photo Gear Hunter.) The function returns the ID of the image. You can then pass that id to a new post call and make it the featured image, or do whatever you wish with it.

def restImgUL(imgPath):
    url='http://xxxxxxxxxxxx.com/wp-json/wp/v2/media'
    data = open(imgPath, 'rb').read()
    fileName = os.path.basename(imgPath)
    res = requests.post(url='http://xxxxxxxxxxxxx.com/wp-json/wp/v2/media',
                        data=data,
                        headers={ 'Content-Type': 'image/jpg','Content-Disposition' : 'attachment; filename=%s'% fileName},
                        auth=('authname', 'authpass'))
    # pp = pprint.PrettyPrinter(indent=4) ## print it pretty.
    # pp.pprint(res.json()) #this is nice when you need it
    newDict=res.json()
    newID= newDict.get('id')
    link = newDict.get('guid').get("rendered")
    print newID, link
    return (newID, link)


问:
How to change uinavigationbar back button text
I am currently trying to change the back button text of a subview that is loaded of a tablecell touch. However even with the way I am trying to implement it it still shows the parents title in the back button.

I am trying to load a new value into the back button inside viewdidload method like so

```<code>UIBarButtonItem *myBarButtonItem = [[UIBarButtonItem alloc] init];
myBarButtonItem.title = @"Back";
self.navigationItem.backBarButtonItem = myBarButtonItem;
[myBarButtonItem release];
</code>```

however its not working.

答:
My suggestion was to add a separate Label to parents Page title Bar.
Worked fine for me.  </p>

```<code>let titleLabel = UILabel(frame: CGRect(x: (view.frame.width * (3/8)), y: 0, width: (view.frame.width * 0.25 ), height:30))
        titleLabel.text = "Title"
        titleLabel.textAlignment = .center
        titleLabel.textColor = UIColor.white
        titleLabel.font = UIFont.systemFont(ofSize: 20)
        navigationItem.titleView = titleLabel
</code>```

Body:
I am currently trying to change the back button text of a subview that is loaded of a tablecell touch. However even with the way I am trying to implement it it still shows the parents title in the back button.

I am trying to load a new value into the back button inside viewdidload method like so

UIBarButtonItem *myBarButtonItem = [[UIBarButtonItem alloc] init];
myBarButtonItem.title = @"Back";
self.navigationItem.backBarButtonItem = myBarButtonItem;
[myBarButtonItem release];

however its not working.

Body:
My suggestion was to add a separate Label to parents Page title Bar.
Worked fine for me.

let titleLabel = UILabel(frame: CGRect(x: (view.frame.width * (3/8)), y: 0, width: (view.frame.width * 0.25 ), height:30))
        titleLabel.text = "Title"
        titleLabel.textAlignment = .center
        titleLabel.textColor = UIColor.white
        titleLabel.font = UIFont.systemFont(ofSize: 20)
        navigationItem.titleView = titleLabel


问:
Powershell convertto-json without labels
how to correctly convert a Powershell array of object properties to a json array of values, that is without the objects property lables in the array.

for example:
I want to make 2 json arrays for chart.js
I will group some process objects:

```<code>$processgroup = get-process | group -property name

$processgroup.gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

$chartlabels = $processgroup.name | convertto-json

$chartlabels

$chartlabels
[
    "ApMsgFwd",
    "ApntEx",
    "Apoint",
    "ApplicationFrameHost",
    "armsvc",
    "BtwRSupportService",
    "chrome",
    "com.docker.proxy",
    "com.docker.service",
    "concentr",
    "conhost",
    "csrss",
    "dllhost",
    "Docker for Windows",
    "dockerd",
    "dwm",
    "Everything",
    "EXCEL",
    "explorer",
    "fontdrvhost",
    "GROOVE",
    "hidfind",
    "HidMonitorSvc",
    "Idle",
    "iexplore",
    "IpOverUsbSvc",
    "jucheck",
    "jusched",
    "LicensingUI",
    "lsass",
    "mDNSResponder",
    "Memory Compression",
    "mqsvc",
    "MSASCuiL",
    "MsMpEng",
    "MSOIDSVC",
    "MSOIDSVCM",
    "MySQLNotifier",
    "NisSrv",
    "notepad",
    "notepad++",
    "nvSCPAPISvr",
    "nvvsvc",
    "nvwmi64",
    "nvxdsync",
    "OfficeClickToRun",
    "OneDrive",
    "OUTLOOK",
    "powershell",
    "powershell_ise",
    "prevhost",
    "Receiver",
    "redirector",
    "rundll32",
    "RuntimeBroker",
    "SearchIndexer",
    "SearchUI",
    "Secure System",
    "SecurityHealthService",
    "SelfServicePlugin",
    "services",
    "SettingSyncHost",
    "ShellExperienceHost",
    "sihost",
    "SkypeHost",
    "smss",
    "SMSvcHost",
    "spiceworks",
    "spiceworks-httpd",
    "spoolsv",
    "SppExtComObj",
    "sppsvc",
    "sqlwriter",
    "svchost",
    "System",
    "SystemSettings",
    "taskhostw",
    "TSVNCache",
    "vmcompute",
    "vmms",
    "vmnat",
    "vmnetdhcp",
    "vmware-authd",
    "vmware-tray",
    "vmware-usbarbitrator64",
    "wfcrun32",
    "wininit",
    "winlogon",
    "WINWORD",
    "WmiPrvSE",
    "WUDFHost"
]

#this is the array I want for charts labels, now for the chart value array

$chartvalues = $processgroup | select count | convertto-json

$chartvalues
[
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  30
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  5
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  4
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  30
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  75
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    }
]
</code>```

how do I omit the "Count" label so PowerShell creates a single json array of the values only, as in the process name array.

I have tried

```<code>$chartvalues = $processgroup.count
</code>```

results in the count of the number of groups

and I have tried

```<code>$chartvalues = $ processgroup | select count -expandproperty count | convertto-json
</code>```

with the same result as above example

答:
You want a list, rather than object with key/value pair, so this should work*:

```<code> $groups| foreach-object {$_.count}|convertto-json
</code>```

When you do select after the pipeline it creates an object, thus pushes the object property name as well as the value as key/value pair into the json conversion process.
i.e. If you have used select for name property, you would get the name/value pair in the json too...

```<code> $groups| select-object name| convertto-json
</code>```

*may be better solutions out there... but itworks..

Body:
how to correctly convert a Powershell array of object properties to a json array of values, that is without the objects property lables in the array.

for example:
I want to make 2 json arrays for chart.js
I will group some process objects:

$processgroup = get-process | group -property name

$processgroup.gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

$chartlabels = $processgroup.name | convertto-json

$chartlabels

$chartlabels
[
    "ApMsgFwd",
    "ApntEx",
    "Apoint",
    "ApplicationFrameHost",
    "armsvc",
    "BtwRSupportService",
    "chrome",
    "com.docker.proxy",
    "com.docker.service",
    "concentr",
    "conhost",
    "csrss",
    "dllhost",
    "Docker for Windows",
    "dockerd",
    "dwm",
    "Everything",
    "EXCEL",
    "explorer",
    "fontdrvhost",
    "GROOVE",
    "hidfind",
    "HidMonitorSvc",
    "Idle",
    "iexplore",
    "IpOverUsbSvc",
    "jucheck",
    "jusched",
    "LicensingUI",
    "lsass",
    "mDNSResponder",
    "Memory Compression",
    "mqsvc",
    "MSASCuiL",
    "MsMpEng",
    "MSOIDSVC",
    "MSOIDSVCM",
    "MySQLNotifier",
    "NisSrv",
    "notepad",
    "notepad++",
    "nvSCPAPISvr",
    "nvvsvc",
    "nvwmi64",
    "nvxdsync",
    "OfficeClickToRun",
    "OneDrive",
    "OUTLOOK",
    "powershell",
    "powershell_ise",
    "prevhost",
    "Receiver",
    "redirector",
    "rundll32",
    "RuntimeBroker",
    "SearchIndexer",
    "SearchUI",
    "Secure System",
    "SecurityHealthService",
    "SelfServicePlugin",
    "services",
    "SettingSyncHost",
    "ShellExperienceHost",
    "sihost",
    "SkypeHost",
    "smss",
    "SMSvcHost",
    "spiceworks",
    "spiceworks-httpd",
    "spoolsv",
    "SppExtComObj",
    "sppsvc",
    "sqlwriter",
    "svchost",
    "System",
    "SystemSettings",
    "taskhostw",
    "TSVNCache",
    "vmcompute",
    "vmms",
    "vmnat",
    "vmnetdhcp",
    "vmware-authd",
    "vmware-tray",
    "vmware-usbarbitrator64",
    "wfcrun32",
    "wininit",
    "winlogon",
    "WINWORD",
    "WmiPrvSE",
    "WUDFHost"
]

#this is the array I want for charts labels, now for the chart value array

$chartvalues = $processgroup | select count | convertto-json

$chartvalues
[
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  30
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  5
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  4
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  30
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  75
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    }
]

how do I omit the "Count" label so PowerShell creates a single json array of the values only, as in the process name array.

I have tried

$chartvalues = $processgroup.count

results in the count of the number of groups

and I have tried

$chartvalues = $ processgroup | select count -expandproperty count | convertto-json

with the same result as above example

Body:
You want a list, rather than object with key/value pair, so this should work*:

 $groups| foreach-object {$_.count}|convertto-json

When you do select after the pipeline it creates an object, thus pushes the object property name as well as the value as key/value pair into the json conversion process.
i.e. If you have used select for name property, you would get the name/value pair in the json too...

 $groups| select-object name| convertto-json

*may be better solutions out there... but itworks..


问:
Order of evaluation
I wonder if construction like this (initialization list) has well defined EO (evaluation order):

```<code>struct MemoryManager
    {
        Pair* firstPair_;//<-beg
        Pair* currentPair_;
        Pair* lastPair_;//<-end

        MemoryManager():lastPair_(currentPair_ = firstPair_ = nullptr)
            {/*e.b.*/}
};
</code>```

If yes I personally would prefer this way to the more conventional:

```<code>    MemoryManager():firstPair_(nullptr),
                    currentPair_(nullptr),
                    lastPair_(nullptr)
    {/*e.b*/}
</code>```

答:
For this specific example, the initialization order for members is irrelevant.  The following constructor would have the same behaviour as the one in the question:

```<code>MemoryManager():firstPair_(lastPair_ = currentPair_ = nullptr)
{/*e.b.*/}
</code>```

This is because the members are POD and so are not default initialized by the constructor at all (12.6.2/4 C++ '03):

If a given nonstatic data member or base class is not named by a mem-initializer-id (including the case where there is no mem-initializer-list because the constructor has no ctor-initializer), then

If the entity is a nonstatic data member of (possibly cv-qualified) class type (or array thereof) or a base class, and the entity class is a non-POD class, the entity is default-initialized (8.5). If the entity is a non- static data member of a const-qualified type, the entity class shall have a user-declared default constructor.

Otherwise, the entity is not initialized. If the entity is of const-qualified type or reference type, or of a (possibly cv-qualified) POD class type (or array thereof) containing (directly or indirectly) a member of a const-qualified type, the program is ill-formed.

For the raw pointer members above, the 'otherwise' bullet applies.

Now, even if the members did have class type, say:

```<code>class MbrType {
public:
  MbrType();
  MbrType(int *);
  MbrType(MbrType const &);
  MbrType & operator=(MbrType const &);
};
</code>```

Then, the constructor as you've written it would result in the members having the values that you expect, but a non optimizing compiler would be allowed to implement your constructor as:

```<code>MemoryManager()
: firstPair_ ()  // implicit call to default constructor
, currentPair_ () // implicit call to default constructor
, lastPair_(currentPair_.operator=(firstPair_.operator=(MbrType (nullptr))))
{/*e.b.*/}
</code>```

Resulting in 6 calls rather than 3.

Title: Order of evaluation

Body:
I wonder if construction like this (initialization list) has well defined EO (evaluation order):

struct MemoryManager
    {
        Pair* firstPair_;//<-beg
        Pair* currentPair_;
        Pair* lastPair_;//<-end

        MemoryManager():lastPair_(currentPair_ = firstPair_ = nullptr)
            {/*e.b.*/}
};

If yes I personally would prefer this way to the more conventional:

    MemoryManager():firstPair_(nullptr),
                    currentPair_(nullptr),
                    lastPair_(nullptr)
    {/*e.b*/}

Body:
For this specific example, the initialization order for members is irrelevant.  The following constructor would have the same behaviour as the one in the question:

MemoryManager():firstPair_(lastPair_ = currentPair_ = nullptr)
{/*e.b.*/}

This is because the members are POD and so are not default initialized by the constructor at all (12.6.2/4 C++ '03):

If a given nonstatic data member or base class is not named by a mem-initializer-id (including the case where there is no mem-initializer-list because the constructor has no ctor-initializer), then

If the entity is a nonstatic data member of (possibly cv-qualified) class type (or array thereof) or a base class, and the entity class is a non-POD class, the entity is default-initialized (8.5). If the entity is a non- static data member of a const-qualified type, the entity class shall have a user-declared default constructor.

Otherwise, the entity is not initialized. If the entity is of const-qualified type or reference type, or of a (possibly cv-qualified) POD class type (or array thereof) containing (directly or indirectly) a member of a const-qualified type, the program is ill-formed.

For the raw pointer members above, the 'otherwise' bullet applies.

Now, even if the members did have class type, say:

class MbrType {
public:
  MbrType();
  MbrType(int *);
  MbrType(MbrType const &);
  MbrType & operator=(MbrType const &);
};

Then, the constructor as you've written it would result in the members having the values that you expect, but a non optimizing compiler would be allowed to implement your constructor as:

MemoryManager()
: firstPair_ ()  // implicit call to default constructor
, currentPair_ () // implicit call to default constructor
, lastPair_(currentPair_.operator=(firstPair_.operator=(MbrType (nullptr))))
{/*e.b.*/}

Resulting in 6 calls rather than 3.


问:
How to create custom searchview in Android Studio?
How to create searchview in Android Studio like this ?

https://i.stack.imgur.com/q90mX.jpg

答:
Use this, Just change the star image with cross image:</p>

```<code><LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_test"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.mmc.testproject.TestActivity">

   <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Fly From:"/>

   <EditText
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:minWidth="100dp"
       android:textSize="20sp"
       android:drawableEnd="@drawable/star"
       android:background="@android:drawable/editbox_background"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Fly to:"/>

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minWidth="100dp"
        android:textSize="20sp"
        android:drawableEnd="@drawable/star"
        android:background="@android:drawable/editbox_background"/>
</LinearLayout>
</code>```

Body:
Use this, Just change the star image with cross image:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_test"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.mmc.testproject.TestActivity">

   <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Fly From:"/>

   <EditText
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:minWidth="100dp"
       android:textSize="20sp"
       android:drawableEnd="@drawable/star"
       android:background="@android:drawable/editbox_background"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Fly to:"/>

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minWidth="100dp"
        android:textSize="20sp"
        android:drawableEnd="@drawable/star"
        android:background="@android:drawable/editbox_background"/>
</LinearLayout>


问:
Transaction issue in ASP Classic
I am facing HTTP 500 error with classic asp application hosted in IIS 7.5 server and Windows server 2008.

I have done the below steps.

32 Bit Enabled in App Pool

Enable Parent Paths = true

MSDTC Security settings updated

Still that is not working with the above changes. But on uninstalling and installing MSDTC and doing a IISRESET works fine.

Note: ASP page enabled with Transaction=required and removing this also works fine.

答:
Open IIS manager and go to ASP section

set send error to browser = true

remove the default script error message

save and restart IIS

Uncheck the "Show friendly error message" from browser. If you have performed the above steps you will be able to see the correct error in you browser.

Check the screenshot below

IIS settings

What is the error you are seeing in the browser??
Check these below links to configure MSDTC and your DB for transaction and authentication (inbound,outbound). For you description it looks like a authentication and transaction related issue in ASP.

Where MSDTC needs to be installed in Distributed transaction case

https://msdn.microsoft.com/en-us/library/dd327979.aspx

Title: Transaction issue in ASP Classic


问:
How to activate option menu when search box is displayed? (SearchManager)
I am trying to build a quick search box. it is basically a widget. Upon clicking, it pops up the quick search box and launch the browser with query string. No activity except searchactivity.

And also added codes for 'recent query suggestion' But having a problem to have menu for 'clear history' Here is what I wanted to implement. When quick search box is displayed, by pressing menu button, I want option menu to be popped up, keypad to be disappeared, quick search box to be stayed.

the implementation of google sample code - Searchable dictionary is not what I want to implement. It starts an activity with instruction message and when a user presses the search button or menu button, it pops up the quick search box. Mine is when it runs from a widget, the quick search box is popped up right away just like the google search widget.

How can I override onCreateOptionMenu on searchmanager? Or is there any way to activate option menu  when the searchmanager is activated?

Please take a look at the images below. the second image is what I want to implement upon clicking menu button.

答: What you need to do is make the search button launch the default search activity when it is pressed.   And make it sorta match the existing search dialog style.  You can notice this is how the official Twitter client works.  You can use apktool (google it) to take a look at the official Twitter clients resource files to get a better idea of how this can be accomplished.</p>