问:
Getting JSONP via jQuery
UPDATE 1:

This is what I get in the browser if I type

http://www.remote_host.com/feed.php?callback=jsonpCallBack

```<code>{
    "rss": {
        "channels": [
            {
                "title": "title goes here",
                "link": "http://www.remote_server.com/feed.php",
                "description": "description goes here",
                "items": [
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    },
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    },
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    }
                ]
            }
        ]
    }
}
</code>```

So this is not jsonp?

ORIGINAL QUESTION:

I have the following script where I am trying to get json data from a remote host:

```<code>$(document).ready(function() {
    get_json_feed();

    function get_json_feed() {
        $.ajax({
            url: 'http://www.remote_host.com/feed.php?type=json',
            type: 'GET',
            dataType: 'jsonp',
            error: function(xhr, status, error) {
                alert("error");
            },
            success: function(json) {
                alert("success");
            }
        });
    }
});
</code>```

But for some reason I am getting an error and warning:

Warning: Resource interpreted as
  Script but transferred with MIME type
  text/html.

Error: Uncaught SyntaxError:
  Unexpected token :

What am I doing wrong?

答:
I don't know exactly what error you are facing, but there are some useful tips for using jsonp here

error: This handler is not called for cross-domain script and JSONP requests.

write jsonp: 'callback', jsonpCallback: 'jsonpCallback' in ajax parameters.
Setting jsonp to callback and then setting jsonpCallback to jsonpCallback makes the querystring look like this:

http://domain.com/jsonp-demo.php?callback=jsonpCallback&name=watever

Loads in a JSON block using JSONP. Will add an extra ?callback=? to the end of your URL to specify the callback.

Your complete script would look like this:

```<code><script>
    $(document).ready(function(){

        $("#useJSONP").click(function(){
            $.ajax({
                url: 'http://domain.com/jsonp-demo.php',
                data: {name: 'Chad'},
                dataType: 'jsonp',
                jsonp: 'callback',
                jsonpCallback: 'jsonpCallback',
                success: function(){
                    alert("success");
                }
            });
        });

    });

    function jsonpCallback(data){
        $('#jsonpResult').text(data.message);
    }
    </script>
</code>```

Example here

Title: Getting JSONP via jQuery

Body:
UPDATE 1:

This is what I get in the browser if I type

http://www.remote_host.com/feed.php?callback=jsonpCallBack

{
    "rss": {
        "channels": [
            {
                "title": "title goes here",
                "link": "http://www.remote_server.com/feed.php",
                "description": "description goes here",
                "items": [
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    },
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    },
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    }
                ]
            }
        ]
    }
}

So this is not jsonp?

ORIGINAL QUESTION:

I have the following script where I am trying to get json data from a remote host:

$(document).ready(function() {
    get_json_feed();

    function get_json_feed() {
        $.ajax({
            url: 'http://www.remote_host.com/feed.php?type=json',
            type: 'GET',
            dataType: 'jsonp',
            error: function(xhr, status, error) {
                alert("error");
            },
            success: function(json) {
                alert("success");
            }
        });
    }
});

But for some reason I am getting an error and warning:

Warning: Resource interpreted as
  Script but transferred with MIME type
  text/html.

Error: Uncaught SyntaxError:
  Unexpected token :

What am I doing wrong?

Body:
I don't know exactly what error you are facing, but there are some useful tips for using jsonp here

error: This handler is not called for cross-domain script and JSONP requests.

write jsonp: 'callback', jsonpCallback: 'jsonpCallback' in ajax parameters.
Setting jsonp to callback and then setting jsonpCallback to jsonpCallback makes the querystring look like this:

http://domain.com/jsonp-demo.php?callback=jsonpCallback&name=watever

Loads in a JSON block using JSONP. Will add an extra ?callback=? to the end of your URL to specify the callback.

Your complete script would look like this:

<script>
    $(document).ready(function(){

        $("#useJSONP").click(function(){
            $.ajax({
                url: 'http://domain.com/jsonp-demo.php',
                data: {name: 'Chad'},
                dataType: 'jsonp',
                jsonp: 'callback',
                jsonpCallback: 'jsonpCallback',
                success: function(){
                    alert("success");
                }
            });
        });

    });

    function jsonpCallback(data){
        $('#jsonpResult').text(data.message);
    }
    </script>

Example here


来源: stackexchange

问:
Excel Macro not showing as add-in
I have been working with this excel macro since April 23rd. Recently it has stopped showing up even though it is showing installed. Any ideas?

What I have already tried:

I have checked the trust center to add the folder I have the macro stored in but it is currently stored on an internal network drive that can not be added to the trust center.

I have also moved the macro to the default directory for Macros. It still will not load in.

When I just drag the macro .xla file into Excel it will pick it up and start showing in the VBA IDE, but only if the file I drag in is stored on the default directory.

Excel Macros installed:

Excel Options

Add-ins

Excel VBA IDE not showing the macros as well as not showing in the ribbon:

Add-ins tab not showing add-ins

Missing from VBA IDE

答:
I am not certain if this applies to your case, but this is what worked for me with the following set up:

- Using Windows

- Add-in stored on the network drive

My problem was that after I installed an add-in it would show up (both IDE and as a custom ribbon), but after I closed Excel and reopened it the add-in would fail to load (no ribbon, no IDE).

First step to fix this is to add a trusted location in Excel settings:

Trust Center -> Trusted Locations

You may need to select [Allow Trusted Locations on my network] before adding a location.

You can add just one folder, or, if it is appropriate, you can even add the whole network drive.

You may want to select [Subfolders in this location are also trusted]

The second step was far from obvious to me. I also needed to add network folder as a trusted location in Internet Explorer of all things:

Settings -> Internet Options -> Security -> Intranet -> Sites -> Advanced

Then you need to add the folder path to the network folder that contains the add-in.

After completing both steps and reopening Excel add-ins in the network folder started to appear both in IDE and as a custom ribbon. These two steps were necessary part of installation for every user.

If you are using multiple add-ins you may want to consider using one network folder for them. You can also take a look at this  question about network add-ins to see how they can be distributed in a more convenient fashion (one of the answers there is mine).

ContentLicense: CC BY-SA 4.0

Title: Excel Macro not showing as add-in


问:
How to divide total days output by individual year in python so that total days doesn't effect one particular year
Iam currently working on analyzing the delay in the response to a request made to each department. Format of data is as below:

```<code>Department     RequestDate     ResponseDate
Electronics    2019-05-01      2019-09-19
Babyshop       2018-08-02      2019-09-30
Grocery        2016-01-01      2018-01-01
Pharmacy       2015-03-01      2018-03-01
</code>```

What iam trying to accomplish is divide total days into respective years. The expected output is as below:

```<code>Department     RequestDate     ResponseDate   2015  2016  2017  2018  2019    TotalDays
Electronics    2019-05-01      2019-09-19      0      0    0     0     149     149
Babyshop       2018-08-02      2019-09-30      0      0    0     152   272     424
Grocery        2016-01-01      2018-01-01      0      365  365   1     0       731
Pharmacy       2015-03-01      2018-03-01      306    365  365   60    0       1096
</code>```

currently my workflow is in excel and it is tidious. Is there any way to make use of python functions.

答:
Here's a generic function that can return the number of days in each year between two datetime.datetime objects.

```<code>def days_per_year(dt1, dt2):
    ''' Return a list of years and number of days in that year
        occurring in the range between dt1 and dt2.
    '''
    # remove hours,minutes,seconds to turn these into pure dates
    dt1 = dt1.replace(hour=0, minute=0, second=0)
    dt2 = dt2.replace(hour=0, minute=0, second=0)
    if dt1 > dt2:
        dt1, dt2 = dt2, dt1 # swap if out of order
    ret = []
    for y in range(dt1.year, dt2.year + 1):
        year_end = min(dt2, datetime.datetime(y + 1, 1, 1))
        year_start = max(dt1, datetime.datetime(y, 1, 1))
        ret.append((y, (year_end - year_start).days))
    return ret

>>> for RequestDate, ResponseDate in (('2019-05-01','2019-09-19'),('2018-08-02','2019-09-30'),('2016-01-01','2018-01-01'),('2015-03-01','2018-03-01')):
    RequestDate = datetime.datetime.strptime(RequestDate, '%Y-%m-%d')
    ResponseDate = datetime.datetime.strptime(ResponseDate, '%Y-%m-%d')
    print(RequestDate, ResponseDate, days_per_year(RequestDate, ResponseDate))

2019-05-01 00:00:00 2019-09-19 00:00:00 [(2019, 141)]
2018-08-02 00:00:00 2019-09-30 00:00:00 [(2018, 152), (2019, 272)]
2016-01-01 00:00:00 2018-01-01 00:00:00 [(2016, 366), (2017, 365), (2018, 0)]
2015-03-01 00:00:00 2018-03-01 00:00:00 [(2015, 306), (2016, 366), (2017, 365), (2018, 59)]
</code>```

It's unclear if you want the last day to count or not, half your examples do but half don't.

Body:
Iam currently working on analyzing the delay in the response to a request made to each department. Format of data is as below:

Department     RequestDate     ResponseDate
Electronics    2019-05-01      2019-09-19
Babyshop       2018-08-02      2019-09-30
Grocery        2016-01-01      2018-01-01
Pharmacy       2015-03-01      2018-03-01

What iam trying to accomplish is divide total days into respective years. The expected output is as below:

Department     RequestDate     ResponseDate   2015  2016  2017  2018  2019    TotalDays
Electronics    2019-05-01      2019-09-19      0      0    0     0     149     149
Babyshop       2018-08-02      2019-09-30      0      0    0     152   272     424
Grocery        2016-01-01      2018-01-01      0      365  365   1     0       731
Pharmacy       2015-03-01      2018-03-01      306    365  365   60    0       1096

currently my workflow is in excel and it is tidious. Is there any way to make use of python functions.

Body:
Here's a generic function that can return the number of days in each year between two datetime.datetime objects.

def days_per_year(dt1, dt2):
    ''' Return a list of years and number of days in that year
        occurring in the range between dt1 and dt2.
    '''
    # remove hours,minutes,seconds to turn these into pure dates
    dt1 = dt1.replace(hour=0, minute=0, second=0)
    dt2 = dt2.replace(hour=0, minute=0, second=0)
    if dt1 > dt2:
        dt1, dt2 = dt2, dt1 # swap if out of order
    ret = []
    for y in range(dt1.year, dt2.year + 1):
        year_end = min(dt2, datetime.datetime(y + 1, 1, 1))
        year_start = max(dt1, datetime.datetime(y, 1, 1))
        ret.append((y, (year_end - year_start).days))
    return ret

>>> for RequestDate, ResponseDate in (('2019-05-01','2019-09-19'),('2018-08-02','2019-09-30'),('2016-01-01','2018-01-01'),('2015-03-01','2018-03-01')):
    RequestDate = datetime.datetime.strptime(RequestDate, '%Y-%m-%d')
    ResponseDate = datetime.datetime.strptime(ResponseDate, '%Y-%m-%d')
    print(RequestDate, ResponseDate, days_per_year(RequestDate, ResponseDate))

2019-05-01 00:00:00 2019-09-19 00:00:00 [(2019, 141)]
2018-08-02 00:00:00 2019-09-30 00:00:00 [(2018, 152), (2019, 272)]
2016-01-01 00:00:00 2018-01-01 00:00:00 [(2016, 366), (2017, 365), (2018, 0)]
2015-03-01 00:00:00 2018-03-01 00:00:00 [(2015, 306), (2016, 366), (2017, 365), (2018, 59)]

It's unclear if you want the last day to count or not, half your examples do but half don't.


问:
Angular Typescript, dealing with return data you are unsure of. Typecasting
How does one deal with a request with data you are not sure about and type checking.

To give a basic idea of what I mean, say I have an http call to an api, where random things can come back, but my component needs to work with an object that has an interface.

I have a more simple example below. Answer to simple example below too!

```<code> export interface IComponentData {
    copy1: string;
    total: string;
}

/* ----- */

componentCopy: IComponentData; // component data

componentCopyLoaded(data: { status: string; data: IComponentData }): void {
    if (data.status === 'error') {
        this.isError = true;
    } else if (data.status === 'success') {
        this.componentCopy = data.data;
    }
}

 ngOnInit(): void {
      this.subscriptions.add(
          this.getService
              .getSomeData('someurl')
              .subscribe(
                  data => this.componentCopyLoaded(data), <-ERROR HERE
                  error => this.componentCopyLoaded(error)
              )
        );
    }
</code>```

What the error says is

```<code>> Argument of type '{ status: string; data: {}; }' is not assignable to
> parameter of type '{ status: string; data: IComponentData; }'. Types
> of property 'data' are incompatible. Property 'total' is missing in
> type '{}' but required in type 'IComponentData'.ts(2345)
</code>```

Of course i can just make the interface properties optional, ie total?: string and the errors disappear but I might as well use any.

I have tried to use generics or extenting, but this is where I get lost, how does one get this to work?

eg

```<code>componentCopyLoaded<T>(data: { status: string; data: T }) <- does this make the data generic?
</code>```

Simple example

```<code>export interface IDataInterface {
    total: number;
}

data: IDataInterface;

dataReturned(data: IDataInterface): void {
    this.data = data;
}

sendData() {
    // I want to put an object in with any kind of data structure
    // Pretend this is a general service that does an api call to anywhere.
    this.dataReturned({total: 1}); <-- this works, sometimes data is this
    this.dataReturned({}); <-- this does not, sometimes data is this
}
</code>```

How it was fixed.
Thanks to joshvito pointing me in the right direction.

So the error was as the image shows

And the fix is

To remove that error the simple example I added this instead

```<code>dataReturned(data: unknown): void { <-- add unknown
    this.data = data as IComponentData; <-- this line removed the Type error
}

sendData() {
    this.dataReturned({total: 1});
    this.dataReturned({});
}
</code>```

答:
"...where random things can come back..." are they random, or is there a few interfaces you can infer dependent on how you call the endpoint. If the latter is true, your generic method will work, you just need to call it with the expected interface. Or can you write a base interface that the others can inherit from?

Probably adding a reproducible example or sharing the data types that are returned from the service call would be helpful for better guidance.

e.g.

```<code>componentCopy: IComponentData; // component data

componentCopyLoaded<T>(data: { status: string; data: T }): void {
    if (data.status === 'error') {
        this.isError = true;
    } else if (data.status === 'success') {
        this.componentCopy = data.data;
    }
}

 ngOnInit(): void {
      this.subscriptions.add(
          this.getService
              .getSomeData('someurl')
              .subscribe(
                  data => this.componentCopyLoaded<IComponentData>(data), <-ERROR HERE
                  error => this.componentCopyLoaded<IErrorData>(error)
              )
        );
    }
</code>```

Typescript has some great utility types too.
https://www.typescriptlang.org/docs/handbook/utility-types.html
For instance, you could use Partial or Required in your method declaration.

```<code>componentCopyLoaded(data: { status: string; data: Partial<IComponentData> }): void {...
</code>```

or

```<code>componentCopyLoaded(data: { status: string; data: Required<IRequiredData> }): void {...
</code>```

Body:
How does one deal with a request with data you are not sure about and type checking.

To give a basic idea of what I mean, say I have an http call to an api, where random things can come back, but my component needs to work with an object that has an interface.

I have a more simple example below. Answer to simple example below too!

 export interface IComponentData {
    copy1: string;
    total: string;
}

/* ----- */

componentCopy: IComponentData; // component data

componentCopyLoaded(data: { status: string; data: IComponentData }): void {
    if (data.status === 'error') {
        this.isError = true;
    } else if (data.status === 'success') {
        this.componentCopy = data.data;
    }
}

 ngOnInit(): void {
      this.subscriptions.add(
          this.getService
              .getSomeData('someurl')
              .subscribe(
                  data => this.componentCopyLoaded(data), <-ERROR HERE
                  error => this.componentCopyLoaded(error)
              )
        );
    }

What the error says is

> Argument of type '{ status: string; data: {}; }' is not assignable to
> parameter of type '{ status: string; data: IComponentData; }'. Types
> of property 'data' are incompatible. Property 'total' is missing in
> type '{}' but required in type 'IComponentData'.ts(2345)

Of course i can just make the interface properties optional, ie total?: string and the errors disappear but I might as well use any.

I have tried to use generics or extenting, but this is where I get lost, how does one get this to work?

eg

componentCopyLoaded<T>(data: { status: string; data: T }) <- does this make the data generic?

Simple example

export interface IDataInterface {
    total: number;
}

data: IDataInterface;

dataReturned(data: IDataInterface): void {
    this.data = data;
}

sendData() {
    // I want to put an object in with any kind of data structure
    // Pretend this is a general service that does an api call to anywhere.
    this.dataReturned({total: 1}); <-- this works, sometimes data is this
    this.dataReturned({}); <-- this does not, sometimes data is this
}

How it was fixed.
Thanks to joshvito pointing me in the right direction.

So the error was as the image shows

And the fix is

To remove that error the simple example I added this instead

dataReturned(data: unknown): void { <-- add unknown
    this.data = data as IComponentData; <-- this line removed the Type error
}

sendData() {
    this.dataReturned({total: 1});
    this.dataReturned({});
}

Body:
"...where random things can come back..." are they random, or is there a few interfaces you can infer dependent on how you call the endpoint. If the latter is true, your generic method will work, you just need to call it with the expected interface. Or can you write a base interface that the others can inherit from?

Probably adding a reproducible example or sharing the data types that are returned from the service call would be helpful for better guidance.

e.g.

componentCopy: IComponentData; // component data

componentCopyLoaded<T>(data: { status: string; data: T }): void {
    if (data.status === 'error') {
        this.isError = true;
    } else if (data.status === 'success') {
        this.componentCopy = data.data;
    }
}

 ngOnInit(): void {
      this.subscriptions.add(
          this.getService
              .getSomeData('someurl')
              .subscribe(
                  data => this.componentCopyLoaded<IComponentData>(data), <-ERROR HERE
                  error => this.componentCopyLoaded<IErrorData>(error)
              )
        );
    }

Typescript has some great utility types too.
https://www.typescriptlang.org/docs/handbook/utility-types.html
For instance, you could use Partial or Required in your method declaration.

componentCopyLoaded(data: { status: string; data: Partial<IComponentData> }): void {...

or

componentCopyLoaded(data: { status: string; data: Required<IRequiredData> }): void {...


问:
Given a dictionary and a list of floats L, how to find which keys has the closest value to each value in L?
Input1:

```<code>d = {1: 0.2, 2: 0.4, 3: 0.5, 4: 0.5, 5: 0.5, 6: 0.7, 7: 0.7, 8: 0.8, 9: 0.95, 10:1}
L = [0.48, 0.72]
</code>```

Expected result1: [3, 6]

Input2:

```<code>d = {1: 0.9, 2: 0.88, 3: 0.88, 4: 0.76, 5: 0.76, 6: 0.7, 7: 0.5, 8: 0.44, 9: 0.2, 10:0}
L = [0.48, 0.77]
</code>```

Expected result2: [7, 4]

You can assume the values in d is sorted (always increase or decrease as the key gets bigger)
If there are values that are equal, return the smallest key.

I'm able to do this in O(n), is there a better way to use binary search to do this?

Body:
Input1:

d = {1: 0.2, 2: 0.4, 3: 0.5, 4: 0.5, 5: 0.5, 6: 0.7, 7: 0.7, 8: 0.8, 9: 0.95, 10:1}
L = [0.48, 0.72]

Expected result1: [3, 6]

Input2:

d = {1: 0.9, 2: 0.88, 3: 0.88, 4: 0.76, 5: 0.76, 6: 0.7, 7: 0.5, 8: 0.44, 9: 0.2, 10:0}
L = [0.48, 0.77]

Expected result2: [7, 4]

You can assume the values in d is sorted (always increase or decrease as the key gets bigger)
If there are values that are equal, return the smallest key.

I'm able to do this in O(n), is there a better way to use binary search to do this?

Body:
One possible solution - without thorough testing - but it's not better than O(n):

def find_closest(source: dict, targets: list) -> list:
    result = {}
    for idx, target in enumerate(targets):
        last = None
        for key, val in source.items():
            if not last or abs(target - val) < last:
                last = abs(target - val)
                result[idx] = key
            elif abs(target - val) > last:
                break
    result = list(result.values())
    return result

if __name__ == '__main__':
    d1 = {1: 0.2, 2: 0.4, 3: 0.5, 4: 0.5, 5: 0.5, 6: 0.7, 7: 0.7, 8: 0.8, 9: 0.95, 10: 1}
    L1 = [0.48, 0.72]

    d2 = {1: 0.9, 2: 0.88, 3: 0.88, 4: 0.76, 5: 0.76, 6: 0.7, 7: 0.5, 8: 0.44, 9: 0.2, 10: 0}
    L2 = [0.48, 0.77]

    d3 = {1: 0.1, 2: 0.2, 3: 0.3, 4: 0.4, 5: 0.5, 6: 0.6, 7: 0.7, 8: 0.8, 9: 0.9, 10: 1.0}
    L3 = [0.48, 0.77]

    d4 = {1: 0.9, 2: 0.8, 3: 0.7, 4: 0.6, 5: 0.5, 6: 0.4, 7: 0.3, 8: 0.2, 9: 0.1, 10: 0.0}
    L4 = [0.48, 0.77]

    print(find_closest(d1, L1))
    print(find_closest(d2, L2))
    print(find_closest(d3, L3))
    print(find_closest(d4, L4))

[3, 6]
[7, 4]
[5, 8]
[5, 2]


问:
How to run a worker (continuously) on Azure App Service
I'm running a Django app on Azure App Service and planning to use django-background-tasks (or Django-Q) to run background tasks.

Whichever I choose, I will need to run some sort of workers after deploying the app to Azure.

For django-background-tasks, I will need to run
python manage.py process_tasks

For Django Q, I will need to run
python manage.py qcluster

And this is all fine if I run it from my computer's command prompt, but what about App Service? Is there anyway I keep these workers running?

答: You need to use App Service Web Jobs: https://learn.microsoft.com/en-us/azure/app-service/webjobs-create</p>


问:
asynchronous call using the NSOperationQueue
I am a beginner in developing iPhone applications.
I was doing this sample program below and got an error- invalid use of void expression

```<code>threadsss.h
------------
#import <Foundation/Foundation.h>

@interface threadsss : NSObject {

    BOOL m_bRunThread;
    int a,b,c;

}
-(void)Thread;
-(void)add;
-(void)display;
@end

threadsss.m
------------

#import "threadsss.h"

@implementation threadsss
-(void)Thread
{
    m_bRunThread = YES;
    NSOperationQueue* queue = [[NSOperationQueue alloc]init];
    NSInvocationOperation* operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(display) object:nil];
    [operation addDependency:[self add]];
    [queue addOperation:operation];
    [queue release];
}
-(void)add
{
    NSLog(@"Going to add a and b!!");
    a=1;
    b=2;
    c = a + b;
    NSLog(@"Finished adding!!");
}
-(void)display
{
    NSLog(@"Into the display method");
    NSLog(@"The value od c is:%d",c);
}
@end

main.m
-------
#import <Foundation/Foundation.h>
#import "threadsss.h"

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    threadsss* thread = [[threadss alloc]init];
    [thread Thread];

    [pool drain];
    return 0;
}
</code>```

I want to make an asynchronous call between the add and the display methods.After calling the display method i want to execute the add method. and in the meanwhile after printing the "I'm into the display method" the display method will wait for the add to perform its operation and the add after doing its operation will notify its completion to the display method.The display method will then print the result c.

I have tried to implement it with that in my mind.Do i need to do any other modification in my program or is the way i have implemented through dependecies is correct.

EDITED

```<code>threadss.h
-----------

#import <Foundation/Foundation.h>

@interface threadss : NSObject {

    BOOL m_bRunThread;
    int a,b,c;
    NSOperationQueue* queue;
    NSInvocationOperation* operation;
    NSInvocationOperation* operation1;
    NSConditionLock* theConditionLock;

}
-(void)Thread;
-(void)add;
-(void)display;
@end

threadss.m
-----------

#import "threadss.h"

@implementation threadss

-(id)init
{
    if (self = [super init]) {
     queue = [[NSOperationQueue alloc]init];
     operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(display) object:nil];
     operation1 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(add) object:nil];
     theConditionLock = [[NSConditionLock alloc]init];
    }
    return self;
}
-(void)Thread
{
    m_bRunThread = YES;

    //[operation addDependency:operation1];
    if (m_bRunThread) {
    [queue addOperation:operation];
    }
    //[operation addDependency:operation1];
    [queue addOperation:operation1];

    //[self performSelectorOnMainThread:@selector(display) withObject:nil waitUntilDone:YES];
    //NSLog(@"I'm going to do the asynchronous communication btwn the threads!!");
    //[self add];
    //[operation addDependency:self];
    sleep(1);
    [queue release];
    [operation release];
    //[operation1 release];
}
-(void)add
{
    NSLog(@"Going to add a and b!!");
    a=1;
    b=2;
    c = a + b;
    NSLog(@"Finished adding!!");
}
-(void)display
{
    NSLog(@"Into the display method");
    [operation1 waitUntilFinished];
    NSLog(@"The Result is:%d",c);

}
@end

main.m
------

#import <Foundation/Foundation.h>
#import "threadss.h"

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    threadss* thread = [[threadss alloc]init];
    [thread Thread];

    [pool drain];
    return 0;
}
</code>```

I made two operation queues.

But using waitUntilFinished on the same queue may lead to deadlock.How do i do the wait in display method for the add operation to complete its execution.

答:
First, it would be easier to answer your question if you identified the line than the compiler was complaining about and showing only the relevant code. However, in this case it's pretty straight-forward. It's this line:

```<code>[operation addDependency:[self add]];
</code>```

The add method returns nothing (void). And you're telling operation to add that as a dependency. What does that mean?

Either, you should change add to return self or call add on the line before:

```<code>[self add];
[operation addDependency:self];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am a beginner in developing iPhone applications.
I was doing this sample program below and got an error- invalid use of void expression

threadsss.h
------------
#import <Foundation/Foundation.h>

@interface threadsss : NSObject {

    BOOL m_bRunThread;
    int a,b,c;

}
-(void)Thread;
-(void)add;
-(void)display;
@end

threadsss.m
------------

#import "threadsss.h"

@implementation threadsss
-(void)Thread
{
    m_bRunThread = YES;
    NSOperationQueue* queue = [[NSOperationQueue alloc]init];
    NSInvocationOperation* operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(display) object:nil];
    [operation addDependency:[self add]];
    [queue addOperation:operation];
    [queue release];
}
-(void)add
{
    NSLog(@"Going to add a and b!!");
    a=1;
    b=2;
    c = a + b;
    NSLog(@"Finished adding!!");
}
-(void)display
{
    NSLog(@"Into the display method");
    NSLog(@"The value od c is:%d",c);
}
@end

main.m
-------
#import <Foundation/Foundation.h>
#import "threadsss.h"

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    threadsss* thread = [[threadss alloc]init];
    [thread Thread];

    [pool drain];
    return 0;
}

I want to make an asynchronous call between the add and the display methods.After calling the display method i want to execute the add method. and in the meanwhile after printing the "I'm into the display method" the display method will wait for the add to perform its operation and the add after doing its operation will notify its completion to the display method.The display method will then print the result c.

I have tried to implement it with that in my mind.Do i need to do any other modification in my program or is the way i have implemented through dependecies is correct.

EDITED

threadss.h
-----------

#import <Foundation/Foundation.h>

@interface threadss : NSObject {

    BOOL m_bRunThread;
    int a,b,c;
    NSOperationQueue* queue;
    NSInvocationOperation* operation;
    NSInvocationOperation* operation1;
    NSConditionLock* theConditionLock;

}
-(void)Thread;
-(void)add;
-(void)display;
@end

threadss.m
-----------

#import "threadss.h"

@implementation threadss

-(id)init
{
    if (self = [super init]) {
     queue = [[NSOperationQueue alloc]init];
     operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(display) object:nil];
     operation1 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(add) object:nil];
     theConditionLock = [[NSConditionLock alloc]init];
    }
    return self;
}
-(void)Thread
{
    m_bRunThread = YES;

    //[operation addDependency:operation1];
    if (m_bRunThread) {
    [queue addOperation:operation];
    }
    //[operation addDependency:operation1];
    [queue addOperation:operation1];

    //[self performSelectorOnMainThread:@selector(display) withObject:nil waitUntilDone:YES];
    //NSLog(@"I'm going to do the asynchronous communication btwn the threads!!");
    //[self add];
    //[operation addDependency:self];
    sleep(1);
    [queue release];
    [operation release];
    //[operation1 release];
}
-(void)add
{
    NSLog(@"Going to add a and b!!");
    a=1;
    b=2;
    c = a + b;
    NSLog(@"Finished adding!!");
}
-(void)display
{
    NSLog(@"Into the display method");
    [operation1 waitUntilFinished];
    NSLog(@"The Result is:%d",c);

}
@end

main.m
------

#import <Foundation/Foundation.h>
#import "threadss.h"

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    threadss* thread = [[threadss alloc]init];
    [thread Thread];

    [pool drain];
    return 0;
}

I made two operation queues.

But using waitUntilFinished on the same queue may lead to deadlock.How do i do the wait in display method for the add operation to complete its execution.

Body:
First, it would be easier to answer your question if you identified the line than the compiler was complaining about and showing only the relevant code. However, in this case it's pretty straight-forward. It's this line:

[operation addDependency:[self add]];

The add method returns nothing (void). And you're telling operation to add that as a dependency. What does that mean?

Either, you should change add to return self or call add on the line before:

[self add];
[operation addDependency:self];


问:
More pythonic way to test for is none
Which way to test for a variable == None is the more pythonic?

if var:

or

if var is not None

?

I personally would favor the primer. But the latter is more explicit.
https://www.python.org/dev/peps/pep-0020/

But for what benefit? Beginner programmers - should this be assumed in production grade software?

答:
You check explicitly with if var is not None:

Reason

```<code>does_not_work = 0

if does_not_work:
    print("Works - is not none")
else:
    print("Is None ... or not?")
</code>```

See  What is Truthy and Falsy? How is it different from True and False?

The simple test checks for truthyness - not None.

Title: More pythonic way to test for is none

Body:
You check explicitly with if var is not None:

Reason

does_not_work = 0

if does_not_work:
    print("Works - is not none")
else:
    print("Is None ... or not?")

See  What is Truthy and Falsy? How is it different from True and False?

The simple test checks for truthyness - not None.


问:
Compiler and Interpreter preferable
When is a compiled language more preferable to an interpreted language and vice versa ?

I know compiler compiles the whole code at once and produces the object code whereas interpreter interprets the code line by line.  When is one more advantageous to to the other?

答:
Advantages of compiled languages :

Programs that are compiled into native machine code tend to be faster
than interpreted code. This is because the process of translating
code at run time adds to the overhead, and can cause the program to
be slower overall.

Disadvantages of compiled languages :

Additional time needed to complete the entire compilation step before
testing

Platform dependence of the generated binary code

Advantages of interpreted languages :

Interpreted languages tend to be more flexible, and often offer
features like dynamic typing and smaller program size.

Also, because interpreters execute the source program code
themselves, the code itself is platform independent.

Disadvantages of interpreted languages :

The most notable disadvantage is typical execution speed compared to
compiled languages.

When one type of language is preferred over the other is based on the type of our application and our preference and priority like portability or cross-platform (interpreted may be preferred), speed or performance (compiled may be preferred) and various other factors.

One example :- If source code hiding is your priority- With natively compiled code the developer deploys the executable macine code of the program and data. With interpreted code the source code itself has to be deployed which can then be inspected and reverse-engineered wit much less effort than what it is to reverse-engineer native machine code .

But it will vary from task to task and also preference of the user/organization which will be using the language and would depend more on the functionalities provided by the language and how well its suited for that particular application rather than the type of language itself. There are lot of other factors that are enormously more consequential than compiled vs interpreted.

Also, if you are considering any software or website, they are seldom written in a single language. So, both the type of language - compiled and interpreted can be the part of same kind of application.

Title: Compiler and Interpreter preferable


问:
how to handle a variable number of arguments in django query
My current project has me building a page where the output can be filtered by category.  Meaning by default you get a full list of items but you can narrow the output by clicking on ( multiple or a single) check boxes.  The idea would be if you only want to see the results from two categories you can choose those two and just see items from those two categories.  (think like an Amazon page where you can can search for an item but filter the results)

This works through a form using the get method.  So the url will look something like:

ip/?family=category_one&family=category_two

My code is as below:

Please note the Firmware model is related to ProductModel through a ManyToManyField and ProductModel is related to Family through a ForeignKey relation

*models

```<code>class Family(models.Model):
    family_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    slug = models.SlugField(null=False, unique=True)
    family_name = models.CharField(max_length=50, editable=True, unique=True)

class ProductModel(models.Model):
    model_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    model_number = models.CharField(max_length=25, editable=True, unique=True)
    family_id = models.ForeignKey(Family, on_delete=models.DO_NOTHING, editable=True, null=False, blank=False)

class Firmware(models.Model):
    firmware_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    version = models.CharField(max_length=50, help_text='The \'version number\' of the firmware',
                               editable=True)
    model_id = models.ManyToManyField(ProductModel, editable=True)
</code>```

*View:

```<code>class FirmwareListView(ListView):
    model = Firmware
    context_object_name = 'firmwares'
    qs = QuerySet()

    def get(self, request, *args, **kwargs):
        requested_families = request.GET.getlist("family")
        if requested_families:
            query = Q(model_id__family_id__family_name__iexact=requested_families[0])
            for f in range(1, len(requested_families)):
                query = query | Q(model_id__family_id__family_name__iexact=requested_families[f])
            self.qs = Firmware.objects.filter(query)
        else:
            self.qs = Firmware.objects.all()
        return super().get(request, *args, **kwargs)

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data()
        context['firmware_list'] = self.qs
        return context
</code>```

The most important parts here are:

```<code>        requested_families = request.GET.getlist("family")
        if requested_families:
            query = Q(model_id__family_id__family_name__iexact=requested_families[0])
            for f in range(1, len(requested_families)):
                query = query | Q(model_id__family_id__family_name__iexact=requested_families[f])
            self.qs = Firmware.objects.filter(query)
</code>```

This query will work (in that it runs and returns results but the results are wrong.  The results seem to be as if they ignore the exact requirement and only run a contains query.  In other words, if I filter by the category foo I will get results for food and foo.  If I run the query by doing the below:

```<code>self.qs = Firmware.objects.filter(Q(model_id__family_id__family_name__iexact=requested_families[0]) | Q(model_id__family_id__family_name__iexact=requested_families[1]))
</code>```

and I choose two categories the result is perfect.  Of course I cannot use the above method in production since I will never know how many categories a user will choose.

I have seen this post  ( Django query with variable number of filter arguments ) and tried all of the suggestions there with no luck.

I believe the issue is I am trying to filter on a field from a model that runs through a many to many field then a foreign key.  There is no way to get around this (that I can think of at least)

Any help offered is greatly appreciated.  I am a bit stuck on this one but there must be a way to do it.  For now the only method I can think of is to perform a separate query on each term and then combine the results at the end.

答:
Figured this one out after much effort.  Well I caused my own problem. First I as passing my query result through another method (I did not mention it in my original question since I thought it was irrelevant) which changed the query.

This second method sorted the output in a unique way.  When I started to look closer at that method I noticed the queryset changed all of sudden in the middle of it.  I found where I made the mistake and voila!  It works fine now.

Bottom line is the method of creating a variable amount of query parameters using the aforementioned method (and re-shown below) work perfect.

To make a variable number of query parameters in Django you can use:

```<code>class ViewName():
    qs = QuerySet()

    def get(self, request, *args, **kwargs):
        get_queries = request.GET.getlist('named_get')
        if get_queries:
            query = Q(query_type=get_queries[0])
                for t in range(1, len(filtered_types)):
                    query = query | Q(query_type=get_queries[t]) #obviously if you need an and here just substitute in & where | currently is
            Model.objects.filter(query)
</code>```

Body:
My current project has me building a page where the output can be filtered by category.  Meaning by default you get a full list of items but you can narrow the output by clicking on ( multiple or a single) check boxes.  The idea would be if you only want to see the results from two categories you can choose those two and just see items from those two categories.  (think like an Amazon page where you can can search for an item but filter the results)

This works through a form using the get method.  So the url will look something like:

ip/?family=category_one&family=category_two

My code is as below:

Please note the Firmware model is related to ProductModel through a ManyToManyField and ProductModel is related to Family through a ForeignKey relation

*models

class Family(models.Model):
    family_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    slug = models.SlugField(null=False, unique=True)
    family_name = models.CharField(max_length=50, editable=True, unique=True)

class ProductModel(models.Model):
    model_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    model_number = models.CharField(max_length=25, editable=True, unique=True)
    family_id = models.ForeignKey(Family, on_delete=models.DO_NOTHING, editable=True, null=False, blank=False)

class Firmware(models.Model):
    firmware_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    version = models.CharField(max_length=50, help_text='The \'version number\' of the firmware',
                               editable=True)
    model_id = models.ManyToManyField(ProductModel, editable=True)

*View:

class FirmwareListView(ListView):
    model = Firmware
    context_object_name = 'firmwares'
    qs = QuerySet()

    def get(self, request, *args, **kwargs):
        requested_families = request.GET.getlist("family")
        if requested_families:
            query = Q(model_id__family_id__family_name__iexact=requested_families[0])
            for f in range(1, len(requested_families)):
                query = query | Q(model_id__family_id__family_name__iexact=requested_families[f])
            self.qs = Firmware.objects.filter(query)
        else:
            self.qs = Firmware.objects.all()
        return super().get(request, *args, **kwargs)

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data()
        context['firmware_list'] = self.qs
        return context

The most important parts here are:

        requested_families = request.GET.getlist("family")
        if requested_families:
            query = Q(model_id__family_id__family_name__iexact=requested_families[0])
            for f in range(1, len(requested_families)):
                query = query | Q(model_id__family_id__family_name__iexact=requested_families[f])
            self.qs = Firmware.objects.filter(query)

This query will work (in that it runs and returns results but the results are wrong.  The results seem to be as if they ignore the exact requirement and only run a contains query.  In other words, if I filter by the category foo I will get results for food and foo.  If I run the query by doing the below:

self.qs = Firmware.objects.filter(Q(model_id__family_id__family_name__iexact=requested_families[0]) | Q(model_id__family_id__family_name__iexact=requested_families[1]))

and I choose two categories the result is perfect.  Of course I cannot use the above method in production since I will never know how many categories a user will choose.

I have seen this post  ( Django query with variable number of filter arguments ) and tried all of the suggestions there with no luck.

I believe the issue is I am trying to filter on a field from a model that runs through a many to many field then a foreign key.  There is no way to get around this (that I can think of at least)

Any help offered is greatly appreciated.  I am a bit stuck on this one but there must be a way to do it.  For now the only method I can think of is to perform a separate query on each term and then combine the results at the end.

Body:
Figured this one out after much effort.  Well I caused my own problem. First I as passing my query result through another method (I did not mention it in my original question since I thought it was irrelevant) which changed the query.

This second method sorted the output in a unique way.  When I started to look closer at that method I noticed the queryset changed all of sudden in the middle of it.  I found where I made the mistake and voila!  It works fine now.

Bottom line is the method of creating a variable amount of query parameters using the aforementioned method (and re-shown below) work perfect.

To make a variable number of query parameters in Django you can use:

class ViewName():
    qs = QuerySet()

    def get(self, request, *args, **kwargs):
        get_queries = request.GET.getlist('named_get')
        if get_queries:
            query = Q(query_type=get_queries[0])
                for t in range(1, len(filtered_types)):
                    query = query | Q(query_type=get_queries[t]) #obviously if you need an and here just substitute in & where | currently is
            Model.objects.filter(query)


问:
Best strategy to reset Oracle sequence monthly
I'm looking for the best strategy to reset a sequence which is used to generate unique keys. These keys are build using a prefix value, also generated by a combination of month and year values, like the following example:

2020060100000001 - Year(4d)Month(2d)Sequence(8d)

The sequence value must be restarted at the first second of each new month.

Is there any Oracle event that allows calling a function or procedure based in this situation to do this job?

Can anyone help me with opinions and experiences?

Thanks a lot!
Rodrigo

答:
If you really want to set the value of a sequence you can use something like the following:</p>

```<code>PROCEDURE SET_SEQUENCE(pinSequence_owner IN VARCHAR2,
                       pinSequence_name  IN VARCHAR2,
                       pinNew_next_value IN NUMBER,
                       pinDebug          IN BOOLEAN := FALSE)
IS
  strSQL               VARCHAR2(4000);
  nNext_number         NUMBER;
  nOriginal_increment  NUMBER;
  nNew_nextval         NUMBER;
  nNew_last_number     NUMBER;
BEGIN
  strSQL := 'SELECT s.LAST_NUMBER, INCREMENT_BY ' ||
              'FROM DBA_SEQUENCES s ' ||
              'WHERE s.SEQUENCE_OWNER = ''' || pinSequence_owner || ''' AND ' ||
                    's.SEQUENCE_NAME = ''' || pinSequence_name || '''';
  EXECUTE IMMEDIATE strSQL INTO nNext_number, nOriginal_increment;

  -- Note that DBA_SEQUENCES.LAST_NUMBER represents the *next* number which will be
  -- returned by a call to NEXTVAL.

  IF pinNew_next_value NOT IN (nNext_number-1, nNext_number)
  THEN
    strSQL := 'ALTER SEQUENCE ' || pinSequence_owner || '.' || pinSequence_name ||
              ' INCREMENT BY ' || TO_CHAR(pinNew_next_value - nNext_number) || ' NOCACHE';
    EXECUTE IMMEDIATE strSQL;

    strSQL := 'SELECT ' || pinSequence_owner || '.' || pinSequence_name || '.NEXTVAL FROM DUAL';
    EXECUTE IMMEDIATE strSQL INTO nNew_nextval;

    strSQL := 'ALTER SEQUENCE ' || pinSequence_owner || '.' || pinSequence_name ||
              ' INCREMENT BY ' || nOriginal_increment || ' NOCACHE';
    EXECUTE IMMEDIATE strSQL;

    strSQL := 'SELECT s.LAST_NUMBER FROM DBA_SEQUENCES s WHERE s.SEQUENCE_OWNER = ''' || pinSequence_owner ||
                ''' AND s.SEQUENCE_NAME = ''' || pinSequence_name || '''';
    EXECUTE IMMEDIATE strSQL INTO nNew_last_number;
  END IF;
END SET_SEQUENCE;
</code>```

Body:
If you really want to set the value of a sequence you can use something like the following:

PROCEDURE SET_SEQUENCE(pinSequence_owner IN VARCHAR2,
                       pinSequence_name  IN VARCHAR2,
                       pinNew_next_value IN NUMBER,
                       pinDebug          IN BOOLEAN := FALSE)
IS
  strSQL               VARCHAR2(4000);
  nNext_number         NUMBER;
  nOriginal_increment  NUMBER;
  nNew_nextval         NUMBER;
  nNew_last_number     NUMBER;
BEGIN
  strSQL := 'SELECT s.LAST_NUMBER, INCREMENT_BY ' ||
              'FROM DBA_SEQUENCES s ' ||
              'WHERE s.SEQUENCE_OWNER = ''' || pinSequence_owner || ''' AND ' ||
                    's.SEQUENCE_NAME = ''' || pinSequence_name || '''';
  EXECUTE IMMEDIATE strSQL INTO nNext_number, nOriginal_increment;

  -- Note that DBA_SEQUENCES.LAST_NUMBER represents the *next* number which will be
  -- returned by a call to NEXTVAL.

  IF pinNew_next_value NOT IN (nNext_number-1, nNext_number)
  THEN
    strSQL := 'ALTER SEQUENCE ' || pinSequence_owner || '.' || pinSequence_name ||
              ' INCREMENT BY ' || TO_CHAR(pinNew_next_value - nNext_number) || ' NOCACHE';
    EXECUTE IMMEDIATE strSQL;

    strSQL := 'SELECT ' || pinSequence_owner || '.' || pinSequence_name || '.NEXTVAL FROM DUAL';
    EXECUTE IMMEDIATE strSQL INTO nNew_nextval;

    strSQL := 'ALTER SEQUENCE ' || pinSequence_owner || '.' || pinSequence_name ||
              ' INCREMENT BY ' || nOriginal_increment || ' NOCACHE';
    EXECUTE IMMEDIATE strSQL;

    strSQL := 'SELECT s.LAST_NUMBER FROM DBA_SEQUENCES s WHERE s.SEQUENCE_OWNER = ''' || pinSequence_owner ||
                ''' AND s.SEQUENCE_NAME = ''' || pinSequence_name || '''';
    EXECUTE IMMEDIATE strSQL INTO nNew_last_number;
  END IF;
END SET_SEQUENCE;


问:
cmake add_custom_command + Xcode: multi output = multi command invocation
I have custom command that generate several headers at once.
All works fine with make/ninja files generated by cmake.
But if I generate Xcode project via cmake -GXCode,
then instead of once gen.sh was invoked 10 times
and not only that, it also will be invoked every build,
even if timestamps of generated file are younger then gen_in.txt.

How can I fix this?

```<code>project(multi_output)
cmake_minimum_required(VERSION 3.17)

set(MANY_HEADERS test0.h test1.h  test2.h  test3.h  test4.h  test5.h  test6.h  test7.h  test8.h  test9.h)

add_custom_command(
  OUTPUT ${MANY_HEADERS}
  COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/gen.sh
  DEPENDS gen_in.txt
  WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
  )

add_executable(foo main.cpp ${MANY_HEADERS})
</code>```

where gen.sh is

#!/bin/sh

echo "gen.sh: start"
sleep 1
echo "gen.sh: hard work done"
for i in `seq 0 9`; do
    cat gen_in.txt > test$i.h
    sed -i bak s/placeholder/$i/g test$i.h
done
```

答:
In OUTPUT option relative paths are treated as relative to the binary directory.

That is, your add_custom_command actually doesn't produce the files declared as OUTPUT.

This is why it is called more and more: the build tool finds out that an OUTPUT file does not exist, and runs the COMMAND for build that file. (Many build tool don't check whether the OUTPUT file is actually created.)

For files created in the source directory you need to specify their absolute path in OUTPUT option:

```<code>set(MANY_HEADERS test0.h test1.h  test2.h  test3.h  test4.h  test5.h  test6.h  test7.h  test8.h  test9.h)
# This will be a list of _absolute paths_ to the headers
set(MANY_HEADERS_ABS)

foreach(HEADER ${MANY_HEADERS})
  list(APPEND MANY_HEADERS_ABS "${CMAKE_CURRENT_SOURCE_DIR}/${HEADER}")
endforeach()

add_custom_command(
  OUTPUT ${MANY_HEADERS_ABS}
  COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/gen.sh
  DEPENDS gen_in.txt
  WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
  )

# In add_executable one could use relative paths too
add_executable(foo main.cpp ${MANY_HEADERS})
</code>```

Note, that add_executable command may accept relative paths to the file both in source and binary trees.

CMake checks whether a file exists or generated (e.g. with add_custom_command) in the source tree, and if it is, the source path is used. Then similar checks are performed for binary tree. (And if this check fails, CMake will emit an error).

Actually, careful inspecting of the make output may give a hint, whether make rebuilds files in the source tree or in the build tree.

This is what is produced by the original code (remember: make is called from the build directory):

```<code>[ 33%] Generating test0.h, test1.h, test2.h, test3.h, test4.h, test5.h, test6.h, test7.h, test8.h, test9.h
</code>```

And this is what is produced when use absolute paths to the source tree. (Out-of-source build, use build/ subdirectory for build.)

```<code>[ 33%] Generating ../test0.h, ../test1.h, ../test2.h, ../test3.h, ../test4.h, ../test5.h, ../test6.h, ../test7.h, ../test8.h, ../test9.h
</code>```

Body:
I have custom command that generate several headers at once.
All works fine with make/ninja files generated by cmake.
But if I generate Xcode project via cmake -GXCode,
then instead of once gen.sh was invoked 10 times
and not only that, it also will be invoked every build,
even if timestamps of generated file are younger then gen_in.txt.

How can I fix this?

project(multi_output)
cmake_minimum_required(VERSION 3.17)

set(MANY_HEADERS test0.h test1.h  test2.h  test3.h  test4.h  test5.h  test6.h  test7.h  test8.h  test9.h)

add_custom_command(
  OUTPUT ${MANY_HEADERS}
  COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/gen.sh
  DEPENDS gen_in.txt
  WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
  )

add_executable(foo main.cpp ${MANY_HEADERS})

where gen.sh is

#!/bin/sh

echo "gen.sh: start"
sleep 1
echo "gen.sh: hard work done"
for i in `seq 0 9`; do
    cat gen_in.txt > test$i.h
    sed -i bak s/placeholder/$i/g test$i.h
done

Body:
In OUTPUT option relative paths are treated as relative to the binary directory.

That is, your add_custom_command actually doesn't produce the files declared as OUTPUT.

This is why it is called more and more: the build tool finds out that an OUTPUT file does not exist, and runs the COMMAND for build that file. (Many build tool don't check whether the OUTPUT file is actually created.)

For files created in the source directory you need to specify their absolute path in OUTPUT option:

set(MANY_HEADERS test0.h test1.h  test2.h  test3.h  test4.h  test5.h  test6.h  test7.h  test8.h  test9.h)
# This will be a list of _absolute paths_ to the headers
set(MANY_HEADERS_ABS)

foreach(HEADER ${MANY_HEADERS})
  list(APPEND MANY_HEADERS_ABS "${CMAKE_CURRENT_SOURCE_DIR}/${HEADER}")
endforeach()

add_custom_command(
  OUTPUT ${MANY_HEADERS_ABS}
  COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/gen.sh
  DEPENDS gen_in.txt
  WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
  )

# In add_executable one could use relative paths too
add_executable(foo main.cpp ${MANY_HEADERS})

Note, that add_executable command may accept relative paths to the file both in source and binary trees.

CMake checks whether a file exists or generated (e.g. with add_custom_command) in the source tree, and if it is, the source path is used. Then similar checks are performed for binary tree. (And if this check fails, CMake will emit an error).

Actually, careful inspecting of the make output may give a hint, whether make rebuilds files in the source tree or in the build tree.

This is what is produced by the original code (remember: make is called from the build directory):

[ 33%] Generating test0.h, test1.h, test2.h, test3.h, test4.h, test5.h, test6.h, test7.h, test8.h, test9.h

And this is what is produced when use absolute paths to the source tree. (Out-of-source build, use build/ subdirectory for build.)

[ 33%] Generating ../test0.h, ../test1.h, ../test2.h, ../test3.h, ../test4.h, ../test5.h, ../test6.h, ../test7.h, ../test8.h, ../test9.h


问:
How to cover test for button click in angular? (Stackblitz attached)
I am making a very simple application which has one input box and a button.

Input is for entering email

Subscribe button with event handler

Entering email and click over the button will make an api call, (This method works)

```<code>  subscribeEmail() {
    this.error = '';

        if (this.userForm.controls.email.status === 'VALID') {

      const params = new HttpParams()
                .set('EMAIL', this.userForm.controls.email.value)
        .set('subscribe','Subscribe')
        .set('b_aaa7182511d7bd278fb9d510d_01681f1b55','')
      console.log(params);
            const mailChimpUrl = this.mailChimpEndpoint + params.toString();

            this.http.jsonp<MailChimpResponse>(mailChimpUrl, 'c').subscribe(response => {
        console.log('response ', response)
                if (response.result && response.result !== 'error') {
                    this.submitted = true;
                }
                else {
                    this.error = response.msg;
                }
            }, error => {
                console.error(error);
                this.error = 'Sorry, an error occurred.';
            });
        }
  }
</code>```

A complete working example here

There is no issues with it and you can also check everything works fine.

Requirement: I am in the need to cover test case for this button click and the http call with params.

I am unable to write the test case and it is showing that the tests are not covered for the http calls with params.

The tests that I have written so for for achieving the button click scenario like,

```<code>describe('HelloComponent', () => {

  let component: HelloComponent;
  let fixture: ComponentFixture<HelloComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
       imports: [
        HttpClientTestingModule,
        ReactiveFormsModule
      ],
      declarations: [HelloComponent]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(HelloComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('check subscribeEmail function has value', (done: DoneFn) => {

    const subscribeButton = fixture.debugElement.query(By.css('.subscribe'));
    subscribeButton.triggerEventHandler('click', {});

    done();
  });
});
</code>```

And the Working stackblitz with test cases here

(Please look into hello.component.spec.ts )

For button click, I have covered and it works

```<code>    const subscribeButton = fixture.debugElement.query(By.css('.subscribe'));
    subscribeButton.triggerEventHandler('click', {});
</code>```

Could you please help me to achieve the result of covering the test case for the button click that has http call with params?

Update:
After some search I have found that I can use httpmock to call the url with params but I am ending up with error as,

Error: Expected one matching request for criteria "Match URL:
  https://gmail.us10.list-manage.com/subscribe/post-json?u=aaa7182511d7bd278fb9d510d&id=01681f1b55&amp",
  found none.

You can also see the Modified stackblitz with httpMock here...

After all try only I am making this post so please consider this question and provide right solution.

A big thanks in advance.

答:
Indeed it would be better to re-factory the code and make it more test friendly.
But the provided example still could be covered with tests. The idea to verify the passed parameters and if parameters are correct then return a predictable response as an observable.

so, the this.http.jsonp returns the expected result only if passed parameters are correct.

import { ComponentFixture, TestBed, async, fakeAsync, tick } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement, Injector }  from '@angular/core';

import { HelloComponent } from './hello.component';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ReactiveFormsModule } from '@angular/forms';
import { moqInjectorProviders, resolveMock } from 'ng-auto-moq';
import { Mock, It } from 'moq.ts';
import { HttpClient, HttpParams } from '@angular/common/http';
import { cold, getTestScheduler } from 'jasmine-marbles';

describe('HelloComponent', () => {
  let component: HelloComponent;
  let fixture: ComponentFixture<HelloComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
       imports: [
        HttpClientTestingModule,
        ReactiveFormsModule
      ],
      declarations: [HelloComponent],
      // setups automatically all dependecies of the component as mock objects
      providers: moqInjectorProviders(HelloComponent)
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(HelloComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('check subscribeEmail function has value', fakeAsync(() => {
    const injector = TestBed.get(Injector);

    // sets mock behaviour
    resolveMock(HttpClient, injector)
      // if jsonp is invoked with first parameter with email substring
      .setup(instance => instance.jsonp(It.Is<string>(url => url.indexOf('me@gmail.com') > 1), 'c'))
      // only in this case return a cold observable
      .returns(cold("a", {a: {result: "success"}}));

    const email = fixture.debugElement.query(By.css('.email-input')).nativeElement;
    // sets email value
    email.value = 'me@gmail.com';
    // notifies angualr that element has changed
    email.dispatchEvent(new Event('input'));

    const subscribeButton = fixture.debugElement.query(By.css('.subscribe'));
    subscribeButton.triggerEventHandler('click', {});

    // flush the observable of jsonp
    getTestScheduler().flush();
    fixture.detectChanges();

    expect(component.submitted).toBe(true);
  }));

  it('sets error when server returns an error', fakeAsync(() => {
    const injector = TestBed.get(Injector);
    const msg = "erorr message";

    resolveMock(HttpClient, injector)
      .setup(instance => instance.jsonp(It.Is<string>(url => url.indexOf('me@gmail.com') > 1), 'c'))
      .returns(cold("a", {a: {result: "error", msg}}));

    const email = fixture.debugElement.query(By.css('.email-input')).nativeElement;
    email.value = 'me@gmail.com';
    email.dispatchEvent(new Event('input'));

    const subscribeButton = fixture.debugElement.query(By.css('.subscribe'));
    subscribeButton.triggerEventHandler('click', {});

    getTestScheduler().flush();
    fixture.detectChanges();

    expect(component.error).toEqual(msg);
  }));
});
```

Here you can find an working example

Please, noticed the I used some extra libs like jasmine-marbles to fake observables or moq.ts to mock HttpClient

Body:
I am making a very simple application which has one input box and a button.

Input is for entering email

Subscribe button with event handler

Entering email and click over the button will make an api call, (This method works)

  subscribeEmail() {
    this.error = '';

        if (this.userForm.controls.email.status === 'VALID') {

      const params = new HttpParams()
                .set('EMAIL', this.userForm.controls.email.value)
        .set('subscribe','Subscribe')
        .set('b_aaa7182511d7bd278fb9d510d_01681f1b55','')
      console.log(params);
            const mailChimpUrl = this.mailChimpEndpoint + params.toString();

            this.http.jsonp<MailChimpResponse>(mailChimpUrl, 'c').subscribe(response => {
        console.log('response ', response)
                if (response.result && response.result !== 'error') {
                    this.submitted = true;
                }
                else {
                    this.error = response.msg;
                }
            }, error => {
                console.error(error);
                this.error = 'Sorry, an error occurred.';
            });
        }
  }

A complete working example here

There is no issues with it and you can also check everything works fine.

Requirement: I am in the need to cover test case for this button click and the http call with params.

I am unable to write the test case and it is showing that the tests are not covered for the http calls with params.

The tests that I have written so for for achieving the button click scenario like,

describe('HelloComponent', () => {

  let component: HelloComponent;
  let fixture: ComponentFixture<HelloComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
       imports: [
        HttpClientTestingModule,
        ReactiveFormsModule
      ],
      declarations: [HelloComponent]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(HelloComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('check subscribeEmail function has value', (done: DoneFn) => {

    const subscribeButton = fixture.debugElement.query(By.css('.subscribe'));
    subscribeButton.triggerEventHandler('click', {});

    done();
  });
});

And the Working stackblitz with test cases here

(Please look into hello.component.spec.ts )

For button click, I have covered and it works

    const subscribeButton = fixture.debugElement.query(By.css('.subscribe'));
    subscribeButton.triggerEventHandler('click', {});

Could you please help me to achieve the result of covering the test case for the button click that has http call with params?

Update:
After some search I have found that I can use httpmock to call the url with params but I am ending up with error as,

Error: Expected one matching request for criteria "Match URL:
  https://gmail.us10.list-manage.com/subscribe/post-json?u=aaa7182511d7bd278fb9d510d&id=01681f1b55&amp",
  found none.

You can also see the Modified stackblitz with httpMock here...

After all try only I am making this post so please consider this question and provide right solution.

A big thanks in advance.

Body:
Indeed it would be better to re-factory the code and make it more test friendly.
But the provided example still could be covered with tests. The idea to verify the passed parameters and if parameters are correct then return a predictable response as an observable.

so, the this.http.jsonp returns the expected result only if passed parameters are correct.

import { ComponentFixture, TestBed, async, fakeAsync, tick } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement, Injector }  from '@angular/core';

import { HelloComponent } from './hello.component';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ReactiveFormsModule } from '@angular/forms';
import { moqInjectorProviders, resolveMock } from 'ng-auto-moq';
import { Mock, It } from 'moq.ts';
import { HttpClient, HttpParams } from '@angular/common/http';
import { cold, getTestScheduler } from 'jasmine-marbles';

describe('HelloComponent', () => {
  let component: HelloComponent;
  let fixture: ComponentFixture<HelloComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
       imports: [
        HttpClientTestingModule,
        ReactiveFormsModule
      ],
      declarations: [HelloComponent],
      // setups automatically all dependecies of the component as mock objects
      providers: moqInjectorProviders(HelloComponent)
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(HelloComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('check subscribeEmail function has value', fakeAsync(() => {
    const injector = TestBed.get(Injector);

    // sets mock behaviour
    resolveMock(HttpClient, injector)
      // if jsonp is invoked with first parameter with email substring
      .setup(instance => instance.jsonp(It.Is<string>(url => url.indexOf('me@gmail.com') > 1), 'c'))
      // only in this case return a cold observable
      .returns(cold("a", {a: {result: "success"}}));

    const email = fixture.debugElement.query(By.css('.email-input')).nativeElement;
    // sets email value
    email.value = 'me@gmail.com';
    // notifies angualr that element has changed
    email.dispatchEvent(new Event('input'));

    const subscribeButton = fixture.debugElement.query(By.css('.subscribe'));
    subscribeButton.triggerEventHandler('click', {});

    // flush the observable of jsonp
    getTestScheduler().flush();
    fixture.detectChanges();

    expect(component.submitted).toBe(true);
  }));

  it('sets error when server returns an error', fakeAsync(() => {
    const injector = TestBed.get(Injector);
    const msg = "erorr message";

    resolveMock(HttpClient, injector)
      .setup(instance => instance.jsonp(It.Is<string>(url => url.indexOf('me@gmail.com') > 1), 'c'))
      .returns(cold("a", {a: {result: "error", msg}}));

    const email = fixture.debugElement.query(By.css('.email-input')).nativeElement;
    email.value = 'me@gmail.com';
    email.dispatchEvent(new Event('input'));

    const subscribeButton = fixture.debugElement.query(By.css('.subscribe'));
    subscribeButton.triggerEventHandler('click', {});

    getTestScheduler().flush();
    fixture.detectChanges();

    expect(component.error).toEqual(msg);
  }));
});

Here you can find an working example

Please, noticed the I used some extra libs like jasmine-marbles to fake observables or moq.ts to mock HttpClient


问:
Is it possible to install an app permanently via the IPA file?
my doubt is this: I developed and published an app on the AppStore (with auto-renwable in-app purchase).
A company would like to sell my app to its customers and they ask me if it is possible to have it without going through the store.
I thought about the IPA file, downloadable and installable directly from an external site.

is there any way to do it? Preventing expiration messages .. In short, install it completely.

Without jailbreak possibly

答:
You can distribute your app without Apple Store. You will need to enroll for Enterprise Account for this. But you can not use in-app purchase which Apple provides. You will need to use other payment gateways.

Also, the enterprise account certificates have 3 years of validity.
More info: https://developer.apple.com/programs/enterprise/


问:
Local Web API 2 Authorize not working with Azure identity token
I have a project that is using SSO and is returning access and identity tokens from Azure AD.  I get the tokens back just fine upon redirect, as well as the role assignments for the login but when attempting to access API endpoints I get HTTP 401 on my local machine but it works just fine on the test server.

I have the [Authorize] prefix for my endpoints and I've tried hitting endpoints with and without the role assignments.  I'm using web config transforms and I've double checked the URLs for the allowed origin to make sure that they're correct.

This just makes it really difficult when trying to debug as I have to push the frontend or backend to the test server instead of being able to work on my local machine.

答:
You would be getting an 403 forbidden status code if it was a role issue.

Ensure the access token retrieved locally aud claim matches the API uri id, which usually follows the format api://{app id}. If that's not the case then locally you're targeting a different API.


问:
Authentication with firebase and angular. How to navigate to other component after the user log in?
I want to authenticate a site that is written in Angular, with the help of firebase.

I found a guide that describes in a detailed and clear way how to do it.

Website address: https://www.positronx.io/full-angular-7-firebase-authentication-system/

The github that the guide attached:https://github.com/SinghDigamber/angularfirebase-authentication

I followed the instructions but i didn't succeed to navigate to other component  after the user logs in (The user remains on the same page).
 when I ran the code from the github, I encountered the same problem.

Partial code from auth.service.ts:

```<code>  // Sign in with email/password
  SignIn(email, password) {
    alert(":)");
    return this.afAuth.signInWithEmailAndPassword(email, password)
      .then((result) => {
        this.ngZone.run(() => {
          this.router.navigate(['/dashboard']);
        });
        this.SetUserData(result.user);
      }).catch((error) => {
        window.alert(error.message)
      })
  }
</code>```

Why the user does not navigate to dashboard component after login?

What could be the cause of the problem? Thank you.

EDIT:
I'll add the code here that I think is relevant:

auth.service.ts:

```<code>import { Injectable, NgZone } from '@angular/core';
//import { User } from "../services/user";
//import { auth } from 'firebase/app';
import { AngularFireAuth } from "@angular/fire/auth";
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';
import { Router } from "@angular/router";

export interface User {
  email: string;
}

@Injectable({
  providedIn: 'root'
})

export class AuthService {
  userData: any; // Save logged in user data
  authStateSubs: any;
  //authStateSubs: any;

  constructor(
    public afs: AngularFirestore,   // Inject Firestore service
    public afAuth: AngularFireAuth, // Inject Firebase auth service
    public router: Router,
    public auth: AngularFireAuth,
    public ngZone: NgZone // NgZone service to remove outside scope warning
  ) {

    /* Saving user data in localstorage when
    logged in and setting up null when logged out */
    this.afAuth.authState.subscribe(user => {
      if (user) {
        this.userData = user;
        localStorage.setItem('user', JSON.stringify(this.userData));
        JSON.parse(localStorage.getItem('user'));

      } else {
        localStorage.setItem('user', null);
        JSON.parse(localStorage.getItem('user'));
      }
    })
  }

  // Sign in with email/password
  SignIn(email, password) {
    return this.afAuth.signInWithEmailAndPassword(email, password)
      .then((result) => {
        alert("after signInWithEmailAndPassword");
        this.ngZone.run(() => {
          alert("after ngZone.run");
          this.router.navigate(['/authorized-zone']);
        });
        this.SetUserData(result.user);
      }).catch((error) => {
        window.alert(error.message)
      })
  }

  // Returns true when user is looged in and email is verified
  get isLoggedIn(): boolean {
    const user = JSON.parse(localStorage.getItem('user'));
    return (user !== null && user.emailVerified !== false) ? true : false;
  }

  /* Setting up user data when sign in with username/password,
  sign up with username/password and sign in with social auth
  provider in Firestore database using AngularFirestore + AngularFirestoreDocument service */
  SetUserData(user) {
    const userRef: AngularFirestoreDocument<any> = this.afs.doc(`users/${user.email}`);
    const userData: User = {
      email: user.email,
    }
    return userRef.set(userData, {
      merge: true
    })
  }

  // Sign out
  SignOut() {
    return this.afAuth.signOut().then(() => {
      localStorage.removeItem('user');
      this.router.navigate(['login']);
    })
  }
}
</code>```

auth.guard.ts:

```<code>import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { AuthService } from "../services/auth.service";
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class AuthGuard implements CanActivate {

  constructor(
    public authService: AuthService,
    public router: Router
  ){ }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if(this.authService.isLoggedIn !== true) {
      this.router.navigate(['login'])
    }
    return true;
  }

}
</code>```

答:
you can try to wait navigation result with promise, maybe it never happens

    this.router.navigate(['dashboard']).then(succeeded => {
      this.SetUserData(result.user);
    });
```
<p>you can use async/await to simplify promise code, in example</p>
<pre class="lang-js prettyprint-override"><code>    async signIn(email, password) {
      alert(":)");
      const result = await this.afAuth.signInWithEmailAndPassword(email, password);

      const succeeded = await this.router.navigate(['dashboard']);

      if (succeeded) {
        this.SetUserData(result.user);
      }
    }
</code>```

try to fork these example and replace environment.ts with your own settings and test how it work

Body:
I want to authenticate a site that is written in Angular, with the help of firebase.

I found a guide that describes in a detailed and clear way how to do it.

Website address: https://www.positronx.io/full-angular-7-firebase-authentication-system/

The github that the guide attached:https://github.com/SinghDigamber/angularfirebase-authentication

I followed the instructions but i didn't succeed to navigate to other component  after the user logs in (The user remains on the same page).
 when I ran the code from the github, I encountered the same problem.

Partial code from auth.service.ts:

  // Sign in with email/password
  SignIn(email, password) {
    alert(":)");
    return this.afAuth.signInWithEmailAndPassword(email, password)
      .then((result) => {
        this.ngZone.run(() => {
          this.router.navigate(['/dashboard']);
        });
        this.SetUserData(result.user);
      }).catch((error) => {
        window.alert(error.message)
      })
  }

Why the user does not navigate to dashboard component after login?

What could be the cause of the problem? Thank you.

EDIT:
I'll add the code here that I think is relevant:

auth.service.ts:

import { Injectable, NgZone } from '@angular/core';
//import { User } from "../services/user";
//import { auth } from 'firebase/app';
import { AngularFireAuth } from "@angular/fire/auth";
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';
import { Router } from "@angular/router";

export interface User {
  email: string;
}

@Injectable({
  providedIn: 'root'
})

export class AuthService {
  userData: any; // Save logged in user data
  authStateSubs: any;
  //authStateSubs: any;

  constructor(
    public afs: AngularFirestore,   // Inject Firestore service
    public afAuth: AngularFireAuth, // Inject Firebase auth service
    public router: Router,
    public auth: AngularFireAuth,
    public ngZone: NgZone // NgZone service to remove outside scope warning
  ) {

    /* Saving user data in localstorage when
    logged in and setting up null when logged out */
    this.afAuth.authState.subscribe(user => {
      if (user) {
        this.userData = user;
        localStorage.setItem('user', JSON.stringify(this.userData));
        JSON.parse(localStorage.getItem('user'));

      } else {
        localStorage.setItem('user', null);
        JSON.parse(localStorage.getItem('user'));
      }
    })
  }

  // Sign in with email/password
  SignIn(email, password) {
    return this.afAuth.signInWithEmailAndPassword(email, password)
      .then((result) => {
        alert("after signInWithEmailAndPassword");
        this.ngZone.run(() => {
          alert("after ngZone.run");
          this.router.navigate(['/authorized-zone']);
        });
        this.SetUserData(result.user);
      }).catch((error) => {
        window.alert(error.message)
      })
  }

  // Returns true when user is looged in and email is verified
  get isLoggedIn(): boolean {
    const user = JSON.parse(localStorage.getItem('user'));
    return (user !== null && user.emailVerified !== false) ? true : false;
  }

  /* Setting up user data when sign in with username/password,
  sign up with username/password and sign in with social auth
  provider in Firestore database using AngularFirestore + AngularFirestoreDocument service */
  SetUserData(user) {
    const userRef: AngularFirestoreDocument<any> = this.afs.doc(`users/${user.email}`);
    const userData: User = {
      email: user.email,
    }
    return userRef.set(userData, {
      merge: true
    })
  }

  // Sign out
  SignOut() {
    return this.afAuth.signOut().then(() => {
      localStorage.removeItem('user');
      this.router.navigate(['login']);
    })
  }
}

auth.guard.ts:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { AuthService } from "../services/auth.service";
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class AuthGuard implements CanActivate {

  constructor(
    public authService: AuthService,
    public router: Router
  ){ }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if(this.authService.isLoggedIn !== true) {
      this.router.navigate(['login'])
    }
    return true;
  }

}

Body:
you can try to wait navigation result with promise, maybe it never happens

    this.router.navigate(['dashboard']).then(succeeded => {
      this.SetUserData(result.user);
    });

you can use async/await to simplify promise code, in example

    async signIn(email, password) {
      alert(":)");
      const result = await this.afAuth.signInWithEmailAndPassword(email, password);

      const succeeded = await this.router.navigate(['dashboard']);

      if (succeeded) {
        this.SetUserData(result.user);
      }
    }

try to fork these example and replace environment.ts with your own settings and test how it work


问:
Import JS file inside node_modules in Angular
I have an angular app, to this I am trying to add an npm package called svgedit. It gets installed. But when I try to reference a java-script file it says

net::ERR_ABORTED 404 (Not Found)

This is how I am trying to reference it in my index.html in the head section,

```<code><script type="module" src="node_modules/svgedit/svgedit-config-es.js"></script>
</code>```

I can access this file from within vs code by clicking "ctrl + left mouse". It opens the file properly meaning the reference is proper. But when it runs it gives the above mentioned error in the console. I have also tried switching the type attribute to "text/javascript".

Basically I am trying to integrate this package in my angular app. What is the correct method to go about it.

答:
Basically I am trying to integrate this package in my angular app. What is the correct method to go about it.

The right way to go about it is to use a bundler like webpack, rollup etc...

Body:
I have an angular app, to this I am trying to add an npm package called svgedit. It gets installed. But when I try to reference a java-script file it says

net::ERR_ABORTED 404 (Not Found)

This is how I am trying to reference it in my index.html in the head section,

I can access this file from within vs code by clicking "ctrl + left mouse". It opens the file properly meaning the reference is proper. But when it runs it gives the above mentioned error in the console. I have also tried switching the type attribute to "text/javascript".

Basically I am trying to integrate this package in my angular app. What is the correct method to go about it.


问:
'Future<dynamic>' has no instance getter 'body' error, when trying to access body of Future SmsMessage variable in Flutter
This is a class in a seperate file

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

class SmsReader {
  SmsMessage sms;
  dynamic messageRead() async {
    SmsReceiver receiver = SmsReceiver();
    receiver.onSmsReceived.listen((SmsMessage msg) {
      sms = msg;
    });
    return sms;
  }
}
</code>```

this file is where an object is created and func is called

```<code>class _HomePageState extends State<HomePage> {

  SmsReader smsReader = SmsReader();
  dynamic sms;

  @override
  void initState() {
    sms = smsReader.messageRead();
    super.initState();
  }
</code>```

Now when I try to
print(sms.body), this error appears

Class 'Future' has no instance getter 'body'.
Receiver: Instance of 'Future'
Tried calling: body

答:
You are defining messageRead as:

dynamic messageRead() async {
```

<p>All <code>async</code> functions should return a <code>Future</code>, you are returning <code>dynamic</code> which defines that "every Type is ok here".</p>

<p>later you are calling <code>messageRead</code> without <code>await</code>, so it returns just a <code>Future</code>. You need to change your code to <code>await</code> <code>messageRead</code>:</p>

<pre class="lang-dart prettyprint-override"><code>Future<SmsMessage> messageRead() async {

...

SmsMessage sms;

...

smsReader.messageRead().then((newSms) => sms = newSms);
</code>```

You need to use then instead of await as you can't await inside the initState function.

Body:
This is a class in a seperate file

import 'package:sms/sms.dart';

class SmsReader {
  SmsMessage sms;
  dynamic messageRead() async {
    SmsReceiver receiver = SmsReceiver();
    receiver.onSmsReceived.listen((SmsMessage msg) {
      sms = msg;
    });
    return sms;
  }
}

this file is where an object is created and func is called

class _HomePageState extends State<HomePage> {

  SmsReader smsReader = SmsReader();
  dynamic sms;

  @override
  void initState() {
    sms = smsReader.messageRead();
    super.initState();
  }

Now when I try to
print(sms.body), this error appears

Class 'Future' has no instance getter 'body'.
Receiver: Instance of 'Future'
Tried calling: body

Body:
You are defining messageRead as:

dynamic messageRead() async {

All async functions should return a Future, you are returning dynamic which defines that "every Type is ok here".

later you are calling messageRead without await, so it returns just a Future. You need to change your code to await messageRead:

Future<SmsMessage> messageRead() async {

...

SmsMessage sms;

...

smsReader.messageRead().then((newSms) => sms = newSms);

You need to use then instead of await as you can't await inside the initState function.


问:
Internals of systemtap
I want to know what actually happens internally when the event written in the tap file occurs and how it is handled? </p>

答:
You should read the documents presented at the end of the SystemTap Documentation page, especially the Locating System Problems Using Dynamic Instrumentation OLS paper, to know a bit more about the internals.

The Introduction to KProbes article at LWN is worth a read too.

Title: Internals of systemtap


问:
How to display a single record in database using Laravel and vue js?
HI how can I display a single record on database using vue js ? I managed to display multiple but I cant display a single row. This is what i did .

```<code><template>
  <div class="container">
    <div class="card-panel z-depth-5 grey lighten-2">
      <blockquote>
        <h3>
          <b>{{tutorial.attributes.title}}</b>
        </h3>
      </blockquote>
      <p class="flow-text">{{tutorial.attributes.content}}</p>
    </div>
  </div>
</template>

<script>
export default {
    name: 'tutorial',
  data: function() {
    return {
        tutorial = {
            id: '',
            content : null,
            title : '',
        },
    };
  },
  mounted() {
    const tutorial_id = this.id;
  },
  props: ['id'],
  methods: {
    get_tutorial: function() {
      //load the tutorials from the api
      axios
        .get('/api/view/' + tutorial_id )
        .then(response => {
          // asign it to data
          this.id = response.data.data.id;
          this.cpntent = response.data.data.content;

        })
        .catch(function(error) {
          // catch errors
          console.log(error);
        });
    }
  }
};
</script>
</code>```

this is my api route : (if i go to '/api/view/1') im successfully fetching the data i think my main mistake here is displaying it.

```<code>Route::get('/view/{id}','TutorialsController@view_tutorial');

 public function view_tutorial($id){
      return TutorialResource::collection(Post::all()->where('id',$id));
}
</code>```

this is my blade :

```<code>@extends('layouts.main')
@section('styles')
<style>
.card-panel {
  border-radius:5px;
}
</style>
@stop
@section('content')

    <div class="app  ">
          <view-tutorial
          :id="{{ $post->id }}"
          >
          </view-tutorial>
    </div>

@endsection

@section('scripts')
<script>
<script src="{{mix('js/app.js')}}"></script>
</script>
@ensection
</code>```

basically i have an href in my template  :href="'/post/' + tutorial.id + '/' + tutorial.slug" that when i click it redirects me to a page where i show the content of the post. this is my web route for that Route::get('/post/{id}/{slug}', 'PostController@read_post');
when i hit that it successfully redirect me to a view where in that view i will display data using vue js. In my template there is a props that will send the Id to the component and do some axios get request using that id so that i will get the specific record in my db. I can display  it with default blade syntax but for the sake of learning im trying it on vue js. Sorry for the noob question.

this is my errors :
In my console :
    SyntaxError: C:\projects\php\blogSite\resources\js\components\View_tutorial.vue: Unexpected token (19:17)

In my command prompt :

```<code>SyntaxError: C:\projects\php\blogSite\resources\js\components\View_tutorial.vue: Unexpected token (19:17)

  17 |   data: function() {
  18 |     return {
> 19 |         tutorial = {
     |                  ^
  20 |             id: '',
  21 |             content : null,
  22 |             title : '',
</code>```

Thanks. I'll appreciate all the help.

答:
You can use route model binding. And get specific record from your database.

Read documents:
https://laravel.com/docs/7.x/routing#route-model-binding

Body:
HI how can I display a single record on database using vue js ? I managed to display multiple but I cant display a single row. This is what i did .

<template>

          {{tutorial.attributes.title}}

{{tutorial.attributes.content}}

</template>

this is my api route : (if i go to '/api/view/1') im successfully fetching the data i think my main mistake here is displaying it.

Route::get('/view/{id}','TutorialsController@view_tutorial');

 public function view_tutorial($id){
      return TutorialResource::collection(Post::all()->where('id',$id));
}

this is my blade :

@extends('layouts.main')
@section('styles')

@stop
@section('content')

          <view-tutorial
          :id="{{ $post->id }}"
          >
          </view-tutorial>

@endsection

@section('scripts')

</script>
@ensection

basically i have an href in my template  :href="'/post/' + tutorial.id + '/' + tutorial.slug" that when i click it redirects me to a page where i show the content of the post. this is my web route for that Route::get('/post/{id}/{slug}', 'PostController@read_post');
when i hit that it successfully redirect me to a view where in that view i will display data using vue js. In my template there is a props that will send the Id to the component and do some axios get request using that id so that i will get the specific record in my db. I can display  it with default blade syntax but for the sake of learning im trying it on vue js. Sorry for the noob question.

this is my errors :
In my console :
    SyntaxError: C:\projects\php\blogSite\resources\js\components\View_tutorial.vue: Unexpected token (19:17)

In my command prompt :

SyntaxError: C:\projects\php\blogSite\resources\js\components\View_tutorial.vue: Unexpected token (19:17)

  17 |   data: function() {
  18 |     return {
> 19 |         tutorial = {
     |                  ^
  20 |             id: '',
  21 |             content : null,
  22 |             title : '',

Thanks. I'll appreciate all the help.


问:
How can I set up SSO with Azure AD and our back end strapi?
I am wondering if anyone has done this before,

I have an azure Active Directory, and I host the front end of our app in IIS. The back is controlled by pm2. How can I set up SSO with Azure AD and our back end strapi?

Thank you for any help

答:
You can easily implement authentication using Azure AD in your strapi CRM web project.

Steps to follow:

Register an application in Azure AD.

Add target API, and grant consent to select permissions.

Choose your Microsoft authentication library ,recommended MSAL

Implement the MSAL library  in your project. It is very simple to implement and code sample that can help you is available here.

Please let me know if you still have any issues.


问:
How to subtract two identical dataframes in pandas
I have got two identical dataframes in pandas/python (a and b) only values are different:

a:

```<code>date       a1 a2 a3
01.01.2020 2  2  2
02.01.2020 3  3  3
03.01.2020 4  4  4
</code>```

b:

```<code>date       a1 a2 a3
01.01.2020 1  1  1
01.01.2020 2  2  2
01.01.2020 3  3  3
</code>```

I need a - b and expect to see result c:

```<code>date       a1 a2 a3
01.01.2020 1  1  1
01.01.2020 1  1  1
01.01.2020 1  1  1
</code>```

a - b does not work and I cannot figure out how. Would you please help me? Thanks!

答:
Assuming that dates in both dataframes are identical,
you can use df.sub:

```<code>df = a.set_index('date').sub(b.set_index('date')).reset_index()
</code>```

Output:

```<code>         date  a1  a2  a3
0  01.01.2020   1   1   1
1  01.01.2020   1   1   1
2  01.01.2020   1   1   1
</code>```

Body:
I have got two identical dataframes in pandas/python (a and b) only values are different:

a:

date       a1 a2 a3
01.01.2020 2  2  2
02.01.2020 3  3  3
03.01.2020 4  4  4

b:

date       a1 a2 a3
01.01.2020 1  1  1
01.01.2020 2  2  2
01.01.2020 3  3  3

I need a - b and expect to see result c:

date       a1 a2 a3
01.01.2020 1  1  1
01.01.2020 1  1  1
01.01.2020 1  1  1

a - b does not work and I cannot figure out how. Would you please help me? Thanks!

Body:
Assuming that dates in both dataframes are identical,
you can use df.sub:

df = a.set_index('date').sub(b.set_index('date')).reset_index()

Output:

         date  a1  a2  a3
0  01.01.2020   1   1   1
1  01.01.2020   1   1   1
2  01.01.2020   1   1   1


问:
Promise.allSettled in babel ES6 implementation
I'm using babel to transpile my node.js@0.10.x code and I'm stuck with promises.

I need allSettled-type functionality that I could use in q and bluebird or angular.$q for example.

On babel's core-js Promise, there is no allSettled method.

Currently I'm using q.allSettled as a workaround:

import { allSettled } from 'q';

Is there something like that in babel polyfill? Alternatively, which is a good algorithm for me to try to implement?

答:
my implementation will be below</p>

```<code>Promise.prototype.myAllSettled = function (arr = []) {
  return new Promise(function processIterable(resolve, reject) {
    let result = [];
    arr.forEach((item) => {
      item
        .then((value) => {
          result.push({ status: "fulfilled", value: value });
          if (arr.length === result.length) resolve(result);
        })
        .catch((err) => {
          result.push({ status: "rejected", reason: `${err}` });
          if (arr.length === result.length) resolve(result);
        });
    });
  });
};
</code>```

Body:
my implementation will be below

Promise.prototype.myAllSettled = function (arr = []) {
  return new Promise(function processIterable(resolve, reject) {
    let result = [];
    arr.forEach((item) => {
      item
        .then((value) => {
          result.push({ status: "fulfilled", value: value });
          if (arr.length === result.length) resolve(result);
        })
        .catch((err) => {
          result.push({ status: "rejected", reason: `${err}` });
          if (arr.length === result.length) resolve(result);
        });
    });
  });
};