问:
Please give a step-by-step explanation of how Infix class from the Python Infix Hack instantination and operators overloading work
This article shows a way to create custom infix operators using functional programming in python.

Here is a simplified version of Infix class described in the article:

```<code>class Infix:
def __init__(self, function):
    self.function = function
def __ror__(self, other):
    return Infix(lambda x, self=self, other=other: self.function(other, x))
def __or__(self, other):
    return self.function(other)
</code>```

And some examples of its usage:

```<code># simple multiplication
x=Infix(lambda x,y: x*y)
print 2 |x| 4
# => 8

# class checking
isa=Infix(lambda x,y: x.__class__==y.__class__)
print [1,2,3] |isa| []
# => True
</code>```

I think I understand the righthand version of the operators and how the double underscore methods work but I just can't wrap my mind around how this hack works.

答:
2 |x| 4 calls x.__ror__(2).__or__(4). Now x.__ror__(2) returns Infix(lambda arg, self=self, other=other: self.function(other, arg)), where in this case self.function is lambda x,y: x*y and other is 2. So we get: Infix(lambda arg, self=x, other=2: other * arg). On this we call .__or__(4), which returns self.function(other) where other is 4. So:

```<code>(lambda arg, self=x, other=2: other * arg)(4)
   ===
arg = 4
self = x
other = 2
other * arg
   ===
4 * 2
   ===
8
</code>```

So we get 8.

Body:
This article shows a way to create custom infix operators using functional programming in python.

Here is a simplified version of Infix class described in the article:

class Infix:
def __init__(self, function):
    self.function = function
def __ror__(self, other):
    return Infix(lambda x, self=self, other=other: self.function(other, x))
def __or__(self, other):
    return self.function(other)

And some examples of its usage:

# simple multiplication
x=Infix(lambda x,y: x*y)
print 2 |x| 4
# => 8

# class checking
isa=Infix(lambda x,y: x.__class__==y.__class__)
print [1,2,3] |isa| []
# => True

I think I understand the righthand version of the operators and how the double underscore methods work but I just can't wrap my mind around how this hack works.

Body:
2 |x| 4 calls x.__ror__(2).__or__(4). Now x.__ror__(2) returns Infix(lambda arg, self=self, other=other: self.function(other, arg)), where in this case self.function is lambda x,y: x*y and other is 2. So we get: Infix(lambda arg, self=x, other=2: other * arg). On this we call .__or__(4), which returns self.function(other) where other is 4. So:

(lambda arg, self=x, other=2: other * arg)(4)
   ===
arg = 4
self = x
other = 2
other * arg
   ===
4 * 2
   ===
8

So we get 8.


来源: stackexchange

问:
Tabs with equal (constant) width in JTabbedPane
I'm trying to get a JTabbedPane where all tabs (the actual tabs, not the components) have the same width (either the minimum width needed for the widest label or a constant width).

I've tried to override BasicTabbedPaneUI.getTabBounds(int tabIndex, Rectangle dest), but apparently this method isn't used by the painting methods of BasicTabbedPaneUI, instead it uses a rects array to determine the tabs size.

My next approach would be to override JTabbedPane.insertTab(String title, Icon icon, Component component, String tip, int index) and setting the preferred size of the label component, but this doesn't seem very elegant and I'm not even sure it would work at all.

Is there a way to achieve this?

答: I think it's not as complicated as you've done. Just use setTabComponentAt() with a JLabel on which you've set preferred size.</p>

OwnerDisplayName: Ole

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Software Monkey


问:
MongoDB - How to convert .or to aggregate equivalent when trying to find documents based on a query string?
Example of a working response (Tag documents):

```<code>[
  {
    _id: 5a27a6b09fe2c0057782199a,
    label: '05',
    createdBy: 5a27a66f4db90e0541315114,
    createdAt: 2017-12-06T08:17:09.480Z,
    updatedAt: null,
    __v: 0,
    occurrences: 1
  },
  ...
]
</code>```

This is my original code:

```<code>Tag.find({})
  .or({label: new RegExp(config.query, 'i')})
  .sort(config.sortBy)
  .limit(config.limit)
  .skip(config.offset)
  .exec((err, tags) => {});
</code>```

This works brilliantly, however I came across a scenario where this approach wasn't going to work (unrelated to the question).

This rewritten code is going to also include the Page documents, specifically the tags array. Here's an example Page document:

```<code>{
  "_id" : ObjectId("5a27a6b09fe2c00577821999"),
  "organisation" : ObjectId("5a17eb11bf3f990b94c01735"),
  "createdBy" : ObjectId("5a27a66f4db90e0541315114"),
  "createdAt" : ISODate("2017-12-06T08:13:36.199Z"),
  "updatedBy" : ObjectId("5a27a66f4db90e0541315114"),
  "updatedAt" : ISODate("2017-12-06T08:18:20.809Z"),
  "tags" : [
    ObjectId("5a27a6b09fe2c0057782199a"),
    ObjectId("5a27a7859fe2c005778219a6"),
    ObjectId("5a27a7859fe2c005778219a4")
  ],
  "content" : "asd",
  "description" : "asdasd",
  "title" : "testing tag creation",
  "parent" : null,
  "__v" : 0
}
</code>```

So this is what I have now:

```<code>Page.aggregate([
  {
    $unwind: "$tags"
  },

  // This bit ain't working
  {
    $match: {
      $or: [{
        label: new RegExp(config.query, 'i')
      }]
    }
  },

  {
    $group: {
      _id: "$tags",
      occurrences: {
        $sum: 1
      }
    }
  },
  {
    $lookup: {
      from: "tags",
      localField: "_id",
      foreignField: "_id",
      as: "tagsData"
    }
  },
  {$limit: config.limit},
  {$skip: config.offset},
  {$sort: {[config.sortBy]: config.order}},
  {
    $project: {
      occurrences: "$occurrences",
      tagData: {
        $arrayElemAt: [
          "$tagsData", 0
        ]
      }
    }
  },
  {
    $addFields: {
      "tagData._id": "$_id",
      "tagData.occurrences": "$occurrences"
    }
  },
  {
    $replaceRoot: {
      newRoot: "$tagData"
    }
  }
  ], (err, tags) => {
    console.log(tags);
  });
</code>```

What I'm trying to do is replace this bit:

```<code>.or({label: new RegExp(config.query, 'i')})
</code>```

With the equivalent in the aggregate framework.

My attempt above always yields an empty array, even if I do $match: {label: '05'} for example I get no results.

I've been checking the docs but they aren't that obvious to me since this is the first time I'm working with aggregation.

I've looked at these two:

https://docs.mongodb.com/manual/reference/operator/aggregation/match/
https://docs.mongodb.com/manual/reference/operator/aggregation/or/

So my question is what am I doing wrong with the query bit?

答:
As I mentioned in the comments Tag.find({}).or({label: new RegExp(config.query, 'i')}) makes  no sense to me, nor most of the aggregation pipeline.

There are few obvious problems in the pipeline that I will aim in the answer:

Page has only Id's of tags, so $match by tag label should be done after $lookup stage, where labels become available.

there is no need to $unwind before $lookup since v3.3

$lookup itself refers to wrong fields localField: "_id" is _id of the page, which would hardly match any document in the tags collection

it is not clear whether $group should count tags, or pages. I am assuming the former in the answer below.

all the transformation stages - hard to guess the intentions, so I excluded them from the snippet below. Also removed sort-limit stages for brevity.

The shell query to count how many times tags with labels that match regexp /05/i were used on all pages:

```<code>db.pages.aggregate([
  {
    $lookup: {
      from: "tags",
      localField: "tags",
      foreignField: "_id",
      as: "tagsData"
    }
  },
  {
      $unwind: "$tagsData"
  },
  {
      $match: {
          "tagsData.label": /05/i
      }
  },
  {
    $group: {
      _id: "$tagsData",
      occurrences: {
        $sum: 1
      }
    }
  }
]);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Example of a working response (Tag documents):

[
  {
    _id: 5a27a6b09fe2c0057782199a,
    label: '05',
    createdBy: 5a27a66f4db90e0541315114,
    createdAt: 2017-12-06T08:17:09.480Z,
    updatedAt: null,
    __v: 0,
    occurrences: 1
  },
  ...
]

This is my original code:

Tag.find({})
  .or({label: new RegExp(config.query, 'i')})
  .sort(config.sortBy)
  .limit(config.limit)
  .skip(config.offset)
  .exec((err, tags) => {});

This works brilliantly, however I came across a scenario where this approach wasn't going to work (unrelated to the question).

This rewritten code is going to also include the Page documents, specifically the tags array. Here's an example Page document:

{
  "_id" : ObjectId("5a27a6b09fe2c00577821999"),
  "organisation" : ObjectId("5a17eb11bf3f990b94c01735"),
  "createdBy" : ObjectId("5a27a66f4db90e0541315114"),
  "createdAt" : ISODate("2017-12-06T08:13:36.199Z"),
  "updatedBy" : ObjectId("5a27a66f4db90e0541315114"),
  "updatedAt" : ISODate("2017-12-06T08:18:20.809Z"),
  "tags" : [
    ObjectId("5a27a6b09fe2c0057782199a"),
    ObjectId("5a27a7859fe2c005778219a6"),
    ObjectId("5a27a7859fe2c005778219a4")
  ],
  "content" : "asd",
  "description" : "asdasd",
  "title" : "testing tag creation",
  "parent" : null,
  "__v" : 0
}

So this is what I have now:

Page.aggregate([
  {
    $unwind: "$tags"
  },

  // This bit ain't working
  {
    $match: {
      $or: [{
        label: new RegExp(config.query, 'i')
      }]
    }
  },

  {
    $group: {
      _id: "$tags",
      occurrences: {
        $sum: 1
      }
    }
  },
  {
    $lookup: {
      from: "tags",
      localField: "_id",
      foreignField: "_id",
      as: "tagsData"
    }
  },
  {$limit: config.limit},
  {$skip: config.offset},
  {$sort: {[config.sortBy]: config.order}},
  {
    $project: {
      occurrences: "$occurrences",
      tagData: {
        $arrayElemAt: [
          "$tagsData", 0
        ]
      }
    }
  },
  {
    $addFields: {
      "tagData._id": "$_id",
      "tagData.occurrences": "$occurrences"
    }
  },
  {
    $replaceRoot: {
      newRoot: "$tagData"
    }
  }
  ], (err, tags) => {
    console.log(tags);
  });

What I'm trying to do is replace this bit:

.or({label: new RegExp(config.query, 'i')})

With the equivalent in the aggregate framework.

My attempt above always yields an empty array, even if I do $match: {label: '05'} for example I get no results.

I've been checking the docs but they aren't that obvious to me since this is the first time I'm working with aggregation.

I've looked at these two:

https://docs.mongodb.com/manual/reference/operator/aggregation/match/
https://docs.mongodb.com/manual/reference/operator/aggregation/or/

So my question is what am I doing wrong with the query bit?

Body:
As I mentioned in the comments Tag.find({}).or({label: new RegExp(config.query, 'i')}) makes  no sense to me, nor most of the aggregation pipeline.

There are few obvious problems in the pipeline that I will aim in the answer:

Page has only Id's of tags, so $match by tag label should be done after $lookup stage, where labels become available.

there is no need to $unwind before $lookup since v3.3

$lookup itself refers to wrong fields localField: "_id" is _id of the page, which would hardly match any document in the tags collection

it is not clear whether $group should count tags, or pages. I am assuming the former in the answer below.

all the transformation stages - hard to guess the intentions, so I excluded them from the snippet below. Also removed sort-limit stages for brevity.

The shell query to count how many times tags with labels that match regexp /05/i were used on all pages:

db.pages.aggregate([
  {
    $lookup: {
      from: "tags",
      localField: "tags",
      foreignField: "_id",
      as: "tagsData"
    }
  },
  {
      $unwind: "$tagsData"
  },
  {
      $match: {
          "tagsData.label": /05/i
      }
  },
  {
    $group: {
      _id: "$tagsData",
      occurrences: {
        $sum: 1
      }
    }
  }
]);


问:
Join two tables and show the retrieved information in thymeleaf
I work with Spring MVC and JPA. I want to join the data out of two classes (tables) and show data out of both tables via thymeleaf html.

These are the two classes I want to join:

```<code>@Entity
@Table(name = "package_aud")
public class PackageAudited {

@Column(name="id")
private Integer id;

@Id
@GeneratedValue
@Column(name="rev")
private Integer rev;

@Column(name="revtype")
private Integer revtype;

@OneToOne
@JoinColumn(name = "rev", nullable=true)
private RevisionInfo info;

... more attributes and getters/setters
</code>```

And

```<code>@Entity
@RevisionEntity(RevListener.class)
@Table(name = "revinfo")
public class RevisionInfo {

@Id
@RevisionNumber
@GeneratedValue
@Column(name="rev")
private Integer rev;

@RevisionTimestamp
@Column(name="revtstmp")
private Date revtstmp;

@Column(name="revuser")
private String revuser;

... getters/setters
</code>```

This is the repository where I try to join the tables with a query:

```<code>public interface PackageAuditedRepository extends
CrudRepository<PackageAudited, Long> {

@Query("SELECT p, c FROM PackageAudited p join p.info c WHERE p.id =:id AND p.rev = c.rev")
List<PackageAudited> findById(@Param("id") Integer id);
</code>```

Controller entry for the html template:

```<code>@PostMapping("/listSelectedPackage")
public String selectedPackage(@RequestParam("packageId") Integer packageId, Model model) {
        Iterable<PackageAudited> specificPackageHistory = this.packageAuditedRepository.findById(packageId);
        model.addAttribute("specificPackageHistory", specificPackageHistory);
        return "/package/listSelectedPackage";
}
</code>```

Html template to show the joined data:

```<code><table class ="center">
<thead>
    <tr>
        ...
    </tr>
</thead>
<tbody>
    <tr th:each="package : ${specificPackageHistory}">
        <td th:text="${package.rev}"> </td>
        <td th:text="${package.id}"> </td>
        <td th:text="${package.revuser}"></td>
        <td th:text="${package.revtstmp}"></td>
    </tr>
</tbody>
</table>
</code>```

My code works when I try to show only the data from the PackageAudited class. My query doesn't get me any results and I'm also not sure if ${package.revuser} and ${package.revtstmp} works.

答:
I've solved it by adding a getter for RevisionEntity info to PackageAudited and changing the thymeleaf html to:</p>

```<code>th:text="${package.info.?getRevuser()}"
...
</code>```

Body:
I work with Spring MVC and JPA. I want to join the data out of two classes (tables) and show data out of both tables via thymeleaf html.

These are the two classes I want to join:

@Entity
@Table(name = "package_aud")
public class PackageAudited {

@Column(name="id")
private Integer id;

@Id
@GeneratedValue
@Column(name="rev")
private Integer rev;

@Column(name="revtype")
private Integer revtype;

@OneToOne
@JoinColumn(name = "rev", nullable=true)
private RevisionInfo info;

... more attributes and getters/setters

And

@Entity
@RevisionEntity(RevListener.class)
@Table(name = "revinfo")
public class RevisionInfo {

@Id
@RevisionNumber
@GeneratedValue
@Column(name="rev")
private Integer rev;

@RevisionTimestamp
@Column(name="revtstmp")
private Date revtstmp;

@Column(name="revuser")
private String revuser;

... getters/setters

This is the repository where I try to join the tables with a query:

public interface PackageAuditedRepository extends
CrudRepository<PackageAudited, Long> {

@Query("SELECT p, c FROM PackageAudited p join p.info c WHERE p.id =:id AND p.rev = c.rev")
List<PackageAudited> findById(@Param("id") Integer id);

Controller entry for the html template:

@PostMapping("/listSelectedPackage")
public String selectedPackage(@RequestParam("packageId") Integer packageId, Model model) {
        Iterable<PackageAudited> specificPackageHistory = this.packageAuditedRepository.findById(packageId);
        model.addAttribute("specificPackageHistory", specificPackageHistory);
        return "/package/listSelectedPackage";
}

Html template to show the joined data:

        ...

My code works when I try to show only the data from the PackageAudited class. My query doesn't get me any results and I'm also not sure if ${package.revuser} and ${package.revtstmp} works.

Body:
I've solved it by adding a getter for RevisionEntity info to PackageAudited and changing the thymeleaf html to:

th:text="${package.info.?getRevuser()}"
...


问:
How do I avoid NullPointerExceptions in lambda comparators?
I want to compare two given objects which might be null at runtime. In my example:

```<code>@Test
public void shouldCompareAgents() {

    Agent a1 = new Agent();
    a1.setId("4711");
    a1.setType(null);

    Agent a2 = new Agent();
    a2.setId(a1.getId());
    a2.setType(a1.getType());

    assertEquals("Agent.getId", 0,
            Comparator.comparing(Agent::getId).compare(a1, a2));

    assertEquals("Agent.getType", 0,
            Comparator.comparing(Agent::getType).compare(a1, a2));
}
</code>```

The assertion by id works fine, by type does not as a1.getType() is null. Is there a way to avoid this? I tried Comparator.nullsLast(...), but that makes no sense as I am not sorting elements here.

I have lots of assertions to do, so I'd prefer "a one-liner". I am new to lambda expressions.

答:
Something like this:

```<code>Comparator.comparing(Agent::getType,
    Comparator.nullsLast(Comparator.naturalOrder()))
</code>```

Since you need this to be used in more places, you can extract it as :

```<code>    private static <R, T extends Comparable<T>> boolean areEqual(R left, R right, Function<R, T> function) {
         return Comparator.comparing(
                 function,
                 Comparator.nullsLast(Comparator.naturalOrder()))
                           .compare(left, right) == 0;
}
</code>```

Body:
I want to compare two given objects which might be null at runtime. In my example:

@Test
public void shouldCompareAgents() {

    Agent a1 = new Agent();
    a1.setId("4711");
    a1.setType(null);

    Agent a2 = new Agent();
    a2.setId(a1.getId());
    a2.setType(a1.getType());

    assertEquals("Agent.getId", 0,
            Comparator.comparing(Agent::getId).compare(a1, a2));

    assertEquals("Agent.getType", 0,
            Comparator.comparing(Agent::getType).compare(a1, a2));
}

The assertion by id works fine, by type does not as a1.getType() is null. Is there a way to avoid this? I tried Comparator.nullsLast(...), but that makes no sense as I am not sorting elements here.

I have lots of assertions to do, so I'd prefer "a one-liner". I am new to lambda expressions.

Body:
Something like this:

Comparator.comparing(Agent::getType,
    Comparator.nullsLast(Comparator.naturalOrder()))

Since you need this to be used in more places, you can extract it as :

    private static <R, T extends Comparable<T>> boolean areEqual(R left, R right, Function<R, T> function) {
         return Comparator.comparing(
                 function,
                 Comparator.nullsLast(Comparator.naturalOrder()))
                           .compare(left, right) == 0;
}


问:
How to recalculate normals?
I'm trying to write a simple shader that moves all verts with a sin wave.

```<code>v.vertex.y += sin(_Time.y * _Speed + v.vertex.x * _Amount * v.vertex.z) * _Distance;
</code>```

The problem is that after moving them, the normals are wrong, thus there are no real time shadows. I've searched a lot and found that I need to recalculate the normals using fake neighbours. None of the implementations were for Unity Shaderlab, so I can't just copy and paste them, and my knowledge of shader code is pretty basic so I can't translate what I found to what I need.

Can anyone help me with what and how to recalculate normals after moving a vertex?

答:
The math behind normal calculation is cross product.

Take vertex A, B and C from a triangle. Then create vectors AB and AC.
ABxAC will give you the normal of the triangle. ACxAB will give the opposite normal (ABxAC = - ACxAB).

en.wikipedia.org/wiki/Cross_product

If you were to move the mesh from Mesh class, there is a RecalculateNormals. But I guess that doesn't apply here as you work on the shader.

Title: How to recalculate normals?

Body:
I'm trying to write a simple shader that moves all verts with a sin wave.

v.vertex.y += sin(_Time.y * _Speed + v.vertex.x * _Amount * v.vertex.z) * _Distance;

The problem is that after moving them, the normals are wrong, thus there are no real time shadows. I've searched a lot and found that I need to recalculate the normals using fake neighbours. None of the implementations were for Unity Shaderlab, so I can't just copy and paste them, and my knowledge of shader code is pretty basic so I can't translate what I found to what I need.

Can anyone help me with what and how to recalculate normals after moving a vertex?


问:
Spark Sql query works with hardcoded value but not with variable
I have a PySpark program in which there is a SQL query like this:

```<code>id = 'abc1'

info = sqlc.sql("SELECT * from df WHERE isn = 'id'")
</code>```

This query does not work. I am returned with a blank set of values. However, if I hardcode the value, it works.

```<code>info = sqlc.sql("SELECT * from df WHERE isn = 'abc1'")
</code>```

I have tried str(id) just to be sure. How can I resolve this?

答:
Use format in Python 3.5 or before:

```<code>info = sqlc.sql("SELECT * from df WHERE isn = '{id}'".format(id=id))
</code>```

or

```<code>info = sqlc.sql("SELECT * from df WHERE isn = '{}'".format(id))
</code>```

Literal string formatting in Python 3.6 and later:

```<code>info = sqlc.sql(f"SELECT * from df WHERE isn = '{id}'")
</code>```

Body:
I have a PySpark program in which there is a SQL query like this:

id = 'abc1'

info = sqlc.sql("SELECT * from df WHERE isn = 'id'")

This query does not work. I am returned with a blank set of values. However, if I hardcode the value, it works.

info = sqlc.sql("SELECT * from df WHERE isn = 'abc1'")

I have tried str(id) just to be sure. How can I resolve this?

Body:
Use format in Python 3.5 or before:

info = sqlc.sql("SELECT * from df WHERE isn = '{id}'".format(id=id))

or

info = sqlc.sql("SELECT * from df WHERE isn = '{}'".format(id))

Literal string formatting in Python 3.6 and later:

info = sqlc.sql(f"SELECT * from df WHERE isn = '{id}'")


问:
How to read XML documentation comments using Roslyn
I would like to be able to read XML documentation comments while parsing C# source code using Roslyn.

```<code>/// <summary>
/// Documentation...
/// </summary>
</code>```

I tried setting the ParseDocumentationComments in the ParseOptions, but it doesn't seem to have an effect?

```<code>var parseOptions = ParseOptions.Default.WithParseDocumentationComments(true);
SyntaxTree unit = SyntaxTree.ParseFile(file, parseOptions);
</code>```

答:
Update :

FirstOrDefault method is no longer available. So use enumerator instead.

Updated code :

```<code>using System;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;

class Program
{
    static void Main(string[] args)
    {
        var tree = CSharpSyntaxTree.ParseText(@"
/// <summary> This is an xml doc comment </summary>
class C
{
}");
        var root = (CompilationUnitSyntax) tree.GetRoot();
        var classNode = (ClassDeclarationSyntax) (root.Members.First());

        var trivias = classNode.GetLeadingTrivia();
        var enumerator = trivias.GetEnumerator();
        while (enumerator.MoveNext())
        {
           var trivia = enumerator.Current;
           if(trivia.Kind().Equals(SyntaxKind.SingleLineDocumentationCommentTrivia))
           {
               var xml = trivia.GetStructure();
               Console.WriteLine(xml);
           }
        }
    }
}
</code>```

Body:
I would like to be able to read XML documentation comments while parsing C# source code using Roslyn.

///
/// Documentation...
///

I tried setting the ParseDocumentationComments in the ParseOptions, but it doesn't seem to have an effect?

var parseOptions = ParseOptions.Default.WithParseDocumentationComments(true);
SyntaxTree unit = SyntaxTree.ParseFile(file, parseOptions);

Body:
Update :

FirstOrDefault method is no longer available. So use enumerator instead.

Updated code :

using System;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;

class Program
{
    static void Main(string[] args)
    {
        var tree = CSharpSyntaxTree.ParseText(@"
/// <summary> This is an xml doc comment </summary>
class C
{
}");
        var root = (CompilationUnitSyntax) tree.GetRoot();
        var classNode = (ClassDeclarationSyntax) (root.Members.First());

        var trivias = classNode.GetLeadingTrivia();
        var enumerator = trivias.GetEnumerator();
        while (enumerator.MoveNext())
        {
           var trivia = enumerator.Current;
           if(trivia.Kind().Equals(SyntaxKind.SingleLineDocumentationCommentTrivia))
           {
               var xml = trivia.GetStructure();
               Console.WriteLine(xml);
           }
        }
    }
}


问:
How to add a character like ("," , "[" , "]") at the end of a JSON-Object

I have a Python-script that makes an File with invalid JSON.
Now I want to manipulate this JSON-File so it becomes a valid JSON-file by adding a comma between every object, at the beginning of the File a '[' and at the end a ']'.
Is there a way to make this with JSON alone or do i have to find a way with other read and write functions?

Exsample_File.json:

```<code>    {
    "firstName": "Bidhan",
    "lastName": "Chatterjee",
    "age": 40,
    "email":"bidhan@example.com"
    }
    {
    "firstName": "hanbid",
    "lastName": "jeeChatter",
    "age": 10,
    "email":"example@bidhan.com"
    }
     ....
    n times
</code>```

New_File.json:

```<code>    [
    {
    "firstName": "Bidhan",
    "lastName": "Chatterjee",
    "age": 40,
    "email":"bidhan@example.com"
    },
    {
    "firstName": "hanbid",
    "lastName": "jeeChatter",
    "age": 10,
    "email":"example@bidhan.com"
    },
     ....
    n times
    ]
</code>```

This is the function that makes this JSON-File. I dont want to touch the other code where the str is generated.

```<code>data = json.loads(str)
    with open('Example_File.json','ab')as outfile:
        json.dump(data, outfile, indent=2)
</code>```

So far i dont have an idea to solve this problem. so there is no code sample that would help.

The result should be like the New-File

答:
Can't you do

```<code>words.replace('}','},')
</code>```

This should replace all instances of '}' with a '},'

Body:
I have a Python-script that makes an File with invalid JSON.
Now I want to manipulate this JSON-File so it becomes a valid JSON-file by adding a comma between every object, at the beginning of the File a '[' and at the end a ']'.
Is there a way to make this with JSON alone or do i have to find a way with other read and write functions?

Exsample_File.json:

    {
    "firstName": "Bidhan",
    "lastName": "Chatterjee",
    "age": 40,
    "email":"bidhan@example.com"
    }
    {
    "firstName": "hanbid",
    "lastName": "jeeChatter",
    "age": 10,
    "email":"example@bidhan.com"
    }
     ....
    n times

New_File.json:

    [
    {
    "firstName": "Bidhan",
    "lastName": "Chatterjee",
    "age": 40,
    "email":"bidhan@example.com"
    },
    {
    "firstName": "hanbid",
    "lastName": "jeeChatter",
    "age": 10,
    "email":"example@bidhan.com"
    },
     ....
    n times
    ]

This is the function that makes this JSON-File. I dont want to touch the other code where the str is generated.

data = json.loads(str)
    with open('Example_File.json','ab')as outfile:
        json.dump(data, outfile, indent=2)

So far i dont have an idea to solve this problem. so there is no code sample that would help.

The result should be like the New-File

Body:
Can't you do

words.replace('}','},')

This should replace all instances of '}' with a '},'


问:
How to sort parallel arrays in javascript while keeping the indexes the same
I am working on a project in my javascript class and I am having trouble sorting parallel arrays. I have successfully sorted them alphabetically, however I also need to sort in ascending order. I have tried using a key to sort, but the professor said we are not allowed to alter the arrays given.I need to be able to sort the mnthCharge but keep the names and other data in line when they are sorted. Any pointers would be greatly appreciated!

var custName = new Array("Smith, Al","Toms, Andy","Jones, Zack","Vargas, Eddie","Donner, Alice","McMullen, Jessie","Nevins, Carol","Stark, Howard","Neeland, Franny","Boxby, Amos");

  var mnthCharge = new Array(140.00, 42.00, 18.00, 18.00, 36.00, 140.00, 42.00, 24.00, 140.00, 24.00);

var pastDueAmt = new Array(0, 0, 84.00, 36.00, 0, 18.00, 42.00, 42.00, 96.00, 0);

  var dayPastDue = new Array(0, 0, 60, 60, 0, 30, 90, 30, 120, 0);

  function recurringCharges()
{
  var d = [];
for(var i=0; i<custName.length; i++){
  //d.push(['Customer': custName[i], 'Recurring': mnthCharge[i], 'Amount': pastDueAmt[i], 'Days': dayPastDue[i]]);
    d.push([custName[i], mnthCharge[i],pastDueAmt[i],dayPastDue[i]]);
}
var sorted = d.sort();```

答:
Specify the item to sort by, and use {} instead [] for object notation:

var custName = ["Smith, Al","Toms, Andy","Jones, Zack","Vargas, Eddie","Donner, Alice","McMullen, Jessie","Nevins, Carol","Stark, Howard","Neeland, Franny","Boxby, Amos"]
var mnthCharge = [140.00, 42.00, 18.00, 18.00, 36.00, 140.00, 42.00, 24.00, 140.00, 24.00]
var pastDueAmt = [0, 0, 84.00, 36.00, 0, 18.00, 42.00, 42.00, 96.00, 0]
var dayPastDue = [0, 0, 60, 60, 0, 30, 90, 30, 120, 0]

for(var d = [], i = 0; i < custName.length; ++i)
    d.push({ Customer: custName[i], Recurring: mnthCharge[i],
             Amount: pastDueAmt[i], Days: dayPastDue[i]       })   // {} instead of []

d.sort(function(a, b) { return (a = a.Customer) > (b = b.Customer) || -(a < b) })

console.log( JSON.stringify( d ).replace(/},/g, '},\n ') )```


问:
Excel VBA "Subscript out of range" Run Error '9'
I have tried to implement the following code so that I can read a cell value and then places this value into another cell on the same Worksheet.

The worksheet has the following name: TestUserGuidance (Has no spaces)
The code is as follows:

```<code>Sub GuideTest()
    Dim dblPower, dblMass, dblRatedSpeed, dblRefLength, dblAwot, dblEngineSpeed, dblRoadSpeed As Double
    Dim dblPMR As Double

    dblPower = Worksheets("TestUserGuidance").Cell("B1").Value
    Worksheets("TestUserGuidance").Cell("E1") = dblPower
End Sub
</code>```

Could anyone please advise where I'm going wrong?

Thanks

答:
Only dblRoadSpeed is declared as double.
To fix it, declare all your variables as individual, in vba you can do in 2 ways.

```<code>Dim dblPower As Double, dblMass As Double
</code>```

Or

```<code>Dim dblPower As Double
Dim dblMass As Double
</code>```

Also, you don't need to declare any variable to do what you are doing.
You can copy the value in one step.

```<code>Worksheets("TestUserGuidance").Range("E1").Value = Worksheets("TestUserGuidance").Range("B1").Value
</code>```

Body:
I have tried to implement the following code so that I can read a cell value and then places this value into another cell on the same Worksheet.

The worksheet has the following name: TestUserGuidance (Has no spaces)
The code is as follows:

Sub GuideTest()
    Dim dblPower, dblMass, dblRatedSpeed, dblRefLength, dblAwot, dblEngineSpeed, dblRoadSpeed As Double
    Dim dblPMR As Double

    dblPower = Worksheets("TestUserGuidance").Cell("B1").Value
    Worksheets("TestUserGuidance").Cell("E1") = dblPower
End Sub

Could anyone please advise where I'm going wrong?

Thanks

Body:
Only dblRoadSpeed is declared as double.
To fix it, declare all your variables as individual, in vba you can do in 2 ways.

Dim dblPower As Double, dblMass As Double

Or

Dim dblPower As Double
Dim dblMass As Double

Also, you don't need to declare any variable to do what you are doing.
You can copy the value in one step.

Worksheets("TestUserGuidance").Range("E1").Value = Worksheets("TestUserGuidance").Range("B1").Value


问:
WordPress plugin management not working anymore
I'm using Wordpress version 4.8.4. In a while, I've experienced some issues in the plugin management panel: I can't manage them at all, no enable/disable, it's impossible to remove or install them.
What can be wrong? Is there any way to fix this?</p>

答:
The first thing to try is changing back to the default theme for any conflicts. If that resolves the issue, you would then disable all plugins and switch back to your theme. Enable each plugin one by one until it breaks again.

If that doesn't work you can turn off all plugins via PHPMyAdmin with the following mySQL statement

```<code>UPDATE wp_options SET option_value = '' WHERE option_name = 'active_plugins';
</code>```

You can run the same query direct in MySQL if you don't have PHPMyadmin.

That will turn off all plugins, then at that point you would do the same as mentioned above. Turn them on one by one until it breaks.

It's usually caused by JS conflicts with plugins and themes. Some plugins might load their scripts as a higher priority than your theme loads its own resources. After that then you would probably need the WordPress forums.

PhilB

Body:
The first thing to try is changing back to the default theme for any conflicts. If that resolves the issue, you would then disable all plugins and switch back to your theme. Enable each plugin one by one until it breaks again.

If that doesn't work you can turn off all plugins via PHPMyAdmin with the following mySQL statement

UPDATE wp_options SET option_value = '' WHERE option_name = 'active_plugins';

You can run the same query direct in MySQL if you don't have PHPMyadmin.

That will turn off all plugins, then at that point you would do the same as mentioned above. Turn them on one by one until it breaks.

It's usually caused by JS conflicts with plugins and themes. Some plugins might load their scripts as a higher priority than your theme loads its own resources. After that then you would probably need the WordPress forums.

PhilB


问:
Subdomain on different ip

Hello guys, i trying to create a new subdomain in my CloudFlare account but didn't work.

The root domain (mysite.com) is linked to heroku app, but i would like to link the subdomain (sub.mysite.com) to other server with different IP. I used 'A' record for this, but didn't work. My config is below. Does anyone know where I'm going wrong? Does using SSL in the root domain can be the problem?

.

答: As Dusan Basic noted, your DNS looks to be correct. Try taking traffic to the subdomain off Cloudflare by clicking the orange load for this record.</p>

Title: Subdomain on different ip


问:
prevent duplicates while inserting records in RabbitMq
Please suggest how to prevent  insert duplicate records in RabbitMQ Queue using java using values.

Example :

```<code>{
  "jsonObject" : {
     "code" : "ABC",
     "number" : "123456",
     "Name"  : "Narasimha"
  }
}
</code>```

if one record available in RabbitMq . if  try to insert one more record with same code and number it should  not allow to insert RabbitMQ.

答:
You cannot do that with RabbitMQ, the amqp body is a buffer and RMQ does not know anything about the body content.

You should handle duplications consumer side.

Read here: https://www.rabbitmq.com/reliability.html

At the Consumer

In the event of network failure (or a node crashing), messages can be
  duplicated, and consumers must be prepared to handle them. If
  possible, the simplest way to handle this is to ensure that your
  consumers handle messages in an idempotent way rather than explicitly
  deal with deduplication.

Body:
Please suggest how to prevent  insert duplicate records in RabbitMQ Queue using java using values.

Example :

{
  "jsonObject" : {
     "code" : "ABC",
     "number" : "123456",
     "Name"  : "Narasimha"
  }
}

if one record available in RabbitMq . if  try to insert one more record with same code and number it should  not allow to insert RabbitMQ.


问:
Db Structure Issue with EF
I have been messing around with Entity Framework code first for the last while trying to see what I can do with it.
One scenario I tested out was trying to duplicate the following DB schema:

Tables:

Person

Player

Manager

Person table holds basic data name,age etc.

Player table only holds information related to a player: currentclubId, positionId etc
The players basic details would be provided through a 1:1 relationship with the Person table on the Player Id and the PersonId.

Manager table is very similar to player table holds a 1:1 relationship with Person Table on the Manager Id and the person Id.

The idea behind this schema is that a person can be player and a manager throughout their career and I wanted to avoid duplication the basic details.

My issue is that EF Generates the Player Model with a Person Property.

```<code>public class Player {
    public Person Person {get;set;}
    .....
}
</code>```

Therefore to get the Players first name you must call Player.Person.FirstName.
This flow was fine for the beginning but I'm starting to see a performance issue with the Player and Manager queries as they have to fetch from two tables.

Is there any way I can refactor this schema to improve the performance while not violating the requirements?

答:
Since you are putting each class in a separate table, there always would be 3 tables. So, in any query, you would have a join statement which causes the performance issue you mentioned. And, actually, the domain you defined, doesn't need separation in tables. They are just ONE object with some small differences. So it's a good idea to merge tables to one, and avoid join queries. To do that, you have some options:

Using inheritance: Make Player and Manager inherit from Person and use TBH approach.

Using ComplexType: Make Player and Manager complex types (EF would see them just like an int, string, enum, etc).

In both cases you would have just one table for all 3 types; and there wouldn't be join at all.

Title: Db Structure Issue with EF

Body:
I have been messing around with Entity Framework code first for the last while trying to see what I can do with it.
One scenario I tested out was trying to duplicate the following DB schema:

Tables:

Person

Player

Manager

Person table holds basic data name,age etc.

Player table only holds information related to a player: currentclubId, positionId etc
The players basic details would be provided through a 1:1 relationship with the Person table on the Player Id and the PersonId.

Manager table is very similar to player table holds a 1:1 relationship with Person Table on the Manager Id and the person Id.

The idea behind this schema is that a person can be player and a manager throughout their career and I wanted to avoid duplication the basic details.

My issue is that EF Generates the Player Model with a Person Property.

public class Player {
    public Person Person {get;set;}
    .....
}

Therefore to get the Players first name you must call Player.Person.FirstName.
This flow was fine for the beginning but I'm starting to see a performance issue with the Player and Manager queries as they have to fetch from two tables.

Is there any way I can refactor this schema to improve the performance while not violating the requirements?


问:
NestJs websockets UnhandledPromiseRejectionWarning
I'm trying to add a 'events' module to my application for using websockets,
but when I add the module I get the following error:

```<code>(node:59905) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Request mapping properties not defined in the @RequestMapping() annotation!
(node:59905) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
</code>```

All the other modules are loaded and mapped successfully and it only happens when I add the EventsModule

so here's the code that I have:

app.module.ts

```<code>@Module({
    modules: [AuthModule, DatabaseModule, UsersModule, TimespansModule, LogsModule, EntitiesModule, EventsModule]
})
</code>```

events.module.ts

```<code>import {EventsComponent} from './events.component';
import {Module} from '@nestjs/common';
@Module({
    controllers: [EventsComponent]
})
export class EventsModule {}
</code>```

events.component.ts

```<code>import {WebSocketGateway, SubscribeMessage, OnGatewayConnection} from '@nestjs/websockets';

@WebSocketGateway({namespace: 'events'})
export class EventsComponent implements OnGatewayConnection {
    handleConnection(client: any) {
        console.log('client connected');
    }

    @SubscribeMessage('stream-received')
    onStream(client, data) {
        console.log('stream received');
    }
}
</code>```

I can't really see what's going wrong here, also the error message doesn't help me a lot.

答:
found the issue in events.module.ts

```<code>import {EventsComponent} from './events.component';
import {Module} from '@nestjs/common';
@Module({
    controllers: [EventsComponent]
})
export class EventsModule {}
</code>```

had to change controllers => components

```<code>import {EventsComponent} from './events.component';
import {Module} from '@nestjs/common';
@Module({
    components: [EventsComponent]
})
export class EventsModule {}
</code>```

Body:
I'm trying to add a 'events' module to my application for using websockets,
but when I add the module I get the following error:

(node:59905) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Request mapping properties not defined in the @RequestMapping() annotation!
(node:59905) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

All the other modules are loaded and mapped successfully and it only happens when I add the EventsModule

so here's the code that I have:

app.module.ts

@Module({
    modules: [AuthModule, DatabaseModule, UsersModule, TimespansModule, LogsModule, EntitiesModule, EventsModule]
})

events.module.ts

import {EventsComponent} from './events.component';
import {Module} from '@nestjs/common';
@Module({
    controllers: [EventsComponent]
})
export class EventsModule {}

events.component.ts

import {WebSocketGateway, SubscribeMessage, OnGatewayConnection} from '@nestjs/websockets';

@WebSocketGateway({namespace: 'events'})
export class EventsComponent implements OnGatewayConnection {
    handleConnection(client: any) {
        console.log('client connected');
    }

    @SubscribeMessage('stream-received')
    onStream(client, data) {
        console.log('stream received');
    }
}

I can't really see what's going wrong here, also the error message doesn't help me a lot.

Body:
found the issue in events.module.ts

import {EventsComponent} from './events.component';
import {Module} from '@nestjs/common';
@Module({
    controllers: [EventsComponent]
})
export class EventsModule {}

had to change controllers => components

import {EventsComponent} from './events.component';
import {Module} from '@nestjs/common';
@Module({
    components: [EventsComponent]
})
export class EventsModule {}


问:
Make docker machine available under host name in Windows
I'm trying to make a docker machine available to my Windows by a host name. After creating it like

```<code>docker-machine create -d virtualbox mymachine
</code>```

and setting up a docker container that exposes the port 80, how can I give that docker machine a host name such that I can enter "http://mymachine/" into my browser to load the website? When I change "mymachine" to the actual IP address then it works.

There is an answer to this question but I would like to achieve it without an entry in the hosts file. Is that possible?

答:
I suggest nginx-proxy. This is what I use all the time. It comes in especially handy when you are running different containers that are all supposed to answer to the same port (e.g. multiple web-services).

nginx-proxy runs seperately from your service and listens to docker-events to update it's own configuration. After you spun up your service and query the port nginx-proxy is listening to, you will be redirected to your service. Therefore you either need to start nginx-proxy with the DEFAULT_HOST flag or send the desired host as header param with the request.

As I am running this only with plain docker, I don't know if it works with docker-machine, though.

If you go for this option, you can decide for a certain domain (e.g. .docker) to be completely resolved to localhost. This can be either done company-wide by DNS, locally with hosts file or an intermediate resolver (the specific solution depends on your OS, of course). If you then try to reach http://service1.docker nginx-proxy will route to the container that has then ENV VIRTUAL_HOST=service1.docker. This is really convenient, because it only needs one-time setup and is from then on dynamic.

Body:
I'm trying to make a docker machine available to my Windows by a host name. After creating it like

docker-machine create -d virtualbox mymachine

and setting up a docker container that exposes the port 80, how can I give that docker machine a host name such that I can enter "http://mymachine/" into my browser to load the website? When I change "mymachine" to the actual IP address then it works.

There is an answer to this question but I would like to achieve it without an entry in the hosts file. Is that possible?

ContentLicense: CC BY-SA 4.0


问:
Integrate one regex into another one
I have the following regex for validating a path in windows:

^([A-Za-z]\:|\\|\.)(\\[^\\\/\:\*\?\""\<\>\|]*)+[\\]$

This just works fine. The path must end with \

I have another regex that checks a given string if it is a so called macro-string. The syntax of a macro-string is:

start with $

ends with $

may only contain [A-Za-z0-9] _ and :

Therefor I have the regex:

[$][\w:]+(?:[$][\w:]+[$][\w:]+)*[$]

Now I want to combine the two regular expression.

So that I can use a macro-string in a path-string.

The following path should be valid:

C:\temp\$emittemppath$\

The following path is invalid:

C:\temp\$emit()temppath$\

With just concat both regex with | the invalid-path would be recogniced as valid.

My question is also, how do I integrate the macro-regex in the other one. So that it checks the macro-syntax between $-chars?

Update:

A macro-name must be always between $

Update 2:

To identify which $ belongs to which part the \ could be used

Title: Integrate one regex into another one

Body:
What you could do is use a positive lookahead (?=to assert that it is a "macro-string":

(?=.*[$][\w:]+(?:[$][\w:]+[$][\w:]+)*[$])

If it is, then you could use add the part to validating a path in windows.

(?=.*[$][\w:]+(?:[$][\w:]+[$][\w:]+)*[$])^([A-Za-z]\:|\\|\.)(\\[^\\\/\:\*\?\""\<\>\|]*)+[\\]$


问:
How can I store multiple key pair values?
I'm currently following a tutorial on storing data in a persistent way, so that it will stay on the device so you can use it in-between sessions.

The tutorial shows how the user can enter in a Name and phone number within the main activity then it will be passed onto the view contacts activity. This uses key-value pairs. This lets the user view their contacts, even when the app is re-started.

However, each time the user adds a name and a phone number within the main activity, the previous name and phone number is overwritten. Allowing me to only store one contact within my list, when I want to store all contacts that have been inputted.

Can anyone help?

MainActivity.cs

```<code>using Android.App;
using Android.Widget;
using Android.OS;
using Android.Content;

namespace Contacts
{
    [Activity(Label = "Contacts", MainLauncher = true, Icon = "@mipmap/icon")]
    public class MainActivity : Activity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it

            Button button = FindViewById<Button>(Resource.Id.submitButton);

            button.Click += delegate
            {

                EditText nameBox = FindViewById<EditText>(Resource.Id.nameBox);
                string name = nameBox.Text;
                EditText phoneBox = FindViewById<EditText>(Resource.Id.phoneBox);
                string phone = phoneBox.Text;

                //add the new contact to the share preferrences

                var localContacts = Application.Context.GetSharedPreferences("MyContacts", FileCreationMode.Private);
                //Private file creation mode, which means that the data can't be accessed by any other app on the phone

                var contactEdit = localContacts.Edit(); // takes the shared preferences and tells it that we want to edit

                //this uses KeyValue pairs
                contactEdit.PutString("Name", name);
                contactEdit.PutString("Phone", phone);
                contactEdit.Commit(); //writes the shared preferences to the device

                //contactEdit.PutStringSet()

                // create a toast notification to confirm the submission

                Android.Widget.Toast.MakeText(this, "Item Added", ToastLength.Short).Show();

                //clear the boxes of the text

                nameBox.Text = "";
                phoneBox.Text = "";

            };

            //Button viewContactButton = FindViewById<Button>(Resource.Id.viewContactButton);

            //viewContactButton.Click += (sender, e) =>
            //{
            //   var intent = new Intent(this,)
            //    StartActivity(Intent);

            //};

            Button btnContactButton = FindViewById<Button>(Resource.Id.viewContactButton);

            btnContactButton.Click += delegate {

                StartActivity(typeof(ViewContactsActivity));
            };

        }
    }
}
</code>```

ViewContactsActivity.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;

namespace Contacts
{
    [Activity(Label = "ViewContactsActivity")]

    public class ViewContactsActivity : ListActivity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.ViewContacts);

            // retrieve the information from shared preferences
            //referencing the same file
            var localContacts = Application.Context.GetSharedPreferences("MyContacts", FileCreationMode.Private);

            string name = localContacts.GetString("Name", null);
            string phone = localContacts.GetString("Phone", null);

            //call the constructor, to overrride the string to control how it looks when you display it

            Contact myContact = new Contact(name, phone);

            //create an array of items that will go in the list

            Contact[] contactList = { myContact };

            //add the list to the list adapter

            ListAdapter = new ArrayAdapter<Contact>(this, Android.Resource.Layout.SimpleListItem1, contactList);

            //contact list is the item we want to display

        }
    }
}
</code>```

using System;

Contact.cs

```<code>namespace Contacts
{
    class Contact
    {

        public string Name { get; set; }
        public string PhoneNumber { get; set; }

        public Contact(string name, string phone)
        {

            Name = name;
            PhoneNumber = phone;
        }

        public override string ToString()
        {
            return Name + "" + PhoneNumber;
        }

        // this chooses how the information will be displayed

    }
}
</code>```

答:
@bamb094, hope this sample application will help in your case.

http://www.c-sharpcorner.com/article/serialization-and-deserialization-in-c-sharp/

Body:
I'm currently following a tutorial on storing data in a persistent way, so that it will stay on the device so you can use it in-between sessions.

The tutorial shows how the user can enter in a Name and phone number within the main activity then it will be passed onto the view contacts activity. This uses key-value pairs. This lets the user view their contacts, even when the app is re-started.

However, each time the user adds a name and a phone number within the main activity, the previous name and phone number is overwritten. Allowing me to only store one contact within my list, when I want to store all contacts that have been inputted.

Can anyone help?

MainActivity.cs

using Android.App;
using Android.Widget;
using Android.OS;
using Android.Content;

namespace Contacts
{
    [Activity(Label = "Contacts", MainLauncher = true, Icon = "@mipmap/icon")]
    public class MainActivity : Activity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it

            Button button = FindViewById<Button>(Resource.Id.submitButton);

            button.Click += delegate
            {

                EditText nameBox = FindViewById<EditText>(Resource.Id.nameBox);
                string name = nameBox.Text;
                EditText phoneBox = FindViewById<EditText>(Resource.Id.phoneBox);
                string phone = phoneBox.Text;

                //add the new contact to the share preferrences

                var localContacts = Application.Context.GetSharedPreferences("MyContacts", FileCreationMode.Private);
                //Private file creation mode, which means that the data can't be accessed by any other app on the phone

                var contactEdit = localContacts.Edit(); // takes the shared preferences and tells it that we want to edit

                //this uses KeyValue pairs
                contactEdit.PutString("Name", name);
                contactEdit.PutString("Phone", phone);
                contactEdit.Commit(); //writes the shared preferences to the device

                //contactEdit.PutStringSet()

                // create a toast notification to confirm the submission

                Android.Widget.Toast.MakeText(this, "Item Added", ToastLength.Short).Show();

                //clear the boxes of the text

                nameBox.Text = "";
                phoneBox.Text = "";

            };

            //Button viewContactButton = FindViewById<Button>(Resource.Id.viewContactButton);

            //viewContactButton.Click += (sender, e) =>
            //{
            //   var intent = new Intent(this,)
            //    StartActivity(Intent);

            //};

            Button btnContactButton = FindViewById<Button>(Resource.Id.viewContactButton);

            btnContactButton.Click += delegate {

                StartActivity(typeof(ViewContactsActivity));
            };

        }
    }
}

ViewContactsActivity.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;

namespace Contacts
{
    [Activity(Label = "ViewContactsActivity")]

    public class ViewContactsActivity : ListActivity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.ViewContacts);

            // retrieve the information from shared preferences
            //referencing the same file
            var localContacts = Application.Context.GetSharedPreferences("MyContacts", FileCreationMode.Private);

            string name = localContacts.GetString("Name", null);
            string phone = localContacts.GetString("Phone", null);

            //call the constructor, to overrride the string to control how it looks when you display it

            Contact myContact = new Contact(name, phone);

            //create an array of items that will go in the list

            Contact[] contactList = { myContact };

            //add the list to the list adapter

            ListAdapter = new ArrayAdapter<Contact>(this, Android.Resource.Layout.SimpleListItem1, contactList);

            //contact list is the item we want to display

        }
    }
}

using System;

Contact.cs

namespace Contacts
{
    class Contact
    {

        public string Name { get; set; }
        public string PhoneNumber { get; set; }

        public Contact(string name, string phone)
        {

            Name = name;
            PhoneNumber = phone;
        }

        public override string ToString()
        {
            return Name + "" + PhoneNumber;
        }

        // this chooses how the information will be displayed

    }
}


答:
You can use Objects.equals:

```<code>assertEquals("Agent.getId", true,
    Objects.equals(a1.getID(),a2.getID());

assertEquals("Agent.getType", true,
    Objects.equals(a1.getType(),a2.getType());
</code>```

Objects.equals handles nulls for you.

Title: How do I avoid NullPointerExceptions in lambda comparators?

Body:
I want to compare two given objects which might be null at runtime. In my example:

@Test
public void shouldCompareAgents() {

    Agent a1 = new Agent();
    a1.setId("4711");
    a1.setType(null);

    Agent a2 = new Agent();
    a2.setId(a1.getId());
    a2.setType(a1.getType());

    assertEquals("Agent.getId", 0,
            Comparator.comparing(Agent::getId).compare(a1, a2));

    assertEquals("Agent.getType", 0,
            Comparator.comparing(Agent::getType).compare(a1, a2));
}

The assertion by id works fine, by type does not as a1.getType() is null. Is there a way to avoid this? I tried Comparator.nullsLast(...), but that makes no sense as I am not sorting elements here.

I have lots of assertions to do, so I'd prefer "a one-liner". I am new to lambda expressions.

Body:
You can use Objects.equals:

assertEquals("Agent.getId", true,
    Objects.equals(a1.getID(),a2.getID());

assertEquals("Agent.getType", true,
    Objects.equals(a1.getType(),a2.getType());

Objects.equals handles nulls for you.


问:
tomcat java : class path resource [my-context.xml] cannot be opened because it does not exist
I can not deploy my .war file on tomcat8.

Here is the logs in the localhost file log:

```<code>06-Dec-2017 11:18:22.001 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log Closing Spring root WebApplicationContext
06-Dec-2017 11:18:22.655 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log ContextListener: contextInitialized()
06-Dec-2017 11:18:22.655 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log SessionListener: contextInitialized()
06-Dec-2017 11:18:34.230 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log Spring WebApplicationInitializers detected on classpath: [org.glassfish.jersey.server.spring.SpringWebApplicationInitializer@5a8b94fb]
06-Dec-2017 11:18:34.350 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log Initializing Spring root WebApplicationContext
06-Dec-2017 11:18:36.864 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.listenerStart Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
 org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from URL location [classpath:security-context.xml]
Offending resource: class path resource [ws-context.xml]; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [security-context.xml]; nested exception is java.io.FileNotFoundException: class path resource [security-context.xml] cannot be opened because it does not exist
        at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:70)
        at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
        at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:76)
        at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.importBeanDefinitionResource(DefaultBeanDefinitionDocumentReader.java:229)
        at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseDefaultElement(DefaultBeanDefinitionDocumentReader.java:180)
        at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:165)
        at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:138)
        at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:94)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:508)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:392)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:336)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
        at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsFromImportedResources(ConfigurationClassBeanDefinitionReader.java:346)
        at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:142)
        at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:116)
        at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:333)
        at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:243)
        at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:273)
        at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:98)
        at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:678)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:520)
        at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
        at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
        at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
        at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4853)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5314)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:753)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:729)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
        at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1129)
        at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1871)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [security-context.xml]; nested exception is java.io.FileNotFoundException: class path resource [security-context.xml] cannot be opened because it does not exist
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:344)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)
        at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.importBeanDefinitionResource(DefaultBeanDefinitionDocumentReader.java:223)
        ... 36 more
Caused by: java.io.FileNotFoundException: class path resource [security-context.xml] cannot be opened because it does not exist
</code>```

Here is the content of ws-context.xml file :

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"  xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
   http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
          http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<context:annotation-config />
<context:component-scan base-package="com.engie.aurora" />

<import resource="classpath:core-context.xml" />
<import resource="classpath:security-context.xml" />

<bean
    class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
     <property name="order" value="2" />
    <property name="ignoreUnresolvablePlaceholders" value="true" />
    <property name="locations">
        <list>
            <value>classpath:tech.properties</value>
            <value>classpath:application.properties</value>
        </list>
    </property>
</bean>

<bean id="log4jInitialization"
    class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetClass" value="org.springframework.util.Log4jConfigurer" />
    <property name="targetMethod" value="initLogging" />
    <property name="arguments">
        <list>
            <value>classpath:log4j.xml</value>
        </list>
    </property>
</bean>

<mvc:annotation-driven
    ignore-default-model-on-redirect="true">
    <mvc:message-converters>
        <bean
            class="org.springframework.http.converter.ResourceHttpMessageConverter" />

    </mvc:message-converters>
</mvc:annotation-driven>
</code>```

Here is the content of /opt/tomcat/conf/context.xml file:

```<code><?xml version='1.0' encoding='utf-8'?>

<Context>
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<WatchedResource>${CATALINA_BASE}/conf/web.xml</WatchedResource>

<Environment override="false" value="${CATALINA_BASE}/conf/myapp/"
type="java.lang.String" name="myappConfigDirectory" />

</Context>
</code>```

CATALINA_BASE is an environment variable with this value : /opt/tomcat

The security-context.xml file is located here : /opt/tomcat/conf/myapp/security-context.xml

The app is located here : /opt/tomcat/webapps/myapp.war

Could you please help me resolve this problem ?

答:
I have resolved the problem by coping the security-conext.yml file in the same location of ws-content.xml file.

Many thanks for your help.

Best regards,
Cao

Body:
I can not deploy my .war file on tomcat8.

Here is the logs in the localhost file log:

06-Dec-2017 11:18:22.001 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log Closing Spring root WebApplicationContext
06-Dec-2017 11:18:22.655 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log ContextListener: contextInitialized()
06-Dec-2017 11:18:22.655 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log SessionListener: contextInitialized()
06-Dec-2017 11:18:34.230 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log Spring WebApplicationInitializers detected on classpath: [org.glassfish.jersey.server.spring.SpringWebApplicationInitializer@5a8b94fb]
06-Dec-2017 11:18:34.350 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log Initializing Spring root WebApplicationContext
06-Dec-2017 11:18:36.864 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.listenerStart Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
 org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from URL location [classpath:security-context.xml]
Offending resource: class path resource [ws-context.xml]; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [security-context.xml]; nested exception is java.io.FileNotFoundException: class path resource [security-context.xml] cannot be opened because it does not exist
        at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:70)
        at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
        at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:76)
        at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.importBeanDefinitionResource(DefaultBeanDefinitionDocumentReader.java:229)
        at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseDefaultElement(DefaultBeanDefinitionDocumentReader.java:180)
        at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:165)
        at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:138)
        at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:94)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:508)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:392)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:336)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
        at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsFromImportedResources(ConfigurationClassBeanDefinitionReader.java:346)
        at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:142)
        at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:116)
        at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:333)
        at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:243)
        at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:273)
        at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:98)
        at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:678)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:520)
        at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
        at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
        at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
        at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4853)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5314)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:753)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:729)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
        at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1129)
        at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1871)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [security-context.xml]; nested exception is java.io.FileNotFoundException: class path resource [security-context.xml] cannot be opened because it does not exist
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:344)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)
        at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.importBeanDefinitionResource(DefaultBeanDefinitionDocumentReader.java:223)
        ... 36 more
Caused by: java.io.FileNotFoundException: class path resource [security-context.xml] cannot be opened because it does not exist

Here is the content of ws-context.xml file :

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"  xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
   http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
          http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<context:annotation-config />
<context:component-scan base-package="com.engie.aurora" />

<import resource="classpath:core-context.xml" />
<import resource="classpath:security-context.xml" />

<bean
    class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
     <property name="order" value="2" />
    <property name="ignoreUnresolvablePlaceholders" value="true" />
    <property name="locations">
        <list>
            <value>classpath:tech.properties</value>
            <value>classpath:application.properties</value>
        </list>
    </property>
</bean>

<bean id="log4jInitialization"
    class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetClass" value="org.springframework.util.Log4jConfigurer" />
    <property name="targetMethod" value="initLogging" />
    <property name="arguments">
        <list>
            <value>classpath:log4j.xml</value>
        </list>
    </property>
</bean>

<mvc:annotation-driven
    ignore-default-model-on-redirect="true">
    <mvc:message-converters>
        <bean
            class="org.springframework.http.converter.ResourceHttpMessageConverter" />

    </mvc:message-converters>
</mvc:annotation-driven>

Here is the content of /opt/tomcat/conf/context.xml file:

<?xml version='1.0' encoding='utf-8'?>

<Context>
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<WatchedResource>${CATALINA_BASE}/conf/web.xml</WatchedResource>

<Environment override="false" value="${CATALINA_BASE}/conf/myapp/"
type="java.lang.String" name="myappConfigDirectory" />

</Context>

CATALINA_BASE is an environment variable with this value : /opt/tomcat

The security-context.xml file is located here : /opt/tomcat/conf/myapp/security-context.xml

The app is located here : /opt/tomcat/webapps/myapp.war

Could you please help me resolve this problem ?


问:
sinon spy.calledOnce inside a promise returns false
I am trying to test that a function inside a stubbed promise was called. Unfortunately the spy on that function seems to be called only after the tests. Here is a simplified version of my React code.

```<code>export default class TheComponent extends React.Component {
  constructor(props) {
    super(props);
  }

  onSend(data) {
    AUtility.aPromise(data).then(() => {
      this.props.onSend(data);
      console.log("Props onSend was called!")
    });
  }

  render() {
    return null;
  }
}
</code>```

and here is the test I try to run.

```<code>it('should call the props function', (done) => {
    const onSendSpy = spy();
    const promiseStub = stub(AUtility, 'aPromise').resolves('mock string');
    wrapper = shallow(<TheComponent onSend={onSendSpy} />
    wrapper.instance().onSend();
    expect(promiseStub.calledOnce).to.be.true;  //this passes
    expect(onSendSpy.calledOnce) //this fails
    done();
});
</code>```

Whenever I run the test the first assertion passes but not the second. However the print statement in my code still prints the string during the test. It seems that the done() function will make the test finish once the promise returns and not once the then block is fully executed. How can I get this test to pass?

答:
I'm by no means an expert, but could you try wrapping the two expect statements in a setTimeout function?

setTimeout(() => {
    expect(promiseStub.calledOnce).to.be.true;
    expect(onSendSpy.calledOnce);
    done(); }, 0);

Body:
I am trying to test that a function inside a stubbed promise was called. Unfortunately the spy on that function seems to be called only after the tests. Here is a simplified version of my React code.

export default class TheComponent extends React.Component {
  constructor(props) {
    super(props);
  }

  onSend(data) {
    AUtility.aPromise(data).then(() => {
      this.props.onSend(data);
      console.log("Props onSend was called!")
    });
  }

  render() {
    return null;
  }
}

and here is the test I try to run.

it('should call the props function', (done) => {
    const onSendSpy = spy();
    const promiseStub = stub(AUtility, 'aPromise').resolves('mock string');
    wrapper = shallow(<TheComponent onSend={onSendSpy} />
    wrapper.instance().onSend();
    expect(promiseStub.calledOnce).to.be.true;  //this passes
    expect(onSendSpy.calledOnce) //this fails
    done();
});

Whenever I run the test the first assertion passes but not the second. However the print statement in my code still prints the string during the test. It seems that the done() function will make the test finish once the promise returns and not once the then block is fully executed. How can I get this test to pass?


问:
Create a mongoose record with a pre-generated id
I am trying to populate a collection with a manually generated id. I need this to make it easier on testers to provide feedback, as we do search records by ID [among other things].

I defined a const array with a few pre-defined keys, and the rest I would like to be generated by mongoose. Below is a fragment filling-up the database with sample data.

```<code>var col = db.collection('clients')
for (let i = 0; i < count; i++) {
  var client = createClientRecord()
  if (cifs.length > i) {
    client._id = cids[i]
  } else {
    client._id = new mongoose.Types.ObjectId
  }
  console.log('client._id:', client._id)
</code>```

This does not work I like want to. I get as many records as I have in the array. Having a mongoose generated ID does not work. Code just gets stuck there.

Also, I defined my schema as:

```<code>const clientSchema = new mongoose.Schema({
  id: {type: String, unique: true, required: true},
  email: { type: String, unique: true, required: true },
  birthName: String,
  ...
})
</code>```

Is this a valid option? Could I manually create unique id myself? Should it be id or _id?

Any ideas/suggestions?

答:
You don't need to generate IDs manually as it will be done by Mongoose automatically. You just need to define a schema - that's all. And please don't specify 'id' and '_id' fields in a schema. Everything will be handled by Mongoose.

As for the last question ('id' or '_id'), '_id' is a MongoDB id itself (Object ID), but 'id' is a stringified getter for '_id'.
'id' and '_id' look similar, but the difference in their types.
'id' is a string, '_id' is an object id, so we have the following condition. They are equal by value, but not by type.

Please note that you may set own ids, but by default it works like explained above.

Please follow this link:
http://mongoosejs.com/docs/guide.html#id

Body:
I am trying to populate a collection with a manually generated id. I need this to make it easier on testers to provide feedback, as we do search records by ID [among other things].

I defined a const array with a few pre-defined keys, and the rest I would like to be generated by mongoose. Below is a fragment filling-up the database with sample data.

var col = db.collection('clients')
for (let i = 0; i < count; i++) {
  var client = createClientRecord()
  if (cifs.length > i) {
    client._id = cids[i]
  } else {
    client._id = new mongoose.Types.ObjectId
  }
  console.log('client._id:', client._id)

This does not work I like want to. I get as many records as I have in the array. Having a mongoose generated ID does not work. Code just gets stuck there.

Also, I defined my schema as:

const clientSchema = new mongoose.Schema({
  id: {type: String, unique: true, required: true},
  email: { type: String, unique: true, required: true },
  birthName: String,
  ...
})

Is this a valid option? Could I manually create unique id myself? Should it be id or _id?

Any ideas/suggestions?


问:
whereBetween doesnt exist and i cant apply paginate
I've this method:

```<code>   public function indexGuest($idAzienda, Request $request){

    $companyId = $idAzienda;
    $ddts = Ddt::where('company_id',$companyId);
    $ddt_urls= Ddt_file_url::all();

    if($request->start_date || $request->end_date){
        $ddts->whereBetween('created_at',[new Carbon($request->start_date),new Carbon($request->end_date)]);
    }
    $ddts->paginate(10);

    return view('guest.ddt-management')->with('ddts', $ddts)->with('ddt_urls',$ddt_urls)
        ->with('companyId',$companyId);

}
</code>```

My start_date and end_date comes in strings like "yyyy-mm-dd".
I've tried to pass it straight to the query and like in the example like a carbon object with no hope!

After executing the query (now only the one without the wherebeeteween clause) i cant apply the method "paginate" to the collection, no error are raised but when i pass it to the view, the "link()" method not work and raise an error again.
where I wrong?

Laravel 5.4

答:
Structure your wheres like this.

```<code>public function indexGuest($idAzienda, Request $request) {
    [...]
    $ddts = Ddt::where('company_id', $companyId)
        ->where(function($query) use ($request) {
            if($s = $request->get("start_date") {
                 $s_date = Carbon::parse($s)->format("Y-m-d");
                 $query->whereDate("created_at", ">=", $s_date);
            }
            if($e = $request->get("end_date") {
                 $e_date = Carbon::parse($e)->format("Y-m-d");
                 $query->whereDate("created_at", "<=", $e_date);
            }
        })
        ->paginate(10);
    [...]
}
</code>```

Body:
I've this method:

   public function indexGuest($idAzienda, Request $request){

    $companyId = $idAzienda;
    $ddts = Ddt::where('company_id',$companyId);
    $ddt_urls= Ddt_file_url::all();

    if($request->start_date || $request->end_date){
        $ddts->whereBetween('created_at',[new Carbon($request->start_date),new Carbon($request->end_date)]);
    }
    $ddts->paginate(10);

    return view('guest.ddt-management')->with('ddts', $ddts)->with('ddt_urls',$ddt_urls)
        ->with('companyId',$companyId);

}

My start_date and end_date comes in strings like "yyyy-mm-dd".
I've tried to pass it straight to the query and like in the example like a carbon object with no hope!

After executing the query (now only the one without the wherebeeteween clause) i cant apply the method "paginate" to the collection, no error are raised but when i pass it to the view, the "link()" method not work and raise an error again.
where I wrong?

Laravel 5.4

Body:
Structure your wheres like this.

public function indexGuest($idAzienda, Request $request) {
    [...]
    $ddts = Ddt::where('company_id', $companyId)
        ->where(function($query) use ($request) {
            if($s = $request->get("start_date") {
                 $s_date = Carbon::parse($s)->format("Y-m-d");
                 $query->whereDate("created_at", ">=", $s_date);
            }
            if($e = $request->get("end_date") {
                 $e_date = Carbon::parse($e)->format("Y-m-d");
                 $query->whereDate("created_at", "<=", $e_date);
            }
        })
        ->paginate(10);
    [...]
}


问:
How to Add a specific number at the end of merging workbooks
I have an excel file that use to merge all the raw data's found in the same folder(Group 1, Group 2, ... Group 15, Group 16), using the code below :

```<code>Sub MergeFiles()
Dim Path, Filename As String, group As Long
group = 1
Path = "C:\Users\calin.lencar\Desktop\DT Project\Project Holiday Group Raw
Data\"
Filename = Dir(Path & "*.csv")

Do While Filename <> "" And Filename <> "Digital Tracking Panel KPIs v1"
  Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
  LastRow = Range("A65536").End(xlUp).Row
  Range("O2", Cells(LastRow, "O")).Value = group
  Range("A2:X" & Range("A65536").End(xlUp).Row).Copy

ThisWorkbook.Worksheets(21).Activate
  Range("A65536").End(xlUp).Offset(1, 0).PasteSpecial
  Application.CutCopyMode = False
  Workbooks(Filename).Close

Filename = Dir()
group = group + 1
Loop

MsgBox "Files have been copied successfully"
End Sub
</code>```

I am trying to add in the column "O:O" of each file the group number. The problem is that it opens them alphabetically: "Group 1, Group 10, Group 11... Group 2, Group 3..." but the group counter still goes : 1, 2, 3...

Could you please help me, I need the group counter to match the number in the file's name(maybe populate O:O with the first number it encounters?) or make excel open the files after explorer name.

Thank you in advance.

答: That's because Dir() just goes to the next alphabetical file in the directory. You could try putting a leading zero into the filenames like "Group 01, Group 02, ..."</p>

Body:
I have an excel file that use to merge all the raw data's found in the same folder(Group 1, Group 2, ... Group 15, Group 16), using the code below :

Sub MergeFiles()
Dim Path, Filename As String, group As Long
group = 1
Path = "C:\Users\calin.lencar\Desktop\DT Project\Project Holiday Group Raw
Data\"
Filename = Dir(Path & "*.csv")

Do While Filename <> "" And Filename <> "Digital Tracking Panel KPIs v1"
  Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
  LastRow = Range("A65536").End(xlUp).Row
  Range("O2", Cells(LastRow, "O")).Value = group
  Range("A2:X" & Range("A65536").End(xlUp).Row).Copy

ThisWorkbook.Worksheets(21).Activate
  Range("A65536").End(xlUp).Offset(1, 0).PasteSpecial
  Application.CutCopyMode = False
  Workbooks(Filename).Close

Filename = Dir()
group = group + 1
Loop

MsgBox "Files have been copied successfully"
End Sub

I am trying to add in the column "O:O" of each file the group number. The problem is that it opens them alphabetically: "Group 1, Group 10, Group 11... Group 2, Group 3..." but the group counter still goes : 1, 2, 3...

Could you please help me, I need the group counter to match the number in the file's name(maybe populate O:O with the first number it encounters?) or make excel open the files after explorer name.

Thank you in advance.


问:
OLEDB External table is not in the expected format / file in different format than extension
I am having a weird issue, I am retrieving an excel file (.xls) from a website then exposing the data as JSON, all is working file with dummy document until I started testing with real data, if I download the file and run my code before opening it in excel I get : "External table is not in the expected format.", when I open the file in excel excel gives me a warning that "the file is in a different format than specified by the extension" however if I save it with excel (2010) and select the option for keeping the same format and extension it works right after. the workaround I was thinking about is to automate excel to open and save the file after each download cycle, however I would love to find a real solution instead.
Code  : var pathToExcel = @"\source\repos\Rica2.0\reports\DataExport.xls";
            var sheetName = "Export";
            var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", pathToExcel);

答:
The problem is that web devs create an html file with a table and give it an xls extension rather than an html extension. They know that users file extensions associates will cause it to be open in Excel and Excel can parse html just fine. And other than that annoying message, it works.

One option is change the file extension to html after you download it. Excel will still open an html file and you'll avoid the message. And since you're doing this all programatically, you don't need the shell to work out what program to open via file associations.


问:
Walking filetree throws error even tho the files should exist
I am trying to walk through a zip file and print out all files, but for some reason, it throws a NoSuchFileException as soon as it goes into any subfolder.

```<code>    FileSystem fs = FileSystems.newFileSystem(Paths.get(folder.getRoot().getAbsolutePath(), "test.zip"), null);

    Files.walkFileTree(fs.getPath("/"), new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attr) {
            System.out.println(file);
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) {
            System.err.println(exc);
            return FileVisitResult.CONTINUE;
        }

    });
</code>```

How come it even wants to go there if they don't exist? Can anyone help me to solve this problem? The files should actually be there, at least they do when the test is executed by hand.

答:
If i execute this code it just works for me:

```<code>import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.util.zip.*;

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        try (ZipFile zipFile = new ZipFile("logs\\subfolder\\subsubfolder\\logs.zip")) {
            zipFile.stream()
               .map(ZipEntry::getName)
               .forEach(System.out::println);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

//         Path fs = FileSystems.getDefault().getPath("logs", "");
//
//         System.out.println(fs.toAbsolutePath());
//
//         SimpleFileVisitor<Path> sfv = new SimpleFileVisitor<Path>() {
//              @Override
//              public FileVisitResult visitFile(Path file, BasicFileAttributes attr) {
//                  System.out.println(file.toAbsolutePath());
//                  return FileVisitResult.CONTINUE;
//              }
//
//              @Override
//              public FileVisitResult visitFileFailed(Path file, IOException exc) {
//                  System.err.println(exc);
//                  return FileVisitResult.CONTINUE;
//              }
//
//          };
//
//         try {
//              Files.walkFileTree(fs, sfv);
//         } catch (IOException e) {
//             // TODO Auto-generated catch block
//             e.printStackTrace();
//         }

    }

}
</code>```

this is an image of the project directory structure in eclipse:

There is a file called access.log in the logs directory.

and this is my console output:

```<code>access.log
Microsoft Access Database (neu).accdb
Microsoft Excel-Arbeitsblatt (neu).xlsx
test/Microsoft Access Database (neu).accdb
test/Microsoft Excel-Arbeitsblatt (neu).xlsx
</code>```

All files that are in the Zip and its subfolder.

List .zip directories without extracting

Body:
I am trying to walk through a zip file and print out all files, but for some reason, it throws a NoSuchFileException as soon as it goes into any subfolder.

    FileSystem fs = FileSystems.newFileSystem(Paths.get(folder.getRoot().getAbsolutePath(), "test.zip"), null);

    Files.walkFileTree(fs.getPath("/"), new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attr) {
            System.out.println(file);
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) {
            System.err.println(exc);
            return FileVisitResult.CONTINUE;
        }

    });

How come it even wants to go there if they don't exist? Can anyone help me to solve this problem? The files should actually be there, at least they do when the test is executed by hand.

Body:
If i execute this code it just works for me:

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.util.zip.*;

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        try (ZipFile zipFile = new ZipFile("logs\\subfolder\\subsubfolder\\logs.zip")) {
            zipFile.stream()
               .map(ZipEntry::getName)
               .forEach(System.out::println);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

//         Path fs = FileSystems.getDefault().getPath("logs", "");
//
//         System.out.println(fs.toAbsolutePath());
//
//         SimpleFileVisitor<Path> sfv = new SimpleFileVisitor<Path>() {
//              @Override
//              public FileVisitResult visitFile(Path file, BasicFileAttributes attr) {
//                  System.out.println(file.toAbsolutePath());
//                  return FileVisitResult.CONTINUE;
//              }
//
//              @Override
//              public FileVisitResult visitFileFailed(Path file, IOException exc) {
//                  System.err.println(exc);
//                  return FileVisitResult.CONTINUE;
//              }
//
//          };
//
//         try {
//              Files.walkFileTree(fs, sfv);
//         } catch (IOException e) {
//             // TODO Auto-generated catch block
//             e.printStackTrace();
//         }

    }

}

this is an image of the project directory structure in eclipse:

There is a file called access.log in the logs directory.

and this is my console output:

access.log
Microsoft Access Database (neu).accdb
Microsoft Excel-Arbeitsblatt (neu).xlsx
test/Microsoft Access Database (neu).accdb
test/Microsoft Excel-Arbeitsblatt (neu).xlsx

All files that are in the Zip and its subfolder.

List .zip directories without extracting