问:
Ionic v5 React Ion-Slides: How to make a button to the next slide?
Ionic Slides by default rely on swiping the screen.

I am also hosting my Ionic app as a webapp on my site, so I want to let users press a button to advance to the next slide as well. ("Swiping" with a mouse is not intuitive.)

According to the documentation linked above, there is a slideNext method, but how do I use this?  I can't figure out how to call it in my code.

For example, what can I add to onClick of IonButton below?  (Code based on the example react conference app)

```<code>const Tutorial: React.FC<TutorialProps> = ({ history, setHasSeenTutorial, setMenuEnabled }) => {
  const [showSkip, setShowSkip] = useState(true);
  const slideRef = useRef<HTMLIonSlidesElement>(null);

  const handleSlideChangeStart = () => {
    slideRef.current!.isEnd().then(isEnd => setShowSkip(!isEnd));
  };

  return (
    <IonPage id="tutorial-page">
      <IonContent fullscreen>

        <IonSlides ref={slideRef} onIonSlideWillChange={handleSlideChangeStart} pager={false}>
          <IonSlide>
            <img src="assets/img/ica-slidebox-img-1.png" alt="" className="slide-image" />
            <h2 className="slide-title">
              Welcome to <b>ICA</b>
            </h2>
            <p>
              The <b>ionic conference app</b> is a practical preview of the ionic framework in action, and a demonstration of proper code use.
            </p>
            <IonButton onClick={// What do I put here to go to the next slide?} />
          </IonSlide>

          <IonSlide>
            <img src="assets/img/ica-slidebox-img-4.png" alt="" className="slide-image" />
            <h2 className="slide-title">Ready to Play?</h2>
            <IonButton fill="clear" onClick={startApp}>
              Continue
              <IonIcon slot="end" icon={arrowForward} />
            </IonButton>
          </IonSlide>
        </IonSlides>
      </IonContent>
    </IonPage>
  );
};
</code>```

答:
This works in ionic 5 for sure.
Please try it

const SlideShow: React.FC = () => {
const slideOpts = {
initialSlide: 0,
speed: 400
};
const mySlides = useRef(null);

const onBtnClicked = async (str:any) => {
const swiper = mySlides.current?.getSwiper();

swiper?.then((e)=>{
if(str=='next'){
e.slideNext()
}else{
e.slidePrev()
}

```<code>    })
  };
const goToSlide1 = async () => {
    const swiper = mySlides.current?.getSwiper();
    swiper?.then((e)=>{
        e.slideTo(0)
    })
  };
const goToSlide2 = async () => {
    const swiper = mySlides.current?.getSwiper();
    swiper?.then((e)=>{
        e.slideTo(1)
    })
  };

const goToSlide3 = async () => {
    const swiper = mySlides.current?.getSwiper();
    swiper?.then((e)=>{
        e.slideTo(2)
    })
  };
return (
    <IonPage>
        <IonContent className='overflow-hidden'>
            <IonCard className='card-size'>
            <IonSlides pager={false} options={slideOpts} ref={mySlides}
            onIonSlideDidChange={(e)=>{
                // console.log('e value',e)
                // onBtnClicked()
                }}>
                <IonSlide>
                    <IonCardContent className='pad-0'>
                    <IonGrid className='pad-0'>
                        <img src={ require(`../../images/backgound.png`).default} className="img-slide" height={71} width={71} alt="" />
                    </IonGrid>
                    {/* <br/> */}
                    <IonGrid>
                        {/* <br/> */}
                        <div className='ion-text-align-center'>
                        <span className="dot active" onClick={goToSlide1}></span>
                        <span className="dot" onClick={goToSlide2}></span>
                        <span className="dot" onClick={goToSlide3}></span>
                        </div>
                    </IonGrid>
                    <h1>Slide 1</h1>
                    <button onClick={()=>onBtnClicked('next')}>Next</button>
                    </IonCardContent>
                </IonSlide>
                <IonSlide>
                    <IonCardContent className='pad-0'>
                    <IonGrid className='pad-0'>
                        <img src={ require(`../../images/backgound.png`).default} className="img-slide" height={71} width={71} alt="" />
                    </IonGrid>
                    {/* <br/> */}
                    <IonGrid>
                        {/* <br/> */}
                        <div className='ion-text-align-center'>
                        <span className="dot" onClick={goToSlide1}></span>
                        <span className="dot active" onClick={goToSlide2}></span>
                        <span className="dot" onClick={goToSlide3}></span>
                        </div>
                    </IonGrid>
                    <h1>Slide 2</h1>
                    <button onClick={()=>onBtnClicked('prev')}>Prev</button>--<button onClick={()=>onBtnClicked('next')}>Next</button>
                    </IonCardContent>

                </IonSlide>
                <IonSlide>
                <IonCardContent className='pad-0'>
                    <IonGrid className='pad-0'>
                        <img src={ require(`../../images/backgound.png`).default} className="img-slide" height={71} width={71} alt="" />
                    </IonGrid>
                    {/* <br/> */}
                    <IonGrid>
                        {/* <br/> */}
                        <div className='ion-text-align-center'>
                        <span className="dot" onClick={goToSlide1}></span>
                        <span className="dot" onClick={goToSlide2}></span>
                        <span className="dot active" onClick={goToSlide3}></span>
                        </div>
                    </IonGrid>
                    <h1>Slide 3</h1>
                    <button onClick={()=>onBtnClicked('prev')}>Prev</button>
                    </IonCardContent>

                </IonSlide>
            </IonSlides>

            </IonCard>

        </IonContent>
    </IonPage>
);
</code>```

};

Body:
Ionic Slides by default rely on swiping the screen.

I am also hosting my Ionic app as a webapp on my site, so I want to let users press a button to advance to the next slide as well. ("Swiping" with a mouse is not intuitive.)

According to the documentation linked above, there is a slideNext method, but how do I use this?  I can't figure out how to call it in my code.

For example, what can I add to onClick of IonButton below?  (Code based on the example react conference app)

const Tutorial: React.FC<TutorialProps> = ({ history, setHasSeenTutorial, setMenuEnabled }) => {
  const [showSkip, setShowSkip] = useState(true);
  const slideRef = useRef<HTMLIonSlidesElement>(null);

  const handleSlideChangeStart = () => {
    slideRef.current!.isEnd().then(isEnd => setShowSkip(!isEnd));
  };

  return (
    <IonPage id="tutorial-page">
      <IonContent fullscreen>

        <IonSlides ref={slideRef} onIonSlideWillChange={handleSlideChangeStart} pager={false}>
          <IonSlide>

              Welcome to ICA

              The ionic conference app is a practical preview of the ionic framework in action, and a demonstration of proper code use.

            <IonButton onClick={// What do I put here to go to the next slide?} />
          </IonSlide>

          <IonSlide>

Ready to Play?

            <IonButton fill="clear" onClick={startApp}>
              Continue
              <IonIcon slot="end" icon={arrowForward} />
            </IonButton>
          </IonSlide>
        </IonSlides>
      </IonContent>
    </IonPage>
  );
};

Body:
This works in ionic 5 for sure.
Please try it

const SlideShow: React.FC = () => {
const slideOpts = {
initialSlide: 0,
speed: 400
};
const mySlides = useRef(null);

const onBtnClicked = async (str:any) => {
const swiper = mySlides.current?.getSwiper();

swiper?.then((e)=>{
if(str=='next'){
e.slideNext()
}else{
e.slidePrev()
}

    })
  };
const goToSlide1 = async () => {
    const swiper = mySlides.current?.getSwiper();
    swiper?.then((e)=>{
        e.slideTo(0)
    })
  };
const goToSlide2 = async () => {
    const swiper = mySlides.current?.getSwiper();
    swiper?.then((e)=>{
        e.slideTo(1)
    })
  };

const goToSlide3 = async () => {
    const swiper = mySlides.current?.getSwiper();
    swiper?.then((e)=>{
        e.slideTo(2)
    })
  };
return (
    <IonPage>
        <IonContent className='overflow-hidden'>
            <IonCard className='card-size'>
            <IonSlides pager={false} options={slideOpts} ref={mySlides}
            onIonSlideDidChange={(e)=>{
                // console.log('e value',e)
                // onBtnClicked()
                }}>
                <IonSlide>
                    <IonCardContent className='pad-0'>
                    <IonGrid className='pad-0'>
                        <img src={ require(`../../images/backgound.png`).default} className="img-slide" height={71} width={71} alt="" />
                    </IonGrid>
                    {/* <br/> */}
                    <IonGrid>
                        {/* <br/> */}
                        <div className='ion-text-align-center'>
                        <span className="dot active" onClick={goToSlide1}></span>
                        <span className="dot" onClick={goToSlide2}></span>
                        <span className="dot" onClick={goToSlide3}></span>
                        </div>
                    </IonGrid>
                    <h1>Slide 1</h1>
                    <button onClick={()=>onBtnClicked('next')}>Next</button>
                    </IonCardContent>
                </IonSlide>
                <IonSlide>
                    <IonCardContent className='pad-0'>
                    <IonGrid className='pad-0'>
                        <img src={ require(`../../images/backgound.png`).default} className="img-slide" height={71} width={71} alt="" />
                    </IonGrid>
                    {/* <br/> */}
                    <IonGrid>
                        {/* <br/> */}
                        <div className='ion-text-align-center'>
                        <span className="dot" onClick={goToSlide1}></span>
                        <span className="dot active" onClick={goToSlide2}></span>
                        <span className="dot" onClick={goToSlide3}></span>
                        </div>
                    </IonGrid>
                    <h1>Slide 2</h1>
                    <button onClick={()=>onBtnClicked('prev')}>Prev</button>--<button onClick={()=>onBtnClicked('next')}>Next</button>
                    </IonCardContent>

                </IonSlide>
                <IonSlide>
                <IonCardContent className='pad-0'>
                    <IonGrid className='pad-0'>
                        <img src={ require(`../../images/backgound.png`).default} className="img-slide" height={71} width={71} alt="" />
                    </IonGrid>
                    {/* <br/> */}
                    <IonGrid>
                        {/* <br/> */}
                        <div className='ion-text-align-center'>
                        <span className="dot" onClick={goToSlide1}></span>
                        <span className="dot" onClick={goToSlide2}></span>
                        <span className="dot active" onClick={goToSlide3}></span>
                        </div>
                    </IonGrid>
                    <h1>Slide 3</h1>
                    <button onClick={()=>onBtnClicked('prev')}>Prev</button>
                    </IonCardContent>

                </IonSlide>
            </IonSlides>

            </IonCard>

        </IonContent>
    </IonPage>
);

};


来源: stackexchange

问:
In Aspnet.Core, can we change port number?
I work on aspnet core web api project. I will publish this project to remote server. When Kestrel is running, default port is 5000 or anythink like this.

I want to change this port to 80 or 8080. Can I do that?

When I try to change from launchSettings, I get this error:

```<code>System.IO.IOException: 'Failed to bind to address http://localhost:80.'
</code>```

答:
Your problem may be because you already have another web server running on your system (e.g. IIS) that is already binding to port 80.

You can check with this powershell command:

Get-Process -Id (Get-NetTCPConnection -LocalPort 80).OwningProcess

This command will show you what process is listening on port 80. If nothing is listening, it will return an error.

ContentLicense: CC BY-SA 4.0

Body:
I work on aspnet core web api project. I will publish this project to remote server. When Kestrel is running, default port is 5000 or anythink like this.

I want to change this port to 80 or 8080. Can I do that?

When I try to change from launchSettings, I get this error:

System.IO.IOException: 'Failed to bind to address http://localhost:80.'


问:
Split a String into an array in Swift?
Say I have a string here:

```<code>var fullName: String = "First Last"
</code>```

I want to split the string base on white space and assign the values to their respective variables

```<code>var fullNameArr = // something like: fullName.explode(" ")

var firstName: String = fullNameArr[0]
var lastName: String? = fullnameArr[1]
</code>```

Also, sometimes users might not have a last name.

答:
The simplest solution is

```<code>let fullName = "First Last"

let components = fullName.components(separatedBy: .whitespacesAndNewlines).compactMap { $0.isEmpty ? nil : $0 }
</code>```

This will handled multiple white spaces in a row of different types (white space, tabs, newlines etc) and only returns a two element array, you can change the CharacterSet to include more character you like, if you want to get cleaver you can use Regular Expression Decoder, this lets you write regular expression that can be used to decoded string directly into your own class/struct that implement the Decoding protocol. For something like this is over kill, but if you are using it as an example for more complicate string it may make more sense.

Title: Split a String into an array in Swift?

Body:
Say I have a string here:

var fullName: String = "First Last"

I want to split the string base on white space and assign the values to their respective variables

var fullNameArr = // something like: fullName.explode(" ")

var firstName: String = fullNameArr[0]
var lastName: String? = fullnameArr[1]

Also, sometimes users might not have a last name.

Body:
The simplest solution is

let fullName = "First Last"

let components = fullName.components(separatedBy: .whitespacesAndNewlines).compactMap { $0.isEmpty ? nil : $0 }

This will handled multiple white spaces in a row of different types (white space, tabs, newlines etc) and only returns a two element array, you can change the CharacterSet to include more character you like, if you want to get cleaver you can use Regular Expression Decoder, this lets you write regular expression that can be used to decoded string directly into your own class/struct that implement the Decoding protocol. For something like this is over kill, but if you are using it as an example for more complicate string it may make more sense.


问:
request.GET.get(' ') returns None
I have the following URL: http://127.0.0.1:8000/application_form/Network%20Adminstrator/
The URL is generated with:  path('application_form/<str:job_title>/', views.ApplicationForm.as_view(), name='application_form')

I keep on trying get_data = self.request.GET.get('job_title') and am expecting to get Network Adminstrator but instead it returns None

My urls.py:

```<code>urlpatterns = [
path('application_form/<str:job_title>/', views.ApplicationForm.as_view(), name='application_form'),
</code>```

]

views.py:

```<code>class ApplicationForm(CreateView):
    model = Requirements
    form_class = ApplicationForm
    template_name = 'requirements/job_specs.html'

    # Passes the request object to forms
    def get_form_kwargs(self):
        kwargs = super(ApplicationForm, self).get_form_kwargs()
        kwargs['request'] = self.request
        return kwargs
</code>```

forms.py:

```<code>class ApplicationForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request')
        super(ApplicationForm, self).__init__(*args, **kwargs)
        get_data = self.request.GET.get('job_title')
        print(get_data)
        dic = {'job_title__job_title': get_data}
        self.fields['qualifications'].queryset = Requirements.objects.get(**dic)

    class Meta:
        model = Applicants
        fields = ['email', 'qualifications']

    email = forms.EmailField(label='', max_length=100, required=True, widget=forms.TextInput(
        attrs={'class': 'form-group form-control input-lg ', 'placeholder': 'Email'}), )
    qualifications = forms.ModelMultipleChoiceField(queryset=None, widget=forms.CheckboxSelectMultiple)
</code>```

Any thoughts or ideas? I am still a bit new to programing in Django and I would really appreciate your time and knowledge.

答: URL kwargs are not in request, but in class itself. Try self.kwargs.get('job_title'). If it's not in your ApplicationForm, you can pass them from get_form_kwargs method same as you passed Request

Title: request.GET.get(' ') returns None

Body:
I have the following URL: http://127.0.0.1:8000/application_form/Network%20Adminstrator/
The URL is generated with:  path('application_form/<str:job_title>/', views.ApplicationForm.as_view(), name='application_form')

I keep on trying get_data = self.request.GET.get('job_title') and am expecting to get Network Adminstrator but instead it returns None

My urls.py:

urlpatterns = [
path('application_form/<str:job_title>/', views.ApplicationForm.as_view(), name='application_form'),

]

views.py:

class ApplicationForm(CreateView):
    model = Requirements
    form_class = ApplicationForm
    template_name = 'requirements/job_specs.html'

    # Passes the request object to forms
    def get_form_kwargs(self):
        kwargs = super(ApplicationForm, self).get_form_kwargs()
        kwargs['request'] = self.request
        return kwargs

forms.py:

class ApplicationForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request')
        super(ApplicationForm, self).__init__(*args, **kwargs)
        get_data = self.request.GET.get('job_title')
        print(get_data)
        dic = {'job_title__job_title': get_data}
        self.fields['qualifications'].queryset = Requirements.objects.get(**dic)

    class Meta:
        model = Applicants
        fields = ['email', 'qualifications']

    email = forms.EmailField(label='', max_length=100, required=True, widget=forms.TextInput(
        attrs={'class': 'form-group form-control input-lg ', 'placeholder': 'Email'}), )
    qualifications = forms.ModelMultipleChoiceField(queryset=None, widget=forms.CheckboxSelectMultiple)

Any thoughts or ideas? I am still a bit new to programing in Django and I would really appreciate your time and knowledge.


问:
Internal Server Error on Terraform provisioned API Gateway Trigger
I'm using Terraform to allocate a Lambda function that's triggered by a request to an API Gateway on AWS. Here's my .tf file:

```<code>dsf
</code>```

This correctly sets up the Lambda function, but something is off with the API Gateway. When I curl with the output URL (https://cqsso4fw67.execute-api.us-east-1.amazonaws.com), it gives me the following:

```<code>curl https://cqsso4fw67.execute-api.us-east-1.amazonaws.com/
{"message":"Internal Server Error"}%
</code>```

If I manually remove this API Gateway and create a new one from the AWS Console within the Lambda function and run curl again, I get "SUCCESS!" (which is what my Lambda should do).

```<code>smf
</code>```

Any ideas how I can fix the .tf file to correctly setup the API Gateway trigger?

Here are the differences between the one created in AWS and the one provisioned in Terraform. Terraform one is at the top.

答:
If anyone comes across this issue, I managed to fix it by greatly simplifying things. I switched out all the API Gateway clauses in the Terraform file with just:

```<code>resource "aws_apigatewayv2_api" "apigw-terraform" {
    name          = "terraform-api"
    protocol_type = "HTTP"
    target        = aws_lambda_function.w-scan-terraform.arn
}
</code>```

The tutorial I was following had implemented something more complex than what I needed.

Body:
I'm using Terraform to allocate a Lambda function that's triggered by a request to an API Gateway on AWS. Here's my .tf file:

dsf

This correctly sets up the Lambda function, but something is off with the API Gateway. When I curl with the output URL (https://cqsso4fw67.execute-api.us-east-1.amazonaws.com), it gives me the following:

curl https://cqsso4fw67.execute-api.us-east-1.amazonaws.com/
{"message":"Internal Server Error"}%

If I manually remove this API Gateway and create a new one from the AWS Console within the Lambda function and run curl again, I get "SUCCESS!" (which is what my Lambda should do).

smf

Any ideas how I can fix the .tf file to correctly setup the API Gateway trigger?

Here are the differences between the one created in AWS and the one provisioned in Terraform. Terraform one is at the top.

Body:
If anyone comes across this issue, I managed to fix it by greatly simplifying things. I switched out all the API Gateway clauses in the Terraform file with just:

resource "aws_apigatewayv2_api" "apigw-terraform" {
    name          = "terraform-api"
    protocol_type = "HTTP"
    target        = aws_lambda_function.w-scan-terraform.arn
}

The tutorial I was following had implemented something more complex than what I needed.


问:
What is Shadow Memory?
What is Shadow Memory? Can SO briefly shed light on how memory profiling tools use it?</p>

答: Shadow Memory is RAM that lives at the same address as ROM.  It's used because it's faster and also because it can be modified (e.g. setting breakpoints).</p>

OwnerDisplayName: Prabhu. S

ContentLicense: CC BY-SA 2.5

Title: What is Shadow Memory?

OwnerDisplayName: MarkusQ


问:
Scrapy CrawlerProcess does not override settings
I'm trying to run multiple scrapy crawlers with CrawlerProcess with few custom settings.

```<code>settings = get_project_settings()
settings['TELNETCONSOLE_ENABLED'] = False
settings['CONCURRENT_REQUESTS'] = 2
settings['CONCURRENT_REQUESTS_PER_DOMAIN'] = 1
settings['DOWNLOAD_DELAY'] = 5
settings['LOG_LEVEL'] = 'DEBUG'

process = CrawlerProcess(settings)
process.crawl(QSpider)
process.start()
</code>```

It works well. I can see settings getting overriden.

```<code>2022-02-09 12:23:39 [scrapy.utils.log] INFO: Scrapy 2.5.1 started (bot: scrapybot)
2022-02-09 12:23:39 [scrapy.utils.log] INFO: Versions: lxml 4.7.1.0, libxml2 2.9.12, cssselect 1.1.0, parsel 1.6.0, w3lib 1.22.0, Twisted 22.1.0, Python 3.9.0 (tags/v3.9.0:9cf6752, Oct  5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)], pyOpenSSL 22.0.0 (OpenSSL 1.1.1m  14 Dec 2021), cryptography 36.0.1, Platform Windows-10-10.0.19041-SP0
2022-02-09 12:23:39 [scrapy.utils.log] DEBUG: Using reactor: twisted.internet.selectreactor.SelectReactor
2022-02-09 12:23:39 [scrapy.crawler] INFO: Overridden settings:
{'CONCURRENT_REQUESTS': 2,
 'CONCURRENT_REQUESTS_PER_DOMAIN': 1,
 'DOWNLOAD_DELAY': 5,
 'TELNETCONSOLE_ENABLED': False}
....
2022-02-09 12:23:46 [scrapy.core.engine] INFO: Spider closed (shutdown)
</code>```

However when I pass a Crawler instance to the crawl method like

```<code>..... # same settings
process = CrawlerProcess(settings)
process.crawl(Crawler(QSpider))
process.start()
</code>```

Nothing gets overridden now. It does not even honor DOWNLOAD_DELAY.

```<code>2022-02-09 12:32:11 [scrapy.utils.log] INFO: Scrapy 2.5.1 started (bot: scrapybot)
2022-02-09 12:32:11 [scrapy.utils.log] INFO: Versions: lxml 4.7.1.0, libxml2 2.9.12, cssselect 1.1.0, parsel 1.6.0, w3lib 1.22.0, Twisted 22.1.0, Python 3.9.0 (tags/v3.9.0:9cf6752, Oct  5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)], pyOpenSSL 22.0.0 (OpenSSL 1.1.1m  14 Dec 2021), cryptography 36.0.1, Platform Windows-10-10.0.19041-SP0
2022-02-09 12:32:11 [scrapy.utils.log] DEBUG: Using reactor: twisted.internet.selectreactor.SelectReactor
2022-02-09 12:32:11 [scrapy.crawler] INFO: Overridden settings:
{}
2022-02-09 12:32:11 [scrapy.extensions.telnet] INFO: Telnet Password:
.....
2022-02-09 12:32:17 [scrapy.core.engine] INFO: Spider closed (finished)
</code>```

Note: Running Scrapy 2.5.1 on Python 3.9.0.

答:
So in order to override some settings, one way would be overriding/setting custom_settings, the spider's static variable, in our script.

so I imported the spider's class and then override the custom_setting:

```<code>from testspiders.spiders.followall import FollowAllSpider
FollowAllSpider.custom_settings={'RETRY_TIMES':10}
</code>```

So this is the whole script:

```<code>from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings
from testspiders.spiders.followall import FollowAllSpider

FollowAllSpider.custom_settings={'RETRY_TIMES':10}
process = CrawlerProcess(get_project_settings())

# 'followall' is the name of one of the spiders of the project.
process.crawl('testspider', domain='scrapinghub.com')
process.start() # the script will block here until the crawling is finished
</code>```

Body:
I'm trying to run multiple scrapy crawlers with CrawlerProcess with few custom settings.

settings = get_project_settings()
settings['TELNETCONSOLE_ENABLED'] = False
settings['CONCURRENT_REQUESTS'] = 2
settings['CONCURRENT_REQUESTS_PER_DOMAIN'] = 1
settings['DOWNLOAD_DELAY'] = 5
settings['LOG_LEVEL'] = 'DEBUG'

process = CrawlerProcess(settings)
process.crawl(QSpider)
process.start()

It works well. I can see settings getting overriden.

2022-02-09 12:23:39 [scrapy.utils.log] INFO: Scrapy 2.5.1 started (bot: scrapybot)
2022-02-09 12:23:39 [scrapy.utils.log] INFO: Versions: lxml 4.7.1.0, libxml2 2.9.12, cssselect 1.1.0, parsel 1.6.0, w3lib 1.22.0, Twisted 22.1.0, Python 3.9.0 (tags/v3.9.0:9cf6752, Oct  5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)], pyOpenSSL 22.0.0 (OpenSSL 1.1.1m  14 Dec 2021), cryptography 36.0.1, Platform Windows-10-10.0.19041-SP0
2022-02-09 12:23:39 [scrapy.utils.log] DEBUG: Using reactor: twisted.internet.selectreactor.SelectReactor
2022-02-09 12:23:39 [scrapy.crawler] INFO: Overridden settings:
{'CONCURRENT_REQUESTS': 2,
 'CONCURRENT_REQUESTS_PER_DOMAIN': 1,
 'DOWNLOAD_DELAY': 5,
 'TELNETCONSOLE_ENABLED': False}
....
2022-02-09 12:23:46 [scrapy.core.engine] INFO: Spider closed (shutdown)

However when I pass a Crawler instance to the crawl method like

..... # same settings
process = CrawlerProcess(settings)
process.crawl(Crawler(QSpider))
process.start()

Nothing gets overridden now. It does not even honor DOWNLOAD_DELAY.

2022-02-09 12:32:11 [scrapy.utils.log] INFO: Scrapy 2.5.1 started (bot: scrapybot)
2022-02-09 12:32:11 [scrapy.utils.log] INFO: Versions: lxml 4.7.1.0, libxml2 2.9.12, cssselect 1.1.0, parsel 1.6.0, w3lib 1.22.0, Twisted 22.1.0, Python 3.9.0 (tags/v3.9.0:9cf6752, Oct  5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)], pyOpenSSL 22.0.0 (OpenSSL 1.1.1m  14 Dec 2021), cryptography 36.0.1, Platform Windows-10-10.0.19041-SP0
2022-02-09 12:32:11 [scrapy.utils.log] DEBUG: Using reactor: twisted.internet.selectreactor.SelectReactor
2022-02-09 12:32:11 [scrapy.crawler] INFO: Overridden settings:
{}
2022-02-09 12:32:11 [scrapy.extensions.telnet] INFO: Telnet Password:
.....
2022-02-09 12:32:17 [scrapy.core.engine] INFO: Spider closed (finished)

Note: Running Scrapy 2.5.1 on Python 3.9.0.

Body:
So in order to override some settings, one way would be overriding/setting custom_settings, the spider's static variable, in our script.

so I imported the spider's class and then override the custom_setting:

from testspiders.spiders.followall import FollowAllSpider
FollowAllSpider.custom_settings={'RETRY_TIMES':10}

So this is the whole script:

from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings
from testspiders.spiders.followall import FollowAllSpider

FollowAllSpider.custom_settings={'RETRY_TIMES':10}
process = CrawlerProcess(get_project_settings())

# 'followall' is the name of one of the spiders of the project.
process.crawl('testspider', domain='scrapinghub.com')
process.start() # the script will block here until the crawling is finished


问:
How implement Live tracking in my flutter app?
I would like implement a live tracking in the background—even if  app wasn’t the currently active app?</p>

答:
Check this awesome blog on how to fetch location when the app is in the background.

https://medium.com/@pierre.sabot/how-to-fetch-user-location-in-background-with-flutter-e3494021bdf5


问:
How do i align a background color for a text to an image?
im quite new to coding... and im making a portfolio that contains all the projects ive currently done... and i want to align the text background color to the image to sort of have a flushed in effect or somehting

```<code>    .project-tile{
        padding: 10px;
        width: 30%;
        border-radius: 10px;
        text-align: center;
        display: inline-block;
    }
    .project-tile img{
        max-height: 300px;
        max-width: 300px;
        box-shadow: 0 0 10px gray;
        border-bottom-left-radius: 10px;
        border-bottom-right-radius: 10px;
        background-color: rgba(128, 128, 128, 0.575);
    }
    .project-tile a{
        text-decoration: underline;
        color: rgb(255, 255, 255);
        font-size: 23px;
        background-color: rgba(128, 128, 128, 0.575);
        display: grid;
        border-top-left-radius: 10px;
        border-top-right-radius: 10px;
        height: 40px;
        align-items: center;
    }
</code>```

html

```<code>    <section id="projects">
        <h2>Here are few of my projects ive been working on</h2>
        <div class="project-tile">
            <a href="https://codepen.io/Leuqas/full/gOXLGoE">Tribute Page</a>
            <img src="https://cdn.discordapp.com/attachments/940847175867457547/940848284073885726/unknown.png" alt="picture">
        </div>
        <div class="project-tile">
            <a href="https://codepen.io/Leuqas/full/PoOWXWp">HTML Documentation Page</a>
            <img src="https://cdn.discordapp.com/attachments/940847175867457547/940847191801618442/unknown.png" alt="picture">
        </div>
        <div class="project-tile">
            <a href="https://codepen.io/Leuqas/full/xxPRMPX">Product Landing Page</a>
            <img src="https://cdn.discordapp.com/attachments/940847175867457547/940849497288880178/unknown.png" alt="picture">
        </div>
    </section>
</code>```

this are my current codes and what it looks like(picture)

答:
you can test this.

.container {
  display:flex;
  justify-content: space-around;
  align-items: center;
  border: 1px solid gray;
  height:100px;
  background-color:gray
}

.container-child{
 background-color:green;
 height:50px;
 width:50px;
 display:flex;
 align-items: center;
 justify-content: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
 <div class="container-child">text</div>
 <div class="container-child">text</div>
 <div class="container-child">text</div>
</div></code>```

Body:
im quite new to coding... and im making a portfolio that contains all the projects ive currently done... and i want to align the text background color to the image to sort of have a flushed in effect or somehting

    .project-tile{
        padding: 10px;
        width: 30%;
        border-radius: 10px;
        text-align: center;
        display: inline-block;
    }
    .project-tile img{
        max-height: 300px;
        max-width: 300px;
        box-shadow: 0 0 10px gray;
        border-bottom-left-radius: 10px;
        border-bottom-right-radius: 10px;
        background-color: rgba(128, 128, 128, 0.575);
    }
    .project-tile a{
        text-decoration: underline;
        color: rgb(255, 255, 255);
        font-size: 23px;
        background-color: rgba(128, 128, 128, 0.575);
        display: grid;
        border-top-left-radius: 10px;
        border-top-right-radius: 10px;
        height: 40px;
        align-items: center;
    }

html

Here are few of my projects ive been working on

            Tribute Page

            HTML Documentation Page

            Product Landing Page

this are my current codes and what it looks like(picture)

Body:
you can test this.

.container {
  display:flex;
  justify-content: space-around;
  align-items: center;
  border: 1px solid gray;
  height:100px;
  background-color:gray
}

.container-child{
 background-color:green;
 height:50px;
 width:50px;
 display:flex;
 align-items: center;
 justify-content: center;
}

<div class="container">
 <div class="container-child">text</div>
 <div class="container-child">text</div>
 <div class="container-child">text</div>
</div>


问:
How to trigger SwiftUI animation via change of non-State variable
It's easy to have an animation begin when a view appears, by using .onAppear(). But I'd like to perform a repeating animation whenever one of the view's non-State variables changes. An example:

Here is a view that I would like to "throb" whenever its throbbing parameter, set externally, is true:

```<code>struct MyCircle: View {
    var throbbing: Bool
    @State var scale = 1.0
    var body: some View {
        Circle()
            .frame(width: 100 * scale, height: 100 * scale)
            .foregroundColor(.blue)
            .animation(.easeInOut.repeatForever(), value: scale)
            .onAppear { scale = 1.2 }
    }
}
</code>```

Currently the code begins throbbing immediately, regardless of the throbbing variable.

But imagine this scenario:

```<code>struct ContentView: View {
    @State var throb: Bool = false
    var body: some View {
        VStack {
            Button("Throb: \(throb ? "ON" : "OFF")") { throb.toggle() }
            MyCircle(throbbing: throb)
        }
    }
}
</code>```

It looks like this:

Any ideas how I can modify MyCircle so that the throbbing starts when the button is tapped and ends when it is tapped again?

答:
There're two interesting things that i've just found when trying to achieve yours target.

Animation will be added when the value changed

Animation that added to the view cannot be removed, and we need to drop the animated view from the view hiearachy by remove its id, new view will be created with zero animations.

```<code>import SwiftUI
import PlaygroundSupport

struct ContentView: View {
    @State var throbbling = false
    @State var circleId = UUID()
    var body: some View {
        VStack {
            Toggle("Throbbling", isOn: $throbbling)
            circle.id(circleId)
                .scaleEffect(throbbling ? 1.2 : 1.0)
                .animation(.easeInOut.repeatForever(), value: throbbling)
                .onChange(of: throbbling) { newValue in
                    if newValue == false {
                        circleId = UUID()
                    }
                }
        }.padding()
    }

    @ViewBuilder
    var circle: some View {
        Circle().fill(.green).frame(width: 100, height: 100)
    }
}

PlaygroundPage.current.setLiveView(ContentView())
</code>```

Body:
It's easy to have an animation begin when a view appears, by using .onAppear(). But I'd like to perform a repeating animation whenever one of the view's non-State variables changes. An example:

Here is a view that I would like to "throb" whenever its throbbing parameter, set externally, is true:

struct MyCircle: View {
    var throbbing: Bool
    @State var scale = 1.0
    var body: some View {
        Circle()
            .frame(width: 100 * scale, height: 100 * scale)
            .foregroundColor(.blue)
            .animation(.easeInOut.repeatForever(), value: scale)
            .onAppear { scale = 1.2 }
    }
}

Currently the code begins throbbing immediately, regardless of the throbbing variable.

But imagine this scenario:

struct ContentView: View {
    @State var throb: Bool = false
    var body: some View {
        VStack {
            Button("Throb: \(throb ? "ON" : "OFF")") { throb.toggle() }
            MyCircle(throbbing: throb)
        }
    }
}

It looks like this:

Any ideas how I can modify MyCircle so that the throbbing starts when the button is tapped and ends when it is tapped again?

Body:
There're two interesting things that i've just found when trying to achieve yours target.

Animation will be added when the value changed

Animation that added to the view cannot be removed, and we need to drop the animated view from the view hiearachy by remove its id, new view will be created with zero animations.

import SwiftUI
import PlaygroundSupport

struct ContentView: View {
    @State var throbbling = false
    @State var circleId = UUID()
    var body: some View {
        VStack {
            Toggle("Throbbling", isOn: $throbbling)
            circle.id(circleId)
                .scaleEffect(throbbling ? 1.2 : 1.0)
                .animation(.easeInOut.repeatForever(), value: throbbling)
                .onChange(of: throbbling) { newValue in
                    if newValue == false {
                        circleId = UUID()
                    }
                }
        }.padding()
    }

    @ViewBuilder
    var circle: some View {
        Circle().fill(.green).frame(width: 100, height: 100)
    }
}

PlaygroundPage.current.setLiveView(ContentView())


问:
How can I know the type of error and response code from IOWebSocketChannel
I am trying to know if the connection error is Connection to 'some URL' was not upgraded to websocket. Also identify response code. The server is emitting 401.

I need this to know if I need to refresh the token and then reconnect.

final channel = IOWebSocketChannel.connect(Url)
final sub = channel.stream.listen((data){
                                        //process data
                                     },
                                    onError: (error){
                                        //confirm this error failing to upgrade and
                                        // response code is 401

                                        // then refresh token and reconnect
                                     })
```

答:
To know the error type

print('error type is ${error.runtimeType}');
```
<p>then you can handle it</p>
<pre class="lang-dart prettyprint-override"><code>if(error is errorType)
{
...
}
</code>```

Body:
To know the error type

print('error type is ${error.runtimeType}');

then you can handle it

if(error is errorType)
{
...
}


问:
error Couldn't find "PLATFORM_NAME" variable in xcodebuild output
I'm trying to run my application on an iPhone simulator. from the console, I can see the build was successful. but on the next line, I get this.

error Couldn't find "PLATFORM_NAME" variable in xcodebuild output. Please report this issue and run your project with Xcode instead. react-native.

答:
Step - 1: Clean the build folder from Xcode.

Xcode toolbar -> Product -> Clean build folder

Step - 2: Delete the App installed in the device/simulator

Step - 3: Go to VSCode and move to ios directory using command line and just to be on the safer side, run the following command (just to remove build folder via VSCode as well)

rm -rf build

Step - 4: Run

pod install

Step - 5: Go back to the project folder and build the app again:

npx react-native run-ios


问:
How would I format this
I just started learning SQL Three weeks ago for College. I am trying to practice making databases. I ran into an issue that I can't really understand how to fix. I found something that was close to my question but I could not really understand what they were trying to do.

I have a database with PLanets and moons, my issue is some planets have many moons. From what I understand on normalization is you can't have duplicate info in one cell?

Here is what I wrote, but if I run it this way I would have multiple moonid in my planet table.

```<code>CREATE TABLE `planet`(
    `plid` int NOT NULL,
    `plname` varchar(50) DEFAULT NULL,
    `plsize` int DEFAULT NULL,
    `moonid` int DEFAULT NULL,
    `pltype` varchar(50),
    `plage` int DEFAULT NULL,
    PRIMARY KEY (`plid`)
)   ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE `moon`(
    `moonid` int NOT NULL,
    `moonname` varchar(50) DEFAULT NULL,
    `moonsize` int DEFAULT NULL,
    `moonage`int DEFAULT NULL,
    `plid` int DEFAULT NULL,
    PRIMARY KEY (`moonid`)
</code>```

This is what was suggested but I don't really see how this would fix my issue.

```<code>CREATE TABLE `moonplanet`(
    `moonid` int NOT NULL,
    `plid` int DEFAULT NULL,
    PRIMARY KEY (`moonid`)
    )ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
</code>```

答:
AFAIK a moon can not be shared by two or more planets, so this is a 1:M relationship. You needn't a separate moonplanet table for the realationship.

We model a 1:M relationship with a column of Moon referencing the Planet and your table has already got it.

Yes, a column with multiple values in one cell breaks 1NF. So just drop the moonid column from the planet table.

Title: How would I format this

Body:
I just started learning SQL Three weeks ago for College. I am trying to practice making databases. I ran into an issue that I can't really understand how to fix. I found something that was close to my question but I could not really understand what they were trying to do.

I have a database with PLanets and moons, my issue is some planets have many moons. From what I understand on normalization is you can't have duplicate info in one cell?

Here is what I wrote, but if I run it this way I would have multiple moonid in my planet table.

CREATE TABLE `planet`(
    `plid` int NOT NULL,
    `plname` varchar(50) DEFAULT NULL,
    `plsize` int DEFAULT NULL,
    `moonid` int DEFAULT NULL,
    `pltype` varchar(50),
    `plage` int DEFAULT NULL,
    PRIMARY KEY (`plid`)
)   ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE `moon`(
    `moonid` int NOT NULL,
    `moonname` varchar(50) DEFAULT NULL,
    `moonsize` int DEFAULT NULL,
    `moonage`int DEFAULT NULL,
    `plid` int DEFAULT NULL,
    PRIMARY KEY (`moonid`)

This is what was suggested but I don't really see how this would fix my issue.

CREATE TABLE `moonplanet`(
    `moonid` int NOT NULL,
    `plid` int DEFAULT NULL,
    PRIMARY KEY (`moonid`)
    )ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;


问:
How to create a dataset for tensorflow from a txt file containing paths and labels?
I'm trying to load the DomainNet dataset into a tensorflow dataset.
Each of the domains contain two .txt files for the training and test data respectively, which is structured as follows:

```<code>painting/aircraft_carrier/painting_001_000106.jpg 0
painting/aircraft_carrier/painting_001_000060.jpg 0
painting/aircraft_carrier/painting_001_000130.jpg 0
painting/aircraft_carrier/painting_001_000058.jpg 0
painting/aircraft_carrier/painting_001_000093.jpg 0
painting/aircraft_carrier/painting_001_000107.jpg 0
painting/aircraft_carrier/painting_001_000088.jpg 0
painting/aircraft_carrier/painting_001_000014.jpg 0
painting/aircraft_carrier/painting_001_000013.jpg 0
...
</code>```

Which is one line per image containing a relative path and a label. My question is, if there is already some built-in way in tensorflow/keras to load this kind of structure, or if I have to parse and load the data manually? So far my google-fu let me down...

答:
You can use tf.data.TextLineDataset to load and process multiple txt files at a time:

import tensorflow as tf
import matplotlib.pyplot as plt

with open('data.txt', 'w') as f:
  f.write('/content/result_image1.png 0\n')
  f.write('/content/result_image2.png 1\n')

with open('more_data.txt', 'w') as f:
  f.write('/content/result_image1.png 1\n')
  f.write('/content/result_image2.png 0\n')

dataset = tf.data.TextLineDataset(['/content/data.txt', '/content/more_data.txt'])
for element in dataset.as_numpy_iterator():
  print(element)
```
```b'/content/result_image1.png 0'
b'/content/result_image2.png 1'
b'/content/result_image1.png 1'
b'/content/result_image2.png 0'
```
<p>Process data:</p>
```def process(x):
  splits = tf.strings.split(x, sep=' ')
  image_path, label = splits[0], splits[1]
  img = tf.io.read_file(image_path)
  img = tf.io.decode_png(img, channels=3)
  return  img, tf.strings.to_number(label, out_type=tf.int32)

dataset = dataset.map(process)
for x, y in dataset.take(1):
  print('Label -->', y)
  plt.imshow(x.numpy())
```
```Label --> tf.Tensor(0, shape=(), dtype=int32)
```

Body:
I'm trying to load the DomainNet dataset into a tensorflow dataset.
Each of the domains contain two .txt files for the training and test data respectively, which is structured as follows:

painting/aircraft_carrier/painting_001_000106.jpg 0
painting/aircraft_carrier/painting_001_000060.jpg 0
painting/aircraft_carrier/painting_001_000130.jpg 0
painting/aircraft_carrier/painting_001_000058.jpg 0
painting/aircraft_carrier/painting_001_000093.jpg 0
painting/aircraft_carrier/painting_001_000107.jpg 0
painting/aircraft_carrier/painting_001_000088.jpg 0
painting/aircraft_carrier/painting_001_000014.jpg 0
painting/aircraft_carrier/painting_001_000013.jpg 0
...

Which is one line per image containing a relative path and a label. My question is, if there is already some built-in way in tensorflow/keras to load this kind of structure, or if I have to parse and load the data manually? So far my google-fu let me down...

Body:
You can use tf.data.TextLineDataset to load and process multiple txt files at a time:

import tensorflow as tf
import matplotlib.pyplot as plt

with open('data.txt', 'w') as f:
  f.write('/content/result_image1.png 0\n')
  f.write('/content/result_image2.png 1\n')

with open('more_data.txt', 'w') as f:
  f.write('/content/result_image1.png 1\n')
  f.write('/content/result_image2.png 0\n')

dataset = tf.data.TextLineDataset(['/content/data.txt', '/content/more_data.txt'])
for element in dataset.as_numpy_iterator():
  print(element)

b'/content/result_image1.png 0'
b'/content/result_image2.png 1'
b'/content/result_image1.png 1'
b'/content/result_image2.png 0'

Process data:

def process(x):
  splits = tf.strings.split(x, sep=' ')
  image_path, label = splits[0], splits[1]
  img = tf.io.read_file(image_path)
  img = tf.io.decode_png(img, channels=3)
  return  img, tf.strings.to_number(label, out_type=tf.int32)

dataset = dataset.map(process)
for x, y in dataset.take(1):
  print('Label -->', y)
  plt.imshow(x.numpy())

Label --> tf.Tensor(0, shape=(), dtype=int32)


问:
Prevent Spring Boot from registering a servlet filter
I have a Spring Boot WebMVC application, and a bean that inherits from AbstractPreAuthenticatedProcessingFilter which I am explicitly adding to a specific spot in the Spring Security filter chain. My Spring Security configuration looks like this:

```<code><http pattern="/rest/**">
  <intercept-url pattern="/**" access="ROLE_USER"/>
  <http-basic/>
  <custom-filter after="BASIC_AUTH_FILTER" ref="preAuthenticationFilter"/>
</http>

<beans:bean id="preAuthenticationFilter" class="a.b.PreAuthenticationFilter">
  <beans:property name="authenticationManager" ref="customAuthenticationManager"/>
</beans:bean>
</code>```

The security configuration works. The problem is, because the PreAuthenticationFilter class inherits from AbstractPreAuthenticatedProcessingFilter, Spring Boot treats it as a general purpose servlet filter and is adding it to the servlet filter chain for all requests. I don't want this filter to be part of the filter chain for all requests. I only want it to be part of the specific Spring Security filter chain that I've configured. Is there a way to prevent Spring Boot from automatically adding the preAuthenticationFilter bean to the filter chain?

答:
If you need to disable registering 2 filters(like i did), include a name for the bean(so that they do not override):</p>
```<code>@Bean(name = "filterRegistrationBean1")
public FilterRegistrationBean<YourFilter1> registration(YourFilter1 f1) {
    FilterRegistrationBean<YourFilter1> registration = new FilterRegistrationBean<>(f1);
    registration.setEnabled(false);
    return registration;
}

@Bean(name = "filterRegistrationBean2")
public FilterRegistrationBean<YourFilter2> registration(YourFilter2 f2) {
    FilterRegistrationBean<YourFilter2> registration = new FilterRegistrationBean<>(f2);
    registration.setEnabled(false);
    return registration;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a Spring Boot WebMVC application, and a bean that inherits from AbstractPreAuthenticatedProcessingFilter which I am explicitly adding to a specific spot in the Spring Security filter chain. My Spring Security configuration looks like this:

<http pattern="/rest/**">
  <intercept-url pattern="/**" access="ROLE_USER"/>
  <http-basic/>
  <custom-filter after="BASIC_AUTH_FILTER" ref="preAuthenticationFilter"/>
</http>

<beans:bean id="preAuthenticationFilter" class="a.b.PreAuthenticationFilter">
  <beans:property name="authenticationManager" ref="customAuthenticationManager"/>
</beans:bean>

The security configuration works. The problem is, because the PreAuthenticationFilter class inherits from AbstractPreAuthenticatedProcessingFilter, Spring Boot treats it as a general purpose servlet filter and is adding it to the servlet filter chain for all requests. I don't want this filter to be part of the filter chain for all requests. I only want it to be part of the specific Spring Security filter chain that I've configured. Is there a way to prevent Spring Boot from automatically adding the preAuthenticationFilter bean to the filter chain?

Body:
If you need to disable registering 2 filters(like i did), include a name for the bean(so that they do not override):

@Bean(name = "filterRegistrationBean1")
public FilterRegistrationBean<YourFilter1> registration(YourFilter1 f1) {
    FilterRegistrationBean<YourFilter1> registration = new FilterRegistrationBean<>(f1);
    registration.setEnabled(false);
    return registration;
}

@Bean(name = "filterRegistrationBean2")
public FilterRegistrationBean<YourFilter2> registration(YourFilter2 f2) {
    FilterRegistrationBean<YourFilter2> registration = new FilterRegistrationBean<>(f2);
    registration.setEnabled(false);
    return registration;
}


问:
Printf Problem with While Loop
I'm creating a temperature converter in C. Basically, you input a minimum and maximum value in degrees Celsius, along with a step, and it displays that information in a list, along with the Fahrenheit equivalent. On some occasions, I have noticed the last Fahrenheit entry not being displayed when it should. For example, when you input a lower limit of 10, a higher limit of 30, and a step of 4, it cuts off the last Fahrenheit temperature. I know it's something to do with the last while loop, but I just can't figure it out.</p>

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

int main (int argc, const char * argv[]) {
double l, h, s;
double lf, hf, sf;
/* Number rows in tables */
int num1, num2;
num1 = 1;
num2 = 1;

/* Lower limit input */
printf("Please give a lower limit: ");
scanf("%4lf", &l);
while (l < 0) {
        printf("Lower limit must be greater than 0: ");
        scanf("%4lf", &l);
}

/* Stores value for Fahrenheit conversion */
lf = l;

/* Higher limit input */
printf("Please give a higher limit: ");
scanf("%4lf", &h);
while (h <= l) {
        printf("Higher limit must be greater than lower limit: ");
        scanf("%4lf", &h);
}

while (h >= 50000) {
        printf("Higher limit must be less than 50000: ");
        scanf("%4lf", &h);
}

hf = h;

/* Step input */
printf("Please input step: ");
scanf("%4lf", &s);
while (s <= 0) {
        printf("Step must be greater than 0: ");
        scanf("%4lf", &s);
}

while (s >= h - l) {
        printf("Step must be less than the difference in temperatures: ");
        scanf("%4lf", &s);
}

sf = s;

/* Celsius table */
printf("\nCelsius\n-------\n");
while (l <= h) {
    printf("%i. %4lf\n", num1, l);
    num1++;
    l = l + s;
}

/* Fahrenheit table */
printf("\nFahrenheit\n----------\n");
/* Converts Celsius to Fahrenheit */
lf = (lf * 1.8) + 32;
hf = (hf * 1.8) + 32;
sf = sf * 1.8;
printf("Lower input: %4lf\n", lf);
printf("Higher input: %4lf\n", hf);
printf("Step: %4lf\n----------\n", sf);
/* This while loop sometimes cuts off the last entry */
while (lf <= hf) {
    printf("%i. %4lf\n", num2, lf);
    num2++;
    lf = lf + sf;
}

return 0;

}
</code>```

答:
Directly after your last while loop, add the following code (and don't forget to #include assert.h):

```<code>printf("lf = %f, hf = %f\n", lf, hf);
assert(lf == hf);
</code>```

you should get this output:

```<code>Celsius
-------
1. 10.000000
2. 14.000000
3. 18.000000
4. 22.000000
5. 26.000000
6. 30.000000

Fahrenheit
----------
Lower input: 50.000000
Higher input: 86.000000
Step: 7.200000
----------
1. 50.000000
2. 57.200000
3. 64.400000
4. 71.600000
5. 78.800000
lf = 86.000000, hf = 86.000000
Assertion failed: lf == hf, file randomdudescode.c, line 77
</code>```

Which is incredibly confusing, because obviously lf == hf.
This illustrates one of the quirks of C and floating point tomfoolery in general.  You have to deal with rounding errors and imprecision.

Title: Printf Problem with While Loop

Body:
I'm creating a temperature converter in C. Basically, you input a minimum and maximum value in degrees Celsius, along with a step, and it displays that information in a list, along with the Fahrenheit equivalent. On some occasions, I have noticed the last Fahrenheit entry not being displayed when it should. For example, when you input a lower limit of 10, a higher limit of 30, and a step of 4, it cuts off the last Fahrenheit temperature. I know it's something to do with the last while loop, but I just can't figure it out.

#include <stdio.h>

int main (int argc, const char * argv[]) {
double l, h, s;
double lf, hf, sf;
/* Number rows in tables */
int num1, num2;
num1 = 1;
num2 = 1;

/* Lower limit input */
printf("Please give a lower limit: ");
scanf("%4lf", &l);
while (l < 0) {
        printf("Lower limit must be greater than 0: ");
        scanf("%4lf", &l);
}

/* Stores value for Fahrenheit conversion */
lf = l;

/* Higher limit input */
printf("Please give a higher limit: ");
scanf("%4lf", &h);
while (h <= l) {
        printf("Higher limit must be greater than lower limit: ");
        scanf("%4lf", &h);
}

while (h >= 50000) {
        printf("Higher limit must be less than 50000: ");
        scanf("%4lf", &h);
}

hf = h;

/* Step input */
printf("Please input step: ");
scanf("%4lf", &s);
while (s <= 0) {
        printf("Step must be greater than 0: ");
        scanf("%4lf", &s);
}

while (s >= h - l) {
        printf("Step must be less than the difference in temperatures: ");
        scanf("%4lf", &s);
}

sf = s;

/* Celsius table */
printf("\nCelsius\n-------\n");
while (l <= h) {
    printf("%i. %4lf\n", num1, l);
    num1++;
    l = l + s;
}

/* Fahrenheit table */
printf("\nFahrenheit\n----------\n");
/* Converts Celsius to Fahrenheit */
lf = (lf * 1.8) + 32;
hf = (hf * 1.8) + 32;
sf = sf * 1.8;
printf("Lower input: %4lf\n", lf);
printf("Higher input: %4lf\n", hf);
printf("Step: %4lf\n----------\n", sf);
/* This while loop sometimes cuts off the last entry */
while (lf <= hf) {
    printf("%i. %4lf\n", num2, lf);
    num2++;
    lf = lf + sf;
}

return 0;

}

Body:
Directly after your last while loop, add the following code (and don't forget to #include assert.h):

printf("lf = %f, hf = %f\n", lf, hf);
assert(lf == hf);

you should get this output:

Celsius
-------
1. 10.000000
2. 14.000000
3. 18.000000
4. 22.000000
5. 26.000000
6. 30.000000

Fahrenheit
----------
Lower input: 50.000000
Higher input: 86.000000
Step: 7.200000
----------
1. 50.000000
2. 57.200000
3. 64.400000
4. 71.600000
5. 78.800000
lf = 86.000000, hf = 86.000000
Assertion failed: lf == hf, file randomdudescode.c, line 77

Which is incredibly confusing, because obviously lf == hf.
This illustrates one of the quirks of C and floating point tomfoolery in general.  You have to deal with rounding errors and imprecision.


答:
using relationship - one to many table structure looks like this....just remove moonid from planet table....using JOIN u can able to fetch multiple moon values</p>
```<code>CREATE TABLE `planet`(
    `plid` int NOT NULL,
    `plname` varchar(50) DEFAULT NULL,
    `plsize` int DEFAULT NULL,
    `pltype` varchar(50),
    `plage` int DEFAULT NULL,
    PRIMARY KEY (`plid`)
)   ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE `moon`(
    `moonid` int NOT NULL,
    `moonname` varchar(50) DEFAULT NULL,
    `moonsize` int DEFAULT NULL,
    `moonage`int DEFAULT NULL,
    `plid` int DEFAULT NULL,
    PRIMARY KEY (`moonid`)
</code>```

Title: How would I format this

Body:
using relationship - one to many table structure looks like this....just remove moonid from planet table....using JOIN u can able to fetch multiple moon values

CREATE TABLE `planet`(
    `plid` int NOT NULL,
    `plname` varchar(50) DEFAULT NULL,
    `plsize` int DEFAULT NULL,
    `pltype` varchar(50),
    `plage` int DEFAULT NULL,
    PRIMARY KEY (`plid`)
)   ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE `moon`(
    `moonid` int NOT NULL,
    `moonname` varchar(50) DEFAULT NULL,
    `moonsize` int DEFAULT NULL,
    `moonage`int DEFAULT NULL,
    `plid` int DEFAULT NULL,
    PRIMARY KEY (`moonid`)


问:
Discord py Number guess command
So, I have a number guess bot that I need some help adding on to.

How it works is that I have the command

!FinalBalance = !finalbalance (number), and based on whatever number is given it will go through and sort through all the guess entries and find the top 5 people who were closest to the final balance number.

Everything works great, but I want to update the !finalbalance command to work like
!finalbalance (amount of winners) (random number) instead of !finalbalance (random number)

You're able to choose the amount of winners / closest guessers instead of it being 5 by default.

Example: !finalbalance 3 4300 .. will send the 3 closest guesses to the random number.

output:
Top 3 Closest Guesses
Final Amount: 4300
1st place: BlahBlah
2nd place: BlahBlahBlah
3rd place: BlahBlahBlah

I would also like for the title to change based on the amount of winners I choose in the command. So !finalbalance 3 (random number), will make the title Top 3 Closest Guesses, and if I did !finalbalance 6 (random number), it would make the title Top 6 Closest Guesses.

Here is the code for the !finalbalance command now.

```<code>@bot.command()
@commands.has_permissions(administrator = True)
async def finalbalance(ctx, amount: float = None):
    global winner_decided
    global user_guesses
    global game_started

    if not game_started:
        if winner_decided:
            await ctx.send("Guessing has not started yet.")
            return

    if amount == None:
        await ctx.send("Please specify an amount to decided the winners.")
        return

    if len(user_guesses) == 0:
        await ctx.send("No user has guessed anything.")
        winner_decided = True
        user_guesses = {}
        return

    winners_embed = discord.Embed(title = "Top 5 closest guesses", description = f"Final amount: {amount}\n")

    ordinal = lambda n: "%d%s" % (n,"tsnrhtdd"[(n//10%10!=1)*(n%10<4)*n%10::4])

    dict_len = len(list(user_guesses.values()))

    for i in range(dict_len if (dict_len <= 5) else 5):
        winner = find_nearest(user_guesses, float(amount))
        del user_guesses[winner[0]]
        winners_embed.add_field(name = f"With ${float(winner[1])} as a guess and ${abs(float(amount) - winner[1])} difference:", value = f"{ordinal(i+1)} place: {winner[0]}", inline = False)

    winners_embed.set_footer(text = f"{dict_len} participants")

    await ctx.send(embed = winners_embed)

    winner_decided = True
    user_guesses = {}
</code>```

Any help on this would be greatly appreciated :)!

Also if needed, here is my pastebin link to the full source code.
https://pastebin.com/Ay88n6wA

答:
Simply add guessers to finalbalance() like this:

```<code>async def finalbalance(ctx, amount: float, guessers: int = 5)
</code>```

Then replace the instances of 5 with guessers.

```<code>for i in range(dict_len if (dict_len <= guessers) else 5):
</code>```

and

```<code>winners_embed = discord.Embed(title = f"Top {guessers} closest guesses", description = f"Final amount: {amount}\n")
</code>```

Title: Discord py Number guess command

Body:
So, I have a number guess bot that I need some help adding on to.

How it works is that I have the command

!FinalBalance = !finalbalance (number), and based on whatever number is given it will go through and sort through all the guess entries and find the top 5 people who were closest to the final balance number.

Everything works great, but I want to update the !finalbalance command to work like
!finalbalance (amount of winners) (random number) instead of !finalbalance (random number)

You're able to choose the amount of winners / closest guessers instead of it being 5 by default.

Example: !finalbalance 3 4300 .. will send the 3 closest guesses to the random number.

output:
Top 3 Closest Guesses
Final Amount: 4300
1st place: BlahBlah
2nd place: BlahBlahBlah
3rd place: BlahBlahBlah

I would also like for the title to change based on the amount of winners I choose in the command. So !finalbalance 3 (random number), will make the title Top 3 Closest Guesses, and if I did !finalbalance 6 (random number), it would make the title Top 6 Closest Guesses.

Here is the code for the !finalbalance command now.

@bot.command()
@commands.has_permissions(administrator = True)
async def finalbalance(ctx, amount: float = None):
    global winner_decided
    global user_guesses
    global game_started

    if not game_started:
        if winner_decided:
            await ctx.send("Guessing has not started yet.")
            return

    if amount == None:
        await ctx.send("Please specify an amount to decided the winners.")
        return

    if len(user_guesses) == 0:
        await ctx.send("No user has guessed anything.")
        winner_decided = True
        user_guesses = {}
        return

    winners_embed = discord.Embed(title = "Top 5 closest guesses", description = f"Final amount: {amount}\n")

    ordinal = lambda n: "%d%s" % (n,"tsnrhtdd"[(n//10%10!=1)*(n%10<4)*n%10::4])

    dict_len = len(list(user_guesses.values()))

    for i in range(dict_len if (dict_len <= 5) else 5):
        winner = find_nearest(user_guesses, float(amount))
        del user_guesses[winner[0]]
        winners_embed.add_field(name = f"With ${float(winner[1])} as a guess and ${abs(float(amount) - winner[1])} difference:", value = f"{ordinal(i+1)} place: {winner[0]}", inline = False)

    winners_embed.set_footer(text = f"{dict_len} participants")

    await ctx.send(embed = winners_embed)

    winner_decided = True
    user_guesses = {}

Any help on this would be greatly appreciated :)!

Also if needed, here is my pastebin link to the full source code.
https://pastebin.com/Ay88n6wA

Body:
Simply add guessers to finalbalance() like this:

async def finalbalance(ctx, amount: float, guessers: int = 5)

Then replace the instances of 5 with guessers.

for i in range(dict_len if (dict_len <= guessers) else 5):

and

winners_embed = discord.Embed(title = f"Top {guessers} closest guesses", description = f"Final amount: {amount}\n")


问:
java.util.Date to XMLGregorianCalendar
Isn't there a convenient way of getting from a java.util.Date to a XMLGregorianCalendar?</p>

答:
My solution</p>
```<code>public static XMLGregorianCalendar DateToXMLGregorianCalendar(Date date) {

    GregorianCalendar gregoriancalendar = new GregorianCalendar();
    gregoriancalendar.setTime(date);
    XMLGregorianCalendar xmlGregorianCalendar = new XMLGregorianCalendarImpl(gregoriancalendar);
    return xmlGregorianCalendar;
}
</code>```

Title: java.util.Date to XMLGregorianCalendar

Body:
My solution

public static XMLGregorianCalendar DateToXMLGregorianCalendar(Date date) {

    GregorianCalendar gregoriancalendar = new GregorianCalendar();
    gregoriancalendar.setTime(date);
    XMLGregorianCalendar xmlGregorianCalendar = new XMLGregorianCalendarImpl(gregoriancalendar);
    return xmlGregorianCalendar;
}


问:
Rails: Getting list of attributes with uniqueness validations from a model
Just wondering if it's possible to return a list of all attributes which possess a uniqueness validation? For example, I have a model Person - I'd like to return a list of the attributes in 'Person' which have a uniqueness constraint. Any ideas?</p>

答:
You can do something like

Person.validators.select { |v| v.is_a?(ActiveRecord::Validations::UniquenessValidator) }

to get the list of uniqueness validators for the Person model. Each validator has an @attributes instance variable, and that's what you probably need.


问:
How to remove UserAccountsDrawerHeader outline on flutter
I'm learning flutter.
I used the UserAccountsDrawerHeader widget using the Drawer widget, but when setting Radius, unnecessary line appears below.
How can you remove it?

Here's my code

```<code>drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: [
            UserAccountsDrawerHeader(
              currentAccountPicture: CircleAvatar(
                child: Image.asset('assets/nyancat_bg.png'),
                backgroundColor: Colors.white,
              ),
              accountName: Text('NYAN CAT'),
              accountEmail: Text('nyancat@abc.com'),
              onDetailsPressed: () {
                debugPrint("arrow is clicked");
              },
              decoration: BoxDecoration(
                  color: Colors.indigo[400],
                  borderRadius: BorderRadius.only(
                      bottomLeft: Radius.circular(20.0),
                      bottomRight: Radius.circular(20.0))),
            )
          ],
        ),
      ),
</code>```

screenshot

答:
Use a ClipRRect to make the border radius. Like so:

```<code>    ClipRRect(
      borderRadius: BorderRadius.only(
        topLeft: Radius.circular(20),
        topRight: Radius.circular(20),
      ),
      child: UserAccountsDrawerHeader(
        currentAccountPicture: CircleAvatar(
          child: Image.asset('assets/nyancat_bg.png'),
          backgroundColor: Colors.white,
        ),
        accountName: Text('NYAN CAT'),
        accountEmail: Text('nyancat@abc.com'),
        onDetailsPressed: () {
          debugPrint("arrow is clicked");
        },
        decoration: BoxDecoration(
          color: Colors.indigo[400],
        ),
      ),
    )
</code>```

Body:
I'm learning flutter.
I used the UserAccountsDrawerHeader widget using the Drawer widget, but when setting Radius, unnecessary line appears below.
How can you remove it?

Here's my code

drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: [
            UserAccountsDrawerHeader(
              currentAccountPicture: CircleAvatar(
                child: Image.asset('assets/nyancat_bg.png'),
                backgroundColor: Colors.white,
              ),
              accountName: Text('NYAN CAT'),
              accountEmail: Text('nyancat@abc.com'),
              onDetailsPressed: () {
                debugPrint("arrow is clicked");
              },
              decoration: BoxDecoration(
                  color: Colors.indigo[400],
                  borderRadius: BorderRadius.only(
                      bottomLeft: Radius.circular(20.0),
                      bottomRight: Radius.circular(20.0))),
            )
          ],
        ),
      ),

screenshot

Body:
Use a ClipRRect to make the border radius. Like so:

    ClipRRect(
      borderRadius: BorderRadius.only(
        topLeft: Radius.circular(20),
        topRight: Radius.circular(20),
      ),
      child: UserAccountsDrawerHeader(
        currentAccountPicture: CircleAvatar(
          child: Image.asset('assets/nyancat_bg.png'),
          backgroundColor: Colors.white,
        ),
        accountName: Text('NYAN CAT'),
        accountEmail: Text('nyancat@abc.com'),
        onDetailsPressed: () {
          debugPrint("arrow is clicked");
        },
        decoration: BoxDecoration(
          color: Colors.indigo[400],
        ),
      ),
    )


问:
Need help to sorting an array in a complicated way c# linq
I have a strict similar to this :

```<code>struct Chunk
 {
   public float d; // distance from player
   public bool active; // is it active
 }
</code>```

I have an array of this struct.

What I need:

I need to sort it so the first element is an inactive chunk that is also the furthest from the player, than the next element is active and is also the closest to the player and that is the pattern,

Inactive, furthest

Active, closest

Inactive, furthest

Active, closest

Inactive, furthest
And so on...

Currently I'm using LINQ,
And I'm doing this :

```<code>chunk = chunk.AsParallel().OrderBy(x => x.active ? x.d : -x.d).ToArray();
</code>```

But I don't know how to make it alternate one after another.

答:
But I don't know how to make it alternate one after another.

If you sort the array so that all the inactives are at the start, descending and all the actives are at the end, descending..

```<code>OrderBy(x => x.active?1:0).ThenBy(x=>-x.d)
</code>```

then you can take an item from the start, then an item from the end, then from the start + 1, then the end - 1 working your way inwards

```<code>public static IEnumerable<Chunk> Interleave(this Chunk[] chunks){

    for(int s = 0, e = chunks.Length - 1; s<e;){

        if(!chunks[s].active)
            yield return chunks[s++];

        if(chunks[e].active)
            yield return chunks[e--];

    }

}
</code>```

There's a bit in this so let's unpack it. This is an extension method that acts on an array of chunk. It's a custom enumerator method, so you'd call foreach on it to use it

```<code>foreach(var c in chunk.Interleave())
</code>```

It contains a for loop that tracks two variables, one for the start index and one for the end. The start increments and the end decrements. At some point they'll meet and s will no longer be less than e, which is when we stop:

```<code>for(int s = 0, e = chunks.Length - 1; s<e;){
</code>```

We need to look at the chunk before we return it, if it's an inactive near the start, yield return it and bump the start on by one. s++ increments s, but resolves to the value s was before it incremented. It's thus conceptually like doing chunks[s]; s += 1; but in a one liner

```<code>if(!chunks[s].active)
    yield return chunks[s++];
</code>```

Then we look at the chunk near the end, if it's active then return the ending one and bump the end index down

The inactive chunks are tracked by s, and if s reaches an active chunk it stops returning (every pass of the loop it is skipped), which means e will work its way down towards s returning only the actives

Similarly if there are more inactives than actives, e will stop decrementing first and s will work its way up towards e

If you never came across yield return before think of it as a way to allow you to resume from where you left off rather than starting the method over again. It's used with enumerations to provide a way for the enumeration to return an item, then be moved on one and return the next item. It works a bit like saving your game and going doing something else, then coming back, realising your save game and carrying on from where you left off. Asking an enumerator for Next makes it load the game, play a bit, then save and stop.. Then you Next again and the latest save id loaded, play some more, save and stop. This way you gradually get through the game a bit at a time. If you started a new enumeration by calling Interleave again, that's like starting a new game over from the beginning

MSDN will get more detailed on yield return if you want to dig in more

Edit:

You can perform an in-place sort of your Chunk[] by having a custom comparer:

```<code>public class InactiveThenDistancedDescending : IComparer
{
   public int Compare(object x, object y)
   {
       var a = (Chunk)x;
       var b = (Chunk)y;
       if(a.Active == b.Active)
         return -a.Distance.CompareTo(b.Distance);
       else
         return a.Active.CompareTo(b.Active);
   }
}
</code>```

And:

```<code>Array.Sort(chunkArray, _someInstanceOfThatComparerAbove);
</code>```

Body:
I have a strict similar to this :

struct Chunk
 {
   public float d; // distance from player
   public bool active; // is it active
 }

I have an array of this struct.

What I need:

I need to sort it so the first element is an inactive chunk that is also the furthest from the player, than the next element is active and is also the closest to the player and that is the pattern,

Inactive, furthest

Active, closest

Inactive, furthest

Active, closest

Inactive, furthest
And so on...

Currently I'm using LINQ,
And I'm doing this :

chunk = chunk.AsParallel().OrderBy(x => x.active ? x.d : -x.d).ToArray();

But I don't know how to make it alternate one after another.

Body:
But I don't know how to make it alternate one after another.

If you sort the array so that all the inactives are at the start, descending and all the actives are at the end, descending..

OrderBy(x => x.active?1:0).ThenBy(x=>-x.d)

then you can take an item from the start, then an item from the end, then from the start + 1, then the end - 1 working your way inwards

public static IEnumerable<Chunk> Interleave(this Chunk[] chunks){

    for(int s = 0, e = chunks.Length - 1; s<e;){

        if(!chunks[s].active)
            yield return chunks[s++];

        if(chunks[e].active)
            yield return chunks[e--];

    }

}

There's a bit in this so let's unpack it. This is an extension method that acts on an array of chunk. It's a custom enumerator method, so you'd call foreach on it to use it

foreach(var c in chunk.Interleave())

It contains a for loop that tracks two variables, one for the start index and one for the end. The start increments and the end decrements. At some point they'll meet and s will no longer be less than e, which is when we stop:

for(int s = 0, e = chunks.Length - 1; s<e;){

We need to look at the chunk before we return it, if it's an inactive near the start, yield return it and bump the start on by one. s++ increments s, but resolves to the value s was before it incremented. It's thus conceptually like doing chunks[s]; s += 1; but in a one liner

if(!chunks[s].active)
    yield return chunks[s++];

Then we look at the chunk near the end, if it's active then return the ending one and bump the end index down

The inactive chunks are tracked by s, and if s reaches an active chunk it stops returning (every pass of the loop it is skipped), which means e will work its way down towards s returning only the actives

Similarly if there are more inactives than actives, e will stop decrementing first and s will work its way up towards e

If you never came across yield return before think of it as a way to allow you to resume from where you left off rather than starting the method over again. It's used with enumerations to provide a way for the enumeration to return an item, then be moved on one and return the next item. It works a bit like saving your game and going doing something else, then coming back, realising your save game and carrying on from where you left off. Asking an enumerator for Next makes it load the game, play a bit, then save and stop.. Then you Next again and the latest save id loaded, play some more, save and stop. This way you gradually get through the game a bit at a time. If you started a new enumeration by calling Interleave again, that's like starting a new game over from the beginning

MSDN will get more detailed on yield return if you want to dig in more

Edit:

You can perform an in-place sort of your Chunk[] by having a custom comparer:

public class InactiveThenDistancedDescending : IComparer
{
   public int Compare(object x, object y)
   {
       var a = (Chunk)x;
       var b = (Chunk)y;
       if(a.Active == b.Active)
         return -a.Distance.CompareTo(b.Distance);
       else
         return a.Active.CompareTo(b.Active);
   }
}

And:

Array.Sort(chunkArray, _someInstanceOfThatComparerAbove);


问:
What did I do/ how can I recover my old conda environment in Python?
I have a go-to conda environment called 'pyvizenv'.

I would use it in python and jupyter labs but it couldn't load plotly/pyviz, so I decided to create a new environment called 'testenv'.

I successfully created the new environment but now it appears it messed something up in my 'pyvizenv' environment.

I get errors in git bash when I try to use it such as:

```<code>EnvironmentLocationNotFound: Not a conda environment: C:\Users\LouD\anaconda3\envs\pyvizenv
ImportError: DLL load failed while importing error: The specified module could not be found
</code>```

Is there any way I can recover 'pyvizenv' or figure out what went wrong?

Here is the code I used in git bash to create my new environment 'testenv':

conda create -n testenv python=3.7 anaconda -y
conda activate testenv
pip install python-dotenv
conda install -c anaconda nb_conda -y
conda install -c conda-forge nodejs -y
conda install update nodejs
conda install -c pyviz holoviz -y
conda install -c plotly plotly -y
set NODE_OPTIONS=--max-old-space-size=4096
jupyter labextension install @jupyter-widgets/jupyterlab-manager --no-build
jupyter labextension install jupyterlab-plotly@4.6.0 --no-build
jupyter labextension install plotlywidget@4.6.0 --no-build
jupyter labextension install @pyviz/jupyterlab_pyviz --no-build
jupyter lab build
set NODE_OPTIONS=
```

Also I am able to see both environments under this location in my folders. (Not sure if this helps)

C:\Users\LouD\anaconda3\envs

答:
set NODE_OPTIONS=... suggests a CMD session.

That set command would not work in a git-bash session.

So try first and make it work as a regular CMD script, or in a regular CMD shell, before testing your environment in git bash.

Body:
I have a go-to conda environment called 'pyvizenv'.

I would use it in python and jupyter labs but it couldn't load plotly/pyviz, so I decided to create a new environment called 'testenv'.

I successfully created the new environment but now it appears it messed something up in my 'pyvizenv' environment.

I get errors in git bash when I try to use it such as:

EnvironmentLocationNotFound: Not a conda environment: C:\Users\LouD\anaconda3\envs\pyvizenv
ImportError: DLL load failed while importing error: The specified module could not be found

Is there any way I can recover 'pyvizenv' or figure out what went wrong?

Here is the code I used in git bash to create my new environment 'testenv':

conda create -n testenv python=3.7 anaconda -y
conda activate testenv
pip install python-dotenv
conda install -c anaconda nb_conda -y
conda install -c conda-forge nodejs -y
conda install update nodejs
conda install -c pyviz holoviz -y
conda install -c plotly plotly -y
set NODE_OPTIONS=--max-old-space-size=4096
jupyter labextension install @jupyter-widgets/jupyterlab-manager --no-build
jupyter labextension install jupyterlab-plotly@4.6.0 --no-build
jupyter labextension install plotlywidget@4.6.0 --no-build
jupyter labextension install @pyviz/jupyterlab_pyviz --no-build
jupyter lab build
set NODE_OPTIONS=

Also I am able to see both environments under this location in my folders. (Not sure if this helps)

C:\Users\LouD\anaconda3\envs


问:
Modify all values in a dictionary
Code goes below:

```<code>d = {'a':0, 'b':0, 'c':0, 'd':0}  #at the beginning, all the values are 0.
s = 'cbad'  #a string
indices = map(s.index, d.keys())  #get every key's index in s, i.e., a-2, b-1, c-0, d-3
#then set the values to keys' index
d = dict(zip(d.keys(), indices))  #this is how I do it, any better way?
print d  #{'a':2, 'c':0, 'b':1, 'd':3}
</code>```

Any other way to do that?

PS. the code above is just a simple one to demonstrate my question.

答:
Something like this might make your code more readable:

```<code>dict([(x,y) for y,x in enumerate('cbad')])
</code>```

But you should give more details what you really want to do. Your code will probably fail if the characters in s do not fit the keys of d. So d is just a container for the keys and the values are not important. Why not start with a list in that case?

Title: Modify all values in a dictionary

Body:
Code goes below:

d = {'a':0, 'b':0, 'c':0, 'd':0}  #at the beginning, all the values are 0.
s = 'cbad'  #a string
indices = map(s.index, d.keys())  #get every key's index in s, i.e., a-2, b-1, c-0, d-3
#then set the values to keys' index
d = dict(zip(d.keys(), indices))  #this is how I do it, any better way?
print d  #{'a':2, 'c':0, 'b':1, 'd':3}

Any other way to do that?

PS. the code above is just a simple one to demonstrate my question.

Body:
Something like this might make your code more readable:

dict([(x,y) for y,x in enumerate('cbad')])

But you should give more details what you really want to do. Your code will probably fail if the characters in s do not fit the keys of d. So d is just a container for the keys and the values are not important. Why not start with a list in that case?


问:
I want to catch this moment and work on it even if it happens again in the future (CA)
```<code>em20 = ta.ema(close, 20)
em50 = ta.ema(close, 50)

Signal = ta.crossover(em20, em50)

CA = ta.valuewhen(Signal, close, 0)
</code>```

答:
The var keyword lets you save a value while not reseting it over and over.

Fron the documentation:

When the var keyword is used, the variable is only initilized once, on
the first bar if the declaration is in the global scope, or the first
time the local block is executed if the declaration is inside a local
block. After that, it will preserve its last value on successive bars,
until we reassign a new value to it. This behavior is very useful in
many cases where a variable’s value must persist through the
iterations of a script across successive bars.

You can use the functionality in order to preserve the value of close only on first ta.crossover() if you'll save the number of crosses and then save the value. Here is an example:

```<code>//@version=5
indicator("My script")

em20 = ta.ema(close, 20)
em50 = ta.ema(close, 50)

var numberOfTimesCrossed = 0

Signal = ta.crossover(em20, em50)

if Signal
    numberOfTimesCrossed += 1

var CA = float(na)

if numberOfTimesCrossed == 1
    CA := ta.valuewhen(Signal, close, 0)

plot(nz(CA))
</code>```

Body:
The var keyword lets you save a value while not reseting it over and over.

Fron the documentation:

When the var keyword is used, the variable is only initilized once, on
the first bar if the declaration is in the global scope, or the first
time the local block is executed if the declaration is inside a local
block. After that, it will preserve its last value on successive bars,
until we reassign a new value to it. This behavior is very useful in
many cases where a variable’s value must persist through the
iterations of a script across successive bars.

You can use the functionality in order to preserve the value of close only on first ta.crossover() if you'll save the number of crosses and then save the value. Here is an example:

//@version=5
indicator("My script")

em20 = ta.ema(close, 20)
em50 = ta.ema(close, 50)

var numberOfTimesCrossed = 0

Signal = ta.crossover(em20, em50)

if Signal
    numberOfTimesCrossed += 1

var CA = float(na)

if numberOfTimesCrossed == 1
    CA := ta.valuewhen(Signal, close, 0)

plot(nz(CA))


问:
Best practise to migrate Web Forms to ASP.NET Core MVC
I am trying to migrate a project from classic ASP.Net Web Forms to ASP.NET MVC.

While I have read through http://www.codeproject.com/Articles/38778/ASP-NET-WebForms-and-ASP-NET-MVC-in-Harmony. I have a basic idea on how the code structure, libraries and routing should be done.

For your information, the scope of my existing project is around 400 pages and 300 tables.

On top of my head I have two approaches:

Start from stretch, rewriting the whole system - Obviously this would require intensive work and take a long time. Any change made on existing system would need a duplicate change made to the new system.

Migrate the page one each - I still have a rebuild the entire core library (for accessing db), and get the page migrated one by one. For this I  would assume to have two core libraries (new and old) running simultaneously with different pages connect to one of those.

Would anyone have similar experience and advise a proper way to start?

For this complete revamp I may also target at the latest technology - .NET Core and MVC6, by taking these would I have extra advantage, or some blockages I would have to take care of?

Any suggestion and opinions are appreciated. Cheers.

答:
I can agree that for many cases a re-write of an ASP.NET application where WebForms is used widely may do not provide any business value.

Therefore we decided to use our experience with ASP NET WebForms to develop a highly compatible port of WebForms for ASP NET Core / .NET 6.0.
We use the solution in our own ASP NET WebForms-based products and projects as well as a licensable component library.

So the Forms can still be used and you can focus on the .NET CORE/6 migration.


问:
How to run Python test case with Appium?
I've created simple test case using Python (in PyCharm editor) which should click on Join/Login button on iOS app, but it doesn't work. Here is the code:

```<code>from appium import webdriver
import unittest
import os

class LoginTests(unittest.TestCase):
    def setUp(self):
        desired_caps = {}
        desired_caps['platformName'] = 'iOS'
        desired_caps['platformVersion'] = '11.0'
        desired_caps['deviceName'] = 'iPhone Simulator' # Run on simulator
        desired_caps['bundleId'] = 'com.matchbook.MatchbookApp'
        desired_caps['app'] = os.path.abspath('/Users/majdukovic/Library/Developer/Xcode/DerivedData/MatchBook-bgvchkbwrithuaegnjgpoffewdag/Build/Products/Debug-iphonesimulator/MatchBook.app') # Path to .app
        self.wd = webdriver.Remote('http://0.0.0.0:4723/wd/hub', desired_caps)
        self.wd.implicitly_wait(60)
        loginButton = self.wd.find_element_by_id("JOIN/LOGIN") # Button ID
        self.assertTrue(loginButton.is_displayed())
        loginButton.click()

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(LoginTests)
    unittest.TextTestRunner(verbosity=2).run(suite)
</code>```

If I run this test case it returns:
"Ran 0 tests in 0.000s

OK"

Appium server is already running and app is opened. In PyCharm Preferences I've selected py.test as default test runner.

Details of my setup:

macOS - HighSierra v10.13

Appium desktop app - v1.2.6

Python - v2.7.10

xCode - v9.0.1

Simulator - iPhone 8, iOS v11.0

答:
File name should be test*.py , For example:

```<code>test1.py
</code>```

Function name should be test*, For example:

```<code>def test_testcase1(self):
</code>```

Body:
I've created simple test case using Python (in PyCharm editor) which should click on Join/Login button on iOS app, but it doesn't work. Here is the code:

from appium import webdriver
import unittest
import os

class LoginTests(unittest.TestCase):
    def setUp(self):
        desired_caps = {}
        desired_caps['platformName'] = 'iOS'
        desired_caps['platformVersion'] = '11.0'
        desired_caps['deviceName'] = 'iPhone Simulator' # Run on simulator
        desired_caps['bundleId'] = 'com.matchbook.MatchbookApp'
        desired_caps['app'] = os.path.abspath('/Users/majdukovic/Library/Developer/Xcode/DerivedData/MatchBook-bgvchkbwrithuaegnjgpoffewdag/Build/Products/Debug-iphonesimulator/MatchBook.app') # Path to .app
        self.wd = webdriver.Remote('http://0.0.0.0:4723/wd/hub', desired_caps)
        self.wd.implicitly_wait(60)
        loginButton = self.wd.find_element_by_id("JOIN/LOGIN") # Button ID
        self.assertTrue(loginButton.is_displayed())
        loginButton.click()

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(LoginTests)
    unittest.TextTestRunner(verbosity=2).run(suite)

If I run this test case it returns:
"Ran 0 tests in 0.000s

OK"

Appium server is already running and app is opened. In PyCharm Preferences I've selected py.test as default test runner.

Details of my setup:

macOS - HighSierra v10.13

Appium desktop app - v1.2.6

Python - v2.7.10

xCode - v9.0.1

Simulator - iPhone 8, iOS v11.0

Body:
File name should be test*.py , For example:

test1.py

Function name should be test*, For example:

def test_testcase1(self):


问:
process.env's are undefined - NestJS
I've decided to write here because I've ran out of ideas. I have a NestJS app in which I use env's - nothing unusual. But something strange happens when I want to use them. I also have my own parser of these values which returns them in a convenient object - that's the first file:

env.ts

```<code>const parseStringEnv = (name: string) => {
  const value: string = process.env[name];

  if (!value) {
    throw new Error(`Invalid env ${name}`);
  }

  return value;
};

const parseIntEnv = (name: string) => {
  const value: string = process.env[name];

  const int: number = parseInt(value);

  if (isNaN(int)) {
    throw new Error(`Invalid env ${name}`);
  }

  return int;
};

const parseBoolEnv = (name: string) => {
  const value: string = process.env[name];

  if (value === "false") {
    return false;
  }

  if (value === "true") {
    return true;
  }

  throw new Error(`Invalid env ${name}`);
};

const parseMongoString = (): string => {
  const host = parseStringEnv("DATABASE_HOST");
  const port = parseStringEnv("DATABASE_PORT");
  const user = parseStringEnv("DATABASE_USER");
  const pwd = parseStringEnv("DATABASE_PWD");
  const dbname = parseStringEnv("DATABASE_NAME");

  return `mongodb://${user}:${pwd}@${host}:${port}/${dbname}?authSource=admin&ssl=false`;
};

export const env = {
  JWT_SECRET: parseStringEnv("JWT_SECRET"),
  PORT_BACKEND: parseIntEnv("PORT_BACKEND"),
  CLIENT_HOST: parseStringEnv("CLIENT_HOST"),
  ENABLE_CORS: parseBoolEnv("ENABLE_CORS"),
  MONGO_URI: parseMongoString(),
};

export type Env = typeof env;

</code>```

I want to use it for setting port on which the app runs on and also the connection parameters for Mongoose:

In main.ts:

```<code><rest of the code>
await app.listen(env.PORT_BACKEND || 8080);
<rest of the code>
</code>```

Now, the magic starts here - the app starts just fine when ONLY ConfigModule is being imported. It will also start without ConfigModule and with require('doting').config() added. When I add MongooseModule, the app crashes because it can't parse env - and the best thing is that exception thrown has nothing to do with env's that are used to create MONGO_URI!! I'm getting "Invalid env JWT_SECRET" from my parser.

In app.module.ts

```<code>import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
import { MongooseModule } from "@nestjs/mongoose";

import { AppController } from "./app.controller";
import { env } from "./common/env";

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
    }),
    MongooseModule.forRoot(env.MONGO_URI), //WTF?
  ],
  controllers: [AppController],
})
export class AppModule {}
</code>```

I've honestly just ran out of ideas what could be wrong. The parser worked just fine in my last project (but I haven't used Mongoose so maybe that's what causes issues). Below is my .env file template.

```<code>JWT_SECRET=
ENABLE_CORS=
PORT_BACKEND=
DATABASE_HOST=
DATABASE_PORT=
DATABASE_USER=
DATABASE_PWD
DATABASE_NAME=
CLIENT_HOST=
</code>```

Thanks for everyone who has spent their time trying to help me ;)

答:
In my case just need to replace the order import module.

```<code>import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
import { MongooseModule } from "@nestjs/mongoose";

import { AppController } from "./app.controller";
import { env } from "./common/env"; // call process.env.xxx here > undefined

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
    }), // process.env.xxx must be called after this line
    MongooseModule.forRoot(env.MONGO_URI),
  ],
  controllers: [AppController],
})
export class AppModule {}
</code>```

so fix

```<code>import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
// should place this at very first line
const envModule = ConfigModule.forRoot({
   isGlobal: true,
})

import { MongooseModule } from "@nestjs/mongoose";

import { AppController } from "./app.controller";
import { env } from "./common/env";

@Module({
  imports: [
    envModule,
    MongooseModule.forRoot(env.MONGO_URI),
  ],
  controllers: [AppController],
})
export class AppModule {}
</code>```

Title: process.env's are undefined - NestJS

Body:
I've decided to write here because I've ran out of ideas. I have a NestJS app in which I use env's - nothing unusual. But something strange happens when I want to use them. I also have my own parser of these values which returns them in a convenient object - that's the first file:

env.ts

const parseStringEnv = (name: string) => {
  const value: string = process.env[name];

  if (!value) {
    throw new Error(`Invalid env ${name}`);
  }

  return value;
};

const parseIntEnv = (name: string) => {
  const value: string = process.env[name];

  const int: number = parseInt(value);

  if (isNaN(int)) {
    throw new Error(`Invalid env ${name}`);
  }

  return int;
};

const parseBoolEnv = (name: string) => {
  const value: string = process.env[name];

  if (value === "false") {
    return false;
  }

  if (value === "true") {
    return true;
  }

  throw new Error(`Invalid env ${name}`);
};

const parseMongoString = (): string => {
  const host = parseStringEnv("DATABASE_HOST");
  const port = parseStringEnv("DATABASE_PORT");
  const user = parseStringEnv("DATABASE_USER");
  const pwd = parseStringEnv("DATABASE_PWD");
  const dbname = parseStringEnv("DATABASE_NAME");

  return `mongodb://${user}:${pwd}@${host}:${port}/${dbname}?authSource=admin&ssl=false`;
};

export const env = {
  JWT_SECRET: parseStringEnv("JWT_SECRET"),
  PORT_BACKEND: parseIntEnv("PORT_BACKEND"),
  CLIENT_HOST: parseStringEnv("CLIENT_HOST"),
  ENABLE_CORS: parseBoolEnv("ENABLE_CORS"),
  MONGO_URI: parseMongoString(),
};

export type Env = typeof env;

I want to use it for setting port on which the app runs on and also the connection parameters for Mongoose:

In main.ts:

<rest of the code>
await app.listen(env.PORT_BACKEND || 8080);
<rest of the code>

Now, the magic starts here - the app starts just fine when ONLY ConfigModule is being imported. It will also start without ConfigModule and with require('doting').config() added. When I add MongooseModule, the app crashes because it can't parse env - and the best thing is that exception thrown has nothing to do with env's that are used to create MONGO_URI!! I'm getting "Invalid env JWT_SECRET" from my parser.

In app.module.ts

import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
import { MongooseModule } from "@nestjs/mongoose";

import { AppController } from "./app.controller";
import { env } from "./common/env";

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
    }),
    MongooseModule.forRoot(env.MONGO_URI), //WTF?
  ],
  controllers: [AppController],
})
export class AppModule {}

I've honestly just ran out of ideas what could be wrong. The parser worked just fine in my last project (but I haven't used Mongoose so maybe that's what causes issues). Below is my .env file template.

JWT_SECRET=
ENABLE_CORS=
PORT_BACKEND=
DATABASE_HOST=
DATABASE_PORT=
DATABASE_USER=
DATABASE_PWD
DATABASE_NAME=
CLIENT_HOST=

Thanks for everyone who has spent their time trying to help me ;)

Body:
In my case just need to replace the order import module.

import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
import { MongooseModule } from "@nestjs/mongoose";

import { AppController } from "./app.controller";
import { env } from "./common/env"; // call process.env.xxx here > undefined

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
    }), // process.env.xxx must be called after this line
    MongooseModule.forRoot(env.MONGO_URI),
  ],
  controllers: [AppController],
})
export class AppModule {}

so fix

import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
// should place this at very first line
const envModule = ConfigModule.forRoot({
   isGlobal: true,
})

import { MongooseModule } from "@nestjs/mongoose";

import { AppController } from "./app.controller";
import { env } from "./common/env";

@Module({
  imports: [
    envModule,
    MongooseModule.forRoot(env.MONGO_URI),
  ],
  controllers: [AppController],
})
export class AppModule {}


问:
How does jmock and mockito create wrappers?
For example, I have the following code:

```<code>SomeClass stub = Mockito.mock(SomeClass.class);
</code>```

After that, stub is a normal implementation of SomeClass, but with its own behavior (default is to just throw some exception, but that's ok)

How can I do the same thing for my library? I would like to be able to wrap some classes, or even better instances with some wrap() method, to mix-in my behavior there.

答: It's a proxy design pattern. Proxy implements mocked interface / extends mocked class, so it can be casted to the mocked type. It can also delegate responsibility to the 'real implementation' if required. Usually, such proxy stub is created with a little mix of reflection.

Body:
For example, I have the following code:

SomeClass stub = Mockito.mock(SomeClass.class);

After that, stub is a normal implementation of SomeClass, but with its own behavior (default is to just throw some exception, but that's ok)

How can I do the same thing for my library? I would like to be able to wrap some classes, or even better instances with some wrap() method, to mix-in my behavior there.