问:
Writing to socket fails after X bytes
I'm attempting to write song data to a socket however after approximately 66338 bytes the following exception is thrown:

```<code>    E/        ( 1016): Connection reset by peer
    E/        ( 1016): java.net.SocketException: Connection reset by peer
    E/        ( 1016):  at org.apache.harmony.luni.platform.OSNetworkSystem.writeSocketImpl(Native Method)
    E/        ( 1016):  at org.apache.harmony.luni.platform.OSNetworkSystem.write(OSNetworkSystem.java:723)
    E/        ( 1016):  at org.apache.harmony.luni.net.PlainSocketImpl.write(PlainSocketImpl.java:578)
    E/        ( 1016):  at org.apache.harmony.luni.net.SocketOutputStream.write(SocketOutputStream.java:59)
    E/        ( 1016):  at com.myprogram.StreamProxy.processRequest(StreamProxy.java:307)
    E/        ( 1016):  at com.myprogram.StreamProxy.run(StreamProxy.java:145)
    E/        ( 1016):  at java.lang.Thread.run(Thread.java:1096)
</code>```

This only happens with certain songs and if one song does it all of the songs in the entire album do the same thing.  I'm wondering if it has something to do with the header information for the song?

Any suggestions on how to debug or fix this would be greatly appreciated.  Thanks.

EDIT:  Here's the code that is reading from an InputStream and writing back out to a socket.  The code is pretty straight forward so I'm not really sure why it would be crashing unless the connection is being closed on the receiving end.  (Note: this is only psuedocode, but gives the general idea)

```<code>    InputStream data = realResponse.getEntity().getContent();
    Socket socket = new ServerSocket(port, 0, InetAddress.getByAddress(new byte[] {127,0,0,1}));
    socket.setSoTimeout(5000);
    port = socket.getLocalPort();
    Socket client = socket.accept();

    ...some code...

    byte[] buff = new byte[1024 * 50];
    while (isRunning && (readBytes = data.read(buff, 0, buff.length)) != -1) {
      client.getOutputStream().write(buff, 0, readBytes);
    }
</code>```

Also, could this have anything to do with the socket buffer filling up? Especially since it seems to crash at 64k every time.

答: The stacktrace says that the peer (server or client) closed the connection, to me it could be that you're reading (parsing) wrong the server's response on the client or vice versa.</p>

Title: Writing to socket fails after X bytes

Body:
I'm attempting to write song data to a socket however after approximately 66338 bytes the following exception is thrown:

    E/        ( 1016): Connection reset by peer
    E/        ( 1016): java.net.SocketException: Connection reset by peer
    E/        ( 1016):  at org.apache.harmony.luni.platform.OSNetworkSystem.writeSocketImpl(Native Method)
    E/        ( 1016):  at org.apache.harmony.luni.platform.OSNetworkSystem.write(OSNetworkSystem.java:723)
    E/        ( 1016):  at org.apache.harmony.luni.net.PlainSocketImpl.write(PlainSocketImpl.java:578)
    E/        ( 1016):  at org.apache.harmony.luni.net.SocketOutputStream.write(SocketOutputStream.java:59)
    E/        ( 1016):  at com.myprogram.StreamProxy.processRequest(StreamProxy.java:307)
    E/        ( 1016):  at com.myprogram.StreamProxy.run(StreamProxy.java:145)
    E/        ( 1016):  at java.lang.Thread.run(Thread.java:1096)

This only happens with certain songs and if one song does it all of the songs in the entire album do the same thing.  I'm wondering if it has something to do with the header information for the song?

Any suggestions on how to debug or fix this would be greatly appreciated.  Thanks.

EDIT:  Here's the code that is reading from an InputStream and writing back out to a socket.  The code is pretty straight forward so I'm not really sure why it would be crashing unless the connection is being closed on the receiving end.  (Note: this is only psuedocode, but gives the general idea)

    InputStream data = realResponse.getEntity().getContent();
    Socket socket = new ServerSocket(port, 0, InetAddress.getByAddress(new byte[] {127,0,0,1}));
    socket.setSoTimeout(5000);
    port = socket.getLocalPort();
    Socket client = socket.accept();

    ...some code...

    byte[] buff = new byte[1024 * 50];
    while (isRunning && (readBytes = data.read(buff, 0, buff.length)) != -1) {
      client.getOutputStream().write(buff, 0, readBytes);
    }

Also, could this have anything to do with the socket buffer filling up? Especially since it seems to crash at 64k every time.


来源: stackexchange

问:
Split/group collectible by consecutive elements
Suppose I have a list/array containing chars. How do I group/split/join them so that I get something like this?</p>

```<code>val input = arrayOf('b', 'b', 'c', 'd', 'e', 'e', 'e')

val output = groupOrSplit(input) // ['bb', 'c', 'd', 'eee']
</code>```

答:
There are no functions to split string like you want in standard library, so you have to write this function by yourself:</p>

```<code>fun splitDistinct(arr: CharArray): List<String> = arr
    .fold(ArrayList<StringBuilder>()) { acc, ch -> acc.apply {
        if (isEmpty() || last().last() != ch)
            add(StringBuilder(ch.toString()))
        else
            last().append(ch)
    }}
    .map { it.toString() }

fun main() {
    val arr = charArrayOf('b', 'b', 'c', 'd', 'e', 'e', 'e')
    println(splitDistinct(arr))
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Suppose I have a list/array containing chars. How do I group/split/join them so that I get something like this?

val input = arrayOf('b', 'b', 'c', 'd', 'e', 'e', 'e')

val output = groupOrSplit(input) // ['bb', 'c', 'd', 'eee']

Body:
There are no functions to split string like you want in standard library, so you have to write this function by yourself:

fun splitDistinct(arr: CharArray): List<String> = arr
    .fold(ArrayList<StringBuilder>()) { acc, ch -> acc.apply {
        if (isEmpty() || last().last() != ch)
            add(StringBuilder(ch.toString()))
        else
            last().append(ch)
    }}
    .map { it.toString() }

fun main() {
    val arr = charArrayOf('b', 'b', 'c', 'd', 'e', 'e', 'e')
    println(splitDistinct(arr))
}


问:
How to define schema table level
I am using EF Core 2.1 with C# for my application.

For some reason, there are a few tables for which I want the schema to be dbo while for others app

```<code>public class MyAppContext : DbContext
{
    private const string _dbSchema = "app";

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema(_dbSchema);
        modelBuilder.ApplyConfiguration(new RegionConfiguration());
        base.OnModelCreating(modelBuilder);
    }
}
</code>```

While for some entities, I want to override the default schema & set it.

```<code>public class RegionConfiguration : IEntityTypeConfiguration<Region>
{
    public void Configure(EntityTypeBuilder<Region> builder)
    {
        // Didn't find any such method -> builder.HasSchema("dbo");
        builder.HasKey(x => x.RegionId); //Primary Key
    }
}
</code>```

How to address this?

答:
As an option, you can also use DataAnnotations instead as alternative to FluentAPI. Both are fine.</p>
```<code>[Table("Region",Schema = "dbo")]
public class Region {}
</code>```

Title: How to define schema table level

Body:
I am using EF Core 2.1 with C# for my application.

For some reason, there are a few tables for which I want the schema to be dbo while for others app

public class MyAppContext : DbContext
{
    private const string _dbSchema = "app";

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema(_dbSchema);
        modelBuilder.ApplyConfiguration(new RegionConfiguration());
        base.OnModelCreating(modelBuilder);
    }
}

While for some entities, I want to override the default schema & set it.

public class RegionConfiguration : IEntityTypeConfiguration<Region>
{
    public void Configure(EntityTypeBuilder<Region> builder)
    {
        // Didn't find any such method -> builder.HasSchema("dbo");
        builder.HasKey(x => x.RegionId); //Primary Key
    }
}

How to address this?

Body:
As an option, you can also use DataAnnotations instead as alternative to FluentAPI. Both are fine.

[Table("Region",Schema = "dbo")]
public class Region {}


问:
How do I configure eclipse classpath used for junit tests?
I have an eclipse project where every source folder has its own associated output folder. Instead of /classes it's called /eclipse-classes.

So if I have a folder:
src/main/java (typical maven thing)
the target folder is:
target/eclipse-classes

And likewise for resources etc.

This seems to work (i.e. eclipse generates .class files that are put inside these folders) but running any Junit tests throws an exception stating "class not found". I'm running JUnit using the built-in eclipse test runner (i.e. right click the class, "run as", "Junit test").

Copying the /eclipse-classes folder to /classes makes them succeed, meaning eclipse is using /classes, but I can't find any configuration options to change it. Is there any way to find out where and why eclipse is still using the /classes folder?

(perhaps relevant, I'm also using the m2eclipse plugin)

Some additional information inspired by Rich Seller's answer:
Maven is configured to run the following on resource changes:

```<code>process-resources resources:testResources
</code>```

While this won't do anything useful (copies to the wrong directory) the resources are not problematic atm since they end up in the correct location.

The .classpath entries look okay. There's a bunch of maven subprojects so the nesting goes a bit deeper than what Rich posted, but otherwise it's exactly the same except for this line:

```<code><classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.module.container"/>
</code>```

I think we might not need that one but it's not hurting anything atm.

edit2: Further testing reveals that eclipse is generating class files in both the /eclipse-classes folders and the /classes folder. It seems that m2eclipse is running mvn build in the background when building automatically, but I can't seem to find a way to disable this. I'll try to get in touch with the m2eclipse developers if nobody here has any other ideas.

答:
I am using gradle. Refreshing gradle project will overwrite .classpath file. So I have to add the following at the end of the build.gradle file in order to let it maintain a JUNIT5 reference.</p>

```<code>eclipse.classpath.file.whenMerged {
    classpath ->
        def JUnitFive = new org.gradle.plugins.ide.eclipse.model.Container('org.eclipse.jdt.junit.JUNIT_CONTAINER/5')
        JUnitFive.exported = true
        classpath.entries << JUnitFive
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have an eclipse project where every source folder has its own associated output folder. Instead of /classes it's called /eclipse-classes.

So if I have a folder:
src/main/java (typical maven thing)
the target folder is:
target/eclipse-classes

And likewise for resources etc.

This seems to work (i.e. eclipse generates .class files that are put inside these folders) but running any Junit tests throws an exception stating "class not found". I'm running JUnit using the built-in eclipse test runner (i.e. right click the class, "run as", "Junit test").

Copying the /eclipse-classes folder to /classes makes them succeed, meaning eclipse is using /classes, but I can't find any configuration options to change it. Is there any way to find out where and why eclipse is still using the /classes folder?

(perhaps relevant, I'm also using the m2eclipse plugin)

Some additional information inspired by Rich Seller's answer:
Maven is configured to run the following on resource changes:

process-resources resources:testResources

While this won't do anything useful (copies to the wrong directory) the resources are not problematic atm since they end up in the correct location.

The .classpath entries look okay. There's a bunch of maven subprojects so the nesting goes a bit deeper than what Rich posted, but otherwise it's exactly the same except for this line:

<classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.module.container"/>

I think we might not need that one but it's not hurting anything atm.

edit2: Further testing reveals that eclipse is generating class files in both the /eclipse-classes folders and the /classes folder. It seems that m2eclipse is running mvn build in the background when building automatically, but I can't seem to find a way to disable this. I'll try to get in touch with the m2eclipse developers if nobody here has any other ideas.

Body:
I am using gradle. Refreshing gradle project will overwrite .classpath file. So I have to add the following at the end of the build.gradle file in order to let it maintain a JUNIT5 reference.

eclipse.classpath.file.whenMerged {
    classpath ->
        def JUnitFive = new org.gradle.plugins.ide.eclipse.model.Container('org.eclipse.jdt.junit.JUNIT_CONTAINER/5')
        JUnitFive.exported = true
        classpath.entries << JUnitFive
}


问:
Issue with the logo and its position using media queries
As the title states my logo for this assignment needs to be in certain areas of the screen in different screen sizes. I have the mobile positioning correctly implemented but I can't seem to find a solution the positioning of the logo for ipad and larger screens.

For large screens the logo needs to be centered directly above the first .product element, which in my case is the A as in Apple

For ipad screens the logo needs to be halfway between the left edge of the screen and the centered h1 element

No matter what I try the logo just stays fixed the left.

I realize that in css its position is set to float:left but I've changed it to display:flex and the various flexbox properties, but it ended up creating more of a problem. I've changed the logo position in each @media query but the logo always ended up staying in place or way off from where it needs to be.

I understand that google is my best friend but I've exhausted all possible methods and have reached my last resort. The last I wanted to do was get stuck and immediately post here without at least trying for several hours. Forgive me for the newbie and probably obvious question but I'm at my wits end and really need help . Thank you.

* {
  box-sizing: border-box;
  text-align: center;
}

body {
  font-family: "Roboto", sans-serif;
  margin: 0;
  padding: 0;
}

body>i> {
  flex-grow: 0;
}

body>header> {
  flex-grow: 1;
}

.logo>img {
  width: 50px;
}

p {
  text-align: left;
  padding: 15px;
}

.navbar {
  background-color: rgb(105, 105, 105);
  padding: 10px;
  color: white;
  width: 100%;
}

.hamburger {
  display: flex;
  flex-direction: row-reverse;
}

.social {
  display: flex;
  padding-top: 20px;
  flex-direction: row;
  justify-content: space-around;
  border-top: 2px solid #e2e2e2;
}

ul {
  list-style: none;
}

li {
  line-height: 5px;
  float: right;
  padding: 0 0 50px 0;
  margin-right: 30px;
  margin-top: -10px;
}

.product {
  border: 1px solid lightgray;
  border-radius: 10px;
  margin: 10px 30px;
  padding: 10px;
}

@media screen and (max-width: 700px) {
  .logo {
    float: left;
  }
  .menu {
    display: none;
  }
  .logo {
    float: left;
  }
}

@media screen and (max-width: 500px) {
  .logo {
    float: none;
  }
  .menu {
    display: none;
  }
}

@media screen and (min-width: 900px) {
  .hamburger {
    display: none;
  }
  .product {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    border: 1px solid lightgray;
    border-radius: 10px;
    margin-left: 30px;
    margin-right: 30px;
    width: 50%;
    text-align: center;
    margin-top: -20px;
    margin-bottom: 0px;
  }
  main {
    display: inline-flex;
  }
  .logo {
    position: absolute;
    left: 0;
    top: 25;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <title>Parcel Sandbox</title>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css" integrity="sha384-5sAR7xN1Nv6T6+dT2mhtzEpVJvfS3NScPQTrOxhwjIuvcA67KV2R5Jz6kr4abQsz" crossorigin="anonymous">
  <link rel="stylesheet" href="style.css" />
</head>

<body>
  <header>
    <div class="logo"><img src="https://uploads.codesandbox.io/uploads/user/6eb75550-4d51-47fd-8ec1-d216b5da5e5c/M4sq-logo.jpeg" /></div>
    <h1>The ABC Company</h1>
  </header>
  <nav class="navbar">
    <div class="hamburger">☰</div>
    <ul class="menu">
      <li>Help</li>
      <li>Products</li>
      <li>About</li>
      <li>Home</li>
    </ul>
  </nav>
  <main>
    <section class="product">
      <i class="fas fa-apple-alt fa-5x"></i>
      <h2>A as in Apple</h2>
      <p>
        We take out fruit very seriously at ABC, that is why the A in ABC is for Apple. Try our new AppleBook App, the coolest new technology disrupting the fruit industry. This is the Uber of Apples!
      </p>
    </section>
    <section class="product">
      <i class="fas fa-money-bill-wave fa-5x"></i>
      <h2>B as in Bail</h2>
      <p>
        Do you need Bail! Our new BailFace app will provide you with lawyers and bail money at the push of a button. Its the Facebook of bail bonds!
      </p>
    </section>
    <section class="product">
      <i class="fas fa-utensils fa-5x"></i>
      <h2>C as in Curry</h2>

      <p>
        Fancy some curry! Our new HurryCurry app will provide curry cooked by Italian chefs right to your door. Its the AirBnB of curry!
      </p>
    </section>
  </main>
  <footer>
    <ul class="social">
      <li class="social_icon"><i class="fab fa-twitter"></i></li>
      <li class="social_icon"><i class="fab fa-facebook"></i></li>
      <li class="social_icon"><i class="fab fa-instagram"></i></li>
    </ul>
  </footer>
</body>

</html></code>```

答:
Try this:

fragment header into 3 equals parts

```<code>header {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}
</code>```

make logo image center

```<code>.logo {
  display: flex;
  align-items: center;
  justify-content: center;
}
</code>```

make heading nowrap

```<code>header h1 {
  white-space: nowrap;
}
</code>```

Look into the snippet how it looks. I commented all floatings and absolute positioning in meadia query.

* {
  box-sizing: border-box;
  text-align: center;
}

body {
  font-family: "Roboto", sans-serif;
  margin: 0;
  padding: 0;
}

body>i> {
  flex-grow: 0;
}

body>header> {
  flex-grow: 1;
}

.logo>img {
  width: 50px;
}

p {
  text-align: left;
  padding: 15px;
}

.navbar {
  background-color: rgb(105, 105, 105);
  padding: 10px;
  color: white;
  width: 100%;
}

.hamburger {
  display: flex;
  flex-direction: row-reverse;
}

.social {
  display: flex;
  padding-top: 20px;
  flex-direction: row;
  justify-content: space-around;
  border-top: 2px solid #e2e2e2;
}

ul {
  list-style: none;
}

li {
  line-height: 5px;
  float: right;
  padding: 0 0 50px 0;
  margin-right: 30px;
  margin-top: -10px;
}

.product {
  border: 1px solid lightgray;
  border-radius: 10px;
  margin: 10px 30px;
  padding: 10px;
}

header {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}

header h1 {
  white-space: nowrap;
}

.logo {
  display: flex;
  align-items: center;
  justify-content: center;
}

@media screen and (max-width: 700px) {
  /*.logo {
    float: left;
  }*/
  .menu {
    display: none;
  }
  /*.logo {
    float: left;
  }*/
}

@media screen and (max-width: 500px) {
  /*.logo {
    float: none;
  }*/
  .menu {
    display: none;
  }
  header {
    display: block;
  }
}

@media screen and (min-width: 900px) {
  .hamburger {
    display: none;
  }
  .product {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    border: 1px solid lightgray;
    border-radius: 10px;
    margin-left: 30px;
    margin-right: 30px;
    width: 50%;
    text-align: center;
    margin-top: -20px;
    margin-bottom: 0px;
  }
  main {
    display: inline-flex;
  }
  /*.logo {
    position: absolute;
    left: 0;
    top: 25;
  }*/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <title>Parcel Sandbox</title>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css" integrity="sha384-5sAR7xN1Nv6T6+dT2mhtzEpVJvfS3NScPQTrOxhwjIuvcA67KV2R5Jz6kr4abQsz" crossorigin="anonymous">
  <link rel="stylesheet" href="style.css" />
</head>

<body>
  <header>
    <div class="logo"><img src="https://uploads.codesandbox.io/uploads/user/6eb75550-4d51-47fd-8ec1-d216b5da5e5c/M4sq-logo.jpeg" /></div>
    <h1>The ABC Company</h1>
  </header>
  <nav class="navbar">
    <div class="hamburger">☰</div>
    <ul class="menu">
      <li>Help</li>
      <li>Products</li>
      <li>About</li>
      <li>Home</li>
    </ul>
  </nav>
  <main>
    <section class="product">
      <i class="fas fa-apple-alt fa-5x"></i>
      <h2>A as in Apple</h2>
      <p>
        We take out fruit very seriously at ABC, that is why the A in ABC is for Apple. Try our new AppleBook App, the coolest new technology disrupting the fruit industry. This is the Uber of Apples!
      </p>
    </section>
    <section class="product">
      <i class="fas fa-money-bill-wave fa-5x"></i>
      <h2>B as in Bail</h2>
      <p>
        Do you need Bail! Our new BailFace app will provide you with lawyers and bail money at the push of a button. Its the Facebook of bail bonds!
      </p>
    </section>
    <section class="product">
      <i class="fas fa-utensils fa-5x"></i>
      <h2>C as in Curry</h2>

      <p>
        Fancy some curry! Our new HurryCurry app will provide curry cooked by Italian chefs right to your door. Its the AirBnB of curry!
      </p>
    </section>
  </main>
  <footer>
    <ul class="social">
      <li class="social_icon"><i class="fab fa-twitter"></i></li>
      <li class="social_icon"><i class="fab fa-facebook"></i></li>
      <li class="social_icon"><i class="fab fa-instagram"></i></li>
    </ul>
  </footer>
</body>

</html></code>```

Body:
As the title states my logo for this assignment needs to be in certain areas of the screen in different screen sizes. I have the mobile positioning correctly implemented but I can't seem to find a solution the positioning of the logo for ipad and larger screens.

For large screens the logo needs to be centered directly above the first .product element, which in my case is the A as in Apple

For ipad screens the logo needs to be halfway between the left edge of the screen and the centered h1 element

No matter what I try the logo just stays fixed the left.

I realize that in css its position is set to float:left but I've changed it to display:flex and the various flexbox properties, but it ended up creating more of a problem. I've changed the logo position in each @media query but the logo always ended up staying in place or way off from where it needs to be.

I understand that google is my best friend but I've exhausted all possible methods and have reached my last resort. The last I wanted to do was get stuck and immediately post here without at least trying for several hours. Forgive me for the newbie and probably obvious question but I'm at my wits end and really need help . Thank you.

* {
  box-sizing: border-box;
  text-align: center;
}

body {
  font-family: "Roboto", sans-serif;
  margin: 0;
  padding: 0;
}

body>i> {
  flex-grow: 0;
}

body>header> {
  flex-grow: 1;
}

.logo>img {
  width: 50px;
}

p {
  text-align: left;
  padding: 15px;
}

.navbar {
  background-color: rgb(105, 105, 105);
  padding: 10px;
  color: white;
  width: 100%;
}

.hamburger {
  display: flex;
  flex-direction: row-reverse;
}

.social {
  display: flex;
  padding-top: 20px;
  flex-direction: row;
  justify-content: space-around;
  border-top: 2px solid #e2e2e2;
}

ul {
  list-style: none;
}

li {
  line-height: 5px;
  float: right;
  padding: 0 0 50px 0;
  margin-right: 30px;
  margin-top: -10px;
}

.product {
  border: 1px solid lightgray;
  border-radius: 10px;
  margin: 10px 30px;
  padding: 10px;
}

@media screen and (max-width: 700px) {
  .logo {
    float: left;
  }
  .menu {
    display: none;
  }
  .logo {
    float: left;
  }
}

@media screen and (max-width: 500px) {
  .logo {
    float: none;
  }
  .menu {
    display: none;
  }
}

@media screen and (min-width: 900px) {
  .hamburger {
    display: none;
  }
  .product {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    border: 1px solid lightgray;
    border-radius: 10px;
    margin-left: 30px;
    margin-right: 30px;
    width: 50%;
    text-align: center;
    margin-top: -20px;
    margin-bottom: 0px;
  }
  main {
    display: inline-flex;
  }
  .logo {
    position: absolute;
    left: 0;
    top: 25;
  }
}

<!DOCTYPE html>

  <title>Parcel Sandbox</title>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css" integrity="sha384-5sAR7xN1Nv6T6+dT2mhtzEpVJvfS3NScPQTrOxhwjIuvcA67KV2R5Jz6kr4abQsz" crossorigin="anonymous">
  <link rel="stylesheet" href="style.css" />

The ABC Company

☰

Help

Products

About

Home

A as in Apple

        We take out fruit very seriously at ABC, that is why the A in ABC is for Apple. Try our new AppleBook App, the coolest new technology disrupting the fruit industry. This is the Uber of Apples!

B as in Bail

        Do you need Bail! Our new BailFace app will provide you with lawyers and bail money at the push of a button. Its the Facebook of bail bonds!

C as in Curry

        Fancy some curry! Our new HurryCurry app will provide curry cooked by Italian chefs right to your door. Its the AirBnB of curry!

Body:
Try this:

fragment header into 3 equals parts

header {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}

make logo image center

.logo {
  display: flex;
  align-items: center;
  justify-content: center;
}

make heading nowrap

header h1 {
  white-space: nowrap;
}

Look into the snippet how it looks. I commented all floatings and absolute positioning in meadia query.

* {
  box-sizing: border-box;
  text-align: center;
}

body {
  font-family: "Roboto", sans-serif;
  margin: 0;
  padding: 0;
}

body>i> {
  flex-grow: 0;
}

body>header> {
  flex-grow: 1;
}

.logo>img {
  width: 50px;
}

p {
  text-align: left;
  padding: 15px;
}

.navbar {
  background-color: rgb(105, 105, 105);
  padding: 10px;
  color: white;
  width: 100%;
}

.hamburger {
  display: flex;
  flex-direction: row-reverse;
}

.social {
  display: flex;
  padding-top: 20px;
  flex-direction: row;
  justify-content: space-around;
  border-top: 2px solid #e2e2e2;
}

ul {
  list-style: none;
}

li {
  line-height: 5px;
  float: right;
  padding: 0 0 50px 0;
  margin-right: 30px;
  margin-top: -10px;
}

.product {
  border: 1px solid lightgray;
  border-radius: 10px;
  margin: 10px 30px;
  padding: 10px;
}

header {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}

header h1 {
  white-space: nowrap;
}

.logo {
  display: flex;
  align-items: center;
  justify-content: center;
}

@media screen and (max-width: 700px) {
  /*.logo {
    float: left;
  }*/
  .menu {
    display: none;
  }
  /*.logo {
    float: left;
  }*/
}

@media screen and (max-width: 500px) {
  /*.logo {
    float: none;
  }*/
  .menu {
    display: none;
  }
  header {
    display: block;
  }
}

@media screen and (min-width: 900px) {
  .hamburger {
    display: none;
  }
  .product {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    border: 1px solid lightgray;
    border-radius: 10px;
    margin-left: 30px;
    margin-right: 30px;
    width: 50%;
    text-align: center;
    margin-top: -20px;
    margin-bottom: 0px;
  }
  main {
    display: inline-flex;
  }
  /*.logo {
    position: absolute;
    left: 0;
    top: 25;
  }*/
}

<!DOCTYPE html>
<html lang="en">

<head>
  <title>Parcel Sandbox</title>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css" integrity="sha384-5sAR7xN1Nv6T6+dT2mhtzEpVJvfS3NScPQTrOxhwjIuvcA67KV2R5Jz6kr4abQsz" crossorigin="anonymous">
  <link rel="stylesheet" href="style.css" />
</head>

<body>
  <header>
    <div class="logo"><img src="https://uploads.codesandbox.io/uploads/user/6eb75550-4d51-47fd-8ec1-d216b5da5e5c/M4sq-logo.jpeg" /></div>
    <h1>The ABC Company</h1>
  </header>
  <nav class="navbar">
    <div class="hamburger">&#9776;</div>
    <ul class="menu">
      <li>Help</li>
      <li>Products</li>
      <li>About</li>
      <li>Home</li>
    </ul>
  </nav>
  <main>
    <section class="product">
      <i class="fas fa-apple-alt fa-5x"></i>
      <h2>A as in Apple</h2>
      <p>
        We take out fruit very seriously at ABC, that is why the A in ABC is for Apple. Try our new AppleBook App, the coolest new technology disrupting the fruit industry. This is the Uber of Apples!
      </p>
    </section>
    <section class="product">
      <i class="fas fa-money-bill-wave fa-5x"></i>
      <h2>B as in Bail</h2>
      <p>
        Do you need Bail! Our new BailFace app will provide you with lawyers and bail money at the push of a button. Its the Facebook of bail bonds!
      </p>
    </section>
    <section class="product">
      <i class="fas fa-utensils fa-5x"></i>
      <h2>C as in Curry</h2>

      <p>
        Fancy some curry! Our new HurryCurry app will provide curry cooked by Italian chefs right to your door. Its the AirBnB of curry!
      </p>
    </section>
  </main>
  <footer>
    <ul class="social">
      <li class="social_icon"><i class="fab fa-twitter"></i></li>
      <li class="social_icon"><i class="fab fa-facebook"></i></li>
      <li class="social_icon"><i class="fab fa-instagram"></i></li>
    </ul>
  </footer>
</body>

</html>


问:
Inject errors into already validated form?
After my form.Form validates the user input values I pass them to a separate (external) process for further processing. This external process can potentially find further errors in the values.

Is there a way to inject these errors into the already validated form so they can be displayed via the usual form error display methods (or are there better alternative approaches)?

One suggestions was to include the external processing in the form validation, which is not ideal because the external process does a lot more than merely validate.

答:
Add error to specific field :

```<code>form.add_error('fieldName', 'error description')
</code>```

**Add error to non fields **

```<code>form.add_error(None, 'error description')
#Only pass None instead of field name
</code>```

OwnerDisplayName: Parand

ContentLicense: CC BY-SA 3.0

Body:
Add error to specific field :

form.add_error('fieldName', 'error description')

**Add error to non fields **

form.add_error(None, 'error description')
#Only pass None instead of field name


问:
Mongoengine custom queryset
I am trying to convert the ObjectId and ISODate to string representations while querying from MongoDB database.

```<code>def mongo_to_dict(obj, exclude_fields):
    return_data = []

    if obj is None:
        return None

    if isinstance(obj, Document):
        return_data.append(("_id", str(obj.id)))

    for field_name in obj._fields:

        if field_name in exclude_fields:
            continue

        if field_name in ("id",):
            continue

        data = obj._data[field_name]

        if isinstance(obj._fields[field_name], ListField):
            return_data.append((field_name, list_field_to_dict(data)))
        elif isinstance(obj._fields[field_name], EmbeddedDocumentField):
            return_data.append((field_name, mongo_to_dict(data, [])))
        elif isinstance(obj._fields[field_name], DictField):
            return_data.append((field_name, data))
        else:
            return_data.append((field_name, mongo_to_python_type(obj._fields[field_name], data)))

    return dict(return_data)

def list_field_to_dict(list_field):
    return_data = []

    for item in list_field:
        if isinstance(item, EmbeddedDocument):
            return_data.append(mongo_to_dict(item, []))
        else:
            return_data.append(mongo_to_python_type(item, item))

    return return_data

def mongo_to_python_type(field, data):
    if isinstance(field, DateTimeField):
        return time.mktime(data.timetuple()) * 1000
    elif isinstance(field, ComplexDateTimeField):
        return field.to_python(data).isoformat()
    elif isinstance(field, StringField):
        return str(data)
    elif isinstance(field, FloatField):
        return float(data)
    elif isinstance(field, IntField):
        return int(data)
    elif isinstance(field, BooleanField):
        return bool(data)
    elif isinstance(field, ObjectIdField):
        return str(data)
    elif isinstance(field, DecimalField):
        return data
    else:
        return str(data)

class Portfolio(Document):
    meta = {'collection': 'Portfolios'}
    PortfolioName = StringField()
    LastUpdateDate = DateTimeField(default=datetime.datetime.now())
    RecentActivity = ListField(default=[])

    def to_dict(self):
        return mongo_to_dict(self, [])
</code>```

Now when i create a Portfolio Object like this

```<code>a = Portfolio(PortfolioName='BB Visa').save()
</code>```

and when i try to get the to_dict() repressentation for the object like a.to_dict(), it works perfectly.

```<code>{'_id': '5581cf9129e457241a32e8f7', 'PortfolioName': 'BB Visa', 'RecentActivity': [], 'LastUpdateDate': 1434570641000.0}
</code>```

But the problem is i want to_dict() to operate on class level not object level.

So when i tried to define a custom queryset like this

```<code>class Portfolio(Document):
    meta = {'collection': 'Portfolios'}
    PortfolioName = StringField()
    LastUpdateDate = DateTimeField(default=datetime.datetime.now())
    RecentActivity = ListField(default=[])

    @queryset_manager
    def to_dict(self, queryset):
        return mongo_to_dict(self, [])
</code>```

Now running the following command Portfolio.to_dict() generates error like below
Traceback (most recent call last):

```<code>  File "/home/ajay/PycharmProjects/solveit/test.py", line 102, in <module>
    print(Portfolio.to_dict())
  File "/home/ajay/.pyenv/versions/3.4.3/lib/python3.4/site-packages/mongoengine/queryset/manager.py", line 43, in __get__
    queryset = self.get_queryset(owner, queryset)
  File "/home/ajay/PycharmProjects/solveit/test.py", line 83, in to_dict
    return mongo_to_dict(self, [])
  File "/home/ajay/PycharmProjects/solveit/test.py", line 28, in mongo_to_dict
    data = obj._data[field_name]
TypeError: 'member_descriptor' object is not subscriptable
</code>```

I understand that QuerySet Manager passes class into the function, thats why the error. How to solve this.

答:
That's an old question but it's very interesting and here still was no good answer. So here is my answer.

Intro

You're right in customizing queryset, but you shouldn't define another queryset_manager for your purposes. As @bellum mentioned @queryset_manager should return QuerySet. Instead you should define method inside QuerySet. You can do this inside your queryset_manager but it still won't work with filter, order_by, skip, limit and such. Instead you should define custom QuerSet and set it as default for model.

Answer

```<code>from mongoengine.queryset import QuerySet

class CustomQuerySet(QuerySet):

    # define your custom method here
    def print_ids(self):
        for doc in self:
            print(doc.id)

class Product(DynamicDocument):
    # set your CustomQuerySet as default queryset_class
    meta = {'queryset_class': CustomQuerySet}
</code>```

Actually your model will use base QuerySet but now it will contain your custom methods.

Examples

```<code>>>> Product.objects.print_ids()
5e46433c943478954eef837d
5e46623705f1fa6c78e3fdbc
5e46627b05f1fa6c78e403a3
</code>```

You may use it with filters:

```<code>>>> Product.objects.filter(id='5e46433c943478954eef837d').print_ids()
5e46433c943478954eef837d
</code>```

You may use ordering, skip, limit and other stuff:

```<code>>>> Product.objects.all().limit(2).print_ids()
5e46433c943478954eef837d
5e46623705f1fa6c78e3fdbc
</code>```

Title: Mongoengine custom queryset

Body:
I am trying to convert the ObjectId and ISODate to string representations while querying from MongoDB database.

def mongo_to_dict(obj, exclude_fields):
    return_data = []

    if obj is None:
        return None

    if isinstance(obj, Document):
        return_data.append(("_id", str(obj.id)))

    for field_name in obj._fields:

        if field_name in exclude_fields:
            continue

        if field_name in ("id",):
            continue

        data = obj._data[field_name]

        if isinstance(obj._fields[field_name], ListField):
            return_data.append((field_name, list_field_to_dict(data)))
        elif isinstance(obj._fields[field_name], EmbeddedDocumentField):
            return_data.append((field_name, mongo_to_dict(data, [])))
        elif isinstance(obj._fields[field_name], DictField):
            return_data.append((field_name, data))
        else:
            return_data.append((field_name, mongo_to_python_type(obj._fields[field_name], data)))

    return dict(return_data)

def list_field_to_dict(list_field):
    return_data = []

    for item in list_field:
        if isinstance(item, EmbeddedDocument):
            return_data.append(mongo_to_dict(item, []))
        else:
            return_data.append(mongo_to_python_type(item, item))

    return return_data

def mongo_to_python_type(field, data):
    if isinstance(field, DateTimeField):
        return time.mktime(data.timetuple()) * 1000
    elif isinstance(field, ComplexDateTimeField):
        return field.to_python(data).isoformat()
    elif isinstance(field, StringField):
        return str(data)
    elif isinstance(field, FloatField):
        return float(data)
    elif isinstance(field, IntField):
        return int(data)
    elif isinstance(field, BooleanField):
        return bool(data)
    elif isinstance(field, ObjectIdField):
        return str(data)
    elif isinstance(field, DecimalField):
        return data
    else:
        return str(data)

class Portfolio(Document):
    meta = {'collection': 'Portfolios'}
    PortfolioName = StringField()
    LastUpdateDate = DateTimeField(default=datetime.datetime.now())
    RecentActivity = ListField(default=[])

    def to_dict(self):
        return mongo_to_dict(self, [])

Now when i create a Portfolio Object like this

a = Portfolio(PortfolioName='BB Visa').save()

and when i try to get the to_dict() repressentation for the object like a.to_dict(), it works perfectly.

{'_id': '5581cf9129e457241a32e8f7', 'PortfolioName': 'BB Visa', 'RecentActivity': [], 'LastUpdateDate': 1434570641000.0}

But the problem is i want to_dict() to operate on class level not object level.

So when i tried to define a custom queryset like this

class Portfolio(Document):
    meta = {'collection': 'Portfolios'}
    PortfolioName = StringField()
    LastUpdateDate = DateTimeField(default=datetime.datetime.now())
    RecentActivity = ListField(default=[])

    @queryset_manager
    def to_dict(self, queryset):
        return mongo_to_dict(self, [])

Now running the following command Portfolio.to_dict() generates error like below
Traceback (most recent call last):

  File "/home/ajay/PycharmProjects/solveit/test.py", line 102, in <module>
    print(Portfolio.to_dict())
  File "/home/ajay/.pyenv/versions/3.4.3/lib/python3.4/site-packages/mongoengine/queryset/manager.py", line 43, in __get__
    queryset = self.get_queryset(owner, queryset)
  File "/home/ajay/PycharmProjects/solveit/test.py", line 83, in to_dict
    return mongo_to_dict(self, [])
  File "/home/ajay/PycharmProjects/solveit/test.py", line 28, in mongo_to_dict
    data = obj._data[field_name]
TypeError: 'member_descriptor' object is not subscriptable

I understand that QuerySet Manager passes class into the function, thats why the error. How to solve this.

Body:
That's an old question but it's very interesting and here still was no good answer. So here is my answer.

Intro

You're right in customizing queryset, but you shouldn't define another queryset_manager for your purposes. As @bellum mentioned @queryset_manager should return QuerySet. Instead you should define method inside QuerySet. You can do this inside your queryset_manager but it still won't work with filter, order_by, skip, limit and such. Instead you should define custom QuerSet and set it as default for model.

Answer

from mongoengine.queryset import QuerySet

class CustomQuerySet(QuerySet):

    # define your custom method here
    def print_ids(self):
        for doc in self:
            print(doc.id)

class Product(DynamicDocument):
    # set your CustomQuerySet as default queryset_class
    meta = {'queryset_class': CustomQuerySet}

Actually your model will use base QuerySet but now it will contain your custom methods.

Examples

>>> Product.objects.print_ids()
5e46433c943478954eef837d
5e46623705f1fa6c78e3fdbc
5e46627b05f1fa6c78e403a3

You may use it with filters:

>>> Product.objects.filter(id='5e46433c943478954eef837d').print_ids()
5e46433c943478954eef837d

You may use ordering, skip, limit and other stuff:

>>> Product.objects.all().limit(2).print_ids()
5e46433c943478954eef837d
5e46623705f1fa6c78e3fdbc


问:
React componentDidUpdate() does not fire
I have an react app with primereact installed and I am using primereact/captcha.

Maybe I have misunderstood something, but isn't the following code supposed to work (console.log('Child component did update'))?

```<code>import React from 'react';
import { Captcha } from 'primereact/captcha';

export default function App() {
  return (
    <div className="App">
      <ParentComponent/>
    </div>
  );
}

class Child extends React.Component {
    componentDidUpdate () {
        console.log('Child component did update');
    }
    render() {
        return (<h2>Child component</h2>);
    }
}

class ParentComponent extends React.Component {
    constructor() {
        super();
        this.state = {
            captchaSovled: false,
            key : Math.random()
        }
    }
    render() {
        let output;
        if (this.state.captchaSolved) {
            output = <Child key={this.state.key} />;
        } else {
            output =<Captcha siteKey="xxxxxxx" onResponse={() => this.setState({ key : Math.random(), captchaSolved: true })} />
        }
        return (
            <div>
                <h1>Parent component</h1>
                {output}
            </div>
        );
    }
}
</code>```

答:
componentDidUpdate is fired, if there is any change in the state or props. As of your component child:

```<code>class Child extends React.Component {
    componentDidUpdate () {
        console.log('Child component did update');
    }
    render() {
        return (<h2>Child component</h2>);
    }
}
</code>```

There is no state or props which are changing, that's why componentDidUpdate never get's invoked.

Body:
I have an react app with primereact installed and I am using primereact/captcha.

Maybe I have misunderstood something, but isn't the following code supposed to work (console.log('Child component did update'))?

import React from 'react';
import { Captcha } from 'primereact/captcha';

export default function App() {
  return (

      <ParentComponent/>

  );
}

class Child extends React.Component {
    componentDidUpdate () {
        console.log('Child component did update');
    }
    render() {
        return (
Child component
);
    }
}

class ParentComponent extends React.Component {
    constructor() {
        super();
        this.state = {
            captchaSovled: false,
            key : Math.random()
        }
    }
    render() {
        let output;
        if (this.state.captchaSolved) {
            output = <Child key={this.state.key} />;
        } else {
            output =<Captcha siteKey="xxxxxxx" onResponse={() => this.setState({ key : Math.random(), captchaSolved: true })} />
        }
        return (

Parent component

                {output}

        );
    }
}

Body:
componentDidUpdate is fired, if there is any change in the state or props. As of your component child:

class Child extends React.Component {
    componentDidUpdate () {
        console.log('Child component did update');
    }
    render() {
        return (<h2>Child component</h2>);
    }
}

There is no state or props which are changing, that's why componentDidUpdate never get's invoked.


问:
Change zoom value in leaflet Tile Layer URL?
I have a map server with Leaflet, and my tiles url is www.examplemyserver.com/{z}/{x}/{y}.png
But my tiles zoom is Upside down with leaflet tiles zoom .
For example when zoom is 1  I want zoom set 21  and when zoom is 2 but set zoom 20  in string my tiles url.

```<code> leafletzoom   I want set myserverzoom
     1              21
     2              20
     3              19
     .              .
     .              .
     .              .
     20             2
     21             1
</code>```

I tried this but not work :

```<code>var ZoomDict={1:21,2:20,3:19,4:18,5:17,6:16,7:15,8:14,9:13,10:12,11:11,12:10,13:9,14:8,15:7,16:6,17:5,18:4,19:3,20:2,21:1};

mp=L.tileLayer('http://www.examplemyserver.com/'+"{ZoomDict['{z}']}"+'/{x}/{y}.jpg').addto(map)// out put: URL for tiles is :  http://www.examplemyserver.com/{ZoomDict['{7}']}/45/245.jpg'
or
mp=L.tileLayer('http://www.examplemyserver.com/'+"ZoomDict['{z}']"+'/{x}/{y}.jpg').addto(map)//out :put URL for tiles is :  http://www.examplemyserver.com/undefind/45/245.jpg'
or
mp=L.tileLayer('http://www.examplemyserver.com/{ZoomDict['{z}']}/{x}/{y}.jpg').addto(map) //out put: URL for tiles is :  http://www.examplemyserver.com/{ZoomDict['{7}']}/45/245.jpg'
</code>```

答:
Unfortunately the Leaflet Tile Layer URL template will just perform string replacement, which leads to the results you report.

In your case you want to customize the zoom value used to build the tiles URL. To do so, you can override the getTileUrl method of Tile Layer class:

const TileLayerCustom = L.TileLayer.extend({
  getTileUrl(coords) {
    return `http://www.examplemyserver.com/${ZoomDict[coords.z]}/${coords.x}/${coords.y}.jpg`;
  }
});

const mp = new TileLayerCustom().addTo(map);
```

Body:
I have a map server with Leaflet, and my tiles url is www.examplemyserver.com/{z}/{x}/{y}.png
But my tiles zoom is Upside down with leaflet tiles zoom .
For example when zoom is 1  I want zoom set 21  and when zoom is 2 but set zoom 20  in string my tiles url.

 leafletzoom   I want set myserverzoom
     1              21
     2              20
     3              19
     .              .
     .              .
     .              .
     20             2
     21             1

I tried this but not work :

var ZoomDict={1:21,2:20,3:19,4:18,5:17,6:16,7:15,8:14,9:13,10:12,11:11,12:10,13:9,14:8,15:7,16:6,17:5,18:4,19:3,20:2,21:1};

mp=L.tileLayer('http://www.examplemyserver.com/'+"{ZoomDict['{z}']}"+'/{x}/{y}.jpg').addto(map)// out put: URL for tiles is :  http://www.examplemyserver.com/{ZoomDict['{7}']}/45/245.jpg'
or
mp=L.tileLayer('http://www.examplemyserver.com/'+"ZoomDict['{z}']"+'/{x}/{y}.jpg').addto(map)//out :put URL for tiles is :  http://www.examplemyserver.com/undefind/45/245.jpg'
or
mp=L.tileLayer('http://www.examplemyserver.com/{ZoomDict['{z}']}/{x}/{y}.jpg').addto(map) //out put: URL for tiles is :  http://www.examplemyserver.com/{ZoomDict['{7}']}/45/245.jpg'


问:
how to autorun php file per day
The website is written in .php with the connection of MySQL
I had a file that's named PMautoemail.php It can be run successfully but I only want it to run once a day. Cronjob couldn't be set up as I am running in a windows server and this website will be run by other people too. What should I do?

答:
You can use Windows Task Scheduler to run the file daily. Think of it as cronjob for Windows.

EDIT:

Another option: Windows Sub-system for Linux. https://learn.microsoft.com/en-us/windows/wsl/install-win10

Title: how to autorun php file per day


问:
Converting Roman Numerals to integers in python
This is now my current code after what user2486 said.

```<code>def romanMap():
    map=(("M",  1000),("CM", 900),("D",  500),("CD", 400),("C",  100),("XC", 90),("L",  50),("XL", 40),("X",  10),("IX", 9),("V",  5),("V", 4),("I",  1))
    return map
firstNum=ns([0])
secondNum=ns([1])
def main():
    ns=str(input("Enter a roman numeral"))
    total=0
    result=0
    while ns:
        firstNum=(romanMap(ns[0]))
         secondNum=(romanMap(ns[1])
        if firstNum is len(ns)>1 or secondNum-1:
                        total=total+firstNum
            ns=ns[1:]
        else:
                        total=total+ns[1]-ns[0]
            ns=ns[2:]
      print (total)
main()
</code>```

I am getting this error with     while ns:
UnboundLocalError: local variable 'ns' referenced before assignment

答:
```<code>def romanToInt(self, s: str) -> int:
    roman_dict = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
    int_equ = 0

    for i in range(len(s)):
        if i > 0 and roman_dict[s[i]] > roman_dict[s[i-1]]:
            int_equ += roman_dict[s[i]] - 2*roman_dict[s[i-1]]
        else:
            int_equ += roman_dict[s[i]]

    return int_equ
</code>```

Body:
This is now my current code after what user2486 said.

def romanMap():
    map=(("M",  1000),("CM", 900),("D",  500),("CD", 400),("C",  100),("XC", 90),("L",  50),("XL", 40),("X",  10),("IX", 9),("V",  5),("V", 4),("I",  1))
    return map
firstNum=ns([0])
secondNum=ns([1])
def main():
    ns=str(input("Enter a roman numeral"))
    total=0
    result=0
    while ns:
        firstNum=(romanMap(ns[0]))
         secondNum=(romanMap(ns[1])
        if firstNum is len(ns)>1 or secondNum-1:
                        total=total+firstNum
            ns=ns[1:]
        else:
                        total=total+ns[1]-ns[0]
            ns=ns[2:]
      print (total)
main()

I am getting this error with     while ns:
UnboundLocalError: local variable 'ns' referenced before assignment


问:
Why OAuth2 is not allowing to contain fragment identifier in redirect URI?
According to the OAuth2.0 spec, the redirect URI should not contain a fragment identifier.

The redirection endpoint URI MUST be an absolute URI as defined by
[RFC3986] Section 4.3. The endpoint URI MAY include an
"application/x-www-form-urlencoded" formatted (per Appendix B) query
component ([RFC3986] Section 3.4), which MUST be retained when adding
additional query parameters. The endpoint URI MUST NOT include a
fragment component.

Are there any specific reasons for why the spec has made such limitations?

Thanks in advance!

答:
URL fragment never leaves your browser. They are intended to be used by front end (That mean if you put a hash fragment to a URL in your browser and visit it, fragment won't reach the server end).

So when authorization server redirects via user agent, fragment will only stay on the user agent. From OAuth perspective this could bring unwanted complexity and security vulnerability. This is further highlighted under Insufficient Redirect URI Validation in best practice draft.


答:
From React doc

componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.

In your code, the Child component is mounted after captchaSolved state is set, therefore only componentDidMount is fired on Child component.

Title: React componentDidUpdate() does not fire


问:
AppBar button-Click event is raised before the LostFocus event of the TextBox in UWP
I have a Textbox tha has LostFocus event, one button that has Click event, and one appbarButton with click event.
Whenever I click on the non-appbar button, if the focus was in the text box it always calls the Lostfocus event before click event. But. when I do same thing by clicking an appbar button, it never allows Lostfocus to run before its click event.
I tried making LostFocus as async method but nothing is working the way I want.
Can anyone help me with the solution?</p>

答: Set AllowFocusOnInteraction = true of the AppBar button. This will trigger the LostFocus event first if any field losses focus before the Click of the AppBar button.</p>


问:
location of .htaccess in bitnami wordpress
i am not able to find the location of .htaccess file in bitnami wordpress. Need to enable content scripting policy in .htaccess file. But this file doesnot exits in nginx bitnami wordpress. Could anyone please help to resolve.</p>

答:
Check Here</p>

```<code><Directory "/opt/bitnami/apps/wordpress/htdocs/">
 Your code here
</Directory>
</code>```

Body:
Check Here

<Directory "/opt/bitnami/apps/wordpress/htdocs/">
 Your code here
</Directory>


问:
Caught NoReverseMatch while rendering: Reverse for '' with arguments '(1,)' and keyword arguments '{}' not found
My view :

```<code>def display(request):
    feed = SoukFeedMaster.objects.filter(person = request.user)
    return render(request, 'soukfeed/display.html', {'feed' : feed ,})
</code>```

My Template :

```<code>{% extends "base.html" %}

    {% block content %}
    {% for x in feed %}
        {% load url from future %}
        <a href="{% url x.content.url_internal_django_link  x.content.id  %}">  {{x.content.content}} </a>
        <br/>
    {% endfor %}

    {% endblock %}
</code>```

Traceback  :

```<code>Environment:

Request Method: GET
Request URL: http://localhost:8000/soukfeed/

Django Version: 1.3
Python Version: 2.7.1
Installed Applications:
['django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.comments',
 'ec.kiosk',
 'ec.chakra',
 'ec.ajax',
 'ec.broadcast',
 'ec.connect',
 'ec.seek_solutions',
 'ec.feed',
 'ec.ec_model',
 'ec.info',
 'ec.souk_info',
 'ec.ec_central',
 'ec.domains',
 'ec.souk',
 'ec.souk_feed',
 'ec.meta',
 'django.contrib.admin']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')

Template error:
In template /volumes/disk2/workspace/templates/ec/soukfeed/display.html, error at line 1
   Caught NoReverseMatch while rendering: Reverse for '' with arguments '(1,)' and keyword arguments '{}' not found.
   1 : {% extends "base.html" %}

    {% block content %}
     {% for x in feed %}
        {% load url from future %}
        <a href="{% url x.content.url_internal_django_link  x.content.id  %}">  {{ x.content.content }} </a>
        <br/>
    {% endfor %}

    {% endblock %}

Traceback:
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/Volumes/Disk2/workspace/ec/ec/souk_feed/views.py" in display
  18.         return render(request, 'soukfeed/display.html', {'feed' : feed ,})
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/shortcuts/__init__.py" in render
  44.     return HttpResponse(loader.render_to_string(*args, **kwargs),
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/loader.py" in render_to_string
  188.         return t.render(context_instance)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/base.py" in render
  123.             return self._render(context)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/base.py" in _render
  117.         return self.nodelist.render(context)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/debug.py" in render_node
  73.             result = node.render(context)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/loader_tags.py" in render
  127.         return compiled_parent._render(context)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/base.py" in _render
  117.         return self.nodelist.render(context)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/debug.py" in render_node
  73.             result = node.render(context)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/loader_tags.py" in render
  64.             result = block.nodelist.render(context)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/debug.py" in render_node
  73.             result = node.render(context)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/defaulttags.py" in render
  227.                 nodelist.append(node.render(context))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/defaulttags.py" in render
  450.                         raise e

Exception Type: TemplateSyntaxError at /soukfeed/
Exception Value: Caught NoReverseMatch while rendering: Reverse for '' with arguments '(1,)' and keyword arguments '{}' not found.
</code>```

答:
I have got the same exception output saying that not able to '(93L,)' and the keyword argument is not found.

Check the urls.py,where you can see that the url is not provided there.So provide the url then youre not going to this error.

Body:
My view :

def display(request):
    feed = SoukFeedMaster.objects.filter(person = request.user)
    return render(request, 'soukfeed/display.html', {'feed' : feed ,})

My Template :

{% extends "base.html" %}

    {% block content %}
    {% for x in feed %}
        {% load url from future %}
          {{x.content.content}}

    {% endfor %}

    {% endblock %}

Traceback  :

Environment:

Request Method: GET
Request URL: http://localhost:8000/soukfeed/

Django Version: 1.3
Python Version: 2.7.1
Installed Applications:
['django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.comments',
 'ec.kiosk',
 'ec.chakra',
 'ec.ajax',
 'ec.broadcast',
 'ec.connect',
 'ec.seek_solutions',
 'ec.feed',
 'ec.ec_model',
 'ec.info',
 'ec.souk_info',
 'ec.ec_central',
 'ec.domains',
 'ec.souk',
 'ec.souk_feed',
 'ec.meta',
 'django.contrib.admin']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')

Template error:
In template /volumes/disk2/workspace/templates/ec/soukfeed/display.html, error at line 1
   Caught NoReverseMatch while rendering: Reverse for '' with arguments '(1,)' and keyword arguments '{}' not found.
   1 : {% extends "base.html" %}

    {% block content %}
     {% for x in feed %}
        {% load url from future %}
          {{ x.content.content }}

    {% endfor %}

    {% endblock %}

Traceback:
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/Volumes/Disk2/workspace/ec/ec/souk_feed/views.py" in display
  18.         return render(request, 'soukfeed/display.html', {'feed' : feed ,})
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/shortcuts/__init__.py" in render
  44.     return HttpResponse(loader.render_to_string(*args, **kwargs),
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/loader.py" in render_to_string
  188.         return t.render(context_instance)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/base.py" in render
  123.             return self._render(context)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/base.py" in _render
  117.         return self.nodelist.render(context)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/debug.py" in render_node
  73.             result = node.render(context)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/loader_tags.py" in render
  127.         return compiled_parent._render(context)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/base.py" in _render
  117.         return self.nodelist.render(context)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/debug.py" in render_node
  73.             result = node.render(context)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/loader_tags.py" in render
  64.             result = block.nodelist.render(context)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/debug.py" in render_node
  73.             result = node.render(context)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/defaulttags.py" in render
  227.                 nodelist.append(node.render(context))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/defaulttags.py" in render
  450.                         raise e

Exception Type: TemplateSyntaxError at /soukfeed/
Exception Value: Caught NoReverseMatch while rendering: Reverse for '' with arguments '(1,)' and keyword arguments '{}' not found.


问:
Place text fields side by side in input-group Bootstarp
I am new to Bootstrap. I am trying to add an input group in which text fields are place side-by-side. However, it is not grouping well. I am getting extra space between the text fields and button.

Here is my code:

```<code><div class="form-group researchPapers">
    <div class="input-group">
        <div class="col-sm-12 form-group">
            <input type="text" id="title[]" name="title[]" class="form-control" placeholder="Title of Paper" />
        </div>
        <div class="col-sm-12 form-group">
            <input type="text" id="journal[]" name="journal[]" class="form-control" placeholder="Name of Journal" />
        </div>
        <div class="input-group-addon">
            <a href="javascript:void(0)" class="btn btn-success addMore"><span class="glyphicon glyphicon glyphicon-plus" aria-hidden="true"></span> Add New</a>
        </div>
    </div>
</div>
</code>```

Any help is highly appreciated.

答:
You can Try this but the problem is you can't get more than one extra text field because it will exceed the div

here's the code

$(document).ready(function() {
  $('#Add').on('click', function() {
    $('#form').append('
<input type="text" id="title[]" name="title[]" class="form-control" placeholder="Title of Paper" />

<input type="text" id="journal[]" name="journal[]" class="form-control" placeholder="Name of Journal" />

<input type="text" id="vol[]" name="vol[]" class="form-control" placeholder="Volume" />

<input type="text" id="issue[]" name="issue[]" class="form-control" placeholder="Issue" />

<input type="text" id="pages[]" name="pages[]" class="form-control" placeholder="Pages" />

<input type="text" id="year[]" name="year[]" class="form-control" placeholder="Year" />

 Add New

')
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<div class="container">
  <div class="panel panel-danger">
    <div class="panel-body">
      <form id="test_form">
        <div class="row">
          <div class="col-sm-12 form-group">
            <label for="name">Published Research Articles</label>
          </div>
        </div>

        <div class="form-group researchPapers">
          <div class="input-group" id="form">
            <div class="col-sm-12 form-group">
              <input type="text" id="title[]" name="title[]" class="form-control" placeholder="Title of Paper" />
            </div>
            <div class="col-sm-4 form-group">
              <input type="text" id="journal[]" name="journal[]" class="form-control" placeholder="Name of Journal" />
            </div>
            <div class="col-sm-2 form-group">
              <input type="text" id="vol[]" name="vol[]" class="form-control" placeholder="Volume" />
            </div>
            <div class="col-sm-2 form-group">
              <input type="text" id="issue[]" name="issue[]" class="form-control" placeholder="Issue" />
            </div>
            <div class="col-sm-2 form-group">
              <input type="text" id="pages[]" name="pages[]" class="form-control" placeholder="Pages" />
            </div>
            <div class="col-sm-2 form-group">
              <input type="text" id="year[]" name="year[]" class="form-control" placeholder="Year" />
            </div>
            <div class="input-group-addon">
              <span class="glyphicon glyphicon glyphicon-plus" aria-hidden="true"></span> Add New
            </div>
          </div>
        </div>
        <input type="submit" name="submit" class="btn btn-primary" value="SUBMIT" />
      </form>
    </div>
  </div>
</div></code>```

Body:
I am new to Bootstrap. I am trying to add an input group in which text fields are place side-by-side. However, it is not grouping well. I am getting extra space between the text fields and button.

Here is my code:

            <input type="text" id="title[]" name="title[]" class="form-control" placeholder="Title of Paper" />

            <input type="text" id="journal[]" name="journal[]" class="form-control" placeholder="Name of Journal" />

             Add New

Any help is highly appreciated.

Body:
You can Try this but the problem is you can't get more than one extra text field because it will exceed the div

here's the code

$(document).ready(function() {
  $('#Add').on('click', function() {
    $('#form').append('<div class="col-sm-12 form-group"><input type="text" id="title[]" name="title[]" class="form-control" placeholder="Title of Paper" /></div><div class="col-sm-4 form-group"><input type="text" id="journal[]" name="journal[]" class="form-control" placeholder="Name of Journal" /></div><div class="col-sm-2 form-group"><input type="text" id="vol[]" name="vol[]" class="form-control" placeholder="Volume" /></div><div class="col-sm-2 form-group"><input type="text" id="issue[]" name="issue[]" class="form-control" placeholder="Issue" /></div><div class="col-sm-2 form-group"><input type="text" id="pages[]" name="pages[]" class="form-control" placeholder="Pages" /></div><div class="col-sm-2 form-group"><input type="text" id="year[]" name="year[]" class="form-control" placeholder="Year" /></div><div class="input-group-addon"><a href="#" class="btn btn-success addMore" id="Add"><span class="glyphicon glyphicon glyphicon-plus" aria-hidden="true"></span> Add New</a></div></div></div>')
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<div class="container">
  <div class="panel panel-danger">
    <div class="panel-body">
      <form id="test_form">
        <div class="row">
          <div class="col-sm-12 form-group">
            <label for="name">Published Research Articles</label>
          </div>
        </div>

        <div class="form-group researchPapers">
          <div class="input-group" id="form">
            <div class="col-sm-12 form-group">
              <input type="text" id="title[]" name="title[]" class="form-control" placeholder="Title of Paper" />
            </div>
            <div class="col-sm-4 form-group">
              <input type="text" id="journal[]" name="journal[]" class="form-control" placeholder="Name of Journal" />
            </div>
            <div class="col-sm-2 form-group">
              <input type="text" id="vol[]" name="vol[]" class="form-control" placeholder="Volume" />
            </div>
            <div class="col-sm-2 form-group">
              <input type="text" id="issue[]" name="issue[]" class="form-control" placeholder="Issue" />
            </div>
            <div class="col-sm-2 form-group">
              <input type="text" id="pages[]" name="pages[]" class="form-control" placeholder="Pages" />
            </div>
            <div class="col-sm-2 form-group">
              <input type="text" id="year[]" name="year[]" class="form-control" placeholder="Year" />
            </div>
            <div class="input-group-addon">
              <a href="#" class="btn btn-success addMore" id="Add"><span class="glyphicon glyphicon glyphicon-plus" aria-hidden="true"></span> Add New</a>
            </div>
          </div>
        </div>
        <input type="submit" name="submit" class="btn btn-primary" value="SUBMIT" />
      </form>
    </div>
  </div>
</div>


问:
How to bypass memory caching while using FIO inside of a docker container?
I am trying to benchmark I/O performance on my host and docker container using flexible IO tool with O_direct enabled in order to bypass memory caching. The result is very suspicious. docker performs almost 50 times better than my host machine which is impossible. It seems like docker is not bypassing the caching at all. even if I ran it with  --privileged mode. This is the command I ran inside of a container, Any suggestions?

```<code>fio --name=seqread --rw=read --direct=1 --ioengine=libaio --bs=4k --numjobs=1 --size=10G --runtime=600  --group_reporting --output-format=json >/home/docker/docker_seqread_4k.json
</code>```

答:
(Note this isn't really a programming question so Stackoverflow is the wrong place to ask this... Maybe Super User or Serverfault would be a better choice and get faster answers?)

The result is very suspicious. docker performs almost 50 times better than my host machine which is impossible. It seems like docker is not bypassing the caching at all.

If your best case latencies are suspiciously small compared to your worst case latencies it is highly likely your suspicions are well founded and that kernel caching is still happening. Asking for O_DIRECT is a hint not an order and the filesystem can choose to ignore it and use the cache anyway (see the part about "You're asking for direct I/O to a file in a filesystem but...").

If you have the option and you're interested in disk speed, it is better to do any such test outside of a container (with all the caveats that implies). Another option when you can't/don't want to disable caching is ensure that you do I/O that is at least two to three times the size (both in terms of amount and the region being used) of RAM so the majority of I/O can't be satisfied by buffers/cache (and if you're doing write I/O then do something like end_fsync=1 too).

In summary, the filesystem being used by docker may make it impossible to accurately do what you're requesting (measure the disk speed by bypassing cache while using whatever your default docker filesystem is).

Body:
I am trying to benchmark I/O performance on my host and docker container using flexible IO tool with O_direct enabled in order to bypass memory caching. The result is very suspicious. docker performs almost 50 times better than my host machine which is impossible. It seems like docker is not bypassing the caching at all. even if I ran it with  --privileged mode. This is the command I ran inside of a container, Any suggestions?

fio --name=seqread --rw=read --direct=1 --ioengine=libaio --bs=4k --numjobs=1 --size=10G --runtime=600  --group_reporting --output-format=json >/home/docker/docker_seqread_4k.json


问:
How to save last components changes?
There is component that is activated by condition ngif.

Use can perform activity, for example open menu, set active element or just write text inside textarea.

After that user leaves this component to another ngif.

After time user returns to previous component.

How to restore last activity, components changes to continue work?

I know, it might be solved using service, but mu component has it's own logic too.

答:
Because ngIf directive always destroy components that doesn't meet the condition, you should not use ngIfto "toggle" the components that storing live data inside without storing it somewhere else when it destroyed. I suggest to use CSS to toggle the components visibility instead.

```<code><your-component [ngStyle]="{'display' : yourToggleExpressions ? 'none' : 'block'}"><your-component/>
</code>```

This way, you hide it from UI while it still running behind.

Title: How to save last components changes?

Body:
Because ngIf directive always destroy components that doesn't meet the condition, you should not use ngIfto "toggle" the components that storing live data inside without storing it somewhere else when it destroyed. I suggest to use CSS to toggle the components visibility instead.

<your-component [ngStyle]="{'display' : yourToggleExpressions ? 'none' : 'block'}"><your-component/>

This way, you hide it from UI while it still running behind.


问:
Maven exec:java : how to open and read a file in the resources directory?
here is the structure of my project.

```<code>proj
  ---src
    ----main
        ----java
            ----Main.java
        ----resources
             ----res.txt
</code>```

I am using m2eclipse plugin with Eclipse.
In Main.java, I have

```<code>File f = new File("res.txt");  System.out.println(f.getAbsolutePath());
</code>```

When I run mvn exec:java, the path got printed out is "...\proj\res.txt". How can I make it look for the resource file in "...\proj\target\classes" directory?

EDIT:

Thanks for the answers to my original question. I have a follow-up questions:

So basically what I want to do is to have the Main class read the "res.txt" and then generate a new "newres.txt" to the resources directory so that I can package this new "newres.txt" to the jar file in the package phase later. Currently I mounted this exec:java to the prepare-package phase. How should I create this "newres.txt" in the resources directory without a hard-coded absolute path or depending on the directory structure of Maven?

答:
Try

```<code>InputStream IS = Main.class.getResourceAsStream("res.txt");
</code>```

to access the content of res.txt. Pay attention to the encoding of your text file (beware of defaults). If your maven project is set on UTF-8 for example, make sure res.txt is encoded in UTF-8 too, otherwise, you'll get funny errors at runtime.

Body:
here is the structure of my project.

proj
  ---src
    ----main
        ----java
            ----Main.java
        ----resources
             ----res.txt

I am using m2eclipse plugin with Eclipse.
In Main.java, I have

File f = new File("res.txt");  System.out.println(f.getAbsolutePath());

When I run mvn exec:java, the path got printed out is "...\proj\res.txt". How can I make it look for the resource file in "...\proj\target\classes" directory?

EDIT:

Thanks for the answers to my original question. I have a follow-up questions:

So basically what I want to do is to have the Main class read the "res.txt" and then generate a new "newres.txt" to the resources directory so that I can package this new "newres.txt" to the jar file in the package phase later. Currently I mounted this exec:java to the prepare-package phase. How should I create this "newres.txt" in the resources directory without a hard-coded absolute path or depending on the directory structure of Maven?

Body:
Try

InputStream IS = Main.class.getResourceAsStream("res.txt");

to access the content of res.txt. Pay attention to the encoding of your text file (beware of defaults). If your maven project is set on UTF-8 for example, make sure res.txt is encoded in UTF-8 too, otherwise, you'll get funny errors at runtime.


问:
How to check if any string in array contains any other string (substring) in other array? (PostgreSQL)
I've got 2 string arrays, and I wanna to compare if any string of first array - contains SUBstring from other one, which storing these SUBstrings.

In other words: I don't wanna compare these arrays and their strings fully, I need to find exactly if strings from one array contains a SUBstrings from other array.

答:
You can use the following approach, if the two arrays are not too big:

```<code>SELECT * FROM
    (SELECT unnest('{apple pie,sugar,brown sugar}'::varchar[]) a1) t1,
    (SELECT unnest('{pie,sugar}'::varchar[]) a2) t2
    where t1.a1 like ('%' || t2.a2 || '%')
</code>```

Otherwise I suggest you to use ts_vectors and the full text search operators: https://www.postgresql.org/docs/current/textsearch.html

Body:
You can use the following approach, if the two arrays are not too big:

SELECT * FROM
    (SELECT unnest('{apple pie,sugar,brown sugar}'::varchar[]) a1) t1,
    (SELECT unnest('{pie,sugar}'::varchar[]) a2) t2
    where t1.a1 like ('%' || t2.a2 || '%')

Otherwise I suggest you to use ts_vectors and the full text search operators: https://www.postgresql.org/docs/current/textsearch.html


答:
You should use the the canDeactivated guard it will call before the ngOnDestroy.

```<code>interface CanDeactivate<T> {
   canDeactivate(component: T,
      currentRoute: ActivatedRouteSnapshot,
      currentState: RouterStateSnapshot,
      nextState?: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean
}
</code>```

Title: How to save last components changes?

Body:
There is component that is activated by condition ngif.

Use can perform activity, for example open menu, set active element or just write text inside textarea.

After that user leaves this component to another ngif.

After time user returns to previous component.

How to restore last activity, components changes to continue work?

I know, it might be solved using service, but mu component has it's own logic too.

Body:
You should use the the canDeactivated guard it will call before the ngOnDestroy.

interface CanDeactivate<T> {
   canDeactivate(component: T,
      currentRoute: ActivatedRouteSnapshot,
      currentState: RouterStateSnapshot,
      nextState?: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean
}


问:
Bokeh Gives me an Empty Plot with ColumnDataSource
I'm a newbie on Bokeh. Been playing around with it successfully and have managed to plot beautiful charts.. But I think some of my basics are still flawed.

I tried the following simple example, and I end up with an empty plot.
I believe this is due to the x axis data being strings? But I'm unable to figure out why, and how to fix it.

Below is the code I tried:

```<code>from bokeh.io import show, output_notebook
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource
import pandas as pd

scores = [['Tom', 85], ['Dick', 30], ['Harry', 60], ['Sally', 80], ['Jimmy', 70], ['Raj', 50]]
scores_df = pd.DataFrame(scores, columns=['Name', 'Score'])

source = ColumnDataSource(scores_df)

fig = figure(title='my chart', plot_width=300, plot_height=300, y_range=(0,100), x_axis_label='Name', y_axis_label='Score')
fig.vbar(x='Name', top='Score', bottom=0, source=source, width=1, color='black')

output_notebook()
show(fig)
</code>```

And this is the output I get:

Please help me understand what i'm missing here?

答:
I believe Bokeh needs an x-range defined in some cases with vBar (especially when categoricals are strings), correct me if I'm wrong!

By adding x_range=scores_df['Name'] to the figure;

```<code>fig = figure(title='my chart', plot_width=300, plot_height=300, y_range=(0,100), x_axis_label='Name', y_axis_label='Score', x_range=scores_df['Name'])
</code>```

The bar chart is plotted
my chart

Body:
I'm a newbie on Bokeh. Been playing around with it successfully and have managed to plot beautiful charts.. But I think some of my basics are still flawed.

I tried the following simple example, and I end up with an empty plot.
I believe this is due to the x axis data being strings? But I'm unable to figure out why, and how to fix it.

Below is the code I tried:

from bokeh.io import show, output_notebook
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource
import pandas as pd

scores = [['Tom', 85], ['Dick', 30], ['Harry', 60], ['Sally', 80], ['Jimmy', 70], ['Raj', 50]]
scores_df = pd.DataFrame(scores, columns=['Name', 'Score'])

source = ColumnDataSource(scores_df)

fig = figure(title='my chart', plot_width=300, plot_height=300, y_range=(0,100), x_axis_label='Name', y_axis_label='Score')
fig.vbar(x='Name', top='Score', bottom=0, source=source, width=1, color='black')

output_notebook()
show(fig)

And this is the output I get:

Please help me understand what i'm missing here?

Body:
I believe Bokeh needs an x-range defined in some cases with vBar (especially when categoricals are strings), correct me if I'm wrong!

By adding x_range=scores_df['Name'] to the figure;

fig = figure(title='my chart', plot_width=300, plot_height=300, y_range=(0,100), x_axis_label='Name', y_axis_label='Score', x_range=scores_df['Name'])

The bar chart is plotted
my chart


问:
Prevent users from changing amount charged on payment page
I am trying to integrate payment gateway on my website.  There are three courses each having different prices. I am passing the value of the amount and package to form.php and i have made the input fields to readonly but the user can still change the amount in inspect element and make it 0 and pass on the value and get the course for free. How can i stop user from changing the value? or is there any other way to pass the value? or encrypt it and then decrypt it again?

here is my code index.php

```<code><div id="outer">
        <div class="box">
            <h4>Rs. 9,900/-</h4>
            <ul>
                <li>2-Days Classroom Training</li>
                <li>E-Learning Course</li>
            </ul>
            <form action="form.php" method="post">
                <input type="hidden" name="amount" value="9900" readonly="readonly">
                <input type="hidden" name="package" value="basic" readonly="readonly">
                <input type="submit" name="BUY NOW" value="BUY NOW">
            </form>
        </div>
        <div class="box">
            <h4>Rs. 11,900/-</h4>
            <ul>
                <li>4-Days Classroom Training</li>
                <li>E-Learning Course</li>
            </ul>
            <form action="form.php" method="post">
                <input type="hidden" name="amount" value="11900" readonly="readonly">
                <input type="hidden" name="package" value="standard" readonly="readonly">
                <input type="submit" name="BUY NOW" value="BUY NOW">
            </form>
        </div>
        <div class="box">
            <h4>Rs. 14,900/-</h4>
            <ul>
                <li>4-Days Classroom Training</li>
                <li>E-Learning Course</li>
                <li>5 Hours Personal Session With The Trainer</li>
            </ul>
            <form action="form.php" method="post">
                <input type="hidden" name="amount" value="14900" readonly="readonly">
                <input type="hidden" name="package" value="pro" readonly="readonly">
                <input type="submit" name="BUY NOW" value="BUY NOW">
            </form>
        </div>
    </div>
</code>```

form.php

```<code><body>
    <?php
        if (isset($_POST['amount']) && isset($_POST['package'])) {
            $amount = $_POST['amount'];
            $package = $_POST['package'];
        }
    ?>

<div>
<table>
    <form name="postForm" action="form_process.php" method="POST" >
    <tr><td>txnid</td><td><input type="text" name="txnid" readonly="readonly" value="<?php echo $txnid=time().rand(1000,99999); ?>" /></td></tr>
    <tr><td>amount</td><td><input type="text" name="amount" readonly="readonly" value="<?php echo $amount; ?>" /></td></tr>
    <tr><td>firstname</td><td><input type="text" name="firstname" value="" /></td></tr>
    <tr><td>email</td><td><input type="text" name="email" value="" /></td></tr>
    <tr><td>phone</td><td><input type="text" name="phone" value="" /></td></tr>
    <tr><td>Package</td><td><input type="text" name="productinfo" readonly="readonly" value="<?php echo $package; ?>"/></td></tr>
    <tr><td colspan="3"><input type="hidden" name="service_provider" value="payu_paisa" size="64" /></td></tr>
    <tr><td><input type="hidden" name="surl" value="http://localhost/payment/success.php" size="64" readonly="readonly" /></td></tr>
    <tr><td><input type="hidden" name="furl" value="http://localhost/payment/failure.php" size="64" readonly="readonly" /></td></tr>
    <tr><td><input type="submit" /></td><td><input type="reset" /></td></tr>
    </form>
</table>
</div>
</body>
</code>```

form_process.php

```<code><script>
    function submitForm() {
      var postForm = document.forms.postForm;
      postForm.submit();
    }
</script>
</head>
<?php
if(!isset($_POST['firstname'])){header("location: form.php");}
// Change the Merchant key here as provided by Payumoney
$MERCHANT_KEY = "*******";

// Change the Merchant Salt as provided by Payumoney
$SALT = "********";

    $firstname =$_POST['firstname'];
    $email =$_POST['email'];
    $phone =$_POST['phone'];
    $productinfo =$_POST['productinfo'];
    $service_provider =$_POST['service_provider'];
    $amount =$_POST['amount'];
    $txnid =$_POST['txnid'];
    $productinfo =$_POST['productinfo'];
    $surl =$_POST['surl'];
    $furl =$_POST['furl'];

    //$ =$_POST[''];

    $hashseq=$MERCHANT_KEY.'|'.$txnid.'|'.$amount.'|'.$productinfo.'|'.$firstname.'|'.$email.'|||||||||||'.$SALT;
    $hash =strtolower(hash("sha512", $hashseq));

?>

<body onload="submitForm();">

<div>
<h2>Payment Gateway Testing Sample</h2>
<table>
<tr><td>Transaction Id</td><td><strong><?php echo $_POST['txnid']; ?></strong></td><td>Amount: </td><td><strong>Rs. <?php echo $_POST['amount']; ?></strong></td>
</table>
<div >
<p>In this page we will genrate hash and send it to payumoney.</p>
<br>
<p>Please be patient. this process might take some time,<br />please do not hit refresh or browser back button or close this window</p>
</div>
</div>

<div>
    <form name="postForm" action="https://sandboxsecure.payu.in/_payment" method="POST" >
        <input type="hidden" name="key" value="<?php echo $MERCHANT_KEY; ?>" />
        <input type="hidden" name="hash" value="<?php echo $hash;  ?>"/>
        <input type="hidden" name="txnid" value="<?php echo $_POST['txnid'];  ?>" />
        <input type="hidden" name="amount" value="<?php echo $_POST['amount'];  ?>" />
        <input type="hidden" name="firstname" value="<?php echo $_POST['firstname'];  ?>" />
        <input type="hidden" name="email" value="<?php echo $_POST['email'];  ?>" />
        <input type="hidden" name="phone" value="<?php echo $_POST['phone'];  ?>" />
        <input type="hidden" name="productinfo" value="<?php echo $_POST['productinfo'];  ?>" />
        <input type="hidden" name="service_provider" value="payu_paisa" size="64" />
        <input type="hidden" name="surl" value="<?php echo $_POST['surl'];  ?>" />
        <input type="hidden" name="furl" value="<?php echo $_POST['furl'];  ?>" />
    </form>
</div>
</body>
</code>```

success.php

```<code><body>
    <script>var time = 5;
setInterval(function() {
  var seconds = time % 60;
  var minutes = (time - seconds) / 60;
  if (seconds.toString().length == 1) {
    seconds = "0" + seconds;
  }
  if (minutes.toString().length == 1) {
    minutes = "0" + minutes;
  }
  document.getElementById("time").innerHTML = minutes + ":" + seconds;
  time--;
  if (time == 0) {
    window.location.href = "index.php";
  }
}, 1000);
</script>

    <div>
        <h2>Payment Success</h2>
    </div>

    <div>
        <?php
            if(isset($_POST['status'])){
                if($_POST['status']=="success"){
                    echo "<p>Payment Done Successfully.<br>Details Are Below.</p>";
                    echo "<p>Txn Id: ".$_POST['txnid']."</p>";
                    echo "<p>Name: ".$_POST['firstname']."</p>";
                    echo "<p>Email: ".$_POST['email']."</p>";
                    echo "<p>Amount: ".$_POST['amount']."</p>";
                    echo "<p>Phone No: ".$_POST['phone']."</p>";
                    echo "<p>Product Info: ".$_POST['productinfo']."</p>";
                    echo "<p>encryptedPaymentId: ".$_POST['encryptedPaymentId']."</p>";
                }
            }

            ?>
    </div>
    <div>Redirecting to home page in <span id="time"></span></div>
</code>```

答:
Never let the user send the price. Each course has an ID. Let's assume this:

course 1, has ID = 1, price = 499, name = 2-Days Classroom Training

course 2, has ID = 2, price = 999, name = 4-Days Classroom Training

On your payment page, inside <forms> send only course_id = X.

On the PHP script which receives the request you know that course_id = X has price = Y... This is the price you will charge.

```<code>// index.php
<form action="form.php" method="post">
    <input type="hidden" name="course_id" value="1" readonly="readonly">
    <label>
        2-days learning course
    </label>
    <input type="submit" name="BUY NOW" value="BUY NOW">
</form>

//form.php
if (isset($_POST['course_id']){
   if ($_POST['course_id'] == 1){
       $amount = 499;
   }
} else {
    echo 'invalid request'; exit();
}
</code>```

Body:
I am trying to integrate payment gateway on my website.  There are three courses each having different prices. I am passing the value of the amount and package to form.php and i have made the input fields to readonly but the user can still change the amount in inspect element and make it 0 and pass on the value and get the course for free. How can i stop user from changing the value? or is there any other way to pass the value? or encrypt it and then decrypt it again?

here is my code index.php

Rs. 9,900/-

2-Days Classroom Training

E-Learning Course

            <form action="form.php" method="post">
                <input type="hidden" name="amount" value="9900" readonly="readonly">
                <input type="hidden" name="package" value="basic" readonly="readonly">
                <input type="submit" name="BUY NOW" value="BUY NOW">
            </form>

Rs. 11,900/-

4-Days Classroom Training

E-Learning Course

            <form action="form.php" method="post">
                <input type="hidden" name="amount" value="11900" readonly="readonly">
                <input type="hidden" name="package" value="standard" readonly="readonly">
                <input type="submit" name="BUY NOW" value="BUY NOW">
            </form>

Rs. 14,900/-

4-Days Classroom Training

E-Learning Course

5 Hours Personal Session With The Trainer

            <form action="form.php" method="post">
                <input type="hidden" name="amount" value="14900" readonly="readonly">
                <input type="hidden" name="package" value="pro" readonly="readonly">
                <input type="submit" name="BUY NOW" value="BUY NOW">
            </form>

form.php

    <?php
        if (isset($_POST['amount']) && isset($_POST['package'])) {
            $amount = $_POST['amount'];
            $package = $_POST['package'];
        }
    ?>

    <form name="postForm" action="form_process.php" method="POST" >

txnid	<input type="text" name="txnid" readonly="readonly" value="<?php echo $txnid=time().rand(1000,99999); ?>" />

amount	<input type="text" name="amount" readonly="readonly" value="<?php echo $amount; ?>" />

firstname	<input type="text" name="firstname" value="" />

email	<input type="text" name="email" value="" />

phone	<input type="text" name="phone" value="" />

Package	<input type="text" name="productinfo" readonly="readonly" value="<?php echo $package; ?>"/>

<input type="hidden" name="service_provider" value="payu_paisa" size="64" />

<input type="hidden" name="surl" value="http://localhost/payment/success.php" size="64" readonly="readonly" />

<input type="hidden" name="furl" value="http://localhost/payment/failure.php" size="64" readonly="readonly" />

<input type="submit" />	<input type="reset" />

    </form>

form_process.php

<?php
if(!isset($_POST['firstname'])){header("location: form.php");}
// Change the Merchant key here as provided by Payumoney
$MERCHANT_KEY = "*******";

// Change the Merchant Salt as provided by Payumoney
$SALT = "********";

    $firstname =$_POST['firstname'];
    $email =$_POST['email'];
    $phone =$_POST['phone'];
    $productinfo =$_POST['productinfo'];
    $service_provider =$_POST['service_provider'];
    $amount =$_POST['amount'];
    $txnid =$_POST['txnid'];
    $productinfo =$_POST['productinfo'];
    $surl =$_POST['surl'];
    $furl =$_POST['furl'];

    //$ =$_POST[''];

    $hashseq=$MERCHANT_KEY.'|'.$txnid.'|'.$amount.'|'.$productinfo.'|'.$firstname.'|'.$email.'|||||||||||'.$SALT;
    $hash =strtolower(hash("sha512", $hashseq));

?>

Payment Gateway Testing Sample

Transaction Id	<?php echo $_POST['txnid']; ?>	Amount: 	Rs. <?php echo $_POST['amount']; ?>

In this page we will genrate hash and send it to payumoney.

Please be patient. this process might take some time,
please do not hit refresh or browser back button or close this window

    <form name="postForm" action="https://sandboxsecure.payu.in/_payment" method="POST" >
        <input type="hidden" name="key" value="<?php echo $MERCHANT_KEY; ?>" />
        <input type="hidden" name="hash" value="<?php echo $hash;  ?>"/>
        <input type="hidden" name="txnid" value="<?php echo $_POST['txnid'];  ?>" />
        <input type="hidden" name="amount" value="<?php echo $_POST['amount'];  ?>" />
        <input type="hidden" name="firstname" value="<?php echo $_POST['firstname'];  ?>" />
        <input type="hidden" name="email" value="<?php echo $_POST['email'];  ?>" />
        <input type="hidden" name="phone" value="<?php echo $_POST['phone'];  ?>" />
        <input type="hidden" name="productinfo" value="<?php echo $_POST['productinfo'];  ?>" />
        <input type="hidden" name="service_provider" value="payu_paisa" size="64" />
        <input type="hidden" name="surl" value="<?php echo $_POST['surl'];  ?>" />
        <input type="hidden" name="furl" value="<?php echo $_POST['furl'];  ?>" />
    </form>

success.php

Payment Success

        <?php
            if(isset($_POST['status'])){
                if($_POST['status']=="success"){
                    echo "
Payment Done Successfully.
Details Are Below.
";
                    echo "
Txn Id: ".$_POST['txnid']."
";
                    echo "
Name: ".$_POST['firstname']."
";
                    echo "
Email: ".$_POST['email']."
";
                    echo "
Amount: ".$_POST['amount']."
";
                    echo "
Phone No: ".$_POST['phone']."
";
                    echo "
Product Info: ".$_POST['productinfo']."
";
                    echo "
encryptedPaymentId: ".$_POST['encryptedPaymentId']."
";
                }
            }

            ?>

Redirecting to home page in

Body:
Never let the user send the price. Each course has an ID. Let's assume this:

course 1, has ID = 1, price = 499, name = 2-Days Classroom Training

course 2, has ID = 2, price = 999, name = 4-Days Classroom Training

On your payment page, inside <forms> send only course_id = X.

On the PHP script which receives the request you know that course_id = X has price = Y... This is the price you will charge.

// index.php
<form action="form.php" method="post">
    <input type="hidden" name="course_id" value="1" readonly="readonly">
    <label>
        2-days learning course
    </label>
    <input type="submit" name="BUY NOW" value="BUY NOW">
</form>

//form.php
if (isset($_POST['course_id']){
   if ($_POST['course_id'] == 1){
       $amount = 499;
   }
} else {
    echo 'invalid request'; exit();
}