问:
Parse a HTML table using Ruby, Nokogiri omitting the column headers
I have trouble parsing a HTML table using Nokogiri and Ruby. My HTML table structure looks like this

```<code><table>
<tbody>
    <tr>
       <td>Firstname</td>
       <td>Lastname</td>
       <td>Middle</td>
    </tr>
    <tr>
       <td>ding</td>
       <td>dong</td>
       <td>ling</td>
    </tr>
    ....
    ....
    .... {more tr's and td's with similar data exists.}
    ....
    ....
    ....
    ....
    ....
 </tbody>
 </table>
</code>```

In the above HTML table I would like to entirely remove the first  and corresponding  elements, so remove Firstname, Lastname and Middle i.e., I want to start stripping the text only from the second . So this way I get only the contents of the table from the second  or tr[2] and no column headers.

Can someone please provide me a code as to how to do this.

Thanks.

答:
Since Nokogiri does support :has CSS pseudo-class you can get heading row with

```<code>@doc.at_css('table#table_id').css('tr:has(th)')
</code>```

and since it does supports :not CSS pseudo-class as well, you can get other rows with

```<code>@doc.at_css('table#table_id').css('tr:not(:has(th))')
</code>```

respectively. Depending on your preferences you might like to avoid negation and just use css('tr:has(td)').

Body:
I have trouble parsing a HTML table using Nokogiri and Ruby. My HTML table structure looks like this

       Firstname
       Lastname
       Middle

       ding
       dong
       ling

    ....
    ....
    .... {more tr's and td's with similar data exists.}
    ....
    ....
    ....
    ....
    ....

In the above HTML table I would like to entirely remove the first  and corresponding  elements, so remove Firstname, Lastname and Middle i.e., I want to start stripping the text only from the second . So this way I get only the contents of the table from the second  or tr[2] and no column headers.

Can someone please provide me a code as to how to do this.

Thanks.

Body:
Since Nokogiri does support :has CSS pseudo-class you can get heading row with

@doc.at_css('table#table_id').css('tr:has(th)')

and since it does supports :not CSS pseudo-class as well, you can get other rows with

@doc.at_css('table#table_id').css('tr:not(:has(th))')

respectively. Depending on your preferences you might like to avoid negation and just use css('tr:has(td)').


来源: stackexchange

问:
What are the Python equivalents to Ruby's bundler / Perl's carton?
I know about virtualenv and pip. But these are a bit different from bundler/carton.

For instance:

pip writes the absolute path to shebang or activate script

pip doesn't have the exec sub command (bundle exec bar)

virtualenv copies the Python interpreter to a local directory

Does every Python developer use virtualenv/pip? Are there other package management tools for Python?

答:
I wrote one — https://github.com/Deepwalker/pundler .
On PIP its pundle, name was already taken.

It uses requirements(_\w+)?.txt files as your desired dependencies and creates frozen(_\w+)?.txt files with frozen versions.

About (_\w+)? thing — this is envs. You can create requirements_test.txt and then use PUNDLEENV=test to use this deps in your run with requirements.txt ones alongside.

And about virtualenv – you need not one, its what pundle takes from bundler in first head.

ContentLicense: CC BY-SA 3.0


问:
File upload using ajax and JavaScript function
Need a big favor! I'm trying to send uploaded file using JavaScript & Ajax, however not getting any success.

I want that when I upload the file, it will call the function myFunction(), and send the file to the PHP path(ajax.php) I've set.

Below is the code I've so far.

```<code><script>
   function myFunction() {
      var x = document.getElementById("up");
      $.ajax({
         type: 'GET',
         url: 'ajax.php',
         data: {},
         beforeSend: function() {},
         success: function(data) {
            alert(data);
         }
      });
   }
</script>
<input type="file" name="images" id="up" onchange="myFunction()" />
</code>```

答:
When you upload a field with ajax, you have to create a formData object, then you can change the attribute data:
Try this:

```<code><script>
    function myFunction() {
        var form = $('form')[0];
        var formData = new FormData(form);

        $.ajax({
            type: 'POST',
            url: 'ajax.php',
            data: formData,
            contentType: false,
            processData: false,
            success: function(data) {
                alert(data);
            }
        });

    }
</script>

<form method="POST">
    <input type="file" name="images" id="up" onchange="myFunction()" />
</form>
</code>```

Body:
Need a big favor! I'm trying to send uploaded file using JavaScript & Ajax, however not getting any success.

I want that when I upload the file, it will call the function myFunction(), and send the file to the PHP path(ajax.php) I've set.

Below is the code I've so far.

<input type="file" name="images" id="up" onchange="myFunction()" />

Body:
When you upload a field with ajax, you have to create a formData object, then you can change the attribute data:
Try this:

<script>
    function myFunction() {
        var form = $('form')[0];
        var formData = new FormData(form);

        $.ajax({
            type: 'POST',
            url: 'ajax.php',
            data: formData,
            contentType: false,
            processData: false,
            success: function(data) {
                alert(data);
            }
        });

    }
</script>

<form method="POST">
    <input type="file" name="images" id="up" onchange="myFunction()" />
</form>


问:
How to remove in bootstrap active class from nav on index page?
I use bootstrap for menu in header. And on default, first link is active(li have class 'active') on index.php, but I want to make no active link on index.php.

How to disable active li only on index page, may be change bootstrap.js or something else?

答: Without further input from you, you can simply remove the class by editing out the HTML.


问:
checking database for necessary updates using dateDiff
hey stackoverflowers. im having a few problems with the code i have written to check my database on refresh if all record dates on the database are between the specified $min and $max values. if not then the record will be updated. this is what i have done so far.

```<code>// check database for necessary updates

    $update = mysql_query("SELECT * FROM rent");

    while($row = mysql_fetch_array( $update )) {

    $datetime_lower   = DateTime::createFromFormat('d/m/Y', $min);
    $datetime_upper   = DateTime::createFromFormat('d/m/Y', $max);
    $datetime_compare = DateTime::createFromFormat('d/m/Y g:i a', $row_update['pDate']);

    $diff_lower = $datetime_lower->diff($datetime_compare);
    $diff_upper = $datetime_upper->diff($datetime_compare);

    if ($datetime_lower < $datetime_compare && $datetime_upper > $datetime_compare) {
        // date is between min and max, do nothing
    } else {
        // date is not between min and max, update cell colour
$result = mysql_query("UPDATE rent SET colour='F0F0F0' WHERE $datetime_lower < $pDate && $datetime_upper > $pDate") or die(mysql_error());
    }
    }
</code>```

the logic behind it seems rather rational but whenever i try to run the code i get the error message:

```<code>Warning: DateTime::diff() expects parameter 1 to be DateTime, boolean given in C:\xampp\htdocs\keypad\main.php on line 41

Warning: DateTime::diff() expects parameter 1 to be DateTime, boolean given in C:\xampp\htdocs\keypad\main.php on line 42
</code>```

any idea whats going on?

答:
I think your approach is not optimized, instead of compare the different from php->mysql->php, you can issue a query to directly update to mysql, like

```<code>update rent set colour='F0F0F0' WHERE pDate>='$min' and pDate<='$max';
</code>```

ContentLicense: CC BY-SA 2.5

Body:
hey stackoverflowers. im having a few problems with the code i have written to check my database on refresh if all record dates on the database are between the specified $min and $max values. if not then the record will be updated. this is what i have done so far.

// check database for necessary updates

    $update = mysql_query("SELECT * FROM rent");

    while($row = mysql_fetch_array( $update )) {

    $datetime_lower   = DateTime::createFromFormat('d/m/Y', $min);
    $datetime_upper   = DateTime::createFromFormat('d/m/Y', $max);
    $datetime_compare = DateTime::createFromFormat('d/m/Y g:i a', $row_update['pDate']);

    $diff_lower = $datetime_lower->diff($datetime_compare);
    $diff_upper = $datetime_upper->diff($datetime_compare);

    if ($datetime_lower < $datetime_compare && $datetime_upper > $datetime_compare) {
        // date is between min and max, do nothing
    } else {
        // date is not between min and max, update cell colour
$result = mysql_query("UPDATE rent SET colour='F0F0F0' WHERE $datetime_lower < $pDate && $datetime_upper > $pDate") or die(mysql_error());
    }
    }

the logic behind it seems rather rational but whenever i try to run the code i get the error message:

Warning: DateTime::diff() expects parameter 1 to be DateTime, boolean given in C:\xampp\htdocs\keypad\main.php on line 41

Warning: DateTime::diff() expects parameter 1 to be DateTime, boolean given in C:\xampp\htdocs\keypad\main.php on line 42

any idea whats going on?

Body:
I think your approach is not optimized, instead of compare the different from php->mysql->php, you can issue a query to directly update to mysql, like

update rent set colour='F0F0F0' WHERE pDate>='$min' and pDate<='$max';


问:
Get a database reference in the new Firebase 4.0 release
In Firebase 3.0+ the method to get the database reference was as such:

```<code>var ref: FIRDatabaseReference!

ref = FIRDatabase.database().reference()

ref.child("rooms").observeSingleEventOfType(.Value, withBlock: { (snapshot) in

    if snapshot.hasChild("room1"){

        print("true rooms exist")

    }else{

        print("false room doesn't exist")
    }

})
</code>```

In Firebase 4.0 the naming convention changed but I can't get it to work!?

```<code>var ref: DatabaseReference!
ref = Database.database().reference()
</code>```

Has anyone else encountered this?

The swift compiler is suggesting removing the () from the lowercase database function call

if you remove it, it then throws the error message:

Database has no member reference

So how do you get the reference then!?

Pod file:

```<code>pod 'Firebase/Core'
pod 'Firebase/Database'
</code>```

答:
For Firebase 4.0, there is a change

Removing the FIR prefix across names for all constants, protocols,
classes, enums, and type definitions.

Renaming FIRApp to FirebaseApp.

Renaming FIROptions to FirebaseOptions.

Link: https://firebase.google.com/docs/reference/ios/naming-migration-guide

Body:
In Firebase 3.0+ the method to get the database reference was as such:

var ref: FIRDatabaseReference!

ref = FIRDatabase.database().reference()

ref.child("rooms").observeSingleEventOfType(.Value, withBlock: { (snapshot) in

    if snapshot.hasChild("room1"){

        print("true rooms exist")

    }else{

        print("false room doesn't exist")
    }

})

In Firebase 4.0 the naming convention changed but I can't get it to work!?

var ref: DatabaseReference!
ref = Database.database().reference()

Has anyone else encountered this?

The swift compiler is suggesting removing the () from the lowercase database function call

if you remove it, it then throws the error message:

Database has no member reference

So how do you get the reference then!?

Pod file:

pod 'Firebase/Core'
pod 'Firebase/Database'


问:
Javascript Regex - get div IDs from string html
Consider the following code:

```<code>const content = "<div id='x'><h2>Lorem Ipsum</h2> <p>is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p></div>"

let ids = content.match(/id='(.*?)'/g).map((val) => {
    return val.replace(/id='/g,'');
})
</code>```

And when I do console.log(ids) - I get the output like this 'x\'' but I need only 'x'. I'm wondering how to achive that result, I've tried by randomly changing regex symbols, because I don't know regex at all - and nothing seems to be working.

No jquery please. Thank you in advance

答:
const content = "

Lorem Ipsum

is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s

"

let ids = content.match(/id='(.*?)'/g).map((val) => {
    return val.replace(/id='/g,'').replace("'",'');
})

console.log(ids)```

Body:
Consider the following code:

const content = "

Lorem Ipsum

is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s

"

let ids = content.match(/id='(.*?)'/g).map((val) => {
    return val.replace(/id='/g,'');
})

And when I do console.log(ids) - I get the output like this 'x\'' but I need only 'x'. I'm wondering how to achive that result, I've tried by randomly changing regex symbols, because I don't know regex at all - and nothing seems to be working.

No jquery please. Thank you in advance

Body:
const content = "<div id='x'><h2>Lorem Ipsum</h2> <p>is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p></div>"

let ids = content.match(/id='(.*?)'/g).map((val) => {
    return val.replace(/id='/g,'').replace("'",'');
})

console.log(ids)


问:
c# a namespace cannot directly contain members such as fields or methods
Can anyone tell what is wrong here ?
I just create one folder call Models and add new class BaseEntity, and I get error.
Till now I didn't get this error when I add new class...

答:
Namespaces cannot start with numbers.

You will have to change the name of your model 3DBook and then change the reference


问:
iPhone making a map like in Fire Emblem
I want to make a RPG where you engage foes utilizing a map/grid. I'm just trying to figure out how this could be done in Objective-C... also, I do not want to use OpenGL; no tilemaps. :P</p>

答:
That game looks like it's using OpenGL ES. But, you could achieve somehting similar with a combination of isometric projection maps and A* pathfinding (and yes, lots and lots of code). Here's some links to research on those subjects. Beyond that, there's not really a definitive answer because there's many ways of doing this.

Isometric projection

A* Pathfinding for Beginners

Title: iPhone making a map like in Fire Emblem

ContentLicense: CC BY-SA 4.0


问:
Unit test case for If condition
I have a  method IsValid:

```<code>public void IsValid(string applicationNumber)
{
    if (!applicationNumber.Length.Equals(15))
    {
        throw new ApplicationException(string.Format("De lengte van de rubriek: aanvraagnummer [001.], met waarde {0}, is niet valide.", applicationNumber));
    } else {
        applicationNumberExpression = "qwerty123456789";

        if (!applicationNumberExpression.IsMatch(applicationNumber))
        {
            throw new ApplicationException(string.Format("Het aanvraagnummer [001.] met waarde {0} is niet conform de voorgeschreven structuur.", applicationNumber));
        }
    }
}
</code>```

I try to write a unit test case for isvalid, but i get some errors.

```<code>public void IsValidTestApplicationNumber()
{
    var appno1 = new MFA.Convana.BusinessLayer.ObjectModel.ApplicationNumber();

    MFA.Convana.BusinessLayer.ObjectModel.ApplicationNumber appno = new
    MFA.Convana.BusinessLayer.ObjectStore.ApplicationNumber();

    string applicationNumber = "qwerty123456789";

    Assert.AreSame(appno.IsValid(applicationNumber);//error in thisline "no overload for method takes one argument"
}
</code>```

答:
Your primary mistake is attempting to assert on a function that returns void. This isn't possible.

You have two options:

a) Leave IsValid as returning void, and replace:

```<code>Assert.AreSame(appno.IsValid(applicationNumber);
</code>```

with:

```<code>appno.IsValid(applicationNumber);
</code>```

OR

b) Change IsValid to return a bool. To do this, change:

```<code>Assert.AreSame(appno.IsValid(applicationNumber);
</code>```

to either:

```<code>Assert.IsTrue(appno.IsValid(applicationNumber));
</code>```

(depending on what you want the test to do)

Also, change:

```<code>public void IsValid(string applicationNumber)
{
    if (!applicationNumber.Length.Equals(15))
    {
        throw new ApplicationException(string.Format("De lengte van de rubriek: aanvraagnummer [001.], met waarde {0}, is niet valide.", applicationNumber));
    } else {
        applicationNumberExpression = "qwerty123456789";

        if (!applicationNumberExpression.IsMatch(applicationNumber))
        {
            throw new ApplicationException(string.Format("Het aanvraagnummer [001.] met waarde {0} is niet conform de voorgeschreven structuur.", applicationNumber));
        }
    }
}
</code>```

to:

```<code>public bool IsValid(string applicationNumber)
{
    if (!applicationNumber.Length.Equals(15))
    {
        throw new ApplicationException(string.Format("De lengte van de rubriek: aanvraagnummer [001.], met waarde {0}, is niet valide.", applicationNumber));
    } else {
        applicationNumberExpression = "qwerty123456789";

        if (!applicationNumberExpression.IsMatch(applicationNumber))
        {
            throw new ApplicationException(string.Format("Het aanvraagnummer [001.] met waarde {0} is niet conform de voorgeschreven structuur.", applicationNumber));
        }
    }
    return true;
}
</code>```

Title: Unit test case for If condition

Body:
I have a  method IsValid:

public void IsValid(string applicationNumber)
{
    if (!applicationNumber.Length.Equals(15))
    {
        throw new ApplicationException(string.Format("De lengte van de rubriek: aanvraagnummer [001.], met waarde {0}, is niet valide.", applicationNumber));
    } else {
        applicationNumberExpression = "qwerty123456789";

        if (!applicationNumberExpression.IsMatch(applicationNumber))
        {
            throw new ApplicationException(string.Format("Het aanvraagnummer [001.] met waarde {0} is niet conform de voorgeschreven structuur.", applicationNumber));
        }
    }
}

I try to write a unit test case for isvalid, but i get some errors.

public void IsValidTestApplicationNumber()
{
    var appno1 = new MFA.Convana.BusinessLayer.ObjectModel.ApplicationNumber();

    MFA.Convana.BusinessLayer.ObjectModel.ApplicationNumber appno = new
    MFA.Convana.BusinessLayer.ObjectStore.ApplicationNumber();

    string applicationNumber = "qwerty123456789";

    Assert.AreSame(appno.IsValid(applicationNumber);//error in thisline "no overload for method takes one argument"
}

Body:
Your primary mistake is attempting to assert on a function that returns void. This isn't possible.

You have two options:

a) Leave IsValid as returning void, and replace:

Assert.AreSame(appno.IsValid(applicationNumber);

with:

appno.IsValid(applicationNumber);

OR

b) Change IsValid to return a bool. To do this, change:

Assert.AreSame(appno.IsValid(applicationNumber);

to either:

Assert.IsTrue(appno.IsValid(applicationNumber));

(depending on what you want the test to do)

Also, change:

public void IsValid(string applicationNumber)
{
    if (!applicationNumber.Length.Equals(15))
    {
        throw new ApplicationException(string.Format("De lengte van de rubriek: aanvraagnummer [001.], met waarde {0}, is niet valide.", applicationNumber));
    } else {
        applicationNumberExpression = "qwerty123456789";

        if (!applicationNumberExpression.IsMatch(applicationNumber))
        {
            throw new ApplicationException(string.Format("Het aanvraagnummer [001.] met waarde {0} is niet conform de voorgeschreven structuur.", applicationNumber));
        }
    }
}

to:

public bool IsValid(string applicationNumber)
{
    if (!applicationNumber.Length.Equals(15))
    {
        throw new ApplicationException(string.Format("De lengte van de rubriek: aanvraagnummer [001.], met waarde {0}, is niet valide.", applicationNumber));
    } else {
        applicationNumberExpression = "qwerty123456789";

        if (!applicationNumberExpression.IsMatch(applicationNumber))
        {
            throw new ApplicationException(string.Format("Het aanvraagnummer [001.] met waarde {0} is niet conform de voorgeschreven structuur.", applicationNumber));
        }
    }
    return true;
}


问:
Preventing SQL Injection/Good Ruby method
What is a good method in Ruby to prevent SQL Injection?</p>

答:
This thread references:

http://www.ruby-forum.com/topic/90258#new

http://www.ruby-forum.com/topic/82349#143790

ActiveRecord's find() method has built in ways to avoid SQL injection by
using the format

```<code> >  :conditions => [ "user_name = ?", user_name]
</code>```

Is there any such system for escaping injection in order?  It seems to
only take a string and feed it to the SQL statement.  This causes a
vulnerability when using params to set : order as in this function:

```<code>     def list
sort_by = params[:sort_by]
@book_pages, @books = paginate :books,
                               :order => sort_by,
                               :per_page => 10
    end
</code>```

We've tried a few methods to sanitize sort_by such as order => ['?',
sort_by] but it just passes that to the SQL statement like a flattened
array.  The 'escaping magic' does not work for order.  Should I use
gsub! to sanitize params[:sort_by]?

Body:
This thread references:

http://www.ruby-forum.com/topic/90258#new

http://www.ruby-forum.com/topic/82349#143790

ActiveRecord's find() method has built in ways to avoid SQL injection by
using the format

 >  :conditions => [ "user_name = ?", user_name]

Is there any such system for escaping injection in order?  It seems to
only take a string and feed it to the SQL statement.  This causes a
vulnerability when using params to set : order as in this function:

     def list
sort_by = params[:sort_by]
@book_pages, @books = paginate :books,
                               :order => sort_by,
                               :per_page => 10
    end

We've tried a few methods to sanitize sort_by such as order => ['?',
sort_by] but it just passes that to the SQL statement like a flattened
array.  The 'escaping magic' does not work for order.  Should I use
gsub! to sanitize params[:sort_by]?


问:
unsupported pseudo: in-viewport
I'm following this guide to detect when my video element comes in viewport then do "x", but keep getting the title error. Not sure if because Im using wordpress with gulp and piling.js

My page uses Piling and I have a video section, when I scroll to that "stack", I want the video to start play but it starts to play on page load.

```<code>// inside document.ready()

 $('video').each(function(){
    if ($(this).is(":in-viewport")) {
        $(this)[0].play();
    } else {
        $(this)[0].pause();
    }
})
</code>```

Uncaught Error: Syntax error, unrecognized expression: unsupported pseudo: in-viewport

```<code><div id='<ID-CHANGES-INSIDE-LOOP>' class='image-block'>
  <video autoplay>
    <source class='video' src='movie.mp4' type='video/mp4'>
  </video>
</div>
</code>```

Is using Piling making this difficult to work?

答:
That pseudo selector needs its plugin to work (it's not part of jQuery selectors), but nowadays you can easily check if an element is in the viewport using .getBoundingClientRect(). Here's the method I use:

```<code>/**
 * Check if an element is in the visible viewport
 * @param {jQuery|HTMLElement} el
 * @return boolean
 */
var IsInViewport = function(el) {
    if (typeof jQuery === "function" && el instanceof jQuery) el = el[0];
    var rect = el.getBoundingClientRect();
    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
        rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
};

// example
if( IsInViewport($('#myvideo')) ) { /* do stuff.. */ }
</code>```

Also, depending on your needs, you could use :visible selector (https://api.jquery.com/visible-selector/).

Title: unsupported pseudo: in-viewport

Body:
I'm following this guide to detect when my video element comes in viewport then do "x", but keep getting the title error. Not sure if because Im using wordpress with gulp and piling.js

My page uses Piling and I have a video section, when I scroll to that "stack", I want the video to start play but it starts to play on page load.

// inside document.ready()

 $('video').each(function(){
    if ($(this).is(":in-viewport")) {
        $(this)[0].play();
    } else {
        $(this)[0].pause();
    }
})

Uncaught Error: Syntax error, unrecognized expression: unsupported pseudo: in-viewport

<div id='<ID-CHANGES-INSIDE-LOOP>' class='image-block'>
  <video autoplay>
    <source class='video' src='movie.mp4' type='video/mp4'>
  </video>

Is using Piling making this difficult to work?

Body:
That pseudo selector needs its plugin to work (it's not part of jQuery selectors), but nowadays you can easily check if an element is in the viewport using .getBoundingClientRect(). Here's the method I use:

/**
 * Check if an element is in the visible viewport
 * @param {jQuery|HTMLElement} el
 * @return boolean
 */
var IsInViewport = function(el) {
    if (typeof jQuery === "function" && el instanceof jQuery) el = el[0];
    var rect = el.getBoundingClientRect();
    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
        rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
};

// example
if( IsInViewport($('#myvideo')) ) { /* do stuff.. */ }

Also, depending on your needs, you could use :visible selector (https://api.jquery.com/visible-selector/).


问:
R:rank of augmented matrix
Is there a way to get rank of augmented matrix. I want to test for dependence with this theorem:

https://en.wikipedia.org/wiki/Rouch%C3%A9%E2%80%93Capelli_theorem

I tried a bit wiht qr() function, but with no luck.

Title: R:rank of augmented matrix

Body:
A <- matrix(1:4, 2)
A
#      [,1] [,2]
# [1,]    1    3
# [2,]    2    4

b <- matrix(5:6, 2)
b
#      [,1]
# [1,]    5
# [2,]    6

qr(A)$rank
# [1] 2

aug <- cbind(A, b)
aug
#      [,1] [,2] [,3]
# [1,]    1    3    5
# [2,]    2    4    6

qr(aug)$rank
# [1] 2


问:
Log4Net and Application Insights-no data is coming through
I'm using Log4Net in my my C# console application and want the logged events to appear in Application Insights as well.

I've added Application Insights as well as the Application Insights Log4Net Appender.

I've followed the instructions here: https://jan-v.nl/post/using-application-insights-in-your-log4net-application with no luck.

Log4Net is logging fine. However, when I go to the Application Insights dashboard, I see this: "THE APPLICATION HAS NO DATA IN APPLICATION INSIGHTS."

At the beginning of my main cs file, I've got this:

```<code>var telemetryClient = new TelemetryClient { InstrumentationKey = ConfigurationManager.AppSettings["applicationInsights"] };
</code>```

at the end, there is this:

```<code>telemetryClient.Flush();
</code>```

In my app.config file, I have this:

```<code> <log4net>
    <root>
      <level value="INFO" />
      <appender-ref ref="FileAppender" />
      <appender-ref ref="aiAppender" />
    </root>
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
      <file value="C:\logs\logfile.txt" />
      <appendToFile value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] – %message%newline" />
      </layout>
    </appender>
    <appender name="aiAppender" type="Microsoft.ApplicationInsights.Log4NetAppender.ApplicationInsightsAppender, Microsoft.ApplicationInsights.Log4NetAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%message%newline" />
      </layout>
    </appender>
  </log4net>
</code>```

When I run the application, I see this sort of thing in the output window:

```<code>Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Message","time":"2017-07-04T10:26:15.7741453Z","tags":{"ai.internal.sdkVersion":"log4net:2.2.0-220","ai.cloud.roleInstance":"xxx","ai.user.id":"AzureAD\\xxx"},"data":{"baseType":"MessageData","baseData":{"ver":2,"message":"xxx","severityLevel":"Information","properties":{xxx"}}}}
</code>```

What am I missing?

答:
Log4Net AI appender will not use the TelemtryClient you create.

Set AI Instrumentation Key like this:

```<code>TelemetryConfiguration.Active.InstrumentationKey = ConfigurationManager.AppSettings["applicationInsights"];
</code>```

See, https://github.com/Microsoft/ApplicationInsights-dotnet-logging

Body:
I'm using Log4Net in my my C# console application and want the logged events to appear in Application Insights as well.

I've added Application Insights as well as the Application Insights Log4Net Appender.

I've followed the instructions here: https://jan-v.nl/post/using-application-insights-in-your-log4net-application with no luck.

Log4Net is logging fine. However, when I go to the Application Insights dashboard, I see this: "THE APPLICATION HAS NO DATA IN APPLICATION INSIGHTS."

At the beginning of my main cs file, I've got this:

var telemetryClient = new TelemetryClient { InstrumentationKey = ConfigurationManager.AppSettings["applicationInsights"] };

at the end, there is this:

telemetryClient.Flush();

In my app.config file, I have this:

 <log4net>
    <root>
      <level value="INFO" />
      <appender-ref ref="FileAppender" />
      <appender-ref ref="aiAppender" />
    </root>
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
      <file value="C:\logs\logfile.txt" />
      <appendToFile value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] – %message%newline" />
      </layout>
    </appender>
    <appender name="aiAppender" type="Microsoft.ApplicationInsights.Log4NetAppender.ApplicationInsightsAppender, Microsoft.ApplicationInsights.Log4NetAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%message%newline" />
      </layout>
    </appender>
  </log4net>

When I run the application, I see this sort of thing in the output window:

Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Message","time":"2017-07-04T10:26:15.7741453Z","tags":{"ai.internal.sdkVersion":"log4net:2.2.0-220","ai.cloud.roleInstance":"xxx","ai.user.id":"AzureAD\\xxx"},"data":{"baseType":"MessageData","baseData":{"ver":2,"message":"xxx","severityLevel":"Information","properties":{xxx"}}}}

What am I missing?

Body:
Log4Net AI appender will not use the TelemtryClient you create.

Set AI Instrumentation Key like this:

TelemetryConfiguration.Active.InstrumentationKey = ConfigurationManager.AppSettings["applicationInsights"];

See, https://github.com/Microsoft/ApplicationInsights-dotnet-logging


问:
Rename List item when there is the same string multiple time
I have List of names like:

```<code>var list = new List<string> {"Allan", "Michael", "Jhon", "Smith", "George", "Jhon"};
</code>```

and a combobox which itemssource is my list. As you can see in the list there is Jhon 2 times, what I want is when I put those name into combobox add "2" to second Jhon. I mean when I open the combobox names in it shoud look like:

```<code>Allan
Michael
Jhon
Smith
George
Jhon2
</code>```

I have tired linq to do that but I'm quite new to c#/linq. Could someone show me simple way to do that?

答:
I would do

```<code>class Program
{
    private static void Main(string[] args)
    {

        var list = new List<string> { "Allan", "Michael", "Jhon", "Smith", "George", "Jhon" };

        var duplicates = list.GroupBy(x => x).Select(r => GetTuple(r.Key, r.Count()))
                             .Where(x => x.Count > 1)
                             .Select(c => { c.Count = 1; return c; }).ToList();

        var result = list.Select(v =>
        {
            var val = duplicates.FirstOrDefault(x => x.Name == v);
            if (val != null)
            {
                if (val.Count != 1)
                {
                    v = v + " " + val.Count;
                }
                val.Count += 1;
            }

            return v;
        }).ToList();

        Console.ReadLine();
    }

    private static FooBar GetTuple(string key, int count)
    {
        return new FooBar(key, count);
    }
}

public class FooBar
{
    public int Count { get; set; }
    public string Name { get; set; }

    public FooBar(string name, int count)
    {
        Count = count;
        Name = name;
    }
}
</code>```

Body:
I have List of names like:

var list = new List<string> {"Allan", "Michael", "Jhon", "Smith", "George", "Jhon"};

and a combobox which itemssource is my list. As you can see in the list there is Jhon 2 times, what I want is when I put those name into combobox add "2" to second Jhon. I mean when I open the combobox names in it shoud look like:

Allan
Michael
Jhon
Smith
George
Jhon2

I have tired linq to do that but I'm quite new to c#/linq. Could someone show me simple way to do that?

Body:
I would do

class Program
{
    private static void Main(string[] args)
    {

        var list = new List<string> { "Allan", "Michael", "Jhon", "Smith", "George", "Jhon" };

        var duplicates = list.GroupBy(x => x).Select(r => GetTuple(r.Key, r.Count()))
                             .Where(x => x.Count > 1)
                             .Select(c => { c.Count = 1; return c; }).ToList();

        var result = list.Select(v =>
        {
            var val = duplicates.FirstOrDefault(x => x.Name == v);
            if (val != null)
            {
                if (val.Count != 1)
                {
                    v = v + " " + val.Count;
                }
                val.Count += 1;
            }

            return v;
        }).ToList();

        Console.ReadLine();
    }

    private static FooBar GetTuple(string key, int count)
    {
        return new FooBar(key, count);
    }
}

public class FooBar
{
    public int Count { get; set; }
    public string Name { get; set; }

    public FooBar(string name, int count)
    {
        Count = count;
        Name = name;
    }
}


问:
What is NPM and why do I need it?
In the past, I made some websites with notepad for example, so we must create a folder TREE and put into it a .htm file, and some folderS with stuff like Javascript, css ...

Maybe I don't understand what NPM really brings, because It seems to do the same thing but automated it ... is it just that ?

For example, why not just unpack a frameworks (e.g. Bootstrap or Kube) without use of NPM and so have folders ready to use ?

Help me to understand please because I'm near the crazy state with all this stuff ...

答:
NPM is a node package manager. It is basically used for managing dependencies of various server side dependencies.

We can manages our server side dependencies manually as well but once our project's dependencies grow it becomes difficult to install and manage.

By using NPM it becomes easy, we just need to install NPM once for all dependencies.

Title: What is NPM and why do I need it?


问:
Which module to use to edit files - Ansible
I want to edit the configuration file of telegraf(system metrics collecting agent).

Telegraf comes in with a default config file which can be edited. There are many input and output plugins defined in there, which are commented out and can be added by removing the comments and also be customized.

I want to edit only some of the plugins defined there, not all of them. For example, consider this is the file,

```<code>[global]
  interval='10s'

[outputs.influxdb]
  host=['http://localhost:8086']

#[outputs.elasticsearch]
#  host=['http://localhost:9200']

[inputs.netstat]
  interface='eth0'
</code>```

Now, I want to edit the 3 blocks, global, outputs.influxdb and inputs.netstat. I don't want to edit outputs.elasticsearch but also want that the block outputs.elasticsearch should remain in the file.

When Using Ansible, I firstly used Template module, but if I use that, then the commented data would be lost.

Then I used the ini_file module, instead of editing the already present block, it adds a new block even if it is already present, and results in something like this,

```<code>[outputs.influxdb]
 host=[http://localhost:8086]
[outputs.influxdb]
 host=[http://xx.xx.xx.xx:8086]
</code>```

Which module is ideal for my scenario ?

答:
There are several options, depending on your purpose.

The lineinfile - module is the best option, if you just want to add, replace or remove one line.

The replace - module is best, if you want to add, replace or delete several lines.

The blockinfile - module can add several lines, surrounded by markers.

If you only want to change two or three lines, you could use as many calls of lineinfile. To change a whole config file, I would recommend, like the commenters suggest, use the template -  module.

Body:
I want to edit the configuration file of telegraf(system metrics collecting agent).

Telegraf comes in with a default config file which can be edited. There are many input and output plugins defined in there, which are commented out and can be added by removing the comments and also be customized.

I want to edit only some of the plugins defined there, not all of them. For example, consider this is the file,

[global]
  interval='10s'

[outputs.influxdb]
  host=['http://localhost:8086']

#[outputs.elasticsearch]
#  host=['http://localhost:9200']

[inputs.netstat]
  interface='eth0'

Now, I want to edit the 3 blocks, global, outputs.influxdb and inputs.netstat. I don't want to edit outputs.elasticsearch but also want that the block outputs.elasticsearch should remain in the file.

When Using Ansible, I firstly used Template module, but if I use that, then the commented data would be lost.

Then I used the ini_file module, instead of editing the already present block, it adds a new block even if it is already present, and results in something like this,

[outputs.influxdb]
 host=[http://localhost:8086]
[outputs.influxdb]
 host=[http://xx.xx.xx.xx:8086]

Which module is ideal for my scenario ?


问:
Segmentation fault (core dumped)
Im trying to implement kmeans algorithm in c++, the probleme is that when i try to implement in the begining a function to intializ the means... it give me this error i searched so hard to see if i exceeded the number of array size but things looks alright and and no overflow exist. this is the code :

header file :

```<code>#ifndef KM_HPP
#define KM_HPP
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#define HIGH_VALUE 50

// fonction d'initialisation
void initMeans(float **, double **, int , int , int );
#endif
</code>```

implementation of the header file :

```<code>#include "km.hpp"

// fonction d'initialisation
void initMeans(float **x, double **v, int n, int p, int c){
    srand(time(0));
    for(int i=0; i<n; i++) x[i][p] = rand()%c;
    v = new double*[c];
    for(int i=0; i<c; i++) v[i] = new double[p];
    for(int i = 0; i < c; i++) for(int j = 0; j < p; j++){
    double num = 0; int denum = 0;
    for(int k = 0; k < n; k++) if(x[k][p] == i){
    num += x[k][j]; denum++;
    }
    v[i][j] = num/denum;
    }
}
</code>```

main file :

```<code>#include "km.hpp"

using namespace std;
//Les variables globale :

char nomExt[40];
int n, p, c;
float **x;
double **v;
FILE *f;

int main(){
    cout<<" donnée le nom de la fichier data :";
    cin>>nomExt;
    f=fopen(nomExt,"r");
    fscanf(f,"%d",&n);
    fscanf(f,"%d",&p);
    fscanf(f,"%d",&c);

    x = new float*[n];
    for(int i=0;i<n;i++) x[i]= new float[p];

    for(int i=0;i<n;i++){
        for(int j=0;j<p;j++) fscanf(f,"%f",&x[i][j]);
    }

    initMeans(x, v, n, p, c);
    for(int i=0;i<c;i++){
        for(int j=0;j<p;j++) cout<<v[i][j]<<"\t";
        cout<<endl;
    }
    for(int j=0;j<p;j++) delete [] x[j];

    delete [] x;
    for(int j=0;j<p;j++) delete [] v[j];

    delete [] v;
        fclose(f);
    return 0;
}
</code>```

x1.txt is the file that containt : number of row (n), number of column (p), number of classe,the column number for the 2D array v (c).
The file that contain the data and main.cpp, header.hpp and header.cpp(header file implementation ) and the make file  all are in the same folder.

error message :

```<code>g++ -o km -O3 km.cpp main.cpp
main.cpp: In function ‘int main()’:
main.cpp:16:19: warning: ignoring return value of ‘int fscanf(FILE*, const char*, ...)’, declared with attribute warn_unused_result [-Wunused-result]
  fscanf(f,"%d",&n);
                   ^
main.cpp:17:19: warning: ignoring return value of ‘int fscanf(FILE*, const char*, ...)’, declared with attribute warn_unused_result [-Wunused-result]
  fscanf(f,"%d",&p);
                   ^
main.cpp:18:19: warning: ignoring return value of ‘int fscanf(FILE*, const char*, ...)’, declared with attribute warn_unused_result [-Wunused-result]
  fscanf(f,"%d",&c);
                   ^
main.cpp:24:47: warning: ignoring return value of ‘int fscanf(FILE*, const char*, ...)’, declared with attribute warn_unused_result [-Wunused-result]
   for(int j=0;j<p;j++) fscanf(f,"%f",&x[i][j]);
</code>```

after executing it says :

```<code>Erreur de segmentation (core dumped) ==> [Segmentation fault (core dumped)]
</code>```

答:
I had the same issue. I was getting segmentation fault when I called a function that returns an integer.
Later I figured, It was a very simple mistake that I did.
while creating an object of a class, I had written this -

Object* object;
instead of Object* object = new Object();

Hope this answer helps.
Thanks,
Shraddha

Title: Segmentation fault (core dumped)

Body:
Im trying to implement kmeans algorithm in c++, the probleme is that when i try to implement in the begining a function to intializ the means... it give me this error i searched so hard to see if i exceeded the number of array size but things looks alright and and no overflow exist. this is the code :

header file :

#ifndef KM_HPP
#define KM_HPP
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#define HIGH_VALUE 50

// fonction d'initialisation
void initMeans(float **, double **, int , int , int );
#endif

implementation of the header file :

#include "km.hpp"

// fonction d'initialisation
void initMeans(float **x, double **v, int n, int p, int c){
    srand(time(0));
    for(int i=0; i<n; i++) x[i][p] = rand()%c;
    v = new double*[c];
    for(int i=0; i<c; i++) v[i] = new double[p];
    for(int i = 0; i < c; i++) for(int j = 0; j < p; j++){
    double num = 0; int denum = 0;
    for(int k = 0; k < n; k++) if(x[k][p] == i){
    num += x[k][j]; denum++;
    }
    v[i][j] = num/denum;
    }
}

main file :

#include "km.hpp"

using namespace std;
//Les variables globale :

char nomExt[40];
int n, p, c;
float **x;
double **v;
FILE *f;

int main(){
    cout<<" donnée le nom de la fichier data :";
    cin>>nomExt;
    f=fopen(nomExt,"r");
    fscanf(f,"%d",&n);
    fscanf(f,"%d",&p);
    fscanf(f,"%d",&c);

    x = new float*[n];
    for(int i=0;i<n;i++) x[i]= new float[p];

    for(int i=0;i<n;i++){
        for(int j=0;j<p;j++) fscanf(f,"%f",&x[i][j]);
    }

    initMeans(x, v, n, p, c);
    for(int i=0;i<c;i++){
        for(int j=0;j<p;j++) cout<<v[i][j]<<"\t";
        cout<<endl;
    }
    for(int j=0;j<p;j++) delete [] x[j];

    delete [] x;
    for(int j=0;j<p;j++) delete [] v[j];

    delete [] v;
        fclose(f);
    return 0;
}

x1.txt is the file that containt : number of row (n), number of column (p), number of classe,the column number for the 2D array v (c).
The file that contain the data and main.cpp, header.hpp and header.cpp(header file implementation ) and the make file  all are in the same folder.

error message :

g++ -o km -O3 km.cpp main.cpp
main.cpp: In function ‘int main()’:
main.cpp:16:19: warning: ignoring return value of ‘int fscanf(FILE*, const char*, ...)’, declared with attribute warn_unused_result [-Wunused-result]
  fscanf(f,"%d",&n);
                   ^
main.cpp:17:19: warning: ignoring return value of ‘int fscanf(FILE*, const char*, ...)’, declared with attribute warn_unused_result [-Wunused-result]
  fscanf(f,"%d",&p);
                   ^
main.cpp:18:19: warning: ignoring return value of ‘int fscanf(FILE*, const char*, ...)’, declared with attribute warn_unused_result [-Wunused-result]
  fscanf(f,"%d",&c);
                   ^
main.cpp:24:47: warning: ignoring return value of ‘int fscanf(FILE*, const char*, ...)’, declared with attribute warn_unused_result [-Wunused-result]
   for(int j=0;j<p;j++) fscanf(f,"%f",&x[i][j]);

after executing it says :

Erreur de segmentation (core dumped) ==> [Segmentation fault (core dumped)]


问:
Pandas: converting strings representing numbers, with characters, into float/ int
From a daily report, I use:

```<code>pd.read_csv(filepath, sep = '\t')
</code>```

to open a dataframe looking like the below (in simplified format):

```<code>finalDf2 = pd.DataFrame(dict(
            Portfolio = pd.Series(['Book1', 'Book1', 'Book2', 'Book3', 'Book1','Book1']),
            Strike = pd.Series(['108','109.10', '111', '114', '108.3', '115.0']),
            Notional = pd.Series(['0', '-0.02', '35', '. 3K', '-0.05K', '0' ]))
     )
</code>```

By running the below on various entries under the "Notional" column:

```<code>type(finalDf2.iloc[ , ]
</code>```

I see the 0s are of type int already.

The nonzero values however are strings. I tried to convert strings to floats by using:

```<code>finalDf2['Notional'].astype(float)
</code>```

but before doing so, how could I convert all cells containing "K" values?
For instance,

. 3K should end up being float or int 30

 -0. 05K should end up being float or int -50

Spacings are actually in the file and thus dataframe unfortunately.

答:
Here is a possible solution:

```<code>def notional_to_num(x):
    if isinstance(x, (int, float)):
        return x
    elif isinstance(x, str):
        return x if 'K' not in x else float(x.replace(" ", "0")[:-1])*1e3
    else:
        raise

finalDf2.loc[:, 'Notional'] = finalDf2['Notional'].apply(notional_to_num)
</code>```

Which gives the following output:

```<code>  Notional Portfolio  Strike
0        0     Book1     108
1    -0.02     Book1  109.10
2       35     Book2     111
3       30     Book3     114
4      -50     Book1   108.3
5        0     Book1   115.0
</code>```

Body:
From a daily report, I use:

pd.read_csv(filepath, sep = '\t')

to open a dataframe looking like the below (in simplified format):

finalDf2 = pd.DataFrame(dict(
            Portfolio = pd.Series(['Book1', 'Book1', 'Book2', 'Book3', 'Book1','Book1']),
            Strike = pd.Series(['108','109.10', '111', '114', '108.3', '115.0']),
            Notional = pd.Series(['0', '-0.02', '35', '. 3K', '-0.05K', '0' ]))
     )

By running the below on various entries under the "Notional" column:

type(finalDf2.iloc[ , ]

I see the 0s are of type int already.

The nonzero values however are strings. I tried to convert strings to floats by using:

finalDf2['Notional'].astype(float)

but before doing so, how could I convert all cells containing "K" values?
For instance,

. 3K should end up being float or int 30

 -0. 05K should end up being float or int -50

Spacings are actually in the file and thus dataframe unfortunately.

Body:
Here is a possible solution:

def notional_to_num(x):
    if isinstance(x, (int, float)):
        return x
    elif isinstance(x, str):
        return x if 'K' not in x else float(x.replace(" ", "0")[:-1])*1e3
    else:
        raise

finalDf2.loc[:, 'Notional'] = finalDf2['Notional'].apply(notional_to_num)

Which gives the following output:

  Notional Portfolio  Strike
0        0     Book1     108
1    -0.02     Book1  109.10
2       35     Book2     111
3       30     Book3     114
4      -50     Book1   108.3
5        0     Book1   115.0


问:
/usr/local has correct permissions, but brew update still says it is not writable
Here are the permissions to my /usr/local directory: drwxr-xr-x.

I did sudo chown -R $user /usr/local, then did brew update again. It didn't work. I tried quitting terminal and opening a new session and trying again and I got the same thing. When I try brew doctor or brew update, it tells me that this directory is not writable. What do I do? What else do I need to be checking?

答:
When I try to brew update Tip me Error: / usr/local must be writable!

sudo chgrp -R admin /usr/local

sudo chmod -R g+w /usr/local

The above method solves my problem


答:
no overload for method takes one argument

Clearly error says everything ...

Assert.AreSame(appno.IsValid(applicationNumber), /*TO WHAT SHOULD IT BE COMPARED*/);

Assert.AreSame(appno.IsValid(applicationNumber), false);

EDIT :
Extending this answer to be more accurate and on topic.

You're trying to compare two values but using reference comparer ( Assert.AreSame ).

This can fail because the 2 references are not the same ( read about references here ).

What you should do is to compare the two values. To do this you have to use different assertion methods.

For your example you can use Assert.IsTrue if you expect your method to return true or Assert.IsFalse if your expected value is false:

```<code>bool result = meObj.IsValid("someString");
// let's say you're expecting false
Assert.IsFalse(result);
// but if you're expecting true then change IsFalse to IsTrue
</code>```

Or you can use AreEqual which in your case will be Assert.AreEqual<bool> :

```<code>bool result = meObj.IsValid("someString");
bool expected = false;
Assert.AreEqual(expected, result);
</code>```

Title: Unit test case for If condition

Body:
no overload for method takes one argument

Clearly error says everything ...

Assert.AreSame(appno.IsValid(applicationNumber), /*TO WHAT SHOULD IT BE COMPARED*/);

Assert.AreSame(appno.IsValid(applicationNumber), false);

EDIT :
Extending this answer to be more accurate and on topic.

You're trying to compare two values but using reference comparer ( Assert.AreSame ).

This can fail because the 2 references are not the same ( read about references here ).

What you should do is to compare the two values. To do this you have to use different assertion methods.

For your example you can use Assert.IsTrue if you expect your method to return true or Assert.IsFalse if your expected value is false:

bool result = meObj.IsValid("someString");
// let's say you're expecting false
Assert.IsFalse(result);
// but if you're expecting true then change IsFalse to IsTrue

Or you can use AreEqual which in your case will be Assert.AreEqual<bool> :

bool result = meObj.IsValid("someString");
bool expected = false;
Assert.AreEqual(expected, result);


问:
Adding video output to ARKit app
Trying to fast-prototype an Augmented reality app by using the ARKitExample app from Apple. I've been trying to add a button that allows me to save a video of everything is on the screen.

I've a AVCaptureSession configured with its input device and output file as:

```<code>private let _session = AVCaptureSession()
</code>```

configuration

```<code>    if let dualCameraDevice = AVCaptureDevice.default(.builtInDualCamera, for: AVMediaType.video, position: .back) {
      defaultVideoDevice = dualCameraDevice
    } else if let backCameraDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: AVMediaType.video, position: .back) {
     defaultVideoDevice = backCameraDevice
    }
            ...
    let videoDeviceInput = try AVCaptureDeviceInput(device: defaultVideoDevice!)
self._session.addInput(videoDeviceInput)
</code>```

output

```<code>let movieFileOutput = AVCaptureMovieFileOutput()

if self._session.canAddOutput(movieFileOutput) {
 self._session.addOutput(movieFileOutput)
 self._session.sessionPreset = AVCaptureSession.Preset.high

 self.movieFileOutput = movieFileOutput
}
</code>```

toggling video recording

```<code>guard let movieFileOutput = self.movieFileOutput else {
            return
        }

        sessionQueue.async { [unowned self] in
            if !movieFileOutput.isRecording {
                if UIDevice.current.isMultitaskingSupported {

                    self.backgroundRecordingID = UIApplication.shared.beginBackgroundTask(expirationHandler: nil)
                }

                connection before starting recording.
                let movieFileOutputConnection = self.movieFileOutput?.connection(with: AVMediaType.video)

//
                let availableVideoCodecTypes = movieFileOutput.availableVideoCodecTypes as [AVVideoCodecType]

                if availableVideoCodecTypes.contains(.hevc) {
                    movieFileOutput.setOutputSettings([AVVideoCodecKey: AVVideoCodecType.hevc], for: movieFileOutputConnection!)
                }

                // Start recording to a temporary file.
                let outputFileName = NSUUID().uuidString
                let outputFilePath = (NSTemporaryDirectory() as NSString).appendingPathComponent((outputFileName as NSString).appendingPathExtension("mov")!)
                movieFileOutput.startRecording(to: URL(fileURLWithPath: outputFilePath), recordingDelegate: self)

            } else {
//-- THIS NEVER EXECS -->>>>
                    movieFileOutput.stopRecording()
                }
            }
</code>```

movieFileOutput.stopRecording() never gets call as movileFileOutput.isRecording remains as false

Not sure whether this is the proper way to capture video of a ARSCNView

Help is appreciated!

答:
Look at Replay Kit (https://developer.apple.com/documentation/replaykit).

A sample (not using SceneKit) is at https://github.com/halmueller/ferries.

Also consider using iOS 11's built in screen recording.

Title: Adding video output to ARKit app

Body:
Trying to fast-prototype an Augmented reality app by using the ARKitExample app from Apple. I've been trying to add a button that allows me to save a video of everything is on the screen.

I've a AVCaptureSession configured with its input device and output file as:

private let _session = AVCaptureSession()

configuration

    if let dualCameraDevice = AVCaptureDevice.default(.builtInDualCamera, for: AVMediaType.video, position: .back) {
      defaultVideoDevice = dualCameraDevice
    } else if let backCameraDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: AVMediaType.video, position: .back) {
     defaultVideoDevice = backCameraDevice
    }
            ...
    let videoDeviceInput = try AVCaptureDeviceInput(device: defaultVideoDevice!)
self._session.addInput(videoDeviceInput)

output

let movieFileOutput = AVCaptureMovieFileOutput()

if self._session.canAddOutput(movieFileOutput) {
 self._session.addOutput(movieFileOutput)
 self._session.sessionPreset = AVCaptureSession.Preset.high

 self.movieFileOutput = movieFileOutput
}

toggling video recording

guard let movieFileOutput = self.movieFileOutput else {
            return
        }

        sessionQueue.async { [unowned self] in
            if !movieFileOutput.isRecording {
                if UIDevice.current.isMultitaskingSupported {

                    self.backgroundRecordingID = UIApplication.shared.beginBackgroundTask(expirationHandler: nil)
                }

                connection before starting recording.
                let movieFileOutputConnection = self.movieFileOutput?.connection(with: AVMediaType.video)

//
                let availableVideoCodecTypes = movieFileOutput.availableVideoCodecTypes as [AVVideoCodecType]

                if availableVideoCodecTypes.contains(.hevc) {
                    movieFileOutput.setOutputSettings([AVVideoCodecKey: AVVideoCodecType.hevc], for: movieFileOutputConnection!)
                }

                // Start recording to a temporary file.
                let outputFileName = NSUUID().uuidString
                let outputFilePath = (NSTemporaryDirectory() as NSString).appendingPathComponent((outputFileName as NSString).appendingPathExtension("mov")!)
                movieFileOutput.startRecording(to: URL(fileURLWithPath: outputFilePath), recordingDelegate: self)

            } else {
//-- THIS NEVER EXECS -->>>>
                    movieFileOutput.stopRecording()
                }
            }

movieFileOutput.stopRecording() never gets call as movileFileOutput.isRecording remains as false

Not sure whether this is the proper way to capture video of a ARSCNView

Help is appreciated!


问:
How to binding xml to datagrid combobox
I have a wpf project which used to binding xml to datagrid like follows:

```<code><DataGrid Name="dgCommunication" ItemsSource="{Binding CommunicationsView}" FontSize="14" CanUserResizeColumns="False" BorderThickness="5" AutoGenerateColumns="False" Margin="10,10,10,15" Background="White">
    <DataGrid.Columns>
         <DataGridTextColumn Header="ParamName" Binding="{Binding ParamName}" IsReadOnly="True"/>
         <DataGridTextColumn Header="ParamValue" Binding="{Binding ParamValues, Mode=TwoWay}" />
         <DataGridTextColumn Header="DefaultValue" Binding="{Binding DefaultValue}" IsReadOnly="True"/>
         <DataGridTextColumn Header="MaxValue" Binding="{Binding MaxValue}" IsReadOnly="True"/>
         <DataGridTextColumn Header="MinValue" Binding="{Binding MinValue}" IsReadOnly="True"/>
    </DataGrid.Columns>
</DataGrid>
</code>```

And the xml file:

```<code><NewDataSet>
   <Communications>
      <ModelNumber>0x01</ModelNumber>
      <ParamName>BaudRate</ParamName>
      <ParamValue>19200</ParamValue>
      <DefaultValue>19200</DefaultValue>
      <MaxValue></MaxValue>
      <MinValue></MinValue>
   </Communications>
   <Communications>
      <ModelNumber>0x01</ModelNumber>
      <ParamName>Parity</ParamName>
      <ParamValue>None</ParamValue>
      <DefaultValue>None</DefaultValue>
      <MaxValue></MaxValue>
      <MinValue></MinValue>
   </Communications>
   <Communications>
      <ModelNumber>0x01</ModelNumber>
      <ParamName>StopBit</ParamName>
      <ParamValue>1</ParamValue>
      <DefaultValue>1</DefaultValue>
      <MaxValue></MaxValue>
      <MinValue></MinValue>
   </Communications>
   <Communications>
      <ModelNumber>0x01</ModelNumber>
      <ParamName>DataBit</ParamName>
      <ParamValue>8</ParamValue>
      <DefaultValue>8</DefaultValue>
      <MaxValue></MaxValue>
      <MinValue></MinValue>
   </Communications>
   <Communications>
      <ModelNumber>0x01</ModelNumber>
      <ParamName>SlaveAddress</ParamName>
      <ParamValue>1</ParamValue>
      <DefaultValue>1</DefaultValue>
      <MaxValue>247</MaxValue>
      <MinValue>1</MinValue>
   </Communications>
   <Communications>
      <ModelNumber>0x01</ModelNumber>
      <ParamName>IP_Address</ParamName>
      <ParamValue>192.168.0.1</ParamValue>
      <DefaultValue>192.168.0.1</DefaultValue>
      <MaxValue></MaxValue>
      <MinValue></MinValue>
   </Communications>
   <Communications>
      <ModelNumber>0x01</ModelNumber>
      <ParamName>IP_Port</ParamName>
      <ParamValue>502</ParamValue>
      <DefaultValue>502</DefaultValue>
      <MaxValue></MaxValue>
      <MinValue></MinValue>
   </Communications>
</NewDataSet>
</code>```

This works fine. But now I have to change some of the DataGridTextColumn into ComboBox, taking BaudRate as an example, I may change the xml to:

```<code><NewDataSet>
    <Communications>
        <ModelNumber>0x01</ModelNumber>
        <ParamName>BaudRate</ParamName>
        <ParamValues>
            <ParamValue>9600</ParamValue>
            <ParamValue>19200</ParamValue>
            <ParamValue>115200</ParamValue>
        </ParamValues>
        <DefaultValue>502</DefaultValue>
        <MaxValue></MaxValue>
        <MinValue></MinValue>
    </Communications>
</NewDataSet>
</code>```

How should I do to make this happen?Thanks in advance!

答:
If you save the ParamValues as an List and using DataGridComboBoxColumn

By using the MVVM-Model the XML-Docuemnt will be the Database and you have to built an model with an logik that will buitl the Objects.
The Viewmodel will use the Modeldata and you can use an binding to the ParamValues if im supposed to be right.

```<code> <DataGridComboBoxColumn Header="Values" ItemsSource="{Binding ParamValues, Mode=TwoWay}" SelectedItemBinding="{Binding SelectedParamValue, Mode=TwoWay}"/>
</code>```

Title: How to binding xml to datagrid combobox

Body:
I have a wpf project which used to binding xml to datagrid like follows:

<DataGrid Name="dgCommunication" ItemsSource="{Binding CommunicationsView}" FontSize="14" CanUserResizeColumns="False" BorderThickness="5" AutoGenerateColumns="False" Margin="10,10,10,15" Background="White">
    <DataGrid.Columns>
         <DataGridTextColumn Header="ParamName" Binding="{Binding ParamName}" IsReadOnly="True"/>
         <DataGridTextColumn Header="ParamValue" Binding="{Binding ParamValues, Mode=TwoWay}" />
         <DataGridTextColumn Header="DefaultValue" Binding="{Binding DefaultValue}" IsReadOnly="True"/>
         <DataGridTextColumn Header="MaxValue" Binding="{Binding MaxValue}" IsReadOnly="True"/>
         <DataGridTextColumn Header="MinValue" Binding="{Binding MinValue}" IsReadOnly="True"/>
    </DataGrid.Columns>
</DataGrid>

And the xml file:

<NewDataSet>
   <Communications>
      <ModelNumber>0x01</ModelNumber>
      <ParamName>BaudRate</ParamName>
      <ParamValue>19200</ParamValue>
      <DefaultValue>19200</DefaultValue>
      <MaxValue></MaxValue>
      <MinValue></MinValue>
   </Communications>
   <Communications>
      <ModelNumber>0x01</ModelNumber>
      <ParamName>Parity</ParamName>
      <ParamValue>None</ParamValue>
      <DefaultValue>None</DefaultValue>
      <MaxValue></MaxValue>
      <MinValue></MinValue>
   </Communications>
   <Communications>
      <ModelNumber>0x01</ModelNumber>
      <ParamName>StopBit</ParamName>
      <ParamValue>1</ParamValue>
      <DefaultValue>1</DefaultValue>
      <MaxValue></MaxValue>
      <MinValue></MinValue>
   </Communications>
   <Communications>
      <ModelNumber>0x01</ModelNumber>
      <ParamName>DataBit</ParamName>
      <ParamValue>8</ParamValue>
      <DefaultValue>8</DefaultValue>
      <MaxValue></MaxValue>
      <MinValue></MinValue>
   </Communications>
   <Communications>
      <ModelNumber>0x01</ModelNumber>
      <ParamName>SlaveAddress</ParamName>
      <ParamValue>1</ParamValue>
      <DefaultValue>1</DefaultValue>
      <MaxValue>247</MaxValue>
      <MinValue>1</MinValue>
   </Communications>
   <Communications>
      <ModelNumber>0x01</ModelNumber>
      <ParamName>IP_Address</ParamName>
      <ParamValue>192.168.0.1</ParamValue>
      <DefaultValue>192.168.0.1</DefaultValue>
      <MaxValue></MaxValue>
      <MinValue></MinValue>
   </Communications>
   <Communications>
      <ModelNumber>0x01</ModelNumber>
      <ParamName>IP_Port</ParamName>
      <ParamValue>502</ParamValue>
      <DefaultValue>502</DefaultValue>
      <MaxValue></MaxValue>
      <MinValue></MinValue>
   </Communications>
</NewDataSet>

This works fine. But now I have to change some of the DataGridTextColumn into ComboBox, taking BaudRate as an example, I may change the xml to:

<NewDataSet>
    <Communications>
        <ModelNumber>0x01</ModelNumber>
        <ParamName>BaudRate</ParamName>
        <ParamValues>
            <ParamValue>9600</ParamValue>
            <ParamValue>19200</ParamValue>
            <ParamValue>115200</ParamValue>
        </ParamValues>
        <DefaultValue>502</DefaultValue>
        <MaxValue></MaxValue>
        <MinValue></MinValue>
    </Communications>
</NewDataSet>

How should I do to make this happen?Thanks in advance!

Body:
If you save the ParamValues as an List and using DataGridComboBoxColumn

By using the MVVM-Model the XML-Docuemnt will be the Database and you have to built an model with an logik that will buitl the Objects.
The Viewmodel will use the Modeldata and you can use an binding to the ParamValues if im supposed to be right.

 <DataGridComboBoxColumn Header="Values" ItemsSource="{Binding ParamValues, Mode=TwoWay}" SelectedItemBinding="{Binding SelectedParamValue, Mode=TwoWay}"/>


问:
Unit test of method with CompletableFuture inside
I have method which in async way calls connector.runSomeService(data) and handles the response in method handleServiceResponse(res, node).

```<code>public void runServiceOnAllNodes(Collection<Node> nodes, Object data) {
    nodes.parallelStream().forEach(node -> {
        CompletableFuture<ResponseEntity> response = CompletableFuture
                .supplyAsync(()-> connector.runSomeService(data));
        response.exceptionally(ex -> {
                    log.error("OMG...OMG!!!")
                    return null;
                })
                .thenAcceptAsync(res -> handleServiceResponse(res, node));
    });
}

private void handleServiceResponse(ResponseEntity res, Node node) {
    if (res.isOK) {
        node.setOKStatus();
    } else {
        node.setFailStatus();
    }
    dbService.saveNode(node);
}
</code>```

Try to create unit test but when I try to verify if response is properly handled, the result of UT is non deterministic.

```<code>@Test
public void testRunServiceOnAllNodes() {
    // given
    List<Collector> nodes = Arrays.asList(node1, node2, node3);
    when(connector.runSomeService(eq(node1), eq(data))).thenReturn(ResponseEntity.ok().body("{message:OK}"));
    when(connector.runSomeService(eq(node2), eq(data))).thenReturn(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(""));
    when(connector.runSomeService(eq(node3), eq(data))).thenThrow(new ResourceAccessException(""));

    // when
    engine.runServiceOnAllNodes(data, collectors);

    // then
    verify(connector, times(1)).runSomeService(eq(node1), eq(data));
    verify(connector, times(1)).runSomeService(eq(node2), eq(data));
    verify(connector, times(1)).runSomeService(eq(node3), eq(data));
    verifyNoMoreInteractions(connector);
    assertEquals(node1.getStatus(), "OK");
    assertEquals(node2.getStatus(), "Fail");
}
</code>```

It can end with a few different results eg.

```<code>Wanted but not invoked:
connector.runSomeService(node2);

However, there were other interactions with this mock:
connector.runSomeService(node1);
</code>```

or

```<code>Argument(s) are different! Wanted:
connector.runSomeService(node1);

Actual invocation has different arguments:
connector.deployFileset(node2);
</code>```

or sometimes it ends with success.

It is clear that the time of execution connector.runSomeService() and the time of the verification can interlace. The order of this two actions is not deterministic.

Using sleep sucks. Tried to gather all responses and calling future.get()

```<code>// when
engine.runServiceOnAllNodes(data, collectors);
for (CompletableFuture future : engine.getResponses()) {
    future.get();
}
</code>```

but I'm getting some exception but I still have the feeling that this way also sucks, isn't it?

答:
I would suggest changing the runServiceOnAllNodes method to return a Future so your test, and, as a bonus, normal clients as well, can explicitly wait for the async behavior to finish.

```<code>public Future<Void> runServiceOnAllNodes(Collection<Node> nodes, Object data) {
    return nodes.parallelStream().map(node -> {
        CompletableFuture<ResponseEntity> response = CompletableFuture
                .supplyAsync(()-> connector.runSomeService(data));
        return response.exceptionally(ex -> {
            LOGGER.error("OMG...OMG!!!");
            return null;
        })
        .thenAcceptAsync(res -> handleServiceResponse(res, node));
    })
    .reduce(CompletableFuture::allOf).orElseGet(() -> CompletableFuture.completedFuture(null));
}
</code>```

In your test, it is then simply a matter of calling get() on the future prior to making assertions and verifications.

Body:
I have method which in async way calls connector.runSomeService(data) and handles the response in method handleServiceResponse(res, node).

public void runServiceOnAllNodes(Collection<Node> nodes, Object data) {
    nodes.parallelStream().forEach(node -> {
        CompletableFuture<ResponseEntity> response = CompletableFuture
                .supplyAsync(()-> connector.runSomeService(data));
        response.exceptionally(ex -> {
                    log.error("OMG...OMG!!!")
                    return null;
                })
                .thenAcceptAsync(res -> handleServiceResponse(res, node));
    });
}

private void handleServiceResponse(ResponseEntity res, Node node) {
    if (res.isOK) {
        node.setOKStatus();
    } else {
        node.setFailStatus();
    }
    dbService.saveNode(node);
}

Try to create unit test but when I try to verify if response is properly handled, the result of UT is non deterministic.

@Test
public void testRunServiceOnAllNodes() {
    // given
    List<Collector> nodes = Arrays.asList(node1, node2, node3);
    when(connector.runSomeService(eq(node1), eq(data))).thenReturn(ResponseEntity.ok().body("{message:OK}"));
    when(connector.runSomeService(eq(node2), eq(data))).thenReturn(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(""));
    when(connector.runSomeService(eq(node3), eq(data))).thenThrow(new ResourceAccessException(""));

    // when
    engine.runServiceOnAllNodes(data, collectors);

    // then
    verify(connector, times(1)).runSomeService(eq(node1), eq(data));
    verify(connector, times(1)).runSomeService(eq(node2), eq(data));
    verify(connector, times(1)).runSomeService(eq(node3), eq(data));
    verifyNoMoreInteractions(connector);
    assertEquals(node1.getStatus(), "OK");
    assertEquals(node2.getStatus(), "Fail");
}

It can end with a few different results eg.

Wanted but not invoked:
connector.runSomeService(node2);

However, there were other interactions with this mock:
connector.runSomeService(node1);

or

Argument(s) are different! Wanted:
connector.runSomeService(node1);

Actual invocation has different arguments:
connector.deployFileset(node2);

or sometimes it ends with success.

It is clear that the time of execution connector.runSomeService() and the time of the verification can interlace. The order of this two actions is not deterministic.

Using sleep sucks. Tried to gather all responses and calling future.get()

// when
engine.runServiceOnAllNodes(data, collectors);
for (CompletableFuture future : engine.getResponses()) {
    future.get();
}

but I'm getting some exception but I still have the feeling that this way also sucks, isn't it?

Body:
I would suggest changing the runServiceOnAllNodes method to return a Future so your test, and, as a bonus, normal clients as well, can explicitly wait for the async behavior to finish.

public Future<Void> runServiceOnAllNodes(Collection<Node> nodes, Object data) {
    return nodes.parallelStream().map(node -> {
        CompletableFuture<ResponseEntity> response = CompletableFuture
                .supplyAsync(()-> connector.runSomeService(data));
        return response.exceptionally(ex -> {
            LOGGER.error("OMG...OMG!!!");
            return null;
        })
        .thenAcceptAsync(res -> handleServiceResponse(res, node));
    })
    .reduce(CompletableFuture::allOf).orElseGet(() -> CompletableFuture.completedFuture(null));
}

In your test, it is then simply a matter of calling get() on the future prior to making assertions and verifications.


问:
Regex to extract attribute from html element
Text from stream:

```<code><option value=\"1999\">1999</option>\r\n    \r\n \r\n\r\n  \r\n\r\
    n
<option value=\"2000\">2000</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2001\">2001</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2002\">2002</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2003\">2003</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2004\">2004</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2005\">2005</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2006\">2006</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2007\">2007</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2008\">2008</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2009\">2009</option>
</code>```

Regex: (?si:<option value=\\\"(?<year>.*?)\\) shouldn't this be the right way to get the year?. meaning for year group, get all characters as long as you don't hit \

答:
try

```<code>\<option\svalue\=\\\"(\d*)\\\"
</code>```

This is the plain regex. change it to what language you are using it

Body:
Text from stream:

<option value=\"1999\">1999</option>\r\n    \r\n \r\n\r\n  \r\n\r\
    n
<option value=\"2000\">2000</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2001\">2001</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2002\">2002</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2003\">2003</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2004\">2004</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2005\">2005</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2006\">2006</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2007\">2007</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2008\">2008</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2009\">2009</option>

Regex: (?si:<option value=\\\"(?<year>.*?)\\) shouldn't this be the right way to get the year?. meaning for year group, get all characters as long as you don't hit \

Body:
try

\<option\svalue\=\\\"(\d*)\\\"

This is the plain regex. change it to what language you are using it


问:
android comparing dates I couldn't compare two dates...I referred many tutorials
I am using the datepicker dialog and am trying to compare the  current date  with the date specified in the dialog.
if the date is before the current date I wish to display invalid date.

Both current date and date entered are in same format. but I am getting error. when printing in console both current date and entered date are coming the the same format

```<code>if(date1.before(currDate))
{
     Toast.makeText(getApplicationContext(), "Enter the valid Date", Toast.LENGTH_LONG).show();
}
</code>```

result:

current date 5/7/2017

picked date 5-7-2017

答:
You can try this code for date comparison</p>

```<code>@SuppressLint("SimpleDateFormat")
public static boolean compareSameDate(String firstDate, String secondDate) {
    boolean flag = false;
    try {
        SimpleDateFormat formatter = new SimpleDateFormat(
            "dd/MM/yyyy",
            Locale.ENGLISH);

        Date date1 = formatter.parse(firstDate);
        Date date2 = formatter.parse(secondDate);

        if (date2.compareTo(date1) == 0) {
            flag = true;
        } else if (date2.compareTo(date1) < 0) {
            flag = true;
        } else {
            flag = false;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return flag;
}
</code>```

Body:
I am using the datepicker dialog and am trying to compare the  current date  with the date specified in the dialog.
if the date is before the current date I wish to display invalid date.

Both current date and date entered are in same format. but I am getting error. when printing in console both current date and entered date are coming the the same format

if(date1.before(currDate))
{
     Toast.makeText(getApplicationContext(), "Enter the valid Date", Toast.LENGTH_LONG).show();
}

result:

current date 5/7/2017

picked date 5-7-2017

Body:
You can try this code for date comparison

@SuppressLint("SimpleDateFormat")
public static boolean compareSameDate(String firstDate, String secondDate) {
    boolean flag = false;
    try {
        SimpleDateFormat formatter = new SimpleDateFormat(
            "dd/MM/yyyy",
            Locale.ENGLISH);

        Date date1 = formatter.parse(firstDate);
        Date date2 = formatter.parse(secondDate);

        if (date2.compareTo(date1) == 0) {
            flag = true;
        } else if (date2.compareTo(date1) < 0) {
            flag = true;
        } else {
            flag = false;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return flag;
}


问:
Composite primary key issue in hibernate
I am creating a hibernate application in which i want to create a composite primary key. Following is the mapping file I have written:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="Fold.ChildrenPark" table="ChildrenPark">
    <composite-id>
    <key-property name="date" not-null="true"/>
    <key-property name="valveOffTime" not-null="true"/>
    <key-property name="valveOnTime" not-null="true"/>
    </composite-id>
    <property name="overHeadTankLevelAfterFilling"/>
    <property name="overHeadTankLevelBeforeFilling"/>
    <property name="rank"/>
  </class>
</hibernate-mapping>
</code>```

But I am getting exception as follows:

```<code> - 1689 [http-listener-1(4)] ERROR org.hibernate.util.xml.ErrorLogger -
   Error parsing XML (11) : Attribute "not-null" must be declared for
   element type "key-property". Severe:   1717 [http-listener-1(4)] WARN
   org.hibernate.util.DTDEntityResolver - recognized obsolete hibernate
   namespace http://hibernate.sourceforge.net/. Use namespace
   http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6
   Migration Guide! Severe:   1719 [http-listener-1(4)] ERROR
   org.hibernate.util.xml.ErrorLogger - Error parsing XML (2) :
   Attribute "not-null" must be declared for element type
   "key-property". Info:   Exception in insertion of data:
   org.hibernate.InvalidMappingException: Unable to read XML
</code>```

So i want to know what is missing to be provided in this code.I searched on net but didn't find anything useful.What does it means?

答:
There  are many things :

1/ change your dtd from :

```<code><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
</code>```

to:

```<code><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
</code>```

this will remove the warning about obsolete hibernate namespace

2/ Remove not-null attribute for key-property, this attribute does not exists for key-property since a PK property cannot be null.

Body:
I am creating a hibernate application in which i want to create a composite primary key. Following is the mapping file I have written:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="Fold.ChildrenPark" table="ChildrenPark">
    <composite-id>
    <key-property name="date" not-null="true"/>
    <key-property name="valveOffTime" not-null="true"/>
    <key-property name="valveOnTime" not-null="true"/>
    </composite-id>
    <property name="overHeadTankLevelAfterFilling"/>
    <property name="overHeadTankLevelBeforeFilling"/>
    <property name="rank"/>
  </class>
</hibernate-mapping>

But I am getting exception as follows:

 - 1689 [http-listener-1(4)] ERROR org.hibernate.util.xml.ErrorLogger -
   Error parsing XML (11) : Attribute "not-null" must be declared for
   element type "key-property". Severe:   1717 [http-listener-1(4)] WARN
   org.hibernate.util.DTDEntityResolver - recognized obsolete hibernate
   namespace http://hibernate.sourceforge.net/. Use namespace
   http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6
   Migration Guide! Severe:   1719 [http-listener-1(4)] ERROR
   org.hibernate.util.xml.ErrorLogger - Error parsing XML (2) :
   Attribute "not-null" must be declared for element type
   "key-property". Info:   Exception in insertion of data:
   org.hibernate.InvalidMappingException: Unable to read XML

So i want to know what is missing to be provided in this code.I searched on net but didn't find anything useful.What does it means?

Body:
There  are many things :

1/ change your dtd from :

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

to:

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

this will remove the warning about obsolete hibernate namespace

2/ Remove not-null attribute for key-property, this attribute does not exists for key-property since a PK property cannot be null.


问:
Rails: Active Model explanation?
What's the difference from Active Resource and Active Record in Rails?</p>

答:
ActiveRecord acts as a layer between a specific database and your application. It is a conventional Object Relationship Mapper (ORM).

ActiveResource acts as a layer between a more abstract network resource such as a REST server and your application. It acts as a sort of wrapper to make a REST resource appear as a database model so similar techniques can be used.

Title: Rails: Active Model explanation?


问:
getting json values into php variable issue
i try to use some sms api and i have to get message-id. First of all here is the my api code.

```<code>$url = 'https://rest.nexmo.com/sms/json?' . http_build_query(
    [
      'api_key' =>  'xxx',
      'api_secret' => 'xxx',
      'to' => 'xxx',
      'from' => 'xxx',
      'text' => 'xxx'
    ]
);
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
</code>```

When i use this code it's working for sending sms and return response. And here is the json response.

```<code>{ "message-count": "1", "messages": [{ "to": "905075214049", "message-id": "0C000000440A086C", "status": "0", "remaining-balance": "1.52250000", "message-price": "0.01910000", "network": "28603" }] }
</code>```

And i use the print_r function to see the structrue of json data. And here it's.

```<code>stdClass Object
(
    [message-count] => 1
    [messages] => Array
        (
            [0] => stdClass Object
                (
                    [to] => xxx
                    [message-id] => 0C000000440A086C
                    [status] => 0
                    [remaining-balance] => 1.52250000
                    [message-price] => 0.01910000
                    [network] => 28603
                )

        )

)
</code>```

I use this code to get "message-id" into my php value.

```<code>$json_decode = json_decode($response);
$sonuc->messages[0]->message-id;
</code>```

My issue is; if i try to get network section from this json it works. But if i try to get "message-id" section it returns only 0 on the screen. I really don't know how can i get full message-id. Please help.

答:
You are using the wrong variable name. Try using </p>

```<code>$sonuc = json_decode($response);
echo $sonuc->messages[0]->message-id;
</code>```

Body:
i try to use some sms api and i have to get message-id. First of all here is the my api code.

$url = 'https://rest.nexmo.com/sms/json?' . http_build_query(
    [
      'api_key' =>  'xxx',
      'api_secret' => 'xxx',
      'to' => 'xxx',
      'from' => 'xxx',
      'text' => 'xxx'
    ]
);
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);

When i use this code it's working for sending sms and return response. And here is the json response.

{ "message-count": "1", "messages": [{ "to": "905075214049", "message-id": "0C000000440A086C", "status": "0", "remaining-balance": "1.52250000", "message-price": "0.01910000", "network": "28603" }] }

And i use the print_r function to see the structrue of json data. And here it's.

stdClass Object
(
    [message-count] => 1
    [messages] => Array
        (
            [0] => stdClass Object
                (
                    [to] => xxx
                    [message-id] => 0C000000440A086C
                    [status] => 0
                    [remaining-balance] => 1.52250000
                    [message-price] => 0.01910000
                    [network] => 28603
                )

        )

)

I use this code to get "message-id" into my php value.

$json_decode = json_decode($response);
$sonuc->messages[0]->message-id;

My issue is; if i try to get network section from this json it works. But if i try to get "message-id" section it returns only 0 on the screen. I really don't know how can i get full message-id. Please help.

Body:
You are using the wrong variable name. Try using

$sonuc = json_decode($response);
echo $sonuc->messages[0]->message-id;


问:
jQuery ui close button is not shown but it works properly
I am using the jQuery-ui dialog and I have added the libraries:

```<code><link rel="stylesheet" href="../css/bootstrap.min.css">
<link rel="stylesheet" href="../css/jquery-ui.css">

<script src="../js/jquery-3.2.1.min.js"></script>
<script src="../js/tether.min.js"></script>
<script src="../js/bootstrap.min.js"></script>
<script src="../js/jquery-ui.js"></script>
</code>```

But when the dialog box appears, you can not see the close button X.

I can see it as this:

And I have these errors at the console:

Failed to load resource: the server responded with a status of 404
  (Not Found)

答:
Errors:

There's 3 pngs that you do not have on your server.

You can point to the pngs at:

CDN

https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/base/images/ui-icons_444444_256x240.png

https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/base/images/ui-icons_555555_256x240.png

https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/base/images/ui-icons_777777_256x240.png

OR

download them and place them on your own server.

In both cases you may have to change the ruleset in either the 1. stylesheet or 2. inline  within the  tag.

Body:
I am using the jQuery-ui dialog and I have added the libraries:

<link rel="stylesheet" href="../css/bootstrap.min.css">
<link rel="stylesheet" href="../css/jquery-ui.css">

But when the dialog box appears, you can not see the close button X.

I can see it as this:

And I have these errors at the console:

Failed to load resource: the server responded with a status of 404
  (Not Found)

Body:
Errors:

There's 3 pngs that you do not have on your server.

You can point to the pngs at:

CDN

https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/base/images/ui-icons_444444_256x240.png

https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/base/images/ui-icons_555555_256x240.png

https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/base/images/ui-icons_777777_256x240.png

OR

download them and place them on your own server.

In both cases you may have to change the ruleset in either the 1. stylesheet or 2. inline <style> tag on your HTML file:

stylesheet: jquery-ui.css lines. To find those specific lines to edit, go to that error log and click each error. You should be redirected to the browser's view of the CSS file to the exact line that you need to edit.

OR

<style>...</style> within the <head> tag.


问:
Extending the Array.prototype
I can extend Array.prototype and use it in javascript like that:

```<code>Object.defineProperty(Array.prototype, 'flatten', {
  value: function flatten() {
      return this.reduce((a, b) => a.concat(b), []);
  }
});

// that allows me to do:
[1, 2, [3, 4]].flatten(); // [1,2,3,4]
[1, 2, [3, 4]].map(e => 5).flatten(); // [5, 5, 5]
</code>```

However under typescript I get an Error: Property 'flatten' does not exist on type 'Array[]'.

I can avoid that doing something like the following, but that is not nice to get a fluent interface...it's harder to read.

```<code> (<any>[1, 2, [3, 4]]).flatten()
 ([1, 2, [3, 4]].map(e => 5) as any).flatten()
</code>```

Can I do something in typescript to avoid a casting to any? Like let to know typescript dynamically than the code of type Array has another method.

答:
You can extend the Array<T> interface to add the flatten method:

```<code>declare global {
    interface Array<T> {
        flatten(): T[]
    }
}
</code>```

Note that you only need to wrap it inside declare global only when you are inside a module. See merging interfaces.

Title: Extending the Array.prototype

Body:
I can extend Array.prototype and use it in javascript like that:

Object.defineProperty(Array.prototype, 'flatten', {
  value: function flatten() {
      return this.reduce((a, b) => a.concat(b), []);
  }
});

// that allows me to do:
[1, 2, [3, 4]].flatten(); // [1,2,3,4]
[1, 2, [3, 4]].map(e => 5).flatten(); // [5, 5, 5]

However under typescript I get an Error: Property 'flatten' does not exist on type 'Array[]'.

I can avoid that doing something like the following, but that is not nice to get a fluent interface...it's harder to read.

 (<any>[1, 2, [3, 4]]).flatten()
 ([1, 2, [3, 4]].map(e => 5) as any).flatten()

Can I do something in typescript to avoid a casting to any? Like let to know typescript dynamically than the code of type Array has another method.

Body:
You can extend the Array<T> interface to add the flatten method:

declare global {
    interface Array<T> {
        flatten(): T[]
    }
}

Note that you only need to wrap it inside declare global only when you are inside a module. See merging interfaces.