问:
The Adaptive card display is not displayed on the cortana channel but works well on teams and emulator
I have created a QnA bot and integrated cortana with it.
I am able to see hero cards on the cortana channel but not adaptive cards.
Though I get the attachment in my reply variable in my code, the card is not rendering.
Alse the speak property of adaptive card seems to be deprecated.

Below is the json response i get as debugging info

```<code>{
  "botId": "ValoremReplyCortanaBot",
  "botRequest": {
    "type": "message",
    "id": "ru2O3ASCqo",
    "timestamp": "2019-05-28T12:28:38.6194349Z",
    "serviceUrl": "https://CortanaBFChannelEastUs.azurewebsites.net/",
    "channelId": "cortana",
    "from": {
      "id": "6E45EE54844A79A85857DE2CEF10B9223A16AE6ACC2360DC007744F9CA7377E5"
    },
    "conversation": {
      "id": "f002bf89-2d89-4e41-a5b6-bcdfa4e35cc3"
    },
    "recipient": {
      "id": "valoremreplycortanabot"
    },
    "locale": "en-US",
    "text": "guide",
    "entities": [
      {
        "type": "Intent",
        "name": "None",
        "entities": []
      },
      {
        "type": "AuthorizationToken",
        "token": "##",
        "status": 0
      },
      {
        "type": "UserInfo",
        "current_location": {
          "StartTime": "2019-05-28T12:28:38.0673147Z",
          "EndTime": null,
          "Hub": {
            "Id": null,
            "Type": "Other",
            "Name": null,
            "Latitude": 10.0126075744629,
            "Longitude": 76.3658599853516,
            "Address": null
          },
          "VenueName": null,
          "Away": false
        },
        "name": {
          "GivenName": "##",
          "FamilyName": "##"
        },
        "email": "##@outlook.com"
      },
      {
        "type": "DeviceInfo",
        "supportsDisplay": "true"
      }
    ],
    "channelData": {
      "skillId": "cc3ef598-4f4f-444f-bd20-87a211581607",
      "skillProductId": "188779dd-2894-4cb3-b93f-b99955039ead",
      "isDebug": true
    }
  },
  "botResponse": {
    "type": "message",
    "timestamp": "2019-05-28T12:28:51.306281Z",
    "serviceUrl": "https://CortanaBFChannelEastUs.azurewebsites.net/",
    "channelId": "cortana",
    "from": {
      "id": "valoremreplycortanabot"
    },
    "conversation": {
      "id": "f002bf89-2d89-4e41-a5b6-bcdfa4e35cc3"
    },
    "recipient": {
      "id": "6E45EE54844A79A85857DE2CEF10B9223A16AE6ACC2360DC007744F9CA7377E5"
    },
    "locale": "en-US",
    "text": "",
    "attachments": [
      {
        "contentType": "application/vnd.microsoft.card.adaptive",
        "content": {
          "type": "AdaptiveCard",
          "version": "1.0",
          "body": [
            {
              "type": "TextBlock",
              "size": "large",
              "weight": "bolder"
            },
            {
              "type": "Image",
              "size": "stretch",
              "url": "##",
              "width": "100px",
              "height": "100px"
            }
          ],
          "actions": [
            {
              "type": "Action.OpenUrl",
              "url": "##",
              "title": "Guide Poster",
              "speak": "Guide Poster"
            }
          ]
        }
      }
    ],
    "entities": [],
    "replyToId": "ru2O3ASCqo"
  }
}
</code>```

答:
The HTML renderer inside Cortana desktop is less forgiving than other clients. Check https://adaptivecards.io/explorer/TextBlock.html

To make sure every element has its REQUIRED fields.

It could be as simple as your TextBlock not having a text object....  Add
"text": ""

Oh, and speak isn't deprecated.  It is at a card level; peer to body.  And... Cortana won't speak it by default. You need to copy it from the card and add it to the message https://github.com/microsoft/cortana-skills-samples/blob/master/Consumer/CSharp/V4Patches/07.using-adaptive-cards.diff

Body:
I have created a QnA bot and integrated cortana with it.
I am able to see hero cards on the cortana channel but not adaptive cards.
Though I get the attachment in my reply variable in my code, the card is not rendering.
Alse the speak property of adaptive card seems to be deprecated.

Below is the json response i get as debugging info

{
  "botId": "ValoremReplyCortanaBot",
  "botRequest": {
    "type": "message",
    "id": "ru2O3ASCqo",
    "timestamp": "2019-05-28T12:28:38.6194349Z",
    "serviceUrl": "https://CortanaBFChannelEastUs.azurewebsites.net/",
    "channelId": "cortana",
    "from": {
      "id": "6E45EE54844A79A85857DE2CEF10B9223A16AE6ACC2360DC007744F9CA7377E5"
    },
    "conversation": {
      "id": "f002bf89-2d89-4e41-a5b6-bcdfa4e35cc3"
    },
    "recipient": {
      "id": "valoremreplycortanabot"
    },
    "locale": "en-US",
    "text": "guide",
    "entities": [
      {
        "type": "Intent",
        "name": "None",
        "entities": []
      },
      {
        "type": "AuthorizationToken",
        "token": "##",
        "status": 0
      },
      {
        "type": "UserInfo",
        "current_location": {
          "StartTime": "2019-05-28T12:28:38.0673147Z",
          "EndTime": null,
          "Hub": {
            "Id": null,
            "Type": "Other",
            "Name": null,
            "Latitude": 10.0126075744629,
            "Longitude": 76.3658599853516,
            "Address": null
          },
          "VenueName": null,
          "Away": false
        },
        "name": {
          "GivenName": "##",
          "FamilyName": "##"
        },
        "email": "##@outlook.com"
      },
      {
        "type": "DeviceInfo",
        "supportsDisplay": "true"
      }
    ],
    "channelData": {
      "skillId": "cc3ef598-4f4f-444f-bd20-87a211581607",
      "skillProductId": "188779dd-2894-4cb3-b93f-b99955039ead",
      "isDebug": true
    }
  },
  "botResponse": {
    "type": "message",
    "timestamp": "2019-05-28T12:28:51.306281Z",
    "serviceUrl": "https://CortanaBFChannelEastUs.azurewebsites.net/",
    "channelId": "cortana",
    "from": {
      "id": "valoremreplycortanabot"
    },
    "conversation": {
      "id": "f002bf89-2d89-4e41-a5b6-bcdfa4e35cc3"
    },
    "recipient": {
      "id": "6E45EE54844A79A85857DE2CEF10B9223A16AE6ACC2360DC007744F9CA7377E5"
    },
    "locale": "en-US",
    "text": "",
    "attachments": [
      {
        "contentType": "application/vnd.microsoft.card.adaptive",
        "content": {
          "type": "AdaptiveCard",
          "version": "1.0",
          "body": [
            {
              "type": "TextBlock",
              "size": "large",
              "weight": "bolder"
            },
            {
              "type": "Image",
              "size": "stretch",
              "url": "##",
              "width": "100px",
              "height": "100px"
            }
          ],
          "actions": [
            {
              "type": "Action.OpenUrl",
              "url": "##",
              "title": "Guide Poster",
              "speak": "Guide Poster"
            }
          ]
        }
      }
    ],
    "entities": [],
    "replyToId": "ru2O3ASCqo"
  }
}


来源: stackexchange

问:
Best way to store variable length data in single column
I'm looking for some opinions on how to best store some data. I have some data that resembles the following:

```<code>id  category    proportion
1   1           0.99
1   7           0.85
2   1           0.55
3   2           0.90
3   3           0.85
</code>```

Basically, unique ID's can belong to varying numbers of categories. Each id and category has a proportion associated with it.

I want to store this data in a single column so that I can add it to a table where each id may only inhabit a single row.

Right now, I've been contemplating two json structures. Consider the example of id = 1. We'd have something like the following two options...

Unnested: {"category1": "1", "proportion1": "0.99", "category2": "7", "proportion2": "0.85"}

Nested: {"category1": {"label": "1", "proportion": "0.99"}, "category2": {"label": "7", "proportion": "0.85"}}

I'm not too familiar with json in Presto/Athena. Use cases would include a) looking up ids given a specific category label or b) grouping id attributes by individual category labels.

For example, I may want to identify all id's that belong to category = 3. I don't think either of these structures would make this easy in Athena.

Looking for any feedback you may have. I do think the optimal structure is one row per id + category combination but that is not an option for this use case.

答:
I think the tabular format that you start out with is preferable to the JSON structures you suggest as alternatives. You can always use SQL to get other formats, so choosing the format that makes the fewest assumptions about access patterns, and looks the most like a table is usually best, unless you have very specific requirements – which it doesn't sound like you have.

In the end it also depends a lot on how you will be producing the data. The beauty of Athena is that it's pretty good at handling most structures that you can throw at it. Keep the data in the format that it is produced in and you can almost always use SQL to get the answer you need. If it turns out to be too slow or too expensive that way you can use Athena to convert the data into other formats and structures that are more suitable, but always keep the data in its original format too – that way you can always create even more versions for new situations.

If it's not too much data you can also use views to create optimised representations for different use cases.

ContentLicense: CC BY-SA 4.0

Body:
I'm looking for some opinions on how to best store some data. I have some data that resembles the following:

id  category    proportion
1   1           0.99
1   7           0.85
2   1           0.55
3   2           0.90
3   3           0.85

Basically, unique ID's can belong to varying numbers of categories. Each id and category has a proportion associated with it.

I want to store this data in a single column so that I can add it to a table where each id may only inhabit a single row.

Right now, I've been contemplating two json structures. Consider the example of id = 1. We'd have something like the following two options...

Unnested: {"category1": "1", "proportion1": "0.99", "category2": "7", "proportion2": "0.85"}

Nested: {"category1": {"label": "1", "proportion": "0.99"}, "category2": {"label": "7", "proportion": "0.85"}}

I'm not too familiar with json in Presto/Athena. Use cases would include a) looking up ids given a specific category label or b) grouping id attributes by individual category labels.

For example, I may want to identify all id's that belong to category = 3. I don't think either of these structures would make this easy in Athena.

Looking for any feedback you may have. I do think the optimal structure is one row per id + category combination but that is not an option for this use case.


问:
EF 4.1 Code First error - The entity type SomeType is not part of the model for the current context
While working with EF code first I get error given below at different times:

The entity type SomeType is not part of the model for the current context.

What are the possible causes of this error?

答:
It may occur because:

DbContext configured with an incorrect connection string

The entity specified is actually not mapped in configuration

ContentLicense: CC BY-SA 3.0


问:
How to add 3rd party JARs to Maven project
My area of expertise is not Java. I develop in other languages on other platforms.

Right now I'm developing a series of Java servlets for a project. The servlets are to run on a CentOS server running FileNetP8.

I actually got all of the planned items finished and running.

Now when I am trying to add a few more services, the library I came across is available via Maven. I have no idea what Maven is. Read up on it today. Created a test project to try it out.

My development environment is Eclipse Photon on Windows 10.

Now my problem is I can't figure out how to add the Filenet JARs to the project. I can't upload them to some Maven repo. Searching the Web says to add them to the local repo, but I don't understand how to do that to the Local repo in Eclipse's builtin Maven.

I think that the JARs don't need to be packaged within the deployment WAR because the app will be deployed to the Websphere server that runs Filenet so they should be available on it. Should I add them as external JAR references to get the project to compile?

答:
Dependencies need to be added in pom.xml under dependencies tag. Maven will download the specified jars from maven central repository for the first time, and it will be saved in your local repo.
If the dependencies are not available in central repo and if they have their own repo, you to need specify it in the repositories tag.

```<code><repositories>
    <repository>
         <id>repo-id</id>
         <name>repo-name</name>
         <url>http://repourl</url>
    </repository>
</repositories>
</code>```

Any change in the pom.xml, maven will automatically download it.

```<code><dependencies>
   <dependency>
      <groupId>dependency-id</groupId>
      <artifactId>artifactid</artifactId>
      <version>1</version>
   </dependency>
</dependencies>
</code>```

Body:
Dependencies need to be added in pom.xml under dependencies tag. Maven will download the specified jars from maven central repository for the first time, and it will be saved in your local repo.
If the dependencies are not available in central repo and if they have their own repo, you to need specify it in the repositories tag.

<repositories>
    <repository>
         <id>repo-id</id>
         <name>repo-name</name>
         <url>http://repourl</url>
    </repository>
</repositories>

Any change in the pom.xml, maven will automatically download it.

<dependencies>
   <dependency>
      <groupId>dependency-id</groupId>
      <artifactId>artifactid</artifactId>
      <version>1</version>
   </dependency>
</dependencies>


问:
Entity Framework Core Assign role to user after created
i would like to know how can i associate a specific role to a user when he is created

I have this on my create User page

```<code>    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }

        _context.Users.Add(User);

        await _context.SaveChangesAsync();

        _toastNotification.AddSuccessToastMessage("Utilizador Adicionado com sucesso");

        return RedirectToPage("./Index");
    }
</code>```

I have tried on the model

```<code>    public User()
    {
        IsActivo = true;
        UserRoles.Add(new UserRole { RoleId = 4 });
    }
</code>```

this does not work unfortunely.

答:
For both users and roles you should be using the associated managers: UserManager<TUser> and RoleManager<TRole>. There's a number of things that need to happen besides simple persistence that the managers handle and that adding directly to the context does not. Here, though, you only need UserManager<TUser> to handle everything.

```<code>public class RegisterModel : PageModel
{
    private readonly UserManager<IdentityUser> _userManager;

    public RegisterModel(UserManager<IdentityUser> userManager)
    {
        _userManager = userManager;
    }

    ...
}
</code>```

Then:

```<code>public async Task<IActionResult> OnPostAsync()
{
    if (!ModelState.IsValid)
    {
        return Page();
    }

    await _userManager.CreateUserAsync(User);
    await _userManager.AddToRoleAsync(User, "foo"); // where "foo" is the name of your role

    _toastNotification.AddSuccessToastMessage("Utilizador Adicionado com sucesso");

    return RedirectToPage("./Index");
}
</code>```

Body:
i would like to know how can i associate a specific role to a user when he is created

I have this on my create User page

    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }

        _context.Users.Add(User);

        await _context.SaveChangesAsync();

        _toastNotification.AddSuccessToastMessage("Utilizador Adicionado com sucesso");

        return RedirectToPage("./Index");
    }

I have tried on the model

    public User()
    {
        IsActivo = true;
        UserRoles.Add(new UserRole { RoleId = 4 });
    }

this does not work unfortunely.

Body:
For both users and roles you should be using the associated managers: UserManager<TUser> and RoleManager<TRole>. There's a number of things that need to happen besides simple persistence that the managers handle and that adding directly to the context does not. Here, though, you only need UserManager<TUser> to handle everything.

public class RegisterModel : PageModel
{
    private readonly UserManager<IdentityUser> _userManager;

    public RegisterModel(UserManager<IdentityUser> userManager)
    {
        _userManager = userManager;
    }

    ...
}

Then:

public async Task<IActionResult> OnPostAsync()
{
    if (!ModelState.IsValid)
    {
        return Page();
    }

    await _userManager.CreateUserAsync(User);
    await _userManager.AddToRoleAsync(User, "foo"); // where "foo" is the name of your role

    _toastNotification.AddSuccessToastMessage("Utilizador Adicionado com sucesso");

    return RedirectToPage("./Index");
}


问:
LinearNDInterpolatorExtrapolate returns error with trivial example
I'm trying to use scipy's LinearNDInterpolatorExtrapolate.

The following minimal code should be as trivial as possible, yet it returns an error

```<code>from scipy.interpolate import NearestNDInterpolator
points = [[0,0,0], [1,0,0], [1,1,0],[0,1,0],[.5,.5,1]]
values = [1,2,3,4,5]
interpolator = NearestNDInterpolator(points,values)
interpolator([.5,.5,.8])
</code>```

returns

```<code>TypeError: only integer scalar arrays can be converted to a scalar index
</code>```

The error seems to come from line 81 of scipy.interpolate.ndgriddata [source]. Unfortunately I could not chase the error further, as I don't understand what tree.query is returning.

Is this a bug or I'm doing something wrong?

答:
In your case, it seems like a problem with value type. Because first values of points and values are Python's integers, the rest are interpreted as integers.

The following fixes your code and returns a correct answer, which is [5]:

import numpy as np
from scipy.interpolate import NearestNDInterpolator
points = np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0],[0, 1, 0],[.5, .5, 1]])
values = np.array([1, 2, 3, 4, 5])
interpolator = NearestNDInterpolator(points, values)
interpolator(np.array([[.5, .5, .8]]))

>>> array([5])
```

Notice two things:

I imported numpy and used np.array. This is the preferable way to work with scipy, because np.array, albeit being static, is much faster comparing to python's list and provides a spectrum of mathematical operations.

When calling interpolator, I used [[...]] instead of your [...]. Why? It highlights the fact that NearestNDInterpolator can interpolate values in multiple points.

Body:
I'm trying to use scipy's LinearNDInterpolatorExtrapolate.

The following minimal code should be as trivial as possible, yet it returns an error

from scipy.interpolate import NearestNDInterpolator
points = [[0,0,0], [1,0,0], [1,1,0],[0,1,0],[.5,.5,1]]
values = [1,2,3,4,5]
interpolator = NearestNDInterpolator(points,values)
interpolator([.5,.5,.8])

returns

TypeError: only integer scalar arrays can be converted to a scalar index

The error seems to come from line 81 of scipy.interpolate.ndgriddata [source]. Unfortunately I could not chase the error further, as I don't understand what tree.query is returning.

Is this a bug or I'm doing something wrong?

Body:
In your case, it seems like a problem with value type. Because first values of points and values are Python's integers, the rest are interpreted as integers.

The following fixes your code and returns a correct answer, which is [5]:

import numpy as np
from scipy.interpolate import NearestNDInterpolator
points = np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0],[0, 1, 0],[.5, .5, 1]])
values = np.array([1, 2, 3, 4, 5])
interpolator = NearestNDInterpolator(points, values)
interpolator(np.array([[.5, .5, .8]]))

>>> array([5])

Notice two things:

I imported numpy and used np.array. This is the preferable way to work with scipy, because np.array, albeit being static, is much faster comparing to python's list and provides a spectrum of mathematical operations.

When calling interpolator, I used [[...]] instead of your [...]. Why? It highlights the fact that NearestNDInterpolator can interpolate values in multiple points.


问:
Azure Search Index with CosmosDB Collection with ShardKey and MongoAPI
I have a problem with Azure Search and a CosmosDB with ShardKey and MongoAPI. My AzureSearchIndexer fills my AzureSearch index with 180,000 records, but all properties are null. Therefore, I believe that my database connection works but somehow the wrong data is selected.

I would expect the 180000 records but with the respective properties.

答:
As Gaurav mentioned, Mongo API is not yet supported in the portal, so you need to use the REST API directly to create a Mongo datasource. Remember to include "ApiKind=MongoDb" in the credentials connection string in the Create a data source section here.

After creating the Mongo datasource with REST API, you can choose to create the index and indexer with REST API as well, or you can use the portal Import data with your existing datasource.


问:
Removing Duplicate Rows in a google Spreadsheet from the end row
i find this code for remove duplicate row in google spraedsheet:
from this url:
https://developers.google.com/apps-script/articles/removing_duplicates

```<code>function removeDuplicates() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
  var data = sheet.getDataRange().getValues();
  var last=sheet.getLastRow();
  var newData = new Array();
  for(i in data){
    //Logger.log(i);
    var row = data[i];
    //Logger.log(row[5]);
    var duplicate = false;
    for(j in newData){
      //Logger.log(newData[j][5]);
      if(row[5] == newData[j][5]){
        duplicate = true;
      }
    }
    if(!duplicate){
      newData.push(row);
    }
  }
  sheet.clearContents();
  sheet.getRange(1, 1, newData.length, newData[0].length).setValues(newData);
}
</code>```

but this function start removing duplicate row from the first row, i want to start removing from the end row of sheet.
How can i do this?

答:
I believe that I reached here pretty late to save you from all the trouble, but just to make sure that people reaching this thread don't end up with the same frustration follow the guideline given here to solve the issue -

https://ladwhocodes.blogspot.com/2019/02/remove-duplicate-rows-from-your-google.html

Follow the comments given on the link to achieve what you want.

Body:
i find this code for remove duplicate row in google spraedsheet:
from this url:
https://developers.google.com/apps-script/articles/removing_duplicates

function removeDuplicates() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
  var data = sheet.getDataRange().getValues();
  var last=sheet.getLastRow();
  var newData = new Array();
  for(i in data){
    //Logger.log(i);
    var row = data[i];
    //Logger.log(row[5]);
    var duplicate = false;
    for(j in newData){
      //Logger.log(newData[j][5]);
      if(row[5] == newData[j][5]){
        duplicate = true;
      }
    }
    if(!duplicate){
      newData.push(row);
    }
  }
  sheet.clearContents();
  sheet.getRange(1, 1, newData.length, newData[0].length).setValues(newData);
}

but this function start removing duplicate row from the first row, i want to start removing from the end row of sheet.
How can i do this?


问:
Able to select "I'm Feeling Lucky" but cannot click it
I am trying to write a simple program to open up chrome, go to Google, and click on "I'm Feeling Lucky." I see that it acts as if the cursor is placed over the icon, but it will not perform a click.

```<code>driver.get("https://www.google.com")
element = WebDriverWait(driver, 20) \
    .until(EC.visibility_of_element_located((By.ID, "gbqfbb")))
element.click()
</code>```

No errors occur in the code, but it will not click the element.

答:
Where you get that ID? When I visit the site, I don't see an element with that ID. It's possible that Google has some sort of way of manipulating this to make it harder for people to automate this process. It's possible that Google doesn't want you doing this.

Either way, you should be able to select the element by something else:

```<code>driver.get("https://www.google.com")
element = WebDriverWait(driver, 20) \
    .until(EC.visibility_of_element_located((By. CSS_SELECTOR, '[jsaction="sf.lck"]')))
element.click()
</code>```

Body:
I am trying to write a simple program to open up chrome, go to Google, and click on "I'm Feeling Lucky." I see that it acts as if the cursor is placed over the icon, but it will not perform a click.

driver.get("https://www.google.com")
element = WebDriverWait(driver, 20) \
    .until(EC.visibility_of_element_located((By.ID, "gbqfbb")))
element.click()

No errors occur in the code, but it will not click the element.

Body:
Where you get that ID? When I visit the site, I don't see an element with that ID. It's possible that Google has some sort of way of manipulating this to make it harder for people to automate this process. It's possible that Google doesn't want you doing this.

Either way, you should be able to select the element by something else:

driver.get("https://www.google.com")
element = WebDriverWait(driver, 20) \
    .until(EC.visibility_of_element_located((By. CSS_SELECTOR, '[jsaction="sf.lck"]')))
element.click()


问:
How do you see if a key includes a value and return the key up 2 levels? Alexa/JS
I want to see if a category is in a pack, and if it is, return that pack name.

So if my string was 'Pack1category1', I want to return 'pack1'.

How could I go about doing this?

```<code>{
    "paidTier": {
        "categoryPacks": {
            "pack1": {
                "categories": [
                    "Pack1category1",
                    "Pack1category2",
                    "Pack1category3",
                    "Pack1category4",
                    "Pack1category5",
                    "Pack1category6"
                ]
            },
            "pack2": {
                "categories": [
                    "Pack2category1",
                    "Pack2category2",
                    "Pack2category3",
                    "Pack2category4",
                    "Pack2category5",
                    "Pack2category6"
                ]
            }
        }
    }
}
</code>```

Something like this:

```<code>var string = 'Pack1category1'
//Loop through paidTier and find string
return 'pack1';
</code>```

or

```<code>var string = 'Pack2category5'
//Loop through paidTier and find string
return 'pack2';
</code>```

I've been at this for at least 10 hours and every method I've tried has failed. Please help! lol

答:
<pre class="lang-js prettyprint-override"><code>// assume `json` is your input object
var desiredCategory = 'Pack1category1';
var packCategories = json.paidTier.categoryPacks

var pack = Object.keys(packCategories).find(pack => packCategories[pack].categories.includes(desiredCategory))
console.log(pack) // 'pack1'
</code>```

Body:
I want to see if a category is in a pack, and if it is, return that pack name.

So if my string was 'Pack1category1', I want to return 'pack1'.

How could I go about doing this?

{
    "paidTier": {
        "categoryPacks": {
            "pack1": {
                "categories": [
                    "Pack1category1",
                    "Pack1category2",
                    "Pack1category3",
                    "Pack1category4",
                    "Pack1category5",
                    "Pack1category6"
                ]
            },
            "pack2": {
                "categories": [
                    "Pack2category1",
                    "Pack2category2",
                    "Pack2category3",
                    "Pack2category4",
                    "Pack2category5",
                    "Pack2category6"
                ]
            }
        }
    }
}

Something like this:

var string = 'Pack1category1'
//Loop through paidTier and find string
return 'pack1';

or

var string = 'Pack2category5'
//Loop through paidTier and find string
return 'pack2';

I've been at this for at least 10 hours and every method I've tried has failed. Please help! lol


问:
Get Used Range of Filtered ListObject
I am trying to copy the visible cells of a filtered table to another sheet.

I am getting an error that Range.Address is an invalid qualifier, although I read, this is how you must refer to a list object range.

```<code>Sub TestRun()
    Dim strng As Range
    Dim lo_b1 As ListObject

    Set lo_b1 = x_bf1.ListObjects(1)
    Set strng = ThisWorkbook.Names("co_st").RefersToRange

    lo_b1.Range.Address.SpecialCells(xlCellTypeVisible).Copy strng

End Sub
</code>```

答:
Here is a tiny example.  Starting with a ListObject in Sheet1:

This will apply a filter and copy the visible rows elsewhere:

```<code>Sub KopyTab()
    Dim rng As Range

    Set rng = ActiveSheet.ListObjects("Table1").Range

    rng.AutoFilter Field:=1, Criteria1:="mike"
    rng.Cells.SpecialCells(xlCellTypeVisible).Copy Sheets("Sheet2").Range("A1")

End Sub
</code>```

The result:

Title: Get Used Range of Filtered ListObject

Body:
I am trying to copy the visible cells of a filtered table to another sheet.

I am getting an error that Range.Address is an invalid qualifier, although I read, this is how you must refer to a list object range.

Sub TestRun()
    Dim strng As Range
    Dim lo_b1 As ListObject

    Set lo_b1 = x_bf1.ListObjects(1)
    Set strng = ThisWorkbook.Names("co_st").RefersToRange

    lo_b1.Range.Address.SpecialCells(xlCellTypeVisible).Copy strng

End Sub

Body:
Here is a tiny example.  Starting with a ListObject in Sheet1:

This will apply a filter and copy the visible rows elsewhere:

Sub KopyTab()
    Dim rng As Range

    Set rng = ActiveSheet.ListObjects("Table1").Range

    rng.AutoFilter Field:=1, Criteria1:="mike"
    rng.Cells.SpecialCells(xlCellTypeVisible).Copy Sheets("Sheet2").Range("A1")

End Sub

The result:


问:
Error CS0234: The type or namespace name 'AspNetCore' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)
I'm trying to upgrade the following template project to ASP.NET Core 1.1:
https://github.com/wilanbigay/aspnet-core-aurelia-typescript-starter

After running dotnet migrate the project.json file has been dropped in favour of the new csproj file.

Using Visual Studio Code and the Nuget4Code extension I've upgraded all components to ASP.NET Core 1.1.

The CsProj now contains entries like so:

```<code><ItemGroup>
    <PackageReference Include="Microsoft.NET.Sdk">
      <Version>1.0.0-alpha-20161104-2</Version>
      <PrivateAssets>All</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.NET.Sdk.Web">
      <Version>1.0.0-alpha-20161104-2</Version>
      <PrivateAssets>All</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.NETCore.App">
      <Version>1.1.0</Version>
    </PackageReference>
    <PackageReference Include="Microsoft.AspNetCore.Mvc">
      <Version>1.1.0</Version>
    </PackageReference>
</code>```

However I have compilation issues.  It seems the AspNetCore namespace can't be found.  I'm getting the error

Error CS0234: The type or namespace name 'AspNetCore' does not exist in the names pace 'Microsoft' (are you missing an assembly reference?)

I'm not sure how I can check references like I used to be able to in Visual Studio in the references section.
How can I resolve this?

答: Just add Microsoft.AspNetCore.WebUtilities nuget package</p>

Body:
I'm trying to upgrade the following template project to ASP.NET Core 1.1:
https://github.com/wilanbigay/aspnet-core-aurelia-typescript-starter

After running dotnet migrate the project.json file has been dropped in favour of the new csproj file.

Using Visual Studio Code and the Nuget4Code extension I've upgraded all components to ASP.NET Core 1.1.

The CsProj now contains entries like so:

<ItemGroup>
    <PackageReference Include="Microsoft.NET.Sdk">
      <Version>1.0.0-alpha-20161104-2</Version>
      <PrivateAssets>All</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.NET.Sdk.Web">
      <Version>1.0.0-alpha-20161104-2</Version>
      <PrivateAssets>All</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.NETCore.App">
      <Version>1.1.0</Version>
    </PackageReference>
    <PackageReference Include="Microsoft.AspNetCore.Mvc">
      <Version>1.1.0</Version>
    </PackageReference>

However I have compilation issues.  It seems the AspNetCore namespace can't be found.  I'm getting the error

Error CS0234: The type or namespace name 'AspNetCore' does not exist in the names pace 'Microsoft' (are you missing an assembly reference?)

I'm not sure how I can check references like I used to be able to in Visual Studio in the references section.
How can I resolve this?


问:
Error when testing Firestore online with Jest: "Auth error:TypeError: fetch is not a function"
I am trying to test Cloud Firestore with Jest, but have the following error.

const admin = require('firebase-admin');
const serviceAccount = require("../../../config/YOUR-PROJECT-NAME-firebase-adminsdk-XXXX-XXXXXX.json");

// const myfirestore: any = new MyFireStore()

describe('MyFirestore', () =>{
  it('getDocument', async () => {

    admin.initializeApp({
      credential: admin.credential.cert(serviceAccount),
      databaseURL: "https://unittest-dfb64.firebaseio.com"
    });

    let result = false
    const db = admin.firestore();
    const collectionRef = db.collection('test')
    const docRef = collectionRef.doc('testDoc')
    const getDoc = await docRef.get()
    if (getDoc && getDoc.exists) {
      result = getDoc.data()
    }

    expect(result).toEqual('testdata')
  }, 100000)
```

"Auth error:TypeError: fetch is not a function".

(source: goodpic.com)

I googled a lot but could not find any hint about this error.
What is the proper way to access to the Firestore data inside Jest test?
Thank you so much for your help in advance.

The full code is uploaded here.

https://github.com/goodpic/firebase-graphql-boilerplate

I checked and tried these docs but could not figure out what is the root of this error.

https://firebase.google.com/docs/functions/unit-testing
https://github.com/firebase/functions-samples/blob/master/quickstarts/uppercase/functions/test/test.online.js
https://gist.github.com/starhoshi/21d1fb870d485a95c86fe93cfe1ac240

答:
I finally found the root of the cause of this issue. The issue was caused by an incompatibility between jest and the gaxios project.

https://github.com/firebase/firebase-admin-node/issues/512#issuecomment-487218219

As a workaround of the issue, I could solve by downgrading gaxios to 1.8.3 as explained in the comment.

```<code>"dependencies": {
    "firebase-admin": "^7.3.0",
    "gaxios": "1.8.3"
  },
  "resolutions": {
    "**/gaxios": "1.8.3"
  },

</code>```

Body:
I am trying to test Cloud Firestore with Jest, but have the following error.

const admin = require('firebase-admin');
const serviceAccount = require("../../../config/YOUR-PROJECT-NAME-firebase-adminsdk-XXXX-XXXXXX.json");

// const myfirestore: any = new MyFireStore()

describe('MyFirestore', () =>{
  it('getDocument', async () => {

    admin.initializeApp({
      credential: admin.credential.cert(serviceAccount),
      databaseURL: "https://unittest-dfb64.firebaseio.com"
    });

    let result = false
    const db = admin.firestore();
    const collectionRef = db.collection('test')
    const docRef = collectionRef.doc('testDoc')
    const getDoc = await docRef.get()
    if (getDoc && getDoc.exists) {
      result = getDoc.data()
    }

    expect(result).toEqual('testdata')
  }, 100000)

"Auth error:TypeError: fetch is not a function".

(source: goodpic.com)

I googled a lot but could not find any hint about this error.
What is the proper way to access to the Firestore data inside Jest test?
Thank you so much for your help in advance.

The full code is uploaded here.

https://github.com/goodpic/firebase-graphql-boilerplate

I checked and tried these docs but could not figure out what is the root of this error.

https://firebase.google.com/docs/functions/unit-testing
https://github.com/firebase/functions-samples/blob/master/quickstarts/uppercase/functions/test/test.online.js
https://gist.github.com/starhoshi/21d1fb870d485a95c86fe93cfe1ac240

Body:
I finally found the root of the cause of this issue. The issue was caused by an incompatibility between jest and the gaxios project.

https://github.com/firebase/firebase-admin-node/issues/512#issuecomment-487218219

As a workaround of the issue, I could solve by downgrading gaxios to 1.8.3 as explained in the comment.

"dependencies": {
    "firebase-admin": "^7.3.0",
    "gaxios": "1.8.3"
  },
  "resolutions": {
    "**/gaxios": "1.8.3"
  },


答:
```<code>const packages = {
    "paidTier": {
        "categoryPacks": {
            "pack1": {
                "categories": [
                    "Pack1category1",
                    "Pack1category2",
                    "Pack1category3",
                    "Pack1category4",
                    "Pack1category5",
                    "Pack1category6"
                ]
            },
            "pack2": {
                "categories": [
                    "Pack2category1",
                    "Pack2category2",
                    "Pack2category3",
                    "Pack2category4",
                    "Pack2category5",
                    "Pack2category6"
                ]
            }
        }
    }
}

const findPack = (categoryName) => Object.keys(packages.paidTier.categoryPacks).find(packName =>
  packages.paidTier.categoryPacks[packName].categories.includes(categoryName)
)

findPack('Pack2category1') // => "pack2"
</code>```

Title: How do you see if a key includes a value and return the key up 2 levels? Alexa/JS


问:
ASP.NET losing connection to SQL Server Express after being published to IIS
I have an ASP.NET application that gets data from a SQL Server Express on the same computer. When I run the ASP.NET project from Visual Studio, the project can reach the database just fine. However, when published to IIS, the project loses the connection. Here is my connection string located in Web.config:

```<code><connectionStrings>
    <add name="conString"
         providerName="System.Data.SqlClient"
         connectionString="Server = DESKTOP-EVAN\SERVER;Database=master;User ID=sa;Password=12345;" />
</connectionStrings>
</code>```

The project can be reached on the published IIS, however no data is there and no error messages show.

I've added the application pool and NT Authority to the SQL login but still no luck connection to the database.

Does anyone have any experience with this? How can I get my published ASP.NET project to connect to my SQL Server Express?

答:
Did you install SQL Server Express on that machine where IIS is running, or on a machine that can be reached from the IIS machine?

Also: did you explicitly define a separate instance name for your SQL Server Express when installing?

By default, the instance name would be SQLEXPRESS - but you seem to refer to  DESKTOP-EVAN\SERVER - so SERVER would be your instance name - is that the case??

If not: can you try DESKTOP-EVAN\SQLEXPRESS as the server/instance name instead?

```<code><connectionStrings>
    <add name="conString"
         connectionString="Server=DESKTOP-EVAN\SQLEXPRESS;Database=master;User ID=sa;Password=12345;"
         providerName="System.Data.SqlClient" />
</connectionStrings>
</code>```

Body:
I have an ASP.NET application that gets data from a SQL Server Express on the same computer. When I run the ASP.NET project from Visual Studio, the project can reach the database just fine. However, when published to IIS, the project loses the connection. Here is my connection string located in Web.config:

<connectionStrings>
    <add name="conString"
         providerName="System.Data.SqlClient"
         connectionString="Server = DESKTOP-EVAN\SERVER;Database=master;User ID=sa;Password=12345;" />
</connectionStrings>

The project can be reached on the published IIS, however no data is there and no error messages show.

I've added the application pool and NT Authority to the SQL login but still no luck connection to the database.

Does anyone have any experience with this? How can I get my published ASP.NET project to connect to my SQL Server Express?

Body:
Did you install SQL Server Express on that machine where IIS is running, or on a machine that can be reached from the IIS machine?

Also: did you explicitly define a separate instance name for your SQL Server Express when installing?

By default, the instance name would be SQLEXPRESS - but you seem to refer to  DESKTOP-EVAN\SERVER - so SERVER would be your instance name - is that the case??

If not: can you try DESKTOP-EVAN\SQLEXPRESS as the server/instance name instead?

<connectionStrings>
    <add name="conString"
         connectionString="Server=DESKTOP-EVAN\SQLEXPRESS;Database=master;User ID=sa;Password=12345;"
         providerName="System.Data.SqlClient" />
</connectionStrings>


问:
How to check whether firebug is installed in Mozilla or not?

Possible Duplicate:

  Javascript that detects Firebug?

How to check whether Firebug is installed in Mozilla or not using JavaScript code?

答:
anywhere in a web page, you could do this:

```<code><script>
if(console) {
    console.log("Firebug is installed and running!");
} else {
    alert("Firebus either isn't installed, or isn't running.");
}
</script>
</code>```

Not perfect if you specifically want to check for Firebug, because it could report that Firebug exists on other browsers such as Chrome, since their Developer Tools also use the same console object as Firebug. If you really need to only check for Firebug, then you could also add a browser detection to make sure you're in Firefox.

Body:
anywhere in a web page, you could do this:

<script>
if(console) {
    console.log("Firebug is installed and running!");
} else {
    alert("Firebus either isn't installed, or isn't running.");
}
</script>

Not perfect if you specifically want to check for Firebug, because it could report that Firebug exists on other browsers such as Chrome, since their Developer Tools also use the same console object as Firebug. If you really need to only check for Firebug, then you could also add a browser detection to make sure you're in Firefox.


问:
Is there a Python equivalent to Ruby's string interpolation?
Ruby example:

```<code>name = "Spongebob Squarepants"
puts "Who lives in a Pineapple under the sea? \n#{name}."
</code>```

The successful Python string concatenation is seemingly verbose to me.

答:
Python 3.6 and newer have literal string interpolation using f-strings:</p>

```<code>name='world'
print(f"Hello {name}!")
</code>```

Body:
Ruby example:

name = "Spongebob Squarepants"
puts "Who lives in a Pineapple under the sea? \n#{name}."

The successful Python string concatenation is seemingly verbose to me.

Body:
Python 3.6 and newer have literal string interpolation using f-strings:

name='world'
print(f"Hello {name}!")


问:
How to map over possibly empty array in Typescript
I have a function whose parameter can either be an empty array or an array with strings.

So I handle this with a union type of  [] | string[]

Then, Inside the function, I check to see if the array.length > 0, and if it IS, then I map over the parameter.

```<code>type Kennel = [] | string[]

const petDogs = (kennel: Kennel)  => {
  if (kennel.length > 0){
    return kennel.map((name:string)=>name)
  } else {
    return "no doggies to pet"
  }
}
</code>```

However, on compilation, I get the error

Cannot invoke an expression whose type lacks a call signature. Type '((callbackfn: (value: never, index: number, array: never[]) => U, thisArg?: any) => U[]) | ((callbackfn: (value: string, index: number, array: string[]) => U, thisArg?: any) => U[])' has no compatible call signatures

I have tried using function overloading, but it didn't solve the compilation error.

example:

```<code>interface PetDogs {
  (kennel: []): string;
  (kennel: string[]): string[];
}
</code>```

答:
[] is a tuple type, which is meant for a different kind of use case. string[] is an array type, and an empty array is still a string[] type. Your code would work without compilation errors:

```<code>type Kennel = string[]

const petDogs = (kennel: Kennel)  => {
  if (kennel.length > 0){
    return kennel.map((name:string)=>name)
  } else {
    return "no doggies to pet"
  }
}

petDogs([]);
petDogs(["Fido", "Doggo"]);

</code>```

Body:
I have a function whose parameter can either be an empty array or an array with strings.

So I handle this with a union type of  [] | string[]

Then, Inside the function, I check to see if the array.length > 0, and if it IS, then I map over the parameter.

type Kennel = [] | string[]

const petDogs = (kennel: Kennel)  => {
  if (kennel.length > 0){
    return kennel.map((name:string)=>name)
  } else {
    return "no doggies to pet"
  }
}

However, on compilation, I get the error

Cannot invoke an expression whose type lacks a call signature. Type '((callbackfn: (value: never, index: number, array: never[]) => U, thisArg?: any) => U[]) | ((callbackfn: (value: string, index: number, array: string[]) => U, thisArg?: any) => U[])' has no compatible call signatures

I have tried using function overloading, but it didn't solve the compilation error.

example:

interface PetDogs {
  (kennel: []): string;
  (kennel: string[]): string[];
}

Body:
[] is a tuple type, which is meant for a different kind of use case. string[] is an array type, and an empty array is still a string[] type. Your code would work without compilation errors:

type Kennel = string[]

const petDogs = (kennel: Kennel)  => {
  if (kennel.length > 0){
    return kennel.map((name:string)=>name)
  } else {
    return "no doggies to pet"
  }
}

petDogs([]);
petDogs(["Fido", "Doggo"]);


问:
Get an array of all UITextFields in UITableView
I have a static TableView that I am using as a form for user input.  I am currently adding targets to each TextField so that I can add textFieldDidChange(_ textField: UITextField) for UIControl.Event.editingChanged

I would like to add all the TextFields to an array so that I can loop through and do this for all the TextFields without having to manual do it for each one.

I have tried the following, but it does not work:

```<code>var textFields = [UITextField]()
for view in self.view.subviews {
    if let textField = view as? UITextField {
        textFields.append(textField)
    }
}
</code>```

Any help would be greatly appreciated

答:
Create a IBOutlet collection connection in the UITableViewController and connect all text fields with the connection. Then you can use this IBOutlet collection as an array of UITextField

```<code>class TableViewController: UITableViewController {

    @IBOutlet var textFields: [UITextField]!

    override func viewDidLoad() {
        super.viewDidLoad()
        textFields.forEach {
            $0.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
        }
    }
    @objc func textFieldDidChange(_ textField: UITextField) {

    }
}
</code>```

Body:
I have a static TableView that I am using as a form for user input.  I am currently adding targets to each TextField so that I can add textFieldDidChange(_ textField: UITextField) for UIControl.Event.editingChanged

I would like to add all the TextFields to an array so that I can loop through and do this for all the TextFields without having to manual do it for each one.

I have tried the following, but it does not work:

var textFields = [UITextField]()
for view in self.view.subviews {
    if let textField = view as? UITextField {
        textFields.append(textField)
    }
}

Any help would be greatly appreciated

Body:
Create a IBOutlet collection connection in the UITableViewController and connect all text fields with the connection. Then you can use this IBOutlet collection as an array of UITextField

class TableViewController: UITableViewController {

    @IBOutlet var textFields: [UITextField]!

    override func viewDidLoad() {
        super.viewDidLoad()
        textFields.forEach {
            $0.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
        }
    }
    @objc func textFieldDidChange(_ textField: UITextField) {

    }
}


问:
MLR resampling creates oneclass problems for multilabel classification
I am trying to measure performance of multilabel classification for some MLR classifiers using cross validation

I tried to use MLR resample method or pass my own subset, however in both situations an error gets thrown (from what I have found out it happens when subset used for training contains only single values for some label)

Below is a small example where this problem occurs:

```<code>learner = mlr::makeLearner("classif.logreg")

learner = makeMultilabelClassifierChainsWrapper(learner)

data = data.frame(
    attr1 = c(1, 2, 2, 1, 2, 1, 2),
    attr2 = c(2, 1, 2, 2, 1, 2, 1),
    lab1 = c(FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE),
    lab2 = c(FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE))

task = mlr::makeMultilabelTask(data=data, target=c('lab1', 'lab2'))

</code>```

here are two ways two get an error:

1.

```<code>rDesc = makeResampleDesc("CV", iters = 3)

resample(learner, task, rDesc)
</code>```

2.

```<code>model = mlr::train(learner, task, subset=c(TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE))
</code>```

The error message:

Error in checkLearnerBeforeTrain(task, learner, weights): Task 'lab1' is a one-class-problem, but learner 'classif.logreg' does not support that!

答:
As there are no learners in MLR that support one-class ( https://mlr.mlr-org.com/articles/tutorial/integrated_learners.html ) classification and splitting the data may require too much fuss (especially for datasets like reutersk500), I have created a wrapper for twoclass learners that, if given task with single target class, will always return this class only value, and for more classes will use wrapped learner:

(This code will be a part of repository https://github.com/lychanl/ChainsOfClassification )

```<code>makeOneClassWrapper = function(learner) {
    learner = checkLearner(learner, type='classif')
    id = paste("classif.oneClassWrapper", getLearnerId(learner), sep = ".")
    packs = getLearnerPackages(learner)
    type = getLearnerType(learner)
    x = mlr::makeBaseWrapper(id, type, learner, packs, makeParamSet(),
        learner.subclass = c("OneClassWrapper"),
        model.subclass = c("OneClassWrapperModel"))
    x$type = "classif"
    x$properties = c(learner$properties, 'oneclass')
    return(x)
}

trainLearner.OneClassWrapper = function(.learner, .task, .subset = NULL, .weights = NULL, ...) {
    if (length(getTaskDesc(.task)$class.levels) <= 1) {
        x = list(oneclass=TRUE, value=.task$task.desc$positive)
        class(x) = "OneClassWrapperModel"
        return(makeChainModel(next.model = x, cl = c(.learner$model.subclass)))
    }

    model = train(.learner$next.learner, .task, .subset, .weights)

    x = list(oneclass=FALSE, model=model)
    class(x) = "OneClassWrapperModel"
    return(makeChainModel(next.model = x, cl = c(.learner$model.subclass)))
}

predictLearner.OneClassWrapper = function(.learner, .model, .newdata, ...) {
    .model = mlr::getLearnerModel(.model, more.unwrap = FALSE)

    if (.model$oneclass) {
        out = as.logical(rep(.model$value, nrow(.newdata)))
    }
    else {
        pred = predict(.model$model, newdata=.newdata)

        if (.learner$predict.type == "response") {
            out = getPredictionResponse(pred)
        } else {
            out = getPredictionProbabilities(pred, cl="TRUE")
        }
    }

    return(as.factor(out))
}

getLearnerProperties.OneClassWrapper = function(.learner) {
    return(.learner$properties)
}

isFailureModel.OneClassWrapperModel = function(model) {
    model = mlr::getLearnerModel(model, more.unwrap = FALSE)

  return(!model$oneclass && isFailureModel(model$model))
}

getFailureModelMsg.OneClassWrapperModel = function(model) {
    model = mlr::getLearnerModel(model, more.unwrap = FALSE)
  if (model$oneclass)
      return("")
  return(getFailureModelMsg(model$model))
}

getFailureModelDump.OneClassWrapperModel = function(model) {
    model = mlr::getLearnerModel(model, more.unwrap = FALSE)
  if (model$oneclass)
      return("")
  return(getFailureModelDump(model$model))
}

registerS3method("trainLearner", "<OneClassWrapper>",
  trainLearner.OneClassWrapper)
registerS3method("getLearnerProperties", "<OneClassWrapper>",
  getLearnerProperties.OneClassWrapper)
registerS3method("isFailureModel", "<OneClassWrapperModel>",
  isFailureModel.OneClassWrapperModel)
registerS3method("getFailureModelMsg", "<OneClassWrapperModel>",
  getFailureModelMsg.OneClassWrapperModel)
registerS3method("getFailureModelDump", "<OneClassWrapperModel>",
  getFailureModelDump.OneClassWrapperModel)
</code>```

Body:
I am trying to measure performance of multilabel classification for some MLR classifiers using cross validation

I tried to use MLR resample method or pass my own subset, however in both situations an error gets thrown (from what I have found out it happens when subset used for training contains only single values for some label)

Below is a small example where this problem occurs:

learner = mlr::makeLearner("classif.logreg")

learner = makeMultilabelClassifierChainsWrapper(learner)

data = data.frame(
    attr1 = c(1, 2, 2, 1, 2, 1, 2),
    attr2 = c(2, 1, 2, 2, 1, 2, 1),
    lab1 = c(FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE),
    lab2 = c(FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE))

task = mlr::makeMultilabelTask(data=data, target=c('lab1', 'lab2'))

here are two ways two get an error:

1.

rDesc = makeResampleDesc("CV", iters = 3)

resample(learner, task, rDesc)

2.

model = mlr::train(learner, task, subset=c(TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE))

The error message:

Error in checkLearnerBeforeTrain(task, learner, weights): Task 'lab1' is a one-class-problem, but learner 'classif.logreg' does not support that!

Body:
As there are no learners in MLR that support one-class ( https://mlr.mlr-org.com/articles/tutorial/integrated_learners.html ) classification and splitting the data may require too much fuss (especially for datasets like reutersk500), I have created a wrapper for twoclass learners that, if given task with single target class, will always return this class only value, and for more classes will use wrapped learner:

(This code will be a part of repository https://github.com/lychanl/ChainsOfClassification )

makeOneClassWrapper = function(learner) {
    learner = checkLearner(learner, type='classif')
    id = paste("classif.oneClassWrapper", getLearnerId(learner), sep = ".")
    packs = getLearnerPackages(learner)
    type = getLearnerType(learner)
    x = mlr::makeBaseWrapper(id, type, learner, packs, makeParamSet(),
        learner.subclass = c("OneClassWrapper"),
        model.subclass = c("OneClassWrapperModel"))
    x$type = "classif"
    x$properties = c(learner$properties, 'oneclass')
    return(x)
}

trainLearner.OneClassWrapper = function(.learner, .task, .subset = NULL, .weights = NULL, ...) {
    if (length(getTaskDesc(.task)$class.levels) <= 1) {
        x = list(oneclass=TRUE, value=.task$task.desc$positive)
        class(x) = "OneClassWrapperModel"
        return(makeChainModel(next.model = x, cl = c(.learner$model.subclass)))
    }

    model = train(.learner$next.learner, .task, .subset, .weights)

    x = list(oneclass=FALSE, model=model)
    class(x) = "OneClassWrapperModel"
    return(makeChainModel(next.model = x, cl = c(.learner$model.subclass)))
}

predictLearner.OneClassWrapper = function(.learner, .model, .newdata, ...) {
    .model = mlr::getLearnerModel(.model, more.unwrap = FALSE)

    if (.model$oneclass) {
        out = as.logical(rep(.model$value, nrow(.newdata)))
    }
    else {
        pred = predict(.model$model, newdata=.newdata)

        if (.learner$predict.type == "response") {
            out = getPredictionResponse(pred)
        } else {
            out = getPredictionProbabilities(pred, cl="TRUE")
        }
    }

    return(as.factor(out))
}

getLearnerProperties.OneClassWrapper = function(.learner) {
    return(.learner$properties)
}

isFailureModel.OneClassWrapperModel = function(model) {
    model = mlr::getLearnerModel(model, more.unwrap = FALSE)

  return(!model$oneclass && isFailureModel(model$model))
}

getFailureModelMsg.OneClassWrapperModel = function(model) {
    model = mlr::getLearnerModel(model, more.unwrap = FALSE)
  if (model$oneclass)
      return("")
  return(getFailureModelMsg(model$model))
}

getFailureModelDump.OneClassWrapperModel = function(model) {
    model = mlr::getLearnerModel(model, more.unwrap = FALSE)
  if (model$oneclass)
      return("")
  return(getFailureModelDump(model$model))
}

registerS3method("trainLearner", "<OneClassWrapper>",
  trainLearner.OneClassWrapper)
registerS3method("getLearnerProperties", "<OneClassWrapper>",
  getLearnerProperties.OneClassWrapper)
registerS3method("isFailureModel", "<OneClassWrapperModel>",
  isFailureModel.OneClassWrapperModel)
registerS3method("getFailureModelMsg", "<OneClassWrapperModel>",
  getFailureModelMsg.OneClassWrapperModel)
registerS3method("getFailureModelDump", "<OneClassWrapperModel>",
  getFailureModelDump.OneClassWrapperModel)


问:
How to bind Close command to a button
The easiest way is to implement ButtonClick event handler and invoke Window.Close() method, but how doing this through a Command binding?

答:
Actually, it is possible without C# code. The key is to use interactions:

```<code><Button Content="Close">
  <i:Interaction.Triggers>
    <i:EventTrigger EventName="Click">
      <ei:CallMethodAction TargetObject="{Binding ElementName=window}" MethodName="Close"/>
    </i:EventTrigger>
  </i:Interaction.Triggers>
</Button>
</code>```

In order for this to work, just set the x:Name of your window to "window", and add these two namespaces:

```<code>xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
</code>```

This requires that you add the Expression Blend SDK DLL to your project, specifically Microsoft.Expression.Interactions.

In case you don't have Blend, the SDK can be downloaded here.

Title: How to bind Close command to a button

Body:
Actually, it is possible without C# code. The key is to use interactions:

<Button Content="Close">
  <i:Interaction.Triggers>
    <i:EventTrigger EventName="Click">
      <ei:CallMethodAction TargetObject="{Binding ElementName=window}" MethodName="Close"/>
    </i:EventTrigger>
  </i:Interaction.Triggers>
</Button>

In order for this to work, just set the x:Name of your window to "window", and add these two namespaces:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"

This requires that you add the Expression Blend SDK DLL to your project, specifically Microsoft.Expression.Interactions.

In case you don't have Blend, the SDK can be downloaded here.


问:
add callback to function(e) Uncaught TypeError: callback is not a function
I have a function which I can not seem to add callback into.

```<code>function ajaxCartFormSubmitted(e) {
  someotherfunctionsinside();
  if (e)...
});

function test () {
    console.log('abraka');

}
</code>```

I try do do

```<code>function ajaxCartFormSubmitted(e, callback) {
  someotherfunctionsinside();
  if (e)...
  if (callback) {
    callback();
  }
});
</code>```

and then calling

```<code>ajaxCartFormSubmitted(test);
</code>```

But I get Uncaught TypeError: callback is not a function. What is the problem? I use jquery 1.3 and cannot upgrade. Thank you.

答:
But I get Uncaught TypeError: callback is not a function. What is the problem?

The problem is that you haven't passed ajaxCartFormSubmitted two arguments, you've only passed it one, which it receives as the parameter e (the first parameter). The callback parameter will be undefined when you do that.

Either pass it two arguments, or change the function so it only expects one.

What the function expects:

```<code>function ajaxCartFormSubmitted(e, callback) {
//           First parameter --^  ^^^^^^^^--- second parameter
</code>```

What you're sending it:

```<code>ajaxCartFormSubmitted(test);
//                    ^^^^------ First (only) argument
</code>```

Body:
I have a function which I can not seem to add callback into.

function ajaxCartFormSubmitted(e) {
  someotherfunctionsinside();
  if (e)...
});

function test () {
    console.log('abraka');

}

I try do do

function ajaxCartFormSubmitted(e, callback) {
  someotherfunctionsinside();
  if (e)...
  if (callback) {
    callback();
  }
});

and then calling

ajaxCartFormSubmitted(test);

But I get Uncaught TypeError: callback is not a function. What is the problem? I use jquery 1.3 and cannot upgrade. Thank you.

Body:
But I get Uncaught TypeError: callback is not a function. What is the problem?

The problem is that you haven't passed ajaxCartFormSubmitted two arguments, you've only passed it one, which it receives as the parameter e (the first parameter). The callback parameter will be undefined when you do that.

Either pass it two arguments, or change the function so it only expects one.

What the function expects:

function ajaxCartFormSubmitted(e, callback) {
//           First parameter --^  ^^^^^^^^--- second parameter

What you're sending it:

ajaxCartFormSubmitted(test);
//                    ^^^^------ First (only) argument


问:
Counting the max of elements based on stack operations c++
You are given a stack of N integers. In one operation, you can either pop an element from the stack or push any popped element into the stack. You need to maximize the top element of the stack after performing exactly K operations. If the stack becomes empty after performing K operations and there is no other way for the stack to be non-empty, print -1.

I'm dynamically allocating the memory and then releasing the memory. I am unable to understand why I'm facing this issue.

```<code>#include "pch.h"
#include<iostream>
using namespace std;
int main()
{
int n, x, max;
cin >> n;
cin >> x;
int* arr = new int[n];
    //Storing the values from the last, since the first element represents
    //top of the stack, so the first element would be latest element which
    //will be pushed into the stack
for (int i = n; i > 0; i--)
{
    cin >> arr[i];
}
max = arr[n];
    //Finding the max by iterating from the last position to the no of
    //stack operations performed.
for (int i = n; i >= x; i--)
{
    if (arr[i] > max)
    {
        max = arr[i];
    }
}
cout << max;
delete arr;
return 0;
}
</code>```

Input :

```<code>6 4
1 2 4 3 3 5
</code>```

Expected Output :

```<code>4
</code>```

Error:

```<code>Error Message : Debug Error ! Program :- Heap Corruption detected : after
normal block c#2368 at 0x01d21e30. CRT detected that the application wrote
memory after end of heap buffer.
</code>```

答:
First you need to get the requirement straight in your head:

You are given a stack of N integers. In one operation, you can either pop an element from the stack or push any popped element into the stack. You need to maximize the top element of the stack after performing exactly K operations. If the stack becomes empty after performing K operations and there is no other way for the stack to be non-empty, print -1.

So, if N is 0 you print -1, otherwise...

If K is 0 you print top(), otherwise...

If K is 1 you have to pop() because you've got nothing to push, so if N was 1 your stack is empty and you must print -1, otherwise print top(): whatever your 2nd-top element happened to be; otherwise...

if x <= N, you can pop x - 1 elements then push the largest of those back on the top of the stack

if x == N, note that means you still won't have popped the final value from the stack, so if it's the largest element you're out of luck: you'll have to push the 2nd-largest back on the top of the stack
otherwise...

if x > N, you can pop all the elements, waste any operations until you've only got 1 operation left (by alternately pushing any one of the not-largest values back then if you have another op to waste popping it off), then using the last op to push the largest value back on the stack; this is equivalent to finding the largest value in the stack

So, code that always finds the smallest element in the top "x" stack elements doesn't model the stack operations you're supposed to have available.

Now, just because you understand what value your program should return doesn't mean you shouldn't model the operations accurately.  It sounds to me like you should use a stack, push, pop and top operations, and keep track of the values you've popped so you can push them back if necessary, and you may need to be able to find the largest you've popped to specifically put it back.

To do all that, it's easiest to use the std::stack data structure, and say std::multiset to store the popped elements in sorted order (so you can find the largest one easily).

Code looks like this.  It can be made more efficient/shorter, but I'll leave that to you.

```<code>#include <iostream>
#include <set>
#include <stack>

#define ASSERT(WHAT, MSG) \
    do { \
        if (!(WHAT)) { \
            std::cerr << "ASSERTION FAILURE AT LINE " \
                << __LINE__ << ": " #WHAT "\n" << MSG << '\n'; \
        } \
    } while (false)

#define DBG(MSG) std::cout << "DBG :" << __LINE__ << " " << MSG << '\n'

// helper functions to be able to stream out containers we're using...
std::ostream& operator<<(std::ostream& os, const std::multiset<int>& s)
{
    os << "{ ";
    for (const auto& x : s) std::cout << x << ' ';
    return os << '}';
}

// note this makes a deep copy of the stack (because "s" is passed by value
// not by reference), so we can pop all the elements destructively
std::ostream& operator<<(std::ostream& os, std::stack<int> s)
{
    os << "{ ";
    while (!s.empty())
    {
        std::cout << s.top() << ' ';
        s.pop();
    }
    return os << '}';
}

int main()
{
    std::stack<int> s;
    std::multiset<int> popped;

    int n, k;

    ASSERT(std::cin >> n >> k, "input must have parseable int values for n and k");

    DBG("n " << n << ", k " << k);
    ASSERT(n >= 0, "n must not be negative");
    ASSERT(k >= 0, "k must not be negative");

    for (int i = 0; i < n; ++i)
    {
        int x;
        ASSERT(std::cin >> x, "input must have parseable int for value #" << i + 1);
        s.push(x);
    }

    DBG("initial stack " << s);

    if (n == 0)
        std::cout << -1 << '\n';
    else if (k == 0)
        std::cout << s.top() << '\n';
    else if (k == 1)
    {
        if (n == 1)
            std::cout << -1 << '\n';
        else
        {
            s.pop(); // have to use up our k1 operation as a pop
            std::cout << s.top() << '\n';
        }
    }
    else if (k <= n) // can't pop all the values
    {
        for (int i = 1; i < k; ++i)
        {
            DBG("popping " << s.top());
            popped.insert(s.top()); // add to popped...
            s.pop(); // ...and remove from stack
        }
        DBG("popped k-1 elements (sorted) " << popped);
        DBG("stack " << s);
        // use the last operation to put the largest popped value back
        // (if the stack's has size 2 or more, could pop another one instead -
        //  no way to know which is better, but if the values are random then
        //  the max of all the popped elements is likely to be more than any
        //  given element)
        s.push(*popped.rbegin());  // largest value seen...
        std::cout << s.top() << '\n';
    }
    else // k > n so can pop all the values...
    {
        DBG("k > n");
        while (!s.empty())
        {
            popped.insert(s.top());
            s.pop();
        }
        // waste however many spare operations we have...
        for (int i = 0; i < k - n - 1; ++i)
            if (i % 2 == 0) // on first, third, fifth iteration...
            {
                DBG("push " << *popped.begin());
                s.push(*popped.begin());  // push lowest value seen back to stack...
                popped.erase(popped.begin());  // ...remove it from popped multiset
            }
            else
            {
                DBG("pop " << s.top());
                popped.insert(s.top());
                s.pop();
            }
        DBG("popped elements (sorted) " << popped);
        DBG("stack " << s);
        s.push(*popped.rbegin());  // push largest value...
        std::cout << s.top() << '\n';
    }
}
</code>```

Body:
You are given a stack of N integers. In one operation, you can either pop an element from the stack or push any popped element into the stack. You need to maximize the top element of the stack after performing exactly K operations. If the stack becomes empty after performing K operations and there is no other way for the stack to be non-empty, print -1.

I'm dynamically allocating the memory and then releasing the memory. I am unable to understand why I'm facing this issue.

#include "pch.h"
#include<iostream>
using namespace std;
int main()
{
int n, x, max;
cin >> n;
cin >> x;
int* arr = new int[n];
    //Storing the values from the last, since the first element represents
    //top of the stack, so the first element would be latest element which
    //will be pushed into the stack
for (int i = n; i > 0; i--)
{
    cin >> arr[i];
}
max = arr[n];
    //Finding the max by iterating from the last position to the no of
    //stack operations performed.
for (int i = n; i >= x; i--)
{
    if (arr[i] > max)
    {
        max = arr[i];
    }
}
cout << max;
delete arr;
return 0;
}

Input :

6 4
1 2 4 3 3 5

Expected Output :

4

Error:

Error Message : Debug Error ! Program :- Heap Corruption detected : after
normal block c#2368 at 0x01d21e30. CRT detected that the application wrote
memory after end of heap buffer.

Body:
First you need to get the requirement straight in your head:

You are given a stack of N integers. In one operation, you can either pop an element from the stack or push any popped element into the stack. You need to maximize the top element of the stack after performing exactly K operations. If the stack becomes empty after performing K operations and there is no other way for the stack to be non-empty, print -1.

So, if N is 0 you print -1, otherwise...

If K is 0 you print top(), otherwise...

If K is 1 you have to pop() because you've got nothing to push, so if N was 1 your stack is empty and you must print -1, otherwise print top(): whatever your 2nd-top element happened to be; otherwise...

if x <= N, you can pop x - 1 elements then push the largest of those back on the top of the stack

if x == N, note that means you still won't have popped the final value from the stack, so if it's the largest element you're out of luck: you'll have to push the 2nd-largest back on the top of the stack
otherwise...

if x > N, you can pop all the elements, waste any operations until you've only got 1 operation left (by alternately pushing any one of the not-largest values back then if you have another op to waste popping it off), then using the last op to push the largest value back on the stack; this is equivalent to finding the largest value in the stack

So, code that always finds the smallest element in the top "x" stack elements doesn't model the stack operations you're supposed to have available.

Now, just because you understand what value your program should return doesn't mean you shouldn't model the operations accurately.  It sounds to me like you should use a stack, push, pop and top operations, and keep track of the values you've popped so you can push them back if necessary, and you may need to be able to find the largest you've popped to specifically put it back.

To do all that, it's easiest to use the std::stack data structure, and say std::multiset to store the popped elements in sorted order (so you can find the largest one easily).

Code looks like this.  It can be made more efficient/shorter, but I'll leave that to you.

#include <iostream>
#include <set>
#include <stack>

#define ASSERT(WHAT, MSG) \
    do { \
        if (!(WHAT)) { \
            std::cerr << "ASSERTION FAILURE AT LINE " \
                << __LINE__ << ": " #WHAT "\n" << MSG << '\n'; \
        } \
    } while (false)

#define DBG(MSG) std::cout << "DBG :" << __LINE__ << " " << MSG << '\n'

// helper functions to be able to stream out containers we're using...
std::ostream& operator<<(std::ostream& os, const std::multiset<int>& s)
{
    os << "{ ";
    for (const auto& x : s) std::cout << x << ' ';
    return os << '}';
}

// note this makes a deep copy of the stack (because "s" is passed by value
// not by reference), so we can pop all the elements destructively
std::ostream& operator<<(std::ostream& os, std::stack<int> s)
{
    os << "{ ";
    while (!s.empty())
    {
        std::cout << s.top() << ' ';
        s.pop();
    }
    return os << '}';
}

int main()
{
    std::stack<int> s;
    std::multiset<int> popped;

    int n, k;

    ASSERT(std::cin >> n >> k, "input must have parseable int values for n and k");

    DBG("n " << n << ", k " << k);
    ASSERT(n >= 0, "n must not be negative");
    ASSERT(k >= 0, "k must not be negative");

    for (int i = 0; i < n; ++i)
    {
        int x;
        ASSERT(std::cin >> x, "input must have parseable int for value #" << i + 1);
        s.push(x);
    }

    DBG("initial stack " << s);

    if (n == 0)
        std::cout << -1 << '\n';
    else if (k == 0)
        std::cout << s.top() << '\n';
    else if (k == 1)
    {
        if (n == 1)
            std::cout << -1 << '\n';
        else
        {
            s.pop(); // have to use up our k1 operation as a pop
            std::cout << s.top() << '\n';
        }
    }
    else if (k <= n) // can't pop all the values
    {
        for (int i = 1; i < k; ++i)
        {
            DBG("popping " << s.top());
            popped.insert(s.top()); // add to popped...
            s.pop(); // ...and remove from stack
        }
        DBG("popped k-1 elements (sorted) " << popped);
        DBG("stack " << s);
        // use the last operation to put the largest popped value back
        // (if the stack's has size 2 or more, could pop another one instead -
        //  no way to know which is better, but if the values are random then
        //  the max of all the popped elements is likely to be more than any
        //  given element)
        s.push(*popped.rbegin());  // largest value seen...
        std::cout << s.top() << '\n';
    }
    else // k > n so can pop all the values...
    {
        DBG("k > n");
        while (!s.empty())
        {
            popped.insert(s.top());
            s.pop();
        }
        // waste however many spare operations we have...
        for (int i = 0; i < k - n - 1; ++i)
            if (i % 2 == 0) // on first, third, fifth iteration...
            {
                DBG("push " << *popped.begin());
                s.push(*popped.begin());  // push lowest value seen back to stack...
                popped.erase(popped.begin());  // ...remove it from popped multiset
            }
            else
            {
                DBG("pop " << s.top());
                popped.insert(s.top());
                s.pop();
            }
        DBG("popped elements (sorted) " << popped);
        DBG("stack " << s);
        s.push(*popped.rbegin());  // push largest value...
        std::cout << s.top() << '\n';
    }
}


问:
How can I get the same piece (duplicate code) of an image from many different photos every time?
From 5000 photos of license plates I want to determine which duplicate code these license plates have.

Here are 2 examples of a duplicate code on a license plate.

In the first example the duplicate code is 2 and in the second example the duplicate code is 1.

With the package Magick and Tesseract, see code below, I was able to retrieve the piece of the photo from the first example where the duplicate code is and to read the duplicate code. Only in the second example and other photos is the photo different.

So I am looking for something that can recognize where the duplicate code is and that will read the duplicate code. Note: The duplicate code is always above the 1st indent mark.

Does someone have an idea how to read the duplicate code automatically from 5000 different photos?

```<code>library(magick)
library(tesseract)

#Load foto:
foto <- image_read("C:/Users/camie/OneDrive/Documenten/kenteken3.jpg")

 #Get piece of photo where duplicate code is retrieved:
foto2 <- image_crop(foto,"10X24-620-170")

#read duplicate code:
cat(ocr(foto3))
</code>```

答:
Here is an approach based on the package EBImage. ImageMagik is great for image manipulation but I think EBImage may provide more quantitative tools that are useful here. As for all image processing, the quality of input image matters a great deal. The approach suggested here would likely benefit from noise and artifact removal, scaling and possibly cropping.

Also, some licenses seem to have additional symbols in the position of interest that are not numbers. Clearly more pre-processing and filtering are needed for such cases.

Sample image

```<code># Starting from EBImage
  if (!require(EBImage)) {
    source("http://bioconductor.org/biocLite.R")
    biocLite("EBImage")
    library(EBImage)
  }

# Test images
#   setwd(<image directory>)
    f1 <- "license1.jpg"
    f2 <- "license2.jpg"

# Read image and convert to normalized greyscale
  img0 <- readImage(f1)
  img <- channel(img0, "grey")
  img <- normalize(img)
# plot(img) # insert plot or display commands as desired

# Rudimentary image process for ~300 pixel wide JPEG
  xmf <- medianFilter(img, 1)
  xgb <- gblur(xmf, 1)
  xth <- xgb < otsu(xgb) # Otsu's algorithm to determine best threshold
  xto <- opening(xth, makeBrush(3, shape = "diamond"))
</code>```

A binary (thresholded) image has been produced and cleaned up to identify objects as shown here.

```<code># Create object mask with unique integer for each object
  xm <- bwlabel(xto)
# plot(colorLabels(xm)) # optional code to visualize the objects
</code>```

In addition to the rudimentary image process, some "object processing" can be applied as shown here. Objects along the edge are not going to be of interest so they are removed. Similarly, artifacts that give rise to horizontal (wide) streaks can be removed as well.

```<code># Drop objects touching the edge
  nx <- dim(xm)[1]
  ny <- dim(xm)[2]
  sel <- unique(c(xm[1,], xm[nx,], xm[,1], xm[,ny]))
  sel <- sel[sel != 0]
  xm <- rmObjects(xm, sel, reenumerate = TRUE)

# Drop exceptionally wide objects (33% of image width)
  major <- computeFeatures.moment(xm)[,"m.majoraxis"]
  sel <- which(major > nx/3)
  xm <- rmObjects(xm, sel, reenumerate = TRUE)
</code>```

The following logic identifies the center of mass for each object with the computeFeatures.moment function of EBImage. It seems that the main symbols will be along a horizontal line while the candidate object will be above that line (lower y-value in EBImage Image object). An alternative approach would be to find objects stacked on one another, i.e., objects with similar x-values.

For the examples I explored, one standard deviation away from the median y-value for the center of mass appears to be sufficient to identify candidate object. This is used to determine the limits shown below. Of course, this logic should be adjusted as dictated by the actual data.

```<code># Determine center of mass for remaining objects
  M <- computeFeatures.moment(xm)
  x <- M[,1]
  y <- M[,2]

# Show suggested limit on image (y coordinates are inverted)
  plot(img)
  limit <- median(y) - sd(y)
  abline(h = limit, col = "red")

# Show centers of mass on original image
  ok <- y < limit
  points(x[!ok], y[!ok], pch = 16, col = "blue")
  points(x[ok], y[ok], pch = 16, col = "red")

</code>```

The image shows the segmented objects after having discarded objects along the edge. Red shows the candidate, blue shows the non-candidates.

Because some licenses have two symbols above the dash, the following code selects the leftmost of possible candidates, expands the object mask and returns a rectangular crop of the image that can be passed to ocr().

```<code># Accept leftmost (first) of candidate objects
  left <- min(x[which(ok)])
  sel <- which(x == left)

# Enlarge object mask and extract the candidate image
  xm <- dilate(xm, makeBrush(7, "disc"))
  ix <- range(apply(xm, 2, function(v) which(v == sel)))
  iy <- range(apply(xm, 1, function(v) which(v == sel)))
  xx <- ix[1]:ix[2]
  yy <- iy[1]:iy[2]

# "Return" selected portion of image
  ans <- img[xx, yy] # this is what can be passed to tesseract
  plot(ans, interpolate = FALSE)
</code>```

Here is the unscaled and extracted candidate image from example 1:

Another sample image

The same code applied to this example gives the following:

With a few more checks for errors and for illogical conditions, the code could be assembled into single function and applied to the list of 5000 files! But of course that assumes they are properly formatted, etc. etc.

Body:
From 5000 photos of license plates I want to determine which duplicate code these license plates have.

Here are 2 examples of a duplicate code on a license plate.

In the first example the duplicate code is 2 and in the second example the duplicate code is 1.

With the package Magick and Tesseract, see code below, I was able to retrieve the piece of the photo from the first example where the duplicate code is and to read the duplicate code. Only in the second example and other photos is the photo different.

So I am looking for something that can recognize where the duplicate code is and that will read the duplicate code. Note: The duplicate code is always above the 1st indent mark.

Does someone have an idea how to read the duplicate code automatically from 5000 different photos?

library(magick)
library(tesseract)

#Load foto:
foto <- image_read("C:/Users/camie/OneDrive/Documenten/kenteken3.jpg")

 #Get piece of photo where duplicate code is retrieved:
foto2 <- image_crop(foto,"10X24-620-170")

#read duplicate code:
cat(ocr(foto3))

Body:
Here is an approach based on the package EBImage. ImageMagik is great for image manipulation but I think EBImage may provide more quantitative tools that are useful here. As for all image processing, the quality of input image matters a great deal. The approach suggested here would likely benefit from noise and artifact removal, scaling and possibly cropping.

Also, some licenses seem to have additional symbols in the position of interest that are not numbers. Clearly more pre-processing and filtering are needed for such cases.

Sample image

# Starting from EBImage
  if (!require(EBImage)) {
    source("http://bioconductor.org/biocLite.R")
    biocLite("EBImage")
    library(EBImage)
  }

# Test images
#   setwd(<image directory>)
    f1 <- "license1.jpg"
    f2 <- "license2.jpg"

# Read image and convert to normalized greyscale
  img0 <- readImage(f1)
  img <- channel(img0, "grey")
  img <- normalize(img)
# plot(img) # insert plot or display commands as desired

# Rudimentary image process for ~300 pixel wide JPEG
  xmf <- medianFilter(img, 1)
  xgb <- gblur(xmf, 1)
  xth <- xgb < otsu(xgb) # Otsu's algorithm to determine best threshold
  xto <- opening(xth, makeBrush(3, shape = "diamond"))

A binary (thresholded) image has been produced and cleaned up to identify objects as shown here.

# Create object mask with unique integer for each object
  xm <- bwlabel(xto)
# plot(colorLabels(xm)) # optional code to visualize the objects

In addition to the rudimentary image process, some "object processing" can be applied as shown here. Objects along the edge are not going to be of interest so they are removed. Similarly, artifacts that give rise to horizontal (wide) streaks can be removed as well.

# Drop objects touching the edge
  nx <- dim(xm)[1]
  ny <- dim(xm)[2]
  sel <- unique(c(xm[1,], xm[nx,], xm[,1], xm[,ny]))
  sel <- sel[sel != 0]
  xm <- rmObjects(xm, sel, reenumerate = TRUE)

# Drop exceptionally wide objects (33% of image width)
  major <- computeFeatures.moment(xm)[,"m.majoraxis"]
  sel <- which(major > nx/3)
  xm <- rmObjects(xm, sel, reenumerate = TRUE)

The following logic identifies the center of mass for each object with the computeFeatures.moment function of EBImage. It seems that the main symbols will be along a horizontal line while the candidate object will be above that line (lower y-value in EBImage Image object). An alternative approach would be to find objects stacked on one another, i.e., objects with similar x-values.

For the examples I explored, one standard deviation away from the median y-value for the center of mass appears to be sufficient to identify candidate object. This is used to determine the limits shown below. Of course, this logic should be adjusted as dictated by the actual data.

# Determine center of mass for remaining objects
  M <- computeFeatures.moment(xm)
  x <- M[,1]
  y <- M[,2]

# Show suggested limit on image (y coordinates are inverted)
  plot(img)
  limit <- median(y) - sd(y)
  abline(h = limit, col = "red")

# Show centers of mass on original image
  ok <- y < limit
  points(x[!ok], y[!ok], pch = 16, col = "blue")
  points(x[ok], y[ok], pch = 16, col = "red")

The image shows the segmented objects after having discarded objects along the edge. Red shows the candidate, blue shows the non-candidates.

Because some licenses have two symbols above the dash, the following code selects the leftmost of possible candidates, expands the object mask and returns a rectangular crop of the image that can be passed to ocr().

# Accept leftmost (first) of candidate objects
  left <- min(x[which(ok)])
  sel <- which(x == left)

# Enlarge object mask and extract the candidate image
  xm <- dilate(xm, makeBrush(7, "disc"))
  ix <- range(apply(xm, 2, function(v) which(v == sel)))
  iy <- range(apply(xm, 1, function(v) which(v == sel)))
  xx <- ix[1]:ix[2]
  yy <- iy[1]:iy[2]

# "Return" selected portion of image
  ans <- img[xx, yy] # this is what can be passed to tesseract
  plot(ans, interpolate = FALSE)

Here is the unscaled and extracted candidate image from example 1:

Another sample image

The same code applied to this example gives the following:

With a few more checks for errors and for illogical conditions, the code could be assembled into single function and applied to the list of 5000 files! But of course that assumes they are properly formatted, etc. etc.


问:
Unable to create regular expression for diffrent URL's
I am new to Jmeter and want to create a regular expression which can capture both the urls's below:

I am trying using this expression:

```<code>movies/(.+?)/(.+?)&amp
</code>```

Its not working for both the url's:

```<code>https://in.bookmyshow.com/bengaluru/movies/avengers-endgame/ET00090482&
https://in.bookmyshow.com/movies/the-tashkent-files/ET00069063/&
</code>```

答:
Try the below regular expression and let me know the results.

movies/(.*?)&

Body:
I am new to Jmeter and want to create a regular expression which can capture both the urls's below:

I am trying using this expression:

movies/(.+?)/(.+?)&amp

Its not working for both the url's:

https://in.bookmyshow.com/bengaluru/movies/avengers-endgame/ET00090482&
https://in.bookmyshow.com/movies/the-tashkent-files/ET00069063/&


问:
Navigating to a section of a page using a reactstrat button's action
Typically if I want to make a link to go to a part of a page I use:

```<code><a style={{ color: 'white' }} href="#topOfPage">
        Personal Info
</a>
</code>```

Since I have to use Button from reactstrap (https://reactstrap.github.io/components/buttons/) instead of  I need to ask how to do the same within the action method of a button. Is this possible?

答:
There are a couple of options:

Try coding it this way:

```<code><Button tag={Link} style={{ color: 'white' }} to="#topOfPage" />
</code>```

You can utilize the same anchor tag href functionality with reactstraps buttons.

Another option, if the above does not work, would to be add the Bootstrap node_module and code it the way you always have. I tend to mix reactstrap and bootstraps npmjs modules in my projects for faster coding.

Body:
Typically if I want to make a link to go to a part of a page I use:

        Personal Info

Since I have to use Button from reactstrap (https://reactstrap.github.io/components/buttons/) instead of  I need to ask how to do the same within the action method of a button. Is this possible?

Body:
There are a couple of options:

Try coding it this way:

<Button tag={Link} style={{ color: 'white' }} to="#topOfPage" />

You can utilize the same anchor tag href functionality with reactstraps buttons.

Another option, if the above does not work, would to be add the Bootstrap node_module and code it the way you always have. I tend to mix reactstrap and bootstraps npmjs modules in my projects for faster coding.


问:
Temporaries problem in C++
I have this piece of code that prints the content of a directory using Boost.Filesystem:

```<code>class Shell {
private:
    const string& command;
    const path& firstPath;
    const path& secondPath;
public:
    // constructor
    Shell(const string& _command, const path& _firstPath, const path& _secondPath = path()): command(_command), firstPath(_firstPath), secondPath(_secondPath) {}

    //destructor
    ~Shell() {}

    //execute commands
    void executeCommand()
    {
        if(command.compare("ls"))
        {
            ls();
        }
    }

    void ls()
    {
        if(exists(firstPath))
        {
            vector<path> vecPath;

            copy(directory_iterator(firstPath), directory_iterator(), back_inserter(vecPath));
            sort(vecPath.begin(), vecPath.end());
            for(vector<path>::iterator it = vecPath.begin(); it != vecPath.end(); ++it)
            {
                cout << *it << endl;
            }
        }
    }
};

int main(int argc, char** argv)
{
    path Path = "c:\\workspace";
    Shell shell("ls", Path); // GOOD
    // Shell shell("ls", "c:\\workspace");  BAD creates temporary !!
    shell.executeCommand();
}
</code>```

If I send my second argument direclty as a const char* I know that it will create a temporary and my constructor argument will only be visible in the constructor, then its lost, because of the reference to temporary.

My question is, why isnt the same thing happening to the first argument, the string, because I am sending him also as a const char* directly, but the value isnt lost outside of the constructor ?

答:
Is there a specific reason why you store references instead of copies?
By changing your class from

```<code>class Shell {
private:
    const string& command;
    const path& firstPath;
    const path& secondPath;
...
</code>```

to

```<code>class Shell {
private:
    const string command;
    const path firstPath;
    const path secondPath;
...
</code>```

you can avoid lot's of your problems and both cases will be correct.
Why this is the case you can see in the answer of sehe

Title: Temporaries problem in C++

Body:
I have this piece of code that prints the content of a directory using Boost.Filesystem:

class Shell {
private:
    const string& command;
    const path& firstPath;
    const path& secondPath;
public:
    // constructor
    Shell(const string& _command, const path& _firstPath, const path& _secondPath = path()): command(_command), firstPath(_firstPath), secondPath(_secondPath) {}

    //destructor
    ~Shell() {}

    //execute commands
    void executeCommand()
    {
        if(command.compare("ls"))
        {
            ls();
        }
    }

    void ls()
    {
        if(exists(firstPath))
        {
            vector<path> vecPath;

            copy(directory_iterator(firstPath), directory_iterator(), back_inserter(vecPath));
            sort(vecPath.begin(), vecPath.end());
            for(vector<path>::iterator it = vecPath.begin(); it != vecPath.end(); ++it)
            {
                cout << *it << endl;
            }
        }
    }
};

int main(int argc, char** argv)
{
    path Path = "c:\\workspace";
    Shell shell("ls", Path); // GOOD
    // Shell shell("ls", "c:\\workspace");  BAD creates temporary !!
    shell.executeCommand();
}

If I send my second argument direclty as a const char* I know that it will create a temporary and my constructor argument will only be visible in the constructor, then its lost, because of the reference to temporary.

My question is, why isnt the same thing happening to the first argument, the string, because I am sending him also as a const char* directly, but the value isnt lost outside of the constructor ?

Body:
Is there a specific reason why you store references instead of copies?
By changing your class from

class Shell {
private:
    const string& command;
    const path& firstPath;
    const path& secondPath;
...

to

class Shell {
private:
    const string command;
    const path firstPath;
    const path secondPath;
...

you can avoid lot's of your problems and both cases will be correct.
Why this is the case you can see in the answer of sehe


问:
How to be explicit about the type of a captured variable in a lambda?
How can I explicitly specify the type of a captured variable for a lambda in C++?

For example, assume I have a function that takes a universal reference and I want to perfect-forward it into a lambda.

I found out, that I can use a std::tuple for this as shown below, but I wonder if there is a more succinct way.

```<code>template<typename T>
auto returns_functor (T&& value)
{
  return [value = std::tuple<T> (std::forward<T> (value))] ()
  {
    /* use std::get<0> (value) */
  };
}
</code>```

Related: Capturing perfectly-forwarded variable in lambda (the accepted answer there suggests this is a different question, but further answers give essentially the above solution).

答:
Another way of capturing rvalue ( universal reference) is as follows,

```<code>template< typename T>
T getRvalue( T&& temp)
{
  auto lambda = [ rTemp = std::move( temp)]() mutable
  {
     return T( std::forward< T>( rTemp));
  };

  return lambda();
}
</code>```

std::move() allows to capture objects of movable type those can't be captured by copy.
mutable is very important here in lambda, until mutable is not used, objects captured by lambda can't be modified and compile will generate following error,

```<code>cannot conver 'rTemp (type 'const T') to type 'std::remove_reference<T>::type&' {aka 'T&'}
return T( std::forward< T>( rTemp));
</code>```

Now about first question,

"How can I explicitly specify the type of a captured variable for a lambda in C++?"

 So It is not required to specify the type, compile will do it, see following link,

https://en.cppreference.com/w/cpp/language/lambda

It states A capture with an initializer acts as if it declares and explicitly captures a variable declared with type auto, whose declarative region is the body of the lambda expression. In simple words, it means auto variable get deduced according to initializer and doesn't requires to specify it's type explicitly, for example

```<code>int x = 1;
auto lambda = [ y = x + 2](){ std::cout<< "y = "<< y<< std::endl;};
</code>```

Here y would be deduced as int by initializer x + 2.

Body:
How can I explicitly specify the type of a captured variable for a lambda in C++?

For example, assume I have a function that takes a universal reference and I want to perfect-forward it into a lambda.

I found out, that I can use a std::tuple for this as shown below, but I wonder if there is a more succinct way.

template<typename T>
auto returns_functor (T&& value)
{
  return [value = std::tuple<T> (std::forward<T> (value))] ()
  {
    /* use std::get<0> (value) */
  };
}

Related: Capturing perfectly-forwarded variable in lambda (the accepted answer there suggests this is a different question, but further answers give essentially the above solution).

Body:
Another way of capturing rvalue ( universal reference) is as follows,

template< typename T>
T getRvalue( T&& temp)
{
  auto lambda = [ rTemp = std::move( temp)]() mutable
  {
     return T( std::forward< T>( rTemp));
  };

  return lambda();
}

std::move() allows to capture objects of movable type those can't be captured by copy.
mutable is very important here in lambda, until mutable is not used, objects captured by lambda can't be modified and compile will generate following error,

cannot conver 'rTemp (type 'const T') to type 'std::remove_reference<T>::type&' {aka 'T&'}
return T( std::forward< T>( rTemp));

Now about first question,

"How can I explicitly specify the type of a captured variable for a lambda in C++?"

 So It is not required to specify the type, compile will do it, see following link,

https://en.cppreference.com/w/cpp/language/lambda

It states A capture with an initializer acts as if it declares and explicitly captures a variable declared with type auto, whose declarative region is the body of the lambda expression. In simple words, it means auto variable get deduced according to initializer and doesn't requires to specify it's type explicitly, for example

int x = 1;
auto lambda = [ y = x + 2](){ std::cout<< "y = "<< y<< std::endl;};

Here y would be deduced as int by initializer x + 2.


问:
How to configure 【Azure】Application Gateway to support multiple App services?
I have 3 app services on Azure, like

app1.azurewebsites.net

app2.azurewebsites.net

app3.azurewebsites.net

And I have created an Application gateway in front of them, with WAF enabled.

And I'm going to setup 3 custom domain and SSL certificate for each of the app service.
What I want to achieve is like below:

visit https://app1.mydomain.com=>Application Gateway=>app1.azurewebsites.net

visit https://app2.mydomain.com=>Application Gateway=>app2.azurewebsites.net

visit https://app3.mydomain.com=>Application Gateway=>app3.azurewebsites.net

Is this possible with only 1 application gateway to support multiple domain? Or I must purchase 3 gateways, which is 3 times cost. Basically I only want to use the WAF to protect my site.

答:
Your ask is possible with one Application Gateway.

Here is the configuration that you need to set up.

Listener 1 (app1.mydomain.com) --> HTTP Setting 1 (Check Use App Service check box) --> Backend Pool 1(app1.azurewebsites.net)

Listener 2 (app2.mydomain.com) --> HTTP Setting 2 (Check Use App Service check box) --> Backend Pool 2(app2.azurewebsites.net)

Listener 3 (app3.mydomain.com) --> HTTP Setting 3 (Check Use App Service check box) --> Backend Pool 3(app3.azurewebsites.net)

So, you need 3 Listener , 3 HTTP Settings, 3 Backend Pool and 3 rules.

You need to create probes for each HTTP Setting and you enable HTTPS protocol and also check pick hostname from Backend HTTP Settings.

Reference: https://learn.microsoft.com/en-us/azure/application-gateway/configure-web-app-portal