问:
How to create a picture that fills in colours based on a matrix?
I have a cell array in MATLAB in the following format:

```<code>aa = {[1 2],[2 3],[1 2 3 4 5 6],[5],[1]}
</code>```

Is it possible to create a diagram in this style (i.e. filling in a block colour for each time a number shows up)?

答:
Since you have vectors with varying lengths in your cell array, you'll need to iterate those in some loop (or alike, see cellfun used below). The rest is initializing some matrix with your desired background value, and set all "pixels" inside that matrix to your desired foreground value.

Here's a small code snippet (tested with Octave 5.1.0 and MATLAB Online):

aa = {[1 2], [2 3], [1 2 3 4 5 6], [5], [1]}

% Determine needed number of rows and columns
r = size(aa, 2);
c = max(cellfun(@max, aa));

% Initialize and fill matrix
A = 255 * ones(r, c);
for I = 1:r
  A(I, aa{I}) = 128;
end

% Show matrix with some colormap and labels
figure('Position', [300, 300, 800, 400]);
imagesc(A, [0, 255]);
colormap('hot');
set(gca, ...
  'FontSize', 12, ...
  'TickLength', [0 0], ...
  'XTick', [1:c], ...
  'XTickLabel', [repmat('V', c, 1) num2str([1:c].')], ...
  'YTick', [], ...
  'XAxisLocation', 'Top');
```

The result looks like this:

(Instead of setting proper colors, I just used some grayscale image with a colormap here.)

Hope that helps!

Body:
I have a cell array in MATLAB in the following format:

aa = {[1 2],[2 3],[1 2 3 4 5 6],[5],[1]}

Is it possible to create a diagram in this style (i.e. filling in a block colour for each time a number shows up)?

Body:
Since you have vectors with varying lengths in your cell array, you'll need to iterate those in some loop (or alike, see cellfun used below). The rest is initializing some matrix with your desired background value, and set all "pixels" inside that matrix to your desired foreground value.

Here's a small code snippet (tested with Octave 5.1.0 and MATLAB Online):

aa = {[1 2], [2 3], [1 2 3 4 5 6], [5], [1]}

% Determine needed number of rows and columns
r = size(aa, 2);
c = max(cellfun(@max, aa));

% Initialize and fill matrix
A = 255 * ones(r, c);
for I = 1:r
  A(I, aa{I}) = 128;
end

% Show matrix with some colormap and labels
figure('Position', [300, 300, 800, 400]);
imagesc(A, [0, 255]);
colormap('hot');
set(gca, ...
  'FontSize', 12, ...
  'TickLength', [0 0], ...
  'XTick', [1:c], ...
  'XTickLabel', [repmat('V', c, 1) num2str([1:c].')], ...
  'YTick', [], ...
  'XAxisLocation', 'Top');

The result looks like this:

(Instead of setting proper colors, I just used some grayscale image with a colormap here.)

Hope that helps!


来源: stackexchange

问:
Actionscript flash.filesystem
I made an mp3 player that populates a list with filenames from an xml file but I want to be able to display the contents of a folder in a list. basically populate the list from a directory insread of from the xml.</p>

答: Flash doesn't allow you to access the local file system in that way. You should look into AIR, as it allows you to do this type of thing. Since AIR is also AS3 based, you won't need to change much code at all, if any. You'll just need to implement the local storage access part.</p>

ContentLicense: CC BY-SA 3.0

Title: Actionscript flash.filesystem


问:
How can i TextField show cursor always
I want show cursor always in textfield but i couldn't see a solution.
What I want to do is always show the cursor like whatsapp.
I want the cursor to appear even if the keyboard is closed</p>

```<code>TextField(
  textCapitalization:TextCapitalization.sentences,
  minLines: 1,
  maxLines: 6,
  controller: _textEditingController,
  focusNode: _focusNode,
)
</code>```

答:
```<code>TextField(
  textCapitalization:TextCapitalization.sentences,
  minLines: 1,
  maxLines: 6,
  autofocus: true,                            // line Added
  controller: _textEditingController,
  focusNode: _focusNode,
)
</code>```

ContentLicense: CC BY-SA 4.0

Title: How can i TextField show cursor always

Body:
I want show cursor always in textfield but i couldn't see a solution.
What I want to do is always show the cursor like whatsapp.
I want the cursor to appear even if the keyboard is closed

TextField(
  textCapitalization:TextCapitalization.sentences,
  minLines: 1,
  maxLines: 6,
  controller: _textEditingController,
  focusNode: _focusNode,
)


问:
window.location removed the token from localStorage
```<code>login(data){
    let appUrl = process.env.MIX_APP_PRO + process.env.MIX_APP_URL;
    axios.post('/api/auth/login', data)
    .then(res => {
        this.responseAfterLogin(res)
    })
    .then(dat => {
       let appUrl = '/hub';
       window.location = appUrl;
    })
    .catch(function(error){
        if(error.response){
            Exception.handle(error.response.data)
        }
    })
}
</code>```

```<code>responseAfterLogin(res){
    const access_token = res.data.access_token;
        const username = res.data.user;
        if(Token.isValid(access_token)){
            AppStorage.store(username, access_token);
        }
    }
}
</code>```

Above are the functions that I am using in order to login a user in to my system and storing the access token to localStorage, The issue however is when user is redirected after successfull login the token some how get deleted from local storage.

Please Help.

```<code>import Token from "./Token";

class AppStorage{
    storeToken(token){
        window.localStorage.setItem('token', token);
    }

    storeUser(user){
        window.localStorage.setItem('user', user);
    }

    store(user, token){
        this.storeToken(token);
        this.storeUser(user);
    }

    clear(){
        window.localStorage.removeItem('user');
        window.localStorage.removeItem('token');
    }

    getToken(){
        return window.localStorage.getItem('token');
    }

    getUser(){
        return window.localStorage.getItem('user');
    }

}

export default AppStorage = new AppStorage()
</code>```

This is App storage class I am using to store and retrieve values in localStorage.

答:
Guys this problem was solved, it was my mistake.

When I uploaded the site on the server I need to generate key for JWT key on time of installation of JWT Modules, which I didn't.

So the user was not logging in properly thats why token was being removed form localStorage as result of un-successful authentication.

Thanks for all the help guys.

Body:
login(data){
    let appUrl = process.env.MIX_APP_PRO + process.env.MIX_APP_URL;
    axios.post('/api/auth/login', data)
    .then(res => {
        this.responseAfterLogin(res)
    })
    .then(dat => {
       let appUrl = '/hub';
       window.location = appUrl;
    })
    .catch(function(error){
        if(error.response){
            Exception.handle(error.response.data)
        }
    })
}

responseAfterLogin(res){
    const access_token = res.data.access_token;
        const username = res.data.user;
        if(Token.isValid(access_token)){
            AppStorage.store(username, access_token);
        }
    }
}

Above are the functions that I am using in order to login a user in to my system and storing the access token to localStorage, The issue however is when user is redirected after successfull login the token some how get deleted from local storage.

Please Help.

import Token from "./Token";

class AppStorage{
    storeToken(token){
        window.localStorage.setItem('token', token);
    }

    storeUser(user){
        window.localStorage.setItem('user', user);
    }

    store(user, token){
        this.storeToken(token);
        this.storeUser(user);
    }

    clear(){
        window.localStorage.removeItem('user');
        window.localStorage.removeItem('token');
    }

    getToken(){
        return window.localStorage.getItem('token');
    }

    getUser(){
        return window.localStorage.getItem('user');
    }

}

export default AppStorage = new AppStorage()

This is App storage class I am using to store and retrieve values in localStorage.


问:
eclipse + ddms - don't copy timestamp etc from ddms logs?
I'm using the eclipse plugin for android development. When I copy/paste log contents from ddms, I always get the timestamp etc in the copy/paste:

```<code>05-16 21:43:09.082: INFO/ActivityManager(110): [message text]
05-16 21:43:09.152: INFO/ActivityManager(110): [message text]
...
</code>```

Is there any way to clip the timestamp + debug level + pid from the paste as seen above, and only get the [message text] copied? It just gets annoying sometimes when sending log details to others as it's a bit noisy for them to look at,

Thanks

答:
Write a 5 line program to remove the first 20 characters of each line to remove the timestamp,
or use line.split(" ") to remove the first 3 parts.

Or use a text editor with block selection such as TextPad

Body:
I'm using the eclipse plugin for android development. When I copy/paste log contents from ddms, I always get the timestamp etc in the copy/paste:

05-16 21:43:09.082: INFO/ActivityManager(110): [message text]
05-16 21:43:09.152: INFO/ActivityManager(110): [message text]
...

Is there any way to clip the timestamp + debug level + pid from the paste as seen above, and only get the [message text] copied? It just gets annoying sometimes when sending log details to others as it's a bit noisy for them to look at,

Thanks


问:
Delete duplicate rows with an order by
I have this table:

I want to delete duplicate rows in that table based on different STATUSIN
and this is my query to duplicate rows:

```<code>;WITH CTE AS
(
   SELECT ID,NIP, ROW_NUMBER()OVER(PARTITION BY STATUSIN ORDER BY STATUSIN) AS RowNumber
   FROM DAILYDATAWH
), CTE2 AS
(
SELECT TOP (1000) *
    FROM CTE
    ORDER BY RowNumber DESC
    )
    DELETE FROM CTE2 WHERE RowNumber > 1
</code>```

and this is the output:

how to delete duplicate rows and show the output like this:

答:
Your code includes:

PARTITION BY STATUSIN ORDER BY STATUSIN

Having the same columns in the partition by and order by makes no sense. You say:

I want to delete duplicate rows in that table based on different
  STATUSIN

Good, you have defined what the ORDER BY should be. This decides which row to keep among duplicates.

The PARTITION BY part must includes the columns that define which columns are duplicate. A guess would be NIP,NAME, but you have to decide for yourself. So try something like this:

ROW_NUMBER() OVER(PARTITION BY NIP,NAME ORDER BY STATUSIN) AS RowNumber

The rest of the code seems ok to me.

Title: Delete duplicate rows with an order by

Body:
I have this table:

I want to delete duplicate rows in that table based on different STATUSIN
and this is my query to duplicate rows:

;WITH CTE AS
(
   SELECT ID,NIP, ROW_NUMBER()OVER(PARTITION BY STATUSIN ORDER BY STATUSIN) AS RowNumber
   FROM DAILYDATAWH
), CTE2 AS
(
SELECT TOP (1000) *
    FROM CTE
    ORDER BY RowNumber DESC
    )
    DELETE FROM CTE2 WHERE RowNumber > 1

and this is the output:

how to delete duplicate rows and show the output like this:


问:
Adding an attribute to configure Decimal precision in Entity Framework Core
I had the following attribute property for my EF 6 .Net Framework app:

```<code>[AttributeUsage(AttributeTargets.Property)]
public sealed class DecimalPrecisionAttribute : Attribute
{
    public DecimalPrecisionAttribute(Byte precision, Byte scale)
    {
        Precision = precision;
        Scale = scale;
    }

    public Byte Precision { get; set; }
    public Byte Scale { get; set; }
}

public class DecimalPrecisionAttributeConvention
    : PrimitivePropertyAttributeConfigurationConvention<DecimalPrecisionAttribute>
{
    public override void Apply(
        ConventionPrimitivePropertyConfiguration configuration,
        DecimalPrecisionAttribute attribute)
    {
        if (attribute.Precision < 1 || attribute.Precision > 38)
        {
            throw new InvalidOperationException("Precision must be between 1 and 38.");
        }

        if (attribute.Scale > attribute.Precision)
        {
            throw new InvalidOperationException(
                "Scale must be between 0 and the Precision value.");
        }

        configuration.HasPrecision(attribute.Precision, attribute.Scale);
    }
}
</code>```

Then in my DbContext:

```<code>    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Add(new DecimalPrecisionAttributeConvention());
        base.OnModelCreating(modelBuilder);
    }
</code>```

This allowed me to set the precision on properties on my POCO's:

```<code>[DecimalPrecision(5,2)]
public Decimal WeirdNumber { get; set; }
</code>```

But I am having trouble puzzling out how to do this for EF Core.

Is there an equivalent in .Core?

I have comme up with the following:

```<code>public static class DecimalPrecisionAttributeConvention
{
    public static void ApplyToTable(IMutableEntityType table)
    {
        foreach (var col in table.GetProperties())
        {
            var attribute = col
                ?.PropertyInfo
                ?.GetCustomAttributes<DecimalPrecisionAttribute>()
                ?.FirstOrDefault();

            if (attribute == null)
            {
                continue;
            }

            if (attribute.Precision < 1 || attribute.Precision > 38)
            {
                throw new InvalidOperationException("Precision must be between 1 and 38.");
            }

            if (attribute.Scale > attribute.Precision)
            {
                throw new InvalidOperationException(
                    "Scale must be between 0 and the Precision value.");
            }

            col.Relational().ColumnType =
                $"decimal({attribute.Precision}, {attribute.Scale})";
        }
    }
}
</code>```

And thin my my on model create:

```<code>    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        foreach (var table in modelBuilder.Model.GetEntityTypes())
        {
            DecimalPrecisionAttributeConvention.ApplyToTable(table);
        }
    }
</code>```

Is the the best way to accomplish this?

答:
For EntityFrameworkCore, I use this solution. In your DbContext, override OnModelCreating method:

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            // Set default precision to decimal property
            foreach (var property in modelBuilder.Model.GetEntityTypes()
                .SelectMany(t => t.GetProperties())
                .Where(p => p.ClrType == typeof(decimal) || p.ClrType == typeof(decimal?)))
            {
                property.SetColumnType("decimal(18, 2)");
            }
        }
</code>```

Hope this helps.

Body:
I had the following attribute property for my EF 6 .Net Framework app:

[AttributeUsage(AttributeTargets.Property)]
public sealed class DecimalPrecisionAttribute : Attribute
{
    public DecimalPrecisionAttribute(Byte precision, Byte scale)
    {
        Precision = precision;
        Scale = scale;
    }

    public Byte Precision { get; set; }
    public Byte Scale { get; set; }
}

public class DecimalPrecisionAttributeConvention
    : PrimitivePropertyAttributeConfigurationConvention<DecimalPrecisionAttribute>
{
    public override void Apply(
        ConventionPrimitivePropertyConfiguration configuration,
        DecimalPrecisionAttribute attribute)
    {
        if (attribute.Precision < 1 || attribute.Precision > 38)
        {
            throw new InvalidOperationException("Precision must be between 1 and 38.");
        }

        if (attribute.Scale > attribute.Precision)
        {
            throw new InvalidOperationException(
                "Scale must be between 0 and the Precision value.");
        }

        configuration.HasPrecision(attribute.Precision, attribute.Scale);
    }
}

Then in my DbContext:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Add(new DecimalPrecisionAttributeConvention());
        base.OnModelCreating(modelBuilder);
    }

This allowed me to set the precision on properties on my POCO's:

[DecimalPrecision(5,2)]
public Decimal WeirdNumber { get; set; }

But I am having trouble puzzling out how to do this for EF Core.

Is there an equivalent in .Core?

I have comme up with the following:

public static class DecimalPrecisionAttributeConvention
{
    public static void ApplyToTable(IMutableEntityType table)
    {
        foreach (var col in table.GetProperties())
        {
            var attribute = col
                ?.PropertyInfo
                ?.GetCustomAttributes<DecimalPrecisionAttribute>()
                ?.FirstOrDefault();

            if (attribute == null)
            {
                continue;
            }

            if (attribute.Precision < 1 || attribute.Precision > 38)
            {
                throw new InvalidOperationException("Precision must be between 1 and 38.");
            }

            if (attribute.Scale > attribute.Precision)
            {
                throw new InvalidOperationException(
                    "Scale must be between 0 and the Precision value.");
            }

            col.Relational().ColumnType =
                $"decimal({attribute.Precision}, {attribute.Scale})";
        }
    }
}

And thin my my on model create:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        foreach (var table in modelBuilder.Model.GetEntityTypes())
        {
            DecimalPrecisionAttributeConvention.ApplyToTable(table);
        }
    }

Is the the best way to accomplish this?

Body:
For EntityFrameworkCore, I use this solution. In your DbContext, override OnModelCreating method:

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            // Set default precision to decimal property
            foreach (var property in modelBuilder.Model.GetEntityTypes()
                .SelectMany(t => t.GetProperties())
                .Where(p => p.ClrType == typeof(decimal) || p.ClrType == typeof(decimal?)))
            {
                property.SetColumnType("decimal(18, 2)");
            }
        }

Hope this helps.


问:
Python 3: extract files from tar.gz archive
I'm currently working with Semantically Enriched Wikipedia.

The resource is inside a 7.5 GB tar.gz archive and each file inside it, it's an XML whose schema is:

```<code><text>
       Plain text
</text>

<annotation>
       Annotation for plain text
</annotation>
</code>```

The current task is to extract each file and then parse the content inside the tags.

First thing I did was to use the tarfile module and its extractall() method, but during the extraction I got this error:

OSError: [Errno 22] Invalid argument: '.\\sew_conservative\\wiki384\\Live_%3F%21*%40_Like_a_Suicide.xml'

while a part of it is correctly extracted (I thought the error was due to the unicode char inside the xml file name, but I'm now seeing that each file has it inside).

So I planned to work on each file inside the archive using some of the API's methods and the code below.

Unfortunately, the TarInfo object which wraps each file doesn't allow to access the file content and the extraction, file by file, takes too much time.

```<code>def parse_sew():
    sew_path = Path("C:/Users/beppe/Desktop/Tesi/Semantically Enriched Wikipedia/sew_conservative.tar.gz")
    with tarfile.open(sew_path, mode='r') as t:
        for item in t:
           // extraction

</code>```

Is the extraction mandatory to parse and use the content of the XML file or it's possible to read the archive content (on-the-fly, without extracting anything) and then parse the content?

UPDATE: I'm extracting the files via tar -xvzf filename.tar.gz command, everything is going well, but after 15 mins I was able to process only 500MB of the hundred GB.

答:
I would suggest you to use 7zip for extraction. You can initiate 7zip extraction from python and then while it is extracting side by side you can read the files getting extracted. This will save quite a lot of time. You can implement is using threads.

Secondly dont use front slashes while giving windows path. You can use \\ in place of /.

Body:
I'm currently working with Semantically Enriched Wikipedia.

The resource is inside a 7.5 GB tar.gz archive and each file inside it, it's an XML whose schema is:

<text>
       Plain text
</text>

<annotation>
       Annotation for plain text
</annotation>

The current task is to extract each file and then parse the content inside the tags.

First thing I did was to use the tarfile module and its extractall() method, but during the extraction I got this error:

OSError: [Errno 22] Invalid argument: '.\\sew_conservative\\wiki384\\Live_%3F%21*%40_Like_a_Suicide.xml'

while a part of it is correctly extracted (I thought the error was due to the unicode char inside the xml file name, but I'm now seeing that each file has it inside).

So I planned to work on each file inside the archive using some of the API's methods and the code below.

Unfortunately, the TarInfo object which wraps each file doesn't allow to access the file content and the extraction, file by file, takes too much time.

def parse_sew():
    sew_path = Path("C:/Users/beppe/Desktop/Tesi/Semantically Enriched Wikipedia/sew_conservative.tar.gz")
    with tarfile.open(sew_path, mode='r') as t:
        for item in t:
           // extraction

Is the extraction mandatory to parse and use the content of the XML file or it's possible to read the archive content (on-the-fly, without extracting anything) and then parse the content?

UPDATE: I'm extracting the files via tar -xvzf filename.tar.gz command, everything is going well, but after 15 mins I was able to process only 500MB of the hundred GB.


问:
Does Vim have indentation guides, Notepad++-style?
In Notepad++, there is a dotted line that runs down from the function keyword through the end of the method. It looks like this:

Does Vim support something similar?

答:
You can also just use tabs for indentation and display them visually with the line

```<code>"Attention:
"There is an invisible space at the end of the line.
"This space is required.
set list lcs=tab:\|\
</code>```

The plus side of this method is, that you can easily tell tabs and spaces apart.

Personally, I prefer using the unicode center dot character (set list lcs=tab:\·\) instead of the pipe symbol, but the pipe symbol is closer to the Notepad++ optic.

Body:
You can also just use tabs for indentation and display them visually with the line

"Attention:
"There is an invisible space at the end of the line.
"This space is required.
set list lcs=tab:\|\

The plus side of this method is, that you can easily tell tabs and spaces apart.

Personally, I prefer using the unicode center dot character (set list lcs=tab:\·\) instead of the pipe symbol, but the pipe symbol is closer to the Notepad++ optic.


问:
Sorting and Balancing Across Multiple Columns

Problem

I have a Hash of data that looks something like this.

```<code>{ "GROUP_A" => [22, 440],
"GROUP_B" => [14, 70],
"GROUP_C" => [60, 620],
"GROUP_D" => [174, 40],
"GROUP_E" => [4, 12]
# ...few hundred more
}
</code>```

GROUP_A has 22 accounts and they are using 440GB of data...and so on.  There are a couple hundred of these groups.  Some have a lot of accounts but use very little storage and some have only a few users and use A LOT of storage, some are just average.

I have X number of buckets (servers) that I want to put these groups of accounts into, and I want there to be approximately the same number of accounts per bucket and have each bucket also contain approximately the same amount of data.  Number of groups is not important, so if a bucket had 1 group of 1000 accounts using 500GB of data and the next bucket had 10 groups of 97 accounts (970 total) using 450GB of data...I'd call it good.

So far I've not come up with an algorithm that will do this.  In my mind I'm thinking of something like this perhaps?

```<code>PASS 1
  Bucket 1:  Group with largest data, 60 users.
  Bucket 2:  Next largest data group, 37 users.
  Bucket 3:  Next largest data group, 72 users.
  Bucket 4:  etc....

PASS 2
  Bucket 1:  Add a group with small amount of data, but more users than average.
  # There's probably a ratio I can calculate to figure this out...divide users/datavmaybe?
  Bucket 2:  Find a "small data" group where sum of users in Bucket 1 ~= sum of users in Bucket 2
  # But then there's no guarantee that the data usages will be close enough
  Bucket 3:  etc...

PASS 3
  Bucket 1:  Now what?  Back to next largest data group?
</code>```

I still think there's a better way to figure this out but it's not coming to me.  If anyone has any thoughts I'm open to suggestions.

Matt

Solution 1.1 - Brute Force Update

Well....here's an update to the first attempt.  This is still not a "knapsack-problem" solution.  Just brute forcing the data so the accounts balance across buckets.  This time I added some logic so that if a bucket has a higher full percentage of accounts vs. data...it will find the largest group (by data) that fits best based on number of accounts.  I get a lot better distribution of data now vs. my first attempt (see the edit history if you want to look at the first attempt).

Right now I load each bucket in sequence, filling bucket one, then bucket two, etc...  I think if I was to modify the code so that I filled them simultaneously (or nearly so) I'd get a better data balance.

e.g. 1st department into bucket 1, 2nd department into bucket 2, etc...until all buckets have one department...  Then start back with bucket 1 again.

```<code>dept_arr_sorted_by_acct =  dept_hsh.sort_by {|key, value| value[0]}
ap "MAX ACCTS: #{max_accts}    AVG ACCTS: #{avg_accts}"
ap "MAX SIZE:  #{max_size}     AVG SIZE:  #{avg_data}"

# puts dept_arr_sorted_by_acct
# exit

bucket_arr = Array.new
used_hsh = Hash.new

server_names.each do |s|
  bucket_hsh = Hash.new
  this_accts=0
  this_data=0
  my_key=""
  my_val=[]
  accts=0
  data=0
  accts_space_pct_used = 0
  data_space_pct_used = 0
  while this_accts < avg_accts

    if accts_space_pct_used <= data_space_pct_used
    # This loop runs if the % used of accts is less than % used of data
      dept_arr_sorted_by_acct.each do |val|
        # Sorted by num accts - ascending.  Loop until we find the last entry in the array that has <= accts than what we need
        next if used_hsh.has_key?(val[0])
          #do nothing
        if val[1][0] <= avg_accts-this_accts
          my_key = val[0]
          my_val = val[1]
          accts = val[1][0]
          data = val[1][1]
        end
      end
    else
    # This loop runs if the % used of data is less than % used of accts
      dept_arr_sorted_by_data = dept_arr_sorted_by_acct.sort { |a,b| b[1][1] <=> a[1][1] }
      dept_arr_sorted_by_data.each do |val|
        # Sorted by size - descending.  Find the first (largest data) entry where accts <= what we need
        next if used_hsh.has_key?(val[0])
          # do nothing
        if val[1][0] <= avg_accts-this_accts
          my_key = val[0]
          my_val = val[1]
          accts = val[1][0]
          data = val[1][1]
          break
        end
      end
    end

    used_hsh[my_key] = my_val
    bucket_hsh[my_key] = my_val
    this_accts = this_accts + accts
    this_data = this_data + data
    accts_space_pct_used = this_accts.to_f / avg_accts * 100
    data_space_pct_used = this_data.to_f / avg_data * 100
  end
  bucket_arr << [this_accts, this_data, bucket_hsh]
end

x=0
while x < bucket_arr.size do
  th = bucket_arr[x][2]
  list_of_depts = []
  th.each_key do |key|
    list_of_depts << key
  end
  ap "Bucket #{x}:  #{bucket_arr[x][0]} accounts :: #{bucket_arr[x][1]} data :: #{list_of_depts.size} departments"
  #ap list_of_depts
  x = x+1
end
</code>```

...and the results...

```<code>"MAX ACCTS: 2279    AVG ACCTS: 379"
"MAX SIZE:  1693315     AVG SIZE:  282219"
"Bucket 0:  379 accounts :: 251670 data :: 7 departments"
"Bucket 1:  379 accounts :: 286747 data :: 10 departments"
"Bucket 2:  379 accounts :: 278226 data :: 14 departments"
"Bucket 3:  379 accounts :: 281292 data :: 19 departments"
"Bucket 4:  379 accounts :: 293777 data :: 28 departments"
"Bucket 5:  379 accounts :: 298675 data :: 78 departments"
</code>```

(379 * 6 <> 2279)  I still need to figure out how to account for when the MAX_ACCTS are not evenly divisible by the number of buckets.  I tried adding a 1% pad to the AVG_ACCTS value, which in this case means the average would be 383 I think, but then all the buckets say they have 383 accounts in them...which can't be true because then there are more accounts in the buckets than MAX_ACCTS.  I've got a mistake in the code somewhere that I haven't found yet.

答: This is an example of the knapsack problem. There are a few solutions, but it's a really tricky problem and it's better to research a good solution than to try and make your own.</p>

Body:
Problem

I have a Hash of data that looks something like this.

{ "GROUP_A" => [22, 440],
"GROUP_B" => [14, 70],
"GROUP_C" => [60, 620],
"GROUP_D" => [174, 40],
"GROUP_E" => [4, 12]
# ...few hundred more
}

GROUP_A has 22 accounts and they are using 440GB of data...and so on.  There are a couple hundred of these groups.  Some have a lot of accounts but use very little storage and some have only a few users and use A LOT of storage, some are just average.

I have X number of buckets (servers) that I want to put these groups of accounts into, and I want there to be approximately the same number of accounts per bucket and have each bucket also contain approximately the same amount of data.  Number of groups is not important, so if a bucket had 1 group of 1000 accounts using 500GB of data and the next bucket had 10 groups of 97 accounts (970 total) using 450GB of data...I'd call it good.

So far I've not come up with an algorithm that will do this.  In my mind I'm thinking of something like this perhaps?

PASS 1
  Bucket 1:  Group with largest data, 60 users.
  Bucket 2:  Next largest data group, 37 users.
  Bucket 3:  Next largest data group, 72 users.
  Bucket 4:  etc....

PASS 2
  Bucket 1:  Add a group with small amount of data, but more users than average.
  # There's probably a ratio I can calculate to figure this out...divide users/datavmaybe?
  Bucket 2:  Find a "small data" group where sum of users in Bucket 1 ~= sum of users in Bucket 2
  # But then there's no guarantee that the data usages will be close enough
  Bucket 3:  etc...

PASS 3
  Bucket 1:  Now what?  Back to next largest data group?

I still think there's a better way to figure this out but it's not coming to me.  If anyone has any thoughts I'm open to suggestions.

Matt

Solution 1.1 - Brute Force Update

Well....here's an update to the first attempt.  This is still not a "knapsack-problem" solution.  Just brute forcing the data so the accounts balance across buckets.  This time I added some logic so that if a bucket has a higher full percentage of accounts vs. data...it will find the largest group (by data) that fits best based on number of accounts.  I get a lot better distribution of data now vs. my first attempt (see the edit history if you want to look at the first attempt).

Right now I load each bucket in sequence, filling bucket one, then bucket two, etc...  I think if I was to modify the code so that I filled them simultaneously (or nearly so) I'd get a better data balance.

e.g. 1st department into bucket 1, 2nd department into bucket 2, etc...until all buckets have one department...  Then start back with bucket 1 again.

dept_arr_sorted_by_acct =  dept_hsh.sort_by {|key, value| value[0]}
ap "MAX ACCTS: #{max_accts}    AVG ACCTS: #{avg_accts}"
ap "MAX SIZE:  #{max_size}     AVG SIZE:  #{avg_data}"

# puts dept_arr_sorted_by_acct
# exit

bucket_arr = Array.new
used_hsh = Hash.new

server_names.each do |s|
  bucket_hsh = Hash.new
  this_accts=0
  this_data=0
  my_key=""
  my_val=[]
  accts=0
  data=0
  accts_space_pct_used = 0
  data_space_pct_used = 0
  while this_accts < avg_accts

    if accts_space_pct_used <= data_space_pct_used
    # This loop runs if the % used of accts is less than % used of data
      dept_arr_sorted_by_acct.each do |val|
        # Sorted by num accts - ascending.  Loop until we find the last entry in the array that has <= accts than what we need
        next if used_hsh.has_key?(val[0])
          #do nothing
        if val[1][0] <= avg_accts-this_accts
          my_key = val[0]
          my_val = val[1]
          accts = val[1][0]
          data = val[1][1]
        end
      end
    else
    # This loop runs if the % used of data is less than % used of accts
      dept_arr_sorted_by_data = dept_arr_sorted_by_acct.sort { |a,b| b[1][1] <=> a[1][1] }
      dept_arr_sorted_by_data.each do |val|
        # Sorted by size - descending.  Find the first (largest data) entry where accts <= what we need
        next if used_hsh.has_key?(val[0])
          # do nothing
        if val[1][0] <= avg_accts-this_accts
          my_key = val[0]
          my_val = val[1]
          accts = val[1][0]
          data = val[1][1]
          break
        end
      end
    end

    used_hsh[my_key] = my_val
    bucket_hsh[my_key] = my_val
    this_accts = this_accts + accts
    this_data = this_data + data
    accts_space_pct_used = this_accts.to_f / avg_accts * 100
    data_space_pct_used = this_data.to_f / avg_data * 100
  end
  bucket_arr << [this_accts, this_data, bucket_hsh]
end

x=0
while x < bucket_arr.size do
  th = bucket_arr[x][2]
  list_of_depts = []
  th.each_key do |key|
    list_of_depts << key
  end
  ap "Bucket #{x}:  #{bucket_arr[x][0]} accounts :: #{bucket_arr[x][1]} data :: #{list_of_depts.size} departments"
  #ap list_of_depts
  x = x+1
end

...and the results...

"MAX ACCTS: 2279    AVG ACCTS: 379"
"MAX SIZE:  1693315     AVG SIZE:  282219"
"Bucket 0:  379 accounts :: 251670 data :: 7 departments"
"Bucket 1:  379 accounts :: 286747 data :: 10 departments"
"Bucket 2:  379 accounts :: 278226 data :: 14 departments"
"Bucket 3:  379 accounts :: 281292 data :: 19 departments"
"Bucket 4:  379 accounts :: 293777 data :: 28 departments"
"Bucket 5:  379 accounts :: 298675 data :: 78 departments"

(379 * 6 <> 2279)  I still need to figure out how to account for when the MAX_ACCTS are not evenly divisible by the number of buckets.  I tried adding a 1% pad to the AVG_ACCTS value, which in this case means the average would be 383 I think, but then all the buckets say they have 383 accounts in them...which can't be true because then there are more accounts in the buckets than MAX_ACCTS.  I've got a mistake in the code somewhere that I haven't found yet.


问:
How to revert this NotificationManager.Policy method?
I have a method to allow Alarms when Do Not Disturb is on in Android P. I have a switch button to toggle on the Alarms and all works fine, but the problem is I don't know what method to use to toggle the Alarms off.

This is my code:

```<code>    private void allowAlarms() {
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    assert notificationManager != null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        notificationManager.setNotificationPolicy(
                new NotificationManager.Policy(NotificationManager.Policy.PRIORITY_CATEGORY_ALARMS,
                        NotificationManager.Policy.PRIORITY_SENDERS_ANY,
                        NotificationManager.Policy.PRIORITY_SENDERS_ANY));
    }
    notificationManager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_PRIORITY);
}
</code>```

I have tried cancelling the notification manager, but this does not work and the alarm still rings.

```<code>notificationManager.cancel(0)
</code>```

I have also tried simply calling the Priority only code again, but this does not work either.

```<code>assert mNotificationManager != null;
                    mNotificationManager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_PRIORITY);
</code>```

I want Alarms to go back to being blocked by default in Priority Only mode, when I toggle the switch off. However, whatever I try, the alarm still rings after I toggle it off. Any ideas?

答:
You have to use something like this:

```<code> notificationManager.setNotificationPolicy(
            new NotificationManager.Policy(NotificationManager.Policy.PRIORITY_CATEGORY_ALARMS | NotificationManager.Policy.PRIORITY_CATEGORY_CALLS | NotificationManager.Policy.PRIORITY_CATEGORY_MESSAGES,
                    NotificationManager.Policy.PRIORITY_SENDERS_ANY,
                    NotificationManager.Policy.PRIORITY_SENDERS_ANY));
</code>```

Meaning that if you want the policy to have a filter for messages or calls you have to set that flag in the category part of the policy. Otherwise it'll always allow no calls or messages.

Body:
I have a method to allow Alarms when Do Not Disturb is on in Android P. I have a switch button to toggle on the Alarms and all works fine, but the problem is I don't know what method to use to toggle the Alarms off.

This is my code:

    private void allowAlarms() {
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    assert notificationManager != null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        notificationManager.setNotificationPolicy(
                new NotificationManager.Policy(NotificationManager.Policy.PRIORITY_CATEGORY_ALARMS,
                        NotificationManager.Policy.PRIORITY_SENDERS_ANY,
                        NotificationManager.Policy.PRIORITY_SENDERS_ANY));
    }
    notificationManager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_PRIORITY);
}

I have tried cancelling the notification manager, but this does not work and the alarm still rings.

notificationManager.cancel(0)

I have also tried simply calling the Priority only code again, but this does not work either.

assert mNotificationManager != null;
                    mNotificationManager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_PRIORITY);

I want Alarms to go back to being blocked by default in Priority Only mode, when I toggle the switch off. However, whatever I try, the alarm still rings after I toggle it off. Any ideas?

Body:
You have to use something like this:

 notificationManager.setNotificationPolicy(
            new NotificationManager.Policy(NotificationManager.Policy.PRIORITY_CATEGORY_ALARMS | NotificationManager.Policy.PRIORITY_CATEGORY_CALLS | NotificationManager.Policy.PRIORITY_CATEGORY_MESSAGES,
                    NotificationManager.Policy.PRIORITY_SENDERS_ANY,
                    NotificationManager.Policy.PRIORITY_SENDERS_ANY));

Meaning that if you want the policy to have a filter for messages or calls you have to set that flag in the category part of the policy. Otherwise it'll always allow no calls or messages.


问:
How can i move the vertices of the ROI in python and opencv?
I trying to draw the contour in the ROI.
But the vertices of the ROI appear on the left side of the image.
I want to move the ROI to the place indicated in the photo, but I don't know how to do it.
I'm new to OpenCV and Python, so any help is much appreciated.
Here is my code.

```<code># Object detected
            center_x = int(detection[0] * width)
            center_y = int(detection[1] * height)
            w = int(detection[2] * width)
            h = int(detection[3] * height)
            # Rectangle coordinates
            x = int(center_x - w / 2)
            y = int(center_y - h / 2)
            boxes.append([x, y, w, h])
            confidences.append(float(confidence))
            class_ids.append(class_id)

indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.4, 0.3)

for i in range(len(boxes)):
    if i in indexes:
        x, y, w, h = boxes[i]
        label = str(classes[class_ids[i]])
        confidence = confidences[i]
        color = colors[class_ids[i]]

        img_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        ret, img_binary = cv2.threshold(img_gray, 15, 255, 0)
        roi = img_binary[y:y+h, x:x+w]
        contours, hierarchy = cv2.findContours(roi, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        cv2.drawContours(frame, contours, -1, (0,255,0), 3)
        print(roi.shape)
        print(x, y, w, h)
</code>```

答:
The returned coordinates of the contours are relative to the ROI passed to findContours.
I.e. the x coordinates of the contours are relative to the top-left corner of the ROI. Same for y.

As you want to display the contours inside of the original image and not inside of the ROI you have to shift them.

There are basically two options:

pass x and y of your ROI to findContours like

```<code>contours, hierarchy = cv2.findContours(roi, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE, offset=(x,y))
</code>```

The returned contours will then have coordinates relative to the original image.

pass x and y to drawContours like

```<code>cv2.drawContours(frame, contours, -1, (0,255,0), 3, offset=(x,y))
</code>```

This will leave the coordinates of your contours relative to the ROI and just display them inside of the original image.

What makes sense for you depends on your application.

The third option is to manually shift the contours by simply adding x to the first dimension and y to the second dimension.
The output will be the same as 1.

Body:
I trying to draw the contour in the ROI.
But the vertices of the ROI appear on the left side of the image.
I want to move the ROI to the place indicated in the photo, but I don't know how to do it.
I'm new to OpenCV and Python, so any help is much appreciated.
Here is my code.

# Object detected
            center_x = int(detection[0] * width)
            center_y = int(detection[1] * height)
            w = int(detection[2] * width)
            h = int(detection[3] * height)
            # Rectangle coordinates
            x = int(center_x - w / 2)
            y = int(center_y - h / 2)
            boxes.append([x, y, w, h])
            confidences.append(float(confidence))
            class_ids.append(class_id)

indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.4, 0.3)

for i in range(len(boxes)):
    if i in indexes:
        x, y, w, h = boxes[i]
        label = str(classes[class_ids[i]])
        confidence = confidences[i]
        color = colors[class_ids[i]]

        img_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        ret, img_binary = cv2.threshold(img_gray, 15, 255, 0)
        roi = img_binary[y:y+h, x:x+w]
        contours, hierarchy = cv2.findContours(roi, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        cv2.drawContours(frame, contours, -1, (0,255,0), 3)
        print(roi.shape)
        print(x, y, w, h)

Body:
The returned coordinates of the contours are relative to the ROI passed to findContours.
I.e. the x coordinates of the contours are relative to the top-left corner of the ROI. Same for y.

As you want to display the contours inside of the original image and not inside of the ROI you have to shift them.

There are basically two options:

pass x and y of your ROI to findContours like

contours, hierarchy = cv2.findContours(roi, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE, offset=(x,y))

The returned contours will then have coordinates relative to the original image.

pass x and y to drawContours like

cv2.drawContours(frame, contours, -1, (0,255,0), 3, offset=(x,y))

This will leave the coordinates of your contours relative to the ROI and just display them inside of the original image.

What makes sense for you depends on your application.

The third option is to manually shift the contours by simply adding x to the first dimension and y to the second dimension.
The output will be the same as 1.


问:
Spring boot: java.lang.NoSuchMethodError: javax.servlet.http.HttpServletRequest.getHttpServletMapping()Ljavax/servlet/http/HttpServletMapping;
When I run this application on built-in server or other tomcat server it
 gives me following error message. I am using jdk8, STS V-3.9.7. Can someone help me resolve it

Simple Springboot application with following content:

application.properties file for view mapping

```<code>    spring.mvc.view.prefix=/WEB-INF/jspViews/
    spring.mvc.view.suffix=.jsp
</code>```

index.jsp

```<code>    <body>
       <h3>Application is working</h3>
     </body>
</code>```

Controller class

```<code>    @Controller
    public class AppController {
       @RequestMapping("/")
       public String indexPage() {
           return "index";
       }
    }
</code>```

pom.xml file

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.demo</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>ehospitalsso</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

web.xml file

```<code> <?xml version="1.0" encoding="UTF-8"?>
    <web-app
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">

      <display-name>demo</display-name>
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
    </web-app>
</code>```

Error StackTrace ::

```<code>java.lang.NoSuchMethodError: javax.servlet.http.HttpServletRequest.getHttpServletMapping()Ljavax/servlet/http/HttpServletMapping;
    at org.apache.catalina.core.ApplicationHttpRequest.setRequest(ApplicationHttpRequest.java:690) ~[catalina.jar:na]
    at org.apache.catalina.core.ApplicationHttpRequest.<init>(ApplicationHttpRequest.java:114) ~[catalina.jar:na]
    at org.apache.catalina.core.ApplicationDispatcher.wrapRequest(ApplicationDispatcher.java:917) ~[catalina.jar:na]
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:358) ~[catalina.jar:na]
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:312) ~[catalina.jar:na]
    at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:170) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:316) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1370) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1116) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1055) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) ~[servlet-api.jar:na]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[servlet-api.jar:na]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [catalina.jar:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:na]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-websocket.jar:9.0.13-dev]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:na]
    at org.springframework.boot.web.servlet.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:130) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.web.servlet.support.ErrorPageFilter.access$000(ErrorPageFilter.java:66) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.web.servlet.support.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:105) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.boot.web.servlet.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:123) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:na]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) [spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:na]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) [catalina.jar:na]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [catalina.jar:na]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) [catalina.jar:na]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [catalina.jar:na]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [catalina.jar:na]
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668) [catalina.jar:na]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [catalina.jar:na]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [catalina.jar:na]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-coyote.jar:9.0.13-dev]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-coyote.jar:9.0.13-dev]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:791) [tomcat-coyote.jar:9.0.13-dev]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1417) [tomcat-coyote.jar:9.0.13-dev]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-coyote.jar:9.0.13-dev]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_161]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_161]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-util.jar:9.0.13-dev]
    at java.lang.Thread.run(Unknown Source) [na:1.8.0_161]
</code>```

Screen Sort:

Kind attend Mr.Avijit for update pox.xml file

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
    </parent>
    <groupId>com.demo</groupId>
    <artifactId>Demo_App</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>Demo_App</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>jstl</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

ServletInitializer  Class

```<code>import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(DemoAppApplication.class);
    }

}
</code>```

DemoAppApplication class

```<code>import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoAppApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoAppApplication.class, args);
    }

}
</code>```

答:
Below Fix Worked for me. Thanks Sven Döring</p>

```<code><properties>
        <tomcat.version>8.5.37</tomcat.version>
    <properties>
</code>```

Body:
When I run this application on built-in server or other tomcat server it
 gives me following error message. I am using jdk8, STS V-3.9.7. Can someone help me resolve it

Simple Springboot application with following content:

application.properties file for view mapping

    spring.mvc.view.prefix=/WEB-INF/jspViews/
    spring.mvc.view.suffix=.jsp

index.jsp

Application is working

Controller class

    @Controller
    public class AppController {
       @RequestMapping("/")
       public String indexPage() {
           return "index";
       }
    }

pom.xml file

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.demo</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>ehospitalsso</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

web.xml file

 <?xml version="1.0" encoding="UTF-8"?>
    <web-app
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">

      <display-name>demo</display-name>
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
    </web-app>

Error StackTrace ::

java.lang.NoSuchMethodError: javax.servlet.http.HttpServletRequest.getHttpServletMapping()Ljavax/servlet/http/HttpServletMapping;
    at org.apache.catalina.core.ApplicationHttpRequest.setRequest(ApplicationHttpRequest.java:690) ~[catalina.jar:na]
    at org.apache.catalina.core.ApplicationHttpRequest.<init>(ApplicationHttpRequest.java:114) ~[catalina.jar:na]
    at org.apache.catalina.core.ApplicationDispatcher.wrapRequest(ApplicationDispatcher.java:917) ~[catalina.jar:na]
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:358) ~[catalina.jar:na]
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:312) ~[catalina.jar:na]
    at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:170) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:316) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1370) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1116) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1055) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) ~[servlet-api.jar:na]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[servlet-api.jar:na]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [catalina.jar:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:na]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-websocket.jar:9.0.13-dev]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:na]
    at org.springframework.boot.web.servlet.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:130) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.web.servlet.support.ErrorPageFilter.access$000(ErrorPageFilter.java:66) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.web.servlet.support.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:105) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.boot.web.servlet.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:123) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:na]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) [spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:na]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) [catalina.jar:na]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [catalina.jar:na]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) [catalina.jar:na]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [catalina.jar:na]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [catalina.jar:na]
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668) [catalina.jar:na]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [catalina.jar:na]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [catalina.jar:na]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-coyote.jar:9.0.13-dev]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-coyote.jar:9.0.13-dev]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:791) [tomcat-coyote.jar:9.0.13-dev]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1417) [tomcat-coyote.jar:9.0.13-dev]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-coyote.jar:9.0.13-dev]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_161]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_161]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-util.jar:9.0.13-dev]
    at java.lang.Thread.run(Unknown Source) [na:1.8.0_161]

Screen Sort:

Kind attend Mr.Avijit for update pox.xml file

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
    </parent>
    <groupId>com.demo</groupId>
    <artifactId>Demo_App</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>Demo_App</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>jstl</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

ServletInitializer  Class

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(DemoAppApplication.class);
    }

}

DemoAppApplication class

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoAppApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoAppApplication.class, args);
    }

}

Body:
Below Fix Worked for me. Thanks Sven Döring

<properties>
        <tomcat.version>8.5.37</tomcat.version>
    <properties>


问:
Upload two files and an object are failing with error 415
I am trying to consume an http rest call that takes input of two files a dto

```<code>@RequestMapping(name = "/my/endpoint", method = RequestMethod.POST, consumes = {MediaType.MULTIPART_FORM_DATA_VALUE,
            MediaType.APPLICATION_JSON_VALUE})
    public @ResponseBody
    EndpointDto createEndpoint(@RequestBody MultipartFile requestFile, @RequestBody MultipartFile responseFile,
                               @RequestBody MyDto myDto){
        return endpointService.createEndpoint(requestFile, responseFile, myDto);
    }
</code>```

I received the following error:

```<code>    org.springframework.web.HttpMediaTypeNotSupportedException:
Content type 'multipart/form-data;boundary=----WebKitFormBoundarylq2UHYfBi0nAsRo7;charset=UTF-8' not supported
</code>```

I consume the endpoint through swagger.
I think that the problem lies in the way I handle the input fields but I don't know what is the problem.

答:
Sample controller

```<code>@PostMapping(value = "/documents")
@Timed
public ResponseEntity<DocumentDTO> createDocument(@RequestPart String document, @RequestParam("file") MultipartFile file, HttpServletRequest httpServletRequest) throws URISyntaxException {

    DocumentDTO documentDTO = convertStringToDTO(document);

    DocumentDTO result = documentService.save(documentDTO, file);
    return ResponseEntity.created(new URI("/api/documents/" + result.getId()))
        .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
        .body(result);
}

// com.fasterxml.jackson.databind.ObjectMapper;
private DocumentDTO convertStringToDTO(String document) {
    ObjectMapper objectMapper = new ObjectMapper();
    DocumentDTO documentDTO = null;
    try {
        documentDTO = objectMapper.readValue(document, DocumentDTO.class);
    } catch (IOException e) {
        log.error("DocumentString to JSON", e);
    }
    return documentDTO;
}
</code>```

You have to send the data in form-data format from front-end with key as a file containing bytes and document JSON object.

Body:
I am trying to consume an http rest call that takes input of two files a dto

@RequestMapping(name = "/my/endpoint", method = RequestMethod.POST, consumes = {MediaType.MULTIPART_FORM_DATA_VALUE,
            MediaType.APPLICATION_JSON_VALUE})
    public @ResponseBody
    EndpointDto createEndpoint(@RequestBody MultipartFile requestFile, @RequestBody MultipartFile responseFile,
                               @RequestBody MyDto myDto){
        return endpointService.createEndpoint(requestFile, responseFile, myDto);
    }

I received the following error:

    org.springframework.web.HttpMediaTypeNotSupportedException:
Content type 'multipart/form-data;boundary=----WebKitFormBoundarylq2UHYfBi0nAsRo7;charset=UTF-8' not supported

I consume the endpoint through swagger.
I think that the problem lies in the way I handle the input fields but I don't know what is the problem.

Body:
Sample controller

@PostMapping(value = "/documents")
@Timed
public ResponseEntity<DocumentDTO> createDocument(@RequestPart String document, @RequestParam("file") MultipartFile file, HttpServletRequest httpServletRequest) throws URISyntaxException {

    DocumentDTO documentDTO = convertStringToDTO(document);

    DocumentDTO result = documentService.save(documentDTO, file);
    return ResponseEntity.created(new URI("/api/documents/" + result.getId()))
        .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
        .body(result);
}

// com.fasterxml.jackson.databind.ObjectMapper;
private DocumentDTO convertStringToDTO(String document) {
    ObjectMapper objectMapper = new ObjectMapper();
    DocumentDTO documentDTO = null;
    try {
        documentDTO = objectMapper.readValue(document, DocumentDTO.class);
    } catch (IOException e) {
        log.error("DocumentString to JSON", e);
    }
    return documentDTO;
}

You have to send the data in form-data format from front-end with key as a file containing bytes and document JSON object.


问:
Moving Background Transition with Image using custom segue swift
I want to get moving background animation like this.

1.I have a problem regarding the transition of the view controllers .
I have attached the following link above for the transition which i want to perform for my view controllers .
Thanks and regards ...

答:
You can try using the HERO pod for such transitions  .
This is the pod for installing HERO

pod 'Hero'


问:
Problem with the CakePHP Search Plugin
I've trying to use the CakePHP Search Plugin along with the Blog tutorial available in the Cookbook and even though I followed the instruction to the letter I Keep getting this error message :Warning (512): SQL Error: 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'parseCriteria' at line 1 .

This is what I've done:

Model:

```<code>class Post extends AppModel {
    var $name = 'Post';
    var $displayField = 'title';

    public $filterArgs = array(
            array('name' => 'title','type' => 'string'),
    );
}
</code>```

Controller:

```<code>class PostsController extends AppController {

   var $name = 'Posts';
   public $components = array('Search.Prg');

   public $presetVars = array(
    array('field' => 'title', 'type' => 'value'),
   );

   function beforeFilter() {
       parent::beforeFilter();
   }

   public function index() {
    $this->Prg->commonProcess();
    $this->paginate = array(
      'conditions' => $this->Post->parseCriteria($this->passedArgs));
    $this->paginate = array('limit' => 15);
    $this->set('posts', $this->paginate());
   }

}
</code>```

View:

```<code><?php
   echo $this->Form->create('Post', array(
       'url' => array_merge(array('action' => 'index'), $this->params['pass'])
            ));
   echo $this->Form->input('title', array('div' => false, 'empty' => true));
   echo $this->Form->submit(__('Search', true), array('div' => false));
   echo $this->Form->end();
?>
</code>```

Do you have any idea why this is happening? Am I missing something?

答:
You're getting that error because you haven't attached the behavior to your Post model.  At the top of your Post model add:</p>

```<code>var $actsAs = array('Search.Searchable');
</code>```

Title: Problem with the CakePHP Search Plugin

Body:
I've trying to use the CakePHP Search Plugin along with the Blog tutorial available in the Cookbook and even though I followed the instruction to the letter I Keep getting this error message :Warning (512): SQL Error: 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'parseCriteria' at line 1 .

This is what I've done:

Model:

class Post extends AppModel {
    var $name = 'Post';
    var $displayField = 'title';

    public $filterArgs = array(
            array('name' => 'title','type' => 'string'),
    );
}

Controller:

class PostsController extends AppController {

   var $name = 'Posts';
   public $components = array('Search.Prg');

   public $presetVars = array(
    array('field' => 'title', 'type' => 'value'),
   );

   function beforeFilter() {
       parent::beforeFilter();
   }

   public function index() {
    $this->Prg->commonProcess();
    $this->paginate = array(
      'conditions' => $this->Post->parseCriteria($this->passedArgs));
    $this->paginate = array('limit' => 15);
    $this->set('posts', $this->paginate());
   }

}

View:

<?php
   echo $this->Form->create('Post', array(
       'url' => array_merge(array('action' => 'index'), $this->params['pass'])
            ));
   echo $this->Form->input('title', array('div' => false, 'empty' => true));
   echo $this->Form->submit(__('Search', true), array('div' => false));
   echo $this->Form->end();
?>

Do you have any idea why this is happening? Am I missing something?

Body:
You're getting that error because you haven't attached the behavior to your Post model.  At the top of your Post model add:

var $actsAs = array('Search.Searchable');


问:
Define outer surface of an Abaqus model and calculate distance integration point-closest surface
I have a problem that I am trying to solve for weeks but with no results. After my simulation in Abaqus, once I have exported the stress at each integration points with the respective coordinate, I need to calculate for each integration point the distance from the closest surface. Of course, the geometry can be arbitrarily complex.

What I had in mind was firstly to determine the coordinates of the nodes that belong to the surface of the model (the idea is to do that without determining an a priori surface or set).

I have found in another thread this piece of code:

```<code>p = mdb.models[name].parts[name]
surf_nodes = []
for face in p.elementFaces():
    if len(face.getElements()) == 1:
        # Then the face has only one associated element, ie it's on the surface.
        # Get the nodes on the face:
        surf_nodes.extend([node for node in face.getNodes() if node not in surf_nodes])
</code>```

The problem is that when I lounch the script I receive this message:

TypeError: MeshFaceArray object is not callable.

Do you know how can I solve this problem? And of course, do you have any idea how to proceed to reach my final goal?

Really thank you very much in advance :)

答:
Try this and let me know if it does not work, then I can assist you further.</p>

```<code>p = mdb.models[name].parts[name]
surf_nodes = []
for face in p.elementFaces:
    if len(face.getElements()) == 1:
        surf_nodes.extend([node for node in face.getNodes() if node not in surf_nodes])
</code>```

Body:
I have a problem that I am trying to solve for weeks but with no results. After my simulation in Abaqus, once I have exported the stress at each integration points with the respective coordinate, I need to calculate for each integration point the distance from the closest surface. Of course, the geometry can be arbitrarily complex.

What I had in mind was firstly to determine the coordinates of the nodes that belong to the surface of the model (the idea is to do that without determining an a priori surface or set).

I have found in another thread this piece of code:

p = mdb.models[name].parts[name]
surf_nodes = []
for face in p.elementFaces():
    if len(face.getElements()) == 1:
        # Then the face has only one associated element, ie it's on the surface.
        # Get the nodes on the face:
        surf_nodes.extend([node for node in face.getNodes() if node not in surf_nodes])

The problem is that when I lounch the script I receive this message:

TypeError: MeshFaceArray object is not callable.

Do you know how can I solve this problem? And of course, do you have any idea how to proceed to reach my final goal?

Really thank you very much in advance :)

Body:
Try this and let me know if it does not work, then I can assist you further.

p = mdb.models[name].parts[name]
surf_nodes = []
for face in p.elementFaces:
    if len(face.getElements()) == 1:
        surf_nodes.extend([node for node in face.getNodes() if node not in surf_nodes])


问:
Particular Thread Count
I want to know how many active threads are there for a particular Thread class.
Lets say I have a class T which extends thread.  In some other class (Ex: Demo) , I want to get the thread count for the T class Thread. I do know Thread.activeCount() method but it will get the count for a thread group. It does not server my need here.  Lets say I have T1 and T2 classes which extends thread and In the Demo class I want to get How many T2 active threads are there.
How should I achieve this? Any Ideas??

PS: I don't have source code for the Class T1 and T2.

Thanks for the help.

答:
```<code>   private static int getThreadCount(){
        int runningThread = 0;
        for (Thread t : Thread.getAllStackTraces().keySet()) if (t.getState()==Thread.State.RUNNABLE && t instanceof YourThreadClassName ) runningThread++;
        System.out.println("Active threads : "+runningThread);
        return runningThread;
    }
</code>```

Justreplace YourThreadClassName with your class that is extended by Thread.

Title: Particular Thread Count

Body:
   private static int getThreadCount(){
        int runningThread = 0;
        for (Thread t : Thread.getAllStackTraces().keySet()) if (t.getState()==Thread.State.RUNNABLE && t instanceof YourThreadClassName ) runningThread++;
        System.out.println("Active threads : "+runningThread);
        return runningThread;
    }

Justreplace YourThreadClassName with your class that is extended by Thread.


问:
php + mysql query returning only a single row (std class) from class function
Can you tell me why this returns only the last row of my query?
As you see I'm extracting as std class. Also I already tried different approaches like a foreach key=>value inside the while but it does not help. I can't populate $out correctly.</p>

```<code>class myclass {

    function Query($sql){

    $results = $this->db->query($sql);

    if (mysqli_num_rows($results)<1){
        throw new Exception('NoResults');
    }

    $out = new stdClass;
    while ($r = $results->fetch_object()){

        $out = $r;
    }

    return $out;
    $out = null;
    }

}

}

---------------

$client = new myclass;

    $sql = "SELECT * FROM books";
    $q = $client->Query($sql);

    print_r($q);
</code>```

答:
You just need to change those lines:

```<code>$out = new stdClass;
while ($r = $results->fetch_object()){
    $out = $r;
}
</code>```

to those ones:

```<code>$out = []; // array that will hold all the objects
while ($r = $results->fetch_object()){
    array_push($out, $r);  // add to the array the current object
}
return $out; //return the array with the objects
</code>```

Body:
Can you tell me why this returns only the last row of my query?
As you see I'm extracting as std class. Also I already tried different approaches like a foreach key=>value inside the while but it does not help. I can't populate $out correctly.

class myclass {

    function Query($sql){

    $results = $this->db->query($sql);

    if (mysqli_num_rows($results)<1){
        throw new Exception('NoResults');
    }

    $out = new stdClass;
    while ($r = $results->fetch_object()){

        $out = $r;
    }

    return $out;
    $out = null;
    }

}

}

---------------

$client = new myclass;

    $sql = "SELECT * FROM books";
    $q = $client->Query($sql);

    print_r($q);

Body:
You just need to change those lines:

$out = new stdClass;
while ($r = $results->fetch_object()){
    $out = $r;
}

to those ones:

$out = []; // array that will hold all the objects
while ($r = $results->fetch_object()){
    array_push($out, $r);  // add to the array the current object
}
return $out; //return the array with the objects


问:
How to name and reference an Excel range using office.js
I'm developing an Excel add-in using office.js library, and need to create some named ranges to track and access later.

However according to the API documentation:

NamedItemCollection: https://github.com/OfficeDev/office-js-docs/blob/master/reference/excel/nameditemcollection.md

NamedItem: https://github.com/OfficeDev/office-js-docs/blob/master/reference/excel/nameditem.md

There is no method for creating named items.

Is there a way to name and reference an Excel range using office.js? Thanks.

答:
there is the Excel.NamedItemCollection which provides an add() method that generates Named references

https://learn.microsoft.com/en-us/javascript/api/excel/excel.nameditemcollection?view=excel-js-preview


问:
Conversion from Simplified to Traditional Chinese
If a website is localized/internationalized with a Simplified Chinese translation...

Is it possible to reliably
automatically convert the text to
Traditional Chinese in a high quality
way?

If so, is it going to be extremely high quality or just a good starting point for a translator to tweak?

Are there open source tools (ideally in PHP) to do
such a conversion?

Is the conversion better one way vs. the other (simplified -> traditional, or vice versa)?

答:
Is it possible to reliably automatically convert the text to Traditional Chinese in a high quality way?

Other answers are focused on the difficulties, but these are exaggerated. One thing is that a substantial portion of the characters are exactly the same. The second thing is the 'simplified' forms are exactly that: simplified forms of the traditional characters. That means mostly there is a 1 to 1 relationship between traditional and simplified characters.

If so, is it going to be extremely high quality or just a good starting point for a translator to tweak?

A few things will need tweaking.

Are there open source tools (ideally in PHP) to do such a conversion?

Not that I am aware of, though you might want to check out the google translate api?

Is the conversion better one way vs. the other (simplified -> traditional, or vice versa)?

A few characters lost distinction in the simplified alphabet. For instance 麵(flour) was simplified to the same character as 面(face, side). For this reason traditional->simplified would be slightly more accurate.

I'd also like to point out that traditional characters are not solely in use in Taiwan (They can be found in HK and occasionally even in the mainland)

I was able to find this and this. Need to create an account to download, though. Never used the site myself so I cannot vouch for it.


问:
Module 'cv2.cv2' has no attribute 'ximgproc'
I am trying to perform a selective search to an image using OpenCV but when I run my code I get this:

```<code>>>> import cv2
>>> ss = cv2.ximgproc.segmentation.createSelectiveSearchSegmentation()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'cv2.cv2' has no attribute 'ximgproc'
</code>```

I've seen similar problems but people solved them installing opencv-contrib-python package. I've already installed this module but the problem persists.

Here is my requirements file:

```<code>opencv-contrib-python==4.1.0.25
opencv-python==4.1.0.25
</code>```

I am using a conda environment with python 3.7

答:
This should solve the issue, if you have pip installed. I found pip installer to be better than conda installer in general.</p>

```<code>pip install opencv-contrib-python
</code>```

Body:
I am trying to perform a selective search to an image using OpenCV but when I run my code I get this:

>>> import cv2
>>> ss = cv2.ximgproc.segmentation.createSelectiveSearchSegmentation()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'cv2.cv2' has no attribute 'ximgproc'

I've seen similar problems but people solved them installing opencv-contrib-python package. I've already installed this module but the problem persists.

Here is my requirements file:

opencv-contrib-python==4.1.0.25
opencv-python==4.1.0.25

I am using a conda environment with python 3.7

Body:
This should solve the issue, if you have pip installed. I found pip installer to be better than conda installer in general.

pip install opencv-contrib-python


问:
CSS: Make image fit the proper area with the absolutely positioned label on the picture
On my webpage there is an area and I'd like to add a image to it. I don't know the image's size and orientation (portrait or landscape). But I want it to fit the area as it is displayed in the picture:

So, if an image has a landscape orientation it must fill the whole width of the area. See picture 1. If the image's width is bigger that the area's width the image's width must be constrained and if its width is smaller - the image must be widened. However if the image's height is bigger than the area's one the image's height must be constrained. See picture 2.

The similar I want for the portrait image. See picture 2.

In short, what I want can be easily done with object-fit: contain;.

.wrapper {
  width: 30%;
  height: 400px;
  overflow: hidden;
  border: 1px solid black;
  position: relative;
}

.img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.label {
  position: absolute;
  top: 0;
  right: 0;
  padding: 15px;
  background-color: #cccccc;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <img class="img" src="https://images.unsplash.com/photo-1500622944204-b135684e99fd?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80" alt="">
  <span class="label">Label</span>
</div></code>```

Here is the CodePen: see the code

But the problem is that I have a label to each picture and I want it to be on the top-right corner of the picture and not the area.

Is there any way to do this with CSS only?

Any help would appreciated! Thank you in advance!

答: instead of the object-fit: contain; replace it with background-size:cover in the img selector css file.</p>

Body:
On my webpage there is an area and I'd like to add a image to it. I don't know the image's size and orientation (portrait or landscape). But I want it to fit the area as it is displayed in the picture:

So, if an image has a landscape orientation it must fill the whole width of the area. See picture 1. If the image's width is bigger that the area's width the image's width must be constrained and if its width is smaller - the image must be widened. However if the image's height is bigger than the area's one the image's height must be constrained. See picture 2.

The similar I want for the portrait image. See picture 2.

In short, what I want can be easily done with object-fit: contain;.

.wrapper {
  width: 30%;
  height: 400px;
  overflow: hidden;
  border: 1px solid black;
  position: relative;
}

.img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.label {
  position: absolute;
  top: 0;
  right: 0;
  padding: 15px;
  background-color: #cccccc;
}

  Label

Here is the CodePen: see the code

But the problem is that I have a label to each picture and I want it to be on the top-right corner of the picture and not the area.

Is there any way to do this with CSS only?

Any help would appreciated! Thank you in advance!


问:
why wont this query delete details from all tables?
I am trying to delete records from tables matching users ID while i delete the user. but somehow it deletes records only from the cv table.

what i am trying is

```<code>if($_GET['deluser'] !='1'){

         $qr = "delete from members where member_id IN(".$_GET['deluser'].")";
         $qr = "delete from company where caller_id IN(".$_GET['deluser'].")";
         $qr = "delete from cv where agent_id IN(".$_GET['deluser'].")";
         $st = $db->prepare($qr);
         $st->execute();

    header('Location: users.php?action=DELETED');
    exit;
</code>```

what could i be doing wrong?

答:
In your case you overwrite the value in $qr every time so you need to execute it, everyone of them separately,

you need also to fix the SQL injection problem so you can fix it
by using bind your data in the execute method or by using bindParam

first, you need to add ? with the same number of input you want to pass

you can check how it work here in this answer

```<code>$in  = str_repeat('?,', count(explode(',', $_GET['deluser'])) - 1) . '?';
</code>```

```<code>$qr = "delete from members where member_id IN($in)";
$st = $db->prepare($qr);
$st->execute(explode(',', $_GET['deluser']));

$qr = "delete from company where caller_id IN($in)";
$st = $db->prepare($qr);
$st->execute(explode(',', $_GET['deluser']));

$qr = "delete from cv where agent_id IN($in)";
$st = $db->prepare($qr);
$st->execute(explode(',', $_GET['deluser']));
</code>```

You can read more about BindParam and Execute in the docs

Body:
I am trying to delete records from tables matching users ID while i delete the user. but somehow it deletes records only from the cv table.

what i am trying is

if($_GET['deluser'] !='1'){

         $qr = "delete from members where member_id IN(".$_GET['deluser'].")";
         $qr = "delete from company where caller_id IN(".$_GET['deluser'].")";
         $qr = "delete from cv where agent_id IN(".$_GET['deluser'].")";
         $st = $db->prepare($qr);
         $st->execute();

    header('Location: users.php?action=DELETED');
    exit;

what could i be doing wrong?

Body:
In your case you overwrite the value in $qr every time so you need to execute it, everyone of them separately,

you need also to fix the SQL injection problem so you can fix it
by using bind your data in the execute method or by using bindParam

first, you need to add ? with the same number of input you want to pass

you can check how it work here in this answer

$in  = str_repeat('?,', count(explode(',', $_GET['deluser'])) - 1) . '?';

$qr = "delete from members where member_id IN($in)";
$st = $db->prepare($qr);
$st->execute(explode(',', $_GET['deluser']));

$qr = "delete from company where caller_id IN($in)";
$st = $db->prepare($qr);
$st->execute(explode(',', $_GET['deluser']));

$qr = "delete from cv where agent_id IN($in)";
$st = $db->prepare($qr);
$st->execute(explode(',', $_GET['deluser']));

You can read more about BindParam and Execute in the docs


问:
Using a sub query in column list
I would like to create a query that would count how many records were created in the last 7, 14 and 28 days.  My result would return something like:

```<code>7Days  14Days  28Days
21     35      56
</code>```

I know how to for each timepsan e.g. 7 days, but I do I capture all three in one query?

```<code>select count(*) from Mytable
where Created > DATEADD(day,-8, getdate())
</code>```

答:
Also not pretty, but doesn't rely on subqueries (table/column names are from AdventureWorks). The case statement returns 1 if it falls within your criteria, 0 otherwise - then you just sum the results :

```<code>select sum(case when datediff(day, modifieddate, getdate()) <= 7
                then 1 else 0 end) as '7days',
       sum(case when datediff(day, modifieddate, getdate()) > 7
                     and datediff(day, modifieddate, getdate()) <= 14
                then 1 else 0 end) as '14days',
       sum(case when datediff(day, modifieddate, getdate()) > 14
                     and datediff(day, modifieddate, getdate()) <= 28
                then 1 else 0 end) as '28days'
from sales.salesorderdetail
</code>```

Edit: Updated the datediff function - the way it was written, it would return a negative number (assuming modifieddate was in the past) causing all items to fall under the first case. Thanks to Andriy M for pointing that out

Title: Using a sub query in column list

Body:
I would like to create a query that would count how many records were created in the last 7, 14 and 28 days.  My result would return something like:

7Days  14Days  28Days
21     35      56

I know how to for each timepsan e.g. 7 days, but I do I capture all three in one query?

select count(*) from Mytable
where Created > DATEADD(day,-8, getdate())

Body:
Also not pretty, but doesn't rely on subqueries (table/column names are from AdventureWorks). The case statement returns 1 if it falls within your criteria, 0 otherwise - then you just sum the results :

select sum(case when datediff(day, modifieddate, getdate()) <= 7
                then 1 else 0 end) as '7days',
       sum(case when datediff(day, modifieddate, getdate()) > 7
                     and datediff(day, modifieddate, getdate()) <= 14
                then 1 else 0 end) as '14days',
       sum(case when datediff(day, modifieddate, getdate()) > 14
                     and datediff(day, modifieddate, getdate()) <= 28
                then 1 else 0 end) as '28days'
from sales.salesorderdetail

Edit: Updated the datediff function - the way it was written, it would return a negative number (assuming modifieddate was in the past) causing all items to fall under the first case. Thanks to Andriy M for pointing that out


问:
TypeError: Object of type WorkItem is not JSON serializable
I received this error after running the script below. I would like to create a json file through the result that is generated in this script. What can I do to correct this problem?

I tried to do it via API but I couldn't get the fields I need from this DevOps table.

```<code>from azure.devops.connection import Connection
from msrest.authentication import BasicAuthentication
from azure.devops.v5_1.work_item_tracking.models import Wiql
import json

token = 'xxx'
team_instance = 'https://dev.azure.com/xxx'

credentials = BasicAuthentication("", token)
connection = Connection(base_url=team_instance, creds=credentials)

def print_work_items(work_items):
    for work_item in work_items:
        with open('teste_project.json', 'w') as json_file:
            json.dump(work_items, json_file)

wit_client = connection.clients.get_work_item_tracking_client()

def get_TC_from_query(query):
    query_wiql = Wiql(query=query)
    results = wit_client.query_by_wiql(query_wiql).work_items
    # WIQL query gives a WorkItemReference => we get the corresponding WorkItem from id
    work_items = (wit_client.get_work_item(int(result.id)) for result in results)
    print_work_items(work_items)

get_TC_from_query(
    """\
SELECT *
FROM workitems
WHERE
        [System.TeamProject] = 'xxx'
        and [System.WorkItemType] = 'Product Backlog Item'
        and [System.State] = 'Done'
ORDER BY [System.ChangedDate] DESC
"""
)
</code>```

TypeError: Object of type WorkItem is not JSON serializable

答:
Inspired by the thread provided by @jordanm. You can override the default() method to serialize additional types.

I made below changes to your code, and it worked when i tested.

First make work_items a list:

work_items = [wit_client.get_work_item(int(result.id)) for result in results]

Then in print_work_items method, i override the default method in json.dump() with default = lambda o: o.__dict__. Please check below:

```<code>def print_work_items(work_items):
    for work_item in work_items:
        with open('teste_project.json', 'w') as json_file:
            json.dump(work_items, json_file, default = lambda o: o.__dict__, sort_keys=True, indent=4)
</code>```

Body:
I received this error after running the script below. I would like to create a json file through the result that is generated in this script. What can I do to correct this problem?

I tried to do it via API but I couldn't get the fields I need from this DevOps table.

from azure.devops.connection import Connection
from msrest.authentication import BasicAuthentication
from azure.devops.v5_1.work_item_tracking.models import Wiql
import json

token = 'xxx'
team_instance = 'https://dev.azure.com/xxx'

credentials = BasicAuthentication("", token)
connection = Connection(base_url=team_instance, creds=credentials)

def print_work_items(work_items):
    for work_item in work_items:
        with open('teste_project.json', 'w') as json_file:
            json.dump(work_items, json_file)

wit_client = connection.clients.get_work_item_tracking_client()

def get_TC_from_query(query):
    query_wiql = Wiql(query=query)
    results = wit_client.query_by_wiql(query_wiql).work_items
    # WIQL query gives a WorkItemReference => we get the corresponding WorkItem from id
    work_items = (wit_client.get_work_item(int(result.id)) for result in results)
    print_work_items(work_items)

get_TC_from_query(
    """\
SELECT *
FROM workitems
WHERE
        [System.TeamProject] = 'xxx'
        and [System.WorkItemType] = 'Product Backlog Item'
        and [System.State] = 'Done'
ORDER BY [System.ChangedDate] DESC
"""
)

TypeError: Object of type WorkItem is not JSON serializable

Body:
Inspired by the thread provided by @jordanm. You can override the default() method to serialize additional types.

I made below changes to your code, and it worked when i tested.

First make work_items a list:

work_items = [wit_client.get_work_item(int(result.id)) for result in results]

Then in print_work_items method, i override the default method in json.dump() with default = lambda o: o.__dict__. Please check below:

def print_work_items(work_items):
    for work_item in work_items:
        with open('teste_project.json', 'w') as json_file:
            json.dump(work_items, json_file, default = lambda o: o.__dict__, sort_keys=True, indent=4)