问:
Stop Apps Script from creating GCP projects
I'm seeing a large number of GCP projects being created by serviceAccount:appsdev-apps-dev-script-auth@system.gserviceaccount.com, following invocation of Apps Scripts.
I'd like to control or block such project creation.

What are the right ways to accomplish that?

答:
That's not possible. Quoting GCP Projects's documentation:

By default GCP projects have an Identity and Access Management (IAM)
  policy with one entry, a Google service account that acts as the owner
  of the default project. The Google service account is
  appsdev-apps-dev-script-auth@system.gserviceaccount.com.

Also:

Every Apps Script project uses the Google Cloud Platform to manage
  authorization, Advanced services, and other details. To configure and
  manage these settings, every Apps Script project has an associated
  Google Cloud Platform project (a GCP project).

You can use a default GCP project or a standard project created by you, but the Apps Script project does need a GCP Project.

Moreover, since April 8, 2019 it's not possible to access the default GCP projects created for Apps Script projects unless they are older.


来源: stackexchange

问:
OUTER/CROSS APPLY Subquery without FROM clause
Most online documentation or tutorials discussing OUTER|CROSS APPLY describe something like:

```<code>SELECT columns
FROM table OUTER|CROSS APPLY (SELECT … FROM …);
</code>```

The subquery is normally a full SELECT … FROM … query.

I must have read somewhere that the subquery doesn’t need a FROM  in which case the columns appear to come from the main query:

```<code>SELECT columns
FROM table OUTER|CROSS APPLY (SELECT … );
</code>```

because I have used it routinely as a method to pre-calculate columns.

The question is what is really happening if the FROM is omitted from the sub query? Is it short for something else? I found that it does not mean the same as from the main table.

I have a sample here: http://sqlfiddle.com/#!18/0188f7/4/1

答:
Omitting the FROM statement is not specific to a CROSS/OUTER APPLY; any valid SQL select statement can omit it.  By not using FROM you have no source for your data, so you can't specify columns within that source.  Rather you can only select values that already exist; be that constants defined in the statement itself, or in some cases (e.g. subqueries) columns referenced from other parts of the query.

This is simpler to understand if you're familiar with Oracle's Dual table; a table with 1 row.  In MS SQL that table would look like this:

```<code>-- Ref: https://blog.sqlauthority.com/2010/07/20/sql-server-select-from-dual-dual-equivalent/
CREATE TABLE DUAL
(
    DUMMY VARCHAR(1) NOT NULL
    , CONSTRAINT CHK_ColumnD_DocExc  CHECK (DUMMY = 'X') -- ensure this column can only hold the value X
    , CONSTRAINT PK_DUAL PRIMARY KEY (DUMMY) -- ensure we can only have unique values... combined with the above means we can only ever have 1 row
)
GO
INSERT INTO DUAL (DUMMY)
VALUES ('X')
GO
</code>```

You can then do select 1 one, 'something else' two from dual.  You're not really using dual; just ensuring that you have a table which will always return exactly 1 row.

Now in SQL anywhere you omit a FROM statement consider that statement as if it said FROM DUAL / it has the same meaning, only SQL allows this more shorthand approach.

Update

You mention in the comments that you don't see how you can reference columns from the original statement when in a subquery (e.g. of the kind you may see when using APPLY).  The below code shows this without the APPLY scenario.  Admittedly the demo code here's not somehting you'd ever use (since you could just to where Something like '%o%' on the original statement without needing the subquery/in statement), but for illustrative purposes it shows exactly the same sort of scenario as you've got with your APPLY scenario; i.e. the statement is just returning the value of SOMETHING for the current row.

```<code>declare @someTable table (
    Id bigint not null identity(1,1)
    , Something nvarchar(32) not null
)
insert @someTable (Something) values ('one'), ('two'), ('three')

select *
from @someTable x
where x.Something in
(
    -- this subquery references the SOMETHING column from above, but doesn't have a FROM statement
    -- note: there is only 1 value at a time for something here; not all 3 values at once; it's the same single value as Something as we have before the in keyword above
    select Something
    where Something like '%o%'
)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Most online documentation or tutorials discussing OUTER|CROSS APPLY describe something like:

SELECT columns
FROM table OUTER|CROSS APPLY (SELECT … FROM …);

The subquery is normally a full SELECT … FROM … query.

I must have read somewhere that the subquery doesn’t need a FROM  in which case the columns appear to come from the main query:

SELECT columns
FROM table OUTER|CROSS APPLY (SELECT … );

because I have used it routinely as a method to pre-calculate columns.

The question is what is really happening if the FROM is omitted from the sub query? Is it short for something else? I found that it does not mean the same as from the main table.

I have a sample here: http://sqlfiddle.com/#!18/0188f7/4/1

Body:
Omitting the FROM statement is not specific to a CROSS/OUTER APPLY; any valid SQL select statement can omit it.  By not using FROM you have no source for your data, so you can't specify columns within that source.  Rather you can only select values that already exist; be that constants defined in the statement itself, or in some cases (e.g. subqueries) columns referenced from other parts of the query.

This is simpler to understand if you're familiar with Oracle's Dual table; a table with 1 row.  In MS SQL that table would look like this:

-- Ref: https://blog.sqlauthority.com/2010/07/20/sql-server-select-from-dual-dual-equivalent/
CREATE TABLE DUAL
(
    DUMMY VARCHAR(1) NOT NULL
    , CONSTRAINT CHK_ColumnD_DocExc  CHECK (DUMMY = 'X') -- ensure this column can only hold the value X
    , CONSTRAINT PK_DUAL PRIMARY KEY (DUMMY) -- ensure we can only have unique values... combined with the above means we can only ever have 1 row
)
GO
INSERT INTO DUAL (DUMMY)
VALUES ('X')
GO

You can then do select 1 one, 'something else' two from dual.  You're not really using dual; just ensuring that you have a table which will always return exactly 1 row.

Now in SQL anywhere you omit a FROM statement consider that statement as if it said FROM DUAL / it has the same meaning, only SQL allows this more shorthand approach.

Update

You mention in the comments that you don't see how you can reference columns from the original statement when in a subquery (e.g. of the kind you may see when using APPLY).  The below code shows this without the APPLY scenario.  Admittedly the demo code here's not somehting you'd ever use (since you could just to where Something like '%o%' on the original statement without needing the subquery/in statement), but for illustrative purposes it shows exactly the same sort of scenario as you've got with your APPLY scenario; i.e. the statement is just returning the value of SOMETHING for the current row.

declare @someTable table (
    Id bigint not null identity(1,1)
    , Something nvarchar(32) not null
)
insert @someTable (Something) values ('one'), ('two'), ('three')

select *
from @someTable x
where x.Something in
(
    -- this subquery references the SOMETHING column from above, but doesn't have a FROM statement
    -- note: there is only 1 value at a time for something here; not all 3 values at once; it's the same single value as Something as we have before the in keyword above
    select Something
    where Something like '%o%'
)


问:
Including a variable value in a XSL select path is not working
I can't quite get my head around this.

So I have this external XML data file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Translations xmlns="http://www.publictalksoftware.co.uk/msa">
  <en>
    <Chairman>Chairman</Chairman>
    <Conductor>Conductor</Conductor>
    <Hospitality>Hospitality</Hospitality>
    <Prayer>Prayer</Prayer>
    <PublicTalk>Public Talk</PublicTalk>
    <Reader>Reader</Reader>
    <ServiceTalk>Service Talk</ServiceTalk>
    <Speaker>Speaker</Speaker>
    <Theme>Theme</Theme>
    <WTStudy>Watchtower Study</WTStudy>
  </en>
</Translations>
</code>```

It is referenced in my master XSL script like this:

```<code><xsl:variable name="Translations" select="document('Workbook-S-140-Compact_2020_v2_Translations.XML')"/>
</code>```

I am able to extract values from this XML file like this:

```<code><xsl:value-of select="$Translations/msa:Translations/msa:en/msa:ServiceTalk"/>
</code>```

The above will pull out the English translation. Here is the thing, in my main XML data file I have the following at the top:

```<code><?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="Workbook-S-140-Compact_2020_v2.xsl"?>
<MeetingWorkBook>
    <Settings>
        <LanguageCode>en</LanguageCode>
        <Direction>ltr</Direction>
        <EditorMode>1</EditorMode>
        <ForeignGroupMode>0</ForeignGroupMode>
        <Now Day="20" Month="2" Year="2020"/>
    </Settings>
</code>```

Notice the LanguageCode entry? I wanted to make use of this so that my transformation was based on the language code. So I initially added a second variable to my XSL file:

```<code>  <xsl:variable name="LangCode">
    msa:<xsl:value-of select="//Settings//LanguageCode"/>
  </xsl:variable>
</code>```

And adjusting my path like this:

```<code><xsl:value-of select="$Translations/msa:Translations/{$LangCode}/msa:ServiceTalk"/>
</code>```

But it doesn't like it. I can't work out how to insert the language code into the path query. I have lots of these translation lines so I am looking for a simple solution if possible.

I have also tried saving the variable as:

```<code>  <xsl:variable name="LangCode">
    <xsl:value-of select="//Settings//LanguageCode"/>
  </xsl:variable>
</code>```

And then using:

```<code><xsl:value-of select="$Translations/msa:Translations/msa:{$LangCode}/msa:ServiceTalk"/>
</code>```

It still fails.

Is it possible to adjust this line:

```<code><xsl:variable name="Translations" select="document('Workbook-S-140-Compact_2020_v2_Translations.XML')"/>
</code>```

So that $Translations is pointing to the Translations/langcode node? Make sense?

答:
You can't use attribute value templates to dynamically construct an XPath expression.

But you can use variables in predicates:

```<code><xsl:value-of select="$Translations/msa:Translations/msa:*[local-name() = $LangCode]/msa:ServiceTalk"/>
</code>```

Body:
I can't quite get my head around this.

So I have this external XML data file:

<?xml version="1.0" encoding="UTF-8"?>
<Translations xmlns="http://www.publictalksoftware.co.uk/msa">
  <en>
    <Chairman>Chairman</Chairman>
    <Conductor>Conductor</Conductor>
    <Hospitality>Hospitality</Hospitality>
    <Prayer>Prayer</Prayer>
    <PublicTalk>Public Talk</PublicTalk>
    <Reader>Reader</Reader>
    <ServiceTalk>Service Talk</ServiceTalk>
    <Speaker>Speaker</Speaker>
    <Theme>Theme</Theme>
    <WTStudy>Watchtower Study</WTStudy>
  </en>
</Translations>

It is referenced in my master XSL script like this:

<xsl:variable name="Translations" select="document('Workbook-S-140-Compact_2020_v2_Translations.XML')"/>

I am able to extract values from this XML file like this:

<xsl:value-of select="$Translations/msa:Translations/msa:en/msa:ServiceTalk"/>

The above will pull out the English translation. Here is the thing, in my main XML data file I have the following at the top:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="Workbook-S-140-Compact_2020_v2.xsl"?>
<MeetingWorkBook>
    <Settings>
        <LanguageCode>en</LanguageCode>
        <Direction>ltr</Direction>
        <EditorMode>1</EditorMode>
        <ForeignGroupMode>0</ForeignGroupMode>
        <Now Day="20" Month="2" Year="2020"/>
    </Settings>

Notice the LanguageCode entry? I wanted to make use of this so that my transformation was based on the language code. So I initially added a second variable to my XSL file:

  <xsl:variable name="LangCode">
    msa:<xsl:value-of select="//Settings//LanguageCode"/>
  </xsl:variable>

And adjusting my path like this:

<xsl:value-of select="$Translations/msa:Translations/{$LangCode}/msa:ServiceTalk"/>

But it doesn't like it. I can't work out how to insert the language code into the path query. I have lots of these translation lines so I am looking for a simple solution if possible.

I have also tried saving the variable as:

  <xsl:variable name="LangCode">
    <xsl:value-of select="//Settings//LanguageCode"/>
  </xsl:variable>

And then using:

<xsl:value-of select="$Translations/msa:Translations/msa:{$LangCode}/msa:ServiceTalk"/>

It still fails.

Is it possible to adjust this line:

<xsl:variable name="Translations" select="document('Workbook-S-140-Compact_2020_v2_Translations.XML')"/>

So that $Translations is pointing to the Translations/langcode node? Make sense?

Body:
You can't use attribute value templates to dynamically construct an XPath expression.

But you can use variables in predicates:

<xsl:value-of select="$Translations/msa:Translations/msa:*[local-name() = $LangCode]/msa:ServiceTalk"/>


问:
Error Opening PGM file with PIL and SKIMAGE
I have following Image file:

Image

I used PIL and Skimage to open it but I get following errors

First with PIL (tried with and without trucate option):
Code:

```<code>from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
img = Image.open("image_output.pgm")
</code>```

Erorr:

```<code>OSError: cannot identify image file 'image_output.pgm'
</code>```

And with Skimage:

Code:

```<code>from skimage import io
img = io.imread("image_output.pgm")
</code>```

Error:

```<code>OSError: cannot identify image file <_io.BufferedReader name='image_output.pgm'>
</code>```

I can open the file with GUI applications like system photo viewer and Matlab.

How can I diagnose what is wrong with image? I compared the byte data with other PGM files which I can open in Python, but could not identify the difference.

Thanks.

答:
Your file is P2 type PGM, which means it is in ASCII - you can view it in a normal text editor. It seems neither PIL, nor skimage want to read that, but are happy to read the corresponding P5 type which is identical except it is written in binary, rather than ASCII.

There are a few options...

1) You could use OpenCV to read it:

```<code>import cv2
im = cv2.imread('a.pgm')
</code>```

2) You could convert it to P5 with ImageMagick and then read the output.pgm file with skimage or PIL:

```<code>magick input.pgm output.pgm
</code>```

3) If adding OpenCV, or ImageMagick as a dependency is a real pain for you, it is possible to read a PGM image yourself:

```<code>#!/usr/bin/env python3

import re
import numpy as np

# Open image file, slurp the lot
with open('input.pgm') as f:
   s = f.read()

# Find anything that looks like numbers
# Technically, there could be comments that should be ignored
l=re.findall(r'[0-9P]+',s)

# List "l" will contain: P5, width, height, 255, pixel1, pixel2, pixel3...
# Technically, if l[3]>255, you should change the type of the Numpy array to uint16, but that is not the case
w, h = int(l[1]), int(l[2])

# Make Numpy image from data
ni = np.array(l[4:],dtype=np.uint8).reshape((h,w))
</code>```

Body:
I have following Image file:

Image

I used PIL and Skimage to open it but I get following errors

First with PIL (tried with and without trucate option):
Code:

from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
img = Image.open("image_output.pgm")

Erorr:

OSError: cannot identify image file 'image_output.pgm'

And with Skimage:

Code:

from skimage import io
img = io.imread("image_output.pgm")

Error:

OSError: cannot identify image file <_io.BufferedReader name='image_output.pgm'>

I can open the file with GUI applications like system photo viewer and Matlab.

How can I diagnose what is wrong with image? I compared the byte data with other PGM files which I can open in Python, but could not identify the difference.

Thanks.

Body:
Your file is P2 type PGM, which means it is in ASCII - you can view it in a normal text editor. It seems neither PIL, nor skimage want to read that, but are happy to read the corresponding P5 type which is identical except it is written in binary, rather than ASCII.

There are a few options...

1) You could use OpenCV to read it:

import cv2
im = cv2.imread('a.pgm')

2) You could convert it to P5 with ImageMagick and then read the output.pgm file with skimage or PIL:

magick input.pgm output.pgm

3) If adding OpenCV, or ImageMagick as a dependency is a real pain for you, it is possible to read a PGM image yourself:

#!/usr/bin/env python3

import re
import numpy as np

# Open image file, slurp the lot
with open('input.pgm') as f:
   s = f.read()

# Find anything that looks like numbers
# Technically, there could be comments that should be ignored
l=re.findall(r'[0-9P]+',s)

# List "l" will contain: P5, width, height, 255, pixel1, pixel2, pixel3...
# Technically, if l[3]>255, you should change the type of the Numpy array to uint16, but that is not the case
w, h = int(l[1]), int(l[2])

# Make Numpy image from data
ni = np.array(l[4:],dtype=np.uint8).reshape((h,w))


问:
Disable mouse scroll middle click event with jQuery
I wrote the below code for disabling the scroll in the mouse while it is clicked.
but my code does not work an when I click with the scroll of my mouse it opens my link.

Here is my code :

$('a').on('mousedown', function(e) {
  if (e.which === 2) {
    console.log('Disabled');
    return false;
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
 click here </code>```

答:
You can use event.preventDefault() to cancel a action

document.onmousedown= function (e) {
    if( e.which == 2 ) {
        e.preventDefault();
        alert("middle button pressed, dont open");
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> click here </code>```

Body:
I wrote the below code for disabling the scroll in the mouse while it is clicked.
but my code does not work an when I click with the scroll of my mouse it opens my link.

Here is my code :

$('a').on('mousedown', function(e) {
  if (e.which === 2) {
    console.log('Disabled');
    return false;
  }
});

 click here

Body:
You can use event.preventDefault() to cancel a action

document.onmousedown= function (e) {
    if( e.which == 2 ) {
        e.preventDefault();
        alert("middle button pressed, dont open");
    }
}

<a href="#dontwanttoopen"> click here </a>


问:
start asynchronous task in windows mobile 6.5
Basically I am an android developer,now working in windows.Could anyone please let me know if there is any way to start asynchronous task with pre post executes similar to android?

Thanks in advance :)

答:
I'm not familiar with Android, but if you want to execute an asynchronous task, you have two options:

Use a thread to execute the task in-process.  In C# that would be the Thread or ThreadPool class, in C++ it's CreateThread.

Spawn a separate process completely for the task.  In C# that would be done with the Process class.  In C++ it would be CreateProcess (or ShellExecuteEx).

Without knowing more about your "task", your code environment and the launching process it's difficult to be any more targeted in my answer.

EDIT

Further investigation leads me to believe that you're talking about an in-proce callback from an asynchronous thread execution, so you're very likely after a thread (though a timer might also achieve what you want, depending on exactly what you're after).  How to implement it is very different depending on the language you're using.  Let us know what language you're developing in and we can give you better direction.

ContentLicense: CC BY-SA 3.0


问:
MySql Admin User lost Privileges
On PreProd - MySqlServer Admin account lost the privileges which was all good yesterday.

When ran show grants for xxxxxadmin;on Dev its resulted as

On Pre-Prod (which was same as Dev)

There is no other admin account to log into the server.  Is there a way to get the Privileges back.

These are Azure MySql databases.

答:
Using Azure Portal you can reset the password.

Navigate to your Azure MySql database in Azure Portal and in Overivew, and clickReset Password.

https://learn.microsoft.com/en-us/azure/mysql/howto-create-manage-server-portal#update-admin-password

Title: MySql Admin User lost Privileges


问:
Why IReadOnlyCollection has ElementAt but not IndexOf
I am working with a IReadOnlyCollection of objects.

Now I'm a bit surprised, because I can use linq extension method ElementAt(). But I don't have access to IndexOf().

This to me looks a bit illogical: I can get the element at a given position, but I cannot get the position of that very same element.

Is there a specific reason for it?

I've already read -> How to get the index of an element in an IEnumerable? and I'm not totally happy with the response.

答:
IReadOnlyCollection is a collection, not a list, so strictly speaking, it should not even have ElementAt(). This method is defined in IEnumerable as a convenience, and IReadOnlyCollection has it because it inherits it from IEnumerable. If you look at the source code, it checks whether the IEnumerable is in fact an IList, and if so it returns the element at the requested index, otherwise it proceeds to do a linear traversal of the IEnumerable until the requested index, which is inefficient.

So, you might ask why IEnumerable has an ElementAt() but not  IndexOf(), but I do not find this question very interesting, because it should not have either of these methods. An IEnumerable is not supposed to be indexable.

Now, a very interesting question is why IReadOnlyList has no IndexOf() either.

IReadOnlyList<T> has no IndexOf() for no good reason whatsoever.

If you really want to find a reason to mention, then the reason is historical:

Back in the mid-nineties when C# was laid down, people had not quite started to realize the benefits of immutability and readonlyness, so the IList<T> interface that they baked into the language was, unfortunately, mutable.

The right thing would have been to come up with IReadOnlyList<T> as the base interface, and make IList<T> extend it, adding mutation methods only, but that's not what happened.

IReadOnlyList<T> was invented a considerable time after IList<T>, and by that time it was too late to redefine IList<T> and make it extend IReadOnlyList<T>.  So, IReadOnlyList<T> was built from scratch.

They could not make IReadOnlyList<T> extend IList<T>, because then it would have inherited the mutation methods, so they based it on IReadOnlyCollection<T> and IEnumerable<T> instead.  They added the this[i] indexer, but then they either forgot to add other methods like IndexOf(), or they intentionally omitted them since they can be implemented as extension methods, thus keeping the interface simpler. But they did not provide any such extension methods.

So, here, is an extension method that adds IndexOf() to IReadOnlyList<T>:

```<code>using Collections = System.Collections.Generic;

    public static int IndexOf<T>( this Collections.IReadOnlyList<T> self, T elementToFind )
    {
        int i = 0;
        foreach( T element in self )
        {
            if( Equals( element, elementToFind ) )
                return i;
            i++;
        }
        return -1;
    }
</code>```

Be aware of the fact that this extension method is not as powerful as a method built into the interface would be.  For example, if you are implementing a collection which expects an IEqualityComparer<T> as a construction (or otherwise separate) parameter, this extension method will be blissfully unaware of it, and this will of course lead to bugs. (Thanks to Grx70 for pointing this out in the comments.)

Body:
IReadOnlyCollection is a collection, not a list, so strictly speaking, it should not even have ElementAt(). This method is defined in IEnumerable as a convenience, and IReadOnlyCollection has it because it inherits it from IEnumerable. If you look at the source code, it checks whether the IEnumerable is in fact an IList, and if so it returns the element at the requested index, otherwise it proceeds to do a linear traversal of the IEnumerable until the requested index, which is inefficient.

So, you might ask why IEnumerable has an ElementAt() but not  IndexOf(), but I do not find this question very interesting, because it should not have either of these methods. An IEnumerable is not supposed to be indexable.

Now, a very interesting question is why IReadOnlyList has no IndexOf() either.

IReadOnlyList<T> has no IndexOf() for no good reason whatsoever.

If you really want to find a reason to mention, then the reason is historical:

Back in the mid-nineties when C# was laid down, people had not quite started to realize the benefits of immutability and readonlyness, so the IList<T> interface that they baked into the language was, unfortunately, mutable.

The right thing would have been to come up with IReadOnlyList<T> as the base interface, and make IList<T> extend it, adding mutation methods only, but that's not what happened.

IReadOnlyList<T> was invented a considerable time after IList<T>, and by that time it was too late to redefine IList<T> and make it extend IReadOnlyList<T>.  So, IReadOnlyList<T> was built from scratch.

They could not make IReadOnlyList<T> extend IList<T>, because then it would have inherited the mutation methods, so they based it on IReadOnlyCollection<T> and IEnumerable<T> instead.  They added the this[i] indexer, but then they either forgot to add other methods like IndexOf(), or they intentionally omitted them since they can be implemented as extension methods, thus keeping the interface simpler. But they did not provide any such extension methods.

So, here, is an extension method that adds IndexOf() to IReadOnlyList<T>:

using Collections = System.Collections.Generic;

    public static int IndexOf<T>( this Collections.IReadOnlyList<T> self, T elementToFind )
    {
        int i = 0;
        foreach( T element in self )
        {
            if( Equals( element, elementToFind ) )
                return i;
            i++;
        }
        return -1;
    }

Be aware of the fact that this extension method is not as powerful as a method built into the interface would be.  For example, if you are implementing a collection which expects an IEqualityComparer<T> as a construction (or otherwise separate) parameter, this extension method will be blissfully unaware of it, and this will of course lead to bugs. (Thanks to Grx70 for pointing this out in the comments.)


问:
Property class validation of curvefit.fitoptions
TL;DR: I would like to use property class validation to validate fitoptions objects, but MATLAB complains.

Consider the following classes:

% SUPERCLASS:
classdef (Abstract) BaseModel
  % CWLvsT is an abstract parent class for different CWL(T) models.

  properties (Abstract = true, Access = protected, Constant = true)
    MODEL   (1,1) string
    FITOPTS (1,1) % ???
  end

end

% SUBCLASS:
classdef RationalFraction < BaseModel
  % This corresponds to a fit of type "rat11".
  properties (Access = protected, Constant = true)
    MODEL = "CWL(T) = (P1 * T + P2) / (T + Q1)";
    FITOPTS = fitoptions('rat11', ...
                  'Lower', [-1, -1E5, -1E4], ...
                  'Upper', [10, 5E5, 5E4], ...
                  'StartPoint', [4, 0, 0]);
  end
end
```

<p>I would like to enforce that subclasses specify some sort of a <code>fitoptions</code> object (there are several types) for the <code>FITOPTS</code> property. </p>

<strong>Attempt #1</strong>:

<p>The first thing I tried was to create an example <code>fitoptions</code> object (according to the definition in the subclass) and see what its <code>class</code> was. The result I got was <code>curvefit.nlsqoptions</code>, so I tried putting that instead of the <code>% ???</code> in the superclass and instantiate the <code>RationalFraction</code> class, but got the following error:</p>

<pre class="lang-none prettyprint-override"><code>Error defining property 'FITOPTS' of class 'BaseModel':
Class named 'curvefit.nlsqoptions' is undefined or does not support property validation.
</code>```

Attempt #2:

I thought that the above error was a sign that there is some superclass for fitoptions against which I should validate the object, so I tried to do metaclass(optsObj) on the example object, but got an empty metaclass. Resorting to a manual search, I did manage to find a good candidate by going over the MATLAB\R2019b\toolbox\curvefit\curvefit\@curvefit folder - curvefit.basefitoptions, but this led to a similar error.

Attempt #3:

I noticed that the fitoptions objects aren't far from plain struct objects, so I tried FITOPTS (1,1) struct — which did result in a successful object creation. Unfortunately, when later referring to this FITOPTS field while trying to call fit, I got the following error:

Error using fit>iParseOptionalArgs (line 949)
Algorithm options must be specified in a FITOPTIONS object or as property-value pairs.
Error in fit (line 113)
[useroptions, useroptargs, probparams] = iParseOptionalArgs( varargin{:} );
```

Which means that the property validation cast the nlsqoptions object into a struct, losing the "extra information" that it held fit options. While this behavior is an interesting find, it is not very helpful in the present scenario.

My question:

Can anybody suggest a way of performing this class validation such that the FITOPTS ends up containing a fit options object?

I'm working with R2019b.

答:
The last error appearing in the question refers to line 949 in fit. If we look in this file, we see that the "candidate" fit options object is passed to a function named isfitoptions which checks whether it's valid or not.

This hints at a different mechanism of validating inputs - passing them to validation functions. Although these functions are meant to validate the value, rather than the class, there's no reason they cannot be used for the latter as well. Thus, if MATLAB's function can be invoked by the user, it can be used for validation, and if not, the same test (simple call to isa) can be implemented as a method in our own class. Fortunately, this function is accessible outside the package/toolbox, and the following leads to the desired result:

  properties (Abstract = true, Access = protected, Constant = true)
    MODEL   (1,1) string
    FITOPTS (1,1) {isfitoptions}
  end
```

Body:
TL;DR: I would like to use property class validation to validate fitoptions objects, but MATLAB complains.

Consider the following classes:

% SUPERCLASS:
classdef (Abstract) BaseModel
  % CWLvsT is an abstract parent class for different CWL(T) models.

  properties (Abstract = true, Access = protected, Constant = true)
    MODEL   (1,1) string
    FITOPTS (1,1) % ???
  end

end

% SUBCLASS:
classdef RationalFraction < BaseModel
  % This corresponds to a fit of type "rat11".
  properties (Access = protected, Constant = true)
    MODEL = "CWL(T) = (P1 * T + P2) / (T + Q1)";
    FITOPTS = fitoptions('rat11', ...
                  'Lower', [-1, -1E5, -1E4], ...
                  'Upper', [10, 5E5, 5E4], ...
                  'StartPoint', [4, 0, 0]);
  end
end

I would like to enforce that subclasses specify some sort of a fitoptions object (there are several types) for the FITOPTS property.

Attempt #1:

The first thing I tried was to create an example fitoptions object (according to the definition in the subclass) and see what its class was. The result I got was curvefit.nlsqoptions, so I tried putting that instead of the % ??? in the superclass and instantiate the RationalFraction class, but got the following error:

Error defining property 'FITOPTS' of class 'BaseModel':
Class named 'curvefit.nlsqoptions' is undefined or does not support property validation.

Attempt #2:

I thought that the above error was a sign that there is some superclass for fitoptions against which I should validate the object, so I tried to do metaclass(optsObj) on the example object, but got an empty metaclass. Resorting to a manual search, I did manage to find a good candidate by going over the MATLAB\R2019b\toolbox\curvefit\curvefit\@curvefit folder - curvefit.basefitoptions, but this led to a similar error.

Attempt #3:

I noticed that the fitoptions objects aren't far from plain struct objects, so I tried FITOPTS (1,1) struct — which did result in a successful object creation. Unfortunately, when later referring to this FITOPTS field while trying to call fit, I got the following error:

Error using fit>iParseOptionalArgs (line 949)
Algorithm options must be specified in a FITOPTIONS object or as property-value pairs.
Error in fit (line 113)
[useroptions, useroptargs, probparams] = iParseOptionalArgs( varargin{:} );

Which means that the property validation cast the nlsqoptions object into a struct, losing the "extra information" that it held fit options. While this behavior is an interesting find, it is not very helpful in the present scenario.

My question:

Can anybody suggest a way of performing this class validation such that the FITOPTS ends up containing a fit options object?

I'm working with R2019b.


问:
Laravel - How to use a single textbox for global search
I have this Laravel-5.8 code whereby users can search using different control fields to search for employee_code, designation and department.

```<code>class HrEmployee extends Model
{
  protected $table = 'hr_employees';

  protected $primaryKey = 'id';

  protected $fillable = [
              'id',
              'employee_code',
              'address',
              'email',
              'employee_designation_id',
              'first_name',
              'emp_image',
              'last_name',
              'other_name',
              'department_id',
          ];

protected $appends = ['full_name'];

 public function user()
 {
    return $this->belongsTo('App\User');
 }

 public function designation()
 {
    return $this->belongsTo('App\Models\Hr\HrDesignation','employee_designation_id');
 }

 public function department()
 {
    return $this->belongsTo('App\Models\Hr\HrDepartment','department_id');
 }
}
</code>```

Controller

```<code>public function index(Request $request)
{
    $userCompany = Auth::user()->company_id;
    $render=[];
        $employees = HrEmployee::where('company_id', $userCompany);
    $employees=$employees->with('department','designation');
    if(isset($request->employee_code))
    {
        $employees=$employees->where('employee_code','like','%'.$request->employee_code.'%');
        $render['employee_code']=$request->employee_code;
    }
    if(isset($request->employee_designation_id))
    {
        $employees=$employees->where('employee_designation_id',$request->employee_designation_id);
        $render['employee_designation_id']=$request->employee_designation_id;
    }
    if(isset($request->department_id))
    {
        $employees=$employees->where('department_id',$request->department_id);
        $render['department_id']=$request->department_id;
    }
    $employees= $employees->paginate(6);
    $employees= $employees->appends($render);
    $data['employees'] = $employees;
    $data['departments']= HrDepartment::where('company_id', $userCompany)->pluck('dept_name','id');
    $data['designations']= HrDesignation::where('company_id', $userCompany)->pluck('designation_name','id');

    return view('hr.employees.index',$data);
}
</code>```

view

```<code>{{ Form::model(request(),['method'=>'get']) }}
     <div class="row" style="margin-bottom: 10px">

        <div orm-group class="col-sm-3">
            {{Form::label('employee_code', 'Employee No.')}}
            {{ Form::text('employee_code',null,['class'=>'form-control','placeholder'=>'Employee Code']) }}

        </div>
        <div class="col-sm-4">
            {{Form::label('department_id', 'Department')}}
            {{ Form::select('department_id',$departments,null,['class'=>'form-control select2bs4','placeholder'=>'Select Department']) }}
        </div>
        <div class="col-sm-4">
            {{Form::label('employee_designation_id', 'Designation')}}
            {{ Form::select('employee_designation_id',$designations,null,['class'=>'form-control select2bs4','placeholder'=>'Select Designation']) }}
        </div>

        <div class="col-xs-3">
            <br>
            {{ Form::submit('Search',['class'=>'btn btn-warning']) }}

        </div>
        {{ Form::close() }}
    </div>
    <br>
      <!-- Default box -->
      <div class="card card-solid">
        <div class="card-body pb-0">
          <div class="row d-flex align-items-stretch">
              @if (count($employees))
              @foreach($employees as $key => $employee)
            <div class="col-12 col-sm-6 col-md-4 d-flex align-items-stretch">
              <div class="card bg-light">
                <div class="card-header text-muted border-bottom-0">
                  {{isset($employee->designation) ? $employee->designation->designation_name : ''}}
                </div>
                <div class="card-body pt-0">
                  <div class="row">
                    <div class="col-7">
                      <h2 class="lead"><b>Staff ID: {{$employee->employee_code}}</b></h2>
                      <h2 class="lead"><b>{{$employee->first_name}} {{$employee->last_name}}</b></h2>

                      <h6 class="lead"><b>Employee Department: </b>{{isset($employee->department) ? $employee->department->dept_name : ''}}</h6>
                      <h6 class="lead"><b>Employment Date: </b>{{$employee->employment_date ? Carbon\Carbon::parse($employee->employment_date)->format('d-m-Y') : 'N/A' }}</h6>
                      <ul class="ml-4 mb-0 fa-ul text-muted">
                        <li class="small"><span class="fa-li"><i class="fas fa-lg fa-envelope"></i></span> Email: {{$employee->email}}</li>
                        <li class="small"><span class="fa-li"><i class="fas fa-lg fa-phone"></i></span> Phone #: {{isset($employee->phone) ? $employee->phone : 'N/A'}}</li>
                      </ul>
                    </div>
                    <div class="col-5 text-center">
                                @if($employee->emp_image != '')
                                    <img src="{{ URL::to('/') }}/public/storage/employees/image/{{ $employee->emp_image }}" class="img-circle img-fluid" />

                                @else
                                    <img class="profile-user-img img-fluid img-circle" src="{{asset('theme/adminlte3/dist/img/default.png')}}" alt="" class="img-circle img-fluid">
                                @endif
                    </div>
                  </div>
                </div>
                <div class="card-footer">
                  <div class="text-right">
                    @can('employee_show')
                    <a href="{{ route('hr.employees.show', ['id'=>$employee->id]) }}" class="btn btn-sm btn-primary">
                      <i class="fas fa-user"></i> View Detail
                    </a>
                    @endcan
                  </div>
                </div>
              </div>
            </div>
            @endforeach
            @else
            <h4 style="text-align:center;">No matching records found</h4>
            @endif
          </div>
        </div>

        <!-- /.card-body -->
        <div class="card-footer align-items-center d-flex justify-content-center">
            {{ $employees->links() }}
        <!-- /.card-footer -->
      </div>
      <!-- /.card -->

    </div>
</code>```

Instead of searching for each field one by one using different control fields. How do I use a sing textbox to search for employee_code, first_name, last_name, department and designation?

Thank you

答:
You can do it with below code:

```<code>   $searchText = $request->searchText;
   $employees = HrEmployee::with(['department','designation'])->where('company_id', $userCompany);

    if($searchText)
    {
        $employees->where(function ($query) use($searchText) {
          $query->where('employee_code','like','%'.$searchText.'%')
           ->orWhere('first_name','like','%'.$searchText.'%')
           ->orWhere('last_name','like','%'.$searchText.'%')
             ->orWhereHas('designation', function($q) use ($searchText) {
                $q->where('designation_name', 'like','%'.$searchText.'%');
             })
             ->orWhereHas('department', function($q) use ($searchText) {
                $q->where('department_name', 'like','%'.$searchText.'%');
             });
        });

    }
     $employees = $employees->get();
    // For pagination
    // $employees = $employees->paginate(6);
</code>```

Here designation_name is name field in designation table and department_name is name field in designation table.

Body:
I have this Laravel-5.8 code whereby users can search using different control fields to search for employee_code, designation and department.

class HrEmployee extends Model
{
  protected $table = 'hr_employees';

  protected $primaryKey = 'id';

  protected $fillable = [
              'id',
              'employee_code',
              'address',
              'email',
              'employee_designation_id',
              'first_name',
              'emp_image',
              'last_name',
              'other_name',
              'department_id',
          ];

protected $appends = ['full_name'];

 public function user()
 {
    return $this->belongsTo('App\User');
 }

 public function designation()
 {
    return $this->belongsTo('App\Models\Hr\HrDesignation','employee_designation_id');
 }

 public function department()
 {
    return $this->belongsTo('App\Models\Hr\HrDepartment','department_id');
 }
}

Controller

public function index(Request $request)
{
    $userCompany = Auth::user()->company_id;
    $render=[];
        $employees = HrEmployee::where('company_id', $userCompany);
    $employees=$employees->with('department','designation');
    if(isset($request->employee_code))
    {
        $employees=$employees->where('employee_code','like','%'.$request->employee_code.'%');
        $render['employee_code']=$request->employee_code;
    }
    if(isset($request->employee_designation_id))
    {
        $employees=$employees->where('employee_designation_id',$request->employee_designation_id);
        $render['employee_designation_id']=$request->employee_designation_id;
    }
    if(isset($request->department_id))
    {
        $employees=$employees->where('department_id',$request->department_id);
        $render['department_id']=$request->department_id;
    }
    $employees= $employees->paginate(6);
    $employees= $employees->appends($render);
    $data['employees'] = $employees;
    $data['departments']= HrDepartment::where('company_id', $userCompany)->pluck('dept_name','id');
    $data['designations']= HrDesignation::where('company_id', $userCompany)->pluck('designation_name','id');

    return view('hr.employees.index',$data);
}

view

{{ Form::model(request(),['method'=>'get']) }}

            {{Form::label('employee_code', 'Employee No.')}}
            {{ Form::text('employee_code',null,['class'=>'form-control','placeholder'=>'Employee Code']) }}

            {{Form::label('department_id', 'Department')}}
            {{ Form::select('department_id',$departments,null,['class'=>'form-control select2bs4','placeholder'=>'Select Department']) }}

            {{Form::label('employee_designation_id', 'Designation')}}
            {{ Form::select('employee_designation_id',$designations,null,['class'=>'form-control select2bs4','placeholder'=>'Select Designation']) }}

            {{ Form::submit('Search',['class'=>'btn btn-warning']) }}

        {{ Form::close() }}

              @if (count($employees))
              @foreach($employees as $key => $employee)

                  {{isset($employee->designation) ? $employee->designation->designation_name : ''}}

Staff ID: {{$employee->employee_code}}

{{$employee->first_name}} {{$employee->last_name}}

Employee Department: {{isset($employee->department) ? $employee->department->dept_name : ''}}

Employment Date: {{$employee->employment_date ? Carbon\Carbon::parse($employee->employment_date)->format('d-m-Y') : 'N/A' }}

 Email: {{$employee->email}}

 Phone #: {{isset($employee->phone) ? $employee->phone : 'N/A'}}

                                @if($employee->emp_image != '')
                                    emp_image }}" class="img-circle img-fluid" />

                                @else

                                @endif

                    @can('employee_show')
                    $employee->id]) }}" class="btn btn-sm btn-primary">
                       View Detail

                    @endcan

            @endforeach
            @else

No matching records found

            @endif

            {{ $employees->links() }}

Instead of searching for each field one by one using different control fields. How do I use a sing textbox to search for employee_code, first_name, last_name, department and designation?

Thank you

Body:
You can do it with below code:

   $searchText = $request->searchText;
   $employees = HrEmployee::with(['department','designation'])->where('company_id', $userCompany);

    if($searchText)
    {
        $employees->where(function ($query) use($searchText) {
          $query->where('employee_code','like','%'.$searchText.'%')
           ->orWhere('first_name','like','%'.$searchText.'%')
           ->orWhere('last_name','like','%'.$searchText.'%')
             ->orWhereHas('designation', function($q) use ($searchText) {
                $q->where('designation_name', 'like','%'.$searchText.'%');
             })
             ->orWhereHas('department', function($q) use ($searchText) {
                $q->where('department_name', 'like','%'.$searchText.'%');
             });
        });

    }
     $employees = $employees->get();
    // For pagination
    // $employees = $employees->paginate(6);

Here designation_name is name field in designation table and department_name is name field in designation table.


问:
Android Q (10) ask permission to get access all storage. Scoped storage
In Android 10 apps that need to access storage need to ask permission to access a concrete path. But apps like file explorer can ask permission for access to the root storage and gain permission to read/write to all storage. That is what I am trying to do.

According to Android we must use ACTION_OPEN_DOCUMENT_TREE for this. The problem I have is that everything seems correct, but the permission is not granted to the app.

```<code>  private void askAndroid10Perm()
    {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
        intent.addFlags(
                Intent.FLAG_GRANT_READ_URI_PERMISSION
                        | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                        | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
                        | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION);
        startActivityForResult(intent, REQUEST_CODE_OPEN_DOCUMENT_TREE);
    }
</code>```

Here the user can see Android file tree and, with main storage selected, click to grant permission. "It will allow - app name - to have full access to all files currently store under this location, and any future content stored here" -> Allow

Then:

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case REQUEST_CODE_OPEN_DOCUMENT_TREE:
            if (resultCode == Activity.RESULT_OK) {
                Uri treeUri = data.getData();
                int takeFlags = data.getFlags();
                takeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION |
                        Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

                    Log.i("TAG", "takePersistableUriPermission: " + treeUri);
                    this.getContentResolver().takePersistableUriPermission(treeUri, takeFlags);

                }

            }
    }
}
</code>```

Log:

takePersistableUriPermission:
  content://com.android.externalstorage.documents/tree/primary%3A

Then the app will still not have permission to access to root.

open failed: EACCES (Permission denied)

Of course I have:

```<code><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</code>```

Granted by the user.

答:
Add line in Manifest</p>
```<code><application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:requestLegacyExternalStorage="true" //Add this Line
    android:label="@string/app_name">

---------<Activity, Sevices or Recivers>----------

</application>
</code>```

Body:
In Android 10 apps that need to access storage need to ask permission to access a concrete path. But apps like file explorer can ask permission for access to the root storage and gain permission to read/write to all storage. That is what I am trying to do.

According to Android we must use ACTION_OPEN_DOCUMENT_TREE for this. The problem I have is that everything seems correct, but the permission is not granted to the app.

  private void askAndroid10Perm()
    {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
        intent.addFlags(
                Intent.FLAG_GRANT_READ_URI_PERMISSION
                        | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                        | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
                        | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION);
        startActivityForResult(intent, REQUEST_CODE_OPEN_DOCUMENT_TREE);
    }

Here the user can see Android file tree and, with main storage selected, click to grant permission. "It will allow - app name - to have full access to all files currently store under this location, and any future content stored here" -> Allow

Then:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case REQUEST_CODE_OPEN_DOCUMENT_TREE:
            if (resultCode == Activity.RESULT_OK) {
                Uri treeUri = data.getData();
                int takeFlags = data.getFlags();
                takeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION |
                        Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

                    Log.i("TAG", "takePersistableUriPermission: " + treeUri);
                    this.getContentResolver().takePersistableUriPermission(treeUri, takeFlags);

                }

            }
    }
}

Log:

takePersistableUriPermission:
  content://com.android.externalstorage.documents/tree/primary%3A

Then the app will still not have permission to access to root.

open failed: EACCES (Permission denied)

Of course I have:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Granted by the user.

Body:
Add line in Manifest

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:requestLegacyExternalStorage="true" //Add this Line
    android:label="@string/app_name">

---------<Activity, Sevices or Recivers>----------

</application>


问:
Problem in working with core data
Am using core data framework in my cocoa application,I have created couple of entities and created reference using NSEntityDescription. When i run the application am getting an error saying that "The managed object model version used to open the persistent store is incompatible with the one that was used to create the persistent store."</p>

答:
You must delete the persistent store file from either:

~/Library/$AppName

~/Library/Application Support/$AppName

(Depending on your version of Xcode.)

Title: Problem in working with core data


问:
Xamarin Android - Porting Android Api 26 --> API 28 - Button bring to front on click
We are updating a Xamarin project from Android 8.0 to 9.0 (API 26 -> API 28).

We detect a different behavior on a layout: we have a button above which we display labels and icons inside a StackLayout.

With the old Android 8.0 version, we could correctly click on the button.
With the new Android 9.0 version, we note that we can correctly click on the button, but when we click the button is brought to the front and hides the StackLayout labels and icons.
When we return to this screen, the button remains in the foreground and the StackLayout labels and icons no longer appear.

How can we force the StackLayout labels and icons to stay on the button even if the button is clicked?
Thanks

```<code>    <StackLayout Orientation="Vertical" AbsoluteLayout.LayoutFlags="All" AbsoluteLayout.LayoutBounds="0,0,1,1">
        <ctrl:TitleBarControl x:Name="titleBar" Title="Menu Trasporto Valori"></ctrl:TitleBarControl>
        <Grid HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" Style="{StaticResource standardGrid}">
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>

            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>

            <Button x:Name="btnProssimo" Image="MondoConPinPoint_48x48.gif" Text="Prossimo" HorizontalOptions="Fill" VerticalOptions="Fill" Grid.Row="0" Grid.Column="0" Style="{StaticResource menuButton}" Command="{Binding ProssimoCommand}"></Button>
            <StackLayout Orientation="Horizontal" Grid.Row="0" Grid.Column="0" HorizontalOptions="Center" VerticalOptions="End">
                <Label Text="Da eseguire:" HorizontalOptions="Center" VerticalOptions="Center"  Style="{StaticResource lightLabel}"></Label>
                <Label Text="{Binding DaEseguire}" HorizontalOptions="Center" VerticalOptions="Center" Style="{StaticResource boldLabel}"></Label>
            </StackLayout>

            <Button x:Name="btnProssimoI" Image="Cacciavite_48x48.gif" Text="Prossimo I" HorizontalOptions="Fill" VerticalOptions="Fill" Grid.Row="1" Grid.Column="0" Style="{StaticResource menuButton}" Command="{Binding ProssimoICommand}"></Button>
            <StackLayout Orientation="Horizontal" Grid.Row="1" Grid.Column="0" HorizontalOptions="Center" VerticalOptions="End">
                <Label Text="Da eseguire:" HorizontalOptions="Center" VerticalOptions="End" Grid.Row="1" Grid.Column="0" Style="{StaticResource lightLabel}"></Label>
                <Label Text="{Binding IDaEseguire}" HorizontalOptions="End" VerticalOptions="End" Grid.Row="1" Grid.Column="0" Style="{StaticResource boldLabel}"></Label>
                <Image x:Name="imgSveglia" Grid.Row="1" Grid.Column="0" VerticalOptions="End" HorizontalOptions="End" Source="Sveglia_24x24.gif" WidthRequest="26" IsVisible="{Binding IsI}"></Image>
            </StackLayout>

        </Grid>
    </StackLayout>
</code>```

答: Please use an ImageButton instead. This should solve your problem.

Body:
We are updating a Xamarin project from Android 8.0 to 9.0 (API 26 -> API 28).

We detect a different behavior on a layout: we have a button above which we display labels and icons inside a StackLayout.

With the old Android 8.0 version, we could correctly click on the button.
With the new Android 9.0 version, we note that we can correctly click on the button, but when we click the button is brought to the front and hides the StackLayout labels and icons.
When we return to this screen, the button remains in the foreground and the StackLayout labels and icons no longer appear.

How can we force the StackLayout labels and icons to stay on the button even if the button is clicked?
Thanks

    <StackLayout Orientation="Vertical" AbsoluteLayout.LayoutFlags="All" AbsoluteLayout.LayoutBounds="0,0,1,1">
        <ctrl:TitleBarControl x:Name="titleBar" Title="Menu Trasporto Valori"></ctrl:TitleBarControl>
        <Grid HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" Style="{StaticResource standardGrid}">
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>

            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>

            <Button x:Name="btnProssimo" Image="MondoConPinPoint_48x48.gif" Text="Prossimo" HorizontalOptions="Fill" VerticalOptions="Fill" Grid.Row="0" Grid.Column="0" Style="{StaticResource menuButton}" Command="{Binding ProssimoCommand}"></Button>
            <StackLayout Orientation="Horizontal" Grid.Row="0" Grid.Column="0" HorizontalOptions="Center" VerticalOptions="End">

            </StackLayout>

            <Button x:Name="btnProssimoI" Image="Cacciavite_48x48.gif" Text="Prossimo I" HorizontalOptions="Fill" VerticalOptions="Fill" Grid.Row="1" Grid.Column="0" Style="{StaticResource menuButton}" Command="{Binding ProssimoICommand}"></Button>
            <StackLayout Orientation="Horizontal" Grid.Row="1" Grid.Column="0" HorizontalOptions="Center" VerticalOptions="End">

                <Image x:Name="imgSveglia" Grid.Row="1" Grid.Column="0" VerticalOptions="End" HorizontalOptions="End" Source="Sveglia_24x24.gif" WidthRequest="26" IsVisible="{Binding IsI}"></Image>
            </StackLayout>

        </Grid>
    </StackLayout>


问:
flink data is not processed by the process function in a timewindow operator
I have a timewindow that I try to determine if I get a new key over a period of time. I am pushing data via kafka and when I debug it, I see that the data is getting to the keyby method but it is not reaching the process method and not being collected by the collector. I am using BoundedOutOfOrdernessTimestampExtractor for assigning watermarks :

```<code>    case class Src(qip:Ip, ref: Ip, ts: Long) extends FooRequest

    class TsExtractor extends BoundedOutOfOrdernessTimestampExtractor[Src](Time.hours(3)){
      override def extractTimestamp(element: Src): Long = element.ts
    }

    class RefFilter extends ProcessWindowFunction[Src, IpDetectionSrc, String, TimeWindow]{
      private lazy val stateDescriptor = new ValueStateDescriptor("refFilter",  createTypeInformation[String])

      override def process(key: String, context: Context, elements: Iterable[Src], out: Collector[IpDetectionSrc]): Unit = {
        println(s"RefIpFilter processing $key")//data is not getting here
        if(Option(context.windowState.getState(stateDescriptor).value()).isEmpty){
          println(s"new key found $key") //data is not getting here also
          context.windowState.getState(stateDescriptor).update(key)
          out.collect(elements.head)
        }
      }
    }

lazy val env: StreamExecutionEnvironment =
    setupEnv(StreamExecutionEnvironment.getExecutionEnvironment)(300000,Some(stateDir), Some(TimeCharacteristic.EventTime))

 lazy val src: DataStream[FooRequest] = env.addSource(consumer)

 lazy val uniqueRef:DataStream[FooRequest] => DataStream[Src] = src => src
        .flatMap(new FlatMapFunction[FooRequest,Src ]{
          override def flatMap(value: FooRequest, out: Collector[Src]): Unit =   value match {
            case r: Src =>
              out.collect(r)
            case invalid =>
              log.warn(s"filtered unexpected request $invalid")
          }
        })
        .assignTimestampsAndWatermarks(new TsExtractor)
        .keyBy(r => r.ref)
        .timeWindow(Time.seconds(120))
        .allowedLateness(Time.seconds(360))
        .process(new RefFilter)

uniqueRef(src).addSink(sink)
env.execute()
</code>```

any assistance will be greatly appreciated

答:
The BoundedOutOfOrdernessTimestampExtractor keeps track of the highest timestamp it has seen so far, and produces watermarks that trail behind this by the configured delay (so three hours, in this case). These watermarks are produced periodically, every 200 msec by default. So with only a single event, the watermark will be 3 hours behind this event, and the window will never be triggered. Furthermore, with finite input, the job will stop running once it has processed all of the events.

context.windowState is per-window state, with a limited lifetime. Each 2 minute window will have its own instance, and it is cleared once the allowed lateness for the window has expired. If you want keyed window state with a global scope, with an indefinite lifetime, use context.globalState instead.

Body:
I have a timewindow that I try to determine if I get a new key over a period of time. I am pushing data via kafka and when I debug it, I see that the data is getting to the keyby method but it is not reaching the process method and not being collected by the collector. I am using BoundedOutOfOrdernessTimestampExtractor for assigning watermarks :

    case class Src(qip:Ip, ref: Ip, ts: Long) extends FooRequest

    class TsExtractor extends BoundedOutOfOrdernessTimestampExtractor[Src](Time.hours(3)){
      override def extractTimestamp(element: Src): Long = element.ts
    }

    class RefFilter extends ProcessWindowFunction[Src, IpDetectionSrc, String, TimeWindow]{
      private lazy val stateDescriptor = new ValueStateDescriptor("refFilter",  createTypeInformation[String])

      override def process(key: String, context: Context, elements: Iterable[Src], out: Collector[IpDetectionSrc]): Unit = {
        println(s"RefIpFilter processing $key")//data is not getting here
        if(Option(context.windowState.getState(stateDescriptor).value()).isEmpty){
          println(s"new key found $key") //data is not getting here also
          context.windowState.getState(stateDescriptor).update(key)
          out.collect(elements.head)
        }
      }
    }

lazy val env: StreamExecutionEnvironment =
    setupEnv(StreamExecutionEnvironment.getExecutionEnvironment)(300000,Some(stateDir), Some(TimeCharacteristic.EventTime))

 lazy val src: DataStream[FooRequest] = env.addSource(consumer)

 lazy val uniqueRef:DataStream[FooRequest] => DataStream[Src] = src => src
        .flatMap(new FlatMapFunction[FooRequest,Src ]{
          override def flatMap(value: FooRequest, out: Collector[Src]): Unit =   value match {
            case r: Src =>
              out.collect(r)
            case invalid =>
              log.warn(s"filtered unexpected request $invalid")
          }
        })
        .assignTimestampsAndWatermarks(new TsExtractor)
        .keyBy(r => r.ref)
        .timeWindow(Time.seconds(120))
        .allowedLateness(Time.seconds(360))
        .process(new RefFilter)

uniqueRef(src).addSink(sink)
env.execute()

any assistance will be greatly appreciated


问:
What does the "-" mean in Xcode project navigator?

Using Xcode 11.

That little em dash is bothering me. I never see an "M" next to Storyboard anymore, no matter how many changes I make to it, and I worry that things might be missed when I commit.

What does it mean, and how can I get back to seeing a "--" in its place?

Thanks!

答:
Well, the "-" indicates the git status for your storyboard, here is the diagram for your reference.

Source:- From Sam's book


问:
Get dispatched NGRX item in browser console
I am new in NGRX and i am using it in Angular2+ app.

I have 2 components CREATE and READ. I am using NGRX to dispatch a message string on click event from CREATE COMPONENT.
I dispatch string message to NGRX STORE from CREATE COMPONENT and show that string message in READ COMPONENT's HTML FILE successfully, like

{{message | async}}

But now i want to get same string in my console and when i console same message variable of READ COMPONENT in READ COMPONENT's TS FILE, i get an object of store whereas i want to get the same string which is being displayed in READ COMPONENT's HTML file.

Is there a method to do this?

答:
message is be an observable, you should subscribe for it in the component.ts file</p>

```<code>message.subscribe((msg) => {
 console.log(msg):
})
</code>```

Body:
message is be an observable, you should subscribe for it in the component.ts file

message.subscribe((msg) => {
 console.log(msg):
})


答:
```<code>{{ Form::model(request(),['method'=>'get']) }}
         <div class="row" style="margin-bottom: 10px">

    <div orm-group class="col-sm-3">
         {{Form::label('search', 'Search')}}
         {{ Form::text('search',null,['class'=>'form-control','placeholder'=>'search']) }}

   </div>

  <div class="col-xs-3">
                <br>
      {{ Form::submit('Search',['class'=>'btn btn-warning']) }}

   </div>
{{ Form::close() }}
</code>```

then your controller function use orwhere()

```<code>public function index(Request $request)
{
    $search = $request->search;
    $userCompany = Auth::user()->company_id;
    $render=[];
        $employees = HrEmployee::where('company_id', $userCompany);
        $employees=$employees->with('department','designation');
        $employees=$employees->where('employee_code','like','%'.$search.'%')
            ->orWhere('employee_designation_id',$search)
            ->orwhere('department_id',$search)
            ->paginate(6);
    $data['employees'] = $employees;
    $data['search'] = $search;

    $data['departments']= HrDepartment::where('company_id', $userCompany)->pluck('dept_name','id');
    $data['designations']= HrDesignation::where('company_id', $userCompany)->pluck('designation_name','id');

    return view('hr.employees.index',$data);
}
</code>```

Title: Laravel - How to use a single textbox for global search

Body:
{{ Form::model(request(),['method'=>'get']) }}
         <div class="row" style="margin-bottom: 10px">

    <div orm-group class="col-sm-3">
         {{Form::label('search', 'Search')}}
         {{ Form::text('search',null,['class'=>'form-control','placeholder'=>'search']) }}

   </div>

  <div class="col-xs-3">
                <br>
      {{ Form::submit('Search',['class'=>'btn btn-warning']) }}

   </div>
{{ Form::close() }}

then your controller function use orwhere()

public function index(Request $request)
{
    $search = $request->search;
    $userCompany = Auth::user()->company_id;
    $render=[];
        $employees = HrEmployee::where('company_id', $userCompany);
        $employees=$employees->with('department','designation');
        $employees=$employees->where('employee_code','like','%'.$search.'%')
            ->orWhere('employee_designation_id',$search)
            ->orwhere('department_id',$search)
            ->paginate(6);
    $data['employees'] = $employees;
    $data['search'] = $search;

    $data['departments']= HrDepartment::where('company_id', $userCompany)->pluck('dept_name','id');
    $data['designations']= HrDesignation::where('company_id', $userCompany)->pluck('designation_name','id');

    return view('hr.employees.index',$data);
}


问:
kotlin 1.3 coroutine usage leads to ClassNotFoundException: kotlinx.coroutines.BuildersKt
I'm building a kotlin jvm project from the command line.

The plain kotlinc foo.kt -include-runtime -d example.jar and kotlin test.jar sequence works well.

However, I just used coroutines in my code for the first time, and the resulting messages led me to understand that I must include the coroutines jar file in the compilation.

```<code>kotlinc -include-runtime -classpath /snap/kotlin/current/lib/kotlinx-coroutines-core-1.0.1.jar -d example.jar example.kt
</code>```

The attempts to run it, both

```<code>kotlin example.jar
kotlin -classpath /snap/kotlin/current/lib/kotlinx-coroutines-core-1.0.1.jar example.jar
</code>```

say Exception in thread "main" java.lang.NoClassDefFoundError: kotlinx/coroutines/BuildersKt , which is vexing because the jarfile seems to hold those symbols:

```<code>$ unzip -l /snap/kotlin/current/lib/kotlinx-coroutines-core-1.0.1.jar |grep BuildersKt
     3687  2018-11-08 08:14   kotlinx/coroutines/BuildersKt.class
     8270  2018-11-08 08:14   kotlinx/coroutines/BuildersKt__Builders_commonKt.class
     3902  2018-11-08 08:14   kotlinx/coroutines/BuildersKt__BuildersKt.class
</code>```

Recall that kotlin Jarfile acts like java -jar Jarfile

```<code>$ java -classpath /snap/kotlin/current/lib/kotlinx-coroutines-core-1.0.1.jar -jar example.jar
Exception in thread "main" java.lang.NoClassDefFoundError: kotlinx/coroutines/BuildersKt
    at ExampleKt.main(example.kt:16)
Caused by: java.lang.ClassNotFoundException: kotlinx.coroutines.BuildersKt
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499)
    ... 1 more
</code>```

Without using gradle or such, can someone explain what one must specify to kotlin/java's command line to make it understand how to build or run with access to coroutine functionality? Thanks in advance!

答:
Edit example.jar's META-INF/MANIFEST.MF: add Class-Path with location of coroutines jar

```<code>Class-Path: /snap/kotlin/current/lib/kotlinx-coroutines-core-1.0.1.jar
</code>```

Then run: kotlin example.jar or java -jar example.jar

Body:
I'm building a kotlin jvm project from the command line.

The plain kotlinc foo.kt -include-runtime -d example.jar and kotlin test.jar sequence works well.

However, I just used coroutines in my code for the first time, and the resulting messages led me to understand that I must include the coroutines jar file in the compilation.

kotlinc -include-runtime -classpath /snap/kotlin/current/lib/kotlinx-coroutines-core-1.0.1.jar -d example.jar example.kt

The attempts to run it, both

kotlin example.jar
kotlin -classpath /snap/kotlin/current/lib/kotlinx-coroutines-core-1.0.1.jar example.jar

say Exception in thread "main" java.lang.NoClassDefFoundError: kotlinx/coroutines/BuildersKt , which is vexing because the jarfile seems to hold those symbols:

$ unzip -l /snap/kotlin/current/lib/kotlinx-coroutines-core-1.0.1.jar |grep BuildersKt
     3687  2018-11-08 08:14   kotlinx/coroutines/BuildersKt.class
     8270  2018-11-08 08:14   kotlinx/coroutines/BuildersKt__Builders_commonKt.class
     3902  2018-11-08 08:14   kotlinx/coroutines/BuildersKt__BuildersKt.class

Recall that kotlin Jarfile acts like java -jar Jarfile

$ java -classpath /snap/kotlin/current/lib/kotlinx-coroutines-core-1.0.1.jar -jar example.jar
Exception in thread "main" java.lang.NoClassDefFoundError: kotlinx/coroutines/BuildersKt
    at ExampleKt.main(example.kt:16)
Caused by: java.lang.ClassNotFoundException: kotlinx.coroutines.BuildersKt
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499)
    ... 1 more

Without using gradle or such, can someone explain what one must specify to kotlin/java's command line to make it understand how to build or run with access to coroutine functionality? Thanks in advance!

Body:
Edit example.jar's META-INF/MANIFEST.MF: add Class-Path with location of coroutines jar

Class-Path: /snap/kotlin/current/lib/kotlinx-coroutines-core-1.0.1.jar

Then run: kotlin example.jar or java -jar example.jar


问:
How to constrain an image on the canvas
I would like to draw an image 200x200 pixels on the canvas, and then do some other things to it. The image I have is 900x690, so ideally I would like to "center crop" the image to use an Android term. This video for some reason tells  us to use a FittedBox and then a SizedBox. I have also tried putting both of those in to a Container. I have tried setting the container size, the sized box size, and the customer painter Size to 200x200 and everything results in a full screen image. Who knows what I am doing wrong :)

Here is the code:

```<code>import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  ui.Image image;

  @override
  void initState() {
    super.initState();
    load('images/noodlejpg.jpg').then((i) {
      setState(() {
        image = i;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(backgroundColor: Colors.blue, title: Text('I am a title')),
      backgroundColor: Colors.teal,
      body: SafeArea(
        child: FittedBox(
          child: SizedBox(
            width: 200.0,
            height: 200.0,
            child: CustomPaint(
              painter: MyPainter(image),
            ),
          ),
        ),
      ),
    );
  }

  Future<ui.Image> load(String asset) async {
    ByteData data = await rootBundle.load(asset);
    ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List());
    ui.FrameInfo fi = await codec.getNextFrame();
    return fi.image;
  }
}

class MyPainter extends CustomPainter {
  ui.Image image;

  MyPainter(this.image);

  @override
  void paint(Canvas canvas, Size size) {
    var paint = new Paint();
    paint.blendMode = BlendMode.srcIn;
    paint.isAntiAlias = true;

    if (image != null) canvas.drawImage(image, Offset.zero, paint);
  }

  @override
  bool shouldRepaint(MyPainter oldDelegate) {
    return image != oldDelegate.image;
  }
}
</code>```

答:
Set image codec size: instantiateImageCodec function</p>

```<code>Future<Codec> instantiateImageCodec (
       Uint8List list,
       {int targetWidth,
       int targetHeight}
)
</code>```

Title: How to constrain an image on the canvas

Body:
I would like to draw an image 200x200 pixels on the canvas, and then do some other things to it. The image I have is 900x690, so ideally I would like to "center crop" the image to use an Android term. This video for some reason tells  us to use a FittedBox and then a SizedBox. I have also tried putting both of those in to a Container. I have tried setting the container size, the sized box size, and the customer painter Size to 200x200 and everything results in a full screen image. Who knows what I am doing wrong :)

Here is the code:

import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  ui.Image image;

  @override
  void initState() {
    super.initState();
    load('images/noodlejpg.jpg').then((i) {
      setState(() {
        image = i;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(backgroundColor: Colors.blue, title: Text('I am a title')),
      backgroundColor: Colors.teal,
      body: SafeArea(
        child: FittedBox(
          child: SizedBox(
            width: 200.0,
            height: 200.0,
            child: CustomPaint(
              painter: MyPainter(image),
            ),
          ),
        ),
      ),
    );
  }

  Future<ui.Image> load(String asset) async {
    ByteData data = await rootBundle.load(asset);
    ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List());
    ui.FrameInfo fi = await codec.getNextFrame();
    return fi.image;
  }
}

class MyPainter extends CustomPainter {
  ui.Image image;

  MyPainter(this.image);

  @override
  void paint(Canvas canvas, Size size) {
    var paint = new Paint();
    paint.blendMode = BlendMode.srcIn;
    paint.isAntiAlias = true;

    if (image != null) canvas.drawImage(image, Offset.zero, paint);
  }

  @override
  bool shouldRepaint(MyPainter oldDelegate) {
    return image != oldDelegate.image;
  }
}

Body:
Set image codec size: instantiateImageCodec function

Future<Codec> instantiateImageCodec (
       Uint8List list,
       {int targetWidth,
       int targetHeight}
)


问:
Extending MaterialCardView doesn't apply themes
According to the material specifications https://material.io/develop/android/components/material-card-view/ colorSurface applies to the card's Background color .

This works when we are specifying the card in our xml like this

```<code><com.google.android.material.card.MaterialCardView
    android:layout_width="100dp"
    android:layout_height="100dp"></com.google.android.material.card.MaterialCardView>
</code>```

When I run this I can see color surface properly being applied to the above card.

This also works if I make a card programmatically

```<code>addView(MaterialCardView(this).apply {
        layoutParams = ViewGroup.LayoutParams(300,300)
    })
</code>```

However once I extend from MaterialCardView to make my own custom view , it appears as if the theme connection to this is lost . The color surface is not applied rather the card defaults to white

```<code>class CustomView @JvmOverloads constructor(
    context: Context?,
    attributeSet: AttributeSet? = null,
    defStyleAttr: Int = 0
) : MaterialCardView(context, attributeSet, defStyleAttr){

}

<com.seed.formviewactivity.CustomView
        android:layout_width="100dp"
        android:layout_height="100dp"></com.seed.formviewactivity.CustomView>
</code>```

My CustomView now doesn't have the colorSurface applied.

Is this a known issue ?

答:
In your constructor you are using defStyleAttr: Int = 0.

You should apply the R.attr.materialCardViewStyle as default value instead of 0.

In this way your custom CardView will use the style defined in you app theme by materialCardViewStyle attribute.

The default value provided by the Material Components Library is:

```<code><style name="AppTheme" parent="Theme.MaterialComponents.DayNight">
  <!-- ... -->
  <item name="materialCardViewStyle">@style/Widget.MaterialComponents.CardView</item>
</style>
</code>```

Body:
According to the material specifications https://material.io/develop/android/components/material-card-view/ colorSurface applies to the card's Background color .

This works when we are specifying the card in our xml like this

<com.google.android.material.card.MaterialCardView
    android:layout_width="100dp"
    android:layout_height="100dp"></com.google.android.material.card.MaterialCardView>

When I run this I can see color surface properly being applied to the above card.

This also works if I make a card programmatically

addView(MaterialCardView(this).apply {
        layoutParams = ViewGroup.LayoutParams(300,300)
    })

However once I extend from MaterialCardView to make my own custom view , it appears as if the theme connection to this is lost . The color surface is not applied rather the card defaults to white

class CustomView @JvmOverloads constructor(
    context: Context?,
    attributeSet: AttributeSet? = null,
    defStyleAttr: Int = 0
) : MaterialCardView(context, attributeSet, defStyleAttr){

}

<com.seed.formviewactivity.CustomView
        android:layout_width="100dp"
        android:layout_height="100dp"></com.seed.formviewactivity.CustomView>

My CustomView now doesn't have the colorSurface applied.

Is this a known issue ?

Body:
In your constructor you are using defStyleAttr: Int = 0.

You should apply the R.attr.materialCardViewStyle as default value instead of 0.

In this way your custom CardView will use the style defined in you app theme by materialCardViewStyle attribute.

The default value provided by the Material Components Library is:

<style name="AppTheme" parent="Theme.MaterialComponents.DayNight">
  <!-- ... -->
  <item name="materialCardViewStyle">@style/Widget.MaterialComponents.CardView</item>
</style>


问:
How do I fix maven error The JAVA_HOME environment variable is not defined correctly?
Issue:

I am getting the Maven error "The JAVA_HOME environment variable is not defined correctly" when I run through Inno setup batch execution. However, I am able to run successfully outside Inno Setup.(e.g Command line, Batch file, Vbs). I am clueless to identify the issue.

Inno Setup Invoked Prompt:

```<code>C:\>mvn -version
The JAVA_HOME environment variable is not defined correctly
This environment variable is needed to run this program
NB: JAVA_HOME should point to a JDK not a JRE
</code>```

Regular Command Prompt:

```<code>C:\>mvn -version
C:\
Apache Maven 3.5.0 (ff8f5e7444045639af65f6095c62210b5713f426; 2017-04-04T01:09:06+05:30)
Maven home: C:\Program Files\apache-maven-3.5.0\bin\..
Java version: 1.8.0_131, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk1.8.0_131\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 7", version: "6.1", arch: "amd64", family: "windows"
</code>```

Maven Command from InnoSetup:

```<code>[Files]
Source: "C:\@Setup\MavenInstaller.bat"; DestDir: "{tmp}"; Flags: ignoreversion
[Run]
Filename: "{cmd}"; Parameters: "/C ""{tmp}\MavenInstaller.bat"""
</code>```

Maven Command from Batch File:

```<code>mvn archetype:generate -DgroupId=com.mycompany.mycomponent-DartifactId=%APPLICATION_NAME% -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
</code>```

Setting JAVA_HOME

Check the If Java 1.8 is installed or not. If not installed, Install the same and set the JAVA HOME as follows.

```<code>SETX JAVA_HOME "C:\Program Files\Java\jdk1.8.0_131"
SETX -m JAVA_HOME "C:\Program Files\Java\jdk1.8.0_131"
REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path /t REG_SZ /d "%path%;C:\Program Files\Java\jdk1.8.0_131\bin;" /f
</code>```

Many Thanks.

答:
```<code>SET JAVA_HOME=C:\Program Files\Java\jdk1.8.0
</code>```

worked fine for me.

Note - Don't put double quotes over the path as mentioned above. Otherwise when you run

```<code>mvn -version
</code>```

it will give following error

Files\java\jdk1.8.0_201\jre""=="" was unexpected at this time.

Body:
Issue:

I am getting the Maven error "The JAVA_HOME environment variable is not defined correctly" when I run through Inno setup batch execution. However, I am able to run successfully outside Inno Setup.(e.g Command line, Batch file, Vbs). I am clueless to identify the issue.

Inno Setup Invoked Prompt:

C:\>mvn -version
The JAVA_HOME environment variable is not defined correctly
This environment variable is needed to run this program
NB: JAVA_HOME should point to a JDK not a JRE

Regular Command Prompt:

C:\>mvn -version
C:\
Apache Maven 3.5.0 (ff8f5e7444045639af65f6095c62210b5713f426; 2017-04-04T01:09:06+05:30)
Maven home: C:\Program Files\apache-maven-3.5.0\bin\..
Java version: 1.8.0_131, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk1.8.0_131\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 7", version: "6.1", arch: "amd64", family: "windows"

Maven Command from InnoSetup:

[Files]
Source: "C:\@Setup\MavenInstaller.bat"; DestDir: "{tmp}"; Flags: ignoreversion
[Run]
Filename: "{cmd}"; Parameters: "/C ""{tmp}\MavenInstaller.bat"""

Maven Command from Batch File:

mvn archetype:generate -DgroupId=com.mycompany.mycomponent-DartifactId=%APPLICATION_NAME% -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Setting JAVA_HOME

Check the If Java 1.8 is installed or not. If not installed, Install the same and set the JAVA HOME as follows.

SETX JAVA_HOME "C:\Program Files\Java\jdk1.8.0_131"
SETX -m JAVA_HOME "C:\Program Files\Java\jdk1.8.0_131"
REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path /t REG_SZ /d "%path%;C:\Program Files\Java\jdk1.8.0_131\bin;" /f

Many Thanks.

Body:
SET JAVA_HOME=C:\Program Files\Java\jdk1.8.0

worked fine for me.

Note - Don't put double quotes over the path as mentioned above. Otherwise when you run

mvn -version

it will give following error

Files\java\jdk1.8.0_201\jre""=="" was unexpected at this time.


问:
How to use Identity in ASP .NET Core 3.1 without EF Core?
I have a project in ASP.NET Core 3.1 and I want to implement Identity to my application. I've found a lot of examples with EF Core, but I'm using LinqConnect (Devart) instead of EF Core and database  - SQL Server.
I'm wondering how to implement identity to my project in a simple way.</p>

答:
Basically all you need to do is to create your custom user store.

public class CustomUserStore : IUserStore<IdentityUser>,
                               IUserClaimStore<IdentityUser>,
                               IUserLoginStore<IdentityUser>,
                               IUserRoleStore<IdentityUser>,
                               IUserPasswordStore<IdentityUser>,
                               IUserSecurityStampStore<IdentityUser>
{
    // interface implementations not shown
}
```

<p>And then inject it :</p>

<pre class="lang-cs prettyprint-override"><code>public void ConfigureServices(IServiceCollection services)
{
    // Add identity types
    services.AddIdentity<ApplicationUser, ApplicationRole>()
        .AddDefaultTokenProviders();

    // Identity Services
    services.AddTransient<IUserStore<ApplicationUser>, CustomUserStore>();
    string connectionString = Configuration.GetConnectionString("DefaultConnection");
    services.AddTransient<SqlConnection>(e => new SqlConnection(connectionString));
    services.AddTransient<DapperUsersTable>();

    // additional configuration
}
</code>```

It is documented in the official documentation.

Body:
Basically all you need to do is to create your custom user store.

public class CustomUserStore : IUserStore<IdentityUser>,
                               IUserClaimStore<IdentityUser>,
                               IUserLoginStore<IdentityUser>,
                               IUserRoleStore<IdentityUser>,
                               IUserPasswordStore<IdentityUser>,
                               IUserSecurityStampStore<IdentityUser>
{
    // interface implementations not shown
}

And then inject it :

public void ConfigureServices(IServiceCollection services)
{
    // Add identity types
    services.AddIdentity<ApplicationUser, ApplicationRole>()
        .AddDefaultTokenProviders();

    // Identity Services
    services.AddTransient<IUserStore<ApplicationUser>, CustomUserStore>();
    string connectionString = Configuration.GetConnectionString("DefaultConnection");
    services.AddTransient<SqlConnection>(e => new SqlConnection(connectionString));
    services.AddTransient<DapperUsersTable>();

    // additional configuration
}

It is documented in the official documentation.


问:
Is there a way to use Nadam optimizer on scikit-learn MLPClassifier?
I'm trying to use diferent optimizers for an scikit-learn's MLPClassifier. As far as their docs show, there is only a few solvers(MLPClassifier's optimizer parameter) available, which are:

‘lbfgs’ is an optimizer in the family of quasi-Newton methods.

‘sgd’ refers to stochastic gradient descent.

‘adam’ refers to a stochastic gradient-based optimizer proposed by Kingma, Diederik, and Jimmy Ba

What I'm trying to use is another one called Nadam. I've tried to mix some parameters to achieve it with solver='adam' and nesterovs_momentum=True, but sklearn's docs says that the last parameter is only used for sgd:

Whether to use Nesterov’s momentum. Only used when solver=’sgd’ and momentum > 0.

I've tried the above because I've thought that meant what keras's nadam stated:

Much like Adam is essentially RMSprop with momentum, Nadam is RMSprop with Nesterov momentum.

Because of all this, I don't think I'm doing the right thing. My code below shows what I've done so far.

from sklearn.neural_network import MLPClassifier
clf = MLPClassifier(solver='adam', nesterovs_momentum=True,)
```

答:
You cannot supply nesterovs_momentum to adam optimizer.

To see this you should have a look at BaseMultilayerPerceptron code on github.

Compare the params accepted by SGDOptimizer with those accepted by AdamOptimizer.

You will see that adam simply doesn't accept nesterovs_momentum.


问:
Vs Code unable to install extension if I don't run vs code as root
In macOS, my Vs Code can't read my extensions if I don't run it as root user.

It happened after I changed owner of /Applications/Visual Studio Code.app/Contents/MacOS/Electron to install an extension called 'Custom CSS and JS Loader'. I don't what is correct permission here, I don't want to reinstall Vs Code currently.

If I run

ll /Applications/Visual\ Studio\ Code.app/Contents/MacOS

I got this output

-rwxr-xr-x  1 xyh  wheel   221K Nov 13 09:01 Electron

Hope to get some help. Thanks !

答:
For me, the output to that ll is:

-rwxr-xr-x  1 bobvork  staff   221K Feb 11 06:56 Electron

I had a similar problem recently, where I installed an extension while running as root. I found that ~/.vscode/extensions contained a file called .obsolete that was owned by root. I just deleted the file, ran VS Code again and it was fixed.

Hope this helps you (or someone else)


问:
Does Webpack tree-shake by default when building production React project?
I'm learning React and want to know if Webpack tree-shakes a React project by default when we do npm run build to create the production version of the project?

答:
Yes it does. You can view the built application in the build/ folder.

If you look at some of those .js files you will see they look quite different from your source contents. Your source will be tree-shaken and minified.


问:
TypeError: 'Pagination' object is not iterable in Flask
I have a table with data(s). I want to get the result set with pagination in API response.

I am using the GET method to call API. Here is the

Requirement:

Need to page number and number of data

pagination data with previous and next URL(s)

My Code :

```<code>@api.route('/', methods=["GET"])
@app.route('/page/<int:page>')
class List(Resource):
    """USER data(s)"""

    def get(self, page=1):
        """GET Lists"""
        all_data = User.query.paginate(page, per_page=2)
        result = user_serializer.dump(all_data)
        return result
</code>```

Issue:

TypeError: 'Pagination' object is not iterable in Flask

答:
The issue with your code is you are trying to pass the Pagination object to your serializer. Instead what the serializer expects is either a list of model instances or a single model instance. Just change your call to this

```<code>result = user_serializer.dump(all_data.items)
</code>```

Sources

https://flask-sqlalchemy.palletsprojects.com/en/2.x/api/#flask_sqlalchemy.Pagination

Body:
I have a table with data(s). I want to get the result set with pagination in API response.

I am using the GET method to call API. Here is the

Requirement:

Need to page number and number of data

pagination data with previous and next URL(s)

My Code :

@api.route('/', methods=["GET"])
@app.route('/page/<int:page>')
class List(Resource):
    """USER data(s)"""

    def get(self, page=1):
        """GET Lists"""
        all_data = User.query.paginate(page, per_page=2)
        result = user_serializer.dump(all_data)
        return result

Issue:

TypeError: 'Pagination' object is not iterable in Flask

Body:
The issue with your code is you are trying to pass the Pagination object to your serializer. Instead what the serializer expects is either a list of model instances or a single model instance. Just change your call to this

result = user_serializer.dump(all_data.items)

Sources

https://flask-sqlalchemy.palletsprojects.com/en/2.x/api/#flask_sqlalchemy.Pagination


问:
Make lambda non-copyable/non-movable
Consider the following code:

```<code>#include <iostream>
#include <thread>

int main() {
    std::thread t;
    const auto l = [x = std::move(t)]{};
    decltype(l) m = std::move(l);
}
</code>```

This code doesn't compile with the following messages:

```<code>prog.cc: In function 'int main()':
prog.cc:7:32: error: use of deleted function 'main()::<lambda()>::<lambda>(const main()::<lambda()>&)'
    7 |     decltype(l) m = std::move(l);
      |                                ^
prog.cc:6:37: note: 'main()::<lambda()>::<lambda>(const main()::<lambda()>&)' is implicitly deleted because the default definition would be ill-formed:
    6 |     const auto l = [x = std::move(t)]{};
      |                                     ^
prog.cc:6:37: error: use of deleted function 'std::thread::thread(const std::thread&)'
In file included from prog.cc:2:
/opt/wandbox/gcc-head/include/c++/10.0.1/thread:154:5: note: declared here
  154 |     thread(const thread&) = delete;
      |     ^~~~~~
</code>```

Is there a way to make lambda non-copyable or non-movable without explicit capturing an any non-copyable variable (i.e. leaving [] empty)?

答:
You can write a simple enveloping aggregate that will prevent the move and copy.

```<code>struct NoCopyMove {
    NoCopyMove(NoCopyMove const&) = delete;
    NoCopyMove(NoCopyMove&&)      = delete;

    void operator=(NoCopyMove const&) = delete;
    void operator=(NoCopyMove&&)      = delete;
};

template<class Functor>
struct Fixed : Functor, NoCopyMove {
    using Functor::operator();
};

template<typename F>
Fixed (F&&) -> Fixed<std::decay_t<F>>;
</code>```

To be used like this

```<code>const auto l = Fixed{[]{}};
</code>```

NoCopyMove is a simple mixin that disables copying and moving. Writing it this way allows us to keep the specializations of Fixed as simple aggregates.

All Fixed does is inherit/initialize as base (with guaranteed copy elision when possible) the functor it's being given as an argument. And then expose its operator().

Since there are no members involved (other then maybe in Functor), and since a lambda cannot possibly inherit from our custom NoCopyMove class, the empty base optimization kicks in for stateless lambdas. So objects are not expected to be any larger than the lambda you initialize them with.

Title: Make lambda non-copyable/non-movable

Body:
Consider the following code:

#include <iostream>
#include <thread>

int main() {
    std::thread t;
    const auto l = [x = std::move(t)]{};
    decltype(l) m = std::move(l);
}

This code doesn't compile with the following messages:

prog.cc: In function 'int main()':
prog.cc:7:32: error: use of deleted function 'main()::<lambda()>::<lambda>(const main()::<lambda()>&)'
    7 |     decltype(l) m = std::move(l);
      |                                ^
prog.cc:6:37: note: 'main()::<lambda()>::<lambda>(const main()::<lambda()>&)' is implicitly deleted because the default definition would be ill-formed:
    6 |     const auto l = [x = std::move(t)]{};
      |                                     ^
prog.cc:6:37: error: use of deleted function 'std::thread::thread(const std::thread&)'
In file included from prog.cc:2:
/opt/wandbox/gcc-head/include/c++/10.0.1/thread:154:5: note: declared here
  154 |     thread(const thread&) = delete;
      |     ^~~~~~

Is there a way to make lambda non-copyable or non-movable without explicit capturing an any non-copyable variable (i.e. leaving [] empty)?

Body:
You can write a simple enveloping aggregate that will prevent the move and copy.

struct NoCopyMove {
    NoCopyMove(NoCopyMove const&) = delete;
    NoCopyMove(NoCopyMove&&)      = delete;

    void operator=(NoCopyMove const&) = delete;
    void operator=(NoCopyMove&&)      = delete;
};

template<class Functor>
struct Fixed : Functor, NoCopyMove {
    using Functor::operator();
};

template<typename F>
Fixed (F&&) -> Fixed<std::decay_t<F>>;

To be used like this

const auto l = Fixed{[]{}};

NoCopyMove is a simple mixin that disables copying and moving. Writing it this way allows us to keep the specializations of Fixed as simple aggregates.

All Fixed does is inherit/initialize as base (with guaranteed copy elision when possible) the functor it's being given as an argument. And then expose its operator().

Since there are no members involved (other then maybe in Functor), and since a lambda cannot possibly inherit from our custom NoCopyMove class, the empty base optimization kicks in for stateless lambdas. So objects are not expected to be any larger than the lambda you initialize them with.


问:
Eclipse not updating dependency JARs in web deployment
In eclipse, I have a project, say ProjectA, which is a dynamic web module. ProjectB is a library used by ProjectA. I have added ProjectB to ProjectA's web deployment assembly, with the deploy path /WEB-INF/lib/ProjectB.jar.

When I deploy ProjectA onto a Tomcat v6.0 server, everything works fine. However, if I make any changes to ProjectB, no matter what I do, these changes don't seem to be picked up by the deployment.

I have tried the following options Project->Clean... from the main menu, and Clean Module Work Directory... from the server's context menu, but neither works. The only thing that seems to work is deleting the Project, then re-importing it into Eclipse.

Any ideas would be greatly appreciated!

Thanks

答: Have you checked that Eclipse recognizes ProjectB.jar as a dependency from Project->Properties->Java Build Path? In general, it should show up there. I'm not sure about your exact situation though.</p>