问:
JavaScript - How to place asterisk in the right side of the text box?
I want to place asterisk in the right side of the each text box individually when I am submitting the empty form/field. The code is working but asterisk is displaying in the end of the form.

This is my code:

```<code>[<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<title></title>
<style type="text/css">
body { font-family:arial, helvetica, sans-serif; font-weight:bold; font-size:13px; color:#000; text-align:left; margin:3px 0px; }
input { text-align:center; border:2px solid #CCC; }
#wrap  { width:400px; height:200px; margin:20px; padding:10px;  }
#une { margin-top:10px; }
#reg {margin-top:10px; }
.a13B { color:#F00; }
.cntr { text-align:center; }
</style>
</head>

<body>

<div id="wrap">
  <form id="regform" name="registerationform" method="POST">
    <table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse" width="300">
      <tr>
        <td>First Name: </td>
        <td class="cntr">
        <input type="text" name="fnametxt" size="20"></td>
      </tr>
      <tr>
        <td>Second Name: </td>
        <td class="cntr">
        <input type="text" name="snametxt" size="20"> </td>
      </tr>
      <tr>
        <td>User Name:</td>
        <td class="cntr">
        <input type="text" name="unametxt" size="20"> </td>
      </tr>
      <tr>
        <td>Email Address: </td>
        <td class="cntr">
        <input type="text" name="emailtxt" size="20"> </td>
      </tr>
      <tr>
        <td>Password : </td>
        <td class="cntr"><input type="password" name="pwdtxt" size="20"> </td>
      </tr>
      <tr>
        <td>Confirm : </td>
        <td class="cntr"><input type="password" name="cpwdtxt" size="20"> </td>
      </tr>
    </table>
    <input id="reg" name="reg" type="button" onclick="regvalidate(this.form)" value="Register Now">
  </form>
  <div id="une" class="a13B">
  </div>
</div>
<!-- end wrap -->
<script type="text/javascript">
var uneObj=document.getElementById("une"); // object ref to msg line
var currentBrdObj;
//
function regvalidate(formObj)
{ uneObj.innerHTML=""; // clear msg line before resubmitting
 // gather object ref to input boxes
  var allInputs=document.getElementById("regform").getElementsByTagName("input");
 // check if value of box is ""
  for(var i=0;i<allInputs.length;i++)
    { if(allInputs\[i\].name !="reg")    // ignore submit button
       { if(allInputs\[i\].value=="")
         { uneObj.innerHTML=msg\[i\];
           if(currentBrdObj){currentBrdObj.style.border="2px solid #CCC"; }
           allInputs\[i\].style.border="2px solid #F00";
           currentBrdObj=allInputs\[i\];
           allInputs\[i\].onclick=function(){ this.style.border="2px solid #CCC"; }
           return;
     } } }
// check if password and confirm are the same
  if((formObj.pwdtxt.value) != (formObj.cpwdtxt.value))
   { uneObj.innerHTML = msg\[msg.length-1\];       // last msg in array
     formObj.pwdtxt.value = ""; formObj.pwdtxt.style.border="";
     formObj.cpwdtxt.value = ""; formObj.cpwdtxt.style.border="";
     return;
    }
// all ok so submit form
 uneObj.innerHTML = "All ok so submitting form";
  formObj.submit();
}
// -----
 var msg =\["*","*",
          "*","*",
          "*","*"\];
     msg\[msg.length\]="Passwords must be equal.<br>Please type a password";

      //
        </script>

</body>

</html>][1]
</code>```

@PawanKumar
Here is your code:

```<code>   <html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script>
$(document).ready(function() {
  $('#submitBtn').on('click', function(e) {
    debugger;
    e.preventDefault();
    var fields = document.getElementsByTagName('input');
    for (var i = 0; i < fields.length; i++) {
      if (fields[i].hasAttribute('required')) {
        if (fields[i].value == "") {
          fields[i].classList.add('redBorder');
          $(fields[i]).after('*');
        } else {
          fields[i].classList.remove('redBorder');
        }
      }
    }
  });
});

</script>

<style>

.redBorder {
  border: 2px solid red;
  border-radius: 2px;
}

</style>

</head>

<form novalidate>
<input type="text" placeholder="first name" required/><br/><br/>
<input type="text" placeholder="last name" /><br/><br/>
<button id="submitBtn" value="Submit">Submit</button>
</form>

</html>
</code>```

答:
Use span element to display asterisk at the end of text box. Try this :

<input type="text" id="name"/>  * ```

Hope this solves your requirement.

Body:
I want to place asterisk in the right side of the each text box individually when I am submitting the empty form/field. The code is working but asterisk is displaying in the end of the form.

This is my code:

[

<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<title></title>

  <form id="regform" name="registerationform" method="POST">

        First Name:

        <input type="text" name="fnametxt" size="20">

        Second Name:

        <input type="text" name="snametxt" size="20">

        User Name:

        <input type="text" name="unametxt" size="20">

        Email Address:

        <input type="text" name="emailtxt" size="20">

        Password :
        <input type="password" name="pwdtxt" size="20">

        Confirm :
        <input type="password" name="cpwdtxt" size="20">

    <input id="reg" name="reg" type="button" onclick="regvalidate(this.form)" value="Register Now">
  </form>

][1]

@PawanKumar
Here is your code:

<form novalidate>
<input type="text" placeholder="first name" required/>

<input type="text" placeholder="last name" />

<button id="submitBtn" value="Submit">Submit</button>
</form>

Body:
Use span element to display asterisk at the end of text box. Try this :

<input type="text" id="name"/> <span style="color:red"> * </span>

Hope this solves your requirement.


来源: stackexchange

问:
Fineuploader with Angular
I'm trying to integrate fineuploader library inside Angular 4. I was referring to https://stackoverflow.com/a/44067445/4261569. My question is too wide to comment there and it looks like the answer is for Angular 2. There is lot of things that has been changed since Angular released it's 4th version.

Moving back to my question: Fineuploader uses

```<code><script type="text/template" id="qq-template">Template code goes here..</script>
</code>```

However, if I try to include it in my uploader.component.html file. It just stips of the script tag. When I researched more on it, I found that, it's default behaviour of angular apps. It strips of all script tag in component.

Is there any alternate way of integrating fineuploader inside angular? I really need to use that library as it is the only thing which is supported in IE9 and provides direct S3 upload feature.

Edit
Question is not about integrating third party libraries in angular. It's about having  inside mycomponent.component.html file. I know for security reasons angular is striping the script tags but using script tag for displaying template is something needed by third party libraries like fineuploader.

答: Solution is just to replace  to . Although, I wasn't able to find the solution to keep script tag inside component but for fineuploader, replacing the element did the trick for me.</p>

ContentLicense: CC BY-SA 3.0

Title: Fineuploader with Angular

Body:
I'm trying to integrate fineuploader library inside Angular 4. I was referring to https://stackoverflow.com/a/44067445/4261569. My question is too wide to comment there and it looks like the answer is for Angular 2. There is lot of things that has been changed since Angular released it's 4th version.

Moving back to my question: Fineuploader uses

However, if I try to include it in my uploader.component.html file. It just stips of the script tag. When I researched more on it, I found that, it's default behaviour of angular apps. It strips of all script tag in component.

Is there any alternate way of integrating fineuploader inside angular? I really need to use that library as it is the only thing which is supported in IE9 and provides direct S3 upload feature.

Edit
Question is not about integrating third party libraries in angular. It's about having  inside mycomponent.component.html file. I know for security reasons angular is striping the script tags but using script tag for displaying template is something needed by third party libraries like fineuploader.


问:
Selectively inheriting from any of multiple classes at runtime
I'm doing scientific computing and I'm beginner in c++. MyNLP is a class which contain all the problem data and methods. I'm using third party libraries for numerical optimization. Each third party is a specific algorithm to solve my problem. In order to use each library, my MyNLP class need to inherit corresponding class from third party library.

For example,

```<code>Class MyNLP :public IPOPT
{
};
</code>```

enable me to use IPOPT algorithm to solve my problem. Similarly,

```<code>class MyNLP: public SQP
{
};
</code>```

enable me to use SQP algorithm.

But in my case, only at the run-time, program decides which class it should inherit. I have to inherit either one of third party class.
Could any one give a  technique to achieve this in cpp?

答:
It seems to me this is an instance of the XY problem:
You asked for a way to switch out the base classes while you actually want a way to use your code for different solvers with little adaption necessary.

Having implemented an NLP solver with IPOPT myself recently, I would recommend another approach:

Why don't you first implement a base class that implements all relevant methods for evaluating the NLP:

Objective value

Objective gradient

Jacobian of the (in)equality constraints

Lagrangian

Hessian of the Lagrangian

Since your solvers will likely use equivalent formats for scalars, vectors and also hopefully sparse matrices (in coordinate format: row vector, column vector, value vector) and the same floating-point type (double), you can then implement lightweight wrappers (based on the solver's interface) around this base class instead of trying to use some kind of some weird runtime polymorphism.

Body:
I'm doing scientific computing and I'm beginner in c++. MyNLP is a class which contain all the problem data and methods. I'm using third party libraries for numerical optimization. Each third party is a specific algorithm to solve my problem. In order to use each library, my MyNLP class need to inherit corresponding class from third party library.

For example,

Class MyNLP :public IPOPT
{
};

enable me to use IPOPT algorithm to solve my problem. Similarly,

class MyNLP: public SQP
{
};

enable me to use SQP algorithm.

But in my case, only at the run-time, program decides which class it should inherit. I have to inherit either one of third party class.
Could any one give a  technique to achieve this in cpp?


问:
Jquery: Closest() div remove not working
Jquery closest div remove not working i found same question on stackoverflow but these answered not resolve my problem

closest div remove js fiddle here

```<code><script>
$(document).ready(function(){
    var counter = 4;
    var name = 1;
    var qty = 1;
    var price = 1;
    $('#addproduct').click(function() {
        $('#dynamicInput').append('<div class="clearfix"></div><div class="pdd" id="dlt"><div class="col-sm-3"><div class="row">' + (counter++)+' <label>Product Name</label></div></div><div class="col-sm-3"><div class="row"><select name="productnm'+(name++)+'"><option>Select Product</option><option>Rice</option><option>Fried Rice</option><option>Biryani</option></select></div></div><div class="col-sm-3"><div class="row"><label>Quantity</label></div></div><div class="col-sm-1 row"><div class="row qunatity-number"><input type="number" name="qunatity'+(qty++)+'" value="1" /></div></div><div class="col-sm-2"><div class="row qunatity-totalprice"><input type="text" name="totalprice'+(price++)+'" placeholder="Total Price" disabled /></div></div><a class="deleter" ><i class="fa fa-trash-o" aria-hidden="true"></i></a></div> ');
    });
    $('.deleter').click(function(){
       $(this).closest("#dlt").remove();
     });

});

</script>
</code>```

答:
You add a click event to the deleter before it is created, since it is created on click to addproduct, which did not happen when the document is loaded. You will need to create an on event, like this:

```<code>$('#dynamicInput').on("click", ".deleter", function() {
    $(this).parent().remove();
});
</code>```

You also need to make sure you do not duplicate HTML ids. It is an incorrect way of HTML programming. When something is unique, use an id. When it is not unique, use a class.

Body:
You add a click event to the deleter before it is created, since it is created on click to addproduct, which did not happen when the document is loaded. You will need to create an on event, like this:

$('#dynamicInput').on("click", ".deleter", function() {
    $(this).parent().remove();
});

You also need to make sure you do not duplicate HTML ids. It is an incorrect way of HTML programming. When something is unique, use an id. When it is not unique, use a class.


问:
How to display 1000 000 as 1Million
How can i implement 'k' or 'm' prefixer to my code? I am not sure how to add it to my code.

i want the number 1000 to display as 1k how can i make the prefixer in my code. can someone please help me add it to my code please.

答:
To use a thousands separator, you can use the Intl.NumberFormat method. For instance Sweden uses the space as thousands separator, so you could reference that:

console.log(new Intl.NumberFormat('se').format(1000000));```

For a way to format a number with K or M suffixes, see this complete answer.

Title: How to display 1000 000 as 1Million

Body:
To use a thousands separator, you can use the Intl.NumberFormat method. For instance Sweden uses the space as thousands separator, so you could reference that:

console.log(new Intl.NumberFormat('se').format(1000000));

For a way to format a number with K or M suffixes, see this complete answer.


问:
Get modified files in FTP folder

I have a local folder which contains files and directories (>2000
files).

I uploaded this entire folder on my ftp.

Now for example let's say my ftp folder is called FTPFolder and my local folder is called LOCALFolder. These two folders are exactly the same for now.

And let's say the both folders contain a file called text.txt.

Now what I would like to do:

If I change the test.txt on the FTP, how could I detect it in C#?
Getting all local files and all FTPfiles and then comparing them is just too long. Has anyone got another way of doing this ?

Basically the goal is to download all files on the FTP which are different from the same files but locally.

答:
Here are possible options:

Check the checksum - the best and fastest way, but it might not be present for the files in the first place.

Check the size of the file and its timestamp. Not ideal, but it might work.

Other than that, I don't think there is anything you can and it's not a C# issue per se.

Title: Get modified files in FTP folder


问:
Error: Invalid Use of Property when attemting to reset Excel UsedRange
I'm trying to reset the Excel 2007 UsedRange as per this discussion:
Excel resetting "UsedRange"

However, I've encountered a problem that I do not understand. I get the error "invalid use of property" at compile time if I reset the UsedRange from a Worksheet object variable, but not via the Worksheets collection, as shown below:

```<code>Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet

Set wb = Excel.Workbooks.Add
Set ws = wb.Worksheets(1)

'Why does this not work?
ws.UsedRange

'And why does this instead?
wb.Worksheets(ws.Name).UsedRange

'Note: Absolute object variables are in use because this code will be used in
'an Access database to start & automate Excel. So the "Active_____." objects
'are not used, such as ActiveBook, ActiveSheet, etc.
</code>```

It seems to me either way should work, but it's like something is missing from the code behind UsedRange that tells the compiler it's a command in addition to a property.

答:
```<code>' Why does this not work?
ws.UsedRange
</code>```

Because it doesn't "do" anything. It's just a range.

You can manipulate it like any other range, for example clear it:

```<code>ws.UsedRange.Clear
</code>```

Body:
I'm trying to reset the Excel 2007 UsedRange as per this discussion:
Excel resetting "UsedRange"

However, I've encountered a problem that I do not understand. I get the error "invalid use of property" at compile time if I reset the UsedRange from a Worksheet object variable, but not via the Worksheets collection, as shown below:

Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet

Set wb = Excel.Workbooks.Add
Set ws = wb.Worksheets(1)

'Why does this not work?
ws.UsedRange

'And why does this instead?
wb.Worksheets(ws.Name).UsedRange

'Note: Absolute object variables are in use because this code will be used in
'an Access database to start & automate Excel. So the "Active_____." objects
'are not used, such as ActiveBook, ActiveSheet, etc.

It seems to me either way should work, but it's like something is missing from the code behind UsedRange that tells the compiler it's a command in addition to a property.

Body:
' Why does this not work?
ws.UsedRange

Because it doesn't "do" anything. It's just a range.

You can manipulate it like any other range, for example clear it:

ws.UsedRange.Clear


问:
How I can make the program keep go next line after complete on if statement
im trying to write a code but for some reason the program is stuck in a loop of the if statements

```<code>#include "std_lib_facilities.h"
int main()
{
    double i = 0;
    double u = 0;
    cout << "Enter one numbers:\n";
    while (cin >> i)
        if (i > u)
        {
            cout << "the largest number is: " << i << '\n'
            << "the smallest number is " << u << "\n";
}
        else if (i < u) {
            cout << "the largest number is " << u << '\n'
                << "the smallest number is " << i << "\n";
        }
        else if (i == u) {
            cout << "The numbers are equal\n";
        }
        cout << "blabla\n";
        keep_window_open();

}
</code>```

So my purpose is that after it checks the "if else" even is some of them true or not I need it to performe  cout << "blabla\n";
the code is not finished, I just need to understand how to make it jump to another line so I will be able to keep write the continue.

答:
If I understood you right, and you just need to print "blabla\n" every time inside the while loop, then you only need to put curly braces around, like this:

```<code>while (cin >> i) {
    if (i > u) { ... }
    else if (i < u) { ... }
    ...
    cout << "blabla\n";
}
</code>```

In general, you better write curly braces everywhere, because avoiding them saves you a second today but can steal an hour several months later, just in case you ever need to add something inside.

Note that you can also use goto construction to pass the execution of a program from any point to any other point, but you better don't use it because it is complex both to write and read.

If instead you just wanted to get one integer, then you should have used cin >> i; in place of your while loop.

Body:
im trying to write a code but for some reason the program is stuck in a loop of the if statements

#include "std_lib_facilities.h"
int main()
{
    double i = 0;
    double u = 0;
    cout << "Enter one numbers:\n";
    while (cin >> i)
        if (i > u)
        {
            cout << "the largest number is: " << i << '\n'
            << "the smallest number is " << u << "\n";
}
        else if (i < u) {
            cout << "the largest number is " << u << '\n'
                << "the smallest number is " << i << "\n";
        }
        else if (i == u) {
            cout << "The numbers are equal\n";
        }
        cout << "blabla\n";
        keep_window_open();

}

So my purpose is that after it checks the "if else" even is some of them true or not I need it to performe  cout << "blabla\n";
the code is not finished, I just need to understand how to make it jump to another line so I will be able to keep write the continue.

Body:
If I understood you right, and you just need to print "blabla\n" every time inside the while loop, then you only need to put curly braces around, like this:

while (cin >> i) {
    if (i > u) { ... }
    else if (i < u) { ... }
    ...
    cout << "blabla\n";
}

In general, you better write curly braces everywhere, because avoiding them saves you a second today but can steal an hour several months later, just in case you ever need to add something inside.

Note that you can also use goto construction to pass the execution of a program from any point to any other point, but you better don't use it because it is complex both to write and read.

If instead you just wanted to get one integer, then you should have used cin >> i; in place of your while loop.


问:
Make new row dirty programmatically and insert a new row after it in DataGridView
I've an editable unbounded datagridview. I'm changing the value of new row programmatically.

Normally, when user types in any field of a new row, it becomes dirty and another new row is inserted below it.

But in my case, when user comes in to any field of a new row, I'm trapping the function key and changing the cell value programmatically.

myGrid.CurrentCell.Value = "xyz";

And it doesn't insert a new row below it.

Now as a work around I tried this on CellValueChanged event handler.

```<code>  if (myGrid.NewRowIndex == e.RowIndex)
  {
    myGrid.Rows.Insert(e.RowIndex + 1, 1);
  }
</code>```

But it throws error saying No row can be inserted after the uncommitted new row..

How could I tell myGrid that I've made current row (which is a new row) dirty and that there is need of a new row after it?

答:
Here I got the solution</p>

```<code>myGrid.NotifyCurrentCellDirty(true);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I've an editable unbounded datagridview. I'm changing the value of new row programmatically.

Normally, when user types in any field of a new row, it becomes dirty and another new row is inserted below it.

But in my case, when user comes in to any field of a new row, I'm trapping the function key and changing the cell value programmatically.

myGrid.CurrentCell.Value = "xyz";

And it doesn't insert a new row below it.

Now as a work around I tried this on CellValueChanged event handler.

  if (myGrid.NewRowIndex == e.RowIndex)
  {
    myGrid.Rows.Insert(e.RowIndex + 1, 1);
  }

But it throws error saying No row can be inserted after the uncommitted new row..

How could I tell myGrid that I've made current row (which is a new row) dirty and that there is need of a new row after it?

Body:
Here I got the solution

myGrid.NotifyCurrentCellDirty(true);


问:
django {% if user.groups == 'FC' %} doens't work
I'm making a website using django.

{% if user.groups == 'FC' %} doesn't work in my template.I have groups like that.

For example, one of my users(username is 'hong) belongs to 'FC' group as you see below.

But,

```<code>{% if user.groups == 'FC' %}
      <li><a href="{% url 'register' %}">register form</a></li>
      <li><a href="{% url 'mypage' %}">fc's my page</a></li>
{% else %}
 <li><a href="{% url 'PT_mypage' %}">fitness' my page</a></li>
{% endif %}
</code>```

if user.groups == ' '  doesn't work.

How I check the users' group? I have to distinguish the users by groups.

答:
You have to use tags.
In your application, you can create a directory which is named : templatetags.

Then, you have to create inside a file user_tags.py which will contain :

```<code>from django import template
from django.contrib.auth.models import Group

register = template.Library()

@register.filter(name='has_group')
def has_group(user, group_name):
    group = Group.objects.filter(name=group_name)
    if group:
        group = group.first()
        return group in user.groups.all()
    else:
        return False
</code>```

Then, in your template, if you want to specify part, ...

```<code>{% load user_tags %}
...
...
{% if request.user|has_group:"yourgroupe" %}
# part which will only accessible for users registered in `yourgroup`
{% endif %}
</code>```

It works in my application with different groups (admin, users, visitors, ..) ;)

ContentLicense: CC BY-SA 4.0

Body:
I'm making a website using django.

{% if user.groups == 'FC' %} doesn't work in my template.I have groups like that.

For example, one of my users(username is 'hong) belongs to 'FC' group as you see below.

But,

{% if user.groups == 'FC' %}

register form

fc's my page

{% else %}

fitness' my page

{% endif %}

if user.groups == ' '  doesn't work.

How I check the users' group? I have to distinguish the users by groups.

Body:
You have to use tags.
In your application, you can create a directory which is named : templatetags.

Then, you have to create inside a file user_tags.py which will contain :

from django import template
from django.contrib.auth.models import Group

register = template.Library()

@register.filter(name='has_group')
def has_group(user, group_name):
    group = Group.objects.filter(name=group_name)
    if group:
        group = group.first()
        return group in user.groups.all()
    else:
        return False

Then, in your template, if you want to specify part, ...

{% load user_tags %}
...
...
{% if request.user|has_group:"yourgroupe" %}
# part which will only accessible for users registered in `yourgroup`
{% endif %}

It works in my application with different groups (admin, users, visitors, ..) ;)


问:
managedObjectContext in Swift 3
I want to work through this example code in which Swift and CoreData is used to create a table. However, using Swift 3 I fail to get it to work. Most importantly, I cannot properly replace the line

```<code>// set up the NSManagedObjectContext
  let appDelegate = NSApplication.sharedApplication().delegate as! AppDelegate
  managedContext = appDelegate.managedObjectContext
</code>```

even though I found this related question (which however is iOS not OS X). How can I replace that piece of code which produces the error message Value of type 'AppDelegate' has no member 'managedContext'?

答:
For macOS and Swift 3.1</p>

```<code>let moc: NSManagedObjectContext = (NSApplication.shared().delegate as! AppDelegate).persistentContainer.viewContext
</code>```

Title: managedObjectContext in Swift 3

Body:
I want to work through this example code in which Swift and CoreData is used to create a table. However, using Swift 3 I fail to get it to work. Most importantly, I cannot properly replace the line

// set up the NSManagedObjectContext
  let appDelegate = NSApplication.sharedApplication().delegate as! AppDelegate
  managedContext = appDelegate.managedObjectContext

even though I found this related question (which however is iOS not OS X). How can I replace that piece of code which produces the error message Value of type 'AppDelegate' has no member 'managedContext'?

Body:
For macOS and Swift 3.1

let moc: NSManagedObjectContext = (NSApplication.shared().delegate as! AppDelegate).persistentContainer.viewContext


问:
Namespace android.support.design is not bound
Code snippet where this issue crops up :

```<code><android.support.design.widget.TextInputLayout
    android:id="@+id/lastName_layout"
    android:layout_weight="2"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android.support.design:hintTextAppearance="@color/colorAccent">

    <EditText
        android:id="@+id/lastName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="#FFF"
        android:backgroundTint="#E0E0E0"
        android:hint="Last Name"/>

</android.support.design.widget.TextInputLayout>
</code>```

Error appears in the last line of the first block. How is the namespace supposed to be defined?

答:
You need add the dependency for this works:

```<code>xmlns:design="http://schemas.android.com/apk/res-auto"
</code>```

Example:

```<code><android.support.design.widget.BottomNavigationView
   android:id="@+id/bottomNavigationView"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   design:menu="@menu/main_menu_nav" />
</code>```

design:menu -> now works fine.

Body:
Code snippet where this issue crops up :

<android.support.design.widget.TextInputLayout
    android:id="@+id/lastName_layout"
    android:layout_weight="2"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android.support.design:hintTextAppearance="@color/colorAccent">

    <EditText
        android:id="@+id/lastName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="#FFF"
        android:backgroundTint="#E0E0E0"
        android:hint="Last Name"/>

</android.support.design.widget.TextInputLayout>

Error appears in the last line of the first block. How is the namespace supposed to be defined?

Body:
You need add the dependency for this works:

xmlns:design="http://schemas.android.com/apk/res-auto"

Example:

<android.support.design.widget.BottomNavigationView
   android:id="@+id/bottomNavigationView"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   design:menu="@menu/main_menu_nav" />

design:menu -> now works fine.


问:
Excel consolidate sum yields different column total
I have two columns that look like this:

```<code>Make/Model      Parc
Abarth*500      15
Abarth*500      19
Abarth*500      2
Abarth*500      14
Abarth*500      15
Abarth*500      25
Abarth*500      20
Abarth*500      17
Abarth*500C     12
Abarth*500C     16
Abarth*500C     23
Abarth*500C     18
Abarth*500C     1
Alfa Romeo*145  405
Alfa Romeo*145  431
Alfa Romeo*146  36
Alfa Romeo*146  80
Alfa Romeo*146  121
Alfa Romeo*146  72
Alfa Romeo*146  39
</code>```

etc...

The sum of the values in the "Parc" column is 10,475,387.

I perform a consolidate on this table to remove the repetitions in "Make/Model" and sum the values in the "Parc" column for each "Make/Model."

Once I perform the consolidation, everything looks as expected:

```<code>Make/Model      Parc
Abarth*500      127
Abarth*500C     70
Alfa Romeo*145  836
Alfa Romeo*146  348
Alfa Romeo*147  3848
Alfa Romeo*155  29
Alfa Romeo*156  3148
Alfa Romeo*159  573
Alfa Romeo*164  111
</code>```

etc...

So what's the problem? The new sum of the "Parc" column is 10,554,076! When I perform random "spot" checks everything seems correct. I do not understand how the sum could have gone up? I have over 18,000 rows in this dataset so individually checking all of the data would be very time consuming.

You can find the full dataset here:
Excel File

Edit:
I added the screenshot of me using the consolidate tool to give you an idea of what I did to get this result.

Edit 2:
I have tried removing all formatting. Also, these numbers are all integers and the option to "Automatically insert a decimal point" is not checked. I have also tried creating a new column of =INT() values to ensure they are all integers. My results are exactly the same in all cases.

答:
The asteriks is a special character in Excel. Easiest solution that I know is to replace the asterisk by a space. To do so in the find/replace box, type '~*' in the find box and ' ' in the replace then do replace all (without quotes).

Both sum and sumif then yield 10,475,387.

Body:
I have two columns that look like this:

Make/Model      Parc
Abarth*500      15
Abarth*500      19
Abarth*500      2
Abarth*500      14
Abarth*500      15
Abarth*500      25
Abarth*500      20
Abarth*500      17
Abarth*500C     12
Abarth*500C     16
Abarth*500C     23
Abarth*500C     18
Abarth*500C     1
Alfa Romeo*145  405
Alfa Romeo*145  431
Alfa Romeo*146  36
Alfa Romeo*146  80
Alfa Romeo*146  121
Alfa Romeo*146  72
Alfa Romeo*146  39

etc...

The sum of the values in the "Parc" column is 10,475,387.

I perform a consolidate on this table to remove the repetitions in "Make/Model" and sum the values in the "Parc" column for each "Make/Model."

Once I perform the consolidation, everything looks as expected:

Make/Model      Parc
Abarth*500      127
Abarth*500C     70
Alfa Romeo*145  836
Alfa Romeo*146  348
Alfa Romeo*147  3848
Alfa Romeo*155  29
Alfa Romeo*156  3148
Alfa Romeo*159  573
Alfa Romeo*164  111

etc...

So what's the problem? The new sum of the "Parc" column is 10,554,076! When I perform random "spot" checks everything seems correct. I do not understand how the sum could have gone up? I have over 18,000 rows in this dataset so individually checking all of the data would be very time consuming.

You can find the full dataset here:
Excel File

Edit:
I added the screenshot of me using the consolidate tool to give you an idea of what I did to get this result.

Edit 2:
I have tried removing all formatting. Also, these numbers are all integers and the option to "Automatically insert a decimal point" is not checked. I have also tried creating a new column of =INT() values to ensure they are all integers. My results are exactly the same in all cases.


问:
operator= doesn't work properly in my custom string class
I'm trying to create a custom string class using std::vector< char >.

Please take a look at my code below.

```<code>#include <iostream>
#include <vector>

class mString {

public:

    mString();
    explicit mString(const char *str);
    mString(const mString &str);

    mString operator=(const char *str);

private:

    typedef std::vector<char> vecChar;
    vecChar _vc;
};

inline mString::mString(){}
inline mString::mString(const char *str) {

    const vecChar::size_type size = strlen(str);
    _vc = vecChar(str, str + size);
}
inline mString::mString(const mString &str) {

    _vc = str._vc;
}

inline mString mString::operator=(const char *str) {

    const vecChar::size_type size = strlen(str);
    _vc = vecChar(str, str + size);
    return *this;
}

int main(int argc, const char * argv[]) {

    /* This works */
    mString a;
    a = "Hello World";

    /* Error : No viable conversion from 'const char[12]' to mString */
    mString b = "Hello World";

    return 0;
}
</code>```

I don't understand why 'mString b = "Hello World";' doesn't work while 'mString a; a= "Hello World";' works.
What do I need to do in order to make it work?

Thank you in advance!

答:
This has nothing common with the assignment operator.

You declared this constructor

```<code>explicit mString(const char *str);
</code>```

with the function specifier explicit.

Thus in this declaration

```<code>mString b = "Hello World";
</code>```

the constructor can not be called to convert the string literal "Hello World"to an object of the type mString.

Remove the function specifier explicit and the declaration will compile.

Or instead of the copy initialization as in the declaration above you could use the direct initialization like

```<code>mString b( "Hello World" );
</code>```

So in this declaration

```<code>mString b = "Hello World";
</code>```

there are used constructors. But in this expression statement

```<code>a= "Hello World";
</code>```

there is indeed used the assignment operator.

Body:
I'm trying to create a custom string class using std::vector< char >.

Please take a look at my code below.

#include <iostream>
#include <vector>

class mString {

public:

    mString();
    explicit mString(const char *str);
    mString(const mString &str);

    mString operator=(const char *str);

private:

    typedef std::vector<char> vecChar;
    vecChar _vc;
};

inline mString::mString(){}
inline mString::mString(const char *str) {

    const vecChar::size_type size = strlen(str);
    _vc = vecChar(str, str + size);
}
inline mString::mString(const mString &str) {

    _vc = str._vc;
}

inline mString mString::operator=(const char *str) {

    const vecChar::size_type size = strlen(str);
    _vc = vecChar(str, str + size);
    return *this;
}

int main(int argc, const char * argv[]) {

    /* This works */
    mString a;
    a = "Hello World";

    /* Error : No viable conversion from 'const char[12]' to mString */
    mString b = "Hello World";

    return 0;
}

I don't understand why 'mString b = "Hello World";' doesn't work while 'mString a; a= "Hello World";' works.
What do I need to do in order to make it work?

Thank you in advance!

Body:
This has nothing common with the assignment operator.

You declared this constructor

explicit mString(const char *str);

with the function specifier explicit.

Thus in this declaration

mString b = "Hello World";

the constructor can not be called to convert the string literal "Hello World"to an object of the type mString.

Remove the function specifier explicit and the declaration will compile.

Or instead of the copy initialization as in the declaration above you could use the direct initialization like

mString b( "Hello World" );

So in this declaration

mString b = "Hello World";

there are used constructors. But in this expression statement

a= "Hello World";

there is indeed used the assignment operator.


问:
How are floating errors handled by the computer
I understand that floating number has their limitations so this can be expected:

```<code>>>> 0.1 + 0.2 == 0.3
False
</code>```

But why is this valid? Computers can't store 0.45, 0.55 reliably either right?

```<code>>>> 0.45 + 0.55 == 1.00
True
</code>```

I want to know how in the first case computer couldn't correct its inaccuracy and in the later one it could.

答:
As you know most decimal numbers can't be stored exactly. That's true for all of your above numbers except 1.0.

But they get stored with a high accuracy. Instead of 0.3, some very close representable number gets used. It's not only very close, it's the closest such number.

When you compute 0.1 + 0.2, then another representable number gets computed, which is also very close to 0.3. You are "unlucky" and it differs from the closest possible representable number.

There's no real luck involved, both 0.1 and 0.2 get represented by a slightly larger number. When added, the two errors add as they're of the same sign and you get something like 0.30000000000000004.

With 0.45 + 0.55, the errors are of different signs and cancel out.

Body:
I understand that floating number has their limitations so this can be expected:

>>> 0.1 + 0.2 == 0.3
False

But why is this valid? Computers can't store 0.45, 0.55 reliably either right?

>>> 0.45 + 0.55 == 1.00
True

I want to know how in the first case computer couldn't correct its inaccuracy and in the later one it could.


问:
Has anyone actually got ASP.NET MVC 5 Identity Facebook logins to work out of the box? (loginInfo always returns null)
Using Visual Studio 2013 Update 5, I have created a boilerplate MVC 5 application with Individual User Accounts auth option selected, and I have been trying to implement social logins using the template code, but have been unsuccessful.

I have ensured all NuGet packages are up to date, and the code is using MVC 5.2.3; Owin 3.0.1; AspNet.Identity 2.0.0.

I can get everything working fine, including authenticator apps using OtpSharp, but the Facebook login is just not working whatever I try.

I have created the Facebook App, set all the relevant options on that and set the AppId and AppSecret in my Startup.Auth.cs file.

When I try to login with Facebook, the MVC site redirects me to Facebook, which prompts me with the auth screen for the app. I click OK and accept this then I am redirected back to the MVC app. If I check the authorised apps under my Facebook account, my app is listed and shows that it has granted permission to the app to retrieve email address.

The callback works fine but when it hits ExternalLoginCallback and in particular:

```<code>var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync()
</code>```

loginInfo always returns null.

Looking at the Request it shows an error of access_denied:

```<code>https://localhost:44301/Account/ExternalLoginCallback?ReturnUrl=%2Fmanage&error=access_denied
</code>```

I have read pretty much every blog post and SO question on this error and whilst most of them are helpful, most are also out of date and not relevant.

It would seem that something is missing from the templated project, or something has changed elsewhere as no matter which tutorial I read, and options I set, the result is the same.

I have tried this internally on a dev machine running IIS Express and externally on a hosted machine running IIS 7.5 too and the results are the same.

I've even decompiled the Microsoft.Owin.Security.Facebook library to see where that particular section of the querystring is set to no help.

If I had any hair I'd have pulled it all out by now.

I'll take any suggestions. Can anyone help?

答:
update the package Owin.Security.Facebook 3.0.1 to 3.1.0

It works for me

Body:
Using Visual Studio 2013 Update 5, I have created a boilerplate MVC 5 application with Individual User Accounts auth option selected, and I have been trying to implement social logins using the template code, but have been unsuccessful.

I have ensured all NuGet packages are up to date, and the code is using MVC 5.2.3; Owin 3.0.1; AspNet.Identity 2.0.0.

I can get everything working fine, including authenticator apps using OtpSharp, but the Facebook login is just not working whatever I try.

I have created the Facebook App, set all the relevant options on that and set the AppId and AppSecret in my Startup.Auth.cs file.

When I try to login with Facebook, the MVC site redirects me to Facebook, which prompts me with the auth screen for the app. I click OK and accept this then I am redirected back to the MVC app. If I check the authorised apps under my Facebook account, my app is listed and shows that it has granted permission to the app to retrieve email address.

The callback works fine but when it hits ExternalLoginCallback and in particular:

var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync()

loginInfo always returns null.

Looking at the Request it shows an error of access_denied:

https://localhost:44301/Account/ExternalLoginCallback?ReturnUrl=%2Fmanage&error=access_denied

I have read pretty much every blog post and SO question on this error and whilst most of them are helpful, most are also out of date and not relevant.

It would seem that something is missing from the templated project, or something has changed elsewhere as no matter which tutorial I read, and options I set, the result is the same.

I have tried this internally on a dev machine running IIS Express and externally on a hosted machine running IIS 7.5 too and the results are the same.

I've even decompiled the Microsoft.Owin.Security.Facebook library to see where that particular section of the querystring is set to no help.

If I had any hair I'd have pulled it all out by now.

I'll take any suggestions. Can anyone help?


问:
How to create and handle custom messages in Xmonad?
I'd like to implement custom messages to be handled by a custom layout.

```<code>data ModifySideContainer = IncrementLeftColumnContainer | IncrementRightColumnContainer deriving Typeable
instance Message ModifySideContainer
</code>```

I'm not too sure how to handle the custom message within pureMessage(https://hackage.haskell.org/package/xmonad-0.13/docs/XMonad-Core.html#v:pureMessage)

This is my current pureMessage implementation (within the custom layout):

```<code>  pureMessage l@(MiddleColumn sr mcc deltaInc _) m = msum [
    fmap resize     (fromMessage m),
    fmap incmastern (fromMessage m)
    ]
    where
      resize Expand = l {splitRatio = (min 0.5 $ sr + deltaInc)}
      resize Shrink = l {splitRatio = (max 0 $ sr - deltaInc)}
      incmastern (IncMasterN x) = l { middleColumnCount = max 0 (mcc+x) }
</code>```

I don't quite understand how this logic works (I've copied it from somewhere), what is msum doing here? I guess I'll know once I find the instance declaration of mplus for Maybe.

答:
Figured it out. You just need to add additional 'layouts' within the list.

Essentially all msum does is get the first Just value and return it for example:
msum [Nothing, Nothing, Just 1, Just 2, Nothing] will return Just 1.

```<code>  pureMessage l@(MiddleColumn sRatio mcc deltaInc _ leftCount rightCount) m = msum [
    fmap resize     (fromMessage m),
    fmap incmastern (fromMessage m),
    fmap incSideContainer (fromMessage m)
    ]
    where
      incSideContainer IncrementLeftColumnContainer = l
        { leftContainerCount = leftCount + 1, rightContainerCount = rightCount - 1}
      incSideContainer IncrementRightColumnContainer = l
        { leftContainerCount = leftCount - 1, rightContainerCount = rightCount + 1}
      resize Expand = l {splitRatio = (min 0.5 $ sRatio + deltaInc)}
      resize Shrink = l {splitRatio = (max 0 $ sRatio - deltaInc)}
      incmastern (IncMasterN x) = l { middleColumnCount = max 0 (mcc+x) }
</code>```

Body:
I'd like to implement custom messages to be handled by a custom layout.

data ModifySideContainer = IncrementLeftColumnContainer | IncrementRightColumnContainer deriving Typeable
instance Message ModifySideContainer

I'm not too sure how to handle the custom message within pureMessage(https://hackage.haskell.org/package/xmonad-0.13/docs/XMonad-Core.html#v:pureMessage)

This is my current pureMessage implementation (within the custom layout):

  pureMessage l@(MiddleColumn sr mcc deltaInc _) m = msum [
    fmap resize     (fromMessage m),
    fmap incmastern (fromMessage m)
    ]
    where
      resize Expand = l {splitRatio = (min 0.5 $ sr + deltaInc)}
      resize Shrink = l {splitRatio = (max 0 $ sr - deltaInc)}
      incmastern (IncMasterN x) = l { middleColumnCount = max 0 (mcc+x) }

I don't quite understand how this logic works (I've copied it from somewhere), what is msum doing here? I guess I'll know once I find the instance declaration of mplus for Maybe.

Body:
Figured it out. You just need to add additional 'layouts' within the list.

Essentially all msum does is get the first Just value and return it for example:
msum [Nothing, Nothing, Just 1, Just 2, Nothing] will return Just 1.

  pureMessage l@(MiddleColumn sRatio mcc deltaInc _ leftCount rightCount) m = msum [
    fmap resize     (fromMessage m),
    fmap incmastern (fromMessage m),
    fmap incSideContainer (fromMessage m)
    ]
    where
      incSideContainer IncrementLeftColumnContainer = l
        { leftContainerCount = leftCount + 1, rightContainerCount = rightCount - 1}
      incSideContainer IncrementRightColumnContainer = l
        { leftContainerCount = leftCount - 1, rightContainerCount = rightCount + 1}
      resize Expand = l {splitRatio = (min 0.5 $ sRatio + deltaInc)}
      resize Shrink = l {splitRatio = (max 0 $ sRatio - deltaInc)}
      incmastern (IncMasterN x) = l { middleColumnCount = max 0 (mcc+x) }


问:
attach role to a user upon registration laravel 5.4
I try to attach one of my roles as default role for users when they register, I tried different ways such as this post  https://linustechtips.com/main/topic/802733-laravel-54-attaching-role-on-registration/ but nothing works:

the role I try to attach to registration form is name => user and id => 3 in case you want to help me with coding

Here is my registration form:

```<code><?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Role;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'fname' => 'required|string|max:255',
            'lname' => 'required|string|max:255',
            'username' => 'required|string|min:4|max:255|unique:users',
            'gender' => 'required',
            'city' => 'sometimes|string|max:255',
            'province' => 'sometimes|string|max:255',
            'country' => 'sometimes|string|max:255',
            'phone' => 'sometimes|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        return User::create([
            'fname' => $data['fname'],
            'lname' => $data['lname'],
            'username' => $data['username'],
            'gender' => $data['gender'],
            'city' => $data['city'],
            'province' => $data['province'],
            'country' => $data['country'],
            'phone' => $data['phone'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }
}
</code>```

Thanks.

答:
Did you use the php artisan make:auth to set up your authentication?

I've added the following to the app\Http\Controllers\Auth\RegisterController.php to assign all users the default role of 'user'

```<code>protected function create(array $data)
{
    $role = Role::where('name', 'user')->first();

    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
    ]);

    $user->assignRole($role);

    return $user;
}
</code>```

And the following in User.php

```<code>public function roles()
{
    return $this->belongsToMany(Role::class);
}

public function assignRole(Role $role)
{
    return $this->roles()->save($role);
}
</code>```

Body:
I try to attach one of my roles as default role for users when they register, I tried different ways such as this post  https://linustechtips.com/main/topic/802733-laravel-54-attaching-role-on-registration/ but nothing works:

the role I try to attach to registration form is name => user and id => 3 in case you want to help me with coding

Here is my registration form:

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Role;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'fname' => 'required|string|max:255',
            'lname' => 'required|string|max:255',
            'username' => 'required|string|min:4|max:255|unique:users',
            'gender' => 'required',
            'city' => 'sometimes|string|max:255',
            'province' => 'sometimes|string|max:255',
            'country' => 'sometimes|string|max:255',
            'phone' => 'sometimes|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        return User::create([
            'fname' => $data['fname'],
            'lname' => $data['lname'],
            'username' => $data['username'],
            'gender' => $data['gender'],
            'city' => $data['city'],
            'province' => $data['province'],
            'country' => $data['country'],
            'phone' => $data['phone'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }
}

Thanks.

Body:
Did you use the php artisan make:auth to set up your authentication?

I've added the following to the app\Http\Controllers\Auth\RegisterController.php to assign all users the default role of 'user'

protected function create(array $data)
{
    $role = Role::where('name', 'user')->first();

    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
    ]);

    $user->assignRole($role);

    return $user;
}

And the following in User.php

public function roles()
{
    return $this->belongsToMany(Role::class);
}

public function assignRole(Role $role)
{
    return $this->roles()->save($role);
}


问:
template v-if="main", not working with return this.$route.path.indexOf('/') === 0 in computed "main"
works with my other routes like "/dashboard", etc, but is appearing in all routes. I basically want this template to only appear when the url is "/". Have tried it throughout my project and just plum doesn't work. PLease help and thank you!! for any suggestions.</p>

```<code><template v-if="main">
  <div id="accordion-nav">
    <div class="accordion-panels">
      <a href="/dashboard">Dashboard <i class="fa fa-caret-right" aria-hidden="true"></i></a>
    </div>
    <div class="accordion-panels">
      <a href="/shifts">Shifts <i class="fa fa-caret-right" aria-hidden="true"></i></a>
    </div>
    <div class="accordion-panels">
      <a href="/other">Other <i class="fa fa-caret-right" aria-hidden="true"></i></a>
    </div>
  </div>
</template>

<script>
export default {
  name: 'accordion-nav',
  computed: {
    main: function () {
      return this.$route.path.indexOf('/') === 0
    }
  }
}
</script>

<style scoped>
</style>
</code>```

答:
Use v-if="main" as a method v-if="main()" instead of a computed property

methods: {
    main: function () {
      return this.$route.path.indexOf('/') === 0
    }

Methods do such complex updates much better than computed properties. Computed = lazy

Body:
works with my other routes like "/dashboard", etc, but is appearing in all routes. I basically want this template to only appear when the url is "/". Have tried it throughout my project and just plum doesn't work. PLease help and thank you!! for any suggestions.

<template v-if="main">

      Dashboard

      Shifts

      Other

</template>


问:
Uicollectionview cell width issue iOS 10
I have a collection view controller and I set up it like this:

```<code>class r : UICollectionViewCell {

    override var bounds: CGRect {
        didSet {
            contentView.frame = bounds
        }
    }
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "1", for: indexPath) as? r

        cell.backgroundColor = UIColor.red

        return cell

    }
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return 5
    }
</code>```

I want that the cell's width is equals to screen's width , for this reason in storyboard I edited cell's width:

but I have a problem :

if I execute it on iPhone 6 simulator I get this(and this is what I want to get on all devices) :

but If execute on iPad Pro I get this :

And I don't understand why.
Can you help me?

P.S I don't want to use tableview for some reasons

答: If u use Constraint so first of all your cell to apply equal width constraint and also storyboard in you should check collection view setting in inspect editor for horizontal and vertical.proper all setting..</p>

Body:
I have a collection view controller and I set up it like this:

class r : UICollectionViewCell {

    override var bounds: CGRect {
        didSet {
            contentView.frame = bounds
        }
    }
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "1", for: indexPath) as? r

        cell.backgroundColor = UIColor.red

        return cell

    }
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return 5
    }

I want that the cell's width is equals to screen's width , for this reason in storyboard I edited cell's width:

but I have a problem :

if I execute it on iPhone 6 simulator I get this(and this is what I want to get on all devices) :

but If execute on iPad Pro I get this :

And I don't understand why.
Can you help me?

P.S I don't want to use tableview for some reasons


问:
Clickable url within facebook social plugin
What is the correct markup for inserting clickable urls/links in the Facebook Social Plugin comments?

I  am not able to find this info in Google, been trying for couple hours now... I even "Binged" it once lol. I know its possible to do since I've seen clickable urls in plugin's comments on many occasions before.

Can someone plz help? Pretty please?

答: You can't insert clickable urls in fb plugin, also facebook doesn't allow google to crawl its content. The reason for that you know better facebook is the big rival to google.</p>


问:
Print PDF duplex
I use PDFBox to print PDF. Faced a problem that some printers do not print duplex if sent to them in PrinterJob Sides.DUPLEX. However, these printers can print duplex if they send them a prepared PCL or PS file. I found here such a link Duplex Printing of PDF document with T&C at the Back  The author creates a third-party ps file and adds a duplex to it. I would like to know if PDFBox can add a duplex directly to the output stream. Or maybe there is some alternative PDFBox, capable of adding duplex when printing.</p>
```<code>import java.awt.print.PrinterJob;
import java.io.File;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.Sides;

import org.apache.pdfbox.pdmodel.PDDocument;

import org.apache.pdfbox.printing.PDFPageable;

public class PrintPDFMain {

    public static void main(String args[]) throws Exception {

        try {
            File file;
            int qty;
            if (args.length < 2) {
                System.out.println("1st param File 2nd param printer name 3rd param qty of copies 4th param duplex (yes/no) \n1st and 2nd params are mandatory");
                return;
            }
            file = new File(args[0]);
            if (!file.exists()) return;
            PDDocument document = PDDocument.load(file);

            PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();

            if (args.length > 2) {

                if (args.length >= 3) {
                    qty = 1;
                    try {
                        qty = Integer.parseInt(args[2]);
                    } catch (NumberFormatException e) {
                        qty = 1;
                    }
                    System.out.println(qty);
                    pras.add(new Copies(qty));
                }
                if (args.length >= 4) {
                    if (args[3].length() == 3) {
                        System.out.println(args[3]);
                        pras.add(Sides.DUPLEX);
                    }
                }
            }

            PrinterJob job = PrinterJob.getPrinterJob();
            job.setPageable(new PDFPageable(document));
            job.print(pras);

            System.out.println("print");
            System.out.println();

        } catch (Exception e) {
            System.out.println("error " + e);
        }
    }

}
</code>```

答: After a thorough check, I found the printer was detected in the system as a model without duplex. After reinstalling the drivers, everything worked.</p>

Title: Print PDF duplex

Body:
I use PDFBox to print PDF. Faced a problem that some printers do not print duplex if sent to them in PrinterJob Sides.DUPLEX. However, these printers can print duplex if they send them a prepared PCL or PS file. I found here such a link Duplex Printing of PDF document with T&C at the Back  The author creates a third-party ps file and adds a duplex to it. I would like to know if PDFBox can add a duplex directly to the output stream. Or maybe there is some alternative PDFBox, capable of adding duplex when printing.

import java.awt.print.PrinterJob;
import java.io.File;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.Sides;

import org.apache.pdfbox.pdmodel.PDDocument;

import org.apache.pdfbox.printing.PDFPageable;

public class PrintPDFMain {

    public static void main(String args[]) throws Exception {

        try {
            File file;
            int qty;
            if (args.length < 2) {
                System.out.println("1st param File 2nd param printer name 3rd param qty of copies 4th param duplex (yes/no) \n1st and 2nd params are mandatory");
                return;
            }
            file = new File(args[0]);
            if (!file.exists()) return;
            PDDocument document = PDDocument.load(file);

            PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();

            if (args.length > 2) {

                if (args.length >= 3) {
                    qty = 1;
                    try {
                        qty = Integer.parseInt(args[2]);
                    } catch (NumberFormatException e) {
                        qty = 1;
                    }
                    System.out.println(qty);
                    pras.add(new Copies(qty));
                }
                if (args.length >= 4) {
                    if (args[3].length() == 3) {
                        System.out.println(args[3]);
                        pras.add(Sides.DUPLEX);
                    }
                }
            }

            PrinterJob job = PrinterJob.getPrinterJob();
            job.setPageable(new PDFPageable(document));
            job.print(pras);

            System.out.println("print");
            System.out.println();

        } catch (Exception e) {
            System.out.println("error " + e);
        }
    }

}


问:
Detect very early crashes
An app I published crashes on certain specific devices. I keep receiving messages from the users that just "can't open" the app. This of course lowers the rating on Google Play.

On Android Vitals there's no reference of these crashes, all crashes I receive are managed and happen after the app start, but if I filter for device model or Android version looking for those that tell me that the app didn't open, I find absolutely NOTHING.

I installed crashlytics, and I was astonished by the fact that I received completely different error communications, so Android Vitals seems just partial?
And anyway, still NOTHING about early crashes.

I tried to install the app on the official Samsung online emulator for some devices that are suspected to crash, and still... guess... NOTHING. So I can't even test it and I'm completely helpless.

How can I do to stop this bad app behaviour, that reduces the number of my happy users? I need a really reliable way to detect ALL crashes.

thank you.

答:
As already mentioned, you can use a crash reporting tool/framework, additionally you should be aware, that offline crashed might not get reported and if the user doesn't allow you to use the internet, there is no way around that, as far as I'm aware.

In the meantime you could try excluding the devices that you suspect to produce crashed while you are trying to fix it (if you care about the rating).

Title: Detect very early crashes


问:
Alarm Manager is not working in Android
I need to setup an Alarm in some interval of times. To achieve it I wrote:

TestFragment class

```<code>private void setupAlarmManager(){
    AlarmManager manager = manager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
    Intent alarmIntent = new Intent(getContext(), AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext(), i, alarmIntent, PendingIntent.FLAG_ONE_SHOT);
    manager.set(AlarmManager.RTC_WAKEUP,1499510100000L, pendingIntent);
    manager.set(AlarmManager.RTC_WAKEUP,1499510220000L, pendingIntent);
}
</code>```

AlarmReceiver class

```<code>public class AlarmReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
}
</code>```

}

I put the debug point at Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show(); but nothing happened.

4PM = 1499510100000L
4:03PM = 1499510220000L

What Am I doing wrong here? Further I want to add a Local notification in onReceive method.

答:
You should use a Calendar object to set up the alarm time.

For an alarm at 4PM you could do something like:

```<code>Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 16);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND,0);
</code>```

Then you set up your AlarmManager as you already did but for the last line use:

```<code>alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
</code>```

Maybe you want to use a repeating Alarm or even a Handler

If so you should visit: https://developer.android.com/training/scheduling/alarms.html

Title: Alarm Manager is not working in Android

Body:
I need to setup an Alarm in some interval of times. To achieve it I wrote:

TestFragment class

private void setupAlarmManager(){
    AlarmManager manager = manager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
    Intent alarmIntent = new Intent(getContext(), AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext(), i, alarmIntent, PendingIntent.FLAG_ONE_SHOT);
    manager.set(AlarmManager.RTC_WAKEUP,1499510100000L, pendingIntent);
    manager.set(AlarmManager.RTC_WAKEUP,1499510220000L, pendingIntent);
}

AlarmReceiver class

public class AlarmReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
}

}

I put the debug point at Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show(); but nothing happened.

4PM = 1499510100000L
4:03PM = 1499510220000L

What Am I doing wrong here? Further I want to add a Local notification in onReceive method.

Body:
You should use a Calendar object to set up the alarm time.

For an alarm at 4PM you could do something like:

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 16);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND,0);

Then you set up your AlarmManager as you already did but for the last line use:

alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

Maybe you want to use a repeating Alarm or even a Handler

If so you should visit: https://developer.android.com/training/scheduling/alarms.html


问:
show post from the same category when you click previous/next button wordpress
I have the below issue. When I click to the previous/next button of the same category unfortunately i receive the previous/next post hronologically instead of the previous/next post of the same category.

Here is the code:

```<code>< div id="previous_post">
< ?php previous_post_link( '%link', __( '<span class="prev"><< Preivous Post</span>', 'esquire' ) ); ? >
< /div>

< div id="next_post">   < ?php next_post_link( '%link', __( '<span class="next">Next Post >></span>',  'esquire' ) ); ? >

< /div>
</code>```

I've tried to fix my problem with this article http://codex.wordpress.org/Function_Reference/next_post_link
but something i am doing wrong.

Any advice please?

答:
Copy the single.php page from your Parent theme and Paste it to your Child-theme's directory. Open the single.php from child-theme directory and add the following code at the end of file [before get_footer(); ]

```<code><?php
$post_id = $post->ID; // Get current post ID
$cat = get_the_category();
$current_cat_id = $cat[0]->cat_ID; // Get current Category ID

$args = array('category'=>$current_cat_id,'orderby'=>'post_date','order'=> 'DESC');
$posts = get_posts($args);
// Get IDs of posts retrieved by get_posts function
$ids = array();
foreach ($posts as $thepost) {
    $ids[] = $thepost->ID;
}
// Get and Echo the Previous and Next post link within same Category
$index = array_search($post->ID, $ids);
$prev_post = $ids[$index-1];
$next_post = $ids[$index+1];
?>

<?php if (!empty($prev_post)){ ?> <a class="previous-post" rel="prev" href="<?php echo get_permalink($prev_post) ?>"> <span class="meta-icon"><i class="fa fa-angle-left fa-lg"></i></span> Previous</a> <?php } ?>

<?php if (!empty($next_post)){ ?> <a class="next-post" rel="next" href="<?php echo get_permalink($next_post) ?>">Next <span class="meta-icon"><i class="fa fa-angle-right fa-lg"></i></span> </a> <?php } ?>
</code>```

After adding this code, paste the following code into your child-theme's Style.css to style the links:

```<code>a.previous-post, a.next-post {
    color: #fff;
    background-color: #4498e7;
    text-align: center;
    height: 34px;
    line-height: 34px;
    font-size: 14px;
    border: 1px solid;
    padding: 0 20px;
    margin-bottom: 30px;
    text-transform: uppercase;
    border-radius: 4px;
    font-weight: bold;
}

a.previous-post:hover, a.next-post:hover {
    color: #4498e7;
    background-color: #fff;
}

a.previous-post {
    float: left !important;
}

a.next-post {
    float: right !important;
}
</code>```

To see these links in actions, visit my website: www.techtutsonline.com

Let me know the results :)

Body:
I have the below issue. When I click to the previous/next button of the same category unfortunately i receive the previous/next post hronologically instead of the previous/next post of the same category.

Here is the code:

< ?php previous_post_link( '%link', __( '<< Preivous Post', 'esquire' ) ); ? >

   < ?php next_post_link( '%link', __( 'Next Post >>',  'esquire' ) ); ? >

I've tried to fix my problem with this article http://codex.wordpress.org/Function_Reference/next_post_link
but something i am doing wrong.

Any advice please?

Body:
Copy the single.php page from your Parent theme and Paste it to your Child-theme's directory. Open the single.php from child-theme directory and add the following code at the end of file [before get_footer(); ]

<?php
$post_id = $post->ID; // Get current post ID
$cat = get_the_category();
$current_cat_id = $cat[0]->cat_ID; // Get current Category ID

$args = array('category'=>$current_cat_id,'orderby'=>'post_date','order'=> 'DESC');
$posts = get_posts($args);
// Get IDs of posts retrieved by get_posts function
$ids = array();
foreach ($posts as $thepost) {
    $ids[] = $thepost->ID;
}
// Get and Echo the Previous and Next post link within same Category
$index = array_search($post->ID, $ids);
$prev_post = $ids[$index-1];
$next_post = $ids[$index+1];
?>

<?php if (!empty($prev_post)){ ?> <a class="previous-post" rel="prev" href="<?php echo get_permalink($prev_post) ?>"> <span class="meta-icon"><i class="fa fa-angle-left fa-lg"></i></span> Previous</a> <?php } ?>

<?php if (!empty($next_post)){ ?> <a class="next-post" rel="next" href="<?php echo get_permalink($next_post) ?>">Next <span class="meta-icon"><i class="fa fa-angle-right fa-lg"></i></span> </a> <?php } ?>

After adding this code, paste the following code into your child-theme's Style.css to style the links:

a.previous-post, a.next-post {
    color: #fff;
    background-color: #4498e7;
    text-align: center;
    height: 34px;
    line-height: 34px;
    font-size: 14px;
    border: 1px solid;
    padding: 0 20px;
    margin-bottom: 30px;
    text-transform: uppercase;
    border-radius: 4px;
    font-weight: bold;
}

a.previous-post:hover, a.next-post:hover {
    color: #4498e7;
    background-color: #fff;
}

a.previous-post {
    float: left !important;
}

a.next-post {
    float: right !important;
}

To see these links in actions, visit my website: www.techtutsonline.com

Let me know the results :)


问:
Deleting the head of doubly linked list
Sorry for such a low quality question but I have no idea why the following code doesn't work.

list points the head of the node.

```<code>void DeleteHeadNode(Node** list, Node * node)
    {
        if ((*list) == node) {
            Node * next = node->nextnode;
            next->prevnode = NULL;
        free(*list);
    }
}
</code>```

答:
The usage of Node** is used as alias. If passed the address of a list variable, one may alter it, by altering the Node* value.

In this way one set the passed list variable to null or to the second node.

The following is a usage pattern.

```<code>void DeleteNode(Node** list, int data)
{
    while (*list != NULL && (*list)->data != data) {
        list = &(node->nextnode);
    }
    if (*list != NULL) {
        Node* found = *list;
        *list = found->nextnode;

        if (found->nextnode != NULL) {
            found->nextnode->prevnode = *list;
        }
        free(found);
    }
}
</code>```

Usage:

```<code>Node* list;
...
DeleteNode(&list, ...);
</code>```

A previous node (prevnode, a double linked list) is not really necessary.

The while loop is of interest: there the alias list is set from the list head to the address of a nextnode field. Hence a subsequent change of *list either changes the passed list variable or some nextnode field.

```<code>void SortedInsertNode(Node** list, int data)
{
    Node* node = (Node*) malloc(sizeof(Node));
    node->data = data;
    node->prevnode = NULL;
    node->nextnode = NULL;
    while (*list != NULL && data >= (*list)->data) {
        node->prevnode = *list;
        list = &(node->nextnode);
    }
    node->nextnode = *list;
    *list = node;

    if (node->nextnode != NULL) {
        node->nextnode->prevnode = *list;
    }
}
</code>```

Deleting the head:

```<code>void DeleteHead(Node** list)
{
    if (*list != null) {
        Node* dead = *list;
        *list = (*list)->nextnode;
        (*list)->prevnede = NULL;
        free(dead);
    }
}
</code>```

Title: Deleting the head of doubly linked list

Body:
Sorry for such a low quality question but I have no idea why the following code doesn't work.

list points the head of the node.

void DeleteHeadNode(Node** list, Node * node)
    {
        if ((*list) == node) {
            Node * next = node->nextnode;
            next->prevnode = NULL;
        free(*list);
    }
}

Body:
The usage of Node** is used as alias. If passed the address of a list variable, one may alter it, by altering the Node* value.

In this way one set the passed list variable to null or to the second node.

The following is a usage pattern.

void DeleteNode(Node** list, int data)
{
    while (*list != NULL && (*list)->data != data) {
        list = &(node->nextnode);
    }
    if (*list != NULL) {
        Node* found = *list;
        *list = found->nextnode;

        if (found->nextnode != NULL) {
            found->nextnode->prevnode = *list;
        }
        free(found);
    }
}

Usage:

Node* list;
...
DeleteNode(&list, ...);

A previous node (prevnode, a double linked list) is not really necessary.

The while loop is of interest: there the alias list is set from the list head to the address of a nextnode field. Hence a subsequent change of *list either changes the passed list variable or some nextnode field.

void SortedInsertNode(Node** list, int data)
{
    Node* node = (Node*) malloc(sizeof(Node));
    node->data = data;
    node->prevnode = NULL;
    node->nextnode = NULL;
    while (*list != NULL && data >= (*list)->data) {
        node->prevnode = *list;
        list = &(node->nextnode);
    }
    node->nextnode = *list;
    *list = node;

    if (node->nextnode != NULL) {
        node->nextnode->prevnode = *list;
    }
}

Deleting the head:

void DeleteHead(Node** list)
{
    if (*list != null) {
        Node* dead = *list;
        *list = (*list)->nextnode;
        (*list)->prevnede = NULL;
        free(dead);
    }
}


问:
Java memory keeps on increasing on running a JavaFX Application
I'm running a JavaFx Application using Netbeans 8.2. When the application is initialised, I click on the application menu to open a file, which pops up the file chooser window. Now, this is where the problem happens. When I look at the memory usage in the System Monitor (on Ubuntu 16.04 LTS), the
java memory usage keeps on increasing (see image) every few seconds until I cancel the file choose window.

I ran the profiler in netbeans to get some insight, but everything seems fine. Even heap usage is within limits. Not sure what the issue is.

Memory Usage Screenshot

答:
Don't worry, it keeps climing up but it eventually gets cleared back down when it does a GC (Garbage Collect). I've noticed that too (also from Netbeans 8.2), which brought me to here.. But then while I was typing, I noticed it drop back down and I was like "Ohhhh, the GC just happened".

It's true JavaFX could probably reuse some objects, but I've noticed for me it doesn't add more than 100MB of RAM, and then collects and resets back down.

You can limit the amount of max RAM you want it to allocate as well so it garbage collects earlier. :)

To set the min/max RAM, go to Project Properties -> Run -> VM Options and put -Xms16M for minimum, and -Xmx400M for maximum.. M/G for Megabyte and Gigabyte..

Example:

-Xms16M -Xmx400M


问:
create a calc spreadsheet containing a list of documents
I need to create a spreadsheet containing a file list. I have a lot of PDF files, ordered like following example:

```<code>"Abbagnano, Nicola - Historia de la Pedagogía.pdf"
"Abbagnano, Nicola - Introduccion Al Existencialismo.pdf"
"Abbagnano, Nicola - La Evolucion de la Dialectica.pdf"
"Adorno, Theodor - Educacion Para la Emancipacion.pdf"
"Adorno, Theodor - Escritos Filosoficos Tempranos.pdf"
etc...
</code>```

I want a list looking like this

```<code>   A        |  B      |   C
Abbagnano | Nicola  | Historia de la Pedagogía
Abbagnano | Nicola  | Introduccion Al Existencialismo
Abbagnano | Nicola  | La Evolucion de la Dialectica
Adorno    | Theodor | Educacion Para la Emancipacion
Adorno    | Theodor | Escritos Filosoficos Tempranos
</code>```

答:
To convert the former into the latter where the former is already in a ColumnA in LibreOffice:

Select ColumnA, Data > Text to Columns, check Comma and add - to Other for Separated by under Separator Options (others unchecked) and Text delimiter ", OK.

Then OK again, select ColumnC and Edit > Find & Replace, Find: .pdf (leave Replace: blank), Replace All, Close. Save As... Text CSV (.csv)(*.csv).

Body:
I need to create a spreadsheet containing a file list. I have a lot of PDF files, ordered like following example:

"Abbagnano, Nicola - Historia de la Pedagogía.pdf"
"Abbagnano, Nicola - Introduccion Al Existencialismo.pdf"
"Abbagnano, Nicola - La Evolucion de la Dialectica.pdf"
"Adorno, Theodor - Educacion Para la Emancipacion.pdf"
"Adorno, Theodor - Escritos Filosoficos Tempranos.pdf"
etc...

I want a list looking like this

   A        |  B      |   C
Abbagnano | Nicola  | Historia de la Pedagogía
Abbagnano | Nicola  | Introduccion Al Existencialismo
Abbagnano | Nicola  | La Evolucion de la Dialectica
Adorno    | Theodor | Educacion Para la Emancipacion
Adorno    | Theodor | Escritos Filosoficos Tempranos


问:
How to exclude a key from an interface in TypeScript
In TypeScript, you can combine two interface types like this

```<code>interface Foo {
    var1: string
}

interface Bar {
    var2: string
}

type Combined = Foo & Bar
</code>```

Instead of combining keys, I want to exclude keys from one interface to another. Is there anyway you can do it in TypeScript?

The reason is, I have an HOC, which manages a property value for other wrapped component like this

```<code>export default function valueHOC<P> (
  Comp: React.ComponentClass<P> | React.StatelessComponent<P>
): React.ComponentClass<P> {
  return class WrappedComponent extends React.Component<P, State> {
    render () {
      return (
        <Comp
          {...this.props}
          value={this.state.value}
        />
      )
    }
}
</code>```

With that I can write

```<code>const ValuedComponent = valueHOC(MyComponent)
</code>```

then

```<code><ValuedComponent />
</code>```

but the problem is, the returned component type is also using the props type from given component, so TypeScript will complain and ask me to provide the value prop. As a result, I will have to write something like

```<code><ValuedComponent value="foo" />
</code>```

Which the value will not be used anyway. What I want here is to return an interface without specific keys, I want to have something like this

```<code>React.ComponentClass<P - {value: string}>
</code>```

Then the value will not be needed in the returned component. Is it possible in TypeScript for now?

答:
You can't remove properties from already existing interfaces. Even trying to extend existing interface with the interface having value property set as optional will return an error.

To avoid this issue, modify the typings of the target component so value property is optional.

e.g.

```<code>// ...
class MyComponent extends React.Component<{value?: string}, State> {
// ...
}
</code>```

and then component produced when using High Order Function

```<code>const valuedComponent = valueHOC(MyComponent);
</code>```

won't ask for value prop.

Body:
In TypeScript, you can combine two interface types like this

interface Foo {
    var1: string
}

interface Bar {
    var2: string
}

type Combined = Foo & Bar

Instead of combining keys, I want to exclude keys from one interface to another. Is there anyway you can do it in TypeScript?

The reason is, I have an HOC, which manages a property value for other wrapped component like this

export default function valueHOC
 (
  Comp: React.ComponentClass
 | React.StatelessComponent

): React.ComponentClass
 {
  return class WrappedComponent extends React.Component
 {
    render () {
      return (
        <Comp
          {...this.props}
          value={this.state.value}
        />
      )
    }
}

With that I can write

const ValuedComponent = valueHOC(MyComponent)

then

<ValuedComponent />

but the problem is, the returned component type is also using the props type from given component, so TypeScript will complain and ask me to provide the value prop. As a result, I will have to write something like

<ValuedComponent value="foo" />

Which the value will not be used anyway. What I want here is to return an interface without specific keys, I want to have something like this

React.ComponentClass

Then the value will not be needed in the returned component. Is it possible in TypeScript for now?

Body:
You can't remove properties from already existing interfaces. Even trying to extend existing interface with the interface having value property set as optional will return an error.

To avoid this issue, modify the typings of the target component so value property is optional.

e.g.

// ...
class MyComponent extends React.Component<{value?: string}, State> {
// ...
}

and then component produced when using High Order Function

const valuedComponent = valueHOC(MyComponent);

won't ask for value prop.


问:
How to group SQL Value if the column is same value
Needed help with SQL, tried for a while and still cant figure it out

MY Create Table

```<code>CREATE TABLE Data
(
    Sender              VARCHAR(255),
    Receiver            VARCHAR(255),
    MSG                 VARCHAR(255),
);
</code>```

After Insert VALUES

```<code>SEND1   REC1    Hey whats up
SEND1   REC2    Yoo how are you
SEND1   REC1    Nothing much
</code>```

What I've been trying to do is to

```<code>Select * FROM DATA WHERE Sender = 'SEND1'
</code>```

However, I just wanted to show the second row and third row, basically if the SENDER and RECEIVER is same as previous row, ignore the previous row and took the last row only and no duplication of the same same SENDER and RECEIVER

Thanks

I am using SQL-SERVER

What I meant is to always take the last row of the same 'Sender' and 'Receiver', the first row and third row has same sender and receiver, so when I select statement, I just want the last one

答:
You could try using the OFFSET clause, to offset (skip) the first message.

```<code>SELECT * FROM Data WHERE Sender = 'SEND1' OFFSET 1;
</code>```

The trouble is you need will an id column or a datetimestamp to ORDER BY so you can guarantee the first message sent is not included.

e.g.

```<code>SELECT
*
FROM Data
WHERE Sender = 'SEND1'
ORDER BY id -- or a datetime column
LIMIT 1000 OFFSET 1;
</code>```

I don't quite understand:

basically if the SENDER and RECEIVER is same as previous row, ignore the previous row and took the last row only and no duplication of the same same SENDER and RECEIVER

But this should cover the case:

I just wanted to show the second row and third row

Body:
Needed help with SQL, tried for a while and still cant figure it out

MY Create Table

CREATE TABLE Data
(
    Sender              VARCHAR(255),
    Receiver            VARCHAR(255),
    MSG                 VARCHAR(255),
);

After Insert VALUES

SEND1   REC1    Hey whats up
SEND1   REC2    Yoo how are you
SEND1   REC1    Nothing much

What I've been trying to do is to

Select * FROM DATA WHERE Sender = 'SEND1'

However, I just wanted to show the second row and third row, basically if the SENDER and RECEIVER is same as previous row, ignore the previous row and took the last row only and no duplication of the same same SENDER and RECEIVER

Thanks

I am using SQL-SERVER

What I meant is to always take the last row of the same 'Sender' and 'Receiver', the first row and third row has same sender and receiver, so when I select statement, I just want the last one

Body:
You could try using the OFFSET clause, to offset (skip) the first message.

SELECT * FROM Data WHERE Sender = 'SEND1' OFFSET 1;

The trouble is you need will an id column or a datetimestamp to ORDER BY so you can guarantee the first message sent is not included.

e.g.

SELECT
*
FROM Data
WHERE Sender = 'SEND1'
ORDER BY id -- or a datetime column
LIMIT 1000 OFFSET 1;

I don't quite understand:

basically if the SENDER and RECEIVER is same as previous row, ignore the previous row and took the last row only and no duplication of the same same SENDER and RECEIVER

But this should cover the case:

I just wanted to show the second row and third row


问:
Python URL get middle string
How to get this string "534641" (this value is dynamic, can be 6,5,4 digits)? How to find "-" before "534641"?

```<code>import re

string = "http://www.test.com.my/white-red-gift-perfume-powerbank-yellow-534641.html?ff=1\u0026s=Ebsr"
m = re.search('-(.+?).html', string).group(1)
print (m)
</code>```

https://repl.it/JSxp

答:
You are almost there. Since what you want is only digits, you could use \d to capture only digits:

```<code>>>> m = re.search('-(\d+).html', string).group(1)
>>> print (m)
534641
</code>```

Another way would be to tell 'all characters excepts -':

```<code>>>> m = re.search('-([^-]+).html', string).group(1)
>>> print (m)
534641
</code>```

For more info, see the doc.

Some quick notes: the .html should be \.html, avoid using names such as 'string', 'list' that are used by python. It could go wrong without knowing why.

Title: Python URL get middle string

Body:
How to get this string "534641" (this value is dynamic, can be 6,5,4 digits)? How to find "-" before "534641"?

import re

string = "http://www.test.com.my/white-red-gift-perfume-powerbank-yellow-534641.html?ff=1\u0026s=Ebsr"
m = re.search('-(.+?).html', string).group(1)
print (m)

https://repl.it/JSxp

Body:
You are almost there. Since what you want is only digits, you could use \d to capture only digits:

>>> m = re.search('-(\d+).html', string).group(1)
>>> print (m)
534641

Another way would be to tell 'all characters excepts -':

>>> m = re.search('-([^-]+).html', string).group(1)
>>> print (m)
534641

For more info, see the doc.

Some quick notes: the .html should be \.html, avoid using names such as 'string', 'list' that are used by python. It could go wrong without knowing why.


问:
is it possible to add images in between the text view in iphone
I'm developing an application. It consists of notes and images also. I'm unable to find the best way of coding to add images and text together.

I want to add the images between the textview and after that, the text has to continue. Is it possible to do like this?

答: You will probably be better to use a webview and load in some static html from the application unless you particularly need textviews, in which case look at holding things in UITableView</p>


问:
python prints folders and sub folders when only folders needed in python
I am making a program that prints all the folders over 90 days in python.

Here is my code:

```<code>import os
from datetime import date
from Tkinter import *
import Tkinter, Tkconstants, tkFileDialog

old_dirs = []
today = date.today()

home1 = os.path.join(os.environ["HOMEPATH"], "Desktop")
desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')

root = Tk()
root.withdraw()
path = tkFileDialog.askdirectory(initialdir=desktop, title="Select folder to
scan from: ")
path = path.encode('utf-8')

for root, dirs, files in os.walk(path):
    for name in dirs:
        filedate = date.fromtimestamp(os.path.getmtime(os.path.join(root, name)))
        if (today - filedate).days > 90:
            print name
            old_dirs.append(name)
</code>```

The problem is that this prints all folders, but it also prints the sub folders of the folders, which I don't need. How can I change the code so that it only prints the folders?

答:
Just break after printing the dirs:

```<code>for root, dirs, files in os.walk(path):
    for name in dirs:
        filedate = date.fromtimestamp(os.path.getmtime(os.path.join(root, name)))
        if (today - filedate).days > 90:
            print name
            old_dirs.append(name)
    break
</code>```

Or look into using os.listdir(), that doesn't recurse into the subdirectories (but you'll have to check for non-directories in the result).

Body:
I am making a program that prints all the folders over 90 days in python.

Here is my code:

import os
from datetime import date
from Tkinter import *
import Tkinter, Tkconstants, tkFileDialog

old_dirs = []
today = date.today()

home1 = os.path.join(os.environ["HOMEPATH"], "Desktop")
desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')

root = Tk()
root.withdraw()
path = tkFileDialog.askdirectory(initialdir=desktop, title="Select folder to
scan from: ")
path = path.encode('utf-8')

for root, dirs, files in os.walk(path):
    for name in dirs:
        filedate = date.fromtimestamp(os.path.getmtime(os.path.join(root, name)))
        if (today - filedate).days > 90:
            print name
            old_dirs.append(name)

The problem is that this prints all folders, but it also prints the sub folders of the folders, which I don't need. How can I change the code so that it only prints the folders?

Body:
Just break after printing the dirs:

for root, dirs, files in os.walk(path):
    for name in dirs:
        filedate = date.fromtimestamp(os.path.getmtime(os.path.join(root, name)))
        if (today - filedate).days > 90:
            print name
            old_dirs.append(name)
    break

Or look into using os.listdir(), that doesn't recurse into the subdirectories (but you'll have to check for non-directories in the result).


答:
```<code>(root, dirs, files) = next(os.walk(path))
for name in dirs:
</code>```

or alternatively use os.listdir

Title: python prints folders and sub folders when only folders needed in python

Body:
(root, dirs, files) = next(os.walk(path))
for name in dirs:

or alternatively use os.listdir


问:
Alternative for Math.round()
In JavaScript when value is 4.3, i want it to round off to 4 and if value is 4.5 or above it rounds off to 5. I want all this without using Math.round().

答:
You can do this

function RoundNum(number){
    var c = number % 1;
    return number-c+(c/1+1.5>>1)*1
}

console.log(RoundNum(2.456));
console.log(RoundNum(102.6));
console.log(RoundNum(203.515));```

Title: Alternative for Math.round()


问:
Is there a way to change node text in bootstrap treeview?
Is there a way to change node text in bootstrap treeview without redrawing the whole tree or removing/adding the node?

I checked here: https://github.com/jonmiles/bootstrap-treeview and here: https://github.com/patternfly/patternfly-bootstrap-treeview but there seem to be no method like "updateNode" or "renameNode".

答:
Simply select the node and update its parameters - </p>

```<code>node = $('#tree').treeview('getNode', <nodeId>);
node.text = '<new value>';
$('#tree').treeview(true).removeNode([]); // refresh hack available in the development github branch.
</code>```

Body:
Simply select the node and update its parameters -

node = $('#tree').treeview('getNode', <nodeId>);
node.text = '<new value>';
$('#tree').treeview(true).removeNode([]); // refresh hack available in the development github branch.


问:
What is the difference between resources and map.resources in Rails
I have been using both of them for a while so I am just curious what is their difference?</p>

答: resources is the new DSL in Rails 3 and replace map.resources from Rails 2</p>