问:
Powershell: How can I use an array or hashtable as an inline lookup
Using Powershell I am calling win32_computersystem. I want to list data about the machine including $_thermalstate - Here is my code

The code looks as though it should work but returns a empty value. I want to create an inline array or hash table that the value $_.thermalstate references.

```<code>Get-WmiObject win32_computersystem | select Name, Model, Caption, @{n="Timezone"; e={$_.currenttimezone}}, Description, DNShostname,Domain,@{n='Domain Role'; E={$_.domainrole}},Roles,Status,@{n='System Type'; e={$_.systemtype}},@{n='Thermal State'; e={$_.thermalstate[@{'3'='safe'}]}}
</code>```

Output

```<code>Name          : MYPC
Model         : Latitude E5470
Caption       : MYPC
Timezone      : 600
Description   : AT/AT COMPATIBLE
DNShostname   : MYPC
Domain        : work.biz
Domain Role   : 1
Roles         : {LM_Workstation, LM_Server, NT}
Status        : OK
System Type   : x64-based PC
Thermal State : Safe
</code>```

答:
According to https://wutils.com/wmi/root/cimv2/win32_computersystem/

```<code>ThermalState property
CIMTYPE         'uint16'
Description     'The ThermalState property identifies the enclosure's thermal state when last booted.'
MappingStrings  ['SMBIOS|Type 3|System Enclosure or Chassis|Thermal State']
read            True
ValueMap        ['1', '2', '3', '4', '5', '6']
Values          ['Other', 'Unknown', 'Safe', 'Warning', 'Critical', 'Non-recoverable']
ThermalState property is in 1 class (Win32_ComputerSystem) of ROOT\cimv2 and in 2 namespaces
</code>```

You could create an enum

```<code>enum ThermalState {
Other          = 1
Unknown        = 2
Safe           = 3
Warning        = 4
Critical       = 5
NonRecoverable = 6
}
</code>```

And use that to get a verbose response from the property

```<code>Get-WmiObject win32_computersystem | Select-Object Name, Model, Caption,
    @{n="Timezone"; e={$_.currenttimezone}}, Description, DNShostname,Domain,
    @{n='Domain Role';E={$_.domainrole}},Roles,Status,
    @{n='System Type'; e={$_.systemtype}},
    @{n='Thermal State'; e={[ThermalState]$_.thermalstate}}
</code>```

Sample output

```<code>Name          : HP-G1610
Model         : ProLiant MicroServer Gen8
Caption       : HP-G1610
Timezone      : 120
Description   : AT/AT COMPATIBLE
DNShostname   : HP-G1610
Domain        : DOMAIN
Domain Role   : 0
Roles         : {...}
Status        : OK
System Type   : x64-based PC
Thermal State : Safe
</code>```

In general to get a list of an enum :

```<code>> $Enum ='System.DayOfWeek'
> [Enum]::GetValues($Enum) | ForEach-Object {'{0} {1}' -f [int]$_,$_ }
0 Sunday
1 Monday
2 Tuesday
3 Wednesday
4 Thursday
5 Friday
6 Saturday
</code>```

Body:
Using Powershell I am calling win32_computersystem. I want to list data about the machine including $_thermalstate - Here is my code

The code looks as though it should work but returns a empty value. I want to create an inline array or hash table that the value $_.thermalstate references.

Get-WmiObject win32_computersystem | select Name, Model, Caption, @{n="Timezone"; e={$_.currenttimezone}}, Description, DNShostname,Domain,@{n='Domain Role'; E={$_.domainrole}},Roles,Status,@{n='System Type'; e={$_.systemtype}},@{n='Thermal State'; e={$_.thermalstate[@{'3'='safe'}]}}

Output

Name          : MYPC
Model         : Latitude E5470
Caption       : MYPC
Timezone      : 600
Description   : AT/AT COMPATIBLE
DNShostname   : MYPC
Domain        : work.biz
Domain Role   : 1
Roles         : {LM_Workstation, LM_Server, NT}
Status        : OK
System Type   : x64-based PC
Thermal State : Safe

Body:
According to https://wutils.com/wmi/root/cimv2/win32_computersystem/

ThermalState property
CIMTYPE         'uint16'
Description     'The ThermalState property identifies the enclosure's thermal state when last booted.'
MappingStrings  ['SMBIOS|Type 3|System Enclosure or Chassis|Thermal State']
read            True
ValueMap        ['1', '2', '3', '4', '5', '6']
Values          ['Other', 'Unknown', 'Safe', 'Warning', 'Critical', 'Non-recoverable']
ThermalState property is in 1 class (Win32_ComputerSystem) of ROOT\cimv2 and in 2 namespaces

You could create an enum

enum ThermalState {
Other          = 1
Unknown        = 2
Safe           = 3
Warning        = 4
Critical       = 5
NonRecoverable = 6
}

And use that to get a verbose response from the property

Get-WmiObject win32_computersystem | Select-Object Name, Model, Caption,
    @{n="Timezone"; e={$_.currenttimezone}}, Description, DNShostname,Domain,
    @{n='Domain Role';E={$_.domainrole}},Roles,Status,
    @{n='System Type'; e={$_.systemtype}},
    @{n='Thermal State'; e={[ThermalState]$_.thermalstate}}

Sample output

Name          : HP-G1610
Model         : ProLiant MicroServer Gen8
Caption       : HP-G1610
Timezone      : 120
Description   : AT/AT COMPATIBLE
DNShostname   : HP-G1610
Domain        : DOMAIN
Domain Role   : 0
Roles         : {...}
Status        : OK
System Type   : x64-based PC
Thermal State : Safe

In general to get a list of an enum :

> $Enum ='System.DayOfWeek'
> [Enum]::GetValues($Enum) | ForEach-Object {'{0} {1}' -f [int]$_,$_ }
0 Sunday
1 Monday
2 Tuesday
3 Wednesday
4 Thursday
5 Friday
6 Saturday


来源: stackexchange

问:
Modal dialog hide behind Main Frame after swich focus
I have a swing application, basically, a main frame that could pop up a modal dialog.
When the modal dialog is showing, if I switch to another window, like firefox. And then switch back to the swing application. The JDialog is not in front any more.

I don't want to set the dialog AlwaysOnTop to be true. because then the dialog will be on top of all windows include windows in other process.

So what should I do so that when I swich back, the modal dialog still on top?

BTW: it is a Applet, so the main frame is actually be set in this way:

```<code>private static Frame findParentFrame(Container owner){
    Container c = owner;
    while(c != null){
        if (c instanceof Frame)
            return (Frame)c;
        c = c.getParent();
    }
    return (Frame)null;
}
</code>```

答: I think what you're asking is for a dialog that's modal to the Java application/frame that is it's parent. When the parent regains focus you can use Toolkit.getDefaultToolkit().getSystemEventQueue(). postEvent(AWTEvent e) to fire an event to the dialog to make it pop back to the top.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a swing application, basically, a main frame that could pop up a modal dialog.
When the modal dialog is showing, if I switch to another window, like firefox. And then switch back to the swing application. The JDialog is not in front any more.

I don't want to set the dialog AlwaysOnTop to be true. because then the dialog will be on top of all windows include windows in other process.

So what should I do so that when I swich back, the modal dialog still on top?

BTW: it is a Applet, so the main frame is actually be set in this way:

private static Frame findParentFrame(Container owner){
    Container c = owner;
    while(c != null){
        if (c instanceof Frame)
            return (Frame)c;
        c = c.getParent();
    }
    return (Frame)null;
}


问:
Sentry doesn't show HttpContext User info in ASP.NET Core application
I've only used the base Sentry configuration from the webPage.

```<code>  "Sentry": {
    "Dsn": "",
    "IncludeRequestPayload": true,
    "SendDefaultPii": true,
    "MinimumBreadcrumbLevel": "Debug",
    "MinimumEventLevel": "Warning",
    "AttachStackTrace": true,
    "Debug": true,
    "DiagnosticsLevel": "Error"
  }
</code>```

From what I've gathered I should see User info which Setry picks up using its middleware from HttpContext.User.

But on the webPage I only see Ip ::1

Should I configure something else ? I can't seem to find any extra configuration.

EDIT

I'm using Sentry version 1.2.0. My HttpContext.

User is set for sure with user information.

For Authentication I'm using Jwt Tokens

```<code>services.AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; })
</code>```

Regards

答:
The latest release (version 1.2.0, from 8 days ago) includes a bug fix where the user when set manually by the application was not reported correctly.

In any case, a user existing in the request should be automatically reported by reading the ClaimsPrincipal. This can be changed by adding your own implementation of IUserFactory to the container which allows you to create a User object by inspecting the HttpContext.

In case you are on version 1.2.0 and still have problems, please raise an issue in the GitHub repository for the Sentry .NET SDK:

https://github.com/getsentry/sentry-dotnet/issues/new

ContentLicense: CC BY-SA 4.0

Body:
I've only used the base Sentry configuration from the webPage.

  "Sentry": {
    "Dsn": "",
    "IncludeRequestPayload": true,
    "SendDefaultPii": true,
    "MinimumBreadcrumbLevel": "Debug",
    "MinimumEventLevel": "Warning",
    "AttachStackTrace": true,
    "Debug": true,
    "DiagnosticsLevel": "Error"
  }

From what I've gathered I should see User info which Setry picks up using its middleware from HttpContext.User.

But on the webPage I only see Ip ::1

Should I configure something else ? I can't seem to find any extra configuration.

EDIT

I'm using Sentry version 1.2.0. My HttpContext.

User is set for sure with user information.

For Authentication I'm using Jwt Tokens

services.AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; })

Regards


问:
Cypress - Can't type in field
I have problem with typing in one of my fields in automated test.
I can't get this field but I don't know why.

This is my code:

cy.get('#reasonRecommendationByAgent')
  .type('Zdůvodnění doporučení zprostředkovatele', {force: true})
  .should('have.value', 'Zdůvodnění doporučení zprostředkovatele')
```

And this is the error message:

Is there anyone who has the same problem?

答:
Try adding a click() before you type:

cy.get('#reasonRecommendationByAgent')
  .click()
  .type('Zdůvodnění doporučení zprostředkovatele', {force: true})
  .should('have.value', 'Zdůvodnění doporučení zprostředkovatele')
```

Title: Cypress - Can't type in field

Body:
I have problem with typing in one of my fields in automated test.
I can't get this field but I don't know why.

This is my code:

cy.get('#reasonRecommendationByAgent')
  .type('Zdůvodnění doporučení zprostředkovatele', {force: true})
  .should('have.value', 'Zdůvodnění doporučení zprostředkovatele')

And this is the error message:

Is there anyone who has the same problem?


问:
how do I group, sort and take out the first N in mysql?
I can get the sorted data in the group, and finally take out the first N in DolphinDB.

But how do I group, sort and take out the first N in mysql?

Thank you first.

The DolphinDB code is as follows：

```<code>sym = `C`MS`MS`MS`IBM`IBM`C`C`C$symbol;
price= 49.6 29.46 29.52 30.02 174.97 175.23 50.76 50.32 51.29;
qty = 2200 1900 2100 3200 6800 5400 1300 2500 8800;
timestamp = [09:34:07,09:36:42,09:36:51,09:36:59,09:32:47,09:35:26,09:34:16,09:34:26,09:38:12];
t1 = table(timestamp, sym, qty, price);
select top 2 * from t1 context by sym csort timestamp;

timestamp sym qty  price
--------- --- ---- ------
09:34:07  C   2200 49.6
09:34:16  C   1300 50.76
09:32:47  IBM 6800 174.97
09:35:26  IBM 5400 175.23
09:36:42  MS  1900 29.46
09:36:51  MS  2100 29.52

</code>```

答:
If you have MySQLv8.0 that supports ROW_NUMBER() you can use something like this:

```<code> SELECT `timestamp`,sym,qty,price
  FROM
      (
      SELECT
      `timestamp`,sym,qty,price,ROW_NUMBER() OVER (PARTITION BY sym ORDER BY timestamp ASC) AS ranking
      FROM `table`
      ) t
WHERE ranking<3
</code>```

https://www.db-fiddle.com/f/8fY2DJmCCv7kCnEAPBAU3B/0

Body:
I can get the sorted data in the group, and finally take out the first N in DolphinDB.

But how do I group, sort and take out the first N in mysql?

Thank you first.

The DolphinDB code is as follows：

sym = `C`MS`MS`MS`IBM`IBM`C`C`C$symbol;
price= 49.6 29.46 29.52 30.02 174.97 175.23 50.76 50.32 51.29;
qty = 2200 1900 2100 3200 6800 5400 1300 2500 8800;
timestamp = [09:34:07,09:36:42,09:36:51,09:36:59,09:32:47,09:35:26,09:34:16,09:34:26,09:38:12];
t1 = table(timestamp, sym, qty, price);
select top 2 * from t1 context by sym csort timestamp;

timestamp sym qty  price
--------- --- ---- ------
09:34:07  C   2200 49.6
09:34:16  C   1300 50.76
09:32:47  IBM 6800 174.97
09:35:26  IBM 5400 175.23
09:36:42  MS  1900 29.46
09:36:51  MS  2100 29.52

Body:
If you have MySQLv8.0 that supports ROW_NUMBER() you can use something like this:

 SELECT `timestamp`,sym,qty,price
  FROM
      (
      SELECT
      `timestamp`,sym,qty,price,ROW_NUMBER() OVER (PARTITION BY sym ORDER BY timestamp ASC) AS ranking
      FROM `table`
      ) t
WHERE ranking<3

https://www.db-fiddle.com/f/8fY2DJmCCv7kCnEAPBAU3B/0


问:
How do you read a file inside a zip file as text, not bytes?
A simple program for reading a CSV file inside a ZIP archive:

import csv, sys, zipfile

zip_file    = zipfile.ZipFile(sys.argv[1])
items_file  = zip_file.open('items.csv', 'rU')

for row in csv.DictReader(items_file):
    pass
```
<p>works in Python 2.7:</p>
<pre class="lang-none prettyprint-override"><code>$ python2.7 test_zip_file_py3k.py ~/data.zip
$
</code>```

but not in Python 3.2:

$ python3.2 test_zip_file_py3k.py ~/data.zip
Traceback (most recent call last):
    File "test_zip_file_py3k.py", line 8, in <module>
    for row in csv.DictReader(items_file):
    File "/somedir/python3.2/csv.py", line 109, in __next__
    self.fieldnames
    File "/somedir/python3.2/csv.py", line 96, in fieldnames
    self._fieldnames = next(self.reader)
_csv.Error: iterator should return strings, not bytes (did you open the file
in text mode?)
```

The csv module in Python 3 wants to see a text file, but zipfile.ZipFile.open returns a zipfile.ZipExtFile that is always treated as binary data.

How does one make this work in Python 3?

答:
Lennart's answer is on the right track (Thanks, Lennart, I voted up your answer) and it almost works:

```<code>$ cat test_zip_file_py3k.py
import csv, io, sys, zipfile

zip_file    = zipfile.ZipFile(sys.argv[1])
items_file  = zip_file.open('items.csv', 'rU')
items_file  = io.TextIOWrapper(items_file, encoding='iso-8859-1', newline='')

for idx, row in enumerate(csv.DictReader(items_file)):
    print('Processing row {0}'.format(idx))

$ python3.1 test_zip_file_py3k.py ~/data.zip
Traceback (most recent call last):
  File "test_zip_file_py3k.py", line 7, in <module>
    items_file  = io.TextIOWrapper(items_file,
                                   encoding='iso-8859-1',
                                   newline='')
AttributeError: readable
</code>```

The problem appears to be that io.TextWrapper's first required parameter is a buffer; not a file object.

This appears to work:

```<code>items_file  = io.TextIOWrapper(io.BytesIO(items_file.read()))
</code>```

This seems a little complex and also it seems annoying to have to read in a whole (perhaps huge) zip file into memory. Any better way?

Here it is in action:

```<code>$ cat test_zip_file_py3k.py
import csv, io, sys, zipfile

zip_file    = zipfile.ZipFile(sys.argv[1])
items_file  = zip_file.open('items.csv', 'rU')
items_file  = io.TextIOWrapper(io.BytesIO(items_file.read()))

for idx, row in enumerate(csv.DictReader(items_file)):
    print('Processing row {0}'.format(idx))

$ python3.1 test_zip_file_py3k.py ~/data.zip
Processing row 0
Processing row 1
Processing row 2
...
Processing row 250
</code>```

Body:
A simple program for reading a CSV file inside a ZIP archive:

import csv, sys, zipfile

zip_file    = zipfile.ZipFile(sys.argv[1])
items_file  = zip_file.open('items.csv', 'rU')

for row in csv.DictReader(items_file):
    pass

works in Python 2.7:

$ python2.7 test_zip_file_py3k.py ~/data.zip
$

but not in Python 3.2:

$ python3.2 test_zip_file_py3k.py ~/data.zip
Traceback (most recent call last):
    File "test_zip_file_py3k.py", line 8, in <module>
    for row in csv.DictReader(items_file):
    File "/somedir/python3.2/csv.py", line 109, in __next__
    self.fieldnames
    File "/somedir/python3.2/csv.py", line 96, in fieldnames
    self._fieldnames = next(self.reader)
_csv.Error: iterator should return strings, not bytes (did you open the file
in text mode?)

The csv module in Python 3 wants to see a text file, but zipfile.ZipFile.open returns a zipfile.ZipExtFile that is always treated as binary data.

How does one make this work in Python 3?

Body:
Lennart's answer is on the right track (Thanks, Lennart, I voted up your answer) and it almost works:

$ cat test_zip_file_py3k.py
import csv, io, sys, zipfile

zip_file    = zipfile.ZipFile(sys.argv[1])
items_file  = zip_file.open('items.csv', 'rU')
items_file  = io.TextIOWrapper(items_file, encoding='iso-8859-1', newline='')

for idx, row in enumerate(csv.DictReader(items_file)):
    print('Processing row {0}'.format(idx))

$ python3.1 test_zip_file_py3k.py ~/data.zip
Traceback (most recent call last):
  File "test_zip_file_py3k.py", line 7, in <module>
    items_file  = io.TextIOWrapper(items_file,
                                   encoding='iso-8859-1',
                                   newline='')
AttributeError: readable

The problem appears to be that io.TextWrapper's first required parameter is a buffer; not a file object.

This appears to work:

items_file  = io.TextIOWrapper(io.BytesIO(items_file.read()))

This seems a little complex and also it seems annoying to have to read in a whole (perhaps huge) zip file into memory. Any better way?

Here it is in action:

$ cat test_zip_file_py3k.py
import csv, io, sys, zipfile

zip_file    = zipfile.ZipFile(sys.argv[1])
items_file  = zip_file.open('items.csv', 'rU')
items_file  = io.TextIOWrapper(io.BytesIO(items_file.read()))

for idx, row in enumerate(csv.DictReader(items_file)):
    print('Processing row {0}'.format(idx))

$ python3.1 test_zip_file_py3k.py ~/data.zip
Processing row 0
Processing row 1
Processing row 2
...
Processing row 250


问:
Android Picasso Recyclerview Image downloading slow
I have endless recyclerview that almost mimics Instagram list/feeds. Where Image is loading into full screen width Imageview. I am using Picasso to load images. Here is my code:

```<code>public class HomeAdapter extends RecyclerView.Adapter {

Context context;

private Contract contract;

List<Feed> feeds;

static final int ITEM_TYPE_HEADER = 0;

static final int ITEM_TYPE_LOAD_MORE = 1;

static final int ITEM_TYPE_DESIGN = 2;

public HomeAdapter(Context context, List<Feed> feeds) {
    this.context = context;
    this.feeds = feeds;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View row;
    if (viewType == ITEM_TYPE_HEADER) {
        row = inflater.inflate(R.layout.list_item_home_header, parent, false);
        return new HeaderHolder(row);
    } else if (viewType == ITEM_TYPE_LOAD_MORE) {
        row = inflater.inflate(R.layout.list_item_load_more, parent, false);
        return new LoadMoreHolder(row);
    } else if (viewType == ITEM_TYPE_DESIGN) {
        row = inflater.inflate(R.layout.list_item_feed_home, parent, false);
        return new DesignItemHolder(row);
    }
    return null;
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
    Feed feed = feeds.get(position);
    if (holder instanceof HeaderHolder) {
        HeaderHolder headerHolder = (HeaderHolder) holder;
        Header header = (Header) feed;
        headerHolder.tvTitle.setText(header.getTitle());
        headerHolder.tvDescription.setText(header.getDescription());

    } else if (holder instanceof LoadMoreHolder) {
        LoadMoreHolder loadMoreHolder = (LoadMoreHolder) holder;
        LoadMore loadMore = (LoadMore) feed;
        if(loadMore.getType() == LOAD_MORE_TYPE_PROGRESS) {
            loadMoreHolder.pbLoadMore.setVisibility(View.VISIBLE);
            loadMoreHolder.rlMessageRetry.setVisibility(View.GONE);
        } else {
            loadMoreHolder.pbLoadMore.setVisibility(View.GONE);
            loadMoreHolder.rlMessageRetry.setVisibility(View.VISIBLE);
            if(StringUtils.isValid(loadMore.getTitle())) {
                loadMoreHolder.tvTitle.setText(loadMore.getTitle());
                loadMoreHolder.tvTitle.setVisibility(View.VISIBLE);
            } else
                loadMoreHolder.tvTitle.setVisibility(View.GONE);

            if(StringUtils.isValid(loadMore.getDescription())) {
                loadMoreHolder.tvDescription.setText(loadMore.getDescription());
                loadMoreHolder.tvDescription.setVisibility(View.VISIBLE);
            } else
                loadMoreHolder.tvDescription.setVisibility(View.GONE);
        }

        loadMoreHolder.btnRetry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onRetryLoadMoreClick();
            }
        });

    } else if (holder instanceof DesignItemHolder) {
        final DesignItemHolder designItemHolder = (DesignItemHolder) holder;
        final DesignFeed designFeed = (DesignFeed) feed;
        String title = getFeedTitle(designFeed.getDesignCategory().getTitle(), designFeed.getEvent().getTitle());
        designItemHolder.tvCategory.setText(StringUtils.toUpperCaseSentence(designFeed.getDesignCategory().getTitle()));
        designItemHolder.tvDate.setText(DateTimeUtils.formatTime(designFeed.getDate()));
        designItemHolder.tvTitle.setText(StringUtils.toUpperCaseSentence(title));
        designItemHolder.tvBrand.setText(getBrandTitle(designFeed.getBrand().getTitle()));

        if(StringUtils.isValid(designFeed.getShopLink())) {
            designItemHolder.tvShop.setVisibility(View.VISIBLE);
            if(StringUtils.isValid(designFeed.getPrice())) {
                designItemHolder.tvPrice.setVisibility(View.VISIBLE);
                designItemHolder.tvPrice.setText(designFeed.getPrice() + " PKR");
            } else
                designItemHolder.tvPrice.setVisibility(View.GONE);

            designItemHolder.tvShop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(contract != null)
                        contract.onOpenShopLink(designFeed.getShopLink());
                }
            });
        }
        else {
            designItemHolder.tvPrice.setVisibility(View.GONE);
            designItemHolder.tvShop.setVisibility(View.GONE);
        }

        showFeedImage(designFeed, designItemHolder.ivThumbnail, designItemHolder.progressBar);

        Picasso.get()
                .load(designFeed.getDesignCategory().getThumbnail())
                .transform(new CircleTransform())
                .placeholder(new ColorDrawable(ContextCompat.getColor(context, R.color.colorGreyLight)))
                .into(designItemHolder.ivCategory);

        designItemHolder.ivThumbnail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onDesignFeedClick(designFeed);
            }
        });

        designItemHolder.tvCategory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onDesignCategoryClick(designFeed.getDesignCategory());
            }
        });

        designItemHolder.ivCategory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onDesignCategoryClick(designFeed.getDesignCategory());
            }
        });

        designItemHolder.tvTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onDesignCategoryClick(designFeed.getDesignCategory());
            }
        });

        designItemHolder.tvBrand.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onBrandClick(designFeed.getBrand());
            }
        });

        designItemHolder.ibFavourite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onFavouriteClick(designFeed);
            }
        });

        designItemHolder.ibShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onShareClick(designFeed);
            }
        });

        designItemHolder.ibDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onDownloadClick(designFeed);
            }
        });
    }
}

private void showFeedImage(final DesignFeed designFeed, final ImageView ivThumbnail, final ProgressBar progressBar) {
    Picasso.get()
            .load(designFeed.getThumbnail())
            .placeholder(new ColorDrawable(ContextCompat.getColor(context, R.color.colorGreyLight)))
            .networkPolicy(NetworkPolicy.OFFLINE)
            .into(ivThumbnail, new Callback() {
                @Override
                public void onSuccess() {
                }

                @Override
                public void onError(Exception e) {
                    //Try again online if cache failed
                    Picasso.get()
                            .load(designFeed.getThumbnail())
                            .placeholder(new ColorDrawable(ContextCompat.getColor(context, R.color.colorGreyLight)))
                            .into(ivThumbnail, new Callback() {
                                @Override
                                public void onSuccess() {
                                }

                                @Override
                                public void onError(Exception e) {

                                }
                            });
                }
            });
}

@Override
public int getItemViewType(int position) {
    Feed feed = feeds.get(position);
    if (feed instanceof Header)
        return ITEM_TYPE_HEADER;
    else if (feed instanceof LoadMore)
        return ITEM_TYPE_LOAD_MORE;
    else if (feed instanceof DesignFeed)
        return ITEM_TYPE_DESIGN;
    else
        return super.getItemViewType(position);
}

@Override
public int getItemCount() {
    return feeds.size();
}

public void insertFeedAtStart(Feed feed) {
    feeds.add(0, feed);
    notifyDataSetChanged();
}

public void updateFeeds(ArrayList<Feed> mFeeds) {
    feeds.addAll(mFeeds);
    notifyDataSetChanged();
}

public void addLoadMoreItem(Feed loadMoreFeed) {
    feeds.add(loadMoreFeed);
    notifyItemInserted(getItemCount() - 1);
}

public void removeItem(int index) {
    feeds.remove(index);
    notifyDataSetChanged();
}

private class DesignItemHolder extends RecyclerView.ViewHolder {
    TextView tvTitle, tvCategory, tvBrand, tvDate, tvPrice, tvShop;
    ImageView ivCategory, ivThumbnail;
    ImageButton ibFavourite, ibShare, ibDownload;
    ProgressBar progressBar;

    DesignItemHolder(View itemView) {
        super(itemView);
        tvTitle = itemView.findViewById(R.id.tvTitle);
        tvCategory = itemView.findViewById(R.id.tvCategory);
        tvBrand = itemView.findViewById(R.id.tvBrand);
        tvDate = itemView.findViewById(R.id.tvDate);
        ivCategory = itemView.findViewById(R.id.ivCategory);
        ivThumbnail = itemView.findViewById(R.id.ivThumbnail);
        tvPrice = itemView.findViewById(R.id.tvPrice);
        tvShop = itemView.findViewById(R.id.tvShop);
        ibFavourite = itemView.findViewById(R.id.ibFavourite);
        ibShare = itemView.findViewById(R.id.ibShare);
        ibDownload = itemView.findViewById(R.id.ibDownload);
        progressBar = itemView.findViewById(R.id.progressBar);
    }
}

private class HeaderHolder extends RecyclerView.ViewHolder {
    TextView tvTitle, tvDescription;
    HeaderHolder(View itemView) {
        super(itemView);
        tvTitle = itemView.findViewById(R.id.tvTitle);
        tvDescription = itemView.findViewById(R.id.tvDescription);
    }
}

private class LoadMoreHolder extends RecyclerView.ViewHolder {
    ProgressBar pbLoadMore;
    RelativeLayout rlMessageRetry;
    TextView tvTitle, tvDescription;
    AppCompatButton btnRetry;

    LoadMoreHolder(View itemView) {
        super(itemView);
        pbLoadMore = itemView.findViewById(R.id.pbLoadMore);
        rlMessageRetry = itemView.findViewById(R.id.rlMessageRetry);
        tvTitle = itemView.findViewById(R.id.tvTitle);
        tvDescription = itemView.findViewById(R.id.tvDescription);
        btnRetry = itemView.findViewById(R.id.btnRetry);
    }
}

public void setContract(Contract contract) {
    this.contract = contract;
}

public interface Contract {

    void onDesignCategoryClick(DesignCategory designCategory);

    void onDesignFeedClick(DesignFeed designCategory);

    void onBrandClick(Brand brand);

    void onRetryLoadMoreClick();

    void onShopClick(String shopLink);

    void onFavouriteClick(DesignFeed designFeed);

    void onShareClick(DesignFeed designFeed);

    void onDownloadClick(DesignFeed designFeed);

    void onOpenShopLink(String shopLink);
}
</code>```

}

Average image size is 80-100 kbs. But image download time is too slow. It almost takes 3-4 seconds to download an image. On the other hand when images are loading from cache it obviously loads an image in no time. I get 15 items from server to load into recyclerview which means 15 images would be downloading in parallel. But still it is quite slow as compared to Instagram or Facebook feeds.

Can anyone guide me about the correct technique to make it as fast as possible, so that when user scrolls down the list images should be already loaded instead him waiting for image to load?

答:
Actually, I have been using the lib for a long time without any networking issue. I tried to analyze the code and found out followings:

The problem could be the transformation Since lib first transforms incoming image then display, Please refer this part

Picasso.get()

```<code>    .load(designFeed.getDesignCategory().getThumbnail())
    .transform(new CircleTransform())
    .placeholder(new ColorDrawable(ContextCompat.getColor(context,
     R.color.colorGreyLight)))
    .into(designItemHolder.ivCategory);
</code>```

Advice: if you are trying to show image in circular view. Then use CircularImageView, do not free I/O.

Check the performance with other a little powerful devices than yours

EDIT

Check your phone for network usage, which app is consuming, how much megabytes, Since some applications silently use your network in the background

Why it is fast in your browser? Because your browser is not doing any extra operation on the image

Body:
I have endless recyclerview that almost mimics Instagram list/feeds. Where Image is loading into full screen width Imageview. I am using Picasso to load images. Here is my code:

public class HomeAdapter extends RecyclerView.Adapter {

Context context;

private Contract contract;

List<Feed> feeds;

static final int ITEM_TYPE_HEADER = 0;

static final int ITEM_TYPE_LOAD_MORE = 1;

static final int ITEM_TYPE_DESIGN = 2;

public HomeAdapter(Context context, List<Feed> feeds) {
    this.context = context;
    this.feeds = feeds;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View row;
    if (viewType == ITEM_TYPE_HEADER) {
        row = inflater.inflate(R.layout.list_item_home_header, parent, false);
        return new HeaderHolder(row);
    } else if (viewType == ITEM_TYPE_LOAD_MORE) {
        row = inflater.inflate(R.layout.list_item_load_more, parent, false);
        return new LoadMoreHolder(row);
    } else if (viewType == ITEM_TYPE_DESIGN) {
        row = inflater.inflate(R.layout.list_item_feed_home, parent, false);
        return new DesignItemHolder(row);
    }
    return null;
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
    Feed feed = feeds.get(position);
    if (holder instanceof HeaderHolder) {
        HeaderHolder headerHolder = (HeaderHolder) holder;
        Header header = (Header) feed;
        headerHolder.tvTitle.setText(header.getTitle());
        headerHolder.tvDescription.setText(header.getDescription());

    } else if (holder instanceof LoadMoreHolder) {
        LoadMoreHolder loadMoreHolder = (LoadMoreHolder) holder;
        LoadMore loadMore = (LoadMore) feed;
        if(loadMore.getType() == LOAD_MORE_TYPE_PROGRESS) {
            loadMoreHolder.pbLoadMore.setVisibility(View.VISIBLE);
            loadMoreHolder.rlMessageRetry.setVisibility(View.GONE);
        } else {
            loadMoreHolder.pbLoadMore.setVisibility(View.GONE);
            loadMoreHolder.rlMessageRetry.setVisibility(View.VISIBLE);
            if(StringUtils.isValid(loadMore.getTitle())) {
                loadMoreHolder.tvTitle.setText(loadMore.getTitle());
                loadMoreHolder.tvTitle.setVisibility(View.VISIBLE);
            } else
                loadMoreHolder.tvTitle.setVisibility(View.GONE);

            if(StringUtils.isValid(loadMore.getDescription())) {
                loadMoreHolder.tvDescription.setText(loadMore.getDescription());
                loadMoreHolder.tvDescription.setVisibility(View.VISIBLE);
            } else
                loadMoreHolder.tvDescription.setVisibility(View.GONE);
        }

        loadMoreHolder.btnRetry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onRetryLoadMoreClick();
            }
        });

    } else if (holder instanceof DesignItemHolder) {
        final DesignItemHolder designItemHolder = (DesignItemHolder) holder;
        final DesignFeed designFeed = (DesignFeed) feed;
        String title = getFeedTitle(designFeed.getDesignCategory().getTitle(), designFeed.getEvent().getTitle());
        designItemHolder.tvCategory.setText(StringUtils.toUpperCaseSentence(designFeed.getDesignCategory().getTitle()));
        designItemHolder.tvDate.setText(DateTimeUtils.formatTime(designFeed.getDate()));
        designItemHolder.tvTitle.setText(StringUtils.toUpperCaseSentence(title));
        designItemHolder.tvBrand.setText(getBrandTitle(designFeed.getBrand().getTitle()));

        if(StringUtils.isValid(designFeed.getShopLink())) {
            designItemHolder.tvShop.setVisibility(View.VISIBLE);
            if(StringUtils.isValid(designFeed.getPrice())) {
                designItemHolder.tvPrice.setVisibility(View.VISIBLE);
                designItemHolder.tvPrice.setText(designFeed.getPrice() + " PKR");
            } else
                designItemHolder.tvPrice.setVisibility(View.GONE);

            designItemHolder.tvShop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(contract != null)
                        contract.onOpenShopLink(designFeed.getShopLink());
                }
            });
        }
        else {
            designItemHolder.tvPrice.setVisibility(View.GONE);
            designItemHolder.tvShop.setVisibility(View.GONE);
        }

        showFeedImage(designFeed, designItemHolder.ivThumbnail, designItemHolder.progressBar);

        Picasso.get()
                .load(designFeed.getDesignCategory().getThumbnail())
                .transform(new CircleTransform())
                .placeholder(new ColorDrawable(ContextCompat.getColor(context, R.color.colorGreyLight)))
                .into(designItemHolder.ivCategory);

        designItemHolder.ivThumbnail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onDesignFeedClick(designFeed);
            }
        });

        designItemHolder.tvCategory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onDesignCategoryClick(designFeed.getDesignCategory());
            }
        });

        designItemHolder.ivCategory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onDesignCategoryClick(designFeed.getDesignCategory());
            }
        });

        designItemHolder.tvTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onDesignCategoryClick(designFeed.getDesignCategory());
            }
        });

        designItemHolder.tvBrand.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onBrandClick(designFeed.getBrand());
            }
        });

        designItemHolder.ibFavourite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onFavouriteClick(designFeed);
            }
        });

        designItemHolder.ibShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onShareClick(designFeed);
            }
        });

        designItemHolder.ibDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onDownloadClick(designFeed);
            }
        });
    }
}

private void showFeedImage(final DesignFeed designFeed, final ImageView ivThumbnail, final ProgressBar progressBar) {
    Picasso.get()
            .load(designFeed.getThumbnail())
            .placeholder(new ColorDrawable(ContextCompat.getColor(context, R.color.colorGreyLight)))
            .networkPolicy(NetworkPolicy.OFFLINE)
            .into(ivThumbnail, new Callback() {
                @Override
                public void onSuccess() {
                }

                @Override
                public void onError(Exception e) {
                    //Try again online if cache failed
                    Picasso.get()
                            .load(designFeed.getThumbnail())
                            .placeholder(new ColorDrawable(ContextCompat.getColor(context, R.color.colorGreyLight)))
                            .into(ivThumbnail, new Callback() {
                                @Override
                                public void onSuccess() {
                                }

                                @Override
                                public void onError(Exception e) {

                                }
                            });
                }
            });
}

@Override
public int getItemViewType(int position) {
    Feed feed = feeds.get(position);
    if (feed instanceof Header)
        return ITEM_TYPE_HEADER;
    else if (feed instanceof LoadMore)
        return ITEM_TYPE_LOAD_MORE;
    else if (feed instanceof DesignFeed)
        return ITEM_TYPE_DESIGN;
    else
        return super.getItemViewType(position);
}

@Override
public int getItemCount() {
    return feeds.size();
}

public void insertFeedAtStart(Feed feed) {
    feeds.add(0, feed);
    notifyDataSetChanged();
}

public void updateFeeds(ArrayList<Feed> mFeeds) {
    feeds.addAll(mFeeds);
    notifyDataSetChanged();
}

public void addLoadMoreItem(Feed loadMoreFeed) {
    feeds.add(loadMoreFeed);
    notifyItemInserted(getItemCount() - 1);
}

public void removeItem(int index) {
    feeds.remove(index);
    notifyDataSetChanged();
}

private class DesignItemHolder extends RecyclerView.ViewHolder {
    TextView tvTitle, tvCategory, tvBrand, tvDate, tvPrice, tvShop;
    ImageView ivCategory, ivThumbnail;
    ImageButton ibFavourite, ibShare, ibDownload;
    ProgressBar progressBar;

    DesignItemHolder(View itemView) {
        super(itemView);
        tvTitle = itemView.findViewById(R.id.tvTitle);
        tvCategory = itemView.findViewById(R.id.tvCategory);
        tvBrand = itemView.findViewById(R.id.tvBrand);
        tvDate = itemView.findViewById(R.id.tvDate);
        ivCategory = itemView.findViewById(R.id.ivCategory);
        ivThumbnail = itemView.findViewById(R.id.ivThumbnail);
        tvPrice = itemView.findViewById(R.id.tvPrice);
        tvShop = itemView.findViewById(R.id.tvShop);
        ibFavourite = itemView.findViewById(R.id.ibFavourite);
        ibShare = itemView.findViewById(R.id.ibShare);
        ibDownload = itemView.findViewById(R.id.ibDownload);
        progressBar = itemView.findViewById(R.id.progressBar);
    }
}

private class HeaderHolder extends RecyclerView.ViewHolder {
    TextView tvTitle, tvDescription;
    HeaderHolder(View itemView) {
        super(itemView);
        tvTitle = itemView.findViewById(R.id.tvTitle);
        tvDescription = itemView.findViewById(R.id.tvDescription);
    }
}

private class LoadMoreHolder extends RecyclerView.ViewHolder {
    ProgressBar pbLoadMore;
    RelativeLayout rlMessageRetry;
    TextView tvTitle, tvDescription;
    AppCompatButton btnRetry;

    LoadMoreHolder(View itemView) {
        super(itemView);
        pbLoadMore = itemView.findViewById(R.id.pbLoadMore);
        rlMessageRetry = itemView.findViewById(R.id.rlMessageRetry);
        tvTitle = itemView.findViewById(R.id.tvTitle);
        tvDescription = itemView.findViewById(R.id.tvDescription);
        btnRetry = itemView.findViewById(R.id.btnRetry);
    }
}

public void setContract(Contract contract) {
    this.contract = contract;
}

public interface Contract {

    void onDesignCategoryClick(DesignCategory designCategory);

    void onDesignFeedClick(DesignFeed designCategory);

    void onBrandClick(Brand brand);

    void onRetryLoadMoreClick();

    void onShopClick(String shopLink);

    void onFavouriteClick(DesignFeed designFeed);

    void onShareClick(DesignFeed designFeed);

    void onDownloadClick(DesignFeed designFeed);

    void onOpenShopLink(String shopLink);
}

}

Average image size is 80-100 kbs. But image download time is too slow. It almost takes 3-4 seconds to download an image. On the other hand when images are loading from cache it obviously loads an image in no time. I get 15 items from server to load into recyclerview which means 15 images would be downloading in parallel. But still it is quite slow as compared to Instagram or Facebook feeds.

Can anyone guide me about the correct technique to make it as fast as possible, so that when user scrolls down the list images should be already loaded instead him waiting for image to load?

Body:
Actually, I have been using the lib for a long time without any networking issue. I tried to analyze the code and found out followings:

The problem could be the transformation Since lib first transforms incoming image then display, Please refer this part

Picasso.get()

    .load(designFeed.getDesignCategory().getThumbnail())
    .transform(new CircleTransform())
    .placeholder(new ColorDrawable(ContextCompat.getColor(context,
     R.color.colorGreyLight)))
    .into(designItemHolder.ivCategory);

Advice: if you are trying to show image in circular view. Then use CircularImageView, do not free I/O.

Check the performance with other a little powerful devices than yours

EDIT

Check your phone for network usage, which app is consuming, how much megabytes, Since some applications silently use your network in the background

Why it is fast in your browser? Because your browser is not doing any extra operation on the image


问:
Jquery dragabble containment - selector not working
My JQuery draggable containment is not working .It keeps going beyond the boundaries set for it. Any help is appreciated.</p>

```<code>     $(function() {
        $( "#crop_square" ).draggable();
        containment: "#area_c"

     });

    <div  id ="area_c" style="width:300px;height:300px;background:blue"  >

           <div id="crop_square"      style="width:100px;height:100px;border:2px solid black;background:none"></div>

     </div>
</code>```

答:
You're not appending the containment option correctly, do it this way (passing the option as an argument to the plugin call) :

```<code> $( "#crop_square" ).draggable({
    containment: "#area_c"
 });
</code>```

Working snippet below :

 $(function() {
        $( "#crop_square" ).draggable({ containment: "#area_c" });
 });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div  id ="area_c" style="width:300px;height:300px;background:blue"  >

           <div id="crop_square"      style="width:100px;height:100px;border:2px solid black;background:none">drag</div>

     </div></code>```

More infos on the draggable widget options here.

Body:
My JQuery draggable containment is not working .It keeps going beyond the boundaries set for it. Any help is appreciated.

     $(function() {
        $( "#crop_square" ).draggable();
        containment: "#area_c"

     });

Body:
You're not appending the containment option correctly, do it this way (passing the option as an argument to the plugin call) :

 $( "#crop_square" ).draggable({
    containment: "#area_c"
 });

Working snippet below :

 $(function() {
        $( "#crop_square" ).draggable({ containment: "#area_c" });
 });

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div  id ="area_c" style="width:300px;height:300px;background:blue"  >

           <div id="crop_square"      style="width:100px;height:100px;border:2px solid black;background:none">drag</div>

     </div>

More infos on the draggable widget options here.


问:
Kubernetes "nice" a pod's CPU usage
I have a cluster w/ 3 nodes.  Hurray!  The cluster doesn't autoscale nodes.

These nodes run an amazing web app, yet most of the time do almost nothing.

I also have a background process that could use an infinite amount of CPU (the usefulness drops rapidly but remains useful).

I want these background pods to run on each Node and slowed down to leave a 20% CPU headroom on the Node.  Or similar.

That's the shape of a DaemonSet.

Can I tell Kubernetes to deprioritize the DaemonSet Pods w/ a 20% headroom?

Can the DaemonSet Pods detect the Nodes CPU usage and deprioritize themselves (risky if buggy)?

QoS looks like it's for scheduling and evicting pods to make room for other pods, but they don't get 'niced'.

Priority also looks like it's for eviction.

答:
You may achieve what you're looking for in many ways.

I imagine that you've already read this and that, based on the theory of this other.

Also RedHat has nice documentation about setting hardware limits via softwarre.

Here you can find how to restrict cpu usage, which may be set inside a container to achieve what you're looking for.

So, to recap: with K8S you can set requests and limits, and inside the container you can set even further restrictive limits.

Hope this gives you the solution or at least the path to follow in order to achieve what you want.

Title: Kubernetes "nice" a pod's CPU usage


问:
Mysql not using DATETIME index when table has other fields
I need some help figuring this out. I'm trying to get Mysql to use an index on a DATETIME field.

Mysql decides not to use the index if there's other (not used) fields in the table. Consider the two cases below:

A simple table with 2 fields works fine:

```<code>DROP TABLE IF EXISTS datetime_index_test;
CREATE TABLE  datetime_index_test (
id INT UNSIGNED NOT NULL AUTO_INCREMENT ,
created DATETIME NOT NULL ,
PRIMARY KEY (id) ,
INDEX (created)
) ENGINE = InnoDB ;

INSERT INTO datetime_index_test (created) VALUES
('2011-04-06 00:00:00'),
('2011-04-06 01:00:00'),
('2011-04-06 02:00:00'),
('2011-04-06 03:00:00'),
('2011-04-06 04:00:00'),
('2011-04-06 05:00:00'),
('2011-04-06 06:00:00'),
('2011-04-06 00:00:00');

EXPLAIN SELECT * FROM datetime_index_test
WHERE created <= '2011-04-06 04:00:00';

+----+-------------+---------------------+-------+---------------+---------+---------+------+------+--------------------------+
| id | select_type | table               | type  | possible_keys | key     | key_len | ref  | rows | Extra                    |
+----+-------------+---------------------+-------+---------------+---------+---------+------+------+--------------------------+
|  1 | SIMPLE      | datetime_index_test | range | created       | created | 4       | NULL |    4 | Using where; Using index |
+----+-------------+---------------------+-------+---------------+---------+---------+------+------+--------------------------+
</code>```

A simple table with 3 fields, does not works fine:

```<code>DROP TABLE IF EXISTS datetime_index_test;
CREATE TABLE  datetime_index_test (
id INT UNSIGNED NOT NULL AUTO_INCREMENT ,
created DATETIME NOT NULL ,
user int(10) unsigned DEFAULT 0,
PRIMARY KEY (id) ,
INDEX (created)
) ENGINE = InnoDB ;

INSERT INTO datetime_index_test (created) VALUES
('2011-04-06 00:00:00'),
('2011-04-06 01:00:00'),
('2011-04-06 02:00:00'),
('2011-04-06 03:00:00'),
('2011-04-06 04:00:00'),
('2011-04-06 05:00:00'),
('2011-04-06 06:00:00'),
('2011-04-06 00:00:00');

EXPLAIN SELECT * FROM datetime_index_test
WHERE created <= '2011-04-06 04:00:00';

+----+-------------+---------------------+------+---------------+------+---------+------+------+-------------+
| id | select_type | table               | type | possible_keys | key  | key_len | ref  | rows | Extra       |
+----+-------------+---------------------+------+---------------+------+---------+------+------+-------------+
|  1 | SIMPLE      | datetime_index_test | ALL  | created       | NULL | NULL    | NULL |    8 | Using where |
+----+-------------+---------------------+------+---------------+------+---------+------+------+-------------+
</code>```

Finally, my question; Can anyone explain to me why Mysql decides not to use the index?

答:
This is due to what I call the 5% rule based on key population (tuple cardinality).

If you index a table where lopsided cardinality exist, the MySQL Query Optimizer wiill always choose the path of least resistance.

EXAMPLE : If a table has a gender column, cardinality is two, M and F.

What is you index such a gender column ??? You essentailly get two giant linked lists.

If you load one million rows into a table with a gender column, you may get 50% M and 50% F.

An index is rendered useless during query optimization if the cardinality of a key combo (key population as I phrased it) is more than 5% of the total table count.

Now, with regard to your example, why the two different EXPLAIN plans ??? My guess is the MySQL Query Optimizer and InnoDB as a tag team.

In the first CREATE TABLE, the table and the indexes are about the same size though small, so it decided in favor of the index by doing an index scan not a full table scan. Keep in mind that non-unique indexes carry around each row's internal primary key (RowID) in its index entries, thus making the indexes almost the same size as the table itself.

In the second CREATE TABLE, because of the introduction of another column, user, you now make the Query Optimizer see a completely different scenario: The table is now bigger that the indexes. Hence, the Query Optimizer became more strict in its interpretation of how to use available indexes. It went to the 5% rule I mentioned before. That rule failed miserably and the Query Optimizer decided in favor of a full table scan.

ContentLicense: CC BY-SA 2.5

Body:
I need some help figuring this out. I'm trying to get Mysql to use an index on a DATETIME field.

Mysql decides not to use the index if there's other (not used) fields in the table. Consider the two cases below:

A simple table with 2 fields works fine:

DROP TABLE IF EXISTS datetime_index_test;
CREATE TABLE  datetime_index_test (
id INT UNSIGNED NOT NULL AUTO_INCREMENT ,
created DATETIME NOT NULL ,
PRIMARY KEY (id) ,
INDEX (created)
) ENGINE = InnoDB ;

INSERT INTO datetime_index_test (created) VALUES
('2011-04-06 00:00:00'),
('2011-04-06 01:00:00'),
('2011-04-06 02:00:00'),
('2011-04-06 03:00:00'),
('2011-04-06 04:00:00'),
('2011-04-06 05:00:00'),
('2011-04-06 06:00:00'),
('2011-04-06 00:00:00');

EXPLAIN SELECT * FROM datetime_index_test
WHERE created <= '2011-04-06 04:00:00';

+----+-------------+---------------------+-------+---------------+---------+---------+------+------+--------------------------+
| id | select_type | table               | type  | possible_keys | key     | key_len | ref  | rows | Extra                    |
+----+-------------+---------------------+-------+---------------+---------+---------+------+------+--------------------------+
|  1 | SIMPLE      | datetime_index_test | range | created       | created | 4       | NULL |    4 | Using where; Using index |
+----+-------------+---------------------+-------+---------------+---------+---------+------+------+--------------------------+

A simple table with 3 fields, does not works fine:

DROP TABLE IF EXISTS datetime_index_test;
CREATE TABLE  datetime_index_test (
id INT UNSIGNED NOT NULL AUTO_INCREMENT ,
created DATETIME NOT NULL ,
user int(10) unsigned DEFAULT 0,
PRIMARY KEY (id) ,
INDEX (created)
) ENGINE = InnoDB ;

INSERT INTO datetime_index_test (created) VALUES
('2011-04-06 00:00:00'),
('2011-04-06 01:00:00'),
('2011-04-06 02:00:00'),
('2011-04-06 03:00:00'),
('2011-04-06 04:00:00'),
('2011-04-06 05:00:00'),
('2011-04-06 06:00:00'),
('2011-04-06 00:00:00');

EXPLAIN SELECT * FROM datetime_index_test
WHERE created <= '2011-04-06 04:00:00';

+----+-------------+---------------------+------+---------------+------+---------+------+------+-------------+
| id | select_type | table               | type | possible_keys | key  | key_len | ref  | rows | Extra       |
+----+-------------+---------------------+------+---------------+------+---------+------+------+-------------+
|  1 | SIMPLE      | datetime_index_test | ALL  | created       | NULL | NULL    | NULL |    8 | Using where |
+----+-------------+---------------------+------+---------------+------+---------+------+------+-------------+

Finally, my question; Can anyone explain to me why Mysql decides not to use the index?


问:
SQL to count number for each value
I have a SQL query and I want to be able to count the total number of priorities which has values set to low, medium, high or unspecified.

Currently it counts to a maximum of 13 rows, i'd expect there to be multiple columns with counts such as... 2, 4, 0

Code:

```<code> SELECT c.Name, COUNT(*) as Count_By_Priority,
 CASE WHEN cb.Priority = 0 THEN "Unspecified" WHEN cb.Priority = 1 THEN "Low" WHEN cb.Priority = 2 THEN "Medium" WHEN cb.Priority = 3 THEN "High" END as PriorityNumber
 FROM TABLE 1 cb
 LEFT JOIN Co c ON c.Id = cb.Id
 WHERE c.Name LIKE %Name%"
 GROUP BY c.Id;
</code>```

It seems to print "Unspecified" for the priority keys when I would be expecting low or alternatives.

答:
Try this,</p>

```<code>SELECT c.Name, COUNT(*) as Count_By_Priority,
CASE WHEN cb.Priority = 0 THEN "Unspecified"
WHEN cb.Priority = 1 THEN "Low"
WHEN cb.Priority = 2 THEN "Medium"
WHEN cb.Priority = 3 THEN "High" END as PriorityNumber

FROM TABLE 1 cb LEFT JOIN Co c ON c.Id = cb.Id

WHERE c.Name LIKE %Name%"

GROUP BY c.Name,PriorityNumber ;
</code>```

Title: SQL to count number for each value

Body:
I have a SQL query and I want to be able to count the total number of priorities which has values set to low, medium, high or unspecified.

Currently it counts to a maximum of 13 rows, i'd expect there to be multiple columns with counts such as... 2, 4, 0

Code:

 SELECT c.Name, COUNT(*) as Count_By_Priority,
 CASE WHEN cb.Priority = 0 THEN "Unspecified" WHEN cb.Priority = 1 THEN "Low" WHEN cb.Priority = 2 THEN "Medium" WHEN cb.Priority = 3 THEN "High" END as PriorityNumber
 FROM TABLE 1 cb
 LEFT JOIN Co c ON c.Id = cb.Id
 WHERE c.Name LIKE %Name%"
 GROUP BY c.Id;

It seems to print "Unspecified" for the priority keys when I would be expecting low or alternatives.

Body:
Try this,

SELECT c.Name, COUNT(*) as Count_By_Priority,
CASE WHEN cb.Priority = 0 THEN "Unspecified"
WHEN cb.Priority = 1 THEN "Low"
WHEN cb.Priority = 2 THEN "Medium"
WHEN cb.Priority = 3 THEN "High" END as PriorityNumber

FROM TABLE 1 cb LEFT JOIN Co c ON c.Id = cb.Id

WHERE c.Name LIKE %Name%"

GROUP BY c.Name,PriorityNumber ;


问:
Why does Laravel login attempt redirects back to the login page?
Laravel redirect me back to the login page after each attempt to login. How do i fix this issue?

I've tried changing the session from 'file' to 'database' and clearing all the cache(both in the browser and in laravel, yet it's still redirects back to the login page)

Here is the web route:

```<code> // Login
 Route::post("/profile/dashboard","LoginController@login")->name('login');
</code>```

Here is my controller:

```<code>    public function login(Request $req)
    {
        // validate form
       $req->validate([
            "email" => "required|email|max:255",
            "password" => "required|max:16",
        ]);

        $user = ["email" => $req->email, "password" => $req->password];

        // Attempt to login
        if (!Auth::attempt($user)) {

            return back();

        }
        // Redirects to dashboard
        return redirect()->route('dashboard');
    }
</code>```

Sorry for the poor formatting. Here is my view:

```<code>   <form action="{{ url("/profile/dashboard") }}"
        method="post" class="user">
        {{ csrf_field() }}
        <div class="form-group">
          <input type="email" name="email" id="email" class="form-control
          form-control-user" aria-describedby="emailHelp"   placeholder="Enter Email Address...">
                          <label class="error" for="email">
                            @include("pages.errors.email")
                          </label>
                        </div>
                        <div class="form-group">
                          <input type="password" name="password" id="password" class="form-control form-control-user" placeholder="Password">
                          <label class="error" for="password">
                            <label class="error" for="password">
                              @include("pages.errors.password")
                            </label>
                          </label>
                        </div>
                        <div class="form-group">
                          <div class="custom-control custom-checkbox small">
                            <input type="checkbox" class="custom-control-input" id="customCheck">
                            <label class="custom-control-label form-check-label" for="customCheck">Remember Me</label>
                          </div>
                        </div>
                        <button type="submit" class="btn btn-outline-success btn-user btn-block text-uppercase">Login</button>
                        <hr>
    <a href="index.html" class="btn  btn-danger btn-google
     btn-user btn-  block text-uppercase">
                          <i class="fab fa-google"></i> Login with Google
                        </a>
  </form>
</code>```

I dont't if this will help but here is my session set to database:

```<code>   'driver' => env('SESSION_DRIVER', 'database'),
</code>```

No Error was generate. It redirects back to the login page without any given error.

答:
https://laravel.com/docs/5.8/validation#quick-displaying-the-validation-errors

So, what if the incoming request parameters do not pass the given validation rules? As mentioned previously, Laravel will automatically redirect the user back to their previous location. In addition, all of the validation errors will automatically be flashed to the session.

Since you're not displaying the $errors variable, you're not getting any useful feedback. Try showing the value of $errors->all() in your form.

Body:
Laravel redirect me back to the login page after each attempt to login. How do i fix this issue?

I've tried changing the session from 'file' to 'database' and clearing all the cache(both in the browser and in laravel, yet it's still redirects back to the login page)

Here is the web route:

 // Login
 Route::post("/profile/dashboard","LoginController@login")->name('login');

Here is my controller:

    public function login(Request $req)
    {
        // validate form
       $req->validate([
            "email" => "required|email|max:255",
            "password" => "required|max:16",
        ]);

        $user = ["email" => $req->email, "password" => $req->password];

        // Attempt to login
        if (!Auth::attempt($user)) {

            return back();

        }
        // Redirects to dashboard
        return redirect()->route('dashboard');
    }

Sorry for the poor formatting. Here is my view:

   <form action="{{ url("/profile/dashboard") }}"
        method="post" class="user">
        {{ csrf_field() }}

          <input type="email" name="email" id="email" class="form-control
          form-control-user" aria-describedby="emailHelp"   placeholder="Enter Email Address...">

                            @include("pages.errors.email")

                          <input type="password" name="password" id="password" class="form-control form-control-user" placeholder="Password">

                              @include("pages.errors.password")

                            <input type="checkbox" class="custom-control-input" id="customCheck">
                            Remember Me

                        <button type="submit" class="btn btn-outline-success btn-user btn-block text-uppercase">Login</button>

                           Login with Google

  </form>

I dont't if this will help but here is my session set to database:

   'driver' => env('SESSION_DRIVER', 'database'),

No Error was generate. It redirects back to the login page without any given error.


问:
How to remove the square brackets around a JSON in PHP
How can I have the php script return json without the square brackets? I am also getting the INT values back with double quotes for some reason. Is it possible to remove those as well?

What I am getting now:

```<code>[{"id":"1","name":"Jack","username":"Jack1","age":"23"}]
</code>```

What I would like:

```<code>{"id": 1,"name":"Jack","username":"Jack1","age":23}
</code>```

The following is the php script that returns the JSON:

```<code><?php

$con = mysqli_connect("localhost", "username", "password", "database");

// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// This SQL statement selects ALL from the table 'Equipment'

$username = $_POST['username'];
$password = $_POST['password'];

$sql = "SELECT username, name FROM DriverInfo WHERE (username = '$username') and password = '$password' ";

// Check if there are results
if ($result = mysqli_query($con, $sql)) {
    // Create temporary connection
    $resultArray = array();
    $tempArray = array();

    // Look through each row
    while ($row = $result->fetch_object()) {
        // Add each row into our results array
        $tempArray = $row;
        array_push($resultArray, $tempArray);
    }

    // Finally, encode the array to JSON and output the results
    echo json_encode($resultArray);
}

mysqli_close($con);
</code>```

答:
Finally, encode the array to JSON and output the results

```<code>echo json_encode(array("data"=>$resultArray));
</code>```

output:

```<code>data:[{"id":1,"name":"Jack","username":"Jack1","age":23}]
</code>```

Body:
How can I have the php script return json without the square brackets? I am also getting the INT values back with double quotes for some reason. Is it possible to remove those as well?

What I am getting now:

[{"id":"1","name":"Jack","username":"Jack1","age":"23"}]

What I would like:

{"id": 1,"name":"Jack","username":"Jack1","age":23}

The following is the php script that returns the JSON:

<?php

$con = mysqli_connect("localhost", "username", "password", "database");

// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// This SQL statement selects ALL from the table 'Equipment'

$username = $_POST['username'];
$password = $_POST['password'];

$sql = "SELECT username, name FROM DriverInfo WHERE (username = '$username') and password = '$password' ";

// Check if there are results
if ($result = mysqli_query($con, $sql)) {
    // Create temporary connection
    $resultArray = array();
    $tempArray = array();

    // Look through each row
    while ($row = $result->fetch_object()) {
        // Add each row into our results array
        $tempArray = $row;
        array_push($resultArray, $tempArray);
    }

    // Finally, encode the array to JSON and output the results
    echo json_encode($resultArray);
}

mysqli_close($con);

Body:
Finally, encode the array to JSON and output the results

echo json_encode(array("data"=>$resultArray));

output:

data:[{"id":1,"name":"Jack","username":"Jack1","age":23}]


答:
You are using aggregation, but your SELECT is inconsistent with your GROUP BY.  I think you intend something like:

```<code>SELECT c.Name, COUNT(*) as Count_By_Priority,
       (CASE WHEN MAX(cb.Priority) = 0 THEN 'Unspecified'
             WHEN MAX(cb.Priority) = 1 THEN 'Low'
             WHEN MAX(cb.Priority) = 2 THEN 'Medium'
             WHEN MAX(cb.Priority) = 3 THEN 'High'
        END) as PriorityNumber
FROM TABLE 1 cb LEFT JOIN
     Co c
     ON c.Id = cb.Id
WHERE c.Name LIKE '%Name%'
GROUP BY c.Id;
</code>```

I'm not sure if you want MAX() or MIN() but MAX() makes sense to me.

Title: SQL to count number for each value

Body:
You are using aggregation, but your SELECT is inconsistent with your GROUP BY.  I think you intend something like:

SELECT c.Name, COUNT(*) as Count_By_Priority,
       (CASE WHEN MAX(cb.Priority) = 0 THEN 'Unspecified'
             WHEN MAX(cb.Priority) = 1 THEN 'Low'
             WHEN MAX(cb.Priority) = 2 THEN 'Medium'
             WHEN MAX(cb.Priority) = 3 THEN 'High'
        END) as PriorityNumber
FROM TABLE 1 cb LEFT JOIN
     Co c
     ON c.Id = cb.Id
WHERE c.Name LIKE '%Name%'
GROUP BY c.Id;

I'm not sure if you want MAX() or MIN() but MAX() makes sense to me.


问:
HTML unordered list sucks in IE7
I've created a HTML ordered list which looks fine in FF, but pretty awful in IE.
My specific problems with the way IE displays the list are:

List markers are missing

Vertical spacing between list items is very uneven

It seems the superscripts are the cause of (2), but I'm not sure how I can fix this problem (without removing the superscripts).

EDIT: I gave up on my single-list dreams and split the list into 3 separate lists. I've removed the link from the text above to avoid confusing future readers.

Thanks,
Don

答: can you set the height of the li elments to account for the superscript?  probably best to do that in CSS.</p>

OwnerDisplayName: Don

Title: HTML unordered list sucks in IE7

LastEditorDisplayName: Don

OwnerDisplayName: Jason


问:
Spring Security Core authAjax, How do I ignore the Referer
I'm using Grails 1.3.7 and the latest spring-security-core plugin.  I've implemented the following method in my LoginController:

```<code>def authAjax = {
   response.setHeader 'Location', SpringSecurityUtils.securityConfig.auth.ajaxLoginFormUrl
   response.sendError HttpServletResponse.SC_UNAUTHORIZED
}
</code>```

And in my global JavaScript file, I have the following:

```<code>$.ajaxSetup({
   error: function(xhr, status, err) {
      if (xhr.status == 401) {
         // display a login form in a dialog
      }
   }
});
</code>```

The login form is the standard login form directly from the plugin documentation.  The only difference is I submit my form using jQuery like so:

```<code>var params = $('#ajaxLoginForm').serialize();
$.post($('#ajaxLoginForm').attr('action'), params, function(jsonData) {
   if (jsonData.success) {
      $('#login-dialog').dialog('close');
   } else {
      alert('TODO: display errors');
   }
}, 'json');
</code>```

The problem is that the first time I click the login button, I seem to be authenticating ok, but the response coming back from the server is a 302 redirect based on the Referer request header.  So the body of my $.post() never gets ran.  I'm getting HTML back instead of JSON.  It doesn't actually hit my LoginController.ajaxSuccess method until the second submission.  I've read and re-read the documentation and I must be missing something.

UPDATE: It looks like it might not be a Referer issue, since the second time the form is posted, the Referer is still there.  So I'm at a complete loss as to why I have to submit the form twice for the ajaxSuccess method to get called.

答:
When you make an un-authorized attempt to access a protected resource, Spring Security saves that request on your session (http://static.springsource.org/spring-security/site/apidocs/org/springframework/security/web/savedrequest/DefaultSavedRequest.html), and then when you successfully authenticate, it redirects you to that request.  You can probably turn this behavior off across the board with Spring Security configuration, but that's probably not what you want for most workflows.  You could also probably explicitly remove the SavedRequest from the session in your authAjax method, but again, that's probably not the best experience for the user.

I believe LoginController.ajaxSuccess only gets hit if there is no SavedRequest to redirect to insted, so the HTML you're getting back should be the result of your original request, which was un-authorized at the time. So, the trick is you want to use whatever function you would have used to process the original request as the success method on your #ajaxLoginForm submission.

Body:
I'm using Grails 1.3.7 and the latest spring-security-core plugin.  I've implemented the following method in my LoginController:

def authAjax = {
   response.setHeader 'Location', SpringSecurityUtils.securityConfig.auth.ajaxLoginFormUrl
   response.sendError HttpServletResponse.SC_UNAUTHORIZED
}

And in my global JavaScript file, I have the following:

$.ajaxSetup({
   error: function(xhr, status, err) {
      if (xhr.status == 401) {
         // display a login form in a dialog
      }
   }
});

The login form is the standard login form directly from the plugin documentation.  The only difference is I submit my form using jQuery like so:

var params = $('#ajaxLoginForm').serialize();
$.post($('#ajaxLoginForm').attr('action'), params, function(jsonData) {
   if (jsonData.success) {
      $('#login-dialog').dialog('close');
   } else {
      alert('TODO: display errors');
   }
}, 'json');

The problem is that the first time I click the login button, I seem to be authenticating ok, but the response coming back from the server is a 302 redirect based on the Referer request header.  So the body of my $.post() never gets ran.  I'm getting HTML back instead of JSON.  It doesn't actually hit my LoginController.ajaxSuccess method until the second submission.  I've read and re-read the documentation and I must be missing something.

UPDATE: It looks like it might not be a Referer issue, since the second time the form is posted, the Referer is still there.  So I'm at a complete loss as to why I have to submit the form twice for the ajaxSuccess method to get called.


问:
How to apply mask behavior in primeng calendar (p-calendar)?
I am new to angular, in p-calendar I'm not able to apply masking behaviour. Example: If user enters 01012012, I want to change it to 01-01-2012. Thanks in advance.</p>

答:
You can use this ngx-mask. Here you are the documentation: ngx-mask

After installation, you can use it in your input like this:

<input mask="00-00-0000">
```


问:
How can I write proper tests for a local notification interface?
I'm using Swift 5, Xcode 10.2

I support iOS versions 10 and up

I have a notification model I can initialise with some data (title, body, actions, etc) and a static class with a function that takes in a notification model and shows a local notification based on its contents. It's all RX and the caller of the function can subscribe to the return value and it will fire an event when the user interacted with the notification (tap, dismiss, custom action, etc).

Now I want to test this class, I'm very new to both writing tests and RX so I'm having some trouble wrapping my head around this. From outside the class all I have is that one function.

I was thinking of what I actually want to test, and it comes down to showing the notification at all and if the mapping mechanism to a strong typed user interaction goes alright.

Another problem is that I don't always know if the permission for showing local notifications was granted, and if it's not been granted how to test if everything works.

How can I grant the permission to show notifications in a test?

How can I test wether the notification was shown?

How do I interact with the notification in a test?

Sorry for asking three questions for the price of one, but they are so related I figured it's better for everyone not to clutter the site with three very similar questions.

答:
You're out of bounds for unit testing here, and what you're looking for is UI testing.

If you want to unit test, you need to create testable classes where you could specifically test small behaviors such as does your init create values you expect, was a certain method invoked after a chain etc.

For actual testing if the notification was shown and interacting with it, you would have to dig into UI testing, where the actual how-to is dependant on how you show the notification etc. UI tests are pretty straightforward to start with, you just fire up the record method, then later clean up and add some additional logic for checking.

These are decent places to start learning about UI testing:
https://developer.apple.com/library/archive/documentation/DeveloperTools/Conceptual/testing_with_xcode/chapters/09-ui_testing.html

https://www.raywenderlich.com/960290-ios-unit-testing-and-ui-testing-tutorial

https://www.swiftbysundell.com/posts/getting-started-with-xcode-ui-testing-in-swift


问:
Use of third party brands
I've no idea where I should ask this question, but I'll give it a try here:

How am I allowed to use third-party like Instagram, Facebook, etc?

At the moment I've got a view which includes a button.

It has an icon of Instagram, and in the text, it says "Instagram" with a normal font. The link will lead to a tableview which contains a few Instagram accounts, am I allowed to do like this?

Or how can I use the brand "Instagram" to link to a few instagram profiles?

I've it like this. and if you click on it, the app will open a tableview with different instagram names. and if ur clicking on it, it will open instagram for you. is this allowed?

答:
Third party services with open API like Instagram and Facebook got a website for developers with a detailed description of how to use their services and company's policy. This information is frequently updated, so only official documentation can be a source of truth.
There are a couple of those websites for example:

Instagram policy

Facebook policy

Title: Use of third party brands


问:
How to extract text from large text
I have Data which is in this format in FILE1.txt

```<code>@E/f1/w/ @H/abc/w/ @demo/file/wk/Fil0.fk
@E/f2/w/ @H/cdv/w/ @demo/file/wk/Fil1.fk
@E/f3/w/ @H/efg/w/ @demo/file/wk/Fil2.fk
@E/f4/w/ @H/mno/w/ @demo/file/wk/Fil3.fk
@E/f5/w/ @H/pqr/w/ @demo/file/wk/Fil4.fk
</code>```

I want to Print data to a File .... FILE2.txt in this Below Format

```<code>Fil0.fk
Fil1.fk
Fil2.fk
Fil3.fk
Fil4.fk
</code>```

答:
Always show what you tried.

Assuming filename x,

with cut:

```<code>$: cut -d/ -f 10 x
</code>```

with sed:

```<code>$: sed 's#^.*/##' x
</code>```

with awk:

```<code>$: awk  ' { gsub("^.*/",""); print; }' x
</code>```

pure bash:

```<code>$: while read line; do echo "${line//*\/}"; done < x
</code>```

Title: How to extract text from large text

Body:
I have Data which is in this format in FILE1.txt

@E/f1/w/ @H/abc/w/ @demo/file/wk/Fil0.fk
@E/f2/w/ @H/cdv/w/ @demo/file/wk/Fil1.fk
@E/f3/w/ @H/efg/w/ @demo/file/wk/Fil2.fk
@E/f4/w/ @H/mno/w/ @demo/file/wk/Fil3.fk
@E/f5/w/ @H/pqr/w/ @demo/file/wk/Fil4.fk

I want to Print data to a File .... FILE2.txt in this Below Format

Fil0.fk
Fil1.fk
Fil2.fk
Fil3.fk
Fil4.fk

Body:
Always show what you tried.

Assuming filename x,

with cut:

$: cut -d/ -f 10 x

with sed:

$: sed 's#^.*/##' x

with awk:

$: awk  ' { gsub("^.*/",""); print; }' x

pure bash:

$: while read line; do echo "${line//*\/}"; done < x


问:
Find the largest element of an array in c++
there is an array containing elements from 1 to 10 and any of the element can be repeat you have to find the index of the largest element.
if there is more than 2 similar largest elements then show the smallest index of those elements.
like [2,2,1,0,0]
then you will print 0.</p>

答:
```<code>#include<bits/stdc++.h>
using namespace std;
int main()
{
    while(1){
    int n;
    cin>>n;
    multimap<int, int> m;
    int num;
    for(int i=1; i<=n; i++)
    {
        cin>>num;
        m.insert({num,i});
    }
    int capacity = 5;
    int arr[capacity];
    for(int i=0; i<capacity; i++){
        arr[i] = m.count(i+1);
        cout<<i<<" is :\t"<<arr[i]<<"times\n";
    }
    int a;
    a = max_element(arr,arr+capacity)-arr;//it was my doubt section
    cout<<a+1;
    }
}
</code>```


问:
Ruby On Rails, SQL and SQL parameters
I have complex SQL query. I need safely to pass parameters to SQL query. How can I avoid sql injections without using activerecord? Where should I keep SQL models/controllers? Does anyone know good practice to work with SQL server without activerecord?</p>

答:
ActiveRecord has sanitize_sql functions for this.
You can check the source code of this methods.

Title: Ruby On Rails, SQL and SQL parameters


问:
Oracle 11g - How to DECLARE a RECORD to store values based on Dynamic SQL
Summary

Exactly as my question states I'm curious to know how I can define a record so that I can store the values retrieved via Dynamic SQL.  I have a table that stores SQL in CLOB columns.  The END goal will be to call a PIPELINED function using the query_id of the query that is to be run.  My issue at the moment is not knowing how to define the TYPE so that I can then PIPE the data out.  I'm unable to define the PIPELINED function due to the fact that when DECLARING a PIPELINED Function it needs a Type.  In my case the TYPE will change based on the desired Query contained in the Query Table.

What I've tried

I've read up on the use of DBMS_SQL and I see that there is a feature of DBMS_SQL that is DBMS_SQL.DEFINE_COLUMN however it requires I explicitly define the columns - unless I'm missing something here.  Again... I don't know the column types coming back from the dynamic sql... they could be anything and in any order.

Example of my problem

The below code is the simplest example of my issue.  The RECORD I wish to populate in the example code below is rec_cursor_query.  In all other non dynamic sql it would be defined based off of a TABLE or explicitly defined using column names and the %TYPE keyword. Can't use this: rec_cursor_query   employees%ROWTYPE;.

```<code>DECLARE

  /* Cursor Pointer */
  cur_Query   SYS_REFCURSOR;

  /* Store Dynamic SQL */
  q           VARCHAR2(2000);

  /* Declare Record based on Dynamic SQL */
  --rec_cursor_query  ????table%ROWTYPE;  /* I realize I can't do this... but what can I do? */

BEGIN

  /* Fake Query Below saved into q */
  q   :=    q'~SELECT 1001 AS pkey, 'Jake' AS firstname, 'Johnson' AS lastname FROM dual~';

  /* Output Query just to show query was saved */
  dbms_output.put_line(q);

  OPEN cur_Query FOR
    q;

  LOOP

    FETCH cur_Query INTO rec_cursor_query; /* Again here... I can't do this due to it not being Defined */

    EXIT WHEN cur_Query%NOTFOUND;

  END LOOP;

  CLOSE cur_Query;

END
;
</code>```

答:
Quite simply this is not possible in Oracle SQL. SQL is strongly datatyped. None of this "if it looks like a duck" nonsense for us! The table() function only works with a pre-defined type (usually a SQL object) because it needs to know the projection. In case you're wondering, we can't use ANYDATASET or ANYTYPE as the return value for pipelined functions (PLS-00630: pipelined functions must have a supported collection return type).

One option to try is Inceptionizing your code by dynamically generating the SQL type for the pipelined function and dynamically generating the PL/SQL for the pipelined function which calls the dynamically generated SQL. But then you're in the realm of executing DDL as part of a query, and that's really messy. In short, I think this might work - although I have never tried it - but I would say this approach is too rickety for use in Production.

The other option is to realise that SQL is the wrong tool for the job. There are other languages which natively support reflection and such metadata-driven capabilities. Use weak ref cursors to pass data to client applications. Ref cursors map to ODBC and JDBC result sets, which can interpret the projection on the fly. Or upgrade to Oracle 12c which introduced support for implicit result sets in DBMS_SQL. Find out more.

Body:
Summary

Exactly as my question states I'm curious to know how I can define a record so that I can store the values retrieved via Dynamic SQL.  I have a table that stores SQL in CLOB columns.  The END goal will be to call a PIPELINED function using the query_id of the query that is to be run.  My issue at the moment is not knowing how to define the TYPE so that I can then PIPE the data out.  I'm unable to define the PIPELINED function due to the fact that when DECLARING a PIPELINED Function it needs a Type.  In my case the TYPE will change based on the desired Query contained in the Query Table.

What I've tried

I've read up on the use of DBMS_SQL and I see that there is a feature of DBMS_SQL that is DBMS_SQL.DEFINE_COLUMN however it requires I explicitly define the columns - unless I'm missing something here.  Again... I don't know the column types coming back from the dynamic sql... they could be anything and in any order.

Example of my problem

The below code is the simplest example of my issue.  The RECORD I wish to populate in the example code below is rec_cursor_query.  In all other non dynamic sql it would be defined based off of a TABLE or explicitly defined using column names and the %TYPE keyword. Can't use this: rec_cursor_query   employees%ROWTYPE;.

DECLARE

  /* Cursor Pointer */
  cur_Query   SYS_REFCURSOR;

  /* Store Dynamic SQL */
  q           VARCHAR2(2000);

  /* Declare Record based on Dynamic SQL */
  --rec_cursor_query  ????table%ROWTYPE;  /* I realize I can't do this... but what can I do? */

BEGIN

  /* Fake Query Below saved into q */
  q   :=    q'~SELECT 1001 AS pkey, 'Jake' AS firstname, 'Johnson' AS lastname FROM dual~';

  /* Output Query just to show query was saved */
  dbms_output.put_line(q);

  OPEN cur_Query FOR
    q;

  LOOP

    FETCH cur_Query INTO rec_cursor_query; /* Again here... I can't do this due to it not being Defined */

    EXIT WHEN cur_Query%NOTFOUND;

  END LOOP;

  CLOSE cur_Query;

END
;


问:
How to create multi steps form
I have been trying to create a multi steps form, working on my css to achieve the result I want but I couldn't achieved the exact solution I wanted.

I was able to design its layout but the issue I am facing is the line I wanted through those links.

Below is what I am trying to achieve:

What I was able to come up with:

If you take a look at the top of the second image. you will see the grey line at the top of those links.

Html Markup

```<code><ul id="owp-checkout-timeline" class="owp-woo-checkout-timeline clr square step-4">

            <li id="timeline-0" data-step="0" class="timeline login active">
            <div class="timeline-wrapper">
                <span class="timeline-step">1.</span>
                <span class="timeline-label">Login</span>
            </div>
        </li>

    <li id="timeline-1" data-step="1" class="timeline billing ">
        <div class="timeline-wrapper">
            <span class="timeline-step">2.</span>
            <span class="timeline-label">Billing</span>
        </div>
    </li>

    <li id="timeline-2" data-step="2" class="timeline shipping" >
        <div class="timeline-wrapper">
            <span class="timeline-step">3.</span>
            <span class="timeline-label">Shipping</span>
        </div>
    </li>

    <li id="timeline-3" data-step="3" class="timeline payment">
        <div class="timeline-wrapper">
            <span class="timeline-step">4.</span>
            <span class="timeline-label">Payment Info</span>
        </div>
    </li>

</ul>
</code>```

Css code

```<code>.owp-woo-checkout-timeline{
        display:-webkit-box;
        display:-moz-box;
        display:-ms-flexbox;
        display:-webkit-flex;
        display:flex;
        margin:0 0 1em;
        padding:0;
        font-size:90%;
        text-transform:uppercase;
}
.owp-woo-checkout-timeline>li.timeline{
    list-style:none;
    text-align:center;
    width:auto;
    padding:0;
    margin:0;
    position:relative;
    text-overflow:ellipsis;
    color:#b71c1c;
    display:block

}

    .timeline-wrapper{
                 display: table-row;
            }
    .timeline-wrapper:before {
    top: 14px;
    bottom: 0;
    position: absolute;
    content: " ";
    width: 100%;
    height: 1px;
    background-color: #ccc;
    z-order: 0;
}

.owp-woo-checkout-timeline>li.timeline .timeline-step,.owp-woo-checkout-timeline>li.timeline .timeline-step:after,
        .owp-woo-checkout-timeline>li.timeline .timeline-step:before{
            background-color:#e65100;
            color:#fff;
            font-weight:bold;
            border-color:#247830;
            padding:6px;
            border-radius:800px;
            }

.owp-woo-checkout-timeline>li.timeline .timeline-step:before{left:0}
.owp-woo-checkout-timeline>li.timeline .timeline-step:after{right:0}

.owp-woo-checkout-timeline>li:first-child .timeline-step:after,
.owp-woo-checkout-timeline>li:first-child
.owp-woo-checkout-timeline{width:50%;margin-left:50%}
.owp-woo-checkout-timeline>li:last-child .timeline-step:after,
.owp-woo-checkout-timeline>li:last-child .timeline-step:before{width:50%;margin-right:50%}
.owp-woo-checkout-timeline>li.active,.progress-indicator>li.active .timeline-step{color:#337AB7}
.owp-woo-checkout-timeline>li.active .timeline-step,.progress-indicator>li.active .timeline-step:after,
.owp-woo-checkout-timeline>li.active .timeline-step:before{background-color:#337AB7;border-color:#122a3f}
.owp-woo-checkout-timeline>li a:hover .timeline-step,.progress-indicator>li a:hover .timeline-step:after,
.owp-woo-checkout-timeline>li a:hover .timeline-step:before{background-color:#5671d0;border-color:#1f306e}
.owp-woo-checkout-timeline>li a:hover .timeline-step{color:#5671d0}
</code>```

答:
Change this z-order: 0; css to z-index:-1; on .timeline-wrapper:before class.
Also change the top position of the line and add position:relative to main circle or font.

Title: How to create multi steps form

Body:
I have been trying to create a multi steps form, working on my css to achieve the result I want but I couldn't achieved the exact solution I wanted.

I was able to design its layout but the issue I am facing is the line I wanted through those links.

Below is what I am trying to achieve:

What I was able to come up with:

If you take a look at the top of the second image. you will see the grey line at the top of those links.

Html Markup

                1.
                Login

            2.
            Billing

            3.
            Shipping

            4.
            Payment Info

Css code

.owp-woo-checkout-timeline{
        display:-webkit-box;
        display:-moz-box;
        display:-ms-flexbox;
        display:-webkit-flex;
        display:flex;
        margin:0 0 1em;
        padding:0;
        font-size:90%;
        text-transform:uppercase;
}
.owp-woo-checkout-timeline>li.timeline{
    list-style:none;
    text-align:center;
    width:auto;
    padding:0;
    margin:0;
    position:relative;
    text-overflow:ellipsis;
    color:#b71c1c;
    display:block

}

    .timeline-wrapper{
                 display: table-row;
            }
    .timeline-wrapper:before {
    top: 14px;
    bottom: 0;
    position: absolute;
    content: " ";
    width: 100%;
    height: 1px;
    background-color: #ccc;
    z-order: 0;
}

.owp-woo-checkout-timeline>li.timeline .timeline-step,.owp-woo-checkout-timeline>li.timeline .timeline-step:after,
        .owp-woo-checkout-timeline>li.timeline .timeline-step:before{
            background-color:#e65100;
            color:#fff;
            font-weight:bold;
            border-color:#247830;
            padding:6px;
            border-radius:800px;
            }

.owp-woo-checkout-timeline>li.timeline .timeline-step:before{left:0}
.owp-woo-checkout-timeline>li.timeline .timeline-step:after{right:0}

.owp-woo-checkout-timeline>li:first-child .timeline-step:after,
.owp-woo-checkout-timeline>li:first-child
.owp-woo-checkout-timeline{width:50%;margin-left:50%}
.owp-woo-checkout-timeline>li:last-child .timeline-step:after,
.owp-woo-checkout-timeline>li:last-child .timeline-step:before{width:50%;margin-right:50%}
.owp-woo-checkout-timeline>li.active,.progress-indicator>li.active .timeline-step{color:#337AB7}
.owp-woo-checkout-timeline>li.active .timeline-step,.progress-indicator>li.active .timeline-step:after,
.owp-woo-checkout-timeline>li.active .timeline-step:before{background-color:#337AB7;border-color:#122a3f}
.owp-woo-checkout-timeline>li a:hover .timeline-step,.progress-indicator>li a:hover .timeline-step:after,
.owp-woo-checkout-timeline>li a:hover .timeline-step:before{background-color:#5671d0;border-color:#1f306e}
.owp-woo-checkout-timeline>li a:hover .timeline-step{color:#5671d0}


问:
List rows order by oldest time
I am a bit new in sql and I have this problem to get an specific information from three tables. I have those three tables.

employee table

company table

employment table

EmployeeID in Employment is FK
CompanyID in Company is FK
EmploymentID in Emplyment is PK
NULL in EmploymentEndDate in Employment means that worker is currently working there.

I have been trying this but is not working

```<code>select Company.CompanyName as CompanyName , CONCAT( Employee.FirstName, ' ' ,Employee.LastName) as EmployeeName , Employment.EmploymentStartDate from Employment LEFT JOIN Employee on Employee.EmployeeID = Employment.EmployeeID
LEFT JOIN Company on Company.CompanyID = Employment.CompanyID
where Employment.EmploymentEndDate is null
and EXISTS(SELECT Employment.CompanyID, MAX(DATEDIFF( DAY,Employment.EmploymentStartDate ,GETDATE())) as MaxDate FROM  Employment where  Employment.EmploymentEndDate is null group by CompanyID)
</code>```

and is giving me this result:

which is wrong because from company "Steve's Widgets Inc" I expect only John Doe which is the most old worker.

This is exactly what I want, List all Companies and gives the name and start date of the Employee that has been working in the Company the longest out of all Employees that are currently working there.
(Expected Columns: CompanyName, EmployeeName, EmploymentStartDate)

答:
```<code>with oldest (companyId, empStart) as
(
select companyId, min(EmploymentStartDate)
from Employment
where EmploymentEndDate is null
group by companyId
)
select c.CompanyName, e.Firstname + ' ' + e.LastName as employeeName, em.employmentStartDate
from Employment em
inner join oldest o on em.CompanyId = o.CompanyID and em.employmentStartDate = o.empStart
inner join employee e on em.EmployeeId = e.EmployeeId
inner join company c on em.CompanyId = c.CompanyId;
</code>```

Title: List rows order by oldest time

Body:
I am a bit new in sql and I have this problem to get an specific information from three tables. I have those three tables.

employee table

company table

employment table

EmployeeID in Employment is FK
CompanyID in Company is FK
EmploymentID in Emplyment is PK
NULL in EmploymentEndDate in Employment means that worker is currently working there.

I have been trying this but is not working

select Company.CompanyName as CompanyName , CONCAT( Employee.FirstName, ' ' ,Employee.LastName) as EmployeeName , Employment.EmploymentStartDate from Employment LEFT JOIN Employee on Employee.EmployeeID = Employment.EmployeeID
LEFT JOIN Company on Company.CompanyID = Employment.CompanyID
where Employment.EmploymentEndDate is null
and EXISTS(SELECT Employment.CompanyID, MAX(DATEDIFF( DAY,Employment.EmploymentStartDate ,GETDATE())) as MaxDate FROM  Employment where  Employment.EmploymentEndDate is null group by CompanyID)

and is giving me this result:

which is wrong because from company "Steve's Widgets Inc" I expect only John Doe which is the most old worker.

This is exactly what I want, List all Companies and gives the name and start date of the Employee that has been working in the Company the longest out of all Employees that are currently working there.
(Expected Columns: CompanyName, EmployeeName, EmploymentStartDate)


问:
Bigquery: Filter by _PARTITIONTIME doesn't propagate on LEFT JOIN
I have 2 partitioned tables:

Table 1:

|user_id|request_id|

Table 2:

|ip|user_id|request_id|

I want to get for all ips from partition_table2:
  - users count(from partition_table1)
  - users requests(from partition_table1)
  - user requests(from partition_table2) for users(from partition_table1)

Info:
  Ip is related to request_id from Table 1, because one user_id can have more than one ip.

Issue:
  When I filter by _PARTITIONTIME in the main query it doesn't propagate to query from WITH when I do LEFT JOIN, but filter by _PARTITIONTIME is propagated when I do INNER JOIN.

Partition pruning doesn't seem to work: https://cloud.google.com/bigquery/docs/querying-partitioned-tables for LEFT JOIN

My Query:

WITH
  users_info AS (
  SELECT
    t2.ip,
    t1.user_id,
    COUNT(DISTINCT t1.request_id) AS user_requests,
    t1._PARTITIONTIME AS date
  FROM partitioned_table1 t1
  INNER JOIN partition_table2 t2
    ON t1.request_id = t2.request_id
    AND t1._PARTITIONTIME = t2._PARTITIONTIME
  GROUP BY t2.ip, t1.user_id, t1._PARTITIONTIME
  )
SELECT
  t2.ip,
  COUNT(DISTINCT m.user_id) AS users,
  COUNT(DISTINCT t2.request_id) AS t2_users_requests,
  SUM(m.user_requests) AS t1_users_requests
FROM partition_table2 t2
LEFT JOIN/INNER JOIN users_info m
  ON t2.ip=m.ip
  AND t2.user_id=m.user_id
  AND m.date = t2._PARTITIONTIME
WHERE DATE(t2._PARTITIONTIME) = "2019-05-20"
GROUP BY t2.ip
```

If I do INNER JOIN this query processes ~4 GB, but with LEFT JOIN it processes ~3 TB

I did something wrong or is this behaviour expected?

EDIT

I need this query to create a VIEW. Condition(DATE(t2._PARTITIONTIME) = "2019-05-20") from the above query I'll use to filter the VIEW when I'll query it.

答: The columns from the right side of a LEFT OUTER JOIN can potentially be NULL, so yes, BigQuery actually needs to execute the join to figure out the results rather than filtering partitions in advance. If you don't want this behavior, use a subquery where you filter on _PARTITIONTIME prior to the join.

Body:
I have 2 partitioned tables:

Table 1:

|user_id|request_id|

Table 2:

|ip|user_id|request_id|

I want to get for all ips from partition_table2:
  - users count(from partition_table1)
  - users requests(from partition_table1)
  - user requests(from partition_table2) for users(from partition_table1)

Info:
  Ip is related to request_id from Table 1, because one user_id can have more than one ip.

Issue:
  When I filter by _PARTITIONTIME in the main query it doesn't propagate to query from WITH when I do LEFT JOIN, but filter by _PARTITIONTIME is propagated when I do INNER JOIN.

Partition pruning doesn't seem to work: https://cloud.google.com/bigquery/docs/querying-partitioned-tables for LEFT JOIN

My Query:

WITH
  users_info AS (
  SELECT
    t2.ip,
    t1.user_id,
    COUNT(DISTINCT t1.request_id) AS user_requests,
    t1._PARTITIONTIME AS date
  FROM partitioned_table1 t1
  INNER JOIN partition_table2 t2
    ON t1.request_id = t2.request_id
    AND t1._PARTITIONTIME = t2._PARTITIONTIME
  GROUP BY t2.ip, t1.user_id, t1._PARTITIONTIME
  )
SELECT
  t2.ip,
  COUNT(DISTINCT m.user_id) AS users,
  COUNT(DISTINCT t2.request_id) AS t2_users_requests,
  SUM(m.user_requests) AS t1_users_requests
FROM partition_table2 t2
LEFT JOIN/INNER JOIN users_info m
  ON t2.ip=m.ip
  AND t2.user_id=m.user_id
  AND m.date = t2._PARTITIONTIME
WHERE DATE(t2._PARTITIONTIME) = "2019-05-20"
GROUP BY t2.ip

If I do INNER JOIN this query processes ~4 GB, but with LEFT JOIN it processes ~3 TB

I did something wrong or is this behaviour expected?

EDIT

I need this query to create a VIEW. Condition(DATE(t2._PARTITIONTIME) = "2019-05-20") from the above query I'll use to filter the VIEW when I'll query it.