答:
Putting that stuff into test.log...

```<code>egrep -o  " loss: [0-9\.]* | accuracy: [0-9\.]* " test.log
 loss: 0.3430
 accuracy: 0.8753
 loss: 0.0849
 accuracy: 0.9739
 loss: 0.0742
 accuracy: 0.9791
 loss: 0.0565
 accuracy: 0.9841
 loss: 0.0409
 accuracy: 0.9881
</code>```

Title: How to parse a text file using regex

Body:
I'm trying to parse some log files to get some numbers out and into a CSV file. The log files have a lot of log messages but below is an excerpt of the lines that need to parse.

I'm trying to get the loss and accuracy numbers out of this text file below into a CSV. Any recommendations for bash or python tricks?

1500/1500 [==============================] - 1802s 1s/step - loss: 0.3430 - accuracy: 0.8753 - val_loss: 0.1110 - val_accuracy: 0.9670
Epoch 00002: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_02_0.069291627_0.98.h5
1500/1500 [==============================] - 1679s 1s/step - loss: 0.0849 - accuracy: 0.9739 - val_loss: 0.0693 - val_accuracy: 0.9807
Epoch 00003: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_03_0.055876694_0.98.h5
1500/1500 [==============================] - 1674s 1s/step - loss: 0.0742 - accuracy: 0.9791 - val_loss: 0.0559 - val_accuracy: 0.9845
Epoch 00004: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_04_0.053867317_0.99.h5
1500/1500 [==============================] - 1671s 1s/step - loss: 0.0565 - accuracy: 0.9841 - val_loss: 0.0539 - val_accuracy: 0.9850
Epoch 00005: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_05_0.053266536_0.99.h5
1500/1500 [==============================] - 1675s 1s/step - loss: 0.0409 - accuracy: 0.9881 - val_loss: 0.0533 - val_accuracy: 0.9855

Here is what I tried in python:

import re
text = r"""00 [==============================] - 1802s 1s/step - loss: 0.3430 - accuracy: 0.8753 - val_loss: 0.1110 - val_accuracy: 0.9670
Epoch 00002: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_02_0.069291627_0.98.h5
1500/1500 [==============================] - 1679s 1s/step - loss: 0.0849 - accuracy: 0.9739 - val_loss: 0.0693 - val_accuracy: 0.9807
Epoch 00003: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_03_0.055876694_0.98.h5
1500/1500 [==============================] - 1674s 1s/step - loss: 0.0742 - accuracy: 0.9791 - val_loss: 0.0559 - val_accuracy: 0.9845
Epoch 00004: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_04_0.053867317_0.99.h5
1500/1500 [==============================] - 1671s 1s/step - loss: 0.0565 - accuracy: 0.9841 - val_loss: 0.0539 - val_accuracy: 0.9850
Epoch 00005: saving model to /root/data-cache/data/tmp/models/ota-cfo-10k_20200527-001913_05_0.053266536_0.99.h5"""
regular_exp = re.compile(r'^.*val_accuracy.*$', re.M)
for match in regular_exp.finditer(text)
   print(match)

Body:
Putting that stuff into test.log...

egrep -o  " loss: [0-9\.]* | accuracy: [0-9\.]* " test.log
 loss: 0.3430
 accuracy: 0.8753
 loss: 0.0849
 accuracy: 0.9739
 loss: 0.0742
 accuracy: 0.9791
 loss: 0.0565
 accuracy: 0.9841
 loss: 0.0409
 accuracy: 0.9881


来源: stackexchange

问:
Javascript, I am not being able to cursor to input box
I can't set focus on html input, I tried this code, And it doesn't work.

```<code>document.getElementById('ember19').focus();
document.getElementById('ember19').click();
document.getElementById('ember19').select();
document.getElementById('ember19').value='Badman55555@hotmail.com';
document.getElementById('ember19').setAttribute('value','Badman55555@hotmail.com');

document.getElementById('ember22').focus();
document.getElementById('ember22').click();
document.getElementById('ember22').select();
document.getElementById('ember22').value='Bad123456';
document.getElementById('ember22').setAttribute('value','Bad123456');
</code>```

Please before answer try your code on this page

```<code>https://id.sonyentertainmentnetwork.com/signin/
</code>```

答:
Try using autofocus

```<code><input type="text" name="myInput" autofocus />
</code>```

https://www.w3schools.com/tags/att_autofocus.asp

ContentLicense: CC BY-SA 4.0

Body:
I can't set focus on html input, I tried this code, And it doesn't work.

document.getElementById('ember19').focus();
document.getElementById('ember19').click();
document.getElementById('ember19').select();
document.getElementById('ember19').value='Badman55555@hotmail.com';
document.getElementById('ember19').setAttribute('value','Badman55555@hotmail.com');

document.getElementById('ember22').focus();
document.getElementById('ember22').click();
document.getElementById('ember22').select();
document.getElementById('ember22').value='Bad123456';
document.getElementById('ember22').setAttribute('value','Bad123456');

Please before answer try your code on this page

https://id.sonyentertainmentnetwork.com/signin/

Body:
Try using autofocus

<input type="text" name="myInput" autofocus />

https://www.w3schools.com/tags/att_autofocus.asp


问:
Flutter: Setting constraints for package versions in pubspec.yaml
I used share package, share pacakge document said add like this,

```<code> share: ">=0.6.y+x <2.0.0"
</code>```

Please set your constraint to share: '>=0.6.y+x <2.0.0'

after run pub get, I got this error,

```<code>Error on line 65, column 10 of pubspec.yaml: Invalid version constraint: Expected version number after ">=" in ">=0.6.y+x <2.0.0", got "0.6.y+x <2.0.0".

   ╷

65 │   share: ">=0.6.y+x <2.0.0"

   │          ^^^^^^^^^^^^^^^^^^

   ╵
pub get failed (65;    ╵)
</code>```

答:
Actually it says to add it like this in the docs:

```<code>share: ^0.6.4+3
</code>```

This should work.

Body:
I used share package, share pacakge document said add like this,

 share: ">=0.6.y+x <2.0.0"

Please set your constraint to share: '>=0.6.y+x <2.0.0'

after run pub get, I got this error,

Error on line 65, column 10 of pubspec.yaml: Invalid version constraint: Expected version number after ">=" in ">=0.6.y+x <2.0.0", got "0.6.y+x <2.0.0".

   ╷

65 │   share: ">=0.6.y+x <2.0.0"

   │          ^^^^^^^^^^^^^^^^^^

   ╵
pub get failed (65;    ╵)

Body:
Actually it says to add it like this in the docs:

share: ^0.6.4+3

This should work.


问:
How to open multiple files and switch between them in nano text editor?
In emacs, you can open new files with Ctrl+X,  Ctrl+F

And go to the previous file with Ctrl+B, and go to the next file with Ctrl+N.

How to do this in nano text editor? While nano is launched, and then open new files, and how to switch between the opened files in the nano text editor?

答:
To switch between open files in nano

alt+. -- move forward one file

alt+, -- move back one file

Steps

Open as many files as you want by listing them as separate arguments to nano, like so:

```<code>nano file1.txt file2.log file3.c file4.js file5.py
</code>```

The first file is opened, e.g. file1.txt. Use the keyboard shortcuts below to switch between the files.

alt+. -- move forward one file

alt+, -- move back one file

nano --version GNU nano, version 2.9.3

ContentLicense: CC BY-SA 3.0

Body:
To switch between open files in nano

alt+. -- move forward one file

alt+, -- move back one file

Steps

Open as many files as you want by listing them as separate arguments to nano, like so:

nano file1.txt file2.log file3.c file4.js file5.py

The first file is opened, e.g. file1.txt. Use the keyboard shortcuts below to switch between the files.

alt+. -- move forward one file

alt+, -- move back one file

nano --version GNU nano, version 2.9.3


问:
How to perform a room transaction usin Rxjava
How can I do a room transaction across 2 different DAOs usin rxjava?

I have this code that I would like to use with Rxjava  but I need it to return some kind of observable

```<code> @Transaction
fun insertStoreWithPictures(store: Store, pictures: List<StorePicture>) {

    insertStore(store)
    insertPictures(pictures)

}
</code>```

The store DAO

```<code>@Dao
abstract public class store {

@Insert
Single<Long> insert(store  entity);
}
</code>```

The storePicture DAO

```<code>@Dao
abstract public class storePicture {

    @Insert
    Completable insert(storePicture... entity);
}
</code>```

答: Best example you can follow to achieve the same - https://blog.mindorks.com/understanding-rxjava-zip-operator-with-example</p>

Body:
How can I do a room transaction across 2 different DAOs usin rxjava?

I have this code that I would like to use with Rxjava  but I need it to return some kind of observable

 @Transaction
fun insertStoreWithPictures(store: Store, pictures: List<StorePicture>) {

    insertStore(store)
    insertPictures(pictures)

}

The store DAO

@Dao
abstract public class store {

@Insert
Single<Long> insert(store  entity);
}

The storePicture DAO

@Dao
abstract public class storePicture {

    @Insert
    Completable insert(storePicture... entity);
}


问:
How to get Map object in react-leaflet on zoom change event
I am using react-leaflet for showing non-geographical map.
I also added some event for zoom changing. (onZoomEnd())

I wonder how to access map object or map component and get current zoom level. Or other maps props?

```<code>  <Map
                center={this.getCalculatedCenterFromState()}
                zoom={this.getCalculatedZoomFromState()}
                minZoom={this.getCalculatedMinZoomFromState()}
                maxZoom={2}
                onZoomEnd={this.mapService.handleZoomstart(/* map.object */)}

               >
</Map
</code>```

I need to access map object in handler method

```<code>handleZoomstart = (map) => {
        // TODO handle move event
    };
</code>```

答:
I just solved the above problem quite simply. React leaflet provides a nice "onViewportChange" callback that captures center and zoom changes when using the map.

You need three things, the declared "Viewport" object, a function that supports callback
and callback.

```<code>const viewport = {
center: [49.32707, 19.10041],
zoom: 5,
};

const onViewportChanged = (viewport) => {
console.log(viewport);
};

return (

<Map viewport={viewport} onViewportChanged={onViewportChanged}></Map>)
</code>```

Best regards

Body:
I am using react-leaflet for showing non-geographical map.
I also added some event for zoom changing. (onZoomEnd())

I wonder how to access map object or map component and get current zoom level. Or other maps props?

  <Map
                center={this.getCalculatedCenterFromState()}
                zoom={this.getCalculatedZoomFromState()}
                minZoom={this.getCalculatedMinZoomFromState()}
                maxZoom={2}
                onZoomEnd={this.mapService.handleZoomstart(/* map.object */)}

               >
</Map

I need to access map object in handler method

handleZoomstart = (map) => {
        // TODO handle move event
    };

Body:
I just solved the above problem quite simply. React leaflet provides a nice "onViewportChange" callback that captures center and zoom changes when using the map.

You need three things, the declared "Viewport" object, a function that supports callback
and callback.

const viewport = {
center: [49.32707, 19.10041],
zoom: 5,
};

const onViewportChanged = (viewport) => {
console.log(viewport);
};

return (

<Map viewport={viewport} onViewportChanged={onViewportChanged}></Map>)

Best regards


问:
FactoryPattern with derived generic classes
This is a short snipped that gets to the point, I hid details that irrelevant. The goal is to make my factory work with my generics designed types. At the end of the post I have my two observations.

Interface

```<code>public interface IWorker<T> where T : IWorkload
{
    T CraftWorkload(string plainWorkload);
    Task DoWork(T workload);
}
</code>```

IWorkload

```<code>public interface IWorkload
{
    // some properties
}
</code>```

Base class

```<code>internal abstract class Worker<T> : IWorker<T> where T : IWorkload
{
    public T CraftWorkload(string workAsJsonString)
    {
        return JsonConvert.DeserializeObject<T>(workAsJsonString, new JsonSerializerSettings
        {
            MissingMemberHandling = MissingMemberHandling.Error
        });
    }

    public abstract Task DoWork(T workload);
}
</code>```

Another derived base class

```<code>internal abstract class RestWorker<T> : Worker<T> where T : IWorkload
{
  // this is a worker that interact with http requests
}
</code>```

Concrete workers

```<code>internal class WorkerA: RestWorker<WorkerA_Workload>
{
    public override Task DoWork(WorkerA_Workload workload)
    {
    }
}

internal abstract class WorkerB: Worker<WorkerB_Workload>
{
    public override Task DoWork(WorkerB_Workload workload)
    {
    }
}
</code>```

WorkersFactory

MessageType is an enum that identifies a worker with a type

```<code>internal interface IWorkerFactory
{
    IWorker<IWorkload> GetWorker(MessageType type);
}

internal class WorkerFactory : IWorkerFactory
{
    public IWorker<IWorkload> GetWorker(MessageType type)
    {
        switch (type)
        {
            case MessageType.WorkerA:
                return new WorkerA() as IWorker<IWorkload>;
            case MessageType.WorkerB:
                return new WorkerB() as IWorker<IWorkload>;
           .
           .
           .
           .
           .
            default:
                throw new ArgumentException("The type must be a type that maps to an available worker");
        }
    }
}
</code>```

Two observation:

If I change the Factory to return without the implicit casting to IWorker<IWorkload> it gets confused

If I cast (as shown in the code) it returns null

Is my inheritance makes sense?

答:
Your IWorker<T> interface represents a worker that is able to both produce objects of type T, and consume objects of type T (since it uses T as both a parameter to a method and a return type of a method).  That means an IWorker<IWorkload> is an object that is able to produce objects of type IWorkload, which WorkerA and WorkerB can do, as the WorkerA_Workload and WorkerB_Workload objects they produce are IWorkload objects.  But it also means that an IWorker<IWorkload> needs to be able to accept *any IWorkload and do work on it.  Neither WorkerA nor WorkerB can do that.  They can only accept WorkerA_Workload and WorkerB_Workload inputs respectively, but in order to implement the interface of IWorker<IWorkload> they would need to be able to accept any other type of workload.

If your workers can actually accept any IWorkload, and they don't actually need to accept a specific type of workload, then you need to adjust your code to basically remove all generic types constrained to IWorkload and instead just use a non-generic IWorkload type in all of those places.  (You'll also need to make IWorker<T> covariant with respect to T.)

If your workers can't actually accept any IWorkload, and need a specific type of workload, then you can't treat all of your workers as an IWorker<IWorkload>, you need to always treat them as an IWorker<T> where T is the actual specific workload type they can accept.

Body:
This is a short snipped that gets to the point, I hid details that irrelevant. The goal is to make my factory work with my generics designed types. At the end of the post I have my two observations.

Interface

public interface IWorker<T> where T : IWorkload
{
    T CraftWorkload(string plainWorkload);
    Task DoWork(T workload);
}

IWorkload

public interface IWorkload
{
    // some properties
}

Base class

internal abstract class Worker<T> : IWorker<T> where T : IWorkload
{
    public T CraftWorkload(string workAsJsonString)
    {
        return JsonConvert.DeserializeObject<T>(workAsJsonString, new JsonSerializerSettings
        {
            MissingMemberHandling = MissingMemberHandling.Error
        });
    }

    public abstract Task DoWork(T workload);
}

Another derived base class

internal abstract class RestWorker<T> : Worker<T> where T : IWorkload
{
  // this is a worker that interact with http requests
}

Concrete workers

internal class WorkerA: RestWorker<WorkerA_Workload>
{
    public override Task DoWork(WorkerA_Workload workload)
    {
    }
}

internal abstract class WorkerB: Worker<WorkerB_Workload>
{
    public override Task DoWork(WorkerB_Workload workload)
    {
    }
}

WorkersFactory

MessageType is an enum that identifies a worker with a type

internal interface IWorkerFactory
{
    IWorker<IWorkload> GetWorker(MessageType type);
}

internal class WorkerFactory : IWorkerFactory
{
    public IWorker<IWorkload> GetWorker(MessageType type)
    {
        switch (type)
        {
            case MessageType.WorkerA:
                return new WorkerA() as IWorker<IWorkload>;
            case MessageType.WorkerB:
                return new WorkerB() as IWorker<IWorkload>;
           .
           .
           .
           .
           .
            default:
                throw new ArgumentException("The type must be a type that maps to an available worker");
        }
    }
}

Two observation:

If I change the Factory to return without the implicit casting to IWorker<IWorkload> it gets confused

If I cast (as shown in the code) it returns null

Is my inheritance makes sense?


问:
Select text in react-select
I'm able to focus a react-select programmatically, but I can't select the text in the input field.

I'm getting a reference to react-select like so:

```<code>const selectRef = useRef()
...
<Select
  ref={selectRef}
  // other props
</Select>
</code>```

And then:

```<code>selectRef.current.focus()
selectRef.current.select()
</code>```

Select focuses successfully, but for the second line (which I believe should work on an input element) I get:

```<code>TypeError: selectRef.current.select is not a function
</code>```

How do I select text inside the react-select's input field?

答:
The reason your code doesn't work is because the ref to the Select component is not the same as the innerRef to the input. You would access it instead via the following object chain...

selectRef -> current (StateManager) -> select(Select Component) -> inputRef (Input Component)

```<code>selectRef.current.select.inputRef.select()

</code>```

Title: Select text in react-select

Body:
I'm able to focus a react-select programmatically, but I can't select the text in the input field.

I'm getting a reference to react-select like so:

const selectRef = useRef()
...
<Select
  ref={selectRef}
  // other props
</Select>

And then:

selectRef.current.focus()
selectRef.current.select()

Select focuses successfully, but for the second line (which I believe should work on an input element) I get:

TypeError: selectRef.current.select is not a function

How do I select text inside the react-select's input field?

Body:
The reason your code doesn't work is because the ref to the Select component is not the same as the innerRef to the input. You would access it instead via the following object chain...

selectRef -> current (StateManager) -> select(Select Component) -> inputRef (Input Component)

selectRef.current.select.inputRef.select()


问:
Lambda functions in python bypass object link
I understand how it's work, but how I can do that python print true and false in this case?)</p>

```<code>def f(func, value):
        global a
        a = 2
        print(func(value))

a = 3
f(lambda x: x == a, 3)
f(lambda x: x == a, 2)
</code>```

答:
If your goal is to have the code check the value of a that you originally declared (i.e. 3) so that it prints True;False instead of the inverse, just don't set a to 2 inside your function:

```<code>def f(func, value):
        print(func(value))

a = 3
f(lambda x: x == a, 3)
f(lambda x: x == a, 2)
</code>```

Using global is generally not recommended because it makes it very easy to confuse yourself by having values change in unexpected ways.

Body:
I understand how it's work, but how I can do that python print true and false in this case?)

def f(func, value):
        global a
        a = 2
        print(func(value))

a = 3
f(lambda x: x == a, 3)
f(lambda x: x == a, 2)

Body:
If your goal is to have the code check the value of a that you originally declared (i.e. 3) so that it prints True;False instead of the inverse, just don't set a to 2 inside your function:

def f(func, value):
        print(func(value))

a = 3
f(lambda x: x == a, 3)
f(lambda x: x == a, 2)

Using global is generally not recommended because it makes it very easy to confuse yourself by having values change in unexpected ways.


问:
How to consolidate / eliminate PHP includes for class files
I have multiple files that I keep including individually.  I want to just put them all in one file to decrease file I/O and just have one include.

Update

Ended up using an auto-loader here is the php.net reference.  Now I don't have to explicitly include each file and according to the reference the files are lazy loaded.

答:
PHP will parse the file. PHP will probably register the classes, and will in any case parse and syntax check the file. But this might still be faster than loading separate files. More separate file I/O will be slower, though it will require less memory because only the needed files are loaded.

I wouldn't worry about either, because memory consuption for the classes alone is close to nil. File I/O will probably not be a problem either. You may have APC cache, which keeps compiled versions of the PHP files into memory, and if not, your OS will probably have some caching features which cause often used files to be loaded faster.


问:
Passing date to Stored Procedure in Oracle SQL error : ORA-01858
I know this question has been answered previously, and I have tried out the solution given in them without success.

I have a stored procedure as below(I have removed non-essential parts) :

```<code>CREATE OR REPLACE PROCEDURE get_days(dt date)
IS
  given_date DATE := TO_DATE('dt', 'DD-MON-YYYY');
BEGIN
  get_day := RTRIM(TO_CHAR(dt1, 'DAY'));
  DBMS_OUTPUT.PUT_LINE ('The day of the given date is '||get_day||);
  DBMS_OUTPUT.PUT_LINE ('Execution  done successfully.');
END get_days;
</code>```

I am having trouble with passing date to the procedure get_days. I have tried in the following ways :

```<code>BEGIN
  --Below I have listed all ways I have tried
  get_days('12/12/12');
  get_days('12-12-12');
  get_days(date '2012-12-12');
  get_days(TO_DATE( '01/01/2018', 'MM/DD/YYYY' ));
END;
</code>```

I don't know what is wrong but I am getting this error - ORA-01858: a non-numeric character was found where a numeric was expected. I have searched for similar errors online but none helped. I am using Oracle Database 11g Express edition. There is probably some minor error in my code but I am not getting what it is.

Any help is highly appreciated !

答:
The immediate cause of the error is that you have

```<code>  given_date DATE := TO_DATE('dt', 'DD-MON-YYYY');
</code>```

instead of

```<code>  given_date DATE := TO_DATE(dt, 'DD-MON-YYYY');
</code>```

In your version you are trying to convert the string literal 'dt' to a date; that literal has no relationship to your dt argument.

However, this is still wrong, as dt is declared as a date datatype already. If you do that then you are really doing:

```<code>  given_date DATE := TO_DATE(TO_CHAR(dt), 'DD-MON-YYYY');
</code>```

which will use your current session NLS_DATE_FORMAT to convert the date to a string; if that isn't 'DD-MON-YYYY' too (or something close enough that Oracle will fudge it) then you will still get an error or, worse, incorrect conversion and invalid results that you might not notice.

So remove that redundant and dangerous conversion:

```<code>CREATE OR REPLACE PROCEDURE get_days(dt date)
IS
BEGIN
  DBMS_OUTPUT.PUT_LINE ('The day of the given date is ' || TO_CHAR(dt, 'FMDAY') || '.');
  DBMS_OUTPUT.PUT_LINE ('Execution  done successfully.');
END get_days;
/
</code>```

You can of course assign the day name to a string variable if you want. I've used the FM format modifier to stop it right-padding the day name, so you don't need to trim it - the full-stop is just there to demonstrate that works. If you want the day name in mixed case you can use 'FMDay' instead of 'FMDAY'.

You should always pass in a date, not a string:

```<code>set serveroutput on;

BEGIN
  get_days(date '2012-12-12');
  get_days(TO_DATE( '01/01/2018', 'MM/DD/YYYY' ));
END;
/

The day of the given date is WEDNESDAY.
Execution  done successfully.
The day of the given date is MONDAY.
Execution  done successfully.

PL/SQL procedure successfully completed.
</code>```

dt might be passed in any format. I am just converting it into DD-MM-YYYY format and storing into given_date

A date doesn't have a format; it has an internal representation which you very rarely need to know or care about. When you query a date value without explicitly converting it to a string, your client converts that to a human-readable form, usually using NLS_DATE_FORMAT to decide what format to display it in. So dt does not have a format, and even if the caller makes the call with a string (as in your first two examples) those will be implicit converted to a date - assuming that's possible - before the call; the procedure will never see those strings, it will only see the converted date value.

Body:
I know this question has been answered previously, and I have tried out the solution given in them without success.

I have a stored procedure as below(I have removed non-essential parts) :

CREATE OR REPLACE PROCEDURE get_days(dt date)
IS
  given_date DATE := TO_DATE('dt', 'DD-MON-YYYY');
BEGIN
  get_day := RTRIM(TO_CHAR(dt1, 'DAY'));
  DBMS_OUTPUT.PUT_LINE ('The day of the given date is '||get_day||);
  DBMS_OUTPUT.PUT_LINE ('Execution  done successfully.');
END get_days;

I am having trouble with passing date to the procedure get_days. I have tried in the following ways :

BEGIN
  --Below I have listed all ways I have tried
  get_days('12/12/12');
  get_days('12-12-12');
  get_days(date '2012-12-12');
  get_days(TO_DATE( '01/01/2018', 'MM/DD/YYYY' ));
END;

I don't know what is wrong but I am getting this error - ORA-01858: a non-numeric character was found where a numeric was expected. I have searched for similar errors online but none helped. I am using Oracle Database 11g Express edition. There is probably some minor error in my code but I am not getting what it is.

Any help is highly appreciated !

Body:
The immediate cause of the error is that you have

  given_date DATE := TO_DATE('dt', 'DD-MON-YYYY');

instead of

  given_date DATE := TO_DATE(dt, 'DD-MON-YYYY');

In your version you are trying to convert the string literal 'dt' to a date; that literal has no relationship to your dt argument.

However, this is still wrong, as dt is declared as a date datatype already. If you do that then you are really doing:

  given_date DATE := TO_DATE(TO_CHAR(dt), 'DD-MON-YYYY');

which will use your current session NLS_DATE_FORMAT to convert the date to a string; if that isn't 'DD-MON-YYYY' too (or something close enough that Oracle will fudge it) then you will still get an error or, worse, incorrect conversion and invalid results that you might not notice.

So remove that redundant and dangerous conversion:

CREATE OR REPLACE PROCEDURE get_days(dt date)
IS
BEGIN
  DBMS_OUTPUT.PUT_LINE ('The day of the given date is ' || TO_CHAR(dt, 'FMDAY') || '.');
  DBMS_OUTPUT.PUT_LINE ('Execution  done successfully.');
END get_days;
/

You can of course assign the day name to a string variable if you want. I've used the FM format modifier to stop it right-padding the day name, so you don't need to trim it - the full-stop is just there to demonstrate that works. If you want the day name in mixed case you can use 'FMDay' instead of 'FMDAY'.

You should always pass in a date, not a string:

set serveroutput on;

BEGIN
  get_days(date '2012-12-12');
  get_days(TO_DATE( '01/01/2018', 'MM/DD/YYYY' ));
END;
/

The day of the given date is WEDNESDAY.
Execution  done successfully.
The day of the given date is MONDAY.
Execution  done successfully.

PL/SQL procedure successfully completed.

dt might be passed in any format. I am just converting it into DD-MM-YYYY format and storing into given_date

A date doesn't have a format; it has an internal representation which you very rarely need to know or care about. When you query a date value without explicitly converting it to a string, your client converts that to a human-readable form, usually using NLS_DATE_FORMAT to decide what format to display it in. So dt does not have a format, and even if the caller makes the call with a string (as in your first two examples) those will be implicit converted to a date - assuming that's possible - before the call; the procedure will never see those strings, it will only see the converted date value.


问:
Convert Variant to String
I have a list on my primary worksheet containing the names of sheets in the workbook. I am trying to iterate over them but the Worksheets function expects a String and the values in the list return Variant types. I get a type mismatch error when I try to access the worksheet with a Variant expression. How do I convert a Variant to a String or is there another way to do this?</p>

```<code>Dim allws As Range
Set allws = Worksheets("Summary").Range("A4:A21").Columns(1)
Dim str As String
str = allws.Item(1).Value 'Type mismatch
Set ws = Worksheets(str)
</code>```

答:
This calls for an array. More detail in the comments:</p>

```<code>Dim allws As Range
Set allws = Worksheets("Summary").Range("A4:A21") ' no need for .Columns

Dim arr() as Variant
arr = allws.Value ' read the value into a 2D Variant array

Dim i as Long
For i = Lbound(arr, 1) to Ubound(arr, 1)
    Dim ws as Worksheet
    Set ws = Worksheets(arr(i))
Next
</code>```

Title: Convert Variant to String

Body:
I have a list on my primary worksheet containing the names of sheets in the workbook. I am trying to iterate over them but the Worksheets function expects a String and the values in the list return Variant types. I get a type mismatch error when I try to access the worksheet with a Variant expression. How do I convert a Variant to a String or is there another way to do this?

Dim allws As Range
Set allws = Worksheets("Summary").Range("A4:A21").Columns(1)
Dim str As String
str = allws.Item(1).Value 'Type mismatch
Set ws = Worksheets(str)

Body:
This calls for an array. More detail in the comments:

Dim allws As Range
Set allws = Worksheets("Summary").Range("A4:A21") ' no need for .Columns

Dim arr() as Variant
arr = allws.Value ' read the value into a 2D Variant array

Dim i as Long
For i = Lbound(arr, 1) to Ubound(arr, 1)
    Dim ws as Worksheet
    Set ws = Worksheets(arr(i))
Next


问:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getBottom()' on a null object reference
It's working fine when I build and run it. But I'm getting this error when I relaunch the app remotely.

this is the only place where I used views. It's in ListAdapter.

I looked around on both Google and StackOverflow and I have found some information. However, I have not got it to work. Now I hope that I can get help with my code.

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getBottom()' on a null object reference
        at android.widget.ListView.fillDown(ListView.java:829)
        at android.widget.ListView.fillFromTop(ListView.java:888)
        at android.widget.ListView.layoutChildren(ListView.java:1958)
        at android.widget.AbsListView.onLayout(AbsListView.java:2991)
        at android.view.View.layout(View.java:22406)
        at android.view.ViewGroup.layout(ViewGroup.java:6594)
        at androidx.constraintlayout.widget.ConstraintLayout.onLayout(ConstraintLayout.java:1915)
        at android.view.View.layout(View.java:22406)
        at android.view.ViewGroup.layout(ViewGroup.java:6594)
        at com.google.android.material.appbar.HeaderScrollingViewBehavior.layoutChild(HeaderScrollingViewBehavior.java:142)
        at com.google.android.material.appbar.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:41)
        at com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1556)
        at androidx.coordinatorlayout.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:888)
        at android.view.View.layout(View.java:22406)
        at android.view.ViewGroup.layout(ViewGroup.java:6594)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:22406)
        at android.view.ViewGroup.layout(ViewGroup.java:6594)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
        at android.view.View.layout(View.java:22406)
        at android.view.ViewGroup.layout(ViewGroup.java:6594)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:22406)
        at android.view.ViewGroup.layout(ViewGroup.java:6594)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
        at android.view.View.layout(View.java:22406)
        at android.view.ViewGroup.layout(ViewGroup.java:6594)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at com.android.internal.policy.DecorView.onLayout(DecorView.java:1075)
        at android.view.View.layout(View.java:22406)
        at android.view.ViewGroup.layout(ViewGroup.java:6594)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:3394)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2863)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1911)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:8526)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:949)
        at android.view.Choreographer.doCallbacks(Choreographer.java:761)
        at android.view.Choreographer.doFrame(Choreographer.java:696)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:935)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7078)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:974)

</code>```
```<code>public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        if(getItem(position)!= null) {
            title = getItem(position).getText();
            date = getItem(position).getDate();
            hour = getItem(position).getHour();
            minute = getItem(position).getMinute();
            SimpleDateFormat formatter = new SimpleDateFormat("dd MMMM yyyy");
            LayoutInflater inflater = LayoutInflater.from(context);
            convertView = inflater.inflate(resource, parent, false);
            TextView titleView = (TextView) convertView.findViewById(R.id.title);
            TextView descpView = (TextView) convertView.findViewById(R.id.description);
            TextView dateView = (TextView) convertView.findViewById(R.id.date);
            titleView.setText(title);
            descpView.setText(hour + ":" + minute);
            dateView.setText(formatter.format(date));
        }

        return convertView;
    }

</code>```

答:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getBottom()' on a null object reference

Some view is getting null causing NullPointerException when calling getBottom() on that view.

So, as the app runs locally without this issue; but not remotely, so the answer will be a kind of a guess.

Assumption 1:  getView returns a null value.

Reason: convertView is marked as @Nullable, so it can be null from the beginning, and can remain null if the condition if(getItem(position)!= null) is not met; and therefore getView() can return a null View.

Recommendation: you need to make sure that getView can't return null value by setting the convertView value outside the if condition like the below snippet.

```<code>public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    if (converView == null) {
        convertView = inflater.inflate(resource, parent, false);
    }
</code>```

Assumption 2:   convertView is null from this expression  convertView = inflater.inflate(resource, parent, false);

Reason: You didn't provide from where you got the resource argument you pass to inflate(); maybe it's a variable value that can change in multiple values; one of which can be null; and therefore making convertView null as well.

Recommendation:

If the resource is not changeable, you can hardcode it by setting its value to say R.layout.list_row; where list_row is the xml layout of your list item.

And If it's changeable, then debug its value to make sure it can't be null by any means.

Body:
It's working fine when I build and run it. But I'm getting this error when I relaunch the app remotely.

this is the only place where I used views. It's in ListAdapter.

I looked around on both Google and StackOverflow and I have found some information. However, I have not got it to work. Now I hope that I can get help with my code.

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getBottom()' on a null object reference
        at android.widget.ListView.fillDown(ListView.java:829)
        at android.widget.ListView.fillFromTop(ListView.java:888)
        at android.widget.ListView.layoutChildren(ListView.java:1958)
        at android.widget.AbsListView.onLayout(AbsListView.java:2991)
        at android.view.View.layout(View.java:22406)
        at android.view.ViewGroup.layout(ViewGroup.java:6594)
        at androidx.constraintlayout.widget.ConstraintLayout.onLayout(ConstraintLayout.java:1915)
        at android.view.View.layout(View.java:22406)
        at android.view.ViewGroup.layout(ViewGroup.java:6594)
        at com.google.android.material.appbar.HeaderScrollingViewBehavior.layoutChild(HeaderScrollingViewBehavior.java:142)
        at com.google.android.material.appbar.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:41)
        at com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1556)
        at androidx.coordinatorlayout.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:888)
        at android.view.View.layout(View.java:22406)
        at android.view.ViewGroup.layout(ViewGroup.java:6594)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:22406)
        at android.view.ViewGroup.layout(ViewGroup.java:6594)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
        at android.view.View.layout(View.java:22406)
        at android.view.ViewGroup.layout(ViewGroup.java:6594)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:22406)
        at android.view.ViewGroup.layout(ViewGroup.java:6594)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
        at android.view.View.layout(View.java:22406)
        at android.view.ViewGroup.layout(ViewGroup.java:6594)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at com.android.internal.policy.DecorView.onLayout(DecorView.java:1075)
        at android.view.View.layout(View.java:22406)
        at android.view.ViewGroup.layout(ViewGroup.java:6594)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:3394)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2863)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1911)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:8526)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:949)
        at android.view.Choreographer.doCallbacks(Choreographer.java:761)
        at android.view.Choreographer.doFrame(Choreographer.java:696)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:935)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7078)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:974)

public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        if(getItem(position)!= null) {
            title = getItem(position).getText();
            date = getItem(position).getDate();
            hour = getItem(position).getHour();
            minute = getItem(position).getMinute();
            SimpleDateFormat formatter = new SimpleDateFormat("dd MMMM yyyy");
            LayoutInflater inflater = LayoutInflater.from(context);
            convertView = inflater.inflate(resource, parent, false);
            TextView titleView = (TextView) convertView.findViewById(R.id.title);
            TextView descpView = (TextView) convertView.findViewById(R.id.description);
            TextView dateView = (TextView) convertView.findViewById(R.id.date);
            titleView.setText(title);
            descpView.setText(hour + ":" + minute);
            dateView.setText(formatter.format(date));
        }

        return convertView;
    }

Body:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getBottom()' on a null object reference

Some view is getting null causing NullPointerException when calling getBottom() on that view.

So, as the app runs locally without this issue; but not remotely, so the answer will be a kind of a guess.

Assumption 1:  getView returns a null value.

Reason: convertView is marked as @Nullable, so it can be null from the beginning, and can remain null if the condition if(getItem(position)!= null) is not met; and therefore getView() can return a null View.

Recommendation: you need to make sure that getView can't return null value by setting the convertView value outside the if condition like the below snippet.

public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    if (converView == null) {
        convertView = inflater.inflate(resource, parent, false);
    }

Assumption 2:   convertView is null from this expression  convertView = inflater.inflate(resource, parent, false);

Reason: You didn't provide from where you got the resource argument you pass to inflate(); maybe it's a variable value that can change in multiple values; one of which can be null; and therefore making convertView null as well.

Recommendation:

If the resource is not changeable, you can hardcode it by setting its value to say R.layout.list_row; where list_row is the xml layout of your list item.

And If it's changeable, then debug its value to make sure it can't be null by any means.


问:
Random number generator with conditions - Python
I am new to Python and trying to generate 5 numbers with 2 conditions:

There must be 3 even and 2 odd numbers

From those 5 numbers 3 must be low (1,51) and 2 high (51,100). Which number will be low or high is not of interest.

I have managed to solve the first part:

```<code>import random
rand_even = random.sample(range(0, 100, 2), 3)
rand_odd = random.sample(range(1, 100, 2), 2)
rand_total = rand_even,rand_odd
print(rand_total)
</code>```

Obviously this is not getting me anywhere
For the second part i thought i could use something like:

```<code>rand_low = random.sample(range(0, 51), 3)
rand_high = random.sample(range(51,100), 2)
</code>```

But obviously this is not the way as i am getting more than 5 numbers.

Any help would be appriciated.
Thank you

答:
I tried working through this problem logically and it got pretty messy.

Heuristically, what about something like this:

def valid_list(l):
    evens, odds = 0, 0
    lows, highs = 0, 0
    for elem in l:
        if elem%2 == 0:
            evens += 1
        else:
            odds += 1
        if elem < 52:
            lows += 1
        else:
            highs += 1
    return evens <= 3 and odds <= 2 and lows <= 3 and highs <= 2

current_list = [random.randint(0, 100)]

while len(current_list) < 5:
    if not valid_list(current_list):
        current_list[-1] = random.randint(0, 100)
    else:
        current_list.append(random.randint(0, 100))

print(current_list)
```

You have a function that constantly checks whether the numbers you have so far are on track/valid, and then a while loop that will keep pegging said function with random numbers until there is a list of 5 numbers that pass valid_list.

This is pretty much the epitome of randomness, haha

Body:
I am new to Python and trying to generate 5 numbers with 2 conditions:

There must be 3 even and 2 odd numbers

From those 5 numbers 3 must be low (1,51) and 2 high (51,100). Which number will be low or high is not of interest.

I have managed to solve the first part:

import random
rand_even = random.sample(range(0, 100, 2), 3)
rand_odd = random.sample(range(1, 100, 2), 2)
rand_total = rand_even,rand_odd
print(rand_total)

Obviously this is not getting me anywhere
For the second part i thought i could use something like:

rand_low = random.sample(range(0, 51), 3)
rand_high = random.sample(range(51,100), 2)

But obviously this is not the way as i am getting more than 5 numbers.

Any help would be appriciated.
Thank you

Body:
I tried working through this problem logically and it got pretty messy.

Heuristically, what about something like this:

def valid_list(l):
    evens, odds = 0, 0
    lows, highs = 0, 0
    for elem in l:
        if elem%2 == 0:
            evens += 1
        else:
            odds += 1
        if elem < 52:
            lows += 1
        else:
            highs += 1
    return evens <= 3 and odds <= 2 and lows <= 3 and highs <= 2

current_list = [random.randint(0, 100)]

while len(current_list) < 5:
    if not valid_list(current_list):
        current_list[-1] = random.randint(0, 100)
    else:
        current_list.append(random.randint(0, 100))

print(current_list)

You have a function that constantly checks whether the numbers you have so far are on track/valid, and then a while loop that will keep pegging said function with random numbers until there is a list of 5 numbers that pass valid_list.

This is pretty much the epitome of randomness, haha


问:
Vendor Bundle Size Not Reducing
I'm trying to get my build much smaller to get my load time faster, but when I run

ng build --prod --aot --vendor-chunk --common-chunk --build-optimizer and then run a lighthouse report from google dev tools

I get

what's odd is that it seems to have worked if I go into the dist folder to look at file sizes, which seem smaller that the lighthouse report.

So far to reduce the size by doing the following:

Removed old/unused package.json entries

changed all material imports to specific path like for paginator I'm importing now as
import { MatPaginator } from "@angular/material/paginator";
instead of import { MatPaginator } from "@angular/material/"; per the advice from other posts.

replaced moment with moment.min.js so that locales don't get added

added brotli for text compression.

Also I want to mention because I don't know if it's relevant, but I don't have a webpack.config.js file only a custom-webpack.config.js for brotli. The only thing I edited in angular.json to get webpack working was this for brotli

```<code>  "architect": {
        "build": {
          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            "customWebpackConfig": {
              "path": "./custom-webpack.config.js"
             },
</code>```

I've never used webpack before so this could be an issue, but I'm not sure.

package.json

```<code>{
  "name": "mean-course",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "webpack-dev-server --mode development --open",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "start:server": "nodemon backend/server.js"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^8.2.13",
    "@angular/cdk": "~8.2.2",
    "@angular/common": "~8.2.4",
    "@angular/compiler": "~8.2.4",
    "@angular/core": "~8.2.4",
    "@angular/forms": "~8.2.4",
    "@angular/material": "^8.2.2",
    "@angular/platform-browser": "~8.2.4",
    "@angular/platform-browser-dynamic": "~8.2.4",
    "@angular/router": "~8.2.4",
    "@ng-bootstrap/ng-bootstrap": "^5.1.5",
    "@ngrx/store": "^8.6.0",
    "ably": "^1.1.22",
    "angular-doka": "file:src/angular-doka",
    "angular-filepond": "^1.0.5",
    "azure-arm-rediscache": "^3.0.0",
    "bootstrap": "^4.4.1",
    "classlist.js": "^1.1.20150312",
    "countdown": "^2.6.0",
    "dotenv": "^8.2.0",
    "filepond": "^4.13.4",
    "filepond-plugin-file-encode": "^2.1.5",
    "filepond-plugin-file-validate-size": "^2.2.0",
    "filepond-plugin-file-validate-type": "^1.2.5",
    "filepond-plugin-image-crop": "^2.0.3",
    "filepond-plugin-image-edit": "^1.6.0",
    "filepond-plugin-image-exif-orientation": "^1.0.7",
    "filepond-plugin-image-preview": "^4.6.1",
    "filepond-plugin-image-resize": "^2.0.4",
    "filepond-plugin-image-transform": "^3.7.2",
    "jquery": "^3.5.1",
    "jsonwebtoken": "^8.5.1",
    "lib-storage-service": "^1.0.2",
    "material": "^0.4.1",
    "moment-mini": "^2.24.0",
    "ng-starrating": "^1.0.20",
    "ngx-bar-rating": "^1.1.0",
    "ngx-clipboard": "^12.3.0",
    "ngx-device-detector": "^1.3.20",
    "ngx-filepond": "^5.0.1",
    "ngx-light-carousel": "^1.0.37-beta.8",
    "ngx-pagination": "^5.0.0",
    "ngx-simple-countdown": "^1.0.2",
    "ngx-spinner": "^8.0.3",
    "ngx-toastr": "^11.2.1",
    "ngx-ui-carousel": "^1.3.2",
    "numeral": "^2.0.6",
    "rxjs": "~6.4.0",
    "tslib": "^1.10.0",
    "tsoa": "^2.5.7",
    "uid": "0.0.2",
    "web-animations-js": "^2.3.2",
    "yamljs": "^0.3.0",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-builders/custom-webpack": "8.4.1",
    "@angular-devkit/build-angular": "^0.803.26",
    "@angular/cli": "~8.3.2",
    "@angular/compiler-cli": "~8.2.4",
    "@angular/language-service": "~8.2.4",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "^8.10.59",
    "brotli-gzip-webpack-plugin": "^0.5.0",
    "brotli-webpack-plugin": "^1.1.0",
    "codelyzer": "^5.0.0",
    "compression-webpack-plugin": "^4.0.0",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "^4.4.1",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.5.3"
  },
  "browser": {
    "crypto": false
  }
}

</code>```

Here is a stats.json file when using ng build --prod

Here's a more detailed version as well

答:
Remove libraries like ngx-spinner, filepond etc. which are huge as they are not treeshakable. Also if you have not configured your server to serve gzip files, do that. It will give you huge reduction in size. Also pre gzip your js files after build my using a utility like gzip-all.

https://www.npmjs.com/package/gzip-all

Also change your server max cache policy to get caching benefits.

Title: Vendor Bundle Size Not Reducing

Body:
I'm trying to get my build much smaller to get my load time faster, but when I run

ng build --prod --aot --vendor-chunk --common-chunk --build-optimizer and then run a lighthouse report from google dev tools

I get

what's odd is that it seems to have worked if I go into the dist folder to look at file sizes, which seem smaller that the lighthouse report.

So far to reduce the size by doing the following:

Removed old/unused package.json entries

changed all material imports to specific path like for paginator I'm importing now as
import { MatPaginator } from "@angular/material/paginator";
instead of import { MatPaginator } from "@angular/material/"; per the advice from other posts.

replaced moment with moment.min.js so that locales don't get added

added brotli for text compression.

Also I want to mention because I don't know if it's relevant, but I don't have a webpack.config.js file only a custom-webpack.config.js for brotli. The only thing I edited in angular.json to get webpack working was this for brotli

  "architect": {
        "build": {
          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            "customWebpackConfig": {
              "path": "./custom-webpack.config.js"
             },

I've never used webpack before so this could be an issue, but I'm not sure.

package.json

{
  "name": "mean-course",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "webpack-dev-server --mode development --open",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "start:server": "nodemon backend/server.js"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^8.2.13",
    "@angular/cdk": "~8.2.2",
    "@angular/common": "~8.2.4",
    "@angular/compiler": "~8.2.4",
    "@angular/core": "~8.2.4",
    "@angular/forms": "~8.2.4",
    "@angular/material": "^8.2.2",
    "@angular/platform-browser": "~8.2.4",
    "@angular/platform-browser-dynamic": "~8.2.4",
    "@angular/router": "~8.2.4",
    "@ng-bootstrap/ng-bootstrap": "^5.1.5",
    "@ngrx/store": "^8.6.0",
    "ably": "^1.1.22",
    "angular-doka": "file:src/angular-doka",
    "angular-filepond": "^1.0.5",
    "azure-arm-rediscache": "^3.0.0",
    "bootstrap": "^4.4.1",
    "classlist.js": "^1.1.20150312",
    "countdown": "^2.6.0",
    "dotenv": "^8.2.0",
    "filepond": "^4.13.4",
    "filepond-plugin-file-encode": "^2.1.5",
    "filepond-plugin-file-validate-size": "^2.2.0",
    "filepond-plugin-file-validate-type": "^1.2.5",
    "filepond-plugin-image-crop": "^2.0.3",
    "filepond-plugin-image-edit": "^1.6.0",
    "filepond-plugin-image-exif-orientation": "^1.0.7",
    "filepond-plugin-image-preview": "^4.6.1",
    "filepond-plugin-image-resize": "^2.0.4",
    "filepond-plugin-image-transform": "^3.7.2",
    "jquery": "^3.5.1",
    "jsonwebtoken": "^8.5.1",
    "lib-storage-service": "^1.0.2",
    "material": "^0.4.1",
    "moment-mini": "^2.24.0",
    "ng-starrating": "^1.0.20",
    "ngx-bar-rating": "^1.1.0",
    "ngx-clipboard": "^12.3.0",
    "ngx-device-detector": "^1.3.20",
    "ngx-filepond": "^5.0.1",
    "ngx-light-carousel": "^1.0.37-beta.8",
    "ngx-pagination": "^5.0.0",
    "ngx-simple-countdown": "^1.0.2",
    "ngx-spinner": "^8.0.3",
    "ngx-toastr": "^11.2.1",
    "ngx-ui-carousel": "^1.3.2",
    "numeral": "^2.0.6",
    "rxjs": "~6.4.0",
    "tslib": "^1.10.0",
    "tsoa": "^2.5.7",
    "uid": "0.0.2",
    "web-animations-js": "^2.3.2",
    "yamljs": "^0.3.0",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-builders/custom-webpack": "8.4.1",
    "@angular-devkit/build-angular": "^0.803.26",
    "@angular/cli": "~8.3.2",
    "@angular/compiler-cli": "~8.2.4",
    "@angular/language-service": "~8.2.4",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "^8.10.59",
    "brotli-gzip-webpack-plugin": "^0.5.0",
    "brotli-webpack-plugin": "^1.1.0",
    "codelyzer": "^5.0.0",
    "compression-webpack-plugin": "^4.0.0",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "^4.4.1",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.5.3"
  },
  "browser": {
    "crypto": false
  }
}

Here is a stats.json file when using ng build --prod

Here's a more detailed version as well


问:
How can I use in select dropdown with selected value with Angular 9
How can I use in select dropdown with selected value with Angular 9.

```<code>            <select [required]="egg.value" [(ngModel)]="protein.egg.sizeEgg"
              #eggSize="ngModel" name="eggSize">
              <option [value]="size" disabled>Size</option>
              <option>S</option>
              <option>M</option>
              <option>L</option>
            </select>
</code>```

in angular 8 it work properly but in angular 9 it do problems inside terminal how can I fix it

terminal error

```<code>ERROR in src/app/home/home.component.html:67:32 - error TS2339: Property 'size' does not exist on type 'HomeComponent'.

67               <option [value]="size" disabled>Size</option>
                                  ~~~~

  src/app/home/home.component.ts:20:16
    20   templateUrl: './home.component.html',
                      ~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component HomeComponent.
src/app/home/home.component.html:67:32 - error TS2339: Property 'size' does not exist on type 'HomeComponent'.

67               <option [value]="size" disabled>Size</option>
                                  ~~~~

  src/app/home/home.component.ts:20:16
    20   templateUrl: './home.component.html',
                      ~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component HomeComponent.

** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **
</code>```

devtool error

```<code>home:1 Refused to load the image 'http://localhost:4200/favicon.ico' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'img-src' was not explicitly set, so 'default-src' is used as a fallback.
</code>```

Please I am wait to your help Thx:-)

答:
I have added two option to handle.

Note : [value] or [ngValue] when you mention string value checking any variable inside component. You are getting this error because it checking this.size params but its doesn't exist.

Option 1:

```<code><select [(ngModel)]="eggSize"
               name="eggSize">
              <option value="size" disabled>Size</option>
              <option value='S'>S</option>
              <option value='M'>M</option>
              <option value='L'>L</option>
            </select>
</code>```

Option 2:

```<code><select [(ngModel)]="eggSize"
               name="eggSize2">
<option *ngFor="let size of listSize" [ngValue]="size">
       {{size}}
    </option>
</select>
</code>```

Option 3 :

```<code><select [(ngModel)]="eggSize"
               name="eggSize">
              <option [value]="" disabled>Size</option>
              <option [value]='1'>S</option>
              <option [value]='2'>M</option>
              <option [value]='2'>L</option>
            </select>
</code>```

https://stackblitz.com/edit/angular-ivy-uq1xjs

Use like this. adding stackblitz for reference.

Body:
How can I use in select dropdown with selected value with Angular 9.

            <select [required]="egg.value" [(ngModel)]="protein.egg.sizeEgg"
              #eggSize="ngModel" name="eggSize">
              <option [value]="size" disabled>Size</option>
              <option>S</option>
              <option>M</option>
              <option>L</option>
            </select>

in angular 8 it work properly but in angular 9 it do problems inside terminal how can I fix it

terminal error

ERROR in src/app/home/home.component.html:67:32 - error TS2339: Property 'size' does not exist on type 'HomeComponent'.

67               <option [value]="size" disabled>Size</option>
                                  ~~~~

  src/app/home/home.component.ts:20:16
    20   templateUrl: './home.component.html',
                      ~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component HomeComponent.
src/app/home/home.component.html:67:32 - error TS2339: Property 'size' does not exist on type 'HomeComponent'.

67               <option [value]="size" disabled>Size</option>
                                  ~~~~

  src/app/home/home.component.ts:20:16
    20   templateUrl: './home.component.html',
                      ~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component HomeComponent.

** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **

devtool error

home:1 Refused to load the image 'http://localhost:4200/favicon.ico' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'img-src' was not explicitly set, so 'default-src' is used as a fallback.

Please I am wait to your help Thx:-)

Body:
I have added two option to handle.

Note : [value] or [ngValue] when you mention string value checking any variable inside component. You are getting this error because it checking this.size params but its doesn't exist.

Option 1:

<select [(ngModel)]="eggSize"
               name="eggSize">
              <option value="size" disabled>Size</option>
              <option value='S'>S</option>
              <option value='M'>M</option>
              <option value='L'>L</option>
            </select>

Option 2:

<select [(ngModel)]="eggSize"
               name="eggSize2">
<option *ngFor="let size of listSize" [ngValue]="size">
       {{size}}
    </option>
</select>

Option 3 :

<select [(ngModel)]="eggSize"
               name="eggSize">
              <option [value]="" disabled>Size</option>
              <option [value]='1'>S</option>
              <option [value]='2'>M</option>
              <option [value]='2'>L</option>
            </select>

https://stackblitz.com/edit/angular-ivy-uq1xjs

Use like this. adding stackblitz for reference.


问:
How to call one asynchronous function after another?
This is what I have:

```<code>  ngOnInit() {
    this._addServ.getDefaultAddress().subscribe((res)=>{
      if(res.status){
        //I need these next two functions to finish their async API requests
        //before selectNormalDelivery is called
        this.selectShippingAddress();
        this.selectBillingAddress();
        this.selectNormalDelivery();
      }
    })
  }
</code>```

I need selectShippingAddress and selectBillingAddress to finish their calls, and then for selectNormalDelivery to be called. How can I accomplish this? I don't want to convert them into promises as they're called other times without needing to be chained. Is this something involving .then?

This is the code for the functions:

```<code>  selectShippingAddress(){
    this.addressService.setShippingAddresses(this.cartService.shippingAddress.address_id).subscribe((res) => {
      console.log('Set shipping address!')
      console.log(res);
    }, err => {
      console.log('Failed to set shipping address')
      console.log(err);
    })
  }

  selectBillingAddress(){
    this.addressService.setPaymentAddresses(this.cartService.billingAddress.address_id).subscribe((res) => {
      console.log('Set billing address!')
      console.log(res);
    }, err => {
      console.log('Failed to set billing address')
      console.log(err);
    })
  }
</code>```

If I try a .then, I get the error Property 'then' does not exist on type 'void'., which makes sense as I'm not trying to return anything, I just need them to complete their calls for the API's sake.

Suggestions?

答:
If I understand correctly, you need to listen to one observable (from getDefaultAddress()), then process two other observables (this.addressService.setShippingAddresses() and this.addressService.setPaymentAddresses()) and after that call function selectNormalDelivery().

You could do so by using RxJS switchMap, catchError, tap operators and forkJoin(). Try the following

import { forkJoin, EMPTY } from 'rxjs';
import { tap, catchError, switchMap } from 'rxjs/operators';

ngOnInit() {
  this._addServ.getDefaultAddress().pipe(
    switchMap((res) => {        // <-- map the observable from `getDefaultAddress()` to another observable
      if(res.status) {
        return forkJoin([       // <-- `forkJoin` emits only after the observables complete
          this.selectShippingAddress(), this.selectBillingAddress()
        ])
      }
    })
  ).subscribe(response => {
    this.selectNormalDelivery()
  })
}

selectShippingAddress() {
  return this.addressService.setShippingAddresses(this.cartService.shippingAddress.address_id).pipe(
    tap((res) => {            // <-- `tap` doesn't alter the response
      console.log('Set shipping address!')
      console.log(res);
    }),
    catchError((err) => {     // <-- `catchError` must return an observable
      console.log('Failed to set shipping address')
      console.log(err);
      return EMPTY;
    }))
}

selectShippingAddress() {
  return this.addressService.setPaymentAddresses(this.cartService.shippingAddress.address_id).pipe(
    tap((res) => {
      console.log('Set billing address!')
      console.log(res);
    }),
    catchError((err) => {
      console.log('Failed to set billing address')
      console.log(err);
      return EMPTY;
    }))
}
```

Body:
This is what I have:

  ngOnInit() {
    this._addServ.getDefaultAddress().subscribe((res)=>{
      if(res.status){
        //I need these next two functions to finish their async API requests
        //before selectNormalDelivery is called
        this.selectShippingAddress();
        this.selectBillingAddress();
        this.selectNormalDelivery();
      }
    })
  }

I need selectShippingAddress and selectBillingAddress to finish their calls, and then for selectNormalDelivery to be called. How can I accomplish this? I don't want to convert them into promises as they're called other times without needing to be chained. Is this something involving .then?

This is the code for the functions:

  selectShippingAddress(){
    this.addressService.setShippingAddresses(this.cartService.shippingAddress.address_id).subscribe((res) => {
      console.log('Set shipping address!')
      console.log(res);
    }, err => {
      console.log('Failed to set shipping address')
      console.log(err);
    })
  }

  selectBillingAddress(){
    this.addressService.setPaymentAddresses(this.cartService.billingAddress.address_id).subscribe((res) => {
      console.log('Set billing address!')
      console.log(res);
    }, err => {
      console.log('Failed to set billing address')
      console.log(err);
    })
  }

If I try a .then, I get the error Property 'then' does not exist on type 'void'., which makes sense as I'm not trying to return anything, I just need them to complete their calls for the API's sake.

Suggestions?


问:
Why code not working for configuring while loop
Why my code not working

a “game” where, through input, enter the number of players who will play the game, how to make so many inputs (for player nicknames) be displayed, how many players are playing? and how to do something to add all the nicknames to the array later?
For example: the host introduced what 5 people play, how to output 5 inputs and then add all the nicknames to the array?

```<code>print("Add players!")
plam = int(input("How many players will be? \n"))

playersNames = []
i = len(playersNames)
while i < plam:
    writePlayerName = input("Write player's nickname:   " + Fore.GREEN)
    print(Fore.WHITE)
    playersNames.append(writePlayerName)
    print(playersNames)
    break;
</code>```

Problem statement

player names can be entered endlessly, but I here restricted that there will be 5 players

答:
Your code is working, but it is not doing what you want to do, because you missed some logical steps:

You only update i once outside the loop.

len function will not make i magically track the length of playerNames it will only put current length when called in to i which is 0, because you call len when playerNames is empty.

You call break in the loop without condition, so your loop will always exit after the first time.

While there are several ways to write this code, and Andrea Pollini gave a good, clean example, here is the minimum fix to your code to do what you want:

```<code>print("Add players!")
plam = int(input("How many players will be? \n"))

playersNames = []

while i < plam:
    writePlayerName = input("Write player's nickname:   " + Fore.GREEN)
    print(Fore.WHITE)
    playersNames.append(writePlayerName)
    print(playersNames)
    i = len(playersNames)
</code>```

Note, that all I did was to move the len call in to the loop, to where the break used to be.

Body:
Why my code not working

a “game” where, through input, enter the number of players who will play the game, how to make so many inputs (for player nicknames) be displayed, how many players are playing? and how to do something to add all the nicknames to the array later?
For example: the host introduced what 5 people play, how to output 5 inputs and then add all the nicknames to the array?

print("Add players!")
plam = int(input("How many players will be? \n"))

playersNames = []
i = len(playersNames)
while i < plam:
    writePlayerName = input("Write player's nickname:   " + Fore.GREEN)
    print(Fore.WHITE)
    playersNames.append(writePlayerName)
    print(playersNames)
    break;

Problem statement

player names can be entered endlessly, but I here restricted that there will be 5 players

Body:
Your code is working, but it is not doing what you want to do, because you missed some logical steps:

You only update i once outside the loop.

len function will not make i magically track the length of playerNames it will only put current length when called in to i which is 0, because you call len when playerNames is empty.

You call break in the loop without condition, so your loop will always exit after the first time.

While there are several ways to write this code, and Andrea Pollini gave a good, clean example, here is the minimum fix to your code to do what you want:

print("Add players!")
plam = int(input("How many players will be? \n"))

playersNames = []

while i < plam:
    writePlayerName = input("Write player's nickname:   " + Fore.GREEN)
    print(Fore.WHITE)
    playersNames.append(writePlayerName)
    print(playersNames)
    i = len(playersNames)

Note, that all I did was to move the len call in to the loop, to where the break used to be.


问:
Is there any PDF creator and viewer/renderer library in FLUTTER with features like zoom-in, zoom-out, page-separator, gesture-recognizer?
PDF generator and renderer library needed in FLUTTER with features like:

zoom-in,

zoom-out,

page-separator,

gesture-recognizer,

double-tap to zoom?

If there is no such library what things are required to create such library using flutter ?

答:
flutter's native_pdf_view has all the features you mentioned.
https://pub.dev/packages/native_pdf_view</p>


问:
Load pdf file from url
I have this url from server
https://xxxx.pdf20200529". How can I load it as pdf in my flutter app?

I use this plugin, but nothing happened.

Code

```<code>OpenFile.open(value);  // value is https://xxxx.pdf20200529
</code>```

Edit

```<code> generatePDF(dynamic value) async {
    final filename = value.substring(value.lastIndexOf("/") + 1);
    var request = await HttpClient().getUrl(Uri.parse(value));
    var response = await request.close();
    var bytes = await consolidateHttpClientResponseBytes(response);
    String dir = (await getApplicationDocumentsDirectory()).path;
    File file = new File('$dir/$filename');
    await file.writeAsBytes(bytes);
    OpenFile.open(file.path);
  }
</code>```

答:
I miss .pdf in this line

```<code>File file = new File('$dir/$filename.pdf');
</code>```

After add .pdf, all PDF viewer able to open.

Title: Load pdf file from url

Body:
I have this url from server
https://xxxx.pdf20200529". How can I load it as pdf in my flutter app?

I use this plugin, but nothing happened.

Code

OpenFile.open(value);  // value is https://xxxx.pdf20200529

Edit

 generatePDF(dynamic value) async {
    final filename = value.substring(value.lastIndexOf("/") + 1);
    var request = await HttpClient().getUrl(Uri.parse(value));
    var response = await request.close();
    var bytes = await consolidateHttpClientResponseBytes(response);
    String dir = (await getApplicationDocumentsDirectory()).path;
    File file = new File('$dir/$filename');
    await file.writeAsBytes(bytes);
    OpenFile.open(file.path);
  }

Body:
I miss .pdf in this line

File file = new File('$dir/$filename.pdf');

After add .pdf, all PDF viewer able to open.


问:
How to Install the Visual C++ Redist Using NSIS
My C++ application needs to install the Visual Studio C++ redistributable. I'm using Visual Studio 2019 Community edition. I use NSIS (version 3.04) to create my install program. Should I try to detect if the redist is installed and only install it if it is not up to date?</p>

答:
There are a melange of answers about how to do this, including many methods of how to detect if the redist is installed. I'm not going to say that all of them are incomplete and don't work in a future proof method, but I have not had success with them. So, I think the best thing to do is just install the redist always and let Microsoft take care of it. As of March 2020 this will add 14MB to your installer program, but maybe in this age of high speed Internet that isn't the big deal it once was. Luckily this is quite simple, and hopefully this question will keep you from following all the dated references and links that I did.

Instructions on the redist from Microsoft can be found here: Redistributing Visual C++ Files

To turn this into NSIS:

Find the file you want to redistribute in your Visual Studio install. For me this is:

```<code>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Redist\MSVC\14.25.28508\vcredist_x86.exe
</code>```

The version number is definitely subject to change (14.25.28508) in the future, likely just when you install updates to Visual Studio, so remember that you'll need to update that path when your install program breaks. You'll also need to choose between vcredist_x86.exe and vcredist_x64.exe depending on whether your build your application as 32-bit or 64-bit.

Add a section like this to your NSIS install file, probably before you do the main installation. All it does is copy the redist file into the filesystem, run it, wait for completion, then delete the redist file.

```<code>Section "Visual Studio Runtime"
  SetOutPath "$INSTDIR"
  File "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Redist\MSVC\14.25.28508\vcredist_x86.exe"
  ExecWait "$INSTDIR\vcredist_x86.exe"
  Delete "$INSTDIR\vcredist_x86.exe"
SectionEnd
</code>```

Substitute the proper path for the redist file you want to use.

As written (and current redist program behavior), this will pop up a dialog that the user will have to follow through to install the redist. You can substitute quiet mode:

```<code>ExecWait '"$INSTDIR\vcredist_x86.exe" /quiet'
</code>```

However I did not have good results with that. YMMV.

Body:
There are a melange of answers about how to do this, including many methods of how to detect if the redist is installed. I'm not going to say that all of them are incomplete and don't work in a future proof method, but I have not had success with them. So, I think the best thing to do is just install the redist always and let Microsoft take care of it. As of March 2020 this will add 14MB to your installer program, but maybe in this age of high speed Internet that isn't the big deal it once was. Luckily this is quite simple, and hopefully this question will keep you from following all the dated references and links that I did.

Instructions on the redist from Microsoft can be found here: Redistributing Visual C++ Files

To turn this into NSIS:

Find the file you want to redistribute in your Visual Studio install. For me this is:

C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Redist\MSVC\14.25.28508\vcredist_x86.exe

The version number is definitely subject to change (14.25.28508) in the future, likely just when you install updates to Visual Studio, so remember that you'll need to update that path when your install program breaks. You'll also need to choose between vcredist_x86.exe and vcredist_x64.exe depending on whether your build your application as 32-bit or 64-bit.

Add a section like this to your NSIS install file, probably before you do the main installation. All it does is copy the redist file into the filesystem, run it, wait for completion, then delete the redist file.

Section "Visual Studio Runtime"
  SetOutPath "$INSTDIR"
  File "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Redist\MSVC\14.25.28508\vcredist_x86.exe"
  ExecWait "$INSTDIR\vcredist_x86.exe"
  Delete "$INSTDIR\vcredist_x86.exe"
SectionEnd

Substitute the proper path for the redist file you want to use.

As written (and current redist program behavior), this will pop up a dialog that the user will have to follow through to install the redist. You can substitute quiet mode:

ExecWait '"$INSTDIR\vcredist_x86.exe" /quiet'

However I did not have good results with that. YMMV.


问:
Get last inserts of the disctinct property type list in mongodb
I have a collection of Account. Each Account document has 3 properties _id, type, age; and there are 3 distinct types Male,Female & Other. Any single document will bear only one of the types.

```<code>{
_id:ObjectId(xxxxx1),
type:"Male",
age:20

}
{
_id:ObjectId(xxxxx2),
type:"Female",
age:20

}
{
_id:ObjectId(xxxxx3),
type:"Male",
age:21

}
{
_id:ObjectId(xxxxx4),
type:"Other",
age:30

}
{
_id:ObjectId(xxxxx5),
type:"Female",
age:31

}
</code>```

My problem is I want to extract very last inserted document of each three type:
The result will be 3 documents

```<code>{
_id:ObjectId(xxxxx3), <--- last insert of the Male type
type:"Male",
age:21

}
{
_id:ObjectId(xxxxx4), <--- last insert of the Other type
type:"Other",
age:30

}
{
_id:ObjectId(xxxxx5), <--- last insert of the Female type
type:"Female",
age:31

}
</code>```

How can I design query for this?

答:
You need to use MongoDB's aggregation :

```<code>db.Account.aggregate([
      {$group : {_id : '$type', lastDoc : {$last : '$$ROOT'}}},
      {$replaceRoot : {newRoot : '$lastDoc'}}])
</code>```

Test : mongoplayground

Explanation :

In aggregate $group stage will group all the matching docs based on condition _id : '$type', So all the docs with same type will be grouped together & using $last we'll get the last document in the grouping process.

Using replaceRoot we'll make lastDoc object as new root of the document.

Body:
I have a collection of Account. Each Account document has 3 properties _id, type, age; and there are 3 distinct types Male,Female & Other. Any single document will bear only one of the types.

{
_id:ObjectId(xxxxx1),
type:"Male",
age:20

}
{
_id:ObjectId(xxxxx2),
type:"Female",
age:20

}
{
_id:ObjectId(xxxxx3),
type:"Male",
age:21

}
{
_id:ObjectId(xxxxx4),
type:"Other",
age:30

}
{
_id:ObjectId(xxxxx5),
type:"Female",
age:31

}

My problem is I want to extract very last inserted document of each three type:
The result will be 3 documents

{
_id:ObjectId(xxxxx3), <--- last insert of the Male type
type:"Male",
age:21

}
{
_id:ObjectId(xxxxx4), <--- last insert of the Other type
type:"Other",
age:30

}
{
_id:ObjectId(xxxxx5), <--- last insert of the Female type
type:"Female",
age:31

}

How can I design query for this?

Body:
You need to use MongoDB's aggregation :

db.Account.aggregate([
      {$group : {_id : '$type', lastDoc : {$last : '$$ROOT'}}},
      {$replaceRoot : {newRoot : '$lastDoc'}}])

Test : mongoplayground

Explanation :

In aggregate $group stage will group all the matching docs based on condition _id : '$type', So all the docs with same type will be grouped together & using $last we'll get the last document in the grouping process.

Using replaceRoot we'll make lastDoc object as new root of the document.


问:
Python: Cannot install module version that I see in pypi.org
I'm trying to upgrade my websockets module, and it appears version 8.1 exists in pypi.org: https://pypi.org/project/websockets/

However, pip install websockets==8.1 throws:

ERROR: Could not find a version that satisfies the requirement
  websockets==8.1 (from versions: 1.0, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5,
  2.6, 2.7, 3.0, 3.1, 3.2, 3.3, 3.4, 4.0.1, 5.0, 5.0.1, 6.0, 7.0) ERROR: No matching distribution found for websockets==8.1

I must be overlooking something. Any advice others can offer would be greatly appreciated!

答: I just tried this with python 3.7.4 and it worked. Make sure you are running python >= 3.6.1 (min version specced in Pypi) and latest Pip </p>


问:
How to implement the Sensor Manager on a ViewSonic Tablet?
I have recently acquired a ViewSonic G Tablet running Android 2.2 for the development of applications.

I have a few applications that use the Sensor Manager to read the orientation values of the phone. I have tested these applications on a few different android phones and they work fine (the sensors are found and the values are output).

However, when I test the applications on the G Tablet, no Orientation sensor is found?? I have no idea why this might be happening, and I was wondering if anyone has any clue what would cause this?

By the way, the tablet has a few other pre-installed applications that use the sensors and they work fine!?

Thank you in advance for any help!

答: Orientation requires both accelerometer and magnetometer combines both sensors to give an up/down and lateral orientation. Perhaps your tablet only has an accelerometer. This should be sufficient for determining which way is up/down, you should access the accelerometer directly.</p>


问:
Print information about which property caused mocha AssertionError
Given the following unit test:

```<code>var object = {
    a: [],
    b: [],
    c: null,
    d: [],
    e: []
};

describe('Multiple assertions', () => {
    it("Should be all arrays", (done) => {
        expect(object).to.have.property('a').that.is.a('array');
        expect(object).to.have.property('b').that.is.a('array');
        expect(object).to.have.property('c').that.is.a('array');
        expect(object).to.have.property('d').that.is.a('array');
        expect(object).to.have.property('e').that.is.a('array');
        done();
    });
});
</code>```

It correctly fails on one of the properties not being an array but it's unclear from the output which property caused the test to fail:

```<code>  1) Multiple assertions
       Should be all arrays:
     AssertionError: expected null to be an array
      at Context.it (server/test/serverTest.js:27:48)
</code>```

Is it possible for mocha to print a more descritive output such as below?

```<code>For property 'c' expected null to be an array
</code>```

答: You can always use try {} catch {} your expect() functions and format the error yourself. But I'm not sure it is the optimal way to answer this question.

Body:
Given the following unit test:

var object = {
    a: [],
    b: [],
    c: null,
    d: [],
    e: []
};

describe('Multiple assertions', () => {
    it("Should be all arrays", (done) => {
        expect(object).to.have.property('a').that.is.a('array');
        expect(object).to.have.property('b').that.is.a('array');
        expect(object).to.have.property('c').that.is.a('array');
        expect(object).to.have.property('d').that.is.a('array');
        expect(object).to.have.property('e').that.is.a('array');
        done();
    });
});

It correctly fails on one of the properties not being an array but it's unclear from the output which property caused the test to fail:

  1) Multiple assertions
       Should be all arrays:
     AssertionError: expected null to be an array
      at Context.it (server/test/serverTest.js:27:48)

Is it possible for mocha to print a more descritive output such as below?

For property 'c' expected null to be an array


问:
Finding if a value does not exist in SQL
My data is structured with 5 columns (let's call them a, b, c, d, e) and 1,000,000+ rows. Each value in b has the potential for ~50 possibilities in e - so there could be up to 50 lines for each unique b value. Every b should have a '-27' among their e values. I would like to query all UNIQUE b where it doesn't have the -27 e value, ignoring all other possibilities for e.

Code so far:

```<code>select a, b, c, d, e
from TestDB
where not exists (select count(distinct b) from TestDB where e = '-27')
</code>```

Would this code be sufficient? In initial tests I've done it appears to be either a) working or b) returning nothing. I'm new to SQL so I appreciate any help or being pointed in the right direction!

**edited to make it clearer I was looking for unique 'b' values.

答:
You need a correlated subquery with NOT EXISTS, i.e. a reference to the main query table.

```<code>select a, b, c, d, e
from TestDB t1
where not exists (select 1 from TestDB t2 where t2.e = '-27' and t1.b = t2.b)
</code>```

Body:
My data is structured with 5 columns (let's call them a, b, c, d, e) and 1,000,000+ rows. Each value in b has the potential for ~50 possibilities in e - so there could be up to 50 lines for each unique b value. Every b should have a '-27' among their e values. I would like to query all UNIQUE b where it doesn't have the -27 e value, ignoring all other possibilities for e.

Code so far:

select a, b, c, d, e
from TestDB
where not exists (select count(distinct b) from TestDB where e = '-27')

Would this code be sufficient? In initial tests I've done it appears to be either a) working or b) returning nothing. I'm new to SQL so I appreciate any help or being pointed in the right direction!

**edited to make it clearer I was looking for unique 'b' values.

Body:
You need a correlated subquery with NOT EXISTS, i.e. a reference to the main query table.

select a, b, c, d, e
from TestDB t1
where not exists (select 1 from TestDB t2 where t2.e = '-27' and t1.b = t2.b)


问:
Need angular jasmine test case for scrollIntoView function call
This is the method I wanted to test but not able to understand how to mock scrollIntoView.
Is there any documentation which can help me to understand jasmine testing.
I am getting error saying ele.scrollIntoView is not a function.</p>

```<code>scrollIntoViewMethod(): void {
    const offsetTopDiv = '.highlight';
    const ele = this.el.nativeElement.querySelector(`${offsetTopDiv}`);
    ele.scrollIntoView({
      behavior: 'smooth',
      block: 'center',
      inline: 'nearest',
    });
  }
</code>```

答:
as I understand el is a ViewChild, then you can mock its querySelector.

it('test', () => {
  // assuming that env is set and ready
  fixture.detectChanges();

  // adding spy
  const querySelectorSpy = spyOn(component.el.nativeElement, 'querySelector');

  // creating a stub
  const eleSpy = {
    scrollIntoView: jasmine.crateSpy('eleSpy.scrollIntoView'),
  };

  // setting the return value
  querySelectorSpy.and.returnValue(eleSpy);

  // action
  component.scrollIntoViewMethod();

  // assertion
  expect(querySelectorSpy).toHaveBeenCalledWith('.highlight');
  expect(eleSpy.scrollIntoView).toHaveBeenCalledWith({
    behavior: 'smooth',
    block: 'center',
    inline: 'nearest',
  });
});
```

Body:
This is the method I wanted to test but not able to understand how to mock scrollIntoView.
Is there any documentation which can help me to understand jasmine testing.
I am getting error saying ele.scrollIntoView is not a function.

scrollIntoViewMethod(): void {
    const offsetTopDiv = '.highlight';
    const ele = this.el.nativeElement.querySelector(`${offsetTopDiv}`);
    ele.scrollIntoView({
      behavior: 'smooth',
      block: 'center',
      inline: 'nearest',
    });
  }