问:
Meteor user accounts issue - Duplicate account being created with OAuth service (accounts-google)
I am working with Meteor User accounts to create users. I have implemented two ways of creating users.

By using accounts-password to create (default one ).

OAuth Services (accounts-google and accounts-facebook)

A user account generated with accounts-password have the document shown below

```<code>{
  "_id": "DQnDpEag2kPevSdJY",
  "createdAt": "2015-12-10T22:34:17.610Z",
  "services": {
    "password": {
      "bcrypt": "XXX"
    },
    "resume": {
      "loginTokens": [
        {
          "when": "2015-12-10T22:34:17.615Z",
          "hashedToken": "XXX"
        }
      ]
    }
  },
 -----
----
}
</code>```

Where as a user account generated with accounts-google or account-facebook have the document shown below.

```<code>{
  "_id": "Ap85ac4r6Xe3paeAh",
  "createdAt": "2015-12-10T22:29:46.854Z",
  "services": {
    "facebook": {
      "accessToken": "XXX",
      "expiresAt": 1454970581716,
      "id": "XXX",
      "email": "myname@gmail.com",
      "name": "Ada Lovelace",
      "first_name": "Ada",
      "last_name": "Lovelace",
      "link": "https://www.facebook.com/app_scoped_user_id/XXX/",
      "gender": "female",
      "locale": "en_US",
      "age_range": {
        "min": 21
      }
    },
---
---
---
</code>```

Now the real issue is, Although the email address used is same for both accounts-password and accounts-google (in my case email is myname@gmail.com), two different user accounts are being created.

I am looking for solution Something like below. (Note: Services has both "Password" and "Facebook" sections under single account)

```<code>{
  "_id": "DQnDpEag2kPevSdJY",
  "createdAt": "2015-12-10T22:34:17.610Z",
  "services": {
    "password": {
      "bcrypt": "XXX"
    },
    "facebook": {
      "accessToken": "XXX",
      "expiresAt": 1454970581716,
      "id": "XXX",
      "email": "myname@gmail.com",
      "name": "Ada Lovelace",
      "first_name": "Ada",
      "last_name": "Lovelace",
      "link": "https://www.facebook.com/app_scoped_user_id/XXX/",
      "gender": "female",
      "locale": "en_US",
      "age_range": {
        "min": 21
      }
    },
  },
 -----
----
}
</code>```

Is there a way where only one account is being generated in both cases, means if a user is already existed and the same is trying with OAuth service, first account should be used to accommodate the service ?

答:
You can use Accounts.setPassword on the server in order to generate a proper bcrypt hash for the accounts:

Accounts.setPassword('Ap85ac4r6Xe3paeAh', 'the-new-password')
```

<p>which will result in</p>

```{
  "_id": "Ap85ac4r6Xe3paeAh",
  "createdAt": "2015-12-10T22:29:46.854Z",
  "services": {
    "password": {
      "bcrypt": "$2b$10$nzHCivxVqxbuFBBPWewPPu.r5x7OR5gJB8PIklU4OoU.WK0MT8jt2"
    },
    "facebook": {
      "accessToken": "XXX",
      "expiresAt": 1454970581716,
      "id": "XXX",
      "email": "myname@gmail.com",
      "name": "Ada Lovelace",
      "first_name": "Ada",
      "last_name": "Lovelace",
      "link": "https://www.facebook.com/app_scoped_user_id/XXX/",
      "gender": "female",
      "locale": "en_US",
      "age_range": {
        "min": 21
      }
    }
  }
}
```

Body:
I am working with Meteor User accounts to create users. I have implemented two ways of creating users.

By using accounts-password to create (default one ).

OAuth Services (accounts-google and accounts-facebook)

A user account generated with accounts-password have the document shown below

{
  "_id": "DQnDpEag2kPevSdJY",
  "createdAt": "2015-12-10T22:34:17.610Z",
  "services": {
    "password": {
      "bcrypt": "XXX"
    },
    "resume": {
      "loginTokens": [
        {
          "when": "2015-12-10T22:34:17.615Z",
          "hashedToken": "XXX"
        }
      ]
    }
  },
 -----
----
}

Where as a user account generated with accounts-google or account-facebook have the document shown below.

{
  "_id": "Ap85ac4r6Xe3paeAh",
  "createdAt": "2015-12-10T22:29:46.854Z",
  "services": {
    "facebook": {
      "accessToken": "XXX",
      "expiresAt": 1454970581716,
      "id": "XXX",
      "email": "myname@gmail.com",
      "name": "Ada Lovelace",
      "first_name": "Ada",
      "last_name": "Lovelace",
      "link": "https://www.facebook.com/app_scoped_user_id/XXX/",
      "gender": "female",
      "locale": "en_US",
      "age_range": {
        "min": 21
      }
    },
---
---
---

Now the real issue is, Although the email address used is same for both accounts-password and accounts-google (in my case email is myname@gmail.com), two different user accounts are being created.

I am looking for solution Something like below. (Note: Services has both "Password" and "Facebook" sections under single account)

{
  "_id": "DQnDpEag2kPevSdJY",
  "createdAt": "2015-12-10T22:34:17.610Z",
  "services": {
    "password": {
      "bcrypt": "XXX"
    },
    "facebook": {
      "accessToken": "XXX",
      "expiresAt": 1454970581716,
      "id": "XXX",
      "email": "myname@gmail.com",
      "name": "Ada Lovelace",
      "first_name": "Ada",
      "last_name": "Lovelace",
      "link": "https://www.facebook.com/app_scoped_user_id/XXX/",
      "gender": "female",
      "locale": "en_US",
      "age_range": {
        "min": 21
      }
    },
  },
 -----
----
}

Is there a way where only one account is being generated in both cases, means if a user is already existed and the same is trying with OAuth service, first account should be used to accommodate the service ?

Body:
You can use Accounts.setPassword on the server in order to generate a proper bcrypt hash for the accounts:

Accounts.setPassword('Ap85ac4r6Xe3paeAh', 'the-new-password')

which will result in

{
  "_id": "Ap85ac4r6Xe3paeAh",
  "createdAt": "2015-12-10T22:29:46.854Z",
  "services": {
    "password": {
      "bcrypt": "$2b$10$nzHCivxVqxbuFBBPWewPPu.r5x7OR5gJB8PIklU4OoU.WK0MT8jt2"
    },
    "facebook": {
      "accessToken": "XXX",
      "expiresAt": 1454970581716,
      "id": "XXX",
      "email": "myname@gmail.com",
      "name": "Ada Lovelace",
      "first_name": "Ada",
      "last_name": "Lovelace",
      "link": "https://www.facebook.com/app_scoped_user_id/XXX/",
      "gender": "female",
      "locale": "en_US",
      "age_range": {
        "min": 21
      }
    }
  }
}


来源: stackexchange

问:
How do I create links in Django such that other users can't access them?
I'm pretty confused about how do I prevent users' from accessing the data of other users.

The case at hand :

I'm creating a Notes + To-Do app in which a user logs in, creates their notes and tasks.

How to create links to those notes such that they aren't accessible by other users? As in the correct syntax for UserPassesTestMixin.

In the To-Do app, how do I keep the tasks of one user unique to them? Similarly for the note app, how do I achieve that?

答:
You can use the decorator in Django called "user_passes_test"

You can import like:

```<code>from django.contrib.auth.decorators import user_passes_test
</code>```

For detail check docs here

ContentLicense: CC BY-SA 4.0

Body:
You can use the decorator in Django called "user_passes_test"

You can import like:

from django.contrib.auth.decorators import user_passes_test

For detail check docs here


问:
numpy not-equally distant range of numbers
Using np.linspace(0,3,100) would give a range of numbers that are equally distant between 0 and 3. what's the best way to get a range of numbers between 0 and 3 but more densely close to 3 and less dense in the beginning, perhaps in a logarithmic way.

----------edit

(np.log10(1), np.log10(4), 100)-1 gives more dense samples close to 0 than 3.

In addition is there also a more mathematically explicit way?

------edit:

This is the best I myself could come up with:
s = -1*(3*10**(-np.linspace(0,4,25))-1)

答:
A slight improvement over np.logspace is np.geomspace, which is more convenient since endpoints can be specified directly. rpoleski's answer then becomes

```<code>4 - np.geomspace(1, 4, 25)[::-1]
</code>```

Body:
A slight improvement over np.logspace is np.geomspace, which is more convenient since endpoints can be specified directly. rpoleski's answer then becomes

4 - np.geomspace(1, 4, 25)[::-1]


问:
Remove countries' political borders from ggplot2 map
I need to remove the political borders of the countries from the following ggplot2 map:

```<code>library(ggplot2)

world = map_data('world')

plot=ggplot() +
geom_polygon(data=world, aes(x=long, y=lat, group=group), fill='NA', color='black', size=0.2)

print(plot)
</code>```

Any suggestion on how I can do this?
Thanks

答:
There are two workarounds to your question:

First workaround: Using maps instead of ggplot2

```<code>library(maps)
world <- maps::map("world", fill=FALSE, plot=TRUE, interior = FALSE)
</code>```

Which results in:

Second workaround: Using maps and ggplot2

```<code>library(maps)
library(magrittr)
library(maptools)
library(raster)
library(ggplot2)

#Defining a general CRS
mycrs <- "+proj=longlat +datum=WGS84 +no_defs"

#Using the original maps package, then converting map into SpatialPolygons object
world <- maps::map("world", fill=TRUE) %$%
  maptools::map2SpatialPolygons(., IDs=names,proj4string=CRS(mycrs))

#The resulting map has self intersection problems so any further operation reports errors; using buffers of width 0 is a fast fix
while(rgeos::gIsValid(world)==FALSE){
  world <- rgeos::gBuffer(world, byid = TRUE, width = 0, quadsegs = 5, capStyle = "ROUND")
}

#Dissolving polygon's limits
world <- raster::aggregate(world)

#Plotting. I add theme_void to your code to erase any axis, etc
ggplot() +
  geom_polygon(data = world, aes(x=long, y=lat, group=group), fill='NA', color='black', size=0.2)+
  theme_void()
</code>```

The result:

Hope it helps

Body:
I need to remove the political borders of the countries from the following ggplot2 map:

library(ggplot2)

world = map_data('world')

plot=ggplot() +
geom_polygon(data=world, aes(x=long, y=lat, group=group), fill='NA', color='black', size=0.2)

print(plot)

Any suggestion on how I can do this?
Thanks

Body:
There are two workarounds to your question:

First workaround: Using maps instead of ggplot2

library(maps)
world <- maps::map("world", fill=FALSE, plot=TRUE, interior = FALSE)

Which results in:

Second workaround: Using maps and ggplot2

library(maps)
library(magrittr)
library(maptools)
library(raster)
library(ggplot2)

#Defining a general CRS
mycrs <- "+proj=longlat +datum=WGS84 +no_defs"

#Using the original maps package, then converting map into SpatialPolygons object
world <- maps::map("world", fill=TRUE) %$%
  maptools::map2SpatialPolygons(., IDs=names,proj4string=CRS(mycrs))

#The resulting map has self intersection problems so any further operation reports errors; using buffers of width 0 is a fast fix
while(rgeos::gIsValid(world)==FALSE){
  world <- rgeos::gBuffer(world, byid = TRUE, width = 0, quadsegs = 5, capStyle = "ROUND")
}

#Dissolving polygon's limits
world <- raster::aggregate(world)

#Plotting. I add theme_void to your code to erase any axis, etc
ggplot() +
  geom_polygon(data = world, aes(x=long, y=lat, group=group), fill='NA', color='black', size=0.2)+
  theme_void()

The result:

Hope it helps


问:
Multiple database drivers scenario: passing interface as type
Scenario: I've got a database type implementing a number of CRUD operations.

I would like to:

abstract away the database layer to support multiple databases

put a cache layer "in front of it" as read-through cache

So my idea was to:

create a database interface for both postgres specific code, and the cache

pass the postgres type to the cache constructor so it can use it to from the database

See below for what I tried, resulting in an error for cacheNew() when assigning :

cannot use dbdriver (variable of type interface{}) as database value in struct literal: missing method GetUser

What is the best way to solve this?

```<code>package main

import "fmt"

type database interface {
    GetUser(string)
}

type postgres struct {
    hostname string
}

func (p *postgres) GetUser(u string) {
    fmt.Printf("Postgres: GetUser %s\n", u)
}

type cache struct {
    db database
}

func cacheNew(dbdriver interface{}) cache {
    return cache{
        db: dbdriver,
    }
}

func (c *cache) GetUser(u string) {
    fmt.Printf("Cache: GetUser %s\n", u)

    c.db.GetUser(u)
}

func main() {
    // var db database

    db := postgres{
        hostname: "x",
    }
    db.GetUser("joe")

    dbViaCache := cacheNew(db)
    dbViaCache.GetUser("joe")
}
</code>```

答:
In order to solve your problem add newPostgres constructor. Below I made a correction of your initial code.</p>

```<code>package main

import "fmt"

type database interface {
    GetUser(string)
}

type postgres struct {
    hostname string
}

func newPostgres(hostname string) *postgres {
    return &postgres{
        hostname: hostname,
    }
}

func (p *postgres) GetUser(u string) {
    fmt.Printf("Postgres: GetUser %s\n", u)
}

type cache struct {
    db database
}

func cacheNew(db database) cache {
    return cache{
        db: db,
    }
}

func (c *cache) GetUser(u string) {
    fmt.Printf("Cache: GetUser %s\n", u)

    c.db.GetUser(u)
}

func main() {
    db := newPostgres("x")

    db.GetUser("joe")

    dbViaCache := cacheNew(db)
    dbViaCache.GetUser("joe")
}
</code>```

Body:
Scenario: I've got a database type implementing a number of CRUD operations.

I would like to:

abstract away the database layer to support multiple databases

put a cache layer "in front of it" as read-through cache

So my idea was to:

create a database interface for both postgres specific code, and the cache

pass the postgres type to the cache constructor so it can use it to from the database

See below for what I tried, resulting in an error for cacheNew() when assigning :

cannot use dbdriver (variable of type interface{}) as database value in struct literal: missing method GetUser

What is the best way to solve this?

package main

import "fmt"

type database interface {
    GetUser(string)
}

type postgres struct {
    hostname string
}

func (p *postgres) GetUser(u string) {
    fmt.Printf("Postgres: GetUser %s\n", u)
}

type cache struct {
    db database
}

func cacheNew(dbdriver interface{}) cache {
    return cache{
        db: dbdriver,
    }
}

func (c *cache) GetUser(u string) {
    fmt.Printf("Cache: GetUser %s\n", u)

    c.db.GetUser(u)
}

func main() {
    // var db database

    db := postgres{
        hostname: "x",
    }
    db.GetUser("joe")

    dbViaCache := cacheNew(db)
    dbViaCache.GetUser("joe")
}

Body:
In order to solve your problem add newPostgres constructor. Below I made a correction of your initial code.

package main

import "fmt"

type database interface {
    GetUser(string)
}

type postgres struct {
    hostname string
}

func newPostgres(hostname string) *postgres {
    return &postgres{
        hostname: hostname,
    }
}

func (p *postgres) GetUser(u string) {
    fmt.Printf("Postgres: GetUser %s\n", u)
}

type cache struct {
    db database
}

func cacheNew(db database) cache {
    return cache{
        db: db,
    }
}

func (c *cache) GetUser(u string) {
    fmt.Printf("Cache: GetUser %s\n", u)

    c.db.GetUser(u)
}

func main() {
    db := newPostgres("x")

    db.GetUser("joe")

    dbViaCache := cacheNew(db)
    dbViaCache.GetUser("joe")
}


问:
Why should I compare the balance with BigDecimal.ONE before a transaction in Java?
I'm looking at a tutorial about a financial transaction from an account to another and before transfering the amount from an account to another they do these 2 comparations:

```<code>fromAccount.getCurrentBalance().compareTo(BigDecimal.ONE) == 1
                && fromAccount.getCurrentBalance().compareTo(amount) == 1
</code>```

I understand that they do the second comparation to compare the balance with the amount, but what I don't understand is why they compare the balance with BigDecimal.ONE. Can somebody explain?

I don't understand for what is this comparation:

```<code>fromAccount.getCurrentBalance().compareTo(BigDecimal.ONE)
</code>```

This is the code:

```<code>if(fromAccount.getCurrentBalance().compareTo(BigDecimal.ONE) == 1
        && fromAccount.getCurrentBalance().compareTo(amount) == 1
){
    fromAccount.setCurrentBalance(fromAccount.getCurrentBalance().subtract(amount));
    accountRepository.save(fromAccount);
    toAccount.setCurrentBalance(toAccount.getCurrentBalance().add(amount));
    accountRepository.save(toAccount);
    Transaction transaction = transactionRepository.save(new Transaction(0L,fromAccountNumber,amount,new Timestamp(System.currentTimeMillis())));
    return transaction;
}
return null;
</code>```

答:
This is just a BigDecimal greater than conditional signature in java. if your CurrentBalance variable datatype is BigDecimal then you can't use the normal integer conditional signature like == or > or <. BigDecimal compareTo() method returns values to determine the equal, greater than and less than operations.

Big Decimal CompareTo() method returns

```<code>0 : if value of this BigDecimal is equal to that of BigDecimal object passed as parameter.
1 : if value of this BigDecimal is greater than that of BigDecimal object passed as parameter.
-1 : if value of this BigDecimal is less than that of BigDecimal object passed as parameter.
</code>```

If we consider this line

```<code>fromAccount.getCurrentBalance().compareTo(BigDecimal.ONE) == 1
</code>```

this line can simply means in an integer datatype

```<code>if(fromAccount.getCurrentBalance() > 1)
</code>```

If I convert both of your conditions in a normal integer datatype operation then it will looks like this.

```<code>if(fromAccount.getCurrentBalance() > 1 && fromAccount.getCurrentBalance() > amount)
</code>```

visit here to understand BigDecimal compareTo() operation.

https://www.geeksforgeeks.org/bigdecimal-compareto-function-in-java/

Body:
I'm looking at a tutorial about a financial transaction from an account to another and before transfering the amount from an account to another they do these 2 comparations:

fromAccount.getCurrentBalance().compareTo(BigDecimal.ONE) == 1
                && fromAccount.getCurrentBalance().compareTo(amount) == 1

I understand that they do the second comparation to compare the balance with the amount, but what I don't understand is why they compare the balance with BigDecimal.ONE. Can somebody explain?

I don't understand for what is this comparation:

fromAccount.getCurrentBalance().compareTo(BigDecimal.ONE)

This is the code:

if(fromAccount.getCurrentBalance().compareTo(BigDecimal.ONE) == 1
        && fromAccount.getCurrentBalance().compareTo(amount) == 1
){
    fromAccount.setCurrentBalance(fromAccount.getCurrentBalance().subtract(amount));
    accountRepository.save(fromAccount);
    toAccount.setCurrentBalance(toAccount.getCurrentBalance().add(amount));
    accountRepository.save(toAccount);
    Transaction transaction = transactionRepository.save(new Transaction(0L,fromAccountNumber,amount,new Timestamp(System.currentTimeMillis())));
    return transaction;
}
return null;

Body:
This is just a BigDecimal greater than conditional signature in java. if your CurrentBalance variable datatype is BigDecimal then you can't use the normal integer conditional signature like == or > or <. BigDecimal compareTo() method returns values to determine the equal, greater than and less than operations.

Big Decimal CompareTo() method returns

0 : if value of this BigDecimal is equal to that of BigDecimal object passed as parameter.
1 : if value of this BigDecimal is greater than that of BigDecimal object passed as parameter.
-1 : if value of this BigDecimal is less than that of BigDecimal object passed as parameter.

If we consider this line

fromAccount.getCurrentBalance().compareTo(BigDecimal.ONE) == 1

this line can simply means in an integer datatype

if(fromAccount.getCurrentBalance() > 1)

If I convert both of your conditions in a normal integer datatype operation then it will looks like this.

if(fromAccount.getCurrentBalance() > 1 && fromAccount.getCurrentBalance() > amount)

visit here to understand BigDecimal compareTo() operation.

https://www.geeksforgeeks.org/bigdecimal-compareto-function-in-java/


答:
In case you are using functions (FBV) you could use if request.user == item.user

```<code>@login_required
def post_edit(request, post_id):
  item = Post.objects.get(pk=post_id)
  if request.user == item.user:
</code>```

CBV - Class Based View - using UserPassesTestMixin

```<code>class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
# [...]
</code>```

Title: How do I create links in Django such that other users can't access them?

Body:
I'm pretty confused about how do I prevent users' from accessing the data of other users.

The case at hand :

I'm creating a Notes + To-Do app in which a user logs in, creates their notes and tasks.

How to create links to those notes such that they aren't accessible by other users? As in the correct syntax for UserPassesTestMixin.

In the To-Do app, how do I keep the tasks of one user unique to them? Similarly for the note app, how do I achieve that?

Body:
In case you are using functions (FBV) you could use if request.user == item.user

@login_required
def post_edit(request, post_id):
  item = Post.objects.get(pk=post_id)
  if request.user == item.user:

CBV - Class Based View - using UserPassesTestMixin

class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
# [...]


问:
How do I bypass undefined JavaScript errors when doing a web scrape with a HttpWebRequest
I am trying to do a HttpWebRequest to scrape a login page's HTML and post data to that web page's username and password controls to 'auto logon' the client essentially. The problem I am running into, is the URI I am using when parsed has JavaScript within and a XML .config file that is not getting downloaded and only available to the actual hosted site it appears.

When I read the response, execution breakes in VS.NET and I get a "Microsoft JScript Runtime error: 'VerticalMenuConfig is undefined"

Looking at the script tags where debugging has stopped I see the reference to "scripts/VerticalMenuConfig.xml".

If I hit continue, the page is all messed up when written to the response of my page, and I still unsuccessfully write to any of the input text boxes. I am using an example like the following that writes to the "Search" text box automatically on Amazon; it is exactly what I need to do: http://www.worldofasp.net/tut/WebRequest/Working_with_HttpWebRequest_and_HttpWebResponse_in_ASPNET_114.aspx

Here is the code that breaks:

```<code><script language="javascript" src="scripts/VerticalMenu.js"></script>
<script>
var vm = new VerticalMenu("tdVertMenu", "scripts/VerticalMenuConfig.xml", "");
vm.openSubMenu("clientLogin");
</code>```

It breaks on the line: var vm = new VerticalMenu...

Is there a better way to do this?

答:
It sounds like you have logged your webserver in to your client's account and are expecting to serve your client with html from that server.  That probably won't work.  Security, session tokens that the webserver has and not the user, relative urls in the scraped html (like your problem with the xml).

You could serve up an auto-submitting form pointed at the other web server - that form would have to contain the user's credentials in plain text!

```<code><form id='f' method='post' action='http://otherwebserver/login'>
<input type='hidden' name='username' value='me' />
<input type='hidden' name='password' value='my password' />
// any other fields that the login page expects
</form>
<script type='text/javascript'>
  document.getElementById('f').submit();
</script>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
It sounds like you have logged your webserver in to your client's account and are expecting to serve your client with html from that server.  That probably won't work.  Security, session tokens that the webserver has and not the user, relative urls in the scraped html (like your problem with the xml).

You could serve up an auto-submitting form pointed at the other web server - that form would have to contain the user's credentials in plain text!

<form id='f' method='post' action='http://otherwebserver/login'>
<input type='hidden' name='username' value='me' />
<input type='hidden' name='password' value='my password' />
// any other fields that the login page expects
</form>
<script type='text/javascript'>
  document.getElementById('f').submit();
</script>


问:
Is it possible to run two python scripts parallel and plotting real time?
I have two Python scripts: 1st is responsible for generating data and save them in .csv file and 2nd for plotting this data in real time. I have to run 1st script in console and then run 2nd script in new instance of console. I want to do all this things in one script but I can't do that. I tried to use mutliprocessing but I failed. I add my 2 scripts:

```<code>#THIS IS DATA GENERATING SCRIPT
import csv
import random
import time
import numpy as np

steps = 12000
shift = [-1, 0, 1]
start_corr_2D = [0, 0]
start_corr_3D = [0, 0, 0]

path_2D = np.zeros(shape=(steps,2))
path_3D = np.zeros(shape=(steps,3))

path_2D[0] = start_corr_2D
path_3D[0] = start_corr_3D

fieldnames = ["X", "Y"]

with open('data.csv', 'w') as csv_file:
    csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    csv_writer.writeheader()

    info = {
        "X": start_corr_2D[0],
        "Y": start_corr_2D[1],
        }

    csv_writer.writerow(info)

for i in range(1, steps):

    with open('data.csv', 'a') as csv_file:
        csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)

        shift_2D = [random.choice(shift), random.choice(shift)]
        shift_3D = [random.choice(shift), random.choice(shift), random.choice(shift)]

        next_corr_2D = list(map(sum, zip(start_corr_2D, shift_2D)))
        next_corr_3D = list(map(sum, zip(start_corr_3D, shift_3D)))
        print(next_corr_2D)

        path_2D[i] = next_corr_2D
        path_3D[i] = next_corr_3D

        start_corr_2D = next_corr_2D
        start_corr_3D = next_corr_3D

        info = {
        "X": next_corr_2D[0],
        "Y": next_corr_2D[1],
        }

        csv_writer.writerow(info)

    time.sleep(0.3)
</code>```

```<code>#THIS SCRIPT IS RESPONSIBLE FOR PLOTTING IN REAL TIME
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.animation import FuncAnimation

j = 0

def animate(i):
    data = pd.read_csv('data.csv')
    xs = data['X']
    ys = data['Y']

    global j
    j += 1
#    print(j)

    plt.cla()
#    plt.scatter(xs, ys, c='red', marker='*')

    if j < 10:
        plt.plot(xs, ys, c='blue', lw=0.6)
    elif j >= 10 and j < 50:
        plt.plot(xs, ys, c='red', lw=0.6)
    else:
        plt.plot(xs, ys, c='green', lw=0.6)

    plt.tight_layout()

ani = FuncAnimation(plt.gcf(), animate, interval=300)

plt.tight_layout()
plt.show()
</code>```

I am doing this operations right now:

But I want to get results from running only 1 script.
I would be grateful for any help.

答:
1.Use GNU parallel:

```<code> parallel -j -8 python ::: "$python_plot_scripts"
</code>```

2.You can draw multiple fig:
multiple_figs_demo

```<code>from matplotlib.path import Path
import matplotlib.patches as patches
</code>```

3.Use:
pyhdf

Body:
I have two Python scripts: 1st is responsible for generating data and save them in .csv file and 2nd for plotting this data in real time. I have to run 1st script in console and then run 2nd script in new instance of console. I want to do all this things in one script but I can't do that. I tried to use mutliprocessing but I failed. I add my 2 scripts:

#THIS IS DATA GENERATING SCRIPT
import csv
import random
import time
import numpy as np

steps = 12000
shift = [-1, 0, 1]
start_corr_2D = [0, 0]
start_corr_3D = [0, 0, 0]

path_2D = np.zeros(shape=(steps,2))
path_3D = np.zeros(shape=(steps,3))

path_2D[0] = start_corr_2D
path_3D[0] = start_corr_3D

fieldnames = ["X", "Y"]

with open('data.csv', 'w') as csv_file:
    csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    csv_writer.writeheader()

    info = {
        "X": start_corr_2D[0],
        "Y": start_corr_2D[1],
        }

    csv_writer.writerow(info)

for i in range(1, steps):

    with open('data.csv', 'a') as csv_file:
        csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)

        shift_2D = [random.choice(shift), random.choice(shift)]
        shift_3D = [random.choice(shift), random.choice(shift), random.choice(shift)]

        next_corr_2D = list(map(sum, zip(start_corr_2D, shift_2D)))
        next_corr_3D = list(map(sum, zip(start_corr_3D, shift_3D)))
        print(next_corr_2D)

        path_2D[i] = next_corr_2D
        path_3D[i] = next_corr_3D

        start_corr_2D = next_corr_2D
        start_corr_3D = next_corr_3D

        info = {
        "X": next_corr_2D[0],
        "Y": next_corr_2D[1],
        }

        csv_writer.writerow(info)

    time.sleep(0.3)

#THIS SCRIPT IS RESPONSIBLE FOR PLOTTING IN REAL TIME
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.animation import FuncAnimation

j = 0

def animate(i):
    data = pd.read_csv('data.csv')
    xs = data['X']
    ys = data['Y']

    global j
    j += 1
#    print(j)

    plt.cla()
#    plt.scatter(xs, ys, c='red', marker='*')

    if j < 10:
        plt.plot(xs, ys, c='blue', lw=0.6)
    elif j >= 10 and j < 50:
        plt.plot(xs, ys, c='red', lw=0.6)
    else:
        plt.plot(xs, ys, c='green', lw=0.6)

    plt.tight_layout()

ani = FuncAnimation(plt.gcf(), animate, interval=300)

plt.tight_layout()
plt.show()

I am doing this operations right now:

But I want to get results from running only 1 script.
I would be grateful for any help.

Body:
1.Use GNU parallel:

 parallel -j -8 python ::: "$python_plot_scripts"

2.You can draw multiple fig:
multiple_figs_demo

from matplotlib.path import Path
import matplotlib.patches as patches

3.Use:
pyhdf


问:
Automatically generate .factorypath on project import when using Maven project in Eclipse IDE
The .factorypath file is a generated file, which eclipse requires for annotation-processing. The m2eclipse plugin does generate this file when using "Update Maven Project" (Alt+F5) and checking "Update project configuration from pom.xml".

However, I don't want to check this file into version control. But if not, and someone from the team does a fresh checkout, and imports the project in eclipse, the .factorypath does not get generated until the  "Update Maven Project" is performed manually. I don't want this manual step when a project gets imported, this has to happen automatically. Is there an option, that a project has to be updated upon import?

答:
Since this is an IDE related question, and you seem to be using Eclipse IDE:

Menu Window > Preferences > Maven > Automatically update Maven projects configuration .

This will make it for you on project import so you would not need that manual step anymore.


问:
Throttle HTTP request in Java Servlet
In a java servlet, how can I throttle http requests coming from users based on the client's IP address?  I do not want to serve more than X requests per second coming from a particular source IP address where X is configurable and having practical values in [0.1; 10] range (from 1 request in 10 sec to 10 requests per sec).</p>

答:
Check if the container you are using provides this kind of Denial Of Service. If no, then you would have to go with a filter.

ServletRequest.getRemoteHost() gives you access to the client IP.

Title: Throttle HTTP request in Java Servlet


问:
Next.js - _app.js state is lost on page refresh / SSR
Not sure if this is a feature or a side-effect of rendering server side but any state stored in the exposed _app.js page is lost whenever I either refresh page or visit page directly from url input.
Next.js proclaim the _app.js page is for "Keeping state when navigating pages", so this should work.

All state is kept when routing client side with the <Link> component.

I'm trying to store non-sensitive data without using cookie/session/local storage.

Can anyone validate if this is the best approach or should I just be using one of these techniques?

Happy to post code if necessary.

答:
I was in the same situation as you. So I wrote a boilerplate example of this. Go visit the example and the code to implement this in your app. https://github.com/fazlulkarimweb/with-next-redux-wrapper-redux-persist

There are no official examples from the Next community for this for now. I think people who are trying to find a solution will be helped by the boilerplate.


问:
C# Generic method for random number generation
I see that there is a similar question for C++. Does anyone know why this method works when the method is non-generic, but as soon as I make it generic, the random number portion of code fails?
Error: Cannot implicitly convert type int to 'T'. If I can't use generics, I will have to rewrite the same function over and over for each different length of array. </p>

```<code>public void fillGenericArray<T>(T[] inputArray) where T : IComparable
{
    var randomNumb1 = new Random();

    for (int i = 0; i < inputArray.Length - 1; i++)
    {
        Console.WriteLine($"{inputArray[i] = randomNumb1.Next(1, 501)},");
    }
}
</code>```

答:
I had to look twice at this, but here's the issue:

Because inputArray is an 'array of type T'

then even though i is an int the expression

```<code>inputArray[i]
</code>```

returns a type T not a type int.

And so, conversely, a type T must be assigned to it.

A generic method like this might achieve your goal:

```<code>public static void fillGenericArray<T>(T[] inputArray)
{
    for (int i = 0; i < inputArray.Length; i++)
    {
        // Where T has a CTor that takes an int as an argument
        inputArray[i] = (T)Activator.CreateInstance(typeof(T), Random.Next(1, 501));
    }
}
</code>```

(Thanks to this SO post for refreshing my memory about instantiating T with arguments.)

You could also use Enumerable.Range() to get the same result without writing a method at all:

```<code>// Generically, for any 'SomeClass' with a CTor(int value)
SomeClass[] arrayOfT =
    Enumerable.Range(1, LENGTH).Select(i => new SomeClass(Random.Next(1, 501)))
    .ToArray();
</code>```

(Slightly Modified with help from this SO post) - see the answer using Enumerable.Range().

Here is a test runner:

```<code>class Program
{
    static Random Random { get; } = new Random();
    const int LENGTH = 10;
    static void Main(string[] args)
    {

        Console.WriteLine();
        Console.WriteLine("With a generic you could do this...");

        SomeClass[] arrayOfT;
        arrayOfT = new SomeClass[LENGTH];
        fillGenericArray<SomeClass>(arrayOfT);
        Console.WriteLine(string.Join(Environment.NewLine, arrayOfT.Select(field=>field.Value)));

        Console.WriteLine();
        Console.WriteLine("But perhaps it's redundant, because Enumerable is already Generic!");

        arrayOfT = Enumerable.Range(1, LENGTH).Select(i => new SomeClass(Random.Next(1, 501))).ToArray();
        Console.WriteLine(string.Join(Environment.NewLine, arrayOfT.Select(field => field.Value)));

        // Pause
        Console.WriteLine(Environment.NewLine + "Any key to exit");
        Console.ReadKey();
    }
    public static void fillGenericArray<T>(T[] inputArray)
    {
        for (int i = 0; i < inputArray.Length; i++)
        {
            inputArray[i] = (T)Activator.CreateInstance(typeof(T), Random.Next(1, 501));
        }
    }
    class SomeClass
    {
        public SomeClass(int value)
        {
            Value = value;
        }
        public int Value { get; set; }
    }
}
</code>```

Clone or Download this example from GitHub.

Body:
I see that there is a similar question for C++. Does anyone know why this method works when the method is non-generic, but as soon as I make it generic, the random number portion of code fails?
Error: Cannot implicitly convert type int to 'T'. If I can't use generics, I will have to rewrite the same function over and over for each different length of array.

public void fillGenericArray<T>(T[] inputArray) where T : IComparable
{
    var randomNumb1 = new Random();

    for (int i = 0; i < inputArray.Length - 1; i++)
    {
        Console.WriteLine($"{inputArray[i] = randomNumb1.Next(1, 501)},");
    }
}

Body:
I had to look twice at this, but here's the issue:

Because inputArray is an 'array of type T'

then even though i is an int the expression

inputArray[i]

returns a type T not a type int.

And so, conversely, a type T must be assigned to it.

A generic method like this might achieve your goal:

public static void fillGenericArray<T>(T[] inputArray)
{
    for (int i = 0; i < inputArray.Length; i++)
    {
        // Where T has a CTor that takes an int as an argument
        inputArray[i] = (T)Activator.CreateInstance(typeof(T), Random.Next(1, 501));
    }
}

(Thanks to this SO post for refreshing my memory about instantiating T with arguments.)

You could also use Enumerable.Range() to get the same result without writing a method at all:

// Generically, for any 'SomeClass' with a CTor(int value)
SomeClass[] arrayOfT =
    Enumerable.Range(1, LENGTH).Select(i => new SomeClass(Random.Next(1, 501)))
    .ToArray();

(Slightly Modified with help from this SO post) - see the answer using Enumerable.Range().

Here is a test runner:

class Program
{
    static Random Random { get; } = new Random();
    const int LENGTH = 10;
    static void Main(string[] args)
    {

        Console.WriteLine();
        Console.WriteLine("With a generic you could do this...");

        SomeClass[] arrayOfT;
        arrayOfT = new SomeClass[LENGTH];
        fillGenericArray<SomeClass>(arrayOfT);
        Console.WriteLine(string.Join(Environment.NewLine, arrayOfT.Select(field=>field.Value)));

        Console.WriteLine();
        Console.WriteLine("But perhaps it's redundant, because Enumerable is already Generic!");

        arrayOfT = Enumerable.Range(1, LENGTH).Select(i => new SomeClass(Random.Next(1, 501))).ToArray();
        Console.WriteLine(string.Join(Environment.NewLine, arrayOfT.Select(field => field.Value)));

        // Pause
        Console.WriteLine(Environment.NewLine + "Any key to exit");
        Console.ReadKey();
    }
    public static void fillGenericArray<T>(T[] inputArray)
    {
        for (int i = 0; i < inputArray.Length; i++)
        {
            inputArray[i] = (T)Activator.CreateInstance(typeof(T), Random.Next(1, 501));
        }
    }
    class SomeClass
    {
        public SomeClass(int value)
        {
            Value = value;
        }
        public int Value { get; set; }
    }
}

Clone or Download this example from GitHub.


问:
Laravel Carbon differents between two dates
I have weekly discounts on the product on my site, when buying, the user is written how much the discount will still be valid. There is a problem in calculating the time between hours and minutes.

In order to calculate how many days there will be a discount, I do it like this:

```<code>$realTime = Carbon::now();
$diff = $realTime->diffInDays($item->created_at);
$date = 7 - $diff;
    if ($diff < 7) {
        Notify::create(
            [
            'user_id' => $this->user->id,
            'title' => 'Message',
            'message' => 'Discount will be available '.$date.' '.Lang::choice('day|days|', $date, [], 'ru'),'',
            'status' => '2',
        ]);
    }
</code>```

This is returned to me by the inscription that the discount will be available for another 1, 2, 3 ... days.

And now, how i can calculate the remaining hours and minutes?

I try something like this:

```<code>$realTime = Carbon::now();
$diff_hours = $realTime->diffInHours($item->created_at);
$date_hours = 168 - $diff_hours;
    if ($diff == 7) {
        Notify::create(
            [
            'user_id' => $this->user->id,
            'title' => 'Message',
            'message' => 'Discount will be available '.$date_hours .' '.Lang::choice('hour|hours|', $date_hours , [], 'ru'),'',
            'status' => '2',
        ]);
    }
</code>```

168 it's hours at 1 week, but maybe I'm doing something wrong? Because in the end I get a negative value of -17 hours. And by the same method, I try to make a difference in minutes, but again I get a negative and incomprehensible value.

UPD: at my database item has format 2020-05-26 23:40:15 i write:

```<code>$realTime = Carbon::now();
$diff = $realTime->diffInDays($item->created_at);
</code>```

$realTime for date now give me:

```<code>object(Carbon\Carbon)#623 (3) { ["date"]=> string(26) "2020-05-30 18:51:23.846522" ["timezone_type"]=> int(3) ["timezone"]=> string(13) "Europe/Moscow" }
</code>```

答:
You should grab the difference in seconds using Carbon and then use its fields to get your work done. Source.</p>

```<code>$totalDuration = $finishTime->diffInSeconds($startTime);

gmdate('H', $totalDuration);//hours

gmdate('m', $totalDuration); // minutes

gmdate('s', $totalDuration);
</code>```

Body:
I have weekly discounts on the product on my site, when buying, the user is written how much the discount will still be valid. There is a problem in calculating the time between hours and minutes.

In order to calculate how many days there will be a discount, I do it like this:

$realTime = Carbon::now();
$diff = $realTime->diffInDays($item->created_at);
$date = 7 - $diff;
    if ($diff < 7) {
        Notify::create(
            [
            'user_id' => $this->user->id,
            'title' => 'Message',
            'message' => 'Discount will be available '.$date.' '.Lang::choice('day|days|', $date, [], 'ru'),'',
            'status' => '2',
        ]);
    }

This is returned to me by the inscription that the discount will be available for another 1, 2, 3 ... days.

And now, how i can calculate the remaining hours and minutes?

I try something like this:

$realTime = Carbon::now();
$diff_hours = $realTime->diffInHours($item->created_at);
$date_hours = 168 - $diff_hours;
    if ($diff == 7) {
        Notify::create(
            [
            'user_id' => $this->user->id,
            'title' => 'Message',
            'message' => 'Discount will be available '.$date_hours .' '.Lang::choice('hour|hours|', $date_hours , [], 'ru'),'',
            'status' => '2',
        ]);
    }

168 it's hours at 1 week, but maybe I'm doing something wrong? Because in the end I get a negative value of -17 hours. And by the same method, I try to make a difference in minutes, but again I get a negative and incomprehensible value.

UPD: at my database item has format 2020-05-26 23:40:15 i write:

$realTime = Carbon::now();
$diff = $realTime->diffInDays($item->created_at);

$realTime for date now give me:

object(Carbon\Carbon)#623 (3) { ["date"]=> string(26) "2020-05-30 18:51:23.846522" ["timezone_type"]=> int(3) ["timezone"]=> string(13) "Europe/Moscow" }

Body:
You should grab the difference in seconds using Carbon and then use its fields to get your work done. Source.

$totalDuration = $finishTime->diffInSeconds($startTime);

gmdate('H', $totalDuration);//hours

gmdate('m', $totalDuration); // minutes

gmdate('s', $totalDuration);


问:
Form element validation using jQuery
I am trying to make a validation page and I need to stop saying "Please fill in the form" when text is entered in the text box. I only needed to validate when the text boxes are empty

<form action="mailto:kyletab03@gmail.com" name="myForm" method="post" onsubmit="return validation();" enctype="text/plain">
  Name:
  <input type="text" name="name" id="name" />

  Surname:
  <input type="text" name="surname" id="surname" />

  Email:
  <input type="email" name="email" id="email" />

  Message:
  <textarea name="Message" maxlength="3500"></textarea>

  <button id="submit" onclick="validation()">Submit</button>
</form>
```

答:
your code is showing an error because in your last line you are using "comments" instead of "Message", also setCustomValidity() takes a string with the error message or an empty string and for it to work well consider using the document's methods for retrieving elements, in addition you will need to add reportValidity() so your code should look like this

```<code>    if (name == "" || surname == "" || email == "" || comments == "") {
    name=document.getElementById('name')
    name.setCustomValidity("Please fill out this field");
    name.reportValidity()
}
else
    name.setCustomValidity('');
    name.reportValidity()
</code>```

also you can consider using a helper function to use the element id dynamically

Update:
 you can use this it will work

```<code> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="mailto:kyletab03@gmail.com" name="myForm" method="post" id='myform' enctype="text/plain">
  Name:
  <input type="text" name="name" id="name" required="required"/><br />
  Surname:
  <input type="text" name="surname" id="surname" required="required" /><br />
  Email:
  <input type="email" name="email" id="email" required="required" /><br />
  Message:
  <textarea name="Message" id="message" maxlength="3500" required="required"></textarea><br />
  <button onlclick='validation()'>Submit</button>
</form>
<script>

function validate(inputID)
{
 var input = document.getElementById(inputID);
 var validityState_object = input.validity;
 if (validityState_object.valueMissing)
 {
  input.setCustomValidity('Please fill out this field');
  input.reportValidity();
 }
 else
 {
  input.setCustomValidity('');
  input.reportValidity();
 }
}
   function validation() {
   var name= document.getElementById('name').value
   var surname=document.getElementById('surname').value
   var email=document.getElementById('email').value
   var message=document.getElementById('message').value

      validate('name')
      validate('surname')
      validate('email')
      validate('message')

 if (name!=''&&surname!=''&&email!=''&&message!='') {
          $('#myform').submit();

    }
}

</script>
</code>```

Title: Form element validation using jQuery

Body:
your code is showing an error because in your last line you are using "comments" instead of "Message", also setCustomValidity() takes a string with the error message or an empty string and for it to work well consider using the document's methods for retrieving elements, in addition you will need to add reportValidity() so your code should look like this

    if (name == "" || surname == "" || email == "" || comments == "") {
    name=document.getElementById('name')
    name.setCustomValidity("Please fill out this field");
    name.reportValidity()
}
else
    name.setCustomValidity('');
    name.reportValidity()

also you can consider using a helper function to use the element id dynamically

Update:
 you can use this it will work

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="mailto:kyletab03@gmail.com" name="myForm" method="post" id='myform' enctype="text/plain">
  Name:
  <input type="text" name="name" id="name" required="required"/><br />
  Surname:
  <input type="text" name="surname" id="surname" required="required" /><br />
  Email:
  <input type="email" name="email" id="email" required="required" /><br />
  Message:
  <textarea name="Message" id="message" maxlength="3500" required="required"></textarea><br />
  <button onlclick='validation()'>Submit</button>
</form>
<script>

function validate(inputID)
{
 var input = document.getElementById(inputID);
 var validityState_object = input.validity;
 if (validityState_object.valueMissing)
 {
  input.setCustomValidity('Please fill out this field');
  input.reportValidity();
 }
 else
 {
  input.setCustomValidity('');
  input.reportValidity();
 }
}
   function validation() {
   var name= document.getElementById('name').value
   var surname=document.getElementById('surname').value
   var email=document.getElementById('email').value
   var message=document.getElementById('message').value

      validate('name')
      validate('surname')
      validate('email')
      validate('message')

 if (name!=''&&surname!=''&&email!=''&&message!='') {
          $('#myform').submit();

    }
}

</script>


问:
UIImageView circular shape swift
I used this code to make UIImageView in a custom UITableViewCell, but the circular shape isn't updated until i pressed on the table cell, I tried the code in both awakeFromNib() and  layoutSubviews() </p>

```<code>  userImage.layer.cornerRadius = userImage.frame.size.width / 2
  userImage.layer.masksToBounds = true
  userImage.layer.borderColor = UIColor.black.cgColor
  userImage.layer.borderWidth = 1
</code>```

答:
update the imageViews cornerRadius just after a little time. Because frame.size.width / 2 will be different at runtime :</p>

```<code>    DispatchQueue.main.asyncAfter(deadline : .now() + 0.05 {
  self.userImage.layer.cornerRadius = userImage.frame.size.width / 2
  self.userImage.layer.masksToBounds = true
  self.userImage.layer.borderColor = UIColor.black.cgColor
  self.userImage.layer.borderWidth = 1

}
</code>```

Title: UIImageView circular shape swift

Body:
I used this code to make UIImageView in a custom UITableViewCell, but the circular shape isn't updated until i pressed on the table cell, I tried the code in both awakeFromNib() and  layoutSubviews()

  userImage.layer.cornerRadius = userImage.frame.size.width / 2
  userImage.layer.masksToBounds = true
  userImage.layer.borderColor = UIColor.black.cgColor
  userImage.layer.borderWidth = 1

Body:
update the imageViews cornerRadius just after a little time. Because frame.size.width / 2 will be different at runtime :

    DispatchQueue.main.asyncAfter(deadline : .now() + 0.05 {
  self.userImage.layer.cornerRadius = userImage.frame.size.width / 2
  self.userImage.layer.masksToBounds = true
  self.userImage.layer.borderColor = UIColor.black.cgColor
  self.userImage.layer.borderWidth = 1

}


问:
Run ANSYS Mechanical APDL from Python in an efficient manner
I have the following code, which writes an Input file and executes ANSYS Mechanical APDL using a Windows command. My issue is the execution time is much longer (15 minutes inside the software, upwards of 1 hour when calling from Python). I need it to be faster because I am varying as many as 'all' the input parameters.

```<code>def RunAPDL(E,t,w,p,aa,bb,lz,alpha,delta):

    ansyspath = r'C:\Program Files\ANSYS.Inc\v181\ansys\bin\winx64\MAPDL.exe'
    directory = r'C:\Users\Erik\Documents\ANSYS'
    jobname = 'file'
    memory = '4096'
    reserve = '1024'
    inputfile = r'C:\Users\Erik\Documents\ANSYS\ShellBucklingInput.inp'
    outputfile = r'C:\Users\Erik\Documents\ANSYS\OutputFile.txt'
    resultsfile = r'C:\Users\Erik\Documents\ANSYS\ShellBuckling.csv'

    # Start time count
    start = time.clock()

    # Write input file
    input_parameters = ('/NERR,200,10000,,OFF,0 \n'
                        'pi = acos(-1) \n'
                        'E = {:6.0f}     ! N/mm2 Young\'s modulus\n'
                        't = {:4.2f}       ! mm thickness\n'
                        'w = {:3.2f}       ! Poisson\'s ratio\n'
                        'p = {:7.2f}    ! N/mm2 external pressure\n'
                        'aa = {:6.2f}   ! mm horizontal radius at u = 0\n'
                        'bb = {:6.2f}   ! mm vertical radius\n'
                        'lz = {:6.2f}   ! mm model height\n'
                        'lu = 2*asin(lz/2/bb) !mm \n'
                        'lv = 2*pi      ! model perimeter at u = 0 \n'
                        'nu = 2*NINT(ABS(aa)/SQRT(ABS(aa)*t)) \n'
                        'nv = 3*nu      ! number of elements along v-axis \n'
                        'alpha = {:4.2f}   ! ratio of lu that is not loaded by p \n'
                        'delta = {:4.2f}*t ! prescribed imperfection magnitude \n'
                        '*ULIB,ShellBucklingLibrary,mac \n'
                        '*USE,ShellBuckling,pi,E,t,w,p,aa,bb,lz,lu,nu,nv,alpha,delta \n'
                        '/CLEAR'
                        ).format(E,t,w,p,aa,bb,lz,alpha,delta)
    with open(inputfile,'w') as f:
        f.write(input_parameters)

    # Call ANSYS
    callstring = ('\"{}\" -p aa_t_a -dir \"{}\" -j \"{}\" -s read'
                  ' -m {} -db {} -t -d win32 -b -i \"{}\" -o \"{}\"'
                  ).format(ansyspath,directory,jobname,memory,reserve,inputfile,outputfile)
    print('Invoking ANSYS with', callstring)
    proc = subprocess.Popen(callstring).wait()

    # Update pressure field for next analysis
    with open(resultsfile,'r') as f:
        lambdaS = float(list(csv.reader(f))[-1][16])
    p = 1.2*lambdaS*p
    print('Updated pressure is',p,' N/mm2.')

    # Stop time count
    stop = time.clock()
    print('Elapsed time is ',stop-start,' seconds.')

    return(p)
</code>```

I execute it by pressing F5 on the Python shell, then messages appear in the shell:

```<code>Invoking ANSYS with "C:\Program Files\ANSYS
Inc\v181\ansys\bin\winx64\MAPDL.exe" -p aa_t_a -dir
"C:\Users\Erik\Documents\ANSYS" -j "file" -s read -m 4096 -db 1024 -t -d
win32 -b -i "C:\Users\Erik\Documents\ANSYS\ShellBucklingInput.inp" -o
"C:\Users\Erik\Documents\ANSYS\OutputFile.txt"
Updated pressure is -0.0046478399999999994  N/mm2.
Elapsed time is  4016.59094467131  seconds.
</code>```

答: I don't know why your code is slower in Python but I suggest you to use PyAnsys package from PyPI. It offers a robust infrastructure to combine Python and APDL.</p>

Body:
I have the following code, which writes an Input file and executes ANSYS Mechanical APDL using a Windows command. My issue is the execution time is much longer (15 minutes inside the software, upwards of 1 hour when calling from Python). I need it to be faster because I am varying as many as 'all' the input parameters.

def RunAPDL(E,t,w,p,aa,bb,lz,alpha,delta):

    ansyspath = r'C:\Program Files\ANSYS.Inc\v181\ansys\bin\winx64\MAPDL.exe'
    directory = r'C:\Users\Erik\Documents\ANSYS'
    jobname = 'file'
    memory = '4096'
    reserve = '1024'
    inputfile = r'C:\Users\Erik\Documents\ANSYS\ShellBucklingInput.inp'
    outputfile = r'C:\Users\Erik\Documents\ANSYS\OutputFile.txt'
    resultsfile = r'C:\Users\Erik\Documents\ANSYS\ShellBuckling.csv'

    # Start time count
    start = time.clock()

    # Write input file
    input_parameters = ('/NERR,200,10000,,OFF,0 \n'
                        'pi = acos(-1) \n'
                        'E = {:6.0f}     ! N/mm2 Young\'s modulus\n'
                        't = {:4.2f}       ! mm thickness\n'
                        'w = {:3.2f}       ! Poisson\'s ratio\n'
                        'p = {:7.2f}    ! N/mm2 external pressure\n'
                        'aa = {:6.2f}   ! mm horizontal radius at u = 0\n'
                        'bb = {:6.2f}   ! mm vertical radius\n'
                        'lz = {:6.2f}   ! mm model height\n'
                        'lu = 2*asin(lz/2/bb) !mm \n'
                        'lv = 2*pi      ! model perimeter at u = 0 \n'
                        'nu = 2*NINT(ABS(aa)/SQRT(ABS(aa)*t)) \n'
                        'nv = 3*nu      ! number of elements along v-axis \n'
                        'alpha = {:4.2f}   ! ratio of lu that is not loaded by p \n'
                        'delta = {:4.2f}*t ! prescribed imperfection magnitude \n'
                        '*ULIB,ShellBucklingLibrary,mac \n'
                        '*USE,ShellBuckling,pi,E,t,w,p,aa,bb,lz,lu,nu,nv,alpha,delta \n'
                        '/CLEAR'
                        ).format(E,t,w,p,aa,bb,lz,alpha,delta)
    with open(inputfile,'w') as f:
        f.write(input_parameters)

    # Call ANSYS
    callstring = ('\"{}\" -p aa_t_a -dir \"{}\" -j \"{}\" -s read'
                  ' -m {} -db {} -t -d win32 -b -i \"{}\" -o \"{}\"'
                  ).format(ansyspath,directory,jobname,memory,reserve,inputfile,outputfile)
    print('Invoking ANSYS with', callstring)
    proc = subprocess.Popen(callstring).wait()

    # Update pressure field for next analysis
    with open(resultsfile,'r') as f:
        lambdaS = float(list(csv.reader(f))[-1][16])
    p = 1.2*lambdaS*p
    print('Updated pressure is',p,' N/mm2.')

    # Stop time count
    stop = time.clock()
    print('Elapsed time is ',stop-start,' seconds.')

    return(p)

I execute it by pressing F5 on the Python shell, then messages appear in the shell:

Invoking ANSYS with "C:\Program Files\ANSYS
Inc\v181\ansys\bin\winx64\MAPDL.exe" -p aa_t_a -dir
"C:\Users\Erik\Documents\ANSYS" -j "file" -s read -m 4096 -db 1024 -t -d
win32 -b -i "C:\Users\Erik\Documents\ANSYS\ShellBucklingInput.inp" -o
"C:\Users\Erik\Documents\ANSYS\OutputFile.txt"
Updated pressure is -0.0046478399999999994  N/mm2.
Elapsed time is  4016.59094467131  seconds.


问:
sql ex ru excercise data mismatch question 63
there are two tables

```<code>Passenger(ID_psg, name)
Pass_in_trip(trip_no, date, ID_psg, place)
</code>```

on which you should find the names of passangers who has travelled more than once on the exact same seat
more precisely the question is like this:

```<code>Find the names of different passengers that ever travelled more than once occupying seats with the same number
</code>```

both tabels are linked to eachother thropugh the id_psg
the column which contains the seat is place from pass_in_trip which contains
which passenger name was seated there via id_psg

my current code is :

```<code>with a(name, heret) as (
select pr.name , count(p.place) as heret from passenger pr
join pass_in_trip p on
pr.id_psg = p.id_psg
group by pr.name , p.place
)

select distinct name from a
where heret > 1
</code>```

on which i grouped the passengers names with their place(seat) ,
i got the correct result in the first database but it had data mismatch on the second one ,
can anyone help me to understand what is wrong in this situation?

答:
looks like the problem was on the join operation
this is the correct code for anyone who faces similar obstacle

```<code>select name from Passenger where id_Psg IN (
select p.ID_psg from
pass_in_trip p
group by p.ID_psg, p.place
having count(p.place) > 1 )
</code>```

search for the names whose id_psg results in that subquerie

Body:
there are two tables

Passenger(ID_psg, name)
Pass_in_trip(trip_no, date, ID_psg, place)

on which you should find the names of passangers who has travelled more than once on the exact same seat
more precisely the question is like this:

Find the names of different passengers that ever travelled more than once occupying seats with the same number

both tabels are linked to eachother thropugh the id_psg
the column which contains the seat is place from pass_in_trip which contains
which passenger name was seated there via id_psg

my current code is :

with a(name, heret) as (
select pr.name , count(p.place) as heret from passenger pr
join pass_in_trip p on
pr.id_psg = p.id_psg
group by pr.name , p.place
)

select distinct name from a
where heret > 1

on which i grouped the passengers names with their place(seat) ,
i got the correct result in the first database but it had data mismatch on the second one ,
can anyone help me to understand what is wrong in this situation?

Body:
looks like the problem was on the join operation
this is the correct code for anyone who faces similar obstacle

select name from Passenger where id_Psg IN (
select p.ID_psg from
pass_in_trip p
group by p.ID_psg, p.place
having count(p.place) > 1 )

search for the names whose id_psg results in that subquerie


问:
How to modify string using RegEx?
How do I transform the string from 'updown' to 'Up/Down' using RegEx?</p>

答:
If you already know the input and output string then there's no use case for regular expressions. Regular expressions are for matching a grammar, which is a set of strings, rather than a single string.

Are you looking for something more general? Perhaps your question is about how to split up the words up and down, or how to capitalize the letters?

Title: How to modify string using RegEx?


问:
How to use CSS counter increment for dynamic page numbers
I am trying to add page numbers to my html print out and came across Counter Increment. I tried using it for my pages, but it is only showing Page 1 every time. Help would be appreciated.

P.S. I have already tried following other solutions similar to mine, but none work so far. My case is different because I am using it inside of a table header.

.page-number{
    text-align:center;
}
thead {
    display:table-header-group;
}

@media print{
     .page-number:before{
        counter-increment: page;
        content: "Page " counter(page);
     }
   }
@media screen{
    .page-number:before {
        counter-increment: page;
        content: "Page " counter(page);
        }
     }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="SetupMainTable">
  <thead>
    <tr>
       <td colspan="4">Company Name</td>
       <td colspan="5" class="right" style="font-size:25px;">Daily Time Ticket</td>
       <td colspan="1"><div class="page-number"></div></td>
    </tr>
  </thead>
</table>  </code>```

Eg:Example that print's same Page 1  on all pages

Code editor link

Code editor Preview link - just press ctrl+p to test

Expected Answer

It Should print incremental Page 1 Page 2 Page 3 number on all pages after pressing ctrl + p Print

Long story short:

Press Ctrl + P → Print current window → Add a footer in the bottom of the page(Current Window) like Page <counter> counter is a number starting from 1 .

So the Page will be like

PS: Counter shouldn't visible on the page

答:
First of all, it was quite a challenge answering this question.
Secondly, why weren't the other examples just working? That's because the counter only fires on every element. When you print, the browser doesn't create new instances of
, at least to source code of your website. It just simply displays it. However, this behaviour can be bypassed by, before printing ('beforeprint'), altering the DOM and recreating the print pages with Javascript. Now, on every page there's a new
 with a new instance of
. Now, the counter works. After printing this code automatically resets the DOM to the state before printing. The User Experience stays the same.

With const pixelHeightA4 = 1000; you can specify how many pixels fit one a4. 1000 comes really close when I was testing.

With const heightOfTHead = 160; you specify the height of the table header on an a4 size.

I hope the comments in code can explain the process.

//alter the dom to print the elements
window.addEventListener('beforeprint', event => {
  //specify the number of rows in the tBody per page

  //You can either hardcode this number or change it for every page with code
  var table = document.getElementsByClassName('SetupMainTable')[0];

  printTableData(table);
  table.style.display = 'none';
});

function printTableData(table) {
  //initialise the table to get the data from
  var table = table.querySelectorAll('tbody')[0];
  var tBody;
  //get the template table
  let temp = document.getElementsByTagName('template')[0];
  //get the number of element for the last page
  const pixelHeightA4 = 1000;
  const heightOfTHead = 160;
  var heightOfContent = heightOfTHead;

  for (var i = 0, row; row = table.rows[i]; i++) {
    //get the height of the current row
    var rowHeight = row.getBoundingClientRect().height;
    var nextRowHeight;
    //get the height of the next row.
    if (i + 1 == table.rows.length) {
      nextRowHeight = 0;
    } else {
      nextRowHeight = (table.rows[i + 1]).getBoundingClientRect().height;
    }

    if (heightOfContent == 160 && table.rows.length - 1 != i) {
      //if it is the first element and not the only element on the last page
      //create new tBody
      tBody = document.createElement('tbody');
      var firstEl = row.cloneNode(true);
      heightOfContent += rowHeight;
      tBody.appendChild(firstEl);
    } else if (((heightOfContent + rowHeight) < pixelHeightA4 && (heightOfContent + rowHeight + nextRowHeight) >= 1000) || table.rows.length - 1 == i) {
      //if the row still fits on the page but the next row doesn't then this is the last table row of the page.

      if (tBody == null) {
        //if there's only one element on the last page, create a new tBody
        tBody = document.createElement('tbody');
      }

      //clone the template
      var clon = temp.content.cloneNode(true);
      //clone the row to append to the tbody
      var cloneRow = row.cloneNode(true);
      //get the table element in the template
      var cloneTable = clon.querySelectorAll('table')[0];
      //append it all togehter
      tBody.appendChild(cloneRow);
      cloneTable.appendChild(tBody);
      //append the table to the page
      document.body.appendChild(clon);

      //reset the tBody
      tBody = null;
      heightOfContent = heightOfTHead;
    } else {
      //clone a row and append it to the tBody
      var cloneRow = row.cloneNode(true);
      heightOfContent += rowHeight;
      tBody.appendChild(cloneRow);
    }

    console.log(heightOfContent);
  }
}

//reset the dom to the state before print
window.addEventListener('afterprint', event => {
  var table = document.getElementsByClassName('SetupMainTable');
  table[0].style.display = 'table';
  //remove all the cloned tables
  var cloneTables = document.getElementsByClassName('templateTable');
  while (cloneTables.length > 0) {
    cloneTables[0].parentNode.removeChild(cloneTables[0]);
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@media print {
  body {
    counter-reset: page;
    color: red;
  }
  .page-number:before {
    counter-increment: page;
    content: "Page "counter(page);
  }
  table {
    break-after: page !important;
    border: 1px solid grey;
    border-collapse: collapse;
  }
  .templateTable {
    display: table;
  }
}

@media screen {
  body {
    counter-reset: page;
  }
  .page-number {
    text-align: center;
  }
  table {
    border: 1px solid grey;
    border-collapse: collapse;
  }
  thead {
    display: table-header-group;
  }
  .page-number:before {
    counter-increment: page;
    content: "Page "counter(page);
  }
  .templateTable {
    display: none;
  }
}

table td,
table th {
  border: 1px solid black;
}

table tr:first-child th {
  border-top: 0;
}

table tr:last-child td {
  border-bottom: 0;
}

table tr td:first-child,
table tr th:first-child {
  border-left: 0;
}

table tr td:last-child,
table tr th:last-child {
  border-right: 0;
}</code>```

        Company Name
        Daily Time Ticket

        123
        abc

        456
        def

header for random dynamic height

        ghi

        101112

        131416
        mno

        171819
        pqr

        small text

Big text

        132435
        vwx

        1325125123
        yza

        xy2532351235z
        bcd

        12351235125
        efg

        1253251235
        hij

        2315346
        klm

        123
        abc

        456
        def

header for random dynamic height

        ghi

        101112

        131416
        mno

        171819
        pqr

        small text

Big text

        132435
        vwx

        1325125123
        yza

        xy2532351235z
        bcd

        12351235125
        efg

        1253251235
        hij

        2315346
        klm

        123
        abc

        456
        def

header for random dynamic height

        ghi

        101112

        131416
        mno

        171819
        pqr

        small text

Big text

        132435
        vwx

        1325125123
        yza

        xy2532351235z
        bcd

        12351235125
        efg

        1253251235
        hij

        2315346
        klm

        123
        abc

        456
        def

header for random dynamic height

        ghi

        101112

        131416
        mno

        171819
        pqr

        small text

Big text

        132435
        vwx

        1325125123
        yza

        xy2532351235z
        bcd

        12351235125
        efg

        1253251235
        hij

        2315346
        klm

  <template id="tables">

            Company Name
            Daily Time Ticket

    </template>
```

Hope this helps, if not, please comment!

Edit1:

It automatically calculates the amount of rows that can fit on one a4 based on the row height of each individual
.

You can test it here (Tested it on chrome)

Body:
I am trying to add page numbers to my html print out and came across Counter Increment. I tried using it for my pages, but it is only showing Page 1 every time. Help would be appreciated.

P.S. I have already tried following other solutions similar to mine, but none work so far. My case is different because I am using it inside of a table header.

.page-number{
    text-align:center;
}
thead {
    display:table-header-group;
}

@media print{
     .page-number:before{
        counter-increment: page;
        content: "Page " counter(page);
     }
   }
@media screen{
    .page-number:before {
        counter-increment: page;
        content: "Page " counter(page);
        }
     }

       Company Name
       Daily Time Ticket

Eg:Example that print's same Page 1  on all pages

Code editor link

Code editor Preview link - just press ctrl+p to test

Expected Answer

It Should print incremental Page 1 Page 2 Page 3 number on all pages after pressing ctrl + p Print

Long story short:

Press Ctrl + P → Print current window → Add a footer in the bottom of the page(Current Window) like Page <counter> counter is a number starting from 1 .

So the Page will be like

PS: Counter shouldn't visible on the page

Body:
First of all, it was quite a challenge answering this question.
Secondly, why weren't the other examples just working? That's because the counter only fires on every element. When you print, the browser doesn't create new instances of <thead>, at least to source code of your website. It just simply displays it. However, this behaviour can be bypassed by, before printing ('beforeprint'), altering the DOM and recreating the print pages with Javascript. Now, on every page there's a new <table> with a new instance of <thead>. Now, the counter works. After printing this code automatically resets the DOM to the state before printing. The User Experience stays the same.

With const pixelHeightA4 = 1000; you can specify how many pixels fit one a4. 1000 comes really close when I was testing.

With const heightOfTHead = 160; you specify the height of the table header on an a4 size.

I hope the comments in code can explain the process.

//alter the dom to print the elements
window.addEventListener('beforeprint', event => {
  //specify the number of rows in the tBody per page

  //You can either hardcode this number or change it for every page with code
  var table = document.getElementsByClassName('SetupMainTable')[0];

  printTableData(table);
  table.style.display = 'none';
});

function printTableData(table) {
  //initialise the table to get the data from
  var table = table.querySelectorAll('tbody')[0];
  var tBody;
  //get the template table
  let temp = document.getElementsByTagName('template')[0];
  //get the number of element for the last page
  const pixelHeightA4 = 1000;
  const heightOfTHead = 160;
  var heightOfContent = heightOfTHead;

  for (var i = 0, row; row = table.rows[i]; i++) {
    //get the height of the current row
    var rowHeight = row.getBoundingClientRect().height;
    var nextRowHeight;
    //get the height of the next row.
    if (i + 1 == table.rows.length) {
      nextRowHeight = 0;
    } else {
      nextRowHeight = (table.rows[i + 1]).getBoundingClientRect().height;
    }

    if (heightOfContent == 160 && table.rows.length - 1 != i) {
      //if it is the first element and not the only element on the last page
      //create new tBody
      tBody = document.createElement('tbody');
      var firstEl = row.cloneNode(true);
      heightOfContent += rowHeight;
      tBody.appendChild(firstEl);
    } else if (((heightOfContent + rowHeight) < pixelHeightA4 && (heightOfContent + rowHeight + nextRowHeight) >= 1000) || table.rows.length - 1 == i) {
      //if the row still fits on the page but the next row doesn't then this is the last table row of the page.

      if (tBody == null) {
        //if there's only one element on the last page, create a new tBody
        tBody = document.createElement('tbody');
      }

      //clone the template
      var clon = temp.content.cloneNode(true);
      //clone the row to append to the tbody
      var cloneRow = row.cloneNode(true);
      //get the table element in the template
      var cloneTable = clon.querySelectorAll('table')[0];
      //append it all togehter
      tBody.appendChild(cloneRow);
      cloneTable.appendChild(tBody);
      //append the table to the page
      document.body.appendChild(clon);

      //reset the tBody
      tBody = null;
      heightOfContent = heightOfTHead;
    } else {
      //clone a row and append it to the tBody
      var cloneRow = row.cloneNode(true);
      heightOfContent += rowHeight;
      tBody.appendChild(cloneRow);
    }

    console.log(heightOfContent);
  }
}

//reset the dom to the state before print
window.addEventListener('afterprint', event => {
  var table = document.getElementsByClassName('SetupMainTable');
  table[0].style.display = 'table';
  //remove all the cloned tables
  var cloneTables = document.getElementsByClassName('templateTable');
  while (cloneTables.length > 0) {
    cloneTables[0].parentNode.removeChild(cloneTables[0]);
  }
});

@media print {
  body {
    counter-reset: page;
    color: red;
  }
  .page-number:before {
    counter-increment: page;
    content: "Page "counter(page);
  }
  table {
    break-after: page !important;
    border: 1px solid grey;
    border-collapse: collapse;
  }
  .templateTable {
    display: table;
  }
}

@media screen {
  body {
    counter-reset: page;
  }
  .page-number {
    text-align: center;
  }
  table {
    border: 1px solid grey;
    border-collapse: collapse;
  }
  thead {
    display: table-header-group;
  }
  .page-number:before {
    counter-increment: page;
    content: "Page "counter(page);
  }
  .templateTable {
    display: none;
  }
}

table td,
table th {
  border: 1px solid black;
}

table tr:first-child th {
  border-top: 0;
}

table tr:last-child td {
  border-bottom: 0;
}

table tr td:first-child,
table tr th:first-child {
  border-left: 0;
}

table tr td:last-child,
table tr th:last-child {
  border-right: 0;
}

<!-- Extra big table with different row seizes for demonstration purposes only -->

<body>
  <table class="SetupMainTable">
    <thead>
      <tr>
        <th colspan="4">Company Name</th>
        <th colspan="5" class="right" style="font-size:25px;">Daily Time Ticket</th>
        <th colspan="1">
          <div class="page-number"></div>
        </th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td colspan="5">123</td>
        <td colspan="5">abc</td>
      </tr>
      <tr>
        <td colspan="5">456</td>
        <td colspan="5">def</td>
      </tr>
      <tr>
        <td colspan="5">
          <h3>header for random dynamic height</h3>
        </td>
        <td colspan="5">ghi</td>
      </tr>
      <tr>
        <td colspan="5">101112</td>
        <td colspan="5"><img src="https://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png" height="100"></td>
      </tr>
      <tr>
        <td colspan="5">131416</td>
        <td colspan="5">mno</td>
      </tr>
      <tr>
        <td colspan="5">171819</td>
        <td colspan="5">pqr</td>
      </tr>
      <tr>
        <td colspan="5"><small>small text</small></td>
        <td colspan="5">
          <h1>Big text</h1>
        </td>
      </tr>
      <tr>
        <td colspan="5">132435</td>
        <td colspan="5">vwx</td>
      </tr>
      <tr>
        <td colspan="5">1325125123</td>
        <td colspan="5">yza</td>
      </tr>
      <tr>
        <td colspan="5">xy2532351235z</td>
        <td colspan="5">bcd</td>
      </tr>
      <tr>
        <td colspan="5">12351235125</td>
        <td colspan="5">efg</td>
      </tr>
      <tr>
        <td colspan="5">1253251235</td>
        <td colspan="5">hij</td>
      </tr>
      <tr>
        <td colspan="5">2315346</td>
        <td colspan="5">klm</td>
      </tr>
      <tr>
        <td colspan="5">123</td>
        <td colspan="5">abc</td>
      </tr>
      <tr>
        <td colspan="5">456</td>
        <td colspan="5">def</td>
      </tr>
      <tr>
        <td colspan="5">
          <h3>header for random dynamic height</h3>
        </td>
        <td colspan="5">ghi</td>
      </tr>
      <tr>
        <td colspan="5">101112</td>
        <td colspan="5"><img src="https://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png" height="100"></td>
      </tr>
      <tr>
        <td colspan="5">131416</td>
        <td colspan="5">mno</td>
      </tr>
      <tr>
        <td colspan="5">171819</td>
        <td colspan="5">pqr</td>
      </tr>
      <tr>
        <td colspan="5"><small>small text</small></td>
        <td colspan="5">
          <h1>Big text</h1>
        </td>
      </tr>
      <tr>
        <td colspan="5">132435</td>
        <td colspan="5">vwx</td>
      </tr>
      <tr>
        <td colspan="5">1325125123</td>
        <td colspan="5">yza</td>
      </tr>
      <tr>
        <td colspan="5">xy2532351235z</td>
        <td colspan="5">bcd</td>
      </tr>
      <tr>
        <td colspan="5">12351235125</td>
        <td colspan="5">efg</td>
      </tr>
      <tr>
        <td colspan="5">1253251235</td>
        <td colspan="5">hij</td>
      </tr>
      <tr>
        <td colspan="5">2315346</td>
        <td colspan="5">klm</td>
      </tr>
      <tr>
        <td colspan="5">123</td>
        <td colspan="5">abc</td>
      </tr>
      <tr>
        <td colspan="5">456</td>
        <td colspan="5">def</td>
      </tr>
      <tr>
        <td colspan="5">
          <h3>header for random dynamic height</h3>
        </td>
        <td colspan="5">ghi</td>
      </tr>
      <tr>
        <td colspan="5">101112</td>
        <td colspan="5"><img src="https://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png" height="100"></td>
      </tr>
      <tr>
        <td colspan="5">131416</td>
        <td colspan="5">mno</td>
      </tr>
      <tr>
        <td colspan="5">171819</td>
        <td colspan="5">pqr</td>
      </tr>
      <tr>
        <td colspan="5"><small>small text</small></td>
        <td colspan="5">
          <h1>Big text</h1>
        </td>
      </tr>
      <tr>
        <td colspan="5">132435</td>
        <td colspan="5">vwx</td>
      </tr>
      <tr>
        <td colspan="5">1325125123</td>
        <td colspan="5">yza</td>
      </tr>
      <tr>
        <td colspan="5">xy2532351235z</td>
        <td colspan="5">bcd</td>
      </tr>
      <tr>
        <td colspan="5">12351235125</td>
        <td colspan="5">efg</td>
      </tr>
      <tr>
        <td colspan="5">1253251235</td>
        <td colspan="5">hij</td>
      </tr>
      <tr>
        <td colspan="5">2315346</td>
        <td colspan="5">klm</td>
      </tr>
      <tr>
        <td colspan="5">123</td>
        <td colspan="5">abc</td>
      </tr>
      <tr>
        <td colspan="5">456</td>
        <td colspan="5">def</td>
      </tr>
      <tr>
        <td colspan="5">
          <h3>header for random dynamic height</h3>
        </td>
        <td colspan="5">ghi</td>
      </tr>
      <tr>
        <td colspan="5">101112</td>
        <td colspan="5"><img src="https://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png" height="100"></td>
      </tr>
      <tr>
        <td colspan="5">131416</td>
        <td colspan="5">mno</td>
      </tr>
      <tr>
        <td colspan="5">171819</td>
        <td colspan="5">pqr</td>
      </tr>
      <tr>
        <td colspan="5"><small>small text</small></td>
        <td colspan="5">
          <h1>Big text</h1>
        </td>
      </tr>
      <tr>
        <td colspan="5">132435</td>
        <td colspan="5">vwx</td>
      </tr>
      <tr>
        <td colspan="5">1325125123</td>
        <td colspan="5">yza</td>
      </tr>
      <tr>
        <td colspan="5">xy2532351235z</td>
        <td colspan="5">bcd</td>
      </tr>
      <tr>
        <td colspan="5">12351235125</td>
        <td colspan="5">efg</td>
      </tr>
      <tr>
        <td colspan="5">1253251235</td>
        <td colspan="5">hij</td>
      </tr>
      <tr>
        <td colspan="5">2315346</td>
        <td colspan="5">klm</td>
      </tr>

    </tbody>
  </table>
  <template id="tables">
      <table class="SetupMainTable templateTable">
        <thead>
          <tr>
            <th colspan="4">Company Name</th>
            <th colspan="5" class="right" style="font-size:25px;">Daily Time Ticket</th>
            <th colspan="1">
              <div class="page-number"></div>
            </th>
          </tr>
        </thead>
      </table>
    </template>
</body>

Hope this helps, if not, please comment!

Edit1:

It automatically calculates the amount of rows that can fit on one a4 based on the row height of each individual <tr>.

You can test it here (Tested it on chrome)


问:
monitoring linux server sockets or files
I have the famous socketexception too many open files bug.
Iam running an apache http server, tomcat server and a mysql database on my server.

I checked the limit of open files with ulimit -n that gave me 1024.
If i want to check how many files are opened by lsof -u tomcat, it gives me 5
same for mysql. I not sure what the problem is.. but i have also a readlink permission denied.

i want to monitor my socket connections and opened files on my server. I thought about using the decribed linux commands in a shell script and send them per mail to me.

The other option i think is using netstat and count maybe the connections.. but its loading very slowly and is giving me getnameinfo fail.

what would be the better command to monitor the bug i have`?

EDIT:

```<code>SHOW GLOBAL VARIABLES LIKE '%open%';
    Variable_name Value
    Com_ha_open 0
    Com_show_open_tables 0
    Open_files 8
    Open_streams 0
    Open_table_definitions 87
    Open_tables 64
    Opened_files 673
    Opened_table_definitions 87
    Opened_tables 628
    Slave_open_temp_tables 0

    SHOW GLOBAL VARIABLES LIKE '%open%';

    Variable_name Value
    have_openssl DISABLED
    innodb_open_files 300
    open_files_limit 2000
    table_open_cache 64

    SHOW GLOBAL VARIABLES LIKE '%connect%'

    character_set_connection latin1
    collation_connection latin1_swedish_ci
    connect_timeout 10
    init_connect
    max_connect_errors 10
    max_connections 400
    max_user_connections 0

    SHOW GLOBAL STATUS LIKE '%connect%';

    Variable_name Value
    Aborted_connects 1
    Connections 35954
    Max_used_connections 102
    Ssl_client_connects 0
    Ssl_connect_renegotiates 0
    Ssl_finished_connects 0
    Threads_connected 11
</code>```

答:
You may check ulimit values with 'ulimit -a' to determine capacity of Open Files.
From OS Command Prompt, ulimit -n 8192 and press enter to enable more Open Files dyamically.
To make this change persist across OS restart, the next URL can be your guide.

https://glassonionblog.wordpress.com/2013/01/27/increase-ulimit-and-file-descriptors-limit/

Where their example is for 500000 capacity, use 8192 for your system, please.

Suggestions to consider for your my.cnf [mysqld] section,

```<code>thread_cache_size=100  # to support your max_used_connections of 102
max_user_connections=400  # from 0 to match max_connections requested
table_open_cache=800  # from 64 to reduce Opened_tables count
innodb_open_files=800  # from 300 to match table_open_cache requested
</code>```

Implementing these details should avoid 'too many open files' message. For additional assistance, view profile, Network profile for contact information and free downloadable Utility Scripts to assist with performance tuning.

Body:
I have the famous socketexception too many open files bug.
Iam running an apache http server, tomcat server and a mysql database on my server.

I checked the limit of open files with ulimit -n that gave me 1024.
If i want to check how many files are opened by lsof -u tomcat, it gives me 5
same for mysql. I not sure what the problem is.. but i have also a readlink permission denied.

i want to monitor my socket connections and opened files on my server. I thought about using the decribed linux commands in a shell script and send them per mail to me.

The other option i think is using netstat and count maybe the connections.. but its loading very slowly and is giving me getnameinfo fail.

what would be the better command to monitor the bug i have`?

EDIT:

SHOW GLOBAL VARIABLES LIKE '%open%';
    Variable_name Value
    Com_ha_open 0
    Com_show_open_tables 0
    Open_files 8
    Open_streams 0
    Open_table_definitions 87
    Open_tables 64
    Opened_files 673
    Opened_table_definitions 87
    Opened_tables 628
    Slave_open_temp_tables 0

    SHOW GLOBAL VARIABLES LIKE '%open%';

    Variable_name Value
    have_openssl DISABLED
    innodb_open_files 300
    open_files_limit 2000
    table_open_cache 64

    SHOW GLOBAL VARIABLES LIKE '%connect%'

    character_set_connection latin1
    collation_connection latin1_swedish_ci
    connect_timeout 10
    init_connect
    max_connect_errors 10
    max_connections 400
    max_user_connections 0

    SHOW GLOBAL STATUS LIKE '%connect%';

    Variable_name Value
    Aborted_connects 1
    Connections 35954
    Max_used_connections 102
    Ssl_client_connects 0
    Ssl_connect_renegotiates 0
    Ssl_finished_connects 0
    Threads_connected 11

Body:
You may check ulimit values with 'ulimit -a' to determine capacity of Open Files.
From OS Command Prompt, ulimit -n 8192 and press enter to enable more Open Files dyamically.
To make this change persist across OS restart, the next URL can be your guide.

https://glassonionblog.wordpress.com/2013/01/27/increase-ulimit-and-file-descriptors-limit/

Where their example is for 500000 capacity, use 8192 for your system, please.

Suggestions to consider for your my.cnf [mysqld] section,

thread_cache_size=100  # to support your max_used_connections of 102
max_user_connections=400  # from 0 to match max_connections requested
table_open_cache=800  # from 64 to reduce Opened_tables count
innodb_open_files=800  # from 300 to match table_open_cache requested

Implementing these details should avoid 'too many open files' message. For additional assistance, view profile, Network profile for contact information and free downloadable Utility Scripts to assist with performance tuning.


答:
```<code>    string = "updown"
    string.gsub!("up", "Up!")
    string.gsub!("down", "Down")
string = "Up!Down"
</code>```

Title: How to modify string using RegEx?

Body: How do I transform the string from 'updown' to 'Up/Down' using RegEx?


问:
Multiple switches with the same parent link
Sandbox https://codesandbox.io/s/agitated-hofstadter-ym4lo

I'm new to react and I'm trying to have the following routes; I'm using a switch in the App component

/authenticate

/panel/dashboard

/panel/accounts

In this case any routing to /panel/ is loaded from the Panel component. I want to handle any further routing for dashboard and accounts here. However, what happens now is, when a user clicks to switch navigation from the Panel component the component does not update (the url does). Whenever I refresh the URL, ofcourse, it does render.

Example

https://gyazo.com/4b76250fd02a2b09859e90abc7386485

Code

App.jsx

```<code>class App extends Component {
  state = {
    redirect: null,
    errors: {},
  };

  render() {
    return (
      <Switch>
        <ProtectedRoute path="/panel" component={Panel} />

        <Route
          path="/authenticate"
          render={(props) => <Authenticate {...props} errors={this.state.errors} handleLogin={(event) => this.handleLogin(event)} />}
        />

        {this.state.redirect ? <Redirect to={this.state.redirect} /> : null}
      </Switch>
    );
  }

  {/* Left some functions out for clarity. */}
}

export default App;
</code>```

Panel.jsx

```<code>class Panel extends Component {
  state = {};

  render() {
    return (
      <div id="panel" className="page-wrapper">
        <Container className="page-container" fluid>
          <Row>
            <Col sm={2} className="column">
              <div className="list-group">
                <NavLink to="/panel/dashboard" exact className="list-group-item list-group-item-action" activeClassName="active">
                  Dashboard
                </NavLink>
                <NavLink to="/panel/accounts" exact className="list-group-item list-group-item-action" activeClassName="active">
                  Accounts
                </NavLink>
              </div>
            </Col>
            <Col sm={10} className="column">
              <Card className="w-100">
                <Switch>
                  <Route path="/panel/dashboard">
                    <h1>Dashboard</h1>
                  </Route>
                  <Route path="/panel/accounts">
                    <h1>Accounts</h1>
                  </Route>
                </Switch>
              </Card>
            </Col>
          </Row>
        </Container>
      </div>
    );
  }
}

export default Panel;
</code>```

I'm having another switch in the Panel component so I do not have to rerender the sidebar, and can just load in the proper component depending on what route the user is (is there anything wrong with doing this, or is the better way in general).

Summary

So the problem is that the components are not loaded in when navigating to /panel and clicking on the navbar.

Edit: Excuse me for some of the things I had within the code. I like to be edgy when writing my code.

答:
You Panel component needs to receive the Router Props either you can use withRouter or pass on the Router Props from ProtectedRoute to the rendered component

```<code>class Panel extends Component {
  state = {};

  render() {
    return (
      <div id="panel" className="page-wrapper">
        <Container className="page-container" fluid>
          <Row>
            <Col sm={2} className="column">
              <div className="list-group">
                <NavLink to="/panel/dashboard" exact className="list-group-item list-group-item-action" activeClassName="active">
                  Dashboard
                </NavLink>
                <NavLink to="/panel/accounts" exact className="list-group-item list-group-item-action" activeClassName="active">
                  Accounts
                </NavLink>
              </div>
            </Col>
            <Col sm={10} className="column">
              <Card className="w-100">
                <Switch>
                  <Route path="/panel/dashboard">
                    <h1>Dashboard</h1>
                  </Route>
                  <Route path="/panel/accounts">
                    <h1>Accounts</h1>
                  </Route>
                </Switch>
              </Card>
            </Col>
          </Row>
        </Container>
      </div>
    );
  }
}

export default withRouter(Panel);
</code>```

Body:
Sandbox https://codesandbox.io/s/agitated-hofstadter-ym4lo

I'm new to react and I'm trying to have the following routes; I'm using a switch in the App component

/authenticate

/panel/dashboard

/panel/accounts

In this case any routing to /panel/ is loaded from the Panel component. I want to handle any further routing for dashboard and accounts here. However, what happens now is, when a user clicks to switch navigation from the Panel component the component does not update (the url does). Whenever I refresh the URL, ofcourse, it does render.

Example

https://gyazo.com/4b76250fd02a2b09859e90abc7386485

Code

App.jsx

class App extends Component {
  state = {
    redirect: null,
    errors: {},
  };

  render() {
    return (
      <Switch>
        <ProtectedRoute path="/panel" component={Panel} />

        <Route
          path="/authenticate"
          render={(props) => <Authenticate {...props} errors={this.state.errors} handleLogin={(event) => this.handleLogin(event)} />}
        />

        {this.state.redirect ? <Redirect to={this.state.redirect} /> : null}
      </Switch>
    );
  }

  {/* Left some functions out for clarity. */}
}

export default App;

Panel.jsx

class Panel extends Component {
  state = {};

  render() {
    return (

        <Container className="page-container" fluid>
          <Row>
            <Col sm={2} className="column">

                <NavLink to="/panel/dashboard" exact className="list-group-item list-group-item-action" activeClassName="active">
                  Dashboard
                </NavLink>
                <NavLink to="/panel/accounts" exact className="list-group-item list-group-item-action" activeClassName="active">
                  Accounts
                </NavLink>

            </Col>
            <Col sm={10} className="column">
              <Card className="w-100">
                <Switch>
                  <Route path="/panel/dashboard">

Dashboard

                  </Route>
                  <Route path="/panel/accounts">

Accounts

                  </Route>
                </Switch>
              </Card>
            </Col>
          </Row>
        </Container>

    );
  }
}

export default Panel;

I'm having another switch in the Panel component so I do not have to rerender the sidebar, and can just load in the proper component depending on what route the user is (is there anything wrong with doing this, or is the better way in general).

Summary

So the problem is that the components are not loaded in when navigating to /panel and clicking on the navbar.

Edit: Excuse me for some of the things I had within the code. I like to be edgy when writing my code.

Body:
You Panel component needs to receive the Router Props either you can use withRouter or pass on the Router Props from ProtectedRoute to the rendered component

class Panel extends Component {
  state = {};

  render() {
    return (
      <div id="panel" className="page-wrapper">
        <Container className="page-container" fluid>
          <Row>
            <Col sm={2} className="column">
              <div className="list-group">
                <NavLink to="/panel/dashboard" exact className="list-group-item list-group-item-action" activeClassName="active">
                  Dashboard
                </NavLink>
                <NavLink to="/panel/accounts" exact className="list-group-item list-group-item-action" activeClassName="active">
                  Accounts
                </NavLink>
              </div>
            </Col>
            <Col sm={10} className="column">
              <Card className="w-100">
                <Switch>
                  <Route path="/panel/dashboard">
                    <h1>Dashboard</h1>
                  </Route>
                  <Route path="/panel/accounts">
                    <h1>Accounts</h1>
                  </Route>
                </Switch>
              </Card>
            </Col>
          </Row>
        </Container>
      </div>
    );
  }
}

export default withRouter(Panel);