问:
Map yarn build output to stage an artifact
I'm trying to use an Azure DevOps yarn YAML task to build my site. That step completes. But where does the built code go?

```<code>##[section]Starting: Yarn
    Task         : Yarn task
Description  : Executes Yarn
Version      : 2.8.1001
Author       : Geek Learning
Help         : [More Information](https://github.com/geeklearningio/gl-vsts-tasks-yarn/wiki/Yarn) (Version 2.8.1001).

Dear Angular and Ember CLI users, please check our [known issues](https://github.com/geeklearningio/gl-vsts-tasks-yarn/wiki/Known-Issues)
==============================================================================
SYSTEMVSSCONNECTION exists true
SYSTEMVSSCONNECTION exists true
    [command]C:\windows\system32\cmd.exe /D /S /C "C:\npm\prefix\yarn.cmd --production build"
yarn install v1.15.2
    [1/4] Resolving packages...
[2/4] Fetching packages...
info fsevents@1.2.4: The platform "win32" is incompatible with this module.
    info "fsevents@1.2.4" is an optional dependency and failed compatibility check. Excluding it from installation.
    info fsevents@1.2.7: The platform "win32" is incompatible with this module.
    info "fsevents@1.2.7" is an optional dependency and failed compatibility check. Excluding it from installation.
    [3/4] Linking dependencies...
warning " > bootstrap@4.3.1" has unmet peer dependency "jquery@1.9.1 - 3".
    warning " > bootstrap@4.3.1" has unmet peer dependency "popper.js@^1.14.7".
    [4/4] Building fresh packages...
Done in 119.26s.
##[section]Finishing: Yarn

##[section]Starting: Stage Files
    ==============================================================================
    Task         : Copy Files
Description  : Copy files from source folder to target folder using match patterns (The match patterns will only match file paths, not folder paths)
Version      : 2.117.2
Author       : Microsoft Corporation
Help         : [More Information](https://go.microsoft.com/fwlink/?LinkID=708389)

##[error]Unhandled: Not found SourceFolder: D:\a\1\a\s\build\
##[section]Finishing: Stage Files
</code>```

Here is my YAML

```<code>task: Yarn@2
inputs:
    ProjectDirectory: './'
Arguments: 'build'
ProductionMode: true

    - task: CopyFiles@2
displayName: 'Stage Files'
inputs:
    SourceFolder: 'D:\_work\1\s\build'
Contents: '**'
TargetFolder: '$(Build.ArtifactStagingDirectory)/dist'
CleanTargetFolder: true
OverWrite: true
</code>```

I have been playing around with the SourceFolder and having no luck.

Adding a "dir" command seems to show that I am in the root folder for my project, but I do not see a build folder

答:
```<code>##[error]Unhandled: Not found SourceFolder: D:\a\1\a\s\build\
</code>```

According to this message, I think the error caused by that the path of source folder are not be specified correctly.

As I mentioned in comments,this value is relevant with your agent local path. Anyway, no matter what the agent is, you can use one same variable to get it: Build.SourcesDirectory.

It is a predefined variable which can get the local path on the agent where your source code file are downloaded.

So, my suggestion is: modify your SourceFolder value as

```<code>inputs:
SourceFolder: '$(Build.SourcesDirectory)'
</code>```

to get your correct build path.

Body:
I'm trying to use an Azure DevOps yarn YAML task to build my site. That step completes. But where does the built code go?

##[section]Starting: Yarn
    Task         : Yarn task
Description  : Executes Yarn
Version      : 2.8.1001
Author       : Geek Learning
Help         : [More Information](https://github.com/geeklearningio/gl-vsts-tasks-yarn/wiki/Yarn) (Version 2.8.1001).

Dear Angular and Ember CLI users, please check our [known issues](https://github.com/geeklearningio/gl-vsts-tasks-yarn/wiki/Known-Issues)
==============================================================================
SYSTEMVSSCONNECTION exists true
SYSTEMVSSCONNECTION exists true
    [command]C:\windows\system32\cmd.exe /D /S /C "C:\npm\prefix\yarn.cmd --production build"
yarn install v1.15.2
    [1/4] Resolving packages...
[2/4] Fetching packages...
info fsevents@1.2.4: The platform "win32" is incompatible with this module.
    info "fsevents@1.2.4" is an optional dependency and failed compatibility check. Excluding it from installation.
    info fsevents@1.2.7: The platform "win32" is incompatible with this module.
    info "fsevents@1.2.7" is an optional dependency and failed compatibility check. Excluding it from installation.
    [3/4] Linking dependencies...
warning " > bootstrap@4.3.1" has unmet peer dependency "jquery@1.9.1 - 3".
    warning " > bootstrap@4.3.1" has unmet peer dependency "popper.js@^1.14.7".
    [4/4] Building fresh packages...
Done in 119.26s.
##[section]Finishing: Yarn

##[section]Starting: Stage Files
    ==============================================================================
    Task         : Copy Files
Description  : Copy files from source folder to target folder using match patterns (The match patterns will only match file paths, not folder paths)
Version      : 2.117.2
Author       : Microsoft Corporation
Help         : [More Information](https://go.microsoft.com/fwlink/?LinkID=708389)

##[error]Unhandled: Not found SourceFolder: D:\a\1\a\s\build\
##[section]Finishing: Stage Files

Here is my YAML

task: Yarn@2
inputs:
    ProjectDirectory: './'
Arguments: 'build'
ProductionMode: true

    - task: CopyFiles@2
displayName: 'Stage Files'
inputs:
    SourceFolder: 'D:\_work\1\s\build'
Contents: '**'
TargetFolder: '$(Build.ArtifactStagingDirectory)/dist'
CleanTargetFolder: true
OverWrite: true

I have been playing around with the SourceFolder and having no luck.

Adding a "dir" command seems to show that I am in the root folder for my project, but I do not see a build folder

Body:
##[error]Unhandled: Not found SourceFolder: D:\a\1\a\s\build\

According to this message, I think the error caused by that the path of source folder are not be specified correctly.

As I mentioned in comments,this value is relevant with your agent local path. Anyway, no matter what the agent is, you can use one same variable to get it: Build.SourcesDirectory.

It is a predefined variable which can get the local path on the agent where your source code file are downloaded.

So, my suggestion is: modify your SourceFolder value as

inputs:
SourceFolder: '$(Build.SourcesDirectory)'

to get your correct build path.


来源: stackexchange

问:
How do I get resource file values in Visual Basic?
I'm new to Visual Basic, and I'm having issues accessing the resource file for my project.

```<code>Dim rm As Resources.ResourceManager = New Resources.ResourceManager("MyProjectName.My.Resources.Resources", [Assembly].GetExecutingAssembly())
Dim myValue = rm.GetString(lookUpKey) 'boom Object reference not set to an instance of an object.
</code>```

I think the issue is with the string "MyProjectName.My.Resources.Resources".

Would I be better off moving the strings into their own resource file?

答:
I thought it was something similar to:

```<code>my.Resource.whateverhere
</code>```

Is that not the kind of resources you are looking for?

ContentLicense: CC BY-SA 3.0

Body:
I'm new to Visual Basic, and I'm having issues accessing the resource file for my project.

Dim rm As Resources.ResourceManager = New Resources.ResourceManager("MyProjectName.My.Resources.Resources", [Assembly].GetExecutingAssembly())
Dim myValue = rm.GetString(lookUpKey) 'boom Object reference not set to an instance of an object.

I think the issue is with the string "MyProjectName.My.Resources.Resources".

Would I be better off moving the strings into their own resource file?

Body:
I thought it was something similar to:

my.Resource.whateverhere

Is that not the kind of resources you are looking for?


问:
Which function can be used to show elements and which can be used to hide them?
I am looking for an Android Studio version of "gameobject.SetActive(true/false);" from Unity. Is there a one? If there is
how to call it?</p>

答:
If the element you're referring to is a View then you would use setVisibility:</p>

```<code>view.setVisibility(View.VISIBLE); //view is visible
view.setVisibility(View.INVISIBLE); //view is invisible, but still takes up space
view.setVisibility(View.GONE); //view is no longer visible, and does not take up space

</code>```

ContentLicense: CC BY-SA 4.0

Body:
If the element you're referring to is a View then you would use setVisibility:

view.setVisibility(View.VISIBLE); //view is visible
view.setVisibility(View.INVISIBLE); //view is invisible, but still takes up space
view.setVisibility(View.GONE); //view is no longer visible, and does not take up space


问:
Why is the positive lookahead in my pcregrep Regex not working?
I wrote a Regex using pcregrep, and everything behaved as expected until I added a positive lookahead.

Scenario:

I have the following text file:

```<code>a
b
c
a
c
</code>```

Goal:

I want to use a Regex with pcregrep to return a line containing a and a line containing c with a line containing b between them that is not captured. So it would capture the first three lines (a, b, c) and return the first (a) and third (c) line. It would not capture the fourth and fifth line because there is no b line between them. So the output would be:

```<code>a
c
</code>```

What I've tried

If I run pcregrep -M 'a\nb\nc\n' (command 1), this captures and returns:

```<code>a
b
c
</code>```

as expected. So I now want to modify this to capture the b line with a positive lookahead. I tried this: pcregrep -M 'a\n(?=(b\n))c\n' (command 2). However, this returns nothing.

My question:

Why does command 2 not return the expected output, where command 1 does? How can I return the desired result? I know there are ways to do this other than pcregrep, but please note that I want to use pcregrep because I'll be extending the functionality to solve similar problems.

答:
Why does command 2 not return the expected output, where command 1 does?
  Because command 2 is a different expression

(?=…) is a ZERO WIDTH lookahead

what you specified is: I want an a, followed by a linefeed followed by a bfollowed by a linefeed. At that position I also want a c followed by a linefeed.

P.S. to just get the a and c maybe this will help?

pcregrep -M 'a\nb\nc\n' | pcregrep -M 'a|c'

Body:
I wrote a Regex using pcregrep, and everything behaved as expected until I added a positive lookahead.

Scenario:

I have the following text file:

a
b
c
a
c

Goal:

I want to use a Regex with pcregrep to return a line containing a and a line containing c with a line containing b between them that is not captured. So it would capture the first three lines (a, b, c) and return the first (a) and third (c) line. It would not capture the fourth and fifth line because there is no b line between them. So the output would be:

a
c

What I've tried

If I run pcregrep -M 'a\nb\nc\n' (command 1), this captures and returns:

a
b
c

as expected. So I now want to modify this to capture the b line with a positive lookahead. I tried this: pcregrep -M 'a\n(?=(b\n))c\n' (command 2). However, this returns nothing.

My question:

Why does command 2 not return the expected output, where command 1 does? How can I return the desired result? I know there are ways to do this other than pcregrep, but please note that I want to use pcregrep because I'll be extending the functionality to solve similar problems.


问:
Why does this code with a character array, which was given a variable as size, compile?
Playing around with templates, I ran into an interesting phenomenon w.r.t to array and defining its size, which I thought is not allowed in C++.

I used a global variable to define the size of an array inside main(), and it worked for some reason (see code below)

1) Why does this even compile? I thought only constexpr may be used for array size

2) Suppose the above is valid, it still does not explain why it works even when sz = 8 which is clearly less than the size of the character string

3) Why are we getting that weird '@' and '?'. I tried different combination of strings, for example, only number characters ("123456789") and it did not appear.

Appreciate any help. Thanks.

Here is my code

```<code>#include <iostream>
#include <cstring>

using namespace std;

int sz = 8;

int main()
{
    const char temp[sz] = "123456abc"; //9 characters + 1 null?

    cout << temp << endl;

    return 0;
}
</code>```

Output:

123456ab�
@

答:
1) Why does this even compile? I thought only constexpr may be used for array size

The asker is correct that Variable Length Arrays  (VLAs) are not Standard C++. The g++ compiler includes support for VLAs by extension. How can this be? A compiler developer can add pretty much anything it wants so long as the behaviour required by the Standard is met. It is up to the developer to document the behaviour.

2) Suppose the above is valid, it still does not explain why it works even when sz = 8 which is clearly less than the size of the character string

Normally g++ emits an error if an array is initialized with values that exceed the size of the array. I have to confirm with documentation to see whether the C++ Standard requires an error in this case. It seems like a good place for an error, but I can't remember if an error is required.

In this case it appears that the VLA extension has a side effect that eliminates the error g++ normally spits out for trying to overfill an array. This makes a lot of sense since the compiler doesn't know the size of the array, in the general case, at compile time and cannot perform the test. No test, no error.

None of this is covered by the C++ Standard because VLA is not supported.

A quick look through the C standard, which does permit VLAs, didn't turn up any guidance for this case. C the rules for initializing VLAs are pretty simple: You can't. The compiler doesn't know how big the array will be at compile time, so it can't initialize. There may be an exception for string literals, but I haven't found one.

I also have not found a good description of the behaviour in GCC documentation.

clang produces the error I expect based on my read of the C standard: error: variable-sized object may not be initialized

Addendum: Probably should have checked Stack Overflow first and saved myself a lot of time: Initializing variable length array .

3) Why are we getting that weird '@' and '?'. I tried different combination of strings, for example, only number characters ("123456789") and it did not appear.

What appears to be happening, and since none of this is standard I have no quotes to back it up, is the string literal is copied into the VLA up to the size of the VLA. The portions of the literal past the end of the VLA are silently discarded. This includes the null terminator, and the behaviour is undefined when printing an unterminated char array.

Solution:

Stick to Standardized behaviour where possible. The major compilers have options to warn you of non-Standard code. Use -pedantic with compilers using the gcc options and /permissive- with recent versions of Visual Studio. When forced to step outside the Standard, consult the compiler documentation or the implementers themselves for the sticky-or-undocumented bits.

If you don't get good answers, try to find another path.

Body:
Playing around with templates, I ran into an interesting phenomenon w.r.t to array and defining its size, which I thought is not allowed in C++.

I used a global variable to define the size of an array inside main(), and it worked for some reason (see code below)

1) Why does this even compile? I thought only constexpr may be used for array size

2) Suppose the above is valid, it still does not explain why it works even when sz = 8 which is clearly less than the size of the character string

3) Why are we getting that weird '@' and '?'. I tried different combination of strings, for example, only number characters ("123456789") and it did not appear.

Appreciate any help. Thanks.

Here is my code

#include <iostream>
#include <cstring>

using namespace std;

int sz = 8;

int main()
{
    const char temp[sz] = "123456abc"; //9 characters + 1 null?

    cout << temp << endl;

    return 0;
}

Output:

123456ab�
@


问:
Is there a way to use Selenium with a page which HTML code is not public?
I'm trying to use Selenium automation but the web page I'm working on doesn't show its HTML code when I try to inspect it.

I've tried to use the information that I have access to but no results so far

Here is a snippet of what I have acces to on the login page:

```<code><body scroll="no" style="margin: 0px;" onfocus="gotFocus()">
<div id="webuidiv" style="width: 100%; height: 100%; position: absolute; z-index: 50;">
<embed name="Framework" width="100%" height="100%" align="baseline" id="Framework" src="" type="application/x-java-applet;version=1.6" codebase="../applets" archive=",jide-common.jar,jide-dock.jar,commons-codec-1.5.jar,init.jar,webtop.jar,navigation.jar,dem.jar,erp.jar,workflow.jar,jviews-gantt-all.jar,jviews-framework-all.jar,icu4j.jar" java_arguments="-Xmx512m" image="" code="com.ssaglobal.webtop.client.init.Webtop.class" mayscript="">
   <noembed>
<DIV style='font-family:verdana'>L'interface utilisateur d'Infor Web requiert un plugin Java 1.6 (ou une version ultérieure). Vous pouvez décharger ce plugin <A href='http://java.com/download'>ici</A></DIV>.
   </noembed>

</div>
</body>
</code>```

I can't see any Selenium locators in order to pick specific elements whereas I expected them to appear by inspecting the page

Is there a way to solve this issue ?

答: Looks like it's embedding a java app.  That would not be html.  That part of the page is running in the Java runtime at that point. </p>

Body:
I'm trying to use Selenium automation but the web page I'm working on doesn't show its HTML code when I try to inspect it.

I've tried to use the information that I have access to but no results so far

Here is a snippet of what I have acces to on the login page:

<embed name="Framework" width="100%" height="100%" align="baseline" id="Framework" src="" type="application/x-java-applet;version=1.6" codebase="../applets" archive=",jide-common.jar,jide-dock.jar,commons-codec-1.5.jar,init.jar,webtop.jar,navigation.jar,dem.jar,erp.jar,workflow.jar,jviews-gantt-all.jar,jviews-framework-all.jar,icu4j.jar" java_arguments="-Xmx512m" image="" code="com.ssaglobal.webtop.client.init.Webtop.class" mayscript="">
   <noembed>

L'interface utilisateur d'Infor Web requiert un plugin Java 1.6 (ou une version ultérieure). Vous pouvez décharger ce plugin ici
.
   </noembed>

I can't see any Selenium locators in order to pick specific elements whereas I expected them to appear by inspecting the page

Is there a way to solve this issue ?


问:
How to stop my set interval after a few tries?
I am trying to stop my set interval function to stop after sending the information to my Iframe but clearInterval() isnt actually working.

i ALSO TRIED TO USE

Here's the code:

```

答:
You'll have better results by initializing the setInterval within your component's mounted function, and by storing the interval ID as part of the component:

```<code>export default {
    data() {
        return {
            this.interval = null;
        }
    },
    mounted() {
        this.interval = setInterval(...);
    },
    connect() {
        clearInterval(this.interval);
    }
}
</code>```

Body:
You'll have better results by initializing the setInterval within your component's mounted function, and by storing the interval ID as part of the component:

export default {
    data() {
        return {
            this.interval = null;
        }
    },
    mounted() {
        this.interval = setInterval(...);
    },
    connect() {
        clearInterval(this.interval);
    }
}


问:
T-SQL - Employee Annual Average
I'm trying to make an annual average of employees, in a year.

The table 'a' is thus constructed:

```<code>CREATE TABLE [dbo]. [A]
(
    [id] [INT] NOT NULL,
    [start] [DATETIME] NOT NULL,
    [end] [DATETIME] NOT NULL,
    [employee_code] [INT] NOT NULL
)

1 - 01/01/2016 - 03/31/2019 - 56
2 - 01/01/1995 - 06/06/2017 - 13
-
-
</code>```

If I simply count the [employee_code] between 01/01/2017 and 12/31/2017 the calculation is incorrect as it does not make a monthly average.

Can you help me? (the correct calculation is to have 12 records indicating the monthly number and at the end divided by 12)

I can't do everything with a T-SQL command.

Can you help me?

hello thanks, yes, that's what I was.
Only one thing, in the query result there are the following records:

```<code>1995 1 0 NULL
1995 2 0 NULL
1995 3 0 NULL
1995 4 0 NULL
1995 5 6 NULL
1995 6 6 NULL
1995 7 10 NULL
1995 8 10 NULL
1995 9 10 NULL
1995 10 12 NULL
1995 11 12 NULL
1995 12 12 NULL
NULL 78 1995 6.500000
</code>```

The initial data from which I started are:

```<code>03/04/1995 10/20/2005 4
03/04/1995 19/06/2016 2
03/04/1995 12/15/2016 2847
03/04/1995            1
03/04/1995            5
03/04/1995            3
02/06/1995 03/07/2009 9
02/06/1995            8
02/06/1995            7
02/06/1995            6
09/15/1995 16/05/2017 34
09/15/1995            33
</code>```

why are the 6 "ecodes" in May and not April?

答:
According to your comment and previous answers, you are looking for something like this?</p>

```<code>DECLARE @A table (
eid int NOT NULL,
estart datetime,
eend datetime,
ecode int)
insert into @A VALUES (1,'02/01/2016','03/31/2019',56),
(2,'05/01/1995','01/06/2017',13);

WITH mnths as (
  select CAST('01/01/1995' as date) as mnth UNION ALL
  select DATEADD(month,1,mnth) FROM mnths WHERE mnth<'12/01/2019'
), edata AS (
  SELECT mnth,
  (SELECT count(ecode) FROM @A A WHERE mnth between estart AND eend) ecnt
  FROM mnths
)
select * FROM(
    SELECT year(mnth) yr, month(mnth) mn, ecnt, null eavg
    FROM edata
    union all
    SELECT year(mnth) yr, null mn, SUM(ecnt) as ecnt, SUM(ecnt) / 12.00 eavg
    FROM edata
    GROUP BY year(mnth)) A
order by
    A.yr,
    CASE WHEN a.mn IS NULL THEN 13 else a.mn END
OPTION (MAXRECURSION 1000)
</code>```

Title: T-SQL - Employee Annual Average

Body:
I'm trying to make an annual average of employees, in a year.

The table 'a' is thus constructed:

CREATE TABLE [dbo]. [A]
(
    [id] [INT] NOT NULL,
    [start] [DATETIME] NOT NULL,
    [end] [DATETIME] NOT NULL,
    [employee_code] [INT] NOT NULL
)

1 - 01/01/2016 - 03/31/2019 - 56
2 - 01/01/1995 - 06/06/2017 - 13
-
-

If I simply count the [employee_code] between 01/01/2017 and 12/31/2017 the calculation is incorrect as it does not make a monthly average.

Can you help me? (the correct calculation is to have 12 records indicating the monthly number and at the end divided by 12)

I can't do everything with a T-SQL command.

Can you help me?

hello thanks, yes, that's what I was.
Only one thing, in the query result there are the following records:

1995 1 0 NULL
1995 2 0 NULL
1995 3 0 NULL
1995 4 0 NULL
1995 5 6 NULL
1995 6 6 NULL
1995 7 10 NULL
1995 8 10 NULL
1995 9 10 NULL
1995 10 12 NULL
1995 11 12 NULL
1995 12 12 NULL
NULL 78 1995 6.500000

The initial data from which I started are:

03/04/1995 10/20/2005 4
03/04/1995 19/06/2016 2
03/04/1995 12/15/2016 2847
03/04/1995            1
03/04/1995            5
03/04/1995            3
02/06/1995 03/07/2009 9
02/06/1995            8
02/06/1995            7
02/06/1995            6
09/15/1995 16/05/2017 34
09/15/1995            33

why are the 6 "ecodes" in May and not April?

Body:
According to your comment and previous answers, you are looking for something like this?

DECLARE @A table (
eid int NOT NULL,
estart datetime,
eend datetime,
ecode int)
insert into @A VALUES (1,'02/01/2016','03/31/2019',56),
(2,'05/01/1995','01/06/2017',13);

WITH mnths as (
  select CAST('01/01/1995' as date) as mnth UNION ALL
  select DATEADD(month,1,mnth) FROM mnths WHERE mnth<'12/01/2019'
), edata AS (
  SELECT mnth,
  (SELECT count(ecode) FROM @A A WHERE mnth between estart AND eend) ecnt
  FROM mnths
)
select * FROM(
    SELECT year(mnth) yr, month(mnth) mn, ecnt, null eavg
    FROM edata
    union all
    SELECT year(mnth) yr, null mn, SUM(ecnt) as ecnt, SUM(ecnt) / 12.00 eavg
    FROM edata
    GROUP BY year(mnth)) A
order by
    A.yr,
    CASE WHEN a.mn IS NULL THEN 13 else a.mn END
OPTION (MAXRECURSION 1000)


问:
Using toastr in symfony 4.2.9 using webpack and encore
I'm trying to add the toastr library into my project using Webpack/Encore but i'm unable to make it work.

I'm using Yarn to mange libraries in node_modules/

In my app.js, i have :

```<code>$(() =>
{
    toastr.info("test");
});
</code>```

And i tried

Simple import in app.js just before my code

```<code>import "toastr";
</code>```

Uncaught ReferenceError: toastr is not defined

Another import i've found while googling my problem

```<code>import * as toastr from 'toastr';
import '../../node_modules/toastr/build/toastr.min.css';
</code>```

This one work but looks like the CSS isn't : The popup is transparent with just borders

Add provide variable in webpack.config.js

```<code>.autoProvideVariables({
        "window.toastr": require.resolve("toastr")
})
</code>```

Uncaught ReferenceError: toastr is not defined

Add entry in webpack.config.js

```<code>.addEntry('toastr', [
    './node_modules/toastr/build/toastr.min.js',
    './node_modules/toastr/build/toastr.min.css'
])
</code>```

Uncaught ReferenceError: toastr is not defined

答:
I managed to make it work in this strange way

In webpack.config.js, the CSS :

```<code>.addEntry('toastr', [
    './node_modules/toastr/build/toastr.min.css'
])
</code>```

In app.js, the import line :

```<code>import * as toastrlib from 'toastr';
$(() =>
{
    toastrlib.info("test");
});
</code>```

I probably missed something, and want to do it the right way. this one is probably a wrong one even if it is working, so i'm still reading for the good solution.

Body:
I'm trying to add the toastr library into my project using Webpack/Encore but i'm unable to make it work.

I'm using Yarn to mange libraries in node_modules/

In my app.js, i have :

$(() =>
{
    toastr.info("test");
});

And i tried

Simple import in app.js just before my code

import "toastr";

Uncaught ReferenceError: toastr is not defined

Another import i've found while googling my problem

import * as toastr from 'toastr';
import '../../node_modules/toastr/build/toastr.min.css';

This one work but looks like the CSS isn't : The popup is transparent with just borders

Add provide variable in webpack.config.js

.autoProvideVariables({
        "window.toastr": require.resolve("toastr")
})

Uncaught ReferenceError: toastr is not defined

Add entry in webpack.config.js

.addEntry('toastr', [
    './node_modules/toastr/build/toastr.min.js',
    './node_modules/toastr/build/toastr.min.css'
])

Uncaught ReferenceError: toastr is not defined

Body:
I managed to make it work in this strange way

In webpack.config.js, the CSS :

.addEntry('toastr', [
    './node_modules/toastr/build/toastr.min.css'
])

In app.js, the import line :

import * as toastrlib from 'toastr';
$(() =>
{
    toastrlib.info("test");
});

I probably missed something, and want to do it the right way. this one is probably a wrong one even if it is working, so i'm still reading for the good solution.


问:
How to read txt file in local storage in Ionic
I'm making a simple app with Ionic 3 to read a .txt file stored in the device, for example in Downloads folder. I want to read the file and write it in the screen.

I've already used FileChooser and FileOpener but those open the file with a text editor. I also tried with File but I was getting some errors.

I don't want to open this file with another app, I just to read the file in my app.

Thanks for the help.

答:
I solved my problem. The way it worked was indeed with File. The problem was that I was installing the wrong way. I was installing like this:

```<code>npm install --save @ionic-native/file
</code>```

And then I tried to import:

```<code>import { File } from '@ionic-native/file';
</code>```

or:

```<code>import { File } from '@ionic-native/file/ngx';
</code>```

Both ways didn't work. Since the problem was in the npm installation I had to uninstall it and install in a different way:

```<code>npm uninstall @ionic-native/file
npm install --save @ionic-native/file@4
</code>```

And then simply import it:

```<code>import { File } from '@ionic-native/file';
</code>```

I solved this when I found this other problem

How to fix "Object(...) is not a function error" using PayPal in Ionic 3

Well that's it.
Thanks everybody!

Body:
I solved my problem. The way it worked was indeed with File. The problem was that I was installing the wrong way. I was installing like this:

npm install --save @ionic-native/file

And then I tried to import:

import { File } from '@ionic-native/file';

or:

import { File } from '@ionic-native/file/ngx';

Both ways didn't work. Since the problem was in the npm installation I had to uninstall it and install in a different way:

npm uninstall @ionic-native/file
npm install --save @ionic-native/file@4

And then simply import it:

import { File } from '@ionic-native/file';

I solved this when I found this other problem

How to fix "Object(...) is not a function error" using PayPal in Ionic 3

Well that's it.
Thanks everybody!


问:
Does Zend have validator for greater than 1900
I have a date of birth field and want to add a validator so that no one enters a value less than 1900. Does zend have a validator than can be used for this? I see alnum but I don't think it's enough because it doesn't set a minimum.

答:
Your better off using the between validator, and specifying between 1900 and our present year.</p>

```<code>$validator = new Zend_Validate_Between(1900, date('Y'));
</code>```

Body:
Your better off using the between validator, and specifying between 1900 and our present year.

$validator = new Zend_Validate_Between(1900, date('Y'));


问:
Print margin at position Xpx (visual only)
I'm using tinyMCE v4. Is it possible to create a print margin (visual only) at custom position (e.g. 700px)? In the image below, print margin is marked with orange color.

答: TinyMCE has no built in way to do this.  You could use CSS to apply something to the  of the document inside the editor to get that effect.

Body: TinyMCE has no built in way to do this.  You could use CSS to apply something to the <body> of the document inside the editor to get that effect.


问:
Creating new post in Wordpress via REST API - how to past meta title and description for Yoast SEO plugin?
I'm creating new post using wordpress rest api. On the WP side, there is Yoast SEO plugin used, where I would need to update meta description and meta title fields through API calls. Is there any way how to send this data?</p>

答:
You can use this wp plug-in : https://github.com/ChazUK/wp-api-yoast-meta</p>

```<code>{
  id: 123,
  ...
  yoast_meta: {
    yoast_wpseo_title: "Testy Test | My WordPress site",
    yoast_wpseo_metadesc: "My description",
    yoast_wpseo_canonical: "http://my-wordpress-site.test/testy-test"
}
</code>```

Body:
You can use this wp plug-in : https://github.com/ChazUK/wp-api-yoast-meta

{
  id: 123,
  ...
  yoast_meta: {
    yoast_wpseo_title: "Testy Test | My WordPress site",
    yoast_wpseo_metadesc: "My description",
    yoast_wpseo_canonical: "http://my-wordpress-site.test/testy-test"
}


问:
How do I select the top 10 values based on specific criteria?
I would like to select the top ten products based on revenue, for three different weeks:

The weeks change automatically (for example, this week I have 5/27, but next week it will automatically update to 6/3).

My dataset automatically updates every week and looks as follows:

I've tried using INDEX MATCH and LARGE, but I couldn't figure out how to do it automatically.

I expect the output to be a formula that would automatically update every time my dataset updates by adding additional weeks' revenue.

Any help would be greatly appreciated!

答:
OK, well I generated some random data before the sheet was shared and it turned out that the best week was last week:

Original data in sheet Data:

Formulas:

B1

```<code>=index(Data!B1:1,COUNTA(Data!1:1)-1)
</code>```

D1

```<code>=index(Data!B1:1,COUNTA(Data!1:1)-2)
</code>```

F1

```<code>=ArrayFormula(index(Data!B1:1,match(max(mmult(transpose(row(Data!B2:index(Data!B2:B,counta(A:A)-1)))^0,Data!B2:index(Data!B2:Z,counta(A:A)-1,counta(Data!1:1)-1))),
mmult(transpose(row(Data!B2:index(Data!A2:B,counta(A:A)-1)))^0,Data!B2:index(Data!B2:Z,counta(A:A)-1,counta(Data!1:1)-1)),0)))
</code>```

A3

```<code>=sortn({Data!A2:A,index(Data!B2:Z,0,counta(Data!1:1)-1)},10,0,2,false)
</code>```

C3

```<code>=sortn({Data!A2:A,index(Data!B2:Z,0,counta(Data!1:1)-2)},10,0,2,false)
</code>```

E3

```<code>=sortn({Data!A2:A,index(Data!B2:Z,0,match(F1,Data!B1:1,0))},10,0,2,false)
</code>```

Body:
OK, well I generated some random data before the sheet was shared and it turned out that the best week was last week:

Original data in sheet Data:

Formulas:

B1

=index(Data!B1:1,COUNTA(Data!1:1)-1)

D1

=index(Data!B1:1,COUNTA(Data!1:1)-2)

F1

=ArrayFormula(index(Data!B1:1,match(max(mmult(transpose(row(Data!B2:index(Data!B2:B,counta(A:A)-1)))^0,Data!B2:index(Data!B2:Z,counta(A:A)-1,counta(Data!1:1)-1))),
mmult(transpose(row(Data!B2:index(Data!A2:B,counta(A:A)-1)))^0,Data!B2:index(Data!B2:Z,counta(A:A)-1,counta(Data!1:1)-1)),0)))

A3

=sortn({Data!A2:A,index(Data!B2:Z,0,counta(Data!1:1)-1)},10,0,2,false)

C3

=sortn({Data!A2:A,index(Data!B2:Z,0,counta(Data!1:1)-2)},10,0,2,false)

E3

=sortn({Data!A2:A,index(Data!B2:Z,0,match(F1,Data!B1:1,0))},10,0,2,false)


问:
Wait until all Ajax requests in a for loop are done before moving on?
I have to make a call to the Agile Central API to get a list of defect suites and then iterate through the list and make a nested call to get the list of defects in each suite, the nested call depends on the outer call. I then have to append the rows of data to a table and then call doneCallback() to signal the end of data collection. The problem I'm having is that doneCallback() is being called before the requests have completed so none of the data is actually passed on

I've tried the approaches in this post: Wait until all jQuery Ajax requests are done? and this post: how to wait until Array is filled (asynchronous). In the console I can see that all the data I want is there but nothing gets appended. My question is: how can I make sure I don't call doneCallback() until all the requests that are made in the loop have finished and pushed the data? Here's my code right now:

```<code>function getSuites() {
        return $.ajax({
            url: suitesURL("71101309592") + "&fetch=Name,FormattedID,Defects",
            type: "GET",
            xhrFields: {
                withCredentials: true
            },
            headers: {
                "zsessionid": apiKey
            }
        });
    }

    function getDefects(_ref) {
        return $.ajax({
            url: _ref,
            type:"GET",
            xhrFields: {
                withCredentials: true
            },
            headers: {
                "zsessionid": apiKey
            }
        });
    }

    // Download the data
    myConnector.getData = function (table, doneCallback) {

        console.log("Getting Data...");

        var ajaxCalls = [], tableData = [];

        var suitesJSON = getSuites();

        suitesJSON.done(function(data) {

            var suites = data.QueryResult.Results;

            for(var i = 0; i < suites.length; i++) {

               (function(i) {
                    var defectsJSON = getDefects(suites[i].Defects._ref + "?fetch=Name,FormattedID,State,Priority,CreationDate,c_RootCause,c_RootCauseCRM");
                    ajaxCalls.push(defectsJSON);

                    defectsJSON.done(function(data) {
                        var defects = data.QueryResult.Results;

                        for(var j = 0; j < defects.length; j++) {
                            tableData.push({
                                "suiteName": suites[i].Name, // This is the name of the suite collected in the outer call
                                "defectName": defects[j].Name,
                                "FormattedID": defects[j].FormattedID,
                                "State": defects[j].State,
                                "Priority": defects[j].Priority,
                                "CreationDate": defects[j].CreationDate,
                                "RootCause": defects[j].c_RootCause,
                                "RootCauseCRM": defects[j].c_RootCauseCRM
                            });
                        }

                    });
               })(i);

            }

        });

        $.when.apply($, ajaxCalls).then(function() {
            console.log(tableData);
            table.appendRows(tableData);
            doneCallback();
        });
};
</code>```

答:
I think the problem is that you are calling $.wait right after getSuites() is executed.

$.wait 'sees' the ajaxCalls array empty (because getSuites() hasn't finish yet) and executes doneCallback().

Try to call $.wait INSIDE the suitesJSON.done function, that way it will be called after the ajaxCalls array is filled with the first response:

```<code>myConnector.getData = function (table, doneCallback) {
    console.log("Getting Data...");
    var ajaxCalls = [], tableData = [];

    var suitesJSON = getSuites();

    suitesJSON.done(function(data) {

        var suites = data.QueryResult.Results;

        for(var i = 0; i < suites.length; i++) {

           (function(i) {
                var defectsJSON = getDefects(suites[i].Defects._ref + "?fetch=Name,FormattedID,State,Priority,CreationDate,c_RootCause,c_RootCauseCRM");
                ajaxCalls.push(defectsJSON);

                defectsJSON.done(function(data) {
                    var defects = data.QueryResult.Results;

                    for(var j = 0; j < defects.length; j++) {
                        tableData.push({
                            "suiteName": suites[i].Name, // This is the name of the suite collected in the outer call
                            "defectName": defects[j].Name,
                            "FormattedID": defects[j].FormattedID,
                            "State": defects[j].State,
                            "Priority": defects[j].Priority,
                            "CreationDate": defects[j].CreationDate,
                            "RootCause": defects[j].c_RootCause,
                            "RootCauseCRM": defects[j].c_RootCauseCRM
                        });
                    }

                });
           })(i);

        }

        $.when.apply($, ajaxCalls).then(function() {
            console.log(tableData);
            table.appendRows(tableData);
            doneCallback();
        });
    });
};
</code>```

Body:
I have to make a call to the Agile Central API to get a list of defect suites and then iterate through the list and make a nested call to get the list of defects in each suite, the nested call depends on the outer call. I then have to append the rows of data to a table and then call doneCallback() to signal the end of data collection. The problem I'm having is that doneCallback() is being called before the requests have completed so none of the data is actually passed on

I've tried the approaches in this post: Wait until all jQuery Ajax requests are done? and this post: how to wait until Array is filled (asynchronous). In the console I can see that all the data I want is there but nothing gets appended. My question is: how can I make sure I don't call doneCallback() until all the requests that are made in the loop have finished and pushed the data? Here's my code right now:

function getSuites() {
        return $.ajax({
            url: suitesURL("71101309592") + "&fetch=Name,FormattedID,Defects",
            type: "GET",
            xhrFields: {
                withCredentials: true
            },
            headers: {
                "zsessionid": apiKey
            }
        });
    }

    function getDefects(_ref) {
        return $.ajax({
            url: _ref,
            type:"GET",
            xhrFields: {
                withCredentials: true
            },
            headers: {
                "zsessionid": apiKey
            }
        });
    }

    // Download the data
    myConnector.getData = function (table, doneCallback) {

        console.log("Getting Data...");

        var ajaxCalls = [], tableData = [];

        var suitesJSON = getSuites();

        suitesJSON.done(function(data) {

            var suites = data.QueryResult.Results;

            for(var i = 0; i < suites.length; i++) {

               (function(i) {
                    var defectsJSON = getDefects(suites[i].Defects._ref + "?fetch=Name,FormattedID,State,Priority,CreationDate,c_RootCause,c_RootCauseCRM");
                    ajaxCalls.push(defectsJSON);

                    defectsJSON.done(function(data) {
                        var defects = data.QueryResult.Results;

                        for(var j = 0; j < defects.length; j++) {
                            tableData.push({
                                "suiteName": suites[i].Name, // This is the name of the suite collected in the outer call
                                "defectName": defects[j].Name,
                                "FormattedID": defects[j].FormattedID,
                                "State": defects[j].State,
                                "Priority": defects[j].Priority,
                                "CreationDate": defects[j].CreationDate,
                                "RootCause": defects[j].c_RootCause,
                                "RootCauseCRM": defects[j].c_RootCauseCRM
                            });
                        }

                    });
               })(i);

            }

        });

        $.when.apply($, ajaxCalls).then(function() {
            console.log(tableData);
            table.appendRows(tableData);
            doneCallback();
        });
};

Body:
I think the problem is that you are calling $.wait right after getSuites() is executed.

$.wait 'sees' the ajaxCalls array empty (because getSuites() hasn't finish yet) and executes doneCallback().

Try to call $.wait INSIDE the suitesJSON.done function, that way it will be called after the ajaxCalls array is filled with the first response:

myConnector.getData = function (table, doneCallback) {
    console.log("Getting Data...");
    var ajaxCalls = [], tableData = [];

    var suitesJSON = getSuites();

    suitesJSON.done(function(data) {

        var suites = data.QueryResult.Results;

        for(var i = 0; i < suites.length; i++) {

           (function(i) {
                var defectsJSON = getDefects(suites[i].Defects._ref + "?fetch=Name,FormattedID,State,Priority,CreationDate,c_RootCause,c_RootCauseCRM");
                ajaxCalls.push(defectsJSON);

                defectsJSON.done(function(data) {
                    var defects = data.QueryResult.Results;

                    for(var j = 0; j < defects.length; j++) {
                        tableData.push({
                            "suiteName": suites[i].Name, // This is the name of the suite collected in the outer call
                            "defectName": defects[j].Name,
                            "FormattedID": defects[j].FormattedID,
                            "State": defects[j].State,
                            "Priority": defects[j].Priority,
                            "CreationDate": defects[j].CreationDate,
                            "RootCause": defects[j].c_RootCause,
                            "RootCauseCRM": defects[j].c_RootCauseCRM
                        });
                    }

                });
           })(i);

        }

        $.when.apply($, ajaxCalls).then(function() {
            console.log(tableData);
            table.appendRows(tableData);
            doneCallback();
        });
    });
};


问:
Retrieving a row when specific text strings occur in SQL
I'm trying to retrieve rows that contain only a specific text string(s). The issue is that sometimes the text string can me mixed in with other text strings, and when this occurs, I do NOT want to retrieve this row. Here's an idea of the data that I'm working with:

```<code>    MED_TABLE
______________________________________
med_code    |   med_name
______________________________________
1            calcium potassium iodine fluoride
2            potassium calcium
3            hydrochloride; calcium
4            iodine, calcium, fluoride
5            iodine calcium phosphate
6            calcium phosphate
7            IODINE
8            calcium PHOSPHATE iodine
</code>```

If I want to return rows that ONLY contain the strings 'calcium phosphate' and/or 'iodine', either independently or in pair, what's an efficient way of going about this? In this case, I would only want to return rows 5, 6, 7, 8.

I was trying to do this by using a query like this:

```<code>SELECT med_code, med_name
FROM med_table
WHERE lower(med_name) LIKE '%calcium phosphate%'
OR WHERE lower(med_name) LIKE '%iodine%'
</code>```

But this returns rows that contain text strings that I do not want.

答:
You can compare the text with like and then just compare the length of the column this will give the above result which you are expecting

```<code>SELECT med_code, med_name
FROM med_table
WHERE (lower(med_name) LIKE '%calcium phosphate%' AND length(Column)=18

OR WHERE (lower(med_name) LIKE '%iodine%' AND length(Column)= 7)
</code>```

The length of the column should be the Length of the string of LIKE clause check the syntax as just wrote this runtime Also add the condition for both combination of string like 'calcium phosphate iodine' and 'iodine ....'

Body:
I'm trying to retrieve rows that contain only a specific text string(s). The issue is that sometimes the text string can me mixed in with other text strings, and when this occurs, I do NOT want to retrieve this row. Here's an idea of the data that I'm working with:

    MED_TABLE
______________________________________
med_code    |   med_name
______________________________________
1            calcium potassium iodine fluoride
2            potassium calcium
3            hydrochloride; calcium
4            iodine, calcium, fluoride
5            iodine calcium phosphate
6            calcium phosphate
7            IODINE
8            calcium PHOSPHATE iodine

If I want to return rows that ONLY contain the strings 'calcium phosphate' and/or 'iodine', either independently or in pair, what's an efficient way of going about this? In this case, I would only want to return rows 5, 6, 7, 8.

I was trying to do this by using a query like this:

SELECT med_code, med_name
FROM med_table
WHERE lower(med_name) LIKE '%calcium phosphate%'
OR WHERE lower(med_name) LIKE '%iodine%'

But this returns rows that contain text strings that I do not want.

Body:
You can compare the text with like and then just compare the length of the column this will give the above result which you are expecting

SELECT med_code, med_name
FROM med_table
WHERE (lower(med_name) LIKE '%calcium phosphate%' AND length(Column)=18

OR WHERE (lower(med_name) LIKE '%iodine%' AND length(Column)= 7)

The length of the column should be the Length of the string of LIKE clause check the syntax as just wrote this runtime Also add the condition for both combination of string like 'calcium phosphate iodine' and 'iodine ....'


问:
I got a token from AAD using Msal, but can't get the user profile using the token acquired. How to validate the token simply on Node backend?
I used the following configuration for requesting the token from AAD.

The app.module.ts file:

```<code>MsalModule.forRoot({
            clientID: 'CLIENT_ID',
            authority: "https://login.microsoftonline.com/TENANT_ID",
            validateAuthority: true,
            cacheLocation: 'sessionStorage',
            postLogoutRedirectUri: 'http://localhost:4200/authorize/signin',
            navigateToLoginRequestUrl: true,
            popUp: true,
            consentScopes: ['user.read', 'https://graph.microsoft.com']
        }
</code>```

It returns the msal.idtoken, accesstoken, and some more msal key value pairs.
Now following code is used to get the profile of the user by pasting the acquired MSAL_IDTOKEN.

```<code>const request = require('request');
const tok = 'MSAL_IDTOKEN HERE';
request.get({ url: "https://graph.microsoft.com/v1.0/me", headers: { "Authorization": "Bearer " + tok, "Content-type": "application/json" } }, function (err, response, body) {

    if (err) {
        console.log('err', err);
    }
    else
        console.log(response.body);
})
</code>```

Now after running the app on Node, it used to return the profile of the user, as found after decoding the token, but now it does not.

答:
I see that you have the right config on the Portal.

If you are using MSAL.js, given some code like this:

```<code>    this.app = new Msal.UserAgentApplication(

        this.applicationConfig.clientID,

        `https://login.microsoftonline.com/${AzureADName}/`,

        () => {

            // callback for login redirect

        },

        {

            redirectUri

        }

    );
</code>```

You would then call this to get user information:

```<code>this.app.getUser();
</code>```

or

```<code>this.app.getAccount();
</code>```

You would have to provide version information to be sure, as the API was changed.

Body:
I used the following configuration for requesting the token from AAD.

The app.module.ts file:

MsalModule.forRoot({
            clientID: 'CLIENT_ID',
            authority: "https://login.microsoftonline.com/TENANT_ID",
            validateAuthority: true,
            cacheLocation: 'sessionStorage',
            postLogoutRedirectUri: 'http://localhost:4200/authorize/signin',
            navigateToLoginRequestUrl: true,
            popUp: true,
            consentScopes: ['user.read', 'https://graph.microsoft.com']
        }

It returns the msal.idtoken, accesstoken, and some more msal key value pairs.
Now following code is used to get the profile of the user by pasting the acquired MSAL_IDTOKEN.

const request = require('request');
const tok = 'MSAL_IDTOKEN HERE';
request.get({ url: "https://graph.microsoft.com/v1.0/me", headers: { "Authorization": "Bearer " + tok, "Content-type": "application/json" } }, function (err, response, body) {

    if (err) {
        console.log('err', err);
    }
    else
        console.log(response.body);
})

Now after running the app on Node, it used to return the profile of the user, as found after decoding the token, but now it does not.

Body:
I see that you have the right config on the Portal.

If you are using MSAL.js, given some code like this:

    this.app = new Msal.UserAgentApplication(

        this.applicationConfig.clientID,

        `https://login.microsoftonline.com/${AzureADName}/`,

        () => {

            // callback for login redirect

        },

        {

            redirectUri

        }

    );

You would then call this to get user information:

this.app.getUser();

or

this.app.getAccount();

You would have to provide version information to be sure, as the API was changed.


问:
ASP.Net Core 2.1 Vue.JS SPA - Cookie Auth and the Vue.JS Dev Server
I have an application which is essentially a Vue.JS SPA sat within a dotnet core 2.1 app, providing API services. When I start up the app, with my current Startup.cs configuration, it starts up 3 windows. 1 of these windows is the actual ASP.Net Core app root - the other 2 (don't ask me why 2) are copies of the Vue.js dev server that you get when you do npm run serve.

The problem that I have is that, whilst authentication is working fine if I use the instance running in the first window, if I try to log in using the Vue.JS server windows then I just get a 401 back.

My first thought was CORS, so I set up a CORS policy purely for when running in development mode but this hasn't rectified the issue. Developing without the Vue.JS server isn't really viable as without it I have no HMR and will need to reload the entire application state every time I make a design change.

I have had this setup working before with a .net Framework 4.6 API back end with no problem at all so I can only think it's a modern security enhancement that's blocking the proxying which I need to configure to be off in Development or something.

Any suggestions on how I can solve this are welcome.

Here's my current Startup.cs Configure...

```<code>       public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,
        ApplicationDbContext context, RoleManager<IdentityRole> roleManager, UserManager<ApplicationUser> userManager)
    {
        if (env.IsDevelopment())
        {
            app
                .UseDeveloperExceptionPage()
                .UseDatabaseErrorPage()
                .UseCors("DevelopmentPolicy");
        }
        else
        {
            app
                .UseExceptionHandler("/Home/Error")
                .UseHsts();
        }

        app
            .UseAuthentication()
            .UseHttpsRedirection()
            .UseStaticFiles()
            .UseSpaStaticFiles();

        app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

        app.UseSpa(spa =>
        {
            spa.Options.SourcePath = "VueApp";

            if (env.IsDevelopment())
            {
                spa.UseVueCliServer("serve");
            }
        });

        DbInitializer.Initialize(context, roleManager, userManager, env, loggerFactory);
    }
</code>```

...and ConfigureServices...

```<code>   public void ConfigureServices(IServiceCollection services)
    {
        services
            .AddLogging(builder => builder
                .AddConsole()
                .AddDebug());

        services
            .AddMvc()
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
                .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver());

        services
            .AddCors(options =>
            {
                options.AddPolicy("DevelopmentPolicy",
                    policy => policy.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
            });

        // In production, the Vue files will be served from this directory
        services.AddSpaStaticFiles(configuration => { configuration.RootPath = "wwwroot"; });
        services.AddAuthentication();

        services
            .ConfigureEntityFramework(Configuration)
            .ConfigureEntityServices()
            .ConfigureIdentityDependencies()
            .ConfigureDomainServices()
            .ConfigureApplicationCookie(config =>
            {
                config.SlidingExpiration = true;
                config.Events = new CookieAuthenticationEvents
                {
                    OnRedirectToLogin = cxt =>
                    {
                        cxt.Response.StatusCode = 401;
                        return Task.CompletedTask;
                    },
                    OnRedirectToAccessDenied = cxt =>
                    {
                        cxt.Response.StatusCode = 403;
                        return Task.CompletedTask;
                    },
                    OnRedirectToLogout = cxt => Task.CompletedTask
                };
            });
    }
</code>```

...and Identity gets lumped in with EF configuration here...

```<code>       public static IServiceCollection ConfigureEntityFramework(this IServiceCollection services, string connectionString)
    {
        services
            .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString))
            .AddIdentity<ApplicationUser, IdentityRole>(options =>
                {

                    // Password settings
                    options.Password.RequireDigit = true;
                    options.Password.RequiredLength = 8;
                    options.Password.RequireNonAlphanumeric = true;

                    // Lockout settings
                    options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
                    options.Lockout.MaxFailedAccessAttempts = 10;

                    // User settings
                    options.User.RequireUniqueEmail = true;
                })
            .AddRoleManager<RoleManager<IdentityRole>>()
            .AddSignInManager<SignInManager<ApplicationUser>>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        return services;
    }
</code>```

My vue.config.js looks like this...

```<code>const baseUrl = ''

module.exports = {
    publicPath: baseUrl + '/',

    // place our built files into the parent project where they will be copied
    // into the distribution for deployment
    outputDir: '../wwwroot',

    filenameHashing: true, //process.env.NODE_ENV === 'production',
    lintOnSave: 'error',

    css: {
        modules: false,
        sourceMap: process.env.NODE_ENV !== 'production',
        loaderOptions: {
            sass: {
                data: `
                    $fa-font-path: ${process.env.NODE_ENV !== 'production' ? '"~/fonts"' : '"' + baseUrl + '/fonts"'};
                    @import "@/scss/base/index.scss";
                    @import "@/scss/helpers/index.scss";
                `
            }
        }
    },

    devServer: {
        host: 'localhost',
        port: 8080,
        hot: true,
        open: true,
        openPage: '',
        overlay: true,
        disableHostCheck: true,
        proxy: {
            // Proxy services to a backend API
            '/api': {
                target: process.env.PROXY || 'https://localhost:44368',
                secure: false,
                changeOrigin: true
            }
        }
    },

    // these node_modules use es6 so need transpiling for IE
    transpileDependencies: [
    ]
}
</code>```

答:
I solved this in the end by configuring the app so that it only forces HTTPS when not in development mode. HTTPS was killing the underlying Webpack Development Server and therefore Hot Module replacement - I can now debug successfully in the main window!

Happy to up vote better solutions than that though to get it working without killing SSL (if possible).

Body:
I have an application which is essentially a Vue.JS SPA sat within a dotnet core 2.1 app, providing API services. When I start up the app, with my current Startup.cs configuration, it starts up 3 windows. 1 of these windows is the actual ASP.Net Core app root - the other 2 (don't ask me why 2) are copies of the Vue.js dev server that you get when you do npm run serve.

The problem that I have is that, whilst authentication is working fine if I use the instance running in the first window, if I try to log in using the Vue.JS server windows then I just get a 401 back.

My first thought was CORS, so I set up a CORS policy purely for when running in development mode but this hasn't rectified the issue. Developing without the Vue.JS server isn't really viable as without it I have no HMR and will need to reload the entire application state every time I make a design change.

I have had this setup working before with a .net Framework 4.6 API back end with no problem at all so I can only think it's a modern security enhancement that's blocking the proxying which I need to configure to be off in Development or something.

Any suggestions on how I can solve this are welcome.

Here's my current Startup.cs Configure...

       public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,
        ApplicationDbContext context, RoleManager<IdentityRole> roleManager, UserManager<ApplicationUser> userManager)
    {
        if (env.IsDevelopment())
        {
            app
                .UseDeveloperExceptionPage()
                .UseDatabaseErrorPage()
                .UseCors("DevelopmentPolicy");
        }
        else
        {
            app
                .UseExceptionHandler("/Home/Error")
                .UseHsts();
        }

        app
            .UseAuthentication()
            .UseHttpsRedirection()
            .UseStaticFiles()
            .UseSpaStaticFiles();

        app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

        app.UseSpa(spa =>
        {
            spa.Options.SourcePath = "VueApp";

            if (env.IsDevelopment())
            {
                spa.UseVueCliServer("serve");
            }
        });

        DbInitializer.Initialize(context, roleManager, userManager, env, loggerFactory);
    }

...and ConfigureServices...

   public void ConfigureServices(IServiceCollection services)
    {
        services
            .AddLogging(builder => builder
                .AddConsole()
                .AddDebug());

        services
            .AddMvc()
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
                .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver());

        services
            .AddCors(options =>
            {
                options.AddPolicy("DevelopmentPolicy",
                    policy => policy.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
            });

        // In production, the Vue files will be served from this directory
        services.AddSpaStaticFiles(configuration => { configuration.RootPath = "wwwroot"; });
        services.AddAuthentication();

        services
            .ConfigureEntityFramework(Configuration)
            .ConfigureEntityServices()
            .ConfigureIdentityDependencies()
            .ConfigureDomainServices()
            .ConfigureApplicationCookie(config =>
            {
                config.SlidingExpiration = true;
                config.Events = new CookieAuthenticationEvents
                {
                    OnRedirectToLogin = cxt =>
                    {
                        cxt.Response.StatusCode = 401;
                        return Task.CompletedTask;
                    },
                    OnRedirectToAccessDenied = cxt =>
                    {
                        cxt.Response.StatusCode = 403;
                        return Task.CompletedTask;
                    },
                    OnRedirectToLogout = cxt => Task.CompletedTask
                };
            });
    }

...and Identity gets lumped in with EF configuration here...

       public static IServiceCollection ConfigureEntityFramework(this IServiceCollection services, string connectionString)
    {
        services
            .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString))
            .AddIdentity<ApplicationUser, IdentityRole>(options =>
                {

                    // Password settings
                    options.Password.RequireDigit = true;
                    options.Password.RequiredLength = 8;
                    options.Password.RequireNonAlphanumeric = true;

                    // Lockout settings
                    options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
                    options.Lockout.MaxFailedAccessAttempts = 10;

                    // User settings
                    options.User.RequireUniqueEmail = true;
                })
            .AddRoleManager<RoleManager<IdentityRole>>()
            .AddSignInManager<SignInManager<ApplicationUser>>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        return services;
    }

My vue.config.js looks like this...

const baseUrl = ''

module.exports = {
    publicPath: baseUrl + '/',

    // place our built files into the parent project where they will be copied
    // into the distribution for deployment
    outputDir: '../wwwroot',

    filenameHashing: true, //process.env.NODE_ENV === 'production',
    lintOnSave: 'error',

    css: {
        modules: false,
        sourceMap: process.env.NODE_ENV !== 'production',
        loaderOptions: {
            sass: {
                data: `
                    $fa-font-path: ${process.env.NODE_ENV !== 'production' ? '"~/fonts"' : '"' + baseUrl + '/fonts"'};
                    @import "@/scss/base/index.scss";
                    @import "@/scss/helpers/index.scss";
                `
            }
        }
    },

    devServer: {
        host: 'localhost',
        port: 8080,
        hot: true,
        open: true,
        openPage: '',
        overlay: true,
        disableHostCheck: true,
        proxy: {
            // Proxy services to a backend API
            '/api': {
                target: process.env.PROXY || 'https://localhost:44368',
                secure: false,
                changeOrigin: true
            }
        }
    },

    // these node_modules use es6 so need transpiling for IE
    transpileDependencies: [
    ]
}


问:
Constraint Failed - SQLite 3 - Android
I has the following table on my SQLite.

```<code>    StringBuilder createSql = new StringBuilder();
    createSql.append("create table LIBRARY ( ");
    createSql.append("id integer primary key, ");
    createSql.append("title text, ");
    createSql.append("author text, ");
    createSql.append("publisher text, ");
    createSql.append("thumbnailUrl text, ");
    createSql.append("formatType text, ");
    createSql.append("contentUrl text, ");
    createSql.append("publicationType text, ");
    createSql.append("favorite text, ");
    createSql.append("started text, ");
    createSql.append("normalizedTitle text, ");
    createSql.append("downloaded integer, ");
    createSql.append("wasDownloaded text ");
    createSql.append(");");
</code>```

And the following code to inser a value on that Table.

```<code>public void addLibrary(LibraryItem item) {
    ContentValues row = new ContentValues();
    row.put("title", item.getTitle());
    row.put("author", item.getAuthor());
    row.put("publisher", item.getPublisher());
    row.put("thumbnailUrl", item.getThumbnail());
    row.put("formatType", item.getFormat());
    row.put("contentUrl", item.getContentUrl());
    row.put("publicationType", item.getPublicationType());
    row.put("favorite", item.isFavorite() ? "YES" : "NO");
    row.put("id", item.getItemId());
    row.put("normalizedTitle", StringUtil.normalize(item.getTitle()));
    row.put("downloaded", Calendar.getInstance().getTimeInMillis());
    row.put("wasdownloaded", item.hasContent() ? "YES" : "NO");

    long id = db.insert("LIBRARY", null, row);
    add(id, item.getCategories());
}
</code>```

But when executing it, I got the following error.

```<code>Error inserting id=255 formatType=null author=null title=A Cabana contentUrl=/sdcard/Digital Editions/A Cabana.pdf publicationType=Livro thumbnailUrl=https://api-dls.homolog.abrildigital.com.br/images/22/android_cover_201103092041.jpg wasdownloaded=NO downloaded=1302631109426 normalizedTitle=A Cabana favorite=NO publisher=null
android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
</code>```

What's wrong?

答:
Change your createSQL builder to...

```<code>createSql.append("id integer primary key autoincrement, ");
</code>```

Also.  When you're doing your insert, you don't set the id field.  Instead, what you should do, is do a check at the top of the function.

```<code>if(item.getItemID() == 0)
{
    //Run update here instead.
    //Set the id on the ContentValues here
}
else
{
    //Run insert statement instead.
    //Don't set the id in the ContentValues here.
}
</code>```

Title: Constraint Failed - SQLite 3 - Android

Body:
I has the following table on my SQLite.

    StringBuilder createSql = new StringBuilder();
    createSql.append("create table LIBRARY ( ");
    createSql.append("id integer primary key, ");
    createSql.append("title text, ");
    createSql.append("author text, ");
    createSql.append("publisher text, ");
    createSql.append("thumbnailUrl text, ");
    createSql.append("formatType text, ");
    createSql.append("contentUrl text, ");
    createSql.append("publicationType text, ");
    createSql.append("favorite text, ");
    createSql.append("started text, ");
    createSql.append("normalizedTitle text, ");
    createSql.append("downloaded integer, ");
    createSql.append("wasDownloaded text ");
    createSql.append(");");

And the following code to inser a value on that Table.

public void addLibrary(LibraryItem item) {
    ContentValues row = new ContentValues();
    row.put("title", item.getTitle());
    row.put("author", item.getAuthor());
    row.put("publisher", item.getPublisher());
    row.put("thumbnailUrl", item.getThumbnail());
    row.put("formatType", item.getFormat());
    row.put("contentUrl", item.getContentUrl());
    row.put("publicationType", item.getPublicationType());
    row.put("favorite", item.isFavorite() ? "YES" : "NO");
    row.put("id", item.getItemId());
    row.put("normalizedTitle", StringUtil.normalize(item.getTitle()));
    row.put("downloaded", Calendar.getInstance().getTimeInMillis());
    row.put("wasdownloaded", item.hasContent() ? "YES" : "NO");

    long id = db.insert("LIBRARY", null, row);
    add(id, item.getCategories());
}

But when executing it, I got the following error.

Error inserting id=255 formatType=null author=null title=A Cabana contentUrl=/sdcard/Digital Editions/A Cabana.pdf publicationType=Livro thumbnailUrl=https://api-dls.homolog.abrildigital.com.br/images/22/android_cover_201103092041.jpg wasdownloaded=NO downloaded=1302631109426 normalizedTitle=A Cabana favorite=NO publisher=null
android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed

What's wrong?

Body:
Change your createSQL builder to...

createSql.append("id integer primary key autoincrement, ");

Also.  When you're doing your insert, you don't set the id field.  Instead, what you should do, is do a check at the top of the function.

if(item.getItemID() == 0)
{
    //Run update here instead.
    //Set the id on the ContentValues here
}
else
{
    //Run insert statement instead.
    //Don't set the id in the ContentValues here.
}


问:
Why Do i get null value in the following code concerning java inheritence
I will provide the code and the output given by the compiler for better understanding of the problem. You will notice a null value for Registration Number...there is the problem.
You will notice at the output that i get null value for Registration number...i don't get it because it all seemed right, until it wasn't.

public class Student {
    private String regNo;
    //Student student = new Test();

    public String getRegNo() {
        return regNo;
    }

    public void setRegNo(String number) {
        this.regNo = regNo;
    }

    public void displayRegistrationNumber(){
        System.out.println("Registration number: "+ getRegNo());
    }

}

-----------------------------------------------------------------'
public class Test extends Student{
    private double sub1, sub2;

    public double getSub1() {
        return sub1;
    }

    public void setSub1(double sub1) {
        this.sub1 = sub1;
    }

    public double getSub2() {
        return sub2;
    }

    public void setSub2(double sub2) {
        this.sub2 = sub2;
    }

    public void displayScore(){
        System.out.printf("Scores: Subject1 = %.0f, Subject2 = %.0f \n",getSub1(), getSub2());
    }
}

-----------------------------------------------------------------------
public class Results extends Test {
    private double total;

    public double getTotal() {
        return total;
    }

    public void setTotal(double total) {
        this.total = total;
    }

    public void displayTotalScores(){
        setTotal(getSub1()+getSub2());
        System.out.printf("Total marks: %.0f \n", getTotal());
    }

}
---------------------------------------------------------------------

public class Main_method {
    public static void main(String[] args){
        Results results = new Results();

        results.setRegNo("2017-04-06859");
        results.setSub1(75.47);
        results.setSub2(89);

        results.displayRegistrationNumber();
        results.displayScore();
        results.displayTotalScores();

    }
}

```

<p>Here's the output. Notice the null</p>

```Registration number: null
Scores: Subject1 = 75, Subject2 = 89
Total marks: 164 `
```

答:
Here instead of assigning parameter number to regNo you just reassigned its own value (which is null initially) to it:

```<code>public void setRegNo(String number) {
    this.regNo = regNo;
}
</code>```

so change it to:

```<code>this.regNo = number;
</code>```

Body:
I will provide the code and the output given by the compiler for better understanding of the problem. You will notice a null value for Registration Number...there is the problem.
You will notice at the output that i get null value for Registration number...i don't get it because it all seemed right, until it wasn't.

public class Student {
    private String regNo;
    //Student student = new Test();

    public String getRegNo() {
        return regNo;
    }

    public void setRegNo(String number) {
        this.regNo = regNo;
    }

    public void displayRegistrationNumber(){
        System.out.println("Registration number: "+ getRegNo());
    }

}

-----------------------------------------------------------------'
public class Test extends Student{
    private double sub1, sub2;

    public double getSub1() {
        return sub1;
    }

    public void setSub1(double sub1) {
        this.sub1 = sub1;
    }

    public double getSub2() {
        return sub2;
    }

    public void setSub2(double sub2) {
        this.sub2 = sub2;
    }

    public void displayScore(){
        System.out.printf("Scores: Subject1 = %.0f, Subject2 = %.0f \n",getSub1(), getSub2());
    }
}

-----------------------------------------------------------------------
public class Results extends Test {
    private double total;

    public double getTotal() {
        return total;
    }

    public void setTotal(double total) {
        this.total = total;
    }

    public void displayTotalScores(){
        setTotal(getSub1()+getSub2());
        System.out.printf("Total marks: %.0f \n", getTotal());
    }

}
---------------------------------------------------------------------

public class Main_method {
    public static void main(String[] args){
        Results results = new Results();

        results.setRegNo("2017-04-06859");
        results.setSub1(75.47);
        results.setSub2(89);

        results.displayRegistrationNumber();
        results.displayScore();
        results.displayTotalScores();

    }
}

Here's the output. Notice the null

Registration number: null
Scores: Subject1 = 75, Subject2 = 89
Total marks: 164 `

Body:
Here instead of assigning parameter number to regNo you just reassigned its own value (which is null initially) to it:

public void setRegNo(String number) {
    this.regNo = regNo;
}

so change it to:

this.regNo = number;


问:
How i can save all the id's values in an array?
I have a collection with 941 documents. I want create a collection with only 1 document and the field ids. The value of the field is expected to be an array of all the ids of the previous collection. I'm using the $out in mongo for this purpose.</p>

答:
You can use $group with $push accumulator to get the array of all the documents _id

```<code>db.collection.aggregate([
  { "$group": {
    "_id": null,
    "ids": { "$push": "$_id" }
  }},
  { "$out": "newCollectionName" }
])
</code>```

Body:
You can use $group with $push accumulator to get the array of all the documents _id

db.collection.aggregate([
  { "$group": {
    "_id": null,
    "ids": { "$push": "$_id" }
  }},
  { "$out": "newCollectionName" }
])


问:
WPF style for Grid with defined columns and rows?
In my application I have a lot of grids like this:

```<code><Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="10"/>
        <ColumnDefinition Width="20"/>
        <ColumnDefinition Width="40"/>
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <!-- ... -->
</Grid>
</code>```

They have 4 columns and 3 rows and column widths are set to some value.

Can I create style or some other kind of template to simplify my window that uses 20 grids like this?

I know, that I can create styles for column definitions one by one to avoid Width="10" everywhere, but is it possible to do something like this?

```<code><Grid Style="{StaticResource GridWith4ColumnsAnd3Rows}">
    <!-- ... -->
</Grid>
</code>```

答:
Nice answer is here:

How to create reusable WPF grid layout

I have used <ItemsPanel> control with Grid inside.

Style (in my App.xaml):

```<code><Style x:Key="SchedulerFieldGridStyle1" TargetType="ItemsControl" >
    <Setter Property="ItemsPanel">
        <Setter.Value>
            <ItemsPanelTemplate>
                <Grid Background="LightSteelBlue" Margin="4">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto"/>
                        <ColumnDefinition Width="Auto"/>
                        <ColumnDefinition Width="Auto"/>
                        <ColumnDefinition Width="Auto"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                </Grid>
            </ItemsPanelTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

Part of MainWindow.xaml before:

```<code><Grid Background="LightSteelBlue" Margin="4">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <Label Grid.ColumnSpan="4" Content="Day of week"/>
    <Label Grid.Column="0" Grid.Row="1" Content="From"/>
    <ComboBox Grid.Column="1" Grid.Row="1" />
    <Label Grid.Column="2" Grid.Row="1" Content="To"/>
    <ComboBox Grid.Column="3" Grid.Row="1" />
</Grid>
</code>```

Part of MainWindow.xaml after:

```<code><ItemsControl Style="{StaticResource SchedulerFieldGridStyle1}">
    <Label Grid.ColumnSpan="4" Content="Day of week"/>
    <Label Grid.Column="0" Grid.Row="1" Content="From"/>
    <ComboBox Grid.Column="1" Grid.Row="1"/>
    <Label Grid.Column="2" Grid.Row="1" Content="To"/>
    <ComboBox Grid.Column="3" Grid.Row="1"/>
</ItemsControl>
</code>```

Body:
In my application I have a lot of grids like this:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="10"/>
        <ColumnDefinition Width="20"/>
        <ColumnDefinition Width="40"/>
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>

</Grid>

They have 4 columns and 3 rows and column widths are set to some value.

Can I create style or some other kind of template to simplify my window that uses 20 grids like this?

I know, that I can create styles for column definitions one by one to avoid Width="10" everywhere, but is it possible to do something like this?

<Grid Style="{StaticResource GridWith4ColumnsAnd3Rows}">

</Grid>

Body:
Nice answer is here:

How to create reusable WPF grid layout

I have used <ItemsPanel> control with Grid inside.

Style (in my App.xaml):

<Style x:Key="SchedulerFieldGridStyle1" TargetType="ItemsControl" >
    <Setter Property="ItemsPanel">
        <Setter.Value>
            <ItemsPanelTemplate>
                <Grid Background="LightSteelBlue" Margin="4">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto"/>
                        <ColumnDefinition Width="Auto"/>
                        <ColumnDefinition Width="Auto"/>
                        <ColumnDefinition Width="Auto"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                </Grid>
            </ItemsPanelTemplate>
        </Setter.Value>
    </Setter>
</Style>

Part of MainWindow.xaml before:

<Grid Background="LightSteelBlue" Margin="4">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <Label Grid.ColumnSpan="4" Content="Day of week"/>
    <Label Grid.Column="0" Grid.Row="1" Content="From"/>
    <ComboBox Grid.Column="1" Grid.Row="1" />
    <Label Grid.Column="2" Grid.Row="1" Content="To"/>
    <ComboBox Grid.Column="3" Grid.Row="1" />
</Grid>

Part of MainWindow.xaml after:

<ItemsControl Style="{StaticResource SchedulerFieldGridStyle1}">
    <Label Grid.ColumnSpan="4" Content="Day of week"/>
    <Label Grid.Column="0" Grid.Row="1" Content="From"/>
    <ComboBox Grid.Column="1" Grid.Row="1"/>
    <Label Grid.Column="2" Grid.Row="1" Content="To"/>
    <ComboBox Grid.Column="3" Grid.Row="1"/>
</ItemsControl>


问:
Is there a way to sharescreen using WebRTC on Android
I've built webRTC for Android, and I'd like to use it to share screen.
Is there a way to send either do it out-of-the-box or push a stream of my own frames as a video source.</p>

答:
I've added an example below that shows how to configure a screen share as a video source and add it as a track on a stream.

Get the VideoCapturer

```<code>@TargetApi(21)
private VideoCapturer createScreenCapturer() {
    if (mMediaProjectionPermissionResultCode != Activity.RESULT_OK) {
        report("User didn't give permission to capture the screen.");
        return null;
    }
    return new ScreenCapturerAndroid(
            mMediaProjectionPermissionResultData, new MediaProjection.Callback() {
        @Override
        public void onStop() {
            report("User revoked permission to capture the screen.");
        }
    });
}
</code>```

Initialize the capturer and add the tracks to the local media stream

```<code>private void initScreenCapturStream() {
    mLocalMediaStream = factory.createLocalMediaStream("ARDAMS");
    MediaConstraints videoConstraints = new MediaConstraints();
    videoConstraints.mandatory.add(new MediaConstraints.KeyValuePair("maxHeight", Integer.toString(mPeerConnParams.videoHeight)));
    videoConstraints.mandatory.add(new MediaConstraints.KeyValuePair("maxWidth", Integer.toString(mPeerConnParams.videoWidth)));
    videoConstraints.mandatory.add(new MediaConstraints.KeyValuePair("maxFrameRate", Integer.toString(mPeerConnParams.videoFps)));
    videoConstraints.mandatory.add(new MediaConstraints.KeyValuePair("minFrameRate", Integer.toString(mPeerConnParams.videoFps)));

    mVideoSource = factory.createVideoSource(videoCapturer);
    videoCapturer.startCapture(mPeerConnParams.videoWidth, mPeerConnParams.videoHeight, mPeerConnParams.videoFps);
    VideoTrack localVideoTrack = factory.createVideoTrack(VIDEO_TRACK_ID, mVideoSource);
    localVideoTrack.setEnabled(true);
    mLocalMediaStream.addTrack(factory.createVideoTrack("ARDAMSv0", mVideoSource));
    AudioSource audioSource = factory.createAudioSource(new MediaConstraints());
    mLocalMediaStream.addTrack(factory.createAudioTrack("ARDAMSa0", audioSource));

    mListener.onStatusChanged("STREAMING");
}
</code>```

For more information this might be a good place to start.  Its a Android project that connects to a ProjectRTC signalling server and shares the screen as video.  I found it very helpful!

https://github.com/Jeffiano/ScreenShareRTC

Body:
I've added an example below that shows how to configure a screen share as a video source and add it as a track on a stream.

Get the VideoCapturer

@TargetApi(21)
private VideoCapturer createScreenCapturer() {
    if (mMediaProjectionPermissionResultCode != Activity.RESULT_OK) {
        report("User didn't give permission to capture the screen.");
        return null;
    }
    return new ScreenCapturerAndroid(
            mMediaProjectionPermissionResultData, new MediaProjection.Callback() {
        @Override
        public void onStop() {
            report("User revoked permission to capture the screen.");
        }
    });
}

Initialize the capturer and add the tracks to the local media stream

private void initScreenCapturStream() {
    mLocalMediaStream = factory.createLocalMediaStream("ARDAMS");
    MediaConstraints videoConstraints = new MediaConstraints();
    videoConstraints.mandatory.add(new MediaConstraints.KeyValuePair("maxHeight", Integer.toString(mPeerConnParams.videoHeight)));
    videoConstraints.mandatory.add(new MediaConstraints.KeyValuePair("maxWidth", Integer.toString(mPeerConnParams.videoWidth)));
    videoConstraints.mandatory.add(new MediaConstraints.KeyValuePair("maxFrameRate", Integer.toString(mPeerConnParams.videoFps)));
    videoConstraints.mandatory.add(new MediaConstraints.KeyValuePair("minFrameRate", Integer.toString(mPeerConnParams.videoFps)));

    mVideoSource = factory.createVideoSource(videoCapturer);
    videoCapturer.startCapture(mPeerConnParams.videoWidth, mPeerConnParams.videoHeight, mPeerConnParams.videoFps);
    VideoTrack localVideoTrack = factory.createVideoTrack(VIDEO_TRACK_ID, mVideoSource);
    localVideoTrack.setEnabled(true);
    mLocalMediaStream.addTrack(factory.createVideoTrack("ARDAMSv0", mVideoSource));
    AudioSource audioSource = factory.createAudioSource(new MediaConstraints());
    mLocalMediaStream.addTrack(factory.createAudioTrack("ARDAMSa0", audioSource));

    mListener.onStatusChanged("STREAMING");
}

For more information this might be a good place to start.  Its a Android project that connects to a ProjectRTC signalling server and shares the screen as video.  I found it very helpful!

https://github.com/Jeffiano/ScreenShareRTC


问:
Best way to search data in xml files?
In our new project we have to provide a search functionality to retrieve data from hundreds of xml files. I have a brief of our current plan below, I would like to know your suggestions/improvements on this.

These xml files contain personal information, and the search is based on 10 elements in it for example last name, first name, email etc. Our current plan is to create an master XmlDocument with all the searchable data and a key to the actual file. So that when the user searches the data we first look at master file and get the the results. We will also cache the actual xml files from the recent searches so simillar searches later can be handled quickly.

Our application is a .net 2.0 web application.

答: If you can store then data in a SQL Server database then you could make use of SQL Servers in built XPath query functionality.</p>

OwnerDisplayName: gk

ContentLicense: CC BY-SA 2.5

Title: Best way to search data in xml files?

OwnerDisplayName: Dave Barker


问:
How does runtime resolve calls to .NET 2.0 SP1 assemblies if only .NET 2.0 RTM is present
We have application built against .NET 2.0 on machine with .NET 2.0 SP1 installed. The application references some standard .NET assemblies included in .NET SP1 (i.e. System.Xml.dll).

If we run this application on computer with .net 2.0 RTM, the application runs fine, it even uses System.Xml.dll assembly. But when it tries to use method that doesn't exist in 2.0 RTM, but exists in 2.0 SP1 the application throws MethodNotFoundException.

My question is : How does the runtime resolve System.Xml.dll at all?

The assemblies versions differs in revision number (but the major, minor and build parts are equals). That means that 2.0 RTM and 2.0 SP1 assemblies are different in terms of assembly binding process. The runtime should try to find System.Xml.dll 2.0.50727.1378, but it only finds 2.0.50727.42. Then assembly binding process should fail because there can't be any Publisher policy or redirection in Machine.config. But binding works fine. How can it be?

Another one question which follows of the problem described above.

We can't force all our clients to install .NET 2.0 SP1 on their computers. If we ship System.Xml.dll from .NET 2.0 SP1, how can we force our application to use System.Xml.dll shipped with our application?

Update 1: Looks like System.Xml.dll version is 2.0.0.0, not 2.0.50727.x. That describes why the Runtime successfully resolves it. But the second question still applies: Can we ship System.Xml.dll from SP1 with our application and force our application to use it?

答:
If there is no acceptable answers I'll post my own. Hope it helps somebody.

The first question was how does runtime resolves assemblies from service pack.

I've investigated a little more and have read some articles. I mistakenly have taken a look at AssemblyFileVersion instead of AssemblyVersion. For assemblies in .NET 2.0 SP AssemblyFileVersion is 2.0.50727.1378, and for assemblies from .NET 2.0 RTM it's 2.0.50727.42. Yes, they are different, but it is AssemblyFileVersion, not AssemblyVersion. And assembly binding process uses AssemblyVersion only. But AssemblyVersion is 2.0.0.0 for .NET 2.0 RTM and .NET SPx either. So RTM and SPx assemblies are identical in terms of assembly binding process.

I'm still interested why MS hadn't shipped service pack's assemblies with incremented AssemblyVersion? They could ship SP's assemblies with corresponding Publisher policies to redirect assembly binding from RTM to SP. And if clients would like to use RTM versions of assemblies, they can ignore publisher policy for particular assemblies. Actually, I think that MS refused to go that way because it would be a total mess if client start to ignore publisher policies on some assemblies and don't ignore on others. Than BCL's assemblies couldn't rely on each other, the whole BCL would become inconsistent.

The second question was about the possibility to ship .NET 2.0 SP1 assemblies with our product and to redirect assembly binding from RTM assembly to SP's assembly.

The short answer is "no, it is not possible". But there are 2 possible solutions, but they are quite lame and can be of use only under strict circumstances and in general they are not applicable at all.

The first solution is to disasm CLR assembly and then build it again but with our public key, or we can omit strong-signing at all. Now we will be able to reference this RTM assembly rather than SP's assembly from GAC.

The second solution is to replace RTM's assembly in GAC with SP's assembly using the gacutil tool. The /f (force) option must be used.

Both of these two solutions are very lame. Please, don't use them. In general they can't be used due to some dependencies between assemblies.

Conclusion

In our product we downgraded our product so it could work on .NET 2.0 RTM. But we still use some functionality even from .NET 3.x (linq-to-objects, Action, Func). We just ship some of the 3.x assemblies with our product, e.g. System.Core.dll. Mostly we have no problems with this approach. But we also had to decline using Linq-to-Xml because of some unsolvable problems.


问:
How to fix "Xaml parsing failed"?
I'm using Visual Studio Enterprise 2017. When i try to run my UWP project on Mobile Emulator I'm getting "Xaml parse failed" error.
When i run it on "local machine" everything is ok. I didn't make any changes to xaml header from the beginning. Can anyone help me?

Image showing error below.
https://i.imgur.com/FL3Cr4K.jpg
https://i.imgur.com/65A2t9y.jpg

```<code><Page
    x:Class="KalkulatorBMI.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:KalkulatorBMI"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid Padding="10">
        <!--Padding - margines-->
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="*"/>
            <!-- * zużywa co dostanie.-->
            <RowDefinition Height="auto"/>
        </Grid.RowDefinitions>

        <StackPanel Grid.Row="0">
            <TextBlock Text="Trener persolany" Style="{ThemeResource CaptionTextBlockStyle}"/>
            <TextBlock Text="Użytkownik" Style="{ThemeResource HeaderTextBlockStyle}"/>
        </StackPanel>
        <StackPanel Grid.Row="1" >
            <ListBox Name="lbxUzytkownicy" HorizontalAlignment="Left" Width="150" Height="200" Margin="10" SelectedIndex="0"/>
            <Button Name="ButtonLoguj" Content="Loguj" Margin="10" Click="Click_Loguj"/>
            <StackPanel>
                <TextBlock Text="Nowy uzytkownik" Margin="10,0,0,5"/>
                <TextBox Name="TextboxNowy" Height="32" Width="138" Margin="10,0,0,0" HorizontalAlignment="Left"/>
                <TextBlock Name="TextboxZlaNazwa" Margin="10,5,0,0" Foreground="Red"/>
            </StackPanel>
            <StackPanel Orientation="Horizontal" >
                <Button Name="ButtonUtworz" Content="Dodaj użytkownika" Margin="10" Click="Click_Utworz"/>
                <Button Name="ButtonUsun" Content="Wyczyść listę" Margin="10" Click="Click_Usun"/>
            </StackPanel>
        </StackPanel>
        <StackPanel Grid.Row="2">
            <Button Name="ButtonZakoncz" Margin="10" Content="Zakończ"  Click="Click_Zakoncz" Foreground="Red"/>
        </StackPanel>
    </Grid>
</Page>
</code>```

答:
Assuming there are no other errors in any of your Style and ThemeResource definitions that aren't shown...

Remove the Padding="10" from the first Grid element (line#11?). Grid controls don't provide Padding properties.

Title: How to fix "Xaml parsing failed"?

Body:
I'm using Visual Studio Enterprise 2017. When i try to run my UWP project on Mobile Emulator I'm getting "Xaml parse failed" error.
When i run it on "local machine" everything is ok. I didn't make any changes to xaml header from the beginning. Can anyone help me?

Image showing error below.
https://i.imgur.com/FL3Cr4K.jpg
https://i.imgur.com/65A2t9y.jpg

<Page
    x:Class="KalkulatorBMI.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:KalkulatorBMI"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid Padding="10">

        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="*"/>

            <RowDefinition Height="auto"/>
        </Grid.RowDefinitions>

        <StackPanel Grid.Row="0">
            <TextBlock Text="Trener persolany" Style="{ThemeResource CaptionTextBlockStyle}"/>
            <TextBlock Text="Użytkownik" Style="{ThemeResource HeaderTextBlockStyle}"/>
        </StackPanel>
        <StackPanel Grid.Row="1" >
            <ListBox Name="lbxUzytkownicy" HorizontalAlignment="Left" Width="150" Height="200" Margin="10" SelectedIndex="0"/>
            <Button Name="ButtonLoguj" Content="Loguj" Margin="10" Click="Click_Loguj"/>
            <StackPanel>
                <TextBlock Text="Nowy uzytkownik" Margin="10,0,0,5"/>
                <TextBox Name="TextboxNowy" Height="32" Width="138" Margin="10,0,0,0" HorizontalAlignment="Left"/>
                <TextBlock Name="TextboxZlaNazwa" Margin="10,5,0,0" Foreground="Red"/>
            </StackPanel>
            <StackPanel Orientation="Horizontal" >
                <Button Name="ButtonUtworz" Content="Dodaj użytkownika" Margin="10" Click="Click_Utworz"/>
                <Button Name="ButtonUsun" Content="Wyczyść listę" Margin="10" Click="Click_Usun"/>
            </StackPanel>
        </StackPanel>
        <StackPanel Grid.Row="2">
            <Button Name="ButtonZakoncz" Margin="10" Content="Zakończ"  Click="Click_Zakoncz" Foreground="Red"/>
        </StackPanel>
    </Grid>
</Page>