问:
Why is the event handler called twice?
I'm developing an React JS application that suppose to run on mobile devices.

Here is the code excerpts from the app:

index.tsx:

```<code>import React from 'react';
import ReactDOM from 'react-dom';

import './index.css';
import App from './App';

ReactDOM.render(
    <React.StrictMode>
        <App/>
    </React.StrictMode>,
    document.getElementById('root')
);
</code>```

App.tsx:

```<code>import React from 'react';
import './App.css';

import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';

import {Header} from "./Components/header"
import {Footer} from "./Components/footer"
import {Sidebar} from "./Components/sidebar"
//...

const listener = () => {
    console.log("Main listener")
};

function App() {

    const media = window.matchMedia('(min-width: 700px)');
    media.addEventListener("change", listener);

    return (
        <Router>
            <div className="App">

                <Header />
                <Sidebar />
                <Footer />

                //...

            </div>
        </Router>
    );
}

export default App;
</code>```

The problem is that the change event handler function (listener) is called TWICE! when I resize the browser window. I've read investigated that the reason for that is the React Strict Mode tag. As the official doc says the Strict Mode makes double-invoking the following functions:

Class component constructor, render, and shouldComponentUpdate
methods

Class component static getDerivedStateFromProps method

Function component bodies

State updater functions (the first argument    to setState)

Functions passed to useState, useMemo, or useReducer

My question is WHY the binded event is called TWICE since the doc doesn't list the event handlers as being double invoked!?

It that context WHAT finally makes the change event being invoked twice!?

答:
This is React's StrictMode proactively bringing a bug to your attention. You should not subscribe to events at the top level of a component function, because that's called every time the component is rendered, so every time you add a new subscription to the event. When you have multiple subscriptions to an event (on different event source objects), you get multiple callbacks to your event callback (one for each subscription).

Instead, subscribe once in a useEffect callback with an empty dependencies array (and unsubscribe from a cleanup callback you return from it), details here.

```<code>function App() {

    // An effect only called once on mount (empty deps array)
    useEffect(() => {
        // Subscribe once
        const media = window.matchMedia("(min-width: 700px)");
        media.addEventListener("change", listener);
        // Unsubscribe on unmount
        return () => {
            media.removeEventListener("change", listener);
        };
    }, []);

    // ...
}
</code>```

In a comment you've asked:

...can You please explain me WHY doesn't the following explicit multiple event subscription:

```<code>media.addEventListener("change", listener);
media.addEventListener("change", listener)
</code>```

Because in that code, you're calling addEventListener twice on the same MediaQueryList and passing in the same event handler (listener). If you add the same listener for the same event to the same object twice, the second time is ignored (by the DOM event system; different systems handle it differently).

But that's not what your component is doing. Your component function runs more than once, and each time it creates a new MediaQueryList and adds a handler to it, like this:

const listener = () => {
    console.log("listener fired");
};
const YourComponent = () => {
    const media = window.matchMedia("(min-width: 700px)");
    media.addEventListener("change", listener);
};
YourComponent();
YourComponent();```
</div>
</div>
</p>
<p>Or to put it even more clearly:</p>
```const media1 = window.matchMedia("(min-width: 700px)");
media1.addEventListener("change", listener);
const media2 = window.matchMedia("(min-width: 700px)");
media2.addEventListener("change", listener);
```

Since they're different MediaQueryList objects, the listener gets added every time (once to each object).

If you run that snippet then change your browser size so the listener fires, you'll see it fires twice.

Title: Why is the event handler called twice?

Body:
I'm developing an React JS application that suppose to run on mobile devices.

Here is the code excerpts from the app:

index.tsx:

import React from 'react';
import ReactDOM from 'react-dom';

import './index.css';
import App from './App';

ReactDOM.render(
    <React.StrictMode>
        <App/>
    </React.StrictMode>,
    document.getElementById('root')
);

App.tsx:

import React from 'react';
import './App.css';

import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';

import {Header} from "./Components/header"
import {Footer} from "./Components/footer"
import {Sidebar} from "./Components/sidebar"
//...

const listener = () => {
    console.log("Main listener")
};

function App() {

    const media = window.matchMedia('(min-width: 700px)');
    media.addEventListener("change", listener);

    return (
        <Router>

                <Sidebar />

                //...

        </Router>
    );
}

export default App;

The problem is that the change event handler function (listener) is called TWICE! when I resize the browser window. I've read investigated that the reason for that is the React Strict Mode tag. As the official doc says the Strict Mode makes double-invoking the following functions:

Class component constructor, render, and shouldComponentUpdate
methods

Class component static getDerivedStateFromProps method

Function component bodies

State updater functions (the first argument    to setState)

Functions passed to useState, useMemo, or useReducer

My question is WHY the binded event is called TWICE since the doc doesn't list the event handlers as being double invoked!?

It that context WHAT finally makes the change event being invoked twice!?

Body:
This is React's StrictMode proactively bringing a bug to your attention. You should not subscribe to events at the top level of a component function, because that's called every time the component is rendered, so every time you add a new subscription to the event. When you have multiple subscriptions to an event (on different event source objects), you get multiple callbacks to your event callback (one for each subscription).

Instead, subscribe once in a useEffect callback with an empty dependencies array (and unsubscribe from a cleanup callback you return from it), details here.

function App() {

    // An effect only called once on mount (empty deps array)
    useEffect(() => {
        // Subscribe once
        const media = window.matchMedia("(min-width: 700px)");
        media.addEventListener("change", listener);
        // Unsubscribe on unmount
        return () => {
            media.removeEventListener("change", listener);
        };
    }, []);

    // ...
}

In a comment you've asked:

...can You please explain me WHY doesn't the following explicit multiple event subscription:

media.addEventListener("change", listener);
media.addEventListener("change", listener)

Because in that code, you're calling addEventListener twice on the same MediaQueryList and passing in the same event handler (listener). If you add the same listener for the same event to the same object twice, the second time is ignored (by the DOM event system; different systems handle it differently).

But that's not what your component is doing. Your component function runs more than once, and each time it creates a new MediaQueryList and adds a handler to it, like this:

const listener = () => {
    console.log("listener fired");
};
const YourComponent = () => {
    const media = window.matchMedia("(min-width: 700px)");
    media.addEventListener("change", listener);
};
YourComponent();
YourComponent();

Or to put it even more clearly:

const media1 = window.matchMedia("(min-width: 700px)");
media1.addEventListener("change", listener);
const media2 = window.matchMedia("(min-width: 700px)");
media2.addEventListener("change", listener);

Since they're different MediaQueryList objects, the listener gets added every time (once to each object).

If you run that snippet then change your browser size so the listener fires, you'll see it fires twice.


来源: stackexchange

问:
openapi springboot generator jackson no String-argument constructor/factory method to deserialize from String value
I'm using OpenApi SpringBoot generator to generate controller interfaces and models. This creates model classes with JsonNullable<String> for nullable fields. However I'm getting a Jackson type definition error while POST request is sent with value present in a nullable field.

```<code>com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `org.openapitools.jackson.nullable.JsonNullable` (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('TG')
 at [Source: (PushbackInputStream); line: 3, column: 19] (through reference chain: com.example.rest.CreateRequest["displayName"])
    at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:67) ~[jackson-databind-2.9.7.jar:2.9.7]
    at com.fasterxml.jackson.databind.DeserializationContext.reportBadDefinition(DeserializationContext.java:1452) ~[jackson-databind-2.9.7.jar:2.9.7]
    at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1028) ~[jackson-databind-2.9.7.jar:2.9.7]
    at com.fasterxml.jackson.databind.deser.ValueInstantiator._createFromStringFallbacks(ValueInstantiator.java:371) ~[jackson-databind-2.9.7.jar:2.9.7]
    at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromString(StdValueInstantiator.java:323) ~[jackson-databind-2.9.7.jar:2.9.7]
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromString(BeanDeserializerBase.java:1373) ~[jackson-databind-2.9.7.jar:2.9.7]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:171) ~[jackson-databind-2.9.7.jar:2.9.7]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:161) ~[jackson-databind-2.9.7.jar:2.9.7]
    at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:127) ~[jackson-databind-2.9.7.jar:2.9.7]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:369) ~[jackson-databind-2.9.7.jar:2.9.7]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:159) ~[jackson-databind-2.9.7.jar:2.9.7]
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013) ~[jackson-databind-2.9.7.jar:2.9.7]
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3084) ~[jackson-databind-2.9.7.jar:2.9.7]
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:239) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:227) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:204) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:157) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:130) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:126) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
</code>```

Same thing happens for Integer or any other type. It works if the request contains only non-nullable fields.

Any idea what is going wrong here ?

答:
Solution working for me (in addition to the self-generated code from openapi yaml):

```<code><dependency>
    <groupId>org.openapitools</groupId>
    <artifactId>jackson-databind-nullable</artifactId>
    <version>0.2.1</version>
</dependency>
</code>```

Then in @Configuration class/es:

```<code>@Bean
public JsonNullableModule jsonNullableModule() {
    return new JsonNullableModule();
}
</code>```

and

```<code>@Bean
public RestTemplate restTemplate(ObjectMapper objectMapper) {
    var converter = new MappingJackson2HttpMessageConverter();
    converter.setObjectMapper(objectMapper);
    return new RestTemplateBuilder().additionalMessageConverters(converter).build();
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using OpenApi SpringBoot generator to generate controller interfaces and models. This creates model classes with JsonNullable<String> for nullable fields. However I'm getting a Jackson type definition error while POST request is sent with value present in a nullable field.

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `org.openapitools.jackson.nullable.JsonNullable` (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('TG')
 at [Source: (PushbackInputStream); line: 3, column: 19] (through reference chain: com.example.rest.CreateRequest["displayName"])
    at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:67) ~[jackson-databind-2.9.7.jar:2.9.7]
    at com.fasterxml.jackson.databind.DeserializationContext.reportBadDefinition(DeserializationContext.java:1452) ~[jackson-databind-2.9.7.jar:2.9.7]
    at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1028) ~[jackson-databind-2.9.7.jar:2.9.7]
    at com.fasterxml.jackson.databind.deser.ValueInstantiator._createFromStringFallbacks(ValueInstantiator.java:371) ~[jackson-databind-2.9.7.jar:2.9.7]
    at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromString(StdValueInstantiator.java:323) ~[jackson-databind-2.9.7.jar:2.9.7]
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromString(BeanDeserializerBase.java:1373) ~[jackson-databind-2.9.7.jar:2.9.7]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:171) ~[jackson-databind-2.9.7.jar:2.9.7]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:161) ~[jackson-databind-2.9.7.jar:2.9.7]
    at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:127) ~[jackson-databind-2.9.7.jar:2.9.7]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:369) ~[jackson-databind-2.9.7.jar:2.9.7]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:159) ~[jackson-databind-2.9.7.jar:2.9.7]
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013) ~[jackson-databind-2.9.7.jar:2.9.7]
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3084) ~[jackson-databind-2.9.7.jar:2.9.7]
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:239) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:227) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:204) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:157) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:130) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:126) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]

Same thing happens for Integer or any other type. It works if the request contains only non-nullable fields.

Any idea what is going wrong here ?

Body:
Solution working for me (in addition to the self-generated code from openapi yaml):

<dependency>
    <groupId>org.openapitools</groupId>
    <artifactId>jackson-databind-nullable</artifactId>
    <version>0.2.1</version>
</dependency>

Then in @Configuration class/es:

@Bean
public JsonNullableModule jsonNullableModule() {
    return new JsonNullableModule();
}

and

@Bean
public RestTemplate restTemplate(ObjectMapper objectMapper) {
    var converter = new MappingJackson2HttpMessageConverter();
    converter.setObjectMapper(objectMapper);
    return new RestTemplateBuilder().additionalMessageConverters(converter).build();
}


问:
Postgres Issue: prompt has changed
test=# SELECT COUNT(id) FROM person'

test'#

答:
psql is smart enough to guide us. Look at this simple session:

```<code>postgres=# select
postgres-# (          -- statement was not finished by semicolon
postgres(# select     -- parenthesis was opened, needs to be closed
postgres(# '
postgres'# abc        -- quote was opened, needs to be closed
postgres'# '          -- quote is still opened
postgres(# as x       -- quote was closed, parenthesis still opened
postgres(# )
postgres-# ;          -- parenthesis was closed, statement needs semicolon to completion
┌─────┐
│  x  │
├─────┤
│    ↵│
│ abc↵│
│     │
└─────┘
</code>```

The whole statement looks like

```<code>select (select 'abc' as x);
</code>```

without \n's

Title: Postgres Issue: prompt has changed

Body:
psql is smart enough to guide us. Look at this simple session:

postgres=# select
postgres-# (          -- statement was not finished by semicolon
postgres(# select     -- parenthesis was opened, needs to be closed
postgres(# '
postgres'# abc        -- quote was opened, needs to be closed
postgres'# '          -- quote is still opened
postgres(# as x       -- quote was closed, parenthesis still opened
postgres(# )
postgres-# ;          -- parenthesis was closed, statement needs semicolon to completion
┌─────┐
│  x  │
├─────┤
│    ↵│
│ abc↵│
│     │
└─────┘

The whole statement looks like

select (select 'abc' as x);

without \n's


问:
Mongoose - array of enum strings
I have a Schema that has a property with the type of array of strings that are predefined.

This is what I've tried to do:

interests: {
    type: [String],
    enum: ['football', 'basketball', 'read'],
    required: true
}
```
<p>The thing is that when I'm trying to enter a wrong value that isn't defined on the enum, to the array it wouldn't validate it with the enum list.</p>
<p>for example, this would pass which it shouldn't:</p>
<pre class="lang-js prettyprint-override"><code>{ "interests": ["football", "asdf"] }
</code>```

because "asdf" isn't predefined in the enum list it shouldn't pass the validation but unfortunately, it passes the validation and saves it.

I've tried to check this thing with a string type of values instead of an array of strings and it works.

for example:

interests: {
    type: String,
    enum: ['football', 'basketball', 'read'],
    required: true
}
```
<p>for example, this is failing as expected:</p>
<pre class="lang-js prettyprint-override"><code>{ "interest": "asdf" }
</code>```

In conclusion, I need a schema's property with a type of array of strings that would check it's elements based on predefined values

Is the most effective way to achieve this goal is by using the validate method or there is a better way?

答:
use ref to make a relation to the defined enum schema</p>
```<code>const actionsEnums = new Mongoose.Schema({value: { type: String, enum:["account-deletion","account-update"]}});

const Privilege = new Mongoose.Schema(
  {
    userLevel: { type: String, required: true },
    actions: [{type: String, refs: actionsEnums}],
})
</code>```

Title: Mongoose - array of enum strings

Body:
I have a Schema that has a property with the type of array of strings that are predefined.

This is what I've tried to do:

interests: {
    type: [String],
    enum: ['football', 'basketball', 'read'],
    required: true
}

The thing is that when I'm trying to enter a wrong value that isn't defined on the enum, to the array it wouldn't validate it with the enum list.

for example, this would pass which it shouldn't:

{ "interests": ["football", "asdf"] }

because "asdf" isn't predefined in the enum list it shouldn't pass the validation but unfortunately, it passes the validation and saves it.

I've tried to check this thing with a string type of values instead of an array of strings and it works.

for example:

interests: {
    type: String,
    enum: ['football', 'basketball', 'read'],
    required: true
}

for example, this is failing as expected:

{ "interest": "asdf" }

In conclusion, I need a schema's property with a type of array of strings that would check it's elements based on predefined values

Is the most effective way to achieve this goal is by using the validate method or there is a better way?

Body:
use ref to make a relation to the defined enum schema

const actionsEnums = new Mongoose.Schema({value: { type: String, enum:["account-deletion","account-update"]}});

const Privilege = new Mongoose.Schema(
  {
    userLevel: { type: String, required: true },
    actions: [{type: String, refs: actionsEnums}],
})


问:
Notifications don't seem to be fired from MPMoviePlayerController
I'm trying to get a simple video to play on an iPhone with iOS 4.3 and am running in to issues with dismissing the video player. Below is the code I have set up ... I'm listening for three different notification events to help signal when the movie player and its parent view should exit, but none of those events seem to get fired. My callback method is never invoked. </p>

```<code>NSString* moviePath = [[NSBundle mainBundle] pathForResource:@"sample1" ofType:@"m4v"];
NSLog(@"Here is the movie path: %@", moviePath);
NSURL* movieUrl = [NSURL fileURLWithPath:moviePath];
NSLog(@"Will now try to play movie at the following url: %@", movieUrl);
self.mpvc = [[MPMoviePlayerViewController alloc] initWithContentURL:movieUrl];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:self.mpvc.moviePlayer];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerFinished:) name:MPMoviePlayerDidExitFullscreenNotification object:self.mpvc.moviePlayer];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerFinished:) name:MPMoviePlayerWillExitFullscreenNotification object:self.mpvc.moviePlayer];
[[self.mpvc moviePlayer] prepareToPlay];
[[self.mpvc moviePlayer] setShouldAutoplay:YES];
[[self.mpvc moviePlayer] setFullscreen:YES];

[self.mpvc.view setFrame: self.view.bounds];  // player's frame must match parent's
[self.view addSubview:self.mpvc.view];
</code>```

答:
You probably did a mistake in registering the movie player callbacks. The object parameter should be self.mpvc instead of self.mpvc.moviePlayer. So try to replace your 3 lines with these:

```<code>[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:self.mpvc];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerFinished:) name:MPMoviePlayerDidExitFullscreenNotification object:self.mpvc];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerFinished:) name:MPMoviePlayerWillExitFullscreenNotification object:self.mpvc];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to get a simple video to play on an iPhone with iOS 4.3 and am running in to issues with dismissing the video player. Below is the code I have set up ... I'm listening for three different notification events to help signal when the movie player and its parent view should exit, but none of those events seem to get fired. My callback method is never invoked.

NSString* moviePath = [[NSBundle mainBundle] pathForResource:@"sample1" ofType:@"m4v"];
NSLog(@"Here is the movie path: %@", moviePath);
NSURL* movieUrl = [NSURL fileURLWithPath:moviePath];
NSLog(@"Will now try to play movie at the following url: %@", movieUrl);
self.mpvc = [[MPMoviePlayerViewController alloc] initWithContentURL:movieUrl];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:self.mpvc.moviePlayer];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerFinished:) name:MPMoviePlayerDidExitFullscreenNotification object:self.mpvc.moviePlayer];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerFinished:) name:MPMoviePlayerWillExitFullscreenNotification object:self.mpvc.moviePlayer];
[[self.mpvc moviePlayer] prepareToPlay];
[[self.mpvc moviePlayer] setShouldAutoplay:YES];
[[self.mpvc moviePlayer] setFullscreen:YES];

[self.mpvc.view setFrame: self.view.bounds];  // player's frame must match parent's
[self.view addSubview:self.mpvc.view];

Body:
You probably did a mistake in registering the movie player callbacks. The object parameter should be self.mpvc instead of self.mpvc.moviePlayer. So try to replace your 3 lines with these:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:self.mpvc];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerFinished:) name:MPMoviePlayerDidExitFullscreenNotification object:self.mpvc];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerFinished:) name:MPMoviePlayerWillExitFullscreenNotification object:self.mpvc];


问:
How to handle multiple path parameters in RestAssured?
We have a restAssured GET call:

```<code> public Response getRequest( final int survey_ID){
    httpRequest.header("Content-Type", ContentType.JSON);
    httpRequest.header("Authorization", System.getProperty("apiKey"));
    httpRequest.pathParams("survey_id", survey_ID);
    return httpRequest.get("/{survey_id}");
}
</code>```

Now there's new end-point which accepts multiple path parms like:

```<code> goals/check-enabled?survey_ids=54321,12345
</code>```

[Here Survey_ids could be 1 or many]

So, how could I handle this in my code?
I was thinking to implement something like below, but I suppose there could be a better way.

```<code>  public Response getRequest( final int[] survey_IDs){
    httpRequest.header("Content-Type", ContentType.JSON);
    httpRequest.header("Authorization",
    System.getProperty("apiKey"));
//        another Option
//        for(int survey_ID : survey_IDs){
//            httpRequest.pathParams("survey_id", survey_ID);
//        }
        return httpRequest.get("/{survey_ids}", survey_IDs);
    }
</code>```

Please suggest

Thanks a lot

答:
Right now you are having exactly ONE query parameter (because of the ?param=value syntax) even if it looks like a path parameter with a list.

You can choose between these options:

Specify a multi-value query parameter that'll be sent with the request e.g:

```<code>...given().queryParam("survey_ids", asList("54321", "12345"))...;
</code>```

This will set the parameter survey_ids=54321 and survey_ids=12345

The method needs to be adjusted this way:

```<code>public Response getRequest(List<Integer> survey_IDs) {
</code>```

Stay using one query parameter but split it.

```<code>String[] ids = survey_IDs.split(",");
</code>```
```<code>...given().queryParam("survey_ids", "54321,12345")...;
</code>```

Body:
We have a restAssured GET call:

 public Response getRequest( final int survey_ID){
    httpRequest.header("Content-Type", ContentType.JSON);
    httpRequest.header("Authorization", System.getProperty("apiKey"));
    httpRequest.pathParams("survey_id", survey_ID);
    return httpRequest.get("/{survey_id}");
}

Now there's new end-point which accepts multiple path parms like:

 goals/check-enabled?survey_ids=54321,12345

[Here Survey_ids could be 1 or many]

So, how could I handle this in my code?
I was thinking to implement something like below, but I suppose there could be a better way.

  public Response getRequest( final int[] survey_IDs){
    httpRequest.header("Content-Type", ContentType.JSON);
    httpRequest.header("Authorization",
    System.getProperty("apiKey"));
//        another Option
//        for(int survey_ID : survey_IDs){
//            httpRequest.pathParams("survey_id", survey_ID);
//        }
        return httpRequest.get("/{survey_ids}", survey_IDs);
    }

Please suggest

Thanks a lot

Body:
Right now you are having exactly ONE query parameter (because of the ?param=value syntax) even if it looks like a path parameter with a list.

You can choose between these options:

Specify a multi-value query parameter that'll be sent with the request e.g:

...given().queryParam("survey_ids", asList("54321", "12345"))...;

This will set the parameter survey_ids=54321 and survey_ids=12345

The method needs to be adjusted this way:

public Response getRequest(List<Integer> survey_IDs) {

Stay using one query parameter but split it.

String[] ids = survey_IDs.split(",");

...given().queryParam("survey_ids", "54321,12345")...;


问:
Generating input value on 2 previous filled inputs
I am trying to generate a input value based on 2 earlier input values the user filled in. First is a name, the second one is a date. Now I need to concat and format these 2 values and set them for another input.

This is what I already come up with:

Event listener for first input: Name

Format the Name value

Event listener for second input: Date

Format the Date value

Concat these 2 values

Set the concat value in third input

The code I have so far:

    window.onload = function () {

        /* event listener for first input: Name */
        document.getElementById('input_7_1').addEventListener('change', formatTitle);

        /* function to format the name value properly */
        function formatTitle(){
            document.getElementById('input_7_1').addEventListener("input", function(){
              var title = document.getElementById('input_7_1').value;
              var formatTitle = title.replace(/\s+/g, '');
            });
        }

        /* event listener for second input: Date */
        document.getElementById('input_7_3').addEventListener('change', formatDate);

        /* function to format the date value properly */
        function formatDate(){
            document.getElementById('input_7_3').addEventListener("input", function(){
              var date = document.getElementById('input_7_3').value.replace(/\//g, '');
              var formatDate = date.slice(0, -4);
            });
        }

        /* concat both values in a variable */
        var studentNummer = formatTitle.concat(formatDate);

        /* set value in the third input: Studentnummer */
        function generateInput(){
            document.getElementById('input_7_9').value = studentNummer;
        }
    }
```

I am almost there for my feeling. What am I missing here?

答:
I've simplified your code and made it much more understandable. Try this</p>
```<code>window.onload = function () {
    let studentNoField = document.getElementById('input_7_9');
    let enteredDetails = {name: '', date: ''};

    /* set value in the third input: Studentnummer */
    function generateInput(){
        let studentNumber = Object.values(enteredDetails).join('');
        studentNoField.value = studentNumber;
    }

    /* event listener for first input: Name */
    document.getElementById('input_7_1').addEventListener('input', function(event){
        enteredDetails.name = event.target.value.replace(/\s+/g, '');
        generateInput();
    });

    /* event listener for second input: Date */
    document.getElementById('input_7_3').addEventListener('input', function(event){
        enteredDetails.date = event.target.value.slice(0, -4);
        generateInput();
    });
}
</code>```

Body:
I am trying to generate a input value based on 2 earlier input values the user filled in. First is a name, the second one is a date. Now I need to concat and format these 2 values and set them for another input.

This is what I already come up with:

Event listener for first input: Name

Format the Name value

Event listener for second input: Date

Format the Date value

Concat these 2 values

Set the concat value in third input

The code I have so far:

    window.onload = function () {

        /* event listener for first input: Name */
        document.getElementById('input_7_1').addEventListener('change', formatTitle);

        /* function to format the name value properly */
        function formatTitle(){
            document.getElementById('input_7_1').addEventListener("input", function(){
              var title = document.getElementById('input_7_1').value;
              var formatTitle = title.replace(/\s+/g, '');
            });
        }

        /* event listener for second input: Date */
        document.getElementById('input_7_3').addEventListener('change', formatDate);

        /* function to format the date value properly */
        function formatDate(){
            document.getElementById('input_7_3').addEventListener("input", function(){
              var date = document.getElementById('input_7_3').value.replace(/\//g, '');
              var formatDate = date.slice(0, -4);
            });
        }

        /* concat both values in a variable */
        var studentNummer = formatTitle.concat(formatDate);

        /* set value in the third input: Studentnummer */
        function generateInput(){
            document.getElementById('input_7_9').value = studentNummer;
        }
    }

I am almost there for my feeling. What am I missing here?

Body:
I've simplified your code and made it much more understandable. Try this

window.onload = function () {
    let studentNoField = document.getElementById('input_7_9');
    let enteredDetails = {name: '', date: ''};

    /* set value in the third input: Studentnummer */
    function generateInput(){
        let studentNumber = Object.values(enteredDetails).join('');
        studentNoField.value = studentNumber;
    }

    /* event listener for first input: Name */
    document.getElementById('input_7_1').addEventListener('input', function(event){
        enteredDetails.name = event.target.value.replace(/\s+/g, '');
        generateInput();
    });

    /* event listener for second input: Date */
    document.getElementById('input_7_3').addEventListener('input', function(event){
        enteredDetails.date = event.target.value.slice(0, -4);
        generateInput();
    });
}


问:
Helm: UPGRADE FAILED: cannot patch ... with kind Job, by update field image
I'm trying to deploy updates. Installation works fine, but when I change the image field in the yaml file for Job and try to roll updates, an error occurs.

Error: UPGRADE FAILED: cannot patch "dev1-test-db-migrate-job" with kind Job: Job.batch "dev1-test-db-migrate-job" is invalid: spec.template: Invalid value: core.PodTemplateSpec{ObjectMeta:v1.ObjectMeta{Name:"", GenerateName:"", Namespace:"", SelfLink:"", UID:"", ResourceVersion:"", Generation:0, CreationTimestamp:v1.Time{Time:time.Time{wall:0x0, ext:0, loc:(*time.Location)(nil)}}, DeletionTimestamp:(*v1.Time)(nil), DeletionGracePeriodSeconds:(*int64)(nil), Labels:map[string]string{"controller-uid":"e60854c6-9a57-413c-8f19-175a755c9852", "job-name":"dev1-test-db-migrate-job", "target-app":"db-migrate", "target-domain":"dev1...", "target-service":"test"}, Annotations:map[string]string(nil), OwnerReferences:[]v1.OwnerReference(nil), Finalizers:[]string(nil), ClusterName:"", ManagedFields:[]v1.ManagedFieldsEntry(nil)}, Spec:core.PodSpec{Volumes:[]core.Volume(nil), InitContainers:[]core.Container(nil), Containers:[]core.Container{core.Container{Name:"app", Image:"...:insurance-master-682", Command:[]string{"/bin/sh", "-c"}, Args:[]string{"java -jar ./db/liquibase.jar --logLevel=debug --classpath=./db/mariadb-java-client-2.5.3.jar --driver=org.mariadb.jdbc.Driver --changeLogFile=./db/changelog-insurance.xml --url=$DB_HOST --username=$DB_USER --password=$DB_PASSWORD update"}, WorkingDir:"", Ports:[]core.ContainerPort(nil), EnvFrom:[]core.EnvFromSource{core.EnvFromSource{Prefix:"", ConfigMapRef:(*core.ConfigMapEnvSource)(nil), SecretRef:(*core.SecretEnvSource)(0xc01a48c8a0)}}, Env:[]core.EnvVar(nil), Resources:core.ResourceRequirements{Limits:core.ResourceList{"cpu":resource.Quantity{i:resource.int64Amount{value:200, scale:-3}, d:resource.infDecAmount{Dec:(*inf.Dec)(nil)}, s:"200m", Format:"DecimalSI"}, "memory":resource.Quantity{i:resource.int64Amount{value:268435456, scale:0}, d:resource.infDecAmount{Dec:(*inf.Dec)(nil)}, s:"", Format:"BinarySI"}}, Requests:core.ResourceList{"cpu":resource.Quantity{i:resource.int64Amount{value:100, scale:-3}, d:resource.infDecAmount{Dec:(*inf.Dec)(nil)}, s:"100m", Format:"DecimalSI"}, "memory":resource.Quantity{i:resource.int64Amount{value:134217728, scale:0}, d:resource.infDecAmount{Dec:(*inf.Dec)(nil)}, s:"", Format:"BinarySI"}}}, VolumeMounts:[]core.VolumeMount(nil), VolumeDevices:[]core.VolumeDevice(nil), LivenessProbe:(*core.Probe)(nil), ReadinessProbe:(*core.Probe)(nil), StartupProbe:(*core.Probe)(nil), Lifecycle:(*core.Lifecycle)(nil), TerminationMessagePath:"/dev/termination-log", TerminationMessagePolicy:"File", ImagePullPolicy:"IfNotPresent", SecurityContext:(*core.SecurityContext)(nil), Stdin:false, StdinOnce:false, TTY:false}}, EphemeralContainers:[]core.EphemeralContainer(nil), RestartPolicy:"Never", TerminationGracePeriodSeconds:(*int64)(0xc014591f78), ActiveDeadlineSeconds:(*int64)(nil), DNSPolicy:"ClusterFirst", NodeSelector:map[string]string(nil), ServiceAccountName:"", AutomountServiceAccountToken:(*bool)(nil), NodeName:"", SecurityContext:(*core.PodSecurityContext)(0xc010460000), ImagePullSecrets:[]core.LocalObjectReference{core.LocalObjectReference{Name:"artifactory-tradeplace-registry"}}, Hostname:"", Subdomain:"", Affinity:(*core.Affinity)(nil), SchedulerName:"default-scheduler", Tolerations:[]core.Toleration(nil), HostAliases:[]core.HostAlias(nil), PriorityClassName:"", Priority:(*int32)(nil), PreemptionPolicy:(*core.PreemptionPolicy)(nil), DNSConfig:(*core.PodDNSConfig)(nil), ReadinessGates:[]core.PodReadinessGate(nil), RuntimeClassName:(*string)(nil), Overhead:core.ResourceList(nil), EnableServiceLinks:(*bool)(nil), TopologySpreadConstraints:[]core.TopologySpreadConstraint(nil)}}: field is immutable

I still didn’t understand which field should be immutable, probably Image, but it’s very strange, it makes sense that I can embed Image.

The error occurs when I change the field Image from ...: insurance-master-682 to ...: insurance-master-681 for example

I change the chart file every time I install or update, I change the version field.
So, has anyone encountered this?
while I see the only way out is to apply 'kubectl delete job ...' before updating

part of yamls in 'templetes' directory:

```<code>apiVersion: batch/v1
kind: Job
metadata:
  labels:
    target-domain: dev1...
    target-service: test
  name: dev1-test-db-migrate-job
spec:
  backoffLimit: 0
  template:
    metadata:
      labels:
        target-app: db-migrate
        target-domain: dev1...
        target-service: test
    spec:
      containers:
        - args:
            - java -jar ./db/liquibase.jar --logLevel=debug --classpath=./db/mariadb-java-client-2.5.3.jar
              --driver=org.mariadb.jdbc.Driver --changeLogFile=./db/changelog-insurance.xml
              --url=$DB_HOST --username=$DB_USER --password=$DB_PASSWORD update
          command:
            - /bin/sh
            - -c
          envFrom:
            - secretRef:
                name: dev1-secret-config-deploy-for-app-gk5b59mb86
          image: ...:insurance-master-682
          imagePullPolicy: IfNotPresent
          name: app
          resources:
            limits:
              cpu: 200m
              memory: 256Mi
            requests:
              cpu: 100m
              memory: 128Mi
      imagePullSecrets:
        - name: artifactory-tradeplace-registry
      restartPolicy: Never
</code>```

Chart.yaml example

```<code>apiVersion: v2
name:
description: A Helm chart for Kubernetes
type: application
version: 0.1.20200505t154055
appVersion: 1.16.0
</code>```

答:
The existing job need to be deleted, because the template section in the job is immutable or not updatable. so you have 2 following options.

Always create a new job with a unique name, so it leaves the old jobs and creates a new one - every time if you include the version of image would be sensible.

Automatic cleaning of jobs (more info check here) - The job property ttlSecondsAfterFinished allows helps to delete the job automatically after a sepecified period.
for eg:

```<code>    apiVersion: batch/v1
    kind: Job
    metadata:
      name: pi-with-ttl
    spec:
      ttlSecondsAfterFinished: 100
      template:
        spec:
          containers:
          - name: pi
            image: perl
            command: ["perl",  "-Mbignum=bpi", "-wle", "print bpi(2000)"]
          restartPolicy: Never
</code>```

Body:
I'm trying to deploy updates. Installation works fine, but when I change the image field in the yaml file for Job and try to roll updates, an error occurs.

Error: UPGRADE FAILED: cannot patch "dev1-test-db-migrate-job" with kind Job: Job.batch "dev1-test-db-migrate-job" is invalid: spec.template: Invalid value: core.PodTemplateSpec{ObjectMeta:v1.ObjectMeta{Name:"", GenerateName:"", Namespace:"", SelfLink:"", UID:"", ResourceVersion:"", Generation:0, CreationTimestamp:v1.Time{Time:time.Time{wall:0x0, ext:0, loc:(*time.Location)(nil)}}, DeletionTimestamp:(*v1.Time)(nil), DeletionGracePeriodSeconds:(*int64)(nil), Labels:map[string]string{"controller-uid":"e60854c6-9a57-413c-8f19-175a755c9852", "job-name":"dev1-test-db-migrate-job", "target-app":"db-migrate", "target-domain":"dev1...", "target-service":"test"}, Annotations:map[string]string(nil), OwnerReferences:[]v1.OwnerReference(nil), Finalizers:[]string(nil), ClusterName:"", ManagedFields:[]v1.ManagedFieldsEntry(nil)}, Spec:core.PodSpec{Volumes:[]core.Volume(nil), InitContainers:[]core.Container(nil), Containers:[]core.Container{core.Container{Name:"app", Image:"...:insurance-master-682", Command:[]string{"/bin/sh", "-c"}, Args:[]string{"java -jar ./db/liquibase.jar --logLevel=debug --classpath=./db/mariadb-java-client-2.5.3.jar --driver=org.mariadb.jdbc.Driver --changeLogFile=./db/changelog-insurance.xml --url=$DB_HOST --username=$DB_USER --password=$DB_PASSWORD update"}, WorkingDir:"", Ports:[]core.ContainerPort(nil), EnvFrom:[]core.EnvFromSource{core.EnvFromSource{Prefix:"", ConfigMapRef:(*core.ConfigMapEnvSource)(nil), SecretRef:(*core.SecretEnvSource)(0xc01a48c8a0)}}, Env:[]core.EnvVar(nil), Resources:core.ResourceRequirements{Limits:core.ResourceList{"cpu":resource.Quantity{i:resource.int64Amount{value:200, scale:-3}, d:resource.infDecAmount{Dec:(*inf.Dec)(nil)}, s:"200m", Format:"DecimalSI"}, "memory":resource.Quantity{i:resource.int64Amount{value:268435456, scale:0}, d:resource.infDecAmount{Dec:(*inf.Dec)(nil)}, s:"", Format:"BinarySI"}}, Requests:core.ResourceList{"cpu":resource.Quantity{i:resource.int64Amount{value:100, scale:-3}, d:resource.infDecAmount{Dec:(*inf.Dec)(nil)}, s:"100m", Format:"DecimalSI"}, "memory":resource.Quantity{i:resource.int64Amount{value:134217728, scale:0}, d:resource.infDecAmount{Dec:(*inf.Dec)(nil)}, s:"", Format:"BinarySI"}}}, VolumeMounts:[]core.VolumeMount(nil), VolumeDevices:[]core.VolumeDevice(nil), LivenessProbe:(*core.Probe)(nil), ReadinessProbe:(*core.Probe)(nil), StartupProbe:(*core.Probe)(nil), Lifecycle:(*core.Lifecycle)(nil), TerminationMessagePath:"/dev/termination-log", TerminationMessagePolicy:"File", ImagePullPolicy:"IfNotPresent", SecurityContext:(*core.SecurityContext)(nil), Stdin:false, StdinOnce:false, TTY:false}}, EphemeralContainers:[]core.EphemeralContainer(nil), RestartPolicy:"Never", TerminationGracePeriodSeconds:(*int64)(0xc014591f78), ActiveDeadlineSeconds:(*int64)(nil), DNSPolicy:"ClusterFirst", NodeSelector:map[string]string(nil), ServiceAccountName:"", AutomountServiceAccountToken:(*bool)(nil), NodeName:"", SecurityContext:(*core.PodSecurityContext)(0xc010460000), ImagePullSecrets:[]core.LocalObjectReference{core.LocalObjectReference{Name:"artifactory-tradeplace-registry"}}, Hostname:"", Subdomain:"", Affinity:(*core.Affinity)(nil), SchedulerName:"default-scheduler", Tolerations:[]core.Toleration(nil), HostAliases:[]core.HostAlias(nil), PriorityClassName:"", Priority:(*int32)(nil), PreemptionPolicy:(*core.PreemptionPolicy)(nil), DNSConfig:(*core.PodDNSConfig)(nil), ReadinessGates:[]core.PodReadinessGate(nil), RuntimeClassName:(*string)(nil), Overhead:core.ResourceList(nil), EnableServiceLinks:(*bool)(nil), TopologySpreadConstraints:[]core.TopologySpreadConstraint(nil)}}: field is immutable

I still didn’t understand which field should be immutable, probably Image, but it’s very strange, it makes sense that I can embed Image.

The error occurs when I change the field Image from ...: insurance-master-682 to ...: insurance-master-681 for example

I change the chart file every time I install or update, I change the version field.
So, has anyone encountered this?
while I see the only way out is to apply 'kubectl delete job ...' before updating

part of yamls in 'templetes' directory:

apiVersion: batch/v1
kind: Job
metadata:
  labels:
    target-domain: dev1...
    target-service: test
  name: dev1-test-db-migrate-job
spec:
  backoffLimit: 0
  template:
    metadata:
      labels:
        target-app: db-migrate
        target-domain: dev1...
        target-service: test
    spec:
      containers:
        - args:
            - java -jar ./db/liquibase.jar --logLevel=debug --classpath=./db/mariadb-java-client-2.5.3.jar
              --driver=org.mariadb.jdbc.Driver --changeLogFile=./db/changelog-insurance.xml
              --url=$DB_HOST --username=$DB_USER --password=$DB_PASSWORD update
          command:
            - /bin/sh
            - -c
          envFrom:
            - secretRef:
                name: dev1-secret-config-deploy-for-app-gk5b59mb86
          image: ...:insurance-master-682
          imagePullPolicy: IfNotPresent
          name: app
          resources:
            limits:
              cpu: 200m
              memory: 256Mi
            requests:
              cpu: 100m
              memory: 128Mi
      imagePullSecrets:
        - name: artifactory-tradeplace-registry
      restartPolicy: Never

Chart.yaml example

apiVersion: v2
name:
description: A Helm chart for Kubernetes
type: application
version: 0.1.20200505t154055
appVersion: 1.16.0

Body:
The existing job need to be deleted, because the template section in the job is immutable or not updatable. so you have 2 following options.

Always create a new job with a unique name, so it leaves the old jobs and creates a new one - every time if you include the version of image would be sensible.

Automatic cleaning of jobs (more info check here) - The job property ttlSecondsAfterFinished allows helps to delete the job automatically after a sepecified period.
for eg:

    apiVersion: batch/v1
    kind: Job
    metadata:
      name: pi-with-ttl
    spec:
      ttlSecondsAfterFinished: 100
      template:
        spec:
          containers:
          - name: pi
            image: perl
            command: ["perl",  "-Mbignum=bpi", "-wle", "print bpi(2000)"]
          restartPolicy: Never


问:
Converting Julian to calendar date using pandas
I am trying to convert Julian codes to calendar dates in pandas using :

```<code>pd.to_datetime(43390, unit = 'D', origin = 'Julian')
</code>```

This is giving me ValueError: origin Julian cannot be converted to a Timestamp

答:
Below code works only for 6 digit julian value. It also handles the calendar date for leap and non-leap years.

A Julian date is considered as "CYYDDD". Where C represents century, YY represents Year and DDD represents total days which are then further defined in Days and Months.

```<code>    import pandas as pd
    from datetime import datetime
    jul_date = '120075'
    add_days = int(jul_date[3:6])
    cal_date = pd.to_datetime(datetime.strptime(str(19+int(jul_date[0:1]))+jul_date[1:3]+'-01-01','%Y-%m-%d'))-timedelta(1)+pd.DateOffset(days= add_days)
    print(cal_date.strftime('%Y-%m-%d'))
</code>```

output: 2020-03-15

without timedelta(1): 2020-03-16

Here datetime.strptime function is being used to cast date type from string to date.

%Y represents year in 4 digit (1980)

%m & %d represents month and day in digits.

strftime('%Y-%m-%d') is used to remove timestamp from the date.

timedelta(1) :- It's used to minus one day from the date because we've concatenated year with '01-01'. so when total no's of days being split to days and months, one day will not be extra.

Body:
I am trying to convert Julian codes to calendar dates in pandas using :

pd.to_datetime(43390, unit = 'D', origin = 'Julian')

This is giving me ValueError: origin Julian cannot be converted to a Timestamp

Body:
Below code works only for 6 digit julian value. It also handles the calendar date for leap and non-leap years.

A Julian date is considered as "CYYDDD". Where C represents century, YY represents Year and DDD represents total days which are then further defined in Days and Months.

    import pandas as pd
    from datetime import datetime
    jul_date = '120075'
    add_days = int(jul_date[3:6])
    cal_date = pd.to_datetime(datetime.strptime(str(19+int(jul_date[0:1]))+jul_date[1:3]+'-01-01','%Y-%m-%d'))-timedelta(1)+pd.DateOffset(days= add_days)
    print(cal_date.strftime('%Y-%m-%d'))

output: 2020-03-15

without timedelta(1): 2020-03-16

Here datetime.strptime function is being used to cast date type from string to date.

%Y represents year in 4 digit (1980)

%m & %d represents month and day in digits.

strftime('%Y-%m-%d') is used to remove timestamp from the date.

timedelta(1) :- It's used to minus one day from the date because we've concatenated year with '01-01'. so when total no's of days being split to days and months, one day will not be extra.


问:
cant import python module I just made on github
I want to learn how to make my own collection of functions available to myself and my coworkers. After some reading I settled on making a python package, putting it on github and using pip install git+https:// to make it available to my coworkers. We use anaconda by the way, not sure if it matters.

So I've made the following repository: https://github.com/accountname/reponame and in a fresh anaconda environment using:

```<code>conda create -n github_test python=3.9
</code>```

I will install my package into it using:

```<code>pip install git+https://github.com/accountname/reponame.git
</code>```

This worked! Great! When I run conda list  I get the following output:

```<code># packages in environment at C:\Users\MyName\anaconda3\envs\github_test:
#
# Name                    Version                   Build  Channel
ca-certificates           2021.10.26           haa95532_4
certifi                   2021.10.8        py39haa95532_2
openssl                   1.1.1m               h2bbff1b_0
pip                       21.2.4           py39haa95532_0
python                    3.9.7                h6244533_1
setuptools                58.0.4           py39haa95532_0
sqlite                    3.37.2               h2bbff1b_0
testing                   0.0.1                    pypi_0    pypi
tzdata                    2021e                hda174b7_0
vc                        14.2                 h21ff451_1
vs2015_runtime            14.27.29016          h5e58377_2
wheel                     0.37.1             pyhd3eb1b0_0
wincertstore              0.2              py39haa95532_2
</code>```

To test it out I decided to open python and import the new package:

```<code>(github_test) C:\Users\MyName>python
Python 3.9.7 (default, Sep 16 2021, 16:59:28) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import testing
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'testing'
>>>
</code>```

Importing any of the other modules on the list by the name on the list does work. So I'm thinking my setup.py file is missing some information.

```<code>import setuptools

setuptools.setup(
    name='testing',
    version='0.0.1',
    url='https://github.com/accountname/reponame',
    author='My Name',
    author_email='REDACTED',
    description='testing123',
    install_requires=[]
)
</code>```

I figure this would only work with a public repository. Ideally I would love to be able to use a private repository with this installation and distribution method. Any ideas?

Edits:

Removed my personal information

"Any ideas?" --> You can just point to a private repo and login using the prompt. Man what a time to be alive :D

答: The setuptools.setup call in setup.py seems to be missing a packages parameter. So you are distributing an empty Python project without any importable package. You probably need either packages=setuptools.find_packages() or packages=['testing'].

Body:
I want to learn how to make my own collection of functions available to myself and my coworkers. After some reading I settled on making a python package, putting it on github and using pip install git+https:// to make it available to my coworkers. We use anaconda by the way, not sure if it matters.

So I've made the following repository: https://github.com/accountname/reponame and in a fresh anaconda environment using:

conda create -n github_test python=3.9

I will install my package into it using:

pip install git+https://github.com/accountname/reponame.git

This worked! Great! When I run conda list  I get the following output:

# packages in environment at C:\Users\MyName\anaconda3\envs\github_test:
#
# Name                    Version                   Build  Channel
ca-certificates           2021.10.26           haa95532_4
certifi                   2021.10.8        py39haa95532_2
openssl                   1.1.1m               h2bbff1b_0
pip                       21.2.4           py39haa95532_0
python                    3.9.7                h6244533_1
setuptools                58.0.4           py39haa95532_0
sqlite                    3.37.2               h2bbff1b_0
testing                   0.0.1                    pypi_0    pypi
tzdata                    2021e                hda174b7_0
vc                        14.2                 h21ff451_1
vs2015_runtime            14.27.29016          h5e58377_2
wheel                     0.37.1             pyhd3eb1b0_0
wincertstore              0.2              py39haa95532_2

To test it out I decided to open python and import the new package:

(github_test) C:\Users\MyName>python
Python 3.9.7 (default, Sep 16 2021, 16:59:28) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import testing
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'testing'
>>>

Importing any of the other modules on the list by the name on the list does work. So I'm thinking my setup.py file is missing some information.

import setuptools

setuptools.setup(
    name='testing',
    version='0.0.1',
    url='https://github.com/accountname/reponame',
    author='My Name',
    author_email='REDACTED',
    description='testing123',
    install_requires=[]
)

I figure this would only work with a public repository. Ideally I would love to be able to use a private repository with this installation and distribution method. Any ideas?

Edits:

Removed my personal information

"Any ideas?" --> You can just point to a private repo and login using the prompt. Man what a time to be alive :D


问:
How do I change a button size in javascript
I'm using javascript to create buttons in a chrome extension but I can't find a way to change the size of the button, here's the code.

var buttonShort = document.createElement("button");
buttonShort.innerHTML = "Generate Short Password";

var body = document.getElementsByTagName("body")[0];
body.appendChild(buttonShort);

buttonShort.addEventListener ("click", function() {
  var newWindow = window.open();
  newWindow.document.write("The generated Password is: '" + short() + "'");
  newWindow.focus()
});```

I need to change the size of the button (mainly the width) so if you have any suggestions, please say. Also if you're going to say use CSS, I don't know how to add a CSS file to a javascript file so please tell me how to do that if you don't mind.

Thanks.

答:
put this into head tag:

```<code><style>
p.ex3 {
      font-size: 15px;
    }
</style>
</code>```

and put this into body:

```<code><div><p id="demo" class="ex0">Led Off</p></div>
<button type="button" onclick='document.getElementById("demo").innerHTML = "Led
On"'><p class="ex3">Led On</p></button>
</code>```

Body:
I'm using javascript to create buttons in a chrome extension but I can't find a way to change the size of the button, here's the code.

var buttonShort = document.createElement("button");
buttonShort.innerHTML = "Generate Short Password";

var body = document.getElementsByTagName("body")[0];
body.appendChild(buttonShort);

buttonShort.addEventListener ("click", function() {
  var newWindow = window.open();
  newWindow.document.write("The generated Password is: '" + short() + "'");
  newWindow.focus()
});

I need to change the size of the button (mainly the width) so if you have any suggestions, please say. Also if you're going to say use CSS, I don't know how to add a CSS file to a javascript file so please tell me how to do that if you don't mind.

Thanks.

Body:
put this into head tag:

<style>
p.ex3 {
      font-size: 15px;
    }
</style>

and put this into body:

<div><p id="demo" class="ex0">Led Off</p></div>
<button type="button" onclick='document.getElementById("demo").innerHTML = "Led
On"'><p class="ex3">Led On</p></button>


问:
How can I combine range() functions
For some code I'm writing, I need to iterate from 1-30 skipping 6. What I tried naively is

```<code>a = range(1,6)
b = range(7,31)

for i in a+b:
    print i
</code>```

Is there a way to do it more efficiently?

Title: How can I combine range() functions

Body:
For some code I'm writing, I need to iterate from 1-30 skipping 6. What I tried naively is

a = range(1,6)
b = range(7,31)

for i in a+b:
    print i

Is there a way to do it more efficiently?

Body:
I use list conversion:

>>> list(range(10,13)) + list(range(1,5))
[10, 11, 12, 1, 2, 3, 4]


问:
*this vs this in C++
I understand what this does, but what is the difference between *this and this?

Yes, I have Googled and read over *this in my text book, but I just don't get it...

答:
Case 1

this is a pointer to an object of a class, on which the non-static member function was called. Moreover, when used as an expression the value-category of this is prvalue.

When we call a non-static member function on an object of the class, the address of that object is implicitly passed as the first argument of that member function. This is possible because every non-static member function has an implicit parameter named this which is of type X* for a nonconst member function and const X* for a const member function, where X is some class.

Case 2

When we apply * on this the result is the object to which the pointer this was pointing. We are basically dereferencing the this pointer. That is, *this gives us the object to which the pointer this points. In other words, we get the object on which we called the non-static member function.

Moreover, when used as an expression the value category of *this is lvalue. Also, note that

The type of an expression is never a reference.

Note that lvalue expression is different from lvalue reference. The answer by Marcelo Cantos and comment by cigien seems to be confusion these two concepts.

Summary

this
*this

Pointer to an object of a class on which the non-static member function was called.
Result of dereferencing the this pointer. The result is the actual object on which the non-static member function was called.

prvalue-expression
lvalue-expression

Title: *this vs this in C++


问:
How to display website.com/a/b in the address bar instead of website.com/?x=a&y=b
It's possible to display parametres as a folders (order counts). How to do that?

As result, website.com/?x=a&y=b&z=c would look like website.com/a/b/c - shorter and easier.

Does it depend on server hosting settings? Should I contact hosting customer support about this question? Or, that's just a php issue (some options of $_GET method)?

Thank you.
P.S. How to differ website.com/?x=a and website.com/?y=b ?

答: You're looking for URL rewriting.</p>

Body: You're looking for URL rewriting.


问:
Why does the error occur "Cannot read properties of undefined (reading 'title')"
I have a code where I get data using the post method, but such an error occurs, what's the problem?
todos.js

```<code>router.post('/create', async (req, res) => {
    const todo = new Todo({
        title: req.body.title
    })
    todo.save();
</code>```

create.hbs

```<code><form action="/create" method="POST">
    <h2>Create todo</h2>

    <div class="input-field">
        <input type="text" name="title">
        <label>Todo title</label>
    </div>

    <button type="submit" class="btn">Create</button>
</form>
</code>```

index.js

```<code>const express = require('express');
const mongoose = require('mongoose');
const expressHandlebars = require('express-handlebars');
const PORT = process.env.PORT || 3000;
const todoRoutes = require('./routes/todos')
app.use(todoRoutes);
app.use(express.urlencoded({
    extended:true
}));
</code>```

答:
It appears that req.body is undefined.  That would mean that you don't have any middleware that is reading and parsing the body of the POST request and placing the results into req.body.

Since this is a regular form post, it will using the content-type application/x-www-form-urlencoded which can be parsed with the middleware express.urlencoded().

I see you have that middleware, but it is AFTER your route so it won't run before your route gets called.  Route handlers and middleware run in the order they are declared.  So, change this:

```<code>app.use(todoRoutes);
app.use(express.urlencoded({
    extended:true
}));
</code>```

to this:

```<code>app.use(express.urlencoded({
    extended:true
}));
app.use(todoRoutes);
</code>```

Also, keep in mind that you should be doing server-side validation of everything that the client sends.  In this case, you might be getting a request that doesn't have a title or has an empty title.  Your server should be checking for that and return a non 200 http status if you are getting bad data from the client.  Do not just assume that all the correct data has arrived with the incoming request.  Verify the data before using it.  This is the brute force dirty work that gives you a reliable server.

Body:
I have a code where I get data using the post method, but such an error occurs, what's the problem?
todos.js

router.post('/create', async (req, res) => {
    const todo = new Todo({
        title: req.body.title
    })
    todo.save();

create.hbs

<form action="/create" method="POST">

Create todo

        <input type="text" name="title">
        Todo title

    <button type="submit" class="btn">Create</button>
</form>

index.js

const express = require('express');
const mongoose = require('mongoose');
const expressHandlebars = require('express-handlebars');
const PORT = process.env.PORT || 3000;
const todoRoutes = require('./routes/todos')
app.use(todoRoutes);
app.use(express.urlencoded({
    extended:true
}));

Body:
It appears that req.body is undefined.  That would mean that you don't have any middleware that is reading and parsing the body of the POST request and placing the results into req.body.

Since this is a regular form post, it will using the content-type application/x-www-form-urlencoded which can be parsed with the middleware express.urlencoded().

I see you have that middleware, but it is AFTER your route so it won't run before your route gets called.  Route handlers and middleware run in the order they are declared.  So, change this:

app.use(todoRoutes);
app.use(express.urlencoded({
    extended:true
}));

to this:

app.use(express.urlencoded({
    extended:true
}));
app.use(todoRoutes);

Also, keep in mind that you should be doing server-side validation of everything that the client sends.  In this case, you might be getting a request that doesn't have a title or has an empty title.  Your server should be checking for that and return a non 200 http status if you are getting bad data from the client.  Do not just assume that all the correct data has arrived with the incoming request.  Verify the data before using it.  This is the brute force dirty work that gives you a reliable server.


问:
What does an overflow mean?
While I debug my flutter app, at certain points I see warnings like this:

Bottom overflow by 1234 pixel

BoxConstraints have a negative value

I suppose, my concept of Flutter viewport / layout isn't correct:

Currently, I image an infinite drawing area, where I declaratively
define widgets.

Widgets, which are too large, get drawn outside the
viewport [or clipped].

Could you please refine my probably wrong concept?

答: Generally overflow means, that the widget you want to paint on the screen crosses the border of the screen and therefore isn't visible anymore... This can also happen if you implement non scrollable columns in containers of a certain height... Usually, you can wrap your widget in a SingleChildScrollView widget and as a child choose a column/row (depending on the direction you want it to be aligned...) or make a list view and set the scrolldirection property to Axis.vertical or Axis.horizontal...</p>

Title: What does an overflow mean?


问:
In Ocaml, how do I avoid an unused variable warning if I don't want to use the variable?
Say I'm defining a recursive function on lists that looks something like:

let rec listFunc xs =
    match xs with
    | [] -> aThing
    | h :: t -> listFunc (tailFunc t)
;;
```

where tailFunc is some other function from lists to lists. The compiler will give me an unused variable warning since I didn't use h, but I can't just use the wildcard since I need to be able to access the tail of the list. How do I prevent the compiler from giving me a warning?

答:
You can prefix the h with an underscore.

```<code>let rec listFunc xs =
    match xs with
    | [] -> aThing
    | _h :: t -> listFunc (tailFunc t)
;;
</code>```

or simply:

```<code>let rec listFunc xs =
    match xs with
    | [] -> aThing
    | _ :: t -> listFunc (tailFunc t)
;;
</code>```

Any binding that starts with _ won't be in scope and won't give you unused  variable warnings.

Body:
Say I'm defining a recursive function on lists that looks something like:

let rec listFunc xs =
    match xs with
    | [] -> aThing
    | h :: t -> listFunc (tailFunc t)
;;

where tailFunc is some other function from lists to lists. The compiler will give me an unused variable warning since I didn't use h, but I can't just use the wildcard since I need to be able to access the tail of the list. How do I prevent the compiler from giving me a warning?

Body:
You can prefix the h with an underscore.

let rec listFunc xs =
    match xs with
    | [] -> aThing
    | _h :: t -> listFunc (tailFunc t)
;;

or simply:

let rec listFunc xs =
    match xs with
    | [] -> aThing
    | _ :: t -> listFunc (tailFunc t)
;;

Any binding that starts with _ won't be in scope and won't give you unused  variable warnings.


问:
R adding a new column in a data frame by recursivly filling 1:3 value based on another column
I have a dataframe, e.g.:

```<code>df <- data.frame(Group = rep(c("A", "B", "C"),  times = c(4, 4, 6))
> df
   Group
1      A
2      A
3      B
4      B
5      B
6      B
7      C
8      C
9      C
10     C
11     C
12     C
</code>```

I want to add a new column Type by recursively filling value 1:3 based on the Group column.

The resulting DF is like

```<code>> df2
   Group Type
1      A    1
2      A    2
3      B    1
4      B    2
5      B    3
6      B    1
7      C    1
8      C    2
9      C    3
10     C    1
11     C    2
12     C    3
</code>```

I don't know how to achieve this. Thanks a lot for your help

答:
Here is another dplyr solution using ifelse:

```<code>library(dplyr)

df %>%
  group_by(Group) %>%
  mutate(Type = 1:n(),
         Type = ifelse(Type>=4, Type-3, Type))
</code>```
```<code>Group  Type
   <chr> <dbl>
 1 A         1
 2 A         2
 3 B         1
 4 B         2
 5 B         3
 6 B         1
 7 C         1
 8 C         2
 9 C         3
10 C         1
11 C         2
12 C         3
</code>```

data:

```<code>structure(list(Group = c("A", "A", "B", "B", "B", "B", "C", "C",
"C", "C", "C", "C")), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"))
</code>```

Body:
I have a dataframe, e.g.:

df <- data.frame(Group = rep(c("A", "B", "C"),  times = c(4, 4, 6))
> df
   Group
1      A
2      A
3      B
4      B
5      B
6      B
7      C
8      C
9      C
10     C
11     C
12     C

I want to add a new column Type by recursively filling value 1:3 based on the Group column.

The resulting DF is like

> df2
   Group Type
1      A    1
2      A    2
3      B    1
4      B    2
5      B    3
6      B    1
7      C    1
8      C    2
9      C    3
10     C    1
11     C    2
12     C    3

I don't know how to achieve this. Thanks a lot for your help

Body:
Here is another dplyr solution using ifelse:

library(dplyr)

df %>%
  group_by(Group) %>%
  mutate(Type = 1:n(),
         Type = ifelse(Type>=4, Type-3, Type))

Group  Type
   <chr> <dbl>
 1 A         1
 2 A         2
 3 B         1
 4 B         2
 5 B         3
 6 B         1
 7 C         1
 8 C         2
 9 C         3
10 C         1
11 C         2
12 C         3

data:

structure(list(Group = c("A", "A", "B", "B", "B", "B", "C", "C",
"C", "C", "C", "C")), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"))


问:
Can the httr package make HTTPS calls?
Code that previously worked now throws an error due to the server requesting HTTPS calls and no longer accepts HTTP.

Can this code me modified to work? Or is a new process required for encrypted HTTPS?

Thank you!

```<code># Connecting to EIA API

# install.packages(c("httr", "jsonlite"))

library(httr)
library(jsonlite)

key <- "e77e9bd3c8bc84927fad13088f4bff28"

padd_key <- list('PET.MCRRIP12.M','PET.MCRRIP22.M',
                 'PET.MCRRIP32.M','PET.MCRRIP42.M',
                 'PET.MCRRIP52.M')
startdate <- "2010-01-01" #YYYY-MM-DD
enddate <- "2022-02-13" #YYYY-MM-DD

j = 0
for (i in padd_key) {

  url <- paste('http://api.eia.gov/series/?api_key=',key,'&series_id=',i,sep="")

  res <- GET(url)

  json_data <- fromJSON(rawToChar(res$content))
  data <- data.frame(json_data$series$data)
  data$Year <- substr(data$X1,1,4)
  data$Month <- substr(data$X1,5,6)
  data$Day <- 1

  data$Date <- as.Date(paste(data$Year, data$Month, data$Day, sep='-'))
  colnames(data)[2]  <- json_data$series$name
  data <- data[-c(1,3,4,5)]

  if (j == 0){
    data_final <- data
  }
  else{
    data_final <- merge(data_final,data,by="Date")
  }

  j = j + 1
}

data_final <- subset(data_final, Date >= startdate & Date <= enddate)
</code>```

答:
Yes, it can - you just use https in the URL.

The shortest demonstration I could think of is:

httr::GET("https://httpbin.org/get")
```
<p>In your code you just need to change the line where you define the <code>url</code> variable:</p>
<pre class="lang-r prettyprint-override"><code>url <- paste('https://api.eia.gov/series/?api_key=',key,'&series_id=',i,sep="")
</code>```

Title: Can the httr package make HTTPS calls?

Body:
Code that previously worked now throws an error due to the server requesting HTTPS calls and no longer accepts HTTP.

Can this code me modified to work? Or is a new process required for encrypted HTTPS?

Thank you!

# Connecting to EIA API

# install.packages(c("httr", "jsonlite"))

library(httr)
library(jsonlite)

key <- "e77e9bd3c8bc84927fad13088f4bff28"

padd_key <- list('PET.MCRRIP12.M','PET.MCRRIP22.M',
                 'PET.MCRRIP32.M','PET.MCRRIP42.M',
                 'PET.MCRRIP52.M')
startdate <- "2010-01-01" #YYYY-MM-DD
enddate <- "2022-02-13" #YYYY-MM-DD

j = 0
for (i in padd_key) {

  url <- paste('http://api.eia.gov/series/?api_key=',key,'&series_id=',i,sep="")

  res <- GET(url)

  json_data <- fromJSON(rawToChar(res$content))
  data <- data.frame(json_data$series$data)
  data$Year <- substr(data$X1,1,4)
  data$Month <- substr(data$X1,5,6)
  data$Day <- 1

  data$Date <- as.Date(paste(data$Year, data$Month, data$Day, sep='-'))
  colnames(data)[2]  <- json_data$series$name
  data <- data[-c(1,3,4,5)]

  if (j == 0){
    data_final <- data
  }
  else{
    data_final <- merge(data_final,data,by="Date")
  }

  j = j + 1
}

data_final <- subset(data_final, Date >= startdate & Date <= enddate)

Body:
Yes, it can - you just use https in the URL.

The shortest demonstration I could think of is:

httr::GET("https://httpbin.org/get")

In your code you just need to change the line where you define the url variable:

url <- paste('https://api.eia.gov/series/?api_key=',key,'&series_id=',i,sep="")


问:
Is it advisable to write a test case for every class in your program?
Im am just getting introduced to unit testing and test driven development. Thus far, I have only used Junit as testing framework. A question which emerged and for which I have not yet found a definite answer is: how much test cases do I need to write? Do I have to write a test case for every single class in my program? Or is this a stupid question because unit testing implies testing at the lowest (i.e. class) level?

I think writing a test case for every class is probably the more safe way to go (after all the more you test the lower the number of unforeseen bugs). But I was wondering if there are any widely agreed upon strategies regarding the amount of test cases to write?

答:
Though better than 1:1 ratio or over 100% coverage is ideal, in general I tend to abide by "test that which could possibly break".

This means only testing code with 'working parts'. This excludes POJOs, DTOs, thin wrapper/adapter classes and classes that only exist to fit a framework, and so on.

Also, "test only code that is under your control". This generally means not writing explicit tests for generated code—such as Web service clients generated from WSDL (but it still makes sense to cover them as part of tests written for your own classes).


答:
My guess is that you have your app.use() in the incorrect order. Expressjs executes these in order.

Update your index.js to

const express = require('express');
const mongoose = require('mongoose');
const expressHandlebars = require('express-handlebars');
const PORT = process.env.PORT || 3000;
const todoRoutes = require('./routes/todos')

const app = express()

app.use(express.urlencoded({
    extended:true
}));
app.use(todoRoutes);
```

Title: Why does the error occur "Cannot read properties of undefined (reading 'title')"


问:
Is it possible to use the % type wild card with IN operator
I'm currently analyzing string data and I want to view the count of specific words from a bunch of text.

I have something like these

```<code>SELECT
COUNT(text)
FROM review
WHERE text like "%hate%" or "%love%"
</code>```

but it returns counts for only "%hate%". When I switched it with "%love%" first it returns only counts for "%love%". How do I write the query so that it will return the total counts for a series of words?

答:
You can write</p>
```<code>SELECT    COUNT(text)
FROM review
WHERE text like "%hate%" or text like "%love%";
</code>```

Body:
I'm currently analyzing string data and I want to view the count of specific words from a bunch of text.

I have something like these

SELECT
COUNT(text)
FROM review
WHERE text like "%hate%" or "%love%"

but it returns counts for only "%hate%". When I switched it with "%love%" first it returns only counts for "%love%". How do I write the query so that it will return the total counts for a series of words?

Body:
You can write

SELECT    COUNT(text)
FROM review
WHERE text like "%hate%" or text like "%love%";


问:
Setting storybook SCSS import paths for angular library
I have Storybook set up at the root of an angular library.

To configure the SCSS import paths I have added the following to my library's ng-package.json:

```<code>"lib": {
  "styleIncludePaths": ["<some directory>"]
}
</code>```

However Storybook cannot find stylesheets from that directory.

If I add the following to the root's angular.json under architect > builder > build > options storybook will correctly resolve the import but the angular build will fail because angular.json fails validation:

```<code>"stylePreprocessorOptions": {
  "includePaths": ["<some directory>"]
}
</code>```

How can I make it so the include paths set for the library apply to Storybook, without having to override the default webpack config? Or how can I keep the defaults while only adding the custom include paths?

答:
Since Angular 13 style imports must be added in angular.json, under your-lib > storybook > options > styles. Don't forget to also add your styles to the build-storybook architect.

In your angular.json:

"your-lib": {
  ...
  "storybook": {
      "builder": "@nrwl/storybook:storybook",
      "options": {
          ...
          "projectBuildConfig": "your-lib:build-storybook",
          "styles": [
              "path-to-the-stylesheet/styles.scss",
              "path-to-the-stylesheet/your-theme.scss"
          ],
          ...
      },
      ...

    },
    ...
}
```

You can find this information in the migration-guide of storybook.

Body:
I have Storybook set up at the root of an angular library.

To configure the SCSS import paths I have added the following to my library's ng-package.json:

"lib": {
  "styleIncludePaths": ["<some directory>"]
}

However Storybook cannot find stylesheets from that directory.

If I add the following to the root's angular.json under architect > builder > build > options storybook will correctly resolve the import but the angular build will fail because angular.json fails validation:

"stylePreprocessorOptions": {
  "includePaths": ["<some directory>"]
}

How can I make it so the include paths set for the library apply to Storybook, without having to override the default webpack config? Or how can I keep the defaults while only adding the custom include paths?

Body:
Since Angular 13 style imports must be added in angular.json, under your-lib > storybook > options > styles. Don't forget to also add your styles to the build-storybook architect.

In your angular.json:

"your-lib": {
  ...
  "storybook": {
      "builder": "@nrwl/storybook:storybook",
      "options": {
          ...
          "projectBuildConfig": "your-lib:build-storybook",
          "styles": [
              "path-to-the-stylesheet/styles.scss",
              "path-to-the-stylesheet/your-theme.scss"
          ],
          ...
      },
      ...

    },
    ...
}

You can find this information in the migration-guide of storybook.


问:
Selenium via Eclipse: is it possible to move the cursor position?
I am using the selenium plug in for eclipse to automate the testing of newly created websites. I am trying to click a button that is in a menu and only visible when the cursor is located over the menu. </p>

<p>Is it possible to move the cursor so that this button can be clicked ? </p>

答:
It's unclear if you're using Selenium RC or Selenium 2 and WebDriver.

I can only speak to the latter, but you can use Actions to move the mouse and click.  The basic idea is you define an object that is a series of actions, and then you perform those actions.

An introduction on how to use these is at http://code.google.com/p/selenium/wiki/AdvancedUserInteractions, and a good writeup with Python examples is http://www.theautomatedtester.co.uk/blog/2011/selenium-advanced-user-interactions.html

It sounds like in your case, you would have something like:

```<code>Actions menuClick = new Actions(driver);

builder.MoveToElement(menuElement)
    .MoveToElement(buttonElement)
    .click(buttonElement)

Action menuClick = builder.build();

menuClick.perform();
</code>```

Body:
I am using the selenium plug in for eclipse to automate the testing of newly created websites. I am trying to click a button that is in a menu and only visible when the cursor is located over the menu.

Is it possible to move the cursor so that this button can be clicked ?

Body:
It's unclear if you're using Selenium RC or Selenium 2 and WebDriver.

I can only speak to the latter, but you can use Actions to move the mouse and click.  The basic idea is you define an object that is a series of actions, and then you perform those actions.

An introduction on how to use these is at http://code.google.com/p/selenium/wiki/AdvancedUserInteractions, and a good writeup with Python examples is http://www.theautomatedtester.co.uk/blog/2011/selenium-advanced-user-interactions.html

It sounds like in your case, you would have something like:

Actions menuClick = new Actions(driver);

builder.MoveToElement(menuElement)
    .MoveToElement(buttonElement)
    .click(buttonElement)

Action menuClick = builder.build();

menuClick.perform();


问:
How to make QTableView selection not affect QIcons/QPixmaps set by DecorationRole?
I'm using PyQt6 and have a custom QTableView and a custom QTableModel. The model's data method looks like this:

```<code>    def data(self, index: QModelIndex, role: Qt.ItemDataRole = Qt.ItemDataRole.DisplayRole):
        if role == Qt.ItemDataRole.DecorationRole:
            if not index.column():
                # print(index.row())
                artwork_pixmap = self._tracks[index.row()].artwork_pixmap
                artwork_pixmap = artwork_pixmap if artwork_pixmap else QPixmap(f"icons/album.png")
                icon = QIcon(artwork_pixmap)
                return icon
</code>```

_tracks is a list containing custom objects which have the pixmap I want to display, and if they don't then I just display default pixmap from image album.png. That all works fine, the QIcons get displayed in the first column. But once I select the row it also makes the QIcon blueish, which isn't what I want. And it makes it blueish regardless of the selection color set in the stylesheet of my view. Even if I set it's focus policy to NoFocus, it doesn't select anything on click but it still makes the QIcon in the row I clicked in turn blueish. Is there any way to prevent this?

Here is the example, the first row is the one I clicked in, the background color hasn't change because of NoFocus, but the QIcon became blueish in comparison to it's normal color.

答:
QIcon automatically creates alternate versions of the given pixmap for Disabled and Selected icon modes, the first is a grayed out version of the pixmap, the second overlays a layer based on the palette Highlight role.

To override those icons, just explicitly set the pixmap for the desired state with addPixmap():

    artwork_pixmap = self._tracks[index.row()].artwork_pixmap
    if not artwork_pixmap:
        artwork_pixmap = QPixmap("icons/album.png")
    icon = QIcon(artwork_pixmap)
    icon.addPixmap(artwork_pixmap, QtGui.QIcon.Selected)
    return icon
```

Body:
I'm using PyQt6 and have a custom QTableView and a custom QTableModel. The model's data method looks like this:

    def data(self, index: QModelIndex, role: Qt.ItemDataRole = Qt.ItemDataRole.DisplayRole):
        if role == Qt.ItemDataRole.DecorationRole:
            if not index.column():
                # print(index.row())
                artwork_pixmap = self._tracks[index.row()].artwork_pixmap
                artwork_pixmap = artwork_pixmap if artwork_pixmap else QPixmap(f"icons/album.png")
                icon = QIcon(artwork_pixmap)
                return icon

_tracks is a list containing custom objects which have the pixmap I want to display, and if they don't then I just display default pixmap from image album.png. That all works fine, the QIcons get displayed in the first column. But once I select the row it also makes the QIcon blueish, which isn't what I want. And it makes it blueish regardless of the selection color set in the stylesheet of my view. Even if I set it's focus policy to NoFocus, it doesn't select anything on click but it still makes the QIcon in the row I clicked in turn blueish. Is there any way to prevent this?

Here is the example, the first row is the one I clicked in, the background color hasn't change because of NoFocus, but the QIcon became blueish in comparison to it's normal color.


问:
Firebase: Error (auth/admin-restricted-operation)
I am doing firebase authentication using reactjs but I am unable to do it. its throwing an error, error message->  Firebase: Error (auth/admin-restricted-operation).
how am I restricted ? how come its an admin-restricted-operation...
I have gone through many solution but it didn't really help....
I even created a new project on firebase but the problem still persist...

file: firebaseConfig.js

```<code>import { initializeApp } from "firebase/app";
import { getAuth } from 'firebase/auth'

const firebaseConfig = {
    apiKey: "xxxxx",
    authDomain: "xxxxx",
    projectId: "xxxxx",
    storageBucket: "xxxxx",
    messagingSenderId: "xxxxx",
    appId: "xxxxx",
    measurementId: "xxxxx"
};

const app = initializeApp(firebaseConfig)
export default app
export const auth = getAuth(app)
</code>```

file: signUp.js

```<code>import React, {useState} from 'react'
import { createUserWithEmailAndPassword } from 'firebase/auth'
import { auth } from '../../firebaseConfig'

//css module import
import signupCard from './SignUp.module.css'

export const SignUp = props =>{

    //State....
    const [ credentials, setCredentials ] = useState({
        fnameRef: '',
        snameRef:'',
        phoneRef: '',
        cityRef: '',
        dobRef: '',
        emailRef: '',
        passwordRef: '',
        passwordConfirmationRef: ''
    })

    const signupHandler = async (event) =>{
        event.preventDefault()

        if(credentials.emailRef === '' && credentials.passwordRef === ''){
            console.log('empty fields!!')
        }else{
            try{
                const user = await createUserWithEmailAndPassword(auth, credentials.emailRef, credentials.passwordRef)
                console.log(user)
            }catch(error){
                console.log(error)
            }
        }

    }

    const backHandler = () => {
        props.backButtonDetails(true)
    }

    return(
        <React.Fragment>
            <div className = {signupCard.signupContainer}>

                <form onSubmit={signupHandler}>
                    <div className = {signupCard.signupFormFirst} >
                    <button onClick={backHandler} > back </button>
                        <span className = {signupCard.branding1}>SnowChild</span>
                        <hr className = {signupCard.hrTag}/>
                        <input type = 'text' className = {signupCard.fname} placeholder = 'firstname' id = 'Fname' onChange = {(event) => setCredentials({fnameRef: event.target.value})}/>
                        <input type = 'text' className = {signupCard.sname} placeholder = 'surname' id = 'Sname' onChange = {(event) => setCredentials({snameRef: event.target.value})}/>
                        <input type = 'text' className = {signupCard.phone} placeholder = 'phone' id = 'contact' onChange = {(event) => setCredentials({phoneRef: event.target.value})}/>
                        <input type = 'text' className = {signupCard.city} placeholder = 'city' id = 'Where' onChange = {(event) => setCredentials({cityRef: event.target.value})} />
                        <span className = {signupCard.dateString} >Date of birth</span>
                        <input type = 'date' className = {signupCard.dob} id = 'birthdate' onChange = {(event) => setCredentials({dobRef: event.target.value})}/>
                        <hr className = {signupCard.hrTag}  style = {{margin: '20px 0 10px 0'}}/>
                    </div>
                    <div className = {signupCard.signupFormSecond}>
                        <hr className = {signupCard.hrTag} />
                        <input type = 'email' placeholder = 'Email' className = {signupCard.UNF} id = 'email' onChange = {(event) => setCredentials({emailRef: event.target.value})}/>
                        <input type = 'password' placeholder = 'Password' className = {signupCard.PWD} id = 'password' onChange = {(event) => setCredentials({passwordRef: event.target.value})}/>
                        <input type = 'password' placeholder = 'confirmPassword' className = {signupCard.PWD} id = 'passwordConfirmation' onChange = {(event) => setCredentials({passwordConfirmationRef: event.target.value})}/>
                        <hr className = {signupCard.hrTag} style = {{marginTop: '10px'}}/>
                        <button type = 'submit' className={signupCard.signupButton}> Sign up </button>
                    </div>
                </form>
            </div>
            </React.Fragment>
    )
}
</code>```

what am I doing wrong ??

error

答:
so I find out the answer but I don't know the reason behind it! it is more of an hit and trial answer....

BEFORE:

```<code>const [ credentials, setCredentials ] = useState({
        fnameRef: '',
        snameRef:'',
        phoneRef: '',
        cityRef: '',
        dobRef: '',
        emailRef: '',
        passwordRef: '',
        passwordConfirmationRef: ''
    })
</code>```

AFTER:

```<code> const [currentUser, setCurrentUser ] = useState('')
    const [ credentials, setCredentials ] = useState({
        fnameRef: '',
        snameRef:'',
        phoneRef: '',
        cityRef: '',
        dobRef: ''
    })
    const [ emailRef, setEmailRef ] = useState('')
    const [ passwordRef, setPasswordRef] = useState('')
</code>```

so I convert ```emailRef and passwordRef``` to independent ```State Variables``` but Idk the explanation behind this.... but yeah it did work and now the user is being created.....

Body:
I am doing firebase authentication using reactjs but I am unable to do it. its throwing an error, error message->  Firebase: Error (auth/admin-restricted-operation).
how am I restricted ? how come its an admin-restricted-operation...
I have gone through many solution but it didn't really help....
I even created a new project on firebase but the problem still persist...

file: firebaseConfig.js

import { initializeApp } from "firebase/app";
import { getAuth } from 'firebase/auth'

const firebaseConfig = {
    apiKey: "xxxxx",
    authDomain: "xxxxx",
    projectId: "xxxxx",
    storageBucket: "xxxxx",
    messagingSenderId: "xxxxx",
    appId: "xxxxx",
    measurementId: "xxxxx"
};

const app = initializeApp(firebaseConfig)
export default app
export const auth = getAuth(app)

file: signUp.js

import React, {useState} from 'react'
import { createUserWithEmailAndPassword } from 'firebase/auth'
import { auth } from '../../firebaseConfig'

//css module import
import signupCard from './SignUp.module.css'

export const SignUp = props =>{

    //State....
    const [ credentials, setCredentials ] = useState({
        fnameRef: '',
        snameRef:'',
        phoneRef: '',
        cityRef: '',
        dobRef: '',
        emailRef: '',
        passwordRef: '',
        passwordConfirmationRef: ''
    })

    const signupHandler = async (event) =>{
        event.preventDefault()

        if(credentials.emailRef === '' && credentials.passwordRef === ''){
            console.log('empty fields!!')
        }else{
            try{
                const user = await createUserWithEmailAndPassword(auth, credentials.emailRef, credentials.passwordRef)
                console.log(user)
            }catch(error){
                console.log(error)
            }
        }

    }

    const backHandler = () => {
        props.backButtonDetails(true)
    }

    return(
        <React.Fragment>

                <form onSubmit={signupHandler}>

                    <button onClick={backHandler} > back </button>
                        SnowChild

                        <input type = 'text' className = {signupCard.fname} placeholder = 'firstname' id = 'Fname' onChange = {(event) => setCredentials({fnameRef: event.target.value})}/>
                        <input type = 'text' className = {signupCard.sname} placeholder = 'surname' id = 'Sname' onChange = {(event) => setCredentials({snameRef: event.target.value})}/>
                        <input type = 'text' className = {signupCard.phone} placeholder = 'phone' id = 'contact' onChange = {(event) => setCredentials({phoneRef: event.target.value})}/>
                        <input type = 'text' className = {signupCard.city} placeholder = 'city' id = 'Where' onChange = {(event) => setCredentials({cityRef: event.target.value})} />
                        Date of birth
                        <input type = 'date' className = {signupCard.dob} id = 'birthdate' onChange = {(event) => setCredentials({dobRef: event.target.value})}/>

                        <input type = 'email' placeholder = 'Email' className = {signupCard.UNF} id = 'email' onChange = {(event) => setCredentials({emailRef: event.target.value})}/>
                        <input type = 'password' placeholder = 'Password' className = {signupCard.PWD} id = 'password' onChange = {(event) => setCredentials({passwordRef: event.target.value})}/>
                        <input type = 'password' placeholder = 'confirmPassword' className = {signupCard.PWD} id = 'passwordConfirmation' onChange = {(event) => setCredentials({passwordConfirmationRef: event.target.value})}/>

                        <button type = 'submit' className={signupCard.signupButton}> Sign up </button>

                </form>

            </React.Fragment>
    )
}

what am I doing wrong ??

error

Body:
so I find out the answer but I don't know the reason behind it! it is more of an hit and trial answer....

BEFORE:

const [ credentials, setCredentials ] = useState({
        fnameRef: '',
        snameRef:'',
        phoneRef: '',
        cityRef: '',
        dobRef: '',
        emailRef: '',
        passwordRef: '',
        passwordConfirmationRef: ''
    })

AFTER:

 const [currentUser, setCurrentUser ] = useState('')
    const [ credentials, setCredentials ] = useState({
        fnameRef: '',
        snameRef:'',
        phoneRef: '',
        cityRef: '',
        dobRef: ''
    })
    const [ emailRef, setEmailRef ] = useState('')
    const [ passwordRef, setPasswordRef] = useState('')

so I convert ```emailRef and passwordRef``` to independent ```State Variables``` but Idk the explanation behind this.... but yeah it did work and now the user is being created.....