问:
Test calls async method which returns 'Value cannot be null'
I have an async method which I'm trying to unit test, specifically I want to test that the async method returns a NoContent response given that no customer entities were found. Here is the method in question:

    [HttpGet]
    [Route("customers/{customerNumber}")]
    public virtual async Task<IHttpActionResult> Get([FromUri] CustomerNumber customerNumber)
    {
        var customerEntitiesList = _tableStorageService.GetCustomerEntities(customerNumber);
        var customersList = customerEntitiesList.Select(customerEntity => customerEntity.PartitionKey).ToList();
        if (customersList.Any()) {
            return await Task.FromResult(Ok(customersList));
        }
        return await Task.FromResult(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.NoContent, "No content found.")));
    }
```

<p>To clarify, <code>CustomerNumber</code> is a string representation class and looks like this:</p>

<pre class="lang-c# prettyprint-override"><code>[DebuggerDisplay("{ToString()}")]
public class CustomerNumber
{
    public CustomerNumber(string customerNumber);

    public static bool TryParse(string customerNumber, out CustomerNumber parsedCustomerNumber);
    public override string ToString();

    public static implicit operator string(CustomerNumber customerNumber);
    public static implicit operator CustomerNumber(string customerNumber);
}
</code>```

And here is the unit test:

    [Test]
    public async Task Should_Return_No_Content_If_Customer_Entities_Are_Not_Found()
    {
        const string customerNumber = "WP0000000000";
        var customerEntitiesStub = new List<CustomerEntity>();
        A.CallTo(() => _tableStorageServiceDummy.GetCustomerEntities(customerNumber)).Returns(customerEntitiesStub);

        var result = await _companyController.Get(customerNumber);

        ((ResponseMessageResult)result).Response.StatusCode.Should().Be(HttpStatusCode.NoContent);
    }
```

When I run this test, it just fails before even completing with the error System.ArgumentNullException : Value cannot be null.. Why is this happening and how can I fix it so that I can assert the result? Thanks!

答:
The mock is setup to expect a string but the actual method has a CustomerNumber parameter. Start investigating there.

Because the setup does not match, the customerEntitiesList would be null when the GetCustomerEntities is invoked.

Assuming CustomerNumber can be implicitly converted from a string then the test should be configured with an actual CustomerNumber instance.

```<code>[Test]
public async Task Should_Return_No_Content_If_Customer_Entities_Are_Not_Found() {
    const CustomerNumber customerNumber = "WP0000000000";
    var customerEntitiesStub = new List<CustomerEntity>();
    A.CallTo(() => _tableStorageServiceDummy.GetCustomerEntities(customerNumber)).Returns(customerEntitiesStub);

    var result = await _companyController.Get(customerNumber);

    ((ResponseMessageResult)result).Response.StatusCode.Should().Be(HttpStatusCode.NoContent);
}
</code>```

On a separate not the design of that action wraps the result in tasks. There is currently no reason for that action to be async.

```<code>[HttpGet]
[Route("customers/{customerNumber}")]
public virtual IHttpActionResult Get([FromUri] CustomerNumber customerNumber)
{
    var customerEntitiesList = _tableStorageService.GetCustomerEntities(customerNumber);
    var customersList = customerEntitiesList.Select(customerEntity => customerEntity.PartitionKey).ToList();
    if (customersList.Any()) {
        return Ok(customersList);
    }
    return Request.CreateErrorResponse(HttpStatusCode.NoContent, "No content found.");
}
</code>```

and update the test accordingly.

Body:
I have an async method which I'm trying to unit test, specifically I want to test that the async method returns a NoContent response given that no customer entities were found. Here is the method in question:

    [HttpGet]
    [Route("customers/{customerNumber}")]
    public virtual async Task<IHttpActionResult> Get([FromUri] CustomerNumber customerNumber)
    {
        var customerEntitiesList = _tableStorageService.GetCustomerEntities(customerNumber);
        var customersList = customerEntitiesList.Select(customerEntity => customerEntity.PartitionKey).ToList();
        if (customersList.Any()) {
            return await Task.FromResult(Ok(customersList));
        }
        return await Task.FromResult(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.NoContent, "No content found.")));
    }

To clarify, CustomerNumber is a string representation class and looks like this:

[DebuggerDisplay("{ToString()}")]
public class CustomerNumber
{
    public CustomerNumber(string customerNumber);

    public static bool TryParse(string customerNumber, out CustomerNumber parsedCustomerNumber);
    public override string ToString();

    public static implicit operator string(CustomerNumber customerNumber);
    public static implicit operator CustomerNumber(string customerNumber);
}

And here is the unit test:

    [Test]
    public async Task Should_Return_No_Content_If_Customer_Entities_Are_Not_Found()
    {
        const string customerNumber = "WP0000000000";
        var customerEntitiesStub = new List<CustomerEntity>();
        A.CallTo(() => _tableStorageServiceDummy.GetCustomerEntities(customerNumber)).Returns(customerEntitiesStub);

        var result = await _companyController.Get(customerNumber);

        ((ResponseMessageResult)result).Response.StatusCode.Should().Be(HttpStatusCode.NoContent);
    }

When I run this test, it just fails before even completing with the error System.ArgumentNullException : Value cannot be null.. Why is this happening and how can I fix it so that I can assert the result? Thanks!

Body:
The mock is setup to expect a string but the actual method has a CustomerNumber parameter. Start investigating there.

Because the setup does not match, the customerEntitiesList would be null when the GetCustomerEntities is invoked.

Assuming CustomerNumber can be implicitly converted from a string then the test should be configured with an actual CustomerNumber instance.

[Test]
public async Task Should_Return_No_Content_If_Customer_Entities_Are_Not_Found() {
    const CustomerNumber customerNumber = "WP0000000000";
    var customerEntitiesStub = new List<CustomerEntity>();
    A.CallTo(() => _tableStorageServiceDummy.GetCustomerEntities(customerNumber)).Returns(customerEntitiesStub);

    var result = await _companyController.Get(customerNumber);

    ((ResponseMessageResult)result).Response.StatusCode.Should().Be(HttpStatusCode.NoContent);
}

On a separate not the design of that action wraps the result in tasks. There is currently no reason for that action to be async.

[HttpGet]
[Route("customers/{customerNumber}")]
public virtual IHttpActionResult Get([FromUri] CustomerNumber customerNumber)
{
    var customerEntitiesList = _tableStorageService.GetCustomerEntities(customerNumber);
    var customersList = customerEntitiesList.Select(customerEntity => customerEntity.PartitionKey).ToList();
    if (customersList.Any()) {
        return Ok(customersList);
    }
    return Request.CreateErrorResponse(HttpStatusCode.NoContent, "No content found.");
}

and update the test accordingly.


来源: stackexchange

问:
Delegating method to has_many association ignores preloading
Is it possible to delegate a method to a has_many association in rails, AND still save the preloaded data on that association, all while following the law of demeter?  Currently it seems to me that you are forced to choose one or the other. That is: keep your preloaded data by NOT delegating, or lose your preloaded data and delegate.

Example: I have the following two models:

```<code>class User < ApplicationRecord
  has_many :blogs

  delegate :all_have_title?, to: :blogs, prefix: false, allow_nil: false

  def all_blogs_have_title?
    blogs.all? {|blog| blog.title.present?}
  end
end

class Blog < ApplicationRecord
  belongs_to :user

  def self.all_have_title?
    all.all? {|blog| blog.title.present?}
  end
end
</code>```

Notice: that User#all_blogs_have_title? does the exact same thing as the delegation method of all_have_title?.

The following, as I understand it, violates law of demeter.  However: it maintains your preloaded data:

```<code>user = User.includes(:blogs).first
  User Load (0.1ms)  SELECT  "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ?  [["LIMIT", 1]]
  Blog Load (0.1ms)  SELECT "blogs".* FROM "blogs" WHERE "blogs"."user_id" = 1
  => #<User id: 1, name: "all yes", created_at: "2017-12-05 20:28:00", updated_at: "2017-12-05 20:28:00">

user.all_blogs_have_title?
 => true
</code>```

Notice: when I called  user.all_blogs_have_title? it DID NOT do an additional query.  However, notice that the method all_blogs_have_title? is asking about Blog attributes, which is violating law of demeter.

Other way which applies law of demeter but you lose the preloaded data:

```<code>user = User.includes(:blogs).first
  User Load (0.1ms)  SELECT  "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ?  [["LIMIT", 1]]
  Blog Load (0.1ms)  SELECT "blogs".* FROM "blogs" WHERE "blogs"."user_id" = 1
  => #<User id: 1, name: "all yes", created_at: "2017-12-05 20:28:00", updated_at: "2017-12-05 20:28:00">

user.all_have_title?
  Blog Load (0.2ms)  SELECT "blogs".* FROM "blogs" WHERE "blogs"."user_id" = ?  [["user_id", 1]]
  => true
</code>```

Hopefully the downside of both implementations is apparent. Ideally: I would like to do it the second way with the delegate implementation, but to maintain that preloaded data.  Is this possible?

答:
Here is a solution that follows law of demeter AND honors the preloaded data (doesn't hit the database all over again).  It is certainly a bit odd, but I could not find any other solution, and I really want to know what others think about this:

Models

```<code>class User < ApplicationRecord
  has_many :blogs

  def all_blogs_have_title?
    blogs.all_have_title_present?(self)
  end
end

class Blog < ApplicationRecord
  belongs_to :user

  def self.all_have_title_present?(user)
    user.blogs.any? && user.blogs.all? {|blog| blog.title.present?}
  end
end
</code>```

Usage

```<code>user = User.includes(:blogs).first
  User Load (0.1ms)  SELECT  "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ?  [["LIMIT", 1]]
  Blog Load (0.1ms)  SELECT "blogs".* FROM "blogs" WHERE "blogs"."user_id" = 1
  => #<User id: 1, name: "all yes", created_at: "2017-12-05 20:28:00", updated_at: "2017-12-05 20:28:00">

user.all_blogs_have_title?
=> true
</code>```

So we notice that it is not hitting the database again (honoring the preloaded data), and instead of the user reaching into the attributes of it's neighbor (Blog), it delegates the question to it's neighbor and allows the neighbor (again: Blog) to answer questions about it's own attributes.

The odd thing is clearly inside the Blog model where the class method asks user.blogs, so Blog knows about the association on User.  But perhaps this is ok because, after all, Blog and User share an association with each other.

ContentLicense: CC BY-SA 3.0

Body:
Is it possible to delegate a method to a has_many association in rails, AND still save the preloaded data on that association, all while following the law of demeter?  Currently it seems to me that you are forced to choose one or the other. That is: keep your preloaded data by NOT delegating, or lose your preloaded data and delegate.

Example: I have the following two models:

class User < ApplicationRecord
  has_many :blogs

  delegate :all_have_title?, to: :blogs, prefix: false, allow_nil: false

  def all_blogs_have_title?
    blogs.all? {|blog| blog.title.present?}
  end
end

class Blog < ApplicationRecord
  belongs_to :user

  def self.all_have_title?
    all.all? {|blog| blog.title.present?}
  end
end

Notice: that User#all_blogs_have_title? does the exact same thing as the delegation method of all_have_title?.

The following, as I understand it, violates law of demeter.  However: it maintains your preloaded data:

user = User.includes(:blogs).first
  User Load (0.1ms)  SELECT  "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ?  [["LIMIT", 1]]
  Blog Load (0.1ms)  SELECT "blogs".* FROM "blogs" WHERE "blogs"."user_id" = 1
  => #<User id: 1, name: "all yes", created_at: "2017-12-05 20:28:00", updated_at: "2017-12-05 20:28:00">

user.all_blogs_have_title?
 => true

Notice: when I called  user.all_blogs_have_title? it DID NOT do an additional query.  However, notice that the method all_blogs_have_title? is asking about Blog attributes, which is violating law of demeter.

Other way which applies law of demeter but you lose the preloaded data:

user = User.includes(:blogs).first
  User Load (0.1ms)  SELECT  "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ?  [["LIMIT", 1]]
  Blog Load (0.1ms)  SELECT "blogs".* FROM "blogs" WHERE "blogs"."user_id" = 1
  => #<User id: 1, name: "all yes", created_at: "2017-12-05 20:28:00", updated_at: "2017-12-05 20:28:00">

user.all_have_title?
  Blog Load (0.2ms)  SELECT "blogs".* FROM "blogs" WHERE "blogs"."user_id" = ?  [["user_id", 1]]
  => true

Hopefully the downside of both implementations is apparent. Ideally: I would like to do it the second way with the delegate implementation, but to maintain that preloaded data.  Is this possible?

Body:
Here is a solution that follows law of demeter AND honors the preloaded data (doesn't hit the database all over again).  It is certainly a bit odd, but I could not find any other solution, and I really want to know what others think about this:

Models

class User < ApplicationRecord
  has_many :blogs

  def all_blogs_have_title?
    blogs.all_have_title_present?(self)
  end
end

class Blog < ApplicationRecord
  belongs_to :user

  def self.all_have_title_present?(user)
    user.blogs.any? && user.blogs.all? {|blog| blog.title.present?}
  end
end

Usage

user = User.includes(:blogs).first
  User Load (0.1ms)  SELECT  "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ?  [["LIMIT", 1]]
  Blog Load (0.1ms)  SELECT "blogs".* FROM "blogs" WHERE "blogs"."user_id" = 1
  => #<User id: 1, name: "all yes", created_at: "2017-12-05 20:28:00", updated_at: "2017-12-05 20:28:00">

user.all_blogs_have_title?
=> true

So we notice that it is not hitting the database again (honoring the preloaded data), and instead of the user reaching into the attributes of it's neighbor (Blog), it delegates the question to it's neighbor and allows the neighbor (again: Blog) to answer questions about it's own attributes.

The odd thing is clearly inside the Blog model where the class method asks user.blogs, so Blog knows about the association on User.  But perhaps this is ok because, after all, Blog and User share an association with each other.


问:
Getting float array from C++ to C#
I have float array inside C++ function.

C++ function

```<code>void bleplugin_GetGolfResult(float* result)
{
    float *array = new float[20];
    for(int i=0; i < 20; i++)
      array[i]= 25;
    result = array;
    //DEBUG PRINTING1
    for(int i=0; i < 20; i++)
       cout << result[i] << endl;//Here is correct
    return;
}
</code>```

Inside C#

```<code>[DllImport ("__Internal")]
private static unsafe extern void bleplugin_GetGolfResult (float* result);

public static unsafe float[] result = new float[20];

public unsafe static void GetGolfREsult(){
    fixed (float* ptr_result = result) //or equivalently "... = &f2[0]" address of f2[0]
    {
        bleplugin_GetGolfResult( ptr_result );
        //DEBUG PRINTING2
        for(int i = 0; i < 20; i++)
            Debug.Log("result data " + ptr_result[i]);
    }
    return;
}
</code>```

I called GetGolfREsult() from another function to get result.

//DEBUG PRINTING1 has correct output.

But //DEBUG PRINTING2 produced 0 only.

What could be wrong?

答:
As UnholySheep and nvoigt already stated,

```<code>result = array;
</code>```

overrides the address of the passed pointer, making you lose the reference to the calling function.

Directly writing to your parameter should solve this.

```<code>result[i] = 25;
</code>```

Further you dont actually have to use pointers in c#.
You can actually do the following:

Declare your Import like this:

```<code>private static extern void bleplugin_GetGolfResult (float arr[]);
</code>```

Then you can call it like this:

```<code>float arr = new float[20];
bleplugin_GetGolfResult(arr);
</code>```

Title: Getting float array from C++ to C#

Body:
I have float array inside C++ function.

C++ function

void bleplugin_GetGolfResult(float* result)
{
    float *array = new float[20];
    for(int i=0; i < 20; i++)
      array[i]= 25;
    result = array;
    //DEBUG PRINTING1
    for(int i=0; i < 20; i++)
       cout << result[i] << endl;//Here is correct
    return;
}

Inside C#

[DllImport ("__Internal")]
private static unsafe extern void bleplugin_GetGolfResult (float* result);

public static unsafe float[] result = new float[20];

public unsafe static void GetGolfREsult(){
    fixed (float* ptr_result = result) //or equivalently "... = &f2[0]" address of f2[0]
    {
        bleplugin_GetGolfResult( ptr_result );
        //DEBUG PRINTING2
        for(int i = 0; i < 20; i++)
            Debug.Log("result data " + ptr_result[i]);
    }
    return;
}

I called GetGolfREsult() from another function to get result.

//DEBUG PRINTING1 has correct output.

But //DEBUG PRINTING2 produced 0 only.

What could be wrong?

Body:
As UnholySheep and nvoigt already stated,

result = array;

overrides the address of the passed pointer, making you lose the reference to the calling function.

Directly writing to your parameter should solve this.

result[i] = 25;

Further you dont actually have to use pointers in c#.
You can actually do the following:

Declare your Import like this:

private static extern void bleplugin_GetGolfResult (float arr[]);

Then you can call it like this:

float arr = new float[20];
bleplugin_GetGolfResult(arr);


问:
Syntax to get function pointers in C++11
I am trying to understand function pointers and I have the following test code:

```<code>#include <iostream>

using namespace std;

class Test {
public:
    void test_func() {
        cout << "Test func called.";
    }
};

void outer_test_func(Test &t, void (Test::*func)()) {
    (t.*func)();
}

int main(int argc, char *argv[]) {
    auto t = Test();
    outer_test_func(t, &Test::test_func);
}
</code>```

This works. But from what I understand Test::test_func and &Test::test_func both result in pointers. So why can't I use the former instead of the latter? If I try it g++ complains.

答:
But from what I understand Test::test_func and &Test::test_func both result in pointers.

Test::test_func is not a valid syntax for creating pointer to member function, nor pointer to data members. It has never been a valid C++ syntax.

From cppreference (emphasis mine),

A pointer to non-static member object m which is a member of class C can be initialized with the expression &C::m exactly. Expressions such as &(C::m) or &m inside C's member function do not form pointers to members.

Body:
I am trying to understand function pointers and I have the following test code:

#include <iostream>

using namespace std;

class Test {
public:
    void test_func() {
        cout << "Test func called.";
    }
};

void outer_test_func(Test &t, void (Test::*func)()) {
    (t.*func)();
}

int main(int argc, char *argv[]) {
    auto t = Test();
    outer_test_func(t, &Test::test_func);
}

This works. But from what I understand Test::test_func and &Test::test_func both result in pointers. So why can't I use the former instead of the latter? If I try it g++ complains.


问:
Reason for: Trying to get property of non-object in php
```<code>    if(isset($_POST['uname']))
    {
        $query = "SELECT * FROM user_info";
        $res = $mysqli->query($query);
        $num = $res->num_rows;
        $i = 0;
        $cpwd = $_POST["pswd"];
        $hpwd = SHA1($cpwd);
        $tmp = $_POST["uname"];
        while($i < $num)
        {
            $row = $res->fetch_object();
            $name = $row->Username;
            $pwd = $row->Password;
            if($name == $tmp)
            {
                   //check if user is blocked
            }
            //hashed pwd
            if($pwd == $hpwd)
            {
                //success
                exit();
            }
            //request for pwd change
        else if($pwd == $cpwd)
            {
            //change
                exit();
            }
            else if($pwd != $hpwd)
            {

                //incorrect pwd
            }
        }
        $i++;
    }
    if($i == $num)
    {
        //new user
    }
}
</code>```

答:
get rid of that junk and make it like this

```<code>$query = "SELECT * FROM user_info WHERE Username = ? AND Password = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('ss', $_POST["uname"], SHA1($_POST["pswd"]));
$stmt->execute() or trigger_error($mysqli->error());
if (!$mysqli->affected_rows) {
  //no such user
}
</code>```

I've never used mysqli myself, so, there may be typos.

But I hope you'll be able to get the idea.

ContentLicense: CC BY-SA 2.5

Body:
get rid of that junk and make it like this

$query = "SELECT * FROM user_info WHERE Username = ? AND Password = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('ss', $_POST["uname"], SHA1($_POST["pswd"]));
$stmt->execute() or trigger_error($mysqli->error());
if (!$mysqli->affected_rows) {
  //no such user
}

I've never used mysqli myself, so, there may be typos.

But I hope you'll be able to get the idea.


问:
How to Add Items to List of Lists C#
I am writing file processing system where I need groups of files to stay together.  I figured I need a list of strings and a list of (list of strings) but I am not able add anything to my lists.   Visual Studio isn't offering me .Add for my lists.

```<code>    usings ....

    namespace Main
    {

    public class SisterFiles : List<string>
    { }

    public class FileGroups : List<SisterFiles>
    { }

    static class Program
    {

        /// <summary>
        /// The main entry point for the application.
        /// </summary>

        [STAThread]

        static void Main(string[] args)
        {
            // here is where I would like to assign a list of files to instances of SisterFiles
           // here is where I'd like to add each SisterFile list to FileGroups
           //  but VS only offers Equals/Enumerate or Reference Equals
</code>```

---->>>> Wouldn't let me add anything             SisterFiles { ""} //

```<code>            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            //  go through the list and make sure all the files are together
            //  if they are together
            //   run the program

        }
    }
}
</code>```

Any advice would be helpful.  I know I have a lot to learn about classes and lists!

答:
You can correct your structure as follows.</p>

```<code>public class SisterFiles
{
    public List<string> lstString;
}

public class FileGroups
{
    public List<SisterFiles> lstSisterFiles;
}

class Program
{
    static void Main(string[] args)
    {
        SisterFiles sisterFiles = new SisterFiles();
        sisterFiles.lstString.Add("My String");

        FileGroups fileGroup = new FileGroups();
        fileGroup.lstSisterFiles = new List<SisterFiles>();
        fileGroup.lstSisterFiles.Add(sisterFiles);
    }
}
</code>```

Title: How to Add Items to List of Lists C#

Body:
I am writing file processing system where I need groups of files to stay together.  I figured I need a list of strings and a list of (list of strings) but I am not able add anything to my lists.   Visual Studio isn't offering me .Add for my lists.

    usings ....

    namespace Main
    {

    public class SisterFiles : List<string>
    { }

    public class FileGroups : List<SisterFiles>
    { }

    static class Program
    {

        ///
        /// The main entry point for the application.
        ///

        [STAThread]

        static void Main(string[] args)
        {
            // here is where I would like to assign a list of files to instances of SisterFiles
           // here is where I'd like to add each SisterFile list to FileGroups
           //  but VS only offers Equals/Enumerate or Reference Equals

---->>>> Wouldn't let me add anything             SisterFiles { ""} //

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            //  go through the list and make sure all the files are together
            //  if they are together
            //   run the program

        }
    }
}

Any advice would be helpful.  I know I have a lot to learn about classes and lists!

Body:
You can correct your structure as follows.

public class SisterFiles
{
    public List<string> lstString;
}

public class FileGroups
{
    public List<SisterFiles> lstSisterFiles;
}

class Program
{
    static void Main(string[] args)
    {
        SisterFiles sisterFiles = new SisterFiles();
        sisterFiles.lstString.Add("My String");

        FileGroups fileGroup = new FileGroups();
        fileGroup.lstSisterFiles = new List<SisterFiles>();
        fileGroup.lstSisterFiles.Add(sisterFiles);
    }
}


问:
Get checkbox state and click accordingly using pywinauto
When i use below pywinauto code, i am getting error saying

```<code>from pywinauto.controls.win32_controls import ButtonWrapper
checkbox = ButtonWrapper(app.Dialog.child_window(title='Has Balance',auto_id='HasBalanceCheckEdit',control_type='CheckBox').TCheckBox.WrapperObject())
print(checkbox.GetCheckState())
</code>```

Error:

```<code>raise MatchError(items = name_control_map.keys(), tofind = search_text)
pywinauto.findbestmatch.MatchError: Could not find 'TCheckBox' in 'dict_keys(['Has Balance', 'Has BalanceStatic', 'Static'])'
</code>```

答: used import pywinauto.controls.uia_controls to resolve the above code.

Body:
When i use below pywinauto code, i am getting error saying

from pywinauto.controls.win32_controls import ButtonWrapper
checkbox = ButtonWrapper(app.Dialog.child_window(title='Has Balance',auto_id='HasBalanceCheckEdit',control_type='CheckBox').TCheckBox.WrapperObject())
print(checkbox.GetCheckState())

Error:

raise MatchError(items = name_control_map.keys(), tofind = search_text)
pywinauto.findbestmatch.MatchError: Could not find 'TCheckBox' in 'dict_keys(['Has Balance', 'Has BalanceStatic', 'Static'])'

ContentLicense: CC BY-SA 4.0


问:
HTML5 Video centering source
I have a video that I will be mainly displaying on a portrait screen and I would like the video to be the full height of the screen but centered so the centre of the video is the centre of the screen. I have my current CSS and HTML below. This will display the video of 100% the height but the actual source (video) is played from the left-hand side of itself, not the centre. Is there anyway to do what I'm asking? Also, the video maybe displayed landscape and would need the same result.

Left of this image is what im getting, right is what I want

```<code>.videoContainer
{
    position:absolute;
    height:100%;
    width:100%;
    overflow: hidden;
}

.videoContainer video
{
    width: auto;
    height: 100%
}

  <div class="videoContainer">
    <video width="944" height="532" controls preload="auto" poster="posterimg.jpg">
        <source src="test.mp4" type="video/mp4" />
        <source src="test.webm" type="video/webm">
        <source src="test.ogv" type="video/ogg" type='video/ogg; codecs="theora, vorbis"'>
    </video>
  </div>
</code>```

答:
Try This:

video {
   position: fixed;
   top: 0;
   right: 0;
   bottom: 0;
   left: 0;
   text-align:center;
   height:100%;
   width:100%;
   object-fit:cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="videoContainer">
 <video controls>
   <source src=http://techslides.com/demos/sample-videos/small.webm type=video/webm>
   <source src=http://techslides.com/demos/sample-videos/small.ogv type=video/ogg>
   <source src=http://techslides.com/demos/sample-videos/small.mp4 type=video/mp4>
   <source src=http://techslides.com/demos/sample-videos/small.3gp type=video/3gp>
 </video>
</div></code>```

Title: HTML5 Video centering source

Body:
I have a video that I will be mainly displaying on a portrait screen and I would like the video to be the full height of the screen but centered so the centre of the video is the centre of the screen. I have my current CSS and HTML below. This will display the video of 100% the height but the actual source (video) is played from the left-hand side of itself, not the centre. Is there anyway to do what I'm asking? Also, the video maybe displayed landscape and would need the same result.

Left of this image is what im getting, right is what I want

.videoContainer
{
    position:absolute;
    height:100%;
    width:100%;
    overflow: hidden;
}

.videoContainer video
{
    width: auto;
    height: 100%
}

    <video width="944" height="532" controls preload="auto" poster="posterimg.jpg">
        <source src="test.mp4" type="video/mp4" />
        <source src="test.webm" type="video/webm">
        <source src="test.ogv" type="video/ogg" type='video/ogg; codecs="theora, vorbis"'>
    </video>

Body:
Try This:

video {
   position: fixed;
   top: 0;
   right: 0;
   bottom: 0;
   left: 0;
   text-align:center;
   height:100%;
   width:100%;
   object-fit:cover;
}

<div class="videoContainer">
 <video controls>
   <source src=http://techslides.com/demos/sample-videos/small.webm type=video/webm>
   <source src=http://techslides.com/demos/sample-videos/small.ogv type=video/ogg>
   <source src=http://techslides.com/demos/sample-videos/small.mp4 type=video/mp4>
   <source src=http://techslides.com/demos/sample-videos/small.3gp type=video/3gp>
 </video>
</div>


问:
JavaScript: Dynamically generated object key
```<code>const cars = [
  {
    'id': 'truck',
    'defaultCategory': 'vehicle'
  }
]

const output = []

Object.keys(cars).map((car) => {
  output.push({
      foo: cars[car].defaultCategory
  })
})

console.log(output)
</code>```

This work fine, however what I want to achieve is so that the newly crated object has structure of 'truck': 'vehicle'.

So if I replace push argument with

```<code>${cars[car].id}`: cars[car].defaultCategory
</code>```

I get SyntaxError: Unexpected template string

What am I doing wrong?

答:
Use map on the array, and not the keys (the indexes) to get an array of objects. For each object use computed property names to set the id value as the key:

const cars = [
  {
    'id': 'truck',
    'defaultCategory': 'vehicle'
  }
];

const result = cars.map(({ id, defaultCategory }) => ({ [id]: defaultCategory }));

console.log(result);```

Body:
const cars = [
  {
    'id': 'truck',
    'defaultCategory': 'vehicle'
  }
]

const output = []

Object.keys(cars).map((car) => {
  output.push({
      foo: cars[car].defaultCategory
  })
})

console.log(output)

This work fine, however what I want to achieve is so that the newly crated object has structure of 'truck': 'vehicle'.

So if I replace push argument with

${cars[car].id}`: cars[car].defaultCategory

I get SyntaxError: Unexpected template string

What am I doing wrong?


问:
Rails: "except" vs "slice" to take out certain parameter?
I am trying to create a class instance with one particular key extracted out and save for later

consider this is the type of param:

```<code>Parameters: {"p1": "foo", "p2": "bar", "p3":"param that i want to extract" >
</code>```

I would do something like:

```<code>@my_class = MyClass.new(whiteList_function.except(:p3))
</code>```

or something like

```<code>@my_class = MyClass.new(whiteList_function)
@my_class_key = @my_class.slice(:p3)
</code>```

My whiteList_function:

```<code>def whiteList_function
    params.require(:my_class).permit(:p1,:p2,p3)
end
</code>```

My concern is that, I have searched on SO and some have mentioned the security risk of using except.

So my question is, in this particular usage(take out certain key and use them for later), should I use except or slice?

答:
Using except with parameter hashes is dangerous because you're saying "allow any parameter other than this one" so it opens your model up to mass-assignment attacks.

Unless I'm not thinking of another attack vector you should be fine, because you're filtering your acceptable parameter hash with strong_parameters in your whiteList_function. So, you're fine further filtering that hash with either slice or except, whichever is more appealing to you.

Body:
I am trying to create a class instance with one particular key extracted out and save for later

consider this is the type of param:

Parameters: {"p1": "foo", "p2": "bar", "p3":"param that i want to extract" >

I would do something like:

@my_class = MyClass.new(whiteList_function.except(:p3))

or something like

@my_class = MyClass.new(whiteList_function)
@my_class_key = @my_class.slice(:p3)

My whiteList_function:

def whiteList_function
    params.require(:my_class).permit(:p1,:p2,p3)
end

My concern is that, I have searched on SO and some have mentioned the security risk of using except.

So my question is, in this particular usage(take out certain key and use them for later), should I use except or slice?


问:
Getting the HTTP Referrer in ASP.NET
I'm looking for a quick, easy and reliable way of getting the browser's HTTP Referrer in ASP.Net (C#).  I know the HTTP Referrer itself is unreliable, but I do want a reliable way of getting the referrer if it is present.

答:
Sometime you must to give all the link like this </p>

```<code>System.Web.HttpContext.Current.Request.UrlReferrer.ToString();
</code>```

<p>(in option when "Current" not founded)</p>

Title: Getting the HTTP Referrer in ASP.NET

Body:
Sometime you must to give all the link like this

System.Web.HttpContext.Current.Request.UrlReferrer.ToString();

(in option when "Current" not founded)


问:
Nested flex-box wrapping issue
Edit
Unlike The difference between flex:1 and flex-grow:1 .  While the answer ultimately was the use of flex instead of flex-grow, my question was not the difference between the two but rather how to get nested flex-boxes to wrap appropriately.  For someone struggling with this issue, there would be no way to find that answer on SO without already knowing the issue was the use of flex vs. flex-grow.  If I already knew the issue was the difference between flex and flex-grow, I wouldn't have needed to ask the question.

Edit 2
If this post is going to be flagged as duplicate, it would be better to list it as a duplicate of Nested column flexbox inside row flexbox with wrapping instead of The difference between flex:1 and flex-grow:1.

I have a series of div tags that are defined as display:flex.  They are laid out as a row with 3 columns.  The first two columns are given a width and the third column is allowed to stretch to fill the rest of the space.  The row is also set to wrap so that on smaller screens, the third column will wrap below the other two columns.

Here is some basic example code:

style.css

```<code>.flex-row {
    display: flex;
    flex-direction: row;
    flex-grow: 1;
}

.flex-column {
    display: flex;
    flex-direction: column;
    flex-grow: 1;
    border: 1px solid lightgray;
}

.box {
    display: flex;
    height: 100px;
    width: 300px;
    min-width: 200px;
    flex-shrink: 1;
    border: 1px solid green;
}
</code>```

index.html

```<code><div class="flex-row" style="flex-wrap:wrap">
  <div class="flex-column" style="flex-grow:0">
      Column 1
  </div>

  <div class="flex-column" style="flex-grow:0;width:200px">
    Column 2
  </div>

  <div class="flex-column">
    <div class="flex-row" style="min-width:500px;flex-wrap:wrap">
      <div class="box">Box 1</div>
      <div class="box">Box 2</div>
      <div class="box">Box 3</div>
      <div class="box">Box 4</div>
      <div class="box">Box 5</div>
      <div class="box">Box 6</div>
      <div class="box">Box 7</div>
    </div>
  </div>
</div>
</code>```

(see my plnk here).

The last column contains a flex row with a series of "boxes" (see the example).

The desired effect is that as the screen is resized, the third column will continue to shrink down to the point where all the boxes are in a single column and the boxes have shrunk to their min-width.  At that point, any further reduction in the screen width would cause the third column to wrap below the other two columns and it would then again expand to include as many boxes side by side as possible.

What seems to be happening in practice is that the third column wraps first -- before wrapping the contents it contains.

Here is a visual picture of what I'm want to see happen.

Is this possible to do with flexbox?  If so, what am I doing wrong?

答:
Here is what you desire. What you need to change :

For the flex-column it should be flex: 1; instead of flex-grow:1; and set a min-width to it. This way, it can grow and shrink both.

Using flex-grow:1 limits the container to only grow but not shrink and since you're using the flex-column class in the initial container i.e flex-row you need it to be flexible as the viewport is resized.

/* Styles go here */

.flex-row {
  display: flex;
  flex-direction: flex-row;
  flex-grow: 1;
}

.flex-column {
  display: flex;
  flex-direction: column;
  min-width:100px;
  flex: 1;
  border: 1px solid lightgray;
}

.box {
  display:flex;
  flex-shrink:1;
  border: 1px solid green;
  height:100px;
  width:300px;
  min-width:150px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body>
    <div class="flex-row" style="flex-wrap:wrap">
      <div class="flex-column" style="flex-grow:0">
          Column 1
      </div>

      <div class="flex-column" style="flex-grow:0;width:200px">
        Column 2
      </div>

      <div class="flex-column">
        <div class="flex-row" style="min-width:500px;flex-wrap:wrap">
          <div class="box">Box 1</div>
          <div class="box">Box 2</div>
          <div class="box">Box 3</div>
          <div class="box">Box 4</div>
          <div class="box">Box 5</div>
          <div class="box">Box 6</div>
          <div class="box">Box 7</div>
        </div>
      </div>
    </div>
  </body>

</html></code>```

Title: Nested flex-box wrapping issue

Body:
Edit
Unlike The difference between flex:1 and flex-grow:1 .  While the answer ultimately was the use of flex instead of flex-grow, my question was not the difference between the two but rather how to get nested flex-boxes to wrap appropriately.  For someone struggling with this issue, there would be no way to find that answer on SO without already knowing the issue was the use of flex vs. flex-grow.  If I already knew the issue was the difference between flex and flex-grow, I wouldn't have needed to ask the question.

Edit 2
If this post is going to be flagged as duplicate, it would be better to list it as a duplicate of Nested column flexbox inside row flexbox with wrapping instead of The difference between flex:1 and flex-grow:1.

I have a series of div tags that are defined as display:flex.  They are laid out as a row with 3 columns.  The first two columns are given a width and the third column is allowed to stretch to fill the rest of the space.  The row is also set to wrap so that on smaller screens, the third column will wrap below the other two columns.

Here is some basic example code:

style.css

.flex-row {
    display: flex;
    flex-direction: row;
    flex-grow: 1;
}

.flex-column {
    display: flex;
    flex-direction: column;
    flex-grow: 1;
    border: 1px solid lightgray;
}

.box {
    display: flex;
    height: 100px;
    width: 300px;
    min-width: 200px;
    flex-shrink: 1;
    border: 1px solid green;
}

index.html

      Column 1

    Column 2

Box 1

Box 2

Box 3

Box 4

Box 5

Box 6

Box 7

(see my plnk here).

The last column contains a flex row with a series of "boxes" (see the example).

The desired effect is that as the screen is resized, the third column will continue to shrink down to the point where all the boxes are in a single column and the boxes have shrunk to their min-width.  At that point, any further reduction in the screen width would cause the third column to wrap below the other two columns and it would then again expand to include as many boxes side by side as possible.

What seems to be happening in practice is that the third column wraps first -- before wrapping the contents it contains.

Here is a visual picture of what I'm want to see happen.

Is this possible to do with flexbox?  If so, what am I doing wrong?

Body:
Here is what you desire. What you need to change :

For the flex-column it should be flex: 1; instead of flex-grow:1; and set a min-width to it. This way, it can grow and shrink both.

Using flex-grow:1 limits the container to only grow but not shrink and since you're using the flex-column class in the initial container i.e flex-row you need it to be flexible as the viewport is resized.

/* Styles go here */

.flex-row {
  display: flex;
  flex-direction: flex-row;
  flex-grow: 1;
}

.flex-column {
  display: flex;
  flex-direction: column;
  min-width:100px;
  flex: 1;
  border: 1px solid lightgray;
}

.box {
  display:flex;
  flex-shrink:1;
  border: 1px solid green;
  height:100px;
  width:300px;
  min-width:150px;
}

<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body>
    <div class="flex-row" style="flex-wrap:wrap">
      <div class="flex-column" style="flex-grow:0">
          Column 1
      </div>

      <div class="flex-column" style="flex-grow:0;width:200px">
        Column 2
      </div>

      <div class="flex-column">
        <div class="flex-row" style="min-width:500px;flex-wrap:wrap">
          <div class="box">Box 1</div>
          <div class="box">Box 2</div>
          <div class="box">Box 3</div>
          <div class="box">Box 4</div>
          <div class="box">Box 5</div>
          <div class="box">Box 6</div>
          <div class="box">Box 7</div>
        </div>
      </div>
    </div>
  </body>

</html>


问:
Why does C# disallow readonly local variables?
Having a friendly debate with a co-worker about this.  We have some thoughts about this, but wondering what the SO crowd thinks about this?</p>

答:
A proposal readonly locals and parameters for  was briefly discussed by the C# 7 design team. From C# Design Meeting Notes for Jan 21, 2015:

Parameters and locals can be captured by lambdas and thereby accessed concurrently, but there's no way to protect them from shared-mutual-state issues: they can't be readonly.

In general, most parameters and many locals are never intended to be assigned to after they get their initial value. Allowing readonly on them would express that intent clearly.

One problem is that this feature might be an "attractive nuisance". Whereas the "right thing" to do would nearly always be to make parameters and locals readonly, it would clutter the code significantly to do so.

An idea to partly alleviate this is to allow the combination readonly var on a local variable to be contracted to val or something short like that. More generally we could try to simply think of a shorter keyword than the established readonly to express the readonly-ness.

Discussion continues in the C# Language Design repo. Vote to show your support. https://github.com/dotnet/csharplang/issues/188

OwnerDisplayName: Brian Genisio


问:
WCF error "The X.509 certificate chain building failed" despite trusted root CA
I'm getting the error mentioned in this question:

The X.509 certificate CN=Farm chain building failed. The certificate that was used has a trust chain that cannot be verified. Replace the certificate or change the certificateValidationMode. A certificate chain processed, but terminated in a root certificate which is not trusted by the trust.

What I don't understand why I'm getting this error as the certificate I use for my request to the WCF service is added as shown below:

```<code>client.ClientCredentials.Peer.PeerAuthentication.CertificateValidationMode =
    X509CertificateValidationMode.ChainTrust;
client.ClientCredentials.ClientCertificate.SetCertificate(
    StoreLocation.CurrentUser,
    StoreName.My,
    X509FindType.FindBySerialNumber,
    "MyCertificatesSerialNumber" );
</code>```

The certificate itself is a self-signed certificate in the store shown above. When I click on it to show the certification path, no errors are shown (the root certificate is also a self-signed certificate). The root certificate was manually imported into the trusted root certification authorities.

From the error message I would have expected that there was an error in the certification chain with one of my certificates, but there isn't. Any ideas?

Update

I'm using Internet Explorer 9 as my browser to access the webservice. Programmatically I'm using a C# console application.

答:
I had exactly the same problem - my own trusted root CA which signed another certificate. No errors were shown in the certificate store.

It turned out that having a trusted root CA and a certificate is not sufficient! You also need a certificate revocation list! Take a look at this MSDN Link.

So simply create such a .crl and add it also to the trusted root certificate authorities and everything works fine!

```<code>makecert -crl -n "CN=CARoot" -r -sv CARoot.pvk CARoot.crl
</code>```

or simply turn of the revocation list check:

```<code>...RevocationMode = X509RevocationMode.NoCheck;
</code>```

Body:
I'm getting the error mentioned in this question:

The X.509 certificate CN=Farm chain building failed. The certificate that was used has a trust chain that cannot be verified. Replace the certificate or change the certificateValidationMode. A certificate chain processed, but terminated in a root certificate which is not trusted by the trust.

What I don't understand why I'm getting this error as the certificate I use for my request to the WCF service is added as shown below:

client.ClientCredentials.Peer.PeerAuthentication.CertificateValidationMode =
    X509CertificateValidationMode.ChainTrust;
client.ClientCredentials.ClientCertificate.SetCertificate(
    StoreLocation.CurrentUser,
    StoreName.My,
    X509FindType.FindBySerialNumber,
    "MyCertificatesSerialNumber" );

The certificate itself is a self-signed certificate in the store shown above. When I click on it to show the certification path, no errors are shown (the root certificate is also a self-signed certificate). The root certificate was manually imported into the trusted root certification authorities.

From the error message I would have expected that there was an error in the certification chain with one of my certificates, but there isn't. Any ideas?

Update

I'm using Internet Explorer 9 as my browser to access the webservice. Programmatically I'm using a C# console application.

Body:
I had exactly the same problem - my own trusted root CA which signed another certificate. No errors were shown in the certificate store.

It turned out that having a trusted root CA and a certificate is not sufficient! You also need a certificate revocation list! Take a look at this MSDN Link.

So simply create such a .crl and add it also to the trusted root certificate authorities and everything works fine!

makecert -crl -n "CN=CARoot" -r -sv CARoot.pvk CARoot.crl

or simply turn of the revocation list check:

...RevocationMode = X509RevocationMode.NoCheck;


问:
Check whether or not the current thread is the main thread
Is there any way to check whether or not the current thread is the main thread in Objective-C?

I want to do something like this.

```<code>  - (void)someMethod
  {
    if (IS_THIS_MAIN_THREAD?) {
      NSLog(@"ok. this is main thread.");
    } else {
      NSLog(@"don't call this method from other thread!");
    }
  }
</code>```

答:
```<code>void ensureOnMainQueue(void (^block)(void)) {

    if ([[NSOperationQueue currentQueue] isEqual:[NSOperationQueue mainQueue]]) {

        block();

    } else {

        [[NSOperationQueue mainQueue] addOperationWithBlock:^{

            block();

        }];

    }

}
</code>```

note that i check the operation queue, not the thread, as this is a more safer approach

Body:
Is there any way to check whether or not the current thread is the main thread in Objective-C?

I want to do something like this.

  - (void)someMethod
  {
    if (IS_THIS_MAIN_THREAD?) {
      NSLog(@"ok. this is main thread.");
    } else {
      NSLog(@"don't call this method from other thread!");
    }
  }

Body:
void ensureOnMainQueue(void (^block)(void)) {

    if ([[NSOperationQueue currentQueue] isEqual:[NSOperationQueue mainQueue]]) {

        block();

    } else {

        [[NSOperationQueue mainQueue] addOperationWithBlock:^{

            block();

        }];

    }

}

note that i check the operation queue, not the thread, as this is a more safer approach


问:
Print one more parameter with va_args
I have a function which implements a custom variant of printf.
Does anyone have a clue how I can print out one more parameter with va_list? My format is like "%d some text %s". I need a, to be printed as first parameter.

```<code>void func (int a, char *fmt, ...) {
    va_list ap;
    va_start (ap, fmt);
    // vprintf(stdout, fmt, a, ap) //Can't do like this :(
    vfprintf(fmt, a, ap);          //Or like this :(
    va_end(ap);
}
</code>```

答:
As noted in comments:

Redesign the interface

You would do best to redesign the interface so that the format string only applies to the ... (va_list) arguments; the fixed argument gets treated separately.

Standard reasons for wanting extra arguments are logging things like __FILE__ and __LINE__ (presumably not __func__ if you don't have C99 __VA_ARGS__ support — see below). You would probably do best to remove the option of caller-controlled formatting of those fixed arguments, leaving the fmt to process just the ... arguments.

If you can't redesign the interface

The fact that the %d is part of the format and the int value is not part of the va_list makes life tricky.

If you cannot, or decline to, change the rules for calling the function, you'll need to parse the format, for example separating it into the part up to (but not including) the second %, and use that format with the standalone argument; the remainder of the format is then passed to vprintf(). If you're on a POSIX system and in a multi-threaded program, you might want to use flockfile() and funlockfile() on stdout to ensure that they're treated as a single unit of output despite the multi-threading.

```<code>// Using C99 features
void func(int a, char *fmt, ...)
{
    char *p1 = strchr(fmt, '%');
    if (p1 == 0)
    {
        // No conversion specifications. Not puts(); it adds a newline
        fputs(fmt, stdout);
        return;
    }
    char *p2 = strchr(p1 + 1, '%');
    if (p2 == 0)
    {
        // The user invoked func(1, "iteration %d:\n");?
        printf(fmt, a);
        return;
    }
    int buflen = p2 - fmt + 1;
    char buffer[buflen];
    memmove(buffer, fmt, buflen);
    buffer[buflen-1] = '\0';
    // flockfile(stdout);    // Multi-threading
    printf(buffer, a);
    va_list ap;
    va_start(ap, fmt);
    vprintf(p2, ap);
    va_end(ap);
    // funlockfile(stdout);  // Multi-threading
}
</code>```

The code cheats; it uses a C99 VLA (variable length array) and also interleaved declarations and statements.  In C90, therefore, you'd probably end up using malloc(), or perhaps a fixed size buffer (running risks of overflows), or a hybrid (use a fixed size buffer if the prefix of the format string is small enough to fit, or allocate (and free) if not).

You need to decide on the appropriate error handling strategies.  Note that this isn't bullet-proof code.  Calling func(a, "%% yield is %d; data is [%s]\n", data); throws another spanner in the works.  Also, if you're on POSIX and someone passes "it is %2$s and %1$d things happened", you're in deep trouble.

Yes, I'm on POSIX system. But it is quite old, I am even not able to use approaches with __VA_ARGS__ macros as it appears in C99+ standards.

It's curious that you're on such an old system. However, that simply means you probably won't write code with the n$ notations in it, so it is one less thing to worry about.  The multi-threading issue is less likely to be a problem either.  And you can't use the other C99 features that were shown in my sample code.

You could look at the FFI (foreign function interface) library; I'm not at all sure it will help, though.

Title: Print one more parameter with va_args

Body:
I have a function which implements a custom variant of printf.
Does anyone have a clue how I can print out one more parameter with va_list? My format is like "%d some text %s". I need a, to be printed as first parameter.

void func (int a, char *fmt, ...) {
    va_list ap;
    va_start (ap, fmt);
    // vprintf(stdout, fmt, a, ap) //Can't do like this :(
    vfprintf(fmt, a, ap);          //Or like this :(
    va_end(ap);
}

Body:
As noted in comments:

Redesign the interface

You would do best to redesign the interface so that the format string only applies to the ... (va_list) arguments; the fixed argument gets treated separately.

Standard reasons for wanting extra arguments are logging things like __FILE__ and __LINE__ (presumably not __func__ if you don't have C99 __VA_ARGS__ support — see below). You would probably do best to remove the option of caller-controlled formatting of those fixed arguments, leaving the fmt to process just the ... arguments.

If you can't redesign the interface

The fact that the %d is part of the format and the int value is not part of the va_list makes life tricky.

If you cannot, or decline to, change the rules for calling the function, you'll need to parse the format, for example separating it into the part up to (but not including) the second %, and use that format with the standalone argument; the remainder of the format is then passed to vprintf(). If you're on a POSIX system and in a multi-threaded program, you might want to use flockfile() and funlockfile() on stdout to ensure that they're treated as a single unit of output despite the multi-threading.

// Using C99 features
void func(int a, char *fmt, ...)
{
    char *p1 = strchr(fmt, '%');
    if (p1 == 0)
    {
        // No conversion specifications. Not puts(); it adds a newline
        fputs(fmt, stdout);
        return;
    }
    char *p2 = strchr(p1 + 1, '%');
    if (p2 == 0)
    {
        // The user invoked func(1, "iteration %d:\n");?
        printf(fmt, a);
        return;
    }
    int buflen = p2 - fmt + 1;
    char buffer[buflen];
    memmove(buffer, fmt, buflen);
    buffer[buflen-1] = '\0';
    // flockfile(stdout);    // Multi-threading
    printf(buffer, a);
    va_list ap;
    va_start(ap, fmt);
    vprintf(p2, ap);
    va_end(ap);
    // funlockfile(stdout);  // Multi-threading
}

The code cheats; it uses a C99 VLA (variable length array) and also interleaved declarations and statements.  In C90, therefore, you'd probably end up using malloc(), or perhaps a fixed size buffer (running risks of overflows), or a hybrid (use a fixed size buffer if the prefix of the format string is small enough to fit, or allocate (and free) if not).

You need to decide on the appropriate error handling strategies.  Note that this isn't bullet-proof code.  Calling func(a, "%% yield is %d; data is [%s]\n", data); throws another spanner in the works.  Also, if you're on POSIX and someone passes "it is %2$s and %1$d things happened", you're in deep trouble.

Yes, I'm on POSIX system. But it is quite old, I am even not able to use approaches with __VA_ARGS__ macros as it appears in C99+ standards.

It's curious that you're on such an old system. However, that simply means you probably won't write code with the n$ notations in it, so it is one less thing to worry about.  The multi-threading issue is less likely to be a problem either.  And you can't use the other C99 features that were shown in my sample code.

You could look at the FFI (foreign function interface) library; I'm not at all sure it will help, though.


问:
FirebaseStorage error getting token
I'm getting the following error when trying to get the public downloadUrl from FirebaseStorage. I've set my rules to allow full read and write access, and have no problem storing my data in the storage. However, when I try to get the download url, I get this problem. -

```<code>E/StorageUtil: error getting token java.util.concurrent.ExecutionException: com.google.android.gms.internal.zzbtk: Please sign in before trying to get a token.
</code>```

I've read Firebase getDownloadURL
but was still unable to resolve my issue.

Here's my function-

```<code>    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == 0 && resultCode == RESULT_OK) {

            Uri uri = data.getData();
            final StorageReference filePath = mStorage.child("Photos").child(uri.getLastPathSegment());

            filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {

                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

//                    @SuppressWarnings("VisibleForTests") Uri downloadUri = taskSnapshot.getDownloadUrl();
//                    recognizeImage(downloadUri);

                    filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                        @Override
                        public void onSuccess(Uri uri) {
                            recognizeImage(uri);
                        }
                    });
                }

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

答:
Please add the following lines of code inside the onCreate method of Activity class

```<code>  mAuth = FirebaseAuth.getInstance();
    FirebaseUser user = mAuth.getCurrentUser();
    if (user != null) {

       /* perform your actions here*/

    } else {
        signInAsAnonymous();
    }

 private void signInAnonymously() {
    mAuth.signInAnonymously().addOnSuccessListener(this, new OnSuccessListener<AuthResult>() {
        @Override
        public void onSuccess(AuthResult authResult) {
                        /* perform your actions here*/

        }
    })
            .addOnFailureListener(this, new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    Log.e("MainActivity", "signFailed****** ", exception);
                }
            });
}
</code>```

This is not enough to resolve your issue. Now after adding the above code.

Open Firebase Console> Click on AUTHENTICATION from left menu > SIGN-IN METHOD > ENABLE ANONYMOUS
Now build and run the app if not works let me know

Title: FirebaseStorage error getting token

Body:
I'm getting the following error when trying to get the public downloadUrl from FirebaseStorage. I've set my rules to allow full read and write access, and have no problem storing my data in the storage. However, when I try to get the download url, I get this problem. -

E/StorageUtil: error getting token java.util.concurrent.ExecutionException: com.google.android.gms.internal.zzbtk: Please sign in before trying to get a token.

I've read Firebase getDownloadURL
but was still unable to resolve my issue.

Here's my function-

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == 0 && resultCode == RESULT_OK) {

            Uri uri = data.getData();
            final StorageReference filePath = mStorage.child("Photos").child(uri.getLastPathSegment());

            filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {

                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

//                    @SuppressWarnings("VisibleForTests") Uri downloadUri = taskSnapshot.getDownloadUrl();
//                    recognizeImage(downloadUri);

                    filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                        @Override
                        public void onSuccess(Uri uri) {
                            recognizeImage(uri);
                        }
                    });
                }

            });
        }
    }

Body:
Please add the following lines of code inside the onCreate method of Activity class

  mAuth = FirebaseAuth.getInstance();
    FirebaseUser user = mAuth.getCurrentUser();
    if (user != null) {

       /* perform your actions here*/

    } else {
        signInAsAnonymous();
    }

 private void signInAnonymously() {
    mAuth.signInAnonymously().addOnSuccessListener(this, new OnSuccessListener<AuthResult>() {
        @Override
        public void onSuccess(AuthResult authResult) {
                        /* perform your actions here*/

        }
    })
            .addOnFailureListener(this, new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    Log.e("MainActivity", "signFailed****** ", exception);
                }
            });
}

This is not enough to resolve your issue. Now after adding the above code.

Open Firebase Console> Click on AUTHENTICATION from left menu > SIGN-IN METHOD > ENABLE ANONYMOUS
Now build and run the app if not works let me know


问:
How can I get the combined script result for janusgraph?
Graph is below:

```<code>gremlin> a = graph.addVertex("name", "alice")
gremlin> b = graph.addVertex("name", "bobby")
gremlin> c = graph.addVertex("name", "cindy")
gremlin> d = graph.addVertex("name", "david")
gremlin> e = graph.addVertex("name", "eliza")
gremlin> a.addEdge("rates",b,"tag","ruby","value",9)
gremlin> b.addEdge("rates",c,"tag","ruby","value",8)
gremlin> c.addEdge("rates",d,"tag","ruby","value",7)
gremlin> d.addEdge("rates",e,"tag","ruby","value",6)
gremlin> e.addEdge("rates",a,"tag","java","value",10)
</code>```

I have 3 scripts below:

Script #1

```<code>gremlin> g.V().has('name','alice').
           repeat(out()).
             until(has('name','alice')).
           cyclicPath().
           path().by('name')`
==>[alice,bobby,cindy,david,eliza,alice]
</code>```

Script #2

```<code>gremlin> g.V().has('name','alice').
           repeat(outE().inV()).
             until(has('name','alice')).
           cyclicPath().
           group().
             by('name').
             by(path().unfold().has('value').values('value').fold()).
           next()
==>alice=[9, 8, 7, 6, 10]
</code>```

Script #3

```<code>gremlin> g.V().has('name','alice').
           repeat(outE().inV()).
             until(has('name','alice')).
           cyclicPath().
           group().
             by('name').
             by(path().unfold().has('value').values('value').fold()).
           next().collect { k, v ->
             k + '=' + v.withIndex().collect { Integer it, Integer idx ->
                 return it * (1/(idx + 1))
             }.inject(0.0) { acc,i -> acc + i }
           }
==>alice=18.8333333331
</code>```

My question is, how can I get the result as below listed? Just combine the 3

```<code>alice=[alice,bobby,cindy,david,eliza,alice]=[9, 8, 7, 6, 10]=18.8333333331
</code>```

答: Gremlin code is executed in a Groovy executor, so all Groovy operators are valid here. You can add your results to a list and return the list, i.e. def l = []; l << result1; l << result2; l;.

Body:
Graph is below:

gremlin> a = graph.addVertex("name", "alice")
gremlin> b = graph.addVertex("name", "bobby")
gremlin> c = graph.addVertex("name", "cindy")
gremlin> d = graph.addVertex("name", "david")
gremlin> e = graph.addVertex("name", "eliza")
gremlin> a.addEdge("rates",b,"tag","ruby","value",9)
gremlin> b.addEdge("rates",c,"tag","ruby","value",8)
gremlin> c.addEdge("rates",d,"tag","ruby","value",7)
gremlin> d.addEdge("rates",e,"tag","ruby","value",6)
gremlin> e.addEdge("rates",a,"tag","java","value",10)

I have 3 scripts below:

Script #1

gremlin> g.V().has('name','alice').
           repeat(out()).
             until(has('name','alice')).
           cyclicPath().
           path().by('name')`
==>[alice,bobby,cindy,david,eliza,alice]

Script #2

gremlin> g.V().has('name','alice').
           repeat(outE().inV()).
             until(has('name','alice')).
           cyclicPath().
           group().
             by('name').
             by(path().unfold().has('value').values('value').fold()).
           next()
==>alice=[9, 8, 7, 6, 10]

Script #3

gremlin> g.V().has('name','alice').
           repeat(outE().inV()).
             until(has('name','alice')).
           cyclicPath().
           group().
             by('name').
             by(path().unfold().has('value').values('value').fold()).
           next().collect { k, v ->
             k + '=' + v.withIndex().collect { Integer it, Integer idx ->
                 return it * (1/(idx + 1))
             }.inject(0.0) { acc,i -> acc + i }
           }
==>alice=18.8333333331

My question is, how can I get the result as below listed? Just combine the 3

alice=[alice,bobby,cindy,david,eliza,alice]=[9, 8, 7, 6, 10]=18.8333333331


问:
Count Comparisons for Merge Sort
 I'm trying to count the number of comparisons a merge sort algorithm makes when sorting a list. I've tried multiple ways, but due to the recursion, I am always returned with an answer that is essentially the size of the list. Any suggestion on how to count the number of comparisons this makes? </p>

答:
I can think of two solutions:

less beautiful, but easier to implement.

Declare counter as global variable. You can refer to it in your function by using global counter.

Avoiding global variables

Here:

```<code>mergesort(lefthalf)
mergesort(righthalf)
</code>```

You do not make use of the returned comparison counter. if you make something like:

```<code>count += mergesort(lefthalf)
count += mergesort(righthalf)
</code>```

You will get your comparison count. Remember to initialize your counter with 0 each time you call mergesort()

Title: Count Comparisons for Merge Sort

Body:
I can think of two solutions:

less beautiful, but easier to implement.

Declare counter as global variable. You can refer to it in your function by using global counter.

Avoiding global variables

Here:

mergesort(lefthalf)
mergesort(righthalf)

You do not make use of the returned comparison counter. if you make something like:

count += mergesort(lefthalf)
count += mergesort(righthalf)

You will get your comparison count. Remember to initialize your counter with 0 each time you call mergesort()


问:
files disappear from VS 2015 solution after saving
After installing VS 2015 Pro (14.0.25... with Update 3, licence key has been succesfully added), and creating a new project (especially in Javascript or TypeScript with Ionic 2 templates), when I open a file, (modified it or not), I save it and it disappear from Solution Explorer. Just before it disappear, the icon of the file is updated with a warning icon.

However, if I try to create a C++ project, there is no problem !

In a typescript project, after building, ts files appear again at the end of the build.

All my projects are located in c: disk. I've tried with and without using git.

The two extensions I've installed are : Ionic 2 templates and NPM Task runner. I uninstalled them, but the problem is still here.

When I restart VS, I can see again the files. But the problem is still here.

How to fix it ?

答:
I had same issue on Windows 10.
It seems caused by windows update version 1709.
After I recovered my windows version to 1703, the problem was solved.


问:
How to import zookeeper source code to idea

I get the following error, as the picture show, idea cannot identity any class , cannot find any declaration to go. so, what should i do to make it work

答:
I have imported zookeeper source code in 2 steps:

1. run ant-eclipse command.    This will build eclipse meta files for project.

2. import eclipse project into intellij.


问:
Alternative to Concat on MySql
With the following query:

```<code>"SELECT
'Week' `key`
,concat("KW-" ,WEEK(current_date - INTERVAL 1 WEEK) ) as value"
</code>```

I get :

```<code>Key Value
Week KW-48
</code>```

However when I transform this query to Talend for an automation, it gives me error. Is there any alternative to concat function in Mysql? Thank you.

答:
You don't need an alternative to concat. Your query (which is already a quoted string) contains another double-quoted string inside it. To fix it, simply wrap the KW- bit in single quotes instead of double.

EG:

```<code>"SELECT 'Week' as key, concat('KW-' ,WEEK(current_date - INTERVAL 1 WEEK) ) as value ..."
</code>```

Title: Alternative to Concat on MySql

Body:
With the following query:

"SELECT
'Week' `key`
,concat("KW-" ,WEEK(current_date - INTERVAL 1 WEEK) ) as value"

I get :

Key Value
Week KW-48

However when I transform this query to Talend for an automation, it gives me error. Is there any alternative to concat function in Mysql? Thank you.

Body:
You don't need an alternative to concat. Your query (which is already a quoted string) contains another double-quoted string inside it. To fix it, simply wrap the KW- bit in single quotes instead of double.

EG:

"SELECT 'Week' as key, concat('KW-' ,WEEK(current_date - INTERVAL 1 WEEK) ) as value ..."


问:
SQL Server 2005 - character encoding issue
I'm trying to store this value : țșșțșțșțșîăâ./,șllkoăîâ= into a column in SQL Server.

The column is nvarchar(1000) and the insert statement looks like

```<code>N'țșșțșțșțșîăâ./,șllkoăîâ='
</code>```

But the data inside is still showing up like : ?????????îaâ./,?llkoaîâ=

Any ideas on what I could try ?

EDIT

I just realized that I had changed the datatype in the database , but the linq2sql mapping remained with varchar instead of nvarchar.

That's what was causing the issue - I only saw that after trying the manual insert.

Thanks.

答:
```<code>CREATE TABLE Test (test nvarchar(1000))
INSERT Test (test) VALUES (N'țșșțșțșțșîăâ./,șllkoăîâ=')

-- SSMS query pane = correct results
SELECT * FROM Test
</code>```

Now, right click the table in Object Explorer, "Edit top 200 rows" or "SELECT TOP 1000 rows" gives correct results in SSMS 2008 for me

Next, without N prefix. Data is broken as per your question

```<code>INSERT Test (test) VALUES ('țșșțșțșțșîăâ./,șllkoăîâ=')
SELECT * FROM Test
--gives ?????????îaâ./,?llkoaîâ=
</code>```

So, this shows that SSMS and SQL are behaving exactly as advertised: please show us the exact code (or method) you are using to insert the data

Body:
I'm trying to store this value : țșșțșțșțșîăâ./,șllkoăîâ= into a column in SQL Server.

The column is nvarchar(1000) and the insert statement looks like

N'țșșțșțșțșîăâ./,șllkoăîâ='

But the data inside is still showing up like : ?????????îaâ./,?llkoaîâ=

Any ideas on what I could try ?

EDIT

I just realized that I had changed the datatype in the database , but the linq2sql mapping remained with varchar instead of nvarchar.

That's what was causing the issue - I only saw that after trying the manual insert.

Thanks.

Body:
CREATE TABLE Test (test nvarchar(1000))
INSERT Test (test) VALUES (N'țșșțșțșțșîăâ./,șllkoăîâ=')

-- SSMS query pane = correct results
SELECT * FROM Test

Now, right click the table in Object Explorer, "Edit top 200 rows" or "SELECT TOP 1000 rows" gives correct results in SSMS 2008 for me

Next, without N prefix. Data is broken as per your question

INSERT Test (test) VALUES ('țșșțșțșțșîăâ./,șllkoăîâ=')
SELECT * FROM Test
--gives ?????????îaâ./,?llkoaîâ=

So, this shows that SSMS and SQL are behaving exactly as advertised: please show us the exact code (or method) you are using to insert the data


问:
JPA Transaction - CrudRepository #save(List) not rolled back
I'm using Spring Boot 1.5.9 with spring-boot-starter-data-jpa and Camel 2.20.1.
As input I get an XML file with a sequence of elements, which I unmarshal with JAXB and after that I aggregate them to a list of elements.

For that I defined a Element class where I associate a root element for JAXB and annotated it as a JPA entity.

```<code>@Entity
@Table (name="tblElement", schema="comp")
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Element implements Serializable {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @Column (name="name")
    @XmlElement(required = true)
    private String name;

    public void Element(){}

    //getter and setter methods
    ...
}
</code>```

So my camel route processes a list of entries which I want to store to a MySQL database (version: 5.1.73).

```<code>@Component
public class CompRoute extends RouteBuilder {

    @Autowired
    private ElementDao elementDao;

    @Override
    public void configure() throws Exception {
        DataFormat jaxbDataFormat = new JaxbDataFormat("com.comp.beans");

        from(file:src/test/resources/input)
                .convertBodyTo(byte[].class, "UTF-8")
                .split().tokenizeXML("element")
                .unmarshal(jaxbDataFormat)
                .setProperty("SplitSize", simple("${header.CamelSplitSize}"))

                .aggregate(constant(true), new ArrayListAggregationStrategy())
                    .completionSize(simple("${property.SplitSize}"))

                .bean(elementDao, "insertElementList");
    }
}
</code>```

I'm not so familiar with JPA and the transaction manager, so I configured it according these documentations:

https://spring.io/guides/gs/accessing-data-jpa/

https://docs.spring.io/spring-data/jpa/docs/1.5.0.RELEASE/reference/html/jpa.repositories.html

application.properties

```<code>spring.datasource.url=jdbc:mysql://compserver:3306/comp
spring.datasource.username=user
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
</code>```

JpaConfig.java

```<code>@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackageClasses = CompApplication.class)
class JpaConfig {
    @Autowired
    DataSource dataSource;

    @Bean
    public EntityManagerFactory entityManagerFactory() {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(false);

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);

        String entities = ClassUtils.getPackageName(CompApplication.class);
        factory.setPackagesToScan(entities);
        factory.setDataSource(dataSource);
        factory.afterPropertiesSet();

        return factory.getObject();
    }

    @Bean
    @Qualifier (value = "jpaTransactionManager")
    public PlatformTransactionManager transactionManager() {
        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory());
        return txManager;
    }
}
</code>```

CompApplication.java

```<code>@SpringBootApplication
public class CompApplication {
  public static void main(String[] args) {
          SpringApplication app = new SpringApplication(CompApplication.class);
          app.setBannerMode(Banner.Mode.OFF);
          app.run(args);
  }
</code>```

}

ElementDao.java

```<code>@Service
public class ElementDao {
    @Autowired
    ElementRepository elementRepository;

    @Transactional (transactionManager = "jpaTransactionManager", readOnly = false, propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public void insertElementList(Exchange exchange) {
        if(exchange.getIn().getBody() instanceof List) {
             List<Element> elements= convertListToElementList(exchange.getIn().getBody(List.class));
             if (elements != null) {
                 elementRepository.save(elements);
             }
        }
    }
}
</code>```

ElementRepository.java

```<code>@Repository
public interface ElementRepository extends CrudRepository<Element, Long> {

}
</code>```

But my transaction configuration is not working correct. Because if an error occured e.g. while storing the 5th element, the whole transaction  is not rolled back. It should not insert any elements. But still the first 4 elements are stored and commited.

I don't understand this behavor? How can I set my service #insertElementList transactional that the whole operation is rolled back when an exception occured during database storage?

pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
     <modelVersion>4.0.0</modelVersion>
     <groupId>com.company</groupId>
     <artifactId>company</artifactId>
     <version>0.0.1</version>
     <parent>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-parent</artifactId>
         <version>1.5.9.RELEASE</version>
     </parent>
     <properties>
       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
       <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
       <java.version>1.8</java.version>
       <camel.version>2.20.1</camel.version>
     </properties>
     <dependencies>
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-data-jpa</artifactId>
         </dependency>
         <dependency>
             <groupId>org.apache.camel</groupId>
             <artifactId>camel-spring-boot-starter</artifactId>
             <version>${camel.version}</version>
         </dependency>
         <dependency>
             <groupId>org.apache.camel</groupId>
             <artifactId>camel-jdbc</artifactId>
             <version>${camel.version}</version>
         </dependency>
         <dependency>
             <groupId>mysql</groupId>
             <artifactId>mysql-connector-java</artifactId>
             <version>5.1.45</version>
         </dependency>
         <dependency>
             <groupId>org.apache.camel</groupId>
             <artifactId>camel-jaxb</artifactId>
             <version>2.20.0</version>
         </dependency>
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-artemis</artifactId>
         </dependency>
         <dependency>
             <groupId>org.apache.camel</groupId>
             <artifactId>camel-jms</artifactId>
             <version>${camel.version}</version>
         </dependency>
         <dependency>
             <groupId>com.ibm</groupId>
             <artifactId>com.ibm.mq.allclient</artifactId>
             <version>9.0.0.1</version>
         </dependency>
          <dependency>
             <groupId>net.logstash.logback</groupId>
             <artifactId>logstash-logback-encoder</artifactId>
             <version>4.8</version>
         </dependency>
         <dependency>
             <groupId>ch.qos.logback</groupId>
             <artifactId>logback-core</artifactId>
             <version>1.1.8</version>
         </dependency>
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-test</artifactId>
             <scope>test</scope>
         </dependency>
         <dependency>
             <groupId>commons-io</groupId>
             <artifactId>commons-io</artifactId>
             <version>2.5</version>
         </dependency>
     </dependencies>
 </project>
</code>```

答: I found the solution. The problem was the database and not my configuration. The MySql table was of type MyISAM, which does not support transactions and roll back. So I converted the table to InnoDB and now it works - when the transaction fails, all is rolled back. </p>

Body:
I'm using Spring Boot 1.5.9 with spring-boot-starter-data-jpa and Camel 2.20.1.
As input I get an XML file with a sequence of elements, which I unmarshal with JAXB and after that I aggregate them to a list of elements.

For that I defined a Element class where I associate a root element for JAXB and annotated it as a JPA entity.

@Entity
@Table (name="tblElement", schema="comp")
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Element implements Serializable {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @Column (name="name")
    @XmlElement(required = true)
    private String name;

    public void Element(){}

    //getter and setter methods
    ...
}

So my camel route processes a list of entries which I want to store to a MySQL database (version: 5.1.73).

@Component
public class CompRoute extends RouteBuilder {

    @Autowired
    private ElementDao elementDao;

    @Override
    public void configure() throws Exception {
        DataFormat jaxbDataFormat = new JaxbDataFormat("com.comp.beans");

        from(file:src/test/resources/input)
                .convertBodyTo(byte[].class, "UTF-8")
                .split().tokenizeXML("element")
                .unmarshal(jaxbDataFormat)
                .setProperty("SplitSize", simple("${header.CamelSplitSize}"))

                .aggregate(constant(true), new ArrayListAggregationStrategy())
                    .completionSize(simple("${property.SplitSize}"))

                .bean(elementDao, "insertElementList");
    }
}

I'm not so familiar with JPA and the transaction manager, so I configured it according these documentations:

https://spring.io/guides/gs/accessing-data-jpa/

https://docs.spring.io/spring-data/jpa/docs/1.5.0.RELEASE/reference/html/jpa.repositories.html

application.properties

spring.datasource.url=jdbc:mysql://compserver:3306/comp
spring.datasource.username=user
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

JpaConfig.java

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackageClasses = CompApplication.class)
class JpaConfig {
    @Autowired
    DataSource dataSource;

    @Bean
    public EntityManagerFactory entityManagerFactory() {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(false);

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);

        String entities = ClassUtils.getPackageName(CompApplication.class);
        factory.setPackagesToScan(entities);
        factory.setDataSource(dataSource);
        factory.afterPropertiesSet();

        return factory.getObject();
    }

    @Bean
    @Qualifier (value = "jpaTransactionManager")
    public PlatformTransactionManager transactionManager() {
        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory());
        return txManager;
    }
}

CompApplication.java

@SpringBootApplication
public class CompApplication {
  public static void main(String[] args) {
          SpringApplication app = new SpringApplication(CompApplication.class);
          app.setBannerMode(Banner.Mode.OFF);
          app.run(args);
  }

}

ElementDao.java

@Service
public class ElementDao {
    @Autowired
    ElementRepository elementRepository;

    @Transactional (transactionManager = "jpaTransactionManager", readOnly = false, propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public void insertElementList(Exchange exchange) {
        if(exchange.getIn().getBody() instanceof List) {
             List<Element> elements= convertListToElementList(exchange.getIn().getBody(List.class));
             if (elements != null) {
                 elementRepository.save(elements);
             }
        }
    }
}

ElementRepository.java

@Repository
public interface ElementRepository extends CrudRepository<Element, Long> {

}

But my transaction configuration is not working correct. Because if an error occured e.g. while storing the 5th element, the whole transaction  is not rolled back. It should not insert any elements. But still the first 4 elements are stored and commited.

I don't understand this behavor? How can I set my service #insertElementList transactional that the whole operation is rolled back when an exception occured during database storage?

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
     <modelVersion>4.0.0</modelVersion>
     <groupId>com.company</groupId>
     <artifactId>company</artifactId>
     <version>0.0.1</version>
     <parent>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-parent</artifactId>
         <version>1.5.9.RELEASE</version>
     </parent>
     <properties>
       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
       <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
       <java.version>1.8</java.version>
       <camel.version>2.20.1</camel.version>
     </properties>
     <dependencies>
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-data-jpa</artifactId>
         </dependency>
         <dependency>
             <groupId>org.apache.camel</groupId>
             <artifactId>camel-spring-boot-starter</artifactId>
             <version>${camel.version}</version>
         </dependency>
         <dependency>
             <groupId>org.apache.camel</groupId>
             <artifactId>camel-jdbc</artifactId>
             <version>${camel.version}</version>
         </dependency>
         <dependency>
             <groupId>mysql</groupId>
             <artifactId>mysql-connector-java</artifactId>
             <version>5.1.45</version>
         </dependency>
         <dependency>
             <groupId>org.apache.camel</groupId>
             <artifactId>camel-jaxb</artifactId>
             <version>2.20.0</version>
         </dependency>
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-artemis</artifactId>
         </dependency>
         <dependency>
             <groupId>org.apache.camel</groupId>
             <artifactId>camel-jms</artifactId>
             <version>${camel.version}</version>
         </dependency>
         <dependency>
             <groupId>com.ibm</groupId>
             <artifactId>com.ibm.mq.allclient</artifactId>
             <version>9.0.0.1</version>
         </dependency>
          <dependency>
             <groupId>net.logstash.logback</groupId>
             <artifactId>logstash-logback-encoder</artifactId>
             <version>4.8</version>
         </dependency>
         <dependency>
             <groupId>ch.qos.logback</groupId>
             <artifactId>logback-core</artifactId>
             <version>1.1.8</version>
         </dependency>
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-test</artifactId>
             <scope>test</scope>
         </dependency>
         <dependency>
             <groupId>commons-io</groupId>
             <artifactId>commons-io</artifactId>
             <version>2.5</version>
         </dependency>
     </dependencies>
 </project>


问:
Eigen vectors in python giving seemingly random element-wise signs
I'm running the following code:

```<code>import numpy as np
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt

N = 100
t = 1

a1 = np.full((N-1,), -t)
a2 = np.full((N,), 2*t)
Hamiltonian = np.diag(a1, -1) +  np.diag(a2) + np.diag(a1, 1)

eval, evec = np.linalg.eig(Hamiltonian)
idx = eval.argsort()[::-1]
eval, evec = eval[idx], evec[:,idx]

wave2 = evec[2] / np.sum(abs(evec[2]))
prob2 = evec[2]**2 / np.sum(evec[2]**2)

_ = plt.plot(wave2)
_ = plt.plot(prob2)
plt.show()
</code>```

And the plot that comes out is this:

But I'd expect the blue line to be a sinoid as well. This has got me confused and I can't find what's causing the sudden sign changes. Plotting the function absolutely shows that the values associated with each x are fine, but the signs are screwed up.

Any ideas on what might cause this or how to solve it?

答:
Here's a modified version of your script that does what you expected.  The changes are:

Corrected the indexing for the eigenvectors; they are the columns of evec.

Use np.linalg.eigh instead of np.linalg.eig.  This isn't strictly necessary, but you might as well use the more efficient code.

Don't reverse the order of the sorted eigenvalues.  I keep the eigenvalues sorted from lowest to highest.  Because eigh returns the eigenvalues in ascending order, I just commented out the code that sorts the eigenvalues.

(Only the first change is a required correction.)

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

N = 100
t = 1

a1 = np.full((N-1,), -t)
a2 = np.full((N,), 2*t)
Hamiltonian = np.diag(a1, -1) +  np.diag(a2) + np.diag(a1, 1)

eval, evec = np.linalg.eigh(Hamiltonian)
#idx = eval.argsort()[::-1]
#eval, evec = eval[idx], evec[:,idx]

k = 2
wave2 = evec[:, k] / np.sum(abs(evec[:, k]))
prob2 = evec[:, k]**2 / np.sum(evec[:, k]**2)

_ = plt.plot(wave2)
_ = plt.plot(prob2)
plt.show()
</code>```

The plot:

Body:
I'm running the following code:

import numpy as np
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt

N = 100
t = 1

a1 = np.full((N-1,), -t)
a2 = np.full((N,), 2*t)
Hamiltonian = np.diag(a1, -1) +  np.diag(a2) + np.diag(a1, 1)

eval, evec = np.linalg.eig(Hamiltonian)
idx = eval.argsort()[::-1]
eval, evec = eval[idx], evec[:,idx]

wave2 = evec[2] / np.sum(abs(evec[2]))
prob2 = evec[2]**2 / np.sum(evec[2]**2)

_ = plt.plot(wave2)
_ = plt.plot(prob2)
plt.show()

And the plot that comes out is this:

But I'd expect the blue line to be a sinoid as well. This has got me confused and I can't find what's causing the sudden sign changes. Plotting the function absolutely shows that the values associated with each x are fine, but the signs are screwed up.

Any ideas on what might cause this or how to solve it?

Body:
Here's a modified version of your script that does what you expected.  The changes are:

Corrected the indexing for the eigenvectors; they are the columns of evec.

Use np.linalg.eigh instead of np.linalg.eig.  This isn't strictly necessary, but you might as well use the more efficient code.

Don't reverse the order of the sorted eigenvalues.  I keep the eigenvalues sorted from lowest to highest.  Because eigh returns the eigenvalues in ascending order, I just commented out the code that sorts the eigenvalues.

(Only the first change is a required correction.)

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

N = 100
t = 1

a1 = np.full((N-1,), -t)
a2 = np.full((N,), 2*t)
Hamiltonian = np.diag(a1, -1) +  np.diag(a2) + np.diag(a1, 1)

eval, evec = np.linalg.eigh(Hamiltonian)
#idx = eval.argsort()[::-1]
#eval, evec = eval[idx], evec[:,idx]

k = 2
wave2 = evec[:, k] / np.sum(abs(evec[:, k]))
prob2 = evec[:, k]**2 / np.sum(evec[:, k]**2)

_ = plt.plot(wave2)
_ = plt.plot(prob2)
plt.show()

The plot: