问:
sqrt of uint64_t vs. int64_t
I noticed that calculating the integer part of square root of uint64_t is much more complicated than of int64_t. Please, does anybody have an explanation for this? Why is it seemingly much more difficult to deal with one extra bit?

The following:

```<code>int64_t sqrt_int(int64_t a) {
    return sqrt(a);
}
</code>```

compiles with clang 5.0 and -mfpmath=sse -msse3 -Wall -O3 to

```<code>sqrt_int(long):                           # @sqrt_int(long)
        cvtsi2sd        xmm0, rdi
        sqrtsd  xmm0, xmm0
        cvttsd2si       rax, xmm0
        ret
</code>```

But the following:

```<code>uint64_t sqrt_int(uint64_t a) {
    return sqrt(a);
}
</code>```

compiles to:

```<code>.LCPI0_0:
        .long   1127219200              # 0x43300000
        .long   1160773632              # 0x45300000
        .long   0                       # 0x0
        .long   0                       # 0x0
.LCPI0_1:
        .quad   4841369599423283200     # double 4503599627370496
        .quad   4985484787499139072     # double 1.9342813113834067E+25
.LCPI0_2:
        .quad   4890909195324358656     # double 9.2233720368547758E+18
sqrt_int(unsigned long):                           # @sqrt_int(unsigned long)
        movq    xmm0, rdi
        punpckldq       xmm0, xmmword ptr [rip + .LCPI0_0] # xmm0 = xmm0[0],mem[0],xmm0[1],mem[1]
        subpd   xmm0, xmmword ptr [rip + .LCPI0_1]
        haddpd  xmm0, xmm0
        sqrtsd  xmm0, xmm0
        movsd   xmm1, qword ptr [rip + .LCPI0_2] # xmm1 = mem[0],zero
        movapd  xmm2, xmm0
        subsd   xmm2, xmm1
        cvttsd2si       rax, xmm2
        movabs  rcx, -9223372036854775808
        xor     rcx, rax
        cvttsd2si       rax, xmm0
        ucomisd xmm0, xmm1
        cmovae  rax, rcx
        ret
</code>```

答:
In addition to Zalman's excellent answer: The result of the sqrt is always less than INT64_MAX because the input of sqrt is in the uint64_t range. Therefore a single cvttsd2si is sufficient to convert the double back to uint64_t.
In other words: For all input values a the function

uint64_t sqrt_int(uint64_t a) {
    return sqrt(a);
}
```

<p>has exactly the same behaviour as the modified code</p>

<pre class="lang-c prettyprint-override"><code>uint64_t sqrt_int(uint64_t a) {
    return (int64_t)sqrt(a);
}
</code>```

The latter function compiles to

```<code>.LCPI0_0:
  .long 1127219200 # 0x43300000
  .long 1160773632 # 0x45300000
  .long 0 # 0x0
  .long 0 # 0x0
.LCPI0_1:
  .quad 4841369599423283200 # double 4503599627370496
  .quad 4985484787499139072 # double 1.9342813113834067E+25
sqrt_int(unsigned long): # @sqrt_int(unsigned long)
  movq xmm0, rdi
  punpckldq xmm0, xmmword ptr [rip + .LCPI0_0] # xmm0 = xmm0[0],mem[0],xmm0[1],mem[1]
  subpd xmm0, xmmword ptr [rip + .LCPI0_1]
  haddpd xmm0, xmm0
  sqrtsd xmm0, xmm0
  cvttsd2si rax, xmm0
  ret
</code>```

which is much less instruction than the original code.

Title: sqrt of uint64_t vs. int64_t

Body:
I noticed that calculating the integer part of square root of uint64_t is much more complicated than of int64_t. Please, does anybody have an explanation for this? Why is it seemingly much more difficult to deal with one extra bit?

The following:

int64_t sqrt_int(int64_t a) {
    return sqrt(a);
}

compiles with clang 5.0 and -mfpmath=sse -msse3 -Wall -O3 to

sqrt_int(long):                           # @sqrt_int(long)
        cvtsi2sd        xmm0, rdi
        sqrtsd  xmm0, xmm0
        cvttsd2si       rax, xmm0
        ret

But the following:

uint64_t sqrt_int(uint64_t a) {
    return sqrt(a);
}

compiles to:

.LCPI0_0:
        .long   1127219200              # 0x43300000
        .long   1160773632              # 0x45300000
        .long   0                       # 0x0
        .long   0                       # 0x0
.LCPI0_1:
        .quad   4841369599423283200     # double 4503599627370496
        .quad   4985484787499139072     # double 1.9342813113834067E+25
.LCPI0_2:
        .quad   4890909195324358656     # double 9.2233720368547758E+18
sqrt_int(unsigned long):                           # @sqrt_int(unsigned long)
        movq    xmm0, rdi
        punpckldq       xmm0, xmmword ptr [rip + .LCPI0_0] # xmm0 = xmm0[0],mem[0],xmm0[1],mem[1]
        subpd   xmm0, xmmword ptr [rip + .LCPI0_1]
        haddpd  xmm0, xmm0
        sqrtsd  xmm0, xmm0
        movsd   xmm1, qword ptr [rip + .LCPI0_2] # xmm1 = mem[0],zero
        movapd  xmm2, xmm0
        subsd   xmm2, xmm1
        cvttsd2si       rax, xmm2
        movabs  rcx, -9223372036854775808
        xor     rcx, rax
        cvttsd2si       rax, xmm0
        ucomisd xmm0, xmm1
        cmovae  rax, rcx
        ret

Body:
In addition to Zalman's excellent answer: The result of the sqrt is always less than INT64_MAX because the input of sqrt is in the uint64_t range. Therefore a single cvttsd2si is sufficient to convert the double back to uint64_t.
In other words: For all input values a the function

uint64_t sqrt_int(uint64_t a) {
    return sqrt(a);
}

has exactly the same behaviour as the modified code

uint64_t sqrt_int(uint64_t a) {
    return (int64_t)sqrt(a);
}

The latter function compiles to

.LCPI0_0:
  .long 1127219200 # 0x43300000
  .long 1160773632 # 0x45300000
  .long 0 # 0x0
  .long 0 # 0x0
.LCPI0_1:
  .quad 4841369599423283200 # double 4503599627370496
  .quad 4985484787499139072 # double 1.9342813113834067E+25
sqrt_int(unsigned long): # @sqrt_int(unsigned long)
  movq xmm0, rdi
  punpckldq xmm0, xmmword ptr [rip + .LCPI0_0] # xmm0 = xmm0[0],mem[0],xmm0[1],mem[1]
  subpd xmm0, xmmword ptr [rip + .LCPI0_1]
  haddpd xmm0, xmm0
  sqrtsd xmm0, xmm0
  cvttsd2si rax, xmm0
  ret

which is much less instruction than the original code.


来源: stackexchange

问:
Can Someone Editing my ajax code
when I am using ajax in laravel to post if the button is clicked very fast and to much it will cause some of the posts to finish updating the database faster than others, which cuases a counter field in my database to have wrong data, I am using async:false, my question is can a user edit my ajax in there browser and send the ajax code with out async:false?</p>

答: maybe it can be done, use post request so it can't be injected because it checks CSRF session.</p>

ContentLicense: CC BY-SA 3.0

Title: Can Someone Editing my ajax code


问:
Enable multiple AzureAd in Identityserver4 .NET Core

I'm trying to enable login-functionality to multiple AzureAD's in one identity server.

The reason this is necessary, is that multiple tenants need to be able to login to their own AzureAD through 1 identityserver. Setting these up will happen dynamically.

For this example, I have made an extension to AuthenticationBuilder which allows passing multiple AzureAd's and adds them to the AuthenticationBuilder.

```<code>//startup.cs
        Dictionary<string, string> azure1 = new Dictionary<string, string>();
        azure1.Add("name", "azure1");
        azure1.Add("clientid", <azure1id>);
        azure1.Add("tenantid", <azure1tenant>);
        Dictionary<string, string> azure2 = new Dictionary<string, string>();
        azure2.Add("name", "azure2");
        azure2.Add("clientid", <azure2id>);
        azure2.Add("tenantid", <azure2tenant>);
        Dictionary<string, string>[] ids = { azure1, azure2 };

        services.AddAuthentication()
        .AddCookie()
        .AddAzureAdAuthentications(ids)

//AuthenticationBuilderExtension
    public static AuthenticationBuilder AddAzureAdAuthentications(this AuthenticationBuilder builder, Dictionary<string, string>[] azureAds)
    {
        string name = "";
        string clientid = "";
        string tenantid = "";
        foreach (Dictionary<string, string> azuread in azureAds)
        {
            name = azuread.GetValueOrDefault("name");
            clientid = azuread.GetValueOrDefault("clientid");
            tenantid = azuread.GetValueOrDefault("tenantid");
            builder.AddOpenIdConnect(name, name, options =>
            {
                options.Authority = $"https://login.microsoftonline.com/{tenantid}";
                options.ClientId = clientid;
                options.ResponseType = OpenIdConnectResponseType.IdToken;
            });
        }
        return builder;
    }
</code>```

I would expect the above code to add 2 azureAd's as a login options, this works fine. I would think the authentication-flow would stay intact.

Instead, 2 problems appear.

Both loginoptions lead to the last configuration (azure2), azure1 just vanishes. Which means the last configuration is overwriting the first.

When logging in to azure2 with a valid account, logging in to the identityserver fails and the following error occurs:

Exception: Correlation failed.
  Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler+d__12.MoveNext()

Removing 1 of the 2 AzureAD's from the dictionary results in everything working fine.

UPDATE

Implementing leastprivileges answer (thanks) results in the following:
It "almost" works. The AzureAD's are recognized correctly, leading to the correct flows and accepting only the corresponding accounts. But now the client is not succesfully logged in after the callback to the identityserver.

I feel it's just a small edit regarding the signinscheme, but i can't really figure it out as the documention on this is quite minimal.

```<code>foreach (Dictionary<string, string> azuread in ids)
        {
            string name = azuread.GetValueOrDefault("name");
            string clientid = azuread.GetValueOrDefault("clientid");
            string tenantid = azuread.GetValueOrDefault("tenantid");
            services.AddAuthentication(name).AddCookie($"Cookie{name}").AddOpenIdConnect(name, name, options =>
            {
                options.SignInScheme = $"Cookie{name}";
                options.SignOutScheme = $"Cookie1{name}";
                options.CallbackPath = $"/signin-{name}";
                options.Authority = $"https://login.microsoftonline.com/{tenantid}";
                options.ClientId = clientid;
                options.ResponseType = OpenIdConnectResponseType.IdToken;
            });
        }
</code>```

Solution

Might not be that difficult, but sharing the solution to help others:

```<code>            services.AddAuthentication().AddCookie($"Cookie{name}")
            .AddOpenIdConnect(name, name, options =>
            {
                options.CallbackPath = $"/signin-{name}";
                options.Authority = $"https://login.microsoftonline.com/{tenantid}";
                options.ClientId = clientid;
                options.ResponseType = OpenIdConnectResponseType.IdToken;
            });
</code>```

答:
Each handler needs at least a unique CallbackPath - there are other callbacks for signout and post redirect - they must be set as well if you are using those features.

Also the authentication scheme must be unique.

Body:
I'm trying to enable login-functionality to multiple AzureAD's in one identity server.

The reason this is necessary, is that multiple tenants need to be able to login to their own AzureAD through 1 identityserver. Setting these up will happen dynamically.

For this example, I have made an extension to AuthenticationBuilder which allows passing multiple AzureAd's and adds them to the AuthenticationBuilder.

//startup.cs
        Dictionary<string, string> azure1 = new Dictionary<string, string>();
        azure1.Add("name", "azure1");
        azure1.Add("clientid", <azure1id>);
        azure1.Add("tenantid", <azure1tenant>);
        Dictionary<string, string> azure2 = new Dictionary<string, string>();
        azure2.Add("name", "azure2");
        azure2.Add("clientid", <azure2id>);
        azure2.Add("tenantid", <azure2tenant>);
        Dictionary<string, string>[] ids = { azure1, azure2 };

        services.AddAuthentication()
        .AddCookie()
        .AddAzureAdAuthentications(ids)

//AuthenticationBuilderExtension
    public static AuthenticationBuilder AddAzureAdAuthentications(this AuthenticationBuilder builder, Dictionary<string, string>[] azureAds)
    {
        string name = "";
        string clientid = "";
        string tenantid = "";
        foreach (Dictionary<string, string> azuread in azureAds)
        {
            name = azuread.GetValueOrDefault("name");
            clientid = azuread.GetValueOrDefault("clientid");
            tenantid = azuread.GetValueOrDefault("tenantid");
            builder.AddOpenIdConnect(name, name, options =>
            {
                options.Authority = $"https://login.microsoftonline.com/{tenantid}";
                options.ClientId = clientid;
                options.ResponseType = OpenIdConnectResponseType.IdToken;
            });
        }
        return builder;
    }

I would expect the above code to add 2 azureAd's as a login options, this works fine. I would think the authentication-flow would stay intact.

Instead, 2 problems appear.

Both loginoptions lead to the last configuration (azure2), azure1 just vanishes. Which means the last configuration is overwriting the first.

When logging in to azure2 with a valid account, logging in to the identityserver fails and the following error occurs:

Exception: Correlation failed.
  Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler+d__12.MoveNext()

Removing 1 of the 2 AzureAD's from the dictionary results in everything working fine.

UPDATE

Implementing leastprivileges answer (thanks) results in the following:
It "almost" works. The AzureAD's are recognized correctly, leading to the correct flows and accepting only the corresponding accounts. But now the client is not succesfully logged in after the callback to the identityserver.

I feel it's just a small edit regarding the signinscheme, but i can't really figure it out as the documention on this is quite minimal.

foreach (Dictionary<string, string> azuread in ids)
        {
            string name = azuread.GetValueOrDefault("name");
            string clientid = azuread.GetValueOrDefault("clientid");
            string tenantid = azuread.GetValueOrDefault("tenantid");
            services.AddAuthentication(name).AddCookie($"Cookie{name}").AddOpenIdConnect(name, name, options =>
            {
                options.SignInScheme = $"Cookie{name}";
                options.SignOutScheme = $"Cookie1{name}";
                options.CallbackPath = $"/signin-{name}";
                options.Authority = $"https://login.microsoftonline.com/{tenantid}";
                options.ClientId = clientid;
                options.ResponseType = OpenIdConnectResponseType.IdToken;
            });
        }

Solution

Might not be that difficult, but sharing the solution to help others:

            services.AddAuthentication().AddCookie($"Cookie{name}")
            .AddOpenIdConnect(name, name, options =>
            {
                options.CallbackPath = $"/signin-{name}";
                options.Authority = $"https://login.microsoftonline.com/{tenantid}";
                options.ClientId = clientid;
                options.ResponseType = OpenIdConnectResponseType.IdToken;
            });


问:
Updating a shared variable among threads
There is a master list where each entry contains a string array. There is also a slave list which is actually a hash set and each entry is a string. I have wrote two threads to search an item from the slave list in the master list.

There is a member class for stat and I initialize it right before issuing the threads (and not the constructor). Each thread increments the stat by 1 when he wants to search a slave item in the master list.

While in the real code, the master list for each thread is unique, the following sample code uses one master list for two threads.

```<code>class myClass {
  private List<String []> mainList;
  private HashSet<String> slaveList;
  private int nThread;
  private int stat;
  public myClass(int i)
  {
    nThread = i;
    mainList = new ArrayList<>();
    slaveList = new HashSet<>();
    String [] str1 = {"a1", "a2", "a3"};
    String [] str2 = {"b1", "b2", "b3"};
    mainList.add(str1); mainList.add(str2);
    slaveList.add("b2"); slaveList.add("a3");
  }
  public void doProcess() {
    stat = 0;
    for (int i = 0; i < nThread; i++) {
        final int index = i;
        final List<String []> m = mainList;
        final HashSet<String> s = slaveList;
        new Thread(() -> {
            search(m, s, index);
            System.out.println("done");
        }).start();
    }
  }
  public void search( List<String []> m, HashSet<String> s, int index )
  {
    Iterator<String> itr;
    for ( int x = 0; x < m.size(); x++ ) {
      itr = s.iterator();
      while(itr.hasNext()){
        ++stat;
        System.out.println("index=" + index + " master id=" + x + " slave=" + itr.next() + " stat=" + stat);
      }
    }
  }
}
public class Threadtest {

  public static void main(String[] args) {
    myClass mc = new myClass(2);
    mc.doProcess();
  }
}
</code>```

The output however looks odd!!

```<code>index=0 master id=0 slave=b2 stat=1
index=1 master id=0 slave=b2 stat=1
index=0 master id=0 slave=a3 stat=2
index=1 master id=0 slave=a3 stat=3
index=0 master id=1 slave=b2 stat=4
index=1 master id=1 slave=b2 stat=5
index=0 master id=1 slave=a3 stat=6
index=1 master id=1 slave=a3 stat=7
done
done
</code>```

The second line should print stat=2. It seems that there is a concurrency issue here. The second thread reads the old value of stat which is 0 but the first thread had to increment it by 1 before the second thread.

The output of another run is

```<code>index=0 master id=0 slave=b2 stat=2
index=0 master id=0 slave=a3 stat=3
index=0 master id=1 slave=b2 stat=4
index=1 master id=0 slave=b2 stat=2
index=0 master id=1 slave=a3 stat=5
index=1 master id=0 slave=a3 stat=6
done
index=1 master id=1 slave=b2 stat=7
index=1 master id=1 slave=a3 stat=8
done
</code>```

As you can see, the stat is printed as 2 on the first line!!
How that can be fixed?

答:
It sure is a synchronization problem in your code.

You might want to use synchronized block for accessing stat variable.

Take a look at the documentation.

Body:
There is a master list where each entry contains a string array. There is also a slave list which is actually a hash set and each entry is a string. I have wrote two threads to search an item from the slave list in the master list.

There is a member class for stat and I initialize it right before issuing the threads (and not the constructor). Each thread increments the stat by 1 when he wants to search a slave item in the master list.

While in the real code, the master list for each thread is unique, the following sample code uses one master list for two threads.

class myClass {
  private List<String []> mainList;
  private HashSet<String> slaveList;
  private int nThread;
  private int stat;
  public myClass(int i)
  {
    nThread = i;
    mainList = new ArrayList<>();
    slaveList = new HashSet<>();
    String [] str1 = {"a1", "a2", "a3"};
    String [] str2 = {"b1", "b2", "b3"};
    mainList.add(str1); mainList.add(str2);
    slaveList.add("b2"); slaveList.add("a3");
  }
  public void doProcess() {
    stat = 0;
    for (int i = 0; i < nThread; i++) {
        final int index = i;
        final List<String []> m = mainList;
        final HashSet<String> s = slaveList;
        new Thread(() -> {
            search(m, s, index);
            System.out.println("done");
        }).start();
    }
  }
  public void search( List<String []> m, HashSet<String> s, int index )
  {
    Iterator<String> itr;
    for ( int x = 0; x < m.size(); x++ ) {
      itr = s.iterator();
      while(itr.hasNext()){
        ++stat;
        System.out.println("index=" + index + " master id=" + x + " slave=" + itr.next() + " stat=" + stat);
      }
    }
  }
}
public class Threadtest {

  public static void main(String[] args) {
    myClass mc = new myClass(2);
    mc.doProcess();
  }
}

The output however looks odd!!

index=0 master id=0 slave=b2 stat=1
index=1 master id=0 slave=b2 stat=1
index=0 master id=0 slave=a3 stat=2
index=1 master id=0 slave=a3 stat=3
index=0 master id=1 slave=b2 stat=4
index=1 master id=1 slave=b2 stat=5
index=0 master id=1 slave=a3 stat=6
index=1 master id=1 slave=a3 stat=7
done
done

The second line should print stat=2. It seems that there is a concurrency issue here. The second thread reads the old value of stat which is 0 but the first thread had to increment it by 1 before the second thread.

The output of another run is

index=0 master id=0 slave=b2 stat=2
index=0 master id=0 slave=a3 stat=3
index=0 master id=1 slave=b2 stat=4
index=1 master id=0 slave=b2 stat=2
index=0 master id=1 slave=a3 stat=5
index=1 master id=0 slave=a3 stat=6
done
index=1 master id=1 slave=b2 stat=7
index=1 master id=1 slave=a3 stat=8
done

As you can see, the stat is printed as 2 on the first line!!
How that can be fixed?


问:
Redux with Polymer and dom-repeat
I have a problem with nested dom-repeat's and changes deep in arrays.
Using redux I change properties on an array which has a structure like this:

```<code>[{some: 'value', members: [{ id: 13, hobbies: [{id: 33, name:'hobbyname'}]}]}]
</code>```

When for example a hobby is deleted from a member, I see when I have an observer method on this property and console.log the value of the array that it really changed, the hobby is gone.

The DOM does however not change. The structure of that is something like:

```<code><template id="teamslist" is="dom-repeat" items="[[teams]]">
<template is="dom-repeat" items="[[item.members]]" as="member">
<template is="dom-repeat" items="[[member.hobbies]]" as="hobby">
</code>```

I tried notifying the dom-repeat like this but it does not help:

```<code>this.notifyPath('teams[0].members[0].hobbies.length');
</code>```

Calling render() on the dom-repeat (top-level) does not seem to help either:

```<code>this.$.idfordomrepeat.render()
</code>```

What am I doing wrong here..?

答:
Note that the path segments should be separated by dots. Look here.

Try this.notifyPath('teams.0.members.0.hobbies');

Does that work?

Title: Redux with Polymer and dom-repeat

Body:
I have a problem with nested dom-repeat's and changes deep in arrays.
Using redux I change properties on an array which has a structure like this:

[{some: 'value', members: [{ id: 13, hobbies: [{id: 33, name:'hobbyname'}]}]}]

When for example a hobby is deleted from a member, I see when I have an observer method on this property and console.log the value of the array that it really changed, the hobby is gone.

The DOM does however not change. The structure of that is something like:

<template id="teamslist" is="dom-repeat" items="[[teams]]">
<template is="dom-repeat" items="[[item.members]]" as="member">
<template is="dom-repeat" items="[[member.hobbies]]" as="hobby">

I tried notifying the dom-repeat like this but it does not help:

this.notifyPath('teams[0].members[0].hobbies.length');

Calling render() on the dom-repeat (top-level) does not seem to help either:

this.$.idfordomrepeat.render()

What am I doing wrong here..?


问:
SSIS Flat file column delimiter
I have a csv file that I process and import into a database. the problem is the delimiter needs to be " but within SSIS is this possible as currently the default options are :-

答: you can enter in any delimiter</p>

Title: SSIS Flat file column delimiter

Body: you can enter in any delimiter


答:
You could synchronize the part where you use the shared variable:

```<code>  while(itr.hasNext()){
    int localStat;
    synchronized(this) {
        localStat = ++stat;
    }
    System.out.println("index=" + index + " master id=" + x + " slave=" + itr.next() + " stat=" + localStat );
  }
</code>```

But the lists are still shared and unprotected.

Title: Updating a shared variable among threads

Body:
You could synchronize the part where you use the shared variable:

  while(itr.hasNext()){
    int localStat;
    synchronized(this) {
        localStat = ++stat;
    }
    System.out.println("index=" + index + " master id=" + x + " slave=" + itr.next() + " stat=" + localStat );
  }

But the lists are still shared and unprotected.


问:
how can i open a smaller box in the same browser window
I am trying to open a small dialog/window just like an android alert dialog when i click on a link on my website

I read about bootstrap modal,it looks like what i need, but i am not able to display a website inside a modal

This is an example

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Large Modal</h2>
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" href="http://patecgroup.com" data-target="#myModal">Open Large Modal</button>

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog modal-lg">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">×</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body" >
          <p> Where the website should be</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>
    </div>
  </div>
</div>

</body>
</html>
</code>```

Please how can i get a website inside the modal, or be able to create a window that can do that for me

EDIT
I have also tried the iframe tag inside the modal, and it doesnt work for all websites

答:
<!DOCTYPE html>

  <title>Bootstrap Example</title>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<button class="btn btn-primary" data-toggle="modal" data-target="#myModal">Trigger Modal in iFrame</button>

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Modal title

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

```

Body:
I am trying to open a small dialog/window just like an android alert dialog when i click on a link on my website

I read about bootstrap modal,it looks like what i need, but i am not able to display a website inside a modal

This is an example

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Large Modal

  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" href="http://patecgroup.com" data-target="#myModal">Open Large Modal</button>

          <button type="button" class="close" data-dismiss="modal">×</button>

Modal Header

 Where the website should be

          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

Please how can i get a website inside the modal, or be able to create a window that can do that for me

EDIT
I have also tried the iframe tag inside the modal, and it doesnt work for all websites

Body:
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<button class="btn btn-primary" data-toggle="modal" data-target="#myModal">Trigger Modal in iFrame</button>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
          <iframe src="http://heera.it" width="300" height="380" frameborder="0" allowtransparency="true"></iframe>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
    <!-- /.modal-content -->
  </div>
  <!-- /.modal-dialog -->
</div>
<!-- /.modal -->


问:
assign one line to the other line in pandas
I have an Excel document, then I use read_excel() function, and change the Excel document to a DataFrame called df

Then I want to process every line in df, if the line fits, then I will insert/append this line to a new variable called df1

How do I solve it?

I think I can assign one line in df to one line in df1, so in every loop:

df1.loc[0] = df.loc[0]

But there is a question is that I find if I print df1, and the data in df1 is NaN.

What if I use append?

df1 = df1.append(df.loc[0])

There is an exception: UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)

What should I do?

How to transport one line to the other line?

**|n1|n2|n3

0   | A |  B  | C

1   | E |  F  | G

this is df, for example. and I want to select the index which is 0, and I want to assign it to a new dataframe variable called df1

so this is df1 in my mind:

**|n1|n2|n3

0   | A |  B  | C

but if I use df1.loc[0] = df.loc[0], then df1 will be:

**|n1|n2|n3

0   | nan |  nan  | nan

答:
I am Chinese, I should use Unicode.

So the columns' name should be:

u'你好'

u'谢谢'


问:
Xamarin Forms: ScrollView with KeyBoard
I am on the most current version of Xamarin Forms. I have a Content Page. The Content Page has a grid that has a scrollview that has a stacklayout that contains some image and Entry inputs and some Buttons. When I touch the Entry to enter text, the keyboard covers the Buttons so I can't press the button. This isn't scrollable and I don't know why. Anybody can help me?

Here is my XAML code:

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="Spirocco.LoginPage">
<Grid>
    <ScrollView Orientation="Both" x:Name="scrollView">
        <ScrollView.Content>
            <StackLayout BackgroundColor="#302138">
                <Image Source="login_logo" Margin="0,0,0,0"></Image>
                <StackLayout BackgroundColor="White" Margin="20,0,20,30">
                    <Label Text="ÜDVÖZÖLJÜK!" FontSize="30" FontFamily="Comic Sans MS" Margin="0,15,0,0" TextColor="#302138" HorizontalTextAlignment="Center"></Label>
                    <Entry Text="{Binding Email}" Placeholder="E-mail" Margin="40,0,40,0" Keyboard="Email"/>
                    <Entry Text="{Binding Password}" Placeholder="Jelszó" IsPassword="True" Margin="40,0,40,0"/>
                    <Button Text="BEJELENTKEZÉS" Clicked="Login" TextColor="White" BackgroundColor="#302138" Margin="40,10,40,0"/>
                    <Button Text="REGISZTRÁCIÓ" Clicked="Register" TextColor="White" BackgroundColor="#302138" Margin="40,0,40,25"/>
                </StackLayout>
            </StackLayout>
        </ScrollView.Content>
    </ScrollView>
</Grid>
</code>```

Here is the solution

答:
By default, grid's row height value will be equals to '*' and therefore will take all the space in the screen. This is why it is not scrollable.

By the way, I don't really get why you nest in into a grid.

Try this:

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
     xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
     x:Class="Spirocco.LoginPage">

<ScrollView Orientation="Both" x:Name="scrollView">
    <ScrollView.Content>
        <StackLayout BackgroundColor="#302138">
            <Image Source="login_logo" Margin="0,0,0,0"></Image>
            <StackLayout BackgroundColor="White" Margin="20,0,20,30">
                <Label Text="ÜDVÖZÖLJÜK!" FontSize="30" FontFamily="Comic Sans MS" Margin="0,15,0,0" TextColor="#302138" HorizontalTextAlignment="Center"></Label>
                <Entry Text="{Binding Email}" Placeholder="E-mail" Margin="40,0,40,0" Keyboard="Email"/>
                <Entry Text="{Binding Password}" Placeholder="Jelszó" IsPassword="True" Margin="40,0,40,0"/>
                <Button Text="BEJELENTKEZÉS" Clicked="Login" TextColor="White" BackgroundColor="#302138" Margin="40,10,40,0"/>
                <Button Text="REGISZTRÁCIÓ" Clicked="Register" TextColor="White" BackgroundColor="#302138" Margin="40,0,40,25"/>
            </StackLayout>
        </StackLayout>
    </ScrollView.Content>
</ScrollView>
</code>```

Title: Xamarin Forms: ScrollView with KeyBoard

Body:
I am on the most current version of Xamarin Forms. I have a Content Page. The Content Page has a grid that has a scrollview that has a stacklayout that contains some image and Entry inputs and some Buttons. When I touch the Entry to enter text, the keyboard covers the Buttons so I can't press the button. This isn't scrollable and I don't know why. Anybody can help me?

Here is my XAML code:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="Spirocco.LoginPage">
<Grid>
    <ScrollView Orientation="Both" x:Name="scrollView">
        <ScrollView.Content>
            <StackLayout BackgroundColor="#302138">
                <Image Source="login_logo" Margin="0,0,0,0"></Image>
                <StackLayout BackgroundColor="White" Margin="20,0,20,30">

                    <Entry Text="{Binding Email}" Placeholder="E-mail" Margin="40,0,40,0" Keyboard="Email"/>
                    <Entry Text="{Binding Password}" Placeholder="Jelszó" IsPassword="True" Margin="40,0,40,0"/>
                    <Button Text="BEJELENTKEZÉS" Clicked="Login" TextColor="White" BackgroundColor="#302138" Margin="40,10,40,0"/>
                    <Button Text="REGISZTRÁCIÓ" Clicked="Register" TextColor="White" BackgroundColor="#302138" Margin="40,0,40,25"/>
                </StackLayout>
            </StackLayout>
        </ScrollView.Content>
    </ScrollView>
</Grid>

Here is the solution

Body:
By default, grid's row height value will be equals to '*' and therefore will take all the space in the screen. This is why it is not scrollable.

By the way, I don't really get why you nest in into a grid.

Try this:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
     xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
     x:Class="Spirocco.LoginPage">

<ScrollView Orientation="Both" x:Name="scrollView">
    <ScrollView.Content>
        <StackLayout BackgroundColor="#302138">
            <Image Source="login_logo" Margin="0,0,0,0"></Image>
            <StackLayout BackgroundColor="White" Margin="20,0,20,30">
                <Label Text="ÜDVÖZÖLJÜK!" FontSize="30" FontFamily="Comic Sans MS" Margin="0,15,0,0" TextColor="#302138" HorizontalTextAlignment="Center"></Label>
                <Entry Text="{Binding Email}" Placeholder="E-mail" Margin="40,0,40,0" Keyboard="Email"/>
                <Entry Text="{Binding Password}" Placeholder="Jelszó" IsPassword="True" Margin="40,0,40,0"/>
                <Button Text="BEJELENTKEZÉS" Clicked="Login" TextColor="White" BackgroundColor="#302138" Margin="40,10,40,0"/>
                <Button Text="REGISZTRÁCIÓ" Clicked="Register" TextColor="White" BackgroundColor="#302138" Margin="40,0,40,25"/>
            </StackLayout>
        </StackLayout>
    </ScrollView.Content>
</ScrollView>


问:
How to handle nested quota for pg insertion
I have a table two info two fields:

```<code>create table t (
   id  serial NOT NULL PRIMARY KEY,
   info jsonb
)
</code>```

When I try to insert a row:

```<code>insert into t (info) values ('{"a": "b", "c": "c\"aa\"c"}'::jsonb)
</code>```

I got an error:

```<code>Token "aa" is invalid.
</code>```

How to solve this issue?

答:
cant reproduce:

```<code>t=# create table t (
t(#    id  serial NOT NULL PRIMARY KEY,
t(#    info jsonb
t(# );
CREATE TABLE
t=# insert into t (info) values ('{"a": "b", "c": "c\"aa\"c"}'::jsonb);
INSERT 0 1
t=# select * from t;
 id |            info
----+-----------------------------
  1 | {"a": "b", "c": "c\"aa\"c"}
(1 row)
</code>```

unless I change standard_conforming_strings to off

https://www.postgresql.org/docs/current/static/runtime-config-compatible.html

standard_conforming_strings (boolean) This controls whether ordinary
  string literals ('...') treat backslashes literally, as specified in
  the SQL standard. Beginning in PostgreSQL 9.1, the default is on
  (prior releases defaulted to off). Applications can check this
  parameter to determine how string literals will be processed. The
  presence of this parameter can also be taken as an indication that the
  escape string syntax (E'...') is supported.

with backslash taken as not sting, but escape char - json structure is broken, you see it in error message:

Token "aa" is invalid.

In order to insert valid json, you have to escape backspaces themselves:

```<code>t=# set standard_conforming_strings  to off;
SET
-- now when I have same settings as you:
t=# insert into t (info) values (e'{"a": "b", "c": "c\\"aa\\"c"}'::jsonb);
INSERT 0 1
t=# select * from t;
 id |            info
----+-----------------------------
  5 | {"a": "b", "c": "c\"aa\"c"}
(1 row)
</code>```

Body:
I have a table two info two fields:

create table t (
   id  serial NOT NULL PRIMARY KEY,
   info jsonb
)

When I try to insert a row:

insert into t (info) values ('{"a": "b", "c": "c\"aa\"c"}'::jsonb)

I got an error:

Token "aa" is invalid.

How to solve this issue?

Body:
cant reproduce:

t=# create table t (
t(#    id  serial NOT NULL PRIMARY KEY,
t(#    info jsonb
t(# );
CREATE TABLE
t=# insert into t (info) values ('{"a": "b", "c": "c\"aa\"c"}'::jsonb);
INSERT 0 1
t=# select * from t;
 id |            info
----+-----------------------------
  1 | {"a": "b", "c": "c\"aa\"c"}
(1 row)

unless I change standard_conforming_strings to off

https://www.postgresql.org/docs/current/static/runtime-config-compatible.html

standard_conforming_strings (boolean) This controls whether ordinary
  string literals ('...') treat backslashes literally, as specified in
  the SQL standard. Beginning in PostgreSQL 9.1, the default is on
  (prior releases defaulted to off). Applications can check this
  parameter to determine how string literals will be processed. The
  presence of this parameter can also be taken as an indication that the
  escape string syntax (E'...') is supported.

with backslash taken as not sting, but escape char - json structure is broken, you see it in error message:

Token "aa" is invalid.

In order to insert valid json, you have to escape backspaces themselves:

t=# set standard_conforming_strings  to off;
SET
-- now when I have same settings as you:
t=# insert into t (info) values (e'{"a": "b", "c": "c\\"aa\\"c"}'::jsonb);
INSERT 0 1
t=# select * from t;
 id |            info
----+-----------------------------
  5 | {"a": "b", "c": "c\"aa\"c"}
(1 row)


问:
Get address using geolocation in http website
Recently I created a website in asp.net core and hosted in Azure Shared tier (non-secure). there is one feature on my website, get user address based on geolocation and autofill registration form.

Problem

getCurrentPosition() and watchPosition() no longer work on insecure origins (As of Chrome 50, the Geolocation API will only work on secure contexts such as HTTPS.)

The site is very small and I don't want to spend money on SSL certificate. (I can go with free SSL https://letsencrypt.org/)

Custom SSL certificate hosting only available on Azure Basic and above tier.

Is there any solution/workaround available?

Thanks,

答:
Sign up CloudFlare Free Plan and use their free SSL.

https://www.cloudflare.com/ssl/

ContentLicense: CC BY-SA 4.0


问:
How should I implement ExecuteAsync with RestSharp on Windows Phone 7?
I'm attempting to use the documentation on the RestSharp GitHub wiki to implement calls to my REST API service but I'm having an issue with the ExecuteAsync method in particular.

Currently my code looks like this for the API class:

```<code>public class HarooApi
{
    const string BaseUrl = "https://domain.here";

    readonly string _accountSid;
    readonly string _secretKey;

    public HarooApi(string accountSid, string secretKey)
    {
        _accountSid = accountSid;
        _secretKey = secretKey;
    }

    public T Execute<T>(RestRequest request) where T : new()
    {
        var client = new RestClient();
        client.BaseUrl = BaseUrl;
        client.Authenticator = new HttpBasicAuthenticator(_accountSid, _secretKey);
        request.AddParameter("AccountSid", _accountSid, ParameterType.UrlSegment);
        client.ExecuteAsync<T>(request, (response) =>
        {
            return response.Data;
        });
    }
}
</code>```

I'm aware this slightly deviates from what is on the GitHub page but I'm using this with WP7 and believe the example is for C# hence the usage of the ExecuteAsync method.

My problem is with what the ExecuteAsync command should contain. I can't use return response.Data because I'm warned:

```<code>'System.Action<RestSharp.RestResponse<T>,RestSharp.RestRequestAsyncHandle>' returns void, a return keyword must not be followed by an object expression
</code>```

Does anyone have any insight on how to fix this or a tutorial that may assist?

答:
As an alternative (or complement) to the fine answer by Gusten. You can use ExecuteAsync. This way you do not manually have to handle TaskCompletionSource. Note the async keyword in the signature.

Update:
As of 106.4.0 ExecuteTaskAsync is obsolete. Since 104.2 you should use ExecuteAsync instead:

```<code>public async Task<T> ExecuteAsync<T>(RestRequest request) where T : new()
{
    var client = new RestClient();
    client.BaseUrl = BaseUrl;
    client.Authenticator = new HttpBasicAuthenticator(_accountSid, _secretKey);
    request.AddParameter("AccountSid", _accountSid, ParameterType.UrlSegment);
    IRestResponse<T> response = await client.ExecuteAsync<T>(request);
    return response.Data;
}
</code>```

Old Answer:

```<code>public async Task<T> ExecuteAsync<T>(RestRequest request) where T : new()
{
    var client = new RestClient();
    client.BaseUrl = BaseUrl;
    client.Authenticator = new HttpBasicAuthenticator(_accountSid, _secretKey);
    request.AddParameter("AccountSid", _accountSid, ParameterType.UrlSegment);
    IRestResponse<T> response = await client.ExecuteTaskAsync<T>(request); // Now obsolete
    return response.Data;
}
</code>```

Body:
I'm attempting to use the documentation on the RestSharp GitHub wiki to implement calls to my REST API service but I'm having an issue with the ExecuteAsync method in particular.

Currently my code looks like this for the API class:

public class HarooApi
{
    const string BaseUrl = "https://domain.here";

    readonly string _accountSid;
    readonly string _secretKey;

    public HarooApi(string accountSid, string secretKey)
    {
        _accountSid = accountSid;
        _secretKey = secretKey;
    }

    public T Execute<T>(RestRequest request) where T : new()
    {
        var client = new RestClient();
        client.BaseUrl = BaseUrl;
        client.Authenticator = new HttpBasicAuthenticator(_accountSid, _secretKey);
        request.AddParameter("AccountSid", _accountSid, ParameterType.UrlSegment);
        client.ExecuteAsync<T>(request, (response) =>
        {
            return response.Data;
        });
    }
}

I'm aware this slightly deviates from what is on the GitHub page but I'm using this with WP7 and believe the example is for C# hence the usage of the ExecuteAsync method.

My problem is with what the ExecuteAsync command should contain. I can't use return response.Data because I'm warned:

'System.Action<RestSharp.RestResponse<T>,RestSharp.RestRequestAsyncHandle>' returns void, a return keyword must not be followed by an object expression

Does anyone have any insight on how to fix this or a tutorial that may assist?

Body:
As an alternative (or complement) to the fine answer by Gusten. You can use ExecuteAsync. This way you do not manually have to handle TaskCompletionSource. Note the async keyword in the signature.

Update:
As of 106.4.0 ExecuteTaskAsync is obsolete. Since 104.2 you should use ExecuteAsync instead:

public async Task<T> ExecuteAsync<T>(RestRequest request) where T : new()
{
    var client = new RestClient();
    client.BaseUrl = BaseUrl;
    client.Authenticator = new HttpBasicAuthenticator(_accountSid, _secretKey);
    request.AddParameter("AccountSid", _accountSid, ParameterType.UrlSegment);
    IRestResponse<T> response = await client.ExecuteAsync<T>(request);
    return response.Data;
}

Old Answer:

public async Task<T> ExecuteAsync<T>(RestRequest request) where T : new()
{
    var client = new RestClient();
    client.BaseUrl = BaseUrl;
    client.Authenticator = new HttpBasicAuthenticator(_accountSid, _secretKey);
    request.AddParameter("AccountSid", _accountSid, ParameterType.UrlSegment);
    IRestResponse<T> response = await client.ExecuteTaskAsync<T>(request); // Now obsolete
    return response.Data;
}


问:
Vertically center text in a table header
I'm new to CSS and HTML and I'm trying to vertically center some text in a table header. At the moment the text is aligned with the top of the table cell. I was unsuccessful with vertical-align: middle;, and the only solution seems to be to add padding-top to match the space underneath the text. However this is not the best solution because I would like to have the text fit snugly within the table cell. Any ideas are appreciated.

body {
    font-size: 18px;
    font-family: 'Open Sans', sans-serif;
    text-align: center;
    color: black;
    background-size: 100%;
    padding:0;
}

.mytable {
  border: solid 1px #DDEEEE;
  border-collapse: collapse;
  border-spacing: 0;
  width: 80%;
}

.mytable thead th {
  background-color: #DDEFEF;
  border: solid 1px #DDEEEE;
  color: #336B6B;
  /*padding: 30px;*/
  text-align: center;
  vertical-align: middle;
}

.mytable tbody td {
  border: solid 1px #DDEEEE;
  color: #333;
  padding: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="myWebPage" style="display:block">
  <br><br><br><br>
  <h3>Page title here</h3><br><br><br>

  <table class="mytable" align="center">
    <thead>
      <tr>
        <th><u>Resource</u><br><br><br></th>
        <th><u>Contact</u><br><br><br></th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th align="left">Resource 1<br><br></th>
        <th align="left" width=35%;>999-999-9999<br> <br></th>
      </tr>
      <tr>
        <th align="left">Resource 2<br><br></th>
        <th align="left">888-888-8888<br><br></th>
      </tr>
      <tr>
        <th align="left">Resource 3<br><br></th>
        <th align="left" width=35%;>777-777-7777<br> <br></th>
      </tr>
    </tbody>
  </table>
</div></code>```

答:
Try like this , why are you put
 and  to

Table  The  elements are the data containers of the table.
HTML
 Tag is
A line break is marked up as follows:

```<code>This text contains<br>a line break.
</code>```

body {
    font-size: 18px;
    font-family: 'Open Sans', sans-serif;
    text-align: center;
    color: black;
    background-size: 100%;
    padding:0;
}

.mytable {
  border: solid 1px #DDEEEE;
  border-collapse: collapse;
  border-spacing: 0;
  width: 80%;
}

.mytable thead th {
  background-color: #DDEFEF;
  border: solid 1px #DDEEEE;
  color: #336B6B;
  /*padding: 30px;*/
  text-align: center;
  vertical-align: middle;
}

.mytable tbody td {
  border: solid 1px #DDEEEE;
  color: #333;
  padding: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <h3>Page title here</h3>

  <table class="mytable" align="center">
    <thead>
      <tr>
        <th><u>Resource</u></th>
        <th><u>Contact</u></th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td align="left">Resource 1</td>
        <td align="left" width=35%;>999-999-9999</td>
      </tr>
      <tr>
        <td align="left">Resource 2</td>
        <td align="left">888-888-8888</td>
      </tr>
      <tr>
        <td align="left">Resource 3</td>
        <td align="left" width=35%;>777-777-7777</td>
      </tr>
    </tbody>
  </table></code>```

learn more about  html table https://www.w3schools.com/html/html_tables.asp

Body:
I'm new to CSS and HTML and I'm trying to vertically center some text in a table header. At the moment the text is aligned with the top of the table cell. I was unsuccessful with vertical-align: middle;, and the only solution seems to be to add padding-top to match the space underneath the text. However this is not the best solution because I would like to have the text fit snugly within the table cell. Any ideas are appreciated.

body {
    font-size: 18px;
    font-family: 'Open Sans', sans-serif;
    text-align: center;
    color: black;
    background-size: 100%;
    padding:0;
}

.mytable {
  border: solid 1px #DDEEEE;
  border-collapse: collapse;
  border-spacing: 0;
  width: 80%;
}

.mytable thead th {
  background-color: #DDEFEF;
  border: solid 1px #DDEEEE;
  color: #336B6B;
  /*padding: 30px;*/
  text-align: center;
  vertical-align: middle;
}

.mytable tbody td {
  border: solid 1px #DDEEEE;
  color: #333;
  padding: 30px;
}

Page title here

        Resource

        Contact

        Resource 1

        999-999-9999

        Resource 2

        888-888-8888

        Resource 3

        777-777-7777

Body:
Try like this , why are you put <br> and <td> to <th>

Table <td> The  elements are the data containers of the table.
HTML
 Tag is
A line break is marked up as follows:

This text contains<br>a line break.

body {
    font-size: 18px;
    font-family: 'Open Sans', sans-serif;
    text-align: center;
    color: black;
    background-size: 100%;
    padding:0;
}

.mytable {
  border: solid 1px #DDEEEE;
  border-collapse: collapse;
  border-spacing: 0;
  width: 80%;
}

.mytable thead th {
  background-color: #DDEFEF;
  border: solid 1px #DDEEEE;
  color: #336B6B;
  /*padding: 30px;*/
  text-align: center;
  vertical-align: middle;
}

.mytable tbody td {
  border: solid 1px #DDEEEE;
  color: #333;
  padding: 30px;
}

  <h3>Page title here</h3>

  <table class="mytable" align="center">
    <thead>
      <tr>
        <th><u>Resource</u></th>
        <th><u>Contact</u></th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td align="left">Resource 1</td>
        <td align="left" width=35%;>999-999-9999</td>
      </tr>
      <tr>
        <td align="left">Resource 2</td>
        <td align="left">888-888-8888</td>
      </tr>
      <tr>
        <td align="left">Resource 3</td>
        <td align="left" width=35%;>777-777-7777</td>
      </tr>
    </tbody>
  </table>

learn more about  html table https://www.w3schools.com/html/html_tables.asp


问:
Laravel do check selected items from array on html select as multiple feature
After get all categories and user selected categories for selected post with this result:

```<code>$content_categories = ContentCategories::all()->pluck('title', 'id');

Collection {#209 ▼
  #items: array:3 [▼
    1 => "laravel"
    2 => "nodejs"
    3 => "php"
  ]
}

$selected_categories = $manage_content->categories()->get()->pluck('title', 'id');

Collection {#223 ▼
  #items: array:2 [▼
    1 => "laravel"
    2 => "php"
  ]
}
</code>```

I'm trying to implement this result on html select and do check selected items when we have in $selected_categories, this code only show $content_categories and can not be check items with $selected_categories by default

```<code>{{
  Form::select('categories[]',
          $content_categories,
          $selected_categories,
          array('multiple'=>'multiple'))
}}
</code>```

result:

```<code><select class="multiselect-success" multiple="multiple" name="categories[]">
     <option value="1">laravel</option>
     <option value="2">nodejs</option>
     <option value="3">php</option>
</select>
</code>```

答:
Get IDs of selected categories without titles:

```<code>$selected_categories = $manage_content->categories()->pluck('id');
</code>```

Or use keys() to get keys only:

```<code>Form::select('categories[]', $content_categories, $selected_categories->keys(), array('multiple'=>'multiple'))
</code>```

Body:
After get all categories and user selected categories for selected post with this result:

$content_categories = ContentCategories::all()->pluck('title', 'id');

Collection {#209 ▼
  #items: array:3 [▼
    1 => "laravel"
    2 => "nodejs"
    3 => "php"
  ]
}

$selected_categories = $manage_content->categories()->get()->pluck('title', 'id');

Collection {#223 ▼
  #items: array:2 [▼
    1 => "laravel"
    2 => "php"
  ]
}

I'm trying to implement this result on html select and do check selected items when we have in $selected_categories, this code only show $content_categories and can not be check items with $selected_categories by default

{{
  Form::select('categories[]',
          $content_categories,
          $selected_categories,
          array('multiple'=>'multiple'))
}}

result:

<select class="multiselect-success" multiple="multiple" name="categories[]">
     <option value="1">laravel</option>
     <option value="2">nodejs</option>
     <option value="3">php</option>
</select>

Body:
Get IDs of selected categories without titles:

$selected_categories = $manage_content->categories()->pluck('id');

Or use keys() to get keys only:

Form::select('categories[]', $content_categories, $selected_categories->keys(), array('multiple'=>'multiple'))


问:
502 Bad Gateway error with python app running uwsgi and nginx (centos)
Seen this question asked but all seemed to be Ubuntu and the solutions didn't quite work for me on Centos. I have a flask app trying to run from uwsgi and am getting

```<code>2017/07/26 17:44:24 [crit] 22785#0: *7 connect() to unix:/home/myname/perm_check/index.sock failed (13: Permission denied) while connecting to upstream, client: 127.0.0.1, server: 127.0.0.1, request: "GET / HTTP/1.1", upstream: "uwsgi://unix:/home/myname/perm_check/index.sock:", host: "127.0.0.1"
</code>```

(it runs fine from virtualenv to localhost:500 or localhost:8000 with wsgi as per this https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-uwsgi-and-nginx-on-centos-7  tutorial.

Here are my files:
index.ini

```<code>[uwsgi]
module = wsgi

master = true
processes = 5

socket = index.sock
chmod-socket = 664
vacuum = true

die-on-term = true
</code>```

index.py

```<code>from flask import Flask
app = Flask(__name__)

@app.route("/")
def check():
    return "<h1 style='color:red'>Test run...</h1>"

if __name__ == "__main__":
    app.run(host='0.0.0.0')
</code>```

nginx.conf

```<code># For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    fastcgi_buffers 8 16k;
    fastcgi_buffer_size 32k;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
    listen 80;
    server_name 127.0.0.1;

    location / {
        include uwsgi_params;
        uwsgi_pass unix:/home/myname/perm_check/index.sock;
        }
    }

    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }

# Settings for a TLS enabled server.
#
#    server {
#        listen       443 ssl http2 default_server;
#        listen       [::]:443 ssl http2 default_server;
#        server_name  _;
#        root         /usr/share/nginx/html;
#
#        ssl_certificate "/etc/pki/nginx/server.crt";
#        ssl_certificate_key "/etc/pki/nginx/private/server.key";
#        ssl_session_cache shared:SSL:1m;
#        ssl_session_timeout  10m;
#        ssl_ciphers HIGH:!aNULL:!MD5;
#        ssl_prefer_server_ciphers on;
#
#        # Load configuration files for the default server block.
#        include /etc/nginx/default.d/*.conf;
#
#        location / {
#        }
#
#        error_page 404 /404.html;
#            location = /40x.html {
#        }
#
#        error_page 500 502 503 504 /50x.html;
#            location = /50x.html {
#        }
#    }

}
</code>```

I know I'm missing something simple somewhere but I can't for the life of me figure it out. Permissions for everything is myname:myname and I'm trying to run the uwsgi service from 127.0.0.1.

答: Solved it, needed to disable SELinux and restart the server</p>

Body:
Seen this question asked but all seemed to be Ubuntu and the solutions didn't quite work for me on Centos. I have a flask app trying to run from uwsgi and am getting

2017/07/26 17:44:24 [crit] 22785#0: *7 connect() to unix:/home/myname/perm_check/index.sock failed (13: Permission denied) while connecting to upstream, client: 127.0.0.1, server: 127.0.0.1, request: "GET / HTTP/1.1", upstream: "uwsgi://unix:/home/myname/perm_check/index.sock:", host: "127.0.0.1"

(it runs fine from virtualenv to localhost:500 or localhost:8000 with wsgi as per this https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-uwsgi-and-nginx-on-centos-7  tutorial.

Here are my files:
index.ini

[uwsgi]
module = wsgi

master = true
processes = 5

socket = index.sock
chmod-socket = 664
vacuum = true

die-on-term = true

index.py

from flask import Flask
app = Flask(__name__)

@app.route("/")
def check():
    return "
Test run...
"

if __name__ == "__main__":
    app.run(host='0.0.0.0')

nginx.conf

# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    fastcgi_buffers 8 16k;
    fastcgi_buffer_size 32k;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
    listen 80;
    server_name 127.0.0.1;

    location / {
        include uwsgi_params;
        uwsgi_pass unix:/home/myname/perm_check/index.sock;
        }
    }

    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }

# Settings for a TLS enabled server.
#
#    server {
#        listen       443 ssl http2 default_server;
#        listen       [::]:443 ssl http2 default_server;
#        server_name  _;
#        root         /usr/share/nginx/html;
#
#        ssl_certificate "/etc/pki/nginx/server.crt";
#        ssl_certificate_key "/etc/pki/nginx/private/server.key";
#        ssl_session_cache shared:SSL:1m;
#        ssl_session_timeout  10m;
#        ssl_ciphers HIGH:!aNULL:!MD5;
#        ssl_prefer_server_ciphers on;
#
#        # Load configuration files for the default server block.
#        include /etc/nginx/default.d/*.conf;
#
#        location / {
#        }
#
#        error_page 404 /404.html;
#            location = /40x.html {
#        }
#
#        error_page 500 502 503 504 /50x.html;
#            location = /50x.html {
#        }
#    }

}

I know I'm missing something simple somewhere but I can't for the life of me figure it out. Permissions for everything is myname:myname and I'm trying to run the uwsgi service from 127.0.0.1.


问:
How to bypass "Blocked call to navigator.vibrate because user hasn't tapped on the frame or any embedded frame yet"?
I have a use case where I need to use the navigator.vibrate API to vibrate once an image has finished sliding in from the side:

Code pen demo here: https://codepen.io/ifusion/pen/XeWqpj

Note, this only seems to work on Android Google Chrome & Android Firefox

However if the navigator.vibrate is not activated by an actual touch then in chrome throws an error in the console:

[Intervention] Blocked call to navigator.vibrate because user hasn't tapped on the frame or any embedded frame yet: https://www.chromestatus.com/feature/5644273861001216.

Samsung are using it at the end of the second step on this site: https://explorethenextgalaxy.com/ (Only works on android chrome & android firefox).

Screenshot at the point of it happening: https://www.dropbox.com/s/e8h7s3nzfwdk9dk/Screenshot%202017-09-13%2016.50.24.png?dl=0

I have had a look through their code and they are just using the navigator.vibrate just like I am and can't see them doing anything differently.

Is there a way to by pass this? I have tried .click() etc but the error still shows.

答:
I just faced this problem and found easy solution:

window.navigator.vibrate() && window.navigator.vibrate(100);

using on event handler.

No more error console message.


问:
how to list the selected options and remove the selected options by using jQuery?

Below is my HTML code and i have to add jquery for this how to do?

```<code>    <div class="container">
<div class="row one">
    <h4>Staff Re-Admission</h4>
</div><br>
<div class="row">
    <p>Academic Year</p>
    <select>
        <option>2010/2011</option>
        <option>2010/2011</option>
        <option>2010/2011</option>
    </select>
</div><br>
<div class="row">
<div class="container">
  <div class="row">
  <div class="col-md-12">
  <div class="table-responsive">
    <table class="table" style="width: 100%;">
        <tbody>
        <tr>
          <td style="width: 250px"><p>Staff List</p></td>
          <td></td>
          <td><p>Continue</p></td>
          <td><p>Discontinue</p></td>
        </tr>
        <tr>
          <td><select size="14" class="Staff" multiple="multiple">
            <option value="SJB2017NT021">SJB2017NT021--Vishu</option>
            <option value="SJB2017NT022">SJB2017NT022--Naveen</option>
            <option value="SJB2017NT023">SJB2017NT023--Uday</option>
            <option value="SJB2017NT024">SJB2017NT024--Mohan</option>
            <option value="SJB2017TS019">SJB2017TS019--Thejaswini</option>
            <option value="SJB2017TS020">SJB2017TS020--Prasad</option>
          </select></td>
          <td>
            <button type="submit"  value="" id="Continue">Continue >>
            </button><br><br>
            <button type="submit"  value="" id="Discontinue">Discontinue >>
            </button><br><br>
            <button type="submit" value="" id="Back">Back To List
            <<</button>
          </td>
          <td><select size="14" multiple="multiple" class="Staff" ></select>
          </td>
          <td><select size="14" multiple="multiple" class="Staff" ></select>
          </td>
        <tr>
          <td><button type="submit">submit</button>
          <button type="submit">submit</button>
          </td>
        </tr>
        </tr>
      </tbody>
    </table>
  </div><!--end of .table-responsive-->
  </div>
  </div>
</div>
</div>
</div>
</code>```

when i selcet the option and click on continue it has to be listed in continue box and same if i select discontinue then in discontinue box and if i select back entire thing has to come back how to do this please help me out.

答:
just change the id of another two select with continue and discontinue

```<code><td>
    <select size="14" multiple="multiple" class="continue" ></select>
</td>
<td>
    <select size="14" multiple="multiple" class="discontinue" ></select>
</td>
</code>```

Here is jquery for add to continue and discontinue.

```<code><script>
    $("#Continue").on("click", function(){
        var cont = $(".Staff").val();
        $(".continue").append($(".Staff option:selected"));
        $(".Staff option:selected").remove();
        return false;
    });
    $("#Discontinue").on("click", function(){
        var cont = $(".Staff").val();
        $(".discontinue").append($(".Staff option:selected"));
        $(".Staff option:selected").remove();
        return false;
    });
</script>
</code>```

Body:
Below is my HTML code and i have to add jquery for this how to do?

Staff Re-Admission

Academic Year

    <select>
        <option>2010/2011</option>
        <option>2010/2011</option>
        <option>2010/2011</option>
    </select>

Staff List

Continue

Discontinue

          <select size="14" class="Staff" multiple="multiple">
            <option value="SJB2017NT021">SJB2017NT021--Vishu</option>
            <option value="SJB2017NT022">SJB2017NT022--Naveen</option>
            <option value="SJB2017NT023">SJB2017NT023--Uday</option>
            <option value="SJB2017NT024">SJB2017NT024--Mohan</option>
            <option value="SJB2017TS019">SJB2017TS019--Thejaswini</option>
            <option value="SJB2017TS020">SJB2017TS020--Prasad</option>
          </select>

            <button type="submit"  value="" id="Continue">Continue >>
            </button>

            <button type="submit"  value="" id="Discontinue">Discontinue >>
            </button>

            <button type="submit" value="" id="Back">Back To List
            <<</button>

          <select size="14" multiple="multiple" class="Staff" ></select>

          <select size="14" multiple="multiple" class="Staff" ></select>

          <button type="submit">submit</button>
          <button type="submit">submit</button>

when i selcet the option and click on continue it has to be listed in continue box and same if i select discontinue then in discontinue box and if i select back entire thing has to come back how to do this please help me out.

Body:
just change the id of another two select with continue and discontinue

<td>
    <select size="14" multiple="multiple" class="continue" ></select>
</td>
<td>
    <select size="14" multiple="multiple" class="discontinue" ></select>
</td>

Here is jquery for add to continue and discontinue.

<script>
    $("#Continue").on("click", function(){
        var cont = $(".Staff").val();
        $(".continue").append($(".Staff option:selected"));
        $(".Staff option:selected").remove();
        return false;
    });
    $("#Discontinue").on("click", function(){
        var cont = $(".Staff").val();
        $(".discontinue").append($(".Staff option:selected"));
        $(".Staff option:selected").remove();
        return false;
    });
</script>


问:
Find value in nested JSON and trace backwards for values
With the JSON structure below.

Let's say I know the chapter "number" and section "number".

What would be the best way search and trace backwards from what I have, to get the "number" of the title in titles and then the division "number" ?

Of course there would be a large amount of divisions/titles/chapters and sections.

```<code>[
  {
    "name":"Division",
    "number":1,
    "TITLES":[
      {
        "CHAPTERS":[
          {
            "name":"chapter2",
            "number":2,
            "SECTIONS":[
              {
                "name":"section3",
                "number":3
              }
            ]
          }
        ],
        "name":"title1",
        "number":1
      }
    ]
  }
]
</code>```

答:
This code (assuming a is your array of Data)

var b = [];
var chapternumber = 2;
var sectionnumber = 3;
a.forEach(function (division, divisionindex) {
  division.TITLES.forEach(function (title, titleindex) {
    title.CHAPTERS.forEach(function (chapter, chaptersindex) {
      chapter.SECTIONS.forEach(function (section, sectionsindex) {
        if(section.number === sectionnumber && chapter.number === chapternumber){
          b.push({title: title.number, division: division.number});
        }
      })
    })
  });
})
console.log(b);
```

Outputs an Array with the matching Title and Division number.

Body:
With the JSON structure below.

Let's say I know the chapter "number" and section "number".

What would be the best way search and trace backwards from what I have, to get the "number" of the title in titles and then the division "number" ?

Of course there would be a large amount of divisions/titles/chapters and sections.

[
  {
    "name":"Division",
    "number":1,
    "TITLES":[
      {
        "CHAPTERS":[
          {
            "name":"chapter2",
            "number":2,
            "SECTIONS":[
              {
                "name":"section3",
                "number":3
              }
            ]
          }
        ],
        "name":"title1",
        "number":1
      }
    ]
  }
]

Body:
This code (assuming a is your array of Data)

var b = [];
var chapternumber = 2;
var sectionnumber = 3;
a.forEach(function (division, divisionindex) {
  division.TITLES.forEach(function (title, titleindex) {
    title.CHAPTERS.forEach(function (chapter, chaptersindex) {
      chapter.SECTIONS.forEach(function (section, sectionsindex) {
        if(section.number === sectionnumber && chapter.number === chapternumber){
          b.push({title: title.number, division: division.number});
        }
      })
    })
  });
})
console.log(b);

Outputs an Array with the matching Title and Division number.


问:
How to prevent users from going back to the previous page?
I am using ASP.NET MVC (latest version).

Imagine having 2 pages:

Page-1: "Enter data" >> Page-2: "Thank you"

After submitting Page-1 you are being redirected to Page-2.

My goal: I want to make sure that you can't go back to Page-1 when you hit the browser's back button once you made it to Page-2. Instead I want you rather to stay on Page-2 (or being pushed forward to Page-2 every time you hit the back button).

I have tried all different kind of things. The following is just some simplified pseudo code ...

```<code>[NoBrowserCache]
public ActionResult Page1(int userId)
{
   var user = GetUserFromDb(userId);
   if (user.HasAlreadySubmittedPage1InThePast)
   {
      // forward to page 2
      return RedirectToAction("Page2", routeValues: new { userId = userId });
   }

   var model = new Page1Model();

   return View("Page1", model);
}

[NoBrowserCache]
[HttpPost]
public ActionResult Page1(Page1Model model)
{
   var user = GetUserFromDb(model.UserId);
   if (user.HasAlreadySubmittedPage1InThePast)
   {
       // forward to page 2
       return RedirectToAction("Page2", routeValues: new { userId = model.UserId });
   }

   // Save posted data to the db
   // ...

   return RedirectToAction("Page2", routeValues: new { userId = model.UserId });
}

public class NoBrowserCache : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Haha ... tried everything I found on the web here:
        // Make sure the requested page is not put in the browser cache.
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        filterContext.HttpContext.Response.Cache.SetNoStore();
        filterContext.HttpContext.Response.Cache.AppendCacheExtension("no-cache");
        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.Now);
        filterContext.HttpContext.Response.Expires = 0;
    }
}
</code>```

If only I could make sure that a request is being sent to the server every time I hit the back button. But right now, clicking the back button just pulls Page-1 from my browser's cache without sending a request to the server. So currently, I have no chance to redirect you forward to Page-2 by server means.

Any ideas or suggestions?

Thanks, guys!

Btw: There is no login/authentication involved. So, I can't use Session.Abandon() or stuff like this. And I would rather use some server based code than javascript if possible.

EDIT 2017-5-12
Following @grek40, I made sure that the anti-chaching statements end up in the browser. I therefor completely removed the [NoBrowserCache]-ActionFilterAttribute from my C# code above. Instead I added the following statements in the  section of my _Layout.cshtml:

```<code><meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
</code>```

I confirm that these three lines are being rendered to my browser (used my browser's developer tools to inspect). However, caching still works. I can still move backward without any server requests. Tested this with Google Chrome v62, Firefox Quantum v57 and Microsoft Edge v41 (all on Win10). #

EDIT 2017-6-12
Again following @grek40's suggestions: tried Expires: 0 as well as Expires: -1. No difference. I still didn't manage, to turn off my browser's cache.

答:
This can be done by using javascript. Use the following code

```<code>     <script type = "text/javascript" >
   function preventBack(){window.history.forward();}
    setTimeout("preventBack()", 0);
    window.onunload=function(){null};
   </script>
</code>```

or check the following link1 and link2.

Body:
I am using ASP.NET MVC (latest version).

Imagine having 2 pages:

Page-1: "Enter data" >> Page-2: "Thank you"

After submitting Page-1 you are being redirected to Page-2.

My goal: I want to make sure that you can't go back to Page-1 when you hit the browser's back button once you made it to Page-2. Instead I want you rather to stay on Page-2 (or being pushed forward to Page-2 every time you hit the back button).

I have tried all different kind of things. The following is just some simplified pseudo code ...

[NoBrowserCache]
public ActionResult Page1(int userId)
{
   var user = GetUserFromDb(userId);
   if (user.HasAlreadySubmittedPage1InThePast)
   {
      // forward to page 2
      return RedirectToAction("Page2", routeValues: new { userId = userId });
   }

   var model = new Page1Model();

   return View("Page1", model);
}

[NoBrowserCache]
[HttpPost]
public ActionResult Page1(Page1Model model)
{
   var user = GetUserFromDb(model.UserId);
   if (user.HasAlreadySubmittedPage1InThePast)
   {
       // forward to page 2
       return RedirectToAction("Page2", routeValues: new { userId = model.UserId });
   }

   // Save posted data to the db
   // ...

   return RedirectToAction("Page2", routeValues: new { userId = model.UserId });
}

public class NoBrowserCache : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Haha ... tried everything I found on the web here:
        // Make sure the requested page is not put in the browser cache.
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        filterContext.HttpContext.Response.Cache.SetNoStore();
        filterContext.HttpContext.Response.Cache.AppendCacheExtension("no-cache");
        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.Now);
        filterContext.HttpContext.Response.Expires = 0;
    }
}

If only I could make sure that a request is being sent to the server every time I hit the back button. But right now, clicking the back button just pulls Page-1 from my browser's cache without sending a request to the server. So currently, I have no chance to redirect you forward to Page-2 by server means.

Any ideas or suggestions?

Thanks, guys!

Btw: There is no login/authentication involved. So, I can't use Session.Abandon() or stuff like this. And I would rather use some server based code than javascript if possible.

EDIT 2017-5-12
Following @grek40, I made sure that the anti-chaching statements end up in the browser. I therefor completely removed the [NoBrowserCache]-ActionFilterAttribute from my C# code above. Instead I added the following statements in the  section of my _Layout.cshtml:

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">

I confirm that these three lines are being rendered to my browser (used my browser's developer tools to inspect). However, caching still works. I can still move backward without any server requests. Tested this with Google Chrome v62, Firefox Quantum v57 and Microsoft Edge v41 (all on Win10). #

EDIT 2017-6-12
Again following @grek40's suggestions: tried Expires: 0 as well as Expires: -1. No difference. I still didn't manage, to turn off my browser's cache.

Body:
This can be done by using javascript. Use the following code

     <script type = "text/javascript" >
   function preventBack(){window.history.forward();}
    setTimeout("preventBack()", 0);
    window.onunload=function(){null};
   </script>

or check the following link1 and link2.


问:
Got "else" with no preceding "if" error ruby

links

```<code>- if current_user
= link_to "Edit", edit_job_path(@job), class: "btn btn-sm btn-default"
= link_to "Delete", job_path(@job), method: :delete, data: { confirm: "Are you sure?" }, class: "btn btn-sm btn-default"

- else

 = link_to "Back", root_path, class: "btn btn-sm btn-default"
</code>```

This returns:

```<code>Got "else" with no preceding "if" error ruby
</code>```

Why is that?

答:
Although it is not clearly stated in the question, I assume it is supposed to be a haml file.

It is because the body after the first if line is not indented. So the if body is parsed as empty. The else line then starts on its own.

Body:
links

- if current_user
= link_to "Edit", edit_job_path(@job), class: "btn btn-sm btn-default"
= link_to "Delete", job_path(@job), method: :delete, data: { confirm: "Are you sure?" }, class: "btn btn-sm btn-default"

- else

 = link_to "Back", root_path, class: "btn btn-sm btn-default"

This returns:

Got "else" with no preceding "if" error ruby

Why is that?


问:
Android install apk programmatically
Is it possible to install an apk programmatically in the background or does the user have to accept the installation.

My scenario is that I want my employees to all have the same set of applications installed.

Of course they can install applications by them self, but I want them all to have at least some applications installed.

I'm not talking about installing applications from the market.

答:
It's a huge security concern and I do not think that Android allows that!

At least, I would not allow any util or service to install any app without informing me.

The best way would be console installation using command adb install <apk name>. You can have APKs in a remote server and all employees have to install them and send you the console output.

ContentLicense: CC BY-SA 2.5

Title: Android install apk programmatically


问:
Displays tables that are already stored in localStorage
i want to create New Content. the New content is dataTable and will be saved to localStorage

When i click the ADD NEW TABLE button, the Table has created and saved to localStorage.

BUT

When im refresh the page, The table not display but saved to
  localStorage.

MY JSFiddle

How to be able to display a table [datatable view] that has been created and stored in localStorage when the page is refreshed?

jQuery :

```<code>$("#mainTable").dataTable();

/* CREATE TABLE FITURE */
$('.submitButton').click(function() {
  function getTableList() {
    var addTable = '<div class="tab-pane" id="folder' + localStorage.Index + '">' +
      '<div class="zf-table">' +
      '<table id="table' + localStorage.Index + '" class="table table-bordered table-hover myFade">' +
      '<thead>' +
      '<tr>' +
      '<th style="border-color:rgb(221, 221, 221);"></th>' +
      '<th>Audience Name</th>' +
      '<th>Type</th>' +
      '<th>Size</th>' +
      '<th>Date Created</th>' +
      '<th>Action</th>' +
      '</tr>' +
      '</thead>' +
      '</table>' +
      '</div>' +
      '</div>';
    return addTable;
  }

  if (true) {
    /** INDEX FOR INCREMENT ID **/
    if (typeof(Storage) !== "undefined") {
      if (localStorage.Index) {
        localStorage.Index = Number(localStorage.Index) + 1;
      } else {
        localStorage.Index = 1;
      }
    } // if storage

    var resultTable = JSON.parse(localStorage.getItem("tableList"));
    if (resultTable == null) {
      resultTable = [];
    }
    let newtableHTML = getTableList();
    resultTable.push({
      table: newtableHTML
    });
    // save the new resultTable array
    localStorage.setItem("tableList", JSON.stringify(resultTable));

    /* append Table baru */
    $('.tab-content').append(newtableHTML);
    var newTable = $("#table" + localStorage.Index).dataTable();
    alert("sucess create table");

  } else {
    alert("Failed create Table");
  }
}); // submitButton func

//on init fill the table-content

var resultTable = JSON.parse(localStorage.getItem("tableList"));
if (resultTable != null) {
  //get the nav reference in DOM
  let tableContent = $(".tab-content");

  //clear the html contents
  tableContent.html('');

  for (var i = 0; i < resultTable.length; i++) {
    var items = resultTable[i];
    $(".tab-content").append(items.table);
  }
} else {
  let inititalTable = [];
  inititalTable.push({
    table: $('div.tab-content').html()
  });
  localStorage.setItem("tableList", JSON.stringify(inititalTable));
}
</code>```

答:
seems you forgot to call dataTable() on the table elements read from LocalStorage.

By looping through the stored tables with

```<code>for (var i = 0; i < resultTable.length; i++) {
    var items = resultTable[i];
    $(".tab-content").append(items.table);
}
</code>```

you only append the initial HTML. It must be transformed by the dataTables plugin afterwards to show ordering, searching and paging features.

A possible solution would be calling dataTable() on all tables in tab-content container after the for loop:

```<code>for (var i = 0; i < resultTable.length; i++) {
    var items = resultTable[i];
    $(".tab-content").append(items.table);
}

$(".tab-content table").dataTable();
</code>```

Body:
i want to create New Content. the New content is dataTable and will be saved to localStorage

When i click the ADD NEW TABLE button, the Table has created and saved to localStorage.

BUT

When im refresh the page, The table not display but saved to
  localStorage.

MY JSFiddle

How to be able to display a table [datatable view] that has been created and stored in localStorage when the page is refreshed?

jQuery :

$("#mainTable").dataTable();

/* CREATE TABLE FITURE */
$('.submitButton').click(function() {
  function getTableList() {
    var addTable = '
' +
      '
' +
      '
' +
      '
' +
      '
' +
      '	' +
      'Audience Name	' +
      'Type	' +
      'Size	' +
      'Date Created	' +
      'Action	' +
      '
' +
      '
' +
      '
' +
      '
' +
      '
';
    return addTable;
  }

  if (true) {
    /** INDEX FOR INCREMENT ID **/
    if (typeof(Storage) !== "undefined") {
      if (localStorage.Index) {
        localStorage.Index = Number(localStorage.Index) + 1;
      } else {
        localStorage.Index = 1;
      }
    } // if storage

    var resultTable = JSON.parse(localStorage.getItem("tableList"));
    if (resultTable == null) {
      resultTable = [];
    }
    let newtableHTML = getTableList();
    resultTable.push({
      table: newtableHTML
    });
    // save the new resultTable array
    localStorage.setItem("tableList", JSON.stringify(resultTable));

    /* append Table baru */
    $('.tab-content').append(newtableHTML);
    var newTable = $("#table" + localStorage.Index).dataTable();
    alert("sucess create table");

  } else {
    alert("Failed create Table");
  }
}); // submitButton func

//on init fill the table-content

var resultTable = JSON.parse(localStorage.getItem("tableList"));
if (resultTable != null) {
  //get the nav reference in DOM
  let tableContent = $(".tab-content");

  //clear the html contents
  tableContent.html('');

  for (var i = 0; i < resultTable.length; i++) {
    var items = resultTable[i];
    $(".tab-content").append(items.table);
  }
} else {
  let inititalTable = [];
  inititalTable.push({
    table: $('div.tab-content').html()
  });
  localStorage.setItem("tableList", JSON.stringify(inititalTable));
}

Body:
seems you forgot to call dataTable() on the table elements read from LocalStorage.

By looping through the stored tables with

for (var i = 0; i < resultTable.length; i++) {
    var items = resultTable[i];
    $(".tab-content").append(items.table);
}

you only append the initial HTML. It must be transformed by the dataTables plugin afterwards to show ordering, searching and paging features.

A possible solution would be calling dataTable() on all tables in tab-content container after the for loop:

for (var i = 0; i < resultTable.length; i++) {
    var items = resultTable[i];
    $(".tab-content").append(items.table);
}

$(".tab-content table").dataTable();


答:
Define a height value for the th elements

Define an explicit (absolute) height for your table header cells (th) using length unit values (e.g: 65px), then declare the vertical-align rule on these elements.

Code Snippet Demonstration:

body {
  font-size: 18px;
  font-family: 'Open Sans', sans-serif;
  text-align: center;
  color: black;
  background-size: 100%;
  padding: 0;
}

.mytable {
  border: solid 1px #DDEEEE;
  border-collapse: collapse;
  border-spacing: 0;
  width: 80%;
}

.mytable thead th {
  background-color: #DDEFEF;
  border: solid 1px #DDEEEE;
  color: #336B6B;
  /*padding: 30px;*/
  text-align: center;
  vertical-align: middle;
  /* additional */
  height: 65px;
}

.mytable tbody td {
  border: solid 1px #DDEEEE;
  color: #333;
  padding: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="myWebPage" style="display:block">
  <br><br><br><br>
  <h3>Page title here</h3><br><br><br>

  <table class="mytable" align="center">
    <thead>
      <tr>
        <th><u>Resource</u></th>
        <th><u>Contact</u></th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th align="left">Resource 1<br><br></th>
        <th align="left" width=35%;>999-999-9999<br> <br></th>
      </tr>
      <tr>
        <th align="left">Resource 2<br><br></th>
        <th align="left">888-888-8888<br><br></th>
      </tr>
      <tr>
        <th align="left">Resource 3<br><br></th>
        <th align="left" width=35%;>777-777-7777<br> <br></th>
      </tr>
    </tbody>
  </table>
</div></code>```

Title: Vertically center text in a table header

Body:
Define a height value for the th elements

Define an explicit (absolute) height for your table header cells (th) using length unit values (e.g: 65px), then declare the vertical-align rule on these elements.

Code Snippet Demonstration:

body {
  font-size: 18px;
  font-family: 'Open Sans', sans-serif;
  text-align: center;
  color: black;
  background-size: 100%;
  padding: 0;
}

.mytable {
  border: solid 1px #DDEEEE;
  border-collapse: collapse;
  border-spacing: 0;
  width: 80%;
}

.mytable thead th {
  background-color: #DDEFEF;
  border: solid 1px #DDEEEE;
  color: #336B6B;
  /*padding: 30px;*/
  text-align: center;
  vertical-align: middle;
  /* additional */
  height: 65px;
}

.mytable tbody td {
  border: solid 1px #DDEEEE;
  color: #333;
  padding: 30px;
}

<div id="myWebPage" style="display:block">
  <br><br><br><br>
  <h3>Page title here</h3><br><br><br>

  <table class="mytable" align="center">
    <thead>
      <tr>
        <th><u>Resource</u></th>
        <th><u>Contact</u></th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th align="left">Resource 1<br><br></th>
        <th align="left" width=35%;>999-999-9999<br> <br></th>
      </tr>
      <tr>
        <th align="left">Resource 2<br><br></th>
        <th align="left">888-888-8888<br><br></th>
      </tr>
      <tr>
        <th align="left">Resource 3<br><br></th>
        <th align="left" width=35%;>777-777-7777<br> <br></th>
      </tr>
    </tbody>
  </table>
</div>


问:
How to save/display graphical representation of a Neural Network in a file in Java (Eclipse)?
I have build a NN in Java using the Neuroph API. Within the API there is a package called GraphmlExport. i followed this tutorial:
http://fernando.carrillo.at/neuroph-graphml-export/

I put the three lines of code in my class:

```<code>GraphmlExport ge = new GraphmlExport(myMLPerceptron);
        ge.parse();
        ge.writeToFile("/FILE/PATH/OUT");
        ge.printToStdout();
</code>```

I don't understand what needs to go in the brackets of writeToFile.
i use ge.printToStdout() to see if it works and it does but using that is printing it like this in the Console:

```<code>graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
<key id="d1" for="edge" attr.name="weight" attr.type="double"></key>
<graph id="defaultId" edgedefault="directed">
    <node id="Input-0"></node>
    <edge source="Input-0" target="L1-0">
        <data key="d1">-1.5324200758107742</data>
        </edge>
    <edge source="Input-0" target="L1-1">
        <data key="d1">-6.718888335977713</data>
        </edge>
</code>```

What do i need to change to get it actually displayed properly?

答:
I don't think this requires the file to be created beforehand.
I am not familiar with the library but common practices would be that you give a file path and the library will create it if the file does not exist. Directory should exist though.

The content which is written is XML so I would give it the .xml extension.

So given that you are on Windows10 and assuming your windows user name is ProddoBaggins, try that

```<code>ge.writeToFile("C:\\Users\\ProddoBaggins\\exportFile.xml");
</code>```

then lookup the file C:\Users\ProddoBaggins\exportFile.xml with your file manager, it should be there.

I assume also that if you give the name of a file which already exixts, it will be overwritten.

Edit: I looked it up and it seems that there is a .graphml extension, so you should probably use it. ie

```<code>ge.writeToFile("C:\\Users\\ProddoBaggins\\exportFile.graphml");
</code>```

Edit: Regarding visualization, there is already a post on the subject here

Body:
I have build a NN in Java using the Neuroph API. Within the API there is a package called GraphmlExport. i followed this tutorial:
http://fernando.carrillo.at/neuroph-graphml-export/

I put the three lines of code in my class:

GraphmlExport ge = new GraphmlExport(myMLPerceptron);
        ge.parse();
        ge.writeToFile("/FILE/PATH/OUT");
        ge.printToStdout();

I don't understand what needs to go in the brackets of writeToFile.
i use ge.printToStdout() to see if it works and it does but using that is printing it like this in the Console:

graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
<key id="d1" for="edge" attr.name="weight" attr.type="double"></key>
<graph id="defaultId" edgedefault="directed">
    <node id="Input-0"></node>
    <edge source="Input-0" target="L1-0">
        <data key="d1">-1.5324200758107742</data>
        </edge>
    <edge source="Input-0" target="L1-1">
        <data key="d1">-6.718888335977713</data>
        </edge>

What do i need to change to get it actually displayed properly?

Body:
I don't think this requires the file to be created beforehand.
I am not familiar with the library but common practices would be that you give a file path and the library will create it if the file does not exist. Directory should exist though.

The content which is written is XML so I would give it the .xml extension.

So given that you are on Windows10 and assuming your windows user name is ProddoBaggins, try that

ge.writeToFile("C:\\Users\\ProddoBaggins\\exportFile.xml");

then lookup the file C:\Users\ProddoBaggins\exportFile.xml with your file manager, it should be there.

I assume also that if you give the name of a file which already exixts, it will be overwritten.

Edit: I looked it up and it seems that there is a .graphml extension, so you should probably use it. ie

ge.writeToFile("C:\\Users\\ProddoBaggins\\exportFile.graphml");

Edit: Regarding visualization, there is already a post on the subject here