问:
Is there a way to explicitly set MIME types for Starlette/Uvicorn?
It appears that my simple Starlette/Uvicorn web app is serving up incorrect MIME content type for Jinja templated (served from the same server) JavaScript files. As you can see from the screen shot the uvicorn server is casting the *.js file as type (“text/plain”).

Screenshot

I have scoured the documents for both Starlette and Uvicorn and am simply stumped.

My simple web app is as follows:

```<code>from starlette.applications import Starlette
from starlette.staticfiles import StaticFiles
from starlette.responses import HTMLResponse
from starlette.templating import Jinja2Templates
from starlette.middleware.cors import CORSMiddleware
import uvicorn
from random import randint

port = randint(49152,65535)

templates = Jinja2Templates(directory='templates')

app = Starlette(debug=True)
app.mount('/static', StaticFiles(directory='statics', html=True), name='static')
app.add_middleware(
    CORSMiddleware, allow_origins=["*"], allow_headers=["*"], allow_methods=["*"]
)

@app.route('/')
async def homepage(request):
    template = "index.html"
    context = {"request": request}
    return templates.TemplateResponse(template, context, media_type='text/html')

@app.route('/error')
async def error(request):
    """
    An example error. Switch the `debug` setting to see either tracebacks or 500 pages.
    """
    raise RuntimeError("Oh no")

@app.exception_handler(404)
async def not_found(request, exc):
    """
    Return an HTTP 404 page.
    """
    template = "404.html"
    context = {"request": request}
    return templates.TemplateResponse(template, context, status_code=404)

@app.exception_handler(500)
async def server_error(request, exc):
    """
    Return an HTTP 500 page.
    """
    template = "500.html"
    context = {"request": request}
    return templates.TemplateResponse(template, context, status_code=500)

if __name__ == "__main__":
    uvicorn.run("app-567:app", host='0.0.0.0', port=port, log_level="info", http='h11', loop='asyncio', reload=True)
</code>```

The JavaScript files that are loaded in the head give the same error but load nonetheless. This is a bi-product of the new 'nosniff' default setting in Firefox (73.0 64-bit). The scripts that are loaded as module imports fail outright.

I am running Windows 10 (x64), Python 3.7, uvicorn 0.11.2, and starlette 0.13.1.

Any help is greatly appreciated.
Thank you in advance.

答:
I was able to fix this issue by explicitly setting the mimetypes variables as follows:

```<code>from starlette.applications import Starlette
from starlette.staticfiles import StaticFiles
from starlette.responses import HTMLResponse
from starlette.templating import Jinja2Templates
from starlette.middleware.cors import CORSMiddleware
import uvicorn
from random import randint

import mimetypes
mimetypes.init()

port = randint(49152,65535)

templates = Jinja2Templates(directory='templates')

app = Starlette(debug=True)
app.mount('/static', StaticFiles(directory='statics', html=True), name='static')
app.add_middleware(
    CORSMiddleware, allow_origins=["*"], allow_headers=["*"], allow_methods=["*"]
)

@app.route('/')
async def homepage(request):
    mimetypes.add_type('application/javascript', '.js')
    mimetypes.add_type('text/css', '.css')
    mimetypes.add_type('image/svg+xml', '.svg')
    template = "index.html"
    context = {"request": request}
    return templates.TemplateResponse(template, context, media_type='text/html')

@app.route('/error')
async def error(request):
    """
    An example error. Switch the `debug` setting to see either tracebacks or 500 pages.
    """
    raise RuntimeError("Oh no")

@app.exception_handler(404)
async def not_found(request, exc):
    """
    Return an HTTP 404 page.
    """
    template = "404.html"
    context = {"request": request}
    return templates.TemplateResponse(template, context, status_code=404)

@app.exception_handler(500)
async def server_error(request, exc):
    """
    Return an HTTP 500 page.
    """
    template = "500.html"
    context = {"request": request}
    return templates.TemplateResponse(template, context, status_code=500)

if __name__ == "__main__":
    uvicorn.run("app-567:app", host='0.0.0.0', port=port, log_level="info", http='h11', loop='asyncio', reload=True)
</code>```

Body:
It appears that my simple Starlette/Uvicorn web app is serving up incorrect MIME content type for Jinja templated (served from the same server) JavaScript files. As you can see from the screen shot the uvicorn server is casting the *.js file as type (“text/plain”).

Screenshot

I have scoured the documents for both Starlette and Uvicorn and am simply stumped.

My simple web app is as follows:

from starlette.applications import Starlette
from starlette.staticfiles import StaticFiles
from starlette.responses import HTMLResponse
from starlette.templating import Jinja2Templates
from starlette.middleware.cors import CORSMiddleware
import uvicorn
from random import randint

port = randint(49152,65535)

templates = Jinja2Templates(directory='templates')

app = Starlette(debug=True)
app.mount('/static', StaticFiles(directory='statics', html=True), name='static')
app.add_middleware(
    CORSMiddleware, allow_origins=["*"], allow_headers=["*"], allow_methods=["*"]
)

@app.route('/')
async def homepage(request):
    template = "index.html"
    context = {"request": request}
    return templates.TemplateResponse(template, context, media_type='text/html')

@app.route('/error')
async def error(request):
    """
    An example error. Switch the `debug` setting to see either tracebacks or 500 pages.
    """
    raise RuntimeError("Oh no")

@app.exception_handler(404)
async def not_found(request, exc):
    """
    Return an HTTP 404 page.
    """
    template = "404.html"
    context = {"request": request}
    return templates.TemplateResponse(template, context, status_code=404)

@app.exception_handler(500)
async def server_error(request, exc):
    """
    Return an HTTP 500 page.
    """
    template = "500.html"
    context = {"request": request}
    return templates.TemplateResponse(template, context, status_code=500)

if __name__ == "__main__":
    uvicorn.run("app-567:app", host='0.0.0.0', port=port, log_level="info", http='h11', loop='asyncio', reload=True)

The JavaScript files that are loaded in the head give the same error but load nonetheless. This is a bi-product of the new 'nosniff' default setting in Firefox (73.0 64-bit). The scripts that are loaded as module imports fail outright.

I am running Windows 10 (x64), Python 3.7, uvicorn 0.11.2, and starlette 0.13.1.

Any help is greatly appreciated.
Thank you in advance.

Body:
I was able to fix this issue by explicitly setting the mimetypes variables as follows:

from starlette.applications import Starlette
from starlette.staticfiles import StaticFiles
from starlette.responses import HTMLResponse
from starlette.templating import Jinja2Templates
from starlette.middleware.cors import CORSMiddleware
import uvicorn
from random import randint

import mimetypes
mimetypes.init()

port = randint(49152,65535)

templates = Jinja2Templates(directory='templates')

app = Starlette(debug=True)
app.mount('/static', StaticFiles(directory='statics', html=True), name='static')
app.add_middleware(
    CORSMiddleware, allow_origins=["*"], allow_headers=["*"], allow_methods=["*"]
)

@app.route('/')
async def homepage(request):
    mimetypes.add_type('application/javascript', '.js')
    mimetypes.add_type('text/css', '.css')
    mimetypes.add_type('image/svg+xml', '.svg')
    template = "index.html"
    context = {"request": request}
    return templates.TemplateResponse(template, context, media_type='text/html')

@app.route('/error')
async def error(request):
    """
    An example error. Switch the `debug` setting to see either tracebacks or 500 pages.
    """
    raise RuntimeError("Oh no")

@app.exception_handler(404)
async def not_found(request, exc):
    """
    Return an HTTP 404 page.
    """
    template = "404.html"
    context = {"request": request}
    return templates.TemplateResponse(template, context, status_code=404)

@app.exception_handler(500)
async def server_error(request, exc):
    """
    Return an HTTP 500 page.
    """
    template = "500.html"
    context = {"request": request}
    return templates.TemplateResponse(template, context, status_code=500)

if __name__ == "__main__":
    uvicorn.run("app-567:app", host='0.0.0.0', port=port, log_level="info", http='h11', loop='asyncio', reload=True)


来源: stackexchange

问:
Add marker in Google Maps - Flutter
I need to create some Marker in my app, I get the latitude and longitude by API. How can I will show these markers?

My getPosts code:

```<code>Future<List<Orders>> getPosts() async {
Response response = await http.get(url);
//print(response.body);
if(response.statusCode == 200){
  List<dynamic> body = jsonDecode(response.body);
  List<Orders> orders = body.map((dynamic item) => Orders.fromJson(item)).toList();
  return orders;
} else {
  throw "Can't get orders";
}
</code>```

My class Order:

```<code>class Orders {

final String id;
final String nameRestaurant;
final String address;
final String lat;
final String long;
final bool delivered;
final String orderId;
final String phone;

Orders({@required this.id, @required this.nameRestaurant, @required this.address, @required this.lat,
  @required this.long, @required this.delivered, @required this.orderId, @required this.phone});

factory Orders.fromJson(Map<dynamic, dynamic> json){
  return Orders(
    id: json['id'] as String,
    nameRestaurant: json['nameRestaurant'] as String,
    address: json['address'] as String,
    lat: json['lat'] as String,
    long: json['long'] as String,
    delivered: json['delivered'] as bool,
    orderId: json['orderId'] as String,
    phone: json['phone'] as String
  );
 }
}
</code>```

I followed some tutorials but all of them add marker in onTap function but it don't works to me

答:
To add a list of simple markers, first create a list of markers:

```<code>List<Marker> _markers = <Marker>[];
</code>```

Then add Marker to this list:

```<code>    _markers.add(
      Marker(
      markerId: MarkerId('SomeId'),
      position: LatLng(38.123,35.123),
      infoWindow: InfoWindow(
      title: 'The title of the marker'
      )
     )
   );
</code>```

Consider that in infoWindow you can also add subtitle and other stuff.
Finally add the google map widget:

```<code>GoogleMap(
      initialCameraPosition: CameraPosition(
        target: LatLng(38.9647,35.2233),
        zoom: 9.0,
      ),
      mapType: MapType.normal,
      markers: Set<Marker>.of(_markers),
      onMapCreated: (GoogleMapController controller) {
        _controller.complete(controller);
      },
    )
</code>```

ContentLicense: CC BY-SA 4.0

Title: Add marker in Google Maps - Flutter

Body:
I need to create some Marker in my app, I get the latitude and longitude by API. How can I will show these markers?

My getPosts code:

Future<List<Orders>> getPosts() async {
Response response = await http.get(url);
//print(response.body);
if(response.statusCode == 200){
  List<dynamic> body = jsonDecode(response.body);
  List<Orders> orders = body.map((dynamic item) => Orders.fromJson(item)).toList();
  return orders;
} else {
  throw "Can't get orders";
}

My class Order:

class Orders {

final String id;
final String nameRestaurant;
final String address;
final String lat;
final String long;
final bool delivered;
final String orderId;
final String phone;

Orders({@required this.id, @required this.nameRestaurant, @required this.address, @required this.lat,
  @required this.long, @required this.delivered, @required this.orderId, @required this.phone});

factory Orders.fromJson(Map<dynamic, dynamic> json){
  return Orders(
    id: json['id'] as String,
    nameRestaurant: json['nameRestaurant'] as String,
    address: json['address'] as String,
    lat: json['lat'] as String,
    long: json['long'] as String,
    delivered: json['delivered'] as bool,
    orderId: json['orderId'] as String,
    phone: json['phone'] as String
  );
 }
}

I followed some tutorials but all of them add marker in onTap function but it don't works to me

Body:
To add a list of simple markers, first create a list of markers:

List<Marker> _markers = <Marker>[];

Then add Marker to this list:

    _markers.add(
      Marker(
      markerId: MarkerId('SomeId'),
      position: LatLng(38.123,35.123),
      infoWindow: InfoWindow(
      title: 'The title of the marker'
      )
     )
   );

Consider that in infoWindow you can also add subtitle and other stuff.
Finally add the google map widget:

GoogleMap(
      initialCameraPosition: CameraPosition(
        target: LatLng(38.9647,35.2233),
        zoom: 9.0,
      ),
      mapType: MapType.normal,
      markers: Set<Marker>.of(_markers),
      onMapCreated: (GoogleMapController controller) {
        _controller.complete(controller);
      },
    )


问:
How to get the class type of the contents of an Iterable in scala?
Say I have a method like this:

```<code>def getClassFromIterable(iterable: Iterable[Any]): Class[_] = {
  iterable.head.getClass
}
</code>```

This will get the class of the top of the list, but will fail if the list is empty.

How can I get the class of a passed list that has zero or more elements?

答:
For this kind of problems, please consider using a typeclass instead.

```<code>import scala.collection.immutable.ArraySeq

trait TableEncoder[T] {
  def header: ArraySeq[String]
  def asRow(t: T): ArraySeq[String]
}

object TableEncoder {
  def toTable[T](data: IterableOnce[T])
                (implicit encoder: TableEncoder[T]): ArraySeq[ArraySeq[String]] = {
    val builder = ArraySeq.newBuilder[ArraySeq[String]]

    builder.addOne(encoder.header)
    builder.addAll(data.iterator.map(encoder.asRow))

    builder.result()
  }
}
</code>```

Which you can use like this:

```<code>final case class Point(x: Int, y: Int)
object Point {
  final implicit val PointTableEncoder: TableEncoder[Point] =
    new TableEncoder[Point] {
      override val header: ArraySeq[String] =
        ArraySeq("x", "y")

      override def asRow(point: Point): ArraySeq[String] =
        ArraySeq(
          point.x.toString,
          point.y.toString
        )
    }
}

TableEncoder.toTable(List(Point(1, 2), Point(3, 3)))
// res: ArraySeq[ArraySeq[String]] = ArraySeq(
//   ArraySeq("x", "y"),
//   ArraySeq("1", "2"),
//   ArraySeq("3", "3")
// )
</code>```

Body:
Say I have a method like this:

def getClassFromIterable(iterable: Iterable[Any]): Class[_] = {
  iterable.head.getClass
}

This will get the class of the top of the list, but will fail if the list is empty.

How can I get the class of a passed list that has zero or more elements?

Body:
For this kind of problems, please consider using a typeclass instead.

import scala.collection.immutable.ArraySeq

trait TableEncoder[T] {
  def header: ArraySeq[String]
  def asRow(t: T): ArraySeq[String]
}

object TableEncoder {
  def toTable[T](data: IterableOnce[T])
                (implicit encoder: TableEncoder[T]): ArraySeq[ArraySeq[String]] = {
    val builder = ArraySeq.newBuilder[ArraySeq[String]]

    builder.addOne(encoder.header)
    builder.addAll(data.iterator.map(encoder.asRow))

    builder.result()
  }
}

Which you can use like this:

final case class Point(x: Int, y: Int)
object Point {
  final implicit val PointTableEncoder: TableEncoder[Point] =
    new TableEncoder[Point] {
      override val header: ArraySeq[String] =
        ArraySeq("x", "y")

      override def asRow(point: Point): ArraySeq[String] =
        ArraySeq(
          point.x.toString,
          point.y.toString
        )
    }
}

TableEncoder.toTable(List(Point(1, 2), Point(3, 3)))
// res: ArraySeq[ArraySeq[String]] = ArraySeq(
//   ArraySeq("x", "y"),
//   ArraySeq("1", "2"),
//   ArraySeq("3", "3")
// )


问:
The "http://packagist.org/p/provider-3.json" file could not be downloaded (HTTP/1.1 400 Bad Request)
I am getting an issue of 400 bad request connecting over http, and it seems the package only wants to be installed via http. I tried an override in composer.json as tried by others as workaround to force https - but that doesn't seem to work. I'm not behind a firewall. Mac OS 10.10.3

Issue :

```<code>composer diagnose
Checking composer.json: FAIL
the property name is required
the property description is required
No license specified, it is recommended to do so. For closed-source software you may use "proprietary" as license.
Checking platform settings: OK
Checking git settings: OK
Checking http connectivity to packagist: FAIL
[Composer\Downloader\TransportException] The "http://packagist.org/packages.json" file could not be downloaded (HTTP/1.1 400 Bad Request)
Checking https connectivity to packagist: OK
Checking github.com rate limit: OK
Checking disk free space: OK
Checking composer version: OK

[Composer\Downloader\TransportException]

The "http://packagist.org/p/provider-2013$c2596c5d04e7701561420666ba120ede9429a69c75b732a5a01b18ebb3d64e53.json" file could not be downloaded (HTTP/1.1 400 Bad Request)
</code>```

Composer.json

```<code>{
"repositories": [
     { "packagist": false }
,

    {
         "type": "composer",
         "url": "https://packagist.org"
    }
]
}
</code>```

Composer version 1.0-dev (92faf1c7a83a73794fb914a990be435e1df373ca)
 2015-07-14 12:37:15

答: it looks like iran wifi internet i change to IR-MCI my mobile phone and it is installed as well</p>

ContentLicense: CC BY-SA 3.0

Body:
I am getting an issue of 400 bad request connecting over http, and it seems the package only wants to be installed via http. I tried an override in composer.json as tried by others as workaround to force https - but that doesn't seem to work. I'm not behind a firewall. Mac OS 10.10.3

Issue :

composer diagnose
Checking composer.json: FAIL
the property name is required
the property description is required
No license specified, it is recommended to do so. For closed-source software you may use "proprietary" as license.
Checking platform settings: OK
Checking git settings: OK
Checking http connectivity to packagist: FAIL
[Composer\Downloader\TransportException] The "http://packagist.org/packages.json" file could not be downloaded (HTTP/1.1 400 Bad Request)
Checking https connectivity to packagist: OK
Checking github.com rate limit: OK
Checking disk free space: OK
Checking composer version: OK

[Composer\Downloader\TransportException]

The "http://packagist.org/p/provider-2013$c2596c5d04e7701561420666ba120ede9429a69c75b732a5a01b18ebb3d64e53.json" file could not be downloaded (HTTP/1.1 400 Bad Request)

Composer.json

{
"repositories": [
     { "packagist": false }
,

    {
         "type": "composer",
         "url": "https://packagist.org"
    }
]
}

Composer version 1.0-dev (92faf1c7a83a73794fb914a990be435e1df373ca)
 2015-07-14 12:37:15


问:
Visual Studio Template - How DO I Copy a .gitignore file to the root folder where the .sln file exists?
I have created a multi project visual studio template .vstemplate file. It creates 3 projects and the folders look like this in windows explorer:

```<code>Project1
Project2
Project3
Project.sln
</code>```

I want to include and copy a .gitignore file to the root directory where the .sln file is located. How can I perform this task using the vstemplate xml syntax?

答:
This is not possible using the traditional visual studio template approach. I found a newer way to do this using the dotnet new template approach. This gives you much more flexibility and is a newer approach to project templates. Check out the documentation here:

https://learn.microsoft.com/en-us/dotnet/core/tools/custom-templates

Body:
I have created a multi project visual studio template .vstemplate file. It creates 3 projects and the folders look like this in windows explorer:

Project1
Project2
Project3
Project.sln

I want to include and copy a .gitignore file to the root directory where the .sln file is located. How can I perform this task using the vstemplate xml syntax?


问:
Changing Font Outline color inside a Table Cell with VBA using Application.CommandBar.ExecuteMSO
Win10x64 Office 365  PPT v 16.0.12325.202080 64-bits

I need to show a character with a yellow font color but a black outline, for readability purposes.  This character goes inside a Powerpoint table Cell.

The following link has a method that I'm currently using that consists of creating a dummy shape, adding text to it, modify the shape's textframe2 textrange font line properties and then copying it and pasting it back to the table cell.

http://www.vbaexpress.com/forum/archive/index.php/t-43787.html

This was asked 8 years ago, but I'm currently seeing the same behaviour where we can't directly manipulate the textframe2 wordart format of text inside a cell.  The program doesn't show an error but doesn't work.

I have given up on trying to modify the textrame2 textrange font line properties directly from VBA.

I have managed to get it to activate the font outline color using
Application.CommandBars.ExecuteMso ("TextOutlineColorPicker")

After it's activated I thought I could modify the textframe2 textrange font line properties, but it still doesn't work.

Is there an Application.CommandBars idMso for changing the font outline color and font outline line width inside a table cell?

Or another other than pasting the formatted text inside a table cell.

Edit:
Adding an image to illustrate what I mean by text color and text outline color and the menu used to show them in red circle:

Edit2
Added another snapshot to exemplify a character inside a cell with black outline and a character inside a cell without an outline

Thanks

答:
Here's an example to access a Table on a given slide and change one cell's attributes. The example slide I'm using looks like this

The code itself creates a function that allows you to select a table from a particular slide, and a single cell within the table and highlight it.

```<code>Option Explicit

Sub test()
    HighlightTableCell 1, 2, 3
End Sub

Sub HighlightTableCell(ByVal slideNumber As Long, _
                       ByVal thisRow As Long, _
                       ByVal thisCol As Long)
    Dim theSlide As Slide
    Set theSlide = ActivePresentation.Slides(slideNumber)

    Dim shp As Shape
    For Each shp In theSlide.Shapes
        If shp.Type = msoTable Then
            Dim theTable As Table
            Set theTable = shp.Table
            With theTable.Cell(thisRow, thisCol)
                With .Shape.TextFrame2.TextRange.Characters.Font.Fill
                    .Visible = msoTrue
                    .ForeColor.RGB = RGB(255, 255, 0)
                    .Transparency = 0
                    .Solid
                End With
                With .Shape.TextFrame2.TextRange.Characters.Font.Line
                    .Visible = msoTrue
                    .ForeColor.ObjectThemeColor = msoThemeColorText1
                    .ForeColor.TintAndShade = 0
                    .ForeColor.Brightness = 0
                    .Transparency = 0
                End With
            End With
        End If
    Next shp
End Sub
</code>```

Body:
Here's an example to access a Table on a given slide and change one cell's attributes. The example slide I'm using looks like this

The code itself creates a function that allows you to select a table from a particular slide, and a single cell within the table and highlight it.

Option Explicit

Sub test()
    HighlightTableCell 1, 2, 3
End Sub

Sub HighlightTableCell(ByVal slideNumber As Long, _
                       ByVal thisRow As Long, _
                       ByVal thisCol As Long)
    Dim theSlide As Slide
    Set theSlide = ActivePresentation.Slides(slideNumber)

    Dim shp As Shape
    For Each shp In theSlide.Shapes
        If shp.Type = msoTable Then
            Dim theTable As Table
            Set theTable = shp.Table
            With theTable.Cell(thisRow, thisCol)
                With .Shape.TextFrame2.TextRange.Characters.Font.Fill
                    .Visible = msoTrue
                    .ForeColor.RGB = RGB(255, 255, 0)
                    .Transparency = 0
                    .Solid
                End With
                With .Shape.TextFrame2.TextRange.Characters.Font.Line
                    .Visible = msoTrue
                    .ForeColor.ObjectThemeColor = msoThemeColorText1
                    .ForeColor.TintAndShade = 0
                    .ForeColor.Brightness = 0
                    .Transparency = 0
                End With
            End With
        End If
    Next shp
End Sub


问:
Count number of matching words from an array of words with another array of sentence in Javascript
```<code>var word_array = ['apple', 'mango', 'school'];

var sentences = [
{name: 'Jon', info: 'Jon takes apple in school'},
{name: 'Anna', info: 'Anna loves to eat mango'},
{name: 'Dani', info: 'Dani wants to go to park today'}
];
</code>```

I want to count the matched words for each names of the sentences.

```<code>Output:
Result = [
{name: 'Jon', count: 2},
{name: 'Anna', count: 1},
{name: 'Dani', count: 0}
];
</code>```

答:
You can try with .map() and .reduce() combination.

As the following:

const word_array = ['apple', 'mango', 'school'];

const sentences = [
  {name: 'Jon', info: 'Jon takes apple in school'},
  {name: 'Anna', info: 'Anna loves to eat mango'},
  {name: 'Dani', info: 'Dani wants to go to park today'}
];

const result = sentences.map(({name,info}) => {
  const count = word_array.reduce((a,c) => a + info.split(c).length - 1, 0);
  return { name, count };
});

console.log(result);```

I hope that helps!

Body:
var word_array = ['apple', 'mango', 'school'];

var sentences = [
{name: 'Jon', info: 'Jon takes apple in school'},
{name: 'Anna', info: 'Anna loves to eat mango'},
{name: 'Dani', info: 'Dani wants to go to park today'}
];

I want to count the matched words for each names of the sentences.

Output:
Result = [
{name: 'Jon', count: 2},
{name: 'Anna', count: 1},
{name: 'Dani', count: 0}
];

Body:
You can try with .map() and .reduce() combination.

As the following:

const word_array = ['apple', 'mango', 'school'];

const sentences = [
  {name: 'Jon', info: 'Jon takes apple in school'},
  {name: 'Anna', info: 'Anna loves to eat mango'},
  {name: 'Dani', info: 'Dani wants to go to park today'}
];

const result = sentences.map(({name,info}) => {
  const count = word_array.reduce((a,c) => a + info.split(c).length - 1, 0);
  return { name, count };
});

console.log(result);

I hope that helps!


问:
Kernel Density Plots and Histogram overlay
so I have found a way to over lay my KDE density function with my histogram using ggplot2, however what I've noticed is my histogram y axis is frequency which is correct, but I want to make a secondary y axis for my density plot, I also dont know how to scale up my density plot.

the code im using is:

data_set <- mammals

library(ggplot2)
ggplot(data=data_set, aes(data_set$`Total Averages`))+
  geom_histogram(col='black', fill = 'white', binwidth = 0.5)+
  labs(x = 'Log10 total body mass (kg)', y = 'Frequency', title = 'Average body mass (kg) of mammalian species (male and female)')+
  geom_density(col=2)
```

I have posted the link to the image below of what my plot looks like

答:
Your histogram is plot using the count per bins of your data. To get the density being scaled you can change the representation of the density by passing y = ..count.. for example.

If you want to represent the scale of this density (for example scaled to a maximum of 1), you can pass the sec.axis argument in scale_y_continuous (a lot of posts on SO have developed the use of this particular function) as follow:

df <- data.frame(Total_average = rnorm(100,0,2)) # Dummy example

library(ggplot2)
ggplot(df, aes(Total_average))+
  geom_histogram(col='black', fill = 'white', binwidth = 0.5)+
  labs(x = 'Log10 total body mass (kg)', y = 'Frequency', title = 'Average body mass (kg) of mammalian species (male and female)')+
  geom_density(aes(y = ..count..), col=2)+
  scale_y_continuous(sec.axis = sec_axis(~./20, name = "Scaled Density"))
```

and you get:

Does it answer your question ?

Body:
so I have found a way to over lay my KDE density function with my histogram using ggplot2, however what I've noticed is my histogram y axis is frequency which is correct, but I want to make a secondary y axis for my density plot, I also dont know how to scale up my density plot.

the code im using is:

data_set <- mammals

library(ggplot2)
ggplot(data=data_set, aes(data_set$`Total Averages`))+
  geom_histogram(col='black', fill = 'white', binwidth = 0.5)+
  labs(x = 'Log10 total body mass (kg)', y = 'Frequency', title = 'Average body mass (kg) of mammalian species (male and female)')+
  geom_density(col=2)

I have posted the link to the image below of what my plot looks like

Body:
Your histogram is plot using the count per bins of your data. To get the density being scaled you can change the representation of the density by passing y = ..count.. for example.

If you want to represent the scale of this density (for example scaled to a maximum of 1), you can pass the sec.axis argument in scale_y_continuous (a lot of posts on SO have developed the use of this particular function) as follow:

df <- data.frame(Total_average = rnorm(100,0,2)) # Dummy example

library(ggplot2)
ggplot(df, aes(Total_average))+
  geom_histogram(col='black', fill = 'white', binwidth = 0.5)+
  labs(x = 'Log10 total body mass (kg)', y = 'Frequency', title = 'Average body mass (kg) of mammalian species (male and female)')+
  geom_density(aes(y = ..count..), col=2)+
  scale_y_continuous(sec.axis = sec_axis(~./20, name = "Scaled Density"))

and you get:

Does it answer your question ?


问:
How can I use Drag and Drop to reorder a UITableView?
I know that drag and drop can be used to transfer data throughout and between apps. I'm not interested in that. All I want is to use drag and drop functionality to reorder a table view without transferring data. How do I do that?</p>

答:
If you are performing a drag on a single item locally, you can use tableView(_:moveRowAt:to:). In order to do this, you need to implement UITableViewDragDelegate.

Setup

Start by setting your delegates. Setting dragInteractionEnabled is required for iPhones.

```<code>func viewDidLoad() {
    super.viewDidLoad()
    tableView.dataSource = self
    tableView.delegate = self
    tableView.dragDelegate = self
    tableView.dragInteractionEnabled = true
}
</code>```

UITableViewDragDelegate

Notice that the array is returning a single item. If you return more than one item, then the UITableViewDropDelegate methods will be used instead of tableView(_:moveRowAt:to:). You must set a local object.

```<code>func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
    let dragItem = UIDragItem(itemProvider: NSItemProvider())
    dragItem.localObject = data[indexPath.row]
    return [ dragItem ]
}
</code>```

Moving

This is where the moving happens and is actually a part of UITableViewDelegate.

```<code>func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
    // Update the model
    let mover = data.remove(at: sourceIndexPath.row)
    data.insert(mover, at: destinationIndexPath.row)
}
</code>```

You can also use tableView(_:canMoveRow:at:) and tableView(_:targetIndexPathForMoveFromRowAt: toProposedIndexPath:) if needed.

You can read more here...

Drag and Drop

Adopting Drag and Drop in a Table View

Body:
If you are performing a drag on a single item locally, you can use tableView(_:moveRowAt:to:). In order to do this, you need to implement UITableViewDragDelegate.

Setup

Start by setting your delegates. Setting dragInteractionEnabled is required for iPhones.

func viewDidLoad() {
    super.viewDidLoad()
    tableView.dataSource = self
    tableView.delegate = self
    tableView.dragDelegate = self
    tableView.dragInteractionEnabled = true
}

UITableViewDragDelegate

Notice that the array is returning a single item. If you return more than one item, then the UITableViewDropDelegate methods will be used instead of tableView(_:moveRowAt:to:). You must set a local object.

func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
    let dragItem = UIDragItem(itemProvider: NSItemProvider())
    dragItem.localObject = data[indexPath.row]
    return [ dragItem ]
}

Moving

This is where the moving happens and is actually a part of UITableViewDelegate.

func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
    // Update the model
    let mover = data.remove(at: sourceIndexPath.row)
    data.insert(mover, at: destinationIndexPath.row)
}

You can also use tableView(_:canMoveRow:at:) and tableView(_:targetIndexPathForMoveFromRowAt: toProposedIndexPath:) if needed.

You can read more here...

Drag and Drop

Adopting Drag and Drop in a Table View


问:
converting parts of json string with % into float during loading in python?
How do i load a json so that wherever % appears, preceding number (if any) changes to float.

for example:

```<code>json_string = '[5, "5.2%", {"value": "2%"}]'

json.loads(json_string)
</code>```

this gets decoded to [5, "5.2%", {"value": "2%}]

what is needed is [5, 0.052, {"value": .02}]

I am doing this currently as a post processing after a basic loading of json, but i would like json.loads to handle this for me. Appreciate any help

another solution i attempted but it looks clumsy:

```<code>class JsonXSimpleDecoder(json.JSONDecoder):
    # loads int as int, floats and pct as floats and date as datetime
    def decode(self, s):
        result = super().decode(s)
        return self._decode(result)

    def _decode(self, o):
        if isinstance(o, str):
            result = o
            if "%" in o:
                new = o.replace("%", "")
                if is_number(new):
                    result = float(new) / 100
            elif "." in o and is_number(o):
                result = float(o)
            elif is_number(o):
                result = int(o)
            else:
                try:
                    dt = datetime.date.fromisoformat(o)
                    if isinstance(dt, datetime.date) and dt.isoformat() == o:
                        result = dt
                except ValueError:
                    pass
            return result
        elif isinstance(o, dict):
            return {k: self._decode(v) for k, v in o.items()}
        elif isinstance(o, list):
            return [self._decode(v) for v in o]
        else:
            return o
</code>```

and then:

```<code>results = json.loads(json_string, cls=JsonXSimpleDecoder)
</code>```

答:
Do a replacement on json_string beforehand. Regex works for this, as it's flexible enough to intelligently detect strings that contain numbers, and properly process them when replacing them with just straight numbers.

```<code>import re
import json

json_string = '[5, "5.2%", {"value": "2%"}]'

# Look for a number encased in double-quotes, with a percent sign at the end.
# Strip that match of the quotes and the percent sign (via string slicing),
# then convert it to a float, divide by 100, and convert it back to a string
# and finally, substitute it in for the original.
json_string = re.sub(r'"\d+\.?\d*%"',
                     lambda m: str(float(m.group(0)[1:-2]) / 100),
                     json_string)
# this produces '[5, 0.052000000000000005, {"value": 0.02}]'
# floating point precision is messy (search "is floating point math broken"),
# so this is as good as we're probably going to get.

# then, parse this as JSON, as normal
json_contents = json.loads(json_string)
# [5, 0.052000000000000005, {'value': 0.02}]
</code>```

Body:
How do i load a json so that wherever % appears, preceding number (if any) changes to float.

for example:

json_string = '[5, "5.2%", {"value": "2%"}]'

json.loads(json_string)

this gets decoded to [5, "5.2%", {"value": "2%}]

what is needed is [5, 0.052, {"value": .02}]

I am doing this currently as a post processing after a basic loading of json, but i would like json.loads to handle this for me. Appreciate any help

another solution i attempted but it looks clumsy:

class JsonXSimpleDecoder(json.JSONDecoder):
    # loads int as int, floats and pct as floats and date as datetime
    def decode(self, s):
        result = super().decode(s)
        return self._decode(result)

    def _decode(self, o):
        if isinstance(o, str):
            result = o
            if "%" in o:
                new = o.replace("%", "")
                if is_number(new):
                    result = float(new) / 100
            elif "." in o and is_number(o):
                result = float(o)
            elif is_number(o):
                result = int(o)
            else:
                try:
                    dt = datetime.date.fromisoformat(o)
                    if isinstance(dt, datetime.date) and dt.isoformat() == o:
                        result = dt
                except ValueError:
                    pass
            return result
        elif isinstance(o, dict):
            return {k: self._decode(v) for k, v in o.items()}
        elif isinstance(o, list):
            return [self._decode(v) for v in o]
        else:
            return o

and then:

results = json.loads(json_string, cls=JsonXSimpleDecoder)

Body:
Do a replacement on json_string beforehand. Regex works for this, as it's flexible enough to intelligently detect strings that contain numbers, and properly process them when replacing them with just straight numbers.

import re
import json

json_string = '[5, "5.2%", {"value": "2%"}]'

# Look for a number encased in double-quotes, with a percent sign at the end.
# Strip that match of the quotes and the percent sign (via string slicing),
# then convert it to a float, divide by 100, and convert it back to a string
# and finally, substitute it in for the original.
json_string = re.sub(r'"\d+\.?\d*%"',
                     lambda m: str(float(m.group(0)[1:-2]) / 100),
                     json_string)
# this produces '[5, 0.052000000000000005, {"value": 0.02}]'
# floating point precision is messy (search "is floating point math broken"),
# so this is as good as we're probably going to get.

# then, parse this as JSON, as normal
json_contents = json.loads(json_string)
# [5, 0.052000000000000005, {'value': 0.02}]


问:
Abstract class avoid creating multiple instances of object to pass different inputs
I'm trying to refactor a class using abstract class and am trying to understand if my approach is correct.

For every object I receive, I've a base validator which does some basic checks and then have a custom validator which performs some extra validations based on type of object. I feel this is a good use of abstract classes.

```<code>public abstract class Validator {
    BaseValidator baseValidator;
    abstract void customValidation();

    void validateObject() {
        baseValidator.validate(getInputObject());
        customValidation();
    }

    abstract String getInputObject();
}

public TypeAValidator extends Validator {
    @Override
    public void customValidation() {
        //Do something with getInputObject();
    }

    @Override public String getInputObject() {
        return "someInput";
    }
}
</code>```

I don't think having every input as part of a getter seems the right approach. If I went with a non abstract class approach, I would do this :

```<code>public TypeAValidator {
    BaseValidator baseValidator;

    public void validateObject(String inputObject) {
        baseValidator.validate(inputObject);
        customValidation(inputObject);
    }
}
</code>```

With this approach, all I need to do is call typeAValidator.validateObject(inputObject) without creating a new instance of TypeAValidator everytime which I will need to do with the abstract class approach. Is there something wrong with the way I've modelled my abstract class.

答:
You can mix your own two solutions to make something like this

```<code>public abstract class Validator {
    BaseValidator baseValidator;

    protected abstract void customValidationOnObject(String inputObject);

    public void validateObject(String inputObject) {
        baseValidator.validate(inputObject);
        customValidationOnObject(inputObject);
    }
}

class TypeAValidator extends Validator{

    @Override
    protected void customValidationOnObject(String inputObject) {
        // custom validate the Object
    }
}
</code>```

And you can call TypeAValidator.validateObject(inputObject) on a single TypeAValidator object.

Body:
I'm trying to refactor a class using abstract class and am trying to understand if my approach is correct.

For every object I receive, I've a base validator which does some basic checks and then have a custom validator which performs some extra validations based on type of object. I feel this is a good use of abstract classes.

public abstract class Validator {
    BaseValidator baseValidator;
    abstract void customValidation();

    void validateObject() {
        baseValidator.validate(getInputObject());
        customValidation();
    }

    abstract String getInputObject();
}

public TypeAValidator extends Validator {
    @Override
    public void customValidation() {
        //Do something with getInputObject();
    }

    @Override public String getInputObject() {
        return "someInput";
    }
}

I don't think having every input as part of a getter seems the right approach. If I went with a non abstract class approach, I would do this :

public TypeAValidator {
    BaseValidator baseValidator;

    public void validateObject(String inputObject) {
        baseValidator.validate(inputObject);
        customValidation(inputObject);
    }
}

With this approach, all I need to do is call typeAValidator.validateObject(inputObject) without creating a new instance of TypeAValidator everytime which I will need to do with the abstract class approach. Is there something wrong with the way I've modelled my abstract class.

Body:
You can mix your own two solutions to make something like this

public abstract class Validator {
    BaseValidator baseValidator;

    protected abstract void customValidationOnObject(String inputObject);

    public void validateObject(String inputObject) {
        baseValidator.validate(inputObject);
        customValidationOnObject(inputObject);
    }
}

class TypeAValidator extends Validator{

    @Override
    protected void customValidationOnObject(String inputObject) {
        // custom validate the Object
    }
}

And you can call TypeAValidator.validateObject(inputObject) on a single TypeAValidator object.


问:
Syntax to read xml inside of a stored procedure
I am passing into @xCriteria a XML parameter that looks like:

```<code><?xml version="1.0" encoding="utf-8"?>
<searchParameters xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
     <includeInactive enabled="True" />
</searchParameters>
</code>```

I know the xpath is:  //includeInactive/@enabled

And have tried:

```<code>--determine if we include inactive users
DECLARE @isInactive AS bit

-- SELECT @isInactive = @xCriteria.value('(/includeInactive/@enabled', 'bit')
-- SET @isInactive = @xCriteria.query('/includeInactive/@enabled')
-- SELECT @isInactive.value('(/includeInactive/enabled)[1]', 'bit')
-- SELECT @isInactive = @xCriteria.query('/includeInactive/@enabled')

PRINT '@isInactive'
PRINT @isInactive
</code>```

How can I fetch the boolean value?

答:
You try like this:

```<code>DECLARE @isInactive AS BIT;

SELECT
    @isInactive = CASE @param.value('(/searchParameters/includeInactive)[1]/@enabled', 'bit')
                     WHEN 1 THEN 0 ELSE 1
                  END

SELECT @isInactive;
</code>```

You basically need to select the first ((....)[1]) <includeInactive> node inside the root node, and then get the @enabled attribute off that node.

And you need to clunky CASE expression, since your XML stores the value of enabled, while the variable you want to get is the exact opposite - @isInactive.

Body:
I am passing into @xCriteria a XML parameter that looks like:

<?xml version="1.0" encoding="utf-8"?>
<searchParameters xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
     <includeInactive enabled="True" />
</searchParameters>

I know the xpath is:  //includeInactive/@enabled

And have tried:

--determine if we include inactive users
DECLARE @isInactive AS bit

-- SELECT @isInactive = @xCriteria.value('(/includeInactive/@enabled', 'bit')
-- SET @isInactive = @xCriteria.query('/includeInactive/@enabled')
-- SELECT @isInactive.value('(/includeInactive/enabled)[1]', 'bit')
-- SELECT @isInactive = @xCriteria.query('/includeInactive/@enabled')

PRINT '@isInactive'
PRINT @isInactive

How can I fetch the boolean value?

Body:
You try like this:

DECLARE @isInactive AS BIT;

SELECT
    @isInactive = CASE @param.value('(/searchParameters/includeInactive)[1]/@enabled', 'bit')
                     WHEN 1 THEN 0 ELSE 1
                  END

SELECT @isInactive;

You basically need to select the first ((....)[1]) <includeInactive> node inside the root node, and then get the @enabled attribute off that node.

And you need to clunky CASE expression, since your XML stores the value of enabled, while the variable you want to get is the exact opposite - @isInactive.


问:
Summation of figures in PivotViewer
I am creating a PivotViewer application to show sales history of store branches for a retail businesses.

We are creating dynamic collections from an sql database when the application is opened. The sql query groups the sales amounts by month.

The pivotViewer applications shows each branch and its related sales history amount. however because the sales amount is grouped by month we are getting 12 different images of the store in the results field. This makes the results meaningless.

For example if a user selects the Chadstone store and the sales history for Jan, Feb and March the results field shows 3 different images. Instead we would like it to show 1 result with the figures for each month summed by the year.

I have done some research and it seems Pivot Viewer only reads the lines from the collection and cannot complete any calculations.

Does anyone know if this is true or how it can be resolved?

Thanks

答:
Sadly, the PivotViewer control doesn't support this capability at the moment.  I think with the ability to perform and display the result of calculations, the PivotViewer control would be fantastic for visualising data in place of reports.  Unfortunately, it's a missing piece of the puzzle, and I haven't found any workable way of implementing this sort of behaviour (it's a very locked down control, and is hard to add functionality to).  I spent a bit of time trying, then decided it wasn't feasible.  PivotViewer is to be made a core control in Silverlight 5, and I was expecting a lot of functionality to be added, hopefully allowing this sort of scenario.  However, many announced features of Silverlight 5 were left out of the current beta, this being one of them.  We'll need to cross our fingers that the ability to implement this will be available when it's updated for Silverlight 5 (likely with Silverlight 5 beta 2).

Chris

Title: Summation of figures in PivotViewer


问:
You are using the runtime-only build of Vue where the template compiler is not available
I'm trying to compile my Vue.js app with webpack but I get this warning in the browser.

You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.

What does this mean? How do I resolve the error?

答:
This error pops up if you try to use non-precompiled Vue templates.

To fix this, set the runtimeCompiler option in vue.config.js to true:

```<code>module.exports = {
  runtimeCompiler: true
}
</code>```

Note that this will include additional JavaScript payload into your distribution.

Alternatively, you can use precompiled Vue templates.

Body:
This error pops up if you try to use non-precompiled Vue templates.

To fix this, set the runtimeCompiler option in vue.config.js to true:

module.exports = {
  runtimeCompiler: true
}

Note that this will include additional JavaScript payload into your distribution.

Alternatively, you can use precompiled Vue templates.


问:
In gradle custom plugin, how to insert a task between build and war?
I'am creating a custom plugin and I need to execute the war task after another task has finished, but I could note get it to work.
Here are the task dependencies:

build: compile the java classes.

prepareFrontEnd: requiere build java classes as input so I added a dependsOn build, and create some files as a result.

buildFrontEnd: require the prepareFrontEnd files as input an create a directory structure with the compiled version of the frontEnd, so I added a dependsOn prepareFrontEnd

and finally

war: I need that this task add the output directories of buildFrontEnd, but if I add a dependsOn or mustRunAfter I get a

```<code>FAILURE: Build failed with an exception.

* What went wrong:
Circular dependency between the following tasks:
:assemble
\--- :war
     \--- :buildFrontEnd
          \--- :prepareFrontEnd
               \--- :updatePom
                    \--- :build
                         \--- :assemble (*)

</code>```

How could I solve this?

Here is the plugin url

答:
build usually is the end of the line and usually means assemble +
check.  And the war usually is part of assemble.  So you
have to integrate that way sooner.  For sure you don't want to have something depend on build - it's usually build (or rather assemble) depends on things.

I'd go: classes <- buildFrontEnd <- prepareFrontEnd <- compileJava to start conservatively.

Try how it looks with gradle -m build and adjust if needed.  Other options to chain into:

war: most likely not correct, since the files might be useful while running the code in development

processResources: usefull if you just generate some JS files that will be sent as static resources later

Body:
I'am creating a custom plugin and I need to execute the war task after another task has finished, but I could note get it to work.
Here are the task dependencies:

build: compile the java classes.

prepareFrontEnd: requiere build java classes as input so I added a dependsOn build, and create some files as a result.

buildFrontEnd: require the prepareFrontEnd files as input an create a directory structure with the compiled version of the frontEnd, so I added a dependsOn prepareFrontEnd

and finally

war: I need that this task add the output directories of buildFrontEnd, but if I add a dependsOn or mustRunAfter I get a

FAILURE: Build failed with an exception.

* What went wrong:
Circular dependency between the following tasks:
:assemble
\--- :war
     \--- :buildFrontEnd
          \--- :prepareFrontEnd
               \--- :updatePom
                    \--- :build
                         \--- :assemble (*)

How could I solve this?

Here is the plugin url


问:
react-native link only for one project (Android or iOS)
I want to link only one of my project (Android or iOS) with the npm package.  Is there any way to do it?</p>

答:
You can choose to link libraries for only a certain platform by doing:

For Android: react-native link (your_library_name_here) --platforms android

For iOS: react-native link (your_library_name_here) --platforms ios


问:
"actual and formal argument lists differ in length" error
I'm trying to create a class that will do everything that a different class can do, but it will use random integers in order to create the objects that would normally require user input. Here I have a Pokemon program where I have class where the user creates a Pokemon trainer by inputting their name, and the program will create an ArrayList where the trainer's Pokemon are stored. I have a subclass called ComputerTrainer where it should have the same functionality, but randomly generated Pokemon will be added to the trainer's list of Pokemon. I created a constructor that accesses the protected variables in the PokemonTrainer class, but I'm getting an error that says "reason: actual and formal argument lists differ in length". Why I am getting this error?

Here is the code for the PokemonTrainer class:

```<code>import java.util.ArrayList;
public class PokemonTrainer
{
    // private constants
    private static final int MAX_POKEMON = 2;
    protected ArrayList<Pokemon> pokemonList;
    protected String name;
    protected int numOfPokemon;

    // Write your PokemonTrainer class here
    public PokemonTrainer(String name)
    {
        this.name = name;
        pokemonList = new ArrayList<Pokemon>();
    }

    public boolean addPokemon(Pokemon p)
    {
        if(numOfPokemon < MAX_POKEMON)
        {
            pokemonList.add(p);
            numOfPokemon++;
            return true;
        }
        else
        {
            return false;
        }
    }

    public boolean hasLost()
    {
        int numOfPokemonThatLost = 0;
        for(Pokemon p : pokemonList)
        {
            if(p.hasFainted())
            {
                numOfPokemonThatLost++;
            }
        }
        if(numOfPokemonThatLost == numOfPokemon)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public Pokemon getNextPokemon()
    {
        int nextPokemon = 0;
        int numOfPokemonThatLost = 0;
        for(Pokemon p : pokemonList)
        {
            while(p.hasFainted() && nextPokemon < numOfPokemon)
            {
                nextPokemon++;
                numOfPokemonThatLost++;
                if(nextPokemon < numOfPokemon)
                {
                    p = pokemonList.get(nextPokemon);
                }
            }
        }
        if(numOfPokemonThatLost == numOfPokemon)
        {
            return null;
        }
        else
        {
            return pokemonList.get(nextPokemon);
        }
    }

    public Pokemon getPokemon(int nPokemon)
    {
        return pokemonList.get(nPokemon);
    }

    public int getNumberOfPokemons()
    {
        return pokemonList.size();
    }

    public static int getMaxPokemon()
    {
        return MAX_POKEMON;
    }

    public String toString()
    {
        return name;
    }
}
</code>```

and here is the code for the ComputerTrainer subclass:

```<code>import java.util.ArrayList;
import java.util.Random;
public class ComputerTrainer extends PokemonTrainer
{
    // private constants
    // Possible pokemon names and move names to generate random Pokemon
    private static final String[] POKEMON_NAMES = {"Pikachu", "Bulbasaur", "Charmander", "Squirtle"};
    private static final String[] MOVE_NAMES = {"Tailwhip", "Bodyslam", "Splash", "Shock"};
    private static final int MAX_DAMAGE = 25;
    private static final int MAX_MOVES = 4;

    private PokemonImages images = new PokemonImages();

    // Write a Constructor that sets the name of the ComputerTrainer
    // and adds 2 randomly generated Pokemon to itself
    public ComputerTrainer(String name)
    {
        this.name = name;
        pokemonList = new ArrayList<Pokemon>();
        for(int i = 0; i < PokemonTrainer.getMaxPokemon(); i++)
        {
            Random num = new Random();
            int randomNumber = num.nextInt(POKEMON_NAMES.length);
            Pokemon p = new Pokemon (POKEMON_NAMES[randomNumber], images.getPokemonImage(POKEMON_NAMES[randomNumber]));
            pokemonList.add(p);
            numOfPokemon++;
        }
    }

    /*
     * Adds a randomly generated Pokemon to this ComputerTrainer's
     * collection of Pokemon. A ComputerTrainer can only have 2
     * Pokemon. This method returns true if there was room for the
     * new Pokemon and it was successfully added, false otherwise.
     */
    public boolean addRandomPokemon()
    {
        if(numOfPokemon < PokemonTrainer.getMaxPokemon())
        {
            Random num = new Random();
            int randomNumber = num.nextInt(POKEMON_NAMES.length);
            Pokemon p = new Pokemon (POKEMON_NAMES[randomNumber], images.getPokemonImage(POKEMON_NAMES[randomNumber]));
            pokemonList.add(p);
            numOfPokemon++;
            return true;
        }
        else
        {
            return false;
        }
    }

    // Returns a Move randomly chosen from the set of Moves
    // that this trainer's current Pokemon knows.
    // If all Pokemon have fainted, returns null.
    public Move chooseRandomMove()
    {
        Pokemon currentBattlingPokemon = getNextPokemon();

        // This method isn't finished yet
    }
}
</code>```

The program outputs the following error:

```<code>ComputerTrainer.java:20: error: constructor PokemonTrainer in class PokemonTrainer cannot be applied to given types;
    {
    ^
  required: String
  found: no arguments
  reason: actual and formal argument lists differ in length
</code>```

答:
The problem is that PokemonTrainer only has a constructor that has one String as parameter:

public class PokemonTrainer
{
    public PokemonTrainer(String name) {
        ...
}
```

<p>but you are not <em>calling</em> that constructor from <code>ComputerTrainer</code>:</p>

<pre class="lang-java prettyprint-override"><code>public class ComputerTrainer extends PokemonTrainer
{
    public ComputerTrainer(String name) {
        this.name = name;
        ...
    }
}
</code>```

Java does not automatically call the constructor of the superclass that matches the actual constructor, it calls the default (parameter-less constructor) but the superclass does not have it.

Solution: add an explicit invokation of the correct constructor of the superclass:

public class ComputerTrainer extends PokemonTrainer
{
    public ComputerTrainer(String name) {
        super(name);
        ...
    }
}
```

see Java Language Specification 8.8.7. Constructor Body for more details

Note: the error message is a bit confusing since there is like a hidden super() call as first statement in the ComputerTrainer constructor

Body:
I'm trying to create a class that will do everything that a different class can do, but it will use random integers in order to create the objects that would normally require user input. Here I have a Pokemon program where I have class where the user creates a Pokemon trainer by inputting their name, and the program will create an ArrayList where the trainer's Pokemon are stored. I have a subclass called ComputerTrainer where it should have the same functionality, but randomly generated Pokemon will be added to the trainer's list of Pokemon. I created a constructor that accesses the protected variables in the PokemonTrainer class, but I'm getting an error that says "reason: actual and formal argument lists differ in length". Why I am getting this error?

Here is the code for the PokemonTrainer class:

import java.util.ArrayList;
public class PokemonTrainer
{
    // private constants
    private static final int MAX_POKEMON = 2;
    protected ArrayList<Pokemon> pokemonList;
    protected String name;
    protected int numOfPokemon;

    // Write your PokemonTrainer class here
    public PokemonTrainer(String name)
    {
        this.name = name;
        pokemonList = new ArrayList<Pokemon>();
    }

    public boolean addPokemon(Pokemon p)
    {
        if(numOfPokemon < MAX_POKEMON)
        {
            pokemonList.add(p);
            numOfPokemon++;
            return true;
        }
        else
        {
            return false;
        }
    }

    public boolean hasLost()
    {
        int numOfPokemonThatLost = 0;
        for(Pokemon p : pokemonList)
        {
            if(p.hasFainted())
            {
                numOfPokemonThatLost++;
            }
        }
        if(numOfPokemonThatLost == numOfPokemon)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public Pokemon getNextPokemon()
    {
        int nextPokemon = 0;
        int numOfPokemonThatLost = 0;
        for(Pokemon p : pokemonList)
        {
            while(p.hasFainted() && nextPokemon < numOfPokemon)
            {
                nextPokemon++;
                numOfPokemonThatLost++;
                if(nextPokemon < numOfPokemon)
                {
                    p = pokemonList.get(nextPokemon);
                }
            }
        }
        if(numOfPokemonThatLost == numOfPokemon)
        {
            return null;
        }
        else
        {
            return pokemonList.get(nextPokemon);
        }
    }

    public Pokemon getPokemon(int nPokemon)
    {
        return pokemonList.get(nPokemon);
    }

    public int getNumberOfPokemons()
    {
        return pokemonList.size();
    }

    public static int getMaxPokemon()
    {
        return MAX_POKEMON;
    }

    public String toString()
    {
        return name;
    }
}

and here is the code for the ComputerTrainer subclass:

import java.util.ArrayList;
import java.util.Random;
public class ComputerTrainer extends PokemonTrainer
{
    // private constants
    // Possible pokemon names and move names to generate random Pokemon
    private static final String[] POKEMON_NAMES = {"Pikachu", "Bulbasaur", "Charmander", "Squirtle"};
    private static final String[] MOVE_NAMES = {"Tailwhip", "Bodyslam", "Splash", "Shock"};
    private static final int MAX_DAMAGE = 25;
    private static final int MAX_MOVES = 4;

    private PokemonImages images = new PokemonImages();

    // Write a Constructor that sets the name of the ComputerTrainer
    // and adds 2 randomly generated Pokemon to itself
    public ComputerTrainer(String name)
    {
        this.name = name;
        pokemonList = new ArrayList<Pokemon>();
        for(int i = 0; i < PokemonTrainer.getMaxPokemon(); i++)
        {
            Random num = new Random();
            int randomNumber = num.nextInt(POKEMON_NAMES.length);
            Pokemon p = new Pokemon (POKEMON_NAMES[randomNumber], images.getPokemonImage(POKEMON_NAMES[randomNumber]));
            pokemonList.add(p);
            numOfPokemon++;
        }
    }

    /*
     * Adds a randomly generated Pokemon to this ComputerTrainer's
     * collection of Pokemon. A ComputerTrainer can only have 2
     * Pokemon. This method returns true if there was room for the
     * new Pokemon and it was successfully added, false otherwise.
     */
    public boolean addRandomPokemon()
    {
        if(numOfPokemon < PokemonTrainer.getMaxPokemon())
        {
            Random num = new Random();
            int randomNumber = num.nextInt(POKEMON_NAMES.length);
            Pokemon p = new Pokemon (POKEMON_NAMES[randomNumber], images.getPokemonImage(POKEMON_NAMES[randomNumber]));
            pokemonList.add(p);
            numOfPokemon++;
            return true;
        }
        else
        {
            return false;
        }
    }

    // Returns a Move randomly chosen from the set of Moves
    // that this trainer's current Pokemon knows.
    // If all Pokemon have fainted, returns null.
    public Move chooseRandomMove()
    {
        Pokemon currentBattlingPokemon = getNextPokemon();

        // This method isn't finished yet
    }
}

The program outputs the following error:

ComputerTrainer.java:20: error: constructor PokemonTrainer in class PokemonTrainer cannot be applied to given types;
    {
    ^
  required: String
  found: no arguments
  reason: actual and formal argument lists differ in length

Body:
The problem is that PokemonTrainer only has a constructor that has one String as parameter:

public class PokemonTrainer
{
    public PokemonTrainer(String name) {
        ...
}

but you are not calling that constructor from ComputerTrainer:

public class ComputerTrainer extends PokemonTrainer
{
    public ComputerTrainer(String name) {
        this.name = name;
        ...
    }
}

Java does not automatically call the constructor of the superclass that matches the actual constructor, it calls the default (parameter-less constructor) but the superclass does not have it.

Solution: add an explicit invokation of the correct constructor of the superclass:

public class ComputerTrainer extends PokemonTrainer
{
    public ComputerTrainer(String name) {
        super(name);
        ...
    }
}

see Java Language Specification 8.8.7. Constructor Body for more details

Note: the error message is a bit confusing since there is like a hidden super() call as first statement in the ComputerTrainer constructor


问:
I'm trying to use multiplot to combine plot and splot but x,y labels seem to be shifted
```<code>set xrange [-2:2]
set yrange [-2:2]

set xlabel 'X'
set ylabel 'Y'

set samples 300
set isosamples 300

set lmargin screen 0.1
set rmargin screen 0.9
set tmargin screen 0.9
set bmargin screen 0.1

set multiplot

set pm3d map
set palette grey
unset colorbox
splot x**2+y**2 < 1 ? 0:0.2
unset pm3d

plot sin(x) lc 0
</code>```

This code displays the problem - different positionning of x/y labels by splot, plot.

答:
With gnuplot 5.2.8, the figure can be created with just one plot command:

```<code>pl [-2:2][-2:2] sample [0:2*pi] "+" us (cos(x)):(sin(x)) with filledcurve, sin(x)
</code>```

Thus splot and multiplot are not needed here.

sample is needed to redefine the parameter range (only in case of first plot argument).
A documentation is here: https://github.com/gnuplot/gnuplot/blob/4a7a11e6b528ea362c943cf632fd21a518b15c54/docs/gnuplot.doc#L7856

PS: As you see it also works without $1 for your cairolatex terminal.

Body:
set xrange [-2:2]
set yrange [-2:2]

set xlabel 'X'
set ylabel 'Y'

set samples 300
set isosamples 300

set lmargin screen 0.1
set rmargin screen 0.9
set tmargin screen 0.9
set bmargin screen 0.1

set multiplot

set pm3d map
set palette grey
unset colorbox
splot x**2+y**2 < 1 ? 0:0.2
unset pm3d

plot sin(x) lc 0

This code displays the problem - different positionning of x/y labels by splot, plot.

Body:
With gnuplot 5.2.8, the figure can be created with just one plot command:

pl [-2:2][-2:2] sample [0:2*pi] "+" us (cos(x)):(sin(x)) with filledcurve, sin(x)

Thus splot and multiplot are not needed here.

sample is needed to redefine the parameter range (only in case of first plot argument).
A documentation is here: https://github.com/gnuplot/gnuplot/blob/4a7a11e6b528ea362c943cf632fd21a518b15c54/docs/gnuplot.doc#L7856

PS: As you see it also works without $1 for your cairolatex terminal.


问:
C# Generics Extension Method Issues
so I'm fairly new to writing generic transform model extensions and I was trying to go from a model to an azure service bus message which works as expected. But I'm now trying to do the reverse where it can go from a message to a specified type.

The extension method currently looks like so.

    public static class ModelExtensions
    {
        public static Message ToMessage<TModel>(this TModel model) =>
            new Message(
                Encoding.UTF8.GetBytes(
                    JsonConvert.SerializeObject(model)));

        public static TType FromMessage<TModel, TType>(this TModel model)
        {
            return JsonConvert.DeserializeObject<TType>(JsonConvert.SerializeObject(model));
        }
    }
```

Is there a way to do the reverse of what I have just done to many types depending what is specified on the other side of the extension method for example if on the outside I have done something like.

message.FromMessage()

Any help would be appreciated,
Thanks in advance,
Chris.

答:
Should be as simple as

```<code>public static TModel FromMessage<TModel>(this Message message)
  => JsonConvert.DeserializeObject<TModel>(Encoding.UTF8.GetString(message.Body));
</code>```

Usage

```<code>var result = message.FromMessage<MyLovelyHorse>()
</code>```

Title: C# Generics Extension Method Issues

Body:
so I'm fairly new to writing generic transform model extensions and I was trying to go from a model to an azure service bus message which works as expected. But I'm now trying to do the reverse where it can go from a message to a specified type.

The extension method currently looks like so.

    public static class ModelExtensions
    {
        public static Message ToMessage<TModel>(this TModel model) =>
            new Message(
                Encoding.UTF8.GetBytes(
                    JsonConvert.SerializeObject(model)));

        public static TType FromMessage<TModel, TType>(this TModel model)
        {
            return JsonConvert.DeserializeObject<TType>(JsonConvert.SerializeObject(model));
        }
    }

Is there a way to do the reverse of what I have just done to many types depending what is specified on the other side of the extension method for example if on the outside I have done something like.

message.FromMessage()

Any help would be appreciated,
Thanks in advance,
Chris.

Body:
Should be as simple as

public static TModel FromMessage<TModel>(this Message message)
  => JsonConvert.DeserializeObject<TModel>(Encoding.UTF8.GetString(message.Body));

Usage

var result = message.FromMessage<MyLovelyHorse>()


问:
How to define a certain time for the getch() function in C?
I am trying to have the function getch() of the C language in Windows to work only for a few seconds.</p>

```<code>#include <stdio.h>
#include <windows.h>
int main()
{
    int v1, v2;
    v1=getch();//I want this getch to only be activated for a few seconds
    printf("Example");//That to activate the next function, even if the person reading this programm doesn't click in any key
    return 0;
}
</code>```

答:
You can use kbhit() which tests if a key has been pressed, before committing to the blocking function getch(). The loop below uses clock() to check for timeout.

```<code>#include <conio.h>
#include <stdio.h>
#include <ctype.h>
#include <time.h>

#define TIMEOUT 5   // seconds

int main(void)
{
    clock_t tstart = clock();
    int v1 = 'y';                   // default key press
    while((clock() - tstart) / CLOCKS_PER_SEC < TIMEOUT) {
        if(kbhit()) {
            v1 = getch();
            break;
        }
    }
    if(tolower(v1) == 'y')
        printf("Example\n");
    return 0;
}
</code>```

It's particularly useful in a game, where you don't want to sit there waiting for a key press, and then it isn't quite so simple to use. When you press a function key or a cursor key getch() returns two successive characters, the first is an "escape" value which must be checked for.

Body:
I am trying to have the function getch() of the C language in Windows to work only for a few seconds.

#include <stdio.h>
#include <windows.h>
int main()
{
    int v1, v2;
    v1=getch();//I want this getch to only be activated for a few seconds
    printf("Example");//That to activate the next function, even if the person reading this programm doesn't click in any key
    return 0;
}

Body:
You can use kbhit() which tests if a key has been pressed, before committing to the blocking function getch(). The loop below uses clock() to check for timeout.

#include <conio.h>
#include <stdio.h>
#include <ctype.h>
#include <time.h>

#define TIMEOUT 5   // seconds

int main(void)
{
    clock_t tstart = clock();
    int v1 = 'y';                   // default key press
    while((clock() - tstart) / CLOCKS_PER_SEC < TIMEOUT) {
        if(kbhit()) {
            v1 = getch();
            break;
        }
    }
    if(tolower(v1) == 'y')
        printf("Example\n");
    return 0;
}

It's particularly useful in a game, where you don't want to sit there waiting for a key press, and then it isn't quite so simple to use. When you press a function key or a cursor key getch() returns two successive characters, the first is an "escape" value which must be checked for.


问:
Using the string .replace() function to update lines in a text file
I'm attempting to read a text file and then if the substring doesn't match up with expected value, I want to replace that substring with a curated value. My current code is above along with a sample .txt file.

```<code>def update_atom_count(self, input_file):
    count = 0
    readFile = open(input_file, 'rt')
    writeFile = open(input_file, 'wt')
    for line in readFile:
        if line[0:6] == 'ATOM  ' or line[0:6] == 'TER   ':
            count += 1
            num = line[6:11]
            if int(num) != count:
                writeFile.write(line.replace(num, str(count)))
    writeFile.close()
</code>```

Sample .txt file:

ATOM   1850  OG1 THR A 225     -17.240  12.451  -7.500  1.00 62.47           O
ATOM   1851  CG2 THR A 225     -16.343  13.019  -9.660  1.00 56.69           C
ATOM   1852  N   GLN A 226     -13.575  14.217  -9.123  1.00 57.64           N
ATOM   1853  CA  GLN A 226     -12.637  14.556 -10.203  1.00 68.89           C
ATOM   1854  C   GLN A 226     -11.192  14.229  -9.816  1.00 55.30           C
ATOM   1855  O   GLN A 226     -10.255  14.468 -10.580  1.00 40.73           O
ATOM   1856  CB  GLN A 226     -12.774  16.025 -10.644  1.00 82.60           C
ATOM   1857  CG  GLN A 226     -12.264  16.309 -12.072  1.00 72.63           C
ATOM   1858  CD  GLN A 226     -12.294  17.790 -12.444  0.39 66.96           C
ATOM   1859  OE1 GLN A 226     -12.864  18.615 -11.726  1.00 74.47           O
ATOM   1860  NE2 GLN A 226     -11.673  18.130 -13.572  1.00 46.12           N
ATOM   1861  N   ASP A 227     -11.025  13.673  -8.624  1.00 32.42           N
ATOM   1862  CA  ASP A 227      -9.731  13.184  -8.201  1.00 38.31           C
ATOM   1863  C   ASP A 227      -9.679  11.646  -8.233  1.00 45.89           C
```

<p>My goal is to replace in the second "column" of the text which is <code>' 1850'</code> with <code>'    1'</code> (the extra spacing is for formatting). The output I am expecting is:</p>

<pre class="lang-none prettyprint-override"><code>ATOM      1  CG2 THR A 225     -16.343  13.019  -9.660  1.00 56.69           C
ATOM      2  N   GLN A 226     -13.575  14.217  -9.123  1.00 57.64           N
...
</code>```

答:
Here's a potential solution for you:

```<code>#!/usr/bin/env python3
import os

def update_atom_count(self, input_file):
    count = 0
    readFile = open(input_file, 'rt')
    writeFile = open(input_file + '.temp' , 'wt')
    for line in readFile:
        columns=line.split()
        if columns[0] in set(  ['ATOM', 'TER'] ):
            count += 1
            print( columns[0], count, " ".join(columns[2:]) , file=writeFile )
        else:
            print( line.rstrip(), file=writeFile )

    writeFile.close()
    readFile.close()
    os.rename( input_file + '.temp', input_file )
</code>```

There are a couple of differences in our approach:

I am using a temporary file ( input_file + '.temp' ).  On the
other hand, you are writing to the same file.  I felt uncomfortable
doing that since you have the file open for read and write at the
same time.  This is unchatered ground for me, so I avoid it and
create temporary files ( or just work completely in memory ) .

I don't care about formatting - we can always post process the output
( for instance, we can pipe the file to column -t).

Most notably, I didn't use the replace() function.  This seemed dangerous to me since the number we are replacing may appear anywhere else on the line coincidentally.  We don't want to accidentally modify the data, just the column with the count.

Body:
I'm attempting to read a text file and then if the substring doesn't match up with expected value, I want to replace that substring with a curated value. My current code is above along with a sample .txt file.

def update_atom_count(self, input_file):
    count = 0
    readFile = open(input_file, 'rt')
    writeFile = open(input_file, 'wt')
    for line in readFile:
        if line[0:6] == 'ATOM  ' or line[0:6] == 'TER   ':
            count += 1
            num = line[6:11]
            if int(num) != count:
                writeFile.write(line.replace(num, str(count)))
    writeFile.close()

Sample .txt file:

ATOM   1850  OG1 THR A 225     -17.240  12.451  -7.500  1.00 62.47           O
ATOM   1851  CG2 THR A 225     -16.343  13.019  -9.660  1.00 56.69           C
ATOM   1852  N   GLN A 226     -13.575  14.217  -9.123  1.00 57.64           N
ATOM   1853  CA  GLN A 226     -12.637  14.556 -10.203  1.00 68.89           C
ATOM   1854  C   GLN A 226     -11.192  14.229  -9.816  1.00 55.30           C
ATOM   1855  O   GLN A 226     -10.255  14.468 -10.580  1.00 40.73           O
ATOM   1856  CB  GLN A 226     -12.774  16.025 -10.644  1.00 82.60           C
ATOM   1857  CG  GLN A 226     -12.264  16.309 -12.072  1.00 72.63           C
ATOM   1858  CD  GLN A 226     -12.294  17.790 -12.444  0.39 66.96           C
ATOM   1859  OE1 GLN A 226     -12.864  18.615 -11.726  1.00 74.47           O
ATOM   1860  NE2 GLN A 226     -11.673  18.130 -13.572  1.00 46.12           N
ATOM   1861  N   ASP A 227     -11.025  13.673  -8.624  1.00 32.42           N
ATOM   1862  CA  ASP A 227      -9.731  13.184  -8.201  1.00 38.31           C
ATOM   1863  C   ASP A 227      -9.679  11.646  -8.233  1.00 45.89           C

My goal is to replace in the second "column" of the text which is ' 1850' with '    1' (the extra spacing is for formatting). The output I am expecting is:

ATOM      1  CG2 THR A 225     -16.343  13.019  -9.660  1.00 56.69           C
ATOM      2  N   GLN A 226     -13.575  14.217  -9.123  1.00 57.64           N
...

Body:
Here's a potential solution for you:

#!/usr/bin/env python3
import os

def update_atom_count(self, input_file):
    count = 0
    readFile = open(input_file, 'rt')
    writeFile = open(input_file + '.temp' , 'wt')
    for line in readFile:
        columns=line.split()
        if columns[0] in set(  ['ATOM', 'TER'] ):
            count += 1
            print( columns[0], count, " ".join(columns[2:]) , file=writeFile )
        else:
            print( line.rstrip(), file=writeFile )

    writeFile.close()
    readFile.close()
    os.rename( input_file + '.temp', input_file )

There are a couple of differences in our approach:

I am using a temporary file ( input_file + '.temp' ).  On the
other hand, you are writing to the same file.  I felt uncomfortable
doing that since you have the file open for read and write at the
same time.  This is unchatered ground for me, so I avoid it and
create temporary files ( or just work completely in memory ) .

I don't care about formatting - we can always post process the output
( for instance, we can pipe the file to column -t).

Most notably, I didn't use the replace() function.  This seemed dangerous to me since the number we are replacing may appear anywhere else on the line coincidentally.  We don't want to accidentally modify the data, just the column with the count.


问:
set choices in django model
```<code>class LeaveRequestStatus(IntEnum):
    open = 0
    accepted = 1
    rejected = 2
    closed = 3

class LeaveRequest(models.Model):
    status = models.PositiveSmallIntegerField(default=LeaveRequestStatus.open)
</code>```

so i had to make this changes to the two classes but i still doesnt work

```<code>class LeaveRequestStatus(IntEnum):
    open = (0, 'Open')
    accepted = (1, 'Accepted')
    rejected = (2, 'Rejected')
    closed = (3, 'Closed')

class LeaveRequest(models.Model):
    status = models.PositiveSmallIntegerField(choices=LeaveRequestStatus, default=LeaveRequestStatus.open)
</code>```

But it still doesn't work what i missing or what is not supposed to be there

答:
Another way to do this is using a tuple instead of a class

```<code>CHOICES = (
('open', ('0')),
('accepted', ('1')),
('rejected', ('2')),
('closed', ('3')),
</code>```

)

Then just call it in your model field:

```<code>status = models.PositiveSmallIntegerField(choices=CHOICES)
</code>```

Title: set choices in django model

Body:
class LeaveRequestStatus(IntEnum):
    open = 0
    accepted = 1
    rejected = 2
    closed = 3

class LeaveRequest(models.Model):
    status = models.PositiveSmallIntegerField(default=LeaveRequestStatus.open)

so i had to make this changes to the two classes but i still doesnt work

class LeaveRequestStatus(IntEnum):
    open = (0, 'Open')
    accepted = (1, 'Accepted')
    rejected = (2, 'Rejected')
    closed = (3, 'Closed')

class LeaveRequest(models.Model):
    status = models.PositiveSmallIntegerField(choices=LeaveRequestStatus, default=LeaveRequestStatus.open)

But it still doesn't work what i missing or what is not supposed to be there

Body:
Another way to do this is using a tuple instead of a class

CHOICES = (
('open', ('0')),
('accepted', ('1')),
('rejected', ('2')),
('closed', ('3')),

)

Then just call it in your model field:

status = models.PositiveSmallIntegerField(choices=CHOICES)


问:
How to make "inline-block" to go new line when its necessarry?
Here is my fiddle:

#container {
  background-color: green;
}

.result {
  border-radius: 6px;
  display: inline-block;
  width: 100%;
  max-width: 160px;
  min-width: 100px;
  height: 160px;
  border: 1px solid black;
  background-color: white;
  margin: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
</div></code>```

https://jsfiddle.net/6Laudc0s/

if you try to change the width of the browser, unwanted "green" areas may appear. I want those "cards" to extends 100% always, and go new line only when they are smaller than 100 pixel.
I set min-width, max-width and 100% width, seemingly in vain. When the area is too narrow, I expected the cards to shrink up to 100 pixel but instead they decided to remain the same width, and go new line instead.

答:
Use a css grid instead:

#container {
  background-color: green;
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fit, minmax(100px, 160px));
  grid-auto-rows: minmax(100px, 160px);
  max-width: calc(100vw - 20px);
}

.result {
  border-radius: 6px;
  height: 160px;
  border: 1px solid black;
  background-color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
</div></code>```

Body:
Here is my fiddle:

#container {
  background-color: green;
}

.result {
  border-radius: 6px;
  display: inline-block;
  width: 100%;
  max-width: 160px;
  min-width: 100px;
  height: 160px;
  border: 1px solid black;
  background-color: white;
  margin: 10px;
}

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

https://jsfiddle.net/6Laudc0s/

if you try to change the width of the browser, unwanted "green" areas may appear. I want those "cards" to extends 100% always, and go new line only when they are smaller than 100 pixel.
I set min-width, max-width and 100% width, seemingly in vain. When the area is too narrow, I expected the cards to shrink up to 100 pixel but instead they decided to remain the same width, and go new line instead.

Body:
Use a css grid instead:

#container {
  background-color: green;
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fit, minmax(100px, 160px));
  grid-auto-rows: minmax(100px, 160px);
  max-width: calc(100vw - 20px);
}

.result {
  border-radius: 6px;
  height: 160px;
  border: 1px solid black;
  background-color: white;
}

<div id="container">
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
  <div class="result">1</div>
</div>


问:
Jenkins: set a parameter defaultValue dynamically
I'm trying to set up a multibranch pipeline configuration where the "Deploy" boolean checkbox is defaulted to true on non-production branches, and false on the production build.

```<code>pipeline {
  parameters{
    booleanParam(defaultValue: true, description: 'Do deploy after build', name: 'DEPLOY')
</code>```

Is there some method to conditionally set defaultValue=false when $BRANCH_NAME == "production"?

答:
In your question, it's a bit unclear whether BRANCH_NAME refers to an environment variable (as in env.BRANCH_NAME) or to another parameter (as in params.BRANCH_NAME).

If former, then there's some environment variables, meaning that there's an environment, and so a node must have been allocated with its environment set. To allocate a node, the pipeline needs to start running. To start running, the user needs to select the parameters to run the pipeline. So it's a chicken-and-egg problem: you can't have environment variable before running pipelines, and you need to determine the parameters before running the pipeline.

If latter, and you are thinking of a case where, maybe, there's a String parameter that goes by the name of BRANCH_NAME, and a Boolean parameter that goes by the name of DEPLOY, and on the parameters page the checkbox DEPLOY is unchecked when you type maste into BRANCH_NAME, but once you press the r it magically becomes checked ... then it could be done — with a lot of pain — by using the Active Choice plugin.

Finally, if what you want is to prevent any deploying from the master branch, you  may check for both the parameter and the branch name before deploying, and refuse to deploy if the parameter is false or if the branch is master.

Body:
I'm trying to set up a multibranch pipeline configuration where the "Deploy" boolean checkbox is defaulted to true on non-production branches, and false on the production build.

pipeline {
  parameters{
    booleanParam(defaultValue: true, description: 'Do deploy after build', name: 'DEPLOY')

Is there some method to conditionally set defaultValue=false when $BRANCH_NAME == "production"?