问:
Equal space between buttons in a LinearLayout
I have four buttons arranged vertically in a LinearLayout.

I want the space between the buttons and the space between the topmost button and the top of the linear layout and the space between the bottom most button and the bottom of the layout, to be the same.

In the attached figure, the spaces are depicted as red paths.
I want all the spaces to be of the same size.

How would I go about achiving my goal?

```<code><LinearLayout
            p1:orientation="vertical"
            p1:layout_width="wrap_content"
            p1:layout_height="wrap_content"
            p1:id="@+id/mainButtonLayout">
            <Button
                p1:text="xxx"
                p1:layout_width="match_parent"
                p1:layout_height="wrap_content"
                p1:id="@+id/saButton"
                p1:textColor="#FFFFFF"
                p1:background="@drawable/roundedBlue"
                p1:minHeight="33dp"
                p1:minWidth="175dp"
                p1:layout_marginBottom="20dp" />
            <Button
                p1:text="xxxx"
                p1:layout_width="match_parent"
                p1:layout_height="wrap_content"
                p1:id="@+id/rButton"
                p1:textColor="#FFFFFF"
                p1:background="@drawable/roundedBlue"
                p1:minHeight="33dp"
                p1:minWidth="175dp"
                p1:layout_marginBottom="20dp" />
            <Button
                p1:text="xxxxx"
                p1:layout_width="match_parent"
                p1:layout_height="wrap_content"
                p1:id="@+id/sButton"
                p1:textColor="#FFFFFF"
                p1:background="@drawable/roundedBlue"
                p1:minHeight="33dp"
                p1:minWidth="175dp"
                p1:layout_marginBottom="20dp" />
            <Button
                p1:text="xxxxx"
                p1:layout_width="match_parent"
                p1:layout_height="wrap_content"
                p1:id="@+id/pButton"
                p1:textColor="#FFFFFF"
                p1:background="@drawable/roundedBlue"
                p1:minHeight="33dp"
                p1:minWidth="175dp" />
        </LinearLayout>
</code>```

答:
Use this in between your views,   </p>

```<code><View
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_weight="1" />
</code>```

Body:
I have four buttons arranged vertically in a LinearLayout.

I want the space between the buttons and the space between the topmost button and the top of the linear layout and the space between the bottom most button and the bottom of the layout, to be the same.

In the attached figure, the spaces are depicted as red paths.
I want all the spaces to be of the same size.

How would I go about achiving my goal?

<LinearLayout
            p1:orientation="vertical"
            p1:layout_width="wrap_content"
            p1:layout_height="wrap_content"
            p1:id="@+id/mainButtonLayout">
            <Button
                p1:text="xxx"
                p1:layout_width="match_parent"
                p1:layout_height="wrap_content"
                p1:id="@+id/saButton"
                p1:textColor="#FFFFFF"
                p1:background="@drawable/roundedBlue"
                p1:minHeight="33dp"
                p1:minWidth="175dp"
                p1:layout_marginBottom="20dp" />
            <Button
                p1:text="xxxx"
                p1:layout_width="match_parent"
                p1:layout_height="wrap_content"
                p1:id="@+id/rButton"
                p1:textColor="#FFFFFF"
                p1:background="@drawable/roundedBlue"
                p1:minHeight="33dp"
                p1:minWidth="175dp"
                p1:layout_marginBottom="20dp" />
            <Button
                p1:text="xxxxx"
                p1:layout_width="match_parent"
                p1:layout_height="wrap_content"
                p1:id="@+id/sButton"
                p1:textColor="#FFFFFF"
                p1:background="@drawable/roundedBlue"
                p1:minHeight="33dp"
                p1:minWidth="175dp"
                p1:layout_marginBottom="20dp" />
            <Button
                p1:text="xxxxx"
                p1:layout_width="match_parent"
                p1:layout_height="wrap_content"
                p1:id="@+id/pButton"
                p1:textColor="#FFFFFF"
                p1:background="@drawable/roundedBlue"
                p1:minHeight="33dp"
                p1:minWidth="175dp" />
        </LinearLayout>

Body:
Use this in between your views,

<View
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_weight="1" />


来源: stackexchange

问:
Global Payments Realex HPP - Do NOT send to merchantUrl
We are trying to integrate a payment in React to our backend. After hpp.lightbox.init() successes, it automatically sends the browser to the merchantUrl. We do not want that functionality because our application is an SPA, so we do not want the user to be redirected anywhere. Instead, we would like to send it to our backend endpoint ourselves, and have the user continue on to the next section of the SPA.

Below is example code that we used.

RealexHpp.setHppUrl("https://pay.sandbox.realexpayments.com/pay");
RealexHpp.lightbox.init("payNowButtonId", "backendUrlRealexWillSendToUponReceivingResponse", jsonFromRequestEndpoint);
```

In this example, we do not want to send to "backendUrlRealexWillSendToUponReceivingResponse", but would like to get init()'s response and pass the data ourselves to "backendUrlRealexWillSendToUponReceivingResponse".

We looked at the source code (lines 350-362) and it seems that RealexHpp is creating a form, attaching form to the DOM, and then submitting the form with the response data.

Seeing that, we tried to listen for any form submits, listen for form creations, on both document and window, but to no avail.

So as the title suggests. How can we process the form without sending the user to another page?

答:
The way the JS library behaves is exactly has you mentioned above. A form is created from HPP Response and is then sent to the response URL.

In the example below, you can leave this argument blank. Which will prevent the form from being sent and redirecting to the URl.

To capture the response you can add an event listener to lookout for the response from HPP.

RealexHpp.setHppUrl("https://pay.sandbox.realexpayments.com/pay");
RealexHpp.lightbox.init("payButtonId", "", jsonFromRequestEndpoint);
if (window.addEventListener) {
    window.addEventListener('message', function(e) { receiveMessage(e.data);}, false);
} else {
    window.attachEvent('message', receiveMessage);
}
```

In the above example, I have a function called receiveMessage but you can implement a similar function to execute a different task.

ContentLicense: CC BY-SA 4.0

Body:
We are trying to integrate a payment in React to our backend. After hpp.lightbox.init() successes, it automatically sends the browser to the merchantUrl. We do not want that functionality because our application is an SPA, so we do not want the user to be redirected anywhere. Instead, we would like to send it to our backend endpoint ourselves, and have the user continue on to the next section of the SPA.

Below is example code that we used.

RealexHpp.setHppUrl("https://pay.sandbox.realexpayments.com/pay");
RealexHpp.lightbox.init("payNowButtonId", "backendUrlRealexWillSendToUponReceivingResponse", jsonFromRequestEndpoint);

In this example, we do not want to send to "backendUrlRealexWillSendToUponReceivingResponse", but would like to get init()'s response and pass the data ourselves to "backendUrlRealexWillSendToUponReceivingResponse".

We looked at the source code (lines 350-362) and it seems that RealexHpp is creating a form, attaching form to the DOM, and then submitting the form with the response data.

Seeing that, we tried to listen for any form submits, listen for form creations, on both document and window, but to no avail.

So as the title suggests. How can we process the form without sending the user to another page?

Body:
The way the JS library behaves is exactly has you mentioned above. A form is created from HPP Response and is then sent to the response URL.

In the example below, you can leave this argument blank. Which will prevent the form from being sent and redirecting to the URl.

To capture the response you can add an event listener to lookout for the response from HPP.

RealexHpp.setHppUrl("https://pay.sandbox.realexpayments.com/pay");
RealexHpp.lightbox.init("payButtonId", "", jsonFromRequestEndpoint);
if (window.addEventListener) {
    window.addEventListener('message', function(e) { receiveMessage(e.data);}, false);
} else {
    window.attachEvent('message', receiveMessage);
}

In the above example, I have a function called receiveMessage but you can implement a similar function to execute a different task.


问:
What is the SQL query to show another date format?
I have two MySQL database tabels (named 'accounts' and 'events') with some columns like events.date. This column has a 'date' format. It shows the date as i.e. '2020-02-17'. Now I want to show some data from this combined tables with a query and I want to convert the date formate to DD-MM-YYYY instead of YYYY-MM-DD. I've tried some things but I got errors.

Queries I've tried:

```<code>SELECT events.id, convert(varchar, events.date, 105), events.starttime, events.endtime, events.reason, events.created, events.employee, events.employee_id, REPLACE(REPLACE(REPLACE(accounts.location, '1', 'London'), '2', 'Birmingham'), '3', 'Rochdale') location, events.minutes, ROUND((minutes/60), 2) as hours FROM events JOIN accounts ON events.employee_id = accounts.id ORDER BY date

SELECT events.id, convert(date(4), events.date, 20), events.starttime, events.endtime, events.reason, events.created, events.employee, events.employee_id, REPLACE(REPLACE(REPLACE(accounts.location, '1', 'London'), '2', 'Birmingham'), '3', 'Rochdale') location, events.minutes, ROUND((minutes/60), 2) as hours FROM events JOIN accounts ON events.employee_id = accounts.id ORDER BY date
</code>```

This query works well but shows me the wrong date format:

```<code>SELECT events.id, events.date, events.starttime, events.endtime, events.reason, events.created, events.employee, events.employee_id, REPLACE(REPLACE(REPLACE(accounts.location, '1', 'London'), '2', 'Birmingham'), '3', 'Rochdale') location, events.minutes, ROUND((minutes/60), 2) as hours FROM events JOIN accounts ON events.employee_id = accounts.id ORDER BY date
</code>```

Can you please help me? Many thanks in advance!

答:
You have to use DATE_FORMAT:

SELECT
    events.id,
    DATE_FORMAT(events.date, '%d-%m-%Y'),
    events.starttime,
    events.endtime,
    events.reason,
    events.created,
    events.employee,
    events.employee_id,
    REPLACE(REPLACE(REPLACE(accounts.location, '1', 'London'), '2', 'Birmingham'), '3', 'Rochdale') location,
    events.minutes,
    ROUND((minutes/60), 2) as hours
FROM events
JOIN accounts ON events.employee_id = accounts.id
ORDER BY date
```

Body:
I have two MySQL database tabels (named 'accounts' and 'events') with some columns like events.date. This column has a 'date' format. It shows the date as i.e. '2020-02-17'. Now I want to show some data from this combined tables with a query and I want to convert the date formate to DD-MM-YYYY instead of YYYY-MM-DD. I've tried some things but I got errors.

Queries I've tried:

SELECT events.id, convert(varchar, events.date, 105), events.starttime, events.endtime, events.reason, events.created, events.employee, events.employee_id, REPLACE(REPLACE(REPLACE(accounts.location, '1', 'London'), '2', 'Birmingham'), '3', 'Rochdale') location, events.minutes, ROUND((minutes/60), 2) as hours FROM events JOIN accounts ON events.employee_id = accounts.id ORDER BY date

SELECT events.id, convert(date(4), events.date, 20), events.starttime, events.endtime, events.reason, events.created, events.employee, events.employee_id, REPLACE(REPLACE(REPLACE(accounts.location, '1', 'London'), '2', 'Birmingham'), '3', 'Rochdale') location, events.minutes, ROUND((minutes/60), 2) as hours FROM events JOIN accounts ON events.employee_id = accounts.id ORDER BY date

This query works well but shows me the wrong date format:

SELECT events.id, events.date, events.starttime, events.endtime, events.reason, events.created, events.employee, events.employee_id, REPLACE(REPLACE(REPLACE(accounts.location, '1', 'London'), '2', 'Birmingham'), '3', 'Rochdale') location, events.minutes, ROUND((minutes/60), 2) as hours FROM events JOIN accounts ON events.employee_id = accounts.id ORDER BY date

Can you please help me? Many thanks in advance!


答:
You can use merge in Reduce:

```<code>Reduce(merge, list(df, df1, df2, df3))
#  ID YEAR MONTH DAY HOUR VALUE1 VALUE2 VALUE3 VALUE4
#1  A 2020     1  16   15      1      3      6      9
#2  B 2020     1  16   15      2      4      7     10
#3  C 2020     1  16   15      3      5      8     11
</code>```

Title: How to merge(efficient way) multiple data frame in one go?

Body:
I would like to merge multiple dataframe in one shot. Below the method, I am currently using for merging.
My data:

df <- data.frame('ID'=c('A','B','C'),'YEAR'=c('2020','2020','2020'),'MONTH'=c('1','1','1'),'DAY'=c('16','16','16'),'HOUR'=c('15','15','15'),'VALUE1'=c(1,2,3))

df1 <- data.frame('ID'=c('A','B','C'),'YEAR'=c('2020','2020','2020'),'MONTH'=c('1','1','1'),'DAY'=c('16','16','16'),'HOUR'=c('15','15','15'),'VALUE2'=c(3,4,5))

df2 <- data.frame('ID'=c('A','B','C'),'YEAR'=c('2020','2020','2020'),'MONTH'=c('1','1','1'),'DAY'=c('16','16','16'),'VALUE3'=c(6,7,8))

df3 <- data.frame('ID'=c('A','B','C'),'YEAR'=c('2020','2020','2020'),'MONTH'=c('1','1','1'),'VALUE4'=c(9,10,11))

My method of merging:

df4 <- merge(df,df1,by=c('ID','DAY','MONTH','YEAR','HOUR'),all.x=T)
df5 <- merge(df4,df2,by=c('ID','DAY','MONTH','YEAR'),all.x=T)
df6 <- merge(df5,df3,by=c('ID','MONTH','YEAR'),all.x=T)

My output:

ID MONTH YEAR DAY HOUR VALUE1 VALUE2 VALUE3 VALUE4
1  A     1 2020  16   15      1      3      6      9
2  B     1 2020  16   15      2      4      7     10
3  C     1 2020  16   15      3      5      8     11

Is there any good method of merging which can make code more efficient. I appreciate any help.

Body:
You can use merge in Reduce:

Reduce(merge, list(df, df1, df2, df3))
#  ID YEAR MONTH DAY HOUR VALUE1 VALUE2 VALUE3 VALUE4
#1  A 2020     1  16   15      1      3      6      9
#2  B 2020     1  16   15      2      4      7     10
#3  C 2020     1  16   15      3      5      8     11


问:
multiple `async getter(s)` in one object acting as a cache
Update2: The following works but not quite

const obj = {
    cached_a: 0,
    cached_b: 0,
    cached_c: 0,

    get a() {
        if (this.cached_a == 0) this.cached_a = getA();
        return this.cached_a;
    }
}

const getA = function() {
    console.log('calcing...')
    return 25;
};

console.log('1: ' + obj.a);
console.log('2: ' + obj.a);
```

<p>In my program, the value is not calculated the second time but sent back from the cache.</p>

<pre class="lang-sh prettyprint-override"><code>$ node get-set.js
calcing...
1: 25
2: 25
</code>```

For one, my getA() has to be async. But, I understand that ES6 doesn't allow async getters. If that is correct, I would appreciate a better way of achieving the above (given that getA() has to be async.

Second, how do I use multiple getters (for b and c as well)?

Update1: The getA() (and hopefully, other getters) get values from the server (this is all browser side), and I don't want that to happen if the value has been retrieved once and is cached in the browser.

I am trying to understand and implement getter/setter in an object that is going to act as a cache for values returned from async processes.

'use strict';

// my desired pseudo-object with incorrect code
const obj = {
    a: 0,
    b: 0,
    c: 0,

    get a() {
        if (this.a == 0) this.a = await getA();
        return this.a;
    }

    get b() {
        if (this.b == 0) this.b = await getB();
        return this.b;
    }

    get c() {
        if (this.c == 0) this.c = await getA();
        return this.c;
    }
};

const getA = async function() { … };
const getB = async function() { … };
const getC = async function() { … };
```

Obviously, several problems with the above:

can't have multiple getters (or can I?);

can't have getters named the same as the property as that results in a recursive call (how do I make the act of getting transparent for the user?)

What is a better way to implement this?

答:
There are multiple ways to do this, but at the risk of helping you out with a problem you don't have (I suspect your overall application design has flaws you should correct elsewhere), I'll address your immediate problem.

Your mistakes are rooted in the fact that your property descriptions -- whether expressed as e.g. a: 1 or get a() ... use the same property descriptor (commonly referred to as "name") so your getter redefines what e.g. this.a will refer to, overwriting the previous property description (a: 1) and the same applies to the other properties b and c.

I also want to state that your apparent idea of caching promises leads me to think that perhaps some of your assumptions are wrong -- when a promise resolves, the value is already cached internally. A promise is designed to be settled (resolved or rejected) only once, but every time you attach a callback though the Promise.prototype.then, the [settled] promise will call your callback with the internally cached value. await is little more than syntactic sugar where the interpreter internally runs your code in order, but rest assured whenever an await expression is evaluated, a cached value that was "resolved" once will be used.

What I am trying to tell you is that caching promises does not make sense.

What you can cache is procedure evaluation. You start by assuming that a procedure call (without arguments, to make caching simpler) will always return the same value, which you then may safely associate with the procedure, in your cache:

```<code>const cached = (() => {
    const cache = new WeakMap();
    return (procedure) => {
        var result = cache.get(procedure);
        return result || (cache.set(procedure, result = procedure()), result);
    }
})();
</code>```

Now, if you have a costly operation encapsulated in a function, say request_foobar, instead of using the request_foobar() expression which will perform a lengthy operation that returns the same result every time anyway, you can use cached(request_foobar) expression, which will get you the previous result from cache, if there is a cache hit, or, if there isn't, call the procedure and return the cached result.

The implementation of cached depends on so-called "closure" functions -- the procedure assigned to the cached constant may access objects (variables, constants, etc) in its outer scope, including the actual cache (a map of results based on procedure references).

Body:
Update2: The following works but not quite

const obj = {
    cached_a: 0,
    cached_b: 0,
    cached_c: 0,

    get a() {
        if (this.cached_a == 0) this.cached_a = getA();
        return this.cached_a;
    }
}

const getA = function() {
    console.log('calcing...')
    return 25;
};

console.log('1: ' + obj.a);
console.log('2: ' + obj.a);

In my program, the value is not calculated the second time but sent back from the cache.

$ node get-set.js
calcing...
1: 25
2: 25

For one, my getA() has to be async. But, I understand that ES6 doesn't allow async getters. If that is correct, I would appreciate a better way of achieving the above (given that getA() has to be async.

Second, how do I use multiple getters (for b and c as well)?

Update1: The getA() (and hopefully, other getters) get values from the server (this is all browser side), and I don't want that to happen if the value has been retrieved once and is cached in the browser.

I am trying to understand and implement getter/setter in an object that is going to act as a cache for values returned from async processes.

'use strict';

// my desired pseudo-object with incorrect code
const obj = {
    a: 0,
    b: 0,
    c: 0,

    get a() {
        if (this.a == 0) this.a = await getA();
        return this.a;
    }

    get b() {
        if (this.b == 0) this.b = await getB();
        return this.b;
    }

    get c() {
        if (this.c == 0) this.c = await getA();
        return this.c;
    }
};

const getA = async function() { … };
const getB = async function() { … };
const getC = async function() { … };

Obviously, several problems with the above:

can't have multiple getters (or can I?);

can't have getters named the same as the property as that results in a recursive call (how do I make the act of getting transparent for the user?)

What is a better way to implement this?

Body:
There are multiple ways to do this, but at the risk of helping you out with a problem you don't have (I suspect your overall application design has flaws you should correct elsewhere), I'll address your immediate problem.

Your mistakes are rooted in the fact that your property descriptions -- whether expressed as e.g. a: 1 or get a() ... use the same property descriptor (commonly referred to as "name") so your getter redefines what e.g. this.a will refer to, overwriting the previous property description (a: 1) and the same applies to the other properties b and c.

I also want to state that your apparent idea of caching promises leads me to think that perhaps some of your assumptions are wrong -- when a promise resolves, the value is already cached internally. A promise is designed to be settled (resolved or rejected) only once, but every time you attach a callback though the Promise.prototype.then, the [settled] promise will call your callback with the internally cached value. await is little more than syntactic sugar where the interpreter internally runs your code in order, but rest assured whenever an await expression is evaluated, a cached value that was "resolved" once will be used.

What I am trying to tell you is that caching promises does not make sense.

What you can cache is procedure evaluation. You start by assuming that a procedure call (without arguments, to make caching simpler) will always return the same value, which you then may safely associate with the procedure, in your cache:

const cached = (() => {
    const cache = new WeakMap();
    return (procedure) => {
        var result = cache.get(procedure);
        return result || (cache.set(procedure, result = procedure()), result);
    }
})();

Now, if you have a costly operation encapsulated in a function, say request_foobar, instead of using the request_foobar() expression which will perform a lengthy operation that returns the same result every time anyway, you can use cached(request_foobar) expression, which will get you the previous result from cache, if there is a cache hit, or, if there isn't, call the procedure and return the cached result.

The implementation of cached depends on so-called "closure" functions -- the procedure assigned to the cached constant may access objects (variables, constants, etc) in its outer scope, including the actual cache (a map of results based on procedure references).


问:
"export 'DOCUMENT' was not found in '@angular/platform-browser'
Happened while trying to upgrade IONIC app from version 3 to 4

Updated all plugins and modules to latest available, without any luck.

```<code>ERROR in ./node_modules/ionic-angular/components/app/app.js 24:35-43
"export 'DOCUMENT' was not found in '@angular/platform-browser'
ERROR in ./node_modules/ionic-angular/module.js 195:71-79
"export 'DOCUMENT' was not found in '@angular/platform-browser'
[ERROR] An error occurred while running subprocess ng.
</code>```

This is my IONIC INFO

```<code>Ionic info:
Ionic:

   Ionic CLI                     : 5.1.0 (C:\Users\Acer\AppData\Roaming\npm\node_modules\ionic)
   Ionic Framework               : @ionic/angular 4.6.0
   @angular-devkit/build-angular : 0.800.6
   @angular-devkit/schematics    : 8.0.6
   @angular/cli                  : 8.0.6
   @ionic/angular-toolkit        : 2.0.0

Cordova:

   Cordova CLI       : 9.0.0 (cordova-lib@9.0.1)
   Cordova Platforms : not available
   Cordova Plugins   : not available

Utility:

   cordova-res : 0.5.1
   native-run  : 0.2.6

System:

   Android SDK Tools : 26.1.1 (C:\Users\Acer\AppData\Local\Android\sdk)
   NodeJS            : v10.11.0 (C:\Program Files\nodejs\node.exe)
   npm               : 6.9.2
   OS                : Windows 10
</code>```

would appreciate, somebody could be helpful.

答:
I faced this issue while migrating to angular 8.x.x .

Actually 'DOCUMENT' has been deprecated from '@angular/platform-browser' and is now part of '@angular/common'.

Older plugins still try to import document from '@angular/platform-browser' . Just check in the .js and .js.map files under 'fesm5' as well as 'fesm2015' folder of the plugin in node_modules section.

Better to update the specific plugin to latest angular compatible version.

In my case troubling plugin was 'ngx-clipboard'.

Body:
Happened while trying to upgrade IONIC app from version 3 to 4

Updated all plugins and modules to latest available, without any luck.

ERROR in ./node_modules/ionic-angular/components/app/app.js 24:35-43
"export 'DOCUMENT' was not found in '@angular/platform-browser'
ERROR in ./node_modules/ionic-angular/module.js 195:71-79
"export 'DOCUMENT' was not found in '@angular/platform-browser'
[ERROR] An error occurred while running subprocess ng.

This is my IONIC INFO

Ionic info:
Ionic:

   Ionic CLI                     : 5.1.0 (C:\Users\Acer\AppData\Roaming\npm\node_modules\ionic)
   Ionic Framework               : @ionic/angular 4.6.0
   @angular-devkit/build-angular : 0.800.6
   @angular-devkit/schematics    : 8.0.6
   @angular/cli                  : 8.0.6
   @ionic/angular-toolkit        : 2.0.0

Cordova:

   Cordova CLI       : 9.0.0 (cordova-lib@9.0.1)
   Cordova Platforms : not available
   Cordova Plugins   : not available

Utility:

   cordova-res : 0.5.1
   native-run  : 0.2.6

System:

   Android SDK Tools : 26.1.1 (C:\Users\Acer\AppData\Local\Android\sdk)
   NodeJS            : v10.11.0 (C:\Program Files\nodejs\node.exe)
   npm               : 6.9.2
   OS                : Windows 10

would appreciate, somebody could be helpful.


问:
Configurable token lifetimes in Azure Active Directory for my Web API
I need to create lifetime token for my WEB Api. I’ve used the following guide but the Policy doesn’t work.
As I’ve noticed, for my Web Api the following OrganizationDefaultPolicyScenario works.
I made it work by only using AzureADPolicy with setting -IsOrganizationDefault $true not $false.

My configuration:

```<code>OdataType             :
AlternativeIdentifier :
Definition            : {{"TokenLifetimePolicy":{"Version":1, "AccessTokenLifetime":"02:00:00"}}}
DisplayName           : OrganizationDefaultPolicyScenario
IsOrganizationDefault : True
KeyCredentials        : {}
Type                  : TokenLifetimePolicy

OdataType             :
AlternativeIdentifier :
Definition            : {{"TokenLifetimePolicy":{"Version":1, "AccessTokenLifetime":"08:00:00", "MaxInactiveTime":"30.00:00:00", "MaxAgeMultiFactor":"until-revoked", "MaxAgeSingleFactor":"180.00:00:00"}}}
DisplayName           : WebApiDefaultPolicy
IsOrganizationDefault : False
KeyCredentials        : {}
Type                  : TokenLifetimePolicy

PS C:\Users\1> Get-Azureadapplicationpolicy -id

Id                    :
OdataType             : #microsoft.graph.policy
AlternativeIdentifier :
Definition            : {{"TokenLifetimePolicy":{"Version":1, "AccessTokenLifetime":"08:00:00", "MaxInactiveTime":"30.00:00:00", "MaxAgeMultiFactor":"until-revoked", "MaxAgeSingleFactor":"180.00:00:00"}}}
DisplayName           : WebApiDefaultPolicy
IsOrganizationDefault : False
KeyCredentials        : {}
Type                  : TokenLifetimePolicy
</code>```

答:
Get-Azureadapplicationpolicy means that get the policy assigned to an application.
And as the article said, ‑IsOrganizationDefault, if true, sets the policy as the organization's default policy. If false, does nothing.

So the WebApiDefaultPolicy is assigned to application.

The policy for web sign-in is as below:

```<code>$policy = New-AzureADPolicy -Definition @('{"TokenLifetimePolicy":{"Version":1,"AccessTokenLifetime":"02:00:00","MaxAgeSessionSingleFactor":"02:00:00"}}') -DisplayName "WebPolicyScenario" -IsOrganizationDefault $false -Type "TokenLifetimePolicy"
</code>```

Body:
I need to create lifetime token for my WEB Api. I’ve used the following guide but the Policy doesn’t work.
As I’ve noticed, for my Web Api the following OrganizationDefaultPolicyScenario works.
I made it work by only using AzureADPolicy with setting -IsOrganizationDefault $true not $false.

My configuration:

OdataType             :
AlternativeIdentifier :
Definition            : {{"TokenLifetimePolicy":{"Version":1, "AccessTokenLifetime":"02:00:00"}}}
DisplayName           : OrganizationDefaultPolicyScenario
IsOrganizationDefault : True
KeyCredentials        : {}
Type                  : TokenLifetimePolicy

OdataType             :
AlternativeIdentifier :
Definition            : {{"TokenLifetimePolicy":{"Version":1, "AccessTokenLifetime":"08:00:00", "MaxInactiveTime":"30.00:00:00", "MaxAgeMultiFactor":"until-revoked", "MaxAgeSingleFactor":"180.00:00:00"}}}
DisplayName           : WebApiDefaultPolicy
IsOrganizationDefault : False
KeyCredentials        : {}
Type                  : TokenLifetimePolicy

PS C:\Users\1> Get-Azureadapplicationpolicy -id

Id                    :
OdataType             : #microsoft.graph.policy
AlternativeIdentifier :
Definition            : {{"TokenLifetimePolicy":{"Version":1, "AccessTokenLifetime":"08:00:00", "MaxInactiveTime":"30.00:00:00", "MaxAgeMultiFactor":"until-revoked", "MaxAgeSingleFactor":"180.00:00:00"}}}
DisplayName           : WebApiDefaultPolicy
IsOrganizationDefault : False
KeyCredentials        : {}
Type                  : TokenLifetimePolicy

Body:
Get-Azureadapplicationpolicy means that get the policy assigned to an application.
And as the article said, ‑IsOrganizationDefault, if true, sets the policy as the organization's default policy. If false, does nothing.

So the WebApiDefaultPolicy is assigned to application.

The policy for web sign-in is as below:

$policy = New-AzureADPolicy -Definition @('{"TokenLifetimePolicy":{"Version":1,"AccessTokenLifetime":"02:00:00","MaxAgeSessionSingleFactor":"02:00:00"}}') -DisplayName "WebPolicyScenario" -IsOrganizationDefault $false -Type "TokenLifetimePolicy"


问:
Haskell | Exception: Non-exhaustive patterns in function myAny
I have just started learning haskell and wrote a customized code for any function.
Please suggest why does it still shows Non-exhaustive patterns error even after I have used otherwise or where I am going wrong?

Exceptiom raised :-
    Exception: main.hs:(37,1)-(40,21): Non-exhaustive patterns in function myAny

```<code>myAny :: (a -> Bool) -> [a] -> Bool
myAny f (x:xs)
  | f x == True = True
  | f x == False = myAny f xs
  | otherwise = False
</code>```

答:
The problem here is that haskell cannot deconstruct [] into (x:xs), resulting in the case of an empty list not being covered.

A solution would be to specify:

```<code>myAny :: (a -> Bool) -> [a] -> Bool
myAny f (x:xs)
  -- ...
myAny f [] = False
</code>```

OwnerDisplayName: Sidharath Khanna

Body:
I have just started learning haskell and wrote a customized code for any function.
Please suggest why does it still shows Non-exhaustive patterns error even after I have used otherwise or where I am going wrong?

Exceptiom raised :-
    Exception: main.hs:(37,1)-(40,21): Non-exhaustive patterns in function myAny

myAny :: (a -> Bool) -> [a] -> Bool
myAny f (x:xs)
  | f x == True = True
  | f x == False = myAny f xs
  | otherwise = False

Body:
The problem here is that haskell cannot deconstruct [] into (x:xs), resulting in the case of an empty list not being covered.

A solution would be to specify:

myAny :: (a -> Bool) -> [a] -> Bool
myAny f (x:xs)
  -- ...
myAny f [] = False


问:
In retrospect, best open source stack/tools to build facebook
I have been doing high performance scientific computing in c++ most of my life. I am trying to learn to developing AJAXy web applications. As an exercise, I would like to build something that has a subset of functionality of facebook (profiles, posts with comment threads, friend lists) + the ability to search any post/comment.

I have no experience developing these kind of apps, except minor amount of toying with Google Appengine with GWT+Java and little bit of python. What tools/stack would you suggest using for it? I understand that this a very vague question, but I'd like to get a few opinions and your thought process about how would you go about using it.

How does the choice change, if you want a fast prototype as fast as possible, vs if you are trying to build something that can scale and last a few cycles of feature requests.

To be more specific, I'm lost in questions like, should I consider Drupal, should I consider Lucene for search, Would GWT get me what I want in the UI or would python+django be faster to develop. Probably I should not over think and pick something. But some perspective from others would be nice.

答:
If you have started out with Python, that might be the easiest to get going with, especially since you have some experience with Google's App Engine already.  However, if you have spent most of your time working with C++ ... did you know that C++ has at least two different full-stack web frameworks?

CppCMS

Wt (WebToolkit)

Remember, it's what you develop fastest in that makes the difference in the long run.  What will slow you down most of all is dealing with what you dislike.  So, if long compile times kill you, then try Python, Ruby, PHP, or some other dynamic language.  If having code that is less than perfectly optimized (and slower that it could be) is what bothers you most, use C++, C#, or Java instead.

ContentLicense: CC BY-SA 3.0


问:
How to convert to camel casing after a symbol?
```<code>Input #2: profile.Address.AddressLine1
Result: profile.address.addressLine1

Input #2: MyName
Result: myName
</code>```

<hr>

```<code>using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string inputText = "profile.Business.AddressLine1"; //profile.business.addressLine1
            //string inputText = "MyName"; //myName
            string result = null;

            if (inputText.Contains('.'))
            {
                //make first character lowercase
                result = inputText.Substring(0, 1).ToLower() + inputText.Substring(1);

                //Loop to find period symbol
                //make the next character after the period symbol lowercase
            }
            else
            {
                //make first character lowercase
                result = inputText.Substring(0, 1).ToLower() + inputText.Substring(1);
            }
        }
    }
}
</code>```

答:
I suggest using regular expressions:

Code:

```<code>  using System.Linq; // For test only
  using System.Text.RegularExpressions;

  ...

  Func<string, string> toCamel = (source) =>
    Regex.Replace(source, @"\b\p{Lu}", m => m.Value.ToLower());

  string[] tests = new string[] {
    @"profile.Business.AddressLine1",
    @"MyFunction(Value, SomeId);",
  };

  string report = string.Join(Environment.NewLine, tests
    .Select(test => $"{test,-40} => {toCamel(test)}"));

  Console.WriteLine(report);
</code>```

we Replace every uppercase letter (\p{Lu}) which is preceeded by word boundary (\b) with lowercase one

Outcome:

```<code>profile.Business.AddressLine1            => profile.business.addressLine1
MyFunction(Value, SomeId);               => myFunction(value, someId);
</code>```

If you want to convert after . only, just change the pattern into

```<code>@"\.\p{Lu}"
</code>```

Body:
Input #2: profile.Address.AddressLine1
Result: profile.address.addressLine1

Input #2: MyName
Result: myName

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string inputText = "profile.Business.AddressLine1"; //profile.business.addressLine1
            //string inputText = "MyName"; //myName
            string result = null;

            if (inputText.Contains('.'))
            {
                //make first character lowercase
                result = inputText.Substring(0, 1).ToLower() + inputText.Substring(1);

                //Loop to find period symbol
                //make the next character after the period symbol lowercase
            }
            else
            {
                //make first character lowercase
                result = inputText.Substring(0, 1).ToLower() + inputText.Substring(1);
            }
        }
    }
}

Body:
I suggest using regular expressions:

Code:

  using System.Linq; // For test only
  using System.Text.RegularExpressions;

  ...

  Func<string, string> toCamel = (source) =>
    Regex.Replace(source, @"\b\p{Lu}", m => m.Value.ToLower());

  string[] tests = new string[] {
    @"profile.Business.AddressLine1",
    @"MyFunction(Value, SomeId);",
  };

  string report = string.Join(Environment.NewLine, tests
    .Select(test => $"{test,-40} => {toCamel(test)}"));

  Console.WriteLine(report);

we Replace every uppercase letter (\p{Lu}) which is preceeded by word boundary (\b) with lowercase one

Outcome:

profile.Business.AddressLine1            => profile.business.addressLine1
MyFunction(Value, SomeId);               => myFunction(value, someId);

If you want to convert after . only, just change the pattern into

@"\.\p{Lu}"


问:
link "see more" in the text box, at the overflow
I need to cut responsive text on line 4, like this :

I did it like this:

$(".show-more").on('click', function(){
    $('.text').css('display', 'block');
    $(this).css('display', 'none');
    return false;
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.show-more{
        position: absolute;
        display: block;
        padding:0;
        margin: 0;
        font-size: 11px;
        line-height: 16px;
        font-weight: 400;
        border: none;
        outline: none;
        right: 0px;
        height: 24px;
        width: 93px;
        text-align: left;
        transform: translateY(-20px);
    }
 .text{
        width: auto;
        margin: 0 16px;
        font-size: 11px;
        line-height: 16px;
        font-weight: 400;
        margin-top: -33px;
        display: -webkit-box;
        -webkit-line-clamp: 4;
        -webkit-box-orient: vertical;
        overflow: hidden;
    }</code>```

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

<button class="show-more">...  see-more</button>```

I need to add a 'see more' link but at the end of the fourth line.

Currently, I added a button with the text and then placed it in absolute above the text.

I am looking for a 'cleaner' method because the text can be cut in the middle of a letter.

答:
You can achieve this using only a link  element in your paragraph:

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
  in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
  ... see-more

```

Body:
I need to cut responsive text on line 4, like this :

I did it like this:

$(".show-more").on('click', function(){
    $('.text').css('display', 'block');
    $(this).css('display', 'none');
    return false;
});

.show-more{
        position: absolute;
        display: block;
        padding:0;
        margin: 0;
        font-size: 11px;
        line-height: 16px;
        font-weight: 400;
        border: none;
        outline: none;
        right: 0px;
        height: 24px;
        width: 93px;
        text-align: left;
        transform: translateY(-20px);
    }
 .text{
        width: auto;
        margin: 0 16px;
        font-size: 11px;
        line-height: 16px;
        font-weight: 400;
        margin-top: -33px;
        display: -webkit-box;
        -webkit-line-clamp: 4;
        -webkit-box-orient: vertical;
        overflow: hidden;
    }

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum

<button class="show-more">...  see-more</button>

I need to add a 'see more' link but at the end of the fourth line.

Currently, I added a button with the text and then placed it in absolute above the text.

I am looking for a 'cleaner' method because the text can be cut in the middle of a letter.

Body:
You can achieve this using only a link <a> element in your paragraph:

<p class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
  in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
  <a href="" class="show-more">... see-more</a>
</p>


问:
C code Optimization by compiler for atmel studio
I am using Atmel Studio 7 and in that, optimization level is -O1.
Can I check what portion of code is being optimized by the compiler itself?
If I am disabling the optimization, my binary file size is of 12KB and on using optimization level -O1, binary file size if 5.5KB. </p>

答:
Can I check what portion of code is being optimized by the compiler itself?

All the code is optimized by the compiler, i.e affected by optimization flags except

It's code that's dragged from libraries (libgcc.a, libc.a, libm.a, lib<device>.a).

Startup code (crt<device>.o) which also includes the vector table, or code from other objects that already exist and are not (re-)compiled in the current compilation.  The latter can happen with Makefiles when you change flags therein:  If the modules do not depend on the Makefile itself, make will not rebuild them.

Code from assembly modules (*.S, *.sx, *.s) provided preprocessed assembly code does not use conditional assemblation by means of #ifdef  __OPTIMIZE__ or similar.

Code in inline assembly, provided the inline asm is not optimized away.

In order to determine whether anything of this is in effect, you can respectively:

Link with -Wl,-Map,file.map and inspect that map file (a text file).  It will list which objects have been dragged from where due to which undefined symbol.

Startup code is linked except you -nostartfiles.  Add -Wl,-v to the link stage, you'll see crt<device>.o being linked.

You know your compilation units, assembly modules, don't you?

Add -save-temps to the compilation.  Inline asm will show in the intermediate *.s file as

/* #APP */
;  <line> "<compilation-unit>"
    <inline-asm-code>
/* #NOAPP */
```


问:
why this regular does not Match the html using python
the html is :

```<code><div style="background-color:#A7A7A7;text-align:center;">
<span style="color:#FFFFFF;">{{rk_user.name}}のｽﾃｰﾀｽ</span>
</div>
</code>```

my Regular is :

```<code>a = r'''
<div style="background-color:#([a-z0-9]+);text-align:center;">
\s*<span style="color:#(.+?);">(.+)</span>
</div>
'''
</code>```

but this Regular does not Match the html ,

so what is wrong  ?

thanks

答:
Do not use regular expressions to parse HTML. Please!

Use an HTML parser!

Why not use regex, you ask?

Regular expression to match closing HTML tags

Can you provide some examples of why it is hard to parse XML and HTML with a regex?

Using regular expressions to parse HTML: why not?

Can regular expressions be used to match nested patterns?

How do HTML parses work if they're not using regexp?

And the ever-famous RegEx match open tags except XHTML self-contained tags

Body:
the html is :

{{rk_user.name}}のｽﾃｰﾀｽ

my Regular is :

a = r'''

\s*(.+)

'''

but this Regular does not Match the html ,

so what is wrong  ?

thanks


问:
Efficient way of exporting a range of cells spanning two columns
I am new to VBA and have made necessary adjustments to a script I have found online. What I want to do is to get the values of the range G2:H40000 from an Excel file, with each row cell separated by a Tab, then saved to a UTF-8 text file.

I have tested the script for range G2:H12, and it works. But when it involves 40,000+ row (like G2:H40000) with each cell in column H containing many text, the script takes so long to finish that I had to stop the process after more than an hour.

How can I make the script below run faster and be more efficient?

```<code>Sub ExportToTxt()

    Dim data As Range, row As Range, cell As Range
    Dim output As String

    Set data = Range("G2:H40000")

    For Each row In data.Rows
      For Each cell In row.Cells(1, 1) '1st param 1 excludes the table header
          output = output & cell.Value & vbTab & cell.Offset(0, 1).Value ' Offset 2nd param gets the adjacent cell to its right
      Next cell
      output = output & vbNewLine
    Next row

    ' Write to a UTF-8 encoded text file:
    Filename = "C:\Users\lenovo\Desktop\output.txt"
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set out = fso.CreateTextFile(Filename, True, True) 'Syntax: object.CreateTextFile(filename[,overwrite[,unicode]])
    out.WriteLine (output)

    out.Close

End Sub
</code>```

答:
Try this code, please. It must be very fast...

```<code>Sub ExportToTxt()
    Dim data As Range, fso As Object, out As Object, k As Long, i As Long
    Dim output As String, arrDat As Variant, fileName As String

    Set data = Range("G2:H40000")
    arrDat = data.Value 'an array is created from the above range

    Filename = "C:\Users\lenovo\Desktop\output.txt"
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set out = fso.CreateTextFile(fileName, True, True) 'Syntax: object.CreateTextFile(filename[,overwrite[,unicode]])
        For k = 1 To UBound(arrDat, 1)
           For i = 1 To UBound(arrDat, 2)
              output = output & arrDat(k, i) & vbTab
           Next i
           'the line string is created by array row elements concatenation:
           output = left(output, Len(output) - 1)
           out.WriteLine (output): output = ""'make the output string null after writing it in the text file.
        Next k
    out.Close
End Sub
</code>```

It can be a little simpler for only two columns, but it is designed to work for how many columns you need...

Body:
I am new to VBA and have made necessary adjustments to a script I have found online. What I want to do is to get the values of the range G2:H40000 from an Excel file, with each row cell separated by a Tab, then saved to a UTF-8 text file.

I have tested the script for range G2:H12, and it works. But when it involves 40,000+ row (like G2:H40000) with each cell in column H containing many text, the script takes so long to finish that I had to stop the process after more than an hour.

How can I make the script below run faster and be more efficient?

Sub ExportToTxt()

    Dim data As Range, row As Range, cell As Range
    Dim output As String

    Set data = Range("G2:H40000")

    For Each row In data.Rows
      For Each cell In row.Cells(1, 1) '1st param 1 excludes the table header
          output = output & cell.Value & vbTab & cell.Offset(0, 1).Value ' Offset 2nd param gets the adjacent cell to its right
      Next cell
      output = output & vbNewLine
    Next row

    ' Write to a UTF-8 encoded text file:
    Filename = "C:\Users\lenovo\Desktop\output.txt"
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set out = fso.CreateTextFile(Filename, True, True) 'Syntax: object.CreateTextFile(filename[,overwrite[,unicode]])
    out.WriteLine (output)

    out.Close

End Sub

Body:
Try this code, please. It must be very fast...

Sub ExportToTxt()
    Dim data As Range, fso As Object, out As Object, k As Long, i As Long
    Dim output As String, arrDat As Variant, fileName As String

    Set data = Range("G2:H40000")
    arrDat = data.Value 'an array is created from the above range

    Filename = "C:\Users\lenovo\Desktop\output.txt"
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set out = fso.CreateTextFile(fileName, True, True) 'Syntax: object.CreateTextFile(filename[,overwrite[,unicode]])
        For k = 1 To UBound(arrDat, 1)
           For i = 1 To UBound(arrDat, 2)
              output = output & arrDat(k, i) & vbTab
           Next i
           'the line string is created by array row elements concatenation:
           output = left(output, Len(output) - 1)
           out.WriteLine (output): output = ""'make the output string null after writing it in the text file.
        Next k
    out.Close
End Sub

It can be a little simpler for only two columns, but it is designed to work for how many columns you need...


问:
Why is my docker machine not working under OSX?
I've installed Docker Toolbox v1.8.1b on OSX 10.10.5

This also installs VirtualBox v5.0.2

However, when the installation has finished and I run the Docker Quickstart Terminal, it does its thing, creates a new VM in virtualbox but then doesn't start it, finishing with the message that default is not running.

When I try to run the machine using docker-machine start default I get the message exit status 1.

When I go to VirtualBox and attempt to start the machine there, I get the following error message:

```<code>Failed to load VMMR0.r0 (VERR_VMM_SMAP_BUT_AC_CLEAR).

Result Code:
NS_ERROR_FAILURE (0x80004005)
Component:
ConsoleWrap
Interface:
IConsole {872da645-4a9b-1727-bee2-5585105b9eed}
</code>```

So is anyone else getting this or am I not following the instructions properly?

答:
Just wanted to add: if you have docker for mac installed, they intentionally removed the docker-machine command starting from version 2.2.0.

You can find the discussion here: https://github.com/docker/for-mac/issues/4208

So, you need to install docker-machine separately, using the commands provided by @shivanikoko or using brew:

```<code>brew install docker-machine
</code>```

Body:
I've installed Docker Toolbox v1.8.1b on OSX 10.10.5

This also installs VirtualBox v5.0.2

However, when the installation has finished and I run the Docker Quickstart Terminal, it does its thing, creates a new VM in virtualbox but then doesn't start it, finishing with the message that default is not running.

When I try to run the machine using docker-machine start default I get the message exit status 1.

When I go to VirtualBox and attempt to start the machine there, I get the following error message:

Failed to load VMMR0.r0 (VERR_VMM_SMAP_BUT_AC_CLEAR).

Result Code:
NS_ERROR_FAILURE (0x80004005)
Component:
ConsoleWrap
Interface:
IConsole {872da645-4a9b-1727-bee2-5585105b9eed}

So is anyone else getting this or am I not following the instructions properly?

Body:
Just wanted to add: if you have docker for mac installed, they intentionally removed the docker-machine command starting from version 2.2.0.

You can find the discussion here: https://github.com/docker/for-mac/issues/4208

So, you need to install docker-machine separately, using the commands provided by @shivanikoko or using brew:

brew install docker-machine


问:
"Error during WebSocket handshake: Unexpected response code: 400" while recording application using JMeter
I am trying to record a web application using Jmeter. I am able to record the launch of home page but facing error while logging in. I can see this error in the Network tab of chrome Dev Tools.

```<code>Error during WebSocket handshake: Unexpected response code: 400
</code>```

```<code>main.js?v=1579205232764:2 WebSocket connection to 'wss://<server-ip>/study-search?authorization=<token-value>' failed: Error during WebSocket handshake: Unexpected response code: 400
</code>```

Can someone please help me out?

Thanks!

答:
As of current JMeter version 5.2.1  JMeter cannot either capture or properly proxy the WebSocket traffic so I would recommend splitting the recording in 2 parts:

Before the login (including the login)

After the login (to wit: login without proxy, then turn on proxy, then continue recording)

In any case all the WebSocket calls needs to be captured separately using a 3rd-party sniffer tool like Fiddler or Wireshark and then properly simulated using JMeter WebSocket Samplers plugin

Body:
I am trying to record a web application using Jmeter. I am able to record the launch of home page but facing error while logging in. I can see this error in the Network tab of chrome Dev Tools.

Error during WebSocket handshake: Unexpected response code: 400

main.js?v=1579205232764:2 WebSocket connection to 'wss://<server-ip>/study-search?authorization=<token-value>' failed: Error during WebSocket handshake: Unexpected response code: 400

Can someone please help me out?

Thanks!


问:
need to open home activity on back pressed android
I have a activity stack in normal case is  A -> B -> C and when i received a push notification and have implemented click_action it opens Activity C which is correct.

Now, what is need is when activity C opens from push notification after pressing back button it gets closed and whole application goes in background, but i need to navigate to Home screen (Activity A)

```<code><activity
    android:name="Activity_A"
    android:exported="false"
    android:screenOrientation="sensorPortrait"
    android:theme="@style/MyAppTheme"
    android:windowSoftInputMode="stateHidden|adjustResize" />
<activity
    android:name="Activity_B"
    android:exported="false"
    android:screenOrientation="sensorPortrait"
    android:theme="@style/MyAppTheme"
    android:windowSoftInputMode="stateHidden|adjustResize" />
<activity
    android:name="Activity_C"
    android:exported="false"
    android:screenOrientation="sensorPortrait"
    android:theme="@style/MyAppTheme"
    android:windowSoftInputMode="adjustPan">
    <intent-filter>
        <action android:name="Activity_C" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>
</code>```

答:
When you create the Notification, add both FLAG_ACTIVTY_NEW_TASK and FLAG_ACTIVTY_CLEAR_TASK to the Intent before creating the PendingIntent and the Notification.

This will cause ActivityC to be started in a new task, clearing out any previous activities that might have been there. Upon BACK press in ActivityC, the app will have no active activities, which will retun the user to the HOME screen. Starting the app again will begin with ActivityA.

This will have no effect on the normal progression of activities from A->B->C.

Body:
I have a activity stack in normal case is  A -> B -> C and when i received a push notification and have implemented click_action it opens Activity C which is correct.

Now, what is need is when activity C opens from push notification after pressing back button it gets closed and whole application goes in background, but i need to navigate to Home screen (Activity A)

<activity
    android:name="Activity_A"
    android:exported="false"
    android:screenOrientation="sensorPortrait"
    android:theme="@style/MyAppTheme"
    android:windowSoftInputMode="stateHidden|adjustResize" />
<activity
    android:name="Activity_B"
    android:exported="false"
    android:screenOrientation="sensorPortrait"
    android:theme="@style/MyAppTheme"
    android:windowSoftInputMode="stateHidden|adjustResize" />
<activity
    android:name="Activity_C"
    android:exported="false"
    android:screenOrientation="sensorPortrait"
    android:theme="@style/MyAppTheme"
    android:windowSoftInputMode="adjustPan">
    <intent-filter>
        <action android:name="Activity_C" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>


问:
Exchange Powershell Loop Distribution List
I have this Powershell-Script that Gets-DistributionGroupMembers and or Update the member's policy.

$DL = Get-DistributionGroupMember "Distribution List GroupName"
ForEach ($Member in $DL) { Set-CASMailbox -Identity $Member.Name -OwaMailboxPolicy "Allow Download Access" }
```

The above code is working okay.

My question is:

how do you check if $Member.Name is an individual account or a group

and IF  its a group, Then how do you call the same Action Script recursively.

Thank you in advance.

答:
Untested, but I think you can determine if the member is a group or not by checking the RecipientTypeDetails property.

Something like:

```<code>function Set-DistributionGroupPolicy([string] $group) {
    Get-DistributionGroupMember $group -ResultSize Unlimited | ForEach-Object {
        if ($_.RecipientTypeDetails -match "Group") {
            Write-Verbose "Recursing on group '$($_.Name)'"
            Set-DistributionGroupPolicy $_.Name
        }
        Set-CASMailbox -Identity $_.Name -OwaMailboxPolicy "Allow Download Access"
    }
}

Set-DistributionGroupPolicy
</code>```

Body:
I have this Powershell-Script that Gets-DistributionGroupMembers and or Update the member's policy.

$DL = Get-DistributionGroupMember "Distribution List GroupName"
ForEach ($Member in $DL) { Set-CASMailbox -Identity $Member.Name -OwaMailboxPolicy "Allow Download Access" }

The above code is working okay.

My question is:

how do you check if $Member.Name is an individual account or a group

and IF  its a group, Then how do you call the same Action Script recursively.

Thank you in advance.

Body:
Untested, but I think you can determine if the member is a group or not by checking the RecipientTypeDetails property.

Something like:

function Set-DistributionGroupPolicy([string] $group) {
    Get-DistributionGroupMember $group -ResultSize Unlimited | ForEach-Object {
        if ($_.RecipientTypeDetails -match "Group") {
            Write-Verbose "Recursing on group '$($_.Name)'"
            Set-DistributionGroupPolicy $_.Name
        }
        Set-CASMailbox -Identity $_.Name -OwaMailboxPolicy "Allow Download Access"
    }
}

Set-DistributionGroupPolicy


问:
How to parse JSON data and print on terminal in flutter?
This is my Json data :

```<code>     {
   "result":"0",
   "school_name":"Global Academy International",
   "school_code":"GAIS",
   "dashboard":"{\"privilege\":[{\"activity_id\":159,\"privilege_desc\":\"V4_MYPROFILE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1185},{\"activity_id\":159,\"privilege_desc\":\"V4_MYTIMETABLE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1186},{\"activity_id\":159,\"privilege_desc\":\"V4_MYATTENDANCE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1188},{\"activity_id\":159,\"privilege_desc\":\"V4_MYLEAVESTATUS\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1189},{\"activity_id\":159,\"privilege_desc\":\"V4_MEMO\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1193},{\"activity_id\":161,\"privilege_desc\":\"V4_SUBJECTWISE\",\"activity_desc\":\"V4_STUDENT_ATTENDANCE\",\"privilege_id\":1198},{\"activity_id\":161,\"privilege_desc\":\"V4_SUBJECTWISELATE\",\"activity_desc\":\"V4_STUDENT_ATTENDANCE\",\"privilege_id\":1201},{\"activity_id\":162,\"privilege_desc\":\"V4_LEAVE_REQUISITION\",\"activity_desc\":\"V4_TEACHER_LEAVE\",\"privilege_id\":1203},{\"activity_id\":164,\"privilege_desc\":\"V4_ASSIGNMENT\",\"activity_desc\":\"V4_STUDENT_ASSIGNMENT\",\"privilege_id\":1206},{\"activity_id\":166,\"privilege_desc\":\"V4_SCHOOL_CALENDAR\",\"activity_desc\":\"V4_CALENDAR\",\"privilege_id\":1208},{\"activity_id\":168,\"privilege_desc\":\"V4_LOGOUT\",\"activity_desc\":\"V4_LOGOUT\",\"privilege_id\":1210}],\"resultPrivilege\":\"0\",\"resultProfile\":\"0\",\"profile\":{\"empid\":\"EMP183\",\"name\":\"BACHIR Raji Kashkash\",\"designation\":\"TEACHER\",\"photo_path\":\"/container/school_data/GAIS/photo/Staff/EMP183.jpg\",\"department_name\":\"HIGH SCHOOL - T\"}}",
   "employee_id":"EMP183",
   "school_url":"http://ict.gaiqatar.com"
}
</code>```

I want to print only  this data from jSON data:

```<code>[{\"activity_id\":159,\"privilege_desc\":\"V4_MYPROFILE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1185},{\"activity_id\":159,\"privilege_desc\":\"V4_MYTIMETABLE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1186},{\"activity_id\":168,\"privilege_desc\":\"V4_LOGOUT\",\"activity_desc\":\"V4_LOGOUT\",\"privilege_id\":1210}]
</code>```

How to get this data from whole jSON data ?

答:
Import the following package:

```<code>import 'dart:convert';
</code>```

Decode the json result returned and access the specific field you want:

```<code>final body = json.decode(response.dashboard);
print(body['privilege']);
</code>```

Basically after parsing your initial json you need to parse the nested field as well (privileges) since it's not a valid json object. Usually I would do this from the server and send a proper json response to the client (flutter).

If this can't be done then you just have to parse the json response, walk through it and parse and nested fields as well.

Edit:

Noticed your json wasn't formatted properly this is an example code. You can run this in dartpad

```<code>import 'dart:convert';

void main() {
  final jsonString =  '{\"privilege\":[{\"activity_id\":159,\"privilege_desc\":\"V4_MYPROFILE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1185},{\"activity_id\":159,\"privilege_desc\":\"V4_MYTIMETABLE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1186},{\"activity_id\":168,\"privilege_desc\":\"V4_LOGOUT\",\"activity_desc\":\"V4_LOGOUT\",\"privilege_id\":1210}],\"resultPrivilege\":\"0\",\"resultProfile\":\"0\"}';

  final parsedJson = json.decode(jsonString);
  final privilege = parsedJson['privilege'];
  print(privilege);
}
</code>```

Body:
This is my Json data :

     {
   "result":"0",
   "school_name":"Global Academy International",
   "school_code":"GAIS",
   "dashboard":"{\"privilege\":[{\"activity_id\":159,\"privilege_desc\":\"V4_MYPROFILE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1185},{\"activity_id\":159,\"privilege_desc\":\"V4_MYTIMETABLE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1186},{\"activity_id\":159,\"privilege_desc\":\"V4_MYATTENDANCE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1188},{\"activity_id\":159,\"privilege_desc\":\"V4_MYLEAVESTATUS\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1189},{\"activity_id\":159,\"privilege_desc\":\"V4_MEMO\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1193},{\"activity_id\":161,\"privilege_desc\":\"V4_SUBJECTWISE\",\"activity_desc\":\"V4_STUDENT_ATTENDANCE\",\"privilege_id\":1198},{\"activity_id\":161,\"privilege_desc\":\"V4_SUBJECTWISELATE\",\"activity_desc\":\"V4_STUDENT_ATTENDANCE\",\"privilege_id\":1201},{\"activity_id\":162,\"privilege_desc\":\"V4_LEAVE_REQUISITION\",\"activity_desc\":\"V4_TEACHER_LEAVE\",\"privilege_id\":1203},{\"activity_id\":164,\"privilege_desc\":\"V4_ASSIGNMENT\",\"activity_desc\":\"V4_STUDENT_ASSIGNMENT\",\"privilege_id\":1206},{\"activity_id\":166,\"privilege_desc\":\"V4_SCHOOL_CALENDAR\",\"activity_desc\":\"V4_CALENDAR\",\"privilege_id\":1208},{\"activity_id\":168,\"privilege_desc\":\"V4_LOGOUT\",\"activity_desc\":\"V4_LOGOUT\",\"privilege_id\":1210}],\"resultPrivilege\":\"0\",\"resultProfile\":\"0\",\"profile\":{\"empid\":\"EMP183\",\"name\":\"BACHIR Raji Kashkash\",\"designation\":\"TEACHER\",\"photo_path\":\"/container/school_data/GAIS/photo/Staff/EMP183.jpg\",\"department_name\":\"HIGH SCHOOL - T\"}}",
   "employee_id":"EMP183",
   "school_url":"http://ict.gaiqatar.com"
}

I want to print only  this data from jSON data:

[{\"activity_id\":159,\"privilege_desc\":\"V4_MYPROFILE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1185},{\"activity_id\":159,\"privilege_desc\":\"V4_MYTIMETABLE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1186},{\"activity_id\":168,\"privilege_desc\":\"V4_LOGOUT\",\"activity_desc\":\"V4_LOGOUT\",\"privilege_id\":1210}]

How to get this data from whole jSON data ?

Body:
Import the following package:

import 'dart:convert';

Decode the json result returned and access the specific field you want:

final body = json.decode(response.dashboard);
print(body['privilege']);

Basically after parsing your initial json you need to parse the nested field as well (privileges) since it's not a valid json object. Usually I would do this from the server and send a proper json response to the client (flutter).

If this can't be done then you just have to parse the json response, walk through it and parse and nested fields as well.

Edit:

Noticed your json wasn't formatted properly this is an example code. You can run this in dartpad

import 'dart:convert';

void main() {
  final jsonString =  '{\"privilege\":[{\"activity_id\":159,\"privilege_desc\":\"V4_MYPROFILE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1185},{\"activity_id\":159,\"privilege_desc\":\"V4_MYTIMETABLE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1186},{\"activity_id\":168,\"privilege_desc\":\"V4_LOGOUT\",\"activity_desc\":\"V4_LOGOUT\",\"privilege_id\":1210}],\"resultPrivilege\":\"0\",\"resultProfile\":\"0\"}';

  final parsedJson = json.decode(jsonString);
  final privilege = parsedJson['privilege'];
  print(privilege);
}


问:
Disable mousewheel with preventDefault but can not enable it?
I have 2 button to enable/disable mousewheel as below. I have disabled it, but I can not re-enable

function disableScroll() {
  document.addEventListener("mousewheel", function(event) {
    event.preventDefault();
  }, {
    passive: false
  });
}

function enableScroll() {
  document.removeEventListener("mousewheel", function(event) {
    event.preventDefault();
  }, {
    passive: false
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="disableScroll()">Disable</button>
<button onclick="enableScroll()">Enale</button></code>```

答:
The issue with your current logic is because the event handler you add and the event handler you remove are not the same reference. To address this put the event handler in its own named function and reference it.

let disabledScrollHandler = (e) => {
  e.preventDefault();
}

document.querySelector('#disable').addEventListener('click', () =>
  document.addEventListener('mousewheel', disabledScrollHandler, { passive: false }));

document.querySelector('#enable').addEventListener('click', () =>
  document.removeEventListener('mousewheel', disabledScrollHandler, { passive: false }));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
  height: 1000px;
}</code>```

<button id="disable">Disable</button>
<button id="enable">Enable</button>```
</div>
</div>
</p>

<p>That said, you can achieve this without nested and dynamic event handlers by adding a class to the <code>body</code>. This <code>class</code> sets the <code>overflow</code> state of the element which in turn prevents the scroll behaviour. Try this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>document.querySelector('#disable').addEventListener('click', function() {
  document.body.classList.add('disable-scroll');
});

document.querySelector('#enable').addEventListener('click', function() {
  document.body.classList.remove('disable-scroll');
});</code>```

html, body { height: 1000px; }
body.disable-scroll { overflow: hidden; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="disable">Disable</button>
<button id="enable">Enable</button></code>```

Note that the latter approach also prevents scrolling via the keyboard, if that's a requirement.

Body:
I have 2 button to enable/disable mousewheel as below. I have disabled it, but I can not re-enable

function disableScroll() {
  document.addEventListener("mousewheel", function(event) {
    event.preventDefault();
  }, {
    passive: false
  });
}

function enableScroll() {
  document.removeEventListener("mousewheel", function(event) {
    event.preventDefault();
  }, {
    passive: false
  });
}

<button onclick="disableScroll()">Disable</button>
<button onclick="enableScroll()">Enale</button>

Body:
The issue with your current logic is because the event handler you add and the event handler you remove are not the same reference. To address this put the event handler in its own named function and reference it.

let disabledScrollHandler = (e) => {
  e.preventDefault();
}

document.querySelector('#disable').addEventListener('click', () =>
  document.addEventListener('mousewheel', disabledScrollHandler, { passive: false }));

document.querySelector('#enable').addEventListener('click', () =>
  document.removeEventListener('mousewheel', disabledScrollHandler, { passive: false }));

html,
body {
  height: 1000px;
}

<button id="disable">Disable</button>
<button id="enable">Enable</button>

That said, you can achieve this without nested and dynamic event handlers by adding a class to the body. This class sets the overflow state of the element which in turn prevents the scroll behaviour. Try this:

document.querySelector('#disable').addEventListener('click', function() {
  document.body.classList.add('disable-scroll');
});

document.querySelector('#enable').addEventListener('click', function() {
  document.body.classList.remove('disable-scroll');
});

html, body { height: 1000px; }
body.disable-scroll { overflow: hidden; }

<button id="disable">Disable</button>
<button id="enable">Enable</button>

Note that the latter approach also prevents scrolling via the keyboard, if that's a requirement.


问:
Input of length greater than 255 in postgresql rails
I have a field with datatype string in the rails Postgresql table. What happens when I enter value more than 255. Does the Postgresql cut the string to 255 characters or does it prohibits from entering?</p>

答:
Postgres will throw an error if you try to write a value longer than the field's limit: https://www.postgresql.org/docs/9.1/datatype-character.html

Here's something you can do (with a migration) if you need bigger limits and want to control it instead of using text type:

change_column :table, :column, :string, limit: 510


问:
SQL Tally up value based on the day of the week
Here is what my table looks like

```<code>ID | Date
------------
13  2013-03-21 00:00:00
13  2013-03-23 00:00:00
13  2013-03-24 00:00:00
25  2013-03-21 00:00:00
25  2013-03-22 00:00:00
25  2013-03-21 00:00:00
25  2013-03-23 00:00:00
25  2013-03-28 00:00:00
25  2013-03-21 00:00:00
82  2013-03-22 00:00:00
82  2013-03-22 00:00:00
I want it to output (combine sat & sun into 'weekend'). It'll combine all the Mondays, Tuesdays, Wednesdays, etc. and combine the values.

day | total
--------------
Friday  2
Thursday 3
Weekend 3
</code>```

This is my query so far

```<code>SELECT
  CASE
    WHEN DATENAME(weekday, [date]) = 'Saturday' OR DATENAME(weekday, [date]) = 'Sunday' THEN 'Weekend'
    ELSE DATENAME(weekday, [date])
  END AS Day,
  COUNT(DISTINCT [id]) AS score

  FROM [table]

GROUP BY
  CASE
    WHEN DATENAME(weekday, [date]) = 'Saturday' OR DATENAME(weekday, [date]) = 'Sunday' THEN 'Weekend'
    ELSE DATENAME(weekday, [date])
  END
</code>```

Currently I can get my query to output this, but it seems like it isn't adding both thursdays or sat + sun.

```<code>Day | total
--------------
Friday 2
Thursday 2
Weekend 2
</code>```

答:
Try this!

```<code> select count(id)as Total,Day from
 (
 select id, case when Datename(weekday,dt1) IN('Saturday','Sunday') then 'Weekend' else Datename(weekday,dt1) end as 'Day' from tab
 )x

 group by Day
</code>```

Demo here

Body:
Here is what my table looks like

ID | Date
------------
13  2013-03-21 00:00:00
13  2013-03-23 00:00:00
13  2013-03-24 00:00:00
25  2013-03-21 00:00:00
25  2013-03-22 00:00:00
25  2013-03-21 00:00:00
25  2013-03-23 00:00:00
25  2013-03-28 00:00:00
25  2013-03-21 00:00:00
82  2013-03-22 00:00:00
82  2013-03-22 00:00:00
I want it to output (combine sat & sun into 'weekend'). It'll combine all the Mondays, Tuesdays, Wednesdays, etc. and combine the values.

day | total
--------------
Friday  2
Thursday 3
Weekend 3

This is my query so far

SELECT
  CASE
    WHEN DATENAME(weekday, [date]) = 'Saturday' OR DATENAME(weekday, [date]) = 'Sunday' THEN 'Weekend'
    ELSE DATENAME(weekday, [date])
  END AS Day,
  COUNT(DISTINCT [id]) AS score

  FROM [table]

GROUP BY
  CASE
    WHEN DATENAME(weekday, [date]) = 'Saturday' OR DATENAME(weekday, [date]) = 'Sunday' THEN 'Weekend'
    ELSE DATENAME(weekday, [date])
  END

Currently I can get my query to output this, but it seems like it isn't adding both thursdays or sat + sun.

Day | total
--------------
Friday 2
Thursday 2
Weekend 2

Body:
Try this!

 select count(id)as Total,Day from
 (
 select id, case when Datename(weekday,dt1) IN('Saturday','Sunday') then 'Weekend' else Datename(weekday,dt1) end as 'Day' from tab
 )x

 group by Day

Demo here


问:
ERROR: @angular/material/material has no exported member 'MdButtonModule'
Error below arose after upgrading from @angular/material 2.0.0-beta.11 to 2.0.0-beta.12:

Module @angular/material/material has no exported member 'MdButtonModule'.

Typescript-code:

import { MdButtonModule } from '@angular/material';
```

What happened?

ERROR in c:/dev/my-proj/src/app/app-material/app-material.module.ts
  (4,3): Module
  '"c:/dev/my-proj/node_modules/@angular/material/material"' has no
  exported member 'MdButtonModule'. ERROR in
  c:/dev/my-proj/src/app/app-material/app-material.module.ts (5,3):
  Module '"c:/dev/my-proj/node_modules/@angular/material/material"' has
  no exported member 'MdCardModule'. ERROR in
  c:/dev/my-proj/src/app/app-material/app-material.module.ts (6,3):
  Module '"c:/dev/my-proj/node_modules/@angular/material/material"' has
  no exported member 'MdCheckboxModule'. ERROR in
  c:/dev/my-proj/src/app/app-material/app-material.module.ts (7,3):
  Module '"c:/dev/my-proj/node_modules/@angular/material/material"' has
  no exported member 'MdIconModule'. ERROR in
  c:/dev/my-proj/src/app/app-material/app-material.module.ts (8,3):
  Module '"c:/dev/my-proj/node_modules/@angular/material/material"' has
  no exported member 'MdOptionModule'. ERROR in
  c:/dev/my-proj/src/app/app-material/app-material.module.ts (9,3):
  Module '"c:/dev/my-proj/node_modules/@angular/material/material"' has
  no exported member 'MdProgressSpinnerModule'. ERROR in
  c:/dev/my-proj/src/app/app-material/app-material.module.ts (10,3):
  Module '"c:/dev/my-proj/node_modules/@angular/material/material"' has
  no exported member 'MdSelectModule'. ERROR in
  c:/dev/my-proj/src/app/app-material/app-material.module.ts (11,3):
  Module '"c:/dev/my-proj/node_modules/@angular/material/material"' has
  no exported member 'MdSidenavModule'. ERROR in
  c:/dev/my-proj/src/app/app-material/app-material.module.ts (12,3):
  Module '"c:/dev/my-proj/node_modules/@angular/material/material"' has
  no exported member 'MdToolbarModule'. ERROR in Error: MdButtonModule
  is not an NgModule
      at _getNgModuleMetadata (c:\dev\my-proj\node_modules\@angular\compiler-cli\src\ngtools_impl.js:140:15)
      at _extractLazyRoutesFromStaticModule (c:\dev\my-proj\node_modules\@angular\compiler-cli\src\ngtools_impl.js:109:26)
      at c:\dev\my-proj\node_modules\@angular\compiler-cli\src\ngtools_impl.js:129:27
      at Array.reduce (native)
      at _extractLazyRoutesFromStaticModule (c:\dev\my-proj\node_modules\@angular\compiler-cli\src\ngtools_impl.js:128:10)
      at c:\dev\my-proj\node_modules\@angular\compiler-cli\src\ngtools_impl.js:129:27
      at Array.reduce (native)
      at _extractLazyRoutesFromStaticModule (c:\dev\my-proj\node_modules\@angular\compiler-cli\src\ngtools_impl.js:128:10)
      at Object.listLazyRoutesOfModule (c:\dev\my-proj\node_modules\@angular\compiler-cli\src\ngtools_impl.js:53:22)
      at Function.NgTools_InternalApi_NG_2.listLazyRoutes (c:\dev\my-proj\node_modules\@angular\compiler-cli\src\ngtools_api.js:91:39)
      at AotPlugin._getLazyRoutesFromNgtools (c:\dev\my-proj\node_modules\@ngtools\webpack\src\plugin.js:207:44)
      at _donePromise.Promise.resolve.then.then.then.then.then (c:\dev\my-proj\node_modules\@ngtools\webpack\src\plugin.js:443:24)

答:
Works for me,I put the following line, maybe it can be useful for you.

reference link @angular/material/index.d.ts' is not a module

```<code>import { MatButtonModule } from '@angular/material/button';
</code>```

Body:
Error below arose after upgrading from @angular/material 2.0.0-beta.11 to 2.0.0-beta.12:

Module @angular/material/material has no exported member 'MdButtonModule'.

Typescript-code:

import { MdButtonModule } from '@angular/material';

What happened?

ERROR in c:/dev/my-proj/src/app/app-material/app-material.module.ts
  (4,3): Module
  '"c:/dev/my-proj/node_modules/@angular/material/material"' has no
  exported member 'MdButtonModule'. ERROR in
  c:/dev/my-proj/src/app/app-material/app-material.module.ts (5,3):
  Module '"c:/dev/my-proj/node_modules/@angular/material/material"' has
  no exported member 'MdCardModule'. ERROR in
  c:/dev/my-proj/src/app/app-material/app-material.module.ts (6,3):
  Module '"c:/dev/my-proj/node_modules/@angular/material/material"' has
  no exported member 'MdCheckboxModule'. ERROR in
  c:/dev/my-proj/src/app/app-material/app-material.module.ts (7,3):
  Module '"c:/dev/my-proj/node_modules/@angular/material/material"' has
  no exported member 'MdIconModule'. ERROR in
  c:/dev/my-proj/src/app/app-material/app-material.module.ts (8,3):
  Module '"c:/dev/my-proj/node_modules/@angular/material/material"' has
  no exported member 'MdOptionModule'. ERROR in
  c:/dev/my-proj/src/app/app-material/app-material.module.ts (9,3):
  Module '"c:/dev/my-proj/node_modules/@angular/material/material"' has
  no exported member 'MdProgressSpinnerModule'. ERROR in
  c:/dev/my-proj/src/app/app-material/app-material.module.ts (10,3):
  Module '"c:/dev/my-proj/node_modules/@angular/material/material"' has
  no exported member 'MdSelectModule'. ERROR in
  c:/dev/my-proj/src/app/app-material/app-material.module.ts (11,3):
  Module '"c:/dev/my-proj/node_modules/@angular/material/material"' has
  no exported member 'MdSidenavModule'. ERROR in
  c:/dev/my-proj/src/app/app-material/app-material.module.ts (12,3):
  Module '"c:/dev/my-proj/node_modules/@angular/material/material"' has
  no exported member 'MdToolbarModule'. ERROR in Error: MdButtonModule
  is not an NgModule
      at _getNgModuleMetadata (c:\dev\my-proj\node_modules\@angular\compiler-cli\src\ngtools_impl.js:140:15)
      at _extractLazyRoutesFromStaticModule (c:\dev\my-proj\node_modules\@angular\compiler-cli\src\ngtools_impl.js:109:26)
      at c:\dev\my-proj\node_modules\@angular\compiler-cli\src\ngtools_impl.js:129:27
      at Array.reduce (native)
      at _extractLazyRoutesFromStaticModule (c:\dev\my-proj\node_modules\@angular\compiler-cli\src\ngtools_impl.js:128:10)
      at c:\dev\my-proj\node_modules\@angular\compiler-cli\src\ngtools_impl.js:129:27
      at Array.reduce (native)
      at _extractLazyRoutesFromStaticModule (c:\dev\my-proj\node_modules\@angular\compiler-cli\src\ngtools_impl.js:128:10)
      at Object.listLazyRoutesOfModule (c:\dev\my-proj\node_modules\@angular\compiler-cli\src\ngtools_impl.js:53:22)
      at Function.NgTools_InternalApi_NG_2.listLazyRoutes (c:\dev\my-proj\node_modules\@angular\compiler-cli\src\ngtools_api.js:91:39)
      at AotPlugin._getLazyRoutesFromNgtools (c:\dev\my-proj\node_modules\@ngtools\webpack\src\plugin.js:207:44)
      at _donePromise.Promise.resolve.then.then.then.then.then (c:\dev\my-proj\node_modules\@ngtools\webpack\src\plugin.js:443:24)

Body:
Works for me,I put the following line, maybe it can be useful for you.

reference link @angular/material/index.d.ts' is not a module

import { MatButtonModule } from '@angular/material/button';


问:
Using a generic type of any nested subclass within its abstract superclass
Suppose you have the following abstract java class:

```<code>public abstract class AbstractRequestHandler<I,O> {
    I input;
    O output;
}
</code>```

and the following child classes hierarchy:

```<code>public abstract class AbstractUserRequestHandler<I extends User,O> extends AbstractRequestHandler<I,O>{...}
public abstract class AbstractUniversityRequestHandler<I extends UniversityUser> extends AbstractUserRequestHandler<I,String>{...}
public class StudentRequestHandler extends AbstractUniversityRequestHandler<Student>{...}
public class TeacherRequestHandler extends AbstractUniversityRequestHandler<Teacher>{...}
</code>```

Suppose you need to use at a given point on the super class the generic type, for example in order to deserialize on the constructor the request json to the specific request object using gson library as follow:

```<code>public AbstractRequestHandler(final String inputJson) {
        input = new Gson().fromJson(inputJson,typeOfI);
}
</code>```

You need the type of generic I within variable "typeOfI"

Is there a global solution that allows to get the generic type specified by a concrete child class that respects the following constraints?

The type is gotten at runtime regardless the child classes hierarchy ( that can be also more complex the one given as example on this question )

The developer just needs to define the generic extending the super class without manually specify the generic type somewhere on concrete child class ( for example on overrided method or constructor )

So that if you want to define a new concrete child that assign a new value to a generic you can just write the following concrete class for example:

```<code>public class StudentRequestHandler extends AbstractUniversityRequestHandler<Student>{

    public StudentRequestHandler(String inputJson) {
        super(inputJson);
    }

}
</code>```

I found the following solutions but they don't respect both the asked solution constraints.

Solution that breaks constraint n°2

A solution could be to define an abstract method on the superclass as follow

```<code>protected abstract Type getRequestType();
</code>```

and then implement it on every concrete child class that defines the generic:

```<code>public class StudentRequestHandler extends AbstractUniversityRequestHandler<Student>{

    public StudentRequestHandler(String inputJson) {
        super(inputJson);
    }

    @Override
    protected Type getRequestType() {
        return Student.class;
    }
}
</code>```

Then the getRequestType() method can be used on constructor on the target superclass:

```<code>public AbstractRequestHandler(final String inputJson) {
        request = new Gson().fromJson(inputJson,getRequestType());
}
</code>```

But even if it works regardless the child classes hierarchy ( respect constraint n°1 ) the developer should manually implement an abstract method on each concrete child class.

Solution that breaks constraint n°1

If the hierarchy is simple having only a direct child that extend from the target superclass, as for example:

```<code>public class TeacherRequestHandler extends AbstractRequestHandler<Teacher,String>{...}
</code>```

a working solution has been proposed by @naikus ( https://stackoverflow.com/users/306602/naikus ) on the following stackoverflow thread:
Using a generic type of a subclass within it's abstract superclass?

However this doesn't work if the concrete class is not a direct child of the superclass that defines the generics ( as the one proposed as example on this question ).

答:
I think a working solution would be to extend the one proposed by @naikus. It only needs to go up in the hierarchy on the constructor.</p>

```<code>import java.lang.reflect.ParameterizedType;

public abstract class AbstractRequestHandler<I,O> {

    protected I input;
    protected O output;

    protected Class<I> inputClass;
    protected Class<O> outputClass;

    protected AbstractRequestHandler() {
        Class<?> clazz = getClass();
        while (!clazz.getSuperclass().equals(AbstractRequestHandler.class)) {
            clazz = clazz.getSuperclass();
        }
        ParameterizedType genericSuperclass = (ParameterizedType) clazz.getGenericSuperclass();
        this.inputClass = (Class<I>) genericSuperclass.getActualTypeArguments()[0];
        this.outputClass = (Class<O>) genericSuperclass.getActualTypeArguments()[1];
    }
}
</code>```

Body:
Suppose you have the following abstract java class:

public abstract class AbstractRequestHandler {
    I input;
    O output;
}

and the following child classes hierarchy:

public abstract class AbstractUserRequestHandler extends AbstractRequestHandler{...}
public abstract class AbstractUniversityRequestHandler extends AbstractUserRequestHandler{...}
public class StudentRequestHandler extends AbstractUniversityRequestHandler<Student>{...}
public class TeacherRequestHandler extends AbstractUniversityRequestHandler<Teacher>{...}

Suppose you need to use at a given point on the super class the generic type, for example in order to deserialize on the constructor the request json to the specific request object using gson library as follow:

public AbstractRequestHandler(final String inputJson) {
        input = new Gson().fromJson(inputJson,typeOfI);
}

You need the type of generic I within variable "typeOfI"

Is there a global solution that allows to get the generic type specified by a concrete child class that respects the following constraints?

The type is gotten at runtime regardless the child classes hierarchy ( that can be also more complex the one given as example on this question )

The developer just needs to define the generic extending the super class without manually specify the generic type somewhere on concrete child class ( for example on overrided method or constructor )

So that if you want to define a new concrete child that assign a new value to a generic you can just write the following concrete class for example:

public class StudentRequestHandler extends AbstractUniversityRequestHandler<Student>{

    public StudentRequestHandler(String inputJson) {
        super(inputJson);
    }

}

I found the following solutions but they don't respect both the asked solution constraints.

Solution that breaks constraint n°2

A solution could be to define an abstract method on the superclass as follow

protected abstract Type getRequestType();

and then implement it on every concrete child class that defines the generic:

public class StudentRequestHandler extends AbstractUniversityRequestHandler<Student>{

    public StudentRequestHandler(String inputJson) {
        super(inputJson);
    }

    @Override
    protected Type getRequestType() {
        return Student.class;
    }
}

Then the getRequestType() method can be used on constructor on the target superclass:

public AbstractRequestHandler(final String inputJson) {
        request = new Gson().fromJson(inputJson,getRequestType());
}

But even if it works regardless the child classes hierarchy ( respect constraint n°1 ) the developer should manually implement an abstract method on each concrete child class.

Solution that breaks constraint n°1

If the hierarchy is simple having only a direct child that extend from the target superclass, as for example:

public class TeacherRequestHandler extends AbstractRequestHandler<Teacher,String>{...}

a working solution has been proposed by @naikus ( https://stackoverflow.com/users/306602/naikus ) on the following stackoverflow thread:
Using a generic type of a subclass within it's abstract superclass?

However this doesn't work if the concrete class is not a direct child of the superclass that defines the generics ( as the one proposed as example on this question ).

Body:
I think a working solution would be to extend the one proposed by @naikus. It only needs to go up in the hierarchy on the constructor.

import java.lang.reflect.ParameterizedType;

public abstract class AbstractRequestHandler<I,O> {

    protected I input;
    protected O output;

    protected Class<I> inputClass;
    protected Class<O> outputClass;

    protected AbstractRequestHandler() {
        Class<?> clazz = getClass();
        while (!clazz.getSuperclass().equals(AbstractRequestHandler.class)) {
            clazz = clazz.getSuperclass();
        }
        ParameterizedType genericSuperclass = (ParameterizedType) clazz.getGenericSuperclass();
        this.inputClass = (Class<I>) genericSuperclass.getActualTypeArguments()[0];
        this.outputClass = (Class<O>) genericSuperclass.getActualTypeArguments()[1];
    }
}


问:
recyclerview inside nested scroll view is not scolling
I have a recyclerview inside a nestedScrollView and I have stopped the scrolling of recyclerview to allow nestedScrollView to scroll all the page, but the nestedScrollView is not working.

I have set the nestedScrollingEnabled of the recyclerview to false

I have tried to add a hidden view under the recyclerview but it has shown on top of the bottom items of recyclerview

My layout xml file code is:

```<code><?xml version="1.0" encoding="utf-8"?>

<layout xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:android="http://schemas.android.com/apk/res/android">

<data>
    <variable
        name="viewModel"
        type="com.accad.accadgame.viewmodels.profile.ProfileViewModel" />
</data>

<androidx.core.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true"
    >

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/circleImageView"
            android:layout_width="75dp"
            android:layout_height="0dp"
            android:layout_marginStart="@dimen/default_dim"
            android:layout_marginTop="@dimen/default_xxdim"
            android:layout_marginEnd="@dimen/default_dim"
            android:src="@drawable/profile"
            app:layout_constraintDimensionRatio="h,1:1"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/profile_name"
            style="@style/HeadlineTextViewActiveStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/default_dim"
            android:layout_marginStart="@dimen/default_dim"
            android:layout_marginEnd="@dimen/default_dim"
            android:text="@{viewModel.profileName}"
            app:layout_constraintEnd_toEndOf="@+id/circleImageView"
            app:layout_constraintStart_toStartOf="@+id/circleImageView"
            app:layout_constraintTop_toBottomOf="@+id/circleImageView"
            tools:text="@tools:sample/lorem" />

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/profile_details_list"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_marginTop="@dimen/default_xxdim"
            android:clipToPadding="false"
            android:paddingBottom="@dimen/default_dim"
            android:paddingStart="@dimen/default_dim"
            android:nestedScrollingEnabled="false"
            app:layout_constraintBottom_toBottomOf="parent"
            android:focusable="false"
            app:layout_constraintTop_toBottomOf="@id/profile_name"
            />

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.core.widget.NestedScrollView>
</code>```

答:
Put your static content as the first item in the RV.

I know this might sound bad but trust me, it's so much better than having a nested RecyclerView.

This will fix recycling, scrolling, dragging and so many other issues with nested RV.

Body:
I have a recyclerview inside a nestedScrollView and I have stopped the scrolling of recyclerview to allow nestedScrollView to scroll all the page, but the nestedScrollView is not working.

I have set the nestedScrollingEnabled of the recyclerview to false

I have tried to add a hidden view under the recyclerview but it has shown on top of the bottom items of recyclerview

My layout xml file code is:

<?xml version="1.0" encoding="utf-8"?>

<layout xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:android="http://schemas.android.com/apk/res/android">

<data>
    <variable
        name="viewModel"
        type="com.accad.accadgame.viewmodels.profile.ProfileViewModel" />
</data>

<androidx.core.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true"
    >

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/circleImageView"
            android:layout_width="75dp"
            android:layout_height="0dp"
            android:layout_marginStart="@dimen/default_dim"
            android:layout_marginTop="@dimen/default_xxdim"
            android:layout_marginEnd="@dimen/default_dim"
            android:src="@drawable/profile"
            app:layout_constraintDimensionRatio="h,1:1"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/profile_name"
            style="@style/HeadlineTextViewActiveStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/default_dim"
            android:layout_marginStart="@dimen/default_dim"
            android:layout_marginEnd="@dimen/default_dim"
            android:text="@{viewModel.profileName}"
            app:layout_constraintEnd_toEndOf="@+id/circleImageView"
            app:layout_constraintStart_toStartOf="@+id/circleImageView"
            app:layout_constraintTop_toBottomOf="@+id/circleImageView"
            tools:text="@tools:sample/lorem" />

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/profile_details_list"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_marginTop="@dimen/default_xxdim"
            android:clipToPadding="false"
            android:paddingBottom="@dimen/default_dim"
            android:paddingStart="@dimen/default_dim"
            android:nestedScrollingEnabled="false"
            app:layout_constraintBottom_toBottomOf="parent"
            android:focusable="false"
            app:layout_constraintTop_toBottomOf="@id/profile_name"
            />

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.core.widget.NestedScrollView>