问:
Grid view Updatearguments does Not contain New Values
```<code>public partial class Gridvw_expt2 : System.Web.UI.Page
{
   SqlCommand com;
   SqlDataAdapter da;
   DataSet ds;
   SqlConnection con=new SqlConnection(ConfigurationManager.ConnectionStrings["gj"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{

    com = new SqlCommand("Select * from tblExpt",con);
    da = new SqlDataAdapter(com);
    ds = new DataSet();
    da.Fill(ds);
    if (ds.Tables[0].Rows[0] != null)
    {
        GridView1.AutoGenerateEditButton = true;
        GridView1.DataSource = ds;
        GridView1.DataBind();
        GridView1.RowUpdating += new GridViewUpdateEventHandler(GridView1_RowUpdating);
        GridView1.DataKeyNames = new string[] { "id" };
        GridView1.RowEditing += new GridViewEditEventHandler(GridView1_RowEditing);

    }
    else
        Response.Write("fkj");
}

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    GridViewRow row = GridView1.Rows[e.RowIndex];
    int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);

    string cls = ((TextBox)(row.Cells[2].Controls[0])).Text;
    string nam = ((TextBox)(row.Cells[3].Controls[0])).Text;
    foreach (DictionaryEntry entry in e.NewValues)
    {
        e.NewValues[entry.Key] = Server.HtmlEncode(entry.Value.ToString());
    }
    com = new SqlCommand("Update tblExpt set name='" + nam + "',class='" + cls + "' where id='" + id + "'", con);
    da = new SqlDataAdapter(com);
    GridView1.EditIndex = -1;
    GridView1.DataSource = ds;
    GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
    GridView1.EditIndex = e.NewEditIndex;
    GridView1.DataSource = ds;
    GridView1.DataBind();
}
</code>```

}

In the above code when i try to access e.new values index out of range exception is thrown.

The table being accessed contains 3 fields id, class, name
Please help to solve the problem.

答:
The exception you get is because row.Cells[0].Controls[0] is a DataControlLinkButton and not a TextBox. Since I don´t know the control layout of your grid you could search for your textbox instead.

Instead of:

```<code>int id = int.Parse(((TextBox)(row.Cells[0].Controls[0])).Text);
</code>```

do something like the code below if there is only one TextBox per row:

```<code>TextBox box = (TextBox)row.Cells[0].Controls.OfType<TextBox>().First();
int id = int.Parse( box.Text );
</code>```

If you have nested html and hierarchies check out this SO question for nested searching of controls

Body:
public partial class Gridvw_expt2 : System.Web.UI.Page
{
   SqlCommand com;
   SqlDataAdapter da;
   DataSet ds;
   SqlConnection con=new SqlConnection(ConfigurationManager.ConnectionStrings["gj"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{

    com = new SqlCommand("Select * from tblExpt",con);
    da = new SqlDataAdapter(com);
    ds = new DataSet();
    da.Fill(ds);
    if (ds.Tables[0].Rows[0] != null)
    {
        GridView1.AutoGenerateEditButton = true;
        GridView1.DataSource = ds;
        GridView1.DataBind();
        GridView1.RowUpdating += new GridViewUpdateEventHandler(GridView1_RowUpdating);
        GridView1.DataKeyNames = new string[] { "id" };
        GridView1.RowEditing += new GridViewEditEventHandler(GridView1_RowEditing);

    }
    else
        Response.Write("fkj");
}

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    GridViewRow row = GridView1.Rows[e.RowIndex];
    int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);

    string cls = ((TextBox)(row.Cells[2].Controls[0])).Text;
    string nam = ((TextBox)(row.Cells[3].Controls[0])).Text;
    foreach (DictionaryEntry entry in e.NewValues)
    {
        e.NewValues[entry.Key] = Server.HtmlEncode(entry.Value.ToString());
    }
    com = new SqlCommand("Update tblExpt set name='" + nam + "',class='" + cls + "' where id='" + id + "'", con);
    da = new SqlDataAdapter(com);
    GridView1.EditIndex = -1;
    GridView1.DataSource = ds;
    GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
    GridView1.EditIndex = e.NewEditIndex;
    GridView1.DataSource = ds;
    GridView1.DataBind();
}

}

In the above code when i try to access e.new values index out of range exception is thrown.

The table being accessed contains 3 fields id, class, name
Please help to solve the problem.

Body:
The exception you get is because row.Cells[0].Controls[0] is a DataControlLinkButton and not a TextBox. Since I don´t know the control layout of your grid you could search for your textbox instead.

Instead of:

int id = int.Parse(((TextBox)(row.Cells[0].Controls[0])).Text);

do something like the code below if there is only one TextBox per row:

TextBox box = (TextBox)row.Cells[0].Controls.OfType<TextBox>().First();
int id = int.Parse( box.Text );

If you have nested html and hierarchies check out this SO question for nested searching of controls


来源: stackexchange

问:
How to Embed a PowerBI Report having filters showing start and end date
How to embed Powerbi report that contains start and end date filter I have a embedded report but I have no clue how can I show some data between the Start and end date can somebody point me into the right direction for this.</p>

答: It is not possible in Power BI to use a single slicer (filter) for two columns. Instead, you can use parameters.</p>

ContentLicense: CC BY-SA 3.0


问:
How to get multiple column's rows value in a single column?
I have two table tblCompany and tblUser
Both table contains email id fields, tblCompany contain 3 column as named contact1Email , contact2Email, contact3Email and tblUser contain a column named emailId. Unique field in both table is companyId. I want to get email of company and user's email those are belongs to that company. all those email ids I want in a single column.
I tried it in basic way using below query:

```<code>SELECT DISTINCT contact1Email , contact2Email, contact3Email, emailId
FROM fm_company
INNER JOIN fm_users ON fm_company.companyId = fm_users.companyId
WHERE fm_company.companyId =33
</code>```

this gives bellow result as shown in image

you can see there emailId column contain user's email and contact1Email , contact2Email, contact3Email contain company email.
I want all email in single column as name emailIds. How can it posible using sql query.?

I want a result like

```<code>|EmailIds         |
|-------------------
|a@a.ll
|-------------------
|asdasdasd@asd.asd
|-------------------
|asdasdasd1@asd.asd
|-------------------
|aaaaa@a.ll
|-------------------
|asd@aswq.km
|-------------------
|aa@asd.ff
|-------------------
</code>```

答:
TRY THIS: According to your question you want to display multiple columns email id in single column so I think you should use UNION OR UNION ALL to achieve the desired output in desired format as below:

```<code>SELECT DISTINCT contact1Email
FROM fm_company
INNER JOIN fm_users ON fm_company.companyId = fm_users.companyId
WHERE fm_company.companyId =33
UNION
SELECT DISTINCT contact2Email
FROM fm_company
INNER JOIN fm_users ON fm_company.companyId = fm_users.companyId
WHERE fm_company.companyId =33
UNION
SELECT DISTINCT contact3Email
FROM fm_company
INNER JOIN fm_users ON fm_company.companyId = fm_users.companyId
WHERE fm_company.companyId =33
UNION
SELECT DISTINCT emailId
FROM fm_company
INNER JOIN fm_users ON fm_company.companyId = fm_users.companyId
WHERE fm_company.companyId =33
</code>```

Body:
I have two table tblCompany and tblUser
Both table contains email id fields, tblCompany contain 3 column as named contact1Email , contact2Email, contact3Email and tblUser contain a column named emailId. Unique field in both table is companyId. I want to get email of company and user's email those are belongs to that company. all those email ids I want in a single column.
I tried it in basic way using below query:

SELECT DISTINCT contact1Email , contact2Email, contact3Email, emailId
FROM fm_company
INNER JOIN fm_users ON fm_company.companyId = fm_users.companyId
WHERE fm_company.companyId =33

this gives bellow result as shown in image

you can see there emailId column contain user's email and contact1Email , contact2Email, contact3Email contain company email.
I want all email in single column as name emailIds. How can it posible using sql query.?

I want a result like

|EmailIds         |
|-------------------
|a@a.ll
|-------------------
|asdasdasd@asd.asd
|-------------------
|asdasdasd1@asd.asd
|-------------------
|aaaaa@a.ll
|-------------------
|asd@aswq.km
|-------------------
|aa@asd.ff
|-------------------

Body:
TRY THIS: According to your question you want to display multiple columns email id in single column so I think you should use UNION OR UNION ALL to achieve the desired output in desired format as below:

SELECT DISTINCT contact1Email
FROM fm_company
INNER JOIN fm_users ON fm_company.companyId = fm_users.companyId
WHERE fm_company.companyId =33
UNION
SELECT DISTINCT contact2Email
FROM fm_company
INNER JOIN fm_users ON fm_company.companyId = fm_users.companyId
WHERE fm_company.companyId =33
UNION
SELECT DISTINCT contact3Email
FROM fm_company
INNER JOIN fm_users ON fm_company.companyId = fm_users.companyId
WHERE fm_company.companyId =33
UNION
SELECT DISTINCT emailId
FROM fm_company
INNER JOIN fm_users ON fm_company.companyId = fm_users.companyId
WHERE fm_company.companyId =33


问:
Run as Ant build' Missing in my eclipse
I am unable to right click and run my build.xml file by choosing 'Run as Ant' . Whenever I click it says run configuration and that goes into running Java file options .</p>

答:
Workaround:
Open the ANT-View, add the build file and start it from there.

(Had the problem in JBDS8 after installing IBM Diagnostics Tools)

Title: Run as Ant build' Missing in my eclipse


问:
AngularJS ng-src inside of iframe
I have a problem using ng-src inside of an iframe. I need to do this:

```<code><div class="tab-content">
        <ul class="nav nav-tabs" ng-repeat="document in issues.Document">
            <div class="tab-pane pdf-height col-md-5 padding_0" id="{{document.name}}">
                <iframe ng-src="http://192.168.223.110/cat/{{document.directory}}/{{document.name}}.{{document.type}}" height="100%" width="100%"></iframe>
            </div>
        </ul>
    </div>
</code>```

RESULT:

```<code><iframe ng-src="http://192.168.223.110/cat/{{document.directory}}/{{document.name}}.{{document.type}}" height="100%" width="100%" src="http://192.168.223.110/cat/{{document.directory}}/{{document.name}}.{{document.type}}"></iframe>
</code>```

I know that the problem is $sce, which is a protection from XSS, and that the link needs to be added to the whitelist... So it is working when I do this.

```<code><ul class="nav nav-tabs" ng-repeat="document in issues.Document">
    <div class="tab-pane pdf-height col-md-5 padding_0" id="{{document.name}}">
         <iframe ng-src="{{someUrl}}" height="100%" width="100%"></iframe>
     </div>
</ul>
</code>```

And I define inside the controller:

```<code>$rootScope.someUrl = $sce.trustAsResourceUrl('http://192.168.223.110/cat/files/incoming/12345_3232ASD_pero.pdf');
</code>```

But I can't do it like that because I'm looping with ng-repeat, so the link is generated dynamically. It need's to be readable from the database!

答:
As what Kop4lyf said
you need to add filter in js

```<code>//Create a filter for trust url
    app.filter('trustAsResourceUrl', ['$sce', function($sce) {
    return function(val) {
        return $sce.trustAsResourceUrl(val);
    };
}]);
</code>```

and output ih html as

```<code>ng-src="{{x.title.rendered | trustAsResourceUrl}}"
</code>```

Some other filter :

```<code>//Create a filter for trust html
    app.filter('trustAsHtml', ['$sce', function($sce) {
    return function(val) {
        return $sce.trustAsHtml(val);
    };
}]);
</code>```

Title: AngularJS ng-src inside of iframe

Body:
I have a problem using ng-src inside of an iframe. I need to do this:

RESULT:

I know that the problem is $sce, which is a protection from XSS, and that the link needs to be added to the whitelist... So it is working when I do this.

And I define inside the controller:

$rootScope.someUrl = $sce.trustAsResourceUrl('http://192.168.223.110/cat/files/incoming/12345_3232ASD_pero.pdf');

But I can't do it like that because I'm looping with ng-repeat, so the link is generated dynamically. It need's to be readable from the database!

Body:
As what Kop4lyf said
you need to add filter in js

//Create a filter for trust url
    app.filter('trustAsResourceUrl', ['$sce', function($sce) {
    return function(val) {
        return $sce.trustAsResourceUrl(val);
    };
}]);

and output ih html as

ng-src="{{x.title.rendered | trustAsResourceUrl}}"

Some other filter :

//Create a filter for trust html
    app.filter('trustAsHtml', ['$sce', function($sce) {
    return function(val) {
        return $sce.trustAsHtml(val);
    };
}]);


问:
ekeventviewcontroller hide delete button
I am having tableview EKEvents, if a user taps on an event i will push EKEventViewController.

EKEventViewController comes default with delete button in toolbar how can I hide this.

I tried making a custom viewController subclass of EKEventViewController and in viewWillAppear i was hiding the navigationController's toolbar it was working but not properly.Another problem with this it will allows me to navigate to event details which is not required.

```<code>let eventViewControler = EKEventViewController()
eventViewController.event = self.events[indexPath.row]
eventViewController.allowsEditing = false
self.navigationController.pushViewController(eventViewControler)
</code>```

How can I hide the only delete button.

答:
You can customize rightBarButtonItem.</p>

```<code>let rightButton : UIBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: self, action: "")
self.navigationItem.rightBarButtonItem = rightButton
</code>```

Body:
I am having tableview EKEvents, if a user taps on an event i will push EKEventViewController.

EKEventViewController comes default with delete button in toolbar how can I hide this.

I tried making a custom viewController subclass of EKEventViewController and in viewWillAppear i was hiding the navigationController's toolbar it was working but not properly.Another problem with this it will allows me to navigate to event details which is not required.

let eventViewControler = EKEventViewController()
eventViewController.event = self.events[indexPath.row]
eventViewController.allowsEditing = false
self.navigationController.pushViewController(eventViewControler)

How can I hide the only delete button.

Body:
You can customize rightBarButtonItem.

let rightButton : UIBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: self, action: "")
self.navigationItem.rightBarButtonItem = rightButton


问:
sapui5 how can i get selected item from value help into table cell?
I have a table.a column consists of input fields. How can I get value from searchHelpDialog to table item?

Below is a sample table:

And the value help dialog:

答:
you could use a datamodel, in which the value is written when selected.
this would need to happen in the controller of the fragment you use to build the searchHelpDialog.
also the model needs to be generated, since the rows of your list probably aren't static.</p>


问:
How to set hyperlink for text and send via email
I have below text and want to send as hyperlink via email.

String id1String = "XES";

String id2String = "ZX02";

String appLink = "myapp://myhost/myaction?id1=" + id1String + "&id2=" + id2String;

I have used below code but not working.

```<code>    Intent emailIntent = new Intent(Intent.ACTION_SEND);
    emailIntent.setData(Uri.parse("mailto:"));
    emailIntent.setType("text/html");
    emailIntent.putExtra(Intent.EXTRA_EMAIL, TO);
    emailIntent.putExtra(Intent.EXTRA_CC, CC);
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Your subject");
    emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml(appLink));

    try {
        startActivity(Intent.createChooser(emailIntent, "Send mail..."));
        finish();
        Log.i("Finished send email...", "");
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(MainActivity.this, "There is no email client installed.", Toast.LENGTH_SHORT).show();
    }
</code>```

答:
You can use html text as body in email intent.</p>

```<code> public void mailIntent() {
    String linkUrl = "www.stackoverflow.com";
    String body = "<a href=\"" + linkUrl + "\">" + linkUrl+ "</a>";
    Intent emailIntent = new Intent(Intent.ACTION_SEND);
    emailIntent.setData(Uri.parse("mailto:"));
    emailIntent.setType("text/html");
    emailIntent.putExtra(Intent.EXTRA_EMAIL, "fdads");
    emailIntent.putExtra(Intent.EXTRA_CC, "");
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Your subject");
    emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml(body));
    try {
        startActivity(Intent.createChooser(emailIntent, "Send mail..."));
        finish();
        Log.i("Finished send email...", "");
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(MainActivity.this, "There is no email client installed.", Toast.LENGTH_SHORT).show();
    }
}
</code>```

Body:
I have below text and want to send as hyperlink via email.

String id1String = "XES";

String id2String = "ZX02";

String appLink = "myapp://myhost/myaction?id1=" + id1String + "&id2=" + id2String;

I have used below code but not working.

    Intent emailIntent = new Intent(Intent.ACTION_SEND);
    emailIntent.setData(Uri.parse("mailto:"));
    emailIntent.setType("text/html");
    emailIntent.putExtra(Intent.EXTRA_EMAIL, TO);
    emailIntent.putExtra(Intent.EXTRA_CC, CC);
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Your subject");
    emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml(appLink));

    try {
        startActivity(Intent.createChooser(emailIntent, "Send mail..."));
        finish();
        Log.i("Finished send email...", "");
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(MainActivity.this, "There is no email client installed.", Toast.LENGTH_SHORT).show();
    }

Body:
You can use html text as body in email intent.

 public void mailIntent() {
    String linkUrl = "www.stackoverflow.com";
    String body = "<a href=\"" + linkUrl + "\">" + linkUrl+ "</a>";
    Intent emailIntent = new Intent(Intent.ACTION_SEND);
    emailIntent.setData(Uri.parse("mailto:"));
    emailIntent.setType("text/html");
    emailIntent.putExtra(Intent.EXTRA_EMAIL, "fdads");
    emailIntent.putExtra(Intent.EXTRA_CC, "");
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Your subject");
    emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml(body));
    try {
        startActivity(Intent.createChooser(emailIntent, "Send mail..."));
        finish();
        Log.i("Finished send email...", "");
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(MainActivity.this, "There is no email client installed.", Toast.LENGTH_SHORT).show();
    }
}


问:
cannot select text, cannot click <input>
I create a div on a function

```<code>function formatdata() {
  var div = document.createElement("div");
  div.className = 'inTable';
  div.innerHTML = "<label>Cannot Select</label><input type='text' value='' style='z-index:1300;!important'>";
  return div;
}

$('#data-table tbody').on('click', 'td.details-control', function() {
  var tr = $(this).closest('tr');
  var row = tabel.row(tr);
  if (row.child.isShown()) {
    row.child.hide();
    tr.removeClass('shown');
  } else {
    var data = tabel.row(this).data();
    row.child(formatdata(row.data())).show();
    tr.addClass('shown');
  }
});
</code>```

I cannot select the label, cannot focus on input field with cursor, but use tab key it can focus, i think, its about z-index of this div is lower than parent element, I just create script to get z-index

```<code>$(document.body).click(function() {
  var zind = $(this).css('z-index');
  alert(zin);
});
</code>```

When i clicked the div, parent of div its say "auto", in chrome i check developer tools -> element , but i don't know where is the problem.

Anyone can guide me to know where is the problem?

答:
You need to append the created div into the body

function formatdata() {
  var div = document.createElement("div");
  div.className = 'inTable';
  div.innerHTML = "Cannot Select<input type='text' value='' style='z-index:1300;!important'>";
  return div;
}

document.body.appendChild(formatdata());```

Body:
I create a div on a function

function formatdata() {
  var div = document.createElement("div");
  div.className = 'inTable';
  div.innerHTML = "Cannot Select<input type='text' value='' style='z-index:1300;!important'>";
  return div;
}

$('#data-table tbody').on('click', 'td.details-control', function() {
  var tr = $(this).closest('tr');
  var row = tabel.row(tr);
  if (row.child.isShown()) {
    row.child.hide();
    tr.removeClass('shown');
  } else {
    var data = tabel.row(this).data();
    row.child(formatdata(row.data())).show();
    tr.addClass('shown');
  }
});

I cannot select the label, cannot focus on input field with cursor, but use tab key it can focus, i think, its about z-index of this div is lower than parent element, I just create script to get z-index

$(document.body).click(function() {
  var zind = $(this).css('z-index');
  alert(zin);
});

When i clicked the div, parent of div its say "auto", in chrome i check developer tools -> element , but i don't know where is the problem.

Anyone can guide me to know where is the problem?

Body:
You need to append the created div into the body

function formatdata() {
  var div = document.createElement("div");
  div.className = 'inTable';
  div.innerHTML = "<label>Cannot Select</label><input type='text' value='' style='z-index:1300;!important'>";
  return div;
}

document.body.appendChild(formatdata());


问:
How can I just get the last record in the java.util.List using subList() or any other method?
Say I have a list of elements whose size is 100. Now I only want the 100th record in the list and the rest of all records from 1-99 should be removed from the list.

I have tried the below piece of code but no change in list size as I see it.

//Output list.size() returns 100

```<code>list.subList(list.size()-1, list.size());
</code>```

//Output list.size() returns 100 after subList() called...

How can I get just the last record in the java.util.List using subList() or using any other methods available in Java?

答:
list.subList returns a new List backed by the original List.

You need to store the returned list in a variable in order to use it:

```<code>List<String> subList = list.subList(list.size()-1, list.size());
</code>```

subList.size() will be 1. list will remain unchanged.

If you want to remove all but the last element from the original List, you can write:

```<code>list.subList(0, list.size()-1).clear();
</code>```

Now the original List will contain just 1 element.

Body:
Say I have a list of elements whose size is 100. Now I only want the 100th record in the list and the rest of all records from 1-99 should be removed from the list.

I have tried the below piece of code but no change in list size as I see it.

//Output list.size() returns 100

list.subList(list.size()-1, list.size());

//Output list.size() returns 100 after subList() called...

How can I get just the last record in the java.util.List using subList() or using any other methods available in Java?

Body:
list.subList returns a new List backed by the original List.

You need to store the returned list in a variable in order to use it:

List<String> subList = list.subList(list.size()-1, list.size());

subList.size() will be 1. list will remain unchanged.

If you want to remove all but the last element from the original List, you can write:

list.subList(0, list.size()-1).clear();

Now the original List will contain just 1 element.


问:
Elasticsearch NEST with Where condition
I am trying to MultiMatch search with a condition. I know similar questions have been asked in the past but not with using NEST. This is my current search, it works well across the entire document

```<code> var response = await this.client.SearchAsync<EmployeeDocument>(
                               x => x.Index(this.settings.IndexName).Type("employee").From(page * pageSize)
                                   .Size(pageSize).Query(
                                       q => q.MultiMatch(m => m
                                                .Query(query)
                                                .Type(TextQueryType.MostFields)
                                                .MinimumShouldMatch("90%")
                                                .Fields(f => f
                                                    .Field(_ => _.FullName, 3)
                                                    .Field(_ => _.Number, 3)
                                                    .Field(_ => _.Email)
                                                    .Field(_ => _.CompanyName, 2)
                                                    .Field(_ => _.JobNumber)
                                                    .Field(_ => _.Description))))
                    .Highlight(
                        h => h.PreTags("<mark>").PostTags("</mark>")
                            .Fields(
                                f => f.Field(p => p.FullName),
                                f => f.Field(p => p.CompanyName),
                                f => f.Field(p => p.JobNumber),
                                f => f.Field(p => p.Number),
                                f => f.Field(p => p.Email),
                                f => f.Field(p => p.Description))));
</code>```

How can I add a condition too only search for a specific field? (CompanyId)

So for instance the above code does an employee search, but it only needs to search inside a specific company.

This is what i have tried

```<code>var response = await this.client.SearchAsync<EmployeeDocument>(
                               x => x.Index(this.settings.IndexName).Type("employee").From(page * pageSize)
                                   .Size(pageSize).Query(
                                       q => q.MultiMatch(m => m
                                                .Query(query)
                                                .Type(TextQueryType.MostFields)
                                                .MinimumShouldMatch("90%")
                                                .Fields(f => f
                                                    .Field(_ => _.FullName, 3)
                                                    .Field(_ => _.Number, 3)
                                                    .Field(_ => _.Email)
                                                    .Field(_ => _.CompanyName, 2)
                                                    .Field(_ => _.JobNumber)
                                                    .Field(_ => _.Description))))
                           .Query(_ => _.Bool(b => b.Must(descriptor =>
                                       descriptor.Term(t =>
t.Field(document => document.CompanyGroupId).Value(4213))))) // I ADDED THIS SECTION HERE
                    .Highlight(
                        h => h.PreTags("<mark>").PostTags("</mark>")
                            .Fields(
                                f => f.Field(p => p.FullName),
                                f => f.Field(p => p.CompanyName),
                                f => f.Field(p => p.JobNumber),
                                f => f.Field(p => p.Number),
                                f => f.Field(p => p.Email),
                                f => f.Field(p => p.Description))));
</code>```

I added the extra query to do the bool condition but I does not seem to return the correct output. But I am sure my NEST query is wrong

答:
You want to construct a bool query with a must and filter clause. Using operator overloading on queries, this can be expressed more succinctly

```<code>var query = "query";
var page = 1;
var pageSize = 10;

var searchResponse = client.Search<EmployeeDocument>(x => x
    .Index("indexName")
    .Type("employee")
    .From(page * pageSize)
    .Size(pageSize)
    .Query(q => q
        .MultiMatch(m => m
            .Query(query)
            .Type(TextQueryType.MostFields)
            .MinimumShouldMatch("90%")
            .Fields(f => f
                .Field(ff => ff.FullName, 3)
                .Field(ff => ff.Number, 3)
                .Field(ff => ff.Email)
                .Field(ff => ff.CompanyName, 2)
                .Field(ff => ff.JobNumber)
                .Field(ff => ff.Description)
            )
        ) && +q
        .Term(f => f.CompanyGroupId, 4213)
    )
    .Highlight(h => h
        .PreTags("<mark>")
        .PostTags("</mark>")
        .Fields(
            f => f.Field(p => p.FullName),
            f => f.Field(p => p.CompanyName),
            f => f.Field(p => p.JobNumber),
            f => f.Field(p => p.Number),
            f => f.Field(p => p.Email),
            f => f.Field(p => p.Description)
        )
    )
);
</code>```

which yields the following request

```<code>{
  "from": 10,
  "size": 10,
  "highlight": {
    "pre_tags": [
      "<mark>"
    ],
    "post_tags": [
      "</mark>"
    ],
    "fields": {
      "fullName": {},
      "companyName": {},
      "jobNumber": {},
      "number": {},
      "email": {},
      "description": {}
    }
  },
  "query": {
    "bool": {
      "must": [
        {
          "multi_match": {
            "type": "most_fields",
            "query": "query",
            "minimum_should_match": "90%",
            "fields": [
              "fullName^3",
              "number^3",
              "email",
              "companyName^2",
              "jobNumber",
              "description"
            ]
          }
        }
      ],
      "filter": [
        {
          "term": {
            "companyGroupId": {
              "value": 4213
            }
          }
        }
      ]
    }
  }
}
</code>```

Title: Elasticsearch NEST with Where condition

Body:
I am trying to MultiMatch search with a condition. I know similar questions have been asked in the past but not with using NEST. This is my current search, it works well across the entire document

 var response = await this.client.SearchAsync<EmployeeDocument>(
                               x => x.Index(this.settings.IndexName).Type("employee").From(page * pageSize)
                                   .Size(pageSize).Query(
                                       q => q.MultiMatch(m => m
                                                .Query(query)
                                                .Type(TextQueryType.MostFields)
                                                .MinimumShouldMatch("90%")
                                                .Fields(f => f
                                                    .Field(_ => _.FullName, 3)
                                                    .Field(_ => _.Number, 3)
                                                    .Field(_ => _.Email)
                                                    .Field(_ => _.CompanyName, 2)
                                                    .Field(_ => _.JobNumber)
                                                    .Field(_ => _.Description))))
                    .Highlight(
                        h => h.PreTags("").PostTags("")
                            .Fields(
                                f => f.Field(p => p.FullName),
                                f => f.Field(p => p.CompanyName),
                                f => f.Field(p => p.JobNumber),
                                f => f.Field(p => p.Number),
                                f => f.Field(p => p.Email),
                                f => f.Field(p => p.Description))));

How can I add a condition too only search for a specific field? (CompanyId)

So for instance the above code does an employee search, but it only needs to search inside a specific company.

This is what i have tried

var response = await this.client.SearchAsync<EmployeeDocument>(
                               x => x.Index(this.settings.IndexName).Type("employee").From(page * pageSize)
                                   .Size(pageSize).Query(
                                       q => q.MultiMatch(m => m
                                                .Query(query)
                                                .Type(TextQueryType.MostFields)
                                                .MinimumShouldMatch("90%")
                                                .Fields(f => f
                                                    .Field(_ => _.FullName, 3)
                                                    .Field(_ => _.Number, 3)
                                                    .Field(_ => _.Email)
                                                    .Field(_ => _.CompanyName, 2)
                                                    .Field(_ => _.JobNumber)
                                                    .Field(_ => _.Description))))
                           .Query(_ => _.Bool(b => b.Must(descriptor =>
                                       descriptor.Term(t =>
t.Field(document => document.CompanyGroupId).Value(4213))))) // I ADDED THIS SECTION HERE
                    .Highlight(
                        h => h.PreTags("").PostTags("")
                            .Fields(
                                f => f.Field(p => p.FullName),
                                f => f.Field(p => p.CompanyName),
                                f => f.Field(p => p.JobNumber),
                                f => f.Field(p => p.Number),
                                f => f.Field(p => p.Email),
                                f => f.Field(p => p.Description))));

I added the extra query to do the bool condition but I does not seem to return the correct output. But I am sure my NEST query is wrong

Body:
You want to construct a bool query with a must and filter clause. Using operator overloading on queries, this can be expressed more succinctly

var query = "query";
var page = 1;
var pageSize = 10;

var searchResponse = client.Search<EmployeeDocument>(x => x
    .Index("indexName")
    .Type("employee")
    .From(page * pageSize)
    .Size(pageSize)
    .Query(q => q
        .MultiMatch(m => m
            .Query(query)
            .Type(TextQueryType.MostFields)
            .MinimumShouldMatch("90%")
            .Fields(f => f
                .Field(ff => ff.FullName, 3)
                .Field(ff => ff.Number, 3)
                .Field(ff => ff.Email)
                .Field(ff => ff.CompanyName, 2)
                .Field(ff => ff.JobNumber)
                .Field(ff => ff.Description)
            )
        ) && +q
        .Term(f => f.CompanyGroupId, 4213)
    )
    .Highlight(h => h
        .PreTags("<mark>")
        .PostTags("</mark>")
        .Fields(
            f => f.Field(p => p.FullName),
            f => f.Field(p => p.CompanyName),
            f => f.Field(p => p.JobNumber),
            f => f.Field(p => p.Number),
            f => f.Field(p => p.Email),
            f => f.Field(p => p.Description)
        )
    )
);

which yields the following request

{
  "from": 10,
  "size": 10,
  "highlight": {
    "pre_tags": [
      "<mark>"
    ],
    "post_tags": [
      "</mark>"
    ],
    "fields": {
      "fullName": {},
      "companyName": {},
      "jobNumber": {},
      "number": {},
      "email": {},
      "description": {}
    }
  },
  "query": {
    "bool": {
      "must": [
        {
          "multi_match": {
            "type": "most_fields",
            "query": "query",
            "minimum_should_match": "90%",
            "fields": [
              "fullName^3",
              "number^3",
              "email",
              "companyName^2",
              "jobNumber",
              "description"
            ]
          }
        }
      ],
      "filter": [
        {
          "term": {
            "companyGroupId": {
              "value": 4213
            }
          }
        }
      ]
    }
  }
}


问:
Perform a Select on an ObservableCollection
In the same way I can filter items from my ObservableCollection using the Filter property on the collection's ICollectionView, is it possible to perform a Select on the collection too (In the same way I can with Linq)?

For an example, imagine I have a list of Food objects which doesn't have a Selected property, but I maintain which foods are selected in a separate list. Ideally I would want to perform my Select like so:

view.Select(f => return new { Food = f, Selected = selectedFood.Contains(f)});

I could then bind to the items returned from this Select like so:

```<code><ListBox ItemsSource="{Binding FoodView}">
<ListBox.ItemTemplate>
    <DataTemplate>
        <CheckBox IsChecked="{Binding Selected}">
            <TextBlock Text="{Binding Food.Name}"/>
        </CheckBox>
    </DataTemplate>
</ListBox.ItemTemplate>
</code>```

I'm currently achieving the result I want by maintaining separate ObservableCollections and updating them as needed, but I was wondering if there was a more elegant solution.

Cheers!

答:
I'm not sure if this is what you're looking for but I created an IMultiValueConverter which takes two bindings, the first being the current Data Object and the second being the list of Selected Items:

```<code><ListBox ItemsSource="{Binding FoodItems}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">

                <CheckBox>
                    <CheckBox.IsChecked>
                        <MultiBinding Converter="{StaticResource ListExistsConverter}" Mode="OneWay">
                            <Binding/>
                            <Binding Path="DataContext.SelectedFoodItems" RelativeSource="{RelativeSource AncestorType=UserControl}"/>
                        </MultiBinding>
                    </CheckBox.IsChecked>
                </CheckBox>

                <TextBox Text="{Binding Name}" Width="50" Height="20"/>

            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
</code>```

Converter:

```<code>class ListExistsConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (values == null) return null;
        var item = values[0] as Food;
        var list = values[1] as List<Food>;

        return list.Contains(item);
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
</code>```

The resources used consist of an ObservableCollection<Food> FoodItems and a List<Food> SelectedFoodItems. Perhaps not the most elegant but should be easy to switch between SelectedItem lists as needed.

Body:
In the same way I can filter items from my ObservableCollection using the Filter property on the collection's ICollectionView, is it possible to perform a Select on the collection too (In the same way I can with Linq)?

For an example, imagine I have a list of Food objects which doesn't have a Selected property, but I maintain which foods are selected in a separate list. Ideally I would want to perform my Select like so:

view.Select(f => return new { Food = f, Selected = selectedFood.Contains(f)});

I could then bind to the items returned from this Select like so:

<ListBox ItemsSource="{Binding FoodView}">
<ListBox.ItemTemplate>
    <DataTemplate>
        <CheckBox IsChecked="{Binding Selected}">
            <TextBlock Text="{Binding Food.Name}"/>
        </CheckBox>
    </DataTemplate>
</ListBox.ItemTemplate>

I'm currently achieving the result I want by maintaining separate ObservableCollections and updating them as needed, but I was wondering if there was a more elegant solution.

Cheers!

Body:
I'm not sure if this is what you're looking for but I created an IMultiValueConverter which takes two bindings, the first being the current Data Object and the second being the list of Selected Items:

<ListBox ItemsSource="{Binding FoodItems}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">

                <CheckBox>
                    <CheckBox.IsChecked>
                        <MultiBinding Converter="{StaticResource ListExistsConverter}" Mode="OneWay">
                            <Binding/>
                            <Binding Path="DataContext.SelectedFoodItems" RelativeSource="{RelativeSource AncestorType=UserControl}"/>
                        </MultiBinding>
                    </CheckBox.IsChecked>
                </CheckBox>

                <TextBox Text="{Binding Name}" Width="50" Height="20"/>

            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Converter:

class ListExistsConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (values == null) return null;
        var item = values[0] as Food;
        var list = values[1] as List<Food>;

        return list.Contains(item);
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

The resources used consist of an ObservableCollection<Food> FoodItems and a List<Food> SelectedFoodItems. Perhaps not the most elegant but should be easy to switch between SelectedItem lists as needed.


问:
The sum of prime numbers
I want to calculate the sum of even prime numbers between 101 and 203. But the output for my code is wrong, the output is 52.
Can anyone help me please to get the correct output, in my code I supposed that the even numbers are sure not prime that's why I escaped them. I want to solve it using this method by the prime function. What should I do? Thank you a lot </p>

```<code>#include <stdio.h>
int prime(int n)
{
    int i=2;
    int n2;
    n2 = n/2;
    while (1<=n2) {
        if (n%i == 0) {
            return 0;
        } else {
            return 1;
        }
        i++;
    }
}

int main()
{
    int sum=0;
    for (int i=101; i<=203; i+=2) {
        if (prime(i)==1) {
        }
        sum+=1;
    }
    printf("%d \n",sum);
    return 0;
}
</code>```

答:
THERE ARE NO SUCH THING AS EVEN PRIME NUMBERS... YOU WILL ALWAYS GET 0.

But to really answer your question...

You really don't need to put i++ in your first function. Secondly, try this

```<code>for (int i=101; i<=203; i++)
{
   i++
   if (prime(i)==1)
   {
     sum+=i;
   }
}
</code>```

This should work. You don't need to increment sum by 1, you need to add i each time there is a prime number. The reason why you get 52 is because you do sum+=1, which adds 1 to sum 52 times in the for loop.

Title: The sum of prime numbers

Body:
I want to calculate the sum of even prime numbers between 101 and 203. But the output for my code is wrong, the output is 52.
Can anyone help me please to get the correct output, in my code I supposed that the even numbers are sure not prime that's why I escaped them. I want to solve it using this method by the prime function. What should I do? Thank you a lot

#include <stdio.h>
int prime(int n)
{
    int i=2;
    int n2;
    n2 = n/2;
    while (1<=n2) {
        if (n%i == 0) {
            return 0;
        } else {
            return 1;
        }
        i++;
    }
}

int main()
{
    int sum=0;
    for (int i=101; i<=203; i+=2) {
        if (prime(i)==1) {
        }
        sum+=1;
    }
    printf("%d \n",sum);
    return 0;
}

Body:
THERE ARE NO SUCH THING AS EVEN PRIME NUMBERS... YOU WILL ALWAYS GET 0.

But to really answer your question...

You really don't need to put i++ in your first function. Secondly, try this

for (int i=101; i<=203; i++)
{
   i++
   if (prime(i)==1)
   {
     sum+=i;
   }
}

This should work. You don't need to increment sum by 1, you need to add i each time there is a prime number. The reason why you get 52 is because you do sum+=1, which adds 1 to sum 52 times in the for loop.


问:
Ternary operator is not working scala
I'm trying to make a ternary operator in scala but actually it seems that the '?' character cannot be resolved

here is the completed method

```<code>object Credit {
  def getMaximumWeek(orderId: Int, locale: String): Int = {
    val orderCompletedHistoryCount = Order.getOrderCompletedHistoryCount(orderId, locale);
   orderCompletedHistoryCount == 0 ? 0: Order.getMaximumAllowedWeeks(orderId, locale)
  }
}
</code>```

referenced to this link
,I'm getting an error connot resolve symbol '?' even both method are returning integers

答:
You can use Scalaz for that. The only difference is it requires | sign instead of : sign.

```<code>import scalaz.Scalaz._

false ? "Yes" | "No" // returns No
</code>```

It's not only for booleans, you can try it with Option objects as well:

```<code>None ? "Defined" | "Empty" // returns Empty
</code>```

You should add the following line to build.sbt in order to use it:

```<code>libraryDependencies += "org.scalaz" %% "scalaz-core" % "7.2.16"
</code>```

Title: Ternary operator is not working scala

Body:
I'm trying to make a ternary operator in scala but actually it seems that the '?' character cannot be resolved

here is the completed method

object Credit {
  def getMaximumWeek(orderId: Int, locale: String): Int = {
    val orderCompletedHistoryCount = Order.getOrderCompletedHistoryCount(orderId, locale);
   orderCompletedHistoryCount == 0 ? 0: Order.getMaximumAllowedWeeks(orderId, locale)
  }
}

referenced to this link
,I'm getting an error connot resolve symbol '?' even both method are returning integers

Body:
You can use Scalaz for that. The only difference is it requires | sign instead of : sign.

import scalaz.Scalaz._

false ? "Yes" | "No" // returns No

It's not only for booleans, you can try it with Option objects as well:

None ? "Defined" | "Empty" // returns Empty

You should add the following line to build.sbt in order to use it:

libraryDependencies += "org.scalaz" %% "scalaz-core" % "7.2.16"


问:
How to see where an item is used on Sharepoint Site?
I have many files (images etc.) in different libraries and I'm not sure which of them I am using / are linked within my Sharepoint site.

Like for example I imagine something like this:

```<code>example.jpg  - used in: /SitePages/page1.html, /SitePages/page2.html
example.docx - used in: /MyList/
example2.jpg - used in: -
example3.jpg - used in: -
</code>```

I know that for example hyperlinks change automatically when renaming a page. So there seems to be information about the links within the site...

Is there something similar to see if an item is linked/used on the site like in the example above?

Thanks.

答: There isn't anything in the api that will automatically tell you where a file is being referenced. Something like that would require code that checks for the item that you're looking for which would be easier in a list but a challenge if it appears in the markup or a content editor webpart.</p>

Body:
I have many files (images etc.) in different libraries and I'm not sure which of them I am using / are linked within my Sharepoint site.

Like for example I imagine something like this:

example.jpg  - used in: /SitePages/page1.html, /SitePages/page2.html
example.docx - used in: /MyList/
example2.jpg - used in: -
example3.jpg - used in: -

I know that for example hyperlinks change automatically when renaming a page. So there seems to be information about the links within the site...

Is there something similar to see if an item is linked/used on the site like in the example above?

Thanks.


答:
ArrayList.subList method returns a sublist of your list without modifying your existing list.

So you need to do;

```<code>list = list.subList(list.size()-1, list.size());
</code>```

Title: How can I just get the last record in the java.util.List using subList() or any other method?

Body:
ArrayList.subList method returns a sublist of your list without modifying your existing list.

So you need to do;

list = list.subList(list.size()-1, list.size());


问:
How Can make this JSX compact?
```<code>{
  this.state.isLoadingInputDropDown &&
  <option value="-1" disabled >Loading...</option >
}

{/* TODO : was not able to combine below statements */}
{
  !this.state.isLoadingInputDropDown
  && <option value="-1" >--Select a Accessorial Charge first --</option>
}
{
  !this.state.isLoadingInputDropDown
  && this.state.allInputs.length > 0
  && this.state.allInputs.map(
    (input) => (<option value={input.id} key={input.id}>{input.name}</option>)
  )
}
</code>```

trying to make this JSX one-liner or something compact.
I tried every possible (which I can think of) structure

答:
Maybe you declare the content before returning jsx.</p>

```<code>const dropdown = this.state.isLoadingInputDropDown ? <option value="-1" disabled >Loading...</option > : <option value="-1" >--Select a Accessorial Charge first --</option>;

const otherOptions = this.state.isLoadingInputDropDown || !(this.state.allInputs.length > 0) ? null : this.state.allInputs.map(
    (input) => (<option value={input.id} key={input.id}>{input.name}</option>)
);

return (
    <select>
        { dropdown }
        { otherOptions }
    </select>
);
</code>```

Title: How Can make this JSX compact?

Body:
{
  this.state.isLoadingInputDropDown &&
  <option value="-1" disabled >Loading...</option >
}

{/* TODO : was not able to combine below statements */}
{
  !this.state.isLoadingInputDropDown
  && <option value="-1" >--Select a Accessorial Charge first --</option>
}
{
  !this.state.isLoadingInputDropDown
  && this.state.allInputs.length > 0
  && this.state.allInputs.map(
    (input) => (<option value={input.id} key={input.id}>{input.name}</option>)
  )
}

trying to make this JSX one-liner or something compact.
I tried every possible (which I can think of) structure

Body:
Maybe you declare the content before returning jsx.

const dropdown = this.state.isLoadingInputDropDown ? <option value="-1" disabled >Loading...</option > : <option value="-1" >--Select a Accessorial Charge first --</option>;

const otherOptions = this.state.isLoadingInputDropDown || !(this.state.allInputs.length > 0) ? null : this.state.allInputs.map(
    (input) => (<option value={input.id} key={input.id}>{input.name}</option>)
);

return (
    <select>
        { dropdown }
        { otherOptions }
    </select>
);


问:
Can some share how to write vim map
new to vim, recently came across mapping keyboards issues, what get on google and stackoverflow is only something like this map <C-\> :tab split<CR>:exec("tag ".expand("<cword>"))<CR> and map  :vsp <CR>:exec("tag ".expand("<cword>"))<CR>, then I searched Vim documentation: map http://vimdoc.sourceforge.net/htmldoc/intro.html#<>, but what it also does not explains the syntax, the meanning of the symbols, can someone suggest some reference materials for this? Thanks very much!

答:
A mapping like the ones you mentioned has three parts:

the type of mapping (map/nmap/imap/vmap/... and the corresponding noremap versions). This determines in what modes the mapping is active. map means normal mode, visual mode and operator-pending mode. When using noremap/nnoremap/... the mapping is made with respect to Vims standard keybindings, otherwise the mappings can themselves call mappings.

The key(s) to bind. This can be a normal key, a control character like <C-\>, or a sequence of keys.

a key sequence to map to.

In your first case, you map the key <C-\> (control-backspace) to :tab split<CR>:exec("tag ".expand("<cword>"))<CR> in normal, visual, and operator-pending mode.

Title: Can some share how to write vim map


答:
There are several problems in your code.

In the for loop:

```<code>    for (int i=101; i<=203; i+=2) {
    if (prime(i)==1){
    }sum+=1;
</code>```

The statement sum+=1 should be inside the if block.

Also, you are adding 1 to sum. Instead, you should add i as you want the sum of prime numbers as result:

```<code>sum+=i;
</code>```

The function prime() should return 1 only when while loop checks condition n%i == 0 for all the values of i and for none of the value of i it is true. So, you need to move return 1 to out of the while loop.

Also, in the while loop in prime() this is incorrect:

```<code>while (1<=n2) {
</code>```

It should be:

```<code>while (i<=n2) {
</code>```

Collectively, it should be:

```<code>#include <stdio.h>
int prime(int n)
{
    int i=2;
    int n2;
    n2 = n/2;
    while (i<=n2) {
        if (n%i == 0) {
            return 0;
        }
        i++;
   }
   return 1;
}

int main()
{
    int sum=0;
    for (int i=101; i<=203; i+=2) {
        if (prime(i)==1){
            sum+=i;
        }
    }

    printf("%d \n",sum);
    return 0;
}
</code>```

Title: The sum of prime numbers

Body:
There are several problems in your code.

In the for loop:

    for (int i=101; i<=203; i+=2) {
    if (prime(i)==1){
    }sum+=1;

The statement sum+=1 should be inside the if block.

Also, you are adding 1 to sum. Instead, you should add i as you want the sum of prime numbers as result:

sum+=i;

The function prime() should return 1 only when while loop checks condition n%i == 0 for all the values of i and for none of the value of i it is true. So, you need to move return 1 to out of the while loop.

Also, in the while loop in prime() this is incorrect:

while (1<=n2) {

It should be:

while (i<=n2) {

Collectively, it should be:

#include <stdio.h>
int prime(int n)
{
    int i=2;
    int n2;
    n2 = n/2;
    while (i<=n2) {
        if (n%i == 0) {
            return 0;
        }
        i++;
   }
   return 1;
}

int main()
{
    int sum=0;
    for (int i=101; i<=203; i+=2) {
        if (prime(i)==1){
            sum+=i;
        }
    }

    printf("%d \n",sum);
    return 0;
}


问:
How do I determine whether a randomly generated number is a multiple of 150?
I'm creating a basic mystery box program using randomly generated numbers to determine what rarity item they get. However, if the number they get is a multiple of 150, I want them to get a particular item. I'm not sure how to determine whether the random number is a multiple of 150 though.</p>

```<code>else if (num is in 150 times tables)
{
    code...
}
</code>```

答:
Use the Modulo Operator '%' and check the remainder.

```<code>if (num % 150 == 0)
{
    // It is divisable, do something
}
else
{
    // Not divisable, do something else
}
</code>```

The modulo operator basically says "How many times can I divide the first number by the second, and what do I have left over?". In this example if num divided by 150 has 0 left over then it fits perfectly and you know it's a multiple.

Body:
I'm creating a basic mystery box program using randomly generated numbers to determine what rarity item they get. However, if the number they get is a multiple of 150, I want them to get a particular item. I'm not sure how to determine whether the random number is a multiple of 150 though.

else if (num is in 150 times tables)
{
    code...
}

Body:
Use the Modulo Operator '%' and check the remainder.

if (num % 150 == 0)
{
    // It is divisable, do something
}
else
{
    // Not divisable, do something else
}

The modulo operator basically says "How many times can I divide the first number by the second, and what do I have left over?". In this example if num divided by 150 has 0 left over then it fits perfectly and you know it's a multiple.


问:
Protocols with where clause don't work when referring them as protocols
Let's say I have the following infrastructure:

```<code>protocol Naming {
    var printer: Printer { get }
    var name: String { get }
}

extension Naming {
    var name: String { return "\(type(of: self))" }

    func printName() {
        printer.print(name)
    }
}

protocol Printer {
    func print(_: String)
}
</code>```

I have a protocol that exposes a name and a printer, that is used to print the name.

Now, trying to follow MVC, I add these:

```<code>protocol ModelInjectable {
    associatedtype Model
    var model: Model { get }
}

extension Naming where Self: ModelInjectable, Self.Model: Naming {
    var printer: Printer { return model.printer }
    var name: String { return model.name }
}
</code>```

which allows view controllers to specify they allow a model, and in such cases allow them to conform to Naming by simply forwarding the protocol conformance to the model.

This is a simple VC:

```<code>class MyViewController: UIViewController, ModelInjectable, Naming {
    let model: MyModel

    required init(model: MyModel) {
        self.model = model
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError()
    }
}
</code>```

The problem arise when I try to use a protocol for the model:

```<code>struct MyModel: Naming {
    let printer: Printer
}
</code>```

works as expected, however

```<code>protocol MyModel: Naming {
}
</code>```

gives compile errors:

error: type 'MyViewController' does not conform to protocol 'Naming'
  class MyViewController: NSViewController, ModelInjectable, Naming {

note: candidate has non-matching type 'Printer'
      var printer: Printer { return model.printer }

note: protocol requires property 'printer' with type 'Printer'; do you want to add a stub?
      var printer: Printer { get }

From what I can tell, the extension Naming where Self: ModelInjectable, Self.Model: Naming extension is used by the compiler only when using a concrete type. Using a protocol reference doesn't do the trick. Is this a limitation of the compiler, or am I wrongly using the feature?

答: Unlike e.g. Objective-C protocols, a Swift protocol doesn't conform to itself. As a result, protocol MyModel: Naming doesn’t satisfy the Self.Model: Naming constraint of your protocol extension.

ContentLicense: CC BY-SA 4.0

Body:
Let's say I have the following infrastructure:

protocol Naming {
    var printer: Printer { get }
    var name: String { get }
}

extension Naming {
    var name: String { return "\(type(of: self))" }

    func printName() {
        printer.print(name)
    }
}

protocol Printer {
    func print(_: String)
}

I have a protocol that exposes a name and a printer, that is used to print the name.

Now, trying to follow MVC, I add these:

protocol ModelInjectable {
    associatedtype Model
    var model: Model { get }
}

extension Naming where Self: ModelInjectable, Self.Model: Naming {
    var printer: Printer { return model.printer }
    var name: String { return model.name }
}

which allows view controllers to specify they allow a model, and in such cases allow them to conform to Naming by simply forwarding the protocol conformance to the model.

This is a simple VC:

class MyViewController: UIViewController, ModelInjectable, Naming {
    let model: MyModel

    required init(model: MyModel) {
        self.model = model
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError()
    }
}

The problem arise when I try to use a protocol for the model:

struct MyModel: Naming {
    let printer: Printer
}

works as expected, however

protocol MyModel: Naming {
}

gives compile errors:

error: type 'MyViewController' does not conform to protocol 'Naming'
  class MyViewController: NSViewController, ModelInjectable, Naming {

note: candidate has non-matching type 'Printer'
      var printer: Printer { return model.printer }

note: protocol requires property 'printer' with type 'Printer'; do you want to add a stub?
      var printer: Printer { get }

From what I can tell, the extension Naming where Self: ModelInjectable, Self.Model: Naming extension is used by the compiler only when using a concrete type. Using a protocol reference doesn't do the trick. Is this a limitation of the compiler, or am I wrongly using the feature?


问:
PDFsharp MigraDoc add runtime generated bitmap to table cell
I wanted to use PDFsharp and MigraDoc to generate PDFs. As far as now it all works perfectly.

Now I have come up with an idea to create a bitmap during runtime and add it to one of my table cells.

I've read that it is possible to add bitmaps from resource so, without having them on the harddrive.

See: http://www.pdfsharp.net/wiki/MigraDoc_FilelessImages.ashx

This is my try to adapt it to my small project:

Code for creating the Bitmap:

```<code>Bitmap GreenDot = new Bitmap(32,32);
Graphics GreenDotGraphics = Graphics.FromImage(GreenDot);
GreenDotGraphics.FillEllipse(Brushes.Green,0,0,32,32);

//The next step will be converting the Bitmap to an byte[]

var byteGreenDot = ImageToByte(GreenDot);

//Now converting it to string as seen in the WikiPage

string stringGreenDot = Convert.ToBase64String(byteGreenDot);
string FinalGreenDot = "base64:"+ stringGreenDot;

//Now creating a table
.
.
.
cell = MyRow.Cell[1];
cell.AddImage(FinalGreenDot);
.
.
.
</code>```

Code for converting bitmap to byte[]

```<code>public static byte[] ImageToByte(System.Drawing.Image img)
{
    using(var ms = new MemoryStream())
    {
        img.Save(ms,System.Drawing.Imaging.ImageFormat.Bmp);
        return ms.ToArray();
    }
}
</code>```

As I run the code I'll get a warning saying "warning: Image 'base64:Qk02E[...]==' not found." (the base64 string was truncated for this post).

I guess that I don't convert it correctly to byte[].

Can someone get me on the right track?

答:
Note that you are using a feature that was introduced with version 1.50.

When using version 1.32 or earlier, you get the warning you mention.

Your code works as expected when using version 1.50 beta 2 or later.

Body:
I wanted to use PDFsharp and MigraDoc to generate PDFs. As far as now it all works perfectly.

Now I have come up with an idea to create a bitmap during runtime and add it to one of my table cells.

I've read that it is possible to add bitmaps from resource so, without having them on the harddrive.

See: http://www.pdfsharp.net/wiki/MigraDoc_FilelessImages.ashx

This is my try to adapt it to my small project:

Code for creating the Bitmap:

Bitmap GreenDot = new Bitmap(32,32);
Graphics GreenDotGraphics = Graphics.FromImage(GreenDot);
GreenDotGraphics.FillEllipse(Brushes.Green,0,0,32,32);

//The next step will be converting the Bitmap to an byte[]

var byteGreenDot = ImageToByte(GreenDot);

//Now converting it to string as seen in the WikiPage

string stringGreenDot = Convert.ToBase64String(byteGreenDot);
string FinalGreenDot = "base64:"+ stringGreenDot;

//Now creating a table
.
.
.
cell = MyRow.Cell[1];
cell.AddImage(FinalGreenDot);
.
.
.

Code for converting bitmap to byte[]

public static byte[] ImageToByte(System.Drawing.Image img)
{
    using(var ms = new MemoryStream())
    {
        img.Save(ms,System.Drawing.Imaging.ImageFormat.Bmp);
        return ms.ToArray();
    }
}

As I run the code I'll get a warning saying "warning: Image 'base64:Qk02E[...]==' not found." (the base64 string was truncated for this post).

I guess that I don't convert it correctly to byte[].

Can someone get me on the right track?


问:
Maven2 Eclipse integration
There seem to be two rival  Eclipse plugins for integrating with Maven:
m2Eclipse
and
q4e.

Has anyone recently evaluated or used these plugins?

Why would I choose one or the other?

答: There is only one point where q4e is actually better: dependency viewer. You could see the dependency tree, manage your dependencies visually and even see them in a graph. But, m2eclipse works in a better way, specially because you can create you own build commands (in the run menu). q4e comes with some predefined commands and I can't find where to define a new one. In other words, m2eclipse is more friendly to the maven way.</p>

OwnerDisplayName: David

ContentLicense: CC BY-SA 2.5

Title: Maven2 Eclipse integration

OwnerDisplayName: marcospereira


问:
Targeting ARM architecture with .NET compiler
When you compile windows application in .NET you can set "Platform Target" to be x86 or x64. This would optimize your code to a specific architecture of the processor and allow to escape IL.
Does anyone know if there's something that would allow to achieve the same result for Windows Mobile application? I'm only interested in running my application on ARM architecture.</p>

答:
x86 or x64 doesn't optimize the IL - that's the job of the JITter that runs on the deployed machine. x86 or x64 just marks a bitness flag.

Of course, in the desktop framework you can NGEN your MSIL to a particular CPU - but IIRC, the lack of a native image will just revert to JIT compilation. Besides that, though, I don't think NGEN is available for .NET CF anyway.

I'm not sure why you'd need to restrict to ARM processors, but a P/Invoke to GetSystemInfo will return a SYSTEM_INFO structure with the processor type in it. That could prevent your app continuing on !ARM, but not really from running.

Edit: Re-reading this question, I noticed that besides he C# and .NET tag, there's really no indication that you only want a managed solution. If you're willing to go unmanaged, you can obviously just compile down to ARM.

OwnerDisplayName: Ilya Volodin

OwnerDisplayName: Mark Brackett

LastEditorDisplayName: Mark Brackett


问:
C++ - struct errors
Following an example at: http://www.learncpp.com/cpp-tutorial/47-structs/ relating to structs, and when I tried to compile this program:

```<code>#include <iostream>
void PrintInformation(Employee sEmployee)
{
std::cout<<"ID: "<<sEmployee.nID<<std::endl;
std::cout<<"Age: "<<sEmployee.nAge<<std::endl;
std::cout<<"Wage: "<<sEmployee.fWage<<std::endl;
}

struct Employee {int nID;int nAge;float fWage;};

int main()
{
Employee abc;
abc.nID=123;
abc.nAge=27;
abc.fWage=400;
// print abc's information
PrintInformation(abc);
return 0;
}
</code>```

I get the following:

Why is that?

Thanks.

答:
You need to declare the struct before the function that attempts to use it.

C (and by extension, C++) were designed for "single-pass" compilation.  Therefore, everything must be available to the compiler by the time it's required.

Title: C++ - struct errors

Body:
Following an example at: http://www.learncpp.com/cpp-tutorial/47-structs/ relating to structs, and when I tried to compile this program:

#include <iostream>
void PrintInformation(Employee sEmployee)
{
std::cout<<"ID: "<<sEmployee.nID<<std::endl;
std::cout<<"Age: "<<sEmployee.nAge<<std::endl;
std::cout<<"Wage: "<<sEmployee.fWage<<std::endl;
}

struct Employee {int nID;int nAge;float fWage;};

int main()
{
Employee abc;
abc.nID=123;
abc.nAge=27;
abc.fWage=400;
// print abc's information
PrintInformation(abc);
return 0;
}

I get the following:

Why is that?

Thanks.


问:
Transpose CSV to new format (C#)
I have csv file:

I need to convert it to below format:

I did only this:

```<code>    StreamReader srd = new StreamReader(path: path);
    int rowCount = 0;

    string[] oStreamDataValues = null;
    string[] headerNames = null;

    while (!srd.EndOfStream)
    {
        string oStreamRowData = srd.ReadLine().Trim();
        oStreamDataValues = oStreamRowData.Split(';');

        //headers
        if (rowCount == 0)
        {
            headerNames = oStreamDataValues;
            rowCount++;//second row go to "else"
        }
        //create new csv
        else
        {

        }
        //rowCount++;
    }
    //Console.WriteLine("number of lines " + rowCount);
    srd.Dispose();
</code>```

Can you please help me with transpose to new format?

答:
You can try this for you else clause:

```<code>            else
            {
                string leftColumn = oStreamDataValues[0];

                for (int i = 1; i < oStreamDataValues.Length; i++)
                {
                    string middleColumn = headerNames[i];
                    string rightColumn = oStreamDataValues[i];
                    string newRow = string.Join(";", leftColumn, middleColumn, rightColumn, Environment.NewLine);

                    File.AppendAllText(pathToNewFile, newRow);
                }
            }
</code>```

EDIT: or use Linq:

var result = headerNames.Skip(1).Zip(oStreamDataValues.Skip(1), (a, b) => String.Join(";", oStreamDataValues[0], a, b));

Title: Transpose CSV to new format (C#)

Body:
I have csv file:

I need to convert it to below format:

I did only this:

    StreamReader srd = new StreamReader(path: path);
    int rowCount = 0;

    string[] oStreamDataValues = null;
    string[] headerNames = null;

    while (!srd.EndOfStream)
    {
        string oStreamRowData = srd.ReadLine().Trim();
        oStreamDataValues = oStreamRowData.Split(';');

        //headers
        if (rowCount == 0)
        {
            headerNames = oStreamDataValues;
            rowCount++;//second row go to "else"
        }
        //create new csv
        else
        {

        }
        //rowCount++;
    }
    //Console.WriteLine("number of lines " + rowCount);
    srd.Dispose();

Can you please help me with transpose to new format?

Body:
You can try this for you else clause:

            else
            {
                string leftColumn = oStreamDataValues[0];

                for (int i = 1; i < oStreamDataValues.Length; i++)
                {
                    string middleColumn = headerNames[i];
                    string rightColumn = oStreamDataValues[i];
                    string newRow = string.Join(";", leftColumn, middleColumn, rightColumn, Environment.NewLine);

                    File.AppendAllText(pathToNewFile, newRow);
                }
            }

EDIT: or use Linq:

var result = headerNames.Skip(1).Zip(oStreamDataValues.Skip(1), (a, b) => String.Join(";", oStreamDataValues[0], a, b));


问:
How to select multiple event date in MaterialCalenderView
I am using MaterialCalendarView library, I want to select events dates problematically (no to be select by user in run time) which will  be multiple, After reading the documentation i saw four cases.

SELECTION_MODE_NONE

SELECTION_MODE_SINGLE

SELECTION_MODE_RANGE

SELECTION_MODE_MULTIPLE

I used SELECTION_MODE_NONE as i don't want user to select date.
I tried this but it doesn't show  me selected days which i passed.

```<code>private MaterialCalendarView materialCalendarView;
materialCalendarView = view.findViewById(R.id.newCal);
 Calendar calendar = Calendar.getInstance();
    calendar.set(2017, 12, 1);
    calendar.set(2017, 12, 7);
    calendar.set(2017, 12, 8);
    calendar.set(2017, 12, 9);
    calendar.set(2017, 12, 10);

    materialCalendarView.addDecorator(new CurrentDayDecatator(getActivity()));
    materialCalendarView.setDateSelected(calendar, true);
    materialCalendarView.setSelectionMode(MaterialCalendarView.SELECTION_MODE_NONE);
</code>```

How to implement that? where i am going wrong?

UPDATE:
After taking the login of Umar and Manny i updated my code like this:

```<code>materialCalendarView.setSelectionMode(MaterialCalendarView.SELECTION_MODE_NONE);

    Calendar calendar = Calendar.getInstance();
    calendar.set(2017, 12, 14);

    Calendar calendar2 = Calendar.getInstance();
    calendar.set(2017, 12, 15);

    Calendar calendar3 = Calendar.getInstance();
    calendar.set(2017, 12, 16);

    Calendar calendar4 = Calendar.getInstance();
    calendar.set(2017, 12, 17);

    materialCalendarView.addDecorator(new CurrentDayDecatator(getActivity()));
    materialCalendarView.setDateSelected(calendar, true);
    materialCalendarView.setDateSelected(calendar2, true);
    materialCalendarView.setDateSelected(calendar3, true);
    materialCalendarView.setDateSelected(calendar4, true);
</code>```

So, now i get only the last date selected which is calendar4. But still i am unable to select multiple dates. and by default materialCalendarView selects today's date.

答:
you are setting date on same instance of Calender object. You need multiple calender object and then set those objects to the materialCalenderView

```<code>Calendar calendar = Calendar.getInstance();
calendar.set(2017, 12, 1);

Calendar calendar2 = Calendar.getInstance();
    calendar2.set(2017, 12, 7);

materialCalendarView.setDateSelected(calendar, true);
materialCalendarView.setDateSelected(calendar2, true);
</code>```

Body:
I am using MaterialCalendarView library, I want to select events dates problematically (no to be select by user in run time) which will  be multiple, After reading the documentation i saw four cases.

SELECTION_MODE_NONE

SELECTION_MODE_SINGLE

SELECTION_MODE_RANGE

SELECTION_MODE_MULTIPLE

I used SELECTION_MODE_NONE as i don't want user to select date.
I tried this but it doesn't show  me selected days which i passed.

private MaterialCalendarView materialCalendarView;
materialCalendarView = view.findViewById(R.id.newCal);
 Calendar calendar = Calendar.getInstance();
    calendar.set(2017, 12, 1);
    calendar.set(2017, 12, 7);
    calendar.set(2017, 12, 8);
    calendar.set(2017, 12, 9);
    calendar.set(2017, 12, 10);

    materialCalendarView.addDecorator(new CurrentDayDecatator(getActivity()));
    materialCalendarView.setDateSelected(calendar, true);
    materialCalendarView.setSelectionMode(MaterialCalendarView.SELECTION_MODE_NONE);

How to implement that? where i am going wrong?

UPDATE:
After taking the login of Umar and Manny i updated my code like this:

materialCalendarView.setSelectionMode(MaterialCalendarView.SELECTION_MODE_NONE);

    Calendar calendar = Calendar.getInstance();
    calendar.set(2017, 12, 14);

    Calendar calendar2 = Calendar.getInstance();
    calendar.set(2017, 12, 15);

    Calendar calendar3 = Calendar.getInstance();
    calendar.set(2017, 12, 16);

    Calendar calendar4 = Calendar.getInstance();
    calendar.set(2017, 12, 17);

    materialCalendarView.addDecorator(new CurrentDayDecatator(getActivity()));
    materialCalendarView.setDateSelected(calendar, true);
    materialCalendarView.setDateSelected(calendar2, true);
    materialCalendarView.setDateSelected(calendar3, true);
    materialCalendarView.setDateSelected(calendar4, true);

So, now i get only the last date selected which is calendar4. But still i am unable to select multiple dates. and by default materialCalendarView selects today's date.

Body:
you are setting date on same instance of Calender object. You need multiple calender object and then set those objects to the materialCalenderView

Calendar calendar = Calendar.getInstance();
calendar.set(2017, 12, 1);

Calendar calendar2 = Calendar.getInstance();
    calendar2.set(2017, 12, 7);

materialCalendarView.setDateSelected(calendar, true);
materialCalendarView.setDateSelected(calendar2, true);


问:
find merged user suggestion using list comprehension
 i need to show merged suggestion

 input format

```<code>m = {'user1': {'c1': ['p1', 'e1'],
  'c2': ['p2', 'e2'],
  'c3': ['p2', 'e3'],
  'c4': ['e3', 'p4'],
  'c5': ['e2', 'p5'],
  'c6': ['p3', 'e4', 'p6'],
  'c7': ['e4'],
  'c8': ['p6', 'e5']}}
</code>```

 i need to show  merged suggestion for this user on the basis of p1,p2... and e1,e2 ... on dict values , there could be multiple users

 output format

```<code>user1_merge_suggestions : [ [c1], [c2, c3, c4, c5], [c6, c7, c8] ]
</code>```

 explanation

for key c1 its values are p1 and e1 which is not present in any other key-value pair so c1 is alone appended to the list , for key c2 value p2 is found in key c3 value and value of key c3 which is e3 found in c4 and value of key c5 which is p2 is found in key c2 so they are related  so [c2,c3,c4,c5] and so on

答:
This should work:</p>

```<code>from collections import defaultdict

# first aggregate all users
merged = defaultdict(set)
for u in m:
    for k,v in m[u].iteritems():
        merged[(k,)].update(set(v))

# then merged keys as required as long as possible
cont = True
while cont:
    cont = False
    keys = merged.keys()
    L = len(keys)
    for i in range(L):
        ki = keys[i]
        for j in range(i+1,L):
            kj = keys[j]
            if merged[ki] & merged[kj]:
                merged[ki+kj] = merged[ki].union(merged[kj])
                del merged[ki]
                del merged[kj]
                cont = True

# finally remove remaining artifacts
merged = [k for k,v in merged.iteritems() if v]
</code>```

Body:
 i need to show merged suggestion

 input format

m = {'user1': {'c1': ['p1', 'e1'],
  'c2': ['p2', 'e2'],
  'c3': ['p2', 'e3'],
  'c4': ['e3', 'p4'],
  'c5': ['e2', 'p5'],
  'c6': ['p3', 'e4', 'p6'],
  'c7': ['e4'],
  'c8': ['p6', 'e5']}}

 i need to show  merged suggestion for this user on the basis of p1,p2... and e1,e2 ... on dict values , there could be multiple users

 output format

user1_merge_suggestions : [ [c1], [c2, c3, c4, c5], [c6, c7, c8] ]

 explanation

for key c1 its values are p1 and e1 which is not present in any other key-value pair so c1 is alone appended to the list , for key c2 value p2 is found in key c3 value and value of key c3 which is e3 found in c4 and value of key c5 which is p2 is found in key c2 so they are related  so [c2,c3,c4,c5] and so on

Body:
This should work:

from collections import defaultdict

# first aggregate all users
merged = defaultdict(set)
for u in m:
    for k,v in m[u].iteritems():
        merged[(k,)].update(set(v))

# then merged keys as required as long as possible
cont = True
while cont:
    cont = False
    keys = merged.keys()
    L = len(keys)
    for i in range(L):
        ki = keys[i]
        for j in range(i+1,L):
            kj = keys[j]
            if merged[ki] & merged[kj]:
                merged[ki+kj] = merged[ki].union(merged[kj])
                del merged[ki]
                del merged[kj]
                cont = True

# finally remove remaining artifacts
merged = [k for k,v in merged.iteritems() if v]


问:
open excel file python so it is visible
I'm trying to open a excel so it is displayed visibly.

I am using:

```<code>import subprocess
subprocess.check_call(['open', '-a', 'C:\\1\\2\\22.xlsx'])
</code>```

https://ibb.co/eOhY4b

Sorry if this is obvious but I keep getting this error message.  AS far as I can tell the file is located there.

```<code>FileNotFoundError: [WinError 2] The system cannot find the file specified
</code>```

答:
it didn't work just because open isn't a known command name (this is an action in the windows registry, nothing more). The subprocess error message:

```<code>FileNotFoundError: [WinError 2] The system cannot find the file specified
</code>```

has only one meaning: the executable could not be found. It doesn't (and cannot) check the parameters to see if they're valid filepaths so don't look in that direction (and yes, it's a pity that the message is generic and doesn't say exactly which file could not be found, that a known windows issue)

That would work:

```<code>import os
os.startfile(r'C:\1\2\22.xlsx')
</code>```

os.startfile tries to perform the same thing as when you're clicking on the file in windows explorer.

This solution has the advantage not to depend on win32com.

Aside/discussed in comments: os.path.join('C:', '1', '2', '22.xlsx') doesn't work because it doesn't add the backslash after the drive colon (and for a "good" reason (well a good reason windows-wise): Python os.path.join on Windows).

```<code>>>> os.path.join('C:', '1', '2', '22.xlsx')
'C:1\\2\\22.xlsx'  # wrong
</code>```

a clean way to do it:

```<code>>>> os.path.join('C:', os.sep,'1' , '2', '22.xlsx')
'C:\\1\\2\\22.xlsx'
</code>```

Title: open excel file python so it is visible

Body:
I'm trying to open a excel so it is displayed visibly.

I am using:

import subprocess
subprocess.check_call(['open', '-a', 'C:\\1\\2\\22.xlsx'])

https://ibb.co/eOhY4b

Sorry if this is obvious but I keep getting this error message.  AS far as I can tell the file is located there.

FileNotFoundError: [WinError 2] The system cannot find the file specified

Body:
it didn't work just because open isn't a known command name (this is an action in the windows registry, nothing more). The subprocess error message:

FileNotFoundError: [WinError 2] The system cannot find the file specified

has only one meaning: the executable could not be found. It doesn't (and cannot) check the parameters to see if they're valid filepaths so don't look in that direction (and yes, it's a pity that the message is generic and doesn't say exactly which file could not be found, that a known windows issue)

That would work:

import os
os.startfile(r'C:\1\2\22.xlsx')

os.startfile tries to perform the same thing as when you're clicking on the file in windows explorer.

This solution has the advantage not to depend on win32com.

Aside/discussed in comments: os.path.join('C:', '1', '2', '22.xlsx') doesn't work because it doesn't add the backslash after the drive colon (and for a "good" reason (well a good reason windows-wise): Python os.path.join on Windows).

>>> os.path.join('C:', '1', '2', '22.xlsx')
'C:1\\2\\22.xlsx'  # wrong

a clean way to do it:

>>> os.path.join('C:', os.sep,'1' , '2', '22.xlsx')
'C:\\1\\2\\22.xlsx'


问:
Getting an error while starting Apache Kylin. Using Hadoop-2.6.0, Hbase-0.98, hive-0.14 Versions

java.io.FileNotFoundException:
  /usr/local/hadoop/hadoop-2.6.0/contrib/capacity-scheduler/*.jar (No
  such file or directory)

Thanks in advance

答:
Minimal Hadoop Versions required for Apache kylin installation

```<code>Hadoop: 2.7+
Hive: 0.13 - 1.2.1+
HBase: 0.98 - 0.99, 1.1+
JDK: 1.7+
</code>```

check with this official link
http://kylin.apache.org/docs21/install/hadoop_env.html

Body:
Minimal Hadoop Versions required for Apache kylin installation

Hadoop: 2.7+
Hive: 0.13 - 1.2.1+
HBase: 0.98 - 0.99, 1.1+
JDK: 1.7+

check with this official link
http://kylin.apache.org/docs21/install/hadoop_env.html


问:
Date minus date is not giving desired answer - IONIC 2
When I try to subtract

Wed Dec 06 2017 15:58:59 GMT+0530 (India Standard Time)  minus Tue Nov 28 2017 00:00:00 GMT+0530 (India Standard Time)  , the answer which is coming is -22

But the answer should be 6

What is going wrong and where, below is my page.ts code:

```<code>  this.tt = new Date();
  this.tt1 = this.datePipe.transform(this.tt,'dd/mm/yyyy');

  console.log(this.ent[0],"server DATE");
  // in console we see this - 28-NOV-17 server DATE

  var firstDate= new Date(this.ent[0]);  //Jan 01 2017 00:00:00

  var secondDate = new Date();//Jan 04 2017 00:00:00

  console.log(firstDate);
 // answer in console - Tue Nov 28 2017 00:00:00 GMT+0530 (India Standard Time)

  console.log(secondDate);
 //answer in console - Wed Dec 06 2017 15:58:59 GMT+0530 (India Standard Time)

  console.log(secondDate.getDate() - firstDate.getDate() );
 //answer in console -  -22
</code>```

答:
you can convert both dates to timestamp and subtract the timestamp you will get the result days in millis now convert it to days</p>

```<code>getTimestamp(dateParam:string):string{
    var date = new Date(dateParam); // some mock date
    var milliseconds = date.getTime();
    return milliseconds.toString();
}

var one_day=1000*60*60*24;
console.log(Math.ceil(getTimestamp(secondDate) - getTimestamp(firstDate))/(one_day) );
</code>```

Body:
When I try to subtract

Wed Dec 06 2017 15:58:59 GMT+0530 (India Standard Time)  minus Tue Nov 28 2017 00:00:00 GMT+0530 (India Standard Time)  , the answer which is coming is -22

But the answer should be 6

What is going wrong and where, below is my page.ts code:

  this.tt = new Date();
  this.tt1 = this.datePipe.transform(this.tt,'dd/mm/yyyy');

  console.log(this.ent[0],"server DATE");
  // in console we see this - 28-NOV-17 server DATE

  var firstDate= new Date(this.ent[0]);  //Jan 01 2017 00:00:00

  var secondDate = new Date();//Jan 04 2017 00:00:00

  console.log(firstDate);
 // answer in console - Tue Nov 28 2017 00:00:00 GMT+0530 (India Standard Time)

  console.log(secondDate);
 //answer in console - Wed Dec 06 2017 15:58:59 GMT+0530 (India Standard Time)

  console.log(secondDate.getDate() - firstDate.getDate() );
 //answer in console -  -22

Body:
you can convert both dates to timestamp and subtract the timestamp you will get the result days in millis now convert it to days

getTimestamp(dateParam:string):string{
    var date = new Date(dateParam); // some mock date
    var milliseconds = date.getTime();
    return milliseconds.toString();
}

var one_day=1000*60*60*24;
console.log(Math.ceil(getTimestamp(secondDate) - getTimestamp(firstDate))/(one_day) );


问:
List of all index & index columns in SQL Server DB
How do I get a list of all index & index columns in SQL Server 2005+? The closest I could get is:

```<code>select s.name, t.name, i.name, c.name from sys.tables t
inner join sys.schemas s on t.schema_id = s.schema_id
inner join sys.indexes i on i.object_id = t.object_id
inner join sys.index_columns ic on ic.object_id = t.object_id
inner join sys.columns c on c.object_id = t.object_id and
        ic.column_id = c.column_id

where i.index_id > 0
 and i.type in (1, 2) -- clustered & nonclustered only
 and i.is_primary_key = 0 -- do not include PK indexes
 and i.is_unique_constraint = 0 -- do not include UQ
 and i.is_disabled = 0
 and i.is_hypothetical = 0
 and ic.key_ordinal > 0

order by ic.key_ordinal
</code>```

Which is not exactly what I want.

What I want is, to list all user-defined indexes, (which means no indexes which support unique constraints & primary keys) with all columns (ordered by how do they appear in index definition) plus as much metadata as possible.

答:
Based on the accepted answer and two other questions 1, 2 I have assembled the following query:

```<code>SELECT
    QUOTENAME(t.name) AS TableName,
    QUOTENAME(i.name) AS IndexName,
    i.is_primary_key,
    i.is_unique,
    i.is_unique_constraint,
    STUFF(REPLACE(REPLACE((
        SELECT QUOTENAME(c.name) + CASE WHEN ic.is_descending_key = 1 THEN ' DESC' ELSE '' END AS [data()]
        FROM sys.index_columns AS ic
        INNER JOIN sys.columns AS c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
        WHERE ic.object_id = i.object_id AND ic.index_id = i.index_id AND ic.is_included_column = 0
        ORDER BY ic.key_ordinal
        FOR XML PATH
    ), '<row>', ', '), '</row>', ''), 1, 2, '') AS KeyColumns,
    STUFF(REPLACE(REPLACE((
        SELECT QUOTENAME(c.name) AS [data()]
        FROM sys.index_columns AS ic
        INNER JOIN sys.columns AS c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
        WHERE ic.object_id = i.object_id AND ic.index_id = i.index_id AND ic.is_included_column = 1
        ORDER BY ic.index_column_id
        FOR XML PATH
    ), '<row>', ', '), '</row>', ''), 1, 2, '') AS IncludedColumns,
    u.user_seeks,
    u.user_scans,
    u.user_lookups,
    u.user_updates
FROM sys.tables AS t
INNER JOIN sys.indexes AS i ON t.object_id = i.object_id
LEFT JOIN sys.dm_db_index_usage_stats AS u ON i.object_id = u.object_id AND i.index_id = u.index_id
WHERE t.is_ms_shipped = 0
AND i.type <> 0
</code>```

This query returns results such as below which shows the list of indexes, their columns and usage. Very helpful in determining which index is performing better than others:

Body:
How do I get a list of all index & index columns in SQL Server 2005+? The closest I could get is:

select s.name, t.name, i.name, c.name from sys.tables t
inner join sys.schemas s on t.schema_id = s.schema_id
inner join sys.indexes i on i.object_id = t.object_id
inner join sys.index_columns ic on ic.object_id = t.object_id
inner join sys.columns c on c.object_id = t.object_id and
        ic.column_id = c.column_id

where i.index_id > 0
 and i.type in (1, 2) -- clustered & nonclustered only
 and i.is_primary_key = 0 -- do not include PK indexes
 and i.is_unique_constraint = 0 -- do not include UQ
 and i.is_disabled = 0
 and i.is_hypothetical = 0
 and ic.key_ordinal > 0

order by ic.key_ordinal

Which is not exactly what I want.

What I want is, to list all user-defined indexes, (which means no indexes which support unique constraints & primary keys) with all columns (ordered by how do they appear in index definition) plus as much metadata as possible.

Body:
Based on the accepted answer and two other questions 1, 2 I have assembled the following query:

SELECT
    QUOTENAME(t.name) AS TableName,
    QUOTENAME(i.name) AS IndexName,
    i.is_primary_key,
    i.is_unique,
    i.is_unique_constraint,
    STUFF(REPLACE(REPLACE((
        SELECT QUOTENAME(c.name) + CASE WHEN ic.is_descending_key = 1 THEN ' DESC' ELSE '' END AS [data()]
        FROM sys.index_columns AS ic
        INNER JOIN sys.columns AS c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
        WHERE ic.object_id = i.object_id AND ic.index_id = i.index_id AND ic.is_included_column = 0
        ORDER BY ic.key_ordinal
        FOR XML PATH
    ), '<row>', ', '), '</row>', ''), 1, 2, '') AS KeyColumns,
    STUFF(REPLACE(REPLACE((
        SELECT QUOTENAME(c.name) AS [data()]
        FROM sys.index_columns AS ic
        INNER JOIN sys.columns AS c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
        WHERE ic.object_id = i.object_id AND ic.index_id = i.index_id AND ic.is_included_column = 1
        ORDER BY ic.index_column_id
        FOR XML PATH
    ), '<row>', ', '), '</row>', ''), 1, 2, '') AS IncludedColumns,
    u.user_seeks,
    u.user_scans,
    u.user_lookups,
    u.user_updates
FROM sys.tables AS t
INNER JOIN sys.indexes AS i ON t.object_id = i.object_id
LEFT JOIN sys.dm_db_index_usage_stats AS u ON i.object_id = u.object_id AND i.index_id = u.index_id
WHERE t.is_ms_shipped = 0
AND i.type <> 0

This query returns results such as below which shows the list of indexes, their columns and usage. Very helpful in determining which index is performing better than others:


问:
Android 6.0 : Foreground service is being removed when app is being killed
I created Notification in onStartCommand of my Service class to run a foreground service.

In previous versions of Android (version < 6.0) the service keeps running and the Notification can not be removed even if I kill the app from the recent apps menu. I'm also using BOOT_COMPLETED intent filter for my BroadCastReceiver so that my service starts as my device restarts. Everything is working fine in Lollipop and previous versions. But when I tested in my Marshmallow device, when I clear my ram from recent app, the foreground service is also killed and the Irremovable Notification also being removed. As a result my app stops working. Service does not start when the device restarts either.

Is it causing by the famous DOZE MODE implemented in Android 6.0 and Higher ? Or there is something else ? Please help me someone ? I asked for help earlier but couldn't resolve the problem.

答:
you have to add process attribute in manifest </p>

```<code><service
 android:name=".YourServiceName"
 android:process=".process"
 android:enabled="true"
 android:exported="true"></service>
</code>```

Body:
you have to add process attribute in manifest

<service
 android:name=".YourServiceName"
 android:process=".process"
 android:enabled="true"
 android:exported="true"></service>


问:
The right way to search phone numbers
In my application, I search a user by his phone number on a server.
I have encountered such an issue: in my country, you can write a phone number both as '8xxxxxxxx' and '+7xxxxxxxx' and '7xxxxxxxx'.
So I should perform a search so that a number written in different notation still would be found.
But how is it in different countries? How the numbers are written? Is there a way to perform a valid search?

答:
You'll probably want to look at the E.164 Standard Format.

E.164 organizes phone numbers with all the necessary localization information in a easily human readable and machine parseable format. It defines a simple format for unambiguously storing phone numbers in an easily readable string. The string starts with a + sign, followed by the country code and the “subscriber” number which is the phone number without any context prefixes such as local dialing codes, international dialing codes or formatting.

Numbers stored as E.164 can easily be parsed, formatted and displayed in the appropriate context, since the context of a phone number can greatly affect its format.

The library responsible for this is called Google’s libphonenumber. With libphonenumber you can parse, verify, and format phone number inputs quite easily, do as you type formatting and even glean extra information about the number, like whether it was a mobile or landline or what state or province it was from. Libphonenumber in its basic form consists of a set of rules and regular expressions in an XML file for breaking down and parsing a number.

Title: The right way to search phone numbers


问:
React Native: Align two TextInputs side by side
I am just starting out with React Native and I am developing an app using RN ... I am bit stuck here ... I have a form in one of the app's component that have couple of TextInputs aligned side by side like in the image below

Here is the code that I have written trying to achieve the above design.

```<code>import React, {Component} from 'react';
import {View, Text, StyleSheet, TextInput, TouchableHighlight} from 'react-native';

export default class AddItems extends Component {
    onAdd() {
        alert('Hello');
    }

    render() {
    return (
        <View style={addItemStyles.wrapper}>
            <View>
                <Text>Item to give cash credit for:</Text>
                <View>
                    <View>
                        <TextInput placeholder="Test" style={{justifyContent: 'flex-start',}} />
                    </View>
                    <View>
                        <TextInput placeholder="Test" style={{justifyContent: 'flex-end',}} />
                    </View>
                </View>
            </View>

        </View>
    );
}
}

const addItemStyles = StyleSheet.create({
    wrapper: {
        padding: 10,
        backgroundColor: '#FFFFFF'
    },
    inputLabels: {
        fontSize: 16,
        color: '#000000',
        marginBottom: 7,
    },
    inputField: {
        backgroundColor: '#EEEEEE',
        padding: 10,
        color: '#505050',
        height: 50
    },
    inputWrapper: {
        paddingBottom: 20,
    },
    saveBtn: {
        backgroundColor: '#003E7D',
        alignItems: 'center',
        padding: 12,
    },
    saveBtnText: {
        color: '#FFFFFF',
        fontSize: 18,
    }

});
</code>```

But instead I am getting the view like this.

I know this could be a minor thing but as I said above that I am just starting with React Native so you can consider me as a noob ... Thanks in advance for your help. Looking forward to your answers.

答:
use "flexDirection" in style</p>

```<code>render() {
    return (
        <View style={addItemStyles.wrapper}>
            <View>
                <Text>Item to give cash credit for:</Text>
                <View style={{flexDirection:"row"}}>
                    <View style={{flex:1}}>
                        <TextInput placeholder="Test" style={{justifyContent: 'flex-start',}} />
                    </View>
                    <View style={{flex:1}}>
                        <TextInput placeholder="Test" style={{justifyContent: 'flex-end',}} />
                    </View>
                </View>
            </View>

        </View>
    );
}
</code>```

Body:
I am just starting out with React Native and I am developing an app using RN ... I am bit stuck here ... I have a form in one of the app's component that have couple of TextInputs aligned side by side like in the image below

Here is the code that I have written trying to achieve the above design.

import React, {Component} from 'react';
import {View, Text, StyleSheet, TextInput, TouchableHighlight} from 'react-native';

export default class AddItems extends Component {
    onAdd() {
        alert('Hello');
    }

    render() {
    return (
        <View style={addItemStyles.wrapper}>
            <View>
                <Text>Item to give cash credit for:</Text>
                <View>
                    <View>
                        <TextInput placeholder="Test" style={{justifyContent: 'flex-start',}} />
                    </View>
                    <View>
                        <TextInput placeholder="Test" style={{justifyContent: 'flex-end',}} />
                    </View>
                </View>
            </View>

        </View>
    );
}
}

const addItemStyles = StyleSheet.create({
    wrapper: {
        padding: 10,
        backgroundColor: '#FFFFFF'
    },
    inputLabels: {
        fontSize: 16,
        color: '#000000',
        marginBottom: 7,
    },
    inputField: {
        backgroundColor: '#EEEEEE',
        padding: 10,
        color: '#505050',
        height: 50
    },
    inputWrapper: {
        paddingBottom: 20,
    },
    saveBtn: {
        backgroundColor: '#003E7D',
        alignItems: 'center',
        padding: 12,
    },
    saveBtnText: {
        color: '#FFFFFF',
        fontSize: 18,
    }

});

But instead I am getting the view like this.

I know this could be a minor thing but as I said above that I am just starting with React Native so you can consider me as a noob ... Thanks in advance for your help. Looking forward to your answers.

Body:
use "flexDirection" in style

render() {
    return (
        <View style={addItemStyles.wrapper}>
            <View>
                <Text>Item to give cash credit for:</Text>
                <View style={{flexDirection:"row"}}>
                    <View style={{flex:1}}>
                        <TextInput placeholder="Test" style={{justifyContent: 'flex-start',}} />
                    </View>
                    <View style={{flex:1}}>
                        <TextInput placeholder="Test" style={{justifyContent: 'flex-end',}} />
                    </View>
                </View>
            </View>

        </View>
    );
}