问:
Iterate a Linq Expression and convert it into DB parameter
How i can iterate a Linq Expression and convert it into DB parameter so that i can avoid passing multiple parameter as input to the DAL method

Business Layer:
 In BL i have code like this

```<code>  database.GetProduct(a => a.ProductType == "tea" || a.Price <= 5);
</code>```

In DAL i use plain ADO.Net and want to convert the expression whatever i returned from BL to ADO.Net parameters

Data Access Layer:

```<code> public DataSet GetProduct(Expression<Func<Product, bool>> pred)
 {

    step 1:
          Iterate the predicate and create new sqlparameter.
    step 2:
      return database.ExecuteDataset(parameters)
 }
</code>```

How i  can iterate "pred" & convert it to SQLParameter

答:
You do not want to go down this road.  You are going to be reimplementing LINQ to SQL.  I might suggest that you use optional arguments:</p>

```<code>public DataSet GetProduct(int? maxPrice = null, string type = null)
{
    //... snip ...
    if (price.HasValue) whereClause += " OR price <= " + maxPrice";
    //... snip ...
}
</code>```

Body:
How i can iterate a Linq Expression and convert it into DB parameter so that i can avoid passing multiple parameter as input to the DAL method

Business Layer:
 In BL i have code like this

  database.GetProduct(a => a.ProductType == "tea" || a.Price <= 5);

In DAL i use plain ADO.Net and want to convert the expression whatever i returned from BL to ADO.Net parameters

Data Access Layer:

 public DataSet GetProduct(Expression<Func<Product, bool>> pred)
 {

    step 1:
          Iterate the predicate and create new sqlparameter.
    step 2:
      return database.ExecuteDataset(parameters)
 }

How i  can iterate "pred" & convert it to SQLParameter

Body:
You do not want to go down this road.  You are going to be reimplementing LINQ to SQL.  I might suggest that you use optional arguments:

public DataSet GetProduct(int? maxPrice = null, string type = null)
{
    //... snip ...
    if (price.HasValue) whereClause += " OR price <= " + maxPrice";
    //... snip ...
}


来源: stackexchange

问:
One directional view pager with one fragment
I am facing one problem i have one fragment in view pager which i need to update when user slides from right to left, slide animation should be there with one fragment, here are some code that i am trying, the thing is i have view pager inside fragment as well.

Any suggestions code help will be appreciated.

here are some code that i have tried for one directional view pager

```<code>public class CustomViewPager extends ViewPager {

    private float initialXValue;
    private SwipeDirection direction;

    public CustomViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.direction = SwipeDirection.all;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (this.IsSwipeAllowed(event)) {
            return super.onTouchEvent(event);
        }

        return false;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        if (this.IsSwipeAllowed(event)) {
            return super.onInterceptTouchEvent(event);
        }

        return false;
    }

    private boolean IsSwipeAllowed(MotionEvent event) {
        if (this.direction == SwipeDirection.all) return true;

        if (direction == SwipeDirection.none)//disable any swipe
            return false;

        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            initialXValue = event.getX();
            return true;
        }

        if (event.getAction() == MotionEvent.ACTION_MOVE) {
            try {
                float diffX = event.getX() - initialXValue;
                if (diffX > 0 && direction == SwipeDirection.right) {
                    // swipe from left to right detected
                    return false;
                } else if (diffX < 0 && direction == SwipeDirection.left) {
                    // swipe from right to left detected
                    return false;
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }

        return true;
    }

    public void setAllowedSwipeDirection(SwipeDirection direction) {
        this.direction = direction;
    }
}
</code>```

答:
Can you explain more? i still don't understand, view pager just 1 fragment inside ? and how you swipe with 1 fragment ?

```<code>public class NoSwipeViewPager extends ViewPager {
    private float initialXValue;
    private SwipeDirection direction;

    public NoSwipeViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.direction = SwipeDirection.all;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (this.IsSwipeAllowed(event)) {
            return super.onTouchEvent(event);
        }

        return false;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        if (this.IsSwipeAllowed(event)) {
            return super.onInterceptTouchEvent(event);
        }

        return false;
    }

    public enum SwipeDirection {
        all, left, right, none;
    }

    private boolean IsSwipeAllowed(MotionEvent event) {
        if (this.direction == SwipeDirection.all) return true;

        if (direction == SwipeDirection.none)
            return false;

        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            initialXValue = event.getX();
            return true;
        }

        if (event.getAction() == MotionEvent.ACTION_MOVE) {
            try {
                float diffX = event.getX() - initialXValue;
                if (diffX > 0 && direction == SwipeDirection.right) {
                    return false;
                } else if (diffX < 0 && direction == SwipeDirection.left) {
                    return false;
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }

        return true;
    }

    public void setAllowedSwipeDirection(SwipeDirection direction) {
        this.direction = direction;
    }
}
</code>```

and when you use:

```<code>viewPager.setAllowedSwipeDirection(NoSwipeViewPager.SwipeDirection.left);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am facing one problem i have one fragment in view pager which i need to update when user slides from right to left, slide animation should be there with one fragment, here are some code that i am trying, the thing is i have view pager inside fragment as well.

Any suggestions code help will be appreciated.

here are some code that i have tried for one directional view pager

public class CustomViewPager extends ViewPager {

    private float initialXValue;
    private SwipeDirection direction;

    public CustomViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.direction = SwipeDirection.all;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (this.IsSwipeAllowed(event)) {
            return super.onTouchEvent(event);
        }

        return false;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        if (this.IsSwipeAllowed(event)) {
            return super.onInterceptTouchEvent(event);
        }

        return false;
    }

    private boolean IsSwipeAllowed(MotionEvent event) {
        if (this.direction == SwipeDirection.all) return true;

        if (direction == SwipeDirection.none)//disable any swipe
            return false;

        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            initialXValue = event.getX();
            return true;
        }

        if (event.getAction() == MotionEvent.ACTION_MOVE) {
            try {
                float diffX = event.getX() - initialXValue;
                if (diffX > 0 && direction == SwipeDirection.right) {
                    // swipe from left to right detected
                    return false;
                } else if (diffX < 0 && direction == SwipeDirection.left) {
                    // swipe from right to left detected
                    return false;
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }

        return true;
    }

    public void setAllowedSwipeDirection(SwipeDirection direction) {
        this.direction = direction;
    }
}

Body:
Can you explain more? i still don't understand, view pager just 1 fragment inside ? and how you swipe with 1 fragment ?

public class NoSwipeViewPager extends ViewPager {
    private float initialXValue;
    private SwipeDirection direction;

    public NoSwipeViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.direction = SwipeDirection.all;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (this.IsSwipeAllowed(event)) {
            return super.onTouchEvent(event);
        }

        return false;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        if (this.IsSwipeAllowed(event)) {
            return super.onInterceptTouchEvent(event);
        }

        return false;
    }

    public enum SwipeDirection {
        all, left, right, none;
    }

    private boolean IsSwipeAllowed(MotionEvent event) {
        if (this.direction == SwipeDirection.all) return true;

        if (direction == SwipeDirection.none)
            return false;

        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            initialXValue = event.getX();
            return true;
        }

        if (event.getAction() == MotionEvent.ACTION_MOVE) {
            try {
                float diffX = event.getX() - initialXValue;
                if (diffX > 0 && direction == SwipeDirection.right) {
                    return false;
                } else if (diffX < 0 && direction == SwipeDirection.left) {
                    return false;
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }

        return true;
    }

    public void setAllowedSwipeDirection(SwipeDirection direction) {
        this.direction = direction;
    }
}

and when you use:

viewPager.setAllowedSwipeDirection(NoSwipeViewPager.SwipeDirection.left);


问:
Cannot read property 'geocode' of undefined

var geocoder;
var map;
var infowindow;

function initialize() {
  geocoder = new google.maps.Geocoder();
  var loca = new google.maps.LatLng(41.7475, -74.0872);

  map = new google.maps.Map(document.getElementById('map'), {
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: loca,
    zoom: 8
  });

}

function callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      createMarker(results[i]);
    }
  }
}

function createMarker(place) {
  var placeLoc = place.geometry.location;
  var marker = new google.maps.Marker({
    map: map,
    position: place.geometry.location
  });

  google.maps.event.addListener(marker, 'mouseover', function() {
    infowindow.setContent(place.name);
    infowindow.open(map, this);
  });
}

function codeAddress() {
  var address = document.getElementById("address").value;
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location
      });
      var request = {
        location: results[0].geometry.location,
        radius: 50000,
        name: 'ski',
        keyword: 'mountain',
        type: ['park']
      };
      infowindow = new google.maps.InfoWindow();
      var service = new google.maps.places.PlacesService(map);
      service.nearbySearch(request, callback);
    } else {
      alert("Geocode was not successful for the following reason: " + status);
    }
  });
}

google.maps.event.addDomListener(window, 'load', initialize);
```

My application currently finds the nearest ski areas, based on the latitude and longitude that is hardcoded in. I would like to be able to type in an address and convert that address into the latitude and longitude for the search. I am using Google Maps api and the places library. I know that I somehow need to use geocoding but not sure how to do that. Here is the code:

答:
Your script has no error, it is working fine for me, check the below example.

The problem may be:

1)your places-api script may be wrong.
2)Your codeAddress() is being called before script loads. Make sure the script loads first

var geocoder;
var map;
var infowindow;

function initialize() {
  geocoder = new google.maps.Geocoder();
  var loca = new google.maps.LatLng(41.7475, -74.0872);

  map = new google.maps.Map(document.getElementById('map'), {
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: loca,
    zoom: 8
  });

}

function callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      createMarker(results[i]);
    }
  }
}

function createMarker(place) {
  var placeLoc = place.geometry.location;
  var marker = new google.maps.Marker({
    map: map,
    position: place.geometry.location
  });

  google.maps.event.addListener(marker, 'mouseover', function() {
    infowindow.setContent(place.name);
    infowindow.open(map, this);
  });
}

function codeAddress() {
  var address = document.getElementById("address").value;
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location
      });
      var request = {
        location: results[0].geometry.location,
        radius: 50000,
        name: 'ski',
        keyword: 'mountain',
        type: ['park']
      };
      infowindow = new google.maps.InfoWindow();
      var service = new google.maps.places.PlacesService(map);
      service.nearbySearch(request, callback);
    } else {
      alert("Geocode was not successful for the following reason: " + status);
    }
  });
}

google.maps.event.addDomListener(window, 'load', initialize);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><title>Google Maps API v3 Example : Geocoding Simple</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>

<script type="text/javascript">
</script>

<div align="center" style="height: 30px; width: 530px">
<input id="address" type="textbox">
<input type="button" value="Geocode" onclick="codeAddress()">
</div>
<div id="map" style="height:200px; width: 530px"></div></code>```

Please run the above snippet

Here is a working example

Body:
var geocoder;
var map;
var infowindow;

function initialize() {
  geocoder = new google.maps.Geocoder();
  var loca = new google.maps.LatLng(41.7475, -74.0872);

  map = new google.maps.Map(document.getElementById('map'), {
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: loca,
    zoom: 8
  });

}

function callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      createMarker(results[i]);
    }
  }
}

function createMarker(place) {
  var placeLoc = place.geometry.location;
  var marker = new google.maps.Marker({
    map: map,
    position: place.geometry.location
  });

  google.maps.event.addListener(marker, 'mouseover', function() {
    infowindow.setContent(place.name);
    infowindow.open(map, this);
  });
}

function codeAddress() {
  var address = document.getElementById("address").value;
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location
      });
      var request = {
        location: results[0].geometry.location,
        radius: 50000,
        name: 'ski',
        keyword: 'mountain',
        type: ['park']
      };
      infowindow = new google.maps.InfoWindow();
      var service = new google.maps.places.PlacesService(map);
      service.nearbySearch(request, callback);
    } else {
      alert("Geocode was not successful for the following reason: " + status);
    }
  });
}

google.maps.event.addDomListener(window, 'load', initialize);

My application currently finds the nearest ski areas, based on the latitude and longitude that is hardcoded in. I would like to be able to type in an address and convert that address into the latitude and longitude for the search. I am using Google Maps api and the places library. I know that I somehow need to use geocoding but not sure how to do that. Here is the code:

Body:
Your script has no error, it is working fine for me, check the below example.

The problem may be:

1)your places-api script may be wrong.
2)Your codeAddress() is being called before script loads. Make sure the script loads first

var geocoder;
var map;
var infowindow;

function initialize() {
  geocoder = new google.maps.Geocoder();
  var loca = new google.maps.LatLng(41.7475, -74.0872);

  map = new google.maps.Map(document.getElementById('map'), {
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: loca,
    zoom: 8
  });

}

function callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      createMarker(results[i]);
    }
  }
}

function createMarker(place) {
  var placeLoc = place.geometry.location;
  var marker = new google.maps.Marker({
    map: map,
    position: place.geometry.location
  });

  google.maps.event.addListener(marker, 'mouseover', function() {
    infowindow.setContent(place.name);
    infowindow.open(map, this);
  });
}

function codeAddress() {
  var address = document.getElementById("address").value;
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location
      });
      var request = {
        location: results[0].geometry.location,
        radius: 50000,
        name: 'ski',
        keyword: 'mountain',
        type: ['park']
      };
      infowindow = new google.maps.InfoWindow();
      var service = new google.maps.places.PlacesService(map);
      service.nearbySearch(request, callback);
    } else {
      alert("Geocode was not successful for the following reason: " + status);
    }
  });
}

google.maps.event.addDomListener(window, 'load', initialize);

<title>Google Maps API v3 Example : Geocoding Simple</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>

<script type="text/javascript">
</script>

<div align="center" style="height: 30px; width: 530px">
<input id="address" type="textbox">
<input type="button" value="Geocode" onclick="codeAddress()">
</div>
<div id="map" style="height:200px; width: 530px"></div>

Please run the above snippet

Here is a working example


问:
jQuery custom event - fire event when width is xx
I'm using Jquery UI slider, I want the slider to fire event when it reach 33%, 66% and 100%
I cannot use a different slider lib, the project is very big it'll be a mess to change the slider now.
Any idea?</p>

答:
You have 'change' function inside your slider. From 'ui' parameter you can get current value.. Example:</p>

```<code>$('#slider').slider({
    change: function(event, ui) {
        if(ui.value == 33 || ui.value == 66 || ui.value == 100){
            //do something
        }
    }
});
</code>```

Body:
You have 'change' function inside your slider. From 'ui' parameter you can get current value.. Example:

$('#slider').slider({
    change: function(event, ui) {
        if(ui.value == 33 || ui.value == 66 || ui.value == 100){
            //do something
        }
    }
});


问:
Visual Studio Addin - Cant Create Child Menu Items
i am trying to create a basic menu structure for a visual studio 2008 addin. So far i can create the first top-level menu which in my example below i have called TOPMENU. I am struggling to figure out how to add child items to TOPMENU. I have tried a variety of ways and cant figure it out. Can someone help me finish off the code below? I am currently getting an invalid cast exception when i try to create object "a2" below.</p>

```<code>void IDTExtensibility2.OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
{
 _ApplicationObject = (DTE2)application;
 _AddInInstance = (AddIn)addInInst;

 if (connectMode == ext_ConnectMode.ext_cm_UISetup)
 {
  object[] contextGUIDS = new object[] { };
  Commands2 commands = (Commands2)_ApplicationObject.Commands;
  CommandBar cbMainMenu = ((CommandBars)_ApplicationObject.CommandBars)["MenuBar"];

  try
  {
   // ROOT MENU
   Command cmdProjectManagement = commands.AddNamedCommand2(_AddInInstance, "TOPMENU", "TOPMENU", "",
    true, null, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled,
    (int)vsCommandStyle.vsCommandStyleText, vsCommandControlType.vsCommandControlTypeButton);

   if (cmdProjectManagement != null)
    cmdProjectManagement.AddControl(cbMainMenu, cbMainMenu.Controls.Count);

   // SUB ITEM
   Command cmdCompiledAssemblies = commands.AddNamedCommand2(_AddInInstance, "TOPMENU_CompiledAssemblies", "Compiled Assemblies", String.Empty,
    true, null, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled,
    (int)vsCommandStyle.vsCommandStyleText, vsCommandControlType.vsCommandControlTypeButton);

   CommandBarControl a1 = cbMainMenu.Controls["TOPMENU"];
   CommandBarPopup a2 = (CommandBarPopup)a1;

   if (cmdCompiledAssemblies != null)
    cmdCompiledAssemblies.AddControl(a2.CommandBar, 1);
  }
  catch (Exception ex)
  {
  }
 }
}
</code>```

答:
Full documentation on how to create all sorts of menu's and toolbar's here..

http://www.mztools.com/articles/2005/mz2005003.aspx

ContentLicense: CC BY-SA 2.5

Body:
i am trying to create a basic menu structure for a visual studio 2008 addin. So far i can create the first top-level menu which in my example below i have called TOPMENU. I am struggling to figure out how to add child items to TOPMENU. I have tried a variety of ways and cant figure it out. Can someone help me finish off the code below? I am currently getting an invalid cast exception when i try to create object "a2" below.

void IDTExtensibility2.OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
{
 _ApplicationObject = (DTE2)application;
 _AddInInstance = (AddIn)addInInst;

 if (connectMode == ext_ConnectMode.ext_cm_UISetup)
 {
  object[] contextGUIDS = new object[] { };
  Commands2 commands = (Commands2)_ApplicationObject.Commands;
  CommandBar cbMainMenu = ((CommandBars)_ApplicationObject.CommandBars)["MenuBar"];

  try
  {
   // ROOT MENU
   Command cmdProjectManagement = commands.AddNamedCommand2(_AddInInstance, "TOPMENU", "TOPMENU", "",
    true, null, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled,
    (int)vsCommandStyle.vsCommandStyleText, vsCommandControlType.vsCommandControlTypeButton);

   if (cmdProjectManagement != null)
    cmdProjectManagement.AddControl(cbMainMenu, cbMainMenu.Controls.Count);

   // SUB ITEM
   Command cmdCompiledAssemblies = commands.AddNamedCommand2(_AddInInstance, "TOPMENU_CompiledAssemblies", "Compiled Assemblies", String.Empty,
    true, null, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled,
    (int)vsCommandStyle.vsCommandStyleText, vsCommandControlType.vsCommandControlTypeButton);

   CommandBarControl a1 = cbMainMenu.Controls["TOPMENU"];
   CommandBarPopup a2 = (CommandBarPopup)a1;

   if (cmdCompiledAssemblies != null)
    cmdCompiledAssemblies.AddControl(a2.CommandBar, 1);
  }
  catch (Exception ex)
  {
  }
 }
}


问:
Laravel pass variables to mail template?
My problem is that I want to send variables from my EmailController to my mail view and then email to the address. I have tried several things but it didn't work. Hopefully you can help me.

My Controller:

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Mail\Email;
use Mail;

class EmailController extends Controller
{
public function sendMail(Request $request)
{

    $option = $request->input('vraag');
    $title = $request->input('onderwerp');
    $body = $request->input('bericht');
    $email = $request->input('email');
    $gender = $request->input('aanhef');
    $name = $request->input('naam');

    $data = array(
        'option' => $option,
        'title' => $title,
        'body' => $body,
        'e-mail' => $email,
        'gender' => $gender,
        'name' => $name
    );

    $receiverAddress = 'test@example.com';

           return view('emails.email')->with('option', 'title', 'body', 'e-mail', 'gender', 'name');

}
}
</code>```

I want the request variables to my mail view.
I am getting the error: Undefined variable: data.

My View:

```<code><!DOCTYPE html>
<html>
<head>
   <title></title>
</head>
<body>
   <h1>Contactformulier</h1>
   <?php
     echo $data['option'];
   ?>
</body>
</html>
</code>```

答:
you can use this: </p>

```<code> return view('mailview')->with('name', 'email');
</code>```

Body:
My problem is that I want to send variables from my EmailController to my mail view and then email to the address. I have tried several things but it didn't work. Hopefully you can help me.

My Controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Mail\Email;
use Mail;

class EmailController extends Controller
{
public function sendMail(Request $request)
{

    $option = $request->input('vraag');
    $title = $request->input('onderwerp');
    $body = $request->input('bericht');
    $email = $request->input('email');
    $gender = $request->input('aanhef');
    $name = $request->input('naam');

    $data = array(
        'option' => $option,
        'title' => $title,
        'body' => $body,
        'e-mail' => $email,
        'gender' => $gender,
        'name' => $name
    );

    $receiverAddress = 'test@example.com';

           return view('emails.email')->with('option', 'title', 'body', 'e-mail', 'gender', 'name');

}
}

I want the request variables to my mail view.
I am getting the error: Undefined variable: data.

My View:

<!DOCTYPE html>

   <title></title>

Contactformulier

   <?php
     echo $data['option'];
   ?>

Body:
you can use this:

 return view('mailview')->with('name', 'email');


问:
Return Array from Embedded document
I have a data like in mongodb collection name property.

```<code>{
            "_id": "593a3d828e2ef100d1496e77",
            "feature_type": "house",
            "features": [
                {
                    "name": "h1"
                },
                {
                    "name": "h2"
                }
            ]
        }
</code>```

I want only

```<code> [
            {
                "name": "h1"
            },
            {
                "name": "h2"
            }
        ]
</code>```

as result i tried this by

```<code>req.db.collection('FeatureSettings').findOne({feature_type: req.params.feature_type}, {features: 1});
</code>```

this give

```<code>{
    "_id": "593a3d828e2ef100d1496e77",
    "features": [
        {
            "name": "Hotel"
        },
        {
            "name": "Apartment"
        }
    ]
}
</code>```

what can i do to get result as given above.

答:
Assuming you're using something like mongoose that returns promises, you could use the result of the query</p>

```<code>return req.db.collection('FeatureSettings')
.findOne({feature_type: req.params.feature_type}, {features: 1})
.then((result) => {
    return result.features;
});
</code>```

Title: Return Array from Embedded document

Body:
I have a data like in mongodb collection name property.

{
            "_id": "593a3d828e2ef100d1496e77",
            "feature_type": "house",
            "features": [
                {
                    "name": "h1"
                },
                {
                    "name": "h2"
                }
            ]
        }

I want only

 [
            {
                "name": "h1"
            },
            {
                "name": "h2"
            }
        ]

as result i tried this by

req.db.collection('FeatureSettings').findOne({feature_type: req.params.feature_type}, {features: 1});

this give

{
    "_id": "593a3d828e2ef100d1496e77",
    "features": [
        {
            "name": "Hotel"
        },
        {
            "name": "Apartment"
        }
    ]
}

what can i do to get result as given above.

Body:
Assuming you're using something like mongoose that returns promises, you could use the result of the query

return req.db.collection('FeatureSettings')
.findOne({feature_type: req.params.feature_type}, {features: 1})
.then((result) => {
    return result.features;
});


问:
How to properly handle a null variable perspective in kotlin?
My old java version method looks like:

```<code>@Override
public void closeSimpleAlertDialog() {
    if (mAlertDialog != null && mAlertDialog.isShowing()) {
        mAlertDialog.dismiss();
    }
}
</code>```

As you can tell it is checked whether the null reference link to a dialog mAlertDialog and if not null check call method isShowing(), and only then caused a method of close - dismiss(). Very simple

I faced a problem - how is still in "Kotlin-style" to perform the same operation?

My first version looks here:

```<code>if (mAlertDialog != null && mAlertDialog?.isShowing) {
        mAlertDialog?.dismiss()
}
</code>```

Next step change mAlertDialog != null && mAlertDialog?.isShowing to mAlertDialog?.isShowing ?: false and last version looks like:

```<code>if (mAlertDialog?.isShowing ?: false)
            mAlertDialog?.dismiss()
</code>```

But I don't understand. Why do I need "?" if the null checking already happened before (here: mAlertDialog?.)?

答:
```<code>mAlertDialog?.isShowing ?: false
</code>```

This line is providing a fallback value (false) in case the dialog or the property is null.

What you are probably looking for is:

```<code>alertDialog?.let {
    if (it.isShowing())
        it.dismiss()
}
</code>```

Where "it" is the property before the question mark null-checked.
If alertDialog is null, the let will not be called and note that if you call it without the question mark it will enter even if it's null.

Body:
My old java version method looks like:

@Override
public void closeSimpleAlertDialog() {
    if (mAlertDialog != null && mAlertDialog.isShowing()) {
        mAlertDialog.dismiss();
    }
}

As you can tell it is checked whether the null reference link to a dialog mAlertDialog and if not null check call method isShowing(), and only then caused a method of close - dismiss(). Very simple

I faced a problem - how is still in "Kotlin-style" to perform the same operation?

My first version looks here:

if (mAlertDialog != null && mAlertDialog?.isShowing) {
        mAlertDialog?.dismiss()
}

Next step change mAlertDialog != null && mAlertDialog?.isShowing to mAlertDialog?.isShowing ?: false and last version looks like:

if (mAlertDialog?.isShowing ?: false)
            mAlertDialog?.dismiss()

But I don't understand. Why do I need "?" if the null checking already happened before (here: mAlertDialog?.)?

Body:
mAlertDialog?.isShowing ?: false

This line is providing a fallback value (false) in case the dialog or the property is null.

What you are probably looking for is:

alertDialog?.let {
    if (it.isShowing())
        it.dismiss()
}

Where "it" is the property before the question mark null-checked.
If alertDialog is null, the let will not be called and note that if you call it without the question mark it will enter even if it's null.


问:
Multiple timezones, current time in each moment.js
I'm trying to get my head around Moment JS and the time zone add on.

I would like to get the current time for each office to neatly display in my footer, but not sure where to start.

Hopefull outcome

London
    09.00

Paris
     10.00

Munich
  10.00

Milan
  10.00

Moscow
  11.00

Dubai
  12.00

```

答:
Use:
Moment.js and moment timezone

```<code>$('#London').text(moment.tz('Europe/London').format('HH:mm'));
$('#Paris').text(moment.tz('Europe/Paris').format('HH:mm'));
$('#Berlin').text(moment.tz('Europe/Berlin').format('HH:mm'));
$('#Rome').text(moment.tz('Europe/Rome').format('HH:mm'));
$('#Moscow').text(moment.tz('Europe/Moscow').format('HH:mm'));
$('#Dubai').text(moment.tz('Asia/Dubai').format('HH:mm'));
</code>```

Munich and Milan are not in moment.js data. Instead, use Berlin and Rome.

Fiddle Demo

Body:
Use:
Moment.js and moment timezone

$('#London').text(moment.tz('Europe/London').format('HH:mm'));
$('#Paris').text(moment.tz('Europe/Paris').format('HH:mm'));
$('#Berlin').text(moment.tz('Europe/Berlin').format('HH:mm'));
$('#Rome').text(moment.tz('Europe/Rome').format('HH:mm'));
$('#Moscow').text(moment.tz('Europe/Moscow').format('HH:mm'));
$('#Dubai').text(moment.tz('Asia/Dubai').format('HH:mm'));

Munich and Milan are not in moment.js data. Instead, use Berlin and Rome.

Fiddle Demo


问:
Weka output predictions
I've used the Weka GUI for training and testing a file (making predictions), but can't do the same with the API. The error I'm getting says there's a different number of attributes in the train and test files. In the GUI, this can be solved by checking "Output predictions".

How to do something similar using the API? do you know of any samples out there?

```<code>import weka.classifiers.bayes.NaiveBayes;
import weka.classifiers.meta.FilteredClassifier;
import weka.classifiers.trees.J48;
import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;
import weka.filters.Filter;
import weka.filters.unsupervised.attribute.NominalToBinary;
import weka.filters.unsupervised.attribute.Remove;

public class WekaTutorial
{

  public static void main(String[] args) throws Exception
  {
    DataSource trainSource = new DataSource("/tmp/classes - edited.arff"); // training
    Instances trainData = trainSource.getDataSet();

    DataSource testSource = new DataSource("/tmp/classes_testing.arff");
    Instances testData = testSource.getDataSet();

    if (trainData.classIndex() == -1)
    {
      trainData.setClassIndex(trainData.numAttributes() - 1);
    }

    if (testData.classIndex() == -1)
    {
      testData.setClassIndex(testData.numAttributes() - 1);
    }

    String[] options = weka.core.Utils.splitOptions("weka.filters.unsupervised.attribute.StringToWordVector -R first-last -W 1000 -prune-rate -1.0 -N 0 -stemmer weka.core.stemmers.NullStemmer -M 1 "
            + "-tokenizer \"weka.core.tokenizers.WordTokenizer -delimiters \" \\r\\n\\t.,;:\\\'\\\"()?!\"");

    Remove remove = new Remove();
    remove.setOptions(options);
    remove.setInputFormat(trainData);

    NominalToBinary filter = new NominalToBinary();

    NaiveBayes nb = new NaiveBayes();

    FilteredClassifier fc = new FilteredClassifier();
    fc.setFilter(filter);
    fc.setClassifier(nb);
    // train and make predictions
    fc.buildClassifier(trainData);

    for (int i = 0; i < testData.numInstances(); i++)
    {
      double pred = fc.classifyInstance(testData.instance(i));
      System.out.print("ID: " + testData.instance(i).value(0));
      System.out.print(", actual: " + testData.classAttribute().value((int) testData.instance(i).classValue()));
      System.out.println(", predicted: " + testData.classAttribute().value((int) pred));
    }

  }

}
</code>```

Error:

Exception in thread "main" java.lang.IllegalArgumentException: Src and Dest differ in # of attributes: 2 != 17152

This was not an issue for the GUI.

答:
You need to ensure that categories in train and test sets are compatible, try to

combine train and test sets

List item

preprocess them

save them as arff

open two empty files

copy the header from the top to line "@data"

copy in training set into first file and test set into second file

Title: Weka output predictions

Body:
I've used the Weka GUI for training and testing a file (making predictions), but can't do the same with the API. The error I'm getting says there's a different number of attributes in the train and test files. In the GUI, this can be solved by checking "Output predictions".

How to do something similar using the API? do you know of any samples out there?

import weka.classifiers.bayes.NaiveBayes;
import weka.classifiers.meta.FilteredClassifier;
import weka.classifiers.trees.J48;
import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;
import weka.filters.Filter;
import weka.filters.unsupervised.attribute.NominalToBinary;
import weka.filters.unsupervised.attribute.Remove;

public class WekaTutorial
{

  public static void main(String[] args) throws Exception
  {
    DataSource trainSource = new DataSource("/tmp/classes - edited.arff"); // training
    Instances trainData = trainSource.getDataSet();

    DataSource testSource = new DataSource("/tmp/classes_testing.arff");
    Instances testData = testSource.getDataSet();

    if (trainData.classIndex() == -1)
    {
      trainData.setClassIndex(trainData.numAttributes() - 1);
    }

    if (testData.classIndex() == -1)
    {
      testData.setClassIndex(testData.numAttributes() - 1);
    }

    String[] options = weka.core.Utils.splitOptions("weka.filters.unsupervised.attribute.StringToWordVector -R first-last -W 1000 -prune-rate -1.0 -N 0 -stemmer weka.core.stemmers.NullStemmer -M 1 "
            + "-tokenizer \"weka.core.tokenizers.WordTokenizer -delimiters \" \\r\\n\\t.,;:\\\'\\\"()?!\"");

    Remove remove = new Remove();
    remove.setOptions(options);
    remove.setInputFormat(trainData);

    NominalToBinary filter = new NominalToBinary();

    NaiveBayes nb = new NaiveBayes();

    FilteredClassifier fc = new FilteredClassifier();
    fc.setFilter(filter);
    fc.setClassifier(nb);
    // train and make predictions
    fc.buildClassifier(trainData);

    for (int i = 0; i < testData.numInstances(); i++)
    {
      double pred = fc.classifyInstance(testData.instance(i));
      System.out.print("ID: " + testData.instance(i).value(0));
      System.out.print(", actual: " + testData.classAttribute().value((int) testData.instance(i).classValue()));
      System.out.println(", predicted: " + testData.classAttribute().value((int) pred));
    }

  }

}

Error:

Exception in thread "main" java.lang.IllegalArgumentException: Src and Dest differ in # of attributes: 2 != 17152

This was not an issue for the GUI.


问:
java.lang.ClassNotFoundException: io.jsonwebtoken.Jwts when using JJWT JSON Web Token
When I am trying to use JJWT from Stormpath, it is throwing a run time Exception java.lang.ClassNotFoundException: io.jsonwebtoken.Jwts. I am using Jersey2 embedded on GlassFish 4.1; here is the code that is throwing the exception:

```<code>private String issueToken(String login) {
    Key key = keyGenerator.generateKey();
    //Key key = MacProvider.generateKey();
        String jwtToken = Jwts.builder()
                .setIssuer(uriInfo.getAbsolutePath().toString())
                //.setIssuer("http://trustyapp.com/")
                .setSubject(login)
                .setIssuedAt(new Date())
                .setExpiration(toDate(LocalDateTime.now().plusMinutes(15L)))
                .signWith(SignatureAlgorithm.HS512, key)
                .compact();
        logger.info("#### generating token for a key : " + jwtToken + " - " + key);
        return jwtToken;
}
</code>```

I have imported io.jsonwebtoken.Jwts and my pom.xml has :

```<code><dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.8.2</version>
        <scope>compile</scope>
    </dependency>
</code>```

i also tried it without the above dependency in case the below dependency which is on my pom.xml is enough:

```<code><dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt</artifactId>
        <version>0.7.0</version>
        <scope>compile</scope>
    </dependency>
</code>```

I tried the recommendations from this and this but it did not work, please help

答:
The problem is solved after adding the following dependencies into my pom.xml:

```<code><dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-common</artifactId>
        <version>${version.jersey}</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-jdk-http</artifactId>
        <version>${version.jersey}</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-client</artifactId>
        <version>${version.jersey}</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
        <version>${version.jersey}</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet</artifactId>
        <version>${version.jersey}</version>
    </dependency>
</code>```

I assumed that such dependencies are not required since i am using Jersey 2 which is embedded on the GlassFish4.1.1 Server.

Body:
When I am trying to use JJWT from Stormpath, it is throwing a run time Exception java.lang.ClassNotFoundException: io.jsonwebtoken.Jwts. I am using Jersey2 embedded on GlassFish 4.1; here is the code that is throwing the exception:

private String issueToken(String login) {
    Key key = keyGenerator.generateKey();
    //Key key = MacProvider.generateKey();
        String jwtToken = Jwts.builder()
                .setIssuer(uriInfo.getAbsolutePath().toString())
                //.setIssuer("http://trustyapp.com/")
                .setSubject(login)
                .setIssuedAt(new Date())
                .setExpiration(toDate(LocalDateTime.now().plusMinutes(15L)))
                .signWith(SignatureAlgorithm.HS512, key)
                .compact();
        logger.info("#### generating token for a key : " + jwtToken + " - " + key);
        return jwtToken;
}

I have imported io.jsonwebtoken.Jwts and my pom.xml has :

<dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.8.2</version>
        <scope>compile</scope>
    </dependency>

i also tried it without the above dependency in case the below dependency which is on my pom.xml is enough:

<dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt</artifactId>
        <version>0.7.0</version>
        <scope>compile</scope>
    </dependency>

I tried the recommendations from this and this but it did not work, please help

Body:
The problem is solved after adding the following dependencies into my pom.xml:

<dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-common</artifactId>
        <version>${version.jersey}</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-jdk-http</artifactId>
        <version>${version.jersey}</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-client</artifactId>
        <version>${version.jersey}</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
        <version>${version.jersey}</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet</artifactId>
        <version>${version.jersey}</version>
    </dependency>

I assumed that such dependencies are not required since i am using Jersey 2 which is embedded on the GlassFish4.1.1 Server.


问:
Magento: add message to add to cart Ajax button
I want to add a message in a div for say 5 seconds,

"Product added to cart" on screen.

As presently, when clicking on the button the product is simply added to the cart, but no message is displayed the product is added to the cart, which for some customers is not clear, whether the product is added.

```<code>The relevant Magento code for add to card is like this:

<div class="add-to-cart-buttons -field -field-actions -clearfix">
<button type="button" title="<?php echo $buttonTitle ?>"
class="button btn-cart -button -button-wide add-to-bag -button-fancy"
onclick="productAddToCartForm.submit(this)"><span><span>
<?php echo $buttonTitle ?></span></span></button>
<?php echo $this->getChildHtml('', true, true) ?></div>
</code>```

update: related Javascript

```<code><script type="text/javascript">
    //<![CDATA[
    var ajaxRequest = true;
        var productAddToCartForm = new VarienForm('product_addtocart_form');
        productAddToCartForm.submit = function(button, url) {
            if (this.validator.validate()) {
                var form = this.form;
                var oldUrl = form.action;

                if (url) {
                   form.action = url;
                }
               if(ajaxRequest) {
                    new Ajax.Request('<?php echo $this->getUrl('sischeckout/cart/add'); ?>',{
                        method: "POST",
                        parameters:form.serialize(),
                        onSuccess: function(transport) {
                            try{

                           data = JSON.parse(transport.responseText);

                                }catch(e){ data = {};
                            }
                            if(!data.status) {
                                 alert(data.message);

                            }
                        },
                        onFailure: function(transport) {
                            alert('Invalid Request');
                        }
                    });
                } else {
                    var e = null;
                    try {
                        this.form.submit();
                    } catch (e) {
                    }

                    this.form.action = oldUrl;
                    if (e) {
                        throw e;
                    }

                    if (button && button != 'undefined') {
                        button.disabled = true;
                    }
                }
            } else {
                    if(ajaxRequest) {
                        alert("Product options are required field.");
                    }
                }
        }.bind(productAddToCartForm);

        productAddToCartForm.submitLight = function(button, url){
            if(this.validator) {
                var nv = Validation.methods;
                delete Validation.methods['required-entry'];
                delete Validation.methods['validate-one-required'];
                delete Validation.methods['validate-one-required-by-name'];
                // Remove custom datetime validators
                for (var methodName in Validation.methods) {
                    if (methodName.match(/^validate-datetime-.*/i)) {
                        delete Validation.methods[methodName];
                    }
                }

                if (this.validator.validate()) {
                    if (url) {
                        this.form.action = url;
                    }
                    this.form.submit();
                }
                Object.extend(Validation.methods, nv);
            }
        }.bind(productAddToCartForm);
    //]]>
    </script>
</code>```

答:
First of all, Magento give message when you add products in to cart. There are two types of settings are available in Magento.

When customer add product in cart then it will redirect to cart page and display message that your product added in cart.

When customer add product the cart then it will stay on same page and display message that your product added in cart.

So you have to check why Magento's default message is not display when customer add product in to cart in your site.

Body:
I want to add a message in a div for say 5 seconds,

"Product added to cart" on screen.

As presently, when clicking on the button the product is simply added to the cart, but no message is displayed the product is added to the cart, which for some customers is not clear, whether the product is added.

The relevant Magento code for add to card is like this:

<button type="button" title="<?php echo $buttonTitle ?>"
class="button btn-cart -button -button-wide add-to-bag -button-fancy"
onclick="productAddToCartForm.submit(this)">
<?php echo $buttonTitle ?></button>
<?php echo $this->getChildHtml('', true, true) ?>

update: related Javascript


问:
Why do I give correct positional arguments but still get back a error message?
I've been having an issue with the following code:

```<code>class User:

def __init__(self, first_name, last_name, **profile):
    self.profile = profile
    self.first_name = first_name
    self.last_name = last_name`
    self.profile['first_name'] = first_name
    self.profile['last_name'] = last_name

def query(self, key):
    value = self.profile[key]
    print('Here is the result:' + '\n\t' + str(value))

class UserVip(User):
def __init__(self, first_name, last_name, **profile):
    super().__init__(self, first_name, last_name, **profile)

ron_weasley = UserVip('ron', 'weasley',
                  age=17,`enter code here
                  school='hogwarts'
                  )
</code>```

And when I ran it，I got back this error message

```<code>TypeError: __init__() takes 3 positional arguments but 4 were given
</code>```

But the '**profile'can recieve any number of arguments,can't it?Then I checked the arguments,and tried like this

```<code>ron_weasley = UserVip('ron', 'weasley',
                      school='hogwarts'
                      )
</code>```

It stil went wrong.I had also tried some other means and  been searching for a long time on net. But no use. Do I misundersand the init(),the inherit or the '**(dict)'?Please help or try to give some ideas how to solve this. Thanks in advance.

答:
First you indentation is wrong for __init__ of UserVip class.

Second, you should use User instead of super() for UserVip's super class constructor. Or you can remove self from the argument

Following code works for me.

```<code>class User:

    def __init__(self, first_name, last_name, **profile):
        self.profile = profile
        self.first_name = first_name
        self.last_name = last_name
        self.profile['first_name'] = first_name
        self.profile['last_name'] = last_name

    def query(self, key):
        value = self.profile[key]
        print('Here is the result:' + '\n\t' + str(value))

class UserVip(User):
    def __init__(self, first_name, last_name, **profile):
        User.__init__(self, first_name, last_name, **profile)

ron_weasley = UserVip('ron', 'weasley', age=17,school='hogwarts')
</code>```

Body:
I've been having an issue with the following code:

class User:

def __init__(self, first_name, last_name, **profile):
    self.profile = profile
    self.first_name = first_name
    self.last_name = last_name`
    self.profile['first_name'] = first_name
    self.profile['last_name'] = last_name

def query(self, key):
    value = self.profile[key]
    print('Here is the result:' + '\n\t' + str(value))

class UserVip(User):
def __init__(self, first_name, last_name, **profile):
    super().__init__(self, first_name, last_name, **profile)

ron_weasley = UserVip('ron', 'weasley',
                  age=17,`enter code here
                  school='hogwarts'
                  )

And when I ran it，I got back this error message

TypeError: __init__() takes 3 positional arguments but 4 were given

But the '**profile'can recieve any number of arguments,can't it?Then I checked the arguments,and tried like this

ron_weasley = UserVip('ron', 'weasley',
                      school='hogwarts'
                      )

It stil went wrong.I had also tried some other means and  been searching for a long time on net. But no use. Do I misundersand the init(),the inherit or the '**(dict)'?Please help or try to give some ideas how to solve this. Thanks in advance.

Body:
First you indentation is wrong for __init__ of UserVip class.

Second, you should use User instead of super() for UserVip's super class constructor. Or you can remove self from the argument

Following code works for me.

class User:

    def __init__(self, first_name, last_name, **profile):
        self.profile = profile
        self.first_name = first_name
        self.last_name = last_name
        self.profile['first_name'] = first_name
        self.profile['last_name'] = last_name

    def query(self, key):
        value = self.profile[key]
        print('Here is the result:' + '\n\t' + str(value))

class UserVip(User):
    def __init__(self, first_name, last_name, **profile):
        User.__init__(self, first_name, last_name, **profile)

ron_weasley = UserVip('ron', 'weasley', age=17,school='hogwarts')


问:
What is universal method for `get or default` in python?
I would like to get an attribute of mongoengine model object but it's missing (how it's often in mongo):

unit.city gives me AttributeError

unit.get('city') says that 'Unit' object has no attribute 'get' and I can't find any appropriate method by dir(unit).

So I have to use standard python statement:

```<code>city = unit.city if 'city' in unit else None
</code>```

That is a bit complex for just a get operation, because I have many transformations of that kind.

And so I wonder if there is any universal method for getting attribute value or some default value (if attribute doesn't exist) — such as get for dict type:

```<code>city = unit.get('city') # None
# or
city = unit.get('city', 'Moscow') # 'Moscow'
</code>```

I would define my own function get but I'm interested if there is any in standard libraries. And yet, from operation import getitem doesn't able to do that.

I use python 2, by the way.

答:
In general python, there are two common patterns. A mix of hasattr + getattr or wrapping the whole thing in try / except

```<code>city = getattr(unit,'city','Moscow')
</code>```

Other approach is

```<code>try:
    city = unit.city
except AttributeError:
    city = None
</code>```

The second is argubly more pythonic. However when you are dealing with databases. It's better to use an ORM and avoid this sort of thing all together.

Body:
I would like to get an attribute of mongoengine model object but it's missing (how it's often in mongo):

unit.city gives me AttributeError

unit.get('city') says that 'Unit' object has no attribute 'get' and I can't find any appropriate method by dir(unit).

So I have to use standard python statement:

city = unit.city if 'city' in unit else None

That is a bit complex for just a get operation, because I have many transformations of that kind.

And so I wonder if there is any universal method for getting attribute value or some default value (if attribute doesn't exist) — such as get for dict type:

city = unit.get('city') # None
# or
city = unit.get('city', 'Moscow') # 'Moscow'

I would define my own function get but I'm interested if there is any in standard libraries. And yet, from operation import getitem doesn't able to do that.

I use python 2, by the way.

Body:
In general python, there are two common patterns. A mix of hasattr + getattr or wrapping the whole thing in try / except

city = getattr(unit,'city','Moscow')

Other approach is

try:
    city = unit.city
except AttributeError:
    city = None

The second is argubly more pythonic. However when you are dealing with databases. It's better to use an ORM and avoid this sort of thing all together.


问:
Java: I have a List of cars that i wanna sort by registrationNumber(String) that is inside one of the elements in the list
I have a ist in java, that has car objects inside, and inside one of the car objects is a String thats named RegistrationNumber, and i wanna sort the list by that
    List cars = new ArrayList();</p>

```<code>public Collection<ICar> sortedByRegistrationNumber() {

}
</code>```

答:
```<code>if (list.size() > 0) {
  Collections.sort(list, new Comparator<Car>() {
      @Override
      public int compare(final Car object1, final Car object2) {
          return object1.getRegNo().compareTo(object2.getRegNo());
      }
  });
}
</code>```

If you are using Java 8 then you can do it like this:

```<code>list.stream()
  .sorted((object1, object2) -> object1.getRegNo().compareTo(object2.getRegNo()));
</code>```

Body:
I have a ist in java, that has car objects inside, and inside one of the car objects is a String thats named RegistrationNumber, and i wanna sort the list by that
    List cars = new ArrayList();

public Collection<ICar> sortedByRegistrationNumber() {

}

Body:
if (list.size() > 0) {
  Collections.sort(list, new Comparator<Car>() {
      @Override
      public int compare(final Car object1, final Car object2) {
          return object1.getRegNo().compareTo(object2.getRegNo());
      }
  });
}

If you are using Java 8 then you can do it like this:

list.stream()
  .sorted((object1, object2) -> object1.getRegNo().compareTo(object2.getRegNo()));


答:
Instead of super, you can also classname in your code.

For example, call parent class __init__ using below code

User.__init__(self, first_name, last_name, **profile)

Hope it solves your problem. !

Title: Why do I give correct positional arguments but still get back a error message?


问:
Remove margin for the div for which width is given in percentage
In styled components of React JS, I have given the width for div in percentage to make it responsive....
But the div is getting margin at right which is making the alignment disturbed.
How to get rid of this margin.

```<code>export const BannerHeaderText = styled.h1`
    width: 46.5%;
    height: 64px;
    font-size: 28px;
    font-weight: 600;
    line-height: 1.14;
    `
export const BannerParagraph = styled.p`
    width: 51.4%;
    height: 40px;
    margin-top: 8px;
    font-size: 16px;
    line-height: 1.5;
    color: #000000;
    opacity: 0.38;
    `
</code>```

I am getting the width as I needed.

```<code><BannerParagraphBlock>

                <BannerHeaderText>
                    Solveing the most common problems in marketing
                </BannerHeaderText>

                <BannerParagraph>
                    Exquisite codially mr happiness of neglected distrusts.
                    Boisterous impossible unaffected he me everything.
                </BannerParagraph>

                <SeeAllProductsButton>{message.SayEffectHomePageSeeAllProductsButton.value}</SeeAllProductsButton>

            </BannerParagraphBlock>
</code>```

Missed Data

BannerHeaderText is h1 and BannerParagrap is p
BannerParagraphBlock is section

答:
As we all know. h1 is a block-level element, so it will occupy the space of the nearest block-level ancestor. For block-level element, the horizontal direction satisfy the below equation:

```<code>'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' = width of containing block
</code>```

The default margin、 padding is 0, and border-style is none, so border width is also 0. Thus, when you apply a specific width to h1, the equation may not satisfy.
This situation is called "over-constrained" when margin-right is ignored and is calculated so as to make the equation true.

```<code>If all of the above have a computed value other than 'auto', the values are
said to be "over-constrained" and one of the used values will have to be
different from its computed value. If the 'direction' property of the
containing block has the value 'ltr', the specified value of 'margin-right'
is ignored and the value is calculated so as to make the equality true. If
the value of 'direction' is 'rtl', this happens to 'margin-left' instead.
</code>```

So, it h1 is block-level element, there is no way to remove the right-margin;

If you just want to center h1, you can set

h1 {
    margin-left: auto;
    margin-right: auto;
}

According to the equation above, the margin-left and margin-right will be calculated to same value, so h1 can be centered in this way;

If you want to position h1 anywhere, you can add margin-left or padding-left to arbitrary value to get your purpose;

Or, as you need, you can change h1 from block-level to inline-block, which will really move the right-margin:

h1 {
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <h1>Hello, title!</h1>
  <p>Hello, world!</p>
</body></code>```

Body:
In styled components of React JS, I have given the width for div in percentage to make it responsive....
But the div is getting margin at right which is making the alignment disturbed.
How to get rid of this margin.

export const BannerHeaderText = styled.h1`
    width: 46.5%;
    height: 64px;
    font-size: 28px;
    font-weight: 600;
    line-height: 1.14;
    `
export const BannerParagraph = styled.p`
    width: 51.4%;
    height: 40px;
    margin-top: 8px;
    font-size: 16px;
    line-height: 1.5;
    color: #000000;
    opacity: 0.38;
    `

I am getting the width as I needed.

<BannerParagraphBlock>

                <BannerHeaderText>
                    Solveing the most common problems in marketing
                </BannerHeaderText>

                <BannerParagraph>
                    Exquisite codially mr happiness of neglected distrusts.
                    Boisterous impossible unaffected he me everything.
                </BannerParagraph>

                <SeeAllProductsButton>{message.SayEffectHomePageSeeAllProductsButton.value}</SeeAllProductsButton>

            </BannerParagraphBlock>

Missed Data

BannerHeaderText is h1 and BannerParagrap is p
BannerParagraphBlock is section

Body:
As we all know. h1 is a block-level element, so it will occupy the space of the nearest block-level ancestor. For block-level element, the horizontal direction satisfy the below equation:

'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' = width of containing block

The default margin、 padding is 0, and border-style is none, so border width is also 0. Thus, when you apply a specific width to h1, the equation may not satisfy.
This situation is called "over-constrained" when margin-right is ignored and is calculated so as to make the equation true.

If all of the above have a computed value other than 'auto', the values are
said to be "over-constrained" and one of the used values will have to be
different from its computed value. If the 'direction' property of the
containing block has the value 'ltr', the specified value of 'margin-right'
is ignored and the value is calculated so as to make the equality true. If
the value of 'direction' is 'rtl', this happens to 'margin-left' instead.

So, it h1 is block-level element, there is no way to remove the right-margin;

If you just want to center h1, you can set

h1 {
    margin-left: auto;
    margin-right: auto;
}

According to the equation above, the margin-left and margin-right will be calculated to same value, so h1 can be centered in this way;

If you want to position h1 anywhere, you can add margin-left or padding-left to arbitrary value to get your purpose;

Or, as you need, you can change h1 from block-level to inline-block, which will really move the right-margin:

h1 {
  display: inline-block;
}

<body>
  <h1>Hello, title!</h1>
  <p>Hello, world!</p>
</body>


问:
Link Storyboard to UIViewController with Generic
I have this view controller, meant to present model object details in a generic way:

```<code>class APIModelDetailsVC<T where T: APIModel>: UIViewController {...}
</code>```

I'd like my storyboard to use this class. I'm able to assign it in Interface Builder:

I do the preparation of this ViewController in a tableview's didSelect method (including specifying the type for the generic placeholder):

```<code>override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
  print("didSelectRowAtIndexPath \(indexPath.row)")
  if let vc = UIStoryboard(name: "APIModelDetailsVC", bundle: nil).instantiateInitialViewController() as? APIModelDetailsVC<StarWarsPerson> {
    vc.model = data[indexPath.row]
    self.navigationController?.pushViewController(vc, animated: true)
  }
}
</code>```

When I attempt to navigate to this view controller, I get the following console error:

```<code>Unknown class _TtC14api_collection17APIModelDetailsVC in Interface Builder file.
</code>```

Is this a documented limitation with Storyboards? Is there a way I can/should specify the generic so the storyboard can link to it?

答:
I just ran into the same problem and came up with another workaround:

I create my generic UIViewController in code only. In IB I then create a UIView in a XIB file that has all the controls I need along with a class called "mainView" that has all the outlets.

In viewDidLoad() of the generic UIViewController I then load the view from the XIB, wire it up and insert it into the view controller's main view  like this:

```<code>class RSListViewController<T: RSObjectProtocol>: UIViewController, UITableViewDelegate {

override func viewDidLoad() {

    super.viewDidLoad()

    guard let mainView = Bundle.main.loadNibNamed("mainView", owner: self, options: nil)?.first as? MainView else { return }

    self.mainView = mainView
    self.mainView.tableView.delegate = self
    self.mainView.segControl.addTarget(self, action: #selector(RSListViewController.listTypeChanged(_:)), for: .valueChanged)

    self.view.addSubview(mainView)

}
</code>```

The only caveat that I can see so far is that you cannot address the outlets directly like

```<code>self.buttonAdd
</code>```

but need to go through the view like

```<code>self.mainView.buttonAdd
</code>```

Instead of actions I wire the the events through code with the addTarget like in the code sample above.

It's kind of a mix if you don't want to do "code only" but in my case it seems to work fine. And it does prevent the creation of many dummy ViewControllers which in my view kind of defies the idea of generics. But this is just a matter of personal taste and does not mean to criticize in any way Federico Ojeda's solution.

Body:
I have this view controller, meant to present model object details in a generic way:

class APIModelDetailsVC<T where T: APIModel>: UIViewController {...}

I'd like my storyboard to use this class. I'm able to assign it in Interface Builder:

I do the preparation of this ViewController in a tableview's didSelect method (including specifying the type for the generic placeholder):

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
  print("didSelectRowAtIndexPath \(indexPath.row)")
  if let vc = UIStoryboard(name: "APIModelDetailsVC", bundle: nil).instantiateInitialViewController() as? APIModelDetailsVC<StarWarsPerson> {
    vc.model = data[indexPath.row]
    self.navigationController?.pushViewController(vc, animated: true)
  }
}

When I attempt to navigate to this view controller, I get the following console error:

Unknown class _TtC14api_collection17APIModelDetailsVC in Interface Builder file.

Is this a documented limitation with Storyboards? Is there a way I can/should specify the generic so the storyboard can link to it?

Body:
I just ran into the same problem and came up with another workaround:

I create my generic UIViewController in code only. In IB I then create a UIView in a XIB file that has all the controls I need along with a class called "mainView" that has all the outlets.

In viewDidLoad() of the generic UIViewController I then load the view from the XIB, wire it up and insert it into the view controller's main view  like this:

class RSListViewController<T: RSObjectProtocol>: UIViewController, UITableViewDelegate {

override func viewDidLoad() {

    super.viewDidLoad()

    guard let mainView = Bundle.main.loadNibNamed("mainView", owner: self, options: nil)?.first as? MainView else { return }

    self.mainView = mainView
    self.mainView.tableView.delegate = self
    self.mainView.segControl.addTarget(self, action: #selector(RSListViewController.listTypeChanged(_:)), for: .valueChanged)

    self.view.addSubview(mainView)

}

The only caveat that I can see so far is that you cannot address the outlets directly like

self.buttonAdd

but need to go through the view like

self.mainView.buttonAdd

Instead of actions I wire the the events through code with the addTarget like in the code sample above.

It's kind of a mix if you don't want to do "code only" but in my case it seems to work fine. And it does prevent the creation of many dummy ViewControllers which in my view kind of defies the idea of generics. But this is just a matter of personal taste and does not mean to criticize in any way Federico Ojeda's solution.


答:
you can pass variables to email template as: </p>

```<code>        Mail::send('emails.templatename', $data, function ($m) {
            $m->from(env('INFO_EMAIL'));
            $m->to(env('PROJECT_EMAIL'), 'admin')->subject('Mail Subject');
        });
</code>```

Title: Laravel pass variables to mail template?

Body:
My problem is that I want to send variables from my EmailController to my mail view and then email to the address. I have tried several things but it didn't work. Hopefully you can help me.

My Controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Mail\Email;
use Mail;

class EmailController extends Controller
{
public function sendMail(Request $request)
{

    $option = $request->input('vraag');
    $title = $request->input('onderwerp');
    $body = $request->input('bericht');
    $email = $request->input('email');
    $gender = $request->input('aanhef');
    $name = $request->input('naam');

    $data = array(
        'option' => $option,
        'title' => $title,
        'body' => $body,
        'e-mail' => $email,
        'gender' => $gender,
        'name' => $name
    );

    $receiverAddress = 'test@example.com';

           return view('emails.email')->with('option', 'title', 'body', 'e-mail', 'gender', 'name');

}
}

I want the request variables to my mail view.
I am getting the error: Undefined variable: data.

My View:

<!DOCTYPE html>

   <title></title>

Contactformulier

   <?php
     echo $data['option'];
   ?>

Body:
you can pass variables to email template as:

        Mail::send('emails.templatename', $data, function ($m) {
            $m->from(env('INFO_EMAIL'));
            $m->to(env('PROJECT_EMAIL'), 'admin')->subject('Mail Subject');
        });


问:
How to use RequestBodyAdvice
```<code>@ControllerAdvice
public class RequestBodyAdviceChain implements RequestBodyAdvice {

    @Override
    public boolean supports(MethodParameter methodParameter, Type type,
            Class< ? extends HttpMessageConverter< ? >> aClass) {
        return true;
    }

    @Override
    public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter,
            Type type, Class< ? extends HttpMessageConverter< ? >> aClass) {
        return o;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter,
            Type type, Class< ? extends HttpMessageConverter< ? >> aClass) throws IOException {
        return httpInputMessage;
    }

    @Override
    public Object afterBodyRead(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type,
            Class< ? extends HttpMessageConverter< ? >> aClass) {
        return o;
    }
}
</code>```

Ideally, flow should reach these function first and then go to controller but it's not working.

答:
You should extend WebMvcConfigurationSupport directly for the more specific configuration (instead of @EnableWebMvc if you follow this approach).

Then override this method org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport#createRequestMappingHandlerAdapter and set your RequestBodyAdvice manually.

This should work

Title: How to use RequestBodyAdvice

Body:
@ControllerAdvice
public class RequestBodyAdviceChain implements RequestBodyAdvice {

    @Override
    public boolean supports(MethodParameter methodParameter, Type type,
            Class< ? extends HttpMessageConverter< ? >> aClass) {
        return true;
    }

    @Override
    public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter,
            Type type, Class< ? extends HttpMessageConverter< ? >> aClass) {
        return o;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter,
            Type type, Class< ? extends HttpMessageConverter< ? >> aClass) throws IOException {
        return httpInputMessage;
    }

    @Override
    public Object afterBodyRead(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type,
            Class< ? extends HttpMessageConverter< ? >> aClass) {
        return o;
    }
}

Ideally, flow should reach these function first and then go to controller but it's not working.


问:
Visual Studio Addin - Child menu items not appearing
Have successfully created the top menu item, trying to create first child item but is not appearing and no exception is being thrown...</p>

```<code>void IDTExtensibility2.OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
{
    _ApplicationObject = (DTE2)application;
    _AddInInstance = (AddIn)addInInst;

    if (connectMode == ext_ConnectMode.ext_cm_Startup)
    {
        object[] contextGUIDS = new object[] { };
        Commands2 commands = (Commands2)_ApplicationObject.Commands;
        CommandBars commandBars = (CommandBars)_ApplicationObject.CommandBars;
        CommandBar cbMainMenu = commandBars["MenuBar"];

        try
        {
            // ROOT MENU
            CommandBarPopup cbpProjectManagement = (CommandBarPopup)cbMainMenu.Controls.Add(MsoControlType.msoControlPopup, Type.Missing, Type.Missing, cbMainMenu.Controls.Count, true);
            cbpProjectManagement.Caption = "ROOTMENU";

            // SUB ITEM
            Command cmdCompiledAssemblies = _ApplicationObject.DTE.Commands.AddNamedCommand(_AddInInstance, "VSPM_CA", "CA",
                String.Empty, true, 0, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled);

            CommandBarControl cbcCompiledAssemblies = (CommandBarControl)cmdCompiledAssemblies.AddControl(cbpProjectManagement.CommandBar, 1);
        }
        catch (Exception ex)
        {
            System.Windows.Forms.MessageBox.Show(ex.ToString());
        }
    }
}
</code>```

Body:
Have successfully created the top menu item, trying to create first child item but is not appearing and no exception is being thrown...

void IDTExtensibility2.OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
{
    _ApplicationObject = (DTE2)application;
    _AddInInstance = (AddIn)addInInst;

    if (connectMode == ext_ConnectMode.ext_cm_Startup)
    {
        object[] contextGUIDS = new object[] { };
        Commands2 commands = (Commands2)_ApplicationObject.Commands;
        CommandBars commandBars = (CommandBars)_ApplicationObject.CommandBars;
        CommandBar cbMainMenu = commandBars["MenuBar"];

        try
        {
            // ROOT MENU
            CommandBarPopup cbpProjectManagement = (CommandBarPopup)cbMainMenu.Controls.Add(MsoControlType.msoControlPopup, Type.Missing, Type.Missing, cbMainMenu.Controls.Count, true);
            cbpProjectManagement.Caption = "ROOTMENU";

            // SUB ITEM
            Command cmdCompiledAssemblies = _ApplicationObject.DTE.Commands.AddNamedCommand(_AddInInstance, "VSPM_CA", "CA",
                String.Empty, true, 0, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled);

            CommandBarControl cbcCompiledAssemblies = (CommandBarControl)cmdCompiledAssemblies.AddControl(cbpProjectManagement.CommandBar, 1);
        }
        catch (Exception ex)
        {
            System.Windows.Forms.MessageBox.Show(ex.ToString());
        }
    }
}

Body:
Full documentation on how to create all sorts of menu's and toolbar's here..

http://www.mztools.com/articles/2005/mz2005003.aspx


问:
ResourceBundle on Android in Assets folder
i´m currently useing ResourceBundles in a pure Java program. Now I want to use the same files inside of an Android app. It works as intended, when the file is placed e.g. at /sdcard/. Is there a way to load them directly from the known android folder structure? e.g. from assets wihtout manually coping them to the sdcard?

This works at the sdcard:

```<code>    File file = new File("/sdcard/");
    URL[] urls = new URL[0];
    try {
       urls = new URL[]{file.toURI().toURL()};

    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    ClassLoader loader = new URLClassLoader(urls);
    ResourceBundle rb = ResourceBundle.getBundle("test", Locale.DEFAULT, loader);
</code>```

This url doesn´t work for the assests folder:

```<code>   urls = new URL[]{new URL("file:///android_asset/test/")};
</code>```

Thanks for any help.

答:
Try creating a resources folder on this path src/main/resources and then put or get your files from there by using ResourceBundle on Android.

It works for me.

Body:
i´m currently useing ResourceBundles in a pure Java program. Now I want to use the same files inside of an Android app. It works as intended, when the file is placed e.g. at /sdcard/. Is there a way to load them directly from the known android folder structure? e.g. from assets wihtout manually coping them to the sdcard?

This works at the sdcard:

    File file = new File("/sdcard/");
    URL[] urls = new URL[0];
    try {
       urls = new URL[]{file.toURI().toURL()};

    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    ClassLoader loader = new URLClassLoader(urls);
    ResourceBundle rb = ResourceBundle.getBundle("test", Locale.DEFAULT, loader);

This url doesn´t work for the assests folder:

   urls = new URL[]{new URL("file:///android_asset/test/")};

Thanks for any help.


问:
VBA Getting a date variable always 3 months in the future
I'm trying to find a way to get VBA to calculate a date 3 months in the future from the current date of the system (also as the 1st day of that future month).

This would be then used in filter below.

```<code>Workbooks(FN1).Worksheets("Sheet1").Range(Final1).AutoFilter Field:=18, Operator:= _
    xlFilterValues, Criteria2:=Array(1, "9/1/2017")
</code>```

Basically what I need is to replace the "9/1/2017" with a variable that gets calculated.

Any help would be greatly appreciated. Thank you!

EDIT: Used below code in the end which works great. However, I just found out a problem which makes it a bit more complicated.

```<code>Workbooks(FN1).Worksheets("Sheet1").Range(Res).AutoFilter Field:=18, Operator:= _
    xlFilterValues, Criteria2:=Array(1, DateSerial(Year(Date), Month(Date) + 3, 1))
</code>```

Seems like the filter needs to be set on multiple years, not just the current year. Recorded, it looks like this.

```<code>ActiveSheet.Range("$A$4:$X$2767").AutoFilter Field:=18, Operator:= _
    xlFilterValues, Criteria2:=Array(1, "9/1/2021", 1, "9/1/2020", 1, "9/1/2019", 1, _
    "9/1/2018", 1, "9/1/2017", 1, "9/1/2016", 1, "9/1/2015", 1, "9/1/2014", 1, "9/1/2013")
</code>```

Problem is, the years will be variable as well (ex: Might not have 2013 in the data source next month but 2022 might be added).
So problem gets more complicated as now I would need something that checks every year in the data source Range(Res).Column("R") and, I assume, would loop through all the years and check the 1st day of the month 3 months in the future.

Or rather is it possible to filter just on the month? So it just picks September (in this case) across all years?

答:
If I understood you correctly, you want to get the date of the first of the month (that is 3 months from now) automatically. For that, you can use a combination of DateAdd and DateAdd function:

```<code>Dim myFirstoftheMonth As Date

myFirstoftheMonth = DateAdd("d", 1, WorksheetFunction.DateAdd(Date, 2))
</code>```

afterwards, you can replace your hard-coded "9/1/2017" with myFirstoftheMonth in your Filter.

Body:
I'm trying to find a way to get VBA to calculate a date 3 months in the future from the current date of the system (also as the 1st day of that future month).

This would be then used in filter below.

Workbooks(FN1).Worksheets("Sheet1").Range(Final1).AutoFilter Field:=18, Operator:= _
    xlFilterValues, Criteria2:=Array(1, "9/1/2017")

Basically what I need is to replace the "9/1/2017" with a variable that gets calculated.

Any help would be greatly appreciated. Thank you!

EDIT: Used below code in the end which works great. However, I just found out a problem which makes it a bit more complicated.

Workbooks(FN1).Worksheets("Sheet1").Range(Res).AutoFilter Field:=18, Operator:= _
    xlFilterValues, Criteria2:=Array(1, DateSerial(Year(Date), Month(Date) + 3, 1))

Seems like the filter needs to be set on multiple years, not just the current year. Recorded, it looks like this.

ActiveSheet.Range("$A$4:$X$2767").AutoFilter Field:=18, Operator:= _
    xlFilterValues, Criteria2:=Array(1, "9/1/2021", 1, "9/1/2020", 1, "9/1/2019", 1, _
    "9/1/2018", 1, "9/1/2017", 1, "9/1/2016", 1, "9/1/2015", 1, "9/1/2014", 1, "9/1/2013")

Problem is, the years will be variable as well (ex: Might not have 2013 in the data source next month but 2022 might be added).
So problem gets more complicated as now I would need something that checks every year in the data source Range(Res).Column("R") and, I assume, would loop through all the years and check the 1st day of the month 3 months in the future.

Or rather is it possible to filter just on the month? So it just picks September (in this case) across all years?

Body:
If I understood you correctly, you want to get the date of the first of the month (that is 3 months from now) automatically. For that, you can use a combination of DateAdd and DateAdd function:

Dim myFirstoftheMonth As Date

myFirstoftheMonth = DateAdd("d", 1, WorksheetFunction.DateAdd(Date, 2))

afterwards, you can replace your hard-coded "9/1/2017" with myFirstoftheMonth in your Filter.


问:
Upper diagonal of a 2D numpy array
This seems simple (and is trivial to write a three-line loop for), but how can I use numpy slicing make a list of the index locations of the upper diagonal of a numpy array? I.e.

Given a 4x4 array, I'd like the index locations at the X's:

```<code>[ X X X X ]
[ 0 X X X ]
[ 0 0 X X ]
[ 0 0 0 X ]
</code>```

Giving:

```<code>[ (0,0), (0,1), (0,2), (0,3), (1,1), (1,2), (1,3), (2,2), (2,3), (3,3) ]
</code>```

答: scipy.linalg.triu and nonzero

Title: Upper diagonal of a 2D numpy array

Body:
This seems simple (and is trivial to write a three-line loop for), but how can I use numpy slicing make a list of the index locations of the upper diagonal of a numpy array? I.e.

Given a 4x4 array, I'd like the index locations at the X's:

[ X X X X ]
[ 0 X X X ]
[ 0 0 X X ]
[ 0 0 0 X ]

Giving:

[ (0,0), (0,1), (0,2), (0,3), (1,1), (1,2), (1,3), (2,2), (2,3), (3,3) ]

Body: scipy.linalg.triu and nonzero


问:
Update a form in parallel with an installation script?
I currently have an installation "framework" that does specific things. What I need now to do is be able to call my form in parallel with my script. Something like this:

```<code>InstallationForm f = new InstallationForm();
Application.Run(f);
InstallSoftware(f);

private static void InstallSoftware(InstallationForm f) {
    f.WriteToTextbox("Starting installation...");
    Utils.Execute(@"C:\temp\setup.msi", @"-s C:\temp\instructions.xml");

    ...

    f.WriteToTextbox("Installation finished");
</code>```

The current way I can do this is by adding the Form.Shown handler in InstallSoftware, but that seems really messy. Is there anyway I can do this better?

答:
Your code will not work, because Application.Run(f) returns not until the form was closed.

You may use a simplified Model/View/Controller pattern. Create an InstallationFormController class that has several events, e.g. for textual notifications to be written to your textbox. The InstallationForm registers on these events in it's OnLoad() method and then calls InstallationFormController.Initialize(). That method starts your installation (on a worker thread/task). That installation callback method fires several text events.

```<code>InstallationForm f = new InstallationForm(new InstallationFormController());
Application.Run(f);

internal class InstallationFormController
{
  public event EventHandler<DataEventArgsT<string>> NotificationTextChanged;

  public InstallationFormController()
  {
  }

  public void Initialize()
  {
    Task.Factory.StartNew(DoInstallation);
  }

  private void DoInstallation()
  {
    ...

    OnNotificationTextChanged(new DataEventArgsT<string>("Installation finished"));
  }

  private void OnNotificationTextChanged(DataEventArgsT<string> e)
  {
    if(NotificationTextChanged != null)
      NotificationTextChanged(this, e);
  }
}

public class DataEventArgsT<T> : EventArgs
{
  ...
  public T Data { get; set; }
}

internal class InstallationForm : Form
{
  private readonly InstallationFormController _controller;

  public InstallationForm()
  {
    InitializeComponent();
  }

  public InstallationForm(InstallationFormController controller) : this()
  {
    if(controller == null)
      throw new ArgumentNullException("controller")

    _controller = controller;
  }

  protected override void OnLoad(EventArgs e)
  {
    base.OnLoad(e);

    _controller.NotificationTextChanged += Controller_NotificationTextChanged;
    _controller.Initialize();
  }

  protected virtual void Controller_NotificationTextChanged(object sender, DataEventArgsT<string> e)
  {
    if(this.InvokeRequired)
    { // call this method on UI thread!!!
      var callback = new EventHandler<DataEventArgsT<string>>(Controller_NotificationTextChanged);
      this.Invoke(callback, new object[] {sender, e});
    }
    else
    {
      _myTextBox.Text = e.Data;
    }
  }
  ...
}
</code>```

Body:
I currently have an installation "framework" that does specific things. What I need now to do is be able to call my form in parallel with my script. Something like this:

InstallationForm f = new InstallationForm();
Application.Run(f);
InstallSoftware(f);

private static void InstallSoftware(InstallationForm f) {
    f.WriteToTextbox("Starting installation...");
    Utils.Execute(@"C:\temp\setup.msi", @"-s C:\temp\instructions.xml");

    ...

    f.WriteToTextbox("Installation finished");

The current way I can do this is by adding the Form.Shown handler in InstallSoftware, but that seems really messy. Is there anyway I can do this better?

Body:
Your code will not work, because Application.Run(f) returns not until the form was closed.

You may use a simplified Model/View/Controller pattern. Create an InstallationFormController class that has several events, e.g. for textual notifications to be written to your textbox. The InstallationForm registers on these events in it's OnLoad() method and then calls InstallationFormController.Initialize(). That method starts your installation (on a worker thread/task). That installation callback method fires several text events.

InstallationForm f = new InstallationForm(new InstallationFormController());
Application.Run(f);

internal class InstallationFormController
{
  public event EventHandler<DataEventArgsT<string>> NotificationTextChanged;

  public InstallationFormController()
  {
  }

  public void Initialize()
  {
    Task.Factory.StartNew(DoInstallation);
  }

  private void DoInstallation()
  {
    ...

    OnNotificationTextChanged(new DataEventArgsT<string>("Installation finished"));
  }

  private void OnNotificationTextChanged(DataEventArgsT<string> e)
  {
    if(NotificationTextChanged != null)
      NotificationTextChanged(this, e);
  }
}

public class DataEventArgsT<T> : EventArgs
{
  ...
  public T Data { get; set; }
}

internal class InstallationForm : Form
{
  private readonly InstallationFormController _controller;

  public InstallationForm()
  {
    InitializeComponent();
  }

  public InstallationForm(InstallationFormController controller) : this()
  {
    if(controller == null)
      throw new ArgumentNullException("controller")

    _controller = controller;
  }

  protected override void OnLoad(EventArgs e)
  {
    base.OnLoad(e);

    _controller.NotificationTextChanged += Controller_NotificationTextChanged;
    _controller.Initialize();
  }

  protected virtual void Controller_NotificationTextChanged(object sender, DataEventArgsT<string> e)
  {
    if(this.InvokeRequired)
    { // call this method on UI thread!!!
      var callback = new EventHandler<DataEventArgsT<string>>(Controller_NotificationTextChanged);
      this.Invoke(callback, new object[] {sender, e});
    }
    else
    {
      _myTextBox.Text = e.Data;
    }
  }
  ...
}


问:
C#: Dateformat in C# for Inserting to sql server
I have a textbox with date format dd/MM/yyyy that I want to convert to the format yyyy-MM-dd to insert it into a database.

I tried

```<code>Convert.DateTime/DateTime.ParseExact
</code>```

but it always give me the system's default date format.

I don't know any other method to convert it in C#...

答:
Hope this works!

DateTime variable= Convert.ToDateTime(your date);

Body:
I have a textbox with date format dd/MM/yyyy that I want to convert to the format yyyy-MM-dd to insert it into a database.

I tried

Convert.DateTime/DateTime.ParseExact

but it always give me the system's default date format.

I don't know any other method to convert it in C#...