问:
Block Scoped Function ECMAScript 6 Strange Behaviour
I was reading the new features in ECMA6. One of the new features is Block Scoped Functions . That means we can have a same name for functions in different blocks. As in the code below block1 foo() logs 1 then similarly block2 foo() logs 2 and block0 foo() or global scope logs 4. And that is the expected result. But what i can't understand is that Why does the last console.log(foo()) logs 1 and not 4 because it is under block0 or global scope instead it logs 1 which is block1 foo().

//block0
function foo () { return 4 }
console.log(foo());//will log 4
{
  //block1
    function foo () { return 1 }
    console.log(foo());//will log 1
    {
    //block2
        function foo () { return 2 }//a block level function
        console.log(foo());//will log 2
    }
    console.log(foo());//will again log 1
}
console.log(foo());//should log 4 but logs 1 why?```
</div>
</div>
</p>

<p>Now again if I enclose the above code into a another block it works as expected. This is a bit confusing to me. What actually is causing this behviour?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{//block0
function foo () { return 4 }
console.log(foo());//will log 4
{
  //block1
    function foo () { return 1 }
    console.log(foo());//will log 1
    {
    //block2
        function foo () { return 2 }
        console.log(foo());//will log 2
    }
    console.log(foo());//will again log 1
}
console.log(foo());//will log 4 but
}</code>```

答:
Fully amended answer for in-depth explanation

First things first: the problem appears because you are not using use strict mode. What is the difference in strict and non-strict mode in this case? The difference is the way simple block scoping is treated.

In both modes a brackets block creates a scope. Declarations inside that scope can be viewed inside the scope itself and inside further enclosed scopes.

```<code>{ // level 1 scope
  function asdf() {alert("asdf");}
  { // level 2 scope
    asdf(); // Yay I can use it!
  }
}
</code>```

However, in ES5 and in ES6 non strict, a simple block scope is not treated as a true enclosing scope. Declarations inside a simple block scope get hoisted all the way up to the first true enclosing scope they can find. In those cases, a true enclosing scope is either a function's scope or the global scope.

The above example, in non strict mode is equivalent to this:

```<code>var asdf0 = undefined; // Haha! The declaration has been hoisted up to the global scope!
{ // level 1 scope
  function asdf1() {alert("asdf");}
  asdf0 = asdf1; // The definition is ready and will be assigned to its declaration
  { // level 2 scope
    asdf1(); // Yay I can use it!
  }
}
asdf0(); // Damn! I have access outside of the block scope due to hoisting! Should have used strict mode...
</code>```

If we enclose the previous logic into a function however, we don't get hoisting to the global scope, only up to the function's scope.

```<code>function scopeBlocker() {
  var asdf0 = undefined;
  ...
  ...
}
asdf0(); // Exception! Wasn't hoisted all the way up to the global scope!
</code>```

Now, to come to your example, because you were not using strict mode you fell into the trap of old block scoping. In your first attempt, the second declaration inside the first block scope was hoisted all the way up to its enclosing scope and replaced the first foo declaration. Now because hoisting happens only once, the following declarations were not hoisted thus not replacing anything. In the second case, adding the top level block scope forced the first foo declaration to be hoisted to the global enclosing scope and thus the second foo declaration was now not hoisted because the foo name had already been hoisted.

It is indeed a weird behavior, but I believe that's what's happening here.

Body:
I was reading the new features in ECMA6. One of the new features is Block Scoped Functions . That means we can have a same name for functions in different blocks. As in the code below block1 foo() logs 1 then similarly block2 foo() logs 2 and block0 foo() or global scope logs 4. And that is the expected result. But what i can't understand is that Why does the last console.log(foo()) logs 1 and not 4 because it is under block0 or global scope instead it logs 1 which is block1 foo().

//block0
function foo () { return 4 }
console.log(foo());//will log 4
{
  //block1
    function foo () { return 1 }
    console.log(foo());//will log 1
    {
    //block2
        function foo () { return 2 }//a block level function
        console.log(foo());//will log 2
    }
    console.log(foo());//will again log 1
}
console.log(foo());//should log 4 but logs 1 why?

Now again if I enclose the above code into a another block it works as expected. This is a bit confusing to me. What actually is causing this behviour?

{//block0
function foo () { return 4 }
console.log(foo());//will log 4
{
  //block1
    function foo () { return 1 }
    console.log(foo());//will log 1
    {
    //block2
        function foo () { return 2 }
        console.log(foo());//will log 2
    }
    console.log(foo());//will again log 1
}
console.log(foo());//will log 4 but
}

Body:
Fully amended answer for in-depth explanation

First things first: the problem appears because you are not using use strict mode. What is the difference in strict and non-strict mode in this case? The difference is the way simple block scoping is treated.

In both modes a brackets block creates a scope. Declarations inside that scope can be viewed inside the scope itself and inside further enclosed scopes.

{ // level 1 scope
  function asdf() {alert("asdf");}
  { // level 2 scope
    asdf(); // Yay I can use it!
  }
}

However, in ES5 and in ES6 non strict, a simple block scope is not treated as a true enclosing scope. Declarations inside a simple block scope get hoisted all the way up to the first true enclosing scope they can find. In those cases, a true enclosing scope is either a function's scope or the global scope.

The above example, in non strict mode is equivalent to this:

var asdf0 = undefined; // Haha! The declaration has been hoisted up to the global scope!
{ // level 1 scope
  function asdf1() {alert("asdf");}
  asdf0 = asdf1; // The definition is ready and will be assigned to its declaration
  { // level 2 scope
    asdf1(); // Yay I can use it!
  }
}
asdf0(); // Damn! I have access outside of the block scope due to hoisting! Should have used strict mode...

If we enclose the previous logic into a function however, we don't get hoisting to the global scope, only up to the function's scope.

function scopeBlocker() {
  var asdf0 = undefined;
  ...
  ...
}
asdf0(); // Exception! Wasn't hoisted all the way up to the global scope!

Now, to come to your example, because you were not using strict mode you fell into the trap of old block scoping. In your first attempt, the second declaration inside the first block scope was hoisted all the way up to its enclosing scope and replaced the first foo declaration. Now because hoisting happens only once, the following declarations were not hoisted thus not replacing anything. In the second case, adding the top level block scope forced the first foo declaration to be hoisted to the global enclosing scope and thus the second foo declaration was now not hoisted because the foo name had already been hoisted.

It is indeed a weird behavior, but I believe that's what's happening here.


来源: stackexchange

问:
Add to the beginning of Reactive Forms Array Angular
Please see the relevant plunker

https://plnkr.co/edit/f0BxpinhuqVz8o6IIFaL?p=preview

```<code>stack overflow makes you put code if a plunker is linked
but it is too much code to copy paste here it would just
look messy so I a am putting this comment instead.
</code>```

If you run this and then click the add button a new entry is added to the array, but the form view does not reflect the forms state, instead the first entry is duplicated and the last entry is gone.

If anyone has any ideas or guides as to what I am doing wrong I would be very grateful as I have been pretty stuck on a seemingly easy task.

I tried to follow the official Angular Reactive Forms guide as close as possible to build this example.

答:
Seems like Angular has trouble tracking the index of your objects in your formArray. This can be solved by using trackBy. Add it to your iteration with function:

```<code><div *ngFor="let detail of detailArray.controls; let i=index; trackBy:trackByFn" [formGroupName]="i">
</code>```

and in component:

```<code>trackByFn(index: any, item: any) {
  return index;
}
</code>```

Your PLUNKER

ContentLicense: CC BY-SA 4.0

Body:
Please see the relevant plunker

https://plnkr.co/edit/f0BxpinhuqVz8o6IIFaL?p=preview

stack overflow makes you put code if a plunker is linked
but it is too much code to copy paste here it would just
look messy so I a am putting this comment instead.

If you run this and then click the add button a new entry is added to the array, but the form view does not reflect the forms state, instead the first entry is duplicated and the last entry is gone.

If anyone has any ideas or guides as to what I am doing wrong I would be very grateful as I have been pretty stuck on a seemingly easy task.

I tried to follow the official Angular Reactive Forms guide as close as possible to build this example.

Body:
Seems like Angular has trouble tracking the index of your objects in your formArray. This can be solved by using trackBy. Add it to your iteration with function:

<div *ngFor="let detail of detailArray.controls; let i=index; trackBy:trackByFn" [formGroupName]="i">

and in component:

trackByFn(index: any, item: any) {
  return index;
}

Your PLUNKER

ContentLicense: CC BY-SA 3.0


问:
Get HTML with current input values
I need to get the HTML of the whole page, with the current values of all inputs in their value="...".

I've tried this:

```<code>document.getElementById("htmlId").innerHTML;
</code>```

and this:

```<code>$('html').html();
</code>```

but the both return the HTML page but without the input values.

I know that this looks like this other question, but it is not the same. I really need get the HTML with the value attributes.

答:
As commented before,

.html() or innerHTML will return the markup. value is a property associated with input elements. Yes you have a tag, but eventually you end you initiating this property. So when you change value dynamically, it updates property and not attribute

You will have to loop over all the inputs and set value attribute.

function updateAttribute() {
  var parent = document.querySelector(".content");
  var inputs = parent.querySelectorAll("input");

  for (var i = 0; i < inputs.length; i++) {
    inputs[i].setAttribute("value", inputs[i].value);
  }
}
```

Working Demo

Title: Get HTML with current input values

Body:
I need to get the HTML of the whole page, with the current values of all inputs in their value="...".

I've tried this:

document.getElementById("htmlId").innerHTML;

and this:

$('html').html();

but the both return the HTML page but without the input values.

I know that this looks like this other question, but it is not the same. I really need get the HTML with the value attributes.

Body:
As commented before,

.html() or innerHTML will return the markup. value is a property associated with input elements. Yes you have a tag, but eventually you end you initiating this property. So when you change value dynamically, it updates property and not attribute

You will have to loop over all the inputs and set value attribute.

function updateAttribute() {
  var parent = document.querySelector(".content");
  var inputs = parent.querySelectorAll("input");

  for (var i = 0; i < inputs.length; i++) {
    inputs[i].setAttribute("value", inputs[i].value);
  }
}

Working Demo


问:
issue with column width
ISSUE DEMO

In HTML table, on select of an item in 1st row, 2nd row is made visible(Table has 2 columns).

Now here in 2nd row, column width is shrinked which is highlighted in blue. Why is that so?

Have been trying to surf for couple of days but none seems to be working.

It would be helpful if anyone would point out what's wrong.

function showDiv(select){
   if(select.value==2){
    document.getElementById('future_date').style.display = "block";
   } else{
        document.getElementById('future_date').style.display = "none";
   }
} ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.table1 {
  color: #2a2929;
  padding-top: 20px;
  margin-bottom: 7px;
  text-align: center;
}

.col-md-12 {
  width: 100%;
}

.table1 table {
  width: 100%;
  text-align: center;
  padding: 10px;
  background-color: grey;
  padding-left: 10px;
  padding-right: 10px;
  margin-top: 25px;
}

.table-text-filed{
  width:100%;
  border:1px solid #d4d5d7;
  color:#2a2929;
  text-align: center;
}

.body {
  color: #fff;
  font-size: 18px;
  line-height: 23px;
  font-family: calibri;
}

.table1 td {
  padding: 5px;
  background-color: white;
}

.table1 tr {
  padding: 5px;
  background-color: blue;
}</code>```

        Type

            <select name="token_date_id" onchange="showDiv(this)" class="table-text-filed" required>
                <option value="1">Today</option>
                <option value="2">Future Date</option>
            </select>

        Select Date

            <input type="date" name="token_date" value="" class="table-text-filed" data-date='{"startView": 2}'>

```

答:
What i saw in the demo link is 2 column is showing but both 1 and 2 displayed one after another, not like table cell. the reason is you put display property to block. use table-row instead.

Replace the following line

```<code>document.getElementById('future_date').style.display = "block";
</code>```

With

```<code>document.getElementById('future_date').style.display = "table-row";
</code>```

Hope this helps.

Title: issue with column width

Body:
ISSUE DEMO

In HTML table, on select of an item in 1st row, 2nd row is made visible(Table has 2 columns).

Now here in 2nd row, column width is shrinked which is highlighted in blue. Why is that so?

Have been trying to surf for couple of days but none seems to be working.

It would be helpful if anyone would point out what's wrong.

function showDiv(select){
   if(select.value==2){
    document.getElementById('future_date').style.display = "block";
   } else{
        document.getElementById('future_date').style.display = "none";
   }
}

.table1 {
  color: #2a2929;
  padding-top: 20px;
  margin-bottom: 7px;
  text-align: center;
}

.col-md-12 {
  width: 100%;
}

.table1 table {
  width: 100%;
  text-align: center;
  padding: 10px;
  background-color: grey;
  padding-left: 10px;
  padding-right: 10px;
  margin-top: 25px;
}

.table-text-filed{
  width:100%;
  border:1px solid #d4d5d7;
  color:#2a2929;
  text-align: center;
}

.body {
  color: #fff;
  font-size: 18px;
  line-height: 23px;
  font-family: calibri;
}

.table1 td {
  padding: 5px;
  background-color: white;
}

.table1 tr {
  padding: 5px;
  background-color: blue;
}

        Type

            <select name="token_date_id" onchange="showDiv(this)" class="table-text-filed" required>
                <option value="1">Today</option>
                <option value="2">Future Date</option>
            </select>

        Select Date

            <input type="date" name="token_date" value="" class="table-text-filed" data-date='{"startView": 2}'>

Body:
What i saw in the demo link is 2 column is showing but both 1 and 2 displayed one after another, not like table cell. the reason is you put display property to block. use table-row instead.

Replace the following line

document.getElementById('future_date').style.display = "block";

With

document.getElementById('future_date').style.display = "table-row";

Hope this helps.


问:
octopack nuget package version
My nupkg file seem to version 1.0.0.0 no matter what I did.
I want to specify the version of the package using the version element inside my nuspec file as follow.

```<code><?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
    <metadata>
        <id>SpacePlanning.SavePlanogram</id>
        <version>1.0.1</version>
        <authors>Blah</authors>
    </metadata>
..
</package>
</code>```

My  msbuild  command is

```<code>MSBuild.exe "%WORKSPACE%\LoadPlanogram.sln" /t:Build /p:Configuration=Debug /p:OctopusPackageConfiguration=Debug /p:RunOctoPack=true /p:OctoPackEnforceAddingFiles=true /p:OctopusPackageVersion=1.0.0
</code>```

答:
The MSBuild parameter you're looking for is OctoPackPackageVersion, not OctopusPackageVersion.

I believe that what you're asking (specify a hardcoded version in the .nuspec file and use that) is not possible.

You can choose to specify the version through the MSBuild parameter mentioned above, or in the AssemblyInfo.cs file, using the AssemblyInformationalVersionAttribute or AssemblyVersionAttribute.

```<code>[assembly: AssemblyVersion("1.0.1")]
</code>```

or, if you want to create a pre-release package:

```<code>[assembly: AssemblyInformationalVersion("1.2.3-myhotfix+somemetadata")]
</code>```

You can read about the inner workings of OctoPack when it comes to versioning the package here: Using OctoPack Versioning

Title: octopack nuget package version

Body:
My nupkg file seem to version 1.0.0.0 no matter what I did.
I want to specify the version of the package using the version element inside my nuspec file as follow.

<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
    <metadata>
        <id>SpacePlanning.SavePlanogram</id>
        <version>1.0.1</version>
        <authors>Blah</authors>
    </metadata>
..
</package>

My  msbuild  command is

MSBuild.exe "%WORKSPACE%\LoadPlanogram.sln" /t:Build /p:Configuration=Debug /p:OctopusPackageConfiguration=Debug /p:RunOctoPack=true /p:OctoPackEnforceAddingFiles=true /p:OctopusPackageVersion=1.0.0

Body:
The MSBuild parameter you're looking for is OctoPackPackageVersion, not OctopusPackageVersion.

I believe that what you're asking (specify a hardcoded version in the .nuspec file and use that) is not possible.

You can choose to specify the version through the MSBuild parameter mentioned above, or in the AssemblyInfo.cs file, using the AssemblyInformationalVersionAttribute or AssemblyVersionAttribute.

[assembly: AssemblyVersion("1.0.1")]

or, if you want to create a pre-release package:

[assembly: AssemblyInformationalVersion("1.2.3-myhotfix+somemetadata")]

You can read about the inner workings of OctoPack when it comes to versioning the package here: Using OctoPack Versioning


问:
Optaplanner logging won't work correctly running from RestEasy server
I create RestEasy server which controls optaplanner. I sent requests to the server and that servers start optaplanner. When I start optaplanner from eclipse like normal application then logging works correctly, but when I run my server which starts optaplanner my logs looks like

```<code>2017-06-08 10:35:13,033 [123] INFO  VehicleRoutingSolution TMS_DATA has 1 depots, 20 vehicles and 70 customers with a search space of 10^25.
2017-06-08 10:35:13,034 [123] INFO  Imported: \\xxxx\xxxxx\xxx\xxxx.vrp
2017-06-08 10:35:13,740 [SwingWorker-pool-8-thread-1] INFO  Solving started: time spent (394), best score (70uninitialized/-42308000hard/0soft), environment mode (REPRODUCIBLE), random (JDK with seed 0).
2017-06-08 10:35:13,916 [SwingWorker-pool-8-thread-1] INFO  Custom phase (0) ended: step total (1), time spent (570), best score (-42308000hard/0soft).
2017-06-08 10:35:16,157 [SwingWorker-pool-8-thread-1] INFO  Construction Heuristic phase (1) ended: step total (50), time spent (2811), best score (-38400hard/-2911900soft).
2017-06-08 10:35:21,673 [AWT-EventQueue-0] INFO  Terminating solver early.
2017-06-08 10:35:21,675 [SwingWorker-pool-8-thread-1] INFO  Local Search phase (2) ended: step total (8), time spent (8329), best score (-31200hard/-2911900soft).
2017-06-08 10:35:21,676 [SwingWorker-pool-8-thread-1] INFO  Solving ended: time spent (8330), best score (-31200hard/-2911900soft), average calculate count per second (1306), environment mode (REPRODUCIBLE).
</code>```

My project structure in eclipse looks like

I added optaplanner to build path and to deployment assembly.

It looks like logback.xml level=-info but it is -debug.

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>

  <appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d [%t] %-5p %m%n</pattern>
    </encoder>
  </appender>

  <logger name="org.optaplanner" level="${logback.level.org.optaplanner:-debug}"/>

  <root level="debug">
    <appender-ref ref="consoleAppender" />
  </root>

</configuration>
</code>```

I think that whole application can't find lockback.xml but after extract the .war on tomcat the file is present. Any idea how to bring back optaplanner logging?

答: That was my fault, I include src/test/ to .war and in src/test is logback-test.xml and that file has priority before logback.xml. I found out that logback-test.xml has configured to level=-info</p>

Body:
I create RestEasy server which controls optaplanner. I sent requests to the server and that servers start optaplanner. When I start optaplanner from eclipse like normal application then logging works correctly, but when I run my server which starts optaplanner my logs looks like

2017-06-08 10:35:13,033 [123] INFO  VehicleRoutingSolution TMS_DATA has 1 depots, 20 vehicles and 70 customers with a search space of 10^25.
2017-06-08 10:35:13,034 [123] INFO  Imported: \\xxxx\xxxxx\xxx\xxxx.vrp
2017-06-08 10:35:13,740 [SwingWorker-pool-8-thread-1] INFO  Solving started: time spent (394), best score (70uninitialized/-42308000hard/0soft), environment mode (REPRODUCIBLE), random (JDK with seed 0).
2017-06-08 10:35:13,916 [SwingWorker-pool-8-thread-1] INFO  Custom phase (0) ended: step total (1), time spent (570), best score (-42308000hard/0soft).
2017-06-08 10:35:16,157 [SwingWorker-pool-8-thread-1] INFO  Construction Heuristic phase (1) ended: step total (50), time spent (2811), best score (-38400hard/-2911900soft).
2017-06-08 10:35:21,673 [AWT-EventQueue-0] INFO  Terminating solver early.
2017-06-08 10:35:21,675 [SwingWorker-pool-8-thread-1] INFO  Local Search phase (2) ended: step total (8), time spent (8329), best score (-31200hard/-2911900soft).
2017-06-08 10:35:21,676 [SwingWorker-pool-8-thread-1] INFO  Solving ended: time spent (8330), best score (-31200hard/-2911900soft), average calculate count per second (1306), environment mode (REPRODUCIBLE).

My project structure in eclipse looks like

I added optaplanner to build path and to deployment assembly.

It looks like logback.xml level=-info but it is -debug.

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

  <appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d [%t] %-5p %m%n</pattern>
    </encoder>
  </appender>

  <logger name="org.optaplanner" level="${logback.level.org.optaplanner:-debug}"/>

  <root level="debug">
    <appender-ref ref="consoleAppender" />
  </root>

</configuration>

I think that whole application can't find lockback.xml but after extract the .war on tomcat the file is present. Any idea how to bring back optaplanner logging?


问:
Convert Multiple Text into QR Code Image
I have read some article that describe using ZXing to convert text into QR Code (ImageView).

But i have 3 EditText field to make this. Is it possible ? How to accomplish this ?

答:
Add them to one string with separators

```<code>String qrstring = editext1.getstring().toText+ "%" + editext2.getstring().toText + "#" + editext3.getstring().toText
</code>```

and send this final string to the qr encoder

and use corresponding logic to decode it

Body:
Add them to one string with separators

String qrstring = editext1.getstring().toText+ "%" + editext2.getstring().toText + "#" + editext3.getstring().toText

and send this final string to the qr encoder

and use corresponding logic to decode it


问:
postgresql: btree_gist does not exist
I need to use btree_gist in order to index three fields: a postgis geometry, a date and bigint.

I have postgresql-contrib installed, and I'm able to create the extension without any problem using: CREATE EXTENSION btree_gist; the extension is visible in the extensions list in pgAdmin, but it is not installed according to the command \dx in psql.

Obviously trying to create an index with btree_gist results in an error stating that btree_gist does not exist.

I'm running pqsl 9.5.4.
Is there something that I'm missing?

答:
According to manuels
https://www.postgresql.org/docs/9.5/static/btree-gist.html

btree_gist provides GiST index operator classes that implement B-tree equivalent behavior for the data types int2, int4, int8, float4, float8, numeric, timestamp with time zone, timestamp without time zone, time with time zone, time without time zone, date, interval, oid, money, char, varchar, text, bytea, bit, varbit, macaddr, inet, and cidr.

PostGIS geometries not included here and also Postgis geometries has own index type GIST

And there is a similar question here
Postgres GIST vs Btree index

Title: postgresql: btree_gist does not exist


问:
JSON to textView?
I have my app get JSON data from a link, but I need to get status from the JSON.

Status > Code and Msg.

Here is what I have working:

Screenshot:

I need to have it output >

Code : success (or fail, whatever the json says)

Msg : Licence updated.. (Or whatever the JSON spits out)

Any help would be nice or pointing me in the direction, thanks.

Some of my code:

```<code>public class doit extends AsyncTask<Void,Void,Void>{
String words;

        public doit() throws JSONException {
        }

        @Override
        protected Void doInBackground(Void... voids) {

            try {
                WebView wv = (WebView) findViewById(R.id.webview);
                EditText messages = (EditText) findViewById(R.id.messages);
                Document doc = Jsoup.connect("https://api.deepbot.tv/web/apply/namerefresh.php?s=" + messages.getText().toString()).get();

                words=doc.text();

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

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            texx.setText(words);

        }
</code>```

答:
Try the following, just replace your return: </p>

```<code>   public class doit extends AsyncTask<Void,Void,Void>{
   String words;

    public doit() throws JSONException {
    }

    @Override
    protected Void doInBackground(Void... voids) {

        try {
            WebView wv = (WebView) findViewById(R.id.webview);
            EditText messages = (EditText) findViewById(R.id.messages);
            Document doc = Jsoup.connect("https://api.deepbot.tv/web/apply/namerefresh.php?s=" + messages.getText().toString()).get();

            words=doc.text();

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

        return words;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);

    try {
        JSONObject  jObj = new JSONObject(words);
        String code = jObj.getString("code");
        String name = jObj.getString("msg");
        texx.setText(code +"  "+name);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    }
</code>```

Title: JSON to textView?

Body:
I have my app get JSON data from a link, but I need to get status from the JSON.

Status > Code and Msg.

Here is what I have working:

Screenshot:

I need to have it output >

Code : success (or fail, whatever the json says)

Msg : Licence updated.. (Or whatever the JSON spits out)

Any help would be nice or pointing me in the direction, thanks.

Some of my code:

public class doit extends AsyncTask<Void,Void,Void>{
String words;

        public doit() throws JSONException {
        }

        @Override
        protected Void doInBackground(Void... voids) {

            try {
                WebView wv = (WebView) findViewById(R.id.webview);
                EditText messages = (EditText) findViewById(R.id.messages);
                Document doc = Jsoup.connect("https://api.deepbot.tv/web/apply/namerefresh.php?s=" + messages.getText().toString()).get();

                words=doc.text();

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

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            texx.setText(words);

        }

Body:
Try the following, just replace your return:

   public class doit extends AsyncTask<Void,Void,Void>{
   String words;

    public doit() throws JSONException {
    }

    @Override
    protected Void doInBackground(Void... voids) {

        try {
            WebView wv = (WebView) findViewById(R.id.webview);
            EditText messages = (EditText) findViewById(R.id.messages);
            Document doc = Jsoup.connect("https://api.deepbot.tv/web/apply/namerefresh.php?s=" + messages.getText().toString()).get();

            words=doc.text();

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

        return words;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);

    try {
        JSONObject  jObj = new JSONObject(words);
        String code = jObj.getString("code");
        String name = jObj.getString("msg");
        texx.setText(code +"  "+name);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    }


问:
How to Check Custom template for Posts by default in WP Post Template Plugin
I am using WP Post Template for Post Template

I have two template

Default Template (Selected By Default)

Property

and I want

Default Template

Property (Select By Default)

答:
You need to change code into page.php file. Find below code on same file.

```<code>while ( have_posts() ) : the_post();
        get_template_part( 'template-parts/page/content', 'page' );

            // If comments are open or we have at least one comment, load up the comment template.
            if ( comments_open() || get_comments_number() ) :
                comments_template();
            endif;

        endwhile; // End of the loop.
</code>```

Please change get_template_part( 'template-parts/page/content', 'page' ); this line with

```<code>get_template_part( 'inc/template', 'property' );
</code>```

For that you need to set your template file name is template-property.php

Body:
You need to change code into page.php file. Find below code on same file.

while ( have_posts() ) : the_post();
        get_template_part( 'template-parts/page/content', 'page' );

            // If comments are open or we have at least one comment, load up the comment template.
            if ( comments_open() || get_comments_number() ) :
                comments_template();
            endif;

        endwhile; // End of the loop.

Please change get_template_part( 'template-parts/page/content', 'page' ); this line with

get_template_part( 'inc/template', 'property' );

For that you need to set your template file name is template-property.php


问:
typescript: remove compiler error on non existent object properties
I have just started on angular 2 with typescript and I am coming from a js background.

I have the following code:

```<code>export class AddunitsComponent implements OnInit {
  public centers:any;
  constructor(){
  this.centers = {};
}}
</code>```

Now I have a view with the following input:

```<code><input type="text" [(ngModel)]="centers.name">
</code>```

When I compile the app using ng build --prod, I get an error property name does not exist on type 'Object'

Then I got to know that each property needs to be defined as an interface or in the constructor.

And this is a problem for me now because I have already made all the views which are using lot of inputs for data entry and I was testing without the prod flag, which did not raise any errors.

Is there a way I can disable this check at compile time for production?

答:
Make it optional by using this

```<code><input type="text" [ngModel]="centers?.name">
</code>```

OR

```<code><input type="text" *ngIf='centers?.name' [(ngModel)]="centers.name">
</code>```

Body:
I have just started on angular 2 with typescript and I am coming from a js background.

I have the following code:

export class AddunitsComponent implements OnInit {
  public centers:any;
  constructor(){
  this.centers = {};
}}

Now I have a view with the following input:

<input type="text" [(ngModel)]="centers.name">

When I compile the app using ng build --prod, I get an error property name does not exist on type 'Object'

Then I got to know that each property needs to be defined as an interface or in the constructor.

And this is a problem for me now because I have already made all the views which are using lot of inputs for data entry and I was testing without the prod flag, which did not raise any errors.

Is there a way I can disable this check at compile time for production?

Body:
Make it optional by using this

<input type="text" [ngModel]="centers?.name">

OR

<input type="text" *ngIf='centers?.name' [(ngModel)]="centers.name">


问:
App Crash instantly without exception or log (seems like xamarin/mono bug)
It's a weird situation here :) , I have implemented this code in my fragment to scan TCP Ports in multithread environment , it crash when debugging , and sometimes crash in release mode too with thoose messages :

E/art     (12972): Nested signal detected - original signal being reported

F/art     (12972): art/runtime/fault_handler.cc:117] Check failed: !initialized_

tried to set Target Android to 23 that didn’t work.

tried running adb shell setprop debug.mono.env
  MONO_DEBUG=soft-breakpoints that didn’t work.

tried to compile using different Android API's Versions

ANY IDEA WHY IS THIS HAPPENING ??

HERE IS MY CODE:

```<code>    public void start()
    {
        for (int i = 0; i < 50; i++)
        {
            Task.Run(() => RunScanTcp());
            //ThreadPool.QueueUserWorkItem(RunScanTcp);
            //Thread thread = new Thread(new ThreadStart(RunScanTcp));
            //thread.Start();
        }
    }

    public void RunScanTcp()
    {
        while (abort != true)
        {
                port = port + 1;
                Log.Info("PORT SCANNER", port.ToString());
        }
    }

    public class PortList
    {
        private int start;
        private int stop;
        private int ports;
        private static readonly object _syncRoot = new object();

        public PortList(int starts, int stops)
        {
            start = starts;
            stop = stops;
            ports = start;
        }

        public bool MorePorts()
        {
            lock (_syncRoot)
            {
                return (stop - ports) >= 0;
            }
        }

        public int NextPort()
        {
            lock (_syncRoot)
            {
                if (MorePorts())
                {
                    return ports++;
                }
                return -1;
            }
        }
    }
</code>```

Im compiling using :

Android Version (Android 7.1 Nougat)

Minimum Android Version :

Android 4.1 (API Level 16 - Jelly Bean)

Target Android Version:

Compile Using SDK Version

UPDATE :

After Visual Studio Update 15.2 (26430.12) , and Xamarin 4.5.0.476 - 30/05/2017(dd/mm/yyyy) the application crashed while is connected to debugger too...

Here is the debugger output :

```<code>referenceTable GDEF length=814 1
referenceTable GSUB length=11364 1
referenceTable GPOS length=47302 1
referenceTable head length=54 1
referenceTable GDEF length=428 1
referenceTable GSUB length=2302 1
referenceTable GPOS length=43252 1
referenceTable head length=54 1
referenceTable GDEF length=808 1
referenceTable GSUB length=11364 1
referenceTable GPOS length=49128 1
referenceTable head length=54 1
referenceTable GDEF length=808 1
referenceTable GSUB length=11364 1
referenceTable GPOS length=47320 1
referenceTable head length=54 1
05-31 04:31:51.590 F/art     (17427): art/runtime/fault_handler.cc:117] Check failed: !initialized_
</code>```

Thank's All of you ...

答:
As you described it is working without that part of your code ... so the error must be somewhere in your code.

let's look at it.

```<code>public void start()
{
    for (int i = 0; i < 50; i++)
    {
        Task.Run(() => RunScanTcp());
    }
}

public void RunScanTcp()
{
    while (abort != true)
    {
            port = port + 1;
            Log.Info("PORT SCANNER", port.ToString());
    }
}
</code>```

In the start method you start 50 tasks - and not awaiting any of them - which means, that possibly all tasks run in parallel (at least definitely some tasks try to access port at the same time).

What those tasks execute is a method that accesses port which must be a field of the containing class.

Accessing a shared field from multiple tasks / threads is never a good idea without a lock.

Try using the following code instead (if you really need the parallel tasks for some reason).

```<code>public class YourClass
{

    private bool abort;
    private int port;
    private object portLock = new object();

    public void start()
    {
        for (int i = 0; i < 50; i++)
        {
            Task.Run(() => RunScanTcp());
        }
    }

    public void RunScanTcp()
    {
        while (abort != true && this.port < int.MaxValue)
        {
            lock (this.portLock) {
                port = port + 1;
                Log.Info("PORT SCANNER", port.ToString());
            }
        }
    }

}
</code>```

Possibly a better approach is to only use one task and somewhere await it.

```<code>public class YourClass
{

    private bool abort;
    private int port;
    private object portLock = new object();

    public Task start()
    {
        return Task.Run(() => RunScanTcp());
    }

    public void RunScanTcp()
    {
        lock (this.portLock) {
            while (abort != true && this.port < int.MaxValue)
            {
                port = port + 1;
                Log.Info("PORT SCANNER", port.ToString());
            }
        }
    }

}
</code>```

If that solves your current problem you might want to add another question about how to properly solve what you're actually trying to solve (since your current code basically just increments the port until it is aborted or the app crashes (since it counted above the Int32 MaxValue)

Body:
It's a weird situation here :) , I have implemented this code in my fragment to scan TCP Ports in multithread environment , it crash when debugging , and sometimes crash in release mode too with thoose messages :

E/art     (12972): Nested signal detected - original signal being reported

F/art     (12972): art/runtime/fault_handler.cc:117] Check failed: !initialized_

tried to set Target Android to 23 that didn’t work.

tried running adb shell setprop debug.mono.env
  MONO_DEBUG=soft-breakpoints that didn’t work.

tried to compile using different Android API's Versions

ANY IDEA WHY IS THIS HAPPENING ??

HERE IS MY CODE:

    public void start()
    {
        for (int i = 0; i < 50; i++)
        {
            Task.Run(() => RunScanTcp());
            //ThreadPool.QueueUserWorkItem(RunScanTcp);
            //Thread thread = new Thread(new ThreadStart(RunScanTcp));
            //thread.Start();
        }
    }

    public void RunScanTcp()
    {
        while (abort != true)
        {
                port = port + 1;
                Log.Info("PORT SCANNER", port.ToString());
        }
    }

    public class PortList
    {
        private int start;
        private int stop;
        private int ports;
        private static readonly object _syncRoot = new object();

        public PortList(int starts, int stops)
        {
            start = starts;
            stop = stops;
            ports = start;
        }

        public bool MorePorts()
        {
            lock (_syncRoot)
            {
                return (stop - ports) >= 0;
            }
        }

        public int NextPort()
        {
            lock (_syncRoot)
            {
                if (MorePorts())
                {
                    return ports++;
                }
                return -1;
            }
        }
    }

Im compiling using :

Android Version (Android 7.1 Nougat)

Minimum Android Version :

Android 4.1 (API Level 16 - Jelly Bean)

Target Android Version:

Compile Using SDK Version

UPDATE :

After Visual Studio Update 15.2 (26430.12) , and Xamarin 4.5.0.476 - 30/05/2017(dd/mm/yyyy) the application crashed while is connected to debugger too...

Here is the debugger output :

referenceTable GDEF length=814 1
referenceTable GSUB length=11364 1
referenceTable GPOS length=47302 1
referenceTable head length=54 1
referenceTable GDEF length=428 1
referenceTable GSUB length=2302 1
referenceTable GPOS length=43252 1
referenceTable head length=54 1
referenceTable GDEF length=808 1
referenceTable GSUB length=11364 1
referenceTable GPOS length=49128 1
referenceTable head length=54 1
referenceTable GDEF length=808 1
referenceTable GSUB length=11364 1
referenceTable GPOS length=47320 1
referenceTable head length=54 1
05-31 04:31:51.590 F/art     (17427): art/runtime/fault_handler.cc:117] Check failed: !initialized_

Thank's All of you ...

Body:
As you described it is working without that part of your code ... so the error must be somewhere in your code.

let's look at it.

public void start()
{
    for (int i = 0; i < 50; i++)
    {
        Task.Run(() => RunScanTcp());
    }
}

public void RunScanTcp()
{
    while (abort != true)
    {
            port = port + 1;
            Log.Info("PORT SCANNER", port.ToString());
    }
}

In the start method you start 50 tasks - and not awaiting any of them - which means, that possibly all tasks run in parallel (at least definitely some tasks try to access port at the same time).

What those tasks execute is a method that accesses port which must be a field of the containing class.

Accessing a shared field from multiple tasks / threads is never a good idea without a lock.

Try using the following code instead (if you really need the parallel tasks for some reason).

public class YourClass
{

    private bool abort;
    private int port;
    private object portLock = new object();

    public void start()
    {
        for (int i = 0; i < 50; i++)
        {
            Task.Run(() => RunScanTcp());
        }
    }

    public void RunScanTcp()
    {
        while (abort != true && this.port < int.MaxValue)
        {
            lock (this.portLock) {
                port = port + 1;
                Log.Info("PORT SCANNER", port.ToString());
            }
        }
    }

}

Possibly a better approach is to only use one task and somewhere await it.

public class YourClass
{

    private bool abort;
    private int port;
    private object portLock = new object();

    public Task start()
    {
        return Task.Run(() => RunScanTcp());
    }

    public void RunScanTcp()
    {
        lock (this.portLock) {
            while (abort != true && this.port < int.MaxValue)
            {
                port = port + 1;
                Log.Info("PORT SCANNER", port.ToString());
            }
        }
    }

}

If that solves your current problem you might want to add another question about how to properly solve what you're actually trying to solve (since your current code basically just increments the port until it is aborted or the app crashes (since it counted above the Int32 MaxValue)


问:
Failed to locate Element from a CheckOut Table
I'm not able to locate an element. I want to getText() from the element then convert it to a float and calculate. However, can't seem to find element.

```<code>String unitPrice = driver.findElement(By.cssSelector(".price")).getText();
        //By.xpath(".//*[@id='product_1_1_0_0']/td[4]")).getText();
String unit = driver.findElement(By.cssSelector(".cart_quantity_input.form-control.grey")).getText();
        //By.xpath(".//*[@id='product_1_1_0_0']/td[5]/input[2]")).getText();
String totalPrice = driver.findElement(By.cssSelector("#total_product_price_1_1_0")).getText();
        //By.xpath(".//*[@id='total_product_price_1_1_0']")).getText();

float unitPriceF = Float.parseFloat(unitPrice);
float unitF = Float.parseFloat(unit);
float TotalPriceF = Float.parseFloat(totalPrice);
</code>```

I've tried both xPath and cssSelector, but getting same error in both cases:

no such element: Unable to locate element: {"method":"css
  selector","selector":"#total_product_price_1_1_0"}(..)

This is the HTML structure :

```<code><div id="order-detail-content" class="table_block table-responsive">
<table id="cart_summary" class="table table-bordered stock-management-on">
<thead>
<tr>
<th class="cart_product first_item">Product</th>
<th class="cart_description item">Description</th>
<th class="cart_avail item">Avail.</th>
<th class="cart_unit item">Unit price</th>
<th class="cart_quantity item">Qty</th>
<th class="cart_total item">Total</th>
<th class="cart_delete last_item"> </th>
</tr>
</thead>
<tfoot>
<tr class="cart_total_price">
<td id="cart_voucher" class="cart_voucher" rowspan="3" colspan="3"> </td>
<td class="text-right" colspan="3">Total products</td>
<td id="total_product" class="price" colspan="2">$39.51</td>
</tr>
<tr style="display: none;">
<tr class="cart_total_delivery">
<tr class="cart_total_voucher" style="display:none">
<tr class="cart_total_price">
</tfoot>
<tbody>
<tr id="product_1_1_0_0" class="cart_item last_item first_item address_0 odd">
<td class="cart_product">
<td class="cart_description">
<td class="cart_avail">
<td class="cart_unit" data-title="Unit price">
<span id="product_price_1_1_0" class="price">
<span class="price">$39.51</span>
</span>
</td>
<td class="cart_quantity text-center">
<td class="cart_total" data-title="Total">
<td class="cart_delete text-center" data-title="Delete">
</tr>
</tbody>
</table>
</div>
</code>```

答:
To get the price first, find the row with its id. our price is in the span tag in that row. Now, get those span tag elements into the "List", our price is in the second span element. So, get that element and use ".getText()" to get the data.</p>

```<code>     WebElement row = driver.findElement(By.id("product_1_1_0_0"));
     List<WebElement> span = row.findElements(By.tagName("span"));
     String totalPrice = span.get(1).getText();
</code>```

Body:
I'm not able to locate an element. I want to getText() from the element then convert it to a float and calculate. However, can't seem to find element.

String unitPrice = driver.findElement(By.cssSelector(".price")).getText();
        //By.xpath(".//*[@id='product_1_1_0_0']/td[4]")).getText();
String unit = driver.findElement(By.cssSelector(".cart_quantity_input.form-control.grey")).getText();
        //By.xpath(".//*[@id='product_1_1_0_0']/td[5]/input[2]")).getText();
String totalPrice = driver.findElement(By.cssSelector("#total_product_price_1_1_0")).getText();
        //By.xpath(".//*[@id='total_product_price_1_1_0']")).getText();

float unitPriceF = Float.parseFloat(unitPrice);
float unitF = Float.parseFloat(unit);
float TotalPriceF = Float.parseFloat(totalPrice);

I've tried both xPath and cssSelector, but getting same error in both cases:

no such element: Unable to locate element: {"method":"css
  selector","selector":"#total_product_price_1_1_0"}(..)

This is the HTML structure :

Product
Description
Avail.
Unit price
Qty
Total

Total products
$39.51

$39.51

Body:
To get the price first, find the row with its id. our price is in the span tag in that row. Now, get those span tag elements into the "List", our price is in the second span element. So, get that element and use ".getText()" to get the data.

     WebElement row = driver.findElement(By.id("product_1_1_0_0"));
     List<WebElement> span = row.findElements(By.tagName("span"));
     String totalPrice = span.get(1).getText();


问:
How to maintain the order of a JSONObject
I am using a JSONObject in order to remove a certin attribute I don't need in a JSON String:

```<code>JSONObject jsonObject = new JSONObject(jsonString);
jsonObject.remove("owner");
jsonString = jsonObject.toString();
</code>```

It works ok however the problem is that the JSONObject is "an unordered collection of name/value pairs" and I want to maintain the original order the String had before it went through the JSONObject manipulation.

Any idea how to do this?

答:
In JDK 8 and above, We can do it by using nashorn engine, supported in JDK 8.
Java 8 support to use js engine to evaluate:

```<code>String content = ..json content...
String name = "test";
String result = (String) engine.eval("var json = JSON.stringify("+content+");"
                                + "var jsResult = JSON.parse(json);"
                                + "jsResult.name = \"" + name + "\";"
                                + "jsResult.version = \"1.0\";"
                                + "JSON.stringify( jsResult );"
                            );
</code>```

Body:
I am using a JSONObject in order to remove a certin attribute I don't need in a JSON String:

JSONObject jsonObject = new JSONObject(jsonString);
jsonObject.remove("owner");
jsonString = jsonObject.toString();

It works ok however the problem is that the JSONObject is "an unordered collection of name/value pairs" and I want to maintain the original order the String had before it went through the JSONObject manipulation.

Any idea how to do this?

Body:
In JDK 8 and above, We can do it by using nashorn engine, supported in JDK 8.
Java 8 support to use js engine to evaluate:

String content = ..json content...
String name = "test";
String result = (String) engine.eval("var json = JSON.stringify("+content+");"
                                + "var jsResult = JSON.parse(json);"
                                + "jsResult.name = \"" + name + "\";"
                                + "jsResult.version = \"1.0\";"
                                + "JSON.stringify( jsResult );"
                            );


答:
You need to ensure strict mode is enabled. Since it is enabled in modules by default, I guess your sample code doesn't show that. Kangax's compatibility table shows an appropriate test.

"use strict";
//block0
function foo () { return 4 }
console.log(foo());//will log 4
{
  //block1
    function foo () { return 1 }
    console.log(foo());//will log 1
    {
    //block2
        function foo () { return 2 }//a block level function
        console.log(foo());//will log 2
    }
    console.log(foo());//will again log 1
}
console.log(foo());//logs 4```

Title: Block Scoped Function ECMAScript 6 Strange Behaviour

Body:
I was reading the new features in ECMA6. One of the new features is Block Scoped Functions . That means we can have a same name for functions in different blocks. As in the code below block1 foo() logs 1 then similarly block2 foo() logs 2 and block0 foo() or global scope logs 4. And that is the expected result. But what i can't understand is that Why does the last console.log(foo()) logs 1 and not 4 because it is under block0 or global scope instead it logs 1 which is block1 foo().

//block0
function foo () { return 4 }
console.log(foo());//will log 4
{
  //block1
    function foo () { return 1 }
    console.log(foo());//will log 1
    {
    //block2
        function foo () { return 2 }//a block level function
        console.log(foo());//will log 2
    }
    console.log(foo());//will again log 1
}
console.log(foo());//should log 4 but logs 1 why?

Now again if I enclose the above code into a another block it works as expected. This is a bit confusing to me. What actually is causing this behviour?

{//block0
function foo () { return 4 }
console.log(foo());//will log 4
{
  //block1
    function foo () { return 1 }
    console.log(foo());//will log 1
    {
    //block2
        function foo () { return 2 }
        console.log(foo());//will log 2
    }
    console.log(foo());//will again log 1
}
console.log(foo());//will log 4 but
}


问:
Robomongo connection with Meteor mongodb
I have connected my localhost mongodb from robomongo but having problem in connecting Meteor mongodb.

I am running Meteor from nitrousio not on localhost.

In robomongo connection settings, it is showing "Connected to 'meteor_url:3001'. Authorization failed". I am using correct db in Authentication tab and nothing in username and password. Is this the root cause? If yes, what is the default username and pwd of mongodb? If no, then what should i do?

答:
@Spiralis
it works on robomongo version 1.0 in linux also Thanks.

Just create new connection
and put
Name = Meteor
Address = Localhost
Port = 3001
Done!


问:
Class 'MainActivity' must either be declared abstract or implement abstract method 'onClick(View)' in 'OnClickListener
I have been coding for a very long time and I've only started using Android Stud last month, I'm having a problem with implementing an OnClickListener.

here's the code that is giving me the error.

I hope my question is clear, else I'll happy to give my code snippet.

```<code>public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button scanBnt;
    private TextView formatText, contentText;

    ....
}
</code>```

答:
```<code>Button button = (Button) findViewById(R.id.mybutton);
button.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
         Toast.makeText(this, "Button Clicked", Toast.LENGTH_LONG).show();
    }
});
</code>```

for explanation visit here

Body:
I have been coding for a very long time and I've only started using Android Stud last month, I'm having a problem with implementing an OnClickListener.

here's the code that is giving me the error.

I hope my question is clear, else I'll happy to give my code snippet.

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button scanBnt;
    private TextView formatText, contentText;

    ....
}

Body:
Button button = (Button) findViewById(R.id.mybutton);
button.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
         Toast.makeText(this, "Button Clicked", Toast.LENGTH_LONG).show();
    }
});

for explanation visit here


问:
Remove top gray line on UITableViewCell
I have a UITableViewCell and I want to remove the gray line on the top of it. How can I do this?</p>

答:
I know it is too late to answer this question. However, in swift 3 solution is:

```<code>tableView.separatorStyle = .none
</code>```

Title: Remove top gray line on UITableViewCell

Body:
I know it is too late to answer this question. However, in swift 3 solution is:

tableView.separatorStyle = .none


问:
Yii2 dependent dropdown third level onchange
I have a 3-level dependent dropdown in yii2.
If I select the first, the second is selected automatically (if there is only one matching record of course). But the problem is the third dropdown, because it's not doing anything. The second dropdown onchange event seems to be not working in this case, however its value is changed. (It works of course if I manually change the second dropdown, but that's not what I'm expecting) Is there a workaround for this? Many thanks!</p>

答:
add this code in onchange()

```<code> $.get( "'.Url::toRoute('/city/lists').'", { id: $(this).val() } )
                .done(function( data ) {
                    $( "select#selectid" ).html( data );
                }
            );'

            <select id="selectid"></select>
</code>```

and you have to return option value from

```<code>              actionList($id){
                   $list=Model::findBySql('your quer where id=$id')->all()
 foreach($list as $l){ echo "<option  value='" $l->id."'>'.$l->name.'</option>';
           }
</code>```

I recommend you to watch this video

https://www.youtube.com/watch?v=bpj7dF2orbI

Body:
add this code in onchange()

 $.get( "'.Url::toRoute('/city/lists').'", { id: $(this).val() } )
                .done(function( data ) {
                    $( "select#selectid" ).html( data );
                }
            );'

            <select id="selectid"></select>

and you have to return option value from

              actionList($id){
                   $list=Model::findBySql('your quer where id=$id')->all()
 foreach($list as $l){ echo "<option  value='" $l->id."'>'.$l->name.'</option>';
           }

I recommend you to watch this video

https://www.youtube.com/watch?v=bpj7dF2orbI


问:
What's the login for phpMyAdmin?
I downloaded the most recent version of XAMPP (v.1.7.7) and decided start a database. When I opened phpMyAdmin, it alerts me there is a new version of phpMyAdmin available. I downloaded it from online, and I deleted the old version of phpMyAdmin and replaced it with the current version (v.3.5.1). I opened it up and it came up with a log-in screen. I entered in "root" without a password, but it alerts me I need one. I don't know any password nor I know any alternative log-ins. How would I log-in to enter phpMyAdmin?</p>

答:
In new versions note that you have to change your code to like this:

```<code>mysqli_connect($mysql_hostname, $mysql_username, $mysql_password, $mysql_dbname);
</code>```

And for more look to this:

Fatal error: Uncaught Error: Call to undefined function mysql_connect()

Title: What's the login for phpMyAdmin?

Body:
In new versions note that you have to change your code to like this:

mysqli_connect($mysql_hostname, $mysql_username, $mysql_password, $mysql_dbname);

And for more look to this:

Fatal error: Uncaught Error: Call to undefined function mysql_connect()


答:
You have implemented View.OnClickListener interface in your activity. This interface has one abstract method abstract void onClick(View v) which you need to override in your activity.

Add the following code to your activity,

```<code>@Override
public void onClick(View v) {
    // Your code
}
</code>```

Check out

Title: Class 'MainActivity' must either be declared abstract or implement abstract method 'onClick(View)' in 'OnClickListener

Body:
You have implemented View.OnClickListener interface in your activity. This interface has one abstract method abstract void onClick(View v) which you need to override in your activity.

Add the following code to your activity,

@Override
public void onClick(View v) {
    // Your code
}

Check out


问:
iOS push not going to multiple device IDs
I am fetching an array of device_ids using PHP,
and sending iOS pushes to each of them with this code -

Question - the devices received pushes when array of device_ids (deviceTokens) was 2-3 device_ids. But deviecs did not receive push notifications when deviceTokens array was ~300 device_id long.
What could be the issue? I am new to PHP

(This question has been asked a few times but answers did not reflect problem I am facing)

```<code>$customers_ios = "SELECT * FROM `gcm_user` WHERE `gcmregios` <> '0' and `preference` = '1'";
                $c_ios = mysql_query($customers_ios);

                while($bd = mysql_fetch_array($c_ios)) {
                    $deviceTokens[]= $bd['gcmregios'];

                }

                $arrlength = count($deviceTokens);
                //echo $arrlength;

                // Put your private key's passphrase here:
                $passphrase = 'mypassphrase';//'PushNotification';

                //adhoc_id already setup above
                $message = $adhoc_desc;
                $title =  $adhoc_title;

                $ctx = stream_context_create();
                stream_context_set_option($ctx, 'ssl', 'local_cert', 'PushDistCertificates.pem');
                stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

                //'ssl://gateway.sandbox.push.apple.com:2195'
                // Open a connection to the APNS server
                $fp = stream_socket_client(
                  'ssl://gateway.push.apple.com:2195', $err,
                  $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);

                if (!$fp)
                    continue;

                // Create the payload body
                $body['aps'] =
                array(
                    'alert'=> $title,
                    'message' =>
                    array('ADHOC' =>
                        array('ADHOC_ID' => $adhoc_id,
                            'ADHOC_TITLE' => $title,
                            'ADHOC_DESCRIPTION' =>  $message,
                        )
                    ),
                    'sound'=>'default'
                );

                // Encode the payload as JSON
                $payload = json_encode($body);

                foreach($deviceTokens as $ios_token){
                    $msg = chr(0) . pack("n",32) . pack('H*', str_replace(' ', '', $ios_token)) . pack("n",strlen($payload)) . $payload;
                    $result = fwrite($fp, $msg);
                }
                // Close the connection to the server
                fclose($fp);
</code>```

答: Similar issues we had , Cross checking all device id in the database we found device id as "Simulator" which is device id of virtual device in the xcode. During development DEV team might have tested in Simulator and sooner APNS identifies this id , it  rejects all request. May be specific issues only to us , cross checking will help.</p>

Body:
I am fetching an array of device_ids using PHP,
and sending iOS pushes to each of them with this code -

Question - the devices received pushes when array of device_ids (deviceTokens) was 2-3 device_ids. But deviecs did not receive push notifications when deviceTokens array was ~300 device_id long.
What could be the issue? I am new to PHP

(This question has been asked a few times but answers did not reflect problem I am facing)

$customers_ios = "SELECT * FROM `gcm_user` WHERE `gcmregios` <> '0' and `preference` = '1'";
                $c_ios = mysql_query($customers_ios);

                while($bd = mysql_fetch_array($c_ios)) {
                    $deviceTokens[]= $bd['gcmregios'];

                }

                $arrlength = count($deviceTokens);
                //echo $arrlength;

                // Put your private key's passphrase here:
                $passphrase = 'mypassphrase';//'PushNotification';

                //adhoc_id already setup above
                $message = $adhoc_desc;
                $title =  $adhoc_title;

                $ctx = stream_context_create();
                stream_context_set_option($ctx, 'ssl', 'local_cert', 'PushDistCertificates.pem');
                stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

                //'ssl://gateway.sandbox.push.apple.com:2195'
                // Open a connection to the APNS server
                $fp = stream_socket_client(
                  'ssl://gateway.push.apple.com:2195', $err,
                  $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);

                if (!$fp)
                    continue;

                // Create the payload body
                $body['aps'] =
                array(
                    'alert'=> $title,
                    'message' =>
                    array('ADHOC' =>
                        array('ADHOC_ID' => $adhoc_id,
                            'ADHOC_TITLE' => $title,
                            'ADHOC_DESCRIPTION' =>  $message,
                        )
                    ),
                    'sound'=>'default'
                );

                // Encode the payload as JSON
                $payload = json_encode($body);

                foreach($deviceTokens as $ios_token){
                    $msg = chr(0) . pack("n",32) . pack('H*', str_replace(' ', '', $ios_token)) . pack("n",strlen($payload)) . $payload;
                    $result = fwrite($fp, $msg);
                }
                // Close the connection to the server
                fclose($fp);


问:
Scalacache pass cache instance
To initialise Scalacache instance in my service

```<code>import scala cache._
implicit val scalaCache = ScalaCache(new MyCache())
</code>```

but i am not getting what is new MyCache() so i have to pass a cache instance to construct a Scala Cache.

how to initialise mycache()

how to create a ScalaCache instance

reference : https://index.scala-lang.org/cb372/scalacache

答:
MyCache is some implementation of Cache trait. There is one for each of following:

The following cache implementations are supported, and it's easy to plugin your own implementation:

Google Guava

Memcached

Ehcache

Redis

Caffeine

Specific examples for each are given under https://github.com/cb372/scalacache#cache-implementations.

Title: Scalacache pass cache instance

Body:
To initialise Scalacache instance in my service

import scala cache._
implicit val scalaCache = ScalaCache(new MyCache())

but i am not getting what is new MyCache() so i have to pass a cache instance to construct a Scala Cache.

how to initialise mycache()

how to create a ScalaCache instance

reference : https://index.scala-lang.org/cb372/scalacache


问:
Pass variable in tag file JSP
I want to pass a variable in tag file. My code here:

layout.tag

```<code><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@tag description="My layout" pageEncoding="UTF-8"%>
<%@attribute name="title" type="java.lang.String" required="true" %>
<!DOCTYPE html>
<html>
<head>
    <title>My site | <c:out value="${title}" /></title>
</head>
<body>
</body>
</html>
</code>```

index.jsp

```<code><%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="mySite" tagdir="/WEB-INF/tags" %>
<mySite:layout title="home">
</mySite:layout>`
</code>```

But <c:out value="${title} />" always return ${title}. I tried with ${title} and got the same result. I dont know why...

答:
1.)add <%@ attribute name="greeting" required="true" %> in .tag file, change the name as per you convinence

2.)    <tag:mytag greeting="Satish">  pass the values like this

Title: Pass variable in tag file JSP

Body:
I want to pass a variable in tag file. My code here:

layout.tag

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@tag description="My layout" pageEncoding="UTF-8"%>
<%@attribute name="title" type="java.lang.String" required="true" %>
<!DOCTYPE html>

    <title>My site | <c:out value="${title}" /></title>

index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="mySite" tagdir="/WEB-INF/tags" %>
<mySite:layout title="home">
</mySite:layout>`

But <c:out value="${title} />" always return ${title}. I tried with ${title} and got the same result. I dont know why...


问:
Finding reachable vertices of a vertice in a graph
I am having problem in my code to calculate the reachable vertices in a graph.

I have the following code for the graph

```<code>class Vertices():
    number = 0
    def __init__(self):
        Vertices.number += 1
        self.number = Vertices.number
        self.Reachable= []
</code>```

I create the graph in the following way

```<code>a = Vertices()
a.Reachable = [1,2]
b = Vertices()
b.Reachable = [3]
c = Vertices()
c.Reachable= [3]
List = []
List.append(a)
List.append(b)
List.append(c)
</code>```

Thus vertice 1 that is a has an edge to itself and b . Similarly for b and for c.

We can move around the graph using List ie for vertex a it is reachable to List[trans-1] where trans refers to the Reachable list of a (List[0] and List[1])

Now in this graph I have to calculate the reachability for each vertice ie for each vertice calculate the vertices that it can reach.For eg a can reach a,b and c

I have read that I can use sets to do depth first search in all the list. Can you provide me a solution as to how to proceed.

Can anyone tell me how to use sets as I think that it is quite ideal for this problem seeing that it has union and difference functions associated with it....
PS : This is'nt a school based assignment.....

答:
Why don't you use NetworkX or any other graph library?

Your current representation won't work. How is any function supposed to go from the number 2 to the vertice b ? You need to add the actual object, not just their number.

Once you did that you can do something like this:

```<code>def reachable( start ):
    # the set of reachable nodes
    reachable = set()

    # recursive function to add all reachable nodes to `reachable`
    def finder(node):
        reachable.add(node.)
        for other in node.Reachable:
            finder(other)

    # add everything we can reach from here
    finder(start)
    return reachable
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am having problem in my code to calculate the reachable vertices in a graph.

I have the following code for the graph

class Vertices():
    number = 0
    def __init__(self):
        Vertices.number += 1
        self.number = Vertices.number
        self.Reachable= []

I create the graph in the following way

a = Vertices()
a.Reachable = [1,2]
b = Vertices()
b.Reachable = [3]
c = Vertices()
c.Reachable= [3]
List = []
List.append(a)
List.append(b)
List.append(c)

Thus vertice 1 that is a has an edge to itself and b . Similarly for b and for c.

We can move around the graph using List ie for vertex a it is reachable to List[trans-1] where trans refers to the Reachable list of a (List[0] and List[1])

Now in this graph I have to calculate the reachability for each vertice ie for each vertice calculate the vertices that it can reach.For eg a can reach a,b and c

I have read that I can use sets to do depth first search in all the list. Can you provide me a solution as to how to proceed.

Can anyone tell me how to use sets as I think that it is quite ideal for this problem seeing that it has union and difference functions associated with it....
PS : This is'nt a school based assignment.....

Body:
Why don't you use NetworkX or any other graph library?

Your current representation won't work. How is any function supposed to go from the number 2 to the vertice b ? You need to add the actual object, not just their number.

Once you did that you can do something like this:

def reachable( start ):
    # the set of reachable nodes
    reachable = set()

    # recursive function to add all reachable nodes to `reachable`
    def finder(node):
        reachable.add(node.)
        for other in node.Reachable:
            finder(other)

    # add everything we can reach from here
    finder(start)
    return reachable


问:
Count Values associated with key in Sql Server
I have three tables

Table Category

```<code>CategoryID         Category
1                   Climate
2                   Area
</code>```

Table CategoryDetail

```<code>DetailID    CategoryID      Desc
1            1              Hot
2            1              Cold
3            2              Area1
</code>```

Table CategoryDetailValues

```<code>PK  AnotherFK  CategoryDetailID
1    1           1
2    1           1
3    1           2
4    2           1
</code>```

Here AnotherFK is foreign key referring to another table. In record 1 and 2 duplicate exists that's ok but AnotherFK 1 has reference of CategoryDetailID 1 and 2 which has categoryID of 1 which is not ok

So from above tables
this result is valid from above three table

```<code>PK   AnotherFK    CategoryID  DetailID     Desc
1    1             1            1          Hot
2    1             1            1          Hot
</code>```

But below result is not valid

```<code>PK   AnotherFK    CategoryID  DetailID     Desc
2    1             1           1           Hot
3    1             1           2           Cold
</code>```

I can not put same AnotherFK in two different DetailID which has same CategoryID. I could have eliminated this by introducing CategoryID in CategoryDetailValues table and creating unique constraint but I am not allowed to do so.

Now my aim is to find all those record in CategoryDetailValues table which has different DetailID that are associated with same CategoryID. So that I can delete them.

Trying to achieve this in SQL Server 2012.

答:
You want one value per AnotherFK and Category. So the third table should have a composite key:

CategoryDetailValues(AnotherFK, CategoryID, DetailID, HowMany)

with a unique constraint on AnotherFK, CategoryID and both building a foreign key to CategoryDetail(CategoryID, DetailID).

In order to clean up data first, you'd have to look for ambiguities:

```<code>select AnotherFK, CategoryID, DetailID
from
(
  select
    cdv.AnotherFK, cd.CategoryID, cdv.DetailID,
    count(distinct cd.DetailID) over (partition by cdv.AnotherFK, cd.CategoryID) as cnt
  from CategoryDetailValues cdv
  join CategoryDetail cd on cd.DetailID = cdv.CategoryDetailID
)
where cnt > 1
order by AnotherFK, CategoryID, DetailID
</code>```

Body:
I have three tables

Table Category

CategoryID         Category
1                   Climate
2                   Area

Table CategoryDetail

DetailID    CategoryID      Desc
1            1              Hot
2            1              Cold
3            2              Area1

Table CategoryDetailValues

PK  AnotherFK  CategoryDetailID
1    1           1
2    1           1
3    1           2
4    2           1

Here AnotherFK is foreign key referring to another table. In record 1 and 2 duplicate exists that's ok but AnotherFK 1 has reference of CategoryDetailID 1 and 2 which has categoryID of 1 which is not ok

So from above tables
this result is valid from above three table

PK   AnotherFK    CategoryID  DetailID     Desc
1    1             1            1          Hot
2    1             1            1          Hot

But below result is not valid

PK   AnotherFK    CategoryID  DetailID     Desc
2    1             1           1           Hot
3    1             1           2           Cold

I can not put same AnotherFK in two different DetailID which has same CategoryID. I could have eliminated this by introducing CategoryID in CategoryDetailValues table and creating unique constraint but I am not allowed to do so.

Now my aim is to find all those record in CategoryDetailValues table which has different DetailID that are associated with same CategoryID. So that I can delete them.

Trying to achieve this in SQL Server 2012.

Body:
You want one value per AnotherFK and Category. So the third table should have a composite key:

CategoryDetailValues(AnotherFK, CategoryID, DetailID, HowMany)

with a unique constraint on AnotherFK, CategoryID and both building a foreign key to CategoryDetail(CategoryID, DetailID).

In order to clean up data first, you'd have to look for ambiguities:

select AnotherFK, CategoryID, DetailID
from
(
  select
    cdv.AnotherFK, cd.CategoryID, cdv.DetailID,
    count(distinct cd.DetailID) over (partition by cdv.AnotherFK, cd.CategoryID) as cnt
  from CategoryDetailValues cdv
  join CategoryDetail cd on cd.DetailID = cdv.CategoryDetailID
)
where cnt > 1
order by AnotherFK, CategoryID, DetailID


问:
Merge Scala Seq
I have following Seq as input:

```<code>Seq(Seq(1,2),Seq(2,3),Seq(3,4),Seq(7,8),Seq(8,9))
</code>```

I would like to create another Seq from this like below:

```<code>Seq(Seq(1,4),Seq(7,9))
</code>```

I thought to use sliding operation (take 2) and merge as set to remove duplicates but I am not sure how to achieve it using Seq as it is immutable. Can someone help me?

答:
A more generic Seq-based solution could be:

val data = Seq(Seq(1,2),Seq(2,3),Seq(3,4),Seq(7,8),Seq(8,9))
```

<pre class="lang-scala prettyprint-override"><code>val merged = data.foldLeft(Seq.empty[Seq[Int]]) {
  case (acc :+ (last :+ tail), head :: e)
    if tail == head => acc :+ (last ++ e)
  case (acc, e) => acc :+ e
} //List(List(1, 4), List(7, 9))
</code>```

Title: Merge Scala Seq

Body:
I have following Seq as input:

Seq(Seq(1,2),Seq(2,3),Seq(3,4),Seq(7,8),Seq(8,9))

I would like to create another Seq from this like below:

Seq(Seq(1,4),Seq(7,9))

I thought to use sliding operation (take 2) and merge as set to remove duplicates but I am not sure how to achieve it using Seq as it is immutable. Can someone help me?

Body:
A more generic Seq-based solution could be:

val data = Seq(Seq(1,2),Seq(2,3),Seq(3,4),Seq(7,8),Seq(8,9))

val merged = data.foldLeft(Seq.empty[Seq[Int]]) {
  case (acc :+ (last :+ tail), head :: e)
    if tail == head => acc :+ (last ++ e)
  case (acc, e) => acc :+ e
} //List(List(1, 4), List(7, 9))


问:
Floating Button not showing shadow
I am using vector drawable for floating button. I was wanted to have elevated grey shadow below button. When I preview it in xml it shows me shadow but when I run the application, it doesn't show shadow in device. Any reason why is it happening. Code and Screenshots below :

```<code><android.support.design.widget.FloatingActionButton
        android:id="@+id/fab_add_cg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:elevation="6dp"
        app:borderWidth="0dp"
        app:backgroundTint="@color/blue_4a90e2"
        app:srcCompat="@drawable/add_fab"/>
</code>```

Vector

```<code><?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="26dp"
    android:height="24dp"
    android:viewportWidth="26"
    android:viewportHeight="24">

    <group
        android:translateX="-313.000000"
        android:translateY="-550.000000">
        <group
            android:translateX="295.000000"
            android:translateY="532.000000">
            <group
                android:translateX="18.000000"
                android:translateY="18.000000">
                <group
                    android:translateX="7.000000"
                    android:translateY="5.000000">
                    <path
                        android:fillColor="#FFFFFF"
                        android:fillType="evenOdd"
                        android:strokeWidth="1"
                        android:pathData="M 19 11 L 13 11 L 13 5 L 11 5 L 11 11 L 5 11 L 5 13 L 11 13 L 11 19 L 13 19 L 13 13 L 19 13 Z" />
                </group>
                <path
                    android:fillColor="#FFFFFF"
                    android:fillType="evenOdd"
                    android:strokeWidth="1"
                    android:pathData="M13.4558738,12.2931068 C15.3663592,11.1301456 16.6121845,9.05378641
16.6121845,6.645 C16.6123786,2.99019417 13.6219903,0 9.96737864,0 C6.31276699,0
3.32237864,2.99019417 3.32237864,6.645 C3.32237864,9.05378641
4.56839806,11.1303398 6.47868932,12.2931068 C3.15631068,13.538932
0.664466019,16.4462621 0,19.9347573 L1.66131068,19.9347573 C2.49184466,16.113835
5.89747573,13.2898058 9.96737864,13.2898058 C14.0372816,13.2898058
17.4429126,16.113835 18.2734951,19.9347573 L19.9347573,19.9347573
C19.2703398,16.3630097 16.7784951,13.4558738 13.4558738,12.2931068 Z
M4.98368932,6.645 C4.98368932,3.90398058 7.22635922,1.66131068
9.96737864,1.66131068 C12.7083981,1.66131068 14.951068,3.90398058
14.951068,6.645 C14.951068,9.38601942 12.7083981,11.6286893
9.96737864,11.6286893 C7.22635922,11.6286893 4.98368932,9.38601942
4.98368932,6.645 Z" />
            </group>
        </group>
    </group>
</vector>
</code>```

When I preview:

When I run:

Complete Layout Code:

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:orientation="vertical"
    tools:context="com.fragment">

    <LinearLayout
        android:id="@+id/ll_cg_data"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:visibility="gone">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/rv_"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingLeft="20dp"
            android:paddingRight="20dp"
            android:scrollbars="none" />

        <LinearLayout
            android:id="@+id/ll"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="@dimen/activity_margin_half"
            android:orientation="vertical">

            <com.lifeontrack.utils.RobotoTextView
                android:id="@+id/tv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center_horizontal"
                android:text="@string/good"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="@color/grey_464646_85"
                app:font="Roboto-Medium.ttf" />

            <com.lifeontrack.utils.RobotoButton
                android:id="@+id/btn"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:layout_margin="@dimen/activity_margin_half"
                android:background="@color/blue_4a90e2"
                android:paddingLeft="10dp"
                android:paddingTop="5dp"
                android:text="@string/add"
                android:textAllCaps="true"
                android:textColor="@color/white"
                android:textSize="16sp"
                app:font="Roboto-Medium.ttf" />
        </LinearLayout>

    </LinearLayout>

    <LinearLayout
        android:id="@+id/ll_cg_no_data"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:visibility="gone">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_weight="0.7"
            android:background="@color/blue_eaeff4">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:src="@drawable/_no" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight=".3"
            android:paddingBottom="@dimen/activity_horizontal_margin">

            <com.lifeontrack.utils.RobotoTextView
                android:id="@+id/txt_good_cg"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_margin="@dimen/activity_horizontal_margin"
                android:gravity="center_horizontal"
                android:text="@string/good"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textColor="@android:color/black"
                app:font="Roboto-Regular.ttf" />

            <com.lifeontrack.utils.RobotoButton
                android:id="@+id/btn_add_cg"
                style="?android:textAppearanceButton"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_margin="@dimen/activity_margin_half"
                android:background="@drawable/outline_blue_btn"
                android:text="@string/add"
                android:textAllCaps="true"
                android:textColor="@color/dashboard_icon"
                android:textStyle="bold"
                app:font="Roboto-Medium.ttf" />
        </RelativeLayout>
    </LinearLayout>

    <com.lifeontrack.utils.RobotoTextView
        android:id="@+id/txt_no_records"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="@string/no_records_found"
        android:visibility="gone" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab_add_cg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_centerHorizontal="true"
        app:rippleColor="@android:color/white"
        app:pressedTranslationZ="12dp"
        android:layout_margin="@dimen/fab_margin"
        app:elevation="12dp"
        app:borderWidth="0dp"
        app:backgroundTint="@color/blue_4a90e2"
        app:srcCompat="@drawable/add_fab"/>

</FrameLayout>
</code>```

答:
Use CoordinatorLayout for getting all effects of new resources. And don't forget adding this line: xmlns:app="http://schemas.android.com/apk/res-auto" And it'll be better if you add your content to main layout with <include />

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <include layout="@layout/content" />

    <android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_marginEnd="16dp"
        android:layout_marginBottom="16dp"
        app:elevation="6dp"
        app:borderWidth="0dp"
        app:srcCompat="@drawable/add_fab"
        app:backgroundTint="#4a90e2"/>

</android.support.design.widget.CoordinatorLayout>
</code>```

Title: Floating Button not showing shadow

Body:
I am using vector drawable for floating button. I was wanted to have elevated grey shadow below button. When I preview it in xml it shows me shadow but when I run the application, it doesn't show shadow in device. Any reason why is it happening. Code and Screenshots below :

<android.support.design.widget.FloatingActionButton
        android:id="@+id/fab_add_cg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:elevation="6dp"
        app:borderWidth="0dp"
        app:backgroundTint="@color/blue_4a90e2"
        app:srcCompat="@drawable/add_fab"/>

Vector

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="26dp"
    android:height="24dp"
    android:viewportWidth="26"
    android:viewportHeight="24">

    <group
        android:translateX="-313.000000"
        android:translateY="-550.000000">
        <group
            android:translateX="295.000000"
            android:translateY="532.000000">
            <group
                android:translateX="18.000000"
                android:translateY="18.000000">
                <group
                    android:translateX="7.000000"
                    android:translateY="5.000000">
                    <path
                        android:fillColor="#FFFFFF"
                        android:fillType="evenOdd"
                        android:strokeWidth="1"
                        android:pathData="M 19 11 L 13 11 L 13 5 L 11 5 L 11 11 L 5 11 L 5 13 L 11 13 L 11 19 L 13 19 L 13 13 L 19 13 Z" />
                </group>
                <path
                    android:fillColor="#FFFFFF"
                    android:fillType="evenOdd"
                    android:strokeWidth="1"
                    android:pathData="M13.4558738,12.2931068 C15.3663592,11.1301456 16.6121845,9.05378641
16.6121845,6.645 C16.6123786,2.99019417 13.6219903,0 9.96737864,0 C6.31276699,0
3.32237864,2.99019417 3.32237864,6.645 C3.32237864,9.05378641
4.56839806,11.1303398 6.47868932,12.2931068 C3.15631068,13.538932
0.664466019,16.4462621 0,19.9347573 L1.66131068,19.9347573 C2.49184466,16.113835
5.89747573,13.2898058 9.96737864,13.2898058 C14.0372816,13.2898058
17.4429126,16.113835 18.2734951,19.9347573 L19.9347573,19.9347573
C19.2703398,16.3630097 16.7784951,13.4558738 13.4558738,12.2931068 Z
M4.98368932,6.645 C4.98368932,3.90398058 7.22635922,1.66131068
9.96737864,1.66131068 C12.7083981,1.66131068 14.951068,3.90398058
14.951068,6.645 C14.951068,9.38601942 12.7083981,11.6286893
9.96737864,11.6286893 C7.22635922,11.6286893 4.98368932,9.38601942
4.98368932,6.645 Z" />
            </group>
        </group>
    </group>
</vector>

When I preview:

When I run:

Complete Layout Code:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:orientation="vertical"
    tools:context="com.fragment">

    <LinearLayout
        android:id="@+id/ll_cg_data"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:visibility="gone">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/rv_"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingLeft="20dp"
            android:paddingRight="20dp"
            android:scrollbars="none" />

        <LinearLayout
            android:id="@+id/ll"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="@dimen/activity_margin_half"
            android:orientation="vertical">

            <com.lifeontrack.utils.RobotoTextView
                android:id="@+id/tv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center_horizontal"
                android:text="@string/good"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="@color/grey_464646_85"
                app:font="Roboto-Medium.ttf" />

            <com.lifeontrack.utils.RobotoButton
                android:id="@+id/btn"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:layout_margin="@dimen/activity_margin_half"
                android:background="@color/blue_4a90e2"
                android:paddingLeft="10dp"
                android:paddingTop="5dp"
                android:text="@string/add"
                android:textAllCaps="true"
                android:textColor="@color/white"
                android:textSize="16sp"
                app:font="Roboto-Medium.ttf" />
        </LinearLayout>

    </LinearLayout>

    <LinearLayout
        android:id="@+id/ll_cg_no_data"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:visibility="gone">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_weight="0.7"
            android:background="@color/blue_eaeff4">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:src="@drawable/_no" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight=".3"
            android:paddingBottom="@dimen/activity_horizontal_margin">

            <com.lifeontrack.utils.RobotoTextView
                android:id="@+id/txt_good_cg"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_margin="@dimen/activity_horizontal_margin"
                android:gravity="center_horizontal"
                android:text="@string/good"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textColor="@android:color/black"
                app:font="Roboto-Regular.ttf" />

            <com.lifeontrack.utils.RobotoButton
                android:id="@+id/btn_add_cg"
                style="?android:textAppearanceButton"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_margin="@dimen/activity_margin_half"
                android:background="@drawable/outline_blue_btn"
                android:text="@string/add"
                android:textAllCaps="true"
                android:textColor="@color/dashboard_icon"
                android:textStyle="bold"
                app:font="Roboto-Medium.ttf" />
        </RelativeLayout>
    </LinearLayout>

    <com.lifeontrack.utils.RobotoTextView
        android:id="@+id/txt_no_records"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="@string/no_records_found"
        android:visibility="gone" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab_add_cg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_centerHorizontal="true"
        app:rippleColor="@android:color/white"
        app:pressedTranslationZ="12dp"
        android:layout_margin="@dimen/fab_margin"
        app:elevation="12dp"
        app:borderWidth="0dp"
        app:backgroundTint="@color/blue_4a90e2"
        app:srcCompat="@drawable/add_fab"/>

</FrameLayout>

Body:
Use CoordinatorLayout for getting all effects of new resources. And don't forget adding this line: xmlns:app="http://schemas.android.com/apk/res-auto" And it'll be better if you add your content to main layout with <include />

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <include layout="@layout/content" />

    <android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_marginEnd="16dp"
        android:layout_marginBottom="16dp"
        app:elevation="6dp"
        app:borderWidth="0dp"
        app:srcCompat="@drawable/add_fab"
        app:backgroundTint="#4a90e2"/>

</android.support.design.widget.CoordinatorLayout>


问:
CSS - Line height property, how it works (simple)
So in this simple example I have as final result:

This is a very simple question but I simply can't get my head around it.

To achieve the vertical centering of the numbers I used:

```<code>line-height:100px;
</code>```

Which works great and have been doing it trial and error basis.

My question is specifically why the line-height:50px; just gets if half of the way.

If the small div has a height of 100px and I an positioning relative to it, shouldn't the half of it center it to the half.

This specially puzzles me since, when I center a div:

I would use: margin:50px 0 0 50px; to get this:

I realize this question might be an overkill since the answer might be (probably will be very simple), so sorry! but I guess it is better the "why doesn't this work" questions ;)

Thanks in advance!!

答:
I think line-height is just what is sounds like. It would be different if it was just half of the height, as you would have to account for the font-size, etc. line-height just makes a blocky thing with a height of 100px, in your case, and centers the text within that.

Basically, line-height adds the value ((desired height) - (font-size)) / 2 to the top and bottom of the text, while adding margins does not account for that.

Body:
So in this simple example I have as final result:

This is a very simple question but I simply can't get my head around it.

To achieve the vertical centering of the numbers I used:

line-height:100px;

Which works great and have been doing it trial and error basis.

My question is specifically why the line-height:50px; just gets if half of the way.

If the small div has a height of 100px and I an positioning relative to it, shouldn't the half of it center it to the half.

This specially puzzles me since, when I center a div:

I would use: margin:50px 0 0 50px; to get this:

I realize this question might be an overkill since the answer might be (probably will be very simple), so sorry! but I guess it is better the "why doesn't this work" questions ;)

Thanks in advance!!