问:
C# AutoMapper: set destination value by source value after validation in conditional mapping
I'm fairly new to AutoMapper and want to know how to set a destination member to a value based on a DIFFERENT source property value and if that value is null I just want to apply the default behaviour of Automapper (keep destination value when the source is null)

```<code> CreateMap<ClassA, ClassA>()
                    .ForMember(dest => dest.PropertyA, opt =>
                            opt.MapFrom(src => src.PropertyB!= null ? null : opt.UseDestinationValue())
                    )
</code>```

This doesn't work (don't compile) the opt.UseDestinationValue() , what option can I use here?
Please help

答:
I think you can use the PreCondition option For Mapping Property

```<code>        CreateMap<ClassA, ClassA>()
           .ForMember(dest => dest.PropertyA, opt => {
               opt.PreCondition(src => src.PropertyB!= null);
               opt.MapFrom(src => src.PropertyB);
           });
</code>```

Hope to help you

Body:
I'm fairly new to AutoMapper and want to know how to set a destination member to a value based on a DIFFERENT source property value and if that value is null I just want to apply the default behaviour of Automapper (keep destination value when the source is null)

 CreateMap<ClassA, ClassA>()
                    .ForMember(dest => dest.PropertyA, opt =>
                            opt.MapFrom(src => src.PropertyB!= null ? null : opt.UseDestinationValue())
                    )

This doesn't work (don't compile) the opt.UseDestinationValue() , what option can I use here?
Please help

Body:
I think you can use the PreCondition option For Mapping Property

        CreateMap<ClassA, ClassA>()
           .ForMember(dest => dest.PropertyA, opt => {
               opt.PreCondition(src => src.PropertyB!= null);
               opt.MapFrom(src => src.PropertyB);
           });

Hope to help you


来源: stackexchange

问:
Smarter way to create this responsive css grid
I'm getting crazy with a grid. For my website I have a modular grid with a fixed size, 3 x 2. In this grid I can distribute, without space and with a 1 px margin between every element, some blocks.

I can have 5 types of block:

huge, a 3 x 2 block

big-square, a 2 x 2 block

horizontal, a 2 x 1 block

vertical, a 1 x 2 block

square, 1 x 1 block.

In this image I show some variants, and un the right the "tablet" version.

I have to generate the grid using code so I don't want to create X fixed templates to fill, I want a single template that adapt itself.
Now I'm using float and some class for every variant.

For Example for first cover variant

```<code><section class="cover variant-1">
  <div class="cover-block horizontal" id="block-1">
    <img alt="image" src="https://via.placeholder.com/900x350" />
  </div>
  <div class="cover-block small" id="block-2">
    <img alt="image" src="https://via.placeholder.com/450x350" />
  </div>
  <div class="cover-block square" id="block-3">
    <img alt="image" src="https://via.placeholder.com/450x350" />
  </div>
 <div class="cover-block horizontal" id="block-4">
    <img alt="image" src="https://via.placeholder.com/900x350" />
  </div>
</section>
</code>```

And for the second cover variant

```<code><section class="cover variant-2">
  <div class="cover-block big-square" id="block-1">
    <img alt="image" src="https://via.placeholder.com/900x700" />
  </div>
  <div class="cover-block vertical" id="block-2">
    <img alt="image" src="https://via.placeholder.com/450x700" />
  </div>
</section>
</code>```

The CSS is

```<code>.cover {
  float: none;
  max-width: 1350px;
  max-height: 700px;
  margin: 0;
}
.cover .cover-block {
  float: left;
  position: relative;
  border: 0px solid #fff;
}
.cover .cover-block img {
  width: 100%;
  height: 100%;
}
.cover .cover-block.huge {
  width: 1350px;
  height: 700px;
}
.cover .cover-block.vertical {
  width: 450px;
  height: 700px;
}
.cover .cover-block.horizontal {
  width: 900px;
  height: 350px;
}
.cover .cover-block.big-square {
  width: 900px;
  height: 700px;
}
.cover .cover-block.square {
  width: 450px;
  height: 350px;
}
.cover .variant-1 #block-1 {
  border-width: 0 1px 0 0;
}
.cover .variant-1 #block-2 {
  border-width: 0 1px 0 0;
}
.cover .variant-1 #block-4 {
  border-width: 1px 1px 0 0;
}
.cover .variant-1 #block-5 {
  border-width: 1px 0 0 0;
}
.cover .variant-2 #block-1 {
  border-width: 0 1px 0 0;
}
.cover .variant-2 #block-3 {
  border-width: 1px 1px 0 0;
}
.cover .variant-2 #block-4 {
  border-width: 1px 0 0 0;
}
.cover .variant-2 #block-5 {
  display: none;
}
</code>```

Whit the floats I have to define an ID for every block to handle the 1 pixel space just in one direction, and I have also a lot of media queries to have this grid responsive.

Is there a smarter way to design my grid, maybe using flexbox?

Here is the Codepen

ContentLicense: CC BY-SA 3.0

Body:
I'm getting crazy with a grid. For my website I have a modular grid with a fixed size, 3 x 2. In this grid I can distribute, without space and with a 1 px margin between every element, some blocks.

I can have 5 types of block:

huge, a 3 x 2 block

big-square, a 2 x 2 block

horizontal, a 2 x 1 block

vertical, a 1 x 2 block

square, 1 x 1 block.

In this image I show some variants, and un the right the "tablet" version.

I have to generate the grid using code so I don't want to create X fixed templates to fill, I want a single template that adapt itself.
Now I'm using float and some class for every variant.

For Example for first cover variant

And for the second cover variant

The CSS is

.cover {
  float: none;
  max-width: 1350px;
  max-height: 700px;
  margin: 0;
}
.cover .cover-block {
  float: left;
  position: relative;
  border: 0px solid #fff;
}
.cover .cover-block img {
  width: 100%;
  height: 100%;
}
.cover .cover-block.huge {
  width: 1350px;
  height: 700px;
}
.cover .cover-block.vertical {
  width: 450px;
  height: 700px;
}
.cover .cover-block.horizontal {
  width: 900px;
  height: 350px;
}
.cover .cover-block.big-square {
  width: 900px;
  height: 700px;
}
.cover .cover-block.square {
  width: 450px;
  height: 350px;
}
.cover .variant-1 #block-1 {
  border-width: 0 1px 0 0;
}
.cover .variant-1 #block-2 {
  border-width: 0 1px 0 0;
}
.cover .variant-1 #block-4 {
  border-width: 1px 1px 0 0;
}
.cover .variant-1 #block-5 {
  border-width: 1px 0 0 0;
}
.cover .variant-2 #block-1 {
  border-width: 0 1px 0 0;
}
.cover .variant-2 #block-3 {
  border-width: 1px 1px 0 0;
}
.cover .variant-2 #block-4 {
  border-width: 1px 0 0 0;
}
.cover .variant-2 #block-5 {
  display: none;
}

Whit the floats I have to define an ID for every block to handle the 1 pixel space just in one direction, and I have also a lot of media queries to have this grid responsive.

Is there a smarter way to design my grid, maybe using flexbox?

Here is the Codepen

Body:
Well, I found a simple Grid code. That will create three or more grid item responsive for all displays.

<style>
/* Mobile first */
.grid {
  float: left;
  width: 100%;
}
/* Responsive column widths */
@media (min-width: 700px) {
  /* For Mobile three grid */
  .grid {
    width: 33.33333%;
  }
}
.wrapper {
  margin-bottom: 60px;
}
.wrapper:before,
.wrapper:after{
  content: ' ';
  display: grid;
  clear: both;
}
/* Main Style Begin's */
.grid {
  background-color: #8f1558;
  color: white;
  padding: 50px;
  box-sizing: border-box;
  moz-box-sizing: border-box;
  text-align: center;
}
.grid:nth-child(3n - 2) {
  background-color: #54158f;
}
.grid:nth-child(3n) {
  background-color: #8a0e37;
}
  <style>

<div class="wrapper">
  <div class="grid"><h1>WELCOME FIRST GRID</h1></div>
  <div class="grid"><h1>WELCOME SECOND GRID</h1></div>
  <div class="grid"><h1>WELCOME THIRD GRID</h1></div>
</div>

Want to add more grids then just put a <div> inside the first closing </div> after that adjust the width size in a mobile media query. suppose if I need 4 grid then I will put 25% instead 33.333% for responsive. Good Luck.

ContentLicense: CC BY-SA 4.0


问:
In Neo4j v4.0, Graph Data Science Library: why is Native Projection better than Cypher Projection in terms of performance?
The documentation Creating graphs in the catalog claims such performance advantange when using Native Projection over Cypher Projection, but does not give much explanation.

Native projection

Provides the best performance...

Cypher projection

The more flexible, expressive approach with lesser focus on performance.

As I understand, all projections will end up:

Graph projections are stored entirely in-memory using compressed data structures optimized for topology and property lookup operations.

So why is the performance gain?

In addition, the assumed gained performance is for loading (materialize) the projected graph or later for processing, e.g. with PageRank algorithm?

答:
You are correct, all projections end up stored entirely in-memory. The difference between cypher projection and native projection is how fast we can store or materialize the projected graph. As far as I know, native projection uses internal Neo4j API, which makes it faster to load the graph, but is limited to only specifying node labels and relationship types. Cypher projection, on the other hand, supports all the features of cypher and can be used to filter the subgraph we want to project very flexibly. We can also project a virtual graph. A very common projection of a virtual graph is to project a bipartite graph as a unipartite graph using only cypher projection. You must realize though that the more complex your cypher queries are, the slower the graph projection will be. And even just projecting a single node label and relationship type will be slower with cypher projection than with native projection. But I wouldn't worry much about that until your graph gets bigger than 10s of millions of nodes and relationships

Once the graph is materialized in-memory, the execution times of the algorithms should be the same regardless of the algorithm being projected with cypher projection or native projection.


问:
How can I programmatically click a button on a MessageBox
I have a radiobutton when i check it , it should give a message

```<code>DialogResult click = MessageBox.Show("Would you like to convert the actual values to US Customary ?\n Clicking No changes just the unit system.", "Change Unit Systems to US Customary", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);

if (click == DialogResult.Yes)
{
    //some code
}
</code>```

how can I answer this message from internal code in a button to be NO ?

答:
I don't want the message to appear

If you seriously don't want it then just perform your action when the check changes for that radio button.

```<code>private void radioButton1_CheckedChanged(Object sender, EventArgs e)
{
   //Validate to make sore it was not just deselected
   if (radioButton1.Checked)
   {
     //Do whatever I want when the use checks this radio button
   {
}
</code>```

Body:
I have a radiobutton when i check it , it should give a message

DialogResult click = MessageBox.Show("Would you like to convert the actual values to US Customary ?\n Clicking No changes just the unit system.", "Change Unit Systems to US Customary", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);

if (click == DialogResult.Yes)
{
    //some code
}

how can I answer this message from internal code in a button to be NO ?

Body:
I don't want the message to appear

If you seriously don't want it then just perform your action when the check changes for that radio button.

private void radioButton1_CheckedChanged(Object sender, EventArgs e)
{
   //Validate to make sore it was not just deselected
   if (radioButton1.Checked)
   {
     //Do whatever I want when the use checks this radio button
   {
}


问:
Node.js + Express + i18next how to load language from database
my scenario is a Node.js + Express + Handlebars + i18next app.

I would like to set up default language upon a database configuration key.
If I decide that the default language should be X instead of Y, I would simply change it and save that choice in the backend of my app.
The problem is that I don't want to reload the entire app every time I change the default language and so I cannot do that in i18next.init() method.
The default language should be read from the database at every page request and used if not other choices have been done from the current user.
My idea was the following but it does not work:

```<code>const express = require('express');
const i18next = require('i18next');

const app = express();
...
i18next.init(...);
...
app.use((req, res, next) => {
        const lng = someLogicToDecideLanguage();
        i18next.changeLanguage(lng, (err, t) => {
            if (err) {
                next(err);
            }
            console.log(i18next.language); // it's changed!
            next();
        });
    });
</code>```

If I log i18next.language in the changeLanguage callback result, it seems changed but when the view is rendered the language does not change.

Thanks!

答:
I found the issue. I wasn't changing language on the correct translator instance, the one that i18next clones, makes available in the request and uses for translations. You must change i18next.changeLanguage to req.i18n.changeLanguage:

```<code>app.use((req, res, next) => {
        const lng = someLogicToDecideLanguage();
        req.i18n.changeLanguage(lng, (err, t) => {
            if (err) {
                next(err);
            }
            console.log(i18next.language); // it's changed!
            next();
        });
    });
</code>```

Body:
my scenario is a Node.js + Express + Handlebars + i18next app.

I would like to set up default language upon a database configuration key.
If I decide that the default language should be X instead of Y, I would simply change it and save that choice in the backend of my app.
The problem is that I don't want to reload the entire app every time I change the default language and so I cannot do that in i18next.init() method.
The default language should be read from the database at every page request and used if not other choices have been done from the current user.
My idea was the following but it does not work:

const express = require('express');
const i18next = require('i18next');

const app = express();
...
i18next.init(...);
...
app.use((req, res, next) => {
        const lng = someLogicToDecideLanguage();
        i18next.changeLanguage(lng, (err, t) => {
            if (err) {
                next(err);
            }
            console.log(i18next.language); // it's changed!
            next();
        });
    });

If I log i18next.language in the changeLanguage callback result, it seems changed but when the view is rendered the language does not change.

Thanks!

Body:
I found the issue. I wasn't changing language on the correct translator instance, the one that i18next clones, makes available in the request and uses for translations. You must change i18next.changeLanguage to req.i18n.changeLanguage:

app.use((req, res, next) => {
        const lng = someLogicToDecideLanguage();
        req.i18n.changeLanguage(lng, (err, t) => {
            if (err) {
                next(err);
            }
            console.log(i18next.language); // it's changed!
            next();
        });
    });


问:
Configure domain-wide WebLogic error page
In WebLogic, there's a way to customize standard error pages like HTTP 404 inside the web applications using web.xml

```<code><web-app xmlns="http://java.sun.com/xml/ns/j2ee">
    <error-page>
        <error-code>404</error-code>
        <location>errors/404.htm</location>
    </error-page>
</web-app>
</code>```

Is there a way to configure default domain-wide error page for all the applications WebLogic has running without editing web.xml? Would it be possible to capture the 404 in Apache and serve a common error page?

答:
It's possible to define an error page in Apache WebLogic plugin:

http://download.oracle.com/docs/cd/E12840_01/wls/docs103/plugins/apache.html

ContentLicense: CC BY-SA 2.5

Body:
In WebLogic, there's a way to customize standard error pages like HTTP 404 inside the web applications using web.xml

<web-app xmlns="http://java.sun.com/xml/ns/j2ee">
    <error-page>
        <error-code>404</error-code>
        <location>errors/404.htm</location>
    </error-page>
</web-app>

Is there a way to configure default domain-wide error page for all the applications WebLogic has running without editing web.xml? Would it be possible to capture the 404 in Apache and serve a common error page?


问:
Gson Json Parsing in Java
I want to parse json list. I have used springboot project, database is H2. Database contains few data.

I have successfully displayed json data via @getmapping function.
Code is as below,

```<code>File-----> ProductController.Java
@GetMapping("/products_from_db")
        public  List<Product> getProducts_from_db() {
            return productservice.findAll() ;
        }
</code>```

Second File is as Follows.

```<code>File ----> Product.java

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
//@ToString
@Entity
public class Product {

    @Id
    @GeneratedValue
    private Integer id;
    private String name;
    private int price;

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
</code>```

output:

```<code>[{
    "id": 1,
    "name": "Mango",
    "price": 98
}, {
    "id": 2,
    "name": "Strawberry",
    "price": 92
}, {
    "id": 3,
    "name": "Cadbury",
    "price": 85
}, {
    "id": 4,
    "name": "yash",
    "price": 100
}]
</code>```

I want to display only name and price in back end code only.

答:
Unfortunately Gson isn't as straight forward in certain aspects as, for example, Jackson - where you can simply use the annotation @JsonIgnore.

On the other hand, Gson seems to have more flexibility (although a little too technical sometimes.)

In the case of Gson you have two main options to achieve what you want:

Mark the field you want to ignore as transient: private transient String id (in this case you have to make sure that this won't cause any side effects in your application.)

You can use the very flexible capabilities of Gson, especially the annotation @Expose. for example:

@Expose(Serialize = false)
private String id;

You can find more examples and details here and here.

Please, let us know if it helps.

Title: Gson Json Parsing in Java

Body:
I want to parse json list. I have used springboot project, database is H2. Database contains few data.

I have successfully displayed json data via @getmapping function.
Code is as below,

File-----> ProductController.Java
@GetMapping("/products_from_db")
        public  List<Product> getProducts_from_db() {
            return productservice.findAll() ;
        }

Second File is as Follows.

File ----> Product.java

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
//@ToString
@Entity
public class Product {

    @Id
    @GeneratedValue
    private Integer id;
    private String name;
    private int price;

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                '}';
    }

output:

[{
    "id": 1,
    "name": "Mango",
    "price": 98
}, {
    "id": 2,
    "name": "Strawberry",
    "price": 92
}, {
    "id": 3,
    "name": "Cadbury",
    "price": 85
}, {
    "id": 4,
    "name": "yash",
    "price": 100
}]

I want to display only name and price in back end code only.


问:
How to assign an object from column values in Google Sheet?
I have a google sheet with some data in a single column.
How to assign these values to new object like {'value[0]':value[0], 'value[1]':value[1],..., 'value[i]':value[i]}?

I wrote this script, but it assigns pair from last value of names only:

```<code>function getIngredientsList() {
  const url = "SPREADSHEET_URL";
  const ss = SpreadsheetApp.openByUrl(url);
  const ws = ss.getSheetByName('Base');
  const names = ws.getRange(2, 3, ws.getLastRow() - 1).getValues().map(a => a[0]);
  let nameList;
  for (let i = 0; i < names.length; i++){
    if (names[i] !== ""){
      let name = {[names[i]]:names[i]};
      nameList = Object.assign(name);
    }
  }
  return nameList;
}
</code>```

Where I'm wrong and how to fix it?

答:
More cleaner way to do that is using reduce method:

var names = ['ABC', 'XYZ', 'PQR'];
var result = names.reduce((acc, elem)=>{
    acc[elem] = elem;
    return acc;
},{});

console.log(result);```

Body:
I have a google sheet with some data in a single column.
How to assign these values to new object like {'value[0]':value[0], 'value[1]':value[1],..., 'value[i]':value[i]}?

I wrote this script, but it assigns pair from last value of names only:

function getIngredientsList() {
  const url = "SPREADSHEET_URL";
  const ss = SpreadsheetApp.openByUrl(url);
  const ws = ss.getSheetByName('Base');
  const names = ws.getRange(2, 3, ws.getLastRow() - 1).getValues().map(a => a[0]);
  let nameList;
  for (let i = 0; i < names.length; i++){
    if (names[i] !== ""){
      let name = {[names[i]]:names[i]};
      nameList = Object.assign(name);
    }
  }
  return nameList;
}

Where I'm wrong and how to fix it?


问:
Angular post request sending empty body to node.js server
I am trying to post form data from angular to node.js. The angular post request sends an empty body.
this is my post router
submit function is ts file

```<code>  onSubmit( loginData ) {
if(!loginData) { return; }
this.userService.addUser( loginData as User  )
  .subscribe(user => {
    this.users.push(user);
  });
</code>```

service used to post data

```<code>   addUser(user: User): Observable<User> {
    // console.log('this is '+user.email);
    const url = `${this.usersUrl}/register`;
    return this.http.post<User>(url, user).pipe(
      tap((newUser: User) => this.log(`added user w/ email=${newUser.email}`)),
      catchError(this.handleError<User>('addUser'))
    );
  }
</code>```

答:
Please check once by adding the debug whether the loginData is getting passed in the service or not.
If you don't know how to add debug point simply just print the data using console.log(user)
in the method addUser() as the first line.

And if not getting data then simply modify the method call by:

```<code>this.userService.addUser(loginData).subscribe(user => {
  this.users.push(user);
    });
</code>```

Body:
I am trying to post form data from angular to node.js. The angular post request sends an empty body.
this is my post router
submit function is ts file

  onSubmit( loginData ) {
if(!loginData) { return; }
this.userService.addUser( loginData as User  )
  .subscribe(user => {
    this.users.push(user);
  });

service used to post data

   addUser(user: User): Observable<User> {
    // console.log('this is '+user.email);
    const url = `${this.usersUrl}/register`;
    return this.http.post<User>(url, user).pipe(
      tap((newUser: User) => this.log(`added user w/ email=${newUser.email}`)),
      catchError(this.handleError<User>('addUser'))
    );
  }

Body:
Please check once by adding the debug whether the loginData is getting passed in the service or not.
If you don't know how to add debug point simply just print the data using console.log(user)
in the method addUser() as the first line.

And if not getting data then simply modify the method call by:

this.userService.addUser(loginData).subscribe(user => {
  this.users.push(user);
    });


问:
Using Hindi Font in HTML Websites
I want to create a website in hindi font. for this i have tried @font-family: "Kruti Dev" etc. but I feel that this website will require hindi font on every user's pc.

What's the best way to use hindi font on a website ?

答:
use meta tag in head section

    <meta charset="UTF-8" />
    <title>Hindi Font का उपयोग</title>

We Can Use Hindi Font

इस Page में हम हिन्दी भाषा का उपयोग करेंगे

We Can also use Hindi Hex Code

इस Page में हम हिन्दी भाषा उपयोग करेंगे

Hindi Code Entity

```

Title: Using Hindi Font in HTML Websites

Body:
use meta tag in head section

<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hindi Font का उपयोग</title>
  </head>
  <body>
    <h1>We Can Use Hindi Font</h1>
    <p>इस Page में हम हिन्दी भाषा का उपयोग करेंगे</p>
    <h1>We Can also use Hindi Hex Code</h1>
    <p>&#x0907;&#x0938;&nbsp;Page&nbsp;&#x092E;&#x0947;&#x0902;&nbsp;&#x0939;&#x092E;&nbsp;&#x0939;&#x093F;&#x0928;&#x094D;&#x0926;&#x0940;&nbsp;&#x092D;&#x093E;&#x0937;&#x093E;&nbsp;&#x0909;&#x092A;&#x092F;&#x094B;&#x0917;&nbsp;&#x0915;&#x0930;&#x0947;&#x0902;&#x0917;&#x0947;</p>

    <a href="https://www.anirdesh.com/gujarati/hindi-unicode.php"><h1>Hindi Code Entity</h1></a>
  </body>
</html>


问:
Sql get latest n rows in sql whose sum is greater than or equal to a value
I have a table  of fb_data of following data

```<code>id sessions created_at

1   25     2020-05-28 12:00:00

2   30     2020-05-28 13:00:00

3   24     2020-05-29 14:00:00
</code>```

I want to get latest rows whose sum creates greater than 40 . For e.g  id 2 and 3 creates the sum greater than 40   . Then I want only 2 and 3 rows excluding the rows 1

答:
You can get the sum of sessions for each row with SUM() window function.

So you need all the rows which have sum minus their value of sessions less (or equal?) than 40:

```<code>SELECT id, sessions, created_at
FROM (
  SELECT *, SUM(sessions) OVER (ORDER BY created_at DESC) - sessions total
  FROM tablename
) t
WHERE total < 40
</code>```

See the demo.

Results:

```<code>| id  | sessions | created_at          |
| --- | -------- | ------------------- |
| 3   | 24       | 2020-05-29 14:00:00 |
| 2   | 30       | 2020-05-28 13:00:00 |
</code>```

Body:
I have a table  of fb_data of following data

id sessions created_at

1   25     2020-05-28 12:00:00

2   30     2020-05-28 13:00:00

3   24     2020-05-29 14:00:00

I want to get latest rows whose sum creates greater than 40 . For e.g  id 2 and 3 creates the sum greater than 40   . Then I want only 2 and 3 rows excluding the rows 1

Body:
You can get the sum of sessions for each row with SUM() window function.

So you need all the rows which have sum minus their value of sessions less (or equal?) than 40:

SELECT id, sessions, created_at
FROM (
  SELECT *, SUM(sessions) OVER (ORDER BY created_at DESC) - sessions total
  FROM tablename
) t
WHERE total < 40

See the demo.

Results:

| id  | sessions | created_at          |
| --- | -------- | ------------------- |
| 3   | 24       | 2020-05-29 14:00:00 |
| 2   | 30       | 2020-05-28 13:00:00 |


问:
Adapting readmacros UCI Lisp code to common lisp
I'm trying to make the common lisp equivalent of this UCI Lisp/Interlisp helper function for a pattern mather.

```<code>(DRM /? (LAMBDA () (LIST '*VAR* (READ]
</code>```

The documentation is a follows:

```<code>-Variables, which are used by the pattern matcher, start with a question mark ("?"), as in ?FOO.
-This is converted internally to (*VAR* role-name), so ?FOO becomes (*VAR* FOO).
-The DRM defines ? to convert itself to *VAR* when it is read
</code>```

This is my current implementation of it:

```<code>(set-macro-character #\? (lambda () (list '*var* (read))))
</code>```

But when I ran the match function below:

```<code>(match (ptrans (actor ?x) (object ?x) (to (store)))
   (ptrans (actor (person)) (object (person)) (to (store))) nil)
</code>```

I get the following error that's coming from DRM function:

```<code>*** - EVAL/APPLY: too many arguments given to :LAMBDA
</code>```

Is my implementation correct?

答:
Reader macro functions need to take two arguments: one for the stream from which they can read the source code, and one for the character that triggered them to be called. If you change your implementation to

```<code>(set-macro-character #\? (lambda (stream char)
                           (declare (ignore char))
                           (list '*var* (read stream))))
</code>```

then any occurrence of ?x will be read as (*VAR* X).
Note that this will be evaluated if used as a function argument, which will cause an error if VAR is not a bound function / macro.

You probably want ?x to be read in as '(*VAR* X) (note the quote) to get the list as data.
In that case you should do this:

```<code>(set-macro-character #\? (lambda (stream char)
                           (declare (ignore char))
                           (list 'quote
                                 (list '*var* (read stream)))))
</code>```

to prevent evaluation of the form the reader macro function returns.

Body:
I'm trying to make the common lisp equivalent of this UCI Lisp/Interlisp helper function for a pattern mather.

(DRM /? (LAMBDA () (LIST '*VAR* (READ]

The documentation is a follows:

-Variables, which are used by the pattern matcher, start with a question mark ("?"), as in ?FOO.
-This is converted internally to (*VAR* role-name), so ?FOO becomes (*VAR* FOO).
-The DRM defines ? to convert itself to *VAR* when it is read

This is my current implementation of it:

(set-macro-character #\? (lambda () (list '*var* (read))))

But when I ran the match function below:

(match (ptrans (actor ?x) (object ?x) (to (store)))
   (ptrans (actor (person)) (object (person)) (to (store))) nil)

I get the following error that's coming from DRM function:

*** - EVAL/APPLY: too many arguments given to :LAMBDA

Is my implementation correct?

Body:
Reader macro functions need to take two arguments: one for the stream from which they can read the source code, and one for the character that triggered them to be called. If you change your implementation to

(set-macro-character #\? (lambda (stream char)
                           (declare (ignore char))
                           (list '*var* (read stream))))

then any occurrence of ?x will be read as (*VAR* X).
Note that this will be evaluated if used as a function argument, which will cause an error if VAR is not a bound function / macro.

You probably want ?x to be read in as '(*VAR* X) (note the quote) to get the list as data.
In that case you should do this:

(set-macro-character #\? (lambda (stream char)
                           (declare (ignore char))
                           (list 'quote
                                 (list '*var* (read stream)))))

to prevent evaluation of the form the reader macro function returns.


问:
Send logs from Javascript to ElasticSearch
Is there any Javascript api that allows me to send post requests, either directly through axios post or through Node JS, to Elastic Search?  This is to SEND logs to Elastic Search.</p>

答:
You can send POST requests using fetch.

```<code>  const response = await fetch(url, {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data) // body data type must match "Content-Type" header
  });
</code>```

Body:
You can send POST requests using fetch.

  const response = await fetch(url, {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data) // body data type must match "Content-Type" header
  });


问:
Formatting in Fortran 90/95
I am learning Fortran 90/95, and the book I am using had a discussion about the influence of line printers on the format statement.  According to the book, the program uses the first character of the line to decide the line's position relative to the previous line (i.e. '1' starts a new page, '0' skips a line, '+' overwrites the previous line, and ' ' or any other character writes the new line below the previous line).  I compiled and ran a simple program in the console to test this, but did not observe this behavior.

```<code>program test

integer :: i = 123
character(13) :: hello = 'Hello, World!'

100 format ('0','Count = ',I3)

write (*,*) hello
write (*,100) i

end program
</code>```

The output is

```<code> Hello, World!
0Count = 123
</code>```

where I would have expected

```<code> Hello, World!

Count = 123
</code>```

Does anyone know why this is?  Is this a legacy feature that is not used in Fortran 90/95?  Is it specific behavior for a print to the console?  I would like to know when (if ever) I need to declare a special first character in the format statement when writing.

My compiler is Force 2.0.9, which I believe is based on gfortran.  I am running it on Windows 7, and the console is PowerShell.

Thanks for the help!

答:
Fortran 90/95 is much too recent for me, but I don't recall those formatting options from using FORTRAN in the seventies.

Nevertheless, I think it's a legacy feature, and the fact that you've got '+' to overwrite a line suggests the options are intended for output to a line printer not the console screen.

Title: Formatting in Fortran 90/95

Body:
I am learning Fortran 90/95, and the book I am using had a discussion about the influence of line printers on the format statement.  According to the book, the program uses the first character of the line to decide the line's position relative to the previous line (i.e. '1' starts a new page, '0' skips a line, '+' overwrites the previous line, and ' ' or any other character writes the new line below the previous line).  I compiled and ran a simple program in the console to test this, but did not observe this behavior.

program test

integer :: i = 123
character(13) :: hello = 'Hello, World!'

100 format ('0','Count = ',I3)

write (*,*) hello
write (*,100) i

end program

The output is

 Hello, World!
0Count = 123

where I would have expected

 Hello, World!

Count = 123

Does anyone know why this is?  Is this a legacy feature that is not used in Fortran 90/95?  Is it specific behavior for a print to the console?  I would like to know when (if ever) I need to declare a special first character in the format statement when writing.

My compiler is Force 2.0.9, which I believe is based on gfortran.  I am running it on Windows 7, and the console is PowerShell.

Thanks for the help!


问:
Angular 9: deActivate guard and session timeout
I am having an angular app and spring boot in the backend using BasicAuth for my authentication.

When the session on the server runs out I am getting a 401 and in the httpInterceptor I am then redirecting to the logout page.

On some components I have a form and when the user has not saved the changes, there is a canDeactive guard with a modal pop-up, warning the user of the unsaved changes.
The problem is now, when the session is invalid, the guard fires (since the angular app does not know yet of the invalid session) and I am stuck on the pop-up.
My goal would be to check if the session is valid, before the guard is fired (or evaluate in the guard itself, if the session is valid).
My idea was to call a isAuthenticated function in the backend and in the guard navigate to logout, on a 401 and else show the dialog, but since the call is async it won´t work and I did not figure out how to do it.

component.ts

```<code>createChangeGuard() {
    setTimeout(() => {
      this.myObjectOrig$ = new BehaviorSubject(this.bookingForm.value).asObservable();
      this.isDirty$ = this.bookingForm.valueChanges.pipe(dirtyCheck(this.myObjectOrig$));
      this.myObjectOrig$.pipe(untilDestroyed(this)).subscribe(state => { this.bookingForm.patchValue(state, { emitEvent: false }); });
    }, 1000);
  }

</code>```

dirty-check component

```<code>export interface DirtyComponent {
  isDirty$: Observable<boolean>;
  // isPrinting: boolean;
  hasValidSession$: Observable<boolean>;
}

export function dirtyCheck<U>( source: Observable<U> ) {
  let subscription: Subscription;
  let isDirty = false;
  return function <T>( valueChanges: Observable<T> ): Observable<boolean> {

    const isDirty$ = combineLatest(
      [source,
      valueChanges]
    ).pipe(
      debounceTime(300),
      map(( [a, b] ) => { return isDirty = isEqual(a, b) === false;
      }),
      finalize(() => subscription.unsubscribe()),
      startWith(false),
      shareReplay({ bufferSize: 1, refCount: true }),
    );

    subscription = fromEvent(window, 'beforeunload').subscribe(event => {
        isDirty && (event.returnValue = false) && event.preventDefault();
    });
    return isDirty$;
  };
}
</code>```

deactivate Guard

```<code>export class DirtyCheckGuard implements CanDeactivate<DirtyComponent> {
   ....

    constructor( private modalService: NzModalService,
                 .....
                  ) {
    }

    contentNormal = 'Die Änderungen wurden nicht gespeichert. Wollen Sie wirklich die Seite verlassen?';
    contentPrint = 'Die Änderungen wurden noch nicht gespeichert. Trotzdem drucken?';
    canDeactivate( component: DirtyComponent, currentRoute: ActivatedRouteSnapshot ): Observable<boolean> | boolean {
      let formIsDirty = false;
      ...some logic to set formIsDirty...
      return component.isDirty$.pipe(switchMap(dirty => {
        let navigate;
        if ( (dirty === false && !formIsDirty ) ) {
          // update status to status before the booking went into edit mode since no change was made
            this.checkPage(currentRoute.data.origin);
          return of(true);
        } else if (dirty === true || (dirty === false && formIsDirty)) {
        return this.modalService.create({
          nzTitle: 'Not saved',
          nzContent: content,
          nzFooter: [
            {
              label: 'Abbrechen',
              onClick: () => {navigate = false; this.modalService.closeAll(); }
            },
            {
              label: confirmText,
              type: 'primary',
              onClick: () => { navigate = true; this.checkPage(currentRoute.data.origin); this.modalService.closeAll(); }
            }
          ]
        }).afterClose.pipe(map(() => navigate ));

      }}), take(1));
    }
  }
</code>```

interceptor

```<code>intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
     const requestRoute = this.router.url;
       return next.handle(request).pipe(retry(1), catchError((error: HttpErrorResponse) => {
         // this.errorCount = true;|| this.authenticationService.isLoggedIn() === false
         if (error.status === 401 ) {
             this.authenticationService.logout(requestRoute);
           }
         if (error.error instanceof ErrorEvent) {
               // A client-side or network error occurred. Handle it accordingly.
               console.error('An error occurred:', error.error.message);
             } else {
               console.error('An error occurred:', error);
               // The backend returned an unsuccessful response code.
               // The response body may contain clues as to what went wrong,
               if (error.error !== null){
                   this.showErrorNotification(error.status, error.error?.errorCode, error.error?.errorText);
                   console.error(`Backend returned code ${error.status}, body was: ${error.error?.errorText}}`);
                 }
             }
         return throwError(error.error);
       })
       );
</code>```

authentication service

```<code>async isAuthenticated(){
    const serverUrl = this.baseURL + 'isValidSession';
    const response = await this.http.get(serverUrl, httpOptions).toPromise();
    return response.toString();
 }
</code>```

答:
If you have to validate session on each canActivate. You need to have a api for that.

lets say you have that api in AuthService

```<code>async isSessionValid() {
   var res = await this.http.get('url').toPromise();
   return res;
}
</code>```

then use this promise returned as first statement of guard using same await strategy. if this returns true proceed furter, if this returns false return false from guard.

Body:
I am having an angular app and spring boot in the backend using BasicAuth for my authentication.

When the session on the server runs out I am getting a 401 and in the httpInterceptor I am then redirecting to the logout page.

On some components I have a form and when the user has not saved the changes, there is a canDeactive guard with a modal pop-up, warning the user of the unsaved changes.
The problem is now, when the session is invalid, the guard fires (since the angular app does not know yet of the invalid session) and I am stuck on the pop-up.
My goal would be to check if the session is valid, before the guard is fired (or evaluate in the guard itself, if the session is valid).
My idea was to call a isAuthenticated function in the backend and in the guard navigate to logout, on a 401 and else show the dialog, but since the call is async it won´t work and I did not figure out how to do it.

component.ts

createChangeGuard() {
    setTimeout(() => {
      this.myObjectOrig$ = new BehaviorSubject(this.bookingForm.value).asObservable();
      this.isDirty$ = this.bookingForm.valueChanges.pipe(dirtyCheck(this.myObjectOrig$));
      this.myObjectOrig$.pipe(untilDestroyed(this)).subscribe(state => { this.bookingForm.patchValue(state, { emitEvent: false }); });
    }, 1000);
  }

dirty-check component

export interface DirtyComponent {
  isDirty$: Observable<boolean>;
  // isPrinting: boolean;
  hasValidSession$: Observable<boolean>;
}

export function dirtyCheck( source: Observable ) {
  let subscription: Subscription;
  let isDirty = false;
  return function <T>( valueChanges: Observable<T> ): Observable<boolean> {

    const isDirty$ = combineLatest(
      [source,
      valueChanges]
    ).pipe(
      debounceTime(300),
      map(( [a, b] ) => { return isDirty = isEqual(a, b) === false;
      }),
      finalize(() => subscription.unsubscribe()),
      startWith(false),
      shareReplay({ bufferSize: 1, refCount: true }),
    );

    subscription = fromEvent(window, 'beforeunload').subscribe(event => {
        isDirty && (event.returnValue = false) && event.preventDefault();
    });
    return isDirty$;
  };
}

deactivate Guard

export class DirtyCheckGuard implements CanDeactivate<DirtyComponent> {
   ....

    constructor( private modalService: NzModalService,
                 .....
                  ) {
    }

    contentNormal = 'Die Änderungen wurden nicht gespeichert. Wollen Sie wirklich die Seite verlassen?';
    contentPrint = 'Die Änderungen wurden noch nicht gespeichert. Trotzdem drucken?';
    canDeactivate( component: DirtyComponent, currentRoute: ActivatedRouteSnapshot ): Observable<boolean> | boolean {
      let formIsDirty = false;
      ...some logic to set formIsDirty...
      return component.isDirty$.pipe(switchMap(dirty => {
        let navigate;
        if ( (dirty === false && !formIsDirty ) ) {
          // update status to status before the booking went into edit mode since no change was made
            this.checkPage(currentRoute.data.origin);
          return of(true);
        } else if (dirty === true || (dirty === false && formIsDirty)) {
        return this.modalService.create({
          nzTitle: 'Not saved',
          nzContent: content,
          nzFooter: [
            {
              label: 'Abbrechen',
              onClick: () => {navigate = false; this.modalService.closeAll(); }
            },
            {
              label: confirmText,
              type: 'primary',
              onClick: () => { navigate = true; this.checkPage(currentRoute.data.origin); this.modalService.closeAll(); }
            }
          ]
        }).afterClose.pipe(map(() => navigate ));

      }}), take(1));
    }
  }

interceptor

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
     const requestRoute = this.router.url;
       return next.handle(request).pipe(retry(1), catchError((error: HttpErrorResponse) => {
         // this.errorCount = true;|| this.authenticationService.isLoggedIn() === false
         if (error.status === 401 ) {
             this.authenticationService.logout(requestRoute);
           }
         if (error.error instanceof ErrorEvent) {
               // A client-side or network error occurred. Handle it accordingly.
               console.error('An error occurred:', error.error.message);
             } else {
               console.error('An error occurred:', error);
               // The backend returned an unsuccessful response code.
               // The response body may contain clues as to what went wrong,
               if (error.error !== null){
                   this.showErrorNotification(error.status, error.error?.errorCode, error.error?.errorText);
                   console.error(`Backend returned code ${error.status}, body was: ${error.error?.errorText}}`);
                 }
             }
         return throwError(error.error);
       })
       );

authentication service

async isAuthenticated(){
    const serverUrl = this.baseURL + 'isValidSession';
    const response = await this.http.get(serverUrl, httpOptions).toPromise();
    return response.toString();
 }

Body:
If you have to validate session on each canActivate. You need to have a api for that.

lets say you have that api in AuthService

async isSessionValid() {
   var res = await this.http.get('url').toPromise();
   return res;
}

then use this promise returned as first statement of guard using same await strategy. if this returns true proceed furter, if this returns false return false from guard.


问:
None is printing
```<code>def lucky_number(name):
  number = int(len(name) * 9)
  pr = "Hello " + name + ". Your lucky number is " + str(number)
  print(str(pr))

print(lucky_number("Kay"))
print(lucky_number("Cameron"))
</code>```

output

```<code>Hello Kay. Your lucky number is 27
None
Hello Cameron. Your lucky number is 63
None
</code>```

why iam geting none

答:
try this </p>

```<code>def lucky_number(name):
  number = int(len(name) * 9)
  pr = "Hello " + name + ". Your lucky number is " + str(number)
  return pr

print(lucky_number("Kay"))
print(lucky_number("Cameron"))
</code>```

Title: None is printing

Body:
def lucky_number(name):
  number = int(len(name) * 9)
  pr = "Hello " + name + ". Your lucky number is " + str(number)
  print(str(pr))

print(lucky_number("Kay"))
print(lucky_number("Cameron"))

output

Hello Kay. Your lucky number is 27
None
Hello Cameron. Your lucky number is 63
None

why iam geting none

Body:
try this

def lucky_number(name):
  number = int(len(name) * 9)
  pr = "Hello " + name + ". Your lucky number is " + str(number)
  return pr

print(lucky_number("Kay"))
print(lucky_number("Cameron"))


问:
cycle the LEDS IN ATMEGA8515
I want to read the switches next to the LEDS and cycle the LEDS from 0 to whichever switch is pressed
if none are pressed cycle through all of them with the delay.For this i have used timer0. Since I work on
atmega8515. I used INT0.
Here is my implementation:

```<code>#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

#define BIT(n) (1 << n)

volatile uint8_t led, k, switches, i , j = 1;
            /* uint8_t is the same as unsigned char */
int main(void)
{

    DDRB = 0xff;                /* use all pins on PortB for output */

    led = 1;                    /* init variable representing the LED state */
    PORTB = 0XFF;

    cli( );

    TCCR0|=(1<<CS02) |(1<<CS00);

 //Enable Overflow Interrupt Enable
   TIMSK|=(1<<TOIE0);

 //Initialize Counter
   TCNT0=0;

   GICR = BIT(INT0);
    MCUCR = BIT(ISC01) | BIT(ISC00);

   sei( );

    for ( ; ;);

}

ISR(TIMER0_OVF_vect)
{

  if(switches == 0xff)
  {
    PORTB = ~led;           /* invert the output since a zero means: LED on */
        led <<= 1;              /* move to next LED */
        if (!led)               /* overflow: start with Pin B0 again */
        {
            led = 1;
        }
  }
  else
  {
    for (k = 0; k< 8;k++)
    {
        j =  switches & (1 << k);

        if(j == 0)
        {
           for(i=1;i<=(k +1);i++)
            {
                j = 1;
                PORTB =  ~j;
                j = 1 << i;

                _delay_ms(100);     //without this delay it doesnt cycle the LEDS from to whichever switch is pressed
            }

    }
}
}
</code>```

But using delay loops in ISR is a bad programming practice. How to use the same timer instead of the delay?

答: I think in the ISR, you should just update the LED status and in the main loop you could set the PORTB and read the switches values. In your code, it seems occupy so much time in ISR. </p>

Title: cycle the LEDS IN ATMEGA8515

Body:
I want to read the switches next to the LEDS and cycle the LEDS from 0 to whichever switch is pressed
if none are pressed cycle through all of them with the delay.For this i have used timer0. Since I work on
atmega8515. I used INT0.
Here is my implementation:

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

#define BIT(n) (1 << n)

volatile uint8_t led, k, switches, i , j = 1;
            /* uint8_t is the same as unsigned char */
int main(void)
{

    DDRB = 0xff;                /* use all pins on PortB for output */

    led = 1;                    /* init variable representing the LED state */
    PORTB = 0XFF;

    cli( );

    TCCR0|=(1<<CS02) |(1<<CS00);

 //Enable Overflow Interrupt Enable
   TIMSK|=(1<<TOIE0);

 //Initialize Counter
   TCNT0=0;

   GICR = BIT(INT0);
    MCUCR = BIT(ISC01) | BIT(ISC00);

   sei( );

    for ( ; ;);

}

ISR(TIMER0_OVF_vect)
{

  if(switches == 0xff)
  {
    PORTB = ~led;           /* invert the output since a zero means: LED on */
        led <<= 1;              /* move to next LED */
        if (!led)               /* overflow: start with Pin B0 again */
        {
            led = 1;
        }
  }
  else
  {
    for (k = 0; k< 8;k++)
    {
        j =  switches & (1 << k);

        if(j == 0)
        {
           for(i=1;i<=(k +1);i++)
            {
                j = 1;
                PORTB =  ~j;
                j = 1 << i;

                _delay_ms(100);     //without this delay it doesnt cycle the LEDS from to whichever switch is pressed
            }

    }
}
}

But using delay loops in ISR is a bad programming practice. How to use the same timer instead of the delay?


问:
Subset data in R Shiny using Multiple Variables
I am new to R Shiny.  I am attempting to create an app that allows a user to subset a data.frame based on multiple variables and then see the resulting data.

Here is a small example data set:

```<code>iter,wave,apples
1,1,600
1,1,500
1,1,400
1,2,300
1,2,200
1,2,100
2,1,1000
2,1,1100
2,1,1200
2,2,1300
2,2,1400
2,2,1500
3,1,1100
3,1,2200
3,1,3300
3,2,4400
3,2,5500
3,2,6600
</code>```

I would like the user to be able to specify the value of iter and of wave and see the resulting data.

Here is my attempt at the Shiny code.  I realize I must be making several silly mistakes.

Edit

Here is my revised code.  The end result now comes pretty close to what I want.  The sidebar is still not being displayed perfectly.

```<code>library(shiny)

setwd('C:/Users/mark_/Documents/simple_RShiny_files/explore')

apple.data <- read.csv('subset_data_based_on_multiple_variables.csv',
                        header = TRUE, stringsAsFactors = FALSE)

ui <- fluidPage(

     titlePanel("Subsetting Apple Dataset"),

     sidebarLayout(
          sidebarPanel(
               uiOutput("codePanel")
          ),

          mainPanel(
               tableOutput("view")
          )
     ),

     selectInput("codeInput", inputId ="data1", label = "Choose Iter", choices = unique(apple.data$iter)),
     selectInput("codeInput", inputId ="data2", label = "Choose Wave", choices = unique(apple.data$wave))

)

server <- function(input, output) {

     output$codePanel <- renderUI({

     })

     dataset <- reactive({

          subset(apple.data, (iter == input$data1 & wave == input$data2))

     })

     output$view <- renderTable(dataset())

}

shinyApp(ui = ui, server = server)
</code>```

The output

答:
The problem is that both selectInputs have the same inputId. This works:

```<code>library(shiny)

apple.data <- data.frame(
        iter = c(1L,1L,1L,1L,1L,1L,2L,2L,2L,2L,2L,
                 2L,3L,3L,3L,3L,3L,3L),
        wave = c(1L,1L,1L,2L,2L,2L,1L,1L,1L,2L,2L,
                 2L,1L,1L,1L,2L,2L,2L),
      apples = c(600L,500L,400L,300L,200L,100L,1000L,
                 1100L,1200L,1300L,1400L,1500L,1100L,2200L,3300L,4400L,
                 5500L,6600L)
)

ui <- fluidPage(
    titlePanel("Subsetting Apple Dataset"),
    sidebarLayout(
        sidebarPanel(
            selectInput("codeInput1", label = "Choose Iter", choices = unique(apple.data$iter)),
            selectInput("codeInput2", label = "Choose Wave", choices = unique(apple.data$wave))
        ),
        mainPanel(
            tableOutput("view")
        )
    )
)

server <- function(input, output) {

    dataset <- reactive({
        return(subset(apple.data, (iter == input$codeInput1 & wave == input$codeInput2)))
    })

    output$view <- renderTable(dataset())
}

shinyApp(ui = ui, server = server)

</code>```

Body:
I am new to R Shiny.  I am attempting to create an app that allows a user to subset a data.frame based on multiple variables and then see the resulting data.

Here is a small example data set:

iter,wave,apples
1,1,600
1,1,500
1,1,400
1,2,300
1,2,200
1,2,100
2,1,1000
2,1,1100
2,1,1200
2,2,1300
2,2,1400
2,2,1500
3,1,1100
3,1,2200
3,1,3300
3,2,4400
3,2,5500
3,2,6600

I would like the user to be able to specify the value of iter and of wave and see the resulting data.

Here is my attempt at the Shiny code.  I realize I must be making several silly mistakes.

Edit

Here is my revised code.  The end result now comes pretty close to what I want.  The sidebar is still not being displayed perfectly.

library(shiny)

setwd('C:/Users/mark_/Documents/simple_RShiny_files/explore')

apple.data <- read.csv('subset_data_based_on_multiple_variables.csv',
                        header = TRUE, stringsAsFactors = FALSE)

ui <- fluidPage(

     titlePanel("Subsetting Apple Dataset"),

     sidebarLayout(
          sidebarPanel(
               uiOutput("codePanel")
          ),

          mainPanel(
               tableOutput("view")
          )
     ),

     selectInput("codeInput", inputId ="data1", label = "Choose Iter", choices = unique(apple.data$iter)),
     selectInput("codeInput", inputId ="data2", label = "Choose Wave", choices = unique(apple.data$wave))

)

server <- function(input, output) {

     output$codePanel <- renderUI({

     })

     dataset <- reactive({

          subset(apple.data, (iter == input$data1 & wave == input$data2))

     })

     output$view <- renderTable(dataset())

}

shinyApp(ui = ui, server = server)

The output

Body:
The problem is that both selectInputs have the same inputId. This works:

library(shiny)

apple.data <- data.frame(
        iter = c(1L,1L,1L,1L,1L,1L,2L,2L,2L,2L,2L,
                 2L,3L,3L,3L,3L,3L,3L),
        wave = c(1L,1L,1L,2L,2L,2L,1L,1L,1L,2L,2L,
                 2L,1L,1L,1L,2L,2L,2L),
      apples = c(600L,500L,400L,300L,200L,100L,1000L,
                 1100L,1200L,1300L,1400L,1500L,1100L,2200L,3300L,4400L,
                 5500L,6600L)
)

ui <- fluidPage(
    titlePanel("Subsetting Apple Dataset"),
    sidebarLayout(
        sidebarPanel(
            selectInput("codeInput1", label = "Choose Iter", choices = unique(apple.data$iter)),
            selectInput("codeInput2", label = "Choose Wave", choices = unique(apple.data$wave))
        ),
        mainPanel(
            tableOutput("view")
        )
    )
)

server <- function(input, output) {

    dataset <- reactive({
        return(subset(apple.data, (iter == input$codeInput1 & wave == input$codeInput2)))
    })

    output$view <- renderTable(dataset())
}

shinyApp(ui = ui, server = server)


问:
Drop a localdb database from VS package manager
I would like to be able to write a simple script to be able to drop a localdb database at will.

First I have to stop the instance to kill any active connections by running this in the VS package manager

```<code>SqlLocalDB.exe stop v11.0
</code>```

Then I need to drop the db which I have to do by connecting to (localdb)\v11.0 master db with Linqpad or SSMS

```<code>DROP DATABASE MyDb
</code>```

But I don't want to switch windows to do this, I'd like to just write a script. I can't figure out how to execute the second query from the command line. I've tried this

```<code>SQLCMD.EXE -s "(localdb)\v11.0" -d "master" -q "drop database MyDb"
</code>```

which gives me an error

```<code>SQLCMD.EXE : Sqlcmd: Error: Microsoft SQL Server Native Client 11.0 : Named Pipes Provider:
Could not open a connection to SQL Server [2]. .
</code>```

答:
As of May 2020, you can just type:

```<code>Drop-Database
</code>```

in the Package Manager console and it should work:

```<code>Are you sure you want to perform this action?
Performing the operation "Drop-Database" on target "database 'databasename' on server '(localdb)\mssqllocaldb'".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):y
</code>```

If it doesn't work, you might need to manually install Entity Framework Core tools.

Body:
I would like to be able to write a simple script to be able to drop a localdb database at will.

First I have to stop the instance to kill any active connections by running this in the VS package manager

SqlLocalDB.exe stop v11.0

Then I need to drop the db which I have to do by connecting to (localdb)\v11.0 master db with Linqpad or SSMS

DROP DATABASE MyDb

But I don't want to switch windows to do this, I'd like to just write a script. I can't figure out how to execute the second query from the command line. I've tried this

SQLCMD.EXE -s "(localdb)\v11.0" -d "master" -q "drop database MyDb"

which gives me an error

SQLCMD.EXE : Sqlcmd: Error: Microsoft SQL Server Native Client 11.0 : Named Pipes Provider:
Could not open a connection to SQL Server [2]. .

Body:
As of May 2020, you can just type:

Drop-Database

in the Package Manager console and it should work:

Are you sure you want to perform this action?
Performing the operation "Drop-Database" on target "database 'databasename' on server '(localdb)\mssqllocaldb'".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):y

If it doesn't work, you might need to manually install Entity Framework Core tools.


问:
python docker apis containers.run doesnt print output to console
I have pulled alpine image
I have build the container
I am trying run the image but I do not see any output on my console, anyone whats wrong?
If I run using docker run I can see the output

Python version is 2.7.10

```<code>dockerClient = docker.from_env()
image = dockerClient.images.pull(alpine)
dockerClient.images.build(path = "build/", tag="alpine_tests")
dockerClient.containers.run('alpine_tests', 'pwd')
</code>```

答:
If you really want to see information immediately, you should use docker build in CLI, or subproccess.call(['docker', 'build']) in Python.

When using the Python SDK, the stdout and stderr messages are always not necessary when success. Only when crashed or failed, messages are good.

```<code># docker build
client = docker.from_env()
try:
    client.images.build(
        path='build/',
        tag='alpine_tests',
    )
except docker.errors.BuildError as exc:
    for log in exc.build_log:
        msg = log.get('stream')
        if msg:
            print(msg, end='')
    raise

# docker push
ret = client.images.push(alpine_tests)
last_line = ret.splitlines()[-1]
info = json.loads(last_line)
error = info.get('error')
if error:
    print(error)
    exit(1)
</code>```

Body:
I have pulled alpine image
I have build the container
I am trying run the image but I do not see any output on my console, anyone whats wrong?
If I run using docker run I can see the output

Python version is 2.7.10

dockerClient = docker.from_env()
image = dockerClient.images.pull(alpine)
dockerClient.images.build(path = "build/", tag="alpine_tests")
dockerClient.containers.run('alpine_tests', 'pwd')

Body:
If you really want to see information immediately, you should use docker build in CLI, or subproccess.call(['docker', 'build']) in Python.

When using the Python SDK, the stdout and stderr messages are always not necessary when success. Only when crashed or failed, messages are good.

# docker build
client = docker.from_env()
try:
    client.images.build(
        path='build/',
        tag='alpine_tests',
    )
except docker.errors.BuildError as exc:
    for log in exc.build_log:
        msg = log.get('stream')
        if msg:
            print(msg, end='')
    raise

# docker push
ret = client.images.push(alpine_tests)
last_line = ret.splitlines()[-1]
info = json.loads(last_line)
error = info.get('error')
if error:
    print(error)
    exit(1)


问:
How can i test my resolvers properly with jest?
I'm trying to test my resolvers but i'd like to test each field of the response, here's the code to call the response:

```<code>interface Options {
  source: string;
  variableValues?: Maybe<{ [key: string]: unknown | null }>;
}

let schema: GraphQLSchema;

const gCall = async ({
  source,
  variableValues,
}: Options): Promise<ExecutionResult> => {
  if (!schema) {
    schema = await createSchema();
  }
  return graphql({
    schema,
    source,
    variableValues,
  });
};

export default gCall;
</code>```

And that's the code to test the resolver:

```<code>let connection: Connection;
const challengeMutation = `
mutation CreateChallenge($data: CreateChallengeInput!) {
  createChallenge(data: $data) {
    id
    name
    category
    startDate
    endDate
    goal
    description
  }
}
`;

describe('Create Challenge', () => {
  beforeAll(async () => {
    connection = await databaseTestConnection();
    await connection.createQueryBuilder().delete().from(Challenge).execute();
  });

  afterAll(async () => {
    await connection.createQueryBuilder().delete().from(Challenge).execute();
    await connection.close();
  });

  it('should create challenge', async () => {
    const challenge = {
      name: 'some awesome name',
      category: 'distância',
      startDate: new Date(2020, 7, 4).toISOString(),
      endDate: new Date(2020, 7, 5).toISOString(),
      goal: 5000,
      description: 'some excelent challenge description',
    };

    const response = await gCall({
      source: challengeMutation,
      variableValues: {
        data: challenge,
      },
    });

    expect(response).toMatchObject({
      data: {
        createChallenge: {
          name: challenge.name,
          category: challenge.category,
          startDate: challenge.startDate,
          endDate: challenge.endDate,
          goal: challenge.goal,
          description: challenge.description,
        },
      },
    });
  });
});
</code>```

What I'd like to do is test the fields separately, like this:

```<code>expect(response.data.createChallenge.name).toEqual(challenge.name);
</code>```

But I'm getting the following error when I try to execute the above code:

```<code>Object is possibly 'null' or 'undefined'.
</code>```

What can I do to solve this error and to make this test better?

答:
Object is possibly 'null' or 'undefined'.

TypeScript warns you that the response data might not exist as the graphql "server" might return error instead. So you should use ! operator to assert it's not null.

You should also do that after checking it's not undefined with expect().

Body:
I'm trying to test my resolvers but i'd like to test each field of the response, here's the code to call the response:

interface Options {
  source: string;
  variableValues?: Maybe<{ [key: string]: unknown | null }>;
}

let schema: GraphQLSchema;

const gCall = async ({
  source,
  variableValues,
}: Options): Promise<ExecutionResult> => {
  if (!schema) {
    schema = await createSchema();
  }
  return graphql({
    schema,
    source,
    variableValues,
  });
};

export default gCall;

And that's the code to test the resolver:

let connection: Connection;
const challengeMutation = `
mutation CreateChallenge($data: CreateChallengeInput!) {
  createChallenge(data: $data) {
    id
    name
    category
    startDate
    endDate
    goal
    description
  }
}
`;

describe('Create Challenge', () => {
  beforeAll(async () => {
    connection = await databaseTestConnection();
    await connection.createQueryBuilder().delete().from(Challenge).execute();
  });

  afterAll(async () => {
    await connection.createQueryBuilder().delete().from(Challenge).execute();
    await connection.close();
  });

  it('should create challenge', async () => {
    const challenge = {
      name: 'some awesome name',
      category: 'distância',
      startDate: new Date(2020, 7, 4).toISOString(),
      endDate: new Date(2020, 7, 5).toISOString(),
      goal: 5000,
      description: 'some excelent challenge description',
    };

    const response = await gCall({
      source: challengeMutation,
      variableValues: {
        data: challenge,
      },
    });

    expect(response).toMatchObject({
      data: {
        createChallenge: {
          name: challenge.name,
          category: challenge.category,
          startDate: challenge.startDate,
          endDate: challenge.endDate,
          goal: challenge.goal,
          description: challenge.description,
        },
      },
    });
  });
});

What I'd like to do is test the fields separately, like this:

expect(response.data.createChallenge.name).toEqual(challenge.name);

But I'm getting the following error when I try to execute the above code:

Object is possibly 'null' or 'undefined'.

What can I do to solve this error and to make this test better?


问:
Autorun script for any activity on linux server
so i have around 500 servers for which i wanted to create a script that automatically login and do some trivial activity to create some logs (basically want to send logs through siem tool to check if log sending is working or not) and then automatically logoff from the server.
I am planning that the script can be auto-run on the server every 15 days.
trivial activity can be anything(just want to create logs).
Any help how to achieve that??

EDIT

i was thinking now that stopping and starting a service in server will accomplish my need. Any help on that script. i am actually new in working in linux server. so any help is greatly appriciated.

答:
You could use cron jobs.

In the crontab file of every server you need to make an entry of the time when you wanna run the script in your case every 15 days and the location of your script file.

0 0 */15 * * /path/to/script.sh

Mind you the job would run a bit differently, as it would start at the 1st of every month, then on 16th and then finally on 31st if the month has 31 days.


问:
iOS Validate archive failed with CFBundleIdentifier Collision & Invalid Bundle
I archived my app and would like to upload the ipa file.

But, uploading was failed with these errors.

```<code>App Store Connect Operation Error
CFBundleIdentifier Collision. There is more than one bundle with the     CFBundleIdentifier value 'org.alamofire.Alamofire' under the iOS application     'MyApp.app'.

App Store Connect Operation Error
CFBundleIdentifier Collision. There is more than one bundle with the     CFBundleIdentifier value 'org.alamofire.AlamofireImage' under the iOS application 'MyApp.app'.

App Store Connect Operation Error
CFBundleIdentifier Collision. There is more than one bundle with the     CFBundleIdentifier value 'com.swiftyjson.SwiftyJSON' under the iOS application 'MyApp.app'.

App Store Connect Operation Error
Invalid Bundle. The bundle at 'MyApp.app/Frameworks/MyAppEmbedded.framework' contains disallowed nested bundles.

App Store Connect Operation Error
Invalid Bundle. The bundle at 'MyApp.app/Frameworks/MyAppEmbedded.framework' contains disallowed file 'Frameworks'.

App Store Connect Operation Error
Invalid Bundle. The bundle at 'MyApp.app/PlugIns/MyAppShare.appex' contains disallowed nested bundles.

App Store Connect Operation Error
Invalid Bundle. The bundle at 'MyApp.app/PlugIns/MyAppShare.appex' contains disallowed file 'Frameworks'.
</code>```

Project use Swift, but some third party library use Objective-C.

These are my project structure.

Targets

MyApp          - Main App

MyAppEmbeddded - Embedded Framework

MyAppShare     - Share Extension

MyApp, MyAppEmbedded and MyAppShare use Carthage & CocoaPods.

This is MyApp "Embedded Binaries" and "Linked Frameworks and Libraries"

This is MyAppEmbedded "Linked Frameworks and Libraries"

This is MyAppShare "Linked Frameworks and Libraries"

CFBundleIdentifier Collision Error occurred "Alamofire", "AlamofireImage" and "SwiftyJSON".

These three framework are used by MyAppEmbedded.

So, I think Embedded Framework has something a cause.

Also, I noticed ipa content is strange.

Embedded Framework include three same Embedded Frameworks.

I read some questions about uploading errors and checked Build Settings.

MyApp: "Always Embed Swift Standard Libraries" is YES

MyAppEmedded & MyAppShare: "Always Embed Swift Standard Libraries" is NO

If you know about this error, please tell me about it.

答:
I have modules set like this:

```<code>First module
Second module (embeds First module)
Main App (embeds First and Second module)
</code>```

Setting Embed to Do Not Embed for First module in Second module target (NOT Main App!) solved the problem for me ✅

Body:
I archived my app and would like to upload the ipa file.

But, uploading was failed with these errors.

App Store Connect Operation Error
CFBundleIdentifier Collision. There is more than one bundle with the     CFBundleIdentifier value 'org.alamofire.Alamofire' under the iOS application     'MyApp.app'.

App Store Connect Operation Error
CFBundleIdentifier Collision. There is more than one bundle with the     CFBundleIdentifier value 'org.alamofire.AlamofireImage' under the iOS application 'MyApp.app'.

App Store Connect Operation Error
CFBundleIdentifier Collision. There is more than one bundle with the     CFBundleIdentifier value 'com.swiftyjson.SwiftyJSON' under the iOS application 'MyApp.app'.

App Store Connect Operation Error
Invalid Bundle. The bundle at 'MyApp.app/Frameworks/MyAppEmbedded.framework' contains disallowed nested bundles.

App Store Connect Operation Error
Invalid Bundle. The bundle at 'MyApp.app/Frameworks/MyAppEmbedded.framework' contains disallowed file 'Frameworks'.

App Store Connect Operation Error
Invalid Bundle. The bundle at 'MyApp.app/PlugIns/MyAppShare.appex' contains disallowed nested bundles.

App Store Connect Operation Error
Invalid Bundle. The bundle at 'MyApp.app/PlugIns/MyAppShare.appex' contains disallowed file 'Frameworks'.

Project use Swift, but some third party library use Objective-C.

These are my project structure.

Targets

MyApp          - Main App

MyAppEmbeddded - Embedded Framework

MyAppShare     - Share Extension

MyApp, MyAppEmbedded and MyAppShare use Carthage & CocoaPods.

This is MyApp "Embedded Binaries" and "Linked Frameworks and Libraries"

This is MyAppEmbedded "Linked Frameworks and Libraries"

This is MyAppShare "Linked Frameworks and Libraries"

CFBundleIdentifier Collision Error occurred "Alamofire", "AlamofireImage" and "SwiftyJSON".

These three framework are used by MyAppEmbedded.

So, I think Embedded Framework has something a cause.

Also, I noticed ipa content is strange.

Embedded Framework include three same Embedded Frameworks.

I read some questions about uploading errors and checked Build Settings.

MyApp: "Always Embed Swift Standard Libraries" is YES

MyAppEmedded & MyAppShare: "Always Embed Swift Standard Libraries" is NO

If you know about this error, please tell me about it.

Body:
I have modules set like this:

First module
Second module (embeds First module)
Main App (embeds First and Second module)

Setting Embed to Do Not Embed for First module in Second module target (NOT Main App!) solved the problem for me ✅


问:
Using the len() function with unicode values
Python newbie here.
I have an excel file with 5000 rows and 1 columns.
I'm importing them into Python and will then use if...else
statements to check for specific conditions.

So my data looks like: (in excel)

```<code>Kansas
Colorado
Missouri
Iowa
New York
New Mexico
mycar
car
thisisacar
...
</code>```

There here is the code to import it into Python and the conditional
statements.

```<code>import xlrd
wb = xlrd.open_workbook("file.xls")

wb.sheet_names()
sh = wb.sheet_by_index(0)

for item in sh.col(0):
    value = unicode(item.value)
    if value.startswith("car"):
        print value
        if len(value) == 3:
            print value
</code>```

The idea is to print everything with "car", and then print
value when it only has a length of 3.

The if len(value) == 3 doesn't seem to work. help!

答: len(value) should work fine -- I suggest there's probably some trailing whitespace or similar, so try using len(value.strip()) and see if that solves your problem :)

Body:
Python newbie here.
I have an excel file with 5000 rows and 1 columns.
I'm importing them into Python and will then use if...else
statements to check for specific conditions.

So my data looks like: (in excel)

Kansas
Colorado
Missouri
Iowa
New York
New Mexico
mycar
car
thisisacar
...

There here is the code to import it into Python and the conditional
statements.

import xlrd
wb = xlrd.open_workbook("file.xls")

wb.sheet_names()
sh = wb.sheet_by_index(0)

for item in sh.col(0):
    value = unicode(item.value)
    if value.startswith("car"):
        print value
        if len(value) == 3:
            print value

The idea is to print everything with "car", and then print
value when it only has a length of 3.

The if len(value) == 3 doesn't seem to work. help!


问:
WPF how to clear the texbox content in list view using MVVM
I am using below code and MVVM observable, but "Clear" button not clears the content of text boxes.

What I need to do here?

MainWindow.xaml

```<code><Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="30*"/>
        <RowDefinition Height="10*"/>
    </Grid.RowDefinitions>
    <Grid>
        <ListView ItemsSource="{Binding Credentials, Mode=OneWay}">
            <ListView.View>
                <GridView>
                    <GridViewColumn  Header="User Name">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding UserName}" Width="100"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                    <GridViewColumn  Header="Password">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding Password}" Width="100"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
    <Grid Grid.Row="1" >
        <Button Grid.Column="0" Content="Clear" Command="{Binding ClearTextBoxCommand}" Width="150"/>
    </Grid>

</Grid>
</code>```

MainWindow.xaml.cs

```<code>public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MyViewModel();
    }
}
</code>```

MyViewModel.cs

```<code>public class MyViewModel : INotifyPropertyChanged
{
    private ObservableCollection<Credential> _credentials;

    public RelayCommand ClearTextBoxCommand { get; }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = null)
    {
        var handler = PropertyChanged;
        handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public ObservableCollection<Credential> Credentials
    {
        get => _credentials;
        set
        {
            if (value == _credentials)
                return;

            _credentials = value;
            OnPropertyChanged();
        }
    }

    public MyViewModel()
    {
        var data = new List<Credential> {new Credential {UserName = "user1", Password = "password1"}};
        _credentials = new ObservableCollection<Credential>(data);

        ClearTextBoxCommand = new RelayCommand(ClearTextBox);
    }

    private void ClearTextBox()
    {
        var data = new List<Credential> { new Credential { UserName = "", Password = "" } };
        _credentials = new ObservableCollection<Credential>(data);
        MessageBox.Show("clear done!");
    }
}

public class Credential
{
    public string UserName { get; set; }
    public string Password { get; set; }
}
</code>```

答:
Credentials property has notification about change in setter:

```<code>public ObservableCollection<Credential> Credentials
{
    get => _credentials;
    set
    {
        if (value == _credentials)
            return;

        _credentials = value;
        OnPropertyChanged();
    }
}
</code>```

so if you need to change that collection, use property, not _credentials field

not _credentials = new ObservableCollection<Credential>(data);, but

```<code>private void ClearTextBox()
{
    var data = new List<Credential> { new Credential { UserName = "", Password = "" } };
    Credentials = new ObservableCollection<Credential>(data);
    MessageBox.Show("clear done!");
}
</code>```

Body:
I am using below code and MVVM observable, but "Clear" button not clears the content of text boxes.

What I need to do here?

MainWindow.xaml

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="30*"/>
        <RowDefinition Height="10*"/>
    </Grid.RowDefinitions>
    <Grid>
        <ListView ItemsSource="{Binding Credentials, Mode=OneWay}">
            <ListView.View>
                <GridView>
                    <GridViewColumn  Header="User Name">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding UserName}" Width="100"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                    <GridViewColumn  Header="Password">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding Password}" Width="100"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
    <Grid Grid.Row="1" >
        <Button Grid.Column="0" Content="Clear" Command="{Binding ClearTextBoxCommand}" Width="150"/>
    </Grid>

</Grid>

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MyViewModel();
    }
}

MyViewModel.cs

public class MyViewModel : INotifyPropertyChanged
{
    private ObservableCollection<Credential> _credentials;

    public RelayCommand ClearTextBoxCommand { get; }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = null)
    {
        var handler = PropertyChanged;
        handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public ObservableCollection<Credential> Credentials
    {
        get => _credentials;
        set
        {
            if (value == _credentials)
                return;

            _credentials = value;
            OnPropertyChanged();
        }
    }

    public MyViewModel()
    {
        var data = new List<Credential> {new Credential {UserName = "user1", Password = "password1"}};
        _credentials = new ObservableCollection<Credential>(data);

        ClearTextBoxCommand = new RelayCommand(ClearTextBox);
    }

    private void ClearTextBox()
    {
        var data = new List<Credential> { new Credential { UserName = "", Password = "" } };
        _credentials = new ObservableCollection<Credential>(data);
        MessageBox.Show("clear done!");
    }
}

public class Credential
{
    public string UserName { get; set; }
    public string Password { get; set; }
}

Body:
Credentials property has notification about change in setter:

public ObservableCollection<Credential> Credentials
{
    get => _credentials;
    set
    {
        if (value == _credentials)
            return;

        _credentials = value;
        OnPropertyChanged();
    }
}

so if you need to change that collection, use property, not _credentials field

not _credentials = new ObservableCollection<Credential>(data);, but

private void ClearTextBox()
{
    var data = new List<Credential> { new Credential { UserName = "", Password = "" } };
    Credentials = new ObservableCollection<Credential>(data);
    MessageBox.Show("clear done!");
}


答:
The function returns none after printing the statement. You can modify the code as below to use the return in your favor.

```<code>def lucky_number(name):
    number = int(len(name) * 9)
    pr = 'Hello ' + name + '. Your lucky number is ' + str(number)
    return(str(pr))

print(lucky_number('kay'))
print(lucky_number('Cameron'))
</code>```

Or, you can just call the function and skip the print statement while calling to get rid of this.

```<code>def lucky_number(name):
    number = int(len(name) * 9)
    pr = 'Hello ' + name + '. Your lucky number is ' + str(number)
    print(str(pr))

lucky_number('kay')
lucky_number('Cameron')
</code>```

Title: None is printing

Body:
The function returns none after printing the statement. You can modify the code as below to use the return in your favor.

def lucky_number(name):
    number = int(len(name) * 9)
    pr = 'Hello ' + name + '. Your lucky number is ' + str(number)
    return(str(pr))

print(lucky_number('kay'))
print(lucky_number('Cameron'))

Or, you can just call the function and skip the print statement while calling to get rid of this.

def lucky_number(name):
    number = int(len(name) * 9)
    pr = 'Hello ' + name + '. Your lucky number is ' + str(number)
    print(str(pr))

lucky_number('kay')
lucky_number('Cameron')


问:
Pretty print CSV with many columns with each row as a table
I have a very large CSV with ~50 columns like the follows:

```<code>A,B,C,...,Z
v1,,v3,...,v26
w1,w2,w3,...,w26
</code>```

I want to display it in console, but tools like column -t doesn't work because each line is too long and wraps, making it unable to be read.

My goal is to display it row by row, with each row displayed as a table like <ColumnName> | <Value>:

```<code>----------
A |  v1
B |
C |  v3
...
Z |  v26
----------
<blank line>
----------
A |  w1
B |  w2
...
Z |  w26
----------
</code>```

答:
You must disable word wrap and you can use column in this way

```<code><input column -t -s, | less
</code>```

Body:
I have a very large CSV with ~50 columns like the follows:

A,B,C,...,Z
v1,,v3,...,v26
w1,w2,w3,...,w26

I want to display it in console, but tools like column -t doesn't work because each line is too long and wraps, making it unable to be read.

My goal is to display it row by row, with each row displayed as a table like <ColumnName> | <Value>:

----------
A |  v1
B |
C |  v3
...
Z |  v26
----------
<blank line>
----------
A |  w1
B |  w2
...
Z |  w26
----------

Body:
You must disable word wrap and you can use column in this way

<input column -t -s, | less


问:
Spring @Scheduled method SecurityContext
Is @Scheduled annotated method out of any SecurityContext? When I try to use the following it always has securitycontext/auth as null. If this is not possible then what could be the right way to run user specific authentication aware scheduled task?

```<code>    @Scheduled(fixedDelay = 10000)
    // This method will send notifications to the current user
    public void sendUserNotifications() {
        SecurityContext sc = SecurityContextHolder.getContext();
        Authentication auth = sc.getAuthentication();

        if(auth == null) {

            log.info(">> SecurityContext=[{}], Authentication[auth] is {}, please login to receive notifications", sc, auth);

            return;
        }
</code>```

答:
Given excerpt will never work.

Explanation:

Native session management is provided by underlying servlet API and container. HttpSession object is only created when the user logs in using request.getSession() under the hood and later this HttpSession will be used by SecurityContextHolder.getContext().getAuthentication(); internally.  This means it has a relation with the user's request which is a container-managed thread, not plain old JVM thread on which your scheduler will run.

Here your scheduler does not have any dependency on the user it will run independently on JVM managed thread. So no HttpRequest/HttpSession object will be created at all.

Imagine the very first time when you start the application and no user yet logged in then what would be scenario here.

So you will always get securitycontext/auth as null only.

To answer your question

If this is not possible then what could be the right way to run user
specific authentication aware scheduled task?

One way I can think of right now is, Use of spring provided SessionRegistry.
It keeps track of all currently logged-in users.

So you can pass this SessionRegistry object by autowiring to this scheduler and get list of all principal/logged-in users and send them a notification.

Something like below -

```<code>    @EnableScheduling
    @Component
    public class MyScheduler {

    @Autowired
    @Qualifier("sessionRegistry")
    private SessionRegistry sessionRegistry;
    @Scheduled(fixedDelay = 10000)
    // This method will send notifications to the current user
    public void sendUserNotifications() {
    List<UserDetails> principals = sessionRegistry.getAllPrincipals()
        .stream()
        .filter(principal -> principal instanceof UserDetails)
        .map(UserDetails.class::cast)
        .collect(Collectors.toList());

    // send notification to all users.
   }
</code>```

Also, you have to enable sessionRegistry in your security config first you have to listen to HTTP sessions and then configure registry in your security config.

```<code>        public class AppInitializer implements WebApplicationInitializer {

        @Override
        public void onStartup(ServletContext servletContext) {
        ...
        servletContext.addListener(HttpSessionEventPublisher.class);
         }
        }
</code>```

and security config -

```<code> @Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        // ...
        http.sessionManagement().maxSession(1).sessionRegistry(sessionRegistry());
    }

    @Bean
    public SessionRegistry sessionRegistry() {
        return new SessionRegistryImpl();
    }

    @Bean
    public HttpSessionEventPublisher httpSessionEventPublisher() {
        return new HttpSessionEventPublisher();
    }
 }
</code>```

For more details of how to get current logged in users see here.

Body:
Is @Scheduled annotated method out of any SecurityContext? When I try to use the following it always has securitycontext/auth as null. If this is not possible then what could be the right way to run user specific authentication aware scheduled task?

    @Scheduled(fixedDelay = 10000)
    // This method will send notifications to the current user
    public void sendUserNotifications() {
        SecurityContext sc = SecurityContextHolder.getContext();
        Authentication auth = sc.getAuthentication();

        if(auth == null) {

            log.info(">> SecurityContext=[{}], Authentication[auth] is {}, please login to receive notifications", sc, auth);

            return;
        }

Body:
Given excerpt will never work.

Explanation:

Native session management is provided by underlying servlet API and container. HttpSession object is only created when the user logs in using request.getSession() under the hood and later this HttpSession will be used by SecurityContextHolder.getContext().getAuthentication(); internally.  This means it has a relation with the user's request which is a container-managed thread, not plain old JVM thread on which your scheduler will run.

Here your scheduler does not have any dependency on the user it will run independently on JVM managed thread. So no HttpRequest/HttpSession object will be created at all.

Imagine the very first time when you start the application and no user yet logged in then what would be scenario here.

So you will always get securitycontext/auth as null only.

To answer your question

If this is not possible then what could be the right way to run user
specific authentication aware scheduled task?

One way I can think of right now is, Use of spring provided SessionRegistry.
It keeps track of all currently logged-in users.

So you can pass this SessionRegistry object by autowiring to this scheduler and get list of all principal/logged-in users and send them a notification.

Something like below -

    @EnableScheduling
    @Component
    public class MyScheduler {

    @Autowired
    @Qualifier("sessionRegistry")
    private SessionRegistry sessionRegistry;
    @Scheduled(fixedDelay = 10000)
    // This method will send notifications to the current user
    public void sendUserNotifications() {
    List<UserDetails> principals = sessionRegistry.getAllPrincipals()
        .stream()
        .filter(principal -> principal instanceof UserDetails)
        .map(UserDetails.class::cast)
        .collect(Collectors.toList());

    // send notification to all users.
   }

Also, you have to enable sessionRegistry in your security config first you have to listen to HTTP sessions and then configure registry in your security config.

        public class AppInitializer implements WebApplicationInitializer {

        @Override
        public void onStartup(ServletContext servletContext) {
        ...
        servletContext.addListener(HttpSessionEventPublisher.class);
         }
        }

and security config -

 @Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        // ...
        http.sessionManagement().maxSession(1).sessionRegistry(sessionRegistry());
    }

    @Bean
    public SessionRegistry sessionRegistry() {
        return new SessionRegistryImpl();
    }

    @Bean
    public HttpSessionEventPublisher httpSessionEventPublisher() {
        return new HttpSessionEventPublisher();
    }
 }

For more details of how to get current logged in users see here.