问:
How could i make a div with rounded borders and make the fa icons inside it centered?
So i want a div with rounded borders (to make a circle) and inside that i want my fa icons which would be aligned to the middle.

So basically i want a Circle containing an fa icon in the middle just to make it simple.

.normal-page {
  padding-top: 30px;
}

body .normal-page {
  z-index: 998;
  position: relative;
  padding-bottom: 10px;
  background: url(../images/tpbg.jpg) top center no-repeat #141416;
  border: 1px solid #000;
  border-top: 0;
  min-height: 500px;
}

.container {
  padding-right: 15px;
  padding-left: 15px;
  margin-right: auto;
  margin-left: auto;
}

.vote-container {
  text-align: center;
  padding-left: 30px;
  padding-right: 30px;
  color: #fff;
}

.vote-fa {
  color: #ff8800;
  margin-bottom: 20px;
}

.vote-container a {
  cursor: pointer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="normal-page">
  <div class="container">
    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <i class="fa fa-handshake-o fa-3x vote-fa" aria-hidden="true"></i>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          Click here to vote!
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <i class="fa fa-superpowers fa-3x vote-fa" aria-hidden="true"></i>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          Click here to vote!
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <i class="fa fa-superpowers fa-3x vote-fa" aria-hidden="true"></i>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          Click here to vote!
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <i class="fa fa-superpowers fa-3x vote-fa" aria-hidden="true"></i>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          Click here to vote!
        </div>
      </div>
    </div>
  </div>
</div></code>```

答:
Don't use Font Awesome class "3x" because it doesn't fit always well if it has to work with other code.
Put icons inside a div with rounded corners and set a line-height equal to div height, then you can set font-size here (just put 3em like fa-3x does).

.normal-page {
  padding-top: 30px;
}

body .normal-page {
  z-index: 998;
  position: relative;
  padding-bottom: 10px;
  background: url(../images/tpbg.jpg) top center no-repeat #141416;
  border: 1px solid #000;
  border-top: 0;
  min-height: 500px;
}

.container {
  padding-right: 15px;
  padding-left: 15px;
  margin-right: auto;
  margin-left: auto;
}

.vote-container {
  text-align: center;
  padding-left: 30px;
  padding-right: 30px;
  color: #fff;
}

.vote-fa {
  color: #ff8800;
}

.vote-container a {
  cursor: pointer;
}

.circle {
    width: 70px;
    height: 70px;
    line-height: 70px;
    text-align: center;
    border-radius: 35px;
    background: #fff;
    margin-bottom: 20px;
    font-size: 3em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="normal-page">
  <div class="container">
    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <div class="circle"><i class="fa fa-handshake-o vote-fa" aria-hidden="true"></i></div>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          Click here to vote!
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <div class="circle"><i class="fa fa-superpowers vote-fa" aria-hidden="true"></i></div>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          Click here to vote!
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <div class="circle"><i class="fa fa-superpowers vote-fa" aria-hidden="true"></i></div>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          Click here to vote!
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <div class="circle"><i class="fa fa-superpowers vote-fa" aria-hidden="true"></i></div>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          Click here to vote!
        </div>
      </div>
    </div>
  </div>
</div></code>```

Body:
So i want a div with rounded borders (to make a circle) and inside that i want my fa icons which would be aligned to the middle.

So basically i want a Circle containing an fa icon in the middle just to make it simple.

.normal-page {
  padding-top: 30px;
}

body .normal-page {
  z-index: 998;
  position: relative;
  padding-bottom: 10px;
  background: url(../images/tpbg.jpg) top center no-repeat #141416;
  border: 1px solid #000;
  border-top: 0;
  min-height: 500px;
}

.container {
  padding-right: 15px;
  padding-left: 15px;
  margin-right: auto;
  margin-left: auto;
}

.vote-container {
  text-align: center;
  padding-left: 30px;
  padding-right: 30px;
  color: #fff;
}

.vote-fa {
  color: #ff8800;
  margin-bottom: 20px;
}

.vote-container a {
  cursor: pointer;
}

<link href="https://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.

          Click here to vote!

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.

          Click here to vote!

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.

          Click here to vote!

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.

          Click here to vote!

Body:
Don't use Font Awesome class "3x" because it doesn't fit always well if it has to work with other code.
Put icons inside a div with rounded corners and set a line-height equal to div height, then you can set font-size here (just put 3em like fa-3x does).

.normal-page {
  padding-top: 30px;
}

body .normal-page {
  z-index: 998;
  position: relative;
  padding-bottom: 10px;
  background: url(../images/tpbg.jpg) top center no-repeat #141416;
  border: 1px solid #000;
  border-top: 0;
  min-height: 500px;
}

.container {
  padding-right: 15px;
  padding-left: 15px;
  margin-right: auto;
  margin-left: auto;
}

.vote-container {
  text-align: center;
  padding-left: 30px;
  padding-right: 30px;
  color: #fff;
}

.vote-fa {
  color: #ff8800;
}

.vote-container a {
  cursor: pointer;
}

.circle {
    width: 70px;
    height: 70px;
    line-height: 70px;
    text-align: center;
    border-radius: 35px;
    background: #fff;
    margin-bottom: 20px;
    font-size: 3em;
}

<link href="https://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="normal-page">
  <div class="container">
    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <div class="circle"><i class="fa fa-handshake-o vote-fa" aria-hidden="true"></i></div>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          <a href="#">Click here to vote!</a>
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <div class="circle"><i class="fa fa-superpowers vote-fa" aria-hidden="true"></i></div>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          <a href="#">Click here to vote!</a>
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <div class="circle"><i class="fa fa-superpowers vote-fa" aria-hidden="true"></i></div>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          <a href="#">Click here to vote!</a>
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <div class="circle"><i class="fa fa-superpowers vote-fa" aria-hidden="true"></i></div>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          <a href="#">Click here to vote!</a>
        </div>
      </div>
    </div>
  </div>
</div>


来源: stackexchange

问:
Customizing Doxygen html output
We have a function header format that we have to follow.  It basically looks like this

```<code>/**
* Name: blah
*
* Parameters:
*       int foo
*       bool bar
*
* .....
</code>```

We are attempting to generate some documents with doxygen, but one issue is that when we change he code to:

```<code>/**
* Name: blah
*
* Parameters:
*  \param  int foo
*  \param  bool bar
*
* .....
</code>```

When Doxygen generates the html comments, it adds the Parameters title.  We are required to have line 4, so this creates documents with 2 lines that say Parameters, the first is from line 4 and the second Doxygen auto inserts.

What I'm hoping I can do is either have Doxygen ignore line 4 or add have it not insert it's own "Parameters:" title.  Anyone know if this is possible?

答:
The simple solution is to remove the "Parameters:" text altogether; it is entirely redundant since the Doxygen mark-up makes it perfectly clear that they are parameters!

For that matter the "Name:" label is entirely redundant too, and forces you to place the name in both the comment and the code.  Why would you need that? It's name is right there in the code.  It is an unnecessary comment maintenance headache, and Doxygen will use teh name in the code not the name in the comment in the generated documentation.

If you must attempt to mix your existing format with a Doxygen compatible format it would be easier to use C++/C99 line comments rather than block comments; most C compilers support them:

```<code>// Name: blah
//
// Parameters:
/// \param  foo Description of foo
/// \param  bar Description of bar
</code>```

Note \param <type> <name> is not correct Doxygen syntax; it is \param <name> <description>.  Doxygen gets the type from the code; again specifying the type in the comment is entirely redundant, and another maintenance headache.

I would strongly suggest that you employ a more Doxygen and maintenance friendly function boiler-plate altogether.  I use the following basic form (for what its worth):

```<code>//! @brief  Brief description
//!
//! Full description if necessary.
//! @param p1    p1 description
//! @param p2    p2 description
//! @return Return value description
int foobar( int p1, int p2 ) ;
</code>```

Obviously whether you use /// or //! and \ or @ is a matter of preference.

ContentLicense: CC BY-SA 2.5

Title: Customizing Doxygen html output

Body:
We have a function header format that we have to follow.  It basically looks like this

/**
* Name: blah
*
* Parameters:
*       int foo
*       bool bar
*
* .....

We are attempting to generate some documents with doxygen, but one issue is that when we change he code to:

/**
* Name: blah
*
* Parameters:
*  \param  int foo
*  \param  bool bar
*
* .....

When Doxygen generates the html comments, it adds the Parameters title.  We are required to have line 4, so this creates documents with 2 lines that say Parameters, the first is from line 4 and the second Doxygen auto inserts.

What I'm hoping I can do is either have Doxygen ignore line 4 or add have it not insert it's own "Parameters:" title.  Anyone know if this is possible?

Body:
The simple solution is to remove the "Parameters:" text altogether; it is entirely redundant since the Doxygen mark-up makes it perfectly clear that they are parameters!

For that matter the "Name:" label is entirely redundant too, and forces you to place the name in both the comment and the code.  Why would you need that? It's name is right there in the code.  It is an unnecessary comment maintenance headache, and Doxygen will use teh name in the code not the name in the comment in the generated documentation.

If you must attempt to mix your existing format with a Doxygen compatible format it would be easier to use C++/C99 line comments rather than block comments; most C compilers support them:

// Name: blah
//
// Parameters:
/// \param  foo Description of foo
/// \param  bar Description of bar

Note \param <type> <name> is not correct Doxygen syntax; it is \param <name> <description>.  Doxygen gets the type from the code; again specifying the type in the comment is entirely redundant, and another maintenance headache.

I would strongly suggest that you employ a more Doxygen and maintenance friendly function boiler-plate altogether.  I use the following basic form (for what its worth):

//! @brief  Brief description
//!
//! Full description if necessary.
//! @param p1    p1 description
//! @param p2    p2 description
//! @return Return value description
int foobar( int p1, int p2 ) ;

Obviously whether you use /// or //! and \ or @ is a matter of preference.


问:
Android: Do something when checkBox is checked
I have created custom adapter and two layouts files
the first layout is fragment view which contains  ListView and Button

the second layout contains items which will be represented in the ListView

So

I want when the Checkbox is check make Button visible

All of these operations will be done in my custom adapter class

This is myCustom Adapter

Updated

```<code>public class LampControllerAdapter extends BaseAdapter {
Context mContext;
List<LampModel> mLampModels;
HashMap<Long,LampModel> selection;
Button sC;

  public LampControllerAdapter(Context context, ArrayList<LampModel> lampList) {

    mContext = context;
    mLampModels = lampList;
    selection = new HashMap<Long,LampModel>();
    LayoutInflater in = (LayoutInflater) LayoutInflater.from(context);

    View v = in.inflate(R.layout.fragment_home,null);
   sC = (Button)v.findViewById(R.id.selection_control);

}

@Override
public int getCount() {
    return mLampModels.size();
}

@Override
public Object getItem(int i) {
    return mLampModels.get(i);
}

@Override
public long getItemId(int i) {
    return 0;
}

@Override
public View getView(final int i, View view, ViewGroup parent) {

    ViewHolder holder;
    final LampModel model = (LampModel) getItem(i);
    if (view == null) {
        // Inflating The Layout
        LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
        view = inflater.inflate(R.layout.lamp_controller_item, parent, false);
        holder = new ViewHolder();

        holder.name = (TextView) view.findViewById(R.id.lamp_item_name);
        holder.description = (TextView) view.findViewById(R.id.lamp_item_description);
        holder.select = (CheckBox) view.findViewById(R.id.lamp_item_select);
        view.setTag(holder);

    } else {
        holder = (ViewHolder) view.getTag();
    }

    holder.name.setText(model.getName());
    holder.description.setText(model.getDescription());
    holder.select.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

            if(b){
                selection.put(model.getId(),model);
            }else {
                selection.remove(model.getId());
            }

            if(selection.size() > 0){
                Toast.makeText(mContext, "Not Empty", Toast.LENGTH_SHORT).show();
                sC.setVisibility(View.GONE);
            }else {
                Toast.makeText(mContext, "Empty", Toast.LENGTH_SHORT).show();
            }

        }
    });

    return view;
}

class ViewHolder {
    TextView name, description;
    CheckBox select;
    Switch aSwitch;
}
</code>```

}

答:
try this    </p>

```<code>CheckBox chkBox = ( CheckBox ) findViewById( R.id.chkBox );
chkBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
    {
        if ( isChecked )
        {
            // perform your action here
        }

    }
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have created custom adapter and two layouts files
the first layout is fragment view which contains  ListView and Button

the second layout contains items which will be represented in the ListView

So

I want when the Checkbox is check make Button visible

All of these operations will be done in my custom adapter class

This is myCustom Adapter

Updated

public class LampControllerAdapter extends BaseAdapter {
Context mContext;
List<LampModel> mLampModels;
HashMap<Long,LampModel> selection;
Button sC;

  public LampControllerAdapter(Context context, ArrayList<LampModel> lampList) {

    mContext = context;
    mLampModels = lampList;
    selection = new HashMap<Long,LampModel>();
    LayoutInflater in = (LayoutInflater) LayoutInflater.from(context);

    View v = in.inflate(R.layout.fragment_home,null);
   sC = (Button)v.findViewById(R.id.selection_control);

}

@Override
public int getCount() {
    return mLampModels.size();
}

@Override
public Object getItem(int i) {
    return mLampModels.get(i);
}

@Override
public long getItemId(int i) {
    return 0;
}

@Override
public View getView(final int i, View view, ViewGroup parent) {

    ViewHolder holder;
    final LampModel model = (LampModel) getItem(i);
    if (view == null) {
        // Inflating The Layout
        LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
        view = inflater.inflate(R.layout.lamp_controller_item, parent, false);
        holder = new ViewHolder();

        holder.name = (TextView) view.findViewById(R.id.lamp_item_name);
        holder.description = (TextView) view.findViewById(R.id.lamp_item_description);
        holder.select = (CheckBox) view.findViewById(R.id.lamp_item_select);
        view.setTag(holder);

    } else {
        holder = (ViewHolder) view.getTag();
    }

    holder.name.setText(model.getName());
    holder.description.setText(model.getDescription());
    holder.select.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

            if(b){
                selection.put(model.getId(),model);
            }else {
                selection.remove(model.getId());
            }

            if(selection.size() > 0){
                Toast.makeText(mContext, "Not Empty", Toast.LENGTH_SHORT).show();
                sC.setVisibility(View.GONE);
            }else {
                Toast.makeText(mContext, "Empty", Toast.LENGTH_SHORT).show();
            }

        }
    });

    return view;
}

class ViewHolder {
    TextView name, description;
    CheckBox select;
    Switch aSwitch;
}

}

Body:
try this

CheckBox chkBox = ( CheckBox ) findViewById( R.id.chkBox );
chkBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
    {
        if ( isChecked )
        {
            // perform your action here
        }

    }
});


问:
PHP Fibonacci Sequence
This php method is suppose to print the Fibonacci sequence up to a specified value using a for loop. I am unsure why it does not work?</p>

```<code><?php
function fib ($n) { // a function called fib, declaire variable n (the sequence number)
    for ($n=0;$n<30;$n++) {
        if ($n < 3) { return $n; } // if n is smaller than 3 return n (1 or 2)
        else { return fib ($n - 1) + fib ($n - 2); }
    /* if the number is 3 or above do 2 sums (n-1) and (n-2)
    and then add the 2 sums together (n-1)+(n-2)
    Example Fibonacci number 4
    (4-1)+(4-2) = 5
    3 + 2 = 5
    */
}
print $n;
?>
</code>```

答:
This page did it well. You may check it for a references. Thanks!

```<code><?php

function printFibonacci($n)
{

  $first = 0;
  $second = 1;

  echo "Fibonacci Series \n";

  echo $first.' '.$second.' ';

  for($i = 2; $i < $n; $i++){

    $third = $first + $second;

    echo $third.' ';

    $first = $second;
    $second = $third;

  }
}

/* Function call to print Fibonacci series upto 6 numbers. */

printFibonacci(6);

?>
</code>```

Or

```<code><?php

define('NUM',11);
$a = 0;
$b = 1;

echo "$a $b "; // 0 1

for($i=1   ; $i<= NUM-2 ;  $a=$b, $b=$c, $i++ )
{
  echo $c = $a+$b;
  echo " ";
}

?>
</code>```

Title: PHP Fibonacci Sequence

Body:
This php method is suppose to print the Fibonacci sequence up to a specified value using a for loop. I am unsure why it does not work?

<?php
function fib ($n) { // a function called fib, declaire variable n (the sequence number)
    for ($n=0;$n<30;$n++) {
        if ($n < 3) { return $n; } // if n is smaller than 3 return n (1 or 2)
        else { return fib ($n - 1) + fib ($n - 2); }
    /* if the number is 3 or above do 2 sums (n-1) and (n-2)
    and then add the 2 sums together (n-1)+(n-2)
    Example Fibonacci number 4
    (4-1)+(4-2) = 5
    3 + 2 = 5
    */
}
print $n;
?>

Body:
This page did it well. You may check it for a references. Thanks!

<?php

function printFibonacci($n)
{

  $first = 0;
  $second = 1;

  echo "Fibonacci Series \n";

  echo $first.' '.$second.' ';

  for($i = 2; $i < $n; $i++){

    $third = $first + $second;

    echo $third.' ';

    $first = $second;
    $second = $third;

  }
}

/* Function call to print Fibonacci series upto 6 numbers. */

printFibonacci(6);

?>

Or

<?php

define('NUM',11);
$a = 0;
$b = 1;

echo "$a $b "; // 0 1

for($i=1   ; $i<= NUM-2 ;  $a=$b, $b=$c, $i++ )
{
  echo $c = $a+$b;
  echo " ";
}

?>


问:
Exporting Form INSERT Queries from Microsoft Access 2007 to MySQL
I have inherited a MS Access DB (2007) which I am converting into a MySQL database. I have exported all the custom queries with no issues. But I cannot find the form INSERT query.

The DB has a form which contains sub-forms. There is one submit button which onclick validates the form and then calls acCmdSaveRecord which presumably inserts the record into the database.

Because the database schema is a moderately complex RDB I want to be able to view or export the INSERT query Access runs when saving a record so I can convert it to MySQL.

Is this possible and if so how would I do it?

答:
You can't. That is done by Access behind the scene when using a bound form.

If you link the table from MySQL and bind your (sub)forms to the updated tables and views, the forms will still read and write your data.


问:
How to implement unit tests on IEqualityComparer?
I have a class and a comparer for this class that implements IEqualityComparer:

```<code>class Foo
{
    public int Int { get; set; }
    public string Str { get; set; }

    public Foo(int i, string s)
    {
        Int = i;
        Str = s;
    }

    private sealed class FooEqualityComparer : IEqualityComparer<Foo>
    {
        public bool Equals(Foo x, Foo y)
        {
            if (ReferenceEquals(x, y)) return true;
            if (ReferenceEquals(x, null)) return false;
            if (ReferenceEquals(y, null)) return false;
            if (x.GetType() != y.GetType()) return false;
            return x.Int == y.Int && string.Equals(x.Str, y.Str);
        }

        public int GetHashCode(Foo obj)
        {
            unchecked
            {
                return (obj.Int * 397) ^ (obj.Str != null ? obj.Str.GetHashCode() : 0);
            }
        }
    }

    public static IEqualityComparer<Foo> Comparer { get; } = new FooEqualityComparer();
}
</code>```

The two methods Equals and GetHashCode are used for example in List.Except via an instance of the comparer.

My question is: how to implement properly unit tests on this comparer? I want to detect if someone adds a public property in Foo without modifying the comparer, because in this case the comparer becomes invalid.

If I do something like:

```<code>Assert.That(new Foo(42, "answer"), Is.EqualTo(new Foo(42, "answer")));
</code>```

This cannot detect that a new property was added, and that this property differs in the two objects.

Is there any way to do this?

If it is possible, can we add an attribute to a property to say that this property is not relevant in the comparison?

答:
Basically you could check all the properties you want to check in Equals via reflection. To filter some of them out use an attribute on those properties:

```<code>class Foo
{
    [MyAttribute]
    public string IgnoredProperty { get; set; }
    public string MyProperty { get; set; }
}
</code>```

Now in your comparer check for that specific attribute. Afterwards compare every property that is contained in the remaining list via PropertyInfo.GetValue

```<code>class MyComparer : IEqualityComparer<Foo>
{
    public bool Equals(Foo x, Foo y)
    {
        var properties = this.GetType().GetProperties()
                .Where(x => "Attribute.IsDefined(x, typeof(MyAttribute));
        var equal = true;
        foreach(var p in properties)
           equal &= p.GetValue(x, null) == p.GetValue(y, null);
        return equal;
    }
}
</code>```

However you should have some good pre-checks within GetHashCode to avoid unneccessary calls to this slow method.

EDIT: As you´ve mentioned ReSharper, I assume as you provide the actual properties to be validated at runtime even R# doesn´t know a good way to implement GetHashCode. You will need some properties that will allways be available on your type and that provide a good enough idea of what might be considered equal. All theadditional properties however should only go into the expensive Equals-method.

EDIT2: As mentioned in the comments doing reflection within Equals or even GetHashCode is a bad idea as it´s usually quite slow and can often be avoided. If you know the properties to be checked for eqality at compile-time you should definitly include them within those two methods as doing so gives you much more safety. When you find yourself really to need this because you have to many properties you probably have some basic problem as your class is doing too much.

Body:
I have a class and a comparer for this class that implements IEqualityComparer:

class Foo
{
    public int Int { get; set; }
    public string Str { get; set; }

    public Foo(int i, string s)
    {
        Int = i;
        Str = s;
    }

    private sealed class FooEqualityComparer : IEqualityComparer<Foo>
    {
        public bool Equals(Foo x, Foo y)
        {
            if (ReferenceEquals(x, y)) return true;
            if (ReferenceEquals(x, null)) return false;
            if (ReferenceEquals(y, null)) return false;
            if (x.GetType() != y.GetType()) return false;
            return x.Int == y.Int && string.Equals(x.Str, y.Str);
        }

        public int GetHashCode(Foo obj)
        {
            unchecked
            {
                return (obj.Int * 397) ^ (obj.Str != null ? obj.Str.GetHashCode() : 0);
            }
        }
    }

    public static IEqualityComparer<Foo> Comparer { get; } = new FooEqualityComparer();
}

The two methods Equals and GetHashCode are used for example in List.Except via an instance of the comparer.

My question is: how to implement properly unit tests on this comparer? I want to detect if someone adds a public property in Foo without modifying the comparer, because in this case the comparer becomes invalid.

If I do something like:

Assert.That(new Foo(42, "answer"), Is.EqualTo(new Foo(42, "answer")));

This cannot detect that a new property was added, and that this property differs in the two objects.

Is there any way to do this?

If it is possible, can we add an attribute to a property to say that this property is not relevant in the comparison?

Body:
Basically you could check all the properties you want to check in Equals via reflection. To filter some of them out use an attribute on those properties:

class Foo
{
    [MyAttribute]
    public string IgnoredProperty { get; set; }
    public string MyProperty { get; set; }
}

Now in your comparer check for that specific attribute. Afterwards compare every property that is contained in the remaining list via PropertyInfo.GetValue

class MyComparer : IEqualityComparer<Foo>
{
    public bool Equals(Foo x, Foo y)
    {
        var properties = this.GetType().GetProperties()
                .Where(x => "Attribute.IsDefined(x, typeof(MyAttribute));
        var equal = true;
        foreach(var p in properties)
           equal &= p.GetValue(x, null) == p.GetValue(y, null);
        return equal;
    }
}

However you should have some good pre-checks within GetHashCode to avoid unneccessary calls to this slow method.

EDIT: As you´ve mentioned ReSharper, I assume as you provide the actual properties to be validated at runtime even R# doesn´t know a good way to implement GetHashCode. You will need some properties that will allways be available on your type and that provide a good enough idea of what might be considered equal. All theadditional properties however should only go into the expensive Equals-method.

EDIT2: As mentioned in the comments doing reflection within Equals or even GetHashCode is a bad idea as it´s usually quite slow and can often be avoided. If you know the properties to be checked for eqality at compile-time you should definitly include them within those two methods as doing so gives you much more safety. When you find yourself really to need this because you have to many properties you probably have some basic problem as your class is doing too much.


问:
Failed to upload a object to S3 using signed URL
I have generated signed url using latest aws cli tool. But when i put a object using curl i got signature does not match error.

curl command i used

curl -v -H "content-type:application/vnd.ms-excel" -T users.csv  "https://a054.s3.amazonaws.com/upload/users.csv?AWSAccessKeyId=AKIAJ6U4CWQNUWMWSQ7Q&Expires=1499336527&Signature=gO57XqNKJ%2FmlkHDVXsL0i6Ul2CE%3D"

The error i got

<Error>SignatureDoesNotMatch<Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message><AWSAccessKeyId>AKIAJ6U4CWQNUWMWSQ7Q</AWSAccessKeyId>

Should we use same key name when we upload the object.

Any help would be greatly appreciated.

答:
Unfortunately from my experience that error doesn't tell you very much.

I had a similar issue a couple of weeks ago and resolved it by passing a 'Host' key in the header. See My AWS v4 Authorization Post.

I found that if I tred o do the operation in Postman the correct signature got generated so I was able to look at what was passed in the header and include that in my code. You may want to try this. Other than that, all I can suggest is a trial and error approach. Also, AWS has some good documentation explaining how the signature is generated. Perhaps you can look through it and work out whats missing.


问:
Good Database Solutions for small-medium Traffic Sites and Silverlight
What are some good database solutions that support Silverlight and are solid for a small-medium traffic website

Easy to use/Manage is a very strong plus

edit: Forgot to mention that the database needs to be very smartphone-friendly, it needs to be able to work with devices on iOS, Android, and Windows Phone 7

答: SQL Server Express is a pretty obvious choice. Integrates very well, tons of first class documentation, very reliable, good management studio, upgradeable to more powerful versions etc.</p>


问:
Purpose of char a[0] in converting integer to string using itoa()
I have this code,

```<code>char a[0];
cout << "What is a? " << a << endl;
char *word = itoa(123,a,10);
string yr = string(word);
</code>```

but i have trouble comprehending the array a[0]. I tried to change its value and see if there is any changes, but it seems to make no differences at all.

example, even if a change a[0] to a[1], or any other integer, the output still make no difference

```<code>char a[1];
cout << "What is a? " << a << endl;
char *word = itoa(123,a,10);
string yr = string(word);
</code>```

What is its purpose here?

答:
Since itoa function is non-standard, this is a discussion of a popular signature itoa(int, char*, int).

Second parameter represents a buffer into which a null-terminated string representing the value is copied. It must provide enough space for the entire string: in your case, that is "123", which takes four characters. Your code passes a[] as the buffer, but the size of a[] is insufficient to accommodate the entire "123" string. Hence, the call causes undefined behavior.

You need to make a large enough to fit the destination string. Passing a buffer of size 12 is sufficient to accommodate the longest decimal number that can be produced by itoa on a 32-bit system (i.e. -2147483648). Replace char a[0] with char a[12] in the declaration.

Body:
I have this code,

char a[0];
cout << "What is a? " << a << endl;
char *word = itoa(123,a,10);
string yr = string(word);

but i have trouble comprehending the array a[0]. I tried to change its value and see if there is any changes, but it seems to make no differences at all.

example, even if a change a[0] to a[1], or any other integer, the output still make no difference

char a[1];
cout << "What is a? " << a << endl;
char *word = itoa(123,a,10);
string yr = string(word);

What is its purpose here?


问:
How can i add a second argument on Jsoup getImages method
I'm using the method below to retrieve images from a website,and i want to add a unique id to each image.

How can i do that.

```<code>private static void getImages(String src) throws IOException {
    String folder = null;

    //Exctract the name of the image from the src attribute
    int indexname = src.lastIndexOf("/");
    if (indexname == src.length()) {
        src = src.substring(1, indexname);
    }

    indexname = src.lastIndexOf("/");
    String name = src.substring(indexname, src.length());
    System.out.println(name);

    //Open a URL Stream
    URL url = new URL(src);
    InputStream in = url.openStream();

    OutputStream out = new BufferedOutputStream(new FileOutputStream( folderPath+ name));
    for (int b; (b = in.read()) != -1;) {
        out.write(b);
    }
    out.close();
    in.close();
}
</code>```

答:
I found the awnser :</p>

```<code>private static void getImages(String src,String UrName) throws IOException {
    String folder = "Folder url";

    //Exctract the name of the image from the src attribute
    int indexname = src.lastIndexOf("/");
    if (indexname == src.length()) {
        src = src.substring(1, indexname);
    }

    //Open a URL Stream
    URL url = new URL(src);
    InputStream in = url.openStream();

    OutputStream out = new BufferedOutputStream(new FileOutputStream( folderPath+ "/" +UrName+ ".jpg"));

    for (int b; (b = in.read()) != -1;) {
        out.write(b);
    }
    out.close();
    in.close();
}
</code>```

Body:
I'm using the method below to retrieve images from a website,and i want to add a unique id to each image.

How can i do that.

private static void getImages(String src) throws IOException {
    String folder = null;

    //Exctract the name of the image from the src attribute
    int indexname = src.lastIndexOf("/");
    if (indexname == src.length()) {
        src = src.substring(1, indexname);
    }

    indexname = src.lastIndexOf("/");
    String name = src.substring(indexname, src.length());
    System.out.println(name);

    //Open a URL Stream
    URL url = new URL(src);
    InputStream in = url.openStream();

    OutputStream out = new BufferedOutputStream(new FileOutputStream( folderPath+ name));
    for (int b; (b = in.read()) != -1;) {
        out.write(b);
    }
    out.close();
    in.close();
}

Body:
I found the awnser :

private static void getImages(String src,String UrName) throws IOException {
    String folder = "Folder url";

    //Exctract the name of the image from the src attribute
    int indexname = src.lastIndexOf("/");
    if (indexname == src.length()) {
        src = src.substring(1, indexname);
    }

    //Open a URL Stream
    URL url = new URL(src);
    InputStream in = url.openStream();

    OutputStream out = new BufferedOutputStream(new FileOutputStream( folderPath+ "/" +UrName+ ".jpg"));

    for (int b; (b = in.read()) != -1;) {
        out.write(b);
    }
    out.close();
    in.close();
}


问:
Is there any way to show remote references with git log?
```<code>git log --oneline
</code>```

The above command gives me the followed results:

```<code>5485b34 Modify: something
ccaf2c4 Modify: another thing
85a87e8 Bug Fix: the other thing
</code>```

But because I'm using gerrit and usually gerrit has it's change number as refs/changes/... format, I want to collect list framed as follows:

```<code>refs/changes/85/104085/9 Modify: something
refs/changes/33/104033/9 Modify: another thing
refs/changes/83/104183/2 Bug Fix: the other thing
</code>```

I know there is a way to obtain the mapping between commit IDs and remote references by using "git ls-remote". And by using "git ls-remote", I can make a script to obtain the above result. But is there any better and simpler way to obtain the above results?

答:
You can probably get what you want by using git log --oneline --pretty=format:'you_format_here'

Take a look at the man page for all the available options : https://git-scm.com/docs/pretty-formats

Body:
git log --oneline

The above command gives me the followed results:

5485b34 Modify: something
ccaf2c4 Modify: another thing
85a87e8 Bug Fix: the other thing

But because I'm using gerrit and usually gerrit has it's change number as refs/changes/... format, I want to collect list framed as follows:

refs/changes/85/104085/9 Modify: something
refs/changes/33/104033/9 Modify: another thing
refs/changes/83/104183/2 Bug Fix: the other thing

I know there is a way to obtain the mapping between commit IDs and remote references by using "git ls-remote". And by using "git ls-remote", I can make a script to obtain the above result. But is there any better and simpler way to obtain the above results?


问:
Dynamically generating SQL data on new page with PHP
I'm having trouble with this website I am creating.

Basically I'm trying to create news articles on a page that once you click on the article you'd be taken to a page that would load the content for that article. Is it possible to set it up in a way that I can load the content on a new page depending on the SQL primary key of the article selected?

I can load the articles on the page from the sql database no problem its just determining what data is loaded on a new page that is beating me.

Thanks in advance for any advice anyone can offer in this, even if its just pointing me in the right direction.
I have tried searching online first with no luck so far.

答:
You can use $_GET to create a dynamic content using one page only

EXAMPLE:

article.php?news_id=1:

```<code><?php
    if(isset($_GET['news_id'])){
        $newsID = $_GET['news_id'];
        //query all the data you need using that $newsID
    }
?>
</code>```

Body:
You can use $_GET to create a dynamic content using one page only

EXAMPLE:

article.php?news_id=1:

<?php
    if(isset($_GET['news_id'])){
        $newsID = $_GET['news_id'];
        //query all the data you need using that $newsID
    }
?>


问:
Redirect to www in IIS7 - classic pipeline mode
I want to implement redirects on an IIS7 webserver. Basically, if the subdomain is not included in the URL, I will redirect to the www subdomain.

http://mysite.com/file.aspx redirects to http://www.mysite.com/file.aspx

http://mysite.com/image.jpg redirects to http://www.mysite.com/image.jpg

http://mysite.com/text.html redirects to http://www.mysite.com/text.html

How to do this?

I do not want to write any HTTP Module -- it must be done thru IIS config only.

Also, I am required to use Classic Pipeline mode and cannot install any ISAPI plugins.

Is it possible?

答:
This solution worked for me:

1) Install URL Rewrite component:

http://www.iis.net/download/urlrewrite

2) Add to web.config:

```<code><system.webServer>
 <rewrite>
  <rules>
   <rule name="CanonicalHostNameRule1" stopProcessing="true">
    <match url="(.*)" />
    <conditions>
     <add input="{HTTP_HOST}" pattern="^mysite\.com$" />
    </conditions>
    <action type="Redirect" url="http://www.mysite.com/{R:1}" />
   </rule>
  </rules>
 </rewrite>
</system.webServer>
</code>```

Body:
This solution worked for me:

1) Install URL Rewrite component:

http://www.iis.net/download/urlrewrite

2) Add to web.config:

<system.webServer>
 <rewrite>
  <rules>
   <rule name="CanonicalHostNameRule1" stopProcessing="true">
    <match url="(.*)" />
    <conditions>
     <add input="{HTTP_HOST}" pattern="^mysite\.com$" />
    </conditions>
    <action type="Redirect" url="http://www.mysite.com/{R:1}" />
   </rule>
  </rules>
 </rewrite>
</system.webServer>


问:
Asymmetric error bars in Scipy's odrpack
I am using Scipy's odrpack to fit a linear function to some data that has uncertainties in both the x and y dimensions. Each data point has it's own uncertainty that is asymmetric.

I can fit a function using symmetric uncertainties, but this is not a true representation of my data.

How can I perform the fit with this in mind?

This is my code so far. It receives input data as a command line argument, and the uncertainties i'm using are just random numbers at the moment. (also, two fits are happening, one for positive data points another for the negative. The reasons are unrelated to this question)

```<code>import sys
import numpy as np
import scipy.odr.odrpack as odrpack

def f(B, x):
    return B[0]*x + B[1]

xdata = sys.argv[1].split(',')
xdata = [float(i) for i in xdata]
xdata = np.array(xdata)

#find indices of +/- data
zero_ind = np.where(xdata >= 0)[0][0]

x_p = xdata[zero_ind:]
x_m = xdata[:zero_ind+1]

ydata = sys.argv[2].split(',')
ydata = [float(i) for i in ydata]
ydata = np.array(ydata)

y_p = ydata[zero_ind:]
y_m = ydata[:zero_ind+1]

sx_m = np.random.random(len(x_m))
sx_p = np.random.random(len(x_p))

sy_m = np.random.random(len(y_m))
sy_p = np.random.random(len(y_p))

linear = odrpack.Model(f)

data_p = odrpack.RealData(x_p, y_p, sx=sx_p, sy=sy_p)
odr_p = odrpack.ODR(data_p, linear, beta0=[1.,2.])
out_p = odr_p.run()

data_m = odrpack.RealData(x_m, y_m, sx=sx_m, sy=sy_m)
odr_m = odrpack.ODR(data_m, linear, beta0=[1.,2.])
out_m = odr_m.run()
</code>```

Thanks!

答:
I will just give you solution with random data,I could not bother to import your data

```<code>import numpy as np
import scipy.odr.odrpack as odrpack
np.random.seed(1)

N = 10
x = np.linspace(0,5,N)*(-1)
y = 2*x - 1 + np.random.random(N)
sx = np.random.random(N)
sy = np.random.random(N)

def f(B, x):
    return B[0]*x + B[1]
linear = odrpack.Model(f)
# mydata = odrpack.Data(x, y, wd=1./np.power(sx,2), we=1./np.power(sy,2))
mydata = odrpack.RealData(x, y, sx=sx, sy=sy)

myodr = odrpack.ODR(mydata, linear, beta0=[1., 2.])
myoutput = myodr.run()
myoutput.pprint()
</code>```

Than we got

```<code>Beta: [ 1.92743947 -0.94409236]
Beta Std Error: [ 0.03117086  0.11273067]
Beta Covariance: [[ 0.02047196  0.06690713]
 [ 0.06690713  0.26776027]]
Residual Variance: 0.04746112419196648
Inverse Condition #: 0.10277763521624257
Reason(s) for Halting:
  Sum of squares convergence
</code>```

Body:
I am using Scipy's odrpack to fit a linear function to some data that has uncertainties in both the x and y dimensions. Each data point has it's own uncertainty that is asymmetric.

I can fit a function using symmetric uncertainties, but this is not a true representation of my data.

How can I perform the fit with this in mind?

This is my code so far. It receives input data as a command line argument, and the uncertainties i'm using are just random numbers at the moment. (also, two fits are happening, one for positive data points another for the negative. The reasons are unrelated to this question)

import sys
import numpy as np
import scipy.odr.odrpack as odrpack

def f(B, x):
    return B[0]*x + B[1]

xdata = sys.argv[1].split(',')
xdata = [float(i) for i in xdata]
xdata = np.array(xdata)

#find indices of +/- data
zero_ind = np.where(xdata >= 0)[0][0]

x_p = xdata[zero_ind:]
x_m = xdata[:zero_ind+1]

ydata = sys.argv[2].split(',')
ydata = [float(i) for i in ydata]
ydata = np.array(ydata)

y_p = ydata[zero_ind:]
y_m = ydata[:zero_ind+1]

sx_m = np.random.random(len(x_m))
sx_p = np.random.random(len(x_p))

sy_m = np.random.random(len(y_m))
sy_p = np.random.random(len(y_p))

linear = odrpack.Model(f)

data_p = odrpack.RealData(x_p, y_p, sx=sx_p, sy=sy_p)
odr_p = odrpack.ODR(data_p, linear, beta0=[1.,2.])
out_p = odr_p.run()

data_m = odrpack.RealData(x_m, y_m, sx=sx_m, sy=sy_m)
odr_m = odrpack.ODR(data_m, linear, beta0=[1.,2.])
out_m = odr_m.run()

Thanks!

Body:
I will just give you solution with random data,I could not bother to import your data

import numpy as np
import scipy.odr.odrpack as odrpack
np.random.seed(1)

N = 10
x = np.linspace(0,5,N)*(-1)
y = 2*x - 1 + np.random.random(N)
sx = np.random.random(N)
sy = np.random.random(N)

def f(B, x):
    return B[0]*x + B[1]
linear = odrpack.Model(f)
# mydata = odrpack.Data(x, y, wd=1./np.power(sx,2), we=1./np.power(sy,2))
mydata = odrpack.RealData(x, y, sx=sx, sy=sy)

myodr = odrpack.ODR(mydata, linear, beta0=[1., 2.])
myoutput = myodr.run()
myoutput.pprint()

Than we got

Beta: [ 1.92743947 -0.94409236]
Beta Std Error: [ 0.03117086  0.11273067]
Beta Covariance: [[ 0.02047196  0.06690713]
 [ 0.06690713  0.26776027]]
Residual Variance: 0.04746112419196648
Inverse Condition #: 0.10277763521624257
Reason(s) for Halting:
  Sum of squares convergence


问:
Why can't I add a constraint when creating the table?
```<code>CREATE TABLE `CHARSET`
   (
    CHARSET_CODE varchar(15),
    CHARSET_DESCRIPTION varchar(50),
    APP_REGI_DATE date,
    APP_UPD_DATE date,
    CREATED_BY varchar(20),
    CREATION_DATE date,
    UPDATED_BY varchar(20),
    UPDATE_DATE date,
    LOCALE_CODE varchar(20),
    ADD constraint PK_80 PRIMARY KEY (CHARSET_CODE)

   ) ;
</code>```

Giving me a red pointer on the last line where i am trying to add constraint.

答:
Try this code. You should remove the ADD keyword used before the constraint.

```<code>CREATE TABLE CHARSET
( CHARSET_CODE varchar(15),
CHARSET_DESCRIPTION varchar(50),
APP_REGI_DATE date,
APP_UPD_DATE date,
CREATED_BY varchar(20),
CREATION_DATE date,
UPDATED_BY varchar(20),
UPDATE_DATE date,
LOCALE_CODE varchar(20),
constraint PK_80 PRIMARY KEY (CHARSET_CODE));
</code>```

Body:
CREATE TABLE `CHARSET`
   (
    CHARSET_CODE varchar(15),
    CHARSET_DESCRIPTION varchar(50),
    APP_REGI_DATE date,
    APP_UPD_DATE date,
    CREATED_BY varchar(20),
    CREATION_DATE date,
    UPDATED_BY varchar(20),
    UPDATE_DATE date,
    LOCALE_CODE varchar(20),
    ADD constraint PK_80 PRIMARY KEY (CHARSET_CODE)

   ) ;

Giving me a red pointer on the last line where i am trying to add constraint.

Body:
Try this code. You should remove the ADD keyword used before the constraint.

CREATE TABLE CHARSET
( CHARSET_CODE varchar(15),
CHARSET_DESCRIPTION varchar(50),
APP_REGI_DATE date,
APP_UPD_DATE date,
CREATED_BY varchar(20),
CREATION_DATE date,
UPDATED_BY varchar(20),
UPDATE_DATE date,
LOCALE_CODE varchar(20),
constraint PK_80 PRIMARY KEY (CHARSET_CODE));


问:
fetching from twitter Api
Please i need help on how to fetch data from twitter api for a week.
i'm using nodeJs to write the code and it doesn't seem to work well.

I'm using the twit module in nodeJs btw.

```<code>var today = new Date();
 var day = today.getDate();
 var month = today.getMonth() + 1; //January is 0!
 var year = today.getFullYear();

let months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

 for (let i = 0; i < 7; i++) {
     if (day > 0) {
         day--;
     }
     if (day == 0) {
         month = month - 1;
         day = months[month - 1];
     }
     console.log(day, month, year);
 }
    let params = {
                   q: `to:${firstBrand} since:${year}-${month}-${day-1} until:${year}-${month}-${currentDay}`,
                   count: 5000,
                   language: 'en',
                   entities: false
               };
               let param = {
                   q: `to:${secondBrand} since:${year}-${month}-${day-1} until:${year}-${month}-${currentDay}`,
                   count: 5000,
                   language: 'en',
                   entities: false
               };

               t.get('search/tweets', params, dataGotten);
</code>```

答:
Assuming all your setup is done correctly:

```<code>const Twit = require('twit')

const T = new Twit({
  consumer_key:         '...',
  consumer_secret:      '...',
  access_token:         '...',
  access_token_secret:  '...',
  timeout_ms:           60*1000,  // optional HTTP request timeout to apply to all requests.
});
</code>```

I would try this:

```<code>t.get('search/tweets', params, function(err, data) {
  console.log(data);
});
</code>```

By the way, params is optional argument, so first of all try how it works without them:

```<code>t.get('search/tweets', function(err, data) {
  console.log(data);
});
</code>```

Title: fetching from twitter Api

Body:
Please i need help on how to fetch data from twitter api for a week.
i'm using nodeJs to write the code and it doesn't seem to work well.

I'm using the twit module in nodeJs btw.

var today = new Date();
 var day = today.getDate();
 var month = today.getMonth() + 1; //January is 0!
 var year = today.getFullYear();

let months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

 for (let i = 0; i < 7; i++) {
     if (day > 0) {
         day--;
     }
     if (day == 0) {
         month = month - 1;
         day = months[month - 1];
     }
     console.log(day, month, year);
 }
    let params = {
                   q: `to:${firstBrand} since:${year}-${month}-${day-1} until:${year}-${month}-${currentDay}`,
                   count: 5000,
                   language: 'en',
                   entities: false
               };
               let param = {
                   q: `to:${secondBrand} since:${year}-${month}-${day-1} until:${year}-${month}-${currentDay}`,
                   count: 5000,
                   language: 'en',
                   entities: false
               };

               t.get('search/tweets', params, dataGotten);

Body:
Assuming all your setup is done correctly:

const Twit = require('twit')

const T = new Twit({
  consumer_key:         '...',
  consumer_secret:      '...',
  access_token:         '...',
  access_token_secret:  '...',
  timeout_ms:           60*1000,  // optional HTTP request timeout to apply to all requests.
});

I would try this:

t.get('search/tweets', params, function(err, data) {
  console.log(data);
});

By the way, params is optional argument, so first of all try how it works without them:

t.get('search/tweets', function(err, data) {
  console.log(data);
});


问:
Pentaho table input step goes to idle state
I have a similar table structure in two different schema of MySQL. I am trying to get the data from one schema using table input and inserting the same data to a different schema using insert / update step. When I run the ktr, it is going to idle state after reading 1 row.</p>

答:
Th most probable issue is that you are auto-locking your table. Either the output or the input. The logs won't give you anything.

Start debugging by creating an output table with the same structure as your output table and put a few records in it with a Table output (without truncate). When this works, built your use case by incremental improvement. It should take you 3-5 iterations.


答:
you can pass the news-id as variable in url and get that variable using $_GET method,then execute the sql query.</p>

```<code>     <?php
     $id =$_GET['id];
     ?>
     mysql-"Select * from Table where id =$id"
</code>```

Title: Dynamically generating SQL data on new page with PHP

Body:
I'm having trouble with this website I am creating.

Basically I'm trying to create news articles on a page that once you click on the article you'd be taken to a page that would load the content for that article. Is it possible to set it up in a way that I can load the content on a new page depending on the SQL primary key of the article selected?

I can load the articles on the page from the sql database no problem its just determining what data is loaded on a new page that is beating me.

Thanks in advance for any advice anyone can offer in this, even if its just pointing me in the right direction.
I have tried searching online first with no luck so far.

Body:
you can pass the news-id as variable in url and get that variable using $_GET method,then execute the sql query.

     <?php
     $id =$_GET['id];
     ?>
     mysql-"Select * from Table where id =$id"


问:
regular expression to validate aadhar NO
Need help on validating Addhar Card Number with regular expression. It's 12 digit number, in the following format. It can contain 0 to 9 digits.

e.g. 0000 0000 0000

ContentLicense: CC BY-SA 4.0

Body:
I don't have a regex for you but you can use this function to check valid aadhar no.

function checkUID(uid) {
    if (uid.length != 12) {
        return false;
    }

    var Verhoeff = {
        "d": [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
            [1, 2, 3, 4, 0, 6, 7, 8, 9, 5],
            [2, 3, 4, 0, 1, 7, 8, 9, 5, 6],
            [3, 4, 0, 1, 2, 8, 9, 5, 6, 7],
            [4, 0, 1, 2, 3, 9, 5, 6, 7, 8],
            [5, 9, 8, 7, 6, 0, 4, 3, 2, 1],
            [6, 5, 9, 8, 7, 1, 0, 4, 3, 2],
            [7, 6, 5, 9, 8, 2, 1, 0, 4, 3],
            [8, 7, 6, 5, 9, 3, 2, 1, 0, 4],
            [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]],
        "p": [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
            [1, 5, 7, 6, 2, 8, 3, 0, 9, 4],
            [5, 8, 0, 3, 7, 9, 6, 1, 4, 2],
            [8, 9, 1, 6, 0, 4, 3, 5, 2, 7],
            [9, 4, 5, 3, 1, 2, 6, 8, 7, 0],
            [4, 2, 8, 6, 5, 7, 3, 9, 0, 1],
            [2, 7, 9, 3, 8, 0, 6, 4, 1, 5],
            [7, 0, 4, 6, 9, 1, 3, 2, 5, 8]],
        "j": [0, 4, 3, 2, 1, 5, 6, 7, 8, 9],
        "check": function (str) {
            var c = 0;
            str.replace(/\D+/g, "").split("").reverse().join("").replace(/[\d]/g, function (u, i) {
                c = Verhoeff.d[c][Verhoeff.p[i % 8][parseInt(u, 10)]];
            });
            return c;

        },
        "get": function (str) {

            var c = 0;
            str.replace(/\D+/g, "").split("").reverse().join("").replace(/[\d]/g, function (u, i) {
                c = Verhoeff.d[c][Verhoeff.p[(i + 1) % 8][parseInt(u, 10)]];
            });
            return Verhoeff.j[c];
        }
    };

    String.prototype.verhoeffCheck = (function () {
        var d = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
            [1, 2, 3, 4, 0, 6, 7, 8, 9, 5],
            [2, 3, 4, 0, 1, 7, 8, 9, 5, 6],
            [3, 4, 0, 1, 2, 8, 9, 5, 6, 7],
            [4, 0, 1, 2, 3, 9, 5, 6, 7, 8],
            [5, 9, 8, 7, 6, 0, 4, 3, 2, 1],
            [6, 5, 9, 8, 7, 1, 0, 4, 3, 2],
            [7, 6, 5, 9, 8, 2, 1, 0, 4, 3],
            [8, 7, 6, 5, 9, 3, 2, 1, 0, 4],
            [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]];
        var p = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
            [1, 5, 7, 6, 2, 8, 3, 0, 9, 4],
            [5, 8, 0, 3, 7, 9, 6, 1, 4, 2],
            [8, 9, 1, 6, 0, 4, 3, 5, 2, 7],
            [9, 4, 5, 3, 1, 2, 6, 8, 7, 0],
            [4, 2, 8, 6, 5, 7, 3, 9, 0, 1],
            [2, 7, 9, 3, 8, 0, 6, 4, 1, 5],
            [7, 0, 4, 6, 9, 1, 3, 2, 5, 8]];

        return function () {
            var c = 0;
            this.replace(/\D+/g, "").split("").reverse().join("").replace(/[\d]/g, function (u, i) {
                c = d[c][p[i % 8][parseInt(u, 10)]];
            });
            return (c === 0);
        };
    })();

    if (Verhoeff['check'](uid) === 0) {
        return true;
    } else {
        return false;
    }
}

This function returns true, when its valid aadhar no, else false.
example

console.log("", checkUID("111111111111"));  // false


问:
Dependency Injection vs Factory Pattern
Most of the examples quoted for usage of Dependency Injection, we can solve using the factory pattern as well. Looks like when it comes to usage/design the difference between dependency injection and factory is blurred or thin.

Once someone told me that its how you use it that makes a difference!

I once used StructureMap a DI container to solve a problem, later on I redesigned it to work with a simple factory and removed references to StructureMap.

Can anyone tell me what is the difference between them and where to use what, whats the best practice here?

答:
I had the same question as soon as I read about DI and ended up at this post.
So finally this is what I understood but please correct me if am wrong.

"Long ago there were little kingdoms with their own governing bodies controlling and taking decisions based on their own written rules. Later on formed a big government eliminating all these little governing bodies which has one set of rules(constitution) and are implemented through courts"

The little kingdoms' governing bodies are "Factories"

The big government is the "Dependency Injector".

OwnerDisplayName: Binoj Antony

Title: Dependency Injection vs Factory Pattern

LastEditorDisplayName: Binoj Antony


答:
You can use reflection to get the properties of the type, e.g.:

```<code>var knownPropNames = new string[]
{
    "Int",
    "Str",
};
var props = typeof(Foo).GetProperties(BindingFlags.Public | BindingFlags.Instance);
var unknownProps = props
                    .Where(x => !knownPropNames.Contains(x.Name))
                    .Select(x => x.Name)
                    .ToArray();
// Use assertion instead of Console.WriteLine
Console.WriteLine("Unknown props: {0}", string.Join("; ", unknownProps));
</code>```

This way, you can implement a test that fails if any properties are added. Of course, you'd have to add new properties to the array at the beginning. As using reflection is an expensive operation from a performance point of view, I'd propose to use it in the test, not in the comparer itself if you need to compare lots of objects.

Please also note the use of the BindingFlags parameter so you can restrict the properties to only the public ones and the ones on instance-level.

Also, you can define a custom attribute that you use to mark properties that are not relevant. For example:

```<code>[AttributeUsage(AttributeTargets.Property)]
public class ComparerIgnoreAttribute : Attribute {}
</code>```

You can apply it to a property:

```<code>[ComparerIgnore]
public decimal Dec { get; set; }
</code>```

In addition, you'd have to extend the code that discovers unknown properties:

```<code>var unknownProps = props
                    .Where(x => !knownPropNames.Contains(x.Name)
                        && !x.GetCustomAttributes(typeof(ComparerIgnoreAttribute)).Any())
                    .Select(x => x.Name)
                    .ToArray();
</code>```

Title: How to implement unit tests on IEqualityComparer?

Body:
I have a class and a comparer for this class that implements IEqualityComparer:

class Foo
{
    public int Int { get; set; }
    public string Str { get; set; }

    public Foo(int i, string s)
    {
        Int = i;
        Str = s;
    }

    private sealed class FooEqualityComparer : IEqualityComparer<Foo>
    {
        public bool Equals(Foo x, Foo y)
        {
            if (ReferenceEquals(x, y)) return true;
            if (ReferenceEquals(x, null)) return false;
            if (ReferenceEquals(y, null)) return false;
            if (x.GetType() != y.GetType()) return false;
            return x.Int == y.Int && string.Equals(x.Str, y.Str);
        }

        public int GetHashCode(Foo obj)
        {
            unchecked
            {
                return (obj.Int * 397) ^ (obj.Str != null ? obj.Str.GetHashCode() : 0);
            }
        }
    }

    public static IEqualityComparer<Foo> Comparer { get; } = new FooEqualityComparer();
}

The two methods Equals and GetHashCode are used for example in List.Except via an instance of the comparer.

My question is: how to implement properly unit tests on this comparer? I want to detect if someone adds a public property in Foo without modifying the comparer, because in this case the comparer becomes invalid.

If I do something like:

Assert.That(new Foo(42, "answer"), Is.EqualTo(new Foo(42, "answer")));

This cannot detect that a new property was added, and that this property differs in the two objects.

Is there any way to do this?

If it is possible, can we add an attribute to a property to say that this property is not relevant in the comparison?

Body:
You can use reflection to get the properties of the type, e.g.:

var knownPropNames = new string[]
{
    "Int",
    "Str",
};
var props = typeof(Foo).GetProperties(BindingFlags.Public | BindingFlags.Instance);
var unknownProps = props
                    .Where(x => !knownPropNames.Contains(x.Name))
                    .Select(x => x.Name)
                    .ToArray();
// Use assertion instead of Console.WriteLine
Console.WriteLine("Unknown props: {0}", string.Join("; ", unknownProps));

This way, you can implement a test that fails if any properties are added. Of course, you'd have to add new properties to the array at the beginning. As using reflection is an expensive operation from a performance point of view, I'd propose to use it in the test, not in the comparer itself if you need to compare lots of objects.

Please also note the use of the BindingFlags parameter so you can restrict the properties to only the public ones and the ones on instance-level.

Also, you can define a custom attribute that you use to mark properties that are not relevant. For example:

[AttributeUsage(AttributeTargets.Property)]
public class ComparerIgnoreAttribute : Attribute {}

You can apply it to a property:

[ComparerIgnore]
public decimal Dec { get; set; }

In addition, you'd have to extend the code that discovers unknown properties:

var unknownProps = props
                    .Where(x => !knownPropNames.Contains(x.Name)
                        && !x.GetCustomAttributes(typeof(ComparerIgnoreAttribute)).Any())
                    .Select(x => x.Name)
                    .ToArray();


问:
How can I synchronize these two threads?
here is the class:

```<code>public class Ticker
{
    public event EventHandler Tick;
    public EventArgs e = null;
    public void TickIt()
    {
        while (true)
        {
            System.Threading.Thread.Sleep(300);
            if (Tick != null)
            {
                Tick(this, e);
            }
        }
    }
</code>```

I'm running two threads in the windows form:

```<code>public partial class Form1 : Form
{
    Ticker ticker1 = new Ticker();
    Ticker ticker2 = new Ticker();
    Thread t;
    Thread t1;

    public Form1()
    {
        InitializeComponent();
        ticker1.Tick += ticker1_Tick;
        ticker2.Tick += ticker2_Tick;

        t = new Thread(new ThreadStart(ticker1.TickIt));
        t1 = new Thread(new ThreadStart(ticker2.TickIt)));
        t.Start();
        t1.Start();

    }
    public void ticker1_Tick(object sender, EventArgs e)
    {
        if (this.InvokeRequired)
        {
            this.BeginInvoke((MethodInvoker)delegate
            {
                ticker1_Tick(sender, e);
            });
            return;
        }

        richTextBox1.Text += "t1 ";
    }
    public void ticker2_Tick(object sender, EventArgs e)
    {
        if (this.InvokeRequired)
        {
            this.BeginInvoke((MethodInvoker)delegate
            {
                ticker2_Tick(sender, e);
            });
            return;
        }

        richTextBox2.Text += "t2 ";
    }
</code>```

The problem is after some seconds thread t is ahead of t1 by several ticks.

First of all why is this happening, it doesn't make sense, since each thread should wait 300 ms before ticking?

Second, how can I sync these two threads, so they tick simultaneously and one doesn't get ahead of the other?

I can't put a lock before the while loop, then only one thread will be running, while the other is locked out. Putting a lock elsewhere doesn't change anything.

答:
In your Ticker class, increase your polling frequency and check the system timer until you hit the interval you're looking for. You can use TickCount or Ticks if you can live with millisecond precision, or use StopWatch for higher precision if your system supports it.

To keep them synchronized, they'll need a common reference for a start-time. You can pass this in as a specific future tick to start syncing on or use something like Tick modulus 100. Or poll for a shared static flag that signifies when to start.

You cannot have absolute precision, so define what precision range you can live with from the outset, such as plus-or-minus 5ms between your Ticker threads.

One thing that'll help is to start a shared static StopWatch instance and echo its elapsed time in all of your logging to help you characterize any delays in your app.

Body:
here is the class:

public class Ticker
{
    public event EventHandler Tick;
    public EventArgs e = null;
    public void TickIt()
    {
        while (true)
        {
            System.Threading.Thread.Sleep(300);
            if (Tick != null)
            {
                Tick(this, e);
            }
        }
    }

I'm running two threads in the windows form:

public partial class Form1 : Form
{
    Ticker ticker1 = new Ticker();
    Ticker ticker2 = new Ticker();
    Thread t;
    Thread t1;

    public Form1()
    {
        InitializeComponent();
        ticker1.Tick += ticker1_Tick;
        ticker2.Tick += ticker2_Tick;

        t = new Thread(new ThreadStart(ticker1.TickIt));
        t1 = new Thread(new ThreadStart(ticker2.TickIt)));
        t.Start();
        t1.Start();

    }
    public void ticker1_Tick(object sender, EventArgs e)
    {
        if (this.InvokeRequired)
        {
            this.BeginInvoke((MethodInvoker)delegate
            {
                ticker1_Tick(sender, e);
            });
            return;
        }

        richTextBox1.Text += "t1 ";
    }
    public void ticker2_Tick(object sender, EventArgs e)
    {
        if (this.InvokeRequired)
        {
            this.BeginInvoke((MethodInvoker)delegate
            {
                ticker2_Tick(sender, e);
            });
            return;
        }

        richTextBox2.Text += "t2 ";
    }

The problem is after some seconds thread t is ahead of t1 by several ticks.

First of all why is this happening, it doesn't make sense, since each thread should wait 300 ms before ticking?

Second, how can I sync these two threads, so they tick simultaneously and one doesn't get ahead of the other?

I can't put a lock before the while loop, then only one thread will be running, while the other is locked out. Putting a lock elsewhere doesn't change anything.


问:
How to split csv whose columns may contain comma
Given

```<code>2,1016,7/31/2008 14:22,Geoff Dalgas,6/5/2011 22:21,http://stackoverflow.com,"Corvallis, OR",7679,351,81,b437f461b3fd27387c5d8ab47a293d35,34
</code>```

How to use C# to split the above information into strings as follows:

```<code>2
1016
7/31/2008 14:22
Geoff Dalgas
6/5/2011 22:21
http://stackoverflow.com
Corvallis, OR
7679
351
81
b437f461b3fd27387c5d8ab47a293d35
34
</code>```

As you can see one of the column contains , <= (Corvallis, OR)

Based on
C# Regex Split - commas outside quotes

```<code>string[] result = Regex.Split(samplestring, ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
</code>```

答:
I had a problem with a CSV that contains fields with a quote character in them, so using the TextFieldParser, I came up with the following:

```<code>private static string[] parseCSVLine(string csvLine)
{
  using (TextFieldParser TFP = new TextFieldParser(new MemoryStream(Encoding.UTF8.GetBytes(csvLine))))
  {
    TFP.HasFieldsEnclosedInQuotes = true;
    TFP.SetDelimiters(",");

    try
    {
      return TFP.ReadFields();
    }
    catch (MalformedLineException)
    {
      StringBuilder m_sbLine = new StringBuilder();

      for (int i = 0; i < TFP.ErrorLine.Length; i++)
      {
        if (i > 0 && TFP.ErrorLine[i]== '"' &&(TFP.ErrorLine[i + 1] != ',' && TFP.ErrorLine[i - 1] != ','))
          m_sbLine.Append("\"\"");
        else
          m_sbLine.Append(TFP.ErrorLine[i]);
      }

      return parseCSVLine(m_sbLine.ToString());
    }
  }
}
</code>```

A StreamReader is still used to read the CSV line by line, as follows:

```<code>using(StreamReader SR = new StreamReader(FileName))
{
  while (SR.Peek() >-1)
    myStringArray = parseCSVLine(SR.ReadLine());
}
</code>```

Body:
Given

2,1016,7/31/2008 14:22,Geoff Dalgas,6/5/2011 22:21,http://stackoverflow.com,"Corvallis, OR",7679,351,81,b437f461b3fd27387c5d8ab47a293d35,34

How to use C# to split the above information into strings as follows:

2
1016
7/31/2008 14:22
Geoff Dalgas
6/5/2011 22:21
http://stackoverflow.com
Corvallis, OR
7679
351
81
b437f461b3fd27387c5d8ab47a293d35
34

As you can see one of the column contains , <= (Corvallis, OR)

Based on
C# Regex Split - commas outside quotes

string[] result = Regex.Split(samplestring, ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");

Body:
I had a problem with a CSV that contains fields with a quote character in them, so using the TextFieldParser, I came up with the following:

private static string[] parseCSVLine(string csvLine)
{
  using (TextFieldParser TFP = new TextFieldParser(new MemoryStream(Encoding.UTF8.GetBytes(csvLine))))
  {
    TFP.HasFieldsEnclosedInQuotes = true;
    TFP.SetDelimiters(",");

    try
    {
      return TFP.ReadFields();
    }
    catch (MalformedLineException)
    {
      StringBuilder m_sbLine = new StringBuilder();

      for (int i = 0; i < TFP.ErrorLine.Length; i++)
      {
        if (i > 0 && TFP.ErrorLine[i]== '"' &&(TFP.ErrorLine[i + 1] != ',' && TFP.ErrorLine[i - 1] != ','))
          m_sbLine.Append("\"\"");
        else
          m_sbLine.Append(TFP.ErrorLine[i]);
      }

      return parseCSVLine(m_sbLine.ToString());
    }
  }
}

A StreamReader is still used to read the CSV line by line, as follows:

using(StreamReader SR = new StreamReader(FileName))
{
  while (SR.Peek() >-1)
    myStringArray = parseCSVLine(SR.ReadLine());
}


问:
Liferay 7 message Bus
In Liferay 6.2 we used to configure Custom mail in messaging-spring.xml and do entery in service.properties.. To achieve the same in Liferay 7 OSGI module portlet, can anyone guide me how could I configure a message bus in it?</p>

答:
I found the solution. To avoid java.lang.IllegalStateException: No servlet context name specified you need to change implementation of messaging configuration in your messaging-spring.xml file.

Replace com.liferay.portal.kernel.messaging.config.PluginMessagingConfigurator with com.liferay.portal.kernel.messaging.config.DefaultMessagingConfigurator.

This works for me. I was able to send message from one module, and receive it by two other modules.

Title: Liferay 7 message Bus


问:
trouble with layout android Not Able to generate this View According to icons and line and below text
I am designing following layout structure for one of my application. But dont know how to implement it.

答:
This Design is called Stepper. There are lot of open source library is available for this design. Check the following link. May it will help you.

https://android-arsenal.com/details/1/3049


问:
mongoose aggregate : how to count matching documents and insert counting using Promises
When I perform the following aggregate

```<code>return this.aggregate([
  {
    $lookup: {
      from: 'groups',
      localField: '_group',
      foreignField: '_id',
      as: 'group'
    }
  },
  { $match: query },
  {
    $project: {
      group: {
        $let:{
          vars:{
            firstGroup:{
              $arrayElemAt:["$group",0]
            }
          },
          in:{
            name:"$$firstGroup.name",
            description:"$$firstGroup.description"
          }
        }
      },
      name: 1,
      description: 1,
      _id: 0
    }
  },
  { $sort: sortBy },
  { $limit: resultsPerPage },
  { $skip: skipDocuments }
])
</code>```

with  query = {}
no limit no skip
I get 8 matching roles grouped by group.name

```<code>ROLES: [
{"name":"NewRole","description":"NewRole description","group":{}},{"name":"Visitor","description":"no permissions","group":{}},
{"name":"NewRoleInGroup","description":"NewRoleInGroup description","group":{"name":"GroupA","description":"Description GroupA"}},
{"name":"admin","description":"can RW group, user","group":{"name":"GroupA","description":"Description GroupA"}},
{"name":"employee","description":"can R group, can read user","group":{"name":"GroupA","description":"Description GroupA"}},
{"name":"manager","description":"can R group, can RW user","group":{"name":"GroupA","description":"Description GroupA"}},
{"name":"employee","description":"can R group, can read user","group":{"name":"GroupB","description":"Description GroupB"}},
{"name":"manager","description":"can R group, can RW user","group":{"name":"GroupB","description":"Description GroupB"}},
{"name":"employee","description":"can R group, can read user","group":{"name":"GroupC","description":"Description GroupC"}}
]
</code>```

Now  I would like to insert the total matching documents as the first object in the result to get track of it (when a limit is specified in the aggregate, I should return the total number of docs)

```<code>ROLES: [
{"roleCount": 8},
{"name":"NewRole","description":"NewRole description","group":{}},{"name":"Visitor","description":"no permissions","group":{}},
{"name":"NewRoleInGroup","description":"NewRoleInGroup description","group":{"name":"GroupA","description":"Description GroupA"}},
{"name":"admin","description":"can RW group, user","group":{"name":"GroupA","description":"Description GroupA"}},
{"name":"employee","description":"can R group, can read user","group":{"name":"GroupA","description":"Description GroupA"}}
]
</code>```

Where should I write the count in the pipeline ( I guess after the $match ?)
 and how can I insert the count into the result ?  ( I guess after the  $sort ?)

Maybe there is no way to do it in one aggregate , and the only possibility is to perform first a collection count then the aggregate and insert the counter object before returning the result ( using Promise.all it can be done in parallel.. )

thanks for feedback

答:
My solution is a bit rude but I hope it will help you before finding the best solution. I use the lodash or can be native javascript. Its handle looks like this!</p>

```<code>    ROLES: [
         {"name":"NewRole","description":"NewRole description","group":{}},{"name":"Visitor","description":"no permissions","group":{}},
         {"name":"NewRoleInGroup","description":"NewRoleInGroup description","group":{"name":"GroupA","description":"Description GroupA"}},
         {"name":"admin","description":"can RW group, user","group":{"name":"GroupA","description":"Description GroupA"}},
         {"name":"employee","description":"can R group, can read user","group":{"name":"GroupA","description":"Description GroupA"}},
         {"name":"manager","description":"can R group, can RW user","group":{"name":"GroupA","description":"Description GroupA"}},
         {"name":"employee","description":"can R group, can read user","group":{"name":"GroupB","description":"Description GroupB"}},
         {"name":"manager","description":"can R group, can RW user","group":{"name":"GroupB","description":"Description GroupB"}},
         {"name":"employee","description":"can R group, can read user","group":{"name":"GroupC","description":"Description GroupC"}}
    ];
    ROLES.unshift({"roleCount": ROLES.length})
</code>```

Body:
When I perform the following aggregate

return this.aggregate([
  {
    $lookup: {
      from: 'groups',
      localField: '_group',
      foreignField: '_id',
      as: 'group'
    }
  },
  { $match: query },
  {
    $project: {
      group: {
        $let:{
          vars:{
            firstGroup:{
              $arrayElemAt:["$group",0]
            }
          },
          in:{
            name:"$$firstGroup.name",
            description:"$$firstGroup.description"
          }
        }
      },
      name: 1,
      description: 1,
      _id: 0
    }
  },
  { $sort: sortBy },
  { $limit: resultsPerPage },
  { $skip: skipDocuments }
])

with  query = {}
no limit no skip
I get 8 matching roles grouped by group.name

ROLES: [
{"name":"NewRole","description":"NewRole description","group":{}},{"name":"Visitor","description":"no permissions","group":{}},
{"name":"NewRoleInGroup","description":"NewRoleInGroup description","group":{"name":"GroupA","description":"Description GroupA"}},
{"name":"admin","description":"can RW group, user","group":{"name":"GroupA","description":"Description GroupA"}},
{"name":"employee","description":"can R group, can read user","group":{"name":"GroupA","description":"Description GroupA"}},
{"name":"manager","description":"can R group, can RW user","group":{"name":"GroupA","description":"Description GroupA"}},
{"name":"employee","description":"can R group, can read user","group":{"name":"GroupB","description":"Description GroupB"}},
{"name":"manager","description":"can R group, can RW user","group":{"name":"GroupB","description":"Description GroupB"}},
{"name":"employee","description":"can R group, can read user","group":{"name":"GroupC","description":"Description GroupC"}}
]

Now  I would like to insert the total matching documents as the first object in the result to get track of it (when a limit is specified in the aggregate, I should return the total number of docs)

ROLES: [
{"roleCount": 8},
{"name":"NewRole","description":"NewRole description","group":{}},{"name":"Visitor","description":"no permissions","group":{}},
{"name":"NewRoleInGroup","description":"NewRoleInGroup description","group":{"name":"GroupA","description":"Description GroupA"}},
{"name":"admin","description":"can RW group, user","group":{"name":"GroupA","description":"Description GroupA"}},
{"name":"employee","description":"can R group, can read user","group":{"name":"GroupA","description":"Description GroupA"}}
]

Where should I write the count in the pipeline ( I guess after the $match ?)
 and how can I insert the count into the result ?  ( I guess after the  $sort ?)

Maybe there is no way to do it in one aggregate , and the only possibility is to perform first a collection count then the aggregate and insert the counter object before returning the result ( using Promise.all it can be done in parallel.. )

thanks for feedback

Body:
My solution is a bit rude but I hope it will help you before finding the best solution. I use the lodash or can be native javascript. Its handle looks like this!

    ROLES: [
         {"name":"NewRole","description":"NewRole description","group":{}},{"name":"Visitor","description":"no permissions","group":{}},
         {"name":"NewRoleInGroup","description":"NewRoleInGroup description","group":{"name":"GroupA","description":"Description GroupA"}},
         {"name":"admin","description":"can RW group, user","group":{"name":"GroupA","description":"Description GroupA"}},
         {"name":"employee","description":"can R group, can read user","group":{"name":"GroupA","description":"Description GroupA"}},
         {"name":"manager","description":"can R group, can RW user","group":{"name":"GroupA","description":"Description GroupA"}},
         {"name":"employee","description":"can R group, can read user","group":{"name":"GroupB","description":"Description GroupB"}},
         {"name":"manager","description":"can R group, can RW user","group":{"name":"GroupB","description":"Description GroupB"}},
         {"name":"employee","description":"can R group, can read user","group":{"name":"GroupC","description":"Description GroupC"}}
    ];
    ROLES.unshift({"roleCount": ROLES.length})


问:
Java exceptions on running performance test with JMeter
I am generating a 1000 user load on an application hosted on AWS t2.large server from my 8gb windows machine.
If I downsize my load to 500 i get no failed transactions but if I go with 800-1000 user load, I see the following exceptions:-
1. java.net.bindexception
2. java.net.socketexception
3. java.net.connectexception

Does these signify bottleneck at the server side or my system is not capable to generate that much load. Please also provide resolution steps for the same.

Thanks in advance for your help.
Yash

答:
Most likely you found the bottleneck in your application, I would recommend the following steps:

Check your web or application server connection settings, HTTP servers use to have maximum allowed connections setting and it needs to be more than 1000.

If point 1 is fine you could monitor your AWS instance health via Amazon CloudWatch or JMeter PerfMon Plugin as your server may simply lack CPU or RAM or ran out of available file descriptors/network sockets (it is around 1024 for "normal" Linux user account)

If points 1 and 2 are fine and you are totally sure your application behaves as expected you could also try workarounds listed in Connection Reset since JMeter 2.10 ? JMeter wiki page


问:
Visual studio .SLN executing Exe file / .VBS script
How to launch .Exe file or .VBS script when visual studio solution(.sln) is opened ?</p>

答: Associate a .SLN file with your own executable instead of devenv.  In your executable, if the solution being opened matches then delete the necessary files. Then execute the devenv and pass the solution full path and name as a parameter.


问:
How to solve Navbar overlap with body content or other page in CSS
I have made a navigation bar with CSS and JS. The picture below show my example of nav bar

The problem is, when i choose type "MY ACCOUNT" it will display some content. Then if i hover mouse on "Value Graph" it give me result of overlapping with body content of My Account. Here is the problem.

Here is my CSS For Navbar

```<code>@import url(http://fonts.googleapis.com/css?
family=Open+Sans:400italic,400,300,600);

@font-face {
font-family: 'icomoon';
src:url('../fonts/icomoon.eot');
src:url('../fonts/icomoon.eot?#iefix') format('embedded-opentype'),
url('../fonts/icomoon.woff') format('woff'),
url('../fonts/icomoon.ttf') format('truetype'),
url('../fonts/icomoon.svg#icomoon') format('svg');
  font-weight: normal;
  font-style: normal;
}

/* minimal styles for that navi */
.rmm {margin: 0 auto;}
.rmm ul {margin: 0; padding:0; list-style: none; position: relative;
background: #000;}
.rmm ul:after {content: ""; clear: both; display: block;}
.rmm ul li {float: left;}
.rmm ul li:hover {background: #202020;}
.rmm ul li:hover > ul {display: block;}
.rmm ul li:hover a{color: #fff;}
.rmm ul li a {color: #fff; display: block; text-decoration: none;}
.rmm ul ul {display: none; margin:0; padding: 0; position: absolute; top:
100%;}
.rmm ul ul li {float: none; position: relative;}
.rmm ul ul li a{color: #fff;}
.rmm ul ul li a:hover {background: #202020;}
.rmm ul ul ul {position: absolute; left: 100%; top:0; width: 100%;}

/* mobile menu header button */
.rmm-toggled {width: 100%; background-color: #555555; min-height: 50px;
margin: 0 auto; display: none;}
.rmm-closed ~ .rmm-mobile {display: none!important;}
.rmm-toggled-controls{width: 100%;}
.rmm-toggled-title{width: 60%; float: left; font-size: 27px; color: #fff;
font-weight:600; display: block; padding: 8px 0; text-decoration: none;
text-transform: uppercase; text-align: left; padding-left: 35px;}
.rmm-toggled-button{width: 20%; float: left; margin-top: 3px;
 display:block;
width: 32px;
padding:0 !important;
margin:10px 10px 0 0;
border:1px solid #fff;
border-radius:3px;
float: right;
}
.rmm-toggled-button span{float: left; display:block; margin: 3px 6px;
height: 3px; background:white; width:20px;}

/* normalny back button visible only on mobiles  */
.rmm .rmm-back{display: none; font-size: 12px;}
.rmm .rmm-back:after {display: none;}
.rmm .rmm-back a:after {
font-family: 'icomoon';
speak: none;
-webkit-font-smoothing: antialiased;
content: "\e000";
 position: relative;
display: inline-block;
-webkit-transform: rotate(-60deg);
transform: rotate(-60deg);
top: 1px;
 right: -2px ;
float: left;
font-size: 10px;
}
.rmm-mobile .rmm-back{display: block;}

  /* mobile menu list */
  .rmm-mobile{width: 100%;}
  .rmm-mobile .rmm-dropdown:hover ~ ul, .rmm-mobile .rmm-dropdown:hover > ul
  ,.rmm-mobile .rmm-dropdown:hover + ul {display: none!important;}
   .rmm-mobile ul{width: 100%; position: inherit!important;}
   .rmm-mobile li{width: 100%; }

   /* mobile menu js action */
  .rmm-dropdown{display: block!important;}
  .rmm-mobile .rmm-subview{display: block!important; width: 100%;}
  .rmm-mobile .rmm-subover-hidden{display: none!important;}
  .rmm-mobile .rmm-subover-visible{display: block;}
  .rmm-mobile .rmm-subover-header{display: none!important; padding: 0;
   margin:0;}

  /* mobile menu content */
  .rmm-mobile .rmm-submenu{position: relative; left: 0px;}

  .rmm .rmm-mobile li:hover > ul {display: none;}

  /* arrow down for wide screen */
  .rmm.style {text-align: left; font-family: Tahoma;}
  .rmm.style ul {box-shadow: 0px 0px 9px rgba(0, 0, 0, 0.15);
   background:#990;
   text-transform: uppercase; display: inline-table; text-align:left;}
  .rmm.style ul li {text-align:left;}
  .rmm.style ul li:hover {background: #4b545f;}
  .rmm.style ul ul {display: none; margin:0; background: #5f6975; border-
   radius: 0px; padding: 0; position: absolute;}
  .rmm.style ul li a {color: #fff; font-weight:600; display: block; padding:
   15px 35px; text-decoration: none; font-weight:600; }
  .rmm.style ul ul li {border-bottom: 1px solid #575F6A; border-top: 1px
   solid #6B727C;}
  .rmm.style ul ul li a {padding: 12px 35px; color: #fff; }
  .rmm.style ul ul li a:hover {background: #4b545f;}

   /* arrow down for wide screen */
   .rmm.style ul li > a:not(:only-child):after {
   font-family: 'icomoon';
   speak: none;
  -webkit-font-smoothing: antialiased;
   content: "\e000";
   position: relative;
   display: inline-block;
   -webkit-transform: rotate(210deg);
    transform: rotate(210deg);
    top: -4px;
    left: 1px;
    font-size: 10px;
   }

   /* arrow left for wide screen submenus  */
   .rmm.style ul ul li > a:not(:only-child):after {-webkit-transform:
    rotate(120deg)!important; transform: rotate(120deg)!important; top: 2px;
   font-size: 14px; float: right; margin-right: -20px;}

    /* mobile style */
   .rmm.style .rmm-mobile li > a:not(:only-child):after {-webkit-transform:
     rotate(120deg)!important; transform: rotate(120deg)!important; top:
     4px!important; font-size: 14px!important; float: right; margin-right:
    -20px;}
    .rmm.style .rmm-mobile li{background: #3ab4a6; border-bottom: 1px solid
    #575f6a!important; border-top: 0!important; }
</code>```

Thanks in advance!

答:
I have added z-index on my css. Here is the answer:

```<code>/* arrow down for wide screen */

.rmm.style {text-align:center; font-family: Tahoma; }
.rmm.style ul {box-shadow: 0px 0px 9px rgba(0, 0, 0, 0.15); background-color: #F8F8F8;
text-transform: uppercase; display: inline-table; text-
align:left; z-index: 1; }
</code>```

Body:
I have made a navigation bar with CSS and JS. The picture below show my example of nav bar

The problem is, when i choose type "MY ACCOUNT" it will display some content. Then if i hover mouse on "Value Graph" it give me result of overlapping with body content of My Account. Here is the problem.

Here is my CSS For Navbar

@import url(http://fonts.googleapis.com/css?
family=Open+Sans:400italic,400,300,600);

@font-face {
font-family: 'icomoon';
src:url('../fonts/icomoon.eot');
src:url('../fonts/icomoon.eot?#iefix') format('embedded-opentype'),
url('../fonts/icomoon.woff') format('woff'),
url('../fonts/icomoon.ttf') format('truetype'),
url('../fonts/icomoon.svg#icomoon') format('svg');
  font-weight: normal;
  font-style: normal;
}

/* minimal styles for that navi */
.rmm {margin: 0 auto;}
.rmm ul {margin: 0; padding:0; list-style: none; position: relative;
background: #000;}
.rmm ul:after {content: ""; clear: both; display: block;}
.rmm ul li {float: left;}
.rmm ul li:hover {background: #202020;}
.rmm ul li:hover > ul {display: block;}
.rmm ul li:hover a{color: #fff;}
.rmm ul li a {color: #fff; display: block; text-decoration: none;}
.rmm ul ul {display: none; margin:0; padding: 0; position: absolute; top:
100%;}
.rmm ul ul li {float: none; position: relative;}
.rmm ul ul li a{color: #fff;}
.rmm ul ul li a:hover {background: #202020;}
.rmm ul ul ul {position: absolute; left: 100%; top:0; width: 100%;}

/* mobile menu header button */
.rmm-toggled {width: 100%; background-color: #555555; min-height: 50px;
margin: 0 auto; display: none;}
.rmm-closed ~ .rmm-mobile {display: none!important;}
.rmm-toggled-controls{width: 100%;}
.rmm-toggled-title{width: 60%; float: left; font-size: 27px; color: #fff;
font-weight:600; display: block; padding: 8px 0; text-decoration: none;
text-transform: uppercase; text-align: left; padding-left: 35px;}
.rmm-toggled-button{width: 20%; float: left; margin-top: 3px;
 display:block;
width: 32px;
padding:0 !important;
margin:10px 10px 0 0;
border:1px solid #fff;
border-radius:3px;
float: right;
}
.rmm-toggled-button span{float: left; display:block; margin: 3px 6px;
height: 3px; background:white; width:20px;}

/* normalny back button visible only on mobiles  */
.rmm .rmm-back{display: none; font-size: 12px;}
.rmm .rmm-back:after {display: none;}
.rmm .rmm-back a:after {
font-family: 'icomoon';
speak: none;
-webkit-font-smoothing: antialiased;
content: "\e000";
 position: relative;
display: inline-block;
-webkit-transform: rotate(-60deg);
transform: rotate(-60deg);
top: 1px;
 right: -2px ;
float: left;
font-size: 10px;
}
.rmm-mobile .rmm-back{display: block;}

  /* mobile menu list */
  .rmm-mobile{width: 100%;}
  .rmm-mobile .rmm-dropdown:hover ~ ul, .rmm-mobile .rmm-dropdown:hover > ul
  ,.rmm-mobile .rmm-dropdown:hover + ul {display: none!important;}
   .rmm-mobile ul{width: 100%; position: inherit!important;}
   .rmm-mobile li{width: 100%; }

   /* mobile menu js action */
  .rmm-dropdown{display: block!important;}
  .rmm-mobile .rmm-subview{display: block!important; width: 100%;}
  .rmm-mobile .rmm-subover-hidden{display: none!important;}
  .rmm-mobile .rmm-subover-visible{display: block;}
  .rmm-mobile .rmm-subover-header{display: none!important; padding: 0;
   margin:0;}

  /* mobile menu content */
  .rmm-mobile .rmm-submenu{position: relative; left: 0px;}

  .rmm .rmm-mobile li:hover > ul {display: none;}

  /* arrow down for wide screen */
  .rmm.style {text-align: left; font-family: Tahoma;}
  .rmm.style ul {box-shadow: 0px 0px 9px rgba(0, 0, 0, 0.15);
   background:#990;
   text-transform: uppercase; display: inline-table; text-align:left;}
  .rmm.style ul li {text-align:left;}
  .rmm.style ul li:hover {background: #4b545f;}
  .rmm.style ul ul {display: none; margin:0; background: #5f6975; border-
   radius: 0px; padding: 0; position: absolute;}
  .rmm.style ul li a {color: #fff; font-weight:600; display: block; padding:
   15px 35px; text-decoration: none; font-weight:600; }
  .rmm.style ul ul li {border-bottom: 1px solid #575F6A; border-top: 1px
   solid #6B727C;}
  .rmm.style ul ul li a {padding: 12px 35px; color: #fff; }
  .rmm.style ul ul li a:hover {background: #4b545f;}

   /* arrow down for wide screen */
   .rmm.style ul li > a:not(:only-child):after {
   font-family: 'icomoon';
   speak: none;
  -webkit-font-smoothing: antialiased;
   content: "\e000";
   position: relative;
   display: inline-block;
   -webkit-transform: rotate(210deg);
    transform: rotate(210deg);
    top: -4px;
    left: 1px;
    font-size: 10px;
   }

   /* arrow left for wide screen submenus  */
   .rmm.style ul ul li > a:not(:only-child):after {-webkit-transform:
    rotate(120deg)!important; transform: rotate(120deg)!important; top: 2px;
   font-size: 14px; float: right; margin-right: -20px;}

    /* mobile style */
   .rmm.style .rmm-mobile li > a:not(:only-child):after {-webkit-transform:
     rotate(120deg)!important; transform: rotate(120deg)!important; top:
     4px!important; font-size: 14px!important; float: right; margin-right:
    -20px;}
    .rmm.style .rmm-mobile li{background: #3ab4a6; border-bottom: 1px solid
    #575f6a!important; border-top: 0!important; }

Thanks in advance!

Body:
I have added z-index on my css. Here is the answer:

/* arrow down for wide screen */

.rmm.style {text-align:center; font-family: Tahoma; }
.rmm.style ul {box-shadow: 0px 0px 9px rgba(0, 0, 0, 0.15); background-color: #F8F8F8;
text-transform: uppercase; display: inline-table; text-
align:left; z-index: 1; }


问:
Does the Exclusive-Or form a monoid for Bools?
I made an operator for the xor-function, it looks like that:

```<code>op :: Integer -> Integer -> Maybe Integer
op x y
  | x == 0 && y == 0 = Just 0
  | x == 0 && y == 1 = Just 1
  | x == 1 && y == 0 = Just 1
  | x == 1 && y == 1 = Just 0
  | otherwise = Nothing
</code>```

I used 0 and 1 instead of True and False but that shouldn't make a difference for the result. I read it forms a monoid but I don't understand why. Associativity is obvious and doesn't need a proof(I already made the proof by myself), but what is the identity element and why?

Edit: Here's one without numbers:

```<code>xor :: Bool -> Bool -> Bool
xor x y | x == True && y == False = True
        | x == False && y == True = True
        | otherwise = False
</code>```

答:
I made a stupid mistake in my proof, as amalloy said the identity is false. Here's the complete proof, I hope it's correct now.</p>

```<code>mempty <> p = p
xor False p = p
-- For p = True:
xor False True = True
True = True
-- For p = False:
xor False False = False
False = False
-- Q.E.D
</code>```

Body:
I made an operator for the xor-function, it looks like that:

op :: Integer -> Integer -> Maybe Integer
op x y
  | x == 0 && y == 0 = Just 0
  | x == 0 && y == 1 = Just 1
  | x == 1 && y == 0 = Just 1
  | x == 1 && y == 1 = Just 0
  | otherwise = Nothing

I used 0 and 1 instead of True and False but that shouldn't make a difference for the result. I read it forms a monoid but I don't understand why. Associativity is obvious and doesn't need a proof(I already made the proof by myself), but what is the identity element and why?

Edit: Here's one without numbers:

xor :: Bool -> Bool -> Bool
xor x y | x == True && y == False = True
        | x == False && y == True = True
        | otherwise = False

Body:
I made a stupid mistake in my proof, as amalloy said the identity is false. Here's the complete proof, I hope it's correct now.

mempty <> p = p
xor False p = p
-- For p = True:
xor False True = True
True = True
-- For p = False:
xor False False = False
False = False
-- Q.E.D