问:
Which method dm or dbow works well for document similarity using Doc2Vec?
I'm trying to find out the similarity between 2 documents. I'm using Doc2vec Gensim to train around 10k documents. There are around 10 string type of tags. Each tag consists of a unique word and contains some sort of documents. Model is trained using distributed memory method.

```<code>Doc2Vec(alpha=0.025, min_alpha=0.0001, min_count=2, window=10, dm=1, dm_mean=1, epochs=50, seed=25, vector_size=100, workers=1)
</code>```

I've tried both dm and dbow as well. dm gives better result(similarity score) as compared to dbow. I understood the concepts of dm vs dbow. But don't know which method is good for similarity measures between two documents.

First question: Which method is the best to perform well on similarities?

model.wv.n_similarity(<words_1>, <words_2>) gives similarity score using word vectors.

model.docvecs.similarity_unseen_docs(model, doc1, doc2) gives similarity score using doc vectors where doc1 and doc2 are not tags/ or indexes of doctags. Each doc1 and doc2 contains 10-20 words kind of sentences.

Both wv.n_similarity and docvecs.similarity_unseen_docs provide different similarity scores on same types of documents.

docvecs.similarity_unseen_docs gives little bit good results as compared to wv.n_similarity but wv.n_similarity sometimes also gives good results.

Question: What is the difference between docvecs.similarity_unseen_docs and wv.n_similarity? Can I use docvecs.similarity_unseen_docs to find the similarity score between unseen data (It might be a silly question)?

Why I asked because docvecs.similarity_unseen_docs provides similarity score on tags, not on actual words belonging to their tags. I'm not sure, please correct me here, if I'm wrong.

How can I convert cosine similarity score to probability?

Thanks.

model = Doc2Vec(alpha=0.025, min_alpha=0.0001, min_count=2, window=10, dm=1, dm_mean=1, epochs=50, seed=25, vector_size=100, workers=4)
# Training of the model
tagged_data = [TaggedDocument(words=_d, tags=[str(i)]) for i, _d in enumerate(<list_of_list_of_tokens>)]
model.build_vocab(tagged_data)
model.train(tagged_data, total_examples=model.corpus_count, epochs=model.epochs)

# Finding similarity score
model.wv.n_similarity(<doc_words1>, <doc_words2>)
model.random.seed(25)
model.docvecs.similarity_unseen_docs(model, <doc_words1>, <doc_words2>)
```

答:
Both PV-DM mode (dm=1, the default) and PV-DBOW mode (dm=0) can work well. Which is better will depend on your data and goals. Once you have a robust way to quantitatively score the quality of a model's results, for your project goals – which you'll want to be able to tune all of the model's meta-parameters, including DM/DBOW mode – you can and should try both.

PV-DBOW trains fast, and often works very well on shortish-docs (a few dozens of words). Note, though, that this mode doesn't train usable word-vectors unless you also add the dbow_words=1 option, which will slow training.

Using model.wv.n_similarity() relies on word-vectors only. It averages each set f word-vectors, then reports the cosine-similarity between those two averages. (So, it will only be sensible in PV-DM mode, or PV-DBOW with dbow_words=1 activated.

Using model. docvecs.similarity_unseen_docs() uses infer_vector() to treat each of the supplied docs as new texts, for which a true Doc2Vec doc-vector (not a mere average-of-word-vectors) is calculated. (This method operates on lists-of-words, not lists-of-tags.)

Which is better is something you should test for your goals. The average-of-word-vectors is a simpler, faster technique for making a text-vector – but still works ok for a lot of purposes. The inferred doc-vectors take longer to calculate, but with a good model, may be better for some tasks.

Other notes on your setup:

often, setting min_count as low as 2 is a bad idea: those rare words don't have enough examples to mean much, and actually interfere with the quality of surrounding words

10k documents is on the smallish side for a training corpus, compared to published Doc2Vec results (which usually use tens-of-thousands to millions of documents).

published results often use 10-20 training epochs (though more, like your choice of 50, might be helpful especially for smaller corpuses)

on typical multi-core machines workers=1 will be much slower than the default (workers=3); on a machine with 8 or more cores, up to workers=8 is often a good idea. (Though, unless using the newer corpus_file input option, more workers up to the full count of 16, 32, etc cores doesn't help.)

classic Doc2Vec usage doesn't assign docs just known labels (as in your "10 string type of tags"), but unique IDs for each document. In some cases using, or adding, known labels as tags may help, but beware that if you're only supplying 10 tags, you've essentially turned your 10,000 documents into 10 documents (from the perspective of the model's view, which sees all texts with the same tag as if they were segments of one larger document with that tag). In plain PV-DBOW, training only 10 doc-vectors, of 100-dimensions each, from just 10 distinct examples wouldn't make much sense: it'd be prone to severe overfitting. (In PV-DM or PV-DBOW with dbow_words, the fact that the model is training both 10 doc-vectors and many hundreds/thousands of other vocabulary-word word-vectors would help offset the risk of overfitting.)

Body:
I'm trying to find out the similarity between 2 documents. I'm using Doc2vec Gensim to train around 10k documents. There are around 10 string type of tags. Each tag consists of a unique word and contains some sort of documents. Model is trained using distributed memory method.

Doc2Vec(alpha=0.025, min_alpha=0.0001, min_count=2, window=10, dm=1, dm_mean=1, epochs=50, seed=25, vector_size=100, workers=1)

I've tried both dm and dbow as well. dm gives better result(similarity score) as compared to dbow. I understood the concepts of dm vs dbow. But don't know which method is good for similarity measures between two documents.

First question: Which method is the best to perform well on similarities?

model.wv.n_similarity(<words_1>, <words_2>) gives similarity score using word vectors.

model.docvecs.similarity_unseen_docs(model, doc1, doc2) gives similarity score using doc vectors where doc1 and doc2 are not tags/ or indexes of doctags. Each doc1 and doc2 contains 10-20 words kind of sentences.

Both wv.n_similarity and docvecs.similarity_unseen_docs provide different similarity scores on same types of documents.

docvecs.similarity_unseen_docs gives little bit good results as compared to wv.n_similarity but wv.n_similarity sometimes also gives good results.

Question: What is the difference between docvecs.similarity_unseen_docs and wv.n_similarity? Can I use docvecs.similarity_unseen_docs to find the similarity score between unseen data (It might be a silly question)?

Why I asked because docvecs.similarity_unseen_docs provides similarity score on tags, not on actual words belonging to their tags. I'm not sure, please correct me here, if I'm wrong.

How can I convert cosine similarity score to probability?

Thanks.

model = Doc2Vec(alpha=0.025, min_alpha=0.0001, min_count=2, window=10, dm=1, dm_mean=1, epochs=50, seed=25, vector_size=100, workers=4)
# Training of the model
tagged_data = [TaggedDocument(words=_d, tags=[str(i)]) for i, _d in enumerate(<list_of_list_of_tokens>)]
model.build_vocab(tagged_data)
model.train(tagged_data, total_examples=model.corpus_count, epochs=model.epochs)

# Finding similarity score
model.wv.n_similarity(<doc_words1>, <doc_words2>)
model.random.seed(25)
model.docvecs.similarity_unseen_docs(model, <doc_words1>, <doc_words2>)


来源: stackexchange

问:
How to change all projects in a solution file to C++17 MSVC?
I am using VS2017 (Version 15.9.12) and generated a solution file with CMake 3.14 for the VS compiler Visual Studio 15 2017.
I want to use some C++17 features. When I have a look in the property page of a project the field C/C++->Language->C++ Language Standard is empty. There I can change it to /std:c++17 (and some other options).

Since the code is an external project I do not want to change the CMake file to add CXX_Standard 17.

Does visual studio set a compiler with C++17 option for a whole project or do I have to change this for each subprojects manually?

答: Looks like you have to change this for each subproject.  Alternatively just run cmake -DCMAKE_CXX_STANDARD=17 -S /path/to/external/project -B bld (for example) and CMake will generate the projects with the desired standard (unless overridden by CMakeLists.txt).

ContentLicense: CC BY-SA 4.0


问:
Found unexpected optical bounds (red pixel) on top border at x=14
Recently, I'm updating to Android Studio 3.3 and Gradle 3.3, in this version the gradle.property 'android.enableAapt2=false' has no effect because AAPT2 is now always used. The real problem comes when I delete this line, because can't compile, the next error that throws is:

Android resource compilation failed

error: found unexpected optical bounds (red pixel) on top border at x=14.

In the previous versions we can solve this problem as in this post. Now I can't compile my app cause exists this error.

Update from: 2019-01-24

Finally I found the real problem with the new log error in Android Studio 3.2:

Android resource compilation failed
  Output:  error: .

Command: /Users/myProject/.gradle/caches/transforms-1/files-1.1/aapt2-
  3.2.1-4818971-osx.jar/0a24b213ff9fab058ea2520938e2e6e3/aapt2-3.2.1->4818971-osx/aapt2 compile --legacy \
         -o \
         /Users/myProject/android->app/myProject/app/build/intermediates/res/merged/debug \
         /Users/myProject/android-app/myProject/app/src/main/res/drawable->hdpi/balloon_incoming_normal.9.png

Daemon:  AAPT2 aapt2-3.2.1-4818971-osx Daemon #1

The file produce this problem is:

URL to download

Any idea? Thanks in advance!

答:
I solved this issue following this steps:

Copy the resource, duplicating the file.

Rename the file to original name

Example:
      balloon_outgoing_normal.9 - copy.png
      to
      balloon_outgoing_normal.png

Remove the file 9-patched that doesnt works.

Example:: balloon_outgoing_normal.9.png

Open the file in Android Studio

Right-click on each file (mdpi, hdpi, etc..)

Select Create-9-Patch File... and save each file on your respective folder (mdpi, hdpi, etc..)

After this steps, I had success on compilation.


问:
Find subpage urls with articles and collect data from them
The script should find the addresses of subpages with articles and collect the necessary data from them. The data should go to the database but I don't know how to make the script pull the content of each article from every page of the blog.</p>

```<code>import requests
from bs4 import BeautifulSoup
from nltk.tokenize import RegexpTokenizer
import nltk
import matplotlib.pyplot as plt
import seaborn as sns

url = 'https://xxx/'

r = requests.get(url)
# Extract HTML
html = r.text
# Create a BeautifulSoup object from the HTML
soup = BeautifulSoup(html, "html5lib")

# Get the text

text = soup.get_text()
# Create tokenizer
tokenizer = RegexpTokenizer('\w+')

# Create tokens
tokens = tokenizer.tokenize(text)

# Initialize new list
words = []

# Loop through list

for word in tokens:
    words.append(word.lower())

# Get English stopwords and print some of them
sw = nltk.corpus.stopwords.words('english')

# Initialize new list
words_ns = []

for word in words:
    if word not in sw:
        words_ns.append(word)

# plotting
freqdist1 = nltk.FreqDist(words_ns)
freqdist1.plot(25)

print(soup.get_text())
</code>```

答:
You could do the whole thing with beautifulsoup as requests. The text extraction code is by  @nmgeek; the same question there has other methods to choose from. I am guessing you can then handle the text with nltk. The method is nice as you can play with which selectors you add to list. You can achieve something similar with selector list passed to select i.e. [item.text for item in soup.select('selector list goes here')

Edit: Below gets you all the links but seems website blocks you after a while. Have a look at rotating IPs and these/User-Agents in the loop over all_links

If you have to resort to selenium at least you have the list of all article links to you can loop over and .get with selenium

```<code>import requests
from bs4 import BeautifulSoup as bs

url = 'https://teonite.com/blog/page/{}/index.html'
all_links = []

headers = {
    'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
    'User-Agent' : 'Mozilla/5.0'
}
with requests.Session() as s:
    r = s.get('https://teonite.com/blog/')
    soup = bs(r.content, 'lxml')
    article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')]
    all_links.append(article_links)
    num_pages = int(soup.select_one('.page-number').text.split('/')[1])

    for page in range(2, num_pages + 1):
        r = s.get(url.format(page))
        soup = bs(r.content, 'lxml')
        article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')]
        all_links.append(article_links)

    all_links = [item for i in all_links for item in i]

    for article in all_links:
        #print(article)
        r = s.get(article, headers = headers)
        soup = bs(r.content, 'lxml')
        [t.extract() for t in soup(['style', 'script', '[document]', 'head', 'title'])]
        visible_text = soup.getText()   # taken from https://stackoverflow.com/a/19760007/6241235 @nmgeek
        # here I think you need to consider IP rotation/User-Agent changing
        try:
            print(soup.select_one('.post-title').text)
        except:
            print(article)
            print(soup.select_one('h1').text)
            break
        # do something with text
</code>```

Adding in selenium seems to definitely solve bad request problem of being blocked:

```<code>import requests
from bs4 import BeautifulSoup as bs
from selenium import webdriver

url = 'https://teonite.com/blog/page/{}/index.html'
all_links = []

with requests.Session() as s:
    r = s.get('https://teonite.com/blog/')
    soup = bs(r.content, 'lxml')
    article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')]
    all_links.append(article_links)
    num_pages = int(soup.select_one('.page-number').text.split('/')[1])

    for page in range(2, num_pages + 1):
        r = s.get(url.format(page))
        soup = bs(r.content, 'lxml')
        article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')]
        all_links.append(article_links)

all_links = [item for i in all_links for item in i]

d = webdriver.Chrome()

for article in all_links:
    d.get(article)
    soup = bs(d.page_source, 'lxml')
    [t.extract() for t in soup(['style', 'script', '[document]', 'head', 'title'])]
    visible_text = soup.getText()   # taken from https://stackoverflow.com/a/19760007/6241235 @nmgeek

    try:
        print(soup.select_one('.post-title').text)
    except:
        print(article)
        print(soup.select_one('h1').text)
        break #for debugging
    # do something with text
d.quit()
</code>```

Body:
The script should find the addresses of subpages with articles and collect the necessary data from them. The data should go to the database but I don't know how to make the script pull the content of each article from every page of the blog.

import requests
from bs4 import BeautifulSoup
from nltk.tokenize import RegexpTokenizer
import nltk
import matplotlib.pyplot as plt
import seaborn as sns

url = 'https://xxx/'

r = requests.get(url)
# Extract HTML
html = r.text
# Create a BeautifulSoup object from the HTML
soup = BeautifulSoup(html, "html5lib")

# Get the text

text = soup.get_text()
# Create tokenizer
tokenizer = RegexpTokenizer('\w+')

# Create tokens
tokens = tokenizer.tokenize(text)

# Initialize new list
words = []

# Loop through list

for word in tokens:
    words.append(word.lower())

# Get English stopwords and print some of them
sw = nltk.corpus.stopwords.words('english')

# Initialize new list
words_ns = []

for word in words:
    if word not in sw:
        words_ns.append(word)

# plotting
freqdist1 = nltk.FreqDist(words_ns)
freqdist1.plot(25)

print(soup.get_text())

Body:
You could do the whole thing with beautifulsoup as requests. The text extraction code is by  @nmgeek; the same question there has other methods to choose from. I am guessing you can then handle the text with nltk. The method is nice as you can play with which selectors you add to list. You can achieve something similar with selector list passed to select i.e. [item.text for item in soup.select('selector list goes here')

Edit: Below gets you all the links but seems website blocks you after a while. Have a look at rotating IPs and these/User-Agents in the loop over all_links

If you have to resort to selenium at least you have the list of all article links to you can loop over and .get with selenium

import requests
from bs4 import BeautifulSoup as bs

url = 'https://teonite.com/blog/page/{}/index.html'
all_links = []

headers = {
    'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
    'User-Agent' : 'Mozilla/5.0'
}
with requests.Session() as s:
    r = s.get('https://teonite.com/blog/')
    soup = bs(r.content, 'lxml')
    article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')]
    all_links.append(article_links)
    num_pages = int(soup.select_one('.page-number').text.split('/')[1])

    for page in range(2, num_pages + 1):
        r = s.get(url.format(page))
        soup = bs(r.content, 'lxml')
        article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')]
        all_links.append(article_links)

    all_links = [item for i in all_links for item in i]

    for article in all_links:
        #print(article)
        r = s.get(article, headers = headers)
        soup = bs(r.content, 'lxml')
        [t.extract() for t in soup(['style', 'script', '[document]', 'head', 'title'])]
        visible_text = soup.getText()   # taken from https://stackoverflow.com/a/19760007/6241235 @nmgeek
        # here I think you need to consider IP rotation/User-Agent changing
        try:
            print(soup.select_one('.post-title').text)
        except:
            print(article)
            print(soup.select_one('h1').text)
            break
        # do something with text

Adding in selenium seems to definitely solve bad request problem of being blocked:

import requests
from bs4 import BeautifulSoup as bs
from selenium import webdriver

url = 'https://teonite.com/blog/page/{}/index.html'
all_links = []

with requests.Session() as s:
    r = s.get('https://teonite.com/blog/')
    soup = bs(r.content, 'lxml')
    article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')]
    all_links.append(article_links)
    num_pages = int(soup.select_one('.page-number').text.split('/')[1])

    for page in range(2, num_pages + 1):
        r = s.get(url.format(page))
        soup = bs(r.content, 'lxml')
        article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')]
        all_links.append(article_links)

all_links = [item for i in all_links for item in i]

d = webdriver.Chrome()

for article in all_links:
    d.get(article)
    soup = bs(d.page_source, 'lxml')
    [t.extract() for t in soup(['style', 'script', '[document]', 'head', 'title'])]
    visible_text = soup.getText()   # taken from https://stackoverflow.com/a/19760007/6241235 @nmgeek

    try:
        print(soup.select_one('.post-title').text)
    except:
        print(article)
        print(soup.select_one('h1').text)
        break #for debugging
    # do something with text
d.quit()


问:
Strip known extension from filename
I have a bunch of txt files. I want to strip out the .txt from the filename (which I am reading via os.walk).

How could I achieve this?

fileName.rstrip(".txt") seems to remove the letters .,t,x rather than removing the substring .txt

答:
I would use rpartition (partition from right), and get the first elemnet from resulting tuple:

```<code>fileName.rpartition(".txt")[0]
</code>```

rpartition is guaranteed to generate a 3-element tuple in the form:

```<code>(before, sep, after)
</code>```

So, for filenames with .txt extension e.g. foobar.txt you would get:

```<code>('foobar', '.txt', '')
</code>```

For files that does not end with .txt e.g. foobar:

```<code>('foobar', '', '')
</code>```

so getting the first element would work in all cases.

Title: Strip known extension from filename

Body:
I would use rpartition (partition from right), and get the first elemnet from resulting tuple:

fileName.rpartition(".txt")[0]

rpartition is guaranteed to generate a 3-element tuple in the form:

(before, sep, after)

So, for filenames with .txt extension e.g. foobar.txt you would get:

('foobar', '.txt', '')

For files that does not end with .txt e.g. foobar:

('foobar', '', '')

so getting the first element would work in all cases.


问:
Showing an already existing "Fortune" when going back to the page
"Once a fortune has been generated, if they return to the site they should be shown their existing fortune for the next year from the date it was generated.

If the user wants to generate a new fortune, give them a link to do so."

My problem is I can't figure out how to make it stay on the generated fortune page when going back to the website, I tried searching it up but I did not find anything. I think i already made a reset link but I am unsure.
What kind of code do I need to make it stay on the fortune page?

I searched it up online, I've tried somehow making it check that cookies were applied but we were not taught that.

Main PHP Page (index.php)

```<code><html lang="en">
<head>
    <meta charset="utf-8">
    <title>Week 4 Tutorial - Fortune Teller</title>
</head>

<body>
    <img src="fortune-teller.jpg" alt="The Fortune Teller" style="float:right;" />
    <h1>Fortune Teller</h1>
    <p>The fortune teller has looked deep in your soul, and has a sense of who you are and what will come in your life.</p>
    <p>What is your fate? How long will you live? Will you be successful or struggle in life? Find out below...</p>
    <form method="post" action="fortune.php">
        <label for="fname">First Name</label>
        <input type="text" id="fname" name="fname" />
        <br />
        <label for="colour">Favourite Colour</label>
        <input type="text" id="colour" name="colour" />
        <br />
        <label for="birthmonth">Birth Month</label>
        <select id="birthmonth" name="birthmonth">
            <option value="1">January</option>
            <option value="2">February</option>
            <option value="3">March</option>
            <option value="4">April</option>
            <option value="5">May</option>
            <option value="6">June</option>
            <option value="7">July</option>
            <option value="8">August</option>
            <option value="9">September</option>
            <option value="10">October</option>
            <option value="11">November</option>
            <option value="12">December</option>
        </select>
        <br />
        <input type="submit" id="submit" name="submit" value="Tell my fortune" />
    </form>
</body>
</html>
</code>```

Page after you complete the form

```<code><?php
if(isset($_COOKIE['lastVisit']))
{
$visit = $_COOKIE['lastVisit'];
echo "Your last fortune was told at ". $visit;
}
//set to expire in a year
$year = +31556926 + time();
setcookie('lastVisit', date("G:i - m/d/y"), $year);
?>

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Week 4 Tutorial - Fortune Teller</title>
</head>

<body>
    <img src="fortune-teller.jpg" alt="The Fortune Teller" style="float:right;" />
    <h1>Fortune Teller</h1>
    <p>The fortune teller has looked deep in your soul, and has a sense of who you are and what will come in your life.</p>
    <p>What is your fate? How long will you live? Will you be successful or struggle in life? Find out below...</p>

    <h2>Fortune for <?php echo $_POST['fname']; ?></h2>
    <p>
    <?php
        if($_POST['fname']=="Tony"){
                echo "You like to control everyone within your influence, to shape things to your own liking. ";
        }
        else if($_POST['fname']=="Ebonie"){
            echo "You're' fine when in harmony but changeable when in discord, because many of your best qualities are then reversed. ";
        }
        else if($_POST['fname']=="Eric"){
            echo "You have a vivid imagination who can bring inspired messages to the world. ";
        }
        else if($_POST['fname']=="Kristina"){
            echo "EXTREMES in fortune, health and spirituality. You are very versatile, idealistic and intuitive. ";
        }
        else if($_POST['fname']=="Jamie"){
            echo "You're' honest, benevolent, brilliant and often inventive, full of high inspirations. ";
        }else{
            echo "You're a decent person at best. ";
        }

        //Birthmonth - something to do with the season they were born in
        if($_POST['birthmonth']<4){
            //January, February, March - Q1 (Winter)
            echo "You are independent, analytic, and a born leader. ";
        }
        else if($_POST['birthmonth']<6){
            //April, May, June - Q2 (Spring)
            echo "You may be perceived as being stubborn, bossy, and impulsive. ";
        }
        else if($_POST['birthmonth']<9){
            //July, August, September - Q3 (Summer)
            echo "You are a sincere, candid, and sympathetic individual.. ";
        }
        else if($_POST['birthmonth']<12){
            //October, November, December - Q4 (Fall)
            echo "You are a practical philosopher who values a stable lifestyle. ";
        }

        //favourite colour - something about your job
        if($_POST['colour']=="red"){
            echo "You will find success in your career this month.";
        }
        else if($_POST['colour']=="blue"){
            echo "You need to be careful as you're on the verge of your employment being termenated.";
        }
        else if($_POST['colour']=="green"){
            echo "Show up to work early, keep your nose clean and your head down and you'll get a raise next month.";
        }
        else if($_POST['colour']=="yellow"){
            echo "A management position is in your future.";
        }
        else if($_POST['colour']=="black"){
            echo "Your difficulty working with others will cause tensions in the workplace in the near future.";
        }
        else{
            echo "Keep doing your job as well as you do now, good things will happen.";
        }
    ?>
    </p>
    <?php
      $url = htmlspecialchars($_SERVER['HTTP_REFERER']);
      echo "<a href='$url'>Reset</a>";
    ?>
</body>
</html>
</code>```

The expected outcome is when you complete the form it will save the last time you got to the page, displaying the date of your last fortune which I got it to do, but it also needs to have you remain on that page the next time you enter the page and with a reset button which takes you back to the form.

答:
your index.php is just missing the redirect to the result page.

```<code><?php
// at you index.php
ob_start();
if(isset($_COOKIE['lastVisit'])){
    header("Location: yoursite.com/fortune.php");
    ob_flush();
} else {
?>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Week 4 Tutorial - Fortune Teller</title>
</head>

<body>
    <img src="fortune-teller.jpg" alt="The Fortune Teller" style="float:right;" />
    <h1>Fortune Teller</h1>
    <p>The fortune teller has looked deep in your soul, and has a sense of who you are and what will come in your life.</p>
    <p>What is your fate? How long will you live? Will you be successful or struggle in life? Find out below...</p>
    <form method="post" action="fortune.php">
    ...
<?php
    ob_flush();
}
</code>```

But this is kind of dirty. is it possible to use a database? since if you're only using cookies, it will not be permanent ( user can just delete the cookie from their browser, and it will be gone).

Also, in your fortune.php

```<code><?php
if(isset($_COOKIE['lastVisit']))
{
    $visit = $_COOKIE['lastVisit'];
    echo "Your last fortune was told at ". $visit;
}
//set to expire in a year
$year = +31556926 + time(); // i think you're missing something here
setcookie('lastVisit', date("G:i - m/d/y"), $year);
?>
</code>```

$year = +31556926 + time(); is that a typo? because i don't think $year= +31556926 won't run. anyways, if you do that, it won't end in a year, because everytime the user visits that page (fortune.php), his/her cookie will be set to today (since you're using php's time()) + 31556926. which will never end (the cookie's expiry will always be refreshed.

hope this helps! would be happy to answer if you've got any more questions!

Body:
"Once a fortune has been generated, if they return to the site they should be shown their existing fortune for the next year from the date it was generated.

If the user wants to generate a new fortune, give them a link to do so."

My problem is I can't figure out how to make it stay on the generated fortune page when going back to the website, I tried searching it up but I did not find anything. I think i already made a reset link but I am unsure.
What kind of code do I need to make it stay on the fortune page?

I searched it up online, I've tried somehow making it check that cookies were applied but we were not taught that.

Main PHP Page (index.php)

    <meta charset="utf-8">
    <title>Week 4 Tutorial - Fortune Teller</title>

Fortune Teller

The fortune teller has looked deep in your soul, and has a sense of who you are and what will come in your life.

What is your fate? How long will you live? Will you be successful or struggle in life? Find out below...

    <form method="post" action="fortune.php">
        First Name
        <input type="text" id="fname" name="fname" />

        Favourite Colour
        <input type="text" id="colour" name="colour" />

        Birth Month
        <select id="birthmonth" name="birthmonth">
            <option value="1">January</option>
            <option value="2">February</option>
            <option value="3">March</option>
            <option value="4">April</option>
            <option value="5">May</option>
            <option value="6">June</option>
            <option value="7">July</option>
            <option value="8">August</option>
            <option value="9">September</option>
            <option value="10">October</option>
            <option value="11">November</option>
            <option value="12">December</option>
        </select>

        <input type="submit" id="submit" name="submit" value="Tell my fortune" />
    </form>

Page after you complete the form

<?php
if(isset($_COOKIE['lastVisit']))
{
$visit = $_COOKIE['lastVisit'];
echo "Your last fortune was told at ". $visit;
}
//set to expire in a year
$year = +31556926 + time();
setcookie('lastVisit', date("G:i - m/d/y"), $year);
?>

<!doctype html>

    <meta charset="utf-8">
    <title>Week 4 Tutorial - Fortune Teller</title>

Fortune Teller

The fortune teller has looked deep in your soul, and has a sense of who you are and what will come in your life.

What is your fate? How long will you live? Will you be successful or struggle in life? Find out below...

Fortune for <?php echo $_POST['fname']; ?>

    <?php
        if($_POST['fname']=="Tony"){
                echo "You like to control everyone within your influence, to shape things to your own liking. ";
        }
        else if($_POST['fname']=="Ebonie"){
            echo "You're' fine when in harmony but changeable when in discord, because many of your best qualities are then reversed. ";
        }
        else if($_POST['fname']=="Eric"){
            echo "You have a vivid imagination who can bring inspired messages to the world. ";
        }
        else if($_POST['fname']=="Kristina"){
            echo "EXTREMES in fortune, health and spirituality. You are very versatile, idealistic and intuitive. ";
        }
        else if($_POST['fname']=="Jamie"){
            echo "You're' honest, benevolent, brilliant and often inventive, full of high inspirations. ";
        }else{
            echo "You're a decent person at best. ";
        }

        //Birthmonth - something to do with the season they were born in
        if($_POST['birthmonth']<4){
            //January, February, March - Q1 (Winter)
            echo "You are independent, analytic, and a born leader. ";
        }
        else if($_POST['birthmonth']<6){
            //April, May, June - Q2 (Spring)
            echo "You may be perceived as being stubborn, bossy, and impulsive. ";
        }
        else if($_POST['birthmonth']<9){
            //July, August, September - Q3 (Summer)
            echo "You are a sincere, candid, and sympathetic individual.. ";
        }
        else if($_POST['birthmonth']<12){
            //October, November, December - Q4 (Fall)
            echo "You are a practical philosopher who values a stable lifestyle. ";
        }

        //favourite colour - something about your job
        if($_POST['colour']=="red"){
            echo "You will find success in your career this month.";
        }
        else if($_POST['colour']=="blue"){
            echo "You need to be careful as you're on the verge of your employment being termenated.";
        }
        else if($_POST['colour']=="green"){
            echo "Show up to work early, keep your nose clean and your head down and you'll get a raise next month.";
        }
        else if($_POST['colour']=="yellow"){
            echo "A management position is in your future.";
        }
        else if($_POST['colour']=="black"){
            echo "Your difficulty working with others will cause tensions in the workplace in the near future.";
        }
        else{
            echo "Keep doing your job as well as you do now, good things will happen.";
        }
    ?>

    <?php
      $url = htmlspecialchars($_SERVER['HTTP_REFERER']);
      echo "Reset";
    ?>

The expected outcome is when you complete the form it will save the last time you got to the page, displaying the date of your last fortune which I got it to do, but it also needs to have you remain on that page the next time you enter the page and with a reset button which takes you back to the form.

Body:
your index.php is just missing the redirect to the result page.

<?php
// at you index.php
ob_start();
if(isset($_COOKIE['lastVisit'])){
    header("Location: yoursite.com/fortune.php");
    ob_flush();
} else {
?>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Week 4 Tutorial - Fortune Teller</title>
</head>

<body>
    <img src="fortune-teller.jpg" alt="The Fortune Teller" style="float:right;" />
    <h1>Fortune Teller</h1>
    <p>The fortune teller has looked deep in your soul, and has a sense of who you are and what will come in your life.</p>
    <p>What is your fate? How long will you live? Will you be successful or struggle in life? Find out below...</p>
    <form method="post" action="fortune.php">
    ...
<?php
    ob_flush();
}

But this is kind of dirty. is it possible to use a database? since if you're only using cookies, it will not be permanent ( user can just delete the cookie from their browser, and it will be gone).

Also, in your fortune.php

<?php
if(isset($_COOKIE['lastVisit']))
{
    $visit = $_COOKIE['lastVisit'];
    echo "Your last fortune was told at ". $visit;
}
//set to expire in a year
$year = +31556926 + time(); // i think you're missing something here
setcookie('lastVisit', date("G:i - m/d/y"), $year);
?>

$year = +31556926 + time(); is that a typo? because i don't think $year= +31556926 won't run. anyways, if you do that, it won't end in a year, because everytime the user visits that page (fortune.php), his/her cookie will be set to today (since you're using php's time()) + 31556926. which will never end (the cookie's expiry will always be refreshed.

hope this helps! would be happy to answer if you've got any more questions!


问:
Is %$var dereferencing a Perl hash?
I'm sending a subroutine a hash, and fetching it with my($arg_ref) = @_;

But what exactly is %$arg_ref? Is %$ dereferencing the hash?

答: A good brief introduction to references (creating them and using them) in Perl is perldoc perfeftut. You can also read it online (or get it as a pdf). (It talks more about references in complex data structures than in terms of passing in and out of subroutines, but the syntax is the same.)

OwnerDisplayName: Stian S

LastEditorDisplayName: brian d foy

ContentLicense: CC BY-SA 2.5

Title: Is %$var dereferencing a Perl hash?

OwnerDisplayName: Telemachus


问:
Install my .app release file on iOS device file via terminal from Mac
I've seen a number of similar questions asked, but I'm still not sure they answer my own question. I also read this.

My specific requirements (or lack thereof) are:

I don't want my app to appear on the app store

I just want to install it manually on a number of iOS devices.

I don't mind using the terminal or a third party app.

I don't mind if the user has to manually select "trust this developer/app" from within the iOS device before being able to run the app.

I'm a little confused because what I've read says that I need a developer account, or Enterprise account, to install.

But how is this so? XCode, for example, installs the build perfectly, and I don't have a developer account. Is there not an XCode terminal comman I can execute to simply install the .app file on the device?

Or would this require jail-breaking? If so, how come? XCode does it just fine...

I understand Apple would probably want to restrict this behaviour due to security, but I wanted to ask. Perhaps the only way really is an Apple developer/Enterprise account.

Possible solutions could be:

Fruitstrap => "Install and debug iPhone apps without using Xcode. Designed to work on unjailbroken devices."

Sideloading => But I think this requires revealing your code.

答:
EDIT: for the purpose of building the app on the device as a debug build straight from XCode, you don't need a payed Developer account, you just need to register as a Apple Developer & login to XCode with that account and you should be to build debug builds on your device.

You have a few alternatives here:

1/ export the .ipa file after you build a release version of your app in XCode and distribute it to the devices, you want to install it on. You will however need to sign your app with your certificate of iOS developer. More about it here:

https://wiki.genexus.com/commwiki/servlet/wiki?34616,HowTo%3A+Create+an+.ipa+file+from+XCode

2/ Basically the same thing as above, but you can use some 3rd party service for build distribution (which is easier than distributing .ipa files around. Something like Crashlytics Beta or something. Even TestFlight would work, tho I am not sure if app in store is not required.

Either way, you will have to deal with code signing and need to have a Apple Developer account, unless you distribute it via building it straight to the phone as a debug build.


答:
I would recomment using the OS library.</p>

```<code>name, ext = os.path.splitext(path)
</code>```

Title: Strip known extension from filename

Body:
I have a bunch of txt files. I want to strip out the .txt from the filename (which I am reading via os.walk).

How could I achieve this?

fileName.rstrip(".txt") seems to remove the letters .,t,x rather than removing the substring .txt

Body:
I would recomment using the OS library.

name, ext = os.path.splitext(path)


问:
Union Find to See if Shape Goes on One Side or the Other
I'm quite new to graphs and want to figure out my segmentation fault problem. My output is already correct but for some reason, as numShapes approach a higher number ~40, a segmentation fault error occurs.

Program Details:
The circuit has two sides and you must determine if each shape can fit into side one, if it can't, determine if it can fit into side two, if it can't again, output none. No shape (with their specific X & Y Spacings) must be overlapping.

Thank you.

Code

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <vector>
using namespace std;

int numShapes, XSpacing,YSpacing;
vector<int> Dimension(2,0);

string delimiter(string temp);
void main_pr();
bool bounded(struct Graph* graph,vector<int> coordinates, int N);

struct Edge{
    int src, dest, part;
    int Xll, Yll;
    int Xur, Yur;
};

struct Graph{
    int V, E;
    struct Edge* edge;
};

struct Graph* createGraph(int V, int E){
    struct Graph* graph =
           (struct Graph*) malloc( sizeof(struct Graph) );
    graph->V = V;
    graph->E = E;
    graph->edge =
        (struct Edge*) malloc( graph->E * sizeof( struct Edge ) );

    return graph;
}

int find(int parent[], int i){
    if (parent[i] == -1)
        return i;
    return find(parent, parent[i]);
}

// A utility function to do union of two subsets
void Union(int parent[], int x, int y){
    int xset = find(parent, x);
    int yset = find(parent, y);
    if(xset!=yset){
       parent[xset] = yset;
    }
}

struct Graph* graph;
struct Graph* graph2;

int main(){
int check = 0;
char _temp;
string temp;
string temp1,temp2;

for(int j=0;j<4;j++){
    while(_temp != '='){
        cin>>_temp;
    }
    _temp=0;
    cin>>temp;
    switch(j){
        case 0:
             numShapes = stoi(temp);
             if(numShapes == 0){
                 cout<<"Program terminating...\n";
                 return 0;
             }
        case 1:
             XSpacing = stoi(temp);
        case 2:
             YSpacing = stoi(temp);
        case 3:
            if(j==3)
            for(int i=0;i<temp.size();i++){
                if(temp[i] == 'x')
                    check = 1;
                if(check == 0)
                    temp1.push_back(temp[i]);
                else{
                    if(temp[i] != 'x')
                    temp2.push_back(temp[i]);
                }
        }
    }
}

 Dimension[0]=stoi(temp1);
 Dimension[1]=stoi(temp2);

   main_pr();

return 0;
}

void main_pr(){
string temp;
vector<int> coordinates(4,0);
graph = createGraph(numShapes, numShapes);
graph2 = createGraph(numShapes, numShapes);
int a = 1;
int b = 1;
int check = 0;

for(int i=0; i<numShapes; i++){
        for(int j=0; j<4; j++){
            cin>>temp;
            switch(j){
                case 0:
                    coordinates[0] = stoi(delimiter(temp));
                    break;
                case 1:
                    coordinates[1] = stoi(delimiter(temp));
                    break;
                case 2:
                    coordinates[2] = stoi(delimiter(temp));
                    break;
                case 3:
                    coordinates[3] = stoi(temp);
                    break;
            }
        }
    if(i == 0){
    graph->V = 2;
    graph->E = 2;
    graph->edge[0].src = 0;
    graph->edge[0].dest = 1;
    graph->edge[0].Xll = coordinates[0];
    graph->edge[0].Yll = coordinates[1];
    graph->edge[0].Xur = coordinates[2];
    graph->edge[0].Yur = coordinates[3];
    cout<<"Side 1\n";
    }
    else if(bounded(graph,coordinates,a) == true){
        graph->V = a+2;
        graph->E = a+2;
        graph->edge[a].src = a;
        graph->edge[a].dest = a+1;
        graph->edge[a].Xll = coordinates[0];
        graph->edge[a].Yll = coordinates[1];
        graph->edge[a].Xur = coordinates[2];
        graph->edge[a].Yur = coordinates[3];
        a++;
        cout<<"Side 1\n";
    }
    else if(check == 0){
        graph2->V = 2;
        graph2->E = 2;
        graph2->edge[0].src = 0;
        graph2->edge[0].dest = 1;
        graph2->edge[0].Xll = coordinates[0];
        graph2->edge[0].Yll = coordinates[1];
        graph2->edge[0].Xur = coordinates[2];
        graph2->edge[0].Yur = coordinates[3];
        cout<<"Side 2\n";
        check = 1;
    }
    else if(bounded(graph2,coordinates,b) == true){
        graph->V = b+2;
        graph->E = b+2;
        graph2->edge[b].src = b;
        graph2->edge[b].dest = b+1;
        graph2->edge[b].Xll = coordinates[0];
        graph2->edge[b].Yll = coordinates[1];
        graph2->edge[b].Xur = coordinates[2];
        graph2->edge[b].Yur = coordinates[3];
        b++;
        cout<<"Side 2\n";
    }
    else{
        cout<<"None\n";
    }
}

}

bool bounded(struct Graph* graph,vector<int> coordinates, int N){
int *parent = (int*) malloc( graph->V * sizeof(int) );
int x = XSpacing - 1;
int y = YSpacing - 1;
int const Length = Dimension[0];
int const Height = Dimension[1];
int Xll = coordinates[0];
int Yll = coordinates[1];
int Xur = coordinates[2];
int Yur = coordinates[3];

memset(parent, -1, sizeof(int) * graph->V);

    for(int i = 0; i < graph->E; ++i)
    {
        int A = find(parent, graph->edge[i].src);
        int B = find(parent, graph->edge[i].dest);

                if(Xll >= graph->edge[i].Xll-x && Xur <= graph->edge[i].Xur+x)
                    if(Yll >= graph->edge[i].Yll-y && Yur <= graph->edge[i].Yur+y)
                        return false;

                if((Yll >= graph->edge[i].Yll-y && Yll <= graph->edge[i].Yur+y) || (Yur >= graph->edge[i].Yll-y && Yur <= graph->edge[i].Yur+y)){             //if on the right
                    if(Xll >= graph->edge[i].Xll-x && Xll <= graph->edge[i].Xur+x)
                        return false;
                    if(Xur <= graph->edge[i].Xur+x && Xur >= graph->edge[i].Xll-x)
                        return false;
                }

                if((Xll >= graph->edge[i].Xll-x && Xll <= graph->edge[i].Xur+x) || (Xur >= graph->edge[i].Xll-x && Xur <= graph->edge[i].Xur+x)){             //if on the right
                    if(Yll >= graph->edge[i].Yll-y && Yll <= graph->edge[i].Yur+y)
                        return false;
                    if(Yur <= graph->edge[i].Yur+y && Yur >= graph->edge[i].Yll-y)
                        return false;
                }

        if(A == B)
            return true;

        Union(parent, A, B);
    }
    cout<<endl;

return 0;
}

string delimiter(string temp){

    if(temp.back() == ',')
        temp.pop_back();

return temp;
}
</code>```

Input

```<code>NumShapes=8
XSpacing=10
YSpacing=2
Dimension=100x30
10, 4, 20, 6
25, 5, 55, 8
10, 8, 15, 12
0, 20, 20, 22
0, 20, 10, 22
0, 10, 5, 15
25, 27, 75, 28
25, 10, 55, 13
</code>```

Output

```<code>SIDE1
SIDE2
SIDE1
SIDE1
SIDE2
SIDE2
SIDE1
SIDE1
</code>```

答:
Dont use malloc in c++ to create objects. Actually malloc does not create objects. Here

```<code>struct Graph* graph =  (struct Graph*) malloc( sizeof(struct Graph) );
</code>```

you merely allocate memory for a Graph but you do not construct a Graph object.

From cppreference on std::malloc:

This function does not call constructors or initialize memory in
  any way. There are no ready-to-use smart pointers that could guarantee
  that the matching deallocation function is called. The preferred
  method of memory allocation in C++ is using RAII-ready functions
  std::make_unique, std::make_shared, container constructors, etc, and,
  in low-level library code, new-expression.

Ergo, use standard containers if you can, else use smart pointers. new is for low-level library code and malloc has no place in creating objects in C++.

Body:
I'm quite new to graphs and want to figure out my segmentation fault problem. My output is already correct but for some reason, as numShapes approach a higher number ~40, a segmentation fault error occurs.

Program Details:
The circuit has two sides and you must determine if each shape can fit into side one, if it can't, determine if it can fit into side two, if it can't again, output none. No shape (with their specific X & Y Spacings) must be overlapping.

Thank you.

Code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <vector>
using namespace std;

int numShapes, XSpacing,YSpacing;
vector<int> Dimension(2,0);

string delimiter(string temp);
void main_pr();
bool bounded(struct Graph* graph,vector<int> coordinates, int N);

struct Edge{
    int src, dest, part;
    int Xll, Yll;
    int Xur, Yur;
};

struct Graph{
    int V, E;
    struct Edge* edge;
};

struct Graph* createGraph(int V, int E){
    struct Graph* graph =
           (struct Graph*) malloc( sizeof(struct Graph) );
    graph->V = V;
    graph->E = E;
    graph->edge =
        (struct Edge*) malloc( graph->E * sizeof( struct Edge ) );

    return graph;
}

int find(int parent[], int i){
    if (parent[i] == -1)
        return i;
    return find(parent, parent[i]);
}

// A utility function to do union of two subsets
void Union(int parent[], int x, int y){
    int xset = find(parent, x);
    int yset = find(parent, y);
    if(xset!=yset){
       parent[xset] = yset;
    }
}

struct Graph* graph;
struct Graph* graph2;

int main(){
int check = 0;
char _temp;
string temp;
string temp1,temp2;

for(int j=0;j<4;j++){
    while(_temp != '='){
        cin>>_temp;
    }
    _temp=0;
    cin>>temp;
    switch(j){
        case 0:
             numShapes = stoi(temp);
             if(numShapes == 0){
                 cout<<"Program terminating...\n";
                 return 0;
             }
        case 1:
             XSpacing = stoi(temp);
        case 2:
             YSpacing = stoi(temp);
        case 3:
            if(j==3)
            for(int i=0;i<temp.size();i++){
                if(temp[i] == 'x')
                    check = 1;
                if(check == 0)
                    temp1.push_back(temp[i]);
                else{
                    if(temp[i] != 'x')
                    temp2.push_back(temp[i]);
                }
        }
    }
}

 Dimension[0]=stoi(temp1);
 Dimension[1]=stoi(temp2);

   main_pr();

return 0;
}

void main_pr(){
string temp;
vector<int> coordinates(4,0);
graph = createGraph(numShapes, numShapes);
graph2 = createGraph(numShapes, numShapes);
int a = 1;
int b = 1;
int check = 0;

for(int i=0; i<numShapes; i++){
        for(int j=0; j<4; j++){
            cin>>temp;
            switch(j){
                case 0:
                    coordinates[0] = stoi(delimiter(temp));
                    break;
                case 1:
                    coordinates[1] = stoi(delimiter(temp));
                    break;
                case 2:
                    coordinates[2] = stoi(delimiter(temp));
                    break;
                case 3:
                    coordinates[3] = stoi(temp);
                    break;
            }
        }
    if(i == 0){
    graph->V = 2;
    graph->E = 2;
    graph->edge[0].src = 0;
    graph->edge[0].dest = 1;
    graph->edge[0].Xll = coordinates[0];
    graph->edge[0].Yll = coordinates[1];
    graph->edge[0].Xur = coordinates[2];
    graph->edge[0].Yur = coordinates[3];
    cout<<"Side 1\n";
    }
    else if(bounded(graph,coordinates,a) == true){
        graph->V = a+2;
        graph->E = a+2;
        graph->edge[a].src = a;
        graph->edge[a].dest = a+1;
        graph->edge[a].Xll = coordinates[0];
        graph->edge[a].Yll = coordinates[1];
        graph->edge[a].Xur = coordinates[2];
        graph->edge[a].Yur = coordinates[3];
        a++;
        cout<<"Side 1\n";
    }
    else if(check == 0){
        graph2->V = 2;
        graph2->E = 2;
        graph2->edge[0].src = 0;
        graph2->edge[0].dest = 1;
        graph2->edge[0].Xll = coordinates[0];
        graph2->edge[0].Yll = coordinates[1];
        graph2->edge[0].Xur = coordinates[2];
        graph2->edge[0].Yur = coordinates[3];
        cout<<"Side 2\n";
        check = 1;
    }
    else if(bounded(graph2,coordinates,b) == true){
        graph->V = b+2;
        graph->E = b+2;
        graph2->edge[b].src = b;
        graph2->edge[b].dest = b+1;
        graph2->edge[b].Xll = coordinates[0];
        graph2->edge[b].Yll = coordinates[1];
        graph2->edge[b].Xur = coordinates[2];
        graph2->edge[b].Yur = coordinates[3];
        b++;
        cout<<"Side 2\n";
    }
    else{
        cout<<"None\n";
    }
}

}

bool bounded(struct Graph* graph,vector<int> coordinates, int N){
int *parent = (int*) malloc( graph->V * sizeof(int) );
int x = XSpacing - 1;
int y = YSpacing - 1;
int const Length = Dimension[0];
int const Height = Dimension[1];
int Xll = coordinates[0];
int Yll = coordinates[1];
int Xur = coordinates[2];
int Yur = coordinates[3];

memset(parent, -1, sizeof(int) * graph->V);

    for(int i = 0; i < graph->E; ++i)
    {
        int A = find(parent, graph->edge[i].src);
        int B = find(parent, graph->edge[i].dest);

                if(Xll >= graph->edge[i].Xll-x && Xur <= graph->edge[i].Xur+x)
                    if(Yll >= graph->edge[i].Yll-y && Yur <= graph->edge[i].Yur+y)
                        return false;

                if((Yll >= graph->edge[i].Yll-y && Yll <= graph->edge[i].Yur+y) || (Yur >= graph->edge[i].Yll-y && Yur <= graph->edge[i].Yur+y)){             //if on the right
                    if(Xll >= graph->edge[i].Xll-x && Xll <= graph->edge[i].Xur+x)
                        return false;
                    if(Xur <= graph->edge[i].Xur+x && Xur >= graph->edge[i].Xll-x)
                        return false;
                }

                if((Xll >= graph->edge[i].Xll-x && Xll <= graph->edge[i].Xur+x) || (Xur >= graph->edge[i].Xll-x && Xur <= graph->edge[i].Xur+x)){             //if on the right
                    if(Yll >= graph->edge[i].Yll-y && Yll <= graph->edge[i].Yur+y)
                        return false;
                    if(Yur <= graph->edge[i].Yur+y && Yur >= graph->edge[i].Yll-y)
                        return false;
                }

        if(A == B)
            return true;

        Union(parent, A, B);
    }
    cout<<endl;

return 0;
}

string delimiter(string temp){

    if(temp.back() == ',')
        temp.pop_back();

return temp;
}

Input

NumShapes=8
XSpacing=10
YSpacing=2
Dimension=100x30
10, 4, 20, 6
25, 5, 55, 8
10, 8, 15, 12
0, 20, 20, 22
0, 20, 10, 22
0, 10, 5, 15
25, 27, 75, 28
25, 10, 55, 13

Output

SIDE1
SIDE2
SIDE1
SIDE1
SIDE2
SIDE2
SIDE1
SIDE1

Body:
Dont use malloc in c++ to create objects. Actually malloc does not create objects. Here

struct Graph* graph =  (struct Graph*) malloc( sizeof(struct Graph) );

you merely allocate memory for a Graph but you do not construct a Graph object.

From cppreference on std::malloc:

This function does not call constructors or initialize memory in
  any way. There are no ready-to-use smart pointers that could guarantee
  that the matching deallocation function is called. The preferred
  method of memory allocation in C++ is using RAII-ready functions
  std::make_unique, std::make_shared, container constructors, etc, and,
  in low-level library code, new-expression.

Ergo, use standard containers if you can, else use smart pointers. new is for low-level library code and malloc has no place in creating objects in C++.


问:
Where can I find MySql 4.0.30 for windows?
I need to adapt our testing server to our production one that is stored on Aruba.
Aruba use MySql 4.0.30 but I can't find them nowhere!
Anybody know where can I find it ? or anybody has the installer stored anywhere?

Davide

答:
MySQL does not require much installation steps like most windows software.

Just copy the mysql dir and the mysql data dir from the production environment to your local machine and start mysqld.exe (does not need to be run as a service) from the bin directory with:

```<code>mysqld.exe --defaults-file="C:\path\to\my.ini" MySQL
</code>```

If it does not start, you most likely tweak some path entries in your my.ini.

Or you can install the latest 4.x Server you find and replace the binaries and data files with the ones you get from production. That should totally do it.

ContentLicense: CC BY-SA 3.0

Body:
MySQL does not require much installation steps like most windows software.

Just copy the mysql dir and the mysql data dir from the production environment to your local machine and start mysqld.exe (does not need to be run as a service) from the bin directory with:

mysqld.exe --defaults-file="C:\path\to\my.ini" MySQL

If it does not start, you most likely tweak some path entries in your my.ini.

Or you can install the latest 4.x Server you find and replace the binaries and data files with the ones you get from production. That should totally do it.


问:
Trying to Add a CollectionView to ResuableView Header like Instagram or SNapchat
I want to have a CollectionView in my Header that resembles that on Instagram and Snapchat for my main CollectionView which would be the feed. When I try to add the collectionview from the library and set the header as delegate and datasource after implementing the delegate methods, I still dont see anything in the header.</p>

```<code>    //let layout = UICollectionViewFlowLayout()

    let headerCollection = UICollectionView(frame: CGRect(x: 0, y: 0, width: 50, height: 90), collectionViewLayout: UICollectionViewFlowLayout())

    override func awakeFromNib() {
        super.awakeFromNib()

//       headerCollection.delegate = self
//        headerCollection.dataSource = self
    }

}

extension HeaderforFeed: UICollectionViewDataSource, UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return CollectionViewData.Dict_StrImg.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = UICollectionViewCell(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
        cell.backgroundColor = .red
        return cell
    }

}```
</code>```

答:
its fine i figured it out. I added the collectionview from the library unto my header in storyboard. Then i connected it as an outlet in my UICollectionReusableView class. I then made that class implement the delegate methods for a collectionview but for the one in the header.

Make the reusableview the delegate and datasource and it worked for me

```<code>//  HeaderforFeed.swift
//  finishedFeednStories
//
//  Created by Guh Suck Yu Mada
//  Copyright © 2019 Bumboklat. All rights reserved.
//

import UIKit

class HeaderforFeed: UICollectionReusableView {
    //let layout = UICollectionViewFlowLayout()

    @IBOutlet weak var storiesCollection: UICollectionView!

    override func awakeFromNib() {
        super.awakeFromNib()

       storiesCollection.delegate = self
        storiesCollection.dataSource = self
    }

}

extension HeaderforFeed: UICollectionViewDataSource, UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return CollectionViewData.Dict_StrImg.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "storiesCell", for: indexPath) as! StoriesCell

        cell.storiesImg.image = Array(CollectionViewData.Dict_StrImg)[indexPath.row].value
        cell.storiesLabel.text = Array(CollectionViewData.Dict_StrImg)[indexPath.row].key

        return cell
    }

}
</code>```

Body:
I want to have a CollectionView in my Header that resembles that on Instagram and Snapchat for my main CollectionView which would be the feed. When I try to add the collectionview from the library and set the header as delegate and datasource after implementing the delegate methods, I still dont see anything in the header.

    //let layout = UICollectionViewFlowLayout()

    let headerCollection = UICollectionView(frame: CGRect(x: 0, y: 0, width: 50, height: 90), collectionViewLayout: UICollectionViewFlowLayout())

    override func awakeFromNib() {
        super.awakeFromNib()

//       headerCollection.delegate = self
//        headerCollection.dataSource = self
    }

}

extension HeaderforFeed: UICollectionViewDataSource, UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return CollectionViewData.Dict_StrImg.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = UICollectionViewCell(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
        cell.backgroundColor = .red
        return cell
    }

}```

Body:
its fine i figured it out. I added the collectionview from the library unto my header in storyboard. Then i connected it as an outlet in my UICollectionReusableView class. I then made that class implement the delegate methods for a collectionview but for the one in the header.

Make the reusableview the delegate and datasource and it worked for me

//  HeaderforFeed.swift
//  finishedFeednStories
//
//  Created by Guh Suck Yu Mada
//  Copyright © 2019 Bumboklat. All rights reserved.
//

import UIKit

class HeaderforFeed: UICollectionReusableView {
    //let layout = UICollectionViewFlowLayout()

    @IBOutlet weak var storiesCollection: UICollectionView!

    override func awakeFromNib() {
        super.awakeFromNib()

       storiesCollection.delegate = self
        storiesCollection.dataSource = self
    }

}

extension HeaderforFeed: UICollectionViewDataSource, UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return CollectionViewData.Dict_StrImg.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "storiesCell", for: indexPath) as! StoriesCell

        cell.storiesImg.image = Array(CollectionViewData.Dict_StrImg)[indexPath.row].value
        cell.storiesLabel.text = Array(CollectionViewData.Dict_StrImg)[indexPath.row].key

        return cell
    }

}


问:
Can't load "glyp" properly for opengl using freetype2
It seems as if freetype library isn't loading the font properly and doesn't convert it to bytes for later use as opengl texture.

Here is the result I'm getting with freetype:

I've already tried using another texture so it's unlikely that it's my texture manager's problem.

```<code>Font(const std::string font) //constructor
        :name(font)
    {
        std::string _font = "fonts/" + font + ".ttf";

        FT_Library ft;
        FT_Init_FreeType(&ft);

        FT_Face face;
        if (FT_New_Face(ft, _font.c_str(), 0, &face))
            EXIT_ERROR(-11);

        FT_Set_Pixel_Sizes(face, 0, 48);

        for (unsigned int a = 1; a < 128; a++)
        {
            char c = a;

            if (FT_Load_Char(face, c, FT_LOAD_RENDER))
            {
                EXIT_ERROR(-12);
            }

//This just creates the FontTexture type, as I said before it works
//fine,FontTexture is abstracted from BaseTexture which stores char* with
//data. I also made sure that the stuff is loaded
//there properly from inside FontTexture.

            FontTexture* _char = new FontTexture(
//here is buffer passing
face->glyph->bitmap.buffer,
                0,
                { static_cast<float>(face->glyph->bitmap.width),
                static_cast<float>(face->glyph->bitmap.rows) });

            _char->SetAdvance(face->glyph->advance.x);
            _char->SetBearing({ static_cast<float>(face->glyph->bitmap_left),
                static_cast<float>(face->glyph->bitmap_top )});

//This just caches texture, so instead of loading it multiple times I can
//just call "getTexture(name) store that pointer in the entitie's memory
//and bind when Draw() is being called.
            TextureManager::getTextureManager().PrecacheTexture(std::to_string(a) + font, _char);

            Characters.insert(std::pair<char, FontTexture*>(c, _char));
        }

        FT_Done_Face(face);
        FT_Done_FreeType(ft);
    }
</code>```

答:
The GL_UNPACK_ALIGNMENT parameter defines the alignment of the first pixel in each row (line) of an image when the image is read form the buffer. By default the this parameter is 4.

Each pixel of the glyph image is encoded in one byte and the image is tightly packed. So the the alignment of the glyph image is 1 and the parameter has to be changed before the image is read and the texture is specified:

glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
```

If that is missed, this would cause a shift effect at each line of the image (except if the width of the image is divisible by 4).

Body:
It seems as if freetype library isn't loading the font properly and doesn't convert it to bytes for later use as opengl texture.

Here is the result I'm getting with freetype:

I've already tried using another texture so it's unlikely that it's my texture manager's problem.

Font(const std::string font) //constructor
        :name(font)
    {
        std::string _font = "fonts/" + font + ".ttf";

        FT_Library ft;
        FT_Init_FreeType(&ft);

        FT_Face face;
        if (FT_New_Face(ft, _font.c_str(), 0, &face))
            EXIT_ERROR(-11);

        FT_Set_Pixel_Sizes(face, 0, 48);

        for (unsigned int a = 1; a < 128; a++)
        {
            char c = a;

            if (FT_Load_Char(face, c, FT_LOAD_RENDER))
            {
                EXIT_ERROR(-12);
            }

//This just creates the FontTexture type, as I said before it works
//fine,FontTexture is abstracted from BaseTexture which stores char* with
//data. I also made sure that the stuff is loaded
//there properly from inside FontTexture.

            FontTexture* _char = new FontTexture(
//here is buffer passing
face->glyph->bitmap.buffer,
                0,
                { static_cast<float>(face->glyph->bitmap.width),
                static_cast<float>(face->glyph->bitmap.rows) });

            _char->SetAdvance(face->glyph->advance.x);
            _char->SetBearing({ static_cast<float>(face->glyph->bitmap_left),
                static_cast<float>(face->glyph->bitmap_top )});

//This just caches texture, so instead of loading it multiple times I can
//just call "getTexture(name) store that pointer in the entitie's memory
//and bind when Draw() is being called.
            TextureManager::getTextureManager().PrecacheTexture(std::to_string(a) + font, _char);

            Characters.insert(std::pair<char, FontTexture*>(c, _char));
        }

        FT_Done_Face(face);
        FT_Done_FreeType(ft);
    }

Body:
The GL_UNPACK_ALIGNMENT parameter defines the alignment of the first pixel in each row (line) of an image when the image is read form the buffer. By default the this parameter is 4.

Each pixel of the glyph image is encoded in one byte and the image is tightly packed. So the the alignment of the glyph image is 1 and the parameter has to be changed before the image is read and the texture is specified:

glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

If that is missed, this would cause a shift effect at each line of the image (except if the width of the image is divisible by 4).


问:
React router dom params issue
I tried to Routing the params ":id" in react with a sub Route ":id/history" and the route link not render the component on clicking</p>

```<code><Switch>
     <Route path="/patients/:id" exact component={GeneralData} />
     <Route path="/patients/:id/history" component={History} />
</Switch>
</code>```

答: I think you're omitting exact param.

Title: React router dom params issue

Body:
I tried to Routing the params ":id" in react with a sub Route ":id/history" and the route link not render the component on clicking

<Switch>
     <Route path="/patients/:id" exact component={GeneralData} />
     <Route path="/patients/:id/history" component={History} />
</Switch>

Body: I think you're omitting exact param.


问:
Simple Injector Inject into PageModel ASP.NET Core Razor Pages
Simple Injector (SI) Documentation here shows how to integrate SI with ASP.NET Core:

```<code>private void IntegrateSimpleInjector(IServiceCollection services) {
    container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();

    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    services.AddSingleton<IControllerActivator>(
        new SimpleInjectorControllerActivator(container));
    services.AddSingleton<IViewComponentActivator>(
        new SimpleInjectorViewComponentActivator(container));

    services.EnableSimpleInjectorCrossWiring(container);
    services.UseSimpleInjectorAspNetRequestScoping(container);
}
</code>```

This example code shows how to integrate SI with Controllers and ViewComponents (The MVC model) that we were used to work with before Razor Pages.

However, this doe not integrate SI into Razor Pages, the new feature released with ASP.NET Core 2.0. This is basically a MVVM model (not exactly).

So Razor pages have one PageModel for each view, and it is like the controller. And I would like to inject into the constructor of this class using SI.

答:
Simple Injector offer a simple way to achieve this with the extension method AddPageModelActivation.

```<code>services.AddSimpleInjector(container, options =>
{
    // AddAspNetCore() wraps web requests in a Simple Injector scope.
    options.AddAspNetCore()
        // Ensure activation of a specific framework type to be created by
        // Simple Injector instead of the built-in configuration system.
        .AddControllerActivation()
        .AddViewComponentActivation()
        .AddPageModelActivation()
        .AddTagHelperActivation();
});
</code>```

To see the whole example https://simpleinjector.readthedocs.io/en/latest/aspnetintegration.html

Body:
Simple Injector (SI) Documentation here shows how to integrate SI with ASP.NET Core:

private void IntegrateSimpleInjector(IServiceCollection services) {
    container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();

    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    services.AddSingleton<IControllerActivator>(
        new SimpleInjectorControllerActivator(container));
    services.AddSingleton<IViewComponentActivator>(
        new SimpleInjectorViewComponentActivator(container));

    services.EnableSimpleInjectorCrossWiring(container);
    services.UseSimpleInjectorAspNetRequestScoping(container);
}

This example code shows how to integrate SI with Controllers and ViewComponents (The MVC model) that we were used to work with before Razor Pages.

However, this doe not integrate SI into Razor Pages, the new feature released with ASP.NET Core 2.0. This is basically a MVVM model (not exactly).

So Razor pages have one PageModel for each view, and it is like the controller. And I would like to inject into the constructor of this class using SI.

Body:
Simple Injector offer a simple way to achieve this with the extension method AddPageModelActivation.

services.AddSimpleInjector(container, options =>
{
    // AddAspNetCore() wraps web requests in a Simple Injector scope.
    options.AddAspNetCore()
        // Ensure activation of a specific framework type to be created by
        // Simple Injector instead of the built-in configuration system.
        .AddControllerActivation()
        .AddViewComponentActivation()
        .AddPageModelActivation()
        .AddTagHelperActivation();
});

To see the whole example https://simpleinjector.readthedocs.io/en/latest/aspnetintegration.html


问:
Javascript: how can I access a class property to a function inside nested object
I'm working with javascript classes and there's something I want to do but I don't know how. First of all, this is my class:

```<code>class Company {
  constructor (options) {
    this.employee = options.employee;
    this.algorithm = "AZ1";
  }
}
</code>```

Now, employee is an object which has another object nested inside of it and that final object contains a series of functions:

```<code>employee {
  code {
    generate [Function: generate]
    alter [Function: alter]
  }
}
</code>```

Now, my problem is that I want to access the algorithm from any of these functions?

Btw; I'm trying to do so from an object created with that class:

```<code>const myCompany = new Company({ employee });
</code>```

So I want to access the algorithm property from the generate function within myCompany.

答:
object1.field1 = object2 is a one-way relation:

object1 can access object2 afterwards, via field1

object2 has absolutely no clue about object1 being around, and thus it can not know about its other fields either.

You can pass it as an argument, like object1.field1.dosomething(object1.field2), which in the actual case translates to:

```<code>myCompany.employee.code.generate(myCompany.algorithm)
</code>```

(And of course assumes that generate() is modified to expect such argument. The freshly added option does not affect the pattern)

Body:
I'm working with javascript classes and there's something I want to do but I don't know how. First of all, this is my class:

class Company {
  constructor (options) {
    this.employee = options.employee;
    this.algorithm = "AZ1";
  }
}

Now, employee is an object which has another object nested inside of it and that final object contains a series of functions:

employee {
  code {
    generate [Function: generate]
    alter [Function: alter]
  }
}

Now, my problem is that I want to access the algorithm from any of these functions?

Btw; I'm trying to do so from an object created with that class:

const myCompany = new Company({ employee });

So I want to access the algorithm property from the generate function within myCompany.

Body:
object1.field1 = object2 is a one-way relation:

object1 can access object2 afterwards, via field1

object2 has absolutely no clue about object1 being around, and thus it can not know about its other fields either.

You can pass it as an argument, like object1.field1.dosomething(object1.field2), which in the actual case translates to:

myCompany.employee.code.generate(myCompany.algorithm)

(And of course assumes that generate() is modified to expect such argument. The freshly added option does not affect the pattern)


问:
How to generically format a boolean to a Yes/No string?
I would like to display Yes/No in different languages according to some boolean variable.

Is there a generic way to format it according to the locale passed to it?

If there isn't, what is the standard way to format a boolean besides boolVar ? Resources.Yes : Resources.No.

I'm guessing that boolVar.ToString(IFormatProvider) is involved.

Is my assumption correct?

答:
Unfortunately, Boolean.ToString(IFormatProvider) does not help here:

The provider parameter is reserved. It does not participate in the execution of this method. This means that the Boolean.ToString(IFormatProvider) method, unlike most methods with a provider parameter, does not reflect culture-specific settings.

In any case, Booleans represent True and False, not Yes and No. If you want to map True -> Yes and False -> No, you will have to do that (including localization) yourself; there's no built-in support in the framework for that. Your propopsed solution (Resources.Yes/No) looks fine to me.


问:
Is there a way to set a password strength for Firebase?
```<code> const connect = auth.createUserWithEmailAndPassword(email,pass).catch(function(error){

          if(error.code === 'auth/weak-password'){
          errmsg.style.display = 'block';
          errmsg.style.opacity = '1';
          errmsg.innerHTML= 'The password is too weak.';
      }
</code>```

With the default setting, the requirement for password is 6 characters (letter/number). Is there a way to change this (Ex. require password to be letter-number combined)>

答:
my solution for this is, I also run firebase auth in the backend

I create functions that run validation and create user as callback

it works fine for me

update: I do not recommend this method

Body:
 const connect = auth.createUserWithEmailAndPassword(email,pass).catch(function(error){

          if(error.code === 'auth/weak-password'){
          errmsg.style.display = 'block';
          errmsg.style.opacity = '1';
          errmsg.innerHTML= 'The password is too weak.';
      }

With the default setting, the requirement for password is 6 characters (letter/number). Is there a way to change this (Ex. require password to be letter-number combined)>


问:
Resolve Javascript Promise outside the Promise constructor scope
I have been using ES6 Promise.

Ordinarily, a Promise is constructed and used like this

```<code>new Promise(function(resolve, reject){
    if (someCondition){
        resolve();
    } else {
        reject();
    }
});
</code>```

But I have been doing something like below to take the resolve outside for the sake of flexibility.

```<code>var outsideResolve;
var outsideReject;
new Promise(function(resolve, reject) {
    outsideResolve = resolve;
    outsideReject = reject;
});
</code>```

And later

```<code>onClick = function(){
    outsideResolve();
}
</code>```

This works fine, but is there an easier way to do this? If not, is this a good practice?

答:
I've put together a gist that does that job: https://gist.github.com/thiagoh/c24310b562d50a14f3e7602a82b4ef13

here's how you should use it:

```<code>import ExternalizedPromiseCreator from '../externalized-promise';

describe('ExternalizedPromise', () => {
  let fn: jest.Mock;
  let deferredFn: jest.Mock;
  let neverCalledFn: jest.Mock;
  beforeEach(() => {
    fn = jest.fn();
    deferredFn = jest.fn();
    neverCalledFn = jest.fn();
  });

  it('resolve should resolve the promise', done => {
    const externalizedPromise = ExternalizedPromiseCreator.create(() => fn());

    externalizedPromise
      .promise
      .then(() => deferredFn())
      .catch(() => neverCalledFn())
      .then(() => {
        expect(deferredFn).toHaveBeenCalled();
        expect(neverCalledFn).not.toHaveBeenCalled();
        done();
      });

    expect(fn).toHaveBeenCalled();
    expect(neverCalledFn).not.toHaveBeenCalled();
    expect(deferredFn).not.toHaveBeenCalled();

    externalizedPromise.resolve();
  });
  ...
});
</code>```

Body:
I have been using ES6 Promise.

Ordinarily, a Promise is constructed and used like this

new Promise(function(resolve, reject){
    if (someCondition){
        resolve();
    } else {
        reject();
    }
});

But I have been doing something like below to take the resolve outside for the sake of flexibility.

var outsideResolve;
var outsideReject;
new Promise(function(resolve, reject) {
    outsideResolve = resolve;
    outsideReject = reject;
});

And later

onClick = function(){
    outsideResolve();
}

This works fine, but is there an easier way to do this? If not, is this a good practice?

Body:
I've put together a gist that does that job: https://gist.github.com/thiagoh/c24310b562d50a14f3e7602a82b4ef13

here's how you should use it:

import ExternalizedPromiseCreator from '../externalized-promise';

describe('ExternalizedPromise', () => {
  let fn: jest.Mock;
  let deferredFn: jest.Mock;
  let neverCalledFn: jest.Mock;
  beforeEach(() => {
    fn = jest.fn();
    deferredFn = jest.fn();
    neverCalledFn = jest.fn();
  });

  it('resolve should resolve the promise', done => {
    const externalizedPromise = ExternalizedPromiseCreator.create(() => fn());

    externalizedPromise
      .promise
      .then(() => deferredFn())
      .catch(() => neverCalledFn())
      .then(() => {
        expect(deferredFn).toHaveBeenCalled();
        expect(neverCalledFn).not.toHaveBeenCalled();
        done();
      });

    expect(fn).toHaveBeenCalled();
    expect(neverCalledFn).not.toHaveBeenCalled();
    expect(deferredFn).not.toHaveBeenCalled();

    externalizedPromise.resolve();
  });
  ...
});


问:
How to prevent trigger container's event when trigger children's events in JQuery?
E.g:

My HTML code structure is:

```<code><ul>
  <li class="container_event_click">
    <div class="child_event_click">click fired but doesn't want to trigger container's event</div>
  </li>
</ul>
</code>```

I mean: the container LI has its own click event.Just like selected or not.And the child div has its own click event like show something info of container.But my problem is when I click the child's event it also trigger the container's event.So,how can I resolve this problem.

Thank you very much!!

答:
```<code>$('.child_event_click').click(function(e) {
    e.stopPropagation();
    ...
});
</code>```

Body:
E.g:

My HTML code structure is:

click fired but doesn't want to trigger container's event

I mean: the container LI has its own click event.Just like selected or not.And the child div has its own click event like show something info of container.But my problem is when I click the child's event it also trigger the container's event.So,how can I resolve this problem.

Thank you very much!!


问:
Connect to GoDaddy server database from localhost computer
I programmed a website in PHP that uses a MySQL Server through GoDaddy. I have the same code saved on my local computer and sync it with the directory on GoDaddy through an app. I also use XAMPP on my computer to test any changes I make to the website before I make the changes public. However, the localhost server is different and in no way connected with the cPanel GoDaddy server. Therefore, if something new is added to the database on the public server, I would have to

Download the sql file on the remote phpmyadmin

Upload this file on the localhost phpmyadmin

This is an inefficient process, so now I want to use PHP to connect to the GoDaddy server. To do this, I put the IP Address given to me in the GoDaddy hosting page as the host parameter of the mysqli_connect() function.

```<code>// Set the database access information as constants
define('DB_USER', 'libuc6kfb0jg');
define('DB_PASSWORD', 'MY PASSWORD');
define('DB_HOST', 'MY IP ADDRESS');
define('DB_NAME', 'firstborumdatabase');
</code>```

This user has all privileges on both the remote and the localhost.
On cPanel - Remote MySQL® I have added the IP Address of my computer's localhost server.

```<code>// Make the connection
$dbc = @mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die('Could not connect to MySQL: ' . mysqli_connect_error());
</code>```

When I put this code in, instead of having 'localhost' as my host, which connects to the local MySQL server of XAMPP, it gives the following error

Could not connect to MySQL: Access denied for user 'libuc6kfb0jg'@'[Sensitive Info]' (using password: YES)

Since I know it is not a permissions problem, the next thing I did was use the PORT parameter. So, I added 3306 to the end to no avail, for it gave me the same error. Lastly, I put in this code as a mysql command into the mysql client from the XAMPP Control Panel, and this gave me the same exact error.

Stack Overflow Research

Connect to server database from localhost does not give the same error as me

Connecting to online MySQL database from localhost: I tried changing www.bforborum.com to the its ip address from the GoDaddy My Hosting Page, and this gave the same error

Can't connect to godaddy localhost is answered with the same code that I used except using the PDO api and not the mysqli api

Connecting remote server mysql database to localhost doesn't give any code

Any help would be greatly appreciated.

Edit

I found a flaw: In cPanel, Remote MySQL Database, I added the IP Address that my localhost server is, not my computer's IP Address, if that makes sense. I am now changing the IP Address that I had added in this tool.

答: While giving the user all permissions is crucial for it to have the necessary access to your database that only affects the ability for him to manipulate the database. You need to also whitelist your computers IP with the Servers firewall or you will not be allowed to connect to the remote server.</p>

Body:
I programmed a website in PHP that uses a MySQL Server through GoDaddy. I have the same code saved on my local computer and sync it with the directory on GoDaddy through an app. I also use XAMPP on my computer to test any changes I make to the website before I make the changes public. However, the localhost server is different and in no way connected with the cPanel GoDaddy server. Therefore, if something new is added to the database on the public server, I would have to

Download the sql file on the remote phpmyadmin

Upload this file on the localhost phpmyadmin

This is an inefficient process, so now I want to use PHP to connect to the GoDaddy server. To do this, I put the IP Address given to me in the GoDaddy hosting page as the host parameter of the mysqli_connect() function.

// Set the database access information as constants
define('DB_USER', 'libuc6kfb0jg');
define('DB_PASSWORD', 'MY PASSWORD');
define('DB_HOST', 'MY IP ADDRESS');
define('DB_NAME', 'firstborumdatabase');

This user has all privileges on both the remote and the localhost.
On cPanel - Remote MySQL® I have added the IP Address of my computer's localhost server.

// Make the connection
$dbc = @mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die('Could not connect to MySQL: ' . mysqli_connect_error());

When I put this code in, instead of having 'localhost' as my host, which connects to the local MySQL server of XAMPP, it gives the following error

Could not connect to MySQL: Access denied for user 'libuc6kfb0jg'@'[Sensitive Info]' (using password: YES)

Since I know it is not a permissions problem, the next thing I did was use the PORT parameter. So, I added 3306 to the end to no avail, for it gave me the same error. Lastly, I put in this code as a mysql command into the mysql client from the XAMPP Control Panel, and this gave me the same exact error.

Stack Overflow Research

Connect to server database from localhost does not give the same error as me

Connecting to online MySQL database from localhost: I tried changing www.bforborum.com to the its ip address from the GoDaddy My Hosting Page, and this gave the same error

Can't connect to godaddy localhost is answered with the same code that I used except using the PDO api and not the mysqli api

Connecting remote server mysql database to localhost doesn't give any code

Any help would be greatly appreciated.

Edit

I found a flaw: In cPanel, Remote MySQL Database, I added the IP Address that my localhost server is, not my computer's IP Address, if that makes sense. I am now changing the IP Address that I had added in this tool.


问:
Run Configuration
I'm a new to Intellij + Gradle integration. I created a sample Java gradle project. When I create a new Configuration to try run my test main, it automatically make it a gradle task. Say if I want to run the Configuration as Java command line, instead of gradle task, is there a way to do that?

Thanks,

答: You can set the Platform runner to IntelliJ IDEA (instead of Gradle) as to be used as default when you run a configuration in Settings (Preferences on macOS) | Build, Execution, Deployment | Build Tools | Gradle | Delegate settings | Build and run using setting.

Title: Run Configuration


问:
SFINAE Template Specialization in Separate Source File
I am working maintenance on a program with a bunch of different structures that are fundamentally similar.  I want to write a template method that utilizes SFINAE to enable calling this method from the client.  When I define the template specialization inline, everything works as expected.  However, when I try to move the template definition into a separate compilation unit, I run into issues.  I am trying to move the template implementation into a separate file in order to enable using forward declarations for most of the dependent classes.  The following is an example of what I am attempting to achieve:

```<code>// Impl.h
#pragma once

struct A {
    struct {
        int value;
    } valueA;
};

struct B {
    struct {
        int value;
    } valueB;
};

template<typename T>
int GetValue(T const &value);

// Impl.cpp
#include "Impl.h"
#include <type_traits>

using std::enable_if_t;
using std::remove_reference_t;

template<typename T, typename U, U(T::*Value)>
static inline int GetValueImpl(T const &value) {
    return (value.*Value).value;
}

template<typename T>
enable_if_t<T::valueA, int> GetValue(T const &value) {
    static constexpr auto T::*const Value = &T::valueA;
    typedef remove_reference_t<decltype(value.*Value)> ValueType;
    return GetValueImpl<T, ValueType, Value>(value);
}

template<typename T>
enable_if_t<T::valueB, int> GetValue(T const &value) {
    static constexpr auto T::*const Value = &T::valueB;
    typedef remove_reference_t<decltype(value.*Value)> ValueType;
    return GetValueImpl<T, ValueType, Value>(value);
}

template<> int GetValue(A const &); // C2912 here
template<> int GetValue(B const &); // C2912 here
</code>```

I am using VS2017u2, and am getting error C2912: explicitt specialization 'int GetValue(const A &)' is not a specialization of a function template.  Does anyone know how to make this work with the definitions in a separate compilation unit?

答:
When you write enable_if_t<T::valueA, int>, it is checking for a static member of T called valueA (Which would presumably be a static constexpr bool valueA = /* true or false */;, like what T::value would mean if T was using T = std::is_same; ).

To actually check if it has a member called valueA or valueB, put it in a context where there would be a substitution error if the member didn't exist, or true. Something like:

```<code>// Pointers to member variables can never be null
// so these will always be enabled if `valueA` or
// `valueB` exist in the first place
enable_if_t<&T::valueA != nullptr, int>
enable_if_t<&T::valueB != nullptr, int>

// But that also allows pointers to static members
// so if you don't want that, you can do something else.
// Like checking if `&T::member` is a pointer to a member
// (But this is probably overkill as you have a specific set
// of types and none of those names are ever static members
// and if you didn't there is a small caveat with
// an overloaded `operator&` but that doesn't really matter)
enable_if_t<std::is_same_v<decltype(&T::valueA), decltype(T::valueA) T::*>, int>
enable_if_t<std::is_same_v<decltype(&T::valueB), decltype(T::valueB) T::*>, int>
</code>```

Even after fixing the SFINAE check, you are using the wrong syntax for template instantiation. You should use:

```<code>template int GetValue(A const &);  // No `<>`
template int GetValue(B const &);
</code>```

And after that, it still doesn't work because template<typename T> enable_if_t<..., int> GetValue(T const&); and template<typename T> int GetValue(T const&); are different functions, so it is ambiguous which one it should instantiate (as both would work). You need to make both of those into different functions (GetValueImpl2 in my example) and have GetValue declared the same way as in the header:

```<code>#include <type_traits>
#include "Impl.h"

using std::enable_if_t;
using std::remove_reference_t;

template<typename T, typename U, U(T::*Value)>
static inline int GetValueImpl(T const &value) {
    return (value.*Value).value;
}

template<typename T>
enable_if_t<std::is_same_v<decltype(&T::valueA), decltype(T::valueA) T::*>, int> GetValueImpl2(T const &value) {
    static constexpr auto T::*const Value = &T::valueA;
    using ValueType = decltype(T::valueA);
    return GetValueImpl<T, ValueType, Value>(value);
}

template<typename T>
enable_if_t<std::is_same_v<decltype(&T::valueB), decltype(T::valueB) T::*>, int> GetValueImpl2(T const &value) {
    static constexpr auto T::*const Value = &T::valueB;
    using ValueType = decltype(T::valueB);
    return GetValueImpl<T, ValueType, Value>(value);
}

template<typename T>
int GetValue(T const&value) {
    return GetValueImpl2(value);
}

template int GetValue<A>(A const &);
template int GetValue<B>(B const &);
</code>```

Body:
I am working maintenance on a program with a bunch of different structures that are fundamentally similar.  I want to write a template method that utilizes SFINAE to enable calling this method from the client.  When I define the template specialization inline, everything works as expected.  However, when I try to move the template definition into a separate compilation unit, I run into issues.  I am trying to move the template implementation into a separate file in order to enable using forward declarations for most of the dependent classes.  The following is an example of what I am attempting to achieve:

// Impl.h
#pragma once

struct A {
    struct {
        int value;
    } valueA;
};

struct B {
    struct {
        int value;
    } valueB;
};

template<typename T>
int GetValue(T const &value);

// Impl.cpp
#include "Impl.h"
#include <type_traits>

using std::enable_if_t;
using std::remove_reference_t;

template<typename T, typename U, U(T::*Value)>
static inline int GetValueImpl(T const &value) {
    return (value.*Value).value;
}

template<typename T>
enable_if_t<T::valueA, int> GetValue(T const &value) {
    static constexpr auto T::*const Value = &T::valueA;
    typedef remove_reference_t<decltype(value.*Value)> ValueType;
    return GetValueImpl<T, ValueType, Value>(value);
}

template<typename T>
enable_if_t<T::valueB, int> GetValue(T const &value) {
    static constexpr auto T::*const Value = &T::valueB;
    typedef remove_reference_t<decltype(value.*Value)> ValueType;
    return GetValueImpl<T, ValueType, Value>(value);
}

template<> int GetValue(A const &); // C2912 here
template<> int GetValue(B const &); // C2912 here

I am using VS2017u2, and am getting error C2912: explicitt specialization 'int GetValue(const A &)' is not a specialization of a function template.  Does anyone know how to make this work with the definitions in a separate compilation unit?

Body:
When you write enable_if_t<T::valueA, int>, it is checking for a static member of T called valueA (Which would presumably be a static constexpr bool valueA = /* true or false */;, like what T::value would mean if T was using T = std::is_same<U, V>; ).

To actually check if it has a member called valueA or valueB, put it in a context where there would be a substitution error if the member didn't exist, or true. Something like:

// Pointers to member variables can never be null
// so these will always be enabled if `valueA` or
// `valueB` exist in the first place
enable_if_t<&T::valueA != nullptr, int>
enable_if_t<&T::valueB != nullptr, int>

// But that also allows pointers to static members
// so if you don't want that, you can do something else.
// Like checking if `&T::member` is a pointer to a member
// (But this is probably overkill as you have a specific set
// of types and none of those names are ever static members
// and if you didn't there is a small caveat with
// an overloaded `operator&` but that doesn't really matter)
enable_if_t<std::is_same_v<decltype(&T::valueA), decltype(T::valueA) T::*>, int>
enable_if_t<std::is_same_v<decltype(&T::valueB), decltype(T::valueB) T::*>, int>

Even after fixing the SFINAE check, you are using the wrong syntax for template instantiation. You should use:

template int GetValue(A const &);  // No `<>`
template int GetValue(B const &);

And after that, it still doesn't work because template<typename T> enable_if_t<..., int> GetValue(T const&); and template<typename T> int GetValue(T const&); are different functions, so it is ambiguous which one it should instantiate (as both would work). You need to make both of those into different functions (GetValueImpl2 in my example) and have GetValue declared the same way as in the header:

#include <type_traits>
#include "Impl.h"

using std::enable_if_t;
using std::remove_reference_t;

template<typename T, typename U, U(T::*Value)>
static inline int GetValueImpl(T const &value) {
    return (value.*Value).value;
}

template<typename T>
enable_if_t<std::is_same_v<decltype(&T::valueA), decltype(T::valueA) T::*>, int> GetValueImpl2(T const &value) {
    static constexpr auto T::*const Value = &T::valueA;
    using ValueType = decltype(T::valueA);
    return GetValueImpl<T, ValueType, Value>(value);
}

template<typename T>
enable_if_t<std::is_same_v<decltype(&T::valueB), decltype(T::valueB) T::*>, int> GetValueImpl2(T const &value) {
    static constexpr auto T::*const Value = &T::valueB;
    using ValueType = decltype(T::valueB);
    return GetValueImpl<T, ValueType, Value>(value);
}

template<typename T>
int GetValue(T const&value) {
    return GetValueImpl2(value);
}

template int GetValue<A>(A const &);
template int GetValue<B>(B const &);