问:
PHP get data from web services that returns an stdClass Object
I am trying to get the values from my web service using the following code:

```<code>$client = new SoapClient($url);
$response = $client->GetInfoByNumeroContrato(array(
   'schema' => $schema,
   'numContrato' => $numContract
));
</code>```

I have a method called GetInfoByNumeroContrato that receives two parameters.
When I call my web service the $response gives me a stdClass Object as shown below:

```<code>stdClass Object
(
[GetInfoByNumeroContratoResult] => stdClass Object
    (
        [schema] =>
        [any] => 000559500trueTITULAR BNMARIA  DORES  PEIXOTO220125424DORESRIBEIRO50@GMAIL.COMR DAMIAO DE GOIS ENTRADA 71 BL 1 1 ANDAR N 90000003194460-2921646013411950-10-07T00:00:00+01:00Divorciado003501600006968540097PT50003501600006968540097CGDIPTPLBilhete de IdentidadeSENHORA DA HORAFeminino4010003002015-09-16T00:00:00+01:0024.90falseSENIORtrue2015-10-05T00:00:00+01:00true2016-09-05T00:00:00+01:002015-11-05T00:00:00+00:00M0PT47111799DÉBITO DIRETOCONNECTA000559500falseAGREGADOJOSE  LUIS RIBEIRO  FAIEL220125424R DAMIAO DE GOIS ENTRADA 71 BL 1 1 ANDAR N 90000003204460-2921646013411983-08-23T00:00:00+01:00Outro003501600006968540097Bilhete de IdentidadeSENHORA DA HORAMasculino4010003012015-09-16T00:00:00+01:0024.90falseSENIORtrue2015-10-05T00:00:00+01:00true2016-09-05T00:00:00+01:002015-11-05T00:00:00+00:00M0PT47111799DÉBITO DIRETOCONNECTA
    )

[_exception] =>
)
</code>```

The idea is to get each value individually from [any] and the POST each one.  For example get "000559500" then "true" and so on.

I have already tried to parse this but without success.

Is there any better way to go about this?

When I do the following:

```<code>print $response->GetInfoByNumeroContratoResult->any;
</code>```

I get the following answer:

```<code>000559500trueTITULAR BNMARIA DORES PEIXOTO220125424DORESRIBEIRO50@GMAIL.COMR   DAMIAO DE GOIS ENTRADA 71 BL 1 1 ANDAR N 90000003194460-2921646013411950-10-07T00:00:00+01:00Divorciado003501600006968540097PT50003501600006968540097CGDIPTPLBilhete de IdentidadeSENHORA DA HORAFeminino4010003002015-09-16T00:00:00+01:0024.90falseSENIORtrue2015-10-05T00:00:00+01:00true2016-09-05T00:00:00+01:002015-11-05T00:00:00+00:00M0PT47111799DÉBITO DIRETOCONNECTA000559500falseAGREGADOJOSE LUIS RIBEIRO FAIEL220125424R DAMIAO DE GOIS ENTRADA 71 BL 1 1 ANDAR N 90000003204460-2921646013411983-08-23T00:00:00+01:00Outro003501600006968540097Bilhete de IdentidadeSENHORA DA HORAMasculino4010003012015-09-16T00:00:00+01:0024.90falseSENIORtrue2015-10-05T00:00:00+01:00true2016-09-05T00:00:00+01:002015-11-05T00:00:00+00:00M0PT47111799DÉBITO DIRETOCONNECTA
</code>```

Is it possible to get one by one?

Is it possible to receive from the web service insted getting every thing in [any] recive for example: [contractNumer] => value then [Name] => value and so on? Individualy?

答:
I know this is a late answer, but might save hours for someone else:</p>

```<code>$xml= simplexml_load_string($response->GetInfoByNumeroContratoResult->any);

print_r($xml);  //an array containing the whole XML

print $x->contractNumber; //individually
</code>```

Body:
I am trying to get the values from my web service using the following code:

$client = new SoapClient($url);
$response = $client->GetInfoByNumeroContrato(array(
   'schema' => $schema,
   'numContrato' => $numContract
));

I have a method called GetInfoByNumeroContrato that receives two parameters.
When I call my web service the $response gives me a stdClass Object as shown below:

stdClass Object
(
[GetInfoByNumeroContratoResult] => stdClass Object
    (
        [schema] =>
        [any] => 000559500trueTITULAR BNMARIA  DORES  PEIXOTO220125424DORESRIBEIRO50@GMAIL.COMR DAMIAO DE GOIS ENTRADA 71 BL 1 1 ANDAR N 90000003194460-2921646013411950-10-07T00:00:00+01:00Divorciado003501600006968540097PT50003501600006968540097CGDIPTPLBilhete de IdentidadeSENHORA DA HORAFeminino4010003002015-09-16T00:00:00+01:0024.90falseSENIORtrue2015-10-05T00:00:00+01:00true2016-09-05T00:00:00+01:002015-11-05T00:00:00+00:00M0PT47111799DÉBITO DIRETOCONNECTA000559500falseAGREGADOJOSE  LUIS RIBEIRO  FAIEL220125424R DAMIAO DE GOIS ENTRADA 71 BL 1 1 ANDAR N 90000003204460-2921646013411983-08-23T00:00:00+01:00Outro003501600006968540097Bilhete de IdentidadeSENHORA DA HORAMasculino4010003012015-09-16T00:00:00+01:0024.90falseSENIORtrue2015-10-05T00:00:00+01:00true2016-09-05T00:00:00+01:002015-11-05T00:00:00+00:00M0PT47111799DÉBITO DIRETOCONNECTA
    )

[_exception] =>
)

The idea is to get each value individually from [any] and the POST each one.  For example get "000559500" then "true" and so on.

I have already tried to parse this but without success.

Is there any better way to go about this?

When I do the following:

print $response->GetInfoByNumeroContratoResult->any;

I get the following answer:

000559500trueTITULAR BNMARIA DORES PEIXOTO220125424DORESRIBEIRO50@GMAIL.COMR   DAMIAO DE GOIS ENTRADA 71 BL 1 1 ANDAR N 90000003194460-2921646013411950-10-07T00:00:00+01:00Divorciado003501600006968540097PT50003501600006968540097CGDIPTPLBilhete de IdentidadeSENHORA DA HORAFeminino4010003002015-09-16T00:00:00+01:0024.90falseSENIORtrue2015-10-05T00:00:00+01:00true2016-09-05T00:00:00+01:002015-11-05T00:00:00+00:00M0PT47111799DÉBITO DIRETOCONNECTA000559500falseAGREGADOJOSE LUIS RIBEIRO FAIEL220125424R DAMIAO DE GOIS ENTRADA 71 BL 1 1 ANDAR N 90000003204460-2921646013411983-08-23T00:00:00+01:00Outro003501600006968540097Bilhete de IdentidadeSENHORA DA HORAMasculino4010003012015-09-16T00:00:00+01:0024.90falseSENIORtrue2015-10-05T00:00:00+01:00true2016-09-05T00:00:00+01:002015-11-05T00:00:00+00:00M0PT47111799DÉBITO DIRETOCONNECTA

Is it possible to get one by one?

Is it possible to receive from the web service insted getting every thing in [any] recive for example: [contractNumer] => value then [Name] => value and so on? Individualy?

Body:
I know this is a late answer, but might save hours for someone else:

$xml= simplexml_load_string($response->GetInfoByNumeroContratoResult->any);

print_r($xml);  //an array containing the whole XML

print $x->contractNumber; //individually


来源: stackexchange

问:
Find a value that could appear multiple times but only use other value once
Title maybe a bit confusing because I didn't know how to explain myself...

The problem I have is that I have a comments table in which is stored the instance that the comment is about, the comment itself and the user that commented, I'm trying to collect all the instances that have been commented by a user. But if an instance has been commented twice only select the instance once.

Currently I have this code which is returning all the instances

```<code>$test = @mysql_query("select * from comments where user_id = '$idd'");
while($result = mysql_fetch_array($test))
{
    $id = $result['instance_id'];
    $gender = $result['gender'];
    $name = $result['name'];

    $test2 = @mysql_query("select * from media_link where instance_id = $id");
    $result2 = mysql_fetch_array($test2);

    $media = $result2['media_id'];

    $test3 = @mysql_query("select * from comments where instance_id = $id");
    $result3 = mysql_fetch_array($test3);
    $comments = $result3['comments'];
</code>```

The attributes are then arranged in a table and echoed out within the while loop.

答:
Sounds like a job for the DISTINCT keyword (info here). You weren't super clear on what your schema looks like, but working from what you provided:

```<code>$test = @mysql_query("select distinct instance_id from comments where user_id = '$idd'");
</code>```

This will perform the selection, then ignore any redundant rows in the result, so you'll get each thread/instance that the user commented in, but each thread will only appear once.

ContentLicense: CC BY-SA 3.0

Body:
Title maybe a bit confusing because I didn't know how to explain myself...

The problem I have is that I have a comments table in which is stored the instance that the comment is about, the comment itself and the user that commented, I'm trying to collect all the instances that have been commented by a user. But if an instance has been commented twice only select the instance once.

Currently I have this code which is returning all the instances

$test = @mysql_query("select * from comments where user_id = '$idd'");
while($result = mysql_fetch_array($test))
{
    $id = $result['instance_id'];
    $gender = $result['gender'];
    $name = $result['name'];

    $test2 = @mysql_query("select * from media_link where instance_id = $id");
    $result2 = mysql_fetch_array($test2);

    $media = $result2['media_id'];

    $test3 = @mysql_query("select * from comments where instance_id = $id");
    $result3 = mysql_fetch_array($test3);
    $comments = $result3['comments'];

The attributes are then arranged in a table and echoed out within the while loop.

Body:
Sounds like a job for the DISTINCT keyword (info here). You weren't super clear on what your schema looks like, but working from what you provided:

$test = @mysql_query("select distinct instance_id from comments where user_id = '$idd'");

This will perform the selection, then ignore any redundant rows in the result, so you'll get each thread/instance that the user commented in, but each thread will only appear once.


问:
data is not shown on ionic view page after retrieving data
I am facing the problem of displaying data on View in ionic.
I have tried some code. It didn't work yet. When I print out $person on ts file, I got [object Object]. My json obj is like {"user_name":"user123", "full_name": "yiemon", "email":"yiemon@gmail.com"}.Please help me.

This is my menu.ts

```<code>async ionViewWillEnter() {
     this.person$ = from(this.authService.getProfile().then((res) => {
      this.authService.setProfile(res.data);
      console.log(res.data);
      return res.data;
    }));

    console.log("User_"+this.person$);
    //this.username=this.authService.userProfile.username;
  }
</code>```

This is my menu.html

```<code>  <ion-col class="menu_bottom" >
          <!--  {{(person$ | async)?.user_name}} -->
           <!-- {{person$.user_name}} -->
            {{person$?.user_name}}
   </ion-col>
</code>```

答: After parsing the JSON object and calling the data this way {{userProfile.user_name}}, the data appears.  </p>

ContentLicense: CC BY-SA 4.0

Body:
I am facing the problem of displaying data on View in ionic.
I have tried some code. It didn't work yet. When I print out $person on ts file, I got [object Object]. My json obj is like {"user_name":"user123", "full_name": "yiemon", "email":"yiemon@gmail.com"}.Please help me.

This is my menu.ts

async ionViewWillEnter() {
     this.person$ = from(this.authService.getProfile().then((res) => {
      this.authService.setProfile(res.data);
      console.log(res.data);
      return res.data;
    }));

    console.log("User_"+this.person$);
    //this.username=this.authService.userProfile.username;
  }

This is my menu.html

  <ion-col class="menu_bottom" >

            {{person$?.user_name}}
   </ion-col>


问:
Can we use global symbols in Typescript Declaration files?
I'm trying to implement something like this but I'm not sure it's possible.  I think Typescript only allows unique symbols, not global ones.  Is this correct?

Is there a better way to achieve using global symbols?

```<code>// sample.d.ts
const mySymbol = Symbol.for('internal.symbol')

interface Sample{
    [mySymbol]: string
    a: number
    b: number
}

// sample.js
class SampleClass implements Sample {
    [mySymbol]: string
    a: number
    b: number

    constructor(a: number, b: number){
        this.a = a;
        this.b = b;
        this[mySymbol] = `${a}-${b}`
    }
}

let mySample = new SampleClass(1, 2)

</code>```

Is there a way to accomplish this?  mySymbol can (and ideally will) be a global symbol that will be used by other objects as well so it can be defined separately if that can be accomplished.

答:
You can export your symbol i.e.

```<code>export const mySymbol = Symbol.for('internal.symbol')
</code>```

and then import it into whatever file requires it. This way you won't pollute the global scope and you can import it only when necessary.

Body:
I'm trying to implement something like this but I'm not sure it's possible.  I think Typescript only allows unique symbols, not global ones.  Is this correct?

Is there a better way to achieve using global symbols?

// sample.d.ts
const mySymbol = Symbol.for('internal.symbol')

interface Sample{
    [mySymbol]: string
    a: number
    b: number
}

// sample.js
class SampleClass implements Sample {
    [mySymbol]: string
    a: number
    b: number

    constructor(a: number, b: number){
        this.a = a;
        this.b = b;
        this[mySymbol] = `${a}-${b}`
    }
}

let mySample = new SampleClass(1, 2)

Is there a way to accomplish this?  mySymbol can (and ideally will) be a global symbol that will be used by other objects as well so it can be defined separately if that can be accomplished.

Body:
You can export your symbol i.e.

export const mySymbol = Symbol.for('internal.symbol')

and then import it into whatever file requires it. This way you won't pollute the global scope and you can import it only when necessary.


问:
when does ':' show up in function arguments / keyword arguments in python?
I've been coding in python for quite a while but I came across a piece of code which got me really confused, as I've never seen expressions like this before:

```<code>class A(object):

    def __init__(self, config:dict, pool_args: dict=None, background: bool=True, **kwargs):
         self._config = config
         self._pool_args = pool_args
          ...
</code>```

so what is this type of syntax: config:dict and pool_args: dict=None inside the function argument brackets?

   Are they used often?  I've really never seen this before.

答: These are type hints. See this for more details: https://www.python.org/dev/peps/pep-0484/</p>

Body:
I've been coding in python for quite a while but I came across a piece of code which got me really confused, as I've never seen expressions like this before:

class A(object):

    def __init__(self, config:dict, pool_args: dict=None, background: bool=True, **kwargs):
         self._config = config
         self._pool_args = pool_args
          ...

so what is this type of syntax: config:dict and pool_args: dict=None inside the function argument brackets?

   Are they used often?  I've really never seen this before.


问:
FIRST_VALUE and LAST_VALUE with NULL values
I want to get the top 2 expensive book and least 2 expensive book prices
using FIRST_Value & LAST_Value SQL Server

The presence of Nulls is giving incorrect Min price value, I want the Min price to ignore Nulls

```<code>Select top 2 FIRST_VALUE(price) Over(Order by price) as MinPrice,
FIRST_VALUE(title) Over (order by price) as MinName,
LAST_VALUE(price) Over (order by price desc) as MaxPrice,
LAST_VALUE(title) over (Order by price desc) as MaxName
from titles;
</code>```

Getting this output

```<code>MINPrice    MINName                        Maxprice           MaxName
NULL       The Psychology of Computer        $22.95      But is it Friendly?
NULL       The Psychology of Computer        $21.59      Computer Phobic and
</code>```

Where as the result I am expecting should be

```<code>Minprice     MinName                        Maxprice          Maxname
$2.99        The Gourmet Microwave           $22.95       But is it Friendly?
$2.99        You can Combat stress          $21.59       Computer Phobic and
</code>```

So how do I eliminate NULLs from Min price

答:
```<code>SELECT min(value) FROM table WHERE value IS NOT NULL.
</code>```

It should be something like this.

Body:
I want to get the top 2 expensive book and least 2 expensive book prices
using FIRST_Value & LAST_Value SQL Server

The presence of Nulls is giving incorrect Min price value, I want the Min price to ignore Nulls

Select top 2 FIRST_VALUE(price) Over(Order by price) as MinPrice,
FIRST_VALUE(title) Over (order by price) as MinName,
LAST_VALUE(price) Over (order by price desc) as MaxPrice,
LAST_VALUE(title) over (Order by price desc) as MaxName
from titles;

Getting this output

MINPrice    MINName                        Maxprice           MaxName
NULL       The Psychology of Computer        $22.95      But is it Friendly?
NULL       The Psychology of Computer        $21.59      Computer Phobic and

Where as the result I am expecting should be

Minprice     MinName                        Maxprice          Maxname
$2.99        The Gourmet Microwave           $22.95       But is it Friendly?
$2.99        You can Combat stress          $21.59       Computer Phobic and

So how do I eliminate NULLs from Min price

Body:
SELECT min(value) FROM table WHERE value IS NOT NULL.

It should be something like this.


问:
How do I align the render of this page with bootstrap4 using visual studio
I'm using visual studio 2019 and bootstrap4 (which I'm new to) to develop a web page for account registration. The render does not seem right. I remove ASP tags from the code below. I use a combination of codes from www.w3schools.com/bootstrap4. Below is the code I tried.

```<code>    <div class="form-inline">
        <div class="input-group mb-3">
            <div class="input-group-prepend">
                <span class="input-group-text">Country</span>
            </div>
            <select class="form-control"><option>1</option></select>
        </div>
        <div class="input-group mb-3">
            <div class="input-group-prepend">
                <span class="input-group-text">Business Name</span>
            </div>
            <input type="text" class="form-control" placeholder="Business Name">
        </div>
        <div class="input-group mb-3">
            <div class="input-group-prepend">
                <span class="input-group-text">
                    Street</span>
            </div>
            <input type="text" class="form-control" placeholder="Street, including Building number and Suite">
        </div>
    </div>
    <div class="row">
        <div class="col-xs-12 col-sm-2 col-md-4">
            <div class="form-inline">
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text">
                            City</span>
                    </div>
                    <input type="text" class="form-control" placeholder="City">
                </div>
            </div>
        </div>
        <div class="col-xs-12 col-sm-2 col-md-4">
            <div class="form-inline">
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text">
                            State</span>
                    </div>
                    <select class="form-control"><option>1</option></select>
                </div>
            </div>
        </div>
        <div class="col-xs-12 col-sm-2 col-md-4">
            <div class="form-inline">
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text">
                            Zip code</span>
                    </div>
                    <input type="text" class="form-control" placeholder="Zip code"></div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-xs-12 col-sm-2 col-md-4">
            <div class="form-inline">
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text">
                            Telephone</span>
                    </div>
                    <input type="text" class="form-control" placeholder="Telephone">
                </div>
            </div>
        </div>
        <div class="col-xs-12 col-sm-2 col-md-4">
            <div class="form-inline">
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text">
                            Email Address</span>
                    </div>
                    <input type="text" class="form-control" placeholder="Email address">
                </div>
            </div>
        </div>
        <div class="col-xs-12 col-sm-2 col-md-4">
            <div class="form-inline">
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text">
                            Website</span>
                    </div>
                    <input type="text" class="form-control" placeholder="Website">
                </div>
            </div>
        </div>
    </div>
</code>```

The input fields do not properly align. Can anyone help why the render does not properly align?

答:
After reading the question and the comments it seems you are having trouble with form-control as it is not going up to its full width. That is because you have a custom css file in Content folder of your project structure that overrides the behavior of few tags. See:

Here you can see input,select,textarea tags have been overridden and you can just remove it or comment it out to make it go full width:

UPDATE:
I also noticed that your html for input controls is also incorrect and not well formatted. Here is the correct version of it:

```<code><style>
    .input-group {
        width: 100% !important;
    }
</style>
<div class="container">
        <div class="row">
            <div class="col-xs-12 col-sm-2 col-md-4">
                <div class="form-inline">
                    <div class="input-group mb-3">
                        <div class="input-group-prepend">
                            <span class="input-group-text">Country</span>
                        </div>
                        <select class="form-control">
                            <option>1</option>
                        </select>
                    </div>
                </div>

            </div>
            <div class="col-xs-12 col-sm-2 col-md-4">
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text">Business Name</span>
                    </div>
                    <input type="text" class="form-control" placeholder="Business Name">
                </div>
            </div>
            <div class="col-xs-12 col-sm-2 col-md-4">
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text">Street</span>
                    </div>
                    <input type="text" class="form-control" placeholder="Street, including Building number and Suite">
                </div>
            </div>

        </div>

        <div class="row">
            <div class="col-xs-12 col-sm-2 col-md-4">
                <div class="form-inline">
                    <div class="input-group mb-3">
                        <div class="input-group-prepend">
                            <span class="input-group-text">City</span>
                        </div>
                        <input type="text" class="form-control" placeholder="City">
                    </div>
                </div>
            </div>
            <div class="col-xs-12 col-sm-2 col-md-4">
                <div class="form-inline">
                    <div class="input-group mb-3">
                        <div class="input-group-prepend">
                            <span class="input-group-text">State</span>
                        </div>
                        <select class="form-control">
                            <option>1</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="col-xs-12 col-sm-2 col-md-4">
                <div class="form-inline">
                    <div class="input-group mb-3">
                        <div class="input-group-prepend">
                            <span class="input-group-text">Zip code</span>
                        </div>
                        <input type="text" class="form-control" placeholder="Zip code">
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-12 col-sm-2 col-md-4">
                <div class="form-inline">
                    <div class="input-group mb-3">
                        <div class="input-group-prepend">
                            <span class="input-group-text">Telephone</span>
                        </div>
                        <input type="text" class="form-control" placeholder="Telephone">
                    </div>
                </div>
            </div>
            <div class="col-xs-12 col-sm-2 col-md-4">
                <div class="form-inline">
                    <div class="input-group mb-3">
                        <div class="input-group-prepend">
                            <span class="input-group-text">Email Address</span>
                        </div>
                        <input type="text" class="form-control" placeholder="Email address">
                    </div>
                </div>
            </div>
            <div class="col-xs-12 col-sm-2 col-md-4">
                <div class="form-inline">
                    <div class="input-group mb-3">
                        <div class="input-group-prepend">
                            <span class="input-group-text">Website</span>
                        </div>
                        <input type="text" class="form-control" placeholder="Website">
                    </div>
                </div>
            </div>
        </div>
    </div>
</code>```

See the output here.

Body:
I'm using visual studio 2019 and bootstrap4 (which I'm new to) to develop a web page for account registration. The render does not seem right. I remove ASP tags from the code below. I use a combination of codes from www.w3schools.com/bootstrap4. Below is the code I tried.

                Country

            <select class="form-control"><option>1</option></select>

                Business Name

            <input type="text" class="form-control" placeholder="Business Name">

                    Street

            <input type="text" class="form-control" placeholder="Street, including Building number and Suite">

                            City

                    <input type="text" class="form-control" placeholder="City">

                            State

                    <select class="form-control"><option>1</option></select>

                            Zip code

                    <input type="text" class="form-control" placeholder="Zip code">

                            Telephone

                    <input type="text" class="form-control" placeholder="Telephone">

                            Email Address

                    <input type="text" class="form-control" placeholder="Email address">

                            Website

                    <input type="text" class="form-control" placeholder="Website">

The input fields do not properly align. Can anyone help why the render does not properly align?

Body:
After reading the question and the comments it seems you are having trouble with form-control as it is not going up to its full width. That is because you have a custom css file in Content folder of your project structure that overrides the behavior of few tags. See:

Here you can see input,select,textarea tags have been overridden and you can just remove it or comment it out to make it go full width:

UPDATE:
I also noticed that your html for input controls is also incorrect and not well formatted. Here is the correct version of it:

<style>
    .input-group {
        width: 100% !important;
    }
</style>
<div class="container">
        <div class="row">
            <div class="col-xs-12 col-sm-2 col-md-4">
                <div class="form-inline">
                    <div class="input-group mb-3">
                        <div class="input-group-prepend">
                            <span class="input-group-text">Country</span>
                        </div>
                        <select class="form-control">
                            <option>1</option>
                        </select>
                    </div>
                </div>

            </div>
            <div class="col-xs-12 col-sm-2 col-md-4">
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text">Business Name</span>
                    </div>
                    <input type="text" class="form-control" placeholder="Business Name">
                </div>
            </div>
            <div class="col-xs-12 col-sm-2 col-md-4">
                <div class="input-group mb-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text">Street</span>
                    </div>
                    <input type="text" class="form-control" placeholder="Street, including Building number and Suite">
                </div>
            </div>

        </div>

        <div class="row">
            <div class="col-xs-12 col-sm-2 col-md-4">
                <div class="form-inline">
                    <div class="input-group mb-3">
                        <div class="input-group-prepend">
                            <span class="input-group-text">City</span>
                        </div>
                        <input type="text" class="form-control" placeholder="City">
                    </div>
                </div>
            </div>
            <div class="col-xs-12 col-sm-2 col-md-4">
                <div class="form-inline">
                    <div class="input-group mb-3">
                        <div class="input-group-prepend">
                            <span class="input-group-text">State</span>
                        </div>
                        <select class="form-control">
                            <option>1</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="col-xs-12 col-sm-2 col-md-4">
                <div class="form-inline">
                    <div class="input-group mb-3">
                        <div class="input-group-prepend">
                            <span class="input-group-text">Zip code</span>
                        </div>
                        <input type="text" class="form-control" placeholder="Zip code">
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-12 col-sm-2 col-md-4">
                <div class="form-inline">
                    <div class="input-group mb-3">
                        <div class="input-group-prepend">
                            <span class="input-group-text">Telephone</span>
                        </div>
                        <input type="text" class="form-control" placeholder="Telephone">
                    </div>
                </div>
            </div>
            <div class="col-xs-12 col-sm-2 col-md-4">
                <div class="form-inline">
                    <div class="input-group mb-3">
                        <div class="input-group-prepend">
                            <span class="input-group-text">Email Address</span>
                        </div>
                        <input type="text" class="form-control" placeholder="Email address">
                    </div>
                </div>
            </div>
            <div class="col-xs-12 col-sm-2 col-md-4">
                <div class="form-inline">
                    <div class="input-group mb-3">
                        <div class="input-group-prepend">
                            <span class="input-group-text">Website</span>
                        </div>
                        <input type="text" class="form-control" placeholder="Website">
                    </div>
                </div>
            </div>
        </div>
    </div>

See the output here.


问:
Error: header values must be strings Error: advanced-http: header values must be strings ionic
I would like to retrieve data from API to ionic. First, I was facing issue of CORS and unable to retrieve data from different devices except original port. I was trying to use http native to retrieve data on device. I have a problem of getting header from API.  I am not allowed to modify server. However, I ended up with error as below : Please guide me how to use http native in ionic.

```<code> (in promise): Error: advanced-http: header values must be strings
Error: advanced-http: header values must be strings

</code>```

I have tried with following code:

```<code>login(username: String, password: String) {
    if(username === undefined || username === '' || password === undefined || password === null){
      presentAlert("No username or password", this.alertController);
      return;
    }

      this.mcs.mobileBackend.setAuthenticationType(this.mcs.AUTHENTICATION_TYPES.oauth);
      this.mcs.mobileBackend.authorization.authenticate(username, password).then(
        () => {
          console.log("Test");
          this.http.get(this.mcs.mobileBackend.getCustomCodeUrl(mcsConfig.environment + '_api_care/lovs?code_table_name=activity_code'), {}, {headers:careheader})
      .then(data => {

        console.log(data.status);
        console.log(data.data); // data received by server
        console.log(data.headers);

      })
      .catch(error => {

        console.log(error.status);
        console.log(error.error); // error message as string
        console.log(error.headers);

      });
 }
      ).then(() => {
        console.log('test2' + username + password);
        this.getUserRole();
        this.authenticationState.next(true);
      }).catch(err => {
        console.log(err,Headers);
        presentAlert(err, this.alertController);
      });

  }
getHeader(){
    let headers = new Headers();
    this.createAuthorizationHeader(headers);
    headers.append('Content-Type', 'application/json');
   }
getUserRole() {
    return this.http.get(this.mcs.mobileBackend.getPlatformUrl('users/me'), {},{ }).then(data => {
      console.log(data); console.log(data.headers);
    });
  }
 getReportList(offset: number = 0, limit: number = mcsConfig.rowLimit) {
    let queryParam = '?offset=' + (offset * limit) + '&limit=' + limit;
    //return this.mcs.mobileBackend.customCode.invokeCustomCodeJSONRequest(mcsConfig.environment + '_api_care/my/incidents' + queryParam, 'GET', null);
    return this.http.get(this.mcs.mobileBackend.getCustomCodeUrl(mcsConfig.environment + '_api_care/my/incidents'+ queryParam), {},{headers: this.getMcsHeaders()});
    }
</code>```

The data is not shown.

答:
Here is my header below : </p>

```<code>getMcsHeadersString() {
var cheaders = {};
for (let key in this.mcs.mobileBackend.getHttpHeaders()) {
  cheaders[key]= this.mcs.mobileBackend.getHttpHeaders()[key];
}
//console.log("STring_HeaderKey_"+cheaders['_keys']+"HeaderValue_"+cheaders['_values']);
delete cheaders['_keys'];
delete cheaders['_values'];
return cheaders;
</code>```

<p>} </p>

Body:
I would like to retrieve data from API to ionic. First, I was facing issue of CORS and unable to retrieve data from different devices except original port. I was trying to use http native to retrieve data on device. I have a problem of getting header from API.  I am not allowed to modify server. However, I ended up with error as below : Please guide me how to use http native in ionic.

 (in promise): Error: advanced-http: header values must be strings
Error: advanced-http: header values must be strings

I have tried with following code:

login(username: String, password: String) {
    if(username === undefined || username === '' || password === undefined || password === null){
      presentAlert("No username or password", this.alertController);
      return;
    }

      this.mcs.mobileBackend.setAuthenticationType(this.mcs.AUTHENTICATION_TYPES.oauth);
      this.mcs.mobileBackend.authorization.authenticate(username, password).then(
        () => {
          console.log("Test");
          this.http.get(this.mcs.mobileBackend.getCustomCodeUrl(mcsConfig.environment + '_api_care/lovs?code_table_name=activity_code'), {}, {headers:careheader})
      .then(data => {

        console.log(data.status);
        console.log(data.data); // data received by server
        console.log(data.headers);

      })
      .catch(error => {

        console.log(error.status);
        console.log(error.error); // error message as string
        console.log(error.headers);

      });
 }
      ).then(() => {
        console.log('test2' + username + password);
        this.getUserRole();
        this.authenticationState.next(true);
      }).catch(err => {
        console.log(err,Headers);
        presentAlert(err, this.alertController);
      });

  }
getHeader(){
    let headers = new Headers();
    this.createAuthorizationHeader(headers);
    headers.append('Content-Type', 'application/json');
   }
getUserRole() {
    return this.http.get(this.mcs.mobileBackend.getPlatformUrl('users/me'), {},{ }).then(data => {
      console.log(data); console.log(data.headers);
    });
  }
 getReportList(offset: number = 0, limit: number = mcsConfig.rowLimit) {
    let queryParam = '?offset=' + (offset * limit) + '&limit=' + limit;
    //return this.mcs.mobileBackend.customCode.invokeCustomCodeJSONRequest(mcsConfig.environment + '_api_care/my/incidents' + queryParam, 'GET', null);
    return this.http.get(this.mcs.mobileBackend.getCustomCodeUrl(mcsConfig.environment + '_api_care/my/incidents'+ queryParam), {},{headers: this.getMcsHeaders()});
    }

The data is not shown.

Body:
Here is my header below :

getMcsHeadersString() {
var cheaders = {};
for (let key in this.mcs.mobileBackend.getHttpHeaders()) {
  cheaders[key]= this.mcs.mobileBackend.getHttpHeaders()[key];
}
//console.log("STring_HeaderKey_"+cheaders['_keys']+"HeaderValue_"+cheaders['_values']);
delete cheaders['_keys'];
delete cheaders['_values'];
return cheaders;

}


问:
Has anyone used this twitter api - http://www.twapime.com/
Has anyone tried this api ? I'm having some trouble implementing it on BlackBerry. Tweets do not always send and I cannot access posted tweets.

Here is my code -

```<code>private void twitterSetup(){

        HttpRequest req = new HttpRequest("https://api.twitter.com/oauth/access_token");
        req.setMethod(HttpConnection.POST);
        XAuthSigner signer = new XAuthSigner("", "");
        signer.signForAccessToken(req, "", "");
        try {
        HttpResponse resp = req.send();
        if (resp.getCode() == HttpConnection.HTTP_OK)
        {
        Token accessToken = Token.parse(resp.getBodyContent());
        req.close();
        req = new HttpRequest("http://api.twitter.com/1/statuses/update.xml");
        req.setMethod(HttpConnection.POST);
        req.setBodyParameter("status", "new message");
        req.setSigner(signer, accessToken);
        resp = req.send();

        Tweet[] twts = null;
        try {

            Credential c = new Credential("","","","");
            UserAccountManager uam = UserAccountManager.getInstance(c);
         List[] lists = null;
            ListManager ter = null;
            if (uam.verifyCredential()) {
                 ter = ListManager.getInstance(uam); //pode ser pela classe Timeline tambem.

                ListManager listMngr = ListManager.getInstance(uam);
                lists = listMngr.getLists();
                }

            ter.startGetListTweets(lists[0], null, new SearchDeviceListener() {
            public void searchCompleted() {}
            public void searchFailed(Throwable cause) {}
            public void tweetFound(Tweet tweet) {
                System.out.println(tweet);
            }
            });

        }
        catch(Exception e){
            e.printStackTrace();
        }
        }
        else { }

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

        }
        catch(Exception e){

        }finally {
        try {
        req.close();
        } catch (IOException e) {}
        }

    }
</code>```

Thanks for any help.

答:
Ok,

Here is the class im using to get the twitter content based on type and tag. method getContent is not the most elegant but it works. It just downloads and parses a json file.
Look at http://search.twitter.com/api/

```<code>public class GetTwitterContent implements Runnable {

    private String tag;
    private String type;

    public GetTwitterContent(String type, String tag) {
        this.type = type;
        this.tag = tag;
    }

    public void run() {

        try {

            Hashtable twitterValuesHashtable = new Hashtable();
            String serviceUrl = "";

            if (type.equalsIgnoreCase(Constants.TWITTER_CONTENT_TYPE_HASHTAG)) {
                serviceUrl = Constants.TWITTER_CONTENT_HASHTAG_CONTENT;
            } else if (type.equalsIgnoreCase(Constants.TWITTER_CONTENT_TYPE_USER)) {
                serviceUrl = Constants.TWITTER_CONTENT_USER_CONTENT;
            }

            ByteArrayOutputStream baos = getContent(serviceUrl + this.tag);
            JSONObject jsonObject = new JSONObject(new String(baos.toByteArray(), 0, baos.size(), "utf-8"));
            JSONArray jsonArray = jsonObject.getJSONArray("results");
            for (int counter = 0; counter < jsonArray.length(); ++counter) {
                JSONObject thisJsonObject = (JSONObject) jsonArray.get(counter);
                TwitterResponse twitterResponse = new TwitterResponse();
                twitterResponse.setCreatedAt(thisJsonObject.optString("created_at", "na"));
                twitterResponse.setTweetText(thisJsonObject.optString("text","na"));
                twitterResponse.setFromUser(thisJsonObject.optString("from_user", "na"));
                twitterValuesHashtable.put(new Integer(counter),twitterResponse);
            }
            ServerContent.future.addContent(Constants.TWITTER_KEY, twitterValuesHashtable);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private ByteArrayOutputStream getContent(String url) {

        ByteArrayOutputStream baos = null;
        // len = 0;
        try {

            javax.microedition.io.HttpConnection connection = (javax.microedition.io.HttpConnection) Connector
                    .open(url);
            connection.setRequestMethod(HttpConnection.GET);
            // connection.setRequestProperty("Connection", "close");
            java.io.InputStream inputStream = connection.openDataInputStream();

            // inputStream = getClass().getResourceAsStream(url);
            baos = new ByteArrayOutputStream();
            int c;
            while (true) {
                c = inputStream.read();
                if (c == -1)
                    break;
                // ++len;
                baos.write(c);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return baos;
    }

}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Has anyone tried this api ? I'm having some trouble implementing it on BlackBerry. Tweets do not always send and I cannot access posted tweets.

Here is my code -

private void twitterSetup(){

        HttpRequest req = new HttpRequest("https://api.twitter.com/oauth/access_token");
        req.setMethod(HttpConnection.POST);
        XAuthSigner signer = new XAuthSigner("", "");
        signer.signForAccessToken(req, "", "");
        try {
        HttpResponse resp = req.send();
        if (resp.getCode() == HttpConnection.HTTP_OK)
        {
        Token accessToken = Token.parse(resp.getBodyContent());
        req.close();
        req = new HttpRequest("http://api.twitter.com/1/statuses/update.xml");
        req.setMethod(HttpConnection.POST);
        req.setBodyParameter("status", "new message");
        req.setSigner(signer, accessToken);
        resp = req.send();

        Tweet[] twts = null;
        try {

            Credential c = new Credential("","","","");
            UserAccountManager uam = UserAccountManager.getInstance(c);
         List[] lists = null;
            ListManager ter = null;
            if (uam.verifyCredential()) {
                 ter = ListManager.getInstance(uam); //pode ser pela classe Timeline tambem.

                ListManager listMngr = ListManager.getInstance(uam);
                lists = listMngr.getLists();
                }

            ter.startGetListTweets(lists[0], null, new SearchDeviceListener() {
            public void searchCompleted() {}
            public void searchFailed(Throwable cause) {}
            public void tweetFound(Tweet tweet) {
                System.out.println(tweet);
            }
            });

        }
        catch(Exception e){
            e.printStackTrace();
        }
        }
        else { }

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

        }
        catch(Exception e){

        }finally {
        try {
        req.close();
        } catch (IOException e) {}
        }

    }

Thanks for any help.

Body:
Ok,

Here is the class im using to get the twitter content based on type and tag. method getContent is not the most elegant but it works. It just downloads and parses a json file.
Look at http://search.twitter.com/api/

public class GetTwitterContent implements Runnable {

    private String tag;
    private String type;

    public GetTwitterContent(String type, String tag) {
        this.type = type;
        this.tag = tag;
    }

    public void run() {

        try {

            Hashtable twitterValuesHashtable = new Hashtable();
            String serviceUrl = "";

            if (type.equalsIgnoreCase(Constants.TWITTER_CONTENT_TYPE_HASHTAG)) {
                serviceUrl = Constants.TWITTER_CONTENT_HASHTAG_CONTENT;
            } else if (type.equalsIgnoreCase(Constants.TWITTER_CONTENT_TYPE_USER)) {
                serviceUrl = Constants.TWITTER_CONTENT_USER_CONTENT;
            }

            ByteArrayOutputStream baos = getContent(serviceUrl + this.tag);
            JSONObject jsonObject = new JSONObject(new String(baos.toByteArray(), 0, baos.size(), "utf-8"));
            JSONArray jsonArray = jsonObject.getJSONArray("results");
            for (int counter = 0; counter < jsonArray.length(); ++counter) {
                JSONObject thisJsonObject = (JSONObject) jsonArray.get(counter);
                TwitterResponse twitterResponse = new TwitterResponse();
                twitterResponse.setCreatedAt(thisJsonObject.optString("created_at", "na"));
                twitterResponse.setTweetText(thisJsonObject.optString("text","na"));
                twitterResponse.setFromUser(thisJsonObject.optString("from_user", "na"));
                twitterValuesHashtable.put(new Integer(counter),twitterResponse);
            }
            ServerContent.future.addContent(Constants.TWITTER_KEY, twitterValuesHashtable);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private ByteArrayOutputStream getContent(String url) {

        ByteArrayOutputStream baos = null;
        // len = 0;
        try {

            javax.microedition.io.HttpConnection connection = (javax.microedition.io.HttpConnection) Connector
                    .open(url);
            connection.setRequestMethod(HttpConnection.GET);
            // connection.setRequestProperty("Connection", "close");
            java.io.InputStream inputStream = connection.openDataInputStream();

            // inputStream = getClass().getResourceAsStream(url);
            baos = new ByteArrayOutputStream();
            int c;
            while (true) {
                c = inputStream.read();
                if (c == -1)
                    break;
                // ++len;
                baos.write(c);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return baos;
    }

}


问:
Shall I use POJO or JSONObject for REST calls
Recently I have stumbled upon a situation where my new team is heavily using JsonObject for doing rest data interchange. Their view is while using pojo we are binding tightly with the rest service, while jsonObject gives freedom. Also it saves from unnecessary data serialisation at the same time reducing number of classes heavily.

I have some points to encounter them as:

Pojo gives more meaning to data and we are holding data with correct data type.

If we need only 2 fields of 10 fields of json, we can deserialize to 2 fields class with @JsonIgnore

I don't know exactly on the cost of deserialisation, but somehow I have a feeling it shouldn't be much difference.

Can someone help me understand which perspective is way to go ?

Please provide some pros and cons of using POJO and JSONObject.

Thanks

答:
This argument really boils down to whether you want to use POJOs or Maps for the data you are dealing with, as that is the fundamental difference between the 2 styles of handling data.

JsonObject (from jee7) is just a Map (the actual type signature extends Map<String, JsonValue>).

Using POJO's (eg deserialised using Jackson) are real objects.

So if you dont use domain/model classes for your data normally then I guess a Map will do. If you do (like most developers would), then it's a good idea to extend this practice to your API contracts.

To address specific points:

JsonObject saves from unnecessary data serialisation at the same time reducing number of classes heavily.

It doesn't, both of these JSON API's require serialisation/deserialisation, which is the process of turning wire data into an object. I would bet that Jackson is faster than JsonObject, however as Satyendra Kumar pointed out benchmarking is going to prove it one way or other.

while using pojo we are binding tightly with the rest service, while jsonObject gives freedom

If you are using the data from the API you are bound to the data model, whether you get the data from a property foo by response.getFoo() or response.get("foo").

For a really comprehensive discussion on the tradeoffs between classes and maps, check out this SoftwareEngineering post

It's worth pointing out that using Jackson/POJOs doesn't mean you are tightly coupled to your local model of a REST response. Jackson has excellent support for the Tolerant Reader pattern, which means that new fields in the API response will not break deserialisation, and a bunch of annotations like @JsonCreator, @JsonValue, @JsonIgnore for mapping the API responses back to your local domain model.

It also provides powerful tools for dealing with collections and generics.

Finally if the service you are interacting with is big and complex, if they provide a swagger/raml spec then you can generate the models based on that spec which should greatly reduce the time taken to curate the POJOs.


问:
Storing filename in db from ajax upload not working
When I use $filename below I can never store anything in the database. I've tried basename function but it doesn't seem to store anything.</p>

```<code>        $filename = $_FILES['file']['name'];

        /* Location */
        $location = "../media/images/profile-pics/".$filename;
        $uploadOk = 1;
        $imageFileType = pathinfo($location,PATHINFO_EXTENSION);

        /* Valid Extensions */
        $valid_extensions = array("jpg","jpeg","png");
        /* Check file extension */
        if( !in_array(strtolower($imageFileType),$valid_extensions) ) {
           $uploadOk = 0;
        }

        if($uploadOk == 0){
           echo 0;
        }else{
           /* Upload file */
           if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){

           }else{
              echo 0;
           }
        }

        //$filename = basename($_FILES['file']); removed, but still doesn't store file in db.

        $stmt = $db->prepare("UPDATE contacts SET name = ?, email = ?, phone = ?, jobtitle = ?, profile_pic = ? WHERE id = ?");
        $stmt->bind_param("sssssi", $name, $email, $phone, $jobtitle, $filename, $id);
        $stmt->execute();
        $stmt->close();
</code>```

答: Just get rid of $filename = basename($_FILES['file']); - you've already populated $filename with $_FILES['file']['name'] up above, which is the correct way to access the filename of the file as it was uploaded.

Body:
When I use $filename below I can never store anything in the database. I've tried basename function but it doesn't seem to store anything.

        $filename = $_FILES['file']['name'];

        /* Location */
        $location = "../media/images/profile-pics/".$filename;
        $uploadOk = 1;
        $imageFileType = pathinfo($location,PATHINFO_EXTENSION);

        /* Valid Extensions */
        $valid_extensions = array("jpg","jpeg","png");
        /* Check file extension */
        if( !in_array(strtolower($imageFileType),$valid_extensions) ) {
           $uploadOk = 0;
        }

        if($uploadOk == 0){
           echo 0;
        }else{
           /* Upload file */
           if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){

           }else{
              echo 0;
           }
        }

        //$filename = basename($_FILES['file']); removed, but still doesn't store file in db.

        $stmt = $db->prepare("UPDATE contacts SET name = ?, email = ?, phone = ?, jobtitle = ?, profile_pic = ? WHERE id = ?");
        $stmt->bind_param("sssssi", $name, $email, $phone, $jobtitle, $filename, $id);
        $stmt->execute();
        $stmt->close();


问:
LinkedIn API 2 and VanityName from r_basicprofile
LinkedIn recently updated their API and now I unable to get public user profile url(by VanityName) during OAuth2 authentication phase. Looks like r_basicprofile is not available anymore.

Is there any chance to get this url and if so, could you please describe how?

According to the following LinkedIn documentation Find Profile by VanityName API

The use of this API is restricted to those developers approved by
  LinkedIn and subject to applicable data restrictions in their
  agreements.

But there is no any information how to apply to this API. How to apply to this API and get the appropriate permissions for r_basicprofile?

答:
I think you need to become a partner although I'am struggling with the same thing

https://fullfabric.zendesk.com/hc/en-us/articles/115007056847-Setting-up-a-LinkedIn-application-and-Applying-to-become-a-LinkedIn-Partner


问:
Java Swing: Animations made using Thread.sleep() not working as expected
I am trying to create a sliding menu bar in which the menu bar having initial width of 60px, which grows in width to 260px on the ActionPerformed event of the menu icon button (three small horizontal lines Menu Icon) with the following code:

private void menuLabelBtnActionPerformed(java.awt.event.ActionEvent evt) {
        if(menuToggle.isSelected()){
            menuToggle.setSelected(false);
            Thread th = new Thread(){
                public void run(){
                    try{
                        for(int i=259;i>=210;i=i-15){
                            Thread.sleep(1);
                            i--;
                            slideMenuPane.setBounds(slideMenuPane.getX(), slideMenuPane.getY(), i, slideMenuPane.getHeight());
                        }
                        for(int i=210;i>=110;i=i-35){
                            Thread.sleep(1);
                            i--;
                            slideMenuPane.setBounds(slideMenuPane.getX(), slideMenuPane.getY(), i, slideMenuPane.getHeight());
                        }
                        for(int i=110;i>=60;i=i-5){
                            Thread.sleep(1);
                            i--;
                            slideMenuPane.setBounds(slideMenuPane.getX(), slideMenuPane.getY(), i, slideMenuPane.getHeight());
                        }
                    }catch(Exception e){
                        System.out.println(e);
                    }
                }
            };
            th.start();
        }
        else{
            menuToggle.setSelected(true);
            Thread th = new Thread(){
                public void run(){
                    try{
                        for(int i=61;i<=110;i=i+15){
                            Thread.sleep(1);
                            i++;
                            slideMenuPane.setBounds(slideMenuPane.getX(), slideMenuPane.getY(), i, slideMenuPane.getHeight());
                        }
                        for(int i=110;i<=210;i=i+35){
                            Thread.sleep(1);
                            i++;
                            slideMenuPane.setBounds(slideMenuPane.getX(), slideMenuPane.getY(), i, slideMenuPane.getHeight());
                        }
                        for(int i=210;i<=260;i=i+5){
                            Thread.sleep(1);
                            i++;
                            slideMenuPane.setBounds(slideMenuPane.getX(), slideMenuPane.getY(), i, slideMenuPane.getHeight());
                        }
                    }catch(Exception e){
                        System.out.println(e);
                    }
                }
            };
            th.start();
        }
    }

```

where menuToggle (contained in Other Components) is just used to know if the menu bar is already opened.
In effect this something like this:

However, when I click the menu icon button, there is a blink before the animation starts, it shows the menu bar with its width to be 60px and it lasts for a millisecond.
Is there anyway I can remove the blink?

答: Thread.Sleep() could be causing the issue. Using a Swing Timer to check how much time has elapsed since it last ran shouldn't pause the thread or create graphical issues like Thread.Sleep() does.</p>

Body:
I am trying to create a sliding menu bar in which the menu bar having initial width of 60px, which grows in width to 260px on the ActionPerformed event of the menu icon button (three small horizontal lines Menu Icon) with the following code:

private void menuLabelBtnActionPerformed(java.awt.event.ActionEvent evt) {
        if(menuToggle.isSelected()){
            menuToggle.setSelected(false);
            Thread th = new Thread(){
                public void run(){
                    try{
                        for(int i=259;i>=210;i=i-15){
                            Thread.sleep(1);
                            i--;
                            slideMenuPane.setBounds(slideMenuPane.getX(), slideMenuPane.getY(), i, slideMenuPane.getHeight());
                        }
                        for(int i=210;i>=110;i=i-35){
                            Thread.sleep(1);
                            i--;
                            slideMenuPane.setBounds(slideMenuPane.getX(), slideMenuPane.getY(), i, slideMenuPane.getHeight());
                        }
                        for(int i=110;i>=60;i=i-5){
                            Thread.sleep(1);
                            i--;
                            slideMenuPane.setBounds(slideMenuPane.getX(), slideMenuPane.getY(), i, slideMenuPane.getHeight());
                        }
                    }catch(Exception e){
                        System.out.println(e);
                    }
                }
            };
            th.start();
        }
        else{
            menuToggle.setSelected(true);
            Thread th = new Thread(){
                public void run(){
                    try{
                        for(int i=61;i<=110;i=i+15){
                            Thread.sleep(1);
                            i++;
                            slideMenuPane.setBounds(slideMenuPane.getX(), slideMenuPane.getY(), i, slideMenuPane.getHeight());
                        }
                        for(int i=110;i<=210;i=i+35){
                            Thread.sleep(1);
                            i++;
                            slideMenuPane.setBounds(slideMenuPane.getX(), slideMenuPane.getY(), i, slideMenuPane.getHeight());
                        }
                        for(int i=210;i<=260;i=i+5){
                            Thread.sleep(1);
                            i++;
                            slideMenuPane.setBounds(slideMenuPane.getX(), slideMenuPane.getY(), i, slideMenuPane.getHeight());
                        }
                    }catch(Exception e){
                        System.out.println(e);
                    }
                }
            };
            th.start();
        }
    }

where menuToggle (contained in Other Components) is just used to know if the menu bar is already opened.
In effect this something like this:

However, when I click the menu icon button, there is a blink before the animation starts, it shows the menu bar with its width to be 60px and it lasts for a millisecond.
Is there anyway I can remove the blink?


问:
React: Module not found: Can't resolve 'react-html-parser'
I am trying to install react-html-parser in my docker container 'client':

```<code>docker-compose.yml
client/
      Dockerfile-dev
      node_modules/
      src/
         components/
                   Seeds.jsx
</code>```

and try and import it here:

Seeds.jsx

```<code>import React, { Component } from 'react';
import ReactHtmlParser, { processNodes, convertNodeToElement, htmlparser2 }
from 'react-html-parser';
import axios from 'axios';
</code>```

'axios' and 'react' are instaled allright, but not 'react-html-parser'. Console logs me the error:

```<code>index.js:1437 ./src/components/Seeds.jsx
Module not found: Can't resolve 'react-html-parser' in '/usr/src/app/src/components'
</code>```

package.json

```<code>{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "axios": "^0.18.0",
    "react": "^16.8.2",
    "react-dom": "^16.8.2",
    "react-router-dom": "^4.3.1",
    "react-scripts": "2.1.5",
    "react-html-parser":"^2.0.2", # <---------NEW
    "spotify-web-api-js": "^0.22.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ],
  "devDependencies": {
    "enzyme": "^3.8.0",
    "enzyme-adapter-react-16": "^1.7.1"
  }
}
</code>```

Dockerfile-dev

```<code># base image
FROM node:11.6.0-alpine

# set working directory
WORKDIR /usr/src/app

# add `/usr/src/app/node_modules/.bin` to $PATH
ENV PATH /usr/src/app/node_modules/.bin:$PATH

# install and cache app dependencies
COPY package.json /usr/src/app/package.json

RUN npm install --silent
RUN npm install react-scripts@2.1.2 -g --silent

# start app
CMD ["npm", "start"]
</code>```

docker-compose.yml

```<code>  client:
    build:
      context: ./services/client
      dockerfile: Dockerfile-dev
    volumes:
      - './services/client:/usr/src/app'
      - '/usr/src/app/node_modules'
    ports:
      - 3000:3000
    environment:
      - NODE_ENV=development
      - REACT_APP_WEB_SERVICE_URL=${REACT_APP_WEB_SERVICE_URL}
    depends_on:
      - web
</code>```

I can'f find the module inside my node_modules folder...

what am I missing here?

EDIT: npm install without --silent:

```<code>npm WARN deprecated fsevents@1.2.4: Way too old
npm WARN deprecated core-js@2.6.4: core-js@<2.6.8 is no longer maintained. Please, upgrade to core-js@3 or at least to actual version of core-js@2.
npm WARN deprecated joi@11.4.0: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated circular-json@0.3.3: CircularJSON is in maintenance only, flatted is its successor.
npm WARN deprecated kleur@2.0.2: Please upgrade to kleur@3 or migrate to 'ansi-colors' if you prefer the old syntax. Visit <https://github.com/lukeed/kleur/releases/tag/v3.0.0\> for migration path(s).
npm WARN deprecated flatten@1.0.2: I wrote this module a very long time ago; you should use something else.
npm WARN deprecated hoek@4.2.1: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated topo@2.0.2: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated left-pad@1.3.0: use String.prototype.padStart()

> core-js@2.6.9 postinstall /usr/src/app/node_modules/core-js
> node scripts/postinstall || echo "ignore"

Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!

The project needs your help! Please consider supporting of core-js on Open Collective or Patreon:
> https://opencollective.com/core-js
> https://www.patreon.com/zloirock

Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)

> core-js-pure@3.1.3 postinstall /usr/src/app/node_modules/core-js-pure
> node scripts/postinstall || echo "ignore"

Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!

The project needs your help! Please consider supporting of core-js on Open Collective or Patreon:
> https://opencollective.com/core-js
> https://www.patreon.com/zloirock

Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)

npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN ts-pnp@1.1.2 requires a peer of typescript@* but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules/chokidar/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
</code>```

答:
When your docker-compose.yml file says:

```<code>volumes:
  - '/usr/src/app/node_modules'
</code>```

You're telling Docker your node_modules directory contains critical data that needs to be persisted across container runs.  The first time you launch the container it will get populated from the image, but because that directory contains critical data, Docker will never ever update it again, even if you try to npm install additional modules.

For a near-term workaround, it's enough to docker-compose stop; docker-compose rm; docker-compose up --build your containers.  Deleting the existing container (and its anonymous volume) is important.

Body:
I am trying to install react-html-parser in my docker container 'client':

docker-compose.yml
client/
      Dockerfile-dev
      node_modules/
      src/
         components/
                   Seeds.jsx

and try and import it here:

Seeds.jsx

import React, { Component } from 'react';
import ReactHtmlParser, { processNodes, convertNodeToElement, htmlparser2 }
from 'react-html-parser';
import axios from 'axios';

'axios' and 'react' are instaled allright, but not 'react-html-parser'. Console logs me the error:

index.js:1437 ./src/components/Seeds.jsx
Module not found: Can't resolve 'react-html-parser' in '/usr/src/app/src/components'

package.json

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "axios": "^0.18.0",
    "react": "^16.8.2",
    "react-dom": "^16.8.2",
    "react-router-dom": "^4.3.1",
    "react-scripts": "2.1.5",
    "react-html-parser":"^2.0.2", # <---------NEW
    "spotify-web-api-js": "^0.22.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ],
  "devDependencies": {
    "enzyme": "^3.8.0",
    "enzyme-adapter-react-16": "^1.7.1"
  }
}

Dockerfile-dev

# base image
FROM node:11.6.0-alpine

# set working directory
WORKDIR /usr/src/app

# add `/usr/src/app/node_modules/.bin` to $PATH
ENV PATH /usr/src/app/node_modules/.bin:$PATH

# install and cache app dependencies
COPY package.json /usr/src/app/package.json

RUN npm install --silent
RUN npm install react-scripts@2.1.2 -g --silent

# start app
CMD ["npm", "start"]

docker-compose.yml

  client:
    build:
      context: ./services/client
      dockerfile: Dockerfile-dev
    volumes:
      - './services/client:/usr/src/app'
      - '/usr/src/app/node_modules'
    ports:
      - 3000:3000
    environment:
      - NODE_ENV=development
      - REACT_APP_WEB_SERVICE_URL=${REACT_APP_WEB_SERVICE_URL}
    depends_on:
      - web

I can'f find the module inside my node_modules folder...

what am I missing here?

EDIT: npm install without --silent:

npm WARN deprecated fsevents@1.2.4: Way too old
npm WARN deprecated core-js@2.6.4: core-js@<2.6.8 is no longer maintained. Please, upgrade to core-js@3 or at least to actual version of core-js@2.
npm WARN deprecated joi@11.4.0: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated circular-json@0.3.3: CircularJSON is in maintenance only, flatted is its successor.
npm WARN deprecated kleur@2.0.2: Please upgrade to kleur@3 or migrate to 'ansi-colors' if you prefer the old syntax. Visit <https://github.com/lukeed/kleur/releases/tag/v3.0.0\> for migration path(s).
npm WARN deprecated flatten@1.0.2: I wrote this module a very long time ago; you should use something else.
npm WARN deprecated hoek@4.2.1: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated topo@2.0.2: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated left-pad@1.3.0: use String.prototype.padStart()

> core-js@2.6.9 postinstall /usr/src/app/node_modules/core-js
> node scripts/postinstall || echo "ignore"

Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!

The project needs your help! Please consider supporting of core-js on Open Collective or Patreon:
> https://opencollective.com/core-js
> https://www.patreon.com/zloirock

Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)

> core-js-pure@3.1.3 postinstall /usr/src/app/node_modules/core-js-pure
> node scripts/postinstall || echo "ignore"

Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!

The project needs your help! Please consider supporting of core-js on Open Collective or Patreon:
> https://opencollective.com/core-js
> https://www.patreon.com/zloirock

Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)

npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN ts-pnp@1.1.2 requires a peer of typescript@* but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules/chokidar/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

Body:
When your docker-compose.yml file says:

volumes:
  - '/usr/src/app/node_modules'

You're telling Docker your node_modules directory contains critical data that needs to be persisted across container runs.  The first time you launch the container it will get populated from the image, but because that directory contains critical data, Docker will never ever update it again, even if you try to npm install additional modules.

For a near-term workaround, it's enough to docker-compose stop; docker-compose rm; docker-compose up --build your containers.  Deleting the existing container (and its anonymous volume) is important.


问:
Value of type 'error' has no member 'userinfo'
My code is as follows:

```<code>if signupMode {
    let user = PFUser()
    user.username = emailTextField.text
    user.email = emailTextField.text
    user.password = passwordTextField.text
    user.signUpInBackground(block: {
       (success, error) in

if error != nil {

    let displayErrorMessage = "Please try again later"

    if let errorMessage = error.UserInfo["error"]? as String {
        displayErrorMessage = errorMessage
    }

self.createAlert(title: "Error", message: "Parse Error")
}
</code>```

I just keep getting the error

"value of type 'error' has no member 'userinfo"

What can I do to fix this? I'm using Xcode 8

答:
If you're still getting this error, try this code. Force unwrap error as NSError.</p>

```<code>if let errorMessage = (error! as NSError).userInfo["error"] as? String {
    displayErrorMessage = errorMessage
}
</code>```

Body:
My code is as follows:

if signupMode {
    let user = PFUser()
    user.username = emailTextField.text
    user.email = emailTextField.text
    user.password = passwordTextField.text
    user.signUpInBackground(block: {
       (success, error) in

if error != nil {

    let displayErrorMessage = "Please try again later"

    if let errorMessage = error.UserInfo["error"]? as String {
        displayErrorMessage = errorMessage
    }

self.createAlert(title: "Error", message: "Parse Error")
}

I just keep getting the error

"value of type 'error' has no member 'userinfo"

What can I do to fix this? I'm using Xcode 8

Body:
If you're still getting this error, try this code. Force unwrap error as NSError.

if let errorMessage = (error! as NSError).userInfo["error"] as? String {
    displayErrorMessage = errorMessage
}


问:
How to install Azure Az - Cannot convert value "2.0.0-preview" to type "System.Version"
I get the following Exception when I try to install Azure Az with PowerShell:

PowerShell 5.1 and .NET is installed. All AzureRM, Azure and Azure Az Modules which where previously installed are now uninstalled.

I tried different versions, with clobber and without, with force and without and I also executed the commands in an admin powershell.
For example:

Install-Module -Name Az -AllowClobber

Install-Module -Name Az -RequiredVersion 2.0.0

I had Azure Az already installed on this computer but had to uninstall it. I uninstalled it with this script by Microsoft.

答:
Skimmed through script you used for cleanup and i am confused.

but this should fix issue. Check for all installed AZ module and manually remove them by deleting the folders from machine.  Once the are all gone try re-installing

10 out of 10 times that resolves my module issues.


问:
Is the MS Ribbon/Office UI License worth worrying about?
Imagine I want to create an application which is very similar to MS Word 2007, using C++ in VS2008 and the MFC Feature Pack. For the ribbon, there are 3 options available to me:

Use the ribbon from MFC Feature Pack without acquiring a license.

Probably dodgy in the long run. You're all right until your product becomes a global success, at which point MS Legal send the heavies round. But could they really do anything about it?

Use the ribbon from MFC Feature Pack, but try to acquire a license.

I believe that if I should try to register an Office UI License, the chances are that I would be turned down because it is a competing product:

The license is available for applications on any platform, except for applications that compete directly with the five Office applications that currently have the new UI (Microsoft Word, Excel, PowerPoint, Outlook, and Access).

Use a 3rd party ribbon control.

If I were to buy a license of the BCGControlBar Library for about £500 from BCGSoft -- whose ribbon bar is used by MS in the MFC Feature Pack -- then I could use the ribbon in my app with no problem.

I don't want to spend any money unless absolutely necessary. How about if I use option #1 until I get hassled about it, at which point I could ditch it and go for #3? Would it be too late?

Of course all the above is hypothetical... ;)

Note: I don't care about any patents or copyrights relating to the similarity between my product and Word, that's just an example. This question is only concerned with the ribbon licensing aspect.

答:
IMO, if you're saying that you probably would be specifically denied a license due to the product similarity, proceeding anyway without a license probably isn't going to turn out well for you if Microsoft ever catches wind of it.

I would go with Option 3 to be safe.

OwnerDisplayName: demoncodemonkey

OwnerDisplayName: rmz


问:
How to find occurence of objects in an array
I need to know if an array of objects contains at least two same objects in it, in JavaScript.

I have a form that allow people to create questions (title, description, type, answer options). I need to check whether the user has entered multiple answer options with the same label. They are stored in an array.

```<code>// The array of answer options
let array = [{value: 'a'}, {value: 'b'}, {value: 'c'}, {value: 'a'}]
</code>```

I tried using array.indexOf({value: 'a'}) and array.lastIndexOf({value: 'a'}) but they both give me an index of -1.

答:
If you are only concerned about the value property and you use case is not more complex and you can simply do this in one line via:

let hasDupes = arr => new Set(arr.map(x => x.value)).size !== arr.length

console.log(hasDupes([{value: 'a'}, {value: 'b'}, {value: 'c'},{value: 'a'}]))
console.log(hasDupes([{value: 'a'}, {value: 'b'}, {value: 'c'}]))```

You would use Set to add the values of value and if the size of it is smaller than the actual input array length than you had duplicates. There is no need to do JSON.stringify, compare strings etc if you only care about that one property being checked.

Also JSON.stringify has issues when comparing equality of objects.

Body:
I need to know if an array of objects contains at least two same objects in it, in JavaScript.

I have a form that allow people to create questions (title, description, type, answer options). I need to check whether the user has entered multiple answer options with the same label. They are stored in an array.

// The array of answer options
let array = [{value: 'a'}, {value: 'b'}, {value: 'c'}, {value: 'a'}]

I tried using array.indexOf({value: 'a'}) and array.lastIndexOf({value: 'a'}) but they both give me an index of -1.

Body:
If you are only concerned about the value property and you use case is not more complex and you can simply do this in one line via:

let hasDupes = arr => new Set(arr.map(x => x.value)).size !== arr.length

console.log(hasDupes([{value: 'a'}, {value: 'b'}, {value: 'c'},{value: 'a'}]))
console.log(hasDupes([{value: 'a'}, {value: 'b'}, {value: 'c'}]))

You would use Set to add the values of value and if the size of it is smaller than the actual input array length than you had duplicates. There is no need to do JSON.stringify, compare strings etc if you only care about that one property being checked.

Also JSON.stringify has issues when comparing equality of objects.


问:
Bison: Reduce/reduce conflict on non-tokens
So I'm in the process of making a compiler for C-- and I'm currently making literal, variable and function tables.

And this rule is giving me a reduce/reduce conflict:

```<code>lval: ID { check_var(); }
| ID { check_var(); } LBRACK NUM RBRACK
| ID { check_var(); } LBRACK ID { check_var(); } RBRACK;
</code>```

Error is the following:

```<code>parser.y: warning: 1 reduce/reduce conflict [-Wconflicts-rr]
parser.y:104.6-21: warning: rule useless in parser due to conflicts [-Wother]
 | ID { check_var(); } LBRACK ID { check_var(); } RBRACK;
      ^^^^^^^^^^^^^^^^
</code>```

I have precendece rules to avoid reduce errors on tokens, but now it's pointing to a non token, so not sure what I'm supposed to do?

If it helps by any chance these are my precedence rules:

```<code>%token INPUT OUTPUT WRITE
%token  RETURN VOID IF ELSE WHILE ASSIGN SEMI COMMA
%token LPAREN RPAREN LBRACE RBRACE LBRACK RBRACK
%token NUM ID STRING INT
%left EQ NEQ GE LE GT LT
%left PLUS MINUS
%left TIMES OVER
</code>```

答:
Bison does not check for whether two custom code blocks within your syntax are identical. So it treats your grammar as basically:

```<code>lval: ID action_1
    | ID action_2 LBRACK NUM RBRACK
    | ID action_3 LBRACK ID action_4 RBRACK
;
</code>```

And Bison (by default) acts as an LALR(1) parser, meaning it only looks ahead one token before making decisions. So when it sees that the top of the stack is an ID token and the look-ahead token is an LBRACK token, it can't decide whether it should execute action_2 or action_3, not realizing it doesn't actually matter.

Solve this by using a subrule to combine the common thing that should happen when an ID is followed by an LBRACK (and also in other situations):

```<code>id_with_check: ID { check_var(); } ;

lval: id_with_check
    | id_with_check LBRACK NUM RBRACK
    | id_with_check LBRACK id_with_check RBRACK
;
</code>```

Body:
So I'm in the process of making a compiler for C-- and I'm currently making literal, variable and function tables.

And this rule is giving me a reduce/reduce conflict:

lval: ID { check_var(); }
| ID { check_var(); } LBRACK NUM RBRACK
| ID { check_var(); } LBRACK ID { check_var(); } RBRACK;

Error is the following:

parser.y: warning: 1 reduce/reduce conflict [-Wconflicts-rr]
parser.y:104.6-21: warning: rule useless in parser due to conflicts [-Wother]
 | ID { check_var(); } LBRACK ID { check_var(); } RBRACK;
      ^^^^^^^^^^^^^^^^

I have precendece rules to avoid reduce errors on tokens, but now it's pointing to a non token, so not sure what I'm supposed to do?

If it helps by any chance these are my precedence rules:

%token INPUT OUTPUT WRITE
%token  RETURN VOID IF ELSE WHILE ASSIGN SEMI COMMA
%token LPAREN RPAREN LBRACE RBRACE LBRACK RBRACK
%token NUM ID STRING INT
%left EQ NEQ GE LE GT LT
%left PLUS MINUS
%left TIMES OVER

Body:
Bison does not check for whether two custom code blocks within your syntax are identical. So it treats your grammar as basically:

lval: ID action_1
    | ID action_2 LBRACK NUM RBRACK
    | ID action_3 LBRACK ID action_4 RBRACK
;

And Bison (by default) acts as an LALR(1) parser, meaning it only looks ahead one token before making decisions. So when it sees that the top of the stack is an ID token and the look-ahead token is an LBRACK token, it can't decide whether it should execute action_2 or action_3, not realizing it doesn't actually matter.

Solve this by using a subrule to combine the common thing that should happen when an ID is followed by an LBRACK (and also in other situations):

id_with_check: ID { check_var(); } ;

lval: id_with_check
    | id_with_check LBRACK NUM RBRACK
    | id_with_check LBRACK id_with_check RBRACK
;


问:
RNFirebase core module was not found natively on Android, ensure you have correctly added the RNFirebase and Firebase gradle dependencies
I have this strange error for a hours and I can't fix it. I have all dependencies that I need.

Error

```<code>dependencies {
    implementation project(':react-native-firebase')
    implementation project(':react-native-code-push')
    implementation project(':react-native-sentry')
    implementation project(':react-native-vector-icons')
    implementation project(':react-native-iap')
    implementation project(':react-native-amplitude-analytics')
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.facebook.react:react-native:+"  // From node_modules
    implementation "com.google.android.gms:play-services-base:16.0.1"
    implementation "com.google.firebase:firebase-core:16.0.6"
    implementation "com.google.firebase:firebase-ads:15.0.1"
    implementation "com.google.firebase:firebase-config:16.1.2"
    implementation "com.google.firebase:firebase-messaging:17.3.4"

    implementation "com.google.firebase:firebase-auth:9.6.1"
    implementation "com.google.firebase:firebase-database:9.6.1"

    implementation "com.google.firebase:firebase-messaging:17.3.0"
    implementation "com.google.firebase:firebase-core:16.0.3"
    implementation "com.google.firebase:firebase-auth:16.0.3"
    implementation "com.google.firebase:firebase-database:16.0.1"
}
</code>```

答:
Ensure you have included this line in MainApplication.java

```<code>import io.invertase.firebase.RNFirebasePackage;
</code>```

and

```<code> @Override
protected List<ReactPackage> getPackages() {
  return Arrays.<ReactPackage>asList(
      new MainReactPackage(),
      new RNFirebasePackage(), <----- this
  );
}
</code>```

Body:
I have this strange error for a hours and I can't fix it. I have all dependencies that I need.

Error

dependencies {
    implementation project(':react-native-firebase')
    implementation project(':react-native-code-push')
    implementation project(':react-native-sentry')
    implementation project(':react-native-vector-icons')
    implementation project(':react-native-iap')
    implementation project(':react-native-amplitude-analytics')
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.facebook.react:react-native:+"  // From node_modules
    implementation "com.google.android.gms:play-services-base:16.0.1"
    implementation "com.google.firebase:firebase-core:16.0.6"
    implementation "com.google.firebase:firebase-ads:15.0.1"
    implementation "com.google.firebase:firebase-config:16.1.2"
    implementation "com.google.firebase:firebase-messaging:17.3.4"

    implementation "com.google.firebase:firebase-auth:9.6.1"
    implementation "com.google.firebase:firebase-database:9.6.1"

    implementation "com.google.firebase:firebase-messaging:17.3.0"
    implementation "com.google.firebase:firebase-core:16.0.3"
    implementation "com.google.firebase:firebase-auth:16.0.3"
    implementation "com.google.firebase:firebase-database:16.0.1"
}

Body:
Ensure you have included this line in MainApplication.java

import io.invertase.firebase.RNFirebasePackage;

and

 @Override
protected List<ReactPackage> getPackages() {
  return Arrays.<ReactPackage>asList(
      new MainReactPackage(),
      new RNFirebasePackage(), <----- this
  );
}


问:
SVG element not receiving onclick in Chrome
I am writing a javascript application for Chrome Version 66.0.3359.139 (and maybe other versions eventually). I am trying to make SVG elements that are clickable. I.e., their onclick methods should be called when they are clicked.

Here is my first attempt:

<svg id="svg" width="100%" height="100%"></svg>

```
</div>
</div>
</p>

<p>This code creates one circle at the top of the page, and one at the bottom. The circles are also recalculated when the page resizes, so that they are always visible. As a test, I want to delete the circle when it is clicked.</p>

<p>Sometimes the above code works. However, when I run it full screen, after opening developer tools at the bottom of the window, and then closing the developer tools, then the bottom circle cannot be clicked -- until after the next time I either zoom or resize the window.</p>

<p>I thought maybe it was a browser bug because it shows up when I use developer tools as described above, and does not occur at all in Firefox. However then I noticed that other websites do not have this problem. Besides it can't be that easy to find a browser bug, as so many sites work in Chrome.</p>

<p>Does anyone see a problem with my Javascript code that could be making the bottom circle fail to receive <code>onclick</code> events?</p>

<p><strong>update</strong></p>

<p>I cannot reproduce this problem in Chrome Version 74.0.3729.169 Linux or Windows. It may be specific to Linux chrome Version 66.0.3359.139.</p>

<p>However, that still doesn't mean it's a browser bug... should the code work or not?</p>

<p><strong>update</strong></p>

<p>The problem is also reproducible in Linux Chrome Version 66.0.3359.181. I am having difficulty downgrading to 66.0.3359.139 (I can't find the deb. Google can be annoying that way). So I am now targeting 66.0.3359.181.</p>

<p><strong>update</strong></p>

<p>The present problem seems to be caused by</p>

```
```

<p>If that style is removed, then the present problem does not occur, but another problem occurs. The present problem occurs equally with:</p>

```
```

<p>This is the case both in my version and the D3 version posted by Dataminion.</p>

<p>So we really have a lump under the rug here... we can step on it but it causes a lump somewhere else. Solve the events, but then SVG can't fill the page. Solve both of the above, but upgrade browser (and deal with a new set of bugs).</p>

<p><strong>update</strong></p>

<p>It works with</p>

```
```

<p>with the only drawbacks being the svg is 1 pixel off, and there is an unwanted scrollbar. Note that:</p>

```
```

removes the scrollbar and reintroduces the bug.

So either overflow:hidden or margin:0 causes the problem. Either of these removes the scrollbar. So the problem is related to there not being a scrollbar (regardless of how it is removed).

答:
Why don’t you try a parent div for that svg element? It should work.

Cheer,

Body:
I am writing a javascript application for Chrome Version 66.0.3359.139 (and maybe other versions eventually). I am trying to make SVG elements that are clickable. I.e., their onclick methods should be called when they are clicked.

Here is my first attempt:

<svg id="svg" width="100%" height="100%"></svg>

This code creates one circle at the top of the page, and one at the bottom. The circles are also recalculated when the page resizes, so that they are always visible. As a test, I want to delete the circle when it is clicked.

Sometimes the above code works. However, when I run it full screen, after opening developer tools at the bottom of the window, and then closing the developer tools, then the bottom circle cannot be clicked -- until after the next time I either zoom or resize the window.

I thought maybe it was a browser bug because it shows up when I use developer tools as described above, and does not occur at all in Firefox. However then I noticed that other websites do not have this problem. Besides it can't be that easy to find a browser bug, as so many sites work in Chrome.

Does anyone see a problem with my Javascript code that could be making the bottom circle fail to receive onclick events?

update

I cannot reproduce this problem in Chrome Version 74.0.3729.169 Linux or Windows. It may be specific to Linux chrome Version 66.0.3359.139.

However, that still doesn't mean it's a browser bug... should the code work or not?

update

The problem is also reproducible in Linux Chrome Version 66.0.3359.181. I am having difficulty downgrading to 66.0.3359.139 (I can't find the deb. Google can be annoying that way). So I am now targeting 66.0.3359.181.

update

The present problem seems to be caused by

If that style is removed, then the present problem does not occur, but another problem occurs. The present problem occurs equally with:

This is the case both in my version and the D3 version posted by Dataminion.

So we really have a lump under the rug here... we can step on it but it causes a lump somewhere else. Solve the events, but then SVG can't fill the page. Solve both of the above, but upgrade browser (and deal with a new set of bugs).

update

It works with

with the only drawbacks being the svg is 1 pixel off, and there is an unwanted scrollbar. Note that:

removes the scrollbar and reintroduces the bug.

So either overflow:hidden or margin:0 causes the problem. Either of these removes the scrollbar. So the problem is related to there not being a scrollbar (regardless of how it is removed).