问:
regexp for renaming multiple files using 'rename.pl'
I'm using rename.pl to rename a multiple files. I am having trouble coming up with the right regexp. My file names are of the form:

nn.some.title.string.ext

I want to change just the first '.' to ' - '. I thought this would work but it does not.

```<code>s/\.?/ - /
</code>```

Can someone help me out with this? TIA.

答:
Probably you will want to make sure that firs point is not the last. I mean if by any chance you will have nn_some_title_string.ext file name the script will not change a last dot.</p>

```<code>$fileName = "nn.some.title.string.ext";

$fileName =~s/\.(?=\w+\.\w+)/-/;

print "FileName: " . $fileName ."\n";
</code>```

Body:
I'm using rename.pl to rename a multiple files. I am having trouble coming up with the right regexp. My file names are of the form:

nn.some.title.string.ext

I want to change just the first '.' to ' - '. I thought this would work but it does not.

s/\.?/ - /

Can someone help me out with this? TIA.

Body:
Probably you will want to make sure that firs point is not the last. I mean if by any chance you will have nn_some_title_string.ext file name the script will not change a last dot.

$fileName = "nn.some.title.string.ext";

$fileName =~s/\.(?=\w+\.\w+)/-/;

print "FileName: " . $fileName ."\n";


来源: stackexchange

问:
Truncate NSDate (Zero-out time)
I want to generate a new NSDate with 0 hours, 0 minutes, and 0 seconds for time. The source date can be any random NSDate.

Is there a way to achieve this? The documentation did not help me with this.

Example

Have: 2010-10-30 10:14:13 GMT

Want: 2010-10-30 00:00:00 GMT

答:
With Swift 3, you can choose one of the four following patterns in order to solve your problem.

#1. Using Calendar startOfDay(for:)

startOfDay(for:) has the following declaration:

```<code>func startOfDay(for date: Date) -> Date
</code>```

Returns the first moment of a given Date, as a Date.

The Playground code below shows how to use this method:

```<code>import Foundation

let date = Date()

// Get new date
let calendar = Calendar.current
let newDate = calendar.startOfDay(for: date)

// Format dates
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_UK")
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .long

let formattedDate = dateFormatter.string(from: date)
let formattedNewDate = dateFormatter.string(from: newDate)

// Print formatted dates
print(formattedDate) // Prints: 30/03/2017, 15:14:41 CEST
print(formattedNewDate) // Prints: 30/03/2017, 00:00:00 CEST
</code>```

#2. Using Calendar date(bySettingHour:minute:second:of:matchingPolicy:repeatedTimePolicy:direction:)

date(bySettingHour:minute:second:of:matchingPolicy:repeatedTimePolicy:direction:) has the following declaration:

```<code>func date(bySettingHour hour: Int, minute: Int, second: Int, of date: Date, matchingPolicy: Calendar.MatchingPolicy = default, repeatedTimePolicy: Calendar.RepeatedTimePolicy = default, direction: Calendar.SearchDirection = default) -> Date?
</code>```

Returns a new Date representing the date calculated by setting hour, minute, and second to a given time on a specified Date.

The Playground code below shows how to use this method:

```<code>import Foundation

let date = Date()

// Get new date
let calendar = Calendar.current
let newDate = calendar.date(bySettingHour: 0, minute: 0, second: 0, of: date)

// Format dates
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_UK")
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .long

let formattedDate = dateFormatter.string(from: date)
let formattedNewDate = dateFormatter.string(from: newDate!)

// Print formatted dates
print(formattedDate) // Prints: 30/03/2017, 15:14:41 CEST
print(formattedNewDate) // Prints: 30/03/2017, 00:00:00 CEST
</code>```

#3. Using Calendar dateComponents(_:from:) and date(from:) methods

dateComponents(_:from:) has the following declaration:

```<code>func dateComponents(_ components: Set<Calendar.Component>, from date: Date) -> DateComponents
</code>```

Returns all the date components of a date, using the calendar time zone.

date(from:) has the following declaration:

```<code>func date(from components: DateComponents) -> Date?
</code>```

Returns a date created from the specified components.

The Playground code below shows how to use those methods:

```<code>import Foundation

let date = Date()

// Get new date
let calendar = Calendar.current
let components = calendar.dateComponents([.day, .month, .year], from: date)
let newDate = calendar.date(from: components)

// Format dates
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_UK")
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .long

let formattedDate = dateFormatter.string(from: date)
let formattedNewDate = dateFormatter.string(from: newDate!)

// Print formatted dates
print(formattedDate) // Prints: 30/03/2017, 15:14:41 CEST
print(formattedNewDate) // Prints: 30/03/2017, 00:00:00 CEST
</code>```

#4. Using NSCalendar range(of:start:interval:for:)

range(of:start:interval:for:) has the following declaration:

```<code>func range(of unit: NSCalendar.Unit, start datep: AutoreleasingUnsafeMutablePointer<NSDate?>?, interval tip: UnsafeMutablePointer<TimeInterval>?, for date: Date) -> Bool
</code>```

Returns by reference the starting time and duration of a given calendar unit that contains a given date.

The Playground code below shows how to use this method:

```<code>import Foundation

let date = Date()

// Get new date
let calendar = Calendar.current as NSCalendar
var newDate: NSDate?
calendar.range(of: .day, start: &newDate, interval: nil, for: date)

// Format dates
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_UK")
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .long

let formattedDate = dateFormatter.string(from: date)
let formattedNewDate = dateFormatter.string(from: newDate as! Date)

// Print formatted dates
print(formattedDate) // Prints: 30/03/2017, 15:14:41 CEST
print(formattedNewDate) // Prints: 30/03/2017, 00:00:00 CEST
</code>```

ContentLicense: CC BY-SA 3.0

Title: Truncate NSDate (Zero-out time)

Body:
With Swift 3, you can choose one of the four following patterns in order to solve your problem.

#1. Using Calendar startOfDay(for:)

startOfDay(for:) has the following declaration:

func startOfDay(for date: Date) -> Date

Returns the first moment of a given Date, as a Date.

The Playground code below shows how to use this method:

import Foundation

let date = Date()

// Get new date
let calendar = Calendar.current
let newDate = calendar.startOfDay(for: date)

// Format dates
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_UK")
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .long

let formattedDate = dateFormatter.string(from: date)
let formattedNewDate = dateFormatter.string(from: newDate)

// Print formatted dates
print(formattedDate) // Prints: 30/03/2017, 15:14:41 CEST
print(formattedNewDate) // Prints: 30/03/2017, 00:00:00 CEST

#2. Using Calendar date(bySettingHour:minute:second:of:matchingPolicy:repeatedTimePolicy:direction:)

date(bySettingHour:minute:second:of:matchingPolicy:repeatedTimePolicy:direction:) has the following declaration:

func date(bySettingHour hour: Int, minute: Int, second: Int, of date: Date, matchingPolicy: Calendar.MatchingPolicy = default, repeatedTimePolicy: Calendar.RepeatedTimePolicy = default, direction: Calendar.SearchDirection = default) -> Date?

Returns a new Date representing the date calculated by setting hour, minute, and second to a given time on a specified Date.

The Playground code below shows how to use this method:

import Foundation

let date = Date()

// Get new date
let calendar = Calendar.current
let newDate = calendar.date(bySettingHour: 0, minute: 0, second: 0, of: date)

// Format dates
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_UK")
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .long

let formattedDate = dateFormatter.string(from: date)
let formattedNewDate = dateFormatter.string(from: newDate!)

// Print formatted dates
print(formattedDate) // Prints: 30/03/2017, 15:14:41 CEST
print(formattedNewDate) // Prints: 30/03/2017, 00:00:00 CEST

#3. Using Calendar dateComponents(_:from:) and date(from:) methods

dateComponents(_:from:) has the following declaration:

func dateComponents(_ components: Set<Calendar.Component>, from date: Date) -> DateComponents

Returns all the date components of a date, using the calendar time zone.

date(from:) has the following declaration:

func date(from components: DateComponents) -> Date?

Returns a date created from the specified components.

The Playground code below shows how to use those methods:

import Foundation

let date = Date()

// Get new date
let calendar = Calendar.current
let components = calendar.dateComponents([.day, .month, .year], from: date)
let newDate = calendar.date(from: components)

// Format dates
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_UK")
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .long

let formattedDate = dateFormatter.string(from: date)
let formattedNewDate = dateFormatter.string(from: newDate!)

// Print formatted dates
print(formattedDate) // Prints: 30/03/2017, 15:14:41 CEST
print(formattedNewDate) // Prints: 30/03/2017, 00:00:00 CEST

#4. Using NSCalendar range(of:start:interval:for:)

range(of:start:interval:for:) has the following declaration:

func range(of unit: NSCalendar.Unit, start datep: AutoreleasingUnsafeMutablePointer<NSDate?>?, interval tip: UnsafeMutablePointer<TimeInterval>?, for date: Date) -> Bool

Returns by reference the starting time and duration of a given calendar unit that contains a given date.

The Playground code below shows how to use this method:

import Foundation

let date = Date()

// Get new date
let calendar = Calendar.current as NSCalendar
var newDate: NSDate?
calendar.range(of: .day, start: &newDate, interval: nil, for: date)

// Format dates
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_UK")
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .long

let formattedDate = dateFormatter.string(from: date)
let formattedNewDate = dateFormatter.string(from: newDate as! Date)

// Print formatted dates
print(formattedDate) // Prints: 30/03/2017, 15:14:41 CEST
print(formattedNewDate) // Prints: 30/03/2017, 00:00:00 CEST


问:
Reset atom editor file tree
I've tried looking but can't find a shortcut to reset the file tree in Atom editor. Is there a way to collapse all the files? I've tried right clicking and looking into the menu to no avail.</p>

答:
You can use Opt-click (Mac) or Alt-click (Win/Linux) to collapse or expand everything under a directory.

Be warned though, if your tree is at all large, especially if it encloses something with a lot of sub-items such as a .git directory, a library or template dir with a lot of files, it can be very slow, and it will block Atom UI until it is finished. YMMV.

Title: Reset atom editor file tree


问:
PHP - Dynamic Dropdown on Class value using JS
I have two dropdowns which full information from my SQL table. One dropdown consist of "Colors." The other dropdown consist of members in the specific colors. I already have them in the different optgroup based on their class value which is "color."

My goal is to have the user select "COLOR" and only the members in that class show up in the member dropdown.

Ex. I select Red on the first dropdown. Only members in "Red" will be available in the second dropdown.

Hopefully it can be down using JavaScript

SQL Table:

+-----------+--------------+
| GroupName | MemberName   |
+-----------+--------------+
| Red       | Joe Bob      |
| Red       | Catherine    |
| Blue      | Tommy        |
| Orange    | John Razks   |
| Black     | Trevor Smith |
+-----------+--------------+

+--------+
| Color  |
+--------+
| Red    |
| Blue   |
| Orange |
| Black  |
+--------+```
</div>
</div>
</p>

<p>PHP Code:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php
  $conn = mysqli_connect("#Connecting");
  if(!$conn){ die("Connection Failed".myslqi_connect_error()); }
  else{
    $color_result = mysqli_query($conn, "SELECT * from Color order by Color ASC");
    $colors = array();
    while ($row = mysqli_fetch_assoc($color_result)){ $colors[] = $row['Color']; }
    $member_result = mysqli_query($conn, "SELECT distinct MemberName,GroupName from Members order by MemberName ASC");
    $members = array();
    while ($row = mysqli_fetch_assoc($member_result)){
      if(!isset($members[$row['GroupName']])){ $members[$row['GroupName']] = array(); }
        $members[$row['GroupName']][] = $row; }
  }
?>
<form id=#blah>
Color:
<select id="committee" name="committee">
    <option value="">Select Color</option>
        <?php
            foreach($colors as $color){
              echo "<option value=\"".$color."\">".$color."</option>";
            }
         ?>
            </select>
        </div>

    <div class="sub_category_div" id="sub_category_div">
    Individual:
    <select name="senator" id="senator">
        <option value="">Select Individual</option>
        <?php
        foreach($members as $key => $member_group){
                echo "<optgroup class=\"".$key."\">";
                foreach($member_group as $val){
                    echo "<option value=\"".$val['MemberName']."\">".$val['MemberName']."</option>";
                }
                echo "</optgroup>";
        }
        ?>
    </select>
 </div>
  </form>

  <form id=#id>
  Color:
  <select id="committee" name="committee">
<option value="">Select Color</option>
        <?php
            foreach($colors as $color){
              echo "<option value=\"".$color."\">".$color."</option>";
            }
         ?>
            </select>
        </div>

    <div class="sub_category_div" id="sub_category_div">
    Individual:
    <select name="senator" id="senator">
        <option value="">Select Individual</option>
        <?php
        foreach($members as $key => $member_group){
                echo "<optgroup class=".$key.">";
                foreach($member_group as $val){
                    echo "<option value=\"".$val['ValueName']."\">".$val['MemberName']."</option>";
                }
                echo "</optgroup>";
        }
        ?>
    </select>
  </form></code>```

答:
What would work is to fill the values of an option with the members and read them out in a new select, but it's easier with an example:

HTML & PHP CODE

Of course you can still use your array, but I just like to do it with the "while($fetch = mysqli_fetch_assoc($query))" way. Also It surely doesn't look nice, but that's not part of the question ;)

```<code>// on the color select add this onchange
<select id="color" onchange="setOptions(this.value)">
<?php
  $color_result = mysqli_query($conn, "SELECT * from color ");
  while ($fetch_colors = mysqli_fetch_assoc($color_result)) {
    $color = $fetch_colors['color'];

    // This select is changed: WHERE GroupName='$color',
    // so it just reads the members of the current color
    $member_result = mysqli_query($conn, "SELECT distinct MemberName from Members  WHERE GroupName='$color' order by MemberName ASC");
    $memberstring = "";
    $i=1;
    $count_rows = mysqli_num_rows($member_result);
    // Here just an string gets filled which will be the value of the option
    while ($fetch_member = mysqli_fetch_assoc($member_result)) {
      if ($count_rows==$i) {
        $memberstring.=$fetch_member["MemberName"];
      } else {
        $memberstring.=$fetch_member["MemberName"].",";
        $i++;
      }
    }
    // This is the option with the color and with the value as members
    echo "<option value=\"$memberstring\">".$color."</option>";
  }

 ?>
</select>

<select id="members">
 // In here the options will show up
</select>
</code>```

JAVASCRIPT CODE

So this is a pretty much simplified version of the javascript. Meaning, it just runs on every change of the color option. If you want to have a "clear" option you will have to 1. insert it into the select (also add a special value) 2. write an if in the javascript function, to check if the option is clear.

```<code>function setOptions(val) {
  val = val.split(","); // val is now an array with all the members of the color
  document.getElementById('members').innerHTML = ""; // This clears all "old" members of the select
  var select = document.getElementById("members");

  for (var i = 0; i < val.length; i++) { // Now for each Member in the array a new Option is created
    var option = document.createElement("option");
    option.text = val[i];
    select.add(option);
  }
}
</code>```

More links:
javascript add option,
removing all options

If you have any questions, feel free to ask me in the comment section.

Body:
I have two dropdowns which full information from my SQL table. One dropdown consist of "Colors." The other dropdown consist of members in the specific colors. I already have them in the different optgroup based on their class value which is "color."

My goal is to have the user select "COLOR" and only the members in that class show up in the member dropdown.

Ex. I select Red on the first dropdown. Only members in "Red" will be available in the second dropdown.

Hopefully it can be down using JavaScript

SQL Table:

+-----------+--------------+
| GroupName | MemberName   |
+-----------+--------------+
| Red       | Joe Bob      |
| Red       | Catherine    |
| Blue      | Tommy        |
| Orange    | John Razks   |
| Black     | Trevor Smith |
+-----------+--------------+

+--------+
| Color  |
+--------+
| Red    |
| Blue   |
| Orange |
| Black  |
+--------+

PHP Code:

<?php
  $conn = mysqli_connect("#Connecting");
  if(!$conn){ die("Connection Failed".myslqi_connect_error()); }
  else{
    $color_result = mysqli_query($conn, "SELECT * from Color order by Color ASC");
    $colors = array();
    while ($row = mysqli_fetch_assoc($color_result)){ $colors[] = $row['Color']; }
    $member_result = mysqli_query($conn, "SELECT distinct MemberName,GroupName from Members order by MemberName ASC");
    $members = array();
    while ($row = mysqli_fetch_assoc($member_result)){
      if(!isset($members[$row['GroupName']])){ $members[$row['GroupName']] = array(); }
        $members[$row['GroupName']][] = $row; }
  }
?>
<form id=#blah>
Color:
<select id="committee" name="committee">
    <option value="">Select Color</option>
        <?php
            foreach($colors as $color){
              echo "<option value=\"".$color."\">".$color."</option>";
            }
         ?>
            </select>

    Individual:
    <select name="senator" id="senator">
        <option value="">Select Individual</option>
        <?php
        foreach($members as $key => $member_group){
                echo "<optgroup class=\"".$key."\">";
                foreach($member_group as $val){
                    echo "<option value=\"".$val['MemberName']."\">".$val['MemberName']."</option>";
                }
                echo "</optgroup>";
        }
        ?>
    </select>

  </form>

  <form id=#id>
  Color:
  <select id="committee" name="committee">
<option value="">Select Color</option>
        <?php
            foreach($colors as $color){
              echo "<option value=\"".$color."\">".$color."</option>";
            }
         ?>
            </select>

    Individual:
    <select name="senator" id="senator">
        <option value="">Select Individual</option>
        <?php
        foreach($members as $key => $member_group){
                echo "<optgroup class=".$key.">";
                foreach($member_group as $val){
                    echo "<option value=\"".$val['ValueName']."\">".$val['MemberName']."</option>";
                }
                echo "</optgroup>";
        }
        ?>
    </select>
  </form>

Body:
What would work is to fill the values of an option with the members and read them out in a new select, but it's easier with an example:

HTML & PHP CODE

Of course you can still use your array, but I just like to do it with the "while($fetch = mysqli_fetch_assoc($query))" way. Also It surely doesn't look nice, but that's not part of the question ;)

// on the color select add this onchange
<select id="color" onchange="setOptions(this.value)">
<?php
  $color_result = mysqli_query($conn, "SELECT * from color ");
  while ($fetch_colors = mysqli_fetch_assoc($color_result)) {
    $color = $fetch_colors['color'];

    // This select is changed: WHERE GroupName='$color',
    // so it just reads the members of the current color
    $member_result = mysqli_query($conn, "SELECT distinct MemberName from Members  WHERE GroupName='$color' order by MemberName ASC");
    $memberstring = "";
    $i=1;
    $count_rows = mysqli_num_rows($member_result);
    // Here just an string gets filled which will be the value of the option
    while ($fetch_member = mysqli_fetch_assoc($member_result)) {
      if ($count_rows==$i) {
        $memberstring.=$fetch_member["MemberName"];
      } else {
        $memberstring.=$fetch_member["MemberName"].",";
        $i++;
      }
    }
    // This is the option with the color and with the value as members
    echo "<option value=\"$memberstring\">".$color."</option>";
  }

 ?>
</select>

<select id="members">
 // In here the options will show up
</select>

JAVASCRIPT CODE

So this is a pretty much simplified version of the javascript. Meaning, it just runs on every change of the color option. If you want to have a "clear" option you will have to 1. insert it into the select (also add a special value) 2. write an if in the javascript function, to check if the option is clear.

function setOptions(val) {
  val = val.split(","); // val is now an array with all the members of the color
  document.getElementById('members').innerHTML = ""; // This clears all "old" members of the select
  var select = document.getElementById("members");

  for (var i = 0; i < val.length; i++) { // Now for each Member in the array a new Option is created
    var option = document.createElement("option");
    option.text = val[i];
    select.add(option);
  }
}

More links:
javascript add option,
removing all options

If you have any questions, feel free to ask me in the comment section.


问:
iOS : Open my App Specific Location Settings
I have a requirement to Open up my iOS App Specific Location Settings. I am aware that we can Open the General Location Settings through the below:

[[UIApplication sharedApplication] openURL:[NSURL
  URLWithString:@"prefs:root=LOCATION_SERVICES"]];*

I have two Questions:

Is the above valid and the right as per Apple guidelines (or) should we just Open up the Settings App and allow the user to change the settings?

My requirement is to open my App's Specific Location Settings - the one that shows "Always", "While Using App", "Never", so that the user can modify the same. Is this possible

Thanks in advance.

答:
This will take the user to the app specific settings screen where location, camera, notifications and any other permissions that were requested by the app are listed for the user to toggle.

```<code>[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
</code>```

Hope this helps.

Body:
This will take the user to the app specific settings screen where location, camera, notifications and any other permissions that were requested by the app are listed for the user to toggle.

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];

Hope this helps.


问:
Trying to separate code in a client server model where the client isn't trusted and with minimal duplication
I am working on a client/server game (C#.NET) where I do not want to trust the client to hold any of my server side application code, but want to share objects.

For example imagine you have a right hand weapon slot and a backpack that can carry additional items. Now there's a lot of server side code that will control which items can go in which slots and when you swing your right hand what happens. I don't want to put this code in my client for various reasons, but I am finding often times that if I generate a client side class and server side class for each of these that I see a lot of duplication in data and some duplication in methods. I also have to convert 1 class into the other.

Another example is For Items in the game. Item's have 'Use' abilities (like Use a key, or Use a torch) and properties like Name and Weight. So When I create the Item Class I would prefer to make 1 class like this:

```<code>Public Class Item
{

  int Weight;

  string Name;

  void Use() { //Do something interesting but not public to the client }

}
</code>```

Eventually copies of this object are serialized and sent to the client or server from each other as changes are made. If a Partial Class could span projects that would be very promising (to bad they don't). I don't think sub-classing feels right here (like ServerItem : Item) considering Serialization/Deserialization. I will play around some with Extension methods and see what implications there are for sub-classing but if anyone has any ideas or if I'm just missing something obvious please let me know.

答:
You really want to separate Data from Behaviour, and have just lightweight share-able data classes, and then (on the server) have server-centric classes that use data to determine behaviour. (try looking at a few design patters - maybe 'Decorator')

One lightweight example of what you may want is:

```<code> // lightweight data class thats shared
public class Item
{
    public int Weight { get; set;  }
    public string Name { get; set; }
}

// decorator pattern class that adds behaviour
public class ServerItem
{
    private Item item;
    public ServerItem(Item item)
    {
        this.item = item;
    }

    public void Use()
    {
        // do something with item;
    }
}

ServerItem currentServerItem = new ServerItem(currentItem);
</code>```

Body:
I am working on a client/server game (C#.NET) where I do not want to trust the client to hold any of my server side application code, but want to share objects.

For example imagine you have a right hand weapon slot and a backpack that can carry additional items. Now there's a lot of server side code that will control which items can go in which slots and when you swing your right hand what happens. I don't want to put this code in my client for various reasons, but I am finding often times that if I generate a client side class and server side class for each of these that I see a lot of duplication in data and some duplication in methods. I also have to convert 1 class into the other.

Another example is For Items in the game. Item's have 'Use' abilities (like Use a key, or Use a torch) and properties like Name and Weight. So When I create the Item Class I would prefer to make 1 class like this:

Public Class Item
{

  int Weight;

  string Name;

  void Use() { //Do something interesting but not public to the client }

}

Eventually copies of this object are serialized and sent to the client or server from each other as changes are made. If a Partial Class could span projects that would be very promising (to bad they don't). I don't think sub-classing feels right here (like ServerItem : Item) considering Serialization/Deserialization. I will play around some with Extension methods and see what implications there are for sub-classing but if anyone has any ideas or if I'm just missing something obvious please let me know.

Body:
You really want to separate Data from Behaviour, and have just lightweight share-able data classes, and then (on the server) have server-centric classes that use data to determine behaviour. (try looking at a few design patters - maybe 'Decorator')

One lightweight example of what you may want is:

 // lightweight data class thats shared
public class Item
{
    public int Weight { get; set;  }
    public string Name { get; set; }
}

// decorator pattern class that adds behaviour
public class ServerItem
{
    private Item item;
    public ServerItem(Item item)
    {
        this.item = item;
    }

    public void Use()
    {
        // do something with item;
    }
}

ServerItem currentServerItem = new ServerItem(currentItem);

ContentLicense: CC BY-SA 2.5


问:
CQRS + ES: Can you process multiple commands in parallel?
I can see how commands can be executed in a strict one at a time sequence with the CQRS + ES pattern. Having multiple commands executing in parallel would significantly increase the throughput of the system and make use of all the cores I have on the server. But surely this risks concurrency issues?

Take a simple example, two users update the customers name and submit the commands at the same time. In parallel two processes replay previous events to get aggregates into the latest state and then both determine everything is valid. Both then save a new update event. Whichever one saves last would seem to be the winner because any future replay would result in that last update being the customers name.

What if the result of the command is to send an email to the customer. Now we send two emails instead of the expected one. What if the command results in creating a new aggregate that gets attached to the customer using a customer property, we end up with two new aggregates created but one is a zombie because it is never referenced by the customer because the other aggregate has been saved as the reference instead.

It feels like you would need to implement your own transaction locking capability to ensure you never get overwrites and that is a complex solution I would rather avoid!

UPDATE:

My example was a little too simple. Imagine we have an Invoice and Item entries that go into an Invoice. After adding/changing/removing an Item from the Invoice we need to find the new total and set it into the Invoice.Total property field.

If in parallel two users both add a new Item then the total would be wrong with no explicit locking mechanism. Both recreate the Invoice aggregate and the existing list of Item child aggregates for that Invoice. In parallel both create a new Item and then add up the new total and set it to the Invoice.Total property.

Both then save events for these actions. But now we have an error because whichever command finished last will have a total that does not include the new item from the instance that finished first. This has nothing to do with pessimistic/optimistic concurrency but with transactional locking.

答:
This isn't really a cqrs issue at all; it's really specific to event storage, and a particular strategy of event storage.

Take a simple example, two users update the customers name and submit the commands at the same time. In parallel two processes replay previous events to get aggregates into the latest state and then both determine everything is valid. Both then save a new update event. Whichever one saves last would seem to be the winner because any future replay would result in that last update being the customers name.

There are a few things to notice here -- one is that the same issue exists if these commands are run sequentially; the second undoes the effects of the first. Which is exactly the behavior you would want in some cases; example fixing a spelling error.

Second, notice that, because you are just appending, both edits are preserved; the two changes both exist in the stream; it's the view (the fold), not the stream, that decides which of the two edits wins.

Which means, to a degree, you aren't done yet -- you still need to correctly model the strategy for choosing the "winner".

In cases where edits can conflict, then you need to take precautions against allowing a write that didn't acknowledge all of the previously accepted writes.  In that case, you don't want to append to a stream, but rather compare and swap.

Digression

Using a traditional database the action of writing and reading from records automatically handles the locking for you, it was the database does. Doing it in CQRS+ES is outside a database and so I would need to do it manually.

Part of your confusion, I believe, is that you are conflating appending events with updating history.  The literature is not clear on this point, so it may be valuable to review an alternative approach to maintaining a history.

Imagine, for a moment, that you preserve your state not as a stream of events, but as a document of events.  In the happy path, you load the document, modify your local copy, replace the previous copy with your revision.

In a concurrent write scenario, we have two writers that load the document, make different edits, and then each try to do the replace.  What happens?  If we don't do anything to mitigate concurrent writes, we probably end up with a last writer wins strategy -- corrupting our history by deleting the edits made by the previous writer.

To ensure that we don't lose writes, we need help from the document store.  Specifically, we want some analog of a conditional put (for instance, mongodb:findAndMofidy).  The second writer should get some flavor of ConcurrentModification response, which it can then mitigate (fail, retry, merge).

Nothing about this changes when we are doing event sourcing as she is spoke.

What does change is the nature of the thing that we "PUT"; because we are accepting the discipline that the representations of the events are immutable, and the collection of events is append only, we've restricted the valid edits of a document to a set that allows us to optimize away transferring the entire document every time.

If you like, you can imagine that we send to the event store a description of the changes we want to make to the document.  So the store loads a copy of the document, applies our changes to it, and then stores the updated version.

But the domain model didn't validate that the changes apply to an arbitrary version of the history document, but to a specific version of it.  So the message that we send to describe our changes needs to include a reference to the version of the document that we started from.

You can imagine that the "event store" is a linked list in memory.  "Append" is analogous to updating the document without ensuring that it is unchanged from what you verified.  If we need to make sure that our assumptions are still valid (ie, optimistic concurrency), then we need to compare-and-swap the tail pointer; if a  race has allowed some other writer to update the tail since our read, then the CAS operation should fail, and allows us to recover.

A remote event store needs to offer an analogous interface: see the use of expectedVersion in GetEventStore.

You may find it valuable to review Udi Dahan's writings on collaborative domains.

It feels like you would need to implement your own transaction locking capability to ensure you never get overwrites and that is a complex solution I would rather avoid!

You should keep in mind that you signed on for some sort of locking when you decided to use parallel writers!  Doing the work to control how to maintain data integrity is part of the trade off you signed onto.

The good news, is that you don't need implement a transaction locking strategy; you need to choose a data store that provides a transaction locking strategy.

Compare and swap really isn't all that complex, it's just complicated.

Both then save events for these actions. But now we have an error because whichever command finished last will have a total that does not include the new item from the instance that finished first. This has nothing to do with pessimistic/optimistic concurrency but with transactional locking.

Right -- you can't blindly append to a stream where you are expecting an invariant to hold.  You have to make sure you are appending to the location that you have checked.

There's an alternative design that you may see from time to time, that treats the history as a graph, rather than as a stream.  So each write potentially forks the history, and you merge later if necessary.  You can get a sense for how that might work reviewing Kleppmann's work on CRDTs

My reading tells me that event graphs are still firmly in the complex quadrant.

ContentLicense: CC BY-SA 4.0


问:
Microsoft Access cannot add records join key of table not in recordset
I know this is a repost, I have done my research on everything possible and I couldn't find anything to assist nor help me with my current problem. No matter how many times I re-create my Query or Form, I just can't seem to get it to work correctly. if I run my Query, I will get the correct information displayed, but when it comes to adding information through a custom form I made, I get this error -> "cannot add records join key of table not in recordset".

My current Query, incase you wanted to see. I only access vendorNoID from the vendor table. I require all the information from the rest of the tables.

I am able to enter information in this form for tbl_address and tbl_addressType, but I get the error for vendor / purchaseOrder. Any reason whats causing this?!?!

Any advice will be greatly appreciated

答:
The selected value of the vendor combobox got to be bound to [tbl_purchase_order].[vendorID]. To the table, where the selected value is the foreign key. (@VMai)

In my opinion, open the Query Builder of Form (as picture below), then add column [tbl_purchase_order].[vendorID]

/

Cause I don't have enought reputation for write comment, so I write down here.
Hope it help ! ^^


问:
IIB: Passing local variable to ESQL select statement
I need to retrieve datas from two tables based on the Job code which is given in the input xml in IIB/WMB.

SQL Query

```<code>SELECT D.DEPTNO,D.DNAME,D.LOC,E.EMPNO,E.ENAME,E.JOB,E.SAL FROM DEPT D JOIN EMP E on E.JOB ='MANAGER' OR E.JOB = 'CLERK'
</code>```

ESQL Query

Getting the JOB details from input xml and assigning it to local variable.

```<code>SET type1 = InputRoot.XMLNSC.Employee.Type[1];
SET type2 = InputRoot.XMLNSC.Employee.Type[2];
</code>```

Now I need to pass the above variables to my ESQL query.

```<code>SET Outputroot.XMLNSC.List[] = PASSTHRU('SELECT D.DEPTNO,D.DNAME,D.LOC,E.EMPNO,E.ENAME,E.JOB,E.SAL FROM Database.EMP AS E,Database.DEPT AS D where E.JOB =?' VALUES('type1','type2')) ;
</code>```

But the above query is not working.

答:
There are two problems in this query:

First, you are passing two parameters but only one question mark (?) exists in the query.

Second, you are passing a string value like 'type1' and the correct is to pass the variable:

```<code>SET Outputroot.XMLNSC.List[] = PASSTHRU('SELECT D.DEPTNO,D.DNAME,D.LOC,E.EMPNO,E.ENAME,E.JOB,E.SAL FROM Database.EMP AS E,Database.DEPT AS D where E.JOB =?' VALUES(type1)) ;
</code>```

Body:
I need to retrieve datas from two tables based on the Job code which is given in the input xml in IIB/WMB.

SQL Query

SELECT D.DEPTNO,D.DNAME,D.LOC,E.EMPNO,E.ENAME,E.JOB,E.SAL FROM DEPT D JOIN EMP E on E.JOB ='MANAGER' OR E.JOB = 'CLERK'

ESQL Query

Getting the JOB details from input xml and assigning it to local variable.

SET type1 = InputRoot.XMLNSC.Employee.Type[1];
SET type2 = InputRoot.XMLNSC.Employee.Type[2];

Now I need to pass the above variables to my ESQL query.

SET Outputroot.XMLNSC.List[] = PASSTHRU('SELECT D.DEPTNO,D.DNAME,D.LOC,E.EMPNO,E.ENAME,E.JOB,E.SAL FROM Database.EMP AS E,Database.DEPT AS D where E.JOB =?' VALUES('type1','type2')) ;

But the above query is not working.

Body:
There are two problems in this query:

First, you are passing two parameters but only one question mark (?) exists in the query.

Second, you are passing a string value like 'type1' and the correct is to pass the variable:

SET Outputroot.XMLNSC.List[] = PASSTHRU('SELECT D.DEPTNO,D.DNAME,D.LOC,E.EMPNO,E.ENAME,E.JOB,E.SAL FROM Database.EMP AS E,Database.DEPT AS D where E.JOB =?' VALUES(type1)) ;


问:
Creating new columns in pandas based on conditions satisfied by the columns using functions
I have several columns in a pandas data frame. Based on each one of the columns, I need to create a new column. This function works:

```<code>def f(row):
    if row['col_1'] == 0:
        val = 'Neutral'
    elif row['col_1'] > 0:
        val = 'Growth'
    else:
        val = 'Contraction'
    return val

df['New_Col_1'] = df.apply(f(row) , axis=1)
</code>```

But since I have several columns for comparison (col_2, col_3 etc), I want to pass the name of the column as a parameter in the function.

```<code>def f(row,col_name):
    if row[col_name] == 0:
        val = 'Neutral'
    elif row[col_name] > 0:
        val = 'Growth'
    else:
        val = 'Contraction'
    return val

df['New_Col_1'] = df.apply(f(row,'col_1') , axis=1)
</code>```

But, there is an error. It says parameter 'row' is not defined. How do I overcome this?

答:
The df.apply() is missing a lambda function as mentioned in a comment.</p>

```<code>def f(row,col_name):
    if row[col_name] == 0:
        val = 'Neutral'
    elif row[col_name] > 0:
        val = 'Growth'
    else:
        val = 'Contraction'
    return val

df['New_Col_1'] = df.apply(lambda row: f(row,'col_1') , axis=1)
</code>```

Body:
I have several columns in a pandas data frame. Based on each one of the columns, I need to create a new column. This function works:

def f(row):
    if row['col_1'] == 0:
        val = 'Neutral'
    elif row['col_1'] > 0:
        val = 'Growth'
    else:
        val = 'Contraction'
    return val

df['New_Col_1'] = df.apply(f(row) , axis=1)

But since I have several columns for comparison (col_2, col_3 etc), I want to pass the name of the column as a parameter in the function.

def f(row,col_name):
    if row[col_name] == 0:
        val = 'Neutral'
    elif row[col_name] > 0:
        val = 'Growth'
    else:
        val = 'Contraction'
    return val

df['New_Col_1'] = df.apply(f(row,'col_1') , axis=1)

But, there is an error. It says parameter 'row' is not defined. How do I overcome this?

Body:
The df.apply() is missing a lambda function as mentioned in a comment.

def f(row,col_name):
    if row[col_name] == 0:
        val = 'Neutral'
    elif row[col_name] > 0:
        val = 'Growth'
    else:
        val = 'Contraction'
    return val

df['New_Col_1'] = df.apply(lambda row: f(row,'col_1') , axis=1)


问:
What is the reason behind 76 characters being the length limit for MIME sections for Emails (RFC 2045)?
RFC 2045 defines the maxmimum line length for encoded data as 76. However, I cannot find any explanation as to why it is 76. Is this number entirely arbitrary, or is there some reasoning behind it?</p>

答:
Actually the original RFC 822 defines a limit at 72 characters and the culprit is a teletype, which was a standard output device with the early computers.

You can also "thank" teletype devices for the line terminator in emails (and Windows) being 2 characters, which are CR (Carriage Return) and LF (Line Feed).

It was essential to transmit this sequence at the end of each line in order for a teletype to move a caret to position 0 and advance paper one tick up.

By the time RFC 2822 obsoleted the original, nobody was using teletypes to render emails, so it was relaxed a bit in order to fit into a default TTY monitor device.


问:
How to calculate rolling correlation coefficient in a groupby?
Given a DataFrame how would one calculate the rolling correlation coefficient of a particular column for N periods(5), while in a groupby?

My Attempts, I feel like i'm close, but missing something simple..

Using Corr

```<code>df['cor'] = df.groupby('DIMENSION').val1.apply(lambda x: x.rolling(window=5).corr())
</code>```

Using Another Stack Overflow Suggestion

```<code>df['cor'] = df.groupby('DIMENSION').val1.apply(lambda x: x.rolling(window=5).corr()[df'val1']df['index'])
</code>```

Trying corrwith defaults

```<code>df['cor'] = df.groupby('DIEMNSION').val1.apply(lambda x: x.rolling(window=5).corrwith())
</code>```

DataFrame:

```<code>Dimension,Val1,Index
A,15677,0
A,19191,1
A,19961,2
A,10004,3
A,17899,4
A,10933,5
A,12953,6
A,19431,7
A,17637,8
A,13310,9
A,10113,10
A,19108,11
A,17169,12
A,13859,13
A,11466,14
A,13673,15
A,15049,16
B,14996,17
B,17679,18
B,12944,19
C,19927,20
C,10659,21
C,14561,22
C,18842,23
C,13784,24
C,14562,25
C,10145,26
</code>```

答:
Let's try this:</p>

```<code>def mytrans(x):
    return pd.DataFrame(x['Val1'].rolling(window=5).corr(x['Index']))

df['corr'] = df.groupby('Dimension')[['Val1','Index']].apply(mytrans)

df
</code>```

Body:
Given a DataFrame how would one calculate the rolling correlation coefficient of a particular column for N periods(5), while in a groupby?

My Attempts, I feel like i'm close, but missing something simple..

Using Corr

df['cor'] = df.groupby('DIMENSION').val1.apply(lambda x: x.rolling(window=5).corr())

Using Another Stack Overflow Suggestion

df['cor'] = df.groupby('DIMENSION').val1.apply(lambda x: x.rolling(window=5).corr()[df'val1']df['index'])

Trying corrwith defaults

df['cor'] = df.groupby('DIEMNSION').val1.apply(lambda x: x.rolling(window=5).corrwith())

DataFrame:

Dimension,Val1,Index
A,15677,0
A,19191,1
A,19961,2
A,10004,3
A,17899,4
A,10933,5
A,12953,6
A,19431,7
A,17637,8
A,13310,9
A,10113,10
A,19108,11
A,17169,12
A,13859,13
A,11466,14
A,13673,15
A,15049,16
B,14996,17
B,17679,18
B,12944,19
C,19927,20
C,10659,21
C,14561,22
C,18842,23
C,13784,24
C,14562,25
C,10145,26

Body:
Let's try this:

def mytrans(x):
    return pd.DataFrame(x['Val1'].rolling(window=5).corr(x['Index']))

df['corr'] = df.groupby('Dimension')[['Val1','Index']].apply(mytrans)

df


问:
Silverlight 4 Hosting Requirement
I would like to know if what are the technical specification both hardware and software (windows OS, IIS and the like) of a server to be able to host a silverlight 4 / .net 4 / wcf web service application.

Thank you

答:
You can host a Silverlight in any Html file. All you need is to use the embed-tag.

There is nothing stopping you from hosting Silverlight on Apache running PHP if you want to, but naturally the default is to host it on IIS.

Look at this reply to a related question for an example: embedding silverlight, anything like flash?

Edit:
I see that you changed your question, so this question may belong on another forum. Any computer able to run IIS will be able to host what you ask for. You will probably go for a server running Windows Server 2008, but the hardware specs depend on what your needs are. You should probably aim low first and add more power as you need it.

You may also be interested in using a cloud-based service like Microsofts Azure. It is perfect for hosting an application like yours and it is more or less infinitely scalable.

Title: Silverlight 4 Hosting Requirement


问:
check if progressbar animation is done android
I need to check when the progressbar animation is done.

Then i need to do something.

I already have this:

```<code>private ObjectAnimator progressAnimator;

mProgressBar = (ProgressBar)findViewById(R.id.progressbar);
mProgressBar.setMax(1000);
progressAnimator = ObjectAnimator.ofInt(mProgressBar, "progress", 1000, 0);
progressAnimator.setDuration(10000);
progressAnimator.start();
</code>```

How to check if this animation is done??

答:
You can use:</p>

```<code>if(progressAnimator.isRunning()){
    //Code here
}
</code>```

Body:
I need to check when the progressbar animation is done.

Then i need to do something.

I already have this:

private ObjectAnimator progressAnimator;

mProgressBar = (ProgressBar)findViewById(R.id.progressbar);
mProgressBar.setMax(1000);
progressAnimator = ObjectAnimator.ofInt(mProgressBar, "progress", 1000, 0);
progressAnimator.setDuration(10000);
progressAnimator.start();

How to check if this animation is done??

Body:
You can use:

if(progressAnimator.isRunning()){
    //Code here
}


问:
Receive the position of my viewpager in my main form
I use a viewpager like carousel that contains three images, so I want to get the position that each one is 1, 2, 3 and show me as a message

Example: if I drag to the second it returns me 2, if I move to 3 it returns me 3

```<code>// my form
 ImageAdapter adapter = new ImageAdapter(this);
 var viewPager = FindViewById<ViewPager>(Resource.Id.viewPager);
 viewPager.PersistentDrawingCache = Android.Views.PersistentDrawingCaches.ScrollingCache;
 viewPager.Adapter = adapter;
</code>```

And this is my class:

```<code>   public class ImageAdapter : PagerAdapter
   {
    private Context context;
    private string[] imageList = {
        "image1",
         "image2",
          "image3",};

    public ImageAdapter(Context context)
    {
        this.context = context;
    }

    public override int Count
    {
        get
        {
            return imageList.Length;
        }
    }

    public override bool IsViewFromObject(View view, Java.Lang.Object objectValue)
    {
        return view == ((ImageView)objectValue);
    }

    public override Java.Lang.Object InstantiateItem(View container, int position)
    {
        ImageView imageView = new ImageView(context);
        imageView.SetScaleType(ImageView.ScaleType.CenterCrop);
        Koush.UrlImageViewHelper.SetUrlDrawable(imageView, imageList[position]);
        ((ViewPager)container).AddView(imageView, 0);
        return imageView;
    }

    public override void DestroyItem(View container, int position, Java.Lang.Object objectValue)
    {
        ((ViewPager)container).RemoveView((ImageView)objectValue);
    }
}
</code>```

答:
```<code>viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
        @Override
        public void onPageSelected(int position) {
            super.onPageSelected(position);
            System.out.println("position = " + position);
        }
    });
</code>```

Body:
I use a viewpager like carousel that contains three images, so I want to get the position that each one is 1, 2, 3 and show me as a message

Example: if I drag to the second it returns me 2, if I move to 3 it returns me 3

// my form
 ImageAdapter adapter = new ImageAdapter(this);
 var viewPager = FindViewById<ViewPager>(Resource.Id.viewPager);
 viewPager.PersistentDrawingCache = Android.Views.PersistentDrawingCaches.ScrollingCache;
 viewPager.Adapter = adapter;

And this is my class:

   public class ImageAdapter : PagerAdapter
   {
    private Context context;
    private string[] imageList = {
        "image1",
         "image2",
          "image3",};

    public ImageAdapter(Context context)
    {
        this.context = context;
    }

    public override int Count
    {
        get
        {
            return imageList.Length;
        }
    }

    public override bool IsViewFromObject(View view, Java.Lang.Object objectValue)
    {
        return view == ((ImageView)objectValue);
    }

    public override Java.Lang.Object InstantiateItem(View container, int position)
    {
        ImageView imageView = new ImageView(context);
        imageView.SetScaleType(ImageView.ScaleType.CenterCrop);
        Koush.UrlImageViewHelper.SetUrlDrawable(imageView, imageList[position]);
        ((ViewPager)container).AddView(imageView, 0);
        return imageView;
    }

    public override void DestroyItem(View container, int position, Java.Lang.Object objectValue)
    {
        ((ViewPager)container).RemoveView((ImageView)objectValue);
    }
}


问:
Rebuild or regenerate 'ic_launcher.png' from images in Android Studio
When one first creates a new project, that dialog lets you point
to some external .PNG file, and then when that dialog completes,
it generates 4 different pixel-sizes of images for use as
a launcher-icon.

My question is:  So, if one already has an existing project
created, is there someplace to tell the Studio to re-generate
4 NEW such files, by just re-pointing it elsewhere, to some
other .PNG?

It occurred to me that I could start a new project and then
manually copy all the other files developed so far, such as
the .JAVA and .XML files, etc, but that seems like a lot of
work (that I hope won't be necessary).

答:
You can create an icon using this website https://romannurik.github.io/AndroidAssetStudio/index.html.

Download the icon, go to File Explorer - where your projects are saved, the default path is C:\Users\Your Name\AndroidStudioProjects\Project Name\app\src\main\res\

and copy the folders you downloaded to the res folder.


问:
Using connect-history-api-fallback middleware in FeathersJS for serving Vue.js SPA
As the title suggests, I'm serving a Vue.js single page application from public/index.html in FeathersJS. Since I'm using vue-router's HTML5 history mode, I have to use a middleware like connect-history-api-fallback in order to rewrite the requested frontend location to /index.html.

Setting up this middleware in src/middleware just before app.use(notFound()); doesn't work since Feathers serves the static files before everything else, so by the time the request gets rewritten nothing picks up /index.html and notFound serves a 404 response.

Configuring it before .use('/', serveStatic(app.get('public'))) inside src/app.js is also problematic since it will rewrite every service request to /index.html, making API calls unreachable.

I ended up moving the serveStatic middleware after .configure(services) and placing connect-history-api-fallback right above like so:

```<code>app.use(compress())
  .options('*', cors())
  .use(cors())
  // favicon and serveStatic used to be here
  .use(bodyParser.json())
  .use(bodyParser.urlencoded({ extended: true }))
  .configure(hooks())
  .configure(rest())
  .configure(socketio())
  .configure(services)
  .use(require('connect-history-api-fallback')())
  // now they are down here
  .use(favicon(path.join(app.get('public'), 'favicon.ico')))
  .use('/', serveStatic(app.get('public')))
  .configure(middleware);
</code>```

My question is the following: Are there any performance or security drawbacks to this approach?

答:
With the configuration you posted, there aren't really any security concerns.

If you were to replace your serveStatic middleware with SSR middleware, you would want to delete the CORS headers before the SSR middleware to avoid leaking data through Cross Site Requests (CSRF "attacks" using cookies).

Body:
As the title suggests, I'm serving a Vue.js single page application from public/index.html in FeathersJS. Since I'm using vue-router's HTML5 history mode, I have to use a middleware like connect-history-api-fallback in order to rewrite the requested frontend location to /index.html.

Setting up this middleware in src/middleware just before app.use(notFound()); doesn't work since Feathers serves the static files before everything else, so by the time the request gets rewritten nothing picks up /index.html and notFound serves a 404 response.

Configuring it before .use('/', serveStatic(app.get('public'))) inside src/app.js is also problematic since it will rewrite every service request to /index.html, making API calls unreachable.

I ended up moving the serveStatic middleware after .configure(services) and placing connect-history-api-fallback right above like so:

app.use(compress())
  .options('*', cors())
  .use(cors())
  // favicon and serveStatic used to be here
  .use(bodyParser.json())
  .use(bodyParser.urlencoded({ extended: true }))
  .configure(hooks())
  .configure(rest())
  .configure(socketio())
  .configure(services)
  .use(require('connect-history-api-fallback')())
  // now they are down here
  .use(favicon(path.join(app.get('public'), 'favicon.ico')))
  .use('/', serveStatic(app.get('public')))
  .configure(middleware);

My question is the following: Are there any performance or security drawbacks to this approach?


问:
how can i add in highcharts a different dashStyle just for a part of the graph
At the last two days i want to indicate that i am missing some data, and i'd want it to show a straight dashed line on the same graph. can i change the dashStyle only for parts of the graph?

答:
You can apply 'zones' to a series: http://api.highcharts.com/highcharts/plotOptions.series.zones
Just use the dashStyle option like in this example http://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/series/color-zones-dashstyle-dot/</p>

```<code> zones: [{
        value: 8
    }, {
        dashStyle: 'dot'
    }]
</code>```

Body:
You can apply 'zones' to a series: http://api.highcharts.com/highcharts/plotOptions.series.zones
Just use the dashStyle option like in this example http://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/series/color-zones-dashstyle-dot/

 zones: [{
        value: 8
    }, {
        dashStyle: 'dot'
    }]


问:
Replacing certain characters while allowing unicode (PHP)
So I got a search box in a site we're developing that will search in a database with both English and Greek product strings. I'm trying to clear the text input from all kinds of special characters like: / . , ' ] [ % & _ etc. and replace them with a space or totally delete them. Even double instances of them should be deleted, like ^^, &&, [[ etc.

I have been messing around with preg_replace but can't find a solution...

Thanks in advance.

答:
Why not make an array and use str_replace?

```<code>$unallowedChars = array("^", "&", "/", "."); // more for your choosing

$searchContent = str_replace($unallowedChars, "", $searchContent);
</code>```

Replaces all values of the array with "", in otherwords nothing.

Body:
Why not make an array and use str_replace?

$unallowedChars = array("^", "&", "/", "."); // more for your choosing

$searchContent = str_replace($unallowedChars, "", $searchContent);

Replaces all values of the array with "", in otherwords nothing.


问:
How to edit list in C#
I would like to have an edit function in my program. I am creating a phone book wherein I use list in saving data (no database yet). I would like to have an edit function whenever i click an item in the list but I do not know how to do it.

This is my code for adding:

```<code>Person contact = new Person();
private ObservableCollection<Person> person = new ObservableCollection<Person>();
person.Add(new Person()
    {
        Name = contact.Name,
        Contact = contact.Contact,
        ImagePath = contact.ImagePath,
        Gender = contact.Gender
    });
</code>```

I used selection changed when determining the selected item in the list. A help would be greatly appreciated. Thanks!

答:
You could use a DataGrid control to display and edit a collection of objects: https://msdn.microsoft.com/en-us/library/system.windows.controls.datagrid(v=vs.110).aspx

Set the ItemsSource property of the DataGrid to your ObservableCollection<Person> and double click in a cell to edit a value of a property of a Person object:

```<code>private ObservableCollection<Person> person = new ObservableCollection<Person>();
...
dataGrid.ItemsSource = person;
</code>```

```<code><DataGrid x:Name="dataGrid" />
</code>```

Title: How to edit list in C#

Body:
I would like to have an edit function in my program. I am creating a phone book wherein I use list in saving data (no database yet). I would like to have an edit function whenever i click an item in the list but I do not know how to do it.

This is my code for adding:

Person contact = new Person();
private ObservableCollection<Person> person = new ObservableCollection<Person>();
person.Add(new Person()
    {
        Name = contact.Name,
        Contact = contact.Contact,
        ImagePath = contact.ImagePath,
        Gender = contact.Gender
    });

I used selection changed when determining the selected item in the list. A help would be greatly appreciated. Thanks!

Body:
You could use a DataGrid control to display and edit a collection of objects: https://msdn.microsoft.com/en-us/library/system.windows.controls.datagrid(v=vs.110).aspx

Set the ItemsSource property of the DataGrid to your ObservableCollection<Person> and double click in a cell to edit a value of a property of a Person object:

private ObservableCollection<Person> person = new ObservableCollection<Person>();
...
dataGrid.ItemsSource = person;

<DataGrid x:Name="dataGrid" />


问:
Tell When a UIPageViewController is Scrolling (for Parallax Scrolling of an Image)
I am trying to make an effect similar to that found in the new Yahoo weather app. Basically, each page in the UIPageViewController has a background image, and when scrolling through the page view, the Image's location only scrolls about half the speed. How would I do that? I thought I could use some sort of Delegate Method in the UIPageViewController to get the current offset and then update the images like that. The only problem is that I cannot find anyway to tell if the UIPageViewController is being scrolled! Is there a method for that? Thanks!

答:
In Swift 3 you could write it even shorter: </p>

```<code>if let scrollView = self.pageViewController.view.subviews.first(where: { $0 is UIScrollView }) as? UIScrollView {
    scrollView.delegate = self
}
</code>```

Body:
In Swift 3 you could write it even shorter:

if let scrollView = self.pageViewController.view.subviews.first(where: { $0 is UIScrollView }) as? UIScrollView {
    scrollView.delegate = self
}


问:
Existing name code (java)
I have problem with my school assignment (java code) i would like an warrning message with name that it is already exsits! everything is working fine but i just want to add a code in the brackets.</p>

```<code> public void add (Wapen index)
    {
        if (wapen.contains(index)){
            wapen.add(index);
            System.out.println(" message");

    }else {
        System.out.println("message ");

    }
}
</code>```

答:
Override toString and equals in the SuperWapen class.

```<code>class SuperWapen {
    private String superwapenName;

    @Override
    public String toString() {
        return superwapenName;
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof SuperWapen) {
            return ((SuperWapen)o).superwapenName.equals(superwapenName);
        }
        else {
            return false;
        }
    }
}
</code>```

Then just do:

```<code>public void addWapen (SuperWapen index)
    {
        if (!wapen.contains(index)){
            wapen.add(index);
            System.out.println(" Superwapen is registered for superhero");
        } else {
            System.out.println("Superhero has this superwapen with the name: " + index);
        }
    }
</code>```

Title: Existing name code (java)

Body:
I have problem with my school assignment (java code) i would like an warrning message with name that it is already exsits! everything is working fine but i just want to add a code in the brackets.

 public void add (Wapen index)
    {
        if (wapen.contains(index)){
            wapen.add(index);
            System.out.println(" message");

    }else {
        System.out.println("message ");

    }
}

Body:
Override toString and equals in the SuperWapen class.

class SuperWapen {
    private String superwapenName;

    @Override
    public String toString() {
        return superwapenName;
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof SuperWapen) {
            return ((SuperWapen)o).superwapenName.equals(superwapenName);
        }
        else {
            return false;
        }
    }
}

Then just do:

public void addWapen (SuperWapen index)
    {
        if (!wapen.contains(index)){
            wapen.add(index);
            System.out.println(" Superwapen is registered for superhero");
        } else {
            System.out.println("Superhero has this superwapen with the name: " + index);
        }
    }


问:
Rails View DRYness - Do you set variables in the view or just make clean methods?
I have a view in which I have the same link 3 times (actual view is large):

```<code>%h1= link_to "Title", model_path(@model, :class => "lightbox")
= link_to "Check it out", model_path(@model, :class => "lightbox")
%footer= link_to "Last time", model_path(@model, :class => "lightbox")
</code>```

That model_path(@model, :class => "lightbox") call, though fairly clean, can be made even leaner wrapping it in this (maybe you had some more options, so doing this was worthwhile):

```<code>def popup_model_path(model)
  model_path(model, :class => "lightbox")
end
</code>```

My question is, I am having to recalculate that path 3 times in a view.  What is the preferred way of a) DRYing this up and b) optimizing performance?

I think setting variables at the top of the view might be a good idea here:

```<code>- path = model_path(@model, :class => "lightbox")
-# ... rest of view
</code>```

It's almost like mustache in the end then.  What are your thoughts?

答:
I think using variables in the view is a good idea here. Since these method calls are exactly the same.

The solution as proposed by Matt i prefer in some cases, but not in this case, because i find it confusing: the fact that it is cached in the method is not clear, and if i want to see two different models in one page i still get the first cached link for both models.

So in this case I would choose the somewhat more explicit approach and assign it to a variable in the view.

Body:
I have a view in which I have the same link 3 times (actual view is large):

%h1= link_to "Title", model_path(@model, :class => "lightbox")
= link_to "Check it out", model_path(@model, :class => "lightbox")
%footer= link_to "Last time", model_path(@model, :class => "lightbox")

That model_path(@model, :class => "lightbox") call, though fairly clean, can be made even leaner wrapping it in this (maybe you had some more options, so doing this was worthwhile):

def popup_model_path(model)
  model_path(model, :class => "lightbox")
end

My question is, I am having to recalculate that path 3 times in a view.  What is the preferred way of a) DRYing this up and b) optimizing performance?

I think setting variables at the top of the view might be a good idea here:

- path = model_path(@model, :class => "lightbox")
-# ... rest of view

It's almost like mustache in the end then.  What are your thoughts?


问:
is laravel cloning my mock object?
Im testing a Soap web service with getMockFromWsdl from phpunit, for unit testing within laravel works fine, but when I try to replace the SoapClient in a feature test, it always fails, like the web service never called, but actually the mock is called.

I suspect that laravel is cloning somewhere my $this->soapClient because if I debug the code, it calls the soap mock and gets what is faked in the mock but always receive the error:

```<code>Expectation failed for method name is equal to <string:GetToken> when invoked at least once.
Expected invocation at least once but it never occurred.
</code>```

My code is like:

```<code>public function test_soap_call()
{
    $this->soapClient = $this->getMockFromWsdl(dirname(__FILE__).'/../Mocks/service.wsdl');

    $this->soapClient->expects($this->atLeastOnce())
        ->method('GetToken')
        ->with(['Code' => '03600', 'User' => 'username'])
        ->willReturn(unserialize('O:8:"stdClass":1:{s:26:"GetTokenResult";s:36:"5aae60ec-2bcd-459d-a135-a20eb7c10007";}'));

    $this->app->instance('MySoapClient', $this->soapClient);

    $this->postJson('/api/order', $this->getValidRequest());

}
</code>```

and in my controller (/api/order) I have

```<code>$soap = $this->app->make('MySoapClient');
$soap->GetToken(['Code' => '03600', 'User' => 'username']);
</code>```

Am I using correctly the Laravel Service Container?

PD: Something similar happened to me, when doing a Spy and using $app->instance, where I was trying to get what was passed to an object, but always got null. I solved it declaring the field of the spy static.

答:
Check this from php.net:
http://php.net/manual/en/language.oop5.references.php

... "objects are passed by references by default". This is not completely true. ...

Title: is laravel cloning my mock object?

Body:
Im testing a Soap web service with getMockFromWsdl from phpunit, for unit testing within laravel works fine, but when I try to replace the SoapClient in a feature test, it always fails, like the web service never called, but actually the mock is called.

I suspect that laravel is cloning somewhere my $this->soapClient because if I debug the code, it calls the soap mock and gets what is faked in the mock but always receive the error:

Expectation failed for method name is equal to <string:GetToken> when invoked at least once.
Expected invocation at least once but it never occurred.

My code is like:

public function test_soap_call()
{
    $this->soapClient = $this->getMockFromWsdl(dirname(__FILE__).'/../Mocks/service.wsdl');

    $this->soapClient->expects($this->atLeastOnce())
        ->method('GetToken')
        ->with(['Code' => '03600', 'User' => 'username'])
        ->willReturn(unserialize('O:8:"stdClass":1:{s:26:"GetTokenResult";s:36:"5aae60ec-2bcd-459d-a135-a20eb7c10007";}'));

    $this->app->instance('MySoapClient', $this->soapClient);

    $this->postJson('/api/order', $this->getValidRequest());

}

and in my controller (/api/order) I have

$soap = $this->app->make('MySoapClient');
$soap->GetToken(['Code' => '03600', 'User' => 'username']);

Am I using correctly the Laravel Service Container?

PD: Something similar happened to me, when doing a Spy and using $app->instance, where I was trying to get what was passed to an object, but always got null. I solved it declaring the field of the spy static.


问:
Change data of OpenCV matrix from pointer
I am trying to capture images from several cameras using the cameras driver,OpenCV and C++. My goal is to get as many FPS as possible, and to this end I have found saving the images in the hard drive to be the slowest operation. In order to speed up the process, I am doing each saving in separate threads. Problem is, I still have to wait for the saving to be complete to avoid the captured image being overwritten. Doing this provides good results, but for unknown reasons every 30-40 frames the speed is 10x higher.

I am addressing this by creating a ring buffer where I store the images, as these sudden drops in write speed are very short. I have obtained very good results using this approach, but unfortunately for more than 3 cameras the camera driver can't handle the stress and my program halts, waiting for the first image of the 4th camera to be saved. I checked and it's not the CPU, as 3 cameras + a thread writing random data in the disk works fine.

Now, seeing how using opencv reduced the stress on the camera driver, I would like to create a OpenCV mat buffer to hold the images while they are saved without my camera overwritting them (well, not until the buffer has done a whole lap, which I will make sure won't happen).

I know I can do

```<code>cv::Mat colorFrame(cv::Size(width, height),CV_8UC3,pointerToMemoryOfCamera);
</code>```

to initialize a frame from the memory written by the camera. This does not solve my problem, as it will only point to the data, and the moment the camera overwrites it, it will corrupt the image saved.

How do I create a matrix with a given size and type, and then copy the contents of the memory to this matrix?

答:
You need to create a deep copy. You can use clone:

```<code>cv::Mat colorFrame = cv::Mat(height, width, CV_8UC3, pointerToMemoryOfCamera).clone();
</code>```

You can also speed up the process of saving the images using matwrite and matread functions.

Body:
I am trying to capture images from several cameras using the cameras driver,OpenCV and C++. My goal is to get as many FPS as possible, and to this end I have found saving the images in the hard drive to be the slowest operation. In order to speed up the process, I am doing each saving in separate threads. Problem is, I still have to wait for the saving to be complete to avoid the captured image being overwritten. Doing this provides good results, but for unknown reasons every 30-40 frames the speed is 10x higher.

I am addressing this by creating a ring buffer where I store the images, as these sudden drops in write speed are very short. I have obtained very good results using this approach, but unfortunately for more than 3 cameras the camera driver can't handle the stress and my program halts, waiting for the first image of the 4th camera to be saved. I checked and it's not the CPU, as 3 cameras + a thread writing random data in the disk works fine.

Now, seeing how using opencv reduced the stress on the camera driver, I would like to create a OpenCV mat buffer to hold the images while they are saved without my camera overwritting them (well, not until the buffer has done a whole lap, which I will make sure won't happen).

I know I can do

cv::Mat colorFrame(cv::Size(width, height),CV_8UC3,pointerToMemoryOfCamera);

to initialize a frame from the memory written by the camera. This does not solve my problem, as it will only point to the data, and the moment the camera overwrites it, it will corrupt the image saved.

How do I create a matrix with a given size and type, and then copy the contents of the memory to this matrix?

Body:
You need to create a deep copy. You can use clone:

cv::Mat colorFrame = cv::Mat(height, width, CV_8UC3, pointerToMemoryOfCamera).clone();

You can also speed up the process of saving the images using matwrite and matread functions.


问:
How can I use re.match to find numbers?
I'm trying to use python re module:

```<code>import re

res = re.match(r"\d+", 'editUserProfile!input.jspa?userId=2089')
print(res)
</code>```

I got None type for res, but if I replace the match by findall, I can find the 2089.

Do you know where the problem is ?

答:
The problem is that you're using match() to search for a substring in a string.

The method match() only works for the whole string. If you want to search for a substring inside a string, you should use search().

As stated by khelwood in the comments, you should take a look at: Search vs Match.

Code:

```<code>import re
res = re.search(r"\d+", 'editUserProfile!input.jspa?userId=2089')
print(res.group(0))
</code>```

Output:

```<code>2089
</code>```

Alternatively you can use .split() to isolate the user id.

Code:

```<code>s = 'editUserProfile!input.jspa?userId=2089'
print(s.split('=')[1])
</code>```

Output:

```<code>2089
</code>```

Title: How can I use re.match to find numbers?

Body:
I'm trying to use python re module:

import re

res = re.match(r"\d+", 'editUserProfile!input.jspa?userId=2089')
print(res)

I got None type for res, but if I replace the match by findall, I can find the 2089.

Do you know where the problem is ?

Body:
The problem is that you're using match() to search for a substring in a string.

The method match() only works for the whole string. If you want to search for a substring inside a string, you should use search().

As stated by khelwood in the comments, you should take a look at: Search vs Match.

Code:

import re
res = re.search(r"\d+", 'editUserProfile!input.jspa?userId=2089')
print(res.group(0))

Output:

2089

Alternatively you can use .split() to isolate the user id.

Code:

s = 'editUserProfile!input.jspa?userId=2089'
print(s.split('=')[1])

Output:

2089


问:
Rails nested routes
I am learning Rails and making a reddit clone to help me understand how routing works.

Each post has subreddit. I have the following in my routes file:

```<code>resources :subreddits  do
 resources :posts
end
</code>```

This way I can create new posts with the following url:

```<code>/subreddits/:subreddit_id/posts/new(.:format)
</code>```

Example:

```<code>http://localhost:3000/subreddits/1/posts/new
</code>```

However I still need to specify in the new posts form what subreddit I want to post to belong to. Wheras what I want is a hidden field that sets the subreddit id to the correct one. The correct one being the one given in the URL.

This is what I currently have:

```<code>=simple_form_for @post, html: {multipart: true} do |f|
-if @post.errors.any?
    #errors
        %h2
        =pluralize(@post.errors.count, "error")
        prevented this pin from saving
        %ul
            -@post.errors.full_messages.each do |msg|
                %li= msg

.form-group
    =f.input :title, input_html: {class: 'form-control'}

.form-group
    =f.input :content, input_html: {class: 'form-control'}

=f.hidden_field :subreddit_id, :value => @post.subreddit_id

=f.button :submit, class: "btn btn-primary"
</code>```

I get the following error:

```<code>No route matches {:action=>"show", :controller=>"posts", :id=>33, :subreddit_id=>nil} missing required keys: [:subreddit_id]
</code>```

I think this is because I am trying to access the subreddit id of a post that hasn't been created yet. How do I solve this? Am I going about it in the wrong direction?

答:
Try this and check if it works</p>

```<code>= f.input :title, :as => :hidden, :input_html => { :value => "some value" }
</code>```

Title: Rails nested routes

Body:
I am learning Rails and making a reddit clone to help me understand how routing works.

Each post has subreddit. I have the following in my routes file:

resources :subreddits  do
 resources :posts
end

This way I can create new posts with the following url:

/subreddits/:subreddit_id/posts/new(.:format)

Example:

http://localhost:3000/subreddits/1/posts/new

However I still need to specify in the new posts form what subreddit I want to post to belong to. Wheras what I want is a hidden field that sets the subreddit id to the correct one. The correct one being the one given in the URL.

This is what I currently have:

=simple_form_for @post, html: {multipart: true} do |f|
-if @post.errors.any?
    #errors
        %h2
        =pluralize(@post.errors.count, "error")
        prevented this pin from saving
        %ul
            -@post.errors.full_messages.each do |msg|
                %li= msg

.form-group
    =f.input :title, input_html: {class: 'form-control'}

.form-group
    =f.input :content, input_html: {class: 'form-control'}

=f.hidden_field :subreddit_id, :value => @post.subreddit_id

=f.button :submit, class: "btn btn-primary"

I get the following error:

No route matches {:action=>"show", :controller=>"posts", :id=>33, :subreddit_id=>nil} missing required keys: [:subreddit_id]

I think this is because I am trying to access the subreddit id of a post that hasn't been created yet. How do I solve this? Am I going about it in the wrong direction?

Body:
Try this and check if it works

= f.input :title, :as => :hidden, :input_html => { :value => "some value" }


问:
IAR iccarm Cmake
I have some trouble doing a migration from IAR IDE to Cmake/IAR compiler for arm:

According to my understanding, with a correct CMakeList.txt, I try:

```
/c/CMake/bin/cmake.exe -G"MSYS Makefiles" -DCMAKE_TOOLCHAIN_FILE="C:\CMake\bin\Modules\Compiler\iar.cmake" -DCMAKE_C_COMPILER="C:/Program Files (x86)/IAR Systems/Embedded Workbench 7.0/arm/bin/iccarm.exe" -DCMAKE_ASM_COMPILER="C:/Program Files (x86)/IAR Systems/Embedded Workbench 7.0/arm/bin/iasmarm.exe" ..
```

I get:

```
-- The C compiler identification is IAR
-- The ASM compiler identification is IAR
-- Found assembler: C:/Program Files (x86)/IAR Systems/Embedded Workbench 7.0/arm/bin/iasmarm.exe
-- Check for working C compiler: C:/Program Files (x86)/IAR Systems/Embedded Workbench 7.0/arm/bin/iccarm.exe
CMake Error at C:/CMake/bin/Modules/Compiler/IAR.cmake:41 (message):
  The IAR compiler for this architecture is not yet supported by CMake.
  Please go to https://gitlab.kitware.com/cmake/cmake/issues and enter a
  feature request there.
Call Stack (most recent call first):
  C:/Projects/LabPadIntegration/lpd_firmware/LABPAD_IAR/FIRMWARE/build/CMakeFiles/3.7.2/CMakeSystem.cmake:6 (include)
  C:/Projects/LabPadIntegration/lpd_firmware/LABPAD_IAR/FIRMWARE/build/CMakeFiles/CMakeTmp/CMakeLists.txt:2 (project)

CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: Internal CMake error, TryCompile configure of cmake failed
-- Configuring incomplete, errors occurred!
See also "C:/Projects/LabPadIntegration/lpd_firmware/LABPAD_IAR/FIRMWARE/build/CMakeFiles/CMakeOutput.log".
See also "C:/Projects/LabPadIntegration/lpd_firmware/LABPAD_IAR/FIRMWARE/build/CMakeFiles/CMakeError.log".
```

This sounds strange because if I read the IAR.cmake, the case where this fatal error rises is when the compiler does not match "arm" neither avr.
So I put a message output with the CMAKE_C_COMPILER argument and I get:

```
-- CMAKE_C_COMPILER={C:/Program Files (x86)/IAR Systems/Embedded Workbench 7.0/arm/bin/iccarm.exe}
-- The C compiler identification is IAR
-- The ASM compiler identification is IAR
-- Found assembler: C:/Program Files (x86)/IAR Systems/Embedded Workbench 7.0/arm/bin/iasmarm.exe
-- Check for working C compiler: C:/Program Files (x86)/IAR Systems/Embedded Workbench 7.0/arm/bin/iccarm.exe
CMake Error at C:/CMake/bin/Modules/Compiler/IAR.cmake:41 (message):
  The IAR compiler for this architecture is not yet supported by CMake.
  Please go to https://gitlab.kitware.com/cmake/cmake/issues and enter a
  feature request there.
Call Stack (most recent call first):
  C:/Projects/LabPadIntegration/lpd_firmware/LABPAD_IAR/FIRMWARE/build/CMakeFiles/3.7.2/CMakeSystem.cmake:6 (include)
  C:/Projects/LabPadIntegration/lpd_firmware/LABPAD_IAR/FIRMWARE/build/CMakeFiles/CMakeTmp/CMakeLists.txt:2 (project)

CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: Internal CMake error, TryCompile configure of cmake failed
-- Configuring incomplete, errors occurred!
See also "C:/Projects/LabPadIntegration/lpd_firmware/LABPAD_IAR/FIRMWARE/build/CMakeFiles/CMakeOutput.log".
See also "C:/Projects/LabPadIntegration/lpd_firmware/LABPAD_IAR/FIRMWARE/build/CMakeFiles/CMakeError.log".
```

So I get the trace with CMAKE_C_COMPILER which matches well the value I entered, but the MATCH tells it does not match "arm"...

Any idea ?

答:
I just got some support from the Cmake issue tracker:
My misunderstanding, this is because the file i give as an arg is not a toolchain file</p>

Title: IAR iccarm Cmake

Body:
I have some trouble doing a migration from IAR IDE to Cmake/IAR compiler for arm:

According to my understanding, with a correct CMakeList.txt, I try:

/c/CMake/bin/cmake.exe -G"MSYS Makefiles" -DCMAKE_TOOLCHAIN_FILE="C:\CMake\bin\Modules\Compiler\iar.cmake" -DCMAKE_C_COMPILER="C:/Program Files (x86)/IAR Systems/Embedded Workbench 7.0/arm/bin/iccarm.exe" -DCMAKE_ASM_COMPILER="C:/Program Files (x86)/IAR Systems/Embedded Workbench 7.0/arm/bin/iasmarm.exe" ..

I get:

-- The C compiler identification is IAR
-- The ASM compiler identification is IAR
-- Found assembler: C:/Program Files (x86)/IAR Systems/Embedded Workbench 7.0/arm/bin/iasmarm.exe
-- Check for working C compiler: C:/Program Files (x86)/IAR Systems/Embedded Workbench 7.0/arm/bin/iccarm.exe
CMake Error at C:/CMake/bin/Modules/Compiler/IAR.cmake:41 (message):
  The IAR compiler for this architecture is not yet supported by CMake.
  Please go to https://gitlab.kitware.com/cmake/cmake/issues and enter a
  feature request there.
Call Stack (most recent call first):
  C:/Projects/LabPadIntegration/lpd_firmware/LABPAD_IAR/FIRMWARE/build/CMakeFiles/3.7.2/CMakeSystem.cmake:6 (include)
  C:/Projects/LabPadIntegration/lpd_firmware/LABPAD_IAR/FIRMWARE/build/CMakeFiles/CMakeTmp/CMakeLists.txt:2 (project)

CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: Internal CMake error, TryCompile configure of cmake failed
-- Configuring incomplete, errors occurred!
See also "C:/Projects/LabPadIntegration/lpd_firmware/LABPAD_IAR/FIRMWARE/build/CMakeFiles/CMakeOutput.log".
See also "C:/Projects/LabPadIntegration/lpd_firmware/LABPAD_IAR/FIRMWARE/build/CMakeFiles/CMakeError.log".

This sounds strange because if I read the IAR.cmake, the case where this fatal error rises is when the compiler does not match "arm" neither avr.
So I put a message output with the CMAKE_C_COMPILER argument and I get:

-- CMAKE_C_COMPILER={C:/Program Files (x86)/IAR Systems/Embedded Workbench 7.0/arm/bin/iccarm.exe}
-- The C compiler identification is IAR
-- The ASM compiler identification is IAR
-- Found assembler: C:/Program Files (x86)/IAR Systems/Embedded Workbench 7.0/arm/bin/iasmarm.exe
-- Check for working C compiler: C:/Program Files (x86)/IAR Systems/Embedded Workbench 7.0/arm/bin/iccarm.exe
CMake Error at C:/CMake/bin/Modules/Compiler/IAR.cmake:41 (message):
  The IAR compiler for this architecture is not yet supported by CMake.
  Please go to https://gitlab.kitware.com/cmake/cmake/issues and enter a
  feature request there.
Call Stack (most recent call first):
  C:/Projects/LabPadIntegration/lpd_firmware/LABPAD_IAR/FIRMWARE/build/CMakeFiles/3.7.2/CMakeSystem.cmake:6 (include)
  C:/Projects/LabPadIntegration/lpd_firmware/LABPAD_IAR/FIRMWARE/build/CMakeFiles/CMakeTmp/CMakeLists.txt:2 (project)

CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: Internal CMake error, TryCompile configure of cmake failed
-- Configuring incomplete, errors occurred!
See also "C:/Projects/LabPadIntegration/lpd_firmware/LABPAD_IAR/FIRMWARE/build/CMakeFiles/CMakeOutput.log".
See also "C:/Projects/LabPadIntegration/lpd_firmware/LABPAD_IAR/FIRMWARE/build/CMakeFiles/CMakeError.log".

So I get the trace with CMAKE_C_COMPILER which matches well the value I entered, but the MATCH tells it does not match "arm"...

Any idea ?


问:
how do I throw a error on unknown fields in json request to spring restapi
I have a spring rest api which gets json data and binds to a pojo GetData.
Whenever i recieve unknown fields it doesnt fail or throw any exception. My requirement here is it should throw a error when it receives unknown fields in json data.

```<code>public ResponseEntity<Error> saveLocation(@Valid @RequestBody GetData getdata,BindingResult bindingResults) {
</code>```

Below is my Pojo GetData

```<code>public class GetData{

@JsonProperty("deviceID")
@Pattern(regexp="^[\\p{Alnum}][-\\p{Alnum}\\p{L}]+[\\p{Alnum}]$",message = "Not a valid Device Id")
private String deviceID;

@JsonProperty("Coordinates")
@Pattern(regexp="^[\\p{Alnum}\\-][\\.\\,\\-\\_\\p{Alnum}\\p{L}\\s]+|",message = "Coordinates are not valid")
private String coordinates;}
</code>```

Below is my json request.

```<code>{
"deviceID" : "01dbd619-843b-4197-b954",
"Coordinates" : "12.984012,80.246712",
}
</code>```

Now if i send a request with an extra field say country. It doesn't throw any error.

```<code>{
    "deviceID" : "01dbd619-843b-4197-b954",
    "Coordinates" : "12.984012,80.246712",
    "country" : "dsasa"
}
</code>```

Please suggest how can i have an error for unknown properties being sent in a json request

答:
You need to configure your ObjectMapper to handle such cases:

```<code>objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
</code>```

Body:
I have a spring rest api which gets json data and binds to a pojo GetData.
Whenever i recieve unknown fields it doesnt fail or throw any exception. My requirement here is it should throw a error when it receives unknown fields in json data.

public ResponseEntity<Error> saveLocation(@Valid @RequestBody GetData getdata,BindingResult bindingResults) {

Below is my Pojo GetData

public class GetData{

@JsonProperty("deviceID")
@Pattern(regexp="^[\\p{Alnum}][-\\p{Alnum}\\p{L}]+[\\p{Alnum}]$",message = "Not a valid Device Id")
private String deviceID;

@JsonProperty("Coordinates")
@Pattern(regexp="^[\\p{Alnum}\\-][\\.\\,\\-\\_\\p{Alnum}\\p{L}\\s]+|",message = "Coordinates are not valid")
private String coordinates;}

Below is my json request.

{
"deviceID" : "01dbd619-843b-4197-b954",
"Coordinates" : "12.984012,80.246712",
}

Now if i send a request with an extra field say country. It doesn't throw any error.

{
    "deviceID" : "01dbd619-843b-4197-b954",
    "Coordinates" : "12.984012,80.246712",
    "country" : "dsasa"
}

Please suggest how can i have an error for unknown properties being sent in a json request

Body:
You need to configure your ObjectMapper to handle such cases:

objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);