问:
Oddly drawn GraphicsPath with Graphics.FillPath
I have written some code which creates a rounded rectangle GraphicsPath, based on a custom structure, BorderRadius (which allows me to define the top left, top right, bottom left and bottom right radius of the rectangle), and the initial Rectangle itself:

```<code>public static GraphicsPath CreateRoundRectanglePath(BorderRadius radius, Rectangle rectangle)
{
    GraphicsPath result = new GraphicsPath();

    if (radius.TopLeft > 0)
    {
        result.AddArc(rectangle.X, rectangle.Y, radius.TopLeft, radius.TopLeft, 180, 90);
    }
    else
    {
        result.AddLine(new System.Drawing.Point(rectangle.X, rectangle.Y), new System.Drawing.Point(rectangle.X, rectangle.Y));
    }
    if (radius.TopRight > 0)
    {
        result.AddArc(rectangle.X + rectangle.Width - radius.TopRight, rectangle.Y, radius.TopRight, radius.TopRight, 270, 90);
    }
    else
    {
        result.AddLine(new System.Drawing.Point(rectangle.X + rectangle.Width, rectangle.Y), new System.Drawing.Point(rectangle.X + rectangle.Width, rectangle.Y));
    }
    if (radius.BottomRight > 0)
    {
        result.AddArc(rectangle.X + rectangle.Width - radius.BottomRight, rectangle.Y + rectangle.Height - radius.BottomRight, radius.BottomRight, radius.BottomRight, 0, 90);
    }
    else
    {
        result.AddLine(new System.Drawing.Point(rectangle.X + rectangle.Width, rectangle.Y + rectangle.Height), new System.Drawing.Point(rectangle.X + rectangle.Width, rectangle.Y + rectangle.Height));
    }
    if (radius.BottomLeft > 0)
    {
        result.AddArc(rectangle.X, rectangle.Y + rectangle.Height - radius.BottomLeft, radius.BottomLeft, radius.BottomLeft, 90, 90);
    }
    else
    {
        result.AddLine(new System.Drawing.Point(rectangle.X, rectangle.Y + rectangle.Height), new System.Drawing.Point(rectangle.X, rectangle.Y + rectangle.Height));
    }

    return result;
}
</code>```

Now if I use this along with FillPath and DrawPath, I notice some odd results:

```<code>GraphicsPath path = CreateRoundRectanglePath(new BorderRadius(8), new Rectangle(10, 10, 100, 100));
e.Graphics.DrawPath(new Pen(Color.Black, 1), path);
e.Graphics.FillPath(new SolidBrush(Color.Black), path);
</code>```

I've zoomed into each resulting Rectangle (right hand side) so you can see clearly, the problem:

What I would like to know is: Why are all of the arcs on the drawn rectangle equal, and all of the arcs on the filled rectangle, odd?

Better still, can it be fixed, so that the filled rectangle draws correctly?

EDIT: Is it possible to fill the inside of a GraphicsPath without using FillPath?

EDIT: As per comments....here is an example of the BorderRadius struct

```<code>public struct BorderRadius
{
    public Int32 TopLeft { get; set; }
    public Int32 TopRight { get; set; }
    public Int32 BottomLeft { get; set; }
    public Int32 BottomRight { get; set; }

    public BorderRadius(int all) : this()
    {
        this.TopLeft = this.TopRight = this.BottomLeft = this.BottomRight = all;
    }
}
</code>```

答:
The real reason for the behavior is explained at Pixel behaviour of FillRectangle and DrawRectangle.

It has to do with the default pixel rounding and the fact that FillRectangle/FillPath with integer coordinates end up drawing in the middle of a pixel and get rounded (according to Graphics.PixelOffsetMode).

On the other hand, DrawRectangle/DrawPath draw with a 1px pen that gets perfectly rounded on the pixel boundaries.

Depending on your usage the solution could be to inflate/deflate the rectangle for FillRectangle/FillPath by .5px.

Body:
I have written some code which creates a rounded rectangle GraphicsPath, based on a custom structure, BorderRadius (which allows me to define the top left, top right, bottom left and bottom right radius of the rectangle), and the initial Rectangle itself:

public static GraphicsPath CreateRoundRectanglePath(BorderRadius radius, Rectangle rectangle)
{
    GraphicsPath result = new GraphicsPath();

    if (radius.TopLeft > 0)
    {
        result.AddArc(rectangle.X, rectangle.Y, radius.TopLeft, radius.TopLeft, 180, 90);
    }
    else
    {
        result.AddLine(new System.Drawing.Point(rectangle.X, rectangle.Y), new System.Drawing.Point(rectangle.X, rectangle.Y));
    }
    if (radius.TopRight > 0)
    {
        result.AddArc(rectangle.X + rectangle.Width - radius.TopRight, rectangle.Y, radius.TopRight, radius.TopRight, 270, 90);
    }
    else
    {
        result.AddLine(new System.Drawing.Point(rectangle.X + rectangle.Width, rectangle.Y), new System.Drawing.Point(rectangle.X + rectangle.Width, rectangle.Y));
    }
    if (radius.BottomRight > 0)
    {
        result.AddArc(rectangle.X + rectangle.Width - radius.BottomRight, rectangle.Y + rectangle.Height - radius.BottomRight, radius.BottomRight, radius.BottomRight, 0, 90);
    }
    else
    {
        result.AddLine(new System.Drawing.Point(rectangle.X + rectangle.Width, rectangle.Y + rectangle.Height), new System.Drawing.Point(rectangle.X + rectangle.Width, rectangle.Y + rectangle.Height));
    }
    if (radius.BottomLeft > 0)
    {
        result.AddArc(rectangle.X, rectangle.Y + rectangle.Height - radius.BottomLeft, radius.BottomLeft, radius.BottomLeft, 90, 90);
    }
    else
    {
        result.AddLine(new System.Drawing.Point(rectangle.X, rectangle.Y + rectangle.Height), new System.Drawing.Point(rectangle.X, rectangle.Y + rectangle.Height));
    }

    return result;
}

Now if I use this along with FillPath and DrawPath, I notice some odd results:

GraphicsPath path = CreateRoundRectanglePath(new BorderRadius(8), new Rectangle(10, 10, 100, 100));
e.Graphics.DrawPath(new Pen(Color.Black, 1), path);
e.Graphics.FillPath(new SolidBrush(Color.Black), path);

I've zoomed into each resulting Rectangle (right hand side) so you can see clearly, the problem:

What I would like to know is: Why are all of the arcs on the drawn rectangle equal, and all of the arcs on the filled rectangle, odd?

Better still, can it be fixed, so that the filled rectangle draws correctly?

EDIT: Is it possible to fill the inside of a GraphicsPath without using FillPath?

EDIT: As per comments....here is an example of the BorderRadius struct

public struct BorderRadius
{
    public Int32 TopLeft { get; set; }
    public Int32 TopRight { get; set; }
    public Int32 BottomLeft { get; set; }
    public Int32 BottomRight { get; set; }

    public BorderRadius(int all) : this()
    {
        this.TopLeft = this.TopRight = this.BottomLeft = this.BottomRight = all;
    }
}


来源: stackexchange

问:
Creating Multiple Google Sheets PDFs throws 429 error
I'm stuck.  I'm hoping someone out there has figured out a way to generate a bunch of PDF's off of Google Sheets.

I run the same report for a list of companies and generate PDF snapshots of each report which are saved in Drive.  I get a 429 error every time with the only difference being how many PDFs I generate before getting the error.

The number of PDFs generated is directly correlated to how long I put in the Utilities.sleep function but still only a fraction of the total number of reports (i.e more sleep = slightly more PDFs generated before error).

I've made several attempts at using exponential backoff, but my attempts have been futile.

Any insights on how to avoid the following 429 are appreciated:

Request failed for docs.google.com/a/[redacted]/spreadsheets/d/[redacted]/… returned code 429. Truncated server response: <!DOCTYPE html><meta name="description" content="Web word processing, presentations and spreadsheets"><meta name="viewport" c... (use muteHttpExceptions option to examine full response

Here's the relevant code:

```<code>var foldersave = DriveApp.createFolder('New Reports').getId()
var request = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken(), muteHttpExceptions: true}};

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var gid = sheet.getSheetId();

var values = ss.getActiveSheet().getRange(2, 8, sheet.getLastRow()-1, 1).getValues();

for (var i = 0; i < values.length; i++) {

//set up the new report
var org = sheet.getRange(5,4);
org.setValue(values[i])

//set the PDF parameters
var pdfOpts = '&size=0&fzr=false&portrait=true&fitw=true&gridlines=false&printtitle=false&sheetnames=false&pagenum=CENTER&attachment=false&gid='+gid;
var printRange = '&c1=0' + '&r1=0' + '&c2=4' + '&r2=42';
var url = ss.getUrl().replace(/edit$/, '') + 'export?format=pdf' + pdfOpts + printRange;

//create the PDF
var response = UrlFetchApp.fetch(url, request).getBlob().setName(values[i] + ".pdf");
var dir = DriveApp.getFolderById(foldersave);
var file = dir.createFile(response);
Utilities.sleep(5000);
}
</code>```

答: 429 error means too many requests. The obvious solution then is to slow down on the request by creating a time delay between calls using sleep(). This has been demoed in this SO post.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm stuck.  I'm hoping someone out there has figured out a way to generate a bunch of PDF's off of Google Sheets.

I run the same report for a list of companies and generate PDF snapshots of each report which are saved in Drive.  I get a 429 error every time with the only difference being how many PDFs I generate before getting the error.

The number of PDFs generated is directly correlated to how long I put in the Utilities.sleep function but still only a fraction of the total number of reports (i.e more sleep = slightly more PDFs generated before error).

I've made several attempts at using exponential backoff, but my attempts have been futile.

Any insights on how to avoid the following 429 are appreciated:

Request failed for docs.google.com/a/[redacted]/spreadsheets/d/[redacted]/… returned code 429. Truncated server response: <!DOCTYPE html><meta name="description" content="Web word processing, presentations and spreadsheets"><meta name="viewport" c... (use muteHttpExceptions option to examine full response

Here's the relevant code:

var foldersave = DriveApp.createFolder('New Reports').getId()
var request = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken(), muteHttpExceptions: true}};

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var gid = sheet.getSheetId();

var values = ss.getActiveSheet().getRange(2, 8, sheet.getLastRow()-1, 1).getValues();

for (var i = 0; i < values.length; i++) {

//set up the new report
var org = sheet.getRange(5,4);
org.setValue(values[i])

//set the PDF parameters
var pdfOpts = '&size=0&fzr=false&portrait=true&fitw=true&gridlines=false&printtitle=false&sheetnames=false&pagenum=CENTER&attachment=false&gid='+gid;
var printRange = '&c1=0' + '&r1=0' + '&c2=4' + '&r2=42';
var url = ss.getUrl().replace(/edit$/, '') + 'export?format=pdf' + pdfOpts + printRange;

//create the PDF
var response = UrlFetchApp.fetch(url, request).getBlob().setName(values[i] + ".pdf");
var dir = DriveApp.getFolderById(foldersave);
var file = dir.createFile(response);
Utilities.sleep(5000);
}


问:
how to solve lazy loading?
I am working android application.I have store 1000 values in database.when i retrieve the data from database,it's take more time to retrieve.how can i solve this problem.help me......... </p>

答:
hi for this u display the rotating progress bar befor u display the date
use the below link link text

and link text

ContentLicense: CC BY-SA 2.5

Title: how to solve lazy loading?


问:
Multiple Methods in one Controler in ASP.Net WebAPI
This is first post on StackOverflow. I am new to WebAPI.

I have WebService in ASP.Net already running and functioning. Our company wants to convert Web Service in to a ASP.Net WebAPI. I have a simple class of few random functions which takes multiple parameters and returns string or bool or decimals. Remember that all 15 methods do not have relation with each other like you can Say Class Name is "GeneralKnowledge"
here are few Functions

```<code>1. public string GetPresidentName(DateTime OnTheDate,string CountryName)
2. public DateTime GetReleaseDateOfMovie(string MovieName)
3. public void AddNewCityNames(string[] CityNames)
</code>```

All of them are WebMethod in Web Service. I want to create WebAPI and I will call them from C#.Net WinForm app or Share this API with other people to collect more data and share more data

The main question is that should I create individual Controller for each method or actions under one controller.

Can you please share any example code when anyone has created multiple methods under one controller.

Thanking you
Ishrar.

答:
You can have as many actions in controller as you want.
Just use attribute routing
attribute-routing-in-web-api-2

I don't recommend adding 15 actions into one controller. You can agregate them into few controllers (like PresidentController, MovieController, RegionController). If Your actions dosn't have anything in common with each other then You can create many different controllers. 15 controllers with one action is easier to maintain and read then one controller with 15 actions.
But best option is to create few controllers with few actions in each.

Sample controller:

```<code>[RoutePrefix("api/presidents")]
public class PresidentsController : ApiController
{
    [Route("GetFirstPresident/{countryName}")]
    public IHttpActionResult GetFirstPresident(string countryName)
    {
        var president = string.Format("First president of {0} was XYZ", countryName);
        return Ok(president);
    }

    [Route("GetPresident/{number}/{countryName}")]
    public IHttpActionResult GetPresident(int number, string countryName)
    {
        var president = string.Format("{1} president of {0} was XYZ", countryName, number);
        return Ok(president);
    }
}
</code>```

WebApiConfig.cs:

```<code>public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}
</code>```

Body:
This is first post on StackOverflow. I am new to WebAPI.

I have WebService in ASP.Net already running and functioning. Our company wants to convert Web Service in to a ASP.Net WebAPI. I have a simple class of few random functions which takes multiple parameters and returns string or bool or decimals. Remember that all 15 methods do not have relation with each other like you can Say Class Name is "GeneralKnowledge"
here are few Functions

1. public string GetPresidentName(DateTime OnTheDate,string CountryName)
2. public DateTime GetReleaseDateOfMovie(string MovieName)
3. public void AddNewCityNames(string[] CityNames)

All of them are WebMethod in Web Service. I want to create WebAPI and I will call them from C#.Net WinForm app or Share this API with other people to collect more data and share more data

The main question is that should I create individual Controller for each method or actions under one controller.

Can you please share any example code when anyone has created multiple methods under one controller.

Thanking you
Ishrar.

Body:
You can have as many actions in controller as you want.
Just use attribute routing
attribute-routing-in-web-api-2

I don't recommend adding 15 actions into one controller. You can agregate them into few controllers (like PresidentController, MovieController, RegionController). If Your actions dosn't have anything in common with each other then You can create many different controllers. 15 controllers with one action is easier to maintain and read then one controller with 15 actions.
But best option is to create few controllers with few actions in each.

Sample controller:

[RoutePrefix("api/presidents")]
public class PresidentsController : ApiController
{
    [Route("GetFirstPresident/{countryName}")]
    public IHttpActionResult GetFirstPresident(string countryName)
    {
        var president = string.Format("First president of {0} was XYZ", countryName);
        return Ok(president);
    }

    [Route("GetPresident/{number}/{countryName}")]
    public IHttpActionResult GetPresident(int number, string countryName)
    {
        var president = string.Format("{1} president of {0} was XYZ", countryName, number);
        return Ok(president);
    }
}

WebApiConfig.cs:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}


问:
stuck in pandas if loop all() any()?
I try to write some basic functions and found me know completely stuck in a quite simple problem regarding the use of if elif else on python pandas dataframe. Here is an example:
dummy data:

```<code>d = {'x': [1, 2, 0, -2, -2], 'y': [3, 4, 5, 4, -4]}
df = pd.DataFrame(data=d)
</code>```

my function:

```<code>def cart2sph(data):  #ceval indicates using numerical expressions
    newDF = pd.DataFrame()
    x = data['x'].astype(float)
    y = data['y'].astype(float)
    if (x == 0).all():
      newDF['angle'] = sign(y)* pi / 2
    else:
      newDF['angle'] = arctan(y/x)
    if (x < 0 and y >= 0).all():
      newDF['angle'] += pi
    elif (x < 0 and y < 0).all():
      newDF['angle'] -= pi
    return newDF
</code>```

I always get the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 11, in cart2sph
  File "C:\Users\tpotrusil\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\generic.py", line 955, in __nonzero__
    .format(self.__class__.__name__))
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

...and can´t see the problem!?!

Very thankful for any help!

答:
It looks like you are misunderstanding what .all() does. Your second if statement (and the following elif) can only be true if all values in the x column are strictly negative. Given that you are calculating angles from the origin for each point, you actually want to consider each row separately.

I think you're looking for something like the following, which applies your angle formula to each row, not the entire dataframe.

```<code>def cart2sph(row):
    ''' Called on each (x, y) row of the dataframe. '''
    x, y = row[['x', 'y']]
    if x == 0:
        angle = sign(y)* pi / 2
    else:
        angle = arctan(y/x)
    if (x < 0) & (y >= 0):
        angle += pi
    elif (x < 0) & (y < 0):
        angle -= pi
    return angle

angles = df.apply(cart2sph, axis=1)
</code>```

There is also a faster way to do this by vectorisation, which should give better performance if your dataframe is large:

```<code># Split the x==0/x!=0 cases and recombine (vectorises the first if statement)
angles = pd.concat([
    arctan(df.y / df.x)[df.x != 0],
    (sign(df.y) * pi / 2)[df.x == 0]]).sort_index()

# Add/subtract for specific cases (vectorises the second if statement)
angles[(df.x < 0) & (df.y >= 0)] += pi
angles[(df.x < 0) & (df.y < 0)] -= pi
</code>```

Title: stuck in pandas if loop all() any()?

Body:
I try to write some basic functions and found me know completely stuck in a quite simple problem regarding the use of if elif else on python pandas dataframe. Here is an example:
dummy data:

d = {'x': [1, 2, 0, -2, -2], 'y': [3, 4, 5, 4, -4]}
df = pd.DataFrame(data=d)

my function:

def cart2sph(data):  #ceval indicates using numerical expressions
    newDF = pd.DataFrame()
    x = data['x'].astype(float)
    y = data['y'].astype(float)
    if (x == 0).all():
      newDF['angle'] = sign(y)* pi / 2
    else:
      newDF['angle'] = arctan(y/x)
    if (x < 0 and y >= 0).all():
      newDF['angle'] += pi
    elif (x < 0 and y < 0).all():
      newDF['angle'] -= pi
    return newDF

I always get the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 11, in cart2sph
  File "C:\Users\tpotrusil\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\generic.py", line 955, in __nonzero__
    .format(self.__class__.__name__))
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

...and can´t see the problem!?!

Very thankful for any help!

Body:
It looks like you are misunderstanding what .all() does. Your second if statement (and the following elif) can only be true if all values in the x column are strictly negative. Given that you are calculating angles from the origin for each point, you actually want to consider each row separately.

I think you're looking for something like the following, which applies your angle formula to each row, not the entire dataframe.

def cart2sph(row):
    ''' Called on each (x, y) row of the dataframe. '''
    x, y = row[['x', 'y']]
    if x == 0:
        angle = sign(y)* pi / 2
    else:
        angle = arctan(y/x)
    if (x < 0) & (y >= 0):
        angle += pi
    elif (x < 0) & (y < 0):
        angle -= pi
    return angle

angles = df.apply(cart2sph, axis=1)

There is also a faster way to do this by vectorisation, which should give better performance if your dataframe is large:

# Split the x==0/x!=0 cases and recombine (vectorises the first if statement)
angles = pd.concat([
    arctan(df.y / df.x)[df.x != 0],
    (sign(df.y) * pi / 2)[df.x == 0]]).sort_index()

# Add/subtract for specific cases (vectorises the second if statement)
angles[(df.x < 0) & (df.y >= 0)] += pi
angles[(df.x < 0) & (df.y < 0)] -= pi


问:
tensorflow: how create an const tensor the same shape as a placeholder
I have a place holder for input:

```<code>Y = tf.placeholder(dtype=tf.float32, shape=(None, n_outputs))
</code>```

Now I want to create a constant the same shape the Y:

```<code>w = Y.get_shape()
zero = tf.constant(np.zeros(w), dtype=tf.float32)
</code>```

Error return:

```<code>__index__ returned non-int (type NoneType)
</code>```

答:
why dont you just build your constant with the same shape as your placeholder, something like this should work.

```<code>zero = tf.constant(0, dtype=tf.float32, shape(none, n_outputs))
</code>```

I think because the placeholder has not been feed any data that is why you are getting an error

Body:
I have a place holder for input:

Y = tf.placeholder(dtype=tf.float32, shape=(None, n_outputs))

Now I want to create a constant the same shape the Y:

w = Y.get_shape()
zero = tf.constant(np.zeros(w), dtype=tf.float32)

Error return:

__index__ returned non-int (type NoneType)

Body:
why dont you just build your constant with the same shape as your placeholder, something like this should work.

zero = tf.constant(0, dtype=tf.float32, shape(none, n_outputs))

I think because the placeholder has not been feed any data that is why you are getting an error


问:
How to stop animation of dragged view?
I have a 2 GridViews, and I can drag items from one to another. But after dropping the view, android plays an animation that moves to the original position of dropped view. Like that:

In that example, I dropped top grid item to bottom grid.

I tried to destroy item and DragShadow after dropping it. But it didn't help.
This animation only plays on devices with Android Nougat OS (24+). So I'm wondering, how can I disable it?

答: It's all about View.OnDragListener. In my example, I had OnDragListener only on topGrid. But if I set OnDragListener on both of them, everything works as expected. I guess, Android thinks that you did't handle drop event, cause view where you dropping item from top doesn't have dragListener

Title: How to stop animation of dragged view?


问:
Binding async method into DropDownList ASP.NET MVC 5
MachineDto:

```<code>[Required(ErrorMessage = "This field is required")]
[Display(Name = "Hardware Type")]
public string HardwareType { get; set; }
public IEnumerable<SelectListItem> ListOfHardwares { get; set; }
</code>```

IHardwareRepository:

```<code>public interface IHardwareRepository
{
Task<Entities.Hardware>> GetAllHardwareAsync();
}
</code>```

HardwareRepository:

```<code>public async Task<List<Entities.Hardware>> GetAllHardwareAsync()
        {
            var getAllHardware = await _appContext.Hardwares.ToListAsync();

            return getAllHardware;
        }
</code>```

View:

```<code><div class="form-group">
            @Html.LabelFor(model => model.HardwareType, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.HardwareType, Model.ListOfHardwares, "--Select--", new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.HardwareType, "", new { @class = "text-danger" })
            </div>
        </div>
</code>```

EDIT:

Controller:

```<code>public class HardwareController : Controller
    {
private readonly IUnitOfWork _unitOfWork;

        public HardwareController(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

public async Task<ActionResult> DisplayAll()
        {
            var displayAll = await _unitOfWork.HardwareRepository.GetAllHardwareAsync();

            return View(displayAll);
        }
}
</code>```

EDIT2:
Controller:

```<code>> public async Task<ActionResult> Add()
>         {
>             var model = new ImageDto();
>             var hardwares = await _unitOfWork.HardwareRepository.GetAllHardwareAsync();
>
>             model.ListOfHardwares = hardwares.Select(h => new SelectListItem
>             {
>                 Text = h.Name,
>                 Value = h.Description
>             });
>
>             return View();
}
</code>```

View:

```<code>@model MachineDto

    <div class="form-group">
        @Html.LabelFor(model => model.HardwareType, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.Model.ListOfHardwares, "--Select--", new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.HardwareType, "", new { @class = "text-danger" })
        </div>
</code>```

The problem is that now I want to pass GetAllHardwareAsync to ListOfHardwares and display it via DropDownList. I don't really want to do it by ViewBag. Any ideas?
Thanks in advance!

答:
Somewhere you simply need to set the value on the model using an instance of the repository.  Where you do this depends on where you have (or can get) an instance of the repository and where you want to set the value on the model.

For example, in the majority of cases, the repository would be on the controller and the controller would build the model to send to the view.  Which might look something like this...

```<code>private IHardwareRepository _repository;

public SomeController(IHardwareRepository repository)
{
    // I'm *assuming* you get the repository from dependency injection
    _repository = repository;
}

public async Task<ActionResult> SomeAction()
{
    var model = new MachineDto();
    model.ListOfHardwares = await _repository.GetAllHardwaresAsync();
    return View(model);
}
</code>```

If you're not using dependency injection, perhaps you'd just instantiate your repository directly?  Something like this:

```<code>public async Task<ActionResult> SomeAction()
{
    var repository = new HardwareRepository();
    var model = new MachineDto();
    model.ListOfHardwares = await repository.GetAllHardwaresAsync();
    return View(model);
}
</code>```

Though that would defeat much of the purpose of the interface.  It's really up to you how you manage your dependencies.  The point is that you simply need to populate your model before sending it to the view.  Then the elements on the view can bind to it.

Edit: Given your edit to the question, it looks like the repository is on a unit of work which is already injected into the controller.  In that case it might look like this:

```<code>public async Task<ActionResult> DisplayAll()
{
    var model = new MachineDto();
    model.ListOfHardwares = await _unitOfWork.HardwareRepository.GetAllHardwareAsync();

    return View(model);
}
</code>```

The view itself would of course also need the model declaration at the top, if you don't already have that (so it knows the model type):

```<code>@model MachineDto
</code>```

Edit: On further inspection, it looks like your model wants an IEnumerable<SelectListItem> instead of just the actual data itself.  I generally recommend doing that sort of projection in the view instead of the model, but not strongly enough to really discourage this practice entirely.  Especially if this "model" is purely a view model for just this view.

In this case all you need is a simple projection.  Once you have your list of results, you can project it to the list of the type you need.  Something like this:

```<code>public async Task<ActionResult> DisplayAll()
{
    var model = new MachineDto();
    var hardwares = await _unitOfWork.HardwareRepository.GetAllHardwareAsync();
    model.ListOfHardwares = hardwares.Select(h => new SelectListItem
    {
        Text = h.SomeTextProperty,
        Value = h.SomeIdentifierProperty
    });
    return View(model);
}
</code>```

What you use for SomeTextProperty and SomeIdentifierProperty depends on what properties exist on Hardware and how you want to use those to build your select list.

Body:
MachineDto:

[Required(ErrorMessage = "This field is required")]
[Display(Name = "Hardware Type")]
public string HardwareType { get; set; }
public IEnumerable<SelectListItem> ListOfHardwares { get; set; }

IHardwareRepository:

public interface IHardwareRepository
{
Task<Entities.Hardware>> GetAllHardwareAsync();
}

HardwareRepository:

public async Task<List<Entities.Hardware>> GetAllHardwareAsync()
        {
            var getAllHardware = await _appContext.Hardwares.ToListAsync();

            return getAllHardware;
        }

View:

            @Html.LabelFor(model => model.HardwareType, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.DropDownListFor(model => model.HardwareType, Model.ListOfHardwares, "--Select--", new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.HardwareType, "", new { @class = "text-danger" })

EDIT:

Controller:

public class HardwareController : Controller
    {
private readonly IUnitOfWork _unitOfWork;

        public HardwareController(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

public async Task<ActionResult> DisplayAll()
        {
            var displayAll = await _unitOfWork.HardwareRepository.GetAllHardwareAsync();

            return View(displayAll);
        }
}

EDIT2:
Controller:

> public async Task<ActionResult> Add()
>         {
>             var model = new ImageDto();
>             var hardwares = await _unitOfWork.HardwareRepository.GetAllHardwareAsync();
>
>             model.ListOfHardwares = hardwares.Select(h => new SelectListItem
>             {
>                 Text = h.Name,
>                 Value = h.Description
>             });
>
>             return View();
}

View:

@model MachineDto

        @Html.LabelFor(model => model.HardwareType, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.DropDownListFor(model => model.Model.ListOfHardwares, "--Select--", new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.HardwareType, "", new { @class = "text-danger" })

The problem is that now I want to pass GetAllHardwareAsync to ListOfHardwares and display it via DropDownList. I don't really want to do it by ViewBag. Any ideas?
Thanks in advance!

Body:
Somewhere you simply need to set the value on the model using an instance of the repository.  Where you do this depends on where you have (or can get) an instance of the repository and where you want to set the value on the model.

For example, in the majority of cases, the repository would be on the controller and the controller would build the model to send to the view.  Which might look something like this...

private IHardwareRepository _repository;

public SomeController(IHardwareRepository repository)
{
    // I'm *assuming* you get the repository from dependency injection
    _repository = repository;
}

public async Task<ActionResult> SomeAction()
{
    var model = new MachineDto();
    model.ListOfHardwares = await _repository.GetAllHardwaresAsync();
    return View(model);
}

If you're not using dependency injection, perhaps you'd just instantiate your repository directly?  Something like this:

public async Task<ActionResult> SomeAction()
{
    var repository = new HardwareRepository();
    var model = new MachineDto();
    model.ListOfHardwares = await repository.GetAllHardwaresAsync();
    return View(model);
}

Though that would defeat much of the purpose of the interface.  It's really up to you how you manage your dependencies.  The point is that you simply need to populate your model before sending it to the view.  Then the elements on the view can bind to it.

Edit: Given your edit to the question, it looks like the repository is on a unit of work which is already injected into the controller.  In that case it might look like this:

public async Task<ActionResult> DisplayAll()
{
    var model = new MachineDto();
    model.ListOfHardwares = await _unitOfWork.HardwareRepository.GetAllHardwareAsync();

    return View(model);
}

The view itself would of course also need the model declaration at the top, if you don't already have that (so it knows the model type):

@model MachineDto

Edit: On further inspection, it looks like your model wants an IEnumerable<SelectListItem> instead of just the actual data itself.  I generally recommend doing that sort of projection in the view instead of the model, but not strongly enough to really discourage this practice entirely.  Especially if this "model" is purely a view model for just this view.

In this case all you need is a simple projection.  Once you have your list of results, you can project it to the list of the type you need.  Something like this:

public async Task<ActionResult> DisplayAll()
{
    var model = new MachineDto();
    var hardwares = await _unitOfWork.HardwareRepository.GetAllHardwareAsync();
    model.ListOfHardwares = hardwares.Select(h => new SelectListItem
    {
        Text = h.SomeTextProperty,
        Value = h.SomeIdentifierProperty
    });
    return View(model);
}

What you use for SomeTextProperty and SomeIdentifierProperty depends on what properties exist on Hardware and how you want to use those to build your select list.


问:
How to remove angular expression attributes from element
I'd like to know whether it's possible to remove Angular expressions dynamically.
I tried the following without any success:

My button

```<code><button myDirective [disabled]="someExpression">Clippy</button>
</code>```

My Directive

```<code>@Directive({
   selector: '[myDirective]'
})
export class MyDirective {
   constructor(private element: ElementRef) {}

   ngOnInit() {
      this.element.nativeElement.removeAttribute('disabled');
   }
}
</code>```

The problem

Initially the button won't be disabled, but once someExpression re-evaluates it'll add the disabled attribute back to the element.

Just for clarification, I want to remove an Angular expression dynamically. In the above example it's [disabled]. But this can be any binding in the future. I want my directive to overrule the existing binding.

答:
```<code><button myDirective [disabled]="hideAttr">Clippy - {{hideAttr}}</button>
</code>```

the disabled attribute is not removed when hideAttr is false

https://plnkr.co/edit/h86IUsny6MiLfRI9tsPx

Body:
I'd like to know whether it's possible to remove Angular expressions dynamically.
I tried the following without any success:

My button

<button myDirective [disabled]="someExpression">Clippy</button>

My Directive

@Directive({
   selector: '[myDirective]'
})
export class MyDirective {
   constructor(private element: ElementRef) {}

   ngOnInit() {
      this.element.nativeElement.removeAttribute('disabled');
   }
}

The problem

Initially the button won't be disabled, but once someExpression re-evaluates it'll add the disabled attribute back to the element.

Just for clarification, I want to remove an Angular expression dynamically. In the above example it's [disabled]. But this can be any binding in the future. I want my directive to overrule the existing binding.

Body:
<button myDirective [disabled]="hideAttr">Clippy - {{hideAttr}}</button>

the disabled attribute is not removed when hideAttr is false

https://plnkr.co/edit/h86IUsny6MiLfRI9tsPx


问:
Local Dev Server for AWS Lambdas
Is there a dev server that runs AWS Lambdas locally? My requirements would be

nodejs server, no ruby or go or anything need to install other than node and npm packages

Creates a server that I can query via wget / curl or an API testing tool to send various events to

I should be able to specify a js file that the server uses as lambda and the server should restart / update when I change that file

答:
Here's a solution that does not require serverless or claudiajs.

I usually just write my own little express script for this purpose. I always just use Lambda Proxy integration so it's simpler.

Something like this...

```<code>const bodyParser = require('body-parser')
const express = require('express')

// Two different Lambda handlers
const { api } = require('../src/api')
const { login } = ('../src/login')

const app = express()

app.use(bodyParser.json())

// route and their handlers
app.post('/login', lambdaProxyWrapper(login))
app.all('/*', lambdaProxyWrapper(api))

app.listen(8200, () => console.info('Server running on port 8200...'))

function lambdaProxyWrapper(handler) {
  return (req, res) => {
    // Here we convert the request into a Lambda event
    const event = {
      httpMethod: req.method,
      queryStringParameters: req.query,
      pathParameters: {
        proxy: req.params[0],
      },
      body: JSON.stringify(req.body),
    }

    return handler(event, null, (err, response) => {
      res.status(response.statusCode)
      res.set(response.headers)

      return res.json(JSON.parse(response.body))
    })
  }
}
</code>```

Then, run it with nodemon so it watches the files and reloads as necessary.

```<code>nodemon --watch '{src,scripts}/**/*.js' scripts/server.js
</code>```

Title: Local Dev Server for AWS Lambdas

Body:
Here's a solution that does not require serverless or claudiajs.

I usually just write my own little express script for this purpose. I always just use Lambda Proxy integration so it's simpler.

Something like this...

const bodyParser = require('body-parser')
const express = require('express')

// Two different Lambda handlers
const { api } = require('../src/api')
const { login } = ('../src/login')

const app = express()

app.use(bodyParser.json())

// route and their handlers
app.post('/login', lambdaProxyWrapper(login))
app.all('/*', lambdaProxyWrapper(api))

app.listen(8200, () => console.info('Server running on port 8200...'))

function lambdaProxyWrapper(handler) {
  return (req, res) => {
    // Here we convert the request into a Lambda event
    const event = {
      httpMethod: req.method,
      queryStringParameters: req.query,
      pathParameters: {
        proxy: req.params[0],
      },
      body: JSON.stringify(req.body),
    }

    return handler(event, null, (err, response) => {
      res.status(response.statusCode)
      res.set(response.headers)

      return res.json(JSON.parse(response.body))
    })
  }
}

Then, run it with nodemon so it watches the files and reloads as necessary.

nodemon --watch '{src,scripts}/**/*.js' scripts/server.js


问:
json-server Is there anyway to declare anon-CLI middleware
Using json-server , we can declare CLI middlewares

```<code>You can add your middlewares from the CLI using --middlewares option:

// hello.js
module.exports = (req, res, next) => {
  res.header('X-Hello', 'World')
   next()
}
json-server db.json --middlewares ./hello.js
json-server db.json --middlewares ./first.js ./second.js
</code>```

But how can I declare an use a json-server middleware in my node.js code ?

I tried to push it into the middleware array

```<code> const jsonServer = require('json-server')
 const apiServer = jsonServer.create()  // Returns an Express server for the API
 const apiMiddlewares = jsonServer.defaults() // Returns middlewares used by JSON Server.

 apiMiddlewares.push((req, res, next)  => {
   console.log(new Date(), req.method, req.url)
   next()
 })

 console.log('API MIDDLEWARES ARRAY: ', apiMiddlewares)
</code>```

It's added into the array, but it's never used... no display

答:
Solved by moving my middleware up to the front ... </p>

```<code>app.use('/api',function(req, res, next){
   console.log('A new request received at ' + Date.now())
   next()
})
</code>```

Body:
Using json-server , we can declare CLI middlewares

You can add your middlewares from the CLI using --middlewares option:

// hello.js
module.exports = (req, res, next) => {
  res.header('X-Hello', 'World')
   next()
}
json-server db.json --middlewares ./hello.js
json-server db.json --middlewares ./first.js ./second.js

But how can I declare an use a json-server middleware in my node.js code ?

I tried to push it into the middleware array

 const jsonServer = require('json-server')
 const apiServer = jsonServer.create()  // Returns an Express server for the API
 const apiMiddlewares = jsonServer.defaults() // Returns middlewares used by JSON Server.

 apiMiddlewares.push((req, res, next)  => {
   console.log(new Date(), req.method, req.url)
   next()
 })

 console.log('API MIDDLEWARES ARRAY: ', apiMiddlewares)

It's added into the array, but it's never used... no display

Body:
Solved by moving my middleware up to the front ...

app.use('/api',function(req, res, next){
   console.log('A new request received at ' + Date.now())
   next()
})


问:
SQL Count total of addresses
Here is my data

```<code>Vehicle    | Street       | Number | Postcode
Car          Fakestreet      3       0010NK
Motorbike    Fakestreet      3       0010NK
Car          Fakestreet      4       0010NK
Car          Fakestreet      1       0010NK
Companycar   Fakestreet      1       0010NK
</code>```

I want to count unique adresses per postcode so this is want I want to see:

```<code>Postcode | Total_adresses
0010NK   | 3
</code>```

I thought this must be a simple query so I have this:

```<code>SELECT Postcode, COUNT(*) AS total_adresses
FROM my_database
WHERE Postcode = '0010NK'
GROUP BY Postcode, Street, Number
</code>```

But I get this result:

```<code>Postcode | total_adresses
0010NK   | 2
0010NK   | 2
0010NK   | 1
</code>```

I can't get my head around why it doesn't give me the desired result. Any ideas why?

答:
Just aggregate by the one column:

```<code>SELECT Postcode, COUNT(*) AS total_adresses
FROM my_database
WHERE Postcode = '0010NK'
GROUP BY Postcode;
</code>```

The combination of keys in the GROUP BY defines each row in the aggregated result set.  You want only one row per Postcode, so that is the only key you should have in the GROUP BY.

EDIT:

To count the number of distinct addresses, use COUNT(DISTINCT).  Here is one way:

```<code>SELECT Postcode, COUNT(DISTINCT CONCAT(STREET, ' ', NUMBER, ' ', POSTALCODE) AS total_adresses
FROM my_database
WHERE Postcode = '0010NK'
GROUP BY Postcode;
</code>```

Some databases support:

```<code>SELECT Postcode, COUNT(DISTINCT STREET, NUMBER, POSTALCODE) AS total_adresses
</code>```

Title: SQL Count total of addresses

Body:
Here is my data

Vehicle    | Street       | Number | Postcode
Car          Fakestreet      3       0010NK
Motorbike    Fakestreet      3       0010NK
Car          Fakestreet      4       0010NK
Car          Fakestreet      1       0010NK
Companycar   Fakestreet      1       0010NK

I want to count unique adresses per postcode so this is want I want to see:

Postcode | Total_adresses
0010NK   | 3

I thought this must be a simple query so I have this:

SELECT Postcode, COUNT(*) AS total_adresses
FROM my_database
WHERE Postcode = '0010NK'
GROUP BY Postcode, Street, Number

But I get this result:

Postcode | total_adresses
0010NK   | 2
0010NK   | 2
0010NK   | 1

I can't get my head around why it doesn't give me the desired result. Any ideas why?

Body:
Just aggregate by the one column:

SELECT Postcode, COUNT(*) AS total_adresses
FROM my_database
WHERE Postcode = '0010NK'
GROUP BY Postcode;

The combination of keys in the GROUP BY defines each row in the aggregated result set.  You want only one row per Postcode, so that is the only key you should have in the GROUP BY.

EDIT:

To count the number of distinct addresses, use COUNT(DISTINCT).  Here is one way:

SELECT Postcode, COUNT(DISTINCT CONCAT(STREET, ' ', NUMBER, ' ', POSTALCODE) AS total_adresses
FROM my_database
WHERE Postcode = '0010NK'
GROUP BY Postcode;

Some databases support:

SELECT Postcode, COUNT(DISTINCT STREET, NUMBER, POSTALCODE) AS total_adresses


问:
OO like behaviour in CSS: inheritance possible?
I have a simple border style say:

```<code>.border
{
   /*content*/
}
</code>```

I want several other classes to inherit this border style. Can this be done in CSS only?
Or do I need to specify it in HTML also?

I want:

```<code>.actionArea : .border
{
     /*content */
}
</code>```

Or can this only be done in HTML like:

```<code><div class="actionArea border"/>
</code>```

It would be very annoying if the latter is only possible.

Update

This works good enough, but still is a bit ugly:

```<code>.actionArea, .otherArea, .anotherArea
{
    /*border specification */
}

.actionArea
{
    /*area specification/*
}

.otherArea
{
    /*area specification/*
}

(..)
</code>```

答:
You may use sass . Probably it is the nesting feature you want to use http://sass-lang.com/#nesting

```<code>table.hl {
  margin: 2em 0;
  td.ln {
    text-align: right;
  }
}

li {
  font: {
    family: serif;
    weight: bold;
    size: 1.2em;
  }
}
</code>```

Or as Oded said you can use LESS . LESS is having some interesting feature one of them is mixins . This is not exactly inheritance but it gives you has-a relationship in css

Example copied from LESS

```<code>.bordered {
  border-top: dotted 1px black;
  border-bottom: solid 2px black;
}

#menu a {
  color: #111;
  .bordered;
}
.post a {
  color: red;
  .bordered;
}
</code>```

Body:
I have a simple border style say:

.border
{
   /*content*/
}

I want several other classes to inherit this border style. Can this be done in CSS only?
Or do I need to specify it in HTML also?

I want:

.actionArea : .border
{
     /*content */
}

Or can this only be done in HTML like:

It would be very annoying if the latter is only possible.

Update

This works good enough, but still is a bit ugly:

.actionArea, .otherArea, .anotherArea
{
    /*border specification */
}

.actionArea
{
    /*area specification/*
}

.otherArea
{
    /*area specification/*
}

(..)

Body:
You may use sass . Probably it is the nesting feature you want to use http://sass-lang.com/#nesting

table.hl {
  margin: 2em 0;
  td.ln {
    text-align: right;
  }
}

li {
  font: {
    family: serif;
    weight: bold;
    size: 1.2em;
  }
}

Or as Oded said you can use LESS . LESS is having some interesting feature one of them is mixins . This is not exactly inheritance but it gives you has-a relationship in css

Example copied from LESS

.bordered {
  border-top: dotted 1px black;
  border-bottom: solid 2px black;
}

#menu a {
  color: #111;
  .bordered;
}
.post a {
  color: red;
  .bordered;
}


问:
WordPress : Use the ID instead of the title for the permalink
Natively WordPress uses the title to generate the permalink but for reasons of confidentiality, I would like not to display the title in the url (for post and custom post type only, not pages).
I would like to use the id for example or a series of numbers and letters.

How to change this when we click on "Edit permalink" or when we create a new post?

EDIT:
I do not want to disable url rewrite in Settings → Permalinks.

答:
In the Settings → Permalinks screen, you can choose one of the more common permalink structures.
You have to choose the first one (Plain) to have the permalinks with id of the post.


问:
How to create 2d array with numpy random.choice for every rows?
I'm trying to create a 2d array (which is a six column and lots of rows) with numpy random choice with unique values between 1 and 50 for every row not all of the array

```<code>np.sort(np.random.choice(np.arange(1,50),size=(100,6),replace=False))
</code>```

But this raises an error.

```<code>ValueError: Cannot take a larger sample than population when 'replace=False'
</code>```

Is it possible to make this with an one liner without a loop

Edit

Okey i get the answer.

These are the results with jupyter %time cellmagic

```<code>#@James' solution
np.stack([np.random.choice(np.arange(1,50),size=6,replace=False) for i in range(1_000_000)])
Wall time: 25.1 s

#@Divakar's solution
np.random.rand(1_000_000, 50).argpartition(6,axis=1)[:,:6]+1
Wall time: 1.36 s

#@CoryKramer's solution
np.array([np.random.choice(np.arange(1, 50), size=6, replace=False) for _ in range(1_000_000)])
Wall time: 25.5 s
</code>```

I changed dtypes of np.empty and np.random.randint on @Paul Panzer's solution because it was not working on my pc.

```<code>3.6.0 |Anaconda custom (64-bit)| (default, Dec 23 2016, 11:57:41) [MSC v.1900 64 bit (AMD64)]
</code>```

Fastest one is

```<code>def pp(n):
    draw = np.empty((n, 6), dtype=np.int64)
    # generating random numbers is expensive, so draw a large one and
    # make six out of one
    draw[:, 0] = np.random.randint(0, 50*49*48*47*46*45, (n,),dtype=np.uint64)
    draw[:, 1:] = np.arange(50, 45, -1)
    draw = np.floor_divide.accumulate(draw, axis=-1)
    draw[:, :-1] -= draw[:, 1:] * np.arange(50, 45, -1)
    # map the shorter ranges (:49, :48, :47) to the non-occupied
    # positions; this amounts to incrementing for each number on the
    # left that is not larger. the nasty bit: if due to incrementing
    # new numbers on the left are "overtaken" then for them we also
    # need to increment.
    for i in range(1, 6):
        coll = np.sum(draw[:, :i] <= draw[:, i, None], axis=-1)
        collidx = np.flatnonzero(coll)
        if collidx.size == 0:
            continue
        coll = coll[collidx]
        tot = coll
        while True:
            draw[collidx, i] += coll
            coll = np.sum(draw[collidx, :i] <= draw[collidx, i, None],  axis=-1)
            relidx = np.flatnonzero(coll > tot)
            if relidx.size == 0:
                break
            coll, tot = coll[relidx]-tot[relidx], coll[relidx]
            collidx = collidx[relidx]

    return draw + 1

#@Paul Panzer' solution
pp(1_000_000)
Wall time: 557 ms
</code>```

Thank you all.

Body:
I'm trying to create a 2d array (which is a six column and lots of rows) with numpy random choice with unique values between 1 and 50 for every row not all of the array

np.sort(np.random.choice(np.arange(1,50),size=(100,6),replace=False))

But this raises an error.

ValueError: Cannot take a larger sample than population when 'replace=False'

Is it possible to make this with an one liner without a loop

Edit

Okey i get the answer.

These are the results with jupyter %time cellmagic

#@James' solution
np.stack([np.random.choice(np.arange(1,50),size=6,replace=False) for i in range(1_000_000)])
Wall time: 25.1 s

#@Divakar's solution
np.random.rand(1_000_000, 50).argpartition(6,axis=1)[:,:6]+1
Wall time: 1.36 s

#@CoryKramer's solution
np.array([np.random.choice(np.arange(1, 50), size=6, replace=False) for _ in range(1_000_000)])
Wall time: 25.5 s

I changed dtypes of np.empty and np.random.randint on @Paul Panzer's solution because it was not working on my pc.

3.6.0 |Anaconda custom (64-bit)| (default, Dec 23 2016, 11:57:41) [MSC v.1900 64 bit (AMD64)]

Fastest one is

def pp(n):
    draw = np.empty((n, 6), dtype=np.int64)
    # generating random numbers is expensive, so draw a large one and
    # make six out of one
    draw[:, 0] = np.random.randint(0, 50*49*48*47*46*45, (n,),dtype=np.uint64)
    draw[:, 1:] = np.arange(50, 45, -1)
    draw = np.floor_divide.accumulate(draw, axis=-1)
    draw[:, :-1] -= draw[:, 1:] * np.arange(50, 45, -1)
    # map the shorter ranges (:49, :48, :47) to the non-occupied
    # positions; this amounts to incrementing for each number on the
    # left that is not larger. the nasty bit: if due to incrementing
    # new numbers on the left are "overtaken" then for them we also
    # need to increment.
    for i in range(1, 6):
        coll = np.sum(draw[:, :i] <= draw[:, i, None], axis=-1)
        collidx = np.flatnonzero(coll)
        if collidx.size == 0:
            continue
        coll = coll[collidx]
        tot = coll
        while True:
            draw[collidx, i] += coll
            coll = np.sum(draw[collidx, :i] <= draw[collidx, i, None],  axis=-1)
            relidx = np.flatnonzero(coll > tot)
            if relidx.size == 0:
                break
            coll, tot = coll[relidx]-tot[relidx], coll[relidx]
            collidx = collidx[relidx]

    return draw + 1

#@Paul Panzer' solution
pp(1_000_000)
Wall time: 557 ms

Thank you all.

Body:
This isn't pure numpy but you could wrap your solution within a list comprehension

>>> rows = 10
>>> cols = 6
>>> np.array([np.random.choice(np.arange(1, 50), size=cols, replace=False) for _ in range(rows)])
array([[ 9, 10, 21, 33, 34, 15],
       [48, 46, 36,  7, 37, 45],
       [21, 15,  5,  9, 31, 26],
       [48, 24, 30, 18, 47, 23],
       [22, 31, 19, 32,  3, 33],
       [35, 44, 15, 46, 20, 43],
       [11, 37, 44,  6, 16, 35],
       [42, 49, 41, 28, 12, 19],
       [19,  6, 32,  3,  1, 22],
       [29, 33, 42,  5, 30, 43]])


问:
ReactiveUI command unsubscription
I have 2 Views and 2 ViewModels:

First View:

```<code>public partial class FirstView : Page
{
    FirstViewModel ViewModel;
    public FirstView()
    {
        ViewModel = new FirstViewModel();
        ViewModel.ShowSecondView.Subscribe(_ =>
        {
            NavigationService.Navigate(new SecondView(ViewModel.ChildViewModel));
        });

        this.DataContext = ViewModel;
        InitializeComponent();
    }
}
</code>```

First ViewModel:

```<code>public class FirstViewModel
{
    SecondViewModel ChildViewModel;
    public ReactiveCommand<Unit, Unit> ShowSecondView { get; set; }
    public FirstViewModel()
    {
        ChildViewModel = new SecondViewModel();
        ShowSecondView = ReactiveCommand.Create(() =>
        {
             ChildViewModel.Reconfigure(...);
        });
    }
}
</code>```

Second View:

```<code>public partial class SecondView : Page
{
    SecondViewModel ViewModel;
    public SecondView(SecondViewModel viewModel)
    {
        ViewModel = viewModel;
        ViewModel.GoBack.Subscribe(_ =>
        {
            DoSomethingHard();
            if(NavigationService != null)  NavigationService.GoBack();
        });
        this.DataContext = ViewModel;
        InitializeComponent();
    }
}
</code>```

Second ViewModel:

```<code>public class SecondViewModel
{
    public ReactiveCommand<Unit, Unit> GoBack { get; set; }
    public FirstViewModel()
    {
        VeryLongInitialization();
        GoBack = ReactiveCommand.Create(() => { });
    }
    public void Reconfigure(...)
    { ... }
}
</code>```

So, when I run FirstViewModel.ShowSecondView several times and run SecondViewModel.GoBack several times, DoSomethingHard() execute also several times on each created SecondView.

Why do I want create ChildViewModel in FilstViewModel once? Because creating of SecondViewModel takes long time. And I don't recreate every time SecondViewModel but only reconfigure it.

My question is how can I unsubscribe ViewModel.GoBack.Subscribe in SecondView?

P.S. Maybe I should not recreate SecondView in FirstView but reconfigure it as well as SecondViewModel?

UPDATE 1 (thanks to Julien Mialon)

I add IDisposable goBackSubscr and it works! Am I right to implement it?

```<code>public partial class SecondView : Page
{
    SecondViewModel ViewModel;
    IDisposable goBackSubscr;
    public SecondView(SecondViewModel viewModel)
    {
        ViewModel = viewModel;
        goBackSubscr = ViewModel.GoBack.Subscribe(_ =>
        {
            DoSomethingHard();
            if(NavigationService != null)  NavigationService.GoBack();
            goBackSubscr.Dispose();
        });
        this.DataContext = ViewModel;
        InitializeComponent();
    }
}
</code>```

答:
use WhenAcitvated on your view:
in constructor of your page (it has to be IViewFor):</p>

```<code> this.WhenActivated(
     disposables =>
     {
         ViewModel.Command.Subscribe(...).(disposables);
     });
</code>```

Title: ReactiveUI command unsubscription

Body:
I have 2 Views and 2 ViewModels:

First View:

public partial class FirstView : Page
{
    FirstViewModel ViewModel;
    public FirstView()
    {
        ViewModel = new FirstViewModel();
        ViewModel.ShowSecondView.Subscribe(_ =>
        {
            NavigationService.Navigate(new SecondView(ViewModel.ChildViewModel));
        });

        this.DataContext = ViewModel;
        InitializeComponent();
    }
}

First ViewModel:

public class FirstViewModel
{
    SecondViewModel ChildViewModel;
    public ReactiveCommand<Unit, Unit> ShowSecondView { get; set; }
    public FirstViewModel()
    {
        ChildViewModel = new SecondViewModel();
        ShowSecondView = ReactiveCommand.Create(() =>
        {
             ChildViewModel.Reconfigure(...);
        });
    }
}

Second View:

public partial class SecondView : Page
{
    SecondViewModel ViewModel;
    public SecondView(SecondViewModel viewModel)
    {
        ViewModel = viewModel;
        ViewModel.GoBack.Subscribe(_ =>
        {
            DoSomethingHard();
            if(NavigationService != null)  NavigationService.GoBack();
        });
        this.DataContext = ViewModel;
        InitializeComponent();
    }
}

Second ViewModel:

public class SecondViewModel
{
    public ReactiveCommand<Unit, Unit> GoBack { get; set; }
    public FirstViewModel()
    {
        VeryLongInitialization();
        GoBack = ReactiveCommand.Create(() => { });
    }
    public void Reconfigure(...)
    { ... }
}

So, when I run FirstViewModel.ShowSecondView several times and run SecondViewModel.GoBack several times, DoSomethingHard() execute also several times on each created SecondView.

Why do I want create ChildViewModel in FilstViewModel once? Because creating of SecondViewModel takes long time. And I don't recreate every time SecondViewModel but only reconfigure it.

My question is how can I unsubscribe ViewModel.GoBack.Subscribe in SecondView?

P.S. Maybe I should not recreate SecondView in FirstView but reconfigure it as well as SecondViewModel?

UPDATE 1 (thanks to Julien Mialon)

I add IDisposable goBackSubscr and it works! Am I right to implement it?

public partial class SecondView : Page
{
    SecondViewModel ViewModel;
    IDisposable goBackSubscr;
    public SecondView(SecondViewModel viewModel)
    {
        ViewModel = viewModel;
        goBackSubscr = ViewModel.GoBack.Subscribe(_ =>
        {
            DoSomethingHard();
            if(NavigationService != null)  NavigationService.GoBack();
            goBackSubscr.Dispose();
        });
        this.DataContext = ViewModel;
        InitializeComponent();
    }
}

Body:
use WhenAcitvated on your view:
in constructor of your page (it has to be IViewFor):

 this.WhenActivated(
     disposables =>
     {
         ViewModel.Command.Subscribe(...).(disposables);
     });


问:
Passing strings between activities, intents not working
I am currently working on a project with a friend, where we have a website hosting login details and such. when a user logs in it returns a token to the app, to use as verification for further api calls by the user. (ie. getting the profile). i need to pass this token across other activities (it is a string), and i tried to use intents, but every time i try it comes up with a nullPointerException , where the class i'm calling the intent from can't find the extra i'm sending. i've tried putting the code for creating the intent at the top of the onCreate method, however this returns 401 errors from the server as (i assume) the token has no value because it hasn't been sent by the server using the JSONObject request yet.
here is the code for the main activity (all links removed)(i also didnt include all the imports and variable declarations as i figured they're un-necessary)

```<code>    String Name,Pass,tokenString;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button) findViewById(R.id.button);
    token = (TextView) findViewById(R.id.TV1);
    name = (EditText) findViewById(R.id.name);
    pass = (EditText) findViewById(R.id.pass);
    register = (Button) findViewById(R.id.button2);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

          Name = name.getText().toString();
            Pass = pass.getText().toString();

            if(Name.equals("") || Pass.equals("")){
                Toast.makeText(MainActivity.this, "Fields cannot be left empty!", Toast.LENGTH_SHORT).show();
            }

            StringRequest stringRequest = new StringRequest(Request.Method.POST, Url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {

                        JSONObject jsonObject =  new JSONObject(response);
                        setToken(jsonObject.getString("token"));

                        launchHomeActivity();

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

                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    if(error.networkResponse.statusCode==401) {
                        Toast.makeText(MainActivity.this, "Incorrect login details, please retry", Toast.LENGTH_SHORT).show();
                    }
                }
            }){
                protected Map<String,String> getParams() throws AuthFailureError{
                    Map<String,String> params = new HashMap<String, String>();
                    params.put("key", "****");
                    params.put("email", Name);
                    params.put("password", Pass);
                    return params;
                }
            };
            MySingleton.getInstance(MainActivity.this).addToRequestQueue(stringRequest);
            name.setText("");
            pass.setText("");

        }

    });
    register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            launchRegisterActivity();
        }
    });

}
private void launchRegisterActivity() {

    Intent intent = new Intent(this, RegisterActivity.class);
    startActivity(intent);
}
private void launchHomeActivity() {

    Intent intent = new Intent(this, Home.class);
    startActivity(intent);
}

private void setToken(String token){
    tokenString = token;

}
public String getToken(){
    return tokenString;
}

public void createIntent(){
    Intent i = new Intent(this, Home.class);
    i.putExtra("Token", getToken());
    startActivity(i);
}
}
</code>```

here is the code for the home activity (the relevant bits) :

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    token = (TextView) findViewById(R.id.TV1) ;
    title = (TextView) findViewById(R.id.welcome_Txt);

    Bundle extras = getIntent().getExtras();

   final String tokenString = extras.getString("Token");

            StringRequest stringRequest = new StringRequest(Request.Method.GET, ProfileUrl, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        // JSONArray jsonArray = new JSONArray(response);
                        JSONObject jsonObject =  new JSONObject(response);
                         title.setText("Welcome back " +  jsonObject.getString("token") + "!");

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

                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }){
                protected Map<String,String> getParams() throws AuthFailureError{
                    Map<String,String> params = new HashMap<String, String>();
                    params.put("key", "****");
                    params.put("Token", tokenString);
                    return params;
                }
            };
            MySingleton.getInstance(Home.this).addToRequestQueue(stringRequest);

        }
</code>```

Any help is greatly appreciated.

(p.s i'm very new to android studio, and learning as i go)

答:
You are calling  launchHomeActivity() after getting Response on OnResponse() and accessToken. But you stored the token  on createIntent() which is never called. So call createIntent() on OnResponse() method after getting token.

And this is not best practice to pass token from Activity to Activity. Better would be store the token on SharedPrefrence and access it from anywherer . Make a singleton SharedPreference class and you can use it on whole application.

Body:
I am currently working on a project with a friend, where we have a website hosting login details and such. when a user logs in it returns a token to the app, to use as verification for further api calls by the user. (ie. getting the profile). i need to pass this token across other activities (it is a string), and i tried to use intents, but every time i try it comes up with a nullPointerException , where the class i'm calling the intent from can't find the extra i'm sending. i've tried putting the code for creating the intent at the top of the onCreate method, however this returns 401 errors from the server as (i assume) the token has no value because it hasn't been sent by the server using the JSONObject request yet.
here is the code for the main activity (all links removed)(i also didnt include all the imports and variable declarations as i figured they're un-necessary)

    String Name,Pass,tokenString;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button) findViewById(R.id.button);
    token = (TextView) findViewById(R.id.TV1);
    name = (EditText) findViewById(R.id.name);
    pass = (EditText) findViewById(R.id.pass);
    register = (Button) findViewById(R.id.button2);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

          Name = name.getText().toString();
            Pass = pass.getText().toString();

            if(Name.equals("") || Pass.equals("")){
                Toast.makeText(MainActivity.this, "Fields cannot be left empty!", Toast.LENGTH_SHORT).show();
            }

            StringRequest stringRequest = new StringRequest(Request.Method.POST, Url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {

                        JSONObject jsonObject =  new JSONObject(response);
                        setToken(jsonObject.getString("token"));

                        launchHomeActivity();

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

                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    if(error.networkResponse.statusCode==401) {
                        Toast.makeText(MainActivity.this, "Incorrect login details, please retry", Toast.LENGTH_SHORT).show();
                    }
                }
            }){
                protected Map<String,String> getParams() throws AuthFailureError{
                    Map<String,String> params = new HashMap<String, String>();
                    params.put("key", "****");
                    params.put("email", Name);
                    params.put("password", Pass);
                    return params;
                }
            };
            MySingleton.getInstance(MainActivity.this).addToRequestQueue(stringRequest);
            name.setText("");
            pass.setText("");

        }

    });
    register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            launchRegisterActivity();
        }
    });

}
private void launchRegisterActivity() {

    Intent intent = new Intent(this, RegisterActivity.class);
    startActivity(intent);
}
private void launchHomeActivity() {

    Intent intent = new Intent(this, Home.class);
    startActivity(intent);
}

private void setToken(String token){
    tokenString = token;

}
public String getToken(){
    return tokenString;
}

public void createIntent(){
    Intent i = new Intent(this, Home.class);
    i.putExtra("Token", getToken());
    startActivity(i);
}
}

here is the code for the home activity (the relevant bits) :

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    token = (TextView) findViewById(R.id.TV1) ;
    title = (TextView) findViewById(R.id.welcome_Txt);

    Bundle extras = getIntent().getExtras();

   final String tokenString = extras.getString("Token");

            StringRequest stringRequest = new StringRequest(Request.Method.GET, ProfileUrl, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        // JSONArray jsonArray = new JSONArray(response);
                        JSONObject jsonObject =  new JSONObject(response);
                         title.setText("Welcome back " +  jsonObject.getString("token") + "!");

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

                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }){
                protected Map<String,String> getParams() throws AuthFailureError{
                    Map<String,String> params = new HashMap<String, String>();
                    params.put("key", "****");
                    params.put("Token", tokenString);
                    return params;
                }
            };
            MySingleton.getInstance(Home.this).addToRequestQueue(stringRequest);

        }

Any help is greatly appreciated.

(p.s i'm very new to android studio, and learning as i go)


问:
How to set condition on UI route in angularjs
I'm new in angular and working on UI routing. My issue is how to set condition when user route to new state. What i want is, when user submit the form it should authenticate form data through Mobile OTP popup before going to next state. In my code everything works fine till form but when user submit form, otp popup open but its get hide when its route to new state. So i think i need to put some condition when user go to next state.
Here are my codes

//APP.JS FILE

```<code>.state('main.step4', {
        url: '/step2/step3/step4',
        templateUrl: 'pages/step4.html'
        }
</code>```

//Controller.js

```<code>$scope.getStep2Form = function($index, selectCarList) {
            $scope.selectCar.step2Form = selectCarList;
            $scope.step2Data = $scope.selectCar;
            console.log($scope.step2Data);
        }
        $scope.getStep3Form = function(step3FormData) {
            $scope.selectCar.step3Data = step3FormData;
            console.log($scope.selectCar);

        }
        $scope.showotp=function(){
            open_modal_menu()
        }
</code>```

//CUSTOM.js

```<code>function open_modal_menu() {
            $('.modal-menu').toggleClass('active-modal-menu');
            $('.modal-menu-overlay').addClass('active-overlay');
        }
</code>```

//SERVICES.js

```<code>angular.module('carmobApp.services', [])

.factory('carListDataFactry', function($http) {

var carListData = [];
return {
  all: function() {
    return $http.get("scripts/content.json").then(function(response) {
      carListData = response.data;
      //console.log(teamListData);
      return carListData;
    });

  },
  get: function(selectCarId) {
    for (var i = 0; i < carListData.length; i++) {
      if (carListData[i].id === parseInt(selectCarId)) {
        //console.log(carListData[i]);
        return carListData[i];
      }
    }
    return null;
  }

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

//HTML

```<code><a ui-sref="main.step4" class="button button-green button-full button-icon submitBtn" ng-model="selectCar.step3Data" ng-click="showotp(); getStep3Form(step3FormData)" ng-disabled="selectCarform.$invalid">
    <i class="ion-arrow-right-c" style="color:#fff;"></i> PROCEED NEXT
</a>
</code>```

答: you can use $location.path(""); for redirecting on any route. in js file u can use normal if and else where as in UI u can use angular directives like ngif ( https://docs.angularjs.org/api/ng/directive/ngIf )and ngfor. </p>

Body:
I'm new in angular and working on UI routing. My issue is how to set condition when user route to new state. What i want is, when user submit the form it should authenticate form data through Mobile OTP popup before going to next state. In my code everything works fine till form but when user submit form, otp popup open but its get hide when its route to new state. So i think i need to put some condition when user go to next state.
Here are my codes

//APP.JS FILE

.state('main.step4', {
        url: '/step2/step3/step4',
        templateUrl: 'pages/step4.html'
        }

//Controller.js

$scope.getStep2Form = function($index, selectCarList) {
            $scope.selectCar.step2Form = selectCarList;
            $scope.step2Data = $scope.selectCar;
            console.log($scope.step2Data);
        }
        $scope.getStep3Form = function(step3FormData) {
            $scope.selectCar.step3Data = step3FormData;
            console.log($scope.selectCar);

        }
        $scope.showotp=function(){
            open_modal_menu()
        }

//CUSTOM.js

function open_modal_menu() {
            $('.modal-menu').toggleClass('active-modal-menu');
            $('.modal-menu-overlay').addClass('active-overlay');
        }

//SERVICES.js

angular.module('carmobApp.services', [])

.factory('carListDataFactry', function($http) {

var carListData = [];
return {
  all: function() {
    return $http.get("scripts/content.json").then(function(response) {
      carListData = response.data;
      //console.log(teamListData);
      return carListData;
    });

  },
  get: function(selectCarId) {
    for (var i = 0; i < carListData.length; i++) {
      if (carListData[i].id === parseInt(selectCarId)) {
        //console.log(carListData[i]);
        return carListData[i];
      }
    }
    return null;
  }

};
});

//HTML

     PROCEED NEXT


问:
Unable to access vue data in basic modal
I am trying to loop and reference vue data values within a modal and am getting an error that the field needs to be reactive, despite the values being provided in the component initialization. Any idea why this is?

Fiddle:
https://jsfiddle.net/mwLbw11k/2618/

JS

```<code>// register modal component
Vue.component('modal', {
  template: '#modal-template'
})

// start app
new Vue({
  el: '#app',
  data: {
    myData: [{'first': 'Matt', 'last': 'Smith'}, {'first': 'Tom', 'last': 'Brady'}],
    showModal: false
  }
})
</code>```

HTML

```<code><script type="text/x-template" id="modal-template">
  <transition name="modal">
    <div class="modal-mask">
      <div class="modal-wrapper">
        <div class="modal-container">

          <div class="modal-header">
            <slot name="header">
              default header
            </slot>
          </div>

          <div class="modal-body">
            <slot name="body">
              <ul>
                <li v-for="user in myData"> {{ user.first }} {{ user.last }}</li>
              </ul>
            </slot>
          </div>

          <div class="modal-footer">
            <slot name="footer">
              default footer
              <button class="modal-default-button" @click="$emit('close')">
                OK
              </button>
            </slot>
          </div>
        </div>
      </div>
    </div>
  </transition>
</script>

<!-- app -->
<div id="app">
  <button id="show-modal" @click="showModal = true">Show Modal</button>
  <!-- use the modal component, pass in the prop -->
  <modal v-if="showModal" @close="showModal = false">
  </modal>
</div>
</code>```

Vue Warning

```<code>[Vue warn]: Property or method "myData" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.
</code>```

答:
corrected demo from Bsalex</p>

```<code><modal v-if="showModal" :my-data="myData" @close="showModal = false">
</code>```

Body:
I am trying to loop and reference vue data values within a modal and am getting an error that the field needs to be reactive, despite the values being provided in the component initialization. Any idea why this is?

Fiddle:
https://jsfiddle.net/mwLbw11k/2618/

JS

// register modal component
Vue.component('modal', {
  template: '#modal-template'
})

// start app
new Vue({
  el: '#app',
  data: {
    myData: [{'first': 'Matt', 'last': 'Smith'}, {'first': 'Tom', 'last': 'Brady'}],
    showModal: false
  }
})

HTML

  <button id="show-modal" @click="showModal = true">Show Modal</button>

  <modal v-if="showModal" @close="showModal = false">
  </modal>

Vue Warning

[Vue warn]: Property or method "myData" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

Body:
corrected demo from Bsalex

<modal v-if="showModal" :my-data="myData" @close="showModal = false">


问:
Draw several pcolormesh at different positions
I would like to draw a pcolormesh (here called qm2) with its left bottom pixel in a given position according to another pcolormesh (here called qm1).

I tried following:

```<code>import matplotlib.pyplot as plt
import numpy as np

if __name__ == '__main__':

    s_det = 4
    s_array = 14

    x_shift = 5
    y_shift = 5

    array = np.zeros([s_array, s_array])
    det = np.random.randint(0, 2, [s_det, s_det])

    qm1 = plt.pcolormesh(array, alpha=.0)
    qm2 = plt.pcolormesh(det, cmap='Oranges', edgecolor='black')
    qm2.set_offset_position('data')
    qm2.set_offsets = ([x_shift, y_shift])

    ax = plt.axes()
    ax.set_aspect('equal')
    plt.show()
</code>```

But qm2 remains un-shifted.

I expected something like this:

答:
Apparently the "data" argument is ignored, such that when doing

```<code>qm2.set_offset_position('data')
qm2.set_offsets([x_shift, y_shift])
</code>```

the shift is still in pixels, not in data coordinates.

A workaround would be to define your own transform and add it in front of the existing ones:

```<code>trans = matplotlib.transforms.Affine2D().translate(x_shift, y_shift)
qm2.set_transform(trans + qm2.get_transform())
</code>```

Complete example:

```<code>import matplotlib.pyplot as plt
import numpy as np
import matplotlib.transforms

s_det = 4
s_array = 14

x_shift = 5
y_shift = 5

array = np.zeros([s_array, s_array])
det = np.random.randint(0, 2, [s_det, s_det])

qm1 = plt.pcolormesh(array, alpha=.0)
qm2 = plt.pcolormesh(det, cmap='Oranges', edgecolor='black')

trans = matplotlib.transforms.Affine2D().translate(x_shift, y_shift)
qm2.set_transform(trans + qm2.get_transform())

ax = plt.gca()
ax.set_aspect('equal')
plt.show()
</code>```

Body:
I would like to draw a pcolormesh (here called qm2) with its left bottom pixel in a given position according to another pcolormesh (here called qm1).

I tried following:

import matplotlib.pyplot as plt
import numpy as np

if __name__ == '__main__':

    s_det = 4
    s_array = 14

    x_shift = 5
    y_shift = 5

    array = np.zeros([s_array, s_array])
    det = np.random.randint(0, 2, [s_det, s_det])

    qm1 = plt.pcolormesh(array, alpha=.0)
    qm2 = plt.pcolormesh(det, cmap='Oranges', edgecolor='black')
    qm2.set_offset_position('data')
    qm2.set_offsets = ([x_shift, y_shift])

    ax = plt.axes()
    ax.set_aspect('equal')
    plt.show()

But qm2 remains un-shifted.

I expected something like this:

Body:
Apparently the "data" argument is ignored, such that when doing

qm2.set_offset_position('data')
qm2.set_offsets([x_shift, y_shift])

the shift is still in pixels, not in data coordinates.

A workaround would be to define your own transform and add it in front of the existing ones:

trans = matplotlib.transforms.Affine2D().translate(x_shift, y_shift)
qm2.set_transform(trans + qm2.get_transform())

Complete example:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.transforms

s_det = 4
s_array = 14

x_shift = 5
y_shift = 5

array = np.zeros([s_array, s_array])
det = np.random.randint(0, 2, [s_det, s_det])

qm1 = plt.pcolormesh(array, alpha=.0)
qm2 = plt.pcolormesh(det, cmap='Oranges', edgecolor='black')

trans = matplotlib.transforms.Affine2D().translate(x_shift, y_shift)
qm2.set_transform(trans + qm2.get_transform())

ax = plt.gca()
ax.set_aspect('equal')
plt.show()


答:
You can create each row by itself and then stack them.</p>

```<code>np.stack([np.random.choice(np.arange(1,50),size=6,replace=False) for i in range(100)])
</code>```

Title: How to create 2d array with numpy random.choice for every rows?

Body:
You can create each row by itself and then stack them.

np.stack([np.random.choice(np.arange(1,50),size=6,replace=False) for i in range(100)])


问:
Linking Angular 4 and OpenLayers 4
I have two components:

map

controls

I want the buttons on the controls component to interact with the map. Example adding an interaction to the map:

Controls component:

HTML: <button (click)="add_a_place()" type="button">Add a place</button>

JS: add_a_place() {map.addInteraction(draw_interaction)}

Map component:

JS:

var draw_interaction =  new ol.interaction.Draw({
            source: vector_source,
            type: "Point"
     });
    var map = new ol.Map({
      target: "map",
      layers: [vector_layer],
      view: new ol.View({
          center: [0, 0],
          zoom: 2
        })
    });

Any idea how this could/should be done?

I am using:

Angular 4.0.0

OpenLayers 4.1.1

答:
Here's what I've done to achieve this:

Using component interaction (https://angular.io/guide/component-interaction), I included controlComponent inside mapComponent. Using an eventEmitter, I tell the mapComponent what to do (managing the map inside the MapComponent allows you to use different controlComponent).

MapComponent (HTML) :

```<code><app-control (add_a_place)="add_a_place($event)"> </app-control>
</code>```

MapComponent (TS) :

```<code>add_a_place(event) {
 var draw_interaction =  new ol.interaction.Draw({
        source: vector_source,
        type: "Point"
 });
   var map = new ol.Map({
   target: "map",
   layers: [vector_layer],
   view: new ol.View({
      center: [0, 0],
      zoom: 2
      })
   });
   map.addInteraction(draw_interaction);
}
</code>```

Controls component (HTML):

```<code><button (click)="sendInfo()" type="button">Add a place</button>
</code>```

JS:

```<code>export class VoterComponent {
// change 'any' to the desired type, this is optional
@Output() add_a_place= new EventEmitter<any>();

sendInfo() {
    // this will call MapComponent's add_a_place function
    this.add_a_place.emit('you can pass an argument of type "any" to the mapComponent, depending on the eventEmitter above, but this is optional');
}
</code>```

Don't hesitate if you have questions or if I wasn't clear.

This is the logic for inclusion of 'angular-made' controls, but you can also add openlayers's controls see: https://openlayers.org/en/latest/examples/custom-controls.html

But you could also include MapComponent inside an overlayComponent which includes controls, in which case you would have to reverse the component interaction logic (just ignore this if it isn't clear).

Title: Linking Angular 4 and OpenLayers 4

Body:
Here's what I've done to achieve this:

Using component interaction (https://angular.io/guide/component-interaction), I included controlComponent inside mapComponent. Using an eventEmitter, I tell the mapComponent what to do (managing the map inside the MapComponent allows you to use different controlComponent).

MapComponent (HTML) :

<app-control (add_a_place)="add_a_place($event)"> </app-control>

MapComponent (TS) :

add_a_place(event) {
 var draw_interaction =  new ol.interaction.Draw({
        source: vector_source,
        type: "Point"
 });
   var map = new ol.Map({
   target: "map",
   layers: [vector_layer],
   view: new ol.View({
      center: [0, 0],
      zoom: 2
      })
   });
   map.addInteraction(draw_interaction);
}

Controls component (HTML):

<button (click)="sendInfo()" type="button">Add a place</button>

JS:

export class VoterComponent {
// change 'any' to the desired type, this is optional
@Output() add_a_place= new EventEmitter<any>();

sendInfo() {
    // this will call MapComponent's add_a_place function
    this.add_a_place.emit('you can pass an argument of type "any" to the mapComponent, depending on the eventEmitter above, but this is optional');
}

Don't hesitate if you have questions or if I wasn't clear.

This is the logic for inclusion of 'angular-made' controls, but you can also add openlayers's controls see: https://openlayers.org/en/latest/examples/custom-controls.html

But you could also include MapComponent inside an overlayComponent which includes controls, in which case you would have to reverse the component interaction logic (just ignore this if it isn't clear).


问:
How to dotnet publish with precompiled views for a non portable target?
I have this script:

```<code># common paths
$buildFolder = (Get-Item -Path "./" -Verbose).FullName
$slnFolder = Join-Path $buildFolder "../"
$outputFolder = Join-Path $buildFolder "build"
$webMvcFolder = Join-Path $slnFolder "ConversioIt.Conmania"

# clear existing folder
Remove-Item $outputFolder -Force -Recurse -ErrorAction Ignore
New-Item -Path $outputFolder -ItemType Directory

# restore nuget
Set-Location $slnFolder
dotnet restore

# publish
Set-Location $webMvcFolder
dotnet publish --output (Join-Path $outputFolder "Portable")
dotnet publish --output (Join-Path $outputFolder "Win") -c Release -r win-x64
dotnet publish --output (Join-Path $outputFolder "Linux") -c Release -r linux-x64
dotnet publish --output (Join-Path $outputFolder "OSX") -c Release -r osx-x64
pause
</code>```

My portable output (the first dotnet publish) does precompile the views.

However my Windows, Linuxs and OSX builds do not precompile the views. Instead I get the Areafolder with all the views in the publishing output.

I also set the MvcRazorCompileOnPublish property per this answer:

```<code><PropertyGroup>
  <TargetFramework>netcoreapp2.0</TargetFramework>
  <TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
  <MvcRazorCompileOnPublish>true</MvcRazorCompileOnPublish>
</PropertyGroup>
</code>```

Which does nothing change. I also use the AspNetCore.All Metapackage (2.0), which should automaticly define everything needed for precompilation, if I understood it correct?

So how can I make a standalone build (Which is runnable without .net, e.g. Linux/Win builds) to precompile the views?

答: Razor view precompilation is currently unavailable when performing a self-contained deployment (SCD) in ASP.NET Core 2.0. The feature will be available for SCDs when 2.1 releases. For more information, see View compilation fails when cross-compiling for Linux on Windows.</p>

Body:
I have this script:

# common paths
$buildFolder = (Get-Item -Path "./" -Verbose).FullName
$slnFolder = Join-Path $buildFolder "../"
$outputFolder = Join-Path $buildFolder "build"
$webMvcFolder = Join-Path $slnFolder "ConversioIt.Conmania"

# clear existing folder
Remove-Item $outputFolder -Force -Recurse -ErrorAction Ignore
New-Item -Path $outputFolder -ItemType Directory

# restore nuget
Set-Location $slnFolder
dotnet restore

# publish
Set-Location $webMvcFolder
dotnet publish --output (Join-Path $outputFolder "Portable")
dotnet publish --output (Join-Path $outputFolder "Win") -c Release -r win-x64
dotnet publish --output (Join-Path $outputFolder "Linux") -c Release -r linux-x64
dotnet publish --output (Join-Path $outputFolder "OSX") -c Release -r osx-x64
pause

My portable output (the first dotnet publish) does precompile the views.

However my Windows, Linuxs and OSX builds do not precompile the views. Instead I get the Areafolder with all the views in the publishing output.

I also set the MvcRazorCompileOnPublish property per this answer:

<PropertyGroup>
  <TargetFramework>netcoreapp2.0</TargetFramework>
  <TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
  <MvcRazorCompileOnPublish>true</MvcRazorCompileOnPublish>
</PropertyGroup>

Which does nothing change. I also use the AspNetCore.All Metapackage (2.0), which should automaticly define everything needed for precompilation, if I understood it correct?

So how can I make a standalone build (Which is runnable without .net, e.g. Linux/Win builds) to precompile the views?


问:
Getting error when mouse hover an element
Getting error when mouse hover an element with below code in selenium:

```<code>public void our_medicines(String locatorType, String value) {
 try {
  By locator;
  locator = locatorValue(locatorType, value);
  Actions action = new Actions(driver);
  WebDriverWait wait = new WebDriverWait(driver, 10);
  WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
  action.moveToElement(element).click().build().perform();
 } catch (Exception e) {
  System.err.format("no such element to mousehover" + e);
 }
}
</code>```

This is my locatorValue method:

```<code>public By locatorValue(String locatorTpye, String value) {
 By by;
 switch (locatorTpye) {
  case "id":
   by = By.id(value);
   break;
  case "name":
   by = By.name(value);
   break;
  case "xpath":
   by = By.xpath(value);
   break;
  case "css":
   by = By.cssSelector(value);
   break;
  case "linkText":
   by = By.linkText(value);
   break;
  case "partialLinkText":
   by = By.partialLinkText(value);
   break;
  case "className":
   by = By.className(value);
   break;
  default:
   by = null;
   break;
 }
 return by;
}
</code>```

答:
Okay so the problem I found with your locatorValue method was that it could not handle unspecified locators in this block

```<code>default: by = null;
 break;
 }
 return by; }
</code>```

I added something simple just to deal with that, but you can tune it however you want

```<code>default: throw new Exception("Locator type not defined");
}
return by; }
</code>```

Make sure the locatorType parameter being passed to public void our_medicinesis a valid Locator type.

Body:
Getting error when mouse hover an element with below code in selenium:

public void our_medicines(String locatorType, String value) {
 try {
  By locator;
  locator = locatorValue(locatorType, value);
  Actions action = new Actions(driver);
  WebDriverWait wait = new WebDriverWait(driver, 10);
  WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
  action.moveToElement(element).click().build().perform();
 } catch (Exception e) {
  System.err.format("no such element to mousehover" + e);
 }
}

This is my locatorValue method:

public By locatorValue(String locatorTpye, String value) {
 By by;
 switch (locatorTpye) {
  case "id":
   by = By.id(value);
   break;
  case "name":
   by = By.name(value);
   break;
  case "xpath":
   by = By.xpath(value);
   break;
  case "css":
   by = By.cssSelector(value);
   break;
  case "linkText":
   by = By.linkText(value);
   break;
  case "partialLinkText":
   by = By.partialLinkText(value);
   break;
  case "className":
   by = By.className(value);
   break;
  default:
   by = null;
   break;
 }
 return by;
}

Body:
Okay so the problem I found with your locatorValue method was that it could not handle unspecified locators in this block

default: by = null;
 break;
 }
 return by; }

I added something simple just to deal with that, but you can tune it however you want

default: throw new Exception("Locator type not defined");
}
return by; }

Make sure the locatorType parameter being passed to public void our_medicinesis a valid Locator type.


问:
How to add a script in a partial view in MVC4?
This is the code which I have in my partial view

```<code>@model Contoso.MvcApplication.Models.Exercises.AbsoluteArithmetic

@using(Html.BeginForm())
{
<div>
    <span style="width: 110px; float:left; text-align:center; font-size:2.5em;">@Model.Number1</span>
    <span style="width: 110px; float:left; text-align:center; font-size:2.5em;">+</span>
    <span style="width: 110px; float:left; text-align:center; font-size:2.5em;">@Model.Number2</span>
    <span style="width: 110px; float:left; text-align:center; font-size:2.5em;">=</span>
    <span>
            @Html.EditorFor(model => model.Result)
            @Html.ValidationMessageFor(model => model.Result)
    </span>
</div>
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
</code>```

Please note at the bottom of my code, I've got a @section, and I realized that it's not running if I set a breakpoint there. If I move that line in the _Layout.cshtml it works well, but that's not the idea.

How can I tell to MVC4 in a partial razor view that I want to add that library?

答:
You can add the script directly at the end of the partial view html, without script section (because script section is not rendered in partial views)</p>

```<code><script language="javascript">
   // Your scripts here
   // ....
</script>
</code>```

Body:
This is the code which I have in my partial view

@model Contoso.MvcApplication.Models.Exercises.AbsoluteArithmetic

@using(Html.BeginForm())
{

    @Model.Number1
    +
    @Model.Number2
    =

            @Html.EditorFor(model => model.Result)
            @Html.ValidationMessageFor(model => model.Result)

}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Please note at the bottom of my code, I've got a @section, and I realized that it's not running if I set a breakpoint there. If I move that line in the _Layout.cshtml it works well, but that's not the idea.

How can I tell to MVC4 in a partial razor view that I want to add that library?

Body:
You can add the script directly at the end of the partial view html, without script section (because script section is not rendered in partial views)

<script language="javascript">
   // Your scripts here
   // ....
</script>


问:
Variable arguments inside a macro
I have two functions foo1(a,b) & foo2(a,b,c) and a macro

```<code>#define add(a,b) foo(a,b)
</code>```

I need to re-define macro to accomplish,

1.if add() is called with 2 parameters, then call foo1

if add() is called with 3 parameters then call foo2

Im new to the option VA_ARGS. How can I do that

答:
That usual trick for counting arguments may be adapted for this:

```<code>#define ADD_EXPAND(...) \
        ADD_EXPAND_(__VA_ARGS__, EXPAND_ADD_FUNCS())

#define ADD_EXPAND_(...) \
        EXPAND_ADD_SEL_FUNC(__VA_ARGS__)

#define EXPAND_ADD_SEL_FUNC(first_, second_, third_, func, ...) func

#define EXPAND_ADD_FUNCS() foo2, foo, dummy

#define add(...) ADD_EXPAND(__VA_ARGS__)(__VA_ARGS__)
</code>```

Once you plow through the boiler plate, it basically just involves placing all the arguments in a line, with the function tokens after them, and seeing which function stands out. That's what EXPAND_ADD_SEL_FUNC does.

You can see it live on coliru.

But I'll reiterate what we told you in comments. This is likely to be a sub-par solution to a proper function. I haven't tested it thoroughly, so breakage is easily possible. Use at your own risk.

Title: Variable arguments inside a macro

Body:
I have two functions foo1(a,b) & foo2(a,b,c) and a macro

#define add(a,b) foo(a,b)

I need to re-define macro to accomplish,

1.if add() is called with 2 parameters, then call foo1

if add() is called with 3 parameters then call foo2

Im new to the option VA_ARGS. How can I do that

Body:
That usual trick for counting arguments may be adapted for this:

#define ADD_EXPAND(...) \
        ADD_EXPAND_(__VA_ARGS__, EXPAND_ADD_FUNCS())

#define ADD_EXPAND_(...) \
        EXPAND_ADD_SEL_FUNC(__VA_ARGS__)

#define EXPAND_ADD_SEL_FUNC(first_, second_, third_, func, ...) func

#define EXPAND_ADD_FUNCS() foo2, foo, dummy

#define add(...) ADD_EXPAND(__VA_ARGS__)(__VA_ARGS__)

Once you plow through the boiler plate, it basically just involves placing all the arguments in a line, with the function tokens after them, and seeing which function stands out. That's what EXPAND_ADD_SEL_FUNC does.

You can see it live on coliru.

But I'll reiterate what we told you in comments. This is likely to be a sub-par solution to a proper function. I haven't tested it thoroughly, so breakage is easily possible. Use at your own risk.


问:
How can I allow user without administrator rights start stop application pool in IIS from cmd
When I'm running console in elevated mode following command works fine.
appcmd start apppool /apppool.name:MyApp

I need to start\stop app pool from CI, that runs on different user whithout administrator rights. How can I allow this user to start/stop application pool?

答:
Solved with putting command to .bat file, and running it in elevated powershell from cmd.
Command for cmd
powershell -Command "Start-Process C:*****.bat -Verb RunAs"</p>