问:
htaccess, redirect virtual subdomain to URL parameter
I have a .ne.ro domain (registered in Romania) where visitors can enter with or without 'www':

http://mydomain.ne.ro

http://www.mydomain.ne.ro

I want to redirect http://123.mydomain.ne.ro to http://mydomain.ne.ro?id=123. If visitor enter with 'www|mail|ftp' must be treated as non parameter (obviously).

I tried htaccess subdomain redirct with last url parameter but didn't work.

Current code:

```<code># edited on 05/April/2011 as suggested:
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.mydomain\.ne\.ro$
RewriteCond %{HTTP_HOST} ^(.*)\.mydomain\.ne\.ro$
RewriteRule ^$ /index.php?id=%1 [R,L]
</code>```

Hosted on a hostgator's business plan (linux) and registered at nic.ro, just if asking.

答:
After many suggested code (thanks supersuphot) and a lot of research finally I found an answer.

First I added the subdomain * under mydomain.ne.ro, pointed to domain folder/path:

Then I uploaded .htaccess file with the next code:

```<code>RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.mydomain.ne.ro
RewriteCond %{HTTP_HOST} ^(.+).mydomain.ne.ro
RewriteRule ^([^/]*)$ http://mydomain.ne.ro/?id=%1 [P,L]
</code>```

this works too:

```<code>RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.mydomain\.ne\.ro$
RewriteCond %{HTTP_HOST} ^(.*)\.mydomain\.ne\.ro$
RewriteRule ^$ /index.php?id=%1 [P,L]
</code>```

The most important thing is the P instead R at last line, to keep original subdomain. Check this answer to a related question.

ContentLicense: CC BY-SA 2.5

Body:
I have a .ne.ro domain (registered in Romania) where visitors can enter with or without 'www':

http://mydomain.ne.ro

http://www.mydomain.ne.ro

I want to redirect http://123.mydomain.ne.ro to http://mydomain.ne.ro?id=123. If visitor enter with 'www|mail|ftp' must be treated as non parameter (obviously).

I tried htaccess subdomain redirct with last url parameter but didn't work.

Current code:

# edited on 05/April/2011 as suggested:
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.mydomain\.ne\.ro$
RewriteCond %{HTTP_HOST} ^(.*)\.mydomain\.ne\.ro$
RewriteRule ^$ /index.php?id=%1 [R,L]

Hosted on a hostgator's business plan (linux) and registered at nic.ro, just if asking.

Body:
After many suggested code (thanks supersuphot) and a lot of research finally I found an answer.

First I added the subdomain * under mydomain.ne.ro, pointed to domain folder/path:

Then I uploaded .htaccess file with the next code:

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.mydomain.ne.ro
RewriteCond %{HTTP_HOST} ^(.+).mydomain.ne.ro
RewriteRule ^([^/]*)$ http://mydomain.ne.ro/?id=%1 [P,L]

this works too:

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.mydomain\.ne\.ro$
RewriteCond %{HTTP_HOST} ^(.*)\.mydomain\.ne\.ro$
RewriteRule ^$ /index.php?id=%1 [P,L]

The most important thing is the P instead R at last line, to keep original subdomain. Check this answer to a related question.


来源: stackexchange

问:
Why my JS popup doesn't work on multiple element?
I'm actually creating a forum from scratch. This script create a popup when we click on remove, i make 2 button remove but only one work.
Code:

Html Code ->

```<code><!DOCTYPE html>
<html>
  <head>
    <title>Test</title>
    <link rel="stylesheet" type="text/css" href="styletest.css">
  </head>
  <body>
    <a href="#" id="remove_openpopup">remove</a>
    <a href="#" id="remove_openpopup">remove2</a>

    <div id="popup" class="popup">
      <div class="popup_content">
        <span class="close">×</span>
        <p>Are you sure you wan't delete this categorie ?</p>
        <button class="button_popup close_button">No</button>
        <button class="button_popup close_button" onclick='document.getElementById("remove").submit()'>Yes</button>
      </div>
    </div>
  </body>
</html>
</code>```

JS:

```<code>var modal = document.getElementById("popup");

var btn = document.getElementById("remove_openpopup");

var span = document.getElementsByClassName("close")[0];
var span2 = document.getElementsByClassName("close_button")[0];

btn.onclick = function() {
  modal.style.display = "block";
}

span.onclick = function() {
  modal.style.display = "none";
}

span2.onclick = function() {
  modal.style.display = "none";
}

window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}
</code>```

How can i make: when i click on remove it open my popup but remove2 open it too ?
Can you help me please ? :)

答:
Just for a sample :)
In HTML, I changed id="remove_openpopup" to class="remove_openpopup"

```<code><a href="#" class="remove_openpopup">remove</a>
<a href="#" class="remove_openpopup">remove2</a>
</code>```

In
```

ContentLicense: CC BY-SA 4.0

Body:
I'm actually creating a forum from scratch. This script create a popup when we click on remove, i make 2 button remove but only one work.
Code:

Html Code ->

<!DOCTYPE html>

    <title>Test</title>
    <link rel="stylesheet" type="text/css" href="styletest.css">

    remove
    remove2

        ×

Are you sure you wan't delete this categorie ?

        <button class="button_popup close_button">No</button>
        <button class="button_popup close_button" onclick='document.getElementById("remove").submit()'>Yes</button>

JS:

var modal = document.getElementById("popup");

var btn = document.getElementById("remove_openpopup");

var span = document.getElementsByClassName("close")[0];
var span2 = document.getElementsByClassName("close_button")[0];

btn.onclick = function() {
  modal.style.display = "block";
}

span.onclick = function() {
  modal.style.display = "none";
}

span2.onclick = function() {
  modal.style.display = "none";
}

window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

How can i make: when i click on remove it open my popup but remove2 open it too ?
Can you help me please ? :)

Body:
Just for a sample :)
In HTML, I changed id="remove_openpopup" to class="remove_openpopup"

<a href="#" class="remove_openpopup">remove</a>
<a href="#" class="remove_openpopup">remove2</a>

In <script>, I would do as below.

<script>
var modal = document.getElementById("popup");
var btns = Array.prototype.slice.call(document.querySelectorAll(".remove_openpopup"));
var span = document.getElementsByClassName("close")[0];
var span2 = document.getElementsByClassName("close_button")[0];
btns.forEach(function(btn) {
  btn.onclick = function() {
    modal.style.display = "block";
  }
});
span.onclick = function() {
  modal.style.display = "none";
}
span2.onclick = function() {
  modal.style.display = "none";
}
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}
</script>


问:
How to replace a whitespace between a group of numbers with a dot or a comma?
I have this group of numbers: 1 000 , 30 000 , 400 000 on some text files and it's a lot of them. I want to search all of this group numbers and add between them a dot or comma , like this 1,000 or this 1.000.

I know I can find them like this : \d \d\d\d, but I don't know what do next to replace that white space with a comma or a dot.

答:
If you regex flavour supports lookaround, you can do:

Find: (?<=\d)\s+(?=\d)

Replace: , or .

if it doesn't:

Find: (\d)\s+(\d)

Replace: $1,$2 or $1.$2

Both will replace a space between 2 digits with a comma or a dot


问:
Pytorch neural network (probably) does not learn
my homework is to train a network on a given data set of 3000 frogs, cats and dogs. The network I built doesn't seem to improve at all. Why is that?

The training data x_train is a numpy ndarray of shape (3000,32,32,3).

```<code>class Netz(nn.Module):
    def __init__(self):
        super(Netz, self).__init__()
        self.conv1 = nn.Conv2d(3,28,5)
        self.conv2 = nn.Conv2d(28,100,5)
        self.fc1 = nn.Linear(2500,120)
        self.fc2 = nn.Linear(120,3)

    def forward(self, x):
        x = self.conv1(x)
        x = F.max_pool2d(x,2)
        x = F.relu(x)
        x = self.conv2(x)
        x = F.max_pool2d(x,2)
        x = F.relu(x)
        x = x.view(-1,2500)
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        return F.log_softmax(x)

model = Netz()
optimizer = optim.SGD(model.parameters(), lr=0.1, momentum=0.8)

def train(epoch):
    model.train()
    avg_loss = 0
    correct = 0
    criterion = F.nll_loss
    for i in range(len(x_train)):
        optimizer.zero_grad()
        x = torch.tensor(x_train[i])
        x = x.permute(2, 0, 1)
        x = Variable(x)
        x = x.unsqueeze(0)
        target = Variable(torch.Tensor([y_train[i]]).type(torch.LongTensor))
        out = model(x)
        loss = criterion(out, target)
        avg_loss += loss
        pred = out.argmax(dim=1, keepdim=True)
        correct += pred.eq(target.view_as(pred)).sum().item()
        loss.backward()
        optimizer.step()
        if i%64==0:
            print("epoch ", epoch, " [", i, "/", len(x_train), "] average loss: ", avg_loss.item() / 64, " correct: ", correct, "/64")
            avg_loss = 0
            correct = 0
</code>```

I expect the mean error to decrease over time, but it seems to keep fluctuating around the same number...

答:
Your loss is fluctuating means your network is not powerful enough to extract meaningful embeddings. I can recommend trying one of these few things.

Add more layers.

Use a smaller learning rate.

Use a larger dataset or use a pre-trained model if you only have a small dataset.

Normalize your dataset.

Shuffle training set.

Play with hyperparameters.

Body:
my homework is to train a network on a given data set of 3000 frogs, cats and dogs. The network I built doesn't seem to improve at all. Why is that?

The training data x_train is a numpy ndarray of shape (3000,32,32,3).

class Netz(nn.Module):
    def __init__(self):
        super(Netz, self).__init__()
        self.conv1 = nn.Conv2d(3,28,5)
        self.conv2 = nn.Conv2d(28,100,5)
        self.fc1 = nn.Linear(2500,120)
        self.fc2 = nn.Linear(120,3)

    def forward(self, x):
        x = self.conv1(x)
        x = F.max_pool2d(x,2)
        x = F.relu(x)
        x = self.conv2(x)
        x = F.max_pool2d(x,2)
        x = F.relu(x)
        x = x.view(-1,2500)
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        return F.log_softmax(x)

model = Netz()
optimizer = optim.SGD(model.parameters(), lr=0.1, momentum=0.8)

def train(epoch):
    model.train()
    avg_loss = 0
    correct = 0
    criterion = F.nll_loss
    for i in range(len(x_train)):
        optimizer.zero_grad()
        x = torch.tensor(x_train[i])
        x = x.permute(2, 0, 1)
        x = Variable(x)
        x = x.unsqueeze(0)
        target = Variable(torch.Tensor([y_train[i]]).type(torch.LongTensor))
        out = model(x)
        loss = criterion(out, target)
        avg_loss += loss
        pred = out.argmax(dim=1, keepdim=True)
        correct += pred.eq(target.view_as(pred)).sum().item()
        loss.backward()
        optimizer.step()
        if i%64==0:
            print("epoch ", epoch, " [", i, "/", len(x_train), "] average loss: ", avg_loss.item() / 64, " correct: ", correct, "/64")
            avg_loss = 0
            correct = 0

I expect the mean error to decrease over time, but it seems to keep fluctuating around the same number...


问:
How to run NUnit onetimesetup multiple times for different databases
We have an integration test suite that contains numerous tests executing repository classes.

The objective is to have a [OneTimeSetup] method in the BaseTestFixture, that will create/populate each target database (Postgres/SQL Server) only once before all tests and teardown after all tests.

Got this error:

nunit OneTimeSetUp: SetUp and TearDown methods must not have parameters

How can we run the entire test suite against Postgres, SQL server and both without duplicating tests?

Thanks.

答:
Interesting question. I can't really think of an 'out-the-box' solution myself

One simple workaround would be to do two separate console runs and use the --params flag. That way, you could run a different setup for each database type, dependent on the TestParameters value passed in.

A nicer alternative may be to implement a custom attribute, which would allow you to parameterize SetUpFixtures. (There's an existing discussion on adding this feature here- although it hasn't garnered much interest since 2016.) I think it would be reasonably possible to do this as a custom attribute without modifying NUnit however.

Take a look at how SetUpFixtureAttribute is implemented. I would think you'd want to create your own IFixtureBuilder attribute which works in a similar way, except can be parameterised, and return two suites, with a different setup for each database. I think that would work, although it's not functionality I'm totally familiar with myself.


问:
How to scrape embedded links and tabular information
I'm trying to scrape information about the datasets available on this website.

I want to collect the URLs to the resources and at least the title of the dataset.

Using this resource as an example, I want to capture the URL embedded in "Go to resource" and the title listed in the table:

I have created a basic scraper, but it doesn't seem work:

```<code>import requests
import csv
from bs4 import BeautifulSoup

site = requests.get('https://data.nsw.gov.au/data/dataset');
data_list=[]

if site.status_code is 200:
    content = BeautifulSoup(site.content, 'html.parser')
    internals = content.select('.resource-url-analytics')
    for url in internals:
        title = internals.select=('.resource-url-analytics')[0].get_text()
        link = internals.select=('.resource-url-analytics')[0].get('href')
        new_data = {"title": title, "link": link}
        data_list.append(new_data)
    with open ('selector.csv','w') as file:
            writer = csv.DictWriter(file, fieldnames = ["dataset", "link"], delimiter = ';')
            writer.writeheader()
            for row in data_list:
                writer.writerow(row)
</code>```

I would like to write the output to a CSV with columns for the URLs and the titles.

This is an example of the desired output

Greatly appreciative for any assistance

答:
Have a look at the API for the datasets that will likely be the easiest way to do this.

In the meantime, here is how you can get the API links at id level from those pages and store the entire package info for all packages in one list, data_sets, and just the info of interest in another variable (results).  Be sure to review the API documentation in case there is a better method - for example, it would be nice if ids could be submitted in batches rather than per id.

Answer below is taking advantage of the endpoint detailed in the documentation which is used to get a full JSON representation of a dataset, resource or other object

Taking the current first result on landing page of:

Vegetation of the Guyra 1:25000 map sheet VIS_ID 240.

We want the last child a of parent h3 with a parent having class .dataset-item. In the below, the spaces between selectors are descendant combinators.

```<code>.dataset-item h3 a:last-child
</code>```

You can shorten this to h3 a:last-child  for a small efficiency gain.

This relationship reliably selects all relevant links on page.

Continuing with this example, visiting that retrieved url for first listed item, we can find the id using api endpoint (which retrieves json related to this package), via an attribute=value selector with contains, *, operator. We know this particular api endpoint has a common string so we substring match on the href attribute value:

```<code>[href*="/api/3/action/package_show?id="]
</code>```

The domain can vary and some retrieved links are relative so we have to test if relative and add the appropriate domain.

First page html for that match:

Notes:

data_sets is a list containing all the package data for each package and is extensive. I did this in case you are interest in looking at what is in those packages (besides reviewing the API documentation)

You can get total number of pages from soup object on a page via

```<code>   num_pages = int(soup.select('[href^="/data/dataset?page="]')[-2].text)
</code>```

You can alter the loop for less pages.

Session object is used for efficiency of re-using connection. I'm sure there are other improvements to be made. In particular I would look for any method which reduced the number of requests (why I mentioned looking for a batch id endpoint for example).

There can be none to more than one resource url within a returned package. See example here. You can edit code to handle this.

Python:

```<code>from bs4 import BeautifulSoup as bs
import requests
import csv
from urllib.parse import urlparse

json_api_links = []
data_sets = []

def get_links(s, url, css_selector):
    r = s.get(url)
    soup = bs(r.content, 'lxml')
    base = '{uri.scheme}://{uri.netloc}'.format(uri=urlparse(url))
    links = [base + item['href'] if item['href'][0] == '/' else item['href'] for item in soup.select(css_selector)]
    return links

results = []
#debug = []
with requests.Session() as s:

    for page in range(1,2):  #you decide how many pages to loop

        links = get_links(s, 'https://data.nsw.gov.au/data/dataset?page={}'.format(page), '.dataset-item h3 a:last-child')

        for link in links:
            data = get_links(s, link, '[href*="/api/3/action/package_show?id="]')
            json_api_links.append(data)
            #debug.append((link, data))
    resources = list(set([item.replace('opendata','') for sublist in json_api_links for item in sublist])) #can just leave as set

    for link in resources:
        try:
            r = s.get(link).json()  #entire package info
            data_sets.append(r)
            title = r['result']['title'] #certain items

            if 'resources' in r['result']:
                urls = ' , '.join([item['url'] for item in r['result']['resources']])
            else:
                urls = 'N/A'
        except:
            title = 'N/A'
            urls = 'N/A'
        results.append((title, urls))

    with open('data.csv','w', newline='') as f:
        w = csv.writer(f)
        w.writerow(['Title','Resource Url'])
        for row in results:
            w.writerow(row)
</code>```

All pages

(very long running so consider threading/asyncio):

```<code>from bs4 import BeautifulSoup as bs
import requests
import csv
from urllib.parse import urlparse

json_api_links = []
data_sets = []

def get_links(s, url, css_selector):
    r = s.get(url)
    soup = bs(r.content, 'lxml')
    base = '{uri.scheme}://{uri.netloc}'.format(uri=urlparse(url))
    links = [base + item['href'] if item['href'][0] == '/' else item['href'] for item in soup.select(css_selector)]
    return links

results = []
#debug = []

with requests.Session() as s:
    r = s.get('https://data.nsw.gov.au/data/dataset')
    soup = bs(r.content, 'lxml')
    num_pages = int(soup.select('[href^="/data/dataset?page="]')[-2].text)
    links = [item['href'] for item in soup.select('.dataset-item h3 a:last-child')]

    for link in links:
        data = get_links(s, link, '[href*="/api/3/action/package_show?id="]')
        json_api_links.append(data)
        #debug.append((link, data))
    if num_pages > 1:
        for page in range(1, num_pages + 1):  #you decide how many pages to loop

            links = get_links(s, 'https://data.nsw.gov.au/data/dataset?page={}'.format(page), '.dataset-item h3 a:last-child')

            for link in links:
                data = get_links(s, link, '[href*="/api/3/action/package_show?id="]')
                json_api_links.append(data)
                #debug.append((link, data))

        resources = list(set([item.replace('opendata','') for sublist in json_api_links for item in sublist])) #can just leave as set

        for link in resources:
            try:
                r = s.get(link).json()  #entire package info
                data_sets.append(r)
                title = r['result']['title'] #certain items

                if 'resources' in r['result']:
                    urls = ' , '.join([item['url'] for item in r['result']['resources']])
                else:
                    urls = 'N/A'
            except:
                title = 'N/A'
                urls = 'N/A'
            results.append((title, urls))

    with open('data.csv','w', newline='') as f:
        w = csv.writer(f)
        w.writerow(['Title','Resource Url'])
        for row in results:
            w.writerow(row)
</code>```

Body:
I'm trying to scrape information about the datasets available on this website.

I want to collect the URLs to the resources and at least the title of the dataset.

Using this resource as an example, I want to capture the URL embedded in "Go to resource" and the title listed in the table:

I have created a basic scraper, but it doesn't seem work:

import requests
import csv
from bs4 import BeautifulSoup

site = requests.get('https://data.nsw.gov.au/data/dataset');
data_list=[]

if site.status_code is 200:
    content = BeautifulSoup(site.content, 'html.parser')
    internals = content.select('.resource-url-analytics')
    for url in internals:
        title = internals.select=('.resource-url-analytics')[0].get_text()
        link = internals.select=('.resource-url-analytics')[0].get('href')
        new_data = {"title": title, "link": link}
        data_list.append(new_data)
    with open ('selector.csv','w') as file:
            writer = csv.DictWriter(file, fieldnames = ["dataset", "link"], delimiter = ';')
            writer.writeheader()
            for row in data_list:
                writer.writerow(row)

I would like to write the output to a CSV with columns for the URLs and the titles.

This is an example of the desired output

Greatly appreciative for any assistance

Body:
Have a look at the API for the datasets that will likely be the easiest way to do this.

In the meantime, here is how you can get the API links at id level from those pages and store the entire package info for all packages in one list, data_sets, and just the info of interest in another variable (results).  Be sure to review the API documentation in case there is a better method - for example, it would be nice if ids could be submitted in batches rather than per id.

Answer below is taking advantage of the endpoint detailed in the documentation which is used to get a full JSON representation of a dataset, resource or other object

Taking the current first result on landing page of:

Vegetation of the Guyra 1:25000 map sheet VIS_ID 240.

We want the last child a of parent h3 with a parent having class .dataset-item. In the below, the spaces between selectors are descendant combinators.

.dataset-item h3 a:last-child

You can shorten this to h3 a:last-child  for a small efficiency gain.

This relationship reliably selects all relevant links on page.

Continuing with this example, visiting that retrieved url for first listed item, we can find the id using api endpoint (which retrieves json related to this package), via an attribute=value selector with contains, *, operator. We know this particular api endpoint has a common string so we substring match on the href attribute value:

[href*="/api/3/action/package_show?id="]

The domain can vary and some retrieved links are relative so we have to test if relative and add the appropriate domain.

First page html for that match:

Notes:

data_sets is a list containing all the package data for each package and is extensive. I did this in case you are interest in looking at what is in those packages (besides reviewing the API documentation)

You can get total number of pages from soup object on a page via

   num_pages = int(soup.select('[href^="/data/dataset?page="]')[-2].text)

You can alter the loop for less pages.

Session object is used for efficiency of re-using connection. I'm sure there are other improvements to be made. In particular I would look for any method which reduced the number of requests (why I mentioned looking for a batch id endpoint for example).

There can be none to more than one resource url within a returned package. See example here. You can edit code to handle this.

Python:

from bs4 import BeautifulSoup as bs
import requests
import csv
from urllib.parse import urlparse

json_api_links = []
data_sets = []

def get_links(s, url, css_selector):
    r = s.get(url)
    soup = bs(r.content, 'lxml')
    base = '{uri.scheme}://{uri.netloc}'.format(uri=urlparse(url))
    links = [base + item['href'] if item['href'][0] == '/' else item['href'] for item in soup.select(css_selector)]
    return links

results = []
#debug = []
with requests.Session() as s:

    for page in range(1,2):  #you decide how many pages to loop

        links = get_links(s, 'https://data.nsw.gov.au/data/dataset?page={}'.format(page), '.dataset-item h3 a:last-child')

        for link in links:
            data = get_links(s, link, '[href*="/api/3/action/package_show?id="]')
            json_api_links.append(data)
            #debug.append((link, data))
    resources = list(set([item.replace('opendata','') for sublist in json_api_links for item in sublist])) #can just leave as set

    for link in resources:
        try:
            r = s.get(link).json()  #entire package info
            data_sets.append(r)
            title = r['result']['title'] #certain items

            if 'resources' in r['result']:
                urls = ' , '.join([item['url'] for item in r['result']['resources']])
            else:
                urls = 'N/A'
        except:
            title = 'N/A'
            urls = 'N/A'
        results.append((title, urls))

    with open('data.csv','w', newline='') as f:
        w = csv.writer(f)
        w.writerow(['Title','Resource Url'])
        for row in results:
            w.writerow(row)

All pages

(very long running so consider threading/asyncio):

from bs4 import BeautifulSoup as bs
import requests
import csv
from urllib.parse import urlparse

json_api_links = []
data_sets = []

def get_links(s, url, css_selector):
    r = s.get(url)
    soup = bs(r.content, 'lxml')
    base = '{uri.scheme}://{uri.netloc}'.format(uri=urlparse(url))
    links = [base + item['href'] if item['href'][0] == '/' else item['href'] for item in soup.select(css_selector)]
    return links

results = []
#debug = []

with requests.Session() as s:
    r = s.get('https://data.nsw.gov.au/data/dataset')
    soup = bs(r.content, 'lxml')
    num_pages = int(soup.select('[href^="/data/dataset?page="]')[-2].text)
    links = [item['href'] for item in soup.select('.dataset-item h3 a:last-child')]

    for link in links:
        data = get_links(s, link, '[href*="/api/3/action/package_show?id="]')
        json_api_links.append(data)
        #debug.append((link, data))
    if num_pages > 1:
        for page in range(1, num_pages + 1):  #you decide how many pages to loop

            links = get_links(s, 'https://data.nsw.gov.au/data/dataset?page={}'.format(page), '.dataset-item h3 a:last-child')

            for link in links:
                data = get_links(s, link, '[href*="/api/3/action/package_show?id="]')
                json_api_links.append(data)
                #debug.append((link, data))

        resources = list(set([item.replace('opendata','') for sublist in json_api_links for item in sublist])) #can just leave as set

        for link in resources:
            try:
                r = s.get(link).json()  #entire package info
                data_sets.append(r)
                title = r['result']['title'] #certain items

                if 'resources' in r['result']:
                    urls = ' , '.join([item['url'] for item in r['result']['resources']])
                else:
                    urls = 'N/A'
            except:
                title = 'N/A'
                urls = 'N/A'
            results.append((title, urls))

    with open('data.csv','w', newline='') as f:
        w = csv.writer(f)
        w.writerow(['Title','Resource Url'])
        for row in results:
            w.writerow(row)


问:
How to split a large Excel file into multiple small files in SSIS?
I want to read an Excel file which is 250 Mb large and has more than 300 000 rows. So when I try to process it in Excel source in SSIS it takes too much time and at last fails to process. Can anyone tell me how to split the big file into small ones or any other method that can help?</p>

答:
SQLCMD is better because timeout is MUCH longer. But than you have to save your Excel as CSV, and I do not know if that's possible for your.

If you have a CSV file (i.e. BulkDataFile.csv) and you create a file like this:

```<code>BULK INSERT dbo.TableForBulkData
FROM 'C:\BulkDataFile.csv'
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
</code>```

Then you can use SQLCMD -E -I import.sql  (of you have save the file as import.sql)

Body:
SQLCMD is better because timeout is MUCH longer. But than you have to save your Excel as CSV, and I do not know if that's possible for your.

If you have a CSV file (i.e. BulkDataFile.csv) and you create a file like this:

BULK INSERT dbo.TableForBulkData
FROM 'C:\BulkDataFile.csv'
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)

Then you can use SQLCMD -E -I import.sql  (of you have save the file as import.sql)


问:
How to delete letters only when they form a word (i.e &Co.) and not when they are part of an word (Co-nstruction)
I have to cleanup a column with Companies names by removing Inc, Ltd, &Co, Co, Corp, . , $, &, etc, and the list can be updated later on.

In Sql server 2016 I used Replace but it will replace everywhere those letters not only when they form a specific word, ex: name Co.

```<code>alter table [CompanyList] add CleanLegalName as
    cast (Rtrim( Replace (Replace (Replace (Replace (Replace (Replace (Replace (Replace (REPLACE
        ([Legal Name], ' INC', ''), '.', ''), ' LTD', ''), ' Inc', ''), ' Ltd', ''), ' LIMITED', ''), ' INCOPORATED' ,'') , ',' , '') , ' CO', '')
      ) as varchar(200))
</code>```

The problem is Replace will replace everywhere these letters, like: 'Jane Construction' with 'Jane nstruction' , 'Inca Food' with 'a Food'. How can I remove these letters only when they form a word by themselves and not as part of other word ?
Thank you

答:
Let's say that we have the following scenario

```<code>    CREATE TABLE #Temp([Legal Name] NVARCHAR(MAX))

    INSERT INTO #Temp ([Legal Name]) VALUES ('Beer Acme Co.')
    INSERT INTO #Temp ([Legal Name]) VALUES ('Company of Brothers Co')
    INSERT INTO #Temp ([Legal Name]) VALUES ('My Star Inc.')
    INSERT INTO #Temp ([Legal Name]) VALUES ('Incredible Monsters INC')
    INSERT INTO #Temp ([Legal Name]) VALUES ('Limit Is The Sky Ltd')
    INSERT INTO #Temp ([Legal Name]) VALUES ('Limit Is The Universe Ltd.')
    INSERT INTO #Temp ([Legal Name]) VALUES ('Unlimited Minds Limited.')
    INSERT INTO #Temp ([Legal Name]) VALUES ('Unlimited Borders Limited')
</code>```

I can propose two ways to try help you.

Option 1

Via Scalar-Valued Function

```<code>    CREATE FUNCTION [dbo].[GetClearedName](@VALUE NVARCHAR(MAX))
    RETURNS NVARCHAR(MAX)
    AS
        BEGIN

            DECLARE @PATTERN NVARCHAR(MAX)
            DECLARE @TEMP TABLE ([PATTERN] NVARCHAR(MAX))

            INSERT INTO @TEMP ([PATTERN]) VALUES ('%Co.')
            INSERT INTO @TEMP ([PATTERN]) VALUES ('% Co%')
            INSERT INTO @TEMP ([PATTERN]) VALUES ('%Inc.')
            INSERT INTO @TEMP ([PATTERN]) VALUES ('% Inc')
            INSERT INTO @TEMP ([PATTERN]) VALUES ('% Ltd')
            INSERT INTO @TEMP ([PATTERN]) VALUES ('%Ltd.')
            INSERT INTO @TEMP ([PATTERN]) VALUES ('%Limited.')
            INSERT INTO @TEMP ([PATTERN]) VALUES ('% Limited')

            DECLARE @RESULT NVARCHAR(MAX)

            SET @RESULT = @VALUE

            DECLARE PATTERN_CURSOR CURSOR FOR SELECT [PATTERN] FROM @TEMP

            OPEN PATTERN_CURSOR
            FETCH NEXT FROM PATTERN_CURSOR INTO @PATTERN

            WHILE (@@FETCH_STATUS = 0)
                BEGIN

                    IF (PATINDEX(@PATTERN, @RESULT) > 0)
                        BEGIN
                            SET @RESULT = SUBSTRING(@RESULT, 0, PATINDEX(@PATTERN, @RESULT))
                        END

                    FETCH NEXT FROM PATTERN_CURSOR INTO @PATTERN
                END

            CLOSE PATTERN_CURSOR
            DEALLOCATE PATTERN_CURSOR

            IF (LEN(@RESULT) <> 0)
                RETURN @RESULT

            Return @VALUE
        END
</code>```

You can use the function that way:

```<code>    SELECT [dbo].[GetClearedName]([Legal Name]) FROM #Temp

    DROP TABLE #Temp
</code>```

Option 2

Using #SQL, also this can be converted into a function.

```<code>    SELECT [Legal Name],
        SQL#.RegEx_Replace4k(
            SQL#.RegEx_Replace4k(
                SQL#.RegEx_Replace4k(
                    SQL#.RegEx_Replace4k([Legal Name], N'(CO+\.|\sCO$)', N' ', -1, 1, 'IgnoreCase'),
                                                            N'(INC+\.|\sINC$)', N' ', -1, 1, 'IgnoreCase'),
                                                                    N'(LTD+\.|\sLTD$)', N' ', -1, 1, 'IgnoreCase'),
                                                                        N'(Limited+\.|\sLimited$)', N' ', -1, 1, 'IgnoreCase')
        As [Cleared Name]
    FROM
        #Temp

    DROP TABLE #Temp
</code>```

Expected results

Body:
I have to cleanup a column with Companies names by removing Inc, Ltd, &Co, Co, Corp, . , $, &, etc, and the list can be updated later on.

In Sql server 2016 I used Replace but it will replace everywhere those letters not only when they form a specific word, ex: name Co.

alter table [CompanyList] add CleanLegalName as
    cast (Rtrim( Replace (Replace (Replace (Replace (Replace (Replace (Replace (Replace (REPLACE
        ([Legal Name], ' INC', ''), '.', ''), ' LTD', ''), ' Inc', ''), ' Ltd', ''), ' LIMITED', ''), ' INCOPORATED' ,'') , ',' , '') , ' CO', '')
      ) as varchar(200))

The problem is Replace will replace everywhere these letters, like: 'Jane Construction' with 'Jane nstruction' , 'Inca Food' with 'a Food'. How can I remove these letters only when they form a word by themselves and not as part of other word ?
Thank you

Body:
Let's say that we have the following scenario

    CREATE TABLE #Temp([Legal Name] NVARCHAR(MAX))

    INSERT INTO #Temp ([Legal Name]) VALUES ('Beer Acme Co.')
    INSERT INTO #Temp ([Legal Name]) VALUES ('Company of Brothers Co')
    INSERT INTO #Temp ([Legal Name]) VALUES ('My Star Inc.')
    INSERT INTO #Temp ([Legal Name]) VALUES ('Incredible Monsters INC')
    INSERT INTO #Temp ([Legal Name]) VALUES ('Limit Is The Sky Ltd')
    INSERT INTO #Temp ([Legal Name]) VALUES ('Limit Is The Universe Ltd.')
    INSERT INTO #Temp ([Legal Name]) VALUES ('Unlimited Minds Limited.')
    INSERT INTO #Temp ([Legal Name]) VALUES ('Unlimited Borders Limited')

I can propose two ways to try help you.

Option 1

Via Scalar-Valued Function

    CREATE FUNCTION [dbo].[GetClearedName](@VALUE NVARCHAR(MAX))
    RETURNS NVARCHAR(MAX)
    AS
        BEGIN

            DECLARE @PATTERN NVARCHAR(MAX)
            DECLARE @TEMP TABLE ([PATTERN] NVARCHAR(MAX))

            INSERT INTO @TEMP ([PATTERN]) VALUES ('%Co.')
            INSERT INTO @TEMP ([PATTERN]) VALUES ('% Co%')
            INSERT INTO @TEMP ([PATTERN]) VALUES ('%Inc.')
            INSERT INTO @TEMP ([PATTERN]) VALUES ('% Inc')
            INSERT INTO @TEMP ([PATTERN]) VALUES ('% Ltd')
            INSERT INTO @TEMP ([PATTERN]) VALUES ('%Ltd.')
            INSERT INTO @TEMP ([PATTERN]) VALUES ('%Limited.')
            INSERT INTO @TEMP ([PATTERN]) VALUES ('% Limited')

            DECLARE @RESULT NVARCHAR(MAX)

            SET @RESULT = @VALUE

            DECLARE PATTERN_CURSOR CURSOR FOR SELECT [PATTERN] FROM @TEMP

            OPEN PATTERN_CURSOR
            FETCH NEXT FROM PATTERN_CURSOR INTO @PATTERN

            WHILE (@@FETCH_STATUS = 0)
                BEGIN

                    IF (PATINDEX(@PATTERN, @RESULT) > 0)
                        BEGIN
                            SET @RESULT = SUBSTRING(@RESULT, 0, PATINDEX(@PATTERN, @RESULT))
                        END

                    FETCH NEXT FROM PATTERN_CURSOR INTO @PATTERN
                END

            CLOSE PATTERN_CURSOR
            DEALLOCATE PATTERN_CURSOR

            IF (LEN(@RESULT) <> 0)
                RETURN @RESULT

            Return @VALUE
        END

You can use the function that way:

    SELECT [dbo].[GetClearedName]([Legal Name]) FROM #Temp

    DROP TABLE #Temp

Option 2

Using #SQL, also this can be converted into a function.

    SELECT [Legal Name],
        SQL#.RegEx_Replace4k(
            SQL#.RegEx_Replace4k(
                SQL#.RegEx_Replace4k(
                    SQL#.RegEx_Replace4k([Legal Name], N'(CO+\.|\sCO$)', N' ', -1, 1, 'IgnoreCase'),
                                                            N'(INC+\.|\sINC$)', N' ', -1, 1, 'IgnoreCase'),
                                                                    N'(LTD+\.|\sLTD$)', N' ', -1, 1, 'IgnoreCase'),
                                                                        N'(Limited+\.|\sLimited$)', N' ', -1, 1, 'IgnoreCase')
        As [Cleared Name]
    FROM
        #Temp

    DROP TABLE #Temp

Expected results


问:
How to call javascript function multiple times?
I am using an API from OpenWeatherMap on my website to show weather condition of just some specific places only, altogether in one page.
Here's the code:

  <input type="hidden" name="name" value="dehradun" id="cityName">
  <button onclick="getWeather()">Get weather of Dehradun</button>

  <input type="hidden" name="name" value="pune" id="cityName">
  <button onclick="getWeather()">Get weather of Pune</button> '

```

Suppose if i want to show weather condition of two places using the same Javascript function then its showing the same result for both the places(Of place (Dehradun) mentioned first in code).

Help me solve this problem.

答:
You can Pass both your city name and div (display results) as function parameter

 function getWeather(cityName, className)
 {

  $('.'+className+'').html('');

  var apiCall= 'http://api.openweathermap.org/data/2.5/weather?q=' + cityName + '&mode=json&units=metric&appid=d3d913fca612366a61837ea39a622480';
  $.getJSON(apiCall,weatherCallback);

  function weatherCallback(weatherData)
  {
    var cityName= weatherData.name;;
    var country= weatherData.sys.country;
    var description= weatherData.weather[0].description;
    var temp= weatherData.main.temp;

     $('.'+className+'').append("The Weather in " + cityName + " " + country + " is currently " + description + " with temperature: " + temp);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.jquery.com/jquery-3.0.0.js"></script>

<body>
<button onclick="getWeather('dehradun','wr1')">Get weather of Dehradun</button>
<br><br>
<div class="wr1"></div>
<br><br>
<button onclick="getWeather('pune','wr2')">Get weather of Pune</button>
<br><br>
<div class="wr2"></div>
<br>
</body></code>```

Body:
I am using an API from OpenWeatherMap on my website to show weather condition of just some specific places only, altogether in one page.
Here's the code:

  <input type="hidden" name="name" value="dehradun" id="cityName">
  <button onclick="getWeather()">Get weather of Dehradun</button>

  <input type="hidden" name="name" value="pune" id="cityName">
  <button onclick="getWeather()">Get weather of Pune</button> '

Suppose if i want to show weather condition of two places using the same Javascript function then its showing the same result for both the places(Of place (Dehradun) mentioned first in code).

Help me solve this problem.

Body:
You can Pass both your city name and div (display results) as function parameter

 function getWeather(cityName, className)
 {

  $('.'+className+'').html('');

  var apiCall= 'http://api.openweathermap.org/data/2.5/weather?q=' + cityName + '&mode=json&units=metric&appid=d3d913fca612366a61837ea39a622480';
  $.getJSON(apiCall,weatherCallback);

  function weatherCallback(weatherData)
  {
    var cityName= weatherData.name;;
    var country= weatherData.sys.country;
    var description= weatherData.weather[0].description;
    var temp= weatherData.main.temp;

     $('.'+className+'').append("The Weather in " + cityName + " " + country + " is currently " + description + " with temperature: " + temp);
  }
}

<script src="https://code.jquery.com/jquery-3.0.0.js"></script>

<body>
<button onclick="getWeather('dehradun','wr1')">Get weather of Dehradun</button>
<br><br>
<div class="wr1"></div>
<br><br>
<button onclick="getWeather('pune','wr2')">Get weather of Pune</button>
<br><br>
<div class="wr2"></div>
<br>
</body>


问:
How to draw a dragged and droppped image on to a canvas
I drag and drop images on to a canvas using below code . Can someone please tell me how to draw it on a canvas? Thanks in advance.Earlier my canvas used to be a div and I used to append img to that div and it worked.But now I want it to be drawn to a canvas.</p>

```<code>function dropb(ev) {
  ev.preventDefault();
  const dt = ev.dataTransfer;
  const files = dt.files;

  handleFilesb(files);
}

function handleFilesb(files) {
  for (let i = 0; i < files.length; i++) {
    const file = files[i];

    if (!file.type.startsWith('image/')) {
      continue
    }

    const img = document.createElement("img");
    img.className = "my_image";
    img.setAttribute("width", "300px");
    img.setAttribute("height", "300px");

    img.classList.add("obj");
    img.file = file;

    document.getElementById("area_c"); // canvas
    var ctx = c.getContext("2d");

    ctx.drawImage(img, 10, 10); // this line is not working

    const reader = new FileReader();
    reader.onload = (function(aImg) {
      return function(e) {
        aImg.src = e.target.result;
      };
    })(img);
    reader.readAsDataURL(file);
  }
}

             <div style="display:flex">
                           <canvas id ="area_c" style="width:300px;height:300px;border:3px solid black;z-index:1"  ondrop="dropb(event)"  ondragover="myfkb(event)"   >

                           </canvas>

                            <div  id ="area_c2" style="width:300px;height:300px;border:3px solid black;z-index:1"  >

                            </div>

                            <div >

                                <input type="button"   value="Crop"
                             onclick="crop()">

                            </div>

                   </div>
</code>```

答:
ctx.drawImage(img) comes before img.src... There is no way your image gets drawn.

You need to wait until it loads, and that will be only after the FileReader onload event fired, and even after the img's onload fires:

```<code>img.onload = e => {
  ctx.drawImage(img, 10, 10);
};
const reader = new FileReader();
reader.onload = (function(aImg) {
  return function(e) {
    aImg.src = e.target.result;
  };
})(img);
reader.readAsDataURL(file);
</code>```

But you don't need the FileReader here, use a blob URL instead:

```<code>img.onload = e => {
  ctx.drawImage(img, 10, 10);
};
img.src = URL.createObjetURL(file);
</code>```

const c = document.getElementById("area_c");
c.ondragover = e => {
  e.preventDefault();
}
c.ondrop = dropb;
const ctx = c.getContext("2d");

function dropb(ev) {
  ev.preventDefault();
  const dt = ev.dataTransfer;
  const files = dt.files;

  handleFilesb(files);
}

function handleFilesb(files) {
  for (let i = 0; i < files.length; i++) {
    const file = files[i];

    if (!file.type.startsWith('image/')) {
      continue
    }

    const img = document.createElement("img");
    img.className = "my_image";
    img.setAttribute("width", "300px");
    img.setAttribute("height", "300px");

    img.classList.add("obj");
    img.file = file;
    img.onload = e => {
      ctx.drawImage(img, 10, 10);
    };
    img.src = URL.createObjectURL(file);
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas {
  border: 1px solid
}</code>```

<canvas id="area_c">

</canvas>```

Body:
I drag and drop images on to a canvas using below code . Can someone please tell me how to draw it on a canvas? Thanks in advance.Earlier my canvas used to be a div and I used to append img to that div and it worked.But now I want it to be drawn to a canvas.

function dropb(ev) {
  ev.preventDefault();
  const dt = ev.dataTransfer;
  const files = dt.files;

  handleFilesb(files);
}

function handleFilesb(files) {
  for (let i = 0; i < files.length; i++) {
    const file = files[i];

    if (!file.type.startsWith('image/')) {
      continue
    }

    const img = document.createElement("img");
    img.className = "my_image";
    img.setAttribute("width", "300px");
    img.setAttribute("height", "300px");

    img.classList.add("obj");
    img.file = file;

    document.getElementById("area_c"); // canvas
    var ctx = c.getContext("2d");

    ctx.drawImage(img, 10, 10); // this line is not working

    const reader = new FileReader();
    reader.onload = (function(aImg) {
      return function(e) {
        aImg.src = e.target.result;
      };
    })(img);
    reader.readAsDataURL(file);
  }
}

                           <canvas id ="area_c" style="width:300px;height:300px;border:3px solid black;z-index:1"  ondrop="dropb(event)"  ondragover="myfkb(event)"   >

                           </canvas>

                                <input type="button"   value="Crop"
                             onclick="crop()">

Body:
ctx.drawImage(img) comes before img.src... There is no way your image gets drawn.

You need to wait until it loads, and that will be only after the FileReader onload event fired, and even after the img's onload fires:

img.onload = e => {
  ctx.drawImage(img, 10, 10);
};
const reader = new FileReader();
reader.onload = (function(aImg) {
  return function(e) {
    aImg.src = e.target.result;
  };
})(img);
reader.readAsDataURL(file);

But you don't need the FileReader here, use a blob URL instead:

img.onload = e => {
  ctx.drawImage(img, 10, 10);
};
img.src = URL.createObjetURL(file);

const c = document.getElementById("area_c");
c.ondragover = e => {
  e.preventDefault();
}
c.ondrop = dropb;
const ctx = c.getContext("2d");

function dropb(ev) {
  ev.preventDefault();
  const dt = ev.dataTransfer;
  const files = dt.files;

  handleFilesb(files);
}

function handleFilesb(files) {
  for (let i = 0; i < files.length; i++) {
    const file = files[i];

    if (!file.type.startsWith('image/')) {
      continue
    }

    const img = document.createElement("img");
    img.className = "my_image";
    img.setAttribute("width", "300px");
    img.setAttribute("height", "300px");

    img.classList.add("obj");
    img.file = file;
    img.onload = e => {
      ctx.drawImage(img, 10, 10);
    };
    img.src = URL.createObjectURL(file);
  }
}

canvas {
  border: 1px solid
}

<canvas id="area_c">

</canvas>


问:
How to redirect from old domain to new domain on nginx
I currently have a domain https://dongyhuynhtantrieu.com and now I want to convert it to https://bacsicare.com, how do I do it? I'm currently using wordpress and nginx. I tried the code but it didn't work.

```<code>server {
server_name www.example.com;
rewrite ^ http://example.com$request_uri? permanent;
</code>```

}

答:
You can use return:

```<code>server {
    listen 80;
    server_name old_domain.com www.old_domain.com;
    return 301 http://new_domain.com$request_uri?;
}
</code>```

Or if inside server block:

```<code>if ($request_uri  =  / )  {
      rewrite (.*) http://new_domain.com/ permanent;
  }
</code>```

Body:
I currently have a domain https://dongyhuynhtantrieu.com and now I want to convert it to https://bacsicare.com, how do I do it? I'm currently using wordpress and nginx. I tried the code but it didn't work.

server {
server_name www.example.com;
rewrite ^ http://example.com$request_uri? permanent;

}

Body:
You can use return:

server {
    listen 80;
    server_name old_domain.com www.old_domain.com;
    return 301 http://new_domain.com$request_uri?;
}

Or if inside server block:

if ($request_uri  =  / )  {
      rewrite (.*) http://new_domain.com/ permanent;
  }


问:
Plotting times versus dates while skipping unwanted dates in Python
I want to make a program that monitors my 5000 meters progress. Inspired by this and this, I tried to make it work by combining some of the answers without any luck.

```<code>from __future__ import division
from matplotlib import pyplot as plt
from matplotlib.ticker import FuncFormatter
import matplotlib.dates as mdates
import numpy as np
import datetime as dt

def equidate_ax(fig, ax, dates, fmt="%d.%m.%Y", label="Date"):
    N = len(dates)
    def format_date(index, pos):
        index = np.clip(int(index + 0.5), 0, N - 1)
        return dates[index].strftime(fmt)
    ax.xaxis.set_major_formatter(FuncFormatter(format_date))
    ax.set_xlabel(label)
    fig.autofmt_xdate()

def DistVel2Time(distance, velocity_kph):
    velocity_ms = velocity_kph / 3.6
    time_sec = distance / velocity_ms
    hours = int(time_sec//3600)
    minutes = int((time_sec%3600)//60)
    seconds = int(time_sec%60)
    return "{:02d}:{:02d}".format(minutes, seconds)

times = [DistVel2Time(a, b) for a, b in [(5000, 13), (5000, 15), (5000, 14)]]

dates = [dt.datetime(year, month, day) for year, month, day in [(2019,2,1), (2019,2,2), (2019,2,7)]]

fig_1, ax_1 = plt.subplots()
ax_1.plot(dates, times, 'o--')
ax_1.xaxis_date()
ax_1.xaxis.set_major_formatter(mdates.DateFormatter('%d.%m.%Y'))
#ax_1.yaxis_date()
#ax_1.yaxis.set_major_formatter(mdates.DateFormatter("%M:%S"))
fig_1.autofmt_xdate()
plt.show()

fig_2, ax_2 = plt.subplots()
ax_2.plot(dates, times, 'D--')
ax_2.xaxis_date()
ax_2.xaxis.set_major_formatter(mdates.DateFormatter('%d.%m.%Y'))
equidate_ax(fig_2, ax_2, dates)
plt.show()

fig_1.savefig('fig1.png')
fig_2.savefig('fig2.png')
</code>```

I stole the equidate_ax from @ascripter (from the second link) because I would like to skip all dates that I do not run.

If I run this piece of code, and save the figures, I end up getting the following two figures that are rather strange, as the y-axis does not distinguish between lower or higher values (Figures 1 and 2), and the x-axis for Figure 2 is repeating itself.

Figure 1: fig_1 from the code above.

Figure 2: fig_2 from the code above.

Why is not the y-axis plotting correctly in terms of lower or higher values?

How can I prevent the equidate_ax function from repeating itself and rather skip the unwanted dates?

If anyone could help cleaning up my mess, I would be grateful.

答:
Combining the answers from the questions linked:

You basically have to make sure that matplotlib cannot guess the format of the x-axis but can guess the format of the y-axis.
With this matplotlib will not try to be smart and add dates you do not want to display on the x-axis but at the same time will be smart and sort the times for you on the y-axis.

from __future__ import division
from matplotlib import pyplot as plt
from matplotlib.ticker import FuncFormatter
import matplotlib.dates as mdates
import numpy as np
import datetime as dt

def DistVel2Time(distance, velocity_kph):
    velocity_ms = velocity_kph / 3.6
    time_sec = distance / velocity_ms
    hours = int(time_sec//3600)
    minutes = int((time_sec%3600)//60)
    seconds = int(time_sec%60)
    # note that I return a timedelta object here
    return dt.timedelta(minutes=minutes, seconds=seconds)

# we have to choose a interpretable data-type here, simply take the total time needed in seconds
times = [ DistVel2Time(a, b).total_seconds() for a, b in [(5000, 13), (5000, 15), (5000, 14)]]

# here we want to make sure that matplotlib cannot interpret it so we use strings directly
# change the format as required
dates = [ "%00d.%00d.%000d" % ymd for ymd in [(2019,2,1), (2019,2,2), (2019,2,7)]]

# the formatting function taken from https://stackoverflow.com/questions/48294332/plot-datetime-timedelta-using-matplotlib-and-python
def format_func(x, pos):
    hours = int(x//3600)
    minutes = int((x%3600)//60)
    seconds = int(x%60)

    return "{:d}:{:02d}:{:02d}".format(hours, minutes, seconds)

formatter = FuncFormatter(format_func)

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

ax.plot(dates, times, 'o--')
ax.yaxis.set_major_formatter(formatter)

plt.show()
```

It will produce a plot like this:

Body:
I want to make a program that monitors my 5000 meters progress. Inspired by this and this, I tried to make it work by combining some of the answers without any luck.

from __future__ import division
from matplotlib import pyplot as plt
from matplotlib.ticker import FuncFormatter
import matplotlib.dates as mdates
import numpy as np
import datetime as dt

def equidate_ax(fig, ax, dates, fmt="%d.%m.%Y", label="Date"):
    N = len(dates)
    def format_date(index, pos):
        index = np.clip(int(index + 0.5), 0, N - 1)
        return dates[index].strftime(fmt)
    ax.xaxis.set_major_formatter(FuncFormatter(format_date))
    ax.set_xlabel(label)
    fig.autofmt_xdate()

def DistVel2Time(distance, velocity_kph):
    velocity_ms = velocity_kph / 3.6
    time_sec = distance / velocity_ms
    hours = int(time_sec//3600)
    minutes = int((time_sec%3600)//60)
    seconds = int(time_sec%60)
    return "{:02d}:{:02d}".format(minutes, seconds)

times = [DistVel2Time(a, b) for a, b in [(5000, 13), (5000, 15), (5000, 14)]]

dates = [dt.datetime(year, month, day) for year, month, day in [(2019,2,1), (2019,2,2), (2019,2,7)]]

fig_1, ax_1 = plt.subplots()
ax_1.plot(dates, times, 'o--')
ax_1.xaxis_date()
ax_1.xaxis.set_major_formatter(mdates.DateFormatter('%d.%m.%Y'))
#ax_1.yaxis_date()
#ax_1.yaxis.set_major_formatter(mdates.DateFormatter("%M:%S"))
fig_1.autofmt_xdate()
plt.show()

fig_2, ax_2 = plt.subplots()
ax_2.plot(dates, times, 'D--')
ax_2.xaxis_date()
ax_2.xaxis.set_major_formatter(mdates.DateFormatter('%d.%m.%Y'))
equidate_ax(fig_2, ax_2, dates)
plt.show()

fig_1.savefig('fig1.png')
fig_2.savefig('fig2.png')

I stole the equidate_ax from @ascripter (from the second link) because I would like to skip all dates that I do not run.

If I run this piece of code, and save the figures, I end up getting the following two figures that are rather strange, as the y-axis does not distinguish between lower or higher values (Figures 1 and 2), and the x-axis for Figure 2 is repeating itself.

Figure 1: fig_1 from the code above.

Figure 2: fig_2 from the code above.

Why is not the y-axis plotting correctly in terms of lower or higher values?

How can I prevent the equidate_ax function from repeating itself and rather skip the unwanted dates?

If anyone could help cleaning up my mess, I would be grateful.

Body:
Combining the answers from the questions linked:

You basically have to make sure that matplotlib cannot guess the format of the x-axis but can guess the format of the y-axis.
With this matplotlib will not try to be smart and add dates you do not want to display on the x-axis but at the same time will be smart and sort the times for you on the y-axis.

from __future__ import division
from matplotlib import pyplot as plt
from matplotlib.ticker import FuncFormatter
import matplotlib.dates as mdates
import numpy as np
import datetime as dt

def DistVel2Time(distance, velocity_kph):
    velocity_ms = velocity_kph / 3.6
    time_sec = distance / velocity_ms
    hours = int(time_sec//3600)
    minutes = int((time_sec%3600)//60)
    seconds = int(time_sec%60)
    # note that I return a timedelta object here
    return dt.timedelta(minutes=minutes, seconds=seconds)

# we have to choose a interpretable data-type here, simply take the total time needed in seconds
times = [ DistVel2Time(a, b).total_seconds() for a, b in [(5000, 13), (5000, 15), (5000, 14)]]

# here we want to make sure that matplotlib cannot interpret it so we use strings directly
# change the format as required
dates = [ "%00d.%00d.%000d" % ymd for ymd in [(2019,2,1), (2019,2,2), (2019,2,7)]]

# the formatting function taken from https://stackoverflow.com/questions/48294332/plot-datetime-timedelta-using-matplotlib-and-python
def format_func(x, pos):
    hours = int(x//3600)
    minutes = int((x%3600)//60)
    seconds = int(x%60)

    return "{:d}:{:02d}:{:02d}".format(hours, minutes, seconds)

formatter = FuncFormatter(format_func)

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

ax.plot(dates, times, 'o--')
ax.yaxis.set_major_formatter(formatter)

plt.show()

It will produce a plot like this:


问:
Batch RPG Game with Login Function
I'm creating a D&D style RPG game using batch files and I saw another person using a login feature that creates a batch file that returns you to where you left off. so I tried to replicate it. Almost everything works except for the fact that it won't create the batch file to allow you to go back. When you go through the process of creating a login it goes through it like normal and on the next screen under start even displays that your username is what you set it as but it won't create the batch file. Some of the code might be scattered because I'm still learning and some of it unfinished but this is what I have so far.

```<code>title Lost Mine of Phandelvor
@echo off
:entergame
cls
echo.
echo Welcome to Lost Mine of Phandelvor
echo -------------------
echo.
echo 1. Create Account
echo 2. Login
echo 3. Exit
echo.
set /p input=

if %input% EQU 1 goto createuser
if %input% EQU 2 goto login
if %input% EQU 3 exit
if %input% GEQ 4 goto entergame

:createuser
cls
echo.
echo What would you like your Username to be?
set /p username1=
set v1f=0
goto checkforspaces

:checkforspaces
set x=!v1f!
set Letter%v1f%=!username1:~%x%,1!
if "!Letter%v1f%!" EQU " " (
echo.
echo.
echo Sorry you can't use spaces in your Username.
pause>nul
goto entergame
)
if NOT "!Letter%v1f%!" EQU "" (
set /a v1f=%v1f%+1
)
echo.
echo What would you like your Password to be?
set /p password1=
goto DATA_VALUES

:login
cls
set /p name=Username:
if not exist "%name%.bat" (
echo That is not a valid Username.
pause>nul
goto entergame
)
set /p pass1=Password:
call %name1%.bat
if not %password1% EQU %pass1% (
echo That is not a valid Password.
pause>nul
goto entergame
)
goto create

:DATA_FILES
set lvl1=1
set exp1=0
set expmax1=300
set gp1=10
set hp1=12
set ac1=15
set profbonus1=2
set str1=4
set dex1=1
set con1=2
set int1=0
set wis1=2
set cha1=2
set destination=SAVE_GAME_FILES
set destination2=SAVE_GAME_FILES
goto SAVE_GAME_FILES

:SAVE_GAME_FILES
(
echo set username1=%username1%
echo set password1=%password1%
:DATA_VALUES
echo set lvl1=%lvl1%
echo set exp1=%exp1%
echo set expmax1=%expmax1%
echo set gp1=%gp1%
echo set hp1=%hp1%
echo set ac1=%ac1%
echo set profbonus1=%profbonus1%
echo set str1=%str1%
echo set dex1=%dex1%
echo set con1=%con1%
echo set int1=%int1%
echo set wis1=%wis1%
echo set cha1=%cha1%
echo set destination=%destination%
echo set destination2=%destination2%
)>%username1%.bat
goto start

:start
cls
echo.
echo Currently logged in as %username1%
echo.
echo Welcome to my fantasy style role playing game.
echo You will need to create a character.
echo.
echo Enjoy!
echo.
echo 1. Continue to Character Selection
echo 2. Exit
echo.
set /p input=

if %input% EQU 1 goto create
if %input% EQU 2 exit
if %input% GEQ 3 goto start

:create
cls
echo.
echo Welcome to Character Creation
echo.
echo Pick your race!
echo.
echo 1. Human
echo 2. Dwarf
echo 3. Elf
echo 4. Dragonborn
echo 5. Tiefling
echo.
set /p input=Choice:
if %input%==1 goto createHuman
if %input%==2 goto createDwarf
if %input%==3 goto createElf
if %input%==4 goto createDragonborn
if %input%==5 goto createTiefling
goto create

:createHuman
cls
echo.
echo You have chosen Human as your race!
echo.
echo Choose your class
echo.
echo 1. Fighter
echo 2. Ranger
echo 3. Rogue
echo 4. Wizard
echo.
set /p input=Choise
if %input%==1 goto humanFighter
if %input%==2 goto humanRanger
if %input%==3 goto humanRogue
if %input%==4 goto humanWizard
goto createHuman

:humanFighter
cls
echo.
echo You have chosen Fighter as your class!
echo.
echo Choose your weapon
echo.
echo 1. Battleaxe 1D8 Slashing
echo 2. Longsword 1D8 Slashing
echo 3. Rapier 1D8 Piercing
echo.
set /p input=choise
if %input%==1 goto humanFighter1
if %input%==2 goto humanFighter2
if %input%==3 goto humanFighter3
goto humanFighter

:humanfighter1
set lvl1=1
set exp1=0
set expmax1=300
set gp1=10
set hp1=12
set ac1=15
set profbonus1=2
set str1=4
set dex1=1
set con1=2
set int1=0
set wis1=2
set cha1=2
cls
echo.
echo To find your stats open your character sheet labeled humanfighter1_cs.txt
echo.
echo What's your name?
echo.
set /p name1=Enter:
goto hf1main

:hf1main
cls
echo.
echo %name1% Human Fighter
echo Lvl: %lvl1% Money:%gp1%
echo Hit Points: %hp1%/12
echo Armor: Breastplate Armor Class: %ac1%
echo Exp: %exp1%/%expmax1%
echo Weapon: Battleaxe 1D8 Slashing
echo Stat Modifiers:
echo Strength: +%str1%
echo Dexterity: +%dex1%
echo Constitution: +%con1%
echo Intelligence: +%int1%
echo Wisdom: +%wis1%
echo Charisma: +%cha1%
echo -------------------------------------
echo 1) Continue
echo 2) Exit
echo.
set /p input=Enter:
if %input%==1 goto hf1continue
if %input%==2 exit
</code>```

I expect it to create the batch file after creating an account so that you can log in later.

答:
For your menus, I would like to introduce you to choice.exe as an alternative to Set /P. It is far better to use it when input must be any one of a small set of known values. Set /P allows the end user to enter nothing or anything, and in order to maintain control you need to build in some input verification mechanism. To find out how choice.exe works, open a cmd.exe window and enter choice /? at the prompt.

Here is a rewritten example snippet of your script, (lines 1-43) to hopefully explain why:

```<code>@Echo Off
Title Lost Mine of Phandelvor

:EnterGame
ClS
Echo(
Echo Welcome to Lost Mine of Phandelvor
Echo ----------------------------------
Echo(
Echo 1. Create Account
Echo 2. Login
Echo 3. Exit
Echo(
Choice /C 123
If ErrorLevel 3 Exit /B
If ErrorLevel 2 GoTo Login

:CreateUser
ClS
Echo(
Set "username1="
Set /P "username1=What would you like your Username to be? "
If Not Defined username1 GoTo CreateUser

:CheckForSpaces
If Not "%username1: =%"=="%username1%" (
    Echo Sorry you can not use spaces in your Username.
    Choice /M "Is %username1: =%" okay"
    If ErrorLevel 2 GoTo CreateUser
)
If Exist "%username1%.bat" GoTo :Login
Echo(
Set "password1="
Set /P "password1=What would you like your Password to be? "
</code>```

However, before you continue with your script, based upon what I said about using Set /P. The end user can currently enter anything they want as username1. We've already checked for no entry and for spaces, but you're also saving the name as a filename too, %name%.bat. Along with the decimal character codes 0 through 31, Windows filenames cannot contain any of the following characters, \/:*?"<>|, so you'd need to incorporate further verification of username1. This verification procedure would need to be implemented before line 31 of the code above.

Before you do so however, you may want to consider changing your methodology and not saving the Username to the name of a file. The reason for this is that you'd also be wise not to use filenames ending with a ., or any named CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9 either. So you would further need to include those verification checks of the input too.

Don't forget, you'll probably want to include a verification method for input entries to the %password1% prompt too!

Given the complexity involved with user input and Set /P you can see why I have recommended  choice.exe as a control measure for your menus.

Title: Batch RPG Game with Login Function

Body:
I'm creating a D&D style RPG game using batch files and I saw another person using a login feature that creates a batch file that returns you to where you left off. so I tried to replicate it. Almost everything works except for the fact that it won't create the batch file to allow you to go back. When you go through the process of creating a login it goes through it like normal and on the next screen under start even displays that your username is what you set it as but it won't create the batch file. Some of the code might be scattered because I'm still learning and some of it unfinished but this is what I have so far.

title Lost Mine of Phandelvor
@echo off
:entergame
cls
echo.
echo Welcome to Lost Mine of Phandelvor
echo -------------------
echo.
echo 1. Create Account
echo 2. Login
echo 3. Exit
echo.
set /p input=

if %input% EQU 1 goto createuser
if %input% EQU 2 goto login
if %input% EQU 3 exit
if %input% GEQ 4 goto entergame

:createuser
cls
echo.
echo What would you like your Username to be?
set /p username1=
set v1f=0
goto checkforspaces

:checkforspaces
set x=!v1f!
set Letter%v1f%=!username1:~%x%,1!
if "!Letter%v1f%!" EQU " " (
echo.
echo.
echo Sorry you can't use spaces in your Username.
pause>nul
goto entergame
)
if NOT "!Letter%v1f%!" EQU "" (
set /a v1f=%v1f%+1
)
echo.
echo What would you like your Password to be?
set /p password1=
goto DATA_VALUES

:login
cls
set /p name=Username:
if not exist "%name%.bat" (
echo That is not a valid Username.
pause>nul
goto entergame
)
set /p pass1=Password:
call %name1%.bat
if not %password1% EQU %pass1% (
echo That is not a valid Password.
pause>nul
goto entergame
)
goto create

:DATA_FILES
set lvl1=1
set exp1=0
set expmax1=300
set gp1=10
set hp1=12
set ac1=15
set profbonus1=2
set str1=4
set dex1=1
set con1=2
set int1=0
set wis1=2
set cha1=2
set destination=SAVE_GAME_FILES
set destination2=SAVE_GAME_FILES
goto SAVE_GAME_FILES

:SAVE_GAME_FILES
(
echo set username1=%username1%
echo set password1=%password1%
:DATA_VALUES
echo set lvl1=%lvl1%
echo set exp1=%exp1%
echo set expmax1=%expmax1%
echo set gp1=%gp1%
echo set hp1=%hp1%
echo set ac1=%ac1%
echo set profbonus1=%profbonus1%
echo set str1=%str1%
echo set dex1=%dex1%
echo set con1=%con1%
echo set int1=%int1%
echo set wis1=%wis1%
echo set cha1=%cha1%
echo set destination=%destination%
echo set destination2=%destination2%
)>%username1%.bat
goto start

:start
cls
echo.
echo Currently logged in as %username1%
echo.
echo Welcome to my fantasy style role playing game.
echo You will need to create a character.
echo.
echo Enjoy!
echo.
echo 1. Continue to Character Selection
echo 2. Exit
echo.
set /p input=

if %input% EQU 1 goto create
if %input% EQU 2 exit
if %input% GEQ 3 goto start

:create
cls
echo.
echo Welcome to Character Creation
echo.
echo Pick your race!
echo.
echo 1. Human
echo 2. Dwarf
echo 3. Elf
echo 4. Dragonborn
echo 5. Tiefling
echo.
set /p input=Choice:
if %input%==1 goto createHuman
if %input%==2 goto createDwarf
if %input%==3 goto createElf
if %input%==4 goto createDragonborn
if %input%==5 goto createTiefling
goto create

:createHuman
cls
echo.
echo You have chosen Human as your race!
echo.
echo Choose your class
echo.
echo 1. Fighter
echo 2. Ranger
echo 3. Rogue
echo 4. Wizard
echo.
set /p input=Choise
if %input%==1 goto humanFighter
if %input%==2 goto humanRanger
if %input%==3 goto humanRogue
if %input%==4 goto humanWizard
goto createHuman

:humanFighter
cls
echo.
echo You have chosen Fighter as your class!
echo.
echo Choose your weapon
echo.
echo 1. Battleaxe 1D8 Slashing
echo 2. Longsword 1D8 Slashing
echo 3. Rapier 1D8 Piercing
echo.
set /p input=choise
if %input%==1 goto humanFighter1
if %input%==2 goto humanFighter2
if %input%==3 goto humanFighter3
goto humanFighter

:humanfighter1
set lvl1=1
set exp1=0
set expmax1=300
set gp1=10
set hp1=12
set ac1=15
set profbonus1=2
set str1=4
set dex1=1
set con1=2
set int1=0
set wis1=2
set cha1=2
cls
echo.
echo To find your stats open your character sheet labeled humanfighter1_cs.txt
echo.
echo What's your name?
echo.
set /p name1=Enter:
goto hf1main

:hf1main
cls
echo.
echo %name1% Human Fighter
echo Lvl: %lvl1% Money:%gp1%
echo Hit Points: %hp1%/12
echo Armor: Breastplate Armor Class: %ac1%
echo Exp: %exp1%/%expmax1%
echo Weapon: Battleaxe 1D8 Slashing
echo Stat Modifiers:
echo Strength: +%str1%
echo Dexterity: +%dex1%
echo Constitution: +%con1%
echo Intelligence: +%int1%
echo Wisdom: +%wis1%
echo Charisma: +%cha1%
echo -------------------------------------
echo 1) Continue
echo 2) Exit
echo.
set /p input=Enter:
if %input%==1 goto hf1continue
if %input%==2 exit

I expect it to create the batch file after creating an account so that you can log in later.

Body:
For your menus, I would like to introduce you to choice.exe as an alternative to Set /P. It is far better to use it when input must be any one of a small set of known values. Set /P allows the end user to enter nothing or anything, and in order to maintain control you need to build in some input verification mechanism. To find out how choice.exe works, open a cmd.exe window and enter choice /? at the prompt.

Here is a rewritten example snippet of your script, (lines 1-43) to hopefully explain why:

@Echo Off
Title Lost Mine of Phandelvor

:EnterGame
ClS
Echo(
Echo Welcome to Lost Mine of Phandelvor
Echo ----------------------------------
Echo(
Echo 1. Create Account
Echo 2. Login
Echo 3. Exit
Echo(
Choice /C 123
If ErrorLevel 3 Exit /B
If ErrorLevel 2 GoTo Login

:CreateUser
ClS
Echo(
Set "username1="
Set /P "username1=What would you like your Username to be? "
If Not Defined username1 GoTo CreateUser

:CheckForSpaces
If Not "%username1: =%"=="%username1%" (
    Echo Sorry you can not use spaces in your Username.
    Choice /M "Is %username1: =%" okay"
    If ErrorLevel 2 GoTo CreateUser
)
If Exist "%username1%.bat" GoTo :Login
Echo(
Set "password1="
Set /P "password1=What would you like your Password to be? "

However, before you continue with your script, based upon what I said about using Set /P. The end user can currently enter anything they want as username1. We've already checked for no entry and for spaces, but you're also saving the name as a filename too, %name%.bat. Along with the decimal character codes 0 through 31, Windows filenames cannot contain any of the following characters, \/:*?"<>|, so you'd need to incorporate further verification of username1. This verification procedure would need to be implemented before line 31 of the code above.

Before you do so however, you may want to consider changing your methodology and not saving the Username to the name of a file. The reason for this is that you'd also be wise not to use filenames ending with a ., or any named CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9 either. So you would further need to include those verification checks of the input too.

Don't forget, you'll probably want to include a verification method for input entries to the %password1% prompt too!

Given the complexity involved with user input and Set /P you can see why I have recommended  choice.exe as a control measure for your menus.


问:
C# - skip generics
How I can pass parameters of a generic type in my methods?</p>

```<code>public Type<T, U, V> { ... }

public void Method(??? arg) // where ??? is Type<T, U, V>
{
  ...
}
</code>```

答:
```<code>public Type<T, U, V> { ... }

public void Method<T, U, V>(Type<T, U, V> arg)
{
    ...
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: C# - skip generics

Body:
How I can pass parameters of a generic type in my methods?

public Type<T, U, V> { ... }

public void Method(??? arg) // where ??? is Type<T, U, V>
{
  ...
}


问:
How to use embed
I'm trying to use <embed> but having limited success. These two URLs won't embed, for example.

```<code><embed style="width: 500px; height: 300px;"
  src="https://www.tate.org.uk" width="300" height="150">
</embed>
<embed style="width: 500px; height: 300px;"
  src="http://www.northlondonreadinggroup.co.uk/" width="300" height="150">
</embed>
</code>```

Whereas other URLs will...

https://adsler.co.uk/adsler-blog/

I came across these: How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header? If I post them in my site header, can I bypass iframe restrictions?

```<code><script
src="https://unpkg.com/@ungap
/custom-elements-builtin"></script>
<script type="module" src="x-frame-
bypass.js"></script>
</code>```

答:
As @showdev mentioned, you can use the X-Frame-Options

Here is an example for your case:

```<code><!DOCTYPE html>
<html>
<script src="https://unpkg.com/@ungap/custom-elements-builtin"></script>
<script type="module" src="https://unpkg.com/x-frame-bypass"></script>
<body>

<h2>HTML Iframes</h2>
<p>You can use the height and width attributes to specify the size of the iframe:</p>

<iframe is="x-frame-bypass" src="https://www.tate.org.uk" height="150" width="300"></iframe>

<iframe is="x-frame-bypass" src="http://www.northlondonreadinggroup.co.uk/" height="150" width="300"></iframe>

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

Here is the example that I mentioned: (Just click on run)

https://www.w3schools.com/code/tryit.asp?filename=G4LYCU8V9ILG

Title: How to use embed

Body:
I'm trying to use <embed> but having limited success. These two URLs won't embed, for example.

<embed style="width: 500px; height: 300px;"
  src="https://www.tate.org.uk" width="300" height="150">
</embed>
<embed style="width: 500px; height: 300px;"
  src="http://www.northlondonreadinggroup.co.uk/" width="300" height="150">
</embed>

Whereas other URLs will...

https://adsler.co.uk/adsler-blog/

I came across these: How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header? If I post them in my site header, can I bypass iframe restrictions?

Body:
As @showdev mentioned, you can use the X-Frame-Options

Here is an example for your case:

<!DOCTYPE html>
<html>
<script src="https://unpkg.com/@ungap/custom-elements-builtin"></script>
<script type="module" src="https://unpkg.com/x-frame-bypass"></script>
<body>

<h2>HTML Iframes</h2>
<p>You can use the height and width attributes to specify the size of the iframe:</p>

<iframe is="x-frame-bypass" src="https://www.tate.org.uk" height="150" width="300"></iframe>

<iframe is="x-frame-bypass" src="http://www.northlondonreadinggroup.co.uk/" height="150" width="300"></iframe>

</body>
</html>

Here is the example that I mentioned: (Just click on run)

https://www.w3schools.com/code/tryit.asp?filename=G4LYCU8V9ILG


问:
Unable to run grails command on new project on Mac due to "Could not determine java version" error
I need to do run an existing grails project (which was running on windows) on a Mac system.

Before that, I am trying to setup grails and run a "hello world". I downloaded and installed grails using sdkman. My setup directory is -

/Users/sandeepan.nath/Desktop/setups
where I have created grails directory and ran the sdk install grails command which installed grails and created these -

```<code>SandeepanNath:grails sandeepan.nath$ ls -lrth
total 80
-rw-r--r--   1 sandeepan.nath  1974079253    73B Jun  1 13:03 gradle.properties
drwxr-xr-x   3 sandeepan.nath  1974079253    96B Jun  1 13:03 gradle
-rwxr--r--   1 sandeepan.nath  1974079253   4.9K Jun  1 13:03 gradlew
-rwxr--r--   1 sandeepan.nath  1974079253   2.3K Jun  1 13:03 gradlew.bat
-rwxr--r--   1 sandeepan.nath  1974079253   4.6K Jun  1 13:03 grailsw
-rwxr--r--   1 sandeepan.nath  1974079253   2.3K Jun  1 13:03 grailsw.bat
drwxr-xr-x   5 sandeepan.nath  1974079253   160B Jun  1 13:03 src
-rw-r--r--   1 sandeepan.nath  1974079253   5.3K Jun  1 13:03 grails-wrapper.jar
drwxr-xr-x  12 sandeepan.nath  1974079253   384B Jun  1 13:03 grails-app
-rw-r--r--   1 sandeepan.nath  1974079253   2.9K Jun  1 13:03 build.gradle
drwxr-xr-x   2 sandeepan.nath  1974079253    64B Jun  1 13:03 build
</code>```

I ran grails create-app hello to create a project while inside the grails directory, but it failed -

```<code>SandeepanNath:hello sandeepan.nath$ grails create-app hello
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.codehaus.groovy.reflection.CachedClass (file:/Users/sandeepan.nath/.sdkman/candidates/grails/3.3.10/lib/org.codehaus.groovy/groovy/jars/groovy-2.4.17.jar) to method java.lang.Object.finalize()
WARNING: Please consider reporting this to the maintainers of org.codehaus.groovy.reflection.CachedClass
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
| Error Error initializing classpath: Could not determine java version from '12.0.1'. (Use --stacktrace to see the full trace)
</code>```

I went one level up, outside the grails directory, and created project (worked) -

```<code>SandeepanNath:setups sandeepan.nath$ grails create-app new_proj
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.codehaus.groovy.reflection.CachedClass (file:/Users/sandeepan.nath/.sdkman/candidates/grails/3.3.10/lib/org.codehaus.groovy/groovy/jars/groovy-2.4.17.jar) to method java.lang.Object.finalize()
WARNING: Please consider reporting this to the maintainers of org.codehaus.groovy.reflection.CachedClass
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
| Application created at /Users/sandeepan.nath/Desktop/setups/new_proj
</code>```

and followed the steps to create a project as in https://docs.grails.org/3.3.10/guide/single.html#creatingAnApplication.

Now, when I am inside new_proj, and try running grails command, I am blocked here -

```<code>SandeepanNath:new_proj sandeepan.nath$ grails
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.codehaus.groovy.reflection.CachedClass (file:/Users/sandeepan.nath/.sdkman/candidates/grails/3.3.10/lib/org.codehaus.groovy/groovy/jars/groovy-2.4.17.jar) to method java.lang.Object.finalize()
WARNING: Please consider reporting this to the maintainers of org.codehaus.groovy.reflection.CachedClass
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
| Error Error initializing classpath: Could not determine java version from '12.0.1'. (Use --stacktrace to see the full trace)
</code>```

I have Java home set in the environment PATH variable -

```<code>SandeepanNath:~ sandeepan.nath$ echo $PATH
/Users/sandeepan.nath/.sdkman/candidates/grails/current/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/bin:/opt/apache-maven/bin:/usr/libexec/java_home/bin:/opt/apache-maven/bin:/usr/libexec/java_home:/opt/apache-maven/bin
</code>```

Note - there is no such path as /usr/libexec/java_home/bin

Still, when I try running grails command from within my project, I get this Could not determine java version error -

```<code>SandeepanNath:new_proj sandeepan.nath$ grails --stacktrace
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.codehaus.groovy.reflection.CachedClass (file:/Users/sandeepan.nath/.sdkman/candidates/grails/3.3.10/lib/org.codehaus.groovy/groovy/jars/groovy-2.4.17.jar) to method java.lang.Object.finalize()
WARNING: Please consider reporting this to the maintainers of org.codehaus.groovy.reflection.CachedClass
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
| Error Error initializing classpath: Could not determine java version from '12.0.1'. (NOTE: Stack trace has been filtered. Use --verbose to see entire trace.)
java.lang.IllegalArgumentException: Could not determine java version from '12.0.1'.
    at org.gradle.api.JavaVersion.toVersion(JavaVersion.java:68)
    at org.gradle.api.JavaVersion.current(JavaVersion.java:78)
    at org.gradle.internal.jvm.UnsupportedJavaRuntimeException.assertUsingVersion(UnsupportedJavaRuntimeException.java:29)
    at org.gradle.tooling.internal.consumer.ConnectorServices.checkJavaVersion(ConnectorServices.java:66)
    at org.gradle.tooling.internal.consumer.ConnectorServices.close(ConnectorServices.java:53)
    at org.gradle.tooling.internal.consumer.DefaultGradleConnector.close(DefaultGradleConnector.java:57)
    at org.grails.cli.gradle.cache.CachedGradleOperation.call(CachedGradleOperation.groovy:78)
    at org.grails.cli.GrailsCli.populateContextLoader(GrailsCli.groovy:525)
    at org.grails.cli.GrailsCli.initializeProfile(GrailsCli.groovy:508)
    at org.grails.cli.GrailsCli.initializeApplication(GrailsCli.groovy:306)
    at org.grails.cli.GrailsCli.execute(GrailsCli.groovy:269)
    at org.grails.cli.GrailsCli.main(GrailsCli.groovy:159)
</code>```

答: Install JDK 8 from Oracle,  once installed you should be ok.  Grails 3 requires 7 or 8.   </p>

Body:
I need to do run an existing grails project (which was running on windows) on a Mac system.

Before that, I am trying to setup grails and run a "hello world". I downloaded and installed grails using sdkman. My setup directory is -

/Users/sandeepan.nath/Desktop/setups
where I have created grails directory and ran the sdk install grails command which installed grails and created these -

SandeepanNath:grails sandeepan.nath$ ls -lrth
total 80
-rw-r--r--   1 sandeepan.nath  1974079253    73B Jun  1 13:03 gradle.properties
drwxr-xr-x   3 sandeepan.nath  1974079253    96B Jun  1 13:03 gradle
-rwxr--r--   1 sandeepan.nath  1974079253   4.9K Jun  1 13:03 gradlew
-rwxr--r--   1 sandeepan.nath  1974079253   2.3K Jun  1 13:03 gradlew.bat
-rwxr--r--   1 sandeepan.nath  1974079253   4.6K Jun  1 13:03 grailsw
-rwxr--r--   1 sandeepan.nath  1974079253   2.3K Jun  1 13:03 grailsw.bat
drwxr-xr-x   5 sandeepan.nath  1974079253   160B Jun  1 13:03 src
-rw-r--r--   1 sandeepan.nath  1974079253   5.3K Jun  1 13:03 grails-wrapper.jar
drwxr-xr-x  12 sandeepan.nath  1974079253   384B Jun  1 13:03 grails-app
-rw-r--r--   1 sandeepan.nath  1974079253   2.9K Jun  1 13:03 build.gradle
drwxr-xr-x   2 sandeepan.nath  1974079253    64B Jun  1 13:03 build

I ran grails create-app hello to create a project while inside the grails directory, but it failed -

SandeepanNath:hello sandeepan.nath$ grails create-app hello
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.codehaus.groovy.reflection.CachedClass (file:/Users/sandeepan.nath/.sdkman/candidates/grails/3.3.10/lib/org.codehaus.groovy/groovy/jars/groovy-2.4.17.jar) to method java.lang.Object.finalize()
WARNING: Please consider reporting this to the maintainers of org.codehaus.groovy.reflection.CachedClass
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
| Error Error initializing classpath: Could not determine java version from '12.0.1'. (Use --stacktrace to see the full trace)

I went one level up, outside the grails directory, and created project (worked) -

SandeepanNath:setups sandeepan.nath$ grails create-app new_proj
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.codehaus.groovy.reflection.CachedClass (file:/Users/sandeepan.nath/.sdkman/candidates/grails/3.3.10/lib/org.codehaus.groovy/groovy/jars/groovy-2.4.17.jar) to method java.lang.Object.finalize()
WARNING: Please consider reporting this to the maintainers of org.codehaus.groovy.reflection.CachedClass
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
| Application created at /Users/sandeepan.nath/Desktop/setups/new_proj

and followed the steps to create a project as in https://docs.grails.org/3.3.10/guide/single.html#creatingAnApplication.

Now, when I am inside new_proj, and try running grails command, I am blocked here -

SandeepanNath:new_proj sandeepan.nath$ grails
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.codehaus.groovy.reflection.CachedClass (file:/Users/sandeepan.nath/.sdkman/candidates/grails/3.3.10/lib/org.codehaus.groovy/groovy/jars/groovy-2.4.17.jar) to method java.lang.Object.finalize()
WARNING: Please consider reporting this to the maintainers of org.codehaus.groovy.reflection.CachedClass
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
| Error Error initializing classpath: Could not determine java version from '12.0.1'. (Use --stacktrace to see the full trace)

I have Java home set in the environment PATH variable -

SandeepanNath:~ sandeepan.nath$ echo $PATH
/Users/sandeepan.nath/.sdkman/candidates/grails/current/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/bin:/opt/apache-maven/bin:/usr/libexec/java_home/bin:/opt/apache-maven/bin:/usr/libexec/java_home:/opt/apache-maven/bin

Note - there is no such path as /usr/libexec/java_home/bin

Still, when I try running grails command from within my project, I get this Could not determine java version error -

SandeepanNath:new_proj sandeepan.nath$ grails --stacktrace
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.codehaus.groovy.reflection.CachedClass (file:/Users/sandeepan.nath/.sdkman/candidates/grails/3.3.10/lib/org.codehaus.groovy/groovy/jars/groovy-2.4.17.jar) to method java.lang.Object.finalize()
WARNING: Please consider reporting this to the maintainers of org.codehaus.groovy.reflection.CachedClass
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
| Error Error initializing classpath: Could not determine java version from '12.0.1'. (NOTE: Stack trace has been filtered. Use --verbose to see entire trace.)
java.lang.IllegalArgumentException: Could not determine java version from '12.0.1'.
    at org.gradle.api.JavaVersion.toVersion(JavaVersion.java:68)
    at org.gradle.api.JavaVersion.current(JavaVersion.java:78)
    at org.gradle.internal.jvm.UnsupportedJavaRuntimeException.assertUsingVersion(UnsupportedJavaRuntimeException.java:29)
    at org.gradle.tooling.internal.consumer.ConnectorServices.checkJavaVersion(ConnectorServices.java:66)
    at org.gradle.tooling.internal.consumer.ConnectorServices.close(ConnectorServices.java:53)
    at org.gradle.tooling.internal.consumer.DefaultGradleConnector.close(DefaultGradleConnector.java:57)
    at org.grails.cli.gradle.cache.CachedGradleOperation.call(CachedGradleOperation.groovy:78)
    at org.grails.cli.GrailsCli.populateContextLoader(GrailsCli.groovy:525)
    at org.grails.cli.GrailsCli.initializeProfile(GrailsCli.groovy:508)
    at org.grails.cli.GrailsCli.initializeApplication(GrailsCli.groovy:306)
    at org.grails.cli.GrailsCli.execute(GrailsCli.groovy:269)
    at org.grails.cli.GrailsCli.main(GrailsCli.groovy:159)


问:
Copying an Object in Java without affecting the original via copy constructor
I'm trying to copy an Object, which will then be modified, without changing the original object.

I found this solution and it seemed the best approach would be a copy constructor - from my understanding, this would give me a deep copy (a completely separate object from the original).

So I tried that. However, I've noticed that when the following code executes, it's effecting all previous objects from which it was copied. When I call surveyCopy.take(), which will change values inside of the Survey, it's also changing the values inside of selectedSurvey.

```<code>public class MainDriver {
...
//Code that is supposed to create the copy
case "11":  selectedSurvey = retrieveBlankSurvey(currentSurveys);
            Survey surveyCopy = new Survey(selectedSurvey);
            surveyCopy.take(consoleIO);
            currentSurveys.add(surveyCopy);
            break;
}
</code>```

and here is code for my copy constructor:

```<code>public class Survey implements Serializable
{
    ArrayList<Question> questionList;
    int numQuestions;
    String taker;
    String surveyName;
    boolean isTaken;

    //Copy constructor
    public Survey(Survey incoming)
    {
        this.taker = incoming.getTaker();
        this.numQuestions = incoming.getNumQuestions();
        this.questionList = incoming.getQuestionList();
        this.surveyName = incoming.getSurveyName();
        this.isTaken = incoming.isTaken();
    }
}
</code>```

So what exactly is the issue? Does a copy constructor not work that way? Is the way I coded it wrong?

答:
If we need to copy a simple pojo (Not nested). Then shallow copy is enough.

Cloner class

import java.lang.reflect.Field;

```<code>public class Cloner {
    public static <T> T cloneShallow(T srcEntity, T destEntity){
        try {
            return copy(srcEntity, destEntity);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    private static <T> T copy(T srcEntity, T destEntity) throws IllegalAccessException, InstantiationException {
        if(srcEntity == null){
            return null;
        }

        Class<?> clazz = srcEntity.getClass();

        T newEntity;

        if(destEntity != null){
            newEntity = destEntity;
        }else{
            //create new instance
            newEntity = (T) srcEntity.getClass().newInstance();
        }

        while (clazz != null) {
            copyFields(srcEntity, newEntity, clazz);
            clazz = clazz.getSuperclass();
        }

        return newEntity;
    }

    private static  <T> T copyFields(T entity, T newEntity, Class<?> clazz) throws IllegalAccessException {
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            field.set(newEntity, field.get(entity));
        }
        return newEntity;
    }
}
</code>```

Lets call..

```<code>eg.
Apple apple = new Apple();
apple.setColor("Green");

Apple newApple = Cloner.cloneShallow(apple, new Apple());
( or )
Apple newApple = Cloner.cloneShallow(apple, null);
</code>```

Body:
I'm trying to copy an Object, which will then be modified, without changing the original object.

I found this solution and it seemed the best approach would be a copy constructor - from my understanding, this would give me a deep copy (a completely separate object from the original).

So I tried that. However, I've noticed that when the following code executes, it's effecting all previous objects from which it was copied. When I call surveyCopy.take(), which will change values inside of the Survey, it's also changing the values inside of selectedSurvey.

public class MainDriver {
...
//Code that is supposed to create the copy
case "11":  selectedSurvey = retrieveBlankSurvey(currentSurveys);
            Survey surveyCopy = new Survey(selectedSurvey);
            surveyCopy.take(consoleIO);
            currentSurveys.add(surveyCopy);
            break;
}

and here is code for my copy constructor:

public class Survey implements Serializable
{
    ArrayList<Question> questionList;
    int numQuestions;
    String taker;
    String surveyName;
    boolean isTaken;

    //Copy constructor
    public Survey(Survey incoming)
    {
        this.taker = incoming.getTaker();
        this.numQuestions = incoming.getNumQuestions();
        this.questionList = incoming.getQuestionList();
        this.surveyName = incoming.getSurveyName();
        this.isTaken = incoming.isTaken();
    }
}

So what exactly is the issue? Does a copy constructor not work that way? Is the way I coded it wrong?

Body:
If we need to copy a simple pojo (Not nested). Then shallow copy is enough.

Cloner class

import java.lang.reflect.Field;

public class Cloner {
    public static <T> T cloneShallow(T srcEntity, T destEntity){
        try {
            return copy(srcEntity, destEntity);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    private static <T> T copy(T srcEntity, T destEntity) throws IllegalAccessException, InstantiationException {
        if(srcEntity == null){
            return null;
        }

        Class<?> clazz = srcEntity.getClass();

        T newEntity;

        if(destEntity != null){
            newEntity = destEntity;
        }else{
            //create new instance
            newEntity = (T) srcEntity.getClass().newInstance();
        }

        while (clazz != null) {
            copyFields(srcEntity, newEntity, clazz);
            clazz = clazz.getSuperclass();
        }

        return newEntity;
    }

    private static  <T> T copyFields(T entity, T newEntity, Class<?> clazz) throws IllegalAccessException {
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            field.set(newEntity, field.get(entity));
        }
        return newEntity;
    }
}

Lets call..

eg.
Apple apple = new Apple();
apple.setColor("Green");

Apple newApple = Cloner.cloneShallow(apple, new Apple());
( or )
Apple newApple = Cloner.cloneShallow(apple, null);