问:
C how to get input correctly
I'm trying to get a sentence and a letter from the user and for some reason it's not getting the letter
it's not doing the scanf the same with getcahr();

```<code>void main(){

    char str[100];
    char letter;
    printf("Enter a line: \n");
    scanf("%s", str);
    printf("Enter a letter: ");
    scanf("%c", &letter);
    printf("%c", letter);
}
</code>```

tried putting NULL in the letter no difference

答:
//It appears to misbehave depending on the compiler. I was using CLion to run the code below and I add space before the percentage sign in scanf.

// Hope it helps :)

```<code>#include <stdio.h>

int main() {
    char name[100];
    char a;

    printf("enter anything \n");
    scanf(" %s %c", &name,&a);
    printf("%s space   %c",name,a);
    return 0;
}
</code>```

Title: C how to get input correctly

Body:
I'm trying to get a sentence and a letter from the user and for some reason it's not getting the letter
it's not doing the scanf the same with getcahr();

void main(){

    char str[100];
    char letter;
    printf("Enter a line: \n");
    scanf("%s", str);
    printf("Enter a letter: ");
    scanf("%c", &letter);
    printf("%c", letter);
}

tried putting NULL in the letter no difference

Body:
//It appears to misbehave depending on the compiler. I was using CLion to run the code below and I add space before the percentage sign in scanf.

// Hope it helps :)

#include <stdio.h>

int main() {
    char name[100];
    char a;

    printf("enter anything \n");
    scanf(" %s %c", &name,&a);
    printf("%s space   %c",name,a);
    return 0;
}


来源: stackexchange

问:
Showing user's comments on posts in Django
I am adding a comment section for my posts in a blog, I reached to the part where I can add new comments and get it saved in the db and I can view them in the admin, but I am stuck to showing the username and the comment in the comment section, I have to go the admin and choose the name of the user and the blog name to appear in the page, how do i link them together

Here is the Models.py

```<code>class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True, blank=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
    content = models.TextField(max_length=160)
    timestamp = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.content
</code>```

Here is the views.py:

```<code>class PostDetailView(DetailView):
    model = Post
    template_name = "post_detail.html"

    def get_context_data(self, *args, **kwargs):
        context = super(PostDetailView, self).get_context_data()
        post = get_object_or_404(Post, slug=self.kwargs['slug'])
        comments = Comment.objects.filter(post=post).order_by('-id')
        total_likes = post.total_likes()
        liked = False
        if post.likes.filter(id=self.request.user.id).exists():
            liked = True

        if self.request.method == 'POST':
            comment_form = CommentForm(self.request.POST or None)
            if comment_form.is_valid():
                content = self.request.POST.get('content')
                comment = Comment.objects.create(
                    post=post, user=request.user, content=content)
                comment.save()
                return HttpResponseRedirect("post_detail.html")
        else:
            comment_form = CommentForm()

        context["total_likes"] = total_likes
        context["liked"] = liked
        context["comments"] = comments
        context["comment_form"] = comment_form
        return context

class PostCommentCreateView(LoginRequiredMixin, CreateView):
    model = Comment
    fields = ['content', ]
    success_url = reverse_lazy('score:post-detail')

    def post(self, request, *args, **kwargs):
        form = CommentForm(request.POST)
        if form.is_valid():
            post = form.save()
            post.save()
        print(args, kwargs, request.POST)
        return redirect('score:post-detail', slug=kwargs['slug'])
</code>```

here is the template

```<code>            <form action={% url 'score:post-comment' post.slug %} method="post" class="comment-form" action=".">
            {% comment %} <form method="post" class="comment-form" action="."> {% endcomment %}
            {% csrf_token %}
            {{ comment_form.as_p }}
            {% if request.user.is_authenticated %}
            <input type="submit" value="Submit" class="btn btn-outline-success">
            {% else %}
            <input type="submit" value="Submit" class="btn btn-outline-success" disabled> You must be Logged in to Comment
            {% endif %}
            </form>
</code>```

here is the form

```<code>class CommentForm(forms.ModelForm):
    content = forms.CharField(label="", widget=forms.Textarea(
        attrs={'class': 'form-control', 'placeholder': 'Text goes here!!!', 'rows': '4', 'cols': '50'}))

    class Meta:
        model = Comment
        fields = ('content',)
</code>```

答:
A CreateView is defined to remove most of the boilplate code, so you should not reimplement that in the post method, but let the CreateView do its work.

What you here should do is override the .form_valid(…) method [Django-doc] and the .form_invalid(…) method [Django-doc], and the .get_success_url(…) method [Django-doc] to redirect to the proper view:

```<code>from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.urls import reverse

class PostCommentCreateView(LoginRequiredMixin, CreateView):
    model = Comment
    form_class = CommentForm

    def <b>form_valid</b>(self, form):
        <b>post</b> = get_object_or_404(Post, slug=self.kwargs['slug'])
        form<b>.instance.user = self.request.user</b>
        form<b>.instance.post = post</b>
        return super().form_valid(form)

    def <b>form_invalid</b>(self, form):
        return HttpResponseRedirect(self.get_success_url())

    def <b>get_success_url</b>(self):
        return reverse('score:post-detail', kwargs=dict(slug=self.kwargs['slug']))</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am adding a comment section for my posts in a blog, I reached to the part where I can add new comments and get it saved in the db and I can view them in the admin, but I am stuck to showing the username and the comment in the comment section, I have to go the admin and choose the name of the user and the blog name to appear in the page, how do i link them together

Here is the Models.py

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True, blank=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
    content = models.TextField(max_length=160)
    timestamp = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.content

Here is the views.py:

class PostDetailView(DetailView):
    model = Post
    template_name = "post_detail.html"

    def get_context_data(self, *args, **kwargs):
        context = super(PostDetailView, self).get_context_data()
        post = get_object_or_404(Post, slug=self.kwargs['slug'])
        comments = Comment.objects.filter(post=post).order_by('-id')
        total_likes = post.total_likes()
        liked = False
        if post.likes.filter(id=self.request.user.id).exists():
            liked = True

        if self.request.method == 'POST':
            comment_form = CommentForm(self.request.POST or None)
            if comment_form.is_valid():
                content = self.request.POST.get('content')
                comment = Comment.objects.create(
                    post=post, user=request.user, content=content)
                comment.save()
                return HttpResponseRedirect("post_detail.html")
        else:
            comment_form = CommentForm()

        context["total_likes"] = total_likes
        context["liked"] = liked
        context["comments"] = comments
        context["comment_form"] = comment_form
        return context

class PostCommentCreateView(LoginRequiredMixin, CreateView):
    model = Comment
    fields = ['content', ]
    success_url = reverse_lazy('score:post-detail')

    def post(self, request, *args, **kwargs):
        form = CommentForm(request.POST)
        if form.is_valid():
            post = form.save()
            post.save()
        print(args, kwargs, request.POST)
        return redirect('score:post-detail', slug=kwargs['slug'])

here is the template

            <form action={% url 'score:post-comment' post.slug %} method="post" class="comment-form" action=".">
            {% comment %} <form method="post" class="comment-form" action="."> {% endcomment %}
            {% csrf_token %}
            {{ comment_form.as_p }}
            {% if request.user.is_authenticated %}
            <input type="submit" value="Submit" class="btn btn-outline-success">
            {% else %}
            <input type="submit" value="Submit" class="btn btn-outline-success" disabled> You must be Logged in to Comment
            {% endif %}
            </form>

here is the form

class CommentForm(forms.ModelForm):
    content = forms.CharField(label="", widget=forms.Textarea(
        attrs={'class': 'form-control', 'placeholder': 'Text goes here!!!', 'rows': '4', 'cols': '50'}))

    class Meta:
        model = Comment
        fields = ('content',)

Body:
A CreateView is defined to remove most of the boilplate code, so you should not reimplement that in the post method, but let the CreateView do its work.

What you here should do is override the .form_valid(…) method [Django-doc] and the .form_invalid(…) method [Django-doc], and the .get_success_url(…) method [Django-doc] to redirect to the proper view:

from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.urls import reverse

class PostCommentCreateView(LoginRequiredMixin, CreateView):
    model = Comment
    form_class = CommentForm

    def form_valid(self, form):
        post = get_object_or_404(Post, slug=self.kwargs['slug'])
        form.instance.user = self.request.user
        form.instance.post = post
        return super().form_valid(form)

    def form_invalid(self, form):
        return HttpResponseRedirect(self.get_success_url())

    def get_success_url(self):
        return reverse('score:post-detail', kwargs=dict(slug=self.kwargs['slug']))


问:
click youtube button selenium python check my code
I am trying to click using class to video on youtube

In this page https://likesrock.com using this code

```<code>from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("https://likesrock.com")

element = driver.find_element_by_class_name("ytp-large-play-button ytp-button")
element.click()
</code>```

but the compilor give me this error

Traceback (most recent call last):
    File "C:\Users\youssef\Desktop\python project\xpath.py", line 25, in
      element = driver.find_element_by_class_name("ytp-large-play-button ytp-button")
    File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 413, in find_element_by_class_name
      return self.find_element(by=By.CLASS_NAME, value=name)
    File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 752, in find_element
      'value': value})['value']
    File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 236, in execute
      self.error_handler.check_response(response)
    File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 192, in check_response
      raise exception_class(message, screen, stacktrace)
  NoSuchElementException: Message: Unable to locate element: .ytp-large-play-button ytp-button

please help

答:
```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome("chromedriver.exe")
driver.get('https://youtube.com')

search_bar = driver.find_element_by_xpath('/html/body/ytd-app/div/div/ytd-masthead/div[3]/div[2]/ytd-searchbox/form/div/div[1]/input')
search_bar.send_keys("python")
search_bar.send_keys(Keys.ENTER)
</code>```

Body:
I am trying to click using class to video on youtube

In this page https://likesrock.com using this code

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("https://likesrock.com")

element = driver.find_element_by_class_name("ytp-large-play-button ytp-button")
element.click()

but the compilor give me this error

Traceback (most recent call last):
    File "C:\Users\youssef\Desktop\python project\xpath.py", line 25, in
      element = driver.find_element_by_class_name("ytp-large-play-button ytp-button")
    File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 413, in find_element_by_class_name
      return self.find_element(by=By.CLASS_NAME, value=name)
    File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 752, in find_element
      'value': value})['value']
    File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 236, in execute
      self.error_handler.check_response(response)
    File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 192, in check_response
      raise exception_class(message, screen, stacktrace)
  NoSuchElementException: Message: Unable to locate element: .ytp-large-play-button ytp-button

please help


问:
I want to Train 4 more Word2vec models and average the resulting embedding matrices
I wrote the code below, I used Used spacy to restrict the words in the tweets to content words, i.e., nouns, verbs, and adjectives. Transform the words to lower case and add the POS with an underderscore. E.g.:

love_VERB old-fashioneds_NOUN

now I want to Train 4 more Word2vec models and average the resulting embedding matrices.
but I dont have any idea for it, can you help me please ?

```<code># Tokenization of each document
from gensim.models.word2vec import FAST_VERSION
from gensim.models import Word2Vec
import spacy
import pandas as pd
from zipfile import ZipFile
import wget

url = 'https://raw.githubusercontent.com/dirkhovy/NLPclass/master/data/reviews.full.tsv.zip'
wget.download(url, 'reviews.full.tsv.zip')

with ZipFile('reviews.full.tsv.zip', 'r') as zf:
    zf.extractall()

# nrows , max amount of rows
df = pd.read_csv('reviews.full.tsv', sep='\t', nrows=100000)
documents = df.text.values.tolist()

nlp = spacy.load('en_core_web_sm')  # you can use other methods
# excluded tags
included_tags = {"NOUN", "VERB", "ADJ"}

vocab = [s for s in new_sentences]

sentences = documents[:103]  # first 10 sentences
new_sentences = []
for sentence in sentences:
    new_sentence = []
    for token in nlp(sentence):
        if token.pos_ in included_tags:
            new_sentence.append(token.text.lower()+'_'+token.pos_)
    new_sentences.append(new_sentence)

# initialize model
w2v_model = Word2Vec(
                     size=100,
                     window=15,
                     sample=0.0001,
                     iter=200,
                     negative=5,
                     min_count=1,  # <-- it seems your min_count was too high
                     workers=-1,
                     hs=0
                     )

new_sentences

w2v_model.build_vocab(vocab)

w2v_model.train(vocab,
                total_examples=w2v_model.corpus_count,
                epochs=w2v_model.epochs)
w2v_model.wv['car_NOUN']
</code>```

答:
There's no reason to average together vectors from multiple training runs; it is more likely to destroy any value from the individual runs than provide any benefit.

No one run creates the 'right' final positions, nor do they all approach some idealized positions. Rather, each just creates a set-of-vectors that is internally comparable to others in that same co-trained set. Comparisons or combinations with vectors from other, non-interleaved training runs are usually going to be nonsense.

Instead, aim for one adequate run. If vectors move around a lot, in repeated runs, that's normal. But each reconfiguration should be about as useful, if used for word-to-word comparisons, or analysis of word neighborhoods/directions, or as input to downstream algorithms. If they vary wildly in usefulness, there are likely other inadequacies in the data or model parameters. (For example: too little data – word2vec requires lots to give meaningful results – or a model that's too large for the data – making it prone to overfitting.)

Other observations about your setup:

Just 103 sentences/texts is tiny for word2vec; you shouldn't expect the vectors from such a run to have any of the value that the algorithm would usually provide. (Running such a tiny dataset might be helpful for verifying no halting-errors in the process, or familiarize yourself with the steps/APIs, but the results will tell you nothing.)

min_count=1 is almost always a bad idea in word2vec and similar algorithms. Words that only appear once (or a few times) don't have the variety of subtly-different uses that are needed to train it into a balanced position against other words – so they wind up with weak/strange final positions, and the sheer number of such words dilutes the training effectiveness for other more-frequent words. The common practice of discarding rare words usually gets better results.

iter=200 is an extreme choice which is typically only valuable to try to squeeze results out of inadequate data. (In such a case, you might also have to reduce the vector-size from normal 100-plus dimensions.) So if you seem to need that, getting more data should be a top priority. (Using 20x more data is far, far better than using 20x more iterations on smaller data – but involves the same amount of training time.)

Body:
I wrote the code below, I used Used spacy to restrict the words in the tweets to content words, i.e., nouns, verbs, and adjectives. Transform the words to lower case and add the POS with an underderscore. E.g.:

love_VERB old-fashioneds_NOUN

now I want to Train 4 more Word2vec models and average the resulting embedding matrices.
but I dont have any idea for it, can you help me please ?

# Tokenization of each document
from gensim.models.word2vec import FAST_VERSION
from gensim.models import Word2Vec
import spacy
import pandas as pd
from zipfile import ZipFile
import wget

url = 'https://raw.githubusercontent.com/dirkhovy/NLPclass/master/data/reviews.full.tsv.zip'
wget.download(url, 'reviews.full.tsv.zip')

with ZipFile('reviews.full.tsv.zip', 'r') as zf:
    zf.extractall()

# nrows , max amount of rows
df = pd.read_csv('reviews.full.tsv', sep='\t', nrows=100000)
documents = df.text.values.tolist()

nlp = spacy.load('en_core_web_sm')  # you can use other methods
# excluded tags
included_tags = {"NOUN", "VERB", "ADJ"}

vocab = [s for s in new_sentences]

sentences = documents[:103]  # first 10 sentences
new_sentences = []
for sentence in sentences:
    new_sentence = []
    for token in nlp(sentence):
        if token.pos_ in included_tags:
            new_sentence.append(token.text.lower()+'_'+token.pos_)
    new_sentences.append(new_sentence)

# initialize model
w2v_model = Word2Vec(
                     size=100,
                     window=15,
                     sample=0.0001,
                     iter=200,
                     negative=5,
                     min_count=1,  # <-- it seems your min_count was too high
                     workers=-1,
                     hs=0
                     )

new_sentences

w2v_model.build_vocab(vocab)

w2v_model.train(vocab,
                total_examples=w2v_model.corpus_count,
                epochs=w2v_model.epochs)
w2v_model.wv['car_NOUN']


问:
Include Azure AD authentication in legacy “aspx” project
I am searching a way to include authentication using Azure AD in a legacy web project (net framework 4 apsx) but I can’t found any doc or example, only for most recent MVC project, SPAs...
Anyone have a reference for me?</p>

答:
You can easily implement authentication using Azure AD in your asp.net web project.

Steps to follow:

Register an application in Azure AD.

Add target API, and grant consent to select permissions.

Choose your authentication flow for example OAuth 2.0 authorization code flow

Implement the authentication flow as mentioned in the Microsoft document in your project. It is very simple and requires only get and post requests to implement.

Please let me know if you still have any issues.


问:
Enlarge an image on mouse hover
I want a picture in my windows form application to enlarge on mouse hover and go back to it's normal size when the mouse leaves the picture.

I couldn't find an answer on Stack Overflow but I figured it out and I want to leave my answer for any c# beginners like me.

答:
This is a very simple solution but it worked for my basic needs. </p>

```<code>private void pictureBox1_MouseHover(object sender, EventArgs e)
{
    pictureBox1.Size = new System.Drawing.Size(90, 60); // Desired hovered size
}

private void pictureBox1_MouseLeave(object sender, EventArgs e)
{
    pictureBox1.Size = new System.Drawing.Size(60, 30); // Back to original size
}
</code>```

Title: Enlarge an image on mouse hover

Body:
This is a very simple solution but it worked for my basic needs.

private void pictureBox1_MouseHover(object sender, EventArgs e)
{
    pictureBox1.Size = new System.Drawing.Size(90, 60); // Desired hovered size
}

private void pictureBox1_MouseLeave(object sender, EventArgs e)
{
    pictureBox1.Size = new System.Drawing.Size(60, 30); // Back to original size
}


问:
Using Python and BeautifulSoup to scrape list from an URL
I am new to BeautifulSoup so please excuse any beginner mistakes here. I am attempting to scrape an url and want to store list of movies under one date.
Below is the code I have so far:

```<code>import requests
from bs4 import BeautifulSoup
page = requests.get("https://www.imdb.com/calendar?region=IN&ref_=rlm")
soup = BeautifulSoup(page.content, 'html.parser')
date = soup.find_all("h4")
ul = soup.find_all("ul")
for h4,h1 in zip(date,ul):
    dd_=h4.get_text()
    mv=ul.find_all('a')
    for movie in mv:
        text=movie.get_text()
        print (dd_,text)
        movielist.append((dd_,text))
</code>```

I am getting "AttributeError: ResultSet object has no attribute 'find_all'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?"

Expected result in list or dataframe

```<code>29th May 2020 Romantic
29th May 2020 Sohreyan Da Pind Aa Gaya
5th June 2020 Lakshmi Bomb
and so on
</code>```

Thanks in advance for help.

答:
This script will get all movies and corresponding dates to a dataframe:

```<code>import requests
import pandas as pd
from bs4 import BeautifulSoup

url = 'https://www.imdb.com/calendar?region=IN&ref_=rlm'
soup = BeautifulSoup(requests.get(url).content, 'html.parser')

out, last = [], ''
for tag in soup.select('#main h4, #main li'):
    if tag.name == 'h4':
        last = tag.get_text(strip=True)
    else:
        out.append({'Date':last, 'Movie':tag.get_text(strip=True).rsplit('(', maxsplit=1)[0]})

df = pd.DataFrame(out)
print(df)
</code>```

Prints:

```<code>             Date                          Movie
0     29 May 2020                       Romantic
1     29 May 2020       Sohreyan Da Pind Aa Gaya
2    05 June 2020                    Laxmmi Bomb
3    05 June 2020                   Roohi Afzana
4    05 June 2020                        Nikamma
..            ...                            ...
95  26 March 2021       Untitled Luv Ranjan Film
96  02 April 2021                             F9
97  02 April 2021                    Bell Bottom
98  02 April 2021  NTR Trivikiram Untitled Movie
99  09 April 2021                 Manje Bistre 3

[100 rows x 2 columns]
</code>```

Body:
I am new to BeautifulSoup so please excuse any beginner mistakes here. I am attempting to scrape an url and want to store list of movies under one date.
Below is the code I have so far:

import requests
from bs4 import BeautifulSoup
page = requests.get("https://www.imdb.com/calendar?region=IN&ref_=rlm")
soup = BeautifulSoup(page.content, 'html.parser')
date = soup.find_all("h4")
ul = soup.find_all("ul")
for h4,h1 in zip(date,ul):
    dd_=h4.get_text()
    mv=ul.find_all('a')
    for movie in mv:
        text=movie.get_text()
        print (dd_,text)
        movielist.append((dd_,text))

I am getting "AttributeError: ResultSet object has no attribute 'find_all'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?"

Expected result in list or dataframe

29th May 2020 Romantic
29th May 2020 Sohreyan Da Pind Aa Gaya
5th June 2020 Lakshmi Bomb
and so on

Thanks in advance for help.

Body:
This script will get all movies and corresponding dates to a dataframe:

import requests
import pandas as pd
from bs4 import BeautifulSoup

url = 'https://www.imdb.com/calendar?region=IN&ref_=rlm'
soup = BeautifulSoup(requests.get(url).content, 'html.parser')

out, last = [], ''
for tag in soup.select('#main h4, #main li'):
    if tag.name == 'h4':
        last = tag.get_text(strip=True)
    else:
        out.append({'Date':last, 'Movie':tag.get_text(strip=True).rsplit('(', maxsplit=1)[0]})

df = pd.DataFrame(out)
print(df)

Prints:

             Date                          Movie
0     29 May 2020                       Romantic
1     29 May 2020       Sohreyan Da Pind Aa Gaya
2    05 June 2020                    Laxmmi Bomb
3    05 June 2020                   Roohi Afzana
4    05 June 2020                        Nikamma
..            ...                            ...
95  26 March 2021       Untitled Luv Ranjan Film
96  02 April 2021                             F9
97  02 April 2021                    Bell Bottom
98  02 April 2021  NTR Trivikiram Untitled Movie
99  09 April 2021                 Manje Bistre 3

[100 rows x 2 columns]


问:
Is it safe to apply Terraform plan when it says the database instance must be replaced?
I'm importing the existing resources (AWS RDS) but the terraform plan command showed a summary:

```<code>#aws_db_instance.my_main_db must be replaced
+/- resource "aws_db_instance" "my_main_db" {
~ address = x
allocated_storage = x
+ apply_immediately = x
~ arn = x
~ username = x
+ password = x
(others arguments with alot of +/- and ~)
}
</code>```

my_main_db is online with persistent data. My question is as the title; Is it safe for the existing database to run terrafrom apply? I don't want to lose all my customer data.

答:
"Replace" in Terraform's terminology means to destroy the existing object and create a new one to replace it. The +/- symbol (as opposed to -/+) indicates that this particular resource will be replaced in the "create before destroy" mode, where there will briefly be two database instances existing during the operation. (This may or may not be possible in practice, depending on whether the instance name is changing as part of this operation.)

For aws_db_instance in particular, destroying an instance is equivalent to deleting the instance in the RDS console: unless you have a backup of the contents of the database, it will be lost. Even if you do have a backup, you'll need to restore it via the RDS console or API rather than with Terraform because Terraform doesn't know about the backup/restore mechanism and so its idea of "create" is to produce an entirely new, empty database.

To sum up: applying a plan like this directly is certainly not generally "safe", because Terraform is planning to destroy your database and all of the contents along with it.

If you need to make changes to your database that cannot be performed without creating an entirely new RDS instance, you'll usually need to make those changes outside of Terraform using RDS-specific tools so that you can implement some process for transferring data between the old and new instances, whether that be backup and then restore (which will require a temporary outage) or temporarily running both instances and setting up replication from old to new until you are ready to shut off the old one. The details of such a migration are outside of Terraform's scope, because they are specific to whatever database engine you are using.

Body:
I'm importing the existing resources (AWS RDS) but the terraform plan command showed a summary:

#aws_db_instance.my_main_db must be replaced
+/- resource "aws_db_instance" "my_main_db" {
~ address = x
allocated_storage = x
+ apply_immediately = x
~ arn = x
~ username = x
+ password = x
(others arguments with alot of +/- and ~)
}

my_main_db is online with persistent data. My question is as the title; Is it safe for the existing database to run terrafrom apply? I don't want to lose all my customer data.


问:
Put many pictures into one div with specific size
I have created an app which creates lots of pictures with new Image() according to the context.

I want to put all my photos into one specific div, this div will always have the same size: 90% of the screen.

When I hover over a picture, the real picture will appear.

The photos width have to be resized according to the number of photos.

This is an example of what I want to do:

Every color represents a different picture.

This is when I hover a picture (here: the red one):

I have absolutely no idea of how to make this. If you have an idea or a clue for one of these things you're welcome to help me! Thanks.

答:
when you add the image to div, you could to this. </p>

```<code>$("div > img").css("width",($("div > img").length/100)+"%");
</code>```

<p>I supposed you are using jquery, if not at least you have a better idea.
(Apply a width for every image inside, width is number of images/100 percent). </p>

Body:
when you add the image to div, you could to this.

$("div > img").css("width",($("div > img").length/100)+"%");

I supposed you are using jquery, if not at least you have a better idea.
(Apply a width for every image inside, width is number of images/100 percent).


问:
Get the first word in a String of words & spaces - Substring first word before space
I have a string that has words and spaces, "2h 3m 1s". I want to extract 2h out of it; so get everything before first space.

```<code>var date = "1,340d 1h 15m 52s"  // I want to extract "1,340d".
</code>```

What is the best practice of doing it? What substring function is the best approach?

答:
Swift 5

```<code>var name = ""
if let optionalName = someOptionalString as? String {
    name = optionalName.contains(" ") ? (name.components(separatedBy: " ").first ?? "") : optionalName
}
</code>```

First, we make sure the string is not nil.
Then, we use the ternary operator to assign it accordingly based on it it contains any spaces or not.

ContentLicense: CC BY-SA 3.0

Body:
I have a string that has words and spaces, "2h 3m 1s". I want to extract 2h out of it; so get everything before first space.

var date = "1,340d 1h 15m 52s"  // I want to extract "1,340d".

What is the best practice of doing it? What substring function is the best approach?

Body:
Swift 5

var name = ""
if let optionalName = someOptionalString as? String {
    name = optionalName.contains(" ") ? (name.components(separatedBy: " ").first ?? "") : optionalName
}

First, we make sure the string is not nil.
Then, we use the ternary operator to assign it accordingly based on it it contains any spaces or not.


问:
Dot Operator in Objective-C 2.0
Just picking up Objective-C 2.0 and wanted to know if there is any advantage in using the dot operator for accessing properties instead of the "old" way. Short example of what I mean.

"old" way:

```<code> [myFraction setNumerator: 1];
 [myFraction setDenominator: 3];
</code>```

"new" way:

```<code> myFraction.numerator = 1;
 myFraction.denominator = 3;
</code>```

Thanks!

Rodrigo

答: C++ and C# programmers probably will more naturally adapt to the dot operator when accessing member variables since it has similar usage in those languages.</p>

OwnerDisplayName: Rodrigo Haenggi

ContentLicense: CC BY-SA 2.5

Title: Dot Operator in Objective-C 2.0

Body:
Just picking up Objective-C 2.0 and wanted to know if there is any advantage in using the dot operator for accessing properties instead of the "old" way. Short example of what I mean.

"old" way:

 [myFraction setNumerator: 1];
 [myFraction setDenominator: 3];

"new" way:

 myFraction.numerator = 1;
 myFraction.denominator = 3;

Thanks!

Rodrigo

OwnerDisplayName: ZZ


问:
programmatically load image at coordinate

Hi I want to load a square image (the page curl) as seen in the lower right corner programmatically when the view controller loads.

How to do this?

答: Just add a UIImageView as a subview and set the appropriate frame.


问:
Unable to incorperate an online picture in a report using R markdown and knitr
I am trying to include a picture file from the internet in my R Markdown report. I am hoping to print this out on to a pdf file. However, whenever I try to run my code, I get a LaTeX file not found error. The picture exists on the web, I just can't seem to be able to bring it into my report.

My code:

```<code>```{r, out.width = "50%"}
include_graphics("https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/MC_Drei-Finger-Faultier.jpg/330px-MC_Drei-Finger-Faultier.jpg")
```
</code>```

My error is this:
! LaTeX Error: File `https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/
MC_Drei-Finger-Faultier.jpg/330px-MC_Drei-Finger-Faultier' not found.

The picture in question: https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/MC_Drei-Finger-Faultier.jpg/330px-MC_Drei-Finger-Faultier.jpg

I am using:

knitr v 1.28

rmarkdown v 2

on a mac

答:
To display an image from a URL in a pdf, you have to first download the file. You may need a different mode depending on your OS.

```<code>```{r, out.width = "50%"}
myurl <- "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/MC_Drei-Finger-Faultier.jpg/330px-MC_Drei-Finger-Faultier.jpg"

download.file(url = myurl, destfile = 'temp.jpg', mode = 'wb')

knitr::include_graphics('temp.jpg')
```

Body:
I am trying to include a picture file from the internet in my R Markdown report. I am hoping to print this out on to a pdf file. However, whenever I try to run my code, I get a LaTeX file not found error. The picture exists on the web, I just can't seem to be able to bring it into my report.

My code:

```{r, out.width = "50%"}
include_graphics("https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/MC_Drei-Finger-Faultier.jpg/330px-MC_Drei-Finger-Faultier.jpg")
```

My error is this:
! LaTeX Error: File `https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/
MC_Drei-Finger-Faultier.jpg/330px-MC_Drei-Finger-Faultier' not found.

The picture in question: https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/MC_Drei-Finger-Faultier.jpg/330px-MC_Drei-Finger-Faultier.jpg

I am using:

knitr v 1.28

rmarkdown v 2

on a mac

Body:
To display an image from a URL in a pdf, you have to first download the file. You may need a different mode depending on your OS.

```{r, out.width = "50%"}
myurl <- "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/MC_Drei-Finger-Faultier.jpg/330px-MC_Drei-Finger-Faultier.jpg"

download.file(url = myurl, destfile = 'temp.jpg', mode = 'wb')

knitr::include_graphics('temp.jpg')


问:
Self-modifying code on macOS v10.15 (Catalina) / x64
As part as porting a Forth compiler, I'm trying to create a binary that allows for self-modifying code. The gory details are at https://github.com/klapauciusisgreat/jonesforth-MacOS-x64

Ideally, I create a bunch of pages for user definitions and call mprotect like so:

```<code>#define __NR_exit 0x2000001
#define __NR_open 0x2000005
#define __NR_close 0x2000006
#define __NR_read 0x2000003
#define __NR_write 0x2000004
#define __NR_mprotect 0x200004a

#define PROT_READ 0x01
#define PROT_WRITE 0x02
#define PROT_EXEC 0x04
#define PROT_ALL (PROT_READ | PROT_WRITE | PROT_EXEC)
#define PAGE_SIZE 4096

// https://opensource.apple.com/source/xnu/xnu-201/bsd/sys/errno.h
#define EACCES    13              /* Permission denied */
#define EINVAL    22              /* Invalid argument */
#define ENOTSUP   45              /* Operation not supported */

/* Assembler entry point. */
        .text
        .globl start
start:
        // Use mprotect to allow read/write/execute of the .bss section
        mov $__NR_mprotect, %rax                // mprotect
        lea user_defs_start(%rip), %rdi         // Start address
        and $-PAGE_SIZE,%rdi                    // Align at page boundary
        mov $USER_DEFS_SIZE, %rsi               // Length
        mov $PROT_ALL,%rdx
        syscall
        cmp $EINVAL, %rax
        je 1f
        cmp $EACCES,%rax
        je 2f
        test %rax,%rax
        je 4f                                   // All good, proceed:

        // must be ENOTSUP
        mov $2,%rdi                     // First parameter: stderr
        lea errENOTSUP(%rip),%rsi       // Second parameter: error message
        mov $8,%rdx                     // Third parameter: length of string
        mov $__NR_write,%rax            // Write syscall
        syscall
        jmp 3f

1:
        mov $2,%rdi                     // First parameter: stderr
        lea errEINVAL(%rip),%rsi        // Second parameter: error message
        mov $7,%rdx                     // Third parameter: length of string
        mov $__NR_write,%rax            // Write syscall
        syscall
        jmp 3f

2:
        mov $2,%rdi                     // First parameter: stderr
        lea errEACCES(%rip),%rsi        // Second parameter: error message
        mov $7,%rdx                     // Third parameter: length of string
        mov $__NR_write,%rax            // Write syscall
        syscall

3:
        // did't work -- then exit
        xor %rdi,%rdi
        mov $__NR_exit,%rax     // syscall: exit
        syscall

4:
// All good, let's get started for real:

.
.
.

        .set RETURN_STACK_SIZE,8192
        .set BUFFER_SIZE,4096
        .set USER_DEFS_SIZE,65536*2 // 128 kiB ought to be enough for everybody

        .bss
        .balign 8
user_defs_start:
        .space USER_DEFS_SIZE

</code>```

However, I get an EACCES return value. I suspect that this is because of some security policy apple has set up, but I do not find good documentation.

Where is the source code for mprotect, and/or what are the methods to mark the data area executable and writable at the same time?

I found that compiling with

gcc -segprot __DATA rwx rwx
```

does mark the entire data segment rwx, so it must somehow be possible to do the right thing. But I would prefer to only make the area hosting Forth words executable, not the entire data segment.

I found a similar discussion here, but without any solution.

答:
The segment that I want to 'unprotect' exec permission in has really two values describing its permissions:

the initial protection settings, which for __DATA I want rw-

the maximum protection (loosest) settings, which I want to be rwx.

So first I need to set the maxprot field to rwx. According to the ld manpage, this should be achieved by invoking gcc or ld with the flags -segprot __DATA rwx rw. However, a recent change made by Apple to the linker essentially ignores the maxprot value, and sets maxprot=initprot.

Thanks to Darfink, you can use this script to tweak the maxprot bits after the fact. I thought additional code signing with special entitlements was required, but it's not, at least for the __DATA segment. The __TEXT segment may need code signing with the com.apple.security.cs.disable-executable-page-protection entitlement.

Also see here for a few more details.

Looking at the larger picture, I should also point out that rather to unprotect pieces of an otherwise protected __DATA segment, it may be better to create a complete new data/code segment just for the self-modifying code with rwx permissions from the start. This allows still protecting the rest of data by the operating system, and requires no non-standard tools.

Body:
As part as porting a Forth compiler, I'm trying to create a binary that allows for self-modifying code. The gory details are at https://github.com/klapauciusisgreat/jonesforth-MacOS-x64

Ideally, I create a bunch of pages for user definitions and call mprotect like so:

#define __NR_exit 0x2000001
#define __NR_open 0x2000005
#define __NR_close 0x2000006
#define __NR_read 0x2000003
#define __NR_write 0x2000004
#define __NR_mprotect 0x200004a

#define PROT_READ 0x01
#define PROT_WRITE 0x02
#define PROT_EXEC 0x04
#define PROT_ALL (PROT_READ | PROT_WRITE | PROT_EXEC)
#define PAGE_SIZE 4096

// https://opensource.apple.com/source/xnu/xnu-201/bsd/sys/errno.h
#define EACCES    13              /* Permission denied */
#define EINVAL    22              /* Invalid argument */
#define ENOTSUP   45              /* Operation not supported */

/* Assembler entry point. */
        .text
        .globl start
start:
        // Use mprotect to allow read/write/execute of the .bss section
        mov $__NR_mprotect, %rax                // mprotect
        lea user_defs_start(%rip), %rdi         // Start address
        and $-PAGE_SIZE,%rdi                    // Align at page boundary
        mov $USER_DEFS_SIZE, %rsi               // Length
        mov $PROT_ALL,%rdx
        syscall
        cmp $EINVAL, %rax
        je 1f
        cmp $EACCES,%rax
        je 2f
        test %rax,%rax
        je 4f                                   // All good, proceed:

        // must be ENOTSUP
        mov $2,%rdi                     // First parameter: stderr
        lea errENOTSUP(%rip),%rsi       // Second parameter: error message
        mov $8,%rdx                     // Third parameter: length of string
        mov $__NR_write,%rax            // Write syscall
        syscall
        jmp 3f

1:
        mov $2,%rdi                     // First parameter: stderr
        lea errEINVAL(%rip),%rsi        // Second parameter: error message
        mov $7,%rdx                     // Third parameter: length of string
        mov $__NR_write,%rax            // Write syscall
        syscall
        jmp 3f

2:
        mov $2,%rdi                     // First parameter: stderr
        lea errEACCES(%rip),%rsi        // Second parameter: error message
        mov $7,%rdx                     // Third parameter: length of string
        mov $__NR_write,%rax            // Write syscall
        syscall

3:
        // did't work -- then exit
        xor %rdi,%rdi
        mov $__NR_exit,%rax     // syscall: exit
        syscall

4:
// All good, let's get started for real:

.
.
.

        .set RETURN_STACK_SIZE,8192
        .set BUFFER_SIZE,4096
        .set USER_DEFS_SIZE,65536*2 // 128 kiB ought to be enough for everybody

        .bss
        .balign 8
user_defs_start:
        .space USER_DEFS_SIZE

However, I get an EACCES return value. I suspect that this is because of some security policy apple has set up, but I do not find good documentation.

Where is the source code for mprotect, and/or what are the methods to mark the data area executable and writable at the same time?

I found that compiling with

gcc -segprot __DATA rwx rwx

does mark the entire data segment rwx, so it must somehow be possible to do the right thing. But I would prefer to only make the area hosting Forth words executable, not the entire data segment.

I found a similar discussion here, but without any solution.


问:
Fill list from joined table LINQ
```<code>using System.Collections.Generic;
using ViewModelsDemo.Models;

namespace ViewModelsDemo.ViewModels
{
    public class CustomerViewModel
    {

        public List<JoinedTableClass> JoinedTable { get; set; }
    }
    public class JoinedTableClass
{

    public string FirstField { get; set; }  // Table1
    public string SecondField { get; set; } // Table2
    public string ThirdField{ get; set; }  // Table 2

}

}
</code>```

I tried to do the following, but it's not working.

```<code>        var customerViewModel = new CustomerViewModel
        {

            JoinedTable = (from Cust in Tables.Customer

            join D in Tables.Dep on Cust.Customer_ID equals D.ID

            select new CustomerViewModel  { Cust.FirstName , Cust.LastName , D.Serialz })

        };

        return View(customerViewModel);
</code>```

On the before-last line, I have the following error:

Cannot initiate type "CustomerViewModel" with a collection initiliazed because it does not implemented System.Collections.Ienumerable

答:
//Changing your Implementation
 If you just want list of JoinedTableClass,then use this</p>

```<code>            var JoinedTable = (from Cust in Tables.Customer
                  join D in Tables.Dep on Cust.Customer_ID equals D.ID
                 select new JoinedTableClass
                 {
                   FirstField = Cust.FirstName ,
                   SecondField = Cust.LastName ,
                   ThirdField = D.Serialz
                 }).ToList()

        return View(JoinedTable );
</code>```

Title: Fill list from joined table LINQ

Body:
using System.Collections.Generic;
using ViewModelsDemo.Models;

namespace ViewModelsDemo.ViewModels
{
    public class CustomerViewModel
    {

        public List<JoinedTableClass> JoinedTable { get; set; }
    }
    public class JoinedTableClass
{

    public string FirstField { get; set; }  // Table1
    public string SecondField { get; set; } // Table2
    public string ThirdField{ get; set; }  // Table 2

}

}

I tried to do the following, but it's not working.

        var customerViewModel = new CustomerViewModel
        {

            JoinedTable = (from Cust in Tables.Customer

            join D in Tables.Dep on Cust.Customer_ID equals D.ID

            select new CustomerViewModel  { Cust.FirstName , Cust.LastName , D.Serialz })

        };

        return View(customerViewModel);

On the before-last line, I have the following error:

Cannot initiate type "CustomerViewModel" with a collection initiliazed because it does not implemented System.Collections.Ienumerable

Body:
//Changing your Implementation
 If you just want list of JoinedTableClass,then use this

            var JoinedTable = (from Cust in Tables.Customer
                  join D in Tables.Dep on Cust.Customer_ID equals D.ID
                 select new JoinedTableClass
                 {
                   FirstField = Cust.FirstName ,
                   SecondField = Cust.LastName ,
                   ThirdField = D.Serialz
                 }).ToList()

        return View(JoinedTable );


问:
Retrieving a property from an action value in Angular 9 & NgRx reducer
I'm having trouble retrieving the property of a value in an NgRx reducer. I'm trying to extract the accessToken of the user object and store it in the state. However, despite the user object being valid and containing a valid accessToken, when I try to retrieve the accessToken it returns undefined.

In the debugger if I hover over the user object, I can see the full value with all the properties including accessToken, but if I skip to the next line and hover over accessToken object it shows undefined.

```<code>import { createReducer, on } from '@ngrx/store';
import { User } from 'src/app/models/user.model';
import { AuthActions } from '../action-types';

export const authFeatureKey = 'auth';

export interface AuthState {
  user: User;
  accessToken: string;
}

export const initialAuthState: AuthState = {
  user: undefined,
  accessToken: undefined,
};

const reducer = createReducer(
  initialAuthState,

  on(AuthActions.signup, (state, action) => {
    return {
      user: action.user,
      accessToken: action.user.accessToken,
    };
  }),

  on(AuthActions.signin, (state, action) => {
    // split out to debug.
    const user = <User>action.user; // action.user returns a valid object
    const token = user.accessToken; // despite this being valid in the user object, returns undefined.
    return {
      user: action.user,
      accessToken: token,
    };
  }),

  on(AuthActions.signOut, () => {
    return {
      user: undefined,
      accessToken: undefined,
    };
  }),
);

export function authReducer(state, action) {
  return reducer(state, action);
}
</code>```

These are the actions:

```<code>import { createAction, props } from '@ngrx/store';
import { User } from '../../models/user.model';

export const signup = createAction('[SignUp Page] User SignUp', props<{ user: User }>());

export const signin = createAction('[SignIn Page] User SignIn', props<{ user: User }>());

export const signOut = createAction('[Top Menu] User SignOut');
</code>```

and these are the selectors:

```<code>import { createFeatureSelector, createSelector } from '@ngrx/store';
import * as fromAuth from './reducers';

export const selectAuthState = createFeatureSelector<fromAuth.AuthState>(fromAuth.authFeatureKey);

export const isLoggedIn = createSelector(selectAuthState, (auth) => !!auth.user);

export const isLoggedOut = createSelector(isLoggedIn, (loggedIn) => !loggedIn);

export const getCurrentUser = createSelector(selectAuthState, (auth) => auth.user);

export const getAccessToken = createSelector(selectAuthState, (auth) => auth.accessToken);
</code>```

This is the auth.module.ts, showing the import of the authReducer (as requested)

```<code>import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';

import { StoreModule } from '@ngrx/store';
import { EffectsModule } from '@ngrx/effects';
import { AuthRoutingModule } from './auth-routing.module';
import { AuthService } from './services/auth.service';
import * as fromAuth from './store/reducers';
import { AuthEffects } from './store/auth-effects';

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    AuthRoutingModule,
    HttpClientModule,
    StoreModule.forFeature(fromAuth.authFeatureKey, fromAuth.authReducer),
    EffectsModule.forFeature([AuthEffects]),
  ],
  providers: [AuthService],
})
export class AuthModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: AuthModule,
      providers: [AuthService],
    };
  }
}
</code>```

I have noticed that in the state, it's storing the value somewhat weirdly:

```<code>auth
    user
      user
         userName: "username1"
         email: "email@email.com"
         accessToken: "ey......7z"
         refreshToken: "xxx"
</code>```

So it looks like it's somehow nesting the user object.

答:
The action.user can be valid, it doesn't mean it contains all required information. Especially when httpClient is used and its response is casted to any type.

You need to debug the effect that emits AuthActions.signin to ensure that the user it generates contains .accessToken value.

Body:
I'm having trouble retrieving the property of a value in an NgRx reducer. I'm trying to extract the accessToken of the user object and store it in the state. However, despite the user object being valid and containing a valid accessToken, when I try to retrieve the accessToken it returns undefined.

In the debugger if I hover over the user object, I can see the full value with all the properties including accessToken, but if I skip to the next line and hover over accessToken object it shows undefined.

import { createReducer, on } from '@ngrx/store';
import { User } from 'src/app/models/user.model';
import { AuthActions } from '../action-types';

export const authFeatureKey = 'auth';

export interface AuthState {
  user: User;
  accessToken: string;
}

export const initialAuthState: AuthState = {
  user: undefined,
  accessToken: undefined,
};

const reducer = createReducer(
  initialAuthState,

  on(AuthActions.signup, (state, action) => {
    return {
      user: action.user,
      accessToken: action.user.accessToken,
    };
  }),

  on(AuthActions.signin, (state, action) => {
    // split out to debug.
    const user = <User>action.user; // action.user returns a valid object
    const token = user.accessToken; // despite this being valid in the user object, returns undefined.
    return {
      user: action.user,
      accessToken: token,
    };
  }),

  on(AuthActions.signOut, () => {
    return {
      user: undefined,
      accessToken: undefined,
    };
  }),
);

export function authReducer(state, action) {
  return reducer(state, action);
}

These are the actions:

import { createAction, props } from '@ngrx/store';
import { User } from '../../models/user.model';

export const signup = createAction('[SignUp Page] User SignUp', props<{ user: User }>());

export const signin = createAction('[SignIn Page] User SignIn', props<{ user: User }>());

export const signOut = createAction('[Top Menu] User SignOut');

and these are the selectors:

import { createFeatureSelector, createSelector } from '@ngrx/store';
import * as fromAuth from './reducers';

export const selectAuthState = createFeatureSelector<fromAuth.AuthState>(fromAuth.authFeatureKey);

export const isLoggedIn = createSelector(selectAuthState, (auth) => !!auth.user);

export const isLoggedOut = createSelector(isLoggedIn, (loggedIn) => !loggedIn);

export const getCurrentUser = createSelector(selectAuthState, (auth) => auth.user);

export const getAccessToken = createSelector(selectAuthState, (auth) => auth.accessToken);

This is the auth.module.ts, showing the import of the authReducer (as requested)

import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';

import { StoreModule } from '@ngrx/store';
import { EffectsModule } from '@ngrx/effects';
import { AuthRoutingModule } from './auth-routing.module';
import { AuthService } from './services/auth.service';
import * as fromAuth from './store/reducers';
import { AuthEffects } from './store/auth-effects';

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    AuthRoutingModule,
    HttpClientModule,
    StoreModule.forFeature(fromAuth.authFeatureKey, fromAuth.authReducer),
    EffectsModule.forFeature([AuthEffects]),
  ],
  providers: [AuthService],
})
export class AuthModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: AuthModule,
      providers: [AuthService],
    };
  }
}

I have noticed that in the state, it's storing the value somewhat weirdly:

auth
    user
      user
         userName: "username1"
         email: "email@email.com"
         accessToken: "ey......7z"
         refreshToken: "xxx"

So it looks like it's somehow nesting the user object.


问:
Null checks on extension methods that do not need an instance?
I recently asked this question on the subject, which was closed as a duplicate of this one - as was this one before mine. However, I want to ask a more specific question on a corner case that I feel none of the above questions, or their answers, really covers:

How should an extension method that doesn't really need an instance react to null references?

An example (where the answer is obvious) would be the .IsNullOrEmpty() (which of course should just return true on a null reference), but I believe there might be other cases where it makes sense to call an extension method on an object that might be null.

Another example could be a variation of the method I outlined in my other question, if we for a minute assume that the foreach loop will not throw on a null collection (I know it does, but imagine it doesn't just as a thought experiment).

What would be best practice here? Should we check for null and throw ArgumentNullException anyway, or does it depend on the case? If it does depend on the case, on what criteria should we decide what to do?

答:
If I am understanding you correctly, this is what you're saying:

```<code>public class MyClass
{
    ....
}

public static class MyClassExtension
{
    public static void MyClassExtensionMethod1(this MyClass obj, string name)
    {
        if(obj == null)
        {
            // what to do here, since obj is not used anywhere in this method
        }

        Console.WriteLine(name);
    }
}
</code>```

I think it depends on your school of thought.

Since MyClassExtensionMethod1 doesn't use the MyClass object at all, you can skip the check, and skip notifying client code (or users).

Before going further, I would ask myself, what is the point of having this extension method in the first place, if it doesn't reference an instance of the class passed in?

I would just suggest one of the two following approaches:

If you can modify the code, and this method belongs to MyClass, make MyClassExtensionMethod1 a method in MyClass. Of course, this means that the instance will not be null, so you're changing your expectations :)

```<code>public class MyClass
{
    ...

    public MyClassMethod1(string name)
    {
        Console.WriteLine(name);
    }
}
</code>```

...Or, if you really, really don't need the MyClass instance, move this method to another class, independent of MyClass:

```<code>// not an extension class
public class MyOtherClass
{
    public void MyOtherClassMethod1(string name)
    {
        Console.WriteLine(name);
    }
}
</code>```

Even if you keep your extension method (and whether it throws or not), I suggest adding good documentation on your decision, for future reference.

Body:
If I am understanding you correctly, this is what you're saying:

public class MyClass
{
    ....
}

public static class MyClassExtension
{
    public static void MyClassExtensionMethod1(this MyClass obj, string name)
    {
        if(obj == null)
        {
            // what to do here, since obj is not used anywhere in this method
        }

        Console.WriteLine(name);
    }
}

I think it depends on your school of thought.

Since MyClassExtensionMethod1 doesn't use the MyClass object at all, you can skip the check, and skip notifying client code (or users).

Before going further, I would ask myself, what is the point of having this extension method in the first place, if it doesn't reference an instance of the class passed in?

I would just suggest one of the two following approaches:

If you can modify the code, and this method belongs to MyClass, make MyClassExtensionMethod1 a method in MyClass. Of course, this means that the instance will not be null, so you're changing your expectations :)

public class MyClass
{
    ...

    public MyClassMethod1(string name)
    {
        Console.WriteLine(name);
    }
}

...Or, if you really, really don't need the MyClass instance, move this method to another class, independent of MyClass:

// not an extension class
public class MyOtherClass
{
    public void MyOtherClassMethod1(string name)
    {
        Console.WriteLine(name);
    }
}

Even if you keep your extension method (and whether it throws or not), I suggest adding good documentation on your decision, for future reference.


问:
broker.xml location in Apache Artemis
I downloaded Apache Artemis project from github. Artemis documentation mentions about settings to be done in the file "broker.xml". However, I could not locate the file. I looked into the location https://github.com/apache/activemq-artemis/tree/master/artemis-server/src/main/resources/schema and the file is not present. There are many broker.xml files in other projects.

Could someone please tell the location of the broker.xml file that needs to modified to run the Artemis broker? I intend to run via IDE. I am already able to run a single instance. Now I want to run a cluster for which I need to make changes to the broker.xml but I cannot locate where it is. Thanks.

答:
I will take the example that I have put my uploaded package  under /var/lib/ and I had extract it in the same path into "home_artemis". So, I will go under bin then run ./artemis with the right parameters:

broker name : Master_rep
user login : admin ## used to connect after to hawtio console #
user password : admin
the broker path : /var/lib/home_artemis/bin/brokers/Master_rep/etc

By default, from the path that you will call the script artemis it will create there the broker :
for example you are under

```<code>cd /var/lib
</code>```

and you call

```<code>sudo /usr/local/bin/Artemis_home/bin/artemis create [broker_name]
</code>```

your broker will be created under the path :   /var/lib

For a best practice I advice to put all under the same path like this example :

```<code>cd /var/lib/home_artemis/bin

/artemis create brokers/Master_rep --name Master_rep --user admin --password admin --allow-anonymous /var/lib/home_artemis/bin/brokers/Master_rep/etc
</code>```

Title: broker.xml location in Apache Artemis

Body:
I will take the example that I have put my uploaded package  under /var/lib/ and I had extract it in the same path into "home_artemis". So, I will go under bin then run ./artemis with the right parameters:

broker name : Master_rep
user login : admin ## used to connect after to hawtio console #
user password : admin
the broker path : /var/lib/home_artemis/bin/brokers/Master_rep/etc

By default, from the path that you will call the script artemis it will create there the broker :
for example you are under

cd /var/lib

and you call

sudo /usr/local/bin/Artemis_home/bin/artemis create [broker_name]

your broker will be created under the path :   /var/lib

For a best practice I advice to put all under the same path like this example :

cd /var/lib/home_artemis/bin

/artemis create brokers/Master_rep --name Master_rep --user admin --password admin --allow-anonymous /var/lib/home_artemis/bin/brokers/Master_rep/etc


问:
C++ compile problem with strlen and strcpy

#include<iostream>
using namespace std;

int main()
{
    char a[5],b[5];
    cout<<strlen(a)<<endl;
    strcpy(a,b);
}
```

when I compile the code using g++ filename.cpp the code will be compiled with no issues but when my friends try to do it using dev-c++, they'll get errors!

based on cplusplus.com, I am the one who should get errors!!

so I am just wondering what's causing the difference here?

P.S: I have tried different versions of C++ using -std=c++98 throw -std=c++2a

答:
```<code>char a[5],b[5];
cout<<strlen(a)<<endl;
strcpy(a,b);
</code>```

Both a and b are uninitialised. Your program has undefined behaviour. The compiler has no obligation to generate anything in particular. Any behaviour is acceptable. You cannot reason about code with UB. The program is simply invalid/broken (and the compiler is also not obligated to warn you about UB btw).

As for failing to compile: you did not include the header defining strcpy and strlen. That's in <cstring>. Include that header and the code should compile (it'll still be broken, but it should compile)..

Standard library headers (like iostream) are allowed to include other headers, but they are not required to do so. So, on some systems you may be able to get away with not including a header since some other one pulls it in for you. But that's not guaranteed and you shouldn't rely on it. Always explicitly include the headers for the stuff you need/use.

Body:
#include<iostream>
using namespace std;

int main()
{
    char a[5],b[5];
    cout<<strlen(a)<<endl;
    strcpy(a,b);
}

when I compile the code using g++ filename.cpp the code will be compiled with no issues but when my friends try to do it using dev-c++, they'll get errors!

based on cplusplus.com, I am the one who should get errors!!

so I am just wondering what's causing the difference here?

P.S: I have tried different versions of C++ using -std=c++98 throw -std=c++2a

Body:
char a[5],b[5];
cout<<strlen(a)<<endl;
strcpy(a,b);

Both a and b are uninitialised. Your program has undefined behaviour. The compiler has no obligation to generate anything in particular. Any behaviour is acceptable. You cannot reason about code with UB. The program is simply invalid/broken (and the compiler is also not obligated to warn you about UB btw).

As for failing to compile: you did not include the header defining strcpy and strlen. That's in <cstring>. Include that header and the code should compile (it'll still be broken, but it should compile)..

Standard library headers (like iostream) are allowed to include other headers, but they are not required to do so. So, on some systems you may be able to get away with not including a header since some other one pulls it in for you. But that's not guaranteed and you shouldn't rely on it. Always explicitly include the headers for the stuff you need/use.


问:
How can I show only one item from current position to horizontal RecyclerView?
I have horizontal RecyclerView which has GridView. When I scroll RecyclerView, 2 elements appear at the same time. I just want to show the item at the current position.

Activity:

```<code>recyclerView = findViewById(R.id.recyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false);
recyclerView.setHasFixedSize(false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(new MyRecyclerViewAdapter(this, getTotalCount()));
</code>```

My adapter:

```<code>public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.MyViewHolder> {

    private int count;
    private Context context;

    public MyRecyclerViewAdapter(Context context, int count) {
        this.context = context;
        this.count = count;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new MyViewHolder(ViewUtil.inflate(LayoutInflater.from(context), parent, R.layout.my_recyclerView));
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        MyGridViewAdapter myGridViewAdapter = new MyGridViewAdapter(position);
        holder.gridView.setAdapter(myGridViewAdapter);
    }

    @Override
    public int getItemCount() {
        return count;
    }

    static class MyViewHolder extends RecyclerView.ViewHolder {

        private GridView gridView;

        MyViewHolder(View itemView) {
            super(itemView);
            gridView = itemView.findViewById(R.id.grid);
        }
    }
</code>```

答:
I think you should use PagerSnapHelper</p>

```<code>val snapHelper = PagerSnapHelper()
snapHelper.attachToRecyclerView(recyclerView)
</code>```

Body:
I have horizontal RecyclerView which has GridView. When I scroll RecyclerView, 2 elements appear at the same time. I just want to show the item at the current position.

Activity:

recyclerView = findViewById(R.id.recyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false);
recyclerView.setHasFixedSize(false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(new MyRecyclerViewAdapter(this, getTotalCount()));

My adapter:

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.MyViewHolder> {

    private int count;
    private Context context;

    public MyRecyclerViewAdapter(Context context, int count) {
        this.context = context;
        this.count = count;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new MyViewHolder(ViewUtil.inflate(LayoutInflater.from(context), parent, R.layout.my_recyclerView));
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        MyGridViewAdapter myGridViewAdapter = new MyGridViewAdapter(position);
        holder.gridView.setAdapter(myGridViewAdapter);
    }

    @Override
    public int getItemCount() {
        return count;
    }

    static class MyViewHolder extends RecyclerView.ViewHolder {

        private GridView gridView;

        MyViewHolder(View itemView) {
            super(itemView);
            gridView = itemView.findViewById(R.id.grid);
        }
    }

Body:
I think you should use PagerSnapHelper

val snapHelper = PagerSnapHelper()
snapHelper.attachToRecyclerView(recyclerView)


问:
pyspark operations not scaling up
I have a code in a notebook that works fine but failed however on bigger data with endless computation and a java.lang.OutOfMemoryError: Java heap space.

The process is as follows:

mocking pyspark data

I start with a dataframe with 3 columns namely (User, Time, and Item) as mocked in the code below:

    from pyspark.sql.types import *
    from pyspark.context import SparkContext
    from pyspark.sql.session import SparkSession
    import pandas as pd
    sc = SparkContext.getOrCreate()
    spark = SparkSession(sc)

    df_schema = StructType([ StructField("User", StringType(), True)\
                       ,StructField("Time", IntegerType(), True)\
                       ,StructField("Item", StringType(), True)])
    pddf = pd.DataFrame([["u1",1,"A"],
                    ["u1",1,"A"],
                    ["u1",2,"A"],
                    ["u1",3,"B"],
                    ["u1",3,"C"],
                    ["u1",4,"B"],
                    ["u2",1,"D"],
                    ["u2",2,"D"],
                    ["u2",2,"A"],
                    ["u2",2,"F"],
                    ["u2",3,"D"],
                    ["u2",3,"A"],],columns=["User", "Time", "Item"])

    df = spark.createDataFrame(pddf,schema=df_schema)
    df.show()
```

<p>which gives</p>

```+----+----+----+
|User|Time|Item|
+----+----+----+
|  u1|   1|   A|
|  u1|   1|   A|
|  u1|   2|   A|
|  u1|   3|   B|
|  u1|   3|   C|
|  u1|   4|   B|
|  u2|   1|   D|
|  u2|   2|   D|
|  u2|   2|   A|
|  u2|   2|   F|
|  u2|   3|   D|
|  u2|   3|   A|
+----+----+----+
```

<h3>intermediate step</h3>

<p>Then I compute the topn most common items for each user and create a dataframe with new column <em>uc</em> (uc for uncommon) which is set to 0 if item is <em>in topn list</em> or 1 otherwise.</p>

<pre class="lang-py prettyprint-override"><code>    import pyspark.sql.functions as F
    from pyspark.sql import Window
    ArrayOfTupleType = ArrayType(StructType([
        StructField("itemId", StringType(), False),
        StructField("count", IntegerType(), False)
    ]))

    @F.udf(returnType=ArrayOfTupleType)
    def most_common(x, topn=2):
        from collections import Counter
        c = Counter(x)
        mc = c.most_common(topn)
        return mc
    topn=2
    w0 = Window.partitionBy("User")
    dfd = (df.withColumn("Item_freq", most_common(F.collect_list("Item").over(w0), F.lit(topn)))
             .select("User", "Time" , "Item" , "Item_freq")
             .withColumn("mcs", F.col("Item_freq.itemId"))
             .withColumn("uc", F.when(F.expr("array_contains(mcs, Item)"), 0).otherwise(1)).cache())

    dfd.select("User", "Time", "Item" , "mcs" , "uc").show()
</code>```

which gives the interemediate dataframe below

```<code>+----+----+----+------+---+
|User|Time|Item|mcs   |uc |
+----+----+----+------+---+
|u1  |1   |A   |[A, B]|0  |
|u1  |1   |A   |[A, B]|0  |
|u1  |2   |A   |[A, B]|0  |
|u1  |3   |B   |[A, B]|0  |
|u1  |3   |C   |[A, B]|1  |
|u1  |4   |B   |[A, B]|0  |
|u2  |1   |D   |[D, A]|0  |
|u2  |2   |D   |[D, A]|0  |
|u2  |2   |A   |[D, A]|0  |
|u2  |2   |F   |[D, A]|1  |
|u2  |3   |D   |[D, A]|0  |
|u2  |3   |A   |[D, A]|0  |
+----+----+----+------+---+
</code>```

aggregating step

Then I finally group by user and time which is the operation that failed on real data:

    uncommon = dfd.groupBy("User", "Time").agg(F.sum(F.col("uc")).alias("UncommonItem"))
    uncommon.orderBy("User", "Time", ascending=True).show()
```

<p>which gives the expected results on the dummy data </p>

```+----+----+------------+
|User|Time|UncommonItem|
+----+----+------------+
|u1  |1   |0           |
|u1  |2   |0           |
|u1  |3   |1           |
|u1  |4   |0           |
|u2  |1   |0           |
|u2  |2   |1           |
|u2  |3   |0           |
+----+----+------------+
```

but it failed with a java.lang.OutOfMemoryError: Java heap space on real data.

Increasing the spark.driver.memory from 6G to 60G make only the crash comming after a much longer time untill it fills the 60G. My real data has 1907505 input samples

I am not very experienced with pyspark, and I am not sure where the problem comes from. Many other groupby/agg operation elsewere are fast and do not fail on the same type of data. Therefore I am suspecting that the issue comes from the way i made my dataframe dfd in the intermediate step above.

Any idea on how to optimize the code?

答:
If you are okay to change the approach , you can give the below a shot:

```<code>import pyspark.sql.functions as F

topn=2
w = Window.partitionBy('User','Item')
df1 = df.withColumn("Counts",F.count('Item').over(w))

w1 = Window.partitionBy(df1["User"]).orderBy(df1['Counts'].desc())

(df1.withColumn("dummy",F.when(F.dense_rank().over(w1)<=topn,0).otherwise(1))
.groupBy('User','Time').agg(F.max("dummy").alias('UncommonItem'))).show()
</code>```

```<code>+----+----+------------+
|User|Time|UncommonItem|
+----+----+------------+
|  u1|   1|           0|
|  u1|   2|           0|
|  u1|   3|           1|
|  u1|   4|           0|
|  u2|   1|           0|
|  u2|   2|           1|
|  u2|   3|           0|
+----+----+------------+
</code>```

Steps followed in the answer:

get Count over a window of User and Item

get dense_rank over User and the Count returned in step1

Wherever rank is within 2 (topn) return 1 else 0 and named it dummy

group on User and time and get max of the dummy

Title: pyspark operations not scaling up

Body:
I have a code in a notebook that works fine but failed however on bigger data with endless computation and a java.lang.OutOfMemoryError: Java heap space.

The process is as follows:

mocking pyspark data

I start with a dataframe with 3 columns namely (User, Time, and Item) as mocked in the code below:

    from pyspark.sql.types import *
    from pyspark.context import SparkContext
    from pyspark.sql.session import SparkSession
    import pandas as pd
    sc = SparkContext.getOrCreate()
    spark = SparkSession(sc)

    df_schema = StructType([ StructField("User", StringType(), True)\
                       ,StructField("Time", IntegerType(), True)\
                       ,StructField("Item", StringType(), True)])
    pddf = pd.DataFrame([["u1",1,"A"],
                    ["u1",1,"A"],
                    ["u1",2,"A"],
                    ["u1",3,"B"],
                    ["u1",3,"C"],
                    ["u1",4,"B"],
                    ["u2",1,"D"],
                    ["u2",2,"D"],
                    ["u2",2,"A"],
                    ["u2",2,"F"],
                    ["u2",3,"D"],
                    ["u2",3,"A"],],columns=["User", "Time", "Item"])

    df = spark.createDataFrame(pddf,schema=df_schema)
    df.show()

which gives

+----+----+----+
|User|Time|Item|
+----+----+----+
|  u1|   1|   A|
|  u1|   1|   A|
|  u1|   2|   A|
|  u1|   3|   B|
|  u1|   3|   C|
|  u1|   4|   B|
|  u2|   1|   D|
|  u2|   2|   D|
|  u2|   2|   A|
|  u2|   2|   F|
|  u2|   3|   D|
|  u2|   3|   A|
+----+----+----+

intermediate step

Then I compute the topn most common items for each user and create a dataframe with new column uc (uc for uncommon) which is set to 0 if item is in topn list or 1 otherwise.

    import pyspark.sql.functions as F
    from pyspark.sql import Window
    ArrayOfTupleType = ArrayType(StructType([
        StructField("itemId", StringType(), False),
        StructField("count", IntegerType(), False)
    ]))

    @F.udf(returnType=ArrayOfTupleType)
    def most_common(x, topn=2):
        from collections import Counter
        c = Counter(x)
        mc = c.most_common(topn)
        return mc
    topn=2
    w0 = Window.partitionBy("User")
    dfd = (df.withColumn("Item_freq", most_common(F.collect_list("Item").over(w0), F.lit(topn)))
             .select("User", "Time" , "Item" , "Item_freq")
             .withColumn("mcs", F.col("Item_freq.itemId"))
             .withColumn("uc", F.when(F.expr("array_contains(mcs, Item)"), 0).otherwise(1)).cache())

    dfd.select("User", "Time", "Item" , "mcs" , "uc").show()

which gives the interemediate dataframe below

+----+----+----+------+---+
|User|Time|Item|mcs   |uc |
+----+----+----+------+---+
|u1  |1   |A   |[A, B]|0  |
|u1  |1   |A   |[A, B]|0  |
|u1  |2   |A   |[A, B]|0  |
|u1  |3   |B   |[A, B]|0  |
|u1  |3   |C   |[A, B]|1  |
|u1  |4   |B   |[A, B]|0  |
|u2  |1   |D   |[D, A]|0  |
|u2  |2   |D   |[D, A]|0  |
|u2  |2   |A   |[D, A]|0  |
|u2  |2   |F   |[D, A]|1  |
|u2  |3   |D   |[D, A]|0  |
|u2  |3   |A   |[D, A]|0  |
+----+----+----+------+---+

aggregating step

Then I finally group by user and time which is the operation that failed on real data:

    uncommon = dfd.groupBy("User", "Time").agg(F.sum(F.col("uc")).alias("UncommonItem"))
    uncommon.orderBy("User", "Time", ascending=True).show()

which gives the expected results on the dummy data

+----+----+------------+
|User|Time|UncommonItem|
+----+----+------------+
|u1  |1   |0           |
|u1  |2   |0           |
|u1  |3   |1           |
|u1  |4   |0           |
|u2  |1   |0           |
|u2  |2   |1           |
|u2  |3   |0           |
+----+----+------------+

but it failed with a java.lang.OutOfMemoryError: Java heap space on real data.

Increasing the spark.driver.memory from 6G to 60G make only the crash comming after a much longer time untill it fills the 60G. My real data has 1907505 input samples

I am not very experienced with pyspark, and I am not sure where the problem comes from. Many other groupby/agg operation elsewere are fast and do not fail on the same type of data. Therefore I am suspecting that the issue comes from the way i made my dataframe dfd in the intermediate step above.

Any idea on how to optimize the code?

Body:
If you are okay to change the approach , you can give the below a shot:

import pyspark.sql.functions as F

topn=2
w = Window.partitionBy('User','Item')
df1 = df.withColumn("Counts",F.count('Item').over(w))

w1 = Window.partitionBy(df1["User"]).orderBy(df1['Counts'].desc())

(df1.withColumn("dummy",F.when(F.dense_rank().over(w1)<=topn,0).otherwise(1))
.groupBy('User','Time').agg(F.max("dummy").alias('UncommonItem'))).show()

+----+----+------------+
|User|Time|UncommonItem|
+----+----+------------+
|  u1|   1|           0|
|  u1|   2|           0|
|  u1|   3|           1|
|  u1|   4|           0|
|  u2|   1|           0|
|  u2|   2|           1|
|  u2|   3|           0|
+----+----+------------+

Steps followed in the answer:

get Count over a window of User and Item

get dense_rank over User and the Count returned in step1

Wherever rank is within 2 (topn) return 1 else 0 and named it dummy

group on User and time and get max of the dummy


问:
How to limit number of stacktrace lines from nested Exceptions
Lets have an Exception stacktrace with multiple 'caused by' sections:

```<code>my.Exception1: Bad luck
  at ...
Caused by: my.Exception2
  at ...
Caused by: my.Exception3
  at ...
Caused by: my.Exception4
  at ...
</code>```

each caused by section can span multiple lines. There is a JVM parameter

```<code>-XX:MaxJavaStackTraceDepth
</code>```

but this affects the stacktrace as a whole - it will cut everything below for example Exception3 (the inner most Exception will be out). I would like to keep every 'caused by' section, but limit each part to for example 20 lines. One possible solution I'm aware of is ThrowableRenderer from log4j. Is there something else? The goal is to preserve as much useful information from stacktraces as possible in an limited environment (maximum size in bytes for one log entry).

答:
ThrowableRenderer would be the way to go.  There is also the FilteredPatternLayout from openutils-log4j.

The heavy handed approach would be to get the throwable stacktrace, filter out frames, and reassign the filtered stacktrace for each throwable in the cause chain before you log the exception chain.  Which could be applied in a custom log filter class but that is bending the rules a bit because the filter shouldn't really modify the throwable chain. Those frames would be lost forever so there would be risk there.

Logback has support for filtering of stackframes. See also Filtering the Stack Trace From Hell for some ideas on what information is worth keeping.

Body:
Lets have an Exception stacktrace with multiple 'caused by' sections:

my.Exception1: Bad luck
  at ...
Caused by: my.Exception2
  at ...
Caused by: my.Exception3
  at ...
Caused by: my.Exception4
  at ...

each caused by section can span multiple lines. There is a JVM parameter

-XX:MaxJavaStackTraceDepth

but this affects the stacktrace as a whole - it will cut everything below for example Exception3 (the inner most Exception will be out). I would like to keep every 'caused by' section, but limit each part to for example 20 lines. One possible solution I'm aware of is ThrowableRenderer from log4j. Is there something else? The goal is to preserve as much useful information from stacktraces as possible in an limited environment (maximum size in bytes for one log entry).


问:
how to get the height and width of image in javascript?
I have a code where I am trying to get all images tag height and width.

```<code>var img = $('.data').find('img');
$.each($(img), function() {
console.log('first', this.height, $(this).height, $(this).height());
console.log('second', $(this).clientHeight, $(this).naturalHeight);
console.log('third',  $(this)[0].height,  $(this)[0].clientHeight,  $(this)[0].naturalHeight);
console.log($(this).attr('height'), $(this).prop('height'));                                                                                });
</code>```

Even i tried for img in loop.

tried the same with width , the result will be either 0 or undefined.
  tried same thing for width.

Can you tell me where I am doing wrong

答:
i was not getting the height and width of an image because the image load event happens very late in the load process

Finally I found an answer

```<code>var img = $('.data').find('img');
$.each(img, function() {
  $(this).bind('load', function() {
    console.log($(this).height);
  }
});
</code>```

it worked for both img and $(img)

Body:
I have a code where I am trying to get all images tag height and width.

var img = $('.data').find('img');
$.each($(img), function() {
console.log('first', this.height, $(this).height, $(this).height());
console.log('second', $(this).clientHeight, $(this).naturalHeight);
console.log('third',  $(this)[0].height,  $(this)[0].clientHeight,  $(this)[0].naturalHeight);
console.log($(this).attr('height'), $(this).prop('height'));                                                                                });

Even i tried for img in loop.

tried the same with width , the result will be either 0 or undefined.
  tried same thing for width.

Can you tell me where I am doing wrong

Body:
i was not getting the height and width of an image because the image load event happens very late in the load process

Finally I found an answer

var img = $('.data').find('img');
$.each(img, function() {
  $(this).bind('load', function() {
    console.log($(this).height);
  }
});

it worked for both img and $(img)


问:
How can I get the longest winning and losing streak of a player using Laravel Eloquent or Php?
I've currently got a table which stores some football (or soccer) results.

Each row in the table is for a particular player in that match with the outcome of the match.

outcome_id 1 is win, outcome_id 2 is lose, outcome_id 3 is draw.

I want to try and find out the longest winning streak for a player. For example, assume I am user_id 1 which has 10 rows in this table because I've played 10 matches. Order by match_date_time (so that the data is in the order of the matches played), how can I calculate the number of matches I've won in a row? So i can find the longest winning streak per player. I also want to do the same for longest losing streak too.

```<code>Schema::create('player_match_stats', function (Blueprint $table) {
        $table->id();
        $table->unsignedInteger('season_id')->nullable();
        $table->foreignId('match_id')->constrained('matches')->onDelete('cascade');
        $table->unsignedInteger('user_id');
        $table->unsignedInteger('outcome_id')->nullable();
        $table->unsignedInteger('team_name_id')->nullable();
        $table->dateTime('match_date_time')();
        $table->timestamps();
    });
</code>```

Ideally I'd want to be able to do this via Eloquent/PHP if possible.

Any help would be highly appreciated. Thanks.

答:
Here's a solution:

You get dates of the loses and drew of the player into array.

You make a for loop. You make query to count wins between i and i + 1 dates. You have to take note that at first run (i == 0) you need to get wins before that date, and at last run (i == length of array) you need to get wins after that date.

You make a variable to always store the highest number.

Hope this helps :)

Body:
I've currently got a table which stores some football (or soccer) results.

Each row in the table is for a particular player in that match with the outcome of the match.

outcome_id 1 is win, outcome_id 2 is lose, outcome_id 3 is draw.

I want to try and find out the longest winning streak for a player. For example, assume I am user_id 1 which has 10 rows in this table because I've played 10 matches. Order by match_date_time (so that the data is in the order of the matches played), how can I calculate the number of matches I've won in a row? So i can find the longest winning streak per player. I also want to do the same for longest losing streak too.

Schema::create('player_match_stats', function (Blueprint $table) {
        $table->id();
        $table->unsignedInteger('season_id')->nullable();
        $table->foreignId('match_id')->constrained('matches')->onDelete('cascade');
        $table->unsignedInteger('user_id');
        $table->unsignedInteger('outcome_id')->nullable();
        $table->unsignedInteger('team_name_id')->nullable();
        $table->dateTime('match_date_time')();
        $table->timestamps();
    });

Ideally I'd want to be able to do this via Eloquent/PHP if possible.

Any help would be highly appreciated. Thanks.


问:
How to Pass data between Screen when Icon is pressed
I am working on a project where When I Press Bookmark Icon The Image should pass to the Saved.dart Page. Below code Contain a Bookmark icon. when Ever I press that icon it should pass the image to saved.dart page but it should not push(Should no open Saved.dart page when pressed) to Saved.dart Page.

```<code>import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:image_downloader/image_downloader.dart';
import 'downloadingPage.dart';

class FullScreen extends StatefulWidget {
  String imgUrl;
  FullScreen({this.imgUrl});

  @override
  FullScreenState createState() => FullScreenState(imgUrl);
}

class FullScreenState extends State<FullScreen> {
  Color colour = Colors.black;
  Color colour2 = Colors.red;
  Color colour3 = Colors.black;
  bool isSaved = false;

  String imgUrl;
  FullScreenState(this.imgUrl);

  String message = "";
  String path = "";
  int _progress = 0;

  @override
  void initState() {
    super.initState();
    events = new StreamController<int>.broadcast();

    events.add(0);

    ImageDownloader.callback(onProgressUpdate: (String imageId, int progress) {
      setState(() {
        print("progress $progress");
        _progress = progress;
        events.add(progress);
        if (progress == 100) {
          Navigator.pop(context);
        }
      });
    });
  }

  @override
  void dispose() {
    events.close();
    super.dispose();
  }

  Future<void> _downloadImage(String url,
      {AndroidDestinationType destination, bool whenError = false}) async {
    String fileName;
    String path;
    try {
      String imageId;

      if (whenError) {
        imageId = await ImageDownloader.downloadImage(url).catchError((error) {
          if (error is PlatformException) {
            var path = "";
            if (error.code == "404") {
              print("Not Found Error.");
            } else if (error.code == "unsupported_file") {
              print("UnSupported FIle Error.");
              path = error.details["unsupported_file_path"];
            }
            setState(() {
              message = error.toString();
              path = path;
            });
          }

          print(error);
        }).timeout(Duration(seconds: 10), onTimeout: () {
          print("timeout");
        });
      } else {
        if (destination == null) {
          imageId = await ImageDownloader.downloadImage(url);
        } else {
          imageId = await ImageDownloader.downloadImage(
            url,
            destination: destination,
          );
        }
      }

      if (imageId == null) {
        print("imageId is null");
        return;
      }
      fileName = await ImageDownloader.findName(imageId);
      path = await ImageDownloader.findPath(imageId);
    } on PlatformException catch (error) {
      setState(() {
        message = error.message;
      });
      return;
    }

    if (!mounted) return;
    setState(() {
      message = 'Image Downloaded';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            RaisedButton(
              onPressed: () {
                events.add(0);
                _downloadImage(imgUrl);
                showDialog(
                  context: context,
                  builder: (_) => FunkyOverlay(
                    progress: _progress,
                    message: message,
                  ),
                );
              },
              child: Text("download"),
            ),
            IconButton(
                icon: Icon(
                  Icons.bookmark,
                  color: colour,
                ),
                onPressed: () {
                <-----when user press this icon the current image shold be passed to saved page----->
                })
          ],
        ),
      ),
    );
  }
}
</code>```

The following code is Saved.dart

```<code>import 'package:flutter/material.dart';

class Saved extends StatefulWidget {
  @override
  _SavedState createState() => _SavedState();
}

class _SavedState extends State<Saved> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body:Container(
        // here the images should be displayed
      )
    );
  }
}
</code>```

答:
You cannot pass anything to a Widget that is not initialized. That Widget technically doesn't even exist before you call it.

You will have to save the Image in a variable. And then pass it when you finally do navigate to that screen.

Body:
I am working on a project where When I Press Bookmark Icon The Image should pass to the Saved.dart Page. Below code Contain a Bookmark icon. when Ever I press that icon it should pass the image to saved.dart page but it should not push(Should no open Saved.dart page when pressed) to Saved.dart Page.

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:image_downloader/image_downloader.dart';
import 'downloadingPage.dart';

class FullScreen extends StatefulWidget {
  String imgUrl;
  FullScreen({this.imgUrl});

  @override
  FullScreenState createState() => FullScreenState(imgUrl);
}

class FullScreenState extends State<FullScreen> {
  Color colour = Colors.black;
  Color colour2 = Colors.red;
  Color colour3 = Colors.black;
  bool isSaved = false;

  String imgUrl;
  FullScreenState(this.imgUrl);

  String message = "";
  String path = "";
  int _progress = 0;

  @override
  void initState() {
    super.initState();
    events = new StreamController<int>.broadcast();

    events.add(0);

    ImageDownloader.callback(onProgressUpdate: (String imageId, int progress) {
      setState(() {
        print("progress $progress");
        _progress = progress;
        events.add(progress);
        if (progress == 100) {
          Navigator.pop(context);
        }
      });
    });
  }

  @override
  void dispose() {
    events.close();
    super.dispose();
  }

  Future<void> _downloadImage(String url,
      {AndroidDestinationType destination, bool whenError = false}) async {
    String fileName;
    String path;
    try {
      String imageId;

      if (whenError) {
        imageId = await ImageDownloader.downloadImage(url).catchError((error) {
          if (error is PlatformException) {
            var path = "";
            if (error.code == "404") {
              print("Not Found Error.");
            } else if (error.code == "unsupported_file") {
              print("UnSupported FIle Error.");
              path = error.details["unsupported_file_path"];
            }
            setState(() {
              message = error.toString();
              path = path;
            });
          }

          print(error);
        }).timeout(Duration(seconds: 10), onTimeout: () {
          print("timeout");
        });
      } else {
        if (destination == null) {
          imageId = await ImageDownloader.downloadImage(url);
        } else {
          imageId = await ImageDownloader.downloadImage(
            url,
            destination: destination,
          );
        }
      }

      if (imageId == null) {
        print("imageId is null");
        return;
      }
      fileName = await ImageDownloader.findName(imageId);
      path = await ImageDownloader.findPath(imageId);
    } on PlatformException catch (error) {
      setState(() {
        message = error.message;
      });
      return;
    }

    if (!mounted) return;
    setState(() {
      message = 'Image Downloaded';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            RaisedButton(
              onPressed: () {
                events.add(0);
                _downloadImage(imgUrl);
                showDialog(
                  context: context,
                  builder: (_) => FunkyOverlay(
                    progress: _progress,
                    message: message,
                  ),
                );
              },
              child: Text("download"),
            ),
            IconButton(
                icon: Icon(
                  Icons.bookmark,
                  color: colour,
                ),
                onPressed: () {
                <-----when user press this icon the current image shold be passed to saved page----->
                })
          ],
        ),
      ),
    );
  }
}

The following code is Saved.dart

import 'package:flutter/material.dart';

class Saved extends StatefulWidget {
  @override
  _SavedState createState() => _SavedState();
}

class _SavedState extends State<Saved> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body:Container(
        // here the images should be displayed
      )
    );
  }
}