问:
how to combine an id div and a php id
I don't know the specifications of PHP and an ID DIV. Here's my question :

Can I put in the same time an ID DIV named #modal and an ID PHP RETURN ?

```<code>while ( $contents_print = mysqli_fetch_array( $req_print ) ) {
    echo'
        <div class="row print">
            <div class="col s12 m4">
              <div class="card">
                <div class="card-image">
                  <img data-tags="print" class="activator" src="../00_sources/images/upload/pic_min/' . $contents_print[ 'pic_min' ] . '" alt="' . $contents_print[ 'pic_min' ] . '">
                  <a href="#modal" class="btn-floating halfway-fab waves-effect waves-light primary-color-text modal-trigger"><i class="material-icons">add</i></a>
                </div>
                <div class="card-content">
                    <span class="card-title">'.$contents_print['nom_projet'].'</span>
                  <p>'.$contents_print['detail_projet'].'</p>
                </div>
              </div>
            </div>
         </div>';
}
</code>```

This is my jquery ajax code :

```<code>$(document).ready(function(){
$('.materialboxed').materialbox();
 });

$( document ).ready( function () {
    $.ajax( {
            url: 'core/libs/contents-services.php?action=getFilterContent&id=3',
            type: "get",
            dataType: "html",
            success: function ( reponse ) {
                $( '#modal' ).html( reponse );
            }
        } );

    // the "href" attribute of the modal trigger must specify the modal ID that wants to be triggered
    $( '.modal' ).modal();
} );
</code>```

In my ajax code : the line url: 'core/libs/contents-services.php?action=getFilterContent&id=3', I have to use the id from the php/mysql request

I would like to make a link like this :
url: 'core/libs/contents-services.php?action=getFilterContent&id='.$_GET['id'].',

I hope I'am clear

Thanks for your help

http://portfolio.rabahbook.fr to see my working's site

答:
As I understand you get an Id from response and trying to assign it to ajax href. If this is your case, you can do something as below(please note the url_id variable.): </p>

```<code>var url_id =3;

$( document ).ready( function () {
$.ajax( {
  url: 'core/libs/contents-services.php?action=getFilterContent&id='+url_id,
  type: "get",
  dataType: "html",
  success: function ( reponse ) {
     $( '#modal' ).html( reponse );
     url_id  = response.url_id;/// get url id from response and assign it to
     //your  href
  }
});

 // the "href" attribute of the modal trigger must specify the modal ID
 //that wants to be triggered
 $( '.modal' ).modal();
 } );
 </script>
</code>```

Title: how to combine an id div and a php id

Body:
I don't know the specifications of PHP and an ID DIV. Here's my question :

Can I put in the same time an ID DIV named #modal and an ID PHP RETURN ?

while ( $contents_print = mysqli_fetch_array( $req_print ) ) {
    echo'

                  add

                    '.$contents_print['nom_projet'].'

'.$contents_print['detail_projet'].'

';
}

This is my jquery ajax code :

$(document).ready(function(){
$('.materialboxed').materialbox();
 });

$( document ).ready( function () {
    $.ajax( {
            url: 'core/libs/contents-services.php?action=getFilterContent&id=3',
            type: "get",
            dataType: "html",
            success: function ( reponse ) {
                $( '#modal' ).html( reponse );
            }
        } );

    // the "href" attribute of the modal trigger must specify the modal ID that wants to be triggered
    $( '.modal' ).modal();
} );

In my ajax code : the line url: 'core/libs/contents-services.php?action=getFilterContent&id=3', I have to use the id from the php/mysql request

I would like to make a link like this :
url: 'core/libs/contents-services.php?action=getFilterContent&id='.$_GET['id'].',

I hope I'am clear

Thanks for your help

http://portfolio.rabahbook.fr to see my working's site

Body:
As I understand you get an Id from response and trying to assign it to ajax href. If this is your case, you can do something as below(please note the url_id variable.):

var url_id =3;

$( document ).ready( function () {
$.ajax( {
  url: 'core/libs/contents-services.php?action=getFilterContent&id='+url_id,
  type: "get",
  dataType: "html",
  success: function ( reponse ) {
     $( '#modal' ).html( reponse );
     url_id  = response.url_id;/// get url id from response and assign it to
     //your  href
  }
});

 // the "href" attribute of the modal trigger must specify the modal ID
 //that wants to be triggered
 $( '.modal' ).modal();
 } );
 </script>


来源: stackexchange

问:
npm - EPERM: operation not permitted on Windows
I ran

```<code>npm config set prefix /usr/local
</code>```

After running that command,
When trying to run any npm commands on Windows OS I keep getting the below.

```<code>Error: EPERM: operation not permitted, mkdir 'C:\Program Files (x86)\Git\local'
at Error (native)
</code>```

Have deleted all files from

```<code>C:\Users\<your username>\.config\configstore\
</code>```

It did not work.

Any suggestion ?

答:
I had the same issue, as I was using my company LAN. And I just ran cmd.exe npm and I was able to execute my other commands without any error after that.

```<code>C:\Users\586656>cmd.exe npm
Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.
</code>```

Just sharing this, as it may help other folks who try to do this in their office LAN. Thank you.

ContentLicense: CC BY-SA 3.0

Body:
I ran

npm config set prefix /usr/local

After running that command,
When trying to run any npm commands on Windows OS I keep getting the below.

Error: EPERM: operation not permitted, mkdir 'C:\Program Files (x86)\Git\local'
at Error (native)

Have deleted all files from

C:\Users\<your username>\.config\configstore\

It did not work.

Any suggestion ?

Body:
I had the same issue, as I was using my company LAN. And I just ran cmd.exe npm and I was able to execute my other commands without any error after that.

C:\Users\586656>cmd.exe npm
Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.

Just sharing this, as it may help other folks who try to do this in their office LAN. Thank you.


问:
Load data on page scroll doesnt bot work perfectly
I am working on page where it will load news when it will reach to the end of page.

```<code> $(window).scroll(function () {
    if ($(window).scrollTop() >= $(document).height() - $(window).height() -50) {
        //if ($(window).scrollTop() >= $(document).height() - 100) {
        //alert("I am loading");
        GetRecords();
    }
  });
</code>```

Problem withe the above code it that it send multiple request to the server as i have mentione >= in the if condition i tried few thing but it doesnt seem to work properlt.

When i use == operation and $(window).scrollTop() == $(document).height() - $(window).height() it works fine on desktop but it doesn't trigger in mobile version.

I have header & footer in the page which i event didn't hide for troubleshooting but it still doesn't work properly

Anything which i can do to fix this issue

答:
I did the same thing and i was facing the same problem.

What i did is create a boolean isLoading and pass it to true when request is send
and only when you get the response then change the value to false.

After that add your variable in your scroll position test.

Example

```<code>var isLoading = false;

$(window).scroll(function(e){
  var maxHeight = $(document).height();
  var position = $(this).scrollTop() + $(window).height();
  if(position >= (maxHeight - 50) && !isLoading)
  {
    loadArticles();
    isLoading = true;
  }
});

function loadArticles() {
    loadData()
    .then(data => {
      //some code here
      isLoading = false;
    });
}
</code>```

Demo link of my draft

Body:
I am working on page where it will load news when it will reach to the end of page.

 $(window).scroll(function () {
    if ($(window).scrollTop() >= $(document).height() - $(window).height() -50) {
        //if ($(window).scrollTop() >= $(document).height() - 100) {
        //alert("I am loading");
        GetRecords();
    }
  });

Problem withe the above code it that it send multiple request to the server as i have mentione >= in the if condition i tried few thing but it doesnt seem to work properlt.

When i use == operation and $(window).scrollTop() == $(document).height() - $(window).height() it works fine on desktop but it doesn't trigger in mobile version.

I have header & footer in the page which i event didn't hide for troubleshooting but it still doesn't work properly

Anything which i can do to fix this issue

Body:
I did the same thing and i was facing the same problem.

What i did is create a boolean isLoading and pass it to true when request is send
and only when you get the response then change the value to false.

After that add your variable in your scroll position test.

Example

var isLoading = false;

$(window).scroll(function(e){
  var maxHeight = $(document).height();
  var position = $(this).scrollTop() + $(window).height();
  if(position >= (maxHeight - 50) && !isLoading)
  {
    loadArticles();
    isLoading = true;
  }
});

function loadArticles() {
    loadData()
    .then(data => {
      //some code here
      isLoading = false;
    });
}

Demo link of my draft


问:
Bootstrap Toggle Button, how change size (height and weight)
I need to change those attributes for adapting the UI to the design, but I would like to use Bootstrap as much as I can. Is there a way to do that keeping using the button and relative bootstrap classes?
It looks like it is not possible (tried to play with the inspector but didn't see any reaction...)

Sample below (original code from Bootstrap, just ignore the menu:-) )

.custom-header {
float: left;
}

.custom {

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="navbar navbar-default">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

    <div class="navbar-header custom-header">
      <button type="button" class="navbar-toggle collapsed custom" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li class="active">Link <span class="sr-only">(current)</span></li>
        <li>Link</li>
        <li class="dropdown">
          Dropdown <span class="caret"></span>
          <ul class="dropdown-menu">
            <li>Action</li>
            <li>Another action</li>
            <li>Something else here</li>
            <li role="separator" class="divider"></li>
            <li>Separated link</li>
            <li role="separator" class="divider"></li>
            <li>One more separated link</li>
          </ul>
        </li>
      </ul>
      <form class="navbar-form navbar-left">
        <div class="form-group">
          <input type="text" class="form-control" placeholder="Search">
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
      </form>
      <ul class="nav navbar-nav navbar-right">
        <li>Link</li>
        <li class="dropdown">
          Dropdown <span class="caret"></span>
          <ul class="dropdown-menu">
            <li>Action</li>
            <li>Another action</li>
            <li>Something else here</li>
            <li role="separator" class="divider"></li>
            <li>Separated link</li>
          </ul>
        </li>
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav></code>```

答:
The solution is in the span classes, I solved changed with different values here:</p>

```<code>.navbar-toggle .icon-bar {
    display: block;
    width: 18px;
    height: 1px;
    border-radius: 1px;
}
</code>```

Body:
I need to change those attributes for adapting the UI to the design, but I would like to use Bootstrap as much as I can. Is there a way to do that keeping using the button and relative bootstrap classes?
It looks like it is not possible (tried to play with the inspector but didn't see any reaction...)

Sample below (original code from Bootstrap, just ignore the menu:-) )

.custom-header {
float: left;
}

.custom {

}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

      <button type="button" class="navbar-toggle collapsed custom" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        Toggle navigation

      </button>

Link (current)

Link

          Dropdown

Action

Another action

Something else here

Separated link

One more separated link

      <form class="navbar-form navbar-left">

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

        <button type="submit" class="btn btn-default">Submit</button>
      </form>

Link

          Dropdown

Action

Another action

Something else here

Separated link

Body:
The solution is in the span classes, I solved changed with different values here:

.navbar-toggle .icon-bar {
    display: block;
    width: 18px;
    height: 1px;
    border-radius: 1px;
}


问:
How to implement open file chooser for Android 5.0 above in Xamarin?
I am using below code for opening file chooser, I am not sure how to implement it for Android 5.0 and above.

```<code>Action<IValueCallback, Java.Lang.String, Java.Lang.String> callback;

public FileChooserWebChromeClient(Action<IValueCallback, Java.Lang.String, Java.Lang.String> callback)
{
    this.callback = callback;
}

//For Android 4.1
[Java.Interop.Export]
public void openFileChooser(IValueCallback uploadMsg, Java.Lang.String acceptType, Java.Lang.String capture)
{
    callback(uploadMsg, acceptType, capture);
}

// For Android > 5.0
//I am stuck here, taken from Android
[Java.Interop.Export]
public bool onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)
{
    mUploadCallbackLollipop = filePathCallback;
    openFileChooserActivity();
    return true;
}
</code>```

Callback function:

```<code>var chrome = new FileChooserWebChromeClient((uploadMsg, acceptType, capture) =>
{
    MainActivity.UploadMessage = uploadMsg;
    if(Build.VERSION.SdkInt < BuildVersionCodes.Kitkat)
    {
        var i = new Intent(Intent.ActionGetContent);

        //To set all type of files
        i.SetType("image/*");

        //Here File Chooser dialog is started as Activity, and it gives result while coming back from that Activity.
        ((MainActivity)this.Context).StartActivityForResult(Intent.CreateChooser(i, "File Chooser"), MainActivity.GALLERY_INTENT_CALLED);
    }
    else
    {
        var i = new Intent(Intent.ActionOpenDocument);
        i.AddCategory(Intent.CategoryOpenable);

        //To set all type of files
        i.SetType("image/*");

        //Here File Chooser dialog is started as Activity, and it gives result while coming back from that Activity.
        ((MainActivity)this.Context).StartActivityForResult(Intent.CreateChooser(i, "File Chooser"), MainActivity.GALLERY_KITKAT_INTENT_CALLED);
    }
});
</code>```

How to implement callback for Android 5.0 above, please someone help me

答:
step1 =
    File upload will work , we need to give Read / Write permission in android manifest.
    in Main Activity.cs</p>

```<code>step2=
private Action<int, Result, Intent> resultCallbackvalue;

public void StartActivity(Intent intent, int requestCode, Action<int, Result, Intent> resultCallback)
{
this.resultCallbackvalue = resultCallback;
StartActivityForResult(intent, requestCode);
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (this.resultCallbackvalue != null)
{
this.resultCallbackvalue(requestCode, resultCode, data);
this.resultCallbackvalue = null;
}
}
step3= add ExtendedChromeClient,cs Inheriting from : WebChromeClient

private static int filechooser = 1;
private IValueCallback message;
private MainActivity activity = null;

  public ExtendedChromeClient(MainActivity context)
    {
        this.activity = context;
    }

  public override bool OnShowFileChooser(WebView webView, IValueCallback filePathCallback, FileChooserParams fileChooserParams)
    {
        this.message = filePathCallback;
        Intent chooserIntent = fileChooserParams.CreateIntent();
        chooserIntent.AddCategory(Intent.CategoryOpenable);
        this.activity.StartActivity(Intent.CreateChooser(chooserIntent, "File Chooser"), filechooser, this.OnActivityResult);
        return true;
    }

  private void OnActivityResult(int requestCode, Result resultCode, Intent data)
    {
        if (data != null)
        {
            if (requestCode == filechooser)
            {
                if (null == this.message)
                {
                    return;
                }

                this.message.OnReceiveValue(WebChromeClient.FileChooserParams.ParseResult((int)resultCode, data));
                this.message = null;
            }
        }
    }
</code>```

Body:
I am using below code for opening file chooser, I am not sure how to implement it for Android 5.0 and above.

Action<IValueCallback, Java.Lang.String, Java.Lang.String> callback;

public FileChooserWebChromeClient(Action<IValueCallback, Java.Lang.String, Java.Lang.String> callback)
{
    this.callback = callback;
}

//For Android 4.1
[Java.Interop.Export]
public void openFileChooser(IValueCallback uploadMsg, Java.Lang.String acceptType, Java.Lang.String capture)
{
    callback(uploadMsg, acceptType, capture);
}

// For Android > 5.0
//I am stuck here, taken from Android
[Java.Interop.Export]
public bool onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)
{
    mUploadCallbackLollipop = filePathCallback;
    openFileChooserActivity();
    return true;
}

Callback function:

var chrome = new FileChooserWebChromeClient((uploadMsg, acceptType, capture) =>
{
    MainActivity.UploadMessage = uploadMsg;
    if(Build.VERSION.SdkInt < BuildVersionCodes.Kitkat)
    {
        var i = new Intent(Intent.ActionGetContent);

        //To set all type of files
        i.SetType("image/*");

        //Here File Chooser dialog is started as Activity, and it gives result while coming back from that Activity.
        ((MainActivity)this.Context).StartActivityForResult(Intent.CreateChooser(i, "File Chooser"), MainActivity.GALLERY_INTENT_CALLED);
    }
    else
    {
        var i = new Intent(Intent.ActionOpenDocument);
        i.AddCategory(Intent.CategoryOpenable);

        //To set all type of files
        i.SetType("image/*");

        //Here File Chooser dialog is started as Activity, and it gives result while coming back from that Activity.
        ((MainActivity)this.Context).StartActivityForResult(Intent.CreateChooser(i, "File Chooser"), MainActivity.GALLERY_KITKAT_INTENT_CALLED);
    }
});

How to implement callback for Android 5.0 above, please someone help me

Body:
step1 =
    File upload will work , we need to give Read / Write permission in android manifest.
    in Main Activity.cs

step2=
private Action<int, Result, Intent> resultCallbackvalue;

public void StartActivity(Intent intent, int requestCode, Action<int, Result, Intent> resultCallback)
{
this.resultCallbackvalue = resultCallback;
StartActivityForResult(intent, requestCode);
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (this.resultCallbackvalue != null)
{
this.resultCallbackvalue(requestCode, resultCode, data);
this.resultCallbackvalue = null;
}
}
step3= add ExtendedChromeClient,cs Inheriting from : WebChromeClient

private static int filechooser = 1;
private IValueCallback message;
private MainActivity activity = null;

  public ExtendedChromeClient(MainActivity context)
    {
        this.activity = context;
    }

  public override bool OnShowFileChooser(WebView webView, IValueCallback filePathCallback, FileChooserParams fileChooserParams)
    {
        this.message = filePathCallback;
        Intent chooserIntent = fileChooserParams.CreateIntent();
        chooserIntent.AddCategory(Intent.CategoryOpenable);
        this.activity.StartActivity(Intent.CreateChooser(chooserIntent, "File Chooser"), filechooser, this.OnActivityResult);
        return true;
    }

  private void OnActivityResult(int requestCode, Result resultCode, Intent data)
    {
        if (data != null)
        {
            if (requestCode == filechooser)
            {
                if (null == this.message)
                {
                    return;
                }

                this.message.OnReceiveValue(WebChromeClient.FileChooserParams.ParseResult((int)resultCode, data));
                this.message = null;
            }
        }
    }


问:
Tomcat 8 not responsive serving static content
When deploying our application (Java, Spring) on Tomcat 7 it is fine. Now that we upgraded to Tomcat 8 it is very slow when serving static content. Looking at developer tools (see snapshot below), each request of static content (small .js and .css files) it takes as much as we have configured for connectionTimeout in server.xml. Because default is 20000, it may take 20 secs. for each file. When dropping this to 1000 it will be faster, and take 1 sec. for each one.

This happens in different development machines using default configurations. Other processes (web services requests, etc.) are performing ok.

I wonder what and where to start looking.

答:
In my case I just remove the compress filter from web.xml and everything back to normal.

The xml below don't work with tomcat 8, at least no in my application.

```<code><filter>
    <filter-name>compressionFilter</filter-name>
    <filter-class>com.googlecode.webutilities.filters.CompressionFilter</filter-class>
    <init-param>
        <param-name>compressionThreshold</param-name>
        <param-value>1024</param-value>
    </init-param>
    <init-param>
        <param-name>ignoreURLPattern</param-name>
        <param-value>.*\.(flv|mp3|mpg)</param-value>
    </init-param>
    <init-param>
        <param-name>ignoreMimes</param-name>
        <param-value>images/*,video/*, multipart/x-gzip</param-value>
    </init-param>
    <init-param>
        <param-name>ignoreUserAgentsPattern</param-name>
        <param-value>.*MSIE.*</param-value>
    </init-param>
 </filter>
 <filter-mapping>
    <filter-name>compressionFilter</filter-name>
    <url-pattern>*</url-pattern>
 </filter-mapping>
</code>```

Body:
In my case I just remove the compress filter from web.xml and everything back to normal.

The xml below don't work with tomcat 8, at least no in my application.

<filter>
    <filter-name>compressionFilter</filter-name>
    <filter-class>com.googlecode.webutilities.filters.CompressionFilter</filter-class>
    <init-param>
        <param-name>compressionThreshold</param-name>
        <param-value>1024</param-value>
    </init-param>
    <init-param>
        <param-name>ignoreURLPattern</param-name>
        <param-value>.*\.(flv|mp3|mpg)</param-value>
    </init-param>
    <init-param>
        <param-name>ignoreMimes</param-name>
        <param-value>images/*,video/*, multipart/x-gzip</param-value>
    </init-param>
    <init-param>
        <param-name>ignoreUserAgentsPattern</param-name>
        <param-value>.*MSIE.*</param-value>
    </init-param>
 </filter>
 <filter-mapping>
    <filter-name>compressionFilter</filter-name>
    <url-pattern>*</url-pattern>
 </filter-mapping>


问:
*ngIf to evaluate an updated variable
(Angular / JS learner) I have an object thats value gets updated via a service depending on which child controller is currently active.  I'm trying to get a different button to display based on this objects value.

My Parent Controller looks like:

```<code>import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { ChildDataService } from "../core/helpers/child-data.service";
import { Subscription } from "rxjs/Subscription";

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class ParentComponent implements OnInit {
  childDetails: {title?: string};

  private subscription:Subscription;

  constructor( private childDataService: ChildDataService) {
    this.childDataService.childLoaded$.subscribe(
      newChildDetails => {
        console.log(newChildDetails);
        this.childDetails = newChildDetails
      });
  }
  someFunction(){};

  someFunction2(){};
}
</code>```

And the relevant part of my parents HTML looks like:

```<code><div class="subheader">
  <h1>{{ childDetails.title }}</h1>
  <button *ngIf="childDetails.title == 'dashboard'" (click)="someFunction()">dashboard</button>
  <button *ngIf="childDetails.title == 'page2'" (click)="someFunction2()">page2</button>
</div>
</code>```

This throws the error: "Cannot read property 'title' of undefined".  My service is working as intended as if I remove the 2 buttons the title  works.  A point in the right direction would be awesome. Thanks

答:
Use a safe navigation operator</p>

```<code><div class="subheader">
  <h1>{{ childDetails?.title }}</h1>
  <button *ngIf="childDetails?.title == 'dashboard'" (click)="someFunction()">dashboard</button>
  <button *ngIf="childDetails?.title == 'page2'" (click)="someFunction2()">page2</button>
</div>
</code>```

Title: *ngIf to evaluate an updated variable

Body:
(Angular / JS learner) I have an object thats value gets updated via a service depending on which child controller is currently active.  I'm trying to get a different button to display based on this objects value.

My Parent Controller looks like:

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { ChildDataService } from "../core/helpers/child-data.service";
import { Subscription } from "rxjs/Subscription";

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class ParentComponent implements OnInit {
  childDetails: {title?: string};

  private subscription:Subscription;

  constructor( private childDataService: ChildDataService) {
    this.childDataService.childLoaded$.subscribe(
      newChildDetails => {
        console.log(newChildDetails);
        this.childDetails = newChildDetails
      });
  }
  someFunction(){};

  someFunction2(){};
}

And the relevant part of my parents HTML looks like:

{{ childDetails.title }}

  <button *ngIf="childDetails.title == 'dashboard'" (click)="someFunction()">dashboard</button>
  <button *ngIf="childDetails.title == 'page2'" (click)="someFunction2()">page2</button>

This throws the error: "Cannot read property 'title' of undefined".  My service is working as intended as if I remove the 2 buttons the title  works.  A point in the right direction would be awesome. Thanks

Body:
Use a safe navigation operator

<div class="subheader">
  <h1>{{ childDetails?.title }}</h1>
  <button *ngIf="childDetails?.title == 'dashboard'" (click)="someFunction()">dashboard</button>
  <button *ngIf="childDetails?.title == 'page2'" (click)="someFunction2()">page2</button>
</div>


问:
How to add/reference .jar files in your project when you don't have an IDE
I am new to Java (basically a LAMP developer). I got this JAVA API to parse .pst files and show all the inbox messages.

I tried executing a given .class file but it throws exceptions. I need to add/reference some .jar files provided by the API.

I don't have any IDE for Java yet. Wikihow says

When your Java project requires JAR
  libraries to function, you have to
  configure your project to include the
  libraries in its build path.
  Fortunately, Eclipse makes this
  process simple and easy to remember.
  The build used here is Eclipse Java -
  Ganymede 3.4.0.

So, what configuration do I have to do? Or is it better to get Eclipse IDE? I just have a single .class file to be executed.

A few other questions that I checked but could not get my answer -
How to add external jar libraries to an android project from the command line

How do I include external JARs in my own Project JAR

答:
You should put them on your classpath, like

java -classpath someJar.jar YourMainClass

And, of course, you can do the same for javac.

If you need to have more than one jar or directory on your classpath, you'll need to use your platform's default path separator. For example, on Windows,

java -classpath someJar.jar;myJar.jar YourMainClass

On a side note, you might find it easier to use an IDE to manage this sort of stuff. I've personally used just my slightly scriptable editor and have managed fine. But it's good to know how to do this stuff by command line.

ContentLicense: CC BY-SA 2.5


问:
MVC 5 Razor reload current view
Is there any way to reload the current razor view by clicking on a link, without having to tell it the controller and action?

If I have a link on the Home/Index View, with the Home controller, I can do something like this:

```<code>@Html.ActionLink("some name", "Index", "Home")
</code>```

But, if I want to have a link in the _Layout.cshtml that will be visible on all pages, I need something like this:

```<code>@Html.ActionLink("some name", default action of the current view, current controller, some parameter)
</code>```

It probably can not be done with the actionlink, but is there some other way to do this?

Thanks in advance :)

答:
Your can provide null for the controller, action and route value arguments which will default to the current values.

For example if you have the following method in ProductsController

```<code>public ActionLink Details(int id)
</code>```

and navigated to that url with ../Products/Details/2, then the following link in that page or its layout

```<code>@Html.ActionLink("Refresh Page", null, null, null)
</code>```

will generate the same url, i.e. ../Products/Details/2

Note this works for route values (matching your route definitions), but will not add query string values

Title: MVC 5 Razor reload current view

Body:
Is there any way to reload the current razor view by clicking on a link, without having to tell it the controller and action?

If I have a link on the Home/Index View, with the Home controller, I can do something like this:

@Html.ActionLink("some name", "Index", "Home")

But, if I want to have a link in the _Layout.cshtml that will be visible on all pages, I need something like this:

@Html.ActionLink("some name", default action of the current view, current controller, some parameter)

It probably can not be done with the actionlink, but is there some other way to do this?

Thanks in advance :)

Body:
Your can provide null for the controller, action and route value arguments which will default to the current values.

For example if you have the following method in ProductsController

public ActionLink Details(int id)

and navigated to that url with ../Products/Details/2, then the following link in that page or its layout

@Html.ActionLink("Refresh Page", null, null, null)

will generate the same url, i.e. ../Products/Details/2

Note this works for route values (matching your route definitions), but will not add query string values


问:
Angular 2 Typescript parse json to object
I am newbie to Angular2 and Typescript. I am learning nowadays. I try to get data from a REST service then I want to make a list and insert this data which comes from the service.
So my API link is http://jsonplaceholder.typicode.com/users/1

here is my HttpTestService.ts code;

```<code>import {Component} from '@angular/core';
import {Http} from '@angular/http';
import {Headers} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import {Injectable} from '@angular/core';

import 'rxjs/add/operator/map';

@Injectable()
export class HTTPTestService{
  constructor(private _http:Http){}
    getUser(){
      return this._http.get("http://jsonplaceholder.typicode.com/users/1")
      .map(res=>res.json());
    };
}}
</code>```

Here is my HttpTestComponent.ts;

```<code>import { Component } from '@angular/core';
import {HTTPTestService} from './http-test.service';
import { User } from './user';

@Component({
  selector:'http-test',
  template:`
    <button (click)="onGet()">Get Data</button><br/>
    <div>Output:{{getData}}</div><br/>
    <button (click) = "onPost()">Post Data</button><br/>
    <div>Output:{{postData}}</div><br/>
    <button (click) = "onPromiseGet()">Get Data(w Promise)</button><br/>
    <div>Output:{{getPromiseData}}</div><br/>
  `,
  providers:[HTTPTestService]
})

export class HTTPTestComponent{
  getData:string;
  getPromiseData:string;
  postData:string;

  constructor(private _httpService:HTTPTestService){}

  onGet(){
    console.log('Getting user now.');
    this._httpService.getUser().subscribe(
      data =>this.getData = JSON.stringify(data),
      error=>alert(error),
      ()=>console.log('Finished Get')
    );
  }}
</code>```

And here is my User.ts

```<code> export class User{
  constructor(public id: number,public name:string) { }
 }
</code>```

How do I fill my User class and then how do I add a generic list to my User class.

Best regards

答:
As far as I understand your question, just create a new Object of User type and pass desired data, in your case it is id and name.

```<code>private userList: Array<User> = new Array<User>();

onGet(){
    console.log('Getting user now.');
    this._httpService.getUser().subscribe(
      data => this.parseUser(data),
      error=>alert(error),
      ()=>console.log('Finished Get')
    );
  }

parseUser(data) {
   let user = new User(data.id, data.name);
   this.userList.push(user);
}
</code>```

To create list of users just make an array of User like that
private Users: Array<User> = new Array<User>(); remember to import User.

EDIT.
For test purpose change this

```<code>@Component({
  selector:'http-test',
  template:`
    <button (click)="onGet()">Get Data</button><br/>
    <div>Output:{{getData}}</div><br/>
    <button (click) = "onPost()">Post Data</button><br/>
    <div>Output:{{postData}}</div><br/>
    <button (click) = "onPromiseGet()">Get Data(w Promise)</button><br/>
    <div>Output:{{getPromiseData}}</div><br/>

    <div *ngFor="let user of userList">
       <p>Id: {{user.id}}</p>
       <p>Name: {{user.name}}>/p>
       <br />
    </div>
  `,
  providers:[HTTPTestService]
})
</code>```

When response come angular will print data :)

Body:
I am newbie to Angular2 and Typescript. I am learning nowadays. I try to get data from a REST service then I want to make a list and insert this data which comes from the service.
So my API link is http://jsonplaceholder.typicode.com/users/1

here is my HttpTestService.ts code;

import {Component} from '@angular/core';
import {Http} from '@angular/http';
import {Headers} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import {Injectable} from '@angular/core';

import 'rxjs/add/operator/map';

@Injectable()
export class HTTPTestService{
  constructor(private _http:Http){}
    getUser(){
      return this._http.get("http://jsonplaceholder.typicode.com/users/1")
      .map(res=>res.json());
    };
}}

Here is my HttpTestComponent.ts;

import { Component } from '@angular/core';
import {HTTPTestService} from './http-test.service';
import { User } from './user';

@Component({
  selector:'http-test',
  template:`
    <button (click)="onGet()">Get Data</button>

Output:{{getData}}

    <button (click) = "onPost()">Post Data</button>

Output:{{postData}}

    <button (click) = "onPromiseGet()">Get Data(w Promise)</button>

Output:{{getPromiseData}}

  `,
  providers:[HTTPTestService]
})

export class HTTPTestComponent{
  getData:string;
  getPromiseData:string;
  postData:string;

  constructor(private _httpService:HTTPTestService){}

  onGet(){
    console.log('Getting user now.');
    this._httpService.getUser().subscribe(
      data =>this.getData = JSON.stringify(data),
      error=>alert(error),
      ()=>console.log('Finished Get')
    );
  }}

And here is my User.ts

 export class User{
  constructor(public id: number,public name:string) { }
 }

How do I fill my User class and then how do I add a generic list to my User class.

Best regards

Body:
As far as I understand your question, just create a new Object of User type and pass desired data, in your case it is id and name.

private userList: Array<User> = new Array<User>();

onGet(){
    console.log('Getting user now.');
    this._httpService.getUser().subscribe(
      data => this.parseUser(data),
      error=>alert(error),
      ()=>console.log('Finished Get')
    );
  }

parseUser(data) {
   let user = new User(data.id, data.name);
   this.userList.push(user);
}

To create list of users just make an array of User like that
private Users: Array<User> = new Array<User>(); remember to import User.

EDIT.
For test purpose change this

@Component({
  selector:'http-test',
  template:`
    <button (click)="onGet()">Get Data</button><br/>
    <div>Output:{{getData}}</div><br/>
    <button (click) = "onPost()">Post Data</button><br/>
    <div>Output:{{postData}}</div><br/>
    <button (click) = "onPromiseGet()">Get Data(w Promise)</button><br/>
    <div>Output:{{getPromiseData}}</div><br/>

    <div *ngFor="let user of userList">
       <p>Id: {{user.id}}</p>
       <p>Name: {{user.name}}>/p>
       <br />
    </div>
  `,
  providers:[HTTPTestService]
})

When response come angular will print data :)


问:
In Emacs, can we maximize current active window, and then restore it back in multiple window environment?
I like to open multiple window, each with its own file opened. Sometimes, I want to maximize the one I edited to occupy whole screen, and then to restore it back to its previous size and position..

Is there a way?

According to the emacs menu, I can only figure out enlarge-window, shrink-window.. thats it..

答: Use the command window-configuration-to-register: M-x window-configuration-to-register, press the Enter key, then some register (character), e.g. a. To maximize current window, use C-x 1. When you want to restore, type C-x r j a.


问:
Aggregating rows from table2 to avoid duplicating rows from table 1
I am trying to combine two tables - one with item entries and one with value entries. The table with item entries only contain one entry number, whereas the table with value entries contain more entries per item entry. So its a one to many relationship.

When I join the two tables, SQL gives me duplicate rows for every value entry.
(Item entry no. far left, value entry no. far right)

```<code>**3788138** | 28-CEN | 1 | 13.991,1 | **5223372**
**3788138** | 28-CEN | 1 | 0 | **5010790**
**3788138** | 28-CEN | 1 | 0,06 | **6236002**
</code>```

What I want to do is making one item entry, where I sum the value entries.

```<code>**3788138** | 28-CEN | 1 | **13.991,16**
</code>```

My SQL statement looks like this:

```<code>SELECT ILE.[Entry No_] as 'Varepostløbenr.', ILE.[Posting Date], ILE.[Document No_], ILE.[Location Code], ILE.[Invoiced Quantity], ILE.[Remaining Quantity], ILE.[Positive], ILE.[Open], ILE.[Item No_], VE.[Cost posted to G_L], VE.[Entry No_] as 'Værdipostløbenr.'
FROM [VVS Eksperten AS Salg$Item Ledger Entry] AS ILE JOIN
     [VVS Eksperten AS Salg$Value Entry] AS VE
     ON ILE.[Entry No_] = VE.[Item Ledger Entry No_]
</code>```

Hope someone can help me out :-)

答:
Basically what you want to do is to </p>

```<code>SELECT col_1, col_2..col_n, SUM(value_column)

...

GROUP BY(col_1, col_2..col_n)
</code>```

Body:
I am trying to combine two tables - one with item entries and one with value entries. The table with item entries only contain one entry number, whereas the table with value entries contain more entries per item entry. So its a one to many relationship.

When I join the two tables, SQL gives me duplicate rows for every value entry.
(Item entry no. far left, value entry no. far right)

**3788138** | 28-CEN | 1 | 13.991,1 | **5223372**
**3788138** | 28-CEN | 1 | 0 | **5010790**
**3788138** | 28-CEN | 1 | 0,06 | **6236002**

What I want to do is making one item entry, where I sum the value entries.

**3788138** | 28-CEN | 1 | **13.991,16**

My SQL statement looks like this:

SELECT ILE.[Entry No_] as 'Varepostløbenr.', ILE.[Posting Date], ILE.[Document No_], ILE.[Location Code], ILE.[Invoiced Quantity], ILE.[Remaining Quantity], ILE.[Positive], ILE.[Open], ILE.[Item No_], VE.[Cost posted to G_L], VE.[Entry No_] as 'Værdipostløbenr.'
FROM [VVS Eksperten AS Salg$Item Ledger Entry] AS ILE JOIN
     [VVS Eksperten AS Salg$Value Entry] AS VE
     ON ILE.[Entry No_] = VE.[Item Ledger Entry No_]

Hope someone can help me out :-)

Body:
Basically what you want to do is to

SELECT col_1, col_2..col_n, SUM(value_column)

...

GROUP BY(col_1, col_2..col_n)


问:
SQL Query for paramaterized dynamic table
One of the product teams I manage has an abundance of queries that use dynamic sql queries injecting the table in using concatenation. While it has sanitisation, I am trying to completely remove dynamic sql.

Is there a way to parameterise the table name?
I am trying to think of how I can query a table something like:

```<code>SELECT * FROM (SELECT DISTINCT Table_Name FROM INFORMATION_SCHEMA.Tables WHERE Table_Name = :queryParam)
</code>```

Is this possible?

答:
There is no way to "properly" prevent SQL injection completely from within SQL, the calling application layer should do this prior to executing any SQL statement.

Solve the problem by using an ORM or building the code to protect yourself from SQL injection when you generate the SQL in the application code.

This feels like a classic XY problem, try to take a step back and consider that you need to protect the access to the SQL server itself rather than sanitise everything from within "after" your SQL server has been accessed.

Body:
One of the product teams I manage has an abundance of queries that use dynamic sql queries injecting the table in using concatenation. While it has sanitisation, I am trying to completely remove dynamic sql.

Is there a way to parameterise the table name?
I am trying to think of how I can query a table something like:

SELECT * FROM (SELECT DISTINCT Table_Name FROM INFORMATION_SCHEMA.Tables WHERE Table_Name = :queryParam)

Is this possible?


问:
PhpStorm generating blocks on initialise
I wanted to disable the feature of PhpStorm when initialising fields from constructor to make a comment block like this:

```<code>/**
 * @var ...
 */
</code>```

So I went to settings > editor > file and code templates > includes. And from there I deleted the file for generating that block (forgot how it was called), and now when I initialise fields I am getting this

```<code>/**
 *
 */
</code>```

Which is even more annoying. How can I remove it completely?

答:
ATM it's not possible to not to add PHPDoc for such IDE-added fields.

https://youtrack.jetbrains.com/issue/WI-31771 -- watch this ticket (star/vote/comment) to get notified on any progress.

Body:
I wanted to disable the feature of PhpStorm when initialising fields from constructor to make a comment block like this:

/**
 * @var ...
 */

So I went to settings > editor > file and code templates > includes. And from there I deleted the file for generating that block (forgot how it was called), and now when I initialise fields I am getting this

/**
 *
 */

Which is even more annoying. How can I remove it completely?


问:
MySQL - Best practices for tables with custom and default entries
I want to have a list that consists of default and custom entries. So, for example, on my software when a dealership is created and want to put a car in their inventory I want them to be able to select from a list of types of cars that already exists in the database and also from types of cars they will be adding as needed but only for that dealership.

How should I build this?

Should I have a table with the default types and another one with the custom types of that dealership and when requested I return both? -> each query will have to access 2 tables.

Should I have a single table with a column with the dealership ID and when requested return all that have the dealership ID and all that don't have any dealership ID (the default ones)? -> each query will have to return results with both no ID and dealership ID.

Should I have a single table with a column with the dealership ID and every time a new dealership is created I duplicate the default entries but their ID on it? -> Can really become monstrous and with duplicate entries.

Is there a better way to do this?

Example:

I just created a dealership and when I try to add a car to my inventory I see the options Mercedes, Volkswagen and Kia. But I want to add a Jaguar and it's not on the list. I want to add it only to my dealerships's list, so the next time I try to add a Jaguar the option is already there.

PS: I have tried searching for a solution for this but couldn't find anything.

答:
You definitely should avoid creating a separate table for each dealership.

Your second choice is best. You may want a table with columns like this:

```<code>  id
  zone_id
  dealership_id
  maker_id
  maker_name
  model_id
  model_name
  model_number
</code>```

Then you can run queries like this:

```<code>SELECT model_name, model_number
  FROM tbl
 WHERE (dealership_id = :current_dealer: OR dealership_id IS NULL)
   AND (zone_id = :current_zone: OR zone_id IS NULL)
   AND (maker_id = :current_maker: OR maker_id IS NULL)
</code>```

You can write a query like this to express the precise business rules for the choices for each dealer site.

Why add zones? Some vehicle makers have regional variations on their products. For example, internal combustion engines in California have more stringent regulations about exhaust than the rest of the US. The vehicle makers have zone offices in California to help coordinate that.  Subaru sells a version of its vehicles specifically designed for New England in the Eastern US.

Body:
You definitely should avoid creating a separate table for each dealership.

Your second choice is best. You may want a table with columns like this:

  id
  zone_id
  dealership_id
  maker_id
  maker_name
  model_id
  model_name
  model_number

Then you can run queries like this:

SELECT model_name, model_number
  FROM tbl
 WHERE (dealership_id = :current_dealer: OR dealership_id IS NULL)
   AND (zone_id = :current_zone: OR zone_id IS NULL)
   AND (maker_id = :current_maker: OR maker_id IS NULL)

You can write a query like this to express the precise business rules for the choices for each dealer site.

Why add zones? Some vehicle makers have regional variations on their products. For example, internal combustion engines in California have more stringent regulations about exhaust than the rest of the US. The vehicle makers have zone offices in California to help coordinate that.  Subaru sells a version of its vehicles specifically designed for New England in the Eastern US.


问:
How to get the value of an attribute using XPath
I have been testing using Selenium WebDriver and I have been looking for an XPath code to get the value of the attribute of an HTML element as part of my regression testing. But I couldn't find a good answer.

Here is my sample html element:

```<code><div class="firstdiv" alt="testdiv"></div>
</code>```

I want to get the value of the "alt" attribute using the XPath. I have an XPath to get to the div element using the class attribute which is:

```<code>//div[@class="firstdiv"]
</code>```

Now, I am looking for an XPath code to get the value of the "alt" attribute. The assumption is that I don't know what is the value of the "alt" attribute.

答:
Selenium Xpath can only return elements.
You should pass javascript function that executes xpaths and returns strings to selenium.

I'm not sure why they made it this way. Xpath should support returning strings.

Body:
I have been testing using Selenium WebDriver and I have been looking for an XPath code to get the value of the attribute of an HTML element as part of my regression testing. But I couldn't find a good answer.

Here is my sample html element:

I want to get the value of the "alt" attribute using the XPath. I have an XPath to get to the div element using the class attribute which is:

//div[@class="firstdiv"]

Now, I am looking for an XPath code to get the value of the "alt" attribute. The assumption is that I don't know what is the value of the "alt" attribute.


问:
Where should I store PGO database files?
I have been looking into using Profile Guided Optimisation in Visual C++ 2013. I'm happy with executing the training set using different scenarios as a manual step, but would like the final optimised build and link to work on our CI build server.

With that in mind, where is the best place for me to store the PGO profile databases? Storing them into version control (Git in our case) is the most convenient place, but I'm aware that they are binary files in the order of tens, potentially even hundreds, of megabytes and these won't necessarily store well in a source control system.

Alternatively, is there a better solution or best practices for integrating PGO into our automated builds?

答:
You have multiple choices here, you can pick one of them with considering the tradeoffs.

Do you use PGO for whole code base, or for some hotspots or modules? How often do you refresh the databases.

Is that a huge problem to release sth, with inappropriate PGO databases.

How big is your project, and how big it can be in the worst case

Is it acceptable to store PGO databases in source control in this worst case.

Through your answers you can create a route to yourself.

If you dont refresh the PGO databases too often and if the binary sizes wont ruin your project, you can store them within version control.

If you regenerate them for each commit, you can put them a separate repository which includes, real code bases commit id(on which commit PGO profile databases created) as a commit message

Or if you dont generate them too often, and when you return back to a specific commit, its ok to regenerate the databases you may not store them, just put into CI build machine.

Or you can make another combination around this opinions :)


问:
HTTP-EQUIV="REFRESH" isn't working on android web view
I have a web page with a basic form (like a newsletter subscription).

The user sends its information and gets a success page with a link to the form submission page. If he doesn't click on the link the page will be automatically redirected after 5 seconds.

```<code><meta http-equiv="refresh" content="5;url=www.site.com" />
</code>```

So far so good! It works as expected in both desktop and mobile browsers.

Then I created an android app (min API SDK 21) with a web view to load the site.

The problem is that the auto refresh isn't working inside the web view...

Am I missing something? I'm trying to avoid the javascript hack...

Thanks for your time!

EDIT

I notice that when I click on the new form submission page link it opens the default browser instead of rendering it on the web view!

答:
After searching for the problem, I came to a solution by resetting the URL on URL loading.

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ...

    mWebView = findViewById(R.id.webview);
    mWebView.setWebViewClient(new WebViewClient(){
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            mWebView.loadUrl(url);
            return true;
        }
    });
    mWebView.loadUrl(url);
}
</code>```

It's working, but I think it can be improved.

My initial problem was that I wasn't setting a WebViewClient.

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ...

    mWebView = findViewById(R.id.webview);
    mWebView.loadUrl(url);
}
</code>```

Thus, I think I just need to add a WebViewClient and it'll work

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ...

    mWebView = findViewById(R.id.webview);
    mWebView.setWebViewClient(new WebViewClient());
    mWebView.loadUrl(url);
}
</code>```

Note, and if we want javascript to work we need to enable it

```<code>mWebView.getSettings().setJavaScriptEnabled(true);
</code>```

Body:
I have a web page with a basic form (like a newsletter subscription).

The user sends its information and gets a success page with a link to the form submission page. If he doesn't click on the link the page will be automatically redirected after 5 seconds.

<meta http-equiv="refresh" content="5;url=www.site.com" />

So far so good! It works as expected in both desktop and mobile browsers.

Then I created an android app (min API SDK 21) with a web view to load the site.

The problem is that the auto refresh isn't working inside the web view...

Am I missing something? I'm trying to avoid the javascript hack...

Thanks for your time!

EDIT

I notice that when I click on the new form submission page link it opens the default browser instead of rendering it on the web view!

Body:
After searching for the problem, I came to a solution by resetting the URL on URL loading.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ...

    mWebView = findViewById(R.id.webview);
    mWebView.setWebViewClient(new WebViewClient(){
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            mWebView.loadUrl(url);
            return true;
        }
    });
    mWebView.loadUrl(url);
}

It's working, but I think it can be improved.

My initial problem was that I wasn't setting a WebViewClient.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ...

    mWebView = findViewById(R.id.webview);
    mWebView.loadUrl(url);
}

Thus, I think I just need to add a WebViewClient and it'll work

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ...

    mWebView = findViewById(R.id.webview);
    mWebView.setWebViewClient(new WebViewClient());
    mWebView.loadUrl(url);
}

Note, and if we want javascript to work we need to enable it

mWebView.getSettings().setJavaScriptEnabled(true);


问:
JWT Token for distrubuted system running on multiple server instance
I am using JWT token for rest api's security.

When user is logged in check user's credentials with DB.

If it matched we are encrypting it for further security and then passing it to jwt to create a token

Now in order to match user's token we need to keep password somewhere so that we can match them when user sends any request after logged in

we can do it 2 ways
1. Keep detail in Database and each time rest call is fired check token with token in Database which is too costly for each rest call
2. Preserve secret somewhere in JVM and use it. Here I have tried HttpSession from package

javax.servlet.http.HttpServletRequest

// My key issue code

```<code>// Encrypt it
    Key key = keyGenerator.generateKey(password);
    jwtToken = Jwts.builder()
            .setSubject(username)
            .setIssuer(uriInfo.getAbsolutePath().toString())
            .setIssuedAt(new Date())
            .setExpiration(toDate(LocalDateTime.now().plusMinutes(1)))
            .signWith(SignatureAlgorithm.HS512, key)
            .compact();
</code>```

// Adding details to session

```<code>HttpSession httpSession = currentRequest.getSession();
httpSession.setAttribute("userSecret", password)
</code>```

This works fine for single Server instance.

But at some point we need to scale up and run multiple instance of server.

How do we handle this case where user may logged in using 1 instance and may serving rest call using another instance using load balancing.

As users secret is available only in first Server's JVM.

答:
You can share the private key, which was used for encrypting the JWT, among the servers. When a servers gets an API call, you can try to decrypt the JWT with the private key. If the decryption is successful, you have a valid a JWT and you can process the request. If the decryption fails, that means it's an invalid JWT. Once a JWT has been created, you don't need to hit the database. That's the primary usage of JWT in my opinion.
I am not sure what you mean by userSecret.

Body:
I am using JWT token for rest api's security.

When user is logged in check user's credentials with DB.

If it matched we are encrypting it for further security and then passing it to jwt to create a token

Now in order to match user's token we need to keep password somewhere so that we can match them when user sends any request after logged in

we can do it 2 ways
1. Keep detail in Database and each time rest call is fired check token with token in Database which is too costly for each rest call
2. Preserve secret somewhere in JVM and use it. Here I have tried HttpSession from package

javax.servlet.http.HttpServletRequest

// My key issue code

// Encrypt it
    Key key = keyGenerator.generateKey(password);
    jwtToken = Jwts.builder()
            .setSubject(username)
            .setIssuer(uriInfo.getAbsolutePath().toString())
            .setIssuedAt(new Date())
            .setExpiration(toDate(LocalDateTime.now().plusMinutes(1)))
            .signWith(SignatureAlgorithm.HS512, key)
            .compact();

// Adding details to session

HttpSession httpSession = currentRequest.getSession();
httpSession.setAttribute("userSecret", password)

This works fine for single Server instance.

But at some point we need to scale up and run multiple instance of server.

How do we handle this case where user may logged in using 1 instance and may serving rest call using another instance using load balancing.

As users secret is available only in first Server's JVM.


问:
null reference exception
i get a system null reference exception error that displays as follows.

Am performing validation on 4 "dropdownlists". what could i have done wrong?

code behind below.

```<code>  protected void addExhibitButton_Click(object sender, EventArgs e)
    {

        if (Page.IsValid)
        {
            DateTime exhibitDate = DateTime.Now;
            int caseid = Convert.ToInt32(DropDownListcaseid.SelectedItem.Text);
            string exhibittype = exhibitTypeDropDownList.Text.ToString();
            string storedloc = storedLocationDropDownList.Text.ToString();
            string offid = DropDownList1.SelectedItem.Text.ToString();
            string status = "Pending";
            Stream imgStream = exhibitImageFileUpload.PostedFile.InputStream;
            int imgLen = exhibitImageFileUpload.PostedFile.ContentLength;
            byte[] imgBinaryData = new byte[imgLen];
            int n = imgStream.Read(imgBinaryData,0,imgLen);
            try
            {
                SqlConnection connections = new SqlConnection(strConn);
                SqlCommand command = new SqlCommand("INSERT INTO Exhibits (CaseID, ExhibitType, ExhibitImage, DateReceived, StoredLocation, InvestigationStatus, OfficerID, SuspectID, InvestigatorID, ManagerID, AdminID ) VALUES (@CaseID, @ExhibitType, @ExhibitImage, @DateReceived, @StoredLocation, @InvestigationStatus, @OfficerID, @SuspectID, @InvestigatorID, @ManagerID, @AdminID)", connections);

                SqlParameter param0 = new SqlParameter("@CaseID", SqlDbType.Int);
                param0.Value = caseid;
                command.Parameters.Add(param0);

                SqlParameter param1 = new SqlParameter("@ExhibitType", SqlDbType.NText);
                param1.Value = exhibittype;
                command.Parameters.Add(param1);

                SqlParameter param2 = new SqlParameter("@ExhibitImage", SqlDbType.Image);
                param2.Value = imgBinaryData;
                command.Parameters.Add(param2);

                SqlParameter param3 = new SqlParameter("@DateReceived", SqlDbType.SmallDateTime);
                param3.Value = exhibitDate;
                command.Parameters.Add(param3);

                SqlParameter param4 = new SqlParameter("@StoredLocation", SqlDbType.NText);
                param4.Value = storedloc;
                command.Parameters.Add(param4);

                SqlParameter param5 = new SqlParameter("@InvestigationStatus", SqlDbType.VarChar, 50);
                param5.Value = status;
                command.Parameters.Add(param5);

                SqlParameter param6 = new SqlParameter("@OfficerID", SqlDbType.NChar, 10);
                param6.Value = offid;
                command.Parameters.Add(param6);

                SqlParameter param7 = new SqlParameter("@SuspectID", SqlDbType.NChar, 10);
                param7.Value = DBNull.Value;
                command.Parameters.Add(param7);

                SqlParameter param8 = new SqlParameter("@InvestigatorID", SqlDbType.NChar, 10);
                param8.Value = DBNull.Value;
                command.Parameters.Add(param8);

                SqlParameter param9 = new SqlParameter("@ManagerID", SqlDbType.NChar, 10);
                param9.Value = DBNull.Value;
                command.Parameters.Add(param9);

                SqlParameter param10 = new SqlParameter("@AdminID", SqlDbType.NChar, 10);
                param10.Value = adminID;
                command.Parameters.Add(param10);

                connections.Open();
                int numRowsAffected = command.ExecuteNonQuery();
                connections.Close();

                if (numRowsAffected != 0)
                {

                    DropDownListcaseid.ClearSelection();
                    exhibitTypeDropDownList.Text = null;
                    storedLocationDropDownList.Text = null;
                    DropDownList1.ClearSelection();
                    messageLabel.Text = "Rows Inserted successfully";
                    messageLabel.Visible = true;
                }
                else
                {
                    messageLabel.Text = "An error occured while inserting columns.";
                    messageLabel.Visible = true;

                }
            }
            catch (Exception ex)
            {
                string script = "<script>alert('" + ex.Message + "');</script>";
            }

        }

    }
</code>```

Image of page being run below

I applied validation items to all drop down lists except the one with the browse button(which offcourse is not a dropdown item). clearly according to my knowledge i havent left out any field.so what could be the cause?

答: Debug Your code and You will see which object or property is null. The simplest way to check if dropdownlist has selected item is to check SelectedIndex property, which should be > -1</p>

Title: null reference exception

Body:
i get a system null reference exception error that displays as follows.

Am performing validation on 4 "dropdownlists". what could i have done wrong?

code behind below.

  protected void addExhibitButton_Click(object sender, EventArgs e)
    {

        if (Page.IsValid)
        {
            DateTime exhibitDate = DateTime.Now;
            int caseid = Convert.ToInt32(DropDownListcaseid.SelectedItem.Text);
            string exhibittype = exhibitTypeDropDownList.Text.ToString();
            string storedloc = storedLocationDropDownList.Text.ToString();
            string offid = DropDownList1.SelectedItem.Text.ToString();
            string status = "Pending";
            Stream imgStream = exhibitImageFileUpload.PostedFile.InputStream;
            int imgLen = exhibitImageFileUpload.PostedFile.ContentLength;
            byte[] imgBinaryData = new byte[imgLen];
            int n = imgStream.Read(imgBinaryData,0,imgLen);
            try
            {
                SqlConnection connections = new SqlConnection(strConn);
                SqlCommand command = new SqlCommand("INSERT INTO Exhibits (CaseID, ExhibitType, ExhibitImage, DateReceived, StoredLocation, InvestigationStatus, OfficerID, SuspectID, InvestigatorID, ManagerID, AdminID ) VALUES (@CaseID, @ExhibitType, @ExhibitImage, @DateReceived, @StoredLocation, @InvestigationStatus, @OfficerID, @SuspectID, @InvestigatorID, @ManagerID, @AdminID)", connections);

                SqlParameter param0 = new SqlParameter("@CaseID", SqlDbType.Int);
                param0.Value = caseid;
                command.Parameters.Add(param0);

                SqlParameter param1 = new SqlParameter("@ExhibitType", SqlDbType.NText);
                param1.Value = exhibittype;
                command.Parameters.Add(param1);

                SqlParameter param2 = new SqlParameter("@ExhibitImage", SqlDbType.Image);
                param2.Value = imgBinaryData;
                command.Parameters.Add(param2);

                SqlParameter param3 = new SqlParameter("@DateReceived", SqlDbType.SmallDateTime);
                param3.Value = exhibitDate;
                command.Parameters.Add(param3);

                SqlParameter param4 = new SqlParameter("@StoredLocation", SqlDbType.NText);
                param4.Value = storedloc;
                command.Parameters.Add(param4);

                SqlParameter param5 = new SqlParameter("@InvestigationStatus", SqlDbType.VarChar, 50);
                param5.Value = status;
                command.Parameters.Add(param5);

                SqlParameter param6 = new SqlParameter("@OfficerID", SqlDbType.NChar, 10);
                param6.Value = offid;
                command.Parameters.Add(param6);

                SqlParameter param7 = new SqlParameter("@SuspectID", SqlDbType.NChar, 10);
                param7.Value = DBNull.Value;
                command.Parameters.Add(param7);

                SqlParameter param8 = new SqlParameter("@InvestigatorID", SqlDbType.NChar, 10);
                param8.Value = DBNull.Value;
                command.Parameters.Add(param8);

                SqlParameter param9 = new SqlParameter("@ManagerID", SqlDbType.NChar, 10);
                param9.Value = DBNull.Value;
                command.Parameters.Add(param9);

                SqlParameter param10 = new SqlParameter("@AdminID", SqlDbType.NChar, 10);
                param10.Value = adminID;
                command.Parameters.Add(param10);

                connections.Open();
                int numRowsAffected = command.ExecuteNonQuery();
                connections.Close();

                if (numRowsAffected != 0)
                {

                    DropDownListcaseid.ClearSelection();
                    exhibitTypeDropDownList.Text = null;
                    storedLocationDropDownList.Text = null;
                    DropDownList1.ClearSelection();
                    messageLabel.Text = "Rows Inserted successfully";
                    messageLabel.Visible = true;
                }
                else
                {
                    messageLabel.Text = "An error occured while inserting columns.";
                    messageLabel.Visible = true;

                }
            }
            catch (Exception ex)
            {
                string script = "";
            }

        }

    }

Image of page being run below

I applied validation items to all drop down lists except the one with the browse button(which offcourse is not a dropdown item). clearly according to my knowledge i havent left out any field.so what could be the cause?


问:
How to search for, or return, extended attributes in a here.com search?
I'm trying to search for businesses with disabled (wheelchair) access.  Google led me to https://developer.here.com/documentation/places/topics_api/media-type-place.html where the 'Media Types' documentation describes 'Extended Attributes', one of which is disabledAccess.  I cannot see this attribute in my search results, or see a way to query for businesses with this attribute either available, or set to a certain value.

My Javascript currently looks like:

```<code>request('https://places.cit.api.here.com/places/v1/discover/explore' +
        '?at=' + userLocation.lat + ',' + userLocation.lng +
        '&cat=restaurant' +
        '&app_id=' + appID +
        '&app_code=' + appCode)
</code>```

This returns results but no mention of extended attributes is apparent.  The word 'extended' or 'disabled' is not present in the response.

I have tried the demo lat,lng from a google example {lat: -33.866, lng: 151.196} and also that of New York City {lat: 40.71, lng: -74.006}.  The docs do say that if no extended attributes are available for a business then the element is omitted completely from the results, but surely there would be something for one of the businesses at those locations.

I tried adding a &cs=disabledAccess to the query, but got an error that disabledAccess is not a valid category.

How do I get extended attributes in the results, or for bonus points, query based on extended attributes?

答: Since you're only looking at two locations, it's very likely that the locations you queried had no 'Extended Attributes' at all.  I would try it at a few chain restaurants/areas in tech cities (SF/NY should be fine) but it's unfortunately likely there's nothing you can do here since the data is sparse.</p>

Body:
I'm trying to search for businesses with disabled (wheelchair) access.  Google led me to https://developer.here.com/documentation/places/topics_api/media-type-place.html where the 'Media Types' documentation describes 'Extended Attributes', one of which is disabledAccess.  I cannot see this attribute in my search results, or see a way to query for businesses with this attribute either available, or set to a certain value.

My Javascript currently looks like:

request('https://places.cit.api.here.com/places/v1/discover/explore' +
        '?at=' + userLocation.lat + ',' + userLocation.lng +
        '&cat=restaurant' +
        '&app_id=' + appID +
        '&app_code=' + appCode)

This returns results but no mention of extended attributes is apparent.  The word 'extended' or 'disabled' is not present in the response.

I have tried the demo lat,lng from a google example {lat: -33.866, lng: 151.196} and also that of New York City {lat: 40.71, lng: -74.006}.  The docs do say that if no extended attributes are available for a business then the element is omitted completely from the results, but surely there would be something for one of the businesses at those locations.

I tried adding a &cs=disabledAccess to the query, but got an error that disabledAccess is not a valid category.

How do I get extended attributes in the results, or for bonus points, query based on extended attributes?


问:
Convert string to number, respecting dots and commas for ordering
I need to order some products that are registered by users, based on their price.

I'm using WordPress and when the user ads a product, I get the field via input=text, then convert it with a function.

Unfortunately, the field that receives the converted number is also a text field and I can't change that.

So, I used the same function to convert the number when I loop the posts and get their content.

As far as visual goes, it works perfectly... But when I try to order by the price... It gets messed up.

Here is the function I have:

```<code>//convert the number which is a string, to float
function tofloat($num) {
    $dotPos = strrpos($num, '.');
    $commaPos = strrpos($num, ',');
    $sep = (($dotPos > $commaPos) && $dotPos) ? $dotPos :
        ((($commaPos > $dotPos) && $commaPos) ? $commaPos : false);
    if (!$sep) {
        return floatval(preg_replace("/[^0-9]/", "", $num));
    }

    return floatval(
        preg_replace("/[^0-9]/", "", substr($num, 0, $sep)) . ',' .
        preg_replace("/[^0-9]/", "", substr($num, $sep+1, strlen($num)))
    );
}
$value = get_field('preco_anuncio');
$precoFinal = tofloat($value);
</code>```

Any ideas how to solve that? I need to preserve the 'visual' with dots and commas. Like: 3.567,00 €

答:
Ok, so I got it to work. Don't know if it's the right way or the best way... But it solved my problem and I don't see any problem with it.

Here is what I did:

The input I have is a text input.

I used JavaScript to visually make it look more like a currency field.

When registering into the database, I convert it with the function toFloat that I posted:

```<code>function tofloat($num) {
    $dotPos = strrpos($num, '.');
    $commaPos = strrpos($num, ',');
    $sep = (($dotPos > $commaPos) && $dotPos) ? $dotPos :
    ((($commaPos > $dotPos) && $commaPos) ? $commaPos : false);
    if (!$sep) {
        return floatval(preg_replace("/[^0-9]/", "", $num));
}

return floatval(
    preg_replace("/[^0-9]/", "", substr($num, 0, $sep)) . ',' .
    preg_replace("/[^0-9]/", "", substr($num, $sep+1, strlen($num)))
);
}
</code>```

Then I use the number_format() to remove any dots or spaces:

number_format($precoAd, 2, ',', '');

When I get the value back from the database, I pass it again to number_format() so it will look as I need:

number_format($value, 2, ',', '.');

ContentLicense: CC BY-SA 4.0

Body:
I need to order some products that are registered by users, based on their price.

I'm using WordPress and when the user ads a product, I get the field via input=text, then convert it with a function.

Unfortunately, the field that receives the converted number is also a text field and I can't change that.

So, I used the same function to convert the number when I loop the posts and get their content.

As far as visual goes, it works perfectly... But when I try to order by the price... It gets messed up.

Here is the function I have:

//convert the number which is a string, to float
function tofloat($num) {
    $dotPos = strrpos($num, '.');
    $commaPos = strrpos($num, ',');
    $sep = (($dotPos > $commaPos) && $dotPos) ? $dotPos :
        ((($commaPos > $dotPos) && $commaPos) ? $commaPos : false);
    if (!$sep) {
        return floatval(preg_replace("/[^0-9]/", "", $num));
    }

    return floatval(
        preg_replace("/[^0-9]/", "", substr($num, 0, $sep)) . ',' .
        preg_replace("/[^0-9]/", "", substr($num, $sep+1, strlen($num)))
    );
}
$value = get_field('preco_anuncio');
$precoFinal = tofloat($value);

Any ideas how to solve that? I need to preserve the 'visual' with dots and commas. Like: 3.567,00 €

Body:
Ok, so I got it to work. Don't know if it's the right way or the best way... But it solved my problem and I don't see any problem with it.

Here is what I did:

The input I have is a text input.

I used JavaScript to visually make it look more like a currency field.

When registering into the database, I convert it with the function toFloat that I posted:

function tofloat($num) {
    $dotPos = strrpos($num, '.');
    $commaPos = strrpos($num, ',');
    $sep = (($dotPos > $commaPos) && $dotPos) ? $dotPos :
    ((($commaPos > $dotPos) && $commaPos) ? $commaPos : false);
    if (!$sep) {
        return floatval(preg_replace("/[^0-9]/", "", $num));
}

return floatval(
    preg_replace("/[^0-9]/", "", substr($num, 0, $sep)) . ',' .
    preg_replace("/[^0-9]/", "", substr($num, $sep+1, strlen($num)))
);
}

Then I use the number_format() to remove any dots or spaces:

number_format($precoAd, 2, ',', '');

When I get the value back from the database, I pass it again to number_format() so it will look as I need:

number_format($value, 2, ',', '.');