问:
How to automatically add a class to images in the body field in CKeditor
I would like the ability to add a class to images which are added to the body field in Drupal.

I want to keep things as simple as possible for our users, whereby they don't have to add classes etc.  Ideally they would just click on the image button in the toolbar, paste the URL or upload an image and set align either left or right:
Image properties for adding images in CKeditor

I've tried several options, including: CKEditor adding class to img tag but I cannot get anything to work.

The path to CKEditor is to the CDN //cdn.ckeditor.com/4.5.4/full-all

I'd like to us my own SCSS to make the images float left or right at desktop, and be centered for the small breakpoint.

The text format is 'filtered HTML'.

Is there any way I can get this to work?

Many Thanks

Update

Because I'm using the CKEditor CDN, I've added the following to my local 'ckeditor.config.js' file

```<code>config.extraPlugins = 'image, dialog, dialogui';

// Enable local "imagetoolbar" plugin from /myplugins/imagetoolbar/ folder.
CKEDITOR.plugins.addExternal( 'image', '/plugins/image/' 'plugin.js' );
CKEDITOR.plugins.addExternal( 'dialog', '/plugins/dialog/' 'plugin.js' );
CKEDITOR.plugins.addExternal( 'dialogui', '/plugins/dialog/' 'plugin.js' );

// extraPlugins needs to be set too.
CKEDITOR.replace( 'news', {
extraPlugins: 'image, dialog, dialogui'
} );
</code>```

The example I copied this from has 'news' as the CKEDITOR.replace, which I'm sure is wrong, what should this be? https://www.pluginsforckeditor.com/Tutorials/149/How-to-add-a-plugin-to-CKEditor/en/n149.aspx

答:
You can modify the image plugin in order to have the class of the image already entered. So users just have to paste URL or upload an image.

Fill the default field with what you want.

I hope to help you.

Body:
I would like the ability to add a class to images which are added to the body field in Drupal.

I want to keep things as simple as possible for our users, whereby they don't have to add classes etc.  Ideally they would just click on the image button in the toolbar, paste the URL or upload an image and set align either left or right:
Image properties for adding images in CKeditor

I've tried several options, including: CKEditor adding class to img tag but I cannot get anything to work.

The path to CKEditor is to the CDN //cdn.ckeditor.com/4.5.4/full-all

I'd like to us my own SCSS to make the images float left or right at desktop, and be centered for the small breakpoint.

The text format is 'filtered HTML'.

Is there any way I can get this to work?

Many Thanks

Update

Because I'm using the CKEditor CDN, I've added the following to my local 'ckeditor.config.js' file

config.extraPlugins = 'image, dialog, dialogui';

// Enable local "imagetoolbar" plugin from /myplugins/imagetoolbar/ folder.
CKEDITOR.plugins.addExternal( 'image', '/plugins/image/' 'plugin.js' );
CKEDITOR.plugins.addExternal( 'dialog', '/plugins/dialog/' 'plugin.js' );
CKEDITOR.plugins.addExternal( 'dialogui', '/plugins/dialog/' 'plugin.js' );

// extraPlugins needs to be set too.
CKEDITOR.replace( 'news', {
extraPlugins: 'image, dialog, dialogui'
} );

The example I copied this from has 'news' as the CKEDITOR.replace, which I'm sure is wrong, what should this be? https://www.pluginsforckeditor.com/Tutorials/149/How-to-add-a-plugin-to-CKEditor/en/n149.aspx


来源: stackexchange

问:
cannot convert ‘const timeval’ to ‘__time_t {aka long int}’
I'm trying to compile https://sourceforge.net/p/dom-s-orm/code/HEAD/tree/trunk/src/

And whenever I try to compile it I get this error:

```<code>[root@localhost dev]# gmake all
(cd objects; gmake)
gmake[1]: Entering directory '/home/burst/dev/objects'
--> Compiling object helper Account from ../output/objects/Account_.cxx
In file included from ../output/objects/Account_.hxx:11:0,
                 from ../output/objects/Account_.cxx:4:
../build/contrib/DORM/include/Timestamp.hpp: In constructor ‘DORM::Timestamp::Timestamp(const timeval&)’:
../build/contrib/DORM/include/Timestamp.hpp:19:44: error: cannot convert ‘const timeval’ to ‘__time_t {aka long int}’ in initialization
    Timestamp(const struct timeval &t): tv{t} {};
                                            ^
gmake[1]: *** [../build/gmake/objects.gmk:59: ../output/objects/Account_.o] Error 1
gmake[1]: Leaving directory '/home/burst/dev/objects'
gmake: *** [Makefile:5: all] Error 2
</code>```

The content of Timestamp.hpp is:

```<code>#ifndef DORM__INCLUDE__TIMESTAMP_HPP
#define DORM__INCLUDE__TIMESTAMP_HPP

#include <cppconn/sqlstring.h>

#include <string>
#include <ctime>
#include <sys/time.h>

namespace DORM {

    class Timestamp {
        public:
            struct timeval tv;

            Timestamp(): tv{0, 0} {};
            Timestamp(const time_t &t): tv{t, 0} {};
            Timestamp(const struct timeval &t): tv{t} {};

            Timestamp(const std::string time_str);
            Timestamp(sql::SQLString time_str);

            operator time_t() { return tv.tv_sec; };
            operator timeval() { return tv; };
    };

}

#endif
</code>```

Any help is welcomed to be able to fix this.

Thanks a lot!

Regards

答:
Since struct timeval is a simple C struct, it doesn't have a copy constructor. That makes tv{t} in

```<code>Timestamp(const struct timeval &t): tv{t} {};
</code>```

an aggregate initialization (see syntax 2), trying to initialize tv.sec with t. tv.sec is a time_t not a struct timeval, hence the error.

Use parentheses instead like so:

```<code>Timestamp(const struct timeval &t): tv(t) {};
</code>```

OwnerDisplayName: Menaxerius

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to compile https://sourceforge.net/p/dom-s-orm/code/HEAD/tree/trunk/src/

And whenever I try to compile it I get this error:

[root@localhost dev]# gmake all
(cd objects; gmake)
gmake[1]: Entering directory '/home/burst/dev/objects'
--> Compiling object helper Account from ../output/objects/Account_.cxx
In file included from ../output/objects/Account_.hxx:11:0,
                 from ../output/objects/Account_.cxx:4:
../build/contrib/DORM/include/Timestamp.hpp: In constructor ‘DORM::Timestamp::Timestamp(const timeval&)’:
../build/contrib/DORM/include/Timestamp.hpp:19:44: error: cannot convert ‘const timeval’ to ‘__time_t {aka long int}’ in initialization
    Timestamp(const struct timeval &t): tv{t} {};
                                            ^
gmake[1]: *** [../build/gmake/objects.gmk:59: ../output/objects/Account_.o] Error 1
gmake[1]: Leaving directory '/home/burst/dev/objects'
gmake: *** [Makefile:5: all] Error 2

The content of Timestamp.hpp is:

#ifndef DORM__INCLUDE__TIMESTAMP_HPP
#define DORM__INCLUDE__TIMESTAMP_HPP

#include <cppconn/sqlstring.h>

#include <string>
#include <ctime>
#include <sys/time.h>

namespace DORM {

    class Timestamp {
        public:
            struct timeval tv;

            Timestamp(): tv{0, 0} {};
            Timestamp(const time_t &t): tv{t, 0} {};
            Timestamp(const struct timeval &t): tv{t} {};

            Timestamp(const std::string time_str);
            Timestamp(sql::SQLString time_str);

            operator time_t() { return tv.tv_sec; };
            operator timeval() { return tv; };
    };

}

#endif

Any help is welcomed to be able to fix this.

Thanks a lot!

Regards

Body:
Since struct timeval is a simple C struct, it doesn't have a copy constructor. That makes tv{t} in

Timestamp(const struct timeval &t): tv{t} {};

an aggregate initialization (see syntax 2), trying to initialize tv.sec with t. tv.sec is a time_t not a struct timeval, hence the error.

Use parentheses instead like so:

Timestamp(const struct timeval &t): tv(t) {};


问:
sql server management studio code completion
I've noticed that whenever I add tables / stored procs / functions / whatever to a sql server database, that it takes a while for the code completion to pick up that they are now part of the database.

This is really annoying since the code completion and syntax highlighting become totally broken in the workflow scenario where you create a table and then start writing queries or whatever that deal with this new object.

Does anyone know how to get the code completion / syntax highlighting engine to update it's view of what is in the database to get rid of all these spurious invalid object name errors?

答: A guess: Close and reopen SSMS? Lame and ineffective, and I hope there's a better way.</p>

ContentLicense: CC BY-SA 2.5


问:
How to Block barcode value to TextBox but barcode scanner still can use..?
i am going to make POS system. when use the barcode scanner it write the code in any text box that has focused.

***how to avoid that.
in other word i want to get barcode input from back side.where ever user has focused in the window, without write on focused element.

i used the http://a.kabachnik.info/jquery-scannerdetection-tutorial.html
my try as follow :

```<code>$(document).on('focus click', 'input', function(e){

        var clickedEleID = $(this).attr('id');
        $('#'+clickedEleID).unbind();//prevent other eval function trigger
        $(document).scannerDetection({
                timeBeforeScanTest: 100,
                startChar: [120],
                endChar: [13],
                avgTimeByChar: 30,
                onComplete: function(barcode, qty){

                $('#item_barcode').val(barcode);//where the right place, barcode should be display

                $('#'+clickedEleID).val(null);//focused element will clear
                $('#'+clickedEleID).bind();//again bind the other eval
                }
        });
</code>```

});

Note:barcode reader fire keyevent "13" . my application has function for key event "13" to add bill information to data base. so i  added here

$('#'+clickedEleID).unbind();

答:
You can use an option parameter to control this behavior.

Use this if you don't want the value to appear on any text box

```<code> ignoreIfFocusOn: 'input'
</code>```

Another way would be to add a class (something like 'scannerOff') to all the input fields that you want to be ignored, and then use the below option

```<code>ignoreIfFocusOn: '.scannerOff'
</code>```

Body:
i am going to make POS system. when use the barcode scanner it write the code in any text box that has focused.

***how to avoid that.
in other word i want to get barcode input from back side.where ever user has focused in the window, without write on focused element.

i used the http://a.kabachnik.info/jquery-scannerdetection-tutorial.html
my try as follow :

$(document).on('focus click', 'input', function(e){

        var clickedEleID = $(this).attr('id');
        $('#'+clickedEleID).unbind();//prevent other eval function trigger
        $(document).scannerDetection({
                timeBeforeScanTest: 100,
                startChar: [120],
                endChar: [13],
                avgTimeByChar: 30,
                onComplete: function(barcode, qty){

                $('#item_barcode').val(barcode);//where the right place, barcode should be display

                $('#'+clickedEleID).val(null);//focused element will clear
                $('#'+clickedEleID).bind();//again bind the other eval
                }
        });

});

Note:barcode reader fire keyevent "13" . my application has function for key event "13" to add bill information to data base. so i  added here

$('#'+clickedEleID).unbind();

Body:
You can use an option parameter to control this behavior.

Use this if you don't want the value to appear on any text box

 ignoreIfFocusOn: 'input'

Another way would be to add a class (something like 'scannerOff') to all the input fields that you want to be ignored, and then use the below option

ignoreIfFocusOn: '.scannerOff'


问:
Password confirmation isn't working
For the life of me, I can't figure out what I've done wrong. I want a message to pop up when someone tries entering passwords that don't match below is the form code.

function passcheck() {
  var p1 = _("pass1").value;
  var p2 = _("pass2").value;
  if (p1 != p2) {
    status.innerHTML = "Your passwords don't match";
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="signupform" id="signupform" onSubmit="return false;"><div id="password">Create Password:</div>
  <input id="pass1" type="password" maxlength="88" placeholder="●●●●●●●●●">
  <div id="confirm">Confirm Password:</div>
  <input id="pass2" type="password" onBlur="passcheck()" maxlength="88" placeholder="●●●●●●●●●"></code>```

What am I missing?

答:
try this one

function passcheck() {
  var p1 = document.getElementById("p1").value;
  var p2 = document.getElementById("p2").value;
  if (p1 != p2) {
    document.getElementById("status").innerHTML = "Your passwords don't match";
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="signupform" id="signupform" onSubmit="return false;">
  <div id="password">Create Password:</div>
  <input id="p1" type="password" maxlength="88" placeholder="●●●●●●●●●">
  <div id="confirm">Confirm Password:</div>
  <input id="p2" type="password" onBlur="passcheck()" maxlength="88" placeholder="●●●●●●●●●">

  <div id="status" style='color:red'></div></code>```

Title: Password confirmation isn't working

Body:
For the life of me, I can't figure out what I've done wrong. I want a message to pop up when someone tries entering passwords that don't match below is the form code.

function passcheck() {
  var p1 = _("pass1").value;
  var p2 = _("pass2").value;
  if (p1 != p2) {
    status.innerHTML = "Your passwords don't match";
  }
}

<form name="signupform" id="signupform" onSubmit="return false;">
Create Password:

  <input id="pass1" type="password" maxlength="88" placeholder="●●●●●●●●●">

Confirm Password:

  <input id="pass2" type="password" onBlur="passcheck()" maxlength="88" placeholder="●●●●●●●●●">

What am I missing?

Body:
try this one

function passcheck() {
  var p1 = document.getElementById("p1").value;
  var p2 = document.getElementById("p2").value;
  if (p1 != p2) {
    document.getElementById("status").innerHTML = "Your passwords don't match";
  }
}

<form name="signupform" id="signupform" onSubmit="return false;">
  <div id="password">Create Password:</div>
  <input id="p1" type="password" maxlength="88" placeholder="&#9679;&#9679;&#9679;&#9679;&#9679;&#9679;&#9679;&#9679;&#9679;">
  <div id="confirm">Confirm Password:</div>
  <input id="p2" type="password" onBlur="passcheck()" maxlength="88" placeholder="&#9679;&#9679;&#9679;&#9679;&#9679;&#9679;&#9679;&#9679;&#9679;">

  <div id="status" style='color:red'></div>


问:
How to add favicon.ico on beego?
my routers/default.go, I'm trying to use the original Go solution, but failed, this code can't compiled. I don't know how to replace the router with faviconHandler:</p>

```<code>func faviconHandler(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, "static/img/favicon.ico")
}
func init() {
        beego.Router("/", &controllers.MainController{})
        beego.Router("/favicon.ico", faviconHandler)  // this doesn't work
}
</code>```

答:
Put your favicon.ico file at ./static/ directory

Check this https://beego.me/docs/quickstart/static.md

Title: How to add favicon.ico on beego?

Body:
my routers/default.go, I'm trying to use the original Go solution, but failed, this code can't compiled. I don't know how to replace the router with faviconHandler:

func faviconHandler(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, "static/img/favicon.ico")
}
func init() {
        beego.Router("/", &controllers.MainController{})
        beego.Router("/favicon.ico", faviconHandler)  // this doesn't work
}


问:
Error with expressive annotations requiredif validator
This is my view

```<code>     <div id="Domain">
            <ul class="formlist">
                <li class="width100">
                    <div class="form-check form-check-inline">
                        <label class="form-check-label">
                            @Html.RadioButtonFor(model => model.domain_flag, 1, new { @class = "form-check-input" }) <span>Yes</span>
                        </label>
                    </div>
                    <div class="form-check form-check-inline">
                        <label class="form-check-label">
                            @Html.RadioButtonFor(model => model.domain_flag, 0, new { @class = "form-check-input", @checked = "checked" }) <span>No</span>
                        </label>
                    </div>
                </li>
            </ul>

            <ul class="formlist">
                <li>
                    <div class="frm-marg-b">
                        <label class="label"><b>@Html.LabelFor(model => model.domain_renew_date)</b></label>
                        <div class="textbx">
                            <div class="input-group">
                                @Html.TextBoxFor(model => model.domain_renew_date, new { @type = "datetime", @class = "form-control" })
                                @Html.ValidationMessageFor(model => model.domain_renew_date, "", new { @class = "text-danger" })
                            </div>
                        </div>
                    </div>
                    <div class="frm-marg-b">
                        <label class="label"><b>@Html.LabelFor(model => model.domain_vendor_id)</b></label>
                        <div class="textbx">
                            @Html.DropDownListFor(model => model.domain_vendor_id, Model.domain_Vendor, "Please Select")
                            @Html.ValidationMessageFor(model => model.domain_vendor_id, "", new { @class = "text-danger" })
                        </div>
                    </div>
                </li>
                <li>
                    <div class="frm-marg-b">
                        <label class="label"><b>@Html.LabelFor(model => model.domain_exp_date)</b></label>
                        <div class="textbx">
                            <div class="input-group">
                                @Html.TextBoxFor(model => model.domain_exp_date, new { @type = "datetime", @class = "form-control" })
                                @Html.ValidationMessageFor(model => model.domain_exp_date, "", new { @class = "text-danger" })
                            </div>
                        </div>
                    </div>
                    <div class="frm-marg-b">
                        <label class="label"><b>@Html.LabelFor(model => model.domain_amt)</b></label>
                        <div class="textbx">
                            @Html.EditorFor(model => model.domain_amt, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.domain_amt, "", new { @class = "text-danger" })
                        </div>
                    </div>
                </li>
                <li class="width100">
                    <div class="frm-marg-b">
                        <label class="label"><b>@Html.LabelFor(model => model.domain_remarks)</b></label>
                        <div class="textbx3">
                            @Html.TextAreaFor(model => model.domain_remarks, new { htmlAttributes = new { @class = "form-control", @rows = 2 } })
                            @Html.ValidationMessageFor(model => model.domain_remarks, "", new { @class = "text-danger" })
                        </div>
                    </div>
                </li>
            </ul>
        </div>
</code>```

My model

```<code>    public int? domain_flag { get; set; }
    [Display(Name = "Date of Renewal")]
    [DataType(DataType.Date)]
    [RequiredIf("domain_flag==1",ErrorMessage ="Enter Renew Date")]
    public DateTime? domain_renew_date { get; set; }
    [Display(Name = "Date of Expiry")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:mm/dd/yy}", ApplyFormatInEditMode = true)]
    [RequiredIf("domain_flag==1", ErrorMessage = "Enter Expiry Date")]
    public DateTime? domain_exp_date { get; set; }
    [Display(Name = "Vendor")]
    [RequiredIf("domain_flag==1", ErrorMessage = "Please Select Vendor")]
    public int? domain_vendor_id { get; set; }
    [Display(Name = "Amount(Rs.)")]
    [RequiredIf("domain_flag==1", ErrorMessage = "Enter Amount")]
    [RegularExpression("^[0-9]+$", ErrorMessage = "Enter Numeric Values")]
    public decimal? domain_amt { get; set; }
    [Display(Name = "Comments")]
    public string domain_remarks { get; set; }
</code>```

Global.asax

```<code>                     DataAnnotationsModelValidatorProvider.RegisterAdapter(
            typeof(RequiredIfAttribute), typeof(RequiredIfValidator));
        DataAnnotationsModelValidatorProvider.RegisterAdapter(
            typeof(AssertThatAttribute), typeof(AssertThatValidator));
</code>```

In this as soon as I select the radio button the required if error messages are displayed before entering the values. The error messages should be displayed on click of submit button before posting to the server. Is this possible with expressive annotations nuget package?

答:
Yes it's possible with ExpressiveAnnotations.

@jwaliszko mentioned it.

You have to set the configuation of ea like this at client-side:

```<code><script>
    ea.settings.dependencyTriggers = '';
</code>```

Body:
This is my view

                            @Html.RadioButtonFor(model => model.domain_flag, 1, new { @class = "form-check-input" }) Yes

                            @Html.RadioButtonFor(model => model.domain_flag, 0, new { @class = "form-check-input", @checked = "checked" }) No

                        @Html.LabelFor(model => model.domain_renew_date)

                                @Html.TextBoxFor(model => model.domain_renew_date, new { @type = "datetime", @class = "form-control" })
                                @Html.ValidationMessageFor(model => model.domain_renew_date, "", new { @class = "text-danger" })

                        @Html.LabelFor(model => model.domain_vendor_id)

                            @Html.DropDownListFor(model => model.domain_vendor_id, Model.domain_Vendor, "Please Select")
                            @Html.ValidationMessageFor(model => model.domain_vendor_id, "", new { @class = "text-danger" })

                        @Html.LabelFor(model => model.domain_exp_date)

                                @Html.TextBoxFor(model => model.domain_exp_date, new { @type = "datetime", @class = "form-control" })
                                @Html.ValidationMessageFor(model => model.domain_exp_date, "", new { @class = "text-danger" })

                        @Html.LabelFor(model => model.domain_amt)

                            @Html.EditorFor(model => model.domain_amt, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.domain_amt, "", new { @class = "text-danger" })

                        @Html.LabelFor(model => model.domain_remarks)

                            @Html.TextAreaFor(model => model.domain_remarks, new { htmlAttributes = new { @class = "form-control", @rows = 2 } })
                            @Html.ValidationMessageFor(model => model.domain_remarks, "", new { @class = "text-danger" })

My model

    public int? domain_flag { get; set; }
    [Display(Name = "Date of Renewal")]
    [DataType(DataType.Date)]
    [RequiredIf("domain_flag==1",ErrorMessage ="Enter Renew Date")]
    public DateTime? domain_renew_date { get; set; }
    [Display(Name = "Date of Expiry")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:mm/dd/yy}", ApplyFormatInEditMode = true)]
    [RequiredIf("domain_flag==1", ErrorMessage = "Enter Expiry Date")]
    public DateTime? domain_exp_date { get; set; }
    [Display(Name = "Vendor")]
    [RequiredIf("domain_flag==1", ErrorMessage = "Please Select Vendor")]
    public int? domain_vendor_id { get; set; }
    [Display(Name = "Amount(Rs.)")]
    [RequiredIf("domain_flag==1", ErrorMessage = "Enter Amount")]
    [RegularExpression("^[0-9]+$", ErrorMessage = "Enter Numeric Values")]
    public decimal? domain_amt { get; set; }
    [Display(Name = "Comments")]
    public string domain_remarks { get; set; }

Global.asax

                     DataAnnotationsModelValidatorProvider.RegisterAdapter(
            typeof(RequiredIfAttribute), typeof(RequiredIfValidator));
        DataAnnotationsModelValidatorProvider.RegisterAdapter(
            typeof(AssertThatAttribute), typeof(AssertThatValidator));

In this as soon as I select the radio button the required if error messages are displayed before entering the values. The error messages should be displayed on click of submit button before posting to the server. Is this possible with expressive annotations nuget package?

Body:
Yes it's possible with ExpressiveAnnotations.

@jwaliszko mentioned it.

You have to set the configuation of ea like this at client-side:

<script>
    ea.settings.dependencyTriggers = '';


问:
How to add an onclick method on dynamically created button using jquery
I am fetching data from a php file using ajax. Looping through json object and creating buttons using ajax. I want to add an onclick event on that dynamically created button so that i can call a function, pass the current ID of the record to it, and then do some things to it like deleting or updating.

```<code>'<button type="button" onclick="test()" id="btnHistory" class="btn btn-success">History</button> '
</code>```

but it leaves me an error saying the test function isn't defined.

here's my whole code:

```<code>$.ajax({
    type: "POST",
    url: "../php_scripts/getUnits.php",
    success: function(data){
        var items = JSON.parse(data);

        /*var btnSomething = $("<button>")
        .attr('class', 'btn btn-danger')
        .attr('id', 'asdf')
        .html('Save');
*/

//$('#content').append(btnSomething);

        for (var i = 0; i < items.length; i++) {

            //test();
            $('#myTable').append('<tr><td>' + items[i].unitId + '</td><td>'+
             items[i].pcName +'</td><td>'+ items[i].user + '</td><td>'+
             items[i].department+'</td><td>'+items[i].location+ '</td><td>'+
             items[i].dateAssigned + '</td><td>' + items[i].status +'</td><td>' +
             '<button type="button" onclick="test()" id="btnHistory" class="btn btn-success">History</button> ' +
             '<button id="btnUpdate" class="btn btn-primary">Update</button> ' +
             '<button id="btnDelete" class="btn btn-danger">Delete</button> ' +
             '</td></tr>');
        }

        function test(){
            alert('test');
        }

        /*$(document).on("click", "#btnHistory", function(){
          alert ('History clicked ');
        });*/

    }
});
</code>```

答:
Simple add this function on your script

```<code>function test() {
    alert('working');
//    your code
}
</code>```

It will work for you.

Body:
I am fetching data from a php file using ajax. Looping through json object and creating buttons using ajax. I want to add an onclick event on that dynamically created button so that i can call a function, pass the current ID of the record to it, and then do some things to it like deleting or updating.

'<button type="button" onclick="test()" id="btnHistory" class="btn btn-success">History</button> '

but it leaves me an error saying the test function isn't defined.

here's my whole code:

$.ajax({
    type: "POST",
    url: "../php_scripts/getUnits.php",
    success: function(data){
        var items = JSON.parse(data);

        /*var btnSomething = $("<button>")
        .attr('class', 'btn btn-danger')
        .attr('id', 'asdf')
        .html('Save');
*/

//$('#content').append(btnSomething);

        for (var i = 0; i < items.length; i++) {

            //test();
            $('#myTable').append('
' + items[i].unitId + '	'+
             items[i].pcName +'	'+ items[i].user + '	'+
             items[i].department+'	'+items[i].location+ '	'+
             items[i].dateAssigned + '	' + items[i].status +'	' +
             '<button type="button" onclick="test()" id="btnHistory" class="btn btn-success">History</button> ' +
             '<button id="btnUpdate" class="btn btn-primary">Update</button> ' +
             '<button id="btnDelete" class="btn btn-danger">Delete</button> ' +
             '
');
        }

        function test(){
            alert('test');
        }

        /*$(document).on("click", "#btnHistory", function(){
          alert ('History clicked ');
        });*/

    }
});

Body:
Simple add this function on your script

function test() {
    alert('working');
//    your code
}

It will work for you.


问:
How to scroll down with sikuli
How to scroll down with Sikuli in Selenium Eebdriver with java?

I am using screen.wheel(1 , 8); in my code to scroll down in an open window.

Sometimes it works fine but after running my script 4-5 times it behaves differently. Instead of scrolling vertically it starts scrolling horizontally.

```<code>s.doubleClick("C:\\SikuliX\\Images\\C_Drive.png");
s.wheel( 1, 8);
s.doubleClick("C:\\SikuliX\\Images\\DestinFolder.png");
s.doubleClick("C:\\SikuliX\\Images\\CfgFolder.png")
</code>```

Please help and let me know how I can move the scrollbar vertically for specific steps and in particular window.

答:
You can simply use shortcuts:

Windows Example:

```<code>type(Key.PAGE_DOWN) - scroll down 1 time
type(Key.PAGE_UP) - scroll up 1 time
</code>```

Also if you want to repeat it a few times:

```<code>type(Key.PAGE_DOWN*3) - scroll down 3 times
</code>```

MAC Example:

```<code>type(Key.DOWN, KeyModifier.CMD) - scroll all the way down
</code>```

NOTE:
If you really want to scroll down with the mouse wheel:

```<code>Mouse.wheel(WHEEL_UP, 1)
Mouse.wheel(WHEEL_DOWN, 2)
</code>```

Title: How to scroll down with sikuli

Body:
How to scroll down with Sikuli in Selenium Eebdriver with java?

I am using screen.wheel(1 , 8); in my code to scroll down in an open window.

Sometimes it works fine but after running my script 4-5 times it behaves differently. Instead of scrolling vertically it starts scrolling horizontally.

s.doubleClick("C:\\SikuliX\\Images\\C_Drive.png");
s.wheel( 1, 8);
s.doubleClick("C:\\SikuliX\\Images\\DestinFolder.png");
s.doubleClick("C:\\SikuliX\\Images\\CfgFolder.png")

Please help and let me know how I can move the scrollbar vertically for specific steps and in particular window.

Body:
You can simply use shortcuts:

Windows Example:

type(Key.PAGE_DOWN) - scroll down 1 time
type(Key.PAGE_UP) - scroll up 1 time

Also if you want to repeat it a few times:

type(Key.PAGE_DOWN*3) - scroll down 3 times

MAC Example:

type(Key.DOWN, KeyModifier.CMD) - scroll all the way down

NOTE:
If you really want to scroll down with the mouse wheel:

Mouse.wheel(WHEEL_UP, 1)
Mouse.wheel(WHEEL_DOWN, 2)

ContentLicense: CC BY-SA 4.0


问:
wso2 identity server dashboard forgot password/forgot username not working
I followed the below steps to enable password recovery using email notification.

https://docs.wso2.com/display/IS530/Password+Recovery

When I click forgot password button on dashboard login page, it asks for username and after that throw below error

Code : 20017
Message :Notification based password recovery is not enabled

I checked code in github and found property recovery.notification.password.enable is used but could not locate in any config file or any documentation. I am using WSO2IS 5.3.0.
How can i enable password recovery through end user dashboard if not mentioned in above mentioned steps.

答:
Assume you are following the old and deprecated method. The steps for new APIs are available at the REST API Guide, It is also linked from the section "Password recovery using REST APIs" in the page you referred.

What you need to do is enable the Notification Based Password Recovery Enabled at the Resident Identity Provider configuration at management console and optionally set the expiry time for notifications.


问:
how to Consider the alternatives of 'throw and catch'?
I'm doing the following Ruby Tutorial http://rubymonk.com/learning/books/4-ruby-primer-ascent/chapters/41-exceptions/lessons/93-throw-and-catch.  One of the exercises asks me to:

Change the last example to return the found tile from a method called
  search, instead. search should receive the floor plan as a parameter.

exercise is similar to last example(before exercise) and looks like:

```<code>candy = catch(:found) do
    floor.each do |row|
    row.each do |tile|
        throw(:found, tile) if tile == "jawbreaker" || tile == "gummy"
    end
    end
end
puts candy
</code>```

there is a hint below exercise:

Try replacing the 'catch' line with a method definition and the
  'throw' line with a 'return'.

and i did so:

```<code>candy = search do
    floor.each do |row|
    row.each do |tile|
      return tile if tile == "jawbreaker" || tile == "gummy"
    end
    end
end
puts candy
</code>```

but received error.  can anyone tell me how to do to get the positive result.  and additional question: why is catch(:found) and different throw(:found, tile) in throw / catch code?

答:
okay so i did this and it worked for me. the code is pretty self explanatory if you have reached this far in ruby</p>

```<code>floor = [["blank", "blank", "blank"],
     ["gummy", "blank", "blank"],
     ["blank", "blank", "blank"]]
def search(floor)
floor.each do |row|
row.each do |tile|
  return tile if tile == "jawbreaker" || tile == "gummy"
end
end
end

candy = lambda {|floor| search(floor)}
puts candy.call(floor)
</code>```

Body:
I'm doing the following Ruby Tutorial http://rubymonk.com/learning/books/4-ruby-primer-ascent/chapters/41-exceptions/lessons/93-throw-and-catch.  One of the exercises asks me to:

Change the last example to return the found tile from a method called
  search, instead. search should receive the floor plan as a parameter.

exercise is similar to last example(before exercise) and looks like:

candy = catch(:found) do
    floor.each do |row|
    row.each do |tile|
        throw(:found, tile) if tile == "jawbreaker" || tile == "gummy"
    end
    end
end
puts candy

there is a hint below exercise:

Try replacing the 'catch' line with a method definition and the
  'throw' line with a 'return'.

and i did so:

candy = search do
    floor.each do |row|
    row.each do |tile|
      return tile if tile == "jawbreaker" || tile == "gummy"
    end
    end
end
puts candy

but received error.  can anyone tell me how to do to get the positive result.  and additional question: why is catch(:found) and different throw(:found, tile) in throw / catch code?

Body:
okay so i did this and it worked for me. the code is pretty self explanatory if you have reached this far in ruby

floor = [["blank", "blank", "blank"],
     ["gummy", "blank", "blank"],
     ["blank", "blank", "blank"]]
def search(floor)
floor.each do |row|
row.each do |tile|
  return tile if tile == "jawbreaker" || tile == "gummy"
end
end
end

candy = lambda {|floor| search(floor)}
puts candy.call(floor)


问:
Why does flexbox not center my image?
```<code>section
{
background-color: #EEEEEE;
margin: 10vmin 5vmin;
padding: 2vmin;
display: flex;
justify-content: center;
align-items: center;
flex-flow: column wrap;
}

img
{
height: 30vmax;
border: 1vmin solid black;
border-radius: 30vmax;
margin: 1vmin;
}
</code>```

Entire source code available here : https://codepen.io/de_arth/pen/dvLoyO/

Basically, I'm able to center everything BUT an image, (and a link in the very last section) with flexbox, even though it should be in a single straight line on mobile and desktop displays. What am I doing wrong?

答:
Your code work as is, though there is a invisible/invalid space character in front of these 3 lines

```<code>display: flex;
justify-content: center;
align-items: center;
</code>```

Here is an updated codepen with the same code you already have, where I rewrote those 3 lines

And here is a Stack snippet

body
{
  background-color: #FAFAFA;
}

section
{
  background-color: #EEEEEE;
  margin: 10vmin 5vmin;
  padding: 2vmin;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-flow: column wrap;
}

img
{
  height: 30vmax;
  border: 1vmin solid black;
  border-radius: 30vmax;
  margin: 1vmin;
}

h1, h2
{
  margin: 2vmin;
  text-align: center;
  margin: 5vmin;
}

h1
{
  font-family: 'Roboto', sans-serif;
  font-size: 8vw;
}

h2
{
  font-family: 'Raleway', sans-serif;
  font-size: 3vw;
  font-style: italic;
}

h3
{
  font-family: 'Roboto', sans-serif;
  font-size: 4vw;
  text-align: center;
  margin-bottom: 4vw;
}

p
{
  font-family: 'Raleway', sans-serif;
  font-size: 3vw;
  text-align: center;
}

a
{
  font-family: 'Raleway', sans-serif;
  margin-top: 30vmin;
  text-align: center;
}

#awards > p
{
  line-height: 7vw;
}

@media screen and (min-width: 40.5em)
{

  section
  {
    height: 100vh;
  }

  h1
  {
    font-size: 5vw;
  }

  h2
  {
    font-size: 3vw;
  }

  h3
  {
    font-size: 3vw;
    margin-top: 1vw;
    margin-bottom: 0;
  }

  p
  {
    font-size: 2vw;
    line-height: 2.5vw;
    margin: 0;
  }

  #awards > p
  {
    line-height: 4vw;
  }

  a
  {
    margin-top: 2vw;
    font-size: 3vw;
  }

  section:not(#intro) > h1
  {
    margin: 1vw;
  }

  section:not(#intro) > div
  {
    margin: 1vw;
  }

  footer > p
  {
    margin-bottom: 1vw;
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
  <link href="https://fonts.googleapis.com/css?family=Raleway:300|Roboto" rel="stylesheet">
</head>

<section id = "intro">
  <img src = "https://assets.kennislink.nl/system/files/000/134/321/large/Richard_Feynman_Nobel.jpg?1494968180">
  <div>
    <h1> Richard Feynman </h1>
    <h2> Physicist. Prankster. Genius. </h2>
  </div>
</section>

<section id = "early">
  <h1> Early Life </h1>
  <div>
    <h3> 1918 </h3>
    <p> Born in Queens, New York. </p>
    <h3> 1933 </h3>
    <p> Teaches himself trigonometry, advanced algebra, infinite series, analytic geometry and calculus. </p>
    <h3> 1939 </h3>
    <p> Obtains his B.Sc from the Massachusetts Institute of Technology. </p>
    <h3> 1942 </h3>
    <p> Obtains his PhD from Princeton University. Marries Arline Greenbaum. </h3>
  </div>
</section>

<section id = "bomb">
  <h1> Manhattan Project </h1>
  <div>
    <h3> 1942 </h3>
    <p> Recruited into the project by R R Wilson. </p>
    <h3> 1943 </h3>
    <p> Redloyed at Los Alamos Laboratory, in New Mexico and made group leader.</p>
    <h3> 1945 </h3>
    <p> First wife dies of Tuberculosis. Becomes the only person to see the explosion at the Trinity Nuclear Test without any protection. </p>
  </div>
</section>

<section id = "later">
  <h1> Cornell </h1>
  <div>
    <h3> 1945 </h3>
    <p> Hired as Professor of Theoretical Physics at Cornell University. </p>
    <h3> 1946 </h3>
    <p> Feigns mental illness to avoid being drafted, and later suffers from depression as his father dies. Solves less practical problems due to lack of focus.  </p>
    <h3> 1948 </h3>
    <p> Delivers his first presentation involving Feynman diagrams, and is met with many objections. </p>
    <h3> 1950 </h3>
    <p> Papers citing the Feynman diagrams soon become prevalent, as a tool of unprecedented power. </p>
  </div>
</section>

<section id = "caltech">
  <h1> Caltech </h1>
  <div>
    <h3> 1952 </h3>
    <p> Appointed Professor of Theoretical Physics at California Institute of Technology. Marries Mary Louise Bell. </p>
    <h3> 1958 </h3>
    <p> A divorce is final after a stormy marriage, on the grounds of extreme cruelty. </p>
    <h3> 1960 </h3>
    <p> Marries Gweneth Howarth. Carl was born in 1962, and Michelle was adopted in 1968. </p>
    <h3> 1988 </h3>
    <p> Dies following kidney failure, after a decade long battle with cancer. </p>
  </div>
</section>

<section id = "awards">
  <h1> Awards </h1>
  <p> Albert Einstein Award - 1954 <br> Ernest Orlando Lawrence Award - 1962 <br> The Nobel Prize in Physics - 1965 <br> Oersted Medal - 1972 <br> National Medal of Science - 1979 </p>
   Read more on Wikipedia
</section>

<footer>
  <p> Designed and compiled by Arvind S </p>
</footer></code>```

Title: Why does flexbox not center my image?

Body:
section
{
background-color: #EEEEEE;
margin: 10vmin 5vmin;
padding: 2vmin;
display: flex;
justify-content: center;
align-items: center;
flex-flow: column wrap;
}

img
{
height: 30vmax;
border: 1vmin solid black;
border-radius: 30vmax;
margin: 1vmin;
}

Entire source code available here : https://codepen.io/de_arth/pen/dvLoyO/

Basically, I'm able to center everything BUT an image, (and a link in the very last section) with flexbox, even though it should be in a single straight line on mobile and desktop displays. What am I doing wrong?

Body:
Your code work as is, though there is a invisible/invalid space character in front of these 3 lines

display: flex;
justify-content: center;
align-items: center;

Here is an updated codepen with the same code you already have, where I rewrote those 3 lines

And here is a Stack snippet

body
{
  background-color: #FAFAFA;
}

section
{
  background-color: #EEEEEE;
  margin: 10vmin 5vmin;
  padding: 2vmin;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-flow: column wrap;
}

img
{
  height: 30vmax;
  border: 1vmin solid black;
  border-radius: 30vmax;
  margin: 1vmin;
}

h1, h2
{
  margin: 2vmin;
  text-align: center;
  margin: 5vmin;
}

h1
{
  font-family: 'Roboto', sans-serif;
  font-size: 8vw;
}

h2
{
  font-family: 'Raleway', sans-serif;
  font-size: 3vw;
  font-style: italic;
}

h3
{
  font-family: 'Roboto', sans-serif;
  font-size: 4vw;
  text-align: center;
  margin-bottom: 4vw;
}

p
{
  font-family: 'Raleway', sans-serif;
  font-size: 3vw;
  text-align: center;
}

a
{
  font-family: 'Raleway', sans-serif;
  margin-top: 30vmin;
  text-align: center;
}

#awards > p
{
  line-height: 7vw;
}

@media screen and (min-width: 40.5em)
{

  section
  {
    height: 100vh;
  }

  h1
  {
    font-size: 5vw;
  }

  h2
  {
    font-size: 3vw;
  }

  h3
  {
    font-size: 3vw;
    margin-top: 1vw;
    margin-bottom: 0;
  }

  p
  {
    font-size: 2vw;
    line-height: 2.5vw;
    margin: 0;
  }

  #awards > p
  {
    line-height: 4vw;
  }

  a
  {
    margin-top: 2vw;
    font-size: 3vw;
  }

  section:not(#intro) > h1
  {
    margin: 1vw;
  }

  section:not(#intro) > div
  {
    margin: 1vw;
  }

  footer > p
  {
    margin-bottom: 1vw;
  }

}

<head>
  <link href="https://fonts.googleapis.com/css?family=Raleway:300|Roboto" rel="stylesheet">
</head>

<section id = "intro">
  <img src = "https://assets.kennislink.nl/system/files/000/134/321/large/Richard_Feynman_Nobel.jpg?1494968180">
  <div>
    <h1> Richard Feynman </h1>
    <h2> Physicist. Prankster. Genius. </h2>
  </div>
</section>

<section id = "early">
  <h1> Early Life </h1>
  <div>
    <h3> 1918 </h3>
    <p> Born in Queens, New York. </p>
    <h3> 1933 </h3>
    <p> Teaches himself trigonometry, advanced algebra, infinite series, analytic geometry and calculus. </p>
    <h3> 1939 </h3>
    <p> Obtains his B.Sc from the Massachusetts Institute of Technology. </p>
    <h3> 1942 </h3>
    <p> Obtains his PhD from Princeton University. Marries Arline Greenbaum. </h3>
  </div>
</section>

<section id = "bomb">
  <h1> Manhattan Project </h1>
  <div>
    <h3> 1942 </h3>
    <p> Recruited into the project by R R Wilson. </p>
    <h3> 1943 </h3>
    <p> Redloyed at Los Alamos Laboratory, in New Mexico and made group leader.</p>
    <h3> 1945 </h3>
    <p> First wife dies of Tuberculosis. Becomes the only person to see the explosion at the Trinity Nuclear Test without any protection. </p>
  </div>
</section>

<section id = "later">
  <h1> Cornell </h1>
  <div>
    <h3> 1945 </h3>
    <p> Hired as Professor of Theoretical Physics at Cornell University. </p>
    <h3> 1946 </h3>
    <p> Feigns mental illness to avoid being drafted, and later suffers from depression as his father dies. Solves less practical problems due to lack of focus.  </p>
    <h3> 1948 </h3>
    <p> Delivers his first presentation involving Feynman diagrams, and is met with many objections. </p>
    <h3> 1950 </h3>
    <p> Papers citing the Feynman diagrams soon become prevalent, as a tool of unprecedented power. </p>
  </div>
</section>

<section id = "caltech">
  <h1> Caltech </h1>
  <div>
    <h3> 1952 </h3>
    <p> Appointed Professor of Theoretical Physics at California Institute of Technology. Marries Mary Louise Bell. </p>
    <h3> 1958 </h3>
    <p> A divorce is final after a stormy marriage, on the grounds of extreme cruelty. </p>
    <h3> 1960 </h3>
    <p> Marries Gweneth Howarth. Carl was born in 1962, and Michelle was adopted in 1968. </p>
    <h3> 1988 </h3>
    <p> Dies following kidney failure, after a decade long battle with cancer. </p>
  </div>
</section>

<section id = "awards">
  <h1> Awards </h1>
  <p> Albert Einstein Award - 1954 <br> Ernest Orlando Lawrence Award - 1962 <br> The Nobel Prize in Physics - 1965 <br> Oersted Medal - 1972 <br> National Medal of Science - 1979 </p>
  <a href = "https://en.wikipedia.org/wiki/Richard_Feynman"> Read more on Wikipedia </a>
</section>

<footer>
  <p> Designed and compiled by Arvind S </p>
</footer>


问:
Can't load expo app: Something went wrong
I've created an expo app with exp init MyApp command and started it by running exp start in MyApp directory.

Then I'm scanning barcode which was printed in console with expo mobile app on android device.

Then "Something went wrong" screen is rendered instead of the app.

View log shows "Uncaught Error: Couldn't load exp://.....".

No errors in expo packager console output.

It used to work sometimes ago.

答: In my case, expo app was outdated. I just updated expo from store and it started working. </p>


问:
Parallax scroll text jumps on top on first scroll
Text jumps to the top on first scroll if the property is position:fixed; top:500px or 40% and its invisible, until first scroll if the property is margin-top:500px;

link to the site: http://www.pappu-lighting.com/Series/Kutiq/LAST.html
(the word GEOMETRY)

The code for it:

```<code>#seriq {
color:white;
z-index:9999;
position:absolute;
font-family:futuraat;
font-size:5vw;
padding:0px;
top:70%;
width:100%;
text-align:center;
}
</code>```

I want to make it visible from the beginning and not to jerk to the top.

答:
You can use position:sticky; for the element to stick to particular position as it scrolls and be visible throughtout

https://developer.mozilla.org/en/docs/Web/CSS/position

Body:
Text jumps to the top on first scroll if the property is position:fixed; top:500px or 40% and its invisible, until first scroll if the property is margin-top:500px;

link to the site: http://www.pappu-lighting.com/Series/Kutiq/LAST.html
(the word GEOMETRY)

The code for it:

#seriq {
color:white;
z-index:9999;
position:absolute;
font-family:futuraat;
font-size:5vw;
padding:0px;
top:70%;
width:100%;
text-align:center;
}

I want to make it visible from the beginning and not to jerk to the top.


问:
How to convert viewbag string to int in mvc
In mvc view page i have a view bag name passed from controller.

```<code> <p class="plan-price">@item.Currency@item.Amount
   <span class="plan-unit">
     per month
   </span>
 </p>
</code>```

For example, here Amount is 2900 means how to display 29 ?

答:
You can use all the usual C# number parsing methods when using Razor syntax e.g.
@(int.Parse(Model.MyStringProperty)/100)

Remember that you will need to handle cases where the string is null, empty or not a number.

Body:
In mvc view page i have a view bag name passed from controller.

@item.Currency@item.Amount

     per month

For example, here Amount is 2900 means how to display 29 ?

Body:
You can use all the usual C# number parsing methods when using Razor syntax e.g. <p>@(int.Parse(Model.MyStringProperty)/100)</p>

Remember that you will need to handle cases where the string is null, empty or not a number.


问:
Why my Django view return None as HttpResponse?
This is a function I used in Django view to accept post request, however it returns None sometimes, any idea about this problem?

```<code>def acceptpost(request):
    try:
        print "request.method:", request.method
        print "content_type:", request.content_type
        print "request.body:",request.body
        time.sleep(0.1)
    except Exception as e:
        log.error(e)
        return HttpResponse("error")
    return HttpResponse("OK")
</code>```

The function I used to post data is:

```<code>def post_data(url, data)
    try:
        req = requests.post(url=url, data=data, verify=False)
        response = req.status_code
        content = req.content
    except RequestException as e:
        response = e.response
        log_debug.error("HttpResponse: %s" % response)
        continue
</code>```

This function is in While True,
url is: url = 'http://127.0.0.1:8000/acceptpost/'.

In most of time, I could get the right HttpResponse, which is "ok" in this case, and some time I could only get None, both of the two function runs on localhost, the web server is the Django web server with the address http://127.0.0.1/acceptpost/.
I have not catch any log in function acceptpost, however there are HttpResponse None occasionally, is any idea about this problem?

答:
Your code in itself doesn't seem to have a problem. The None you get comes from e.response which here equals None. This probably means that your request was not sent, thus there is no response to it.

RequestException is a generic exception covering several kind of exceptions. I suggest you see this manual page  (not sure if it is up to date but still gives a pretty good insight of the many exceptions you can get). Differentiating most exceptions in your code will help you debug it I think.

Body:
This is a function I used in Django view to accept post request, however it returns None sometimes, any idea about this problem?

def acceptpost(request):
    try:
        print "request.method:", request.method
        print "content_type:", request.content_type
        print "request.body:",request.body
        time.sleep(0.1)
    except Exception as e:
        log.error(e)
        return HttpResponse("error")
    return HttpResponse("OK")

The function I used to post data is:

def post_data(url, data)
    try:
        req = requests.post(url=url, data=data, verify=False)
        response = req.status_code
        content = req.content
    except RequestException as e:
        response = e.response
        log_debug.error("HttpResponse: %s" % response)
        continue

This function is in While True,
url is: url = 'http://127.0.0.1:8000/acceptpost/'.

In most of time, I could get the right HttpResponse, which is "ok" in this case, and some time I could only get None, both of the two function runs on localhost, the web server is the Django web server with the address http://127.0.0.1/acceptpost/.
I have not catch any log in function acceptpost, however there are HttpResponse None occasionally, is any idea about this problem?


问:
Make a whole div clickable in order to launch a _blank document
How can I write the _blank statement in this location.href call?

```<code>  <div onclick="location.href='http://www.test.com';" style="display:block; height:40px; width:100px; cursor:pointer;"></div>
</code>```

Please note: I need to keep the div and treat it as a href container.

When someone clicks it should open a new browser window, not a popup box.

答:
```<code><div onclick="window.open('http://www.test.com','new_window');" style="display:block; height:40px; width:100px; cursor:pointer;">test</div>
</code>```

Body:
How can I write the _blank statement in this location.href call?

Please note: I need to keep the div and treat it as a href container.

When someone clicks it should open a new browser window, not a popup box.


问:
Google Mock: Mock private variable member that is instantiated in target class's constructor
My question is the same as Mockito: Mock private field initialization but for Google Mock framework. In a nutshell:

```<code>class Target {
private:
    Person person = new Person();

public:
    void testMethod() {
        person.someMethod();
    }
};
</code>```

How can I mock the person instance while making unit tests for Target class?

答:
A non-answer here: simply don't do it this way.

Your problem is the call to new here. Thing is: that makes testing hard, and it also creates a very tight coupling between the Target and the Person class.

The default alternative is: provide a factory to the Target class that creates Person objects for you.

By going for that solution, you

avoid to need to mock the call to new

you end up with a better design!

And unless I am misreading the documentation, mocking calls to new isn't possible with C++ mocking anyway.

Body:
My question is the same as Mockito: Mock private field initialization but for Google Mock framework. In a nutshell:

class Target {
private:
    Person person = new Person();

public:
    void testMethod() {
        person.someMethod();
    }
};

How can I mock the person instance while making unit tests for Target class?


问:
Lost connection to MySQL server during query
I have a huge table and I need to process all rows in it. I'm always getting this Lost connection message and I'm not able to reconnect and restore the cursor to the last position it was. This is basically the code I have here:

```<code>#
import MySQLdb

class DB:
  conn = None

  def connect(self):
    self.conn = MySQLdb.connect('hostname', 'user', '*****', 'some_table', cursorclass=MySQLdb.cursors.SSCursor)

  def query(self, sql):
    try:
     cursor = self.conn.cursor()
     cursor.execute(sql)
   except (AttributeError, MySQLdb.OperationalError):
     self.connect()
     cursor = self.conn.cursor()
     cursor.execute(sql)
   return cursor
#

#
db = DB()
sql = "SELECT bla FROM foo"
data = db.query(sql)

for row in data:
    do_something(row)
#
</code>```

But I'm always getting this:

```<code>#
Traceback (most recent call last):
  File "teste.py", line 124, in <module>
   run()
 File "teste.py", line 109, in run
   for row in data:
 File "/usr/lib64/python2.5/site-packages/MySQLdb/cursors.py", line 417, in next
   row = self.fetchone()
 File "/usr/lib64/python2.5/site-packages/MySQLdb/cursors.py", line 388, in fetchone
   r = self._fetch_row(1)
 File "/usr/lib64/python2.5/site-packages/MySQLdb/cursors.py", line 285, in _fetch_row
   return self._result.fetch_row(size, self._fetch_type)
   _mysql_exceptions.OperationalError: (2013, 'Lost connection to MySQL server during query')
    Exception _mysql_exceptions.OperationalError: (2013, 'Lost connection to MySQL server during query') in <bound method SSCursor.__del__ of <MySQLdb.cursors.SSCursor object at 0x7f7e3c8da410>> ignored
#
</code>```

Do you have any idea?

答:
Multiprocessing and Django DB don't play well together.

I ended up closing Django DB connection first thing in the new process.

So that one will have no references to the connection used by the parent.

```<code>from multiprocessing import Pool

multi_core_arg = [[1,2,3], [4,5,6], [7,8,9]]
n_cpu = 4
pool = Pool(n_cpu)
pool.map(_etl_, multi_core_arg)
pool.close()
pool.join()

def _etl_(x):
    from django.db import connection
    connection.close()
    print(x)
</code>```

OR

Process.start() calls a function which starts with

Some other suggest to use

```<code>from multiprocessing.dummy import Pool as ThreadPool
</code>```

It solved my (2013, Lost connection) problem, but thread use GIL, when doing IO, to will release it when IO finish.

Comparatively, Process spawn a group of workers that communication each other, which may be slower.

I recommend you to time it.
A side tips is to use joblib which is backed by scikit-learn project.
some performance result shows it out perform the native Pool().. although it leave the responsibility to coder to verify the true run time cost.

Body:
I have a huge table and I need to process all rows in it. I'm always getting this Lost connection message and I'm not able to reconnect and restore the cursor to the last position it was. This is basically the code I have here:

#
import MySQLdb

class DB:
  conn = None

  def connect(self):
    self.conn = MySQLdb.connect('hostname', 'user', '*****', 'some_table', cursorclass=MySQLdb.cursors.SSCursor)

  def query(self, sql):
    try:
     cursor = self.conn.cursor()
     cursor.execute(sql)
   except (AttributeError, MySQLdb.OperationalError):
     self.connect()
     cursor = self.conn.cursor()
     cursor.execute(sql)
   return cursor
#

#
db = DB()
sql = "SELECT bla FROM foo"
data = db.query(sql)

for row in data:
    do_something(row)
#

But I'm always getting this:

#
Traceback (most recent call last):
  File "teste.py", line 124, in <module>
   run()
 File "teste.py", line 109, in run
   for row in data:
 File "/usr/lib64/python2.5/site-packages/MySQLdb/cursors.py", line 417, in next
   row = self.fetchone()
 File "/usr/lib64/python2.5/site-packages/MySQLdb/cursors.py", line 388, in fetchone
   r = self._fetch_row(1)
 File "/usr/lib64/python2.5/site-packages/MySQLdb/cursors.py", line 285, in _fetch_row
   return self._result.fetch_row(size, self._fetch_type)
   _mysql_exceptions.OperationalError: (2013, 'Lost connection to MySQL server during query')
    Exception _mysql_exceptions.OperationalError: (2013, 'Lost connection to MySQL server during query') in <bound method SSCursor.__del__ of <MySQLdb.cursors.SSCursor object at 0x7f7e3c8da410>> ignored
#

Do you have any idea?

Body:
Multiprocessing and Django DB don't play well together.

I ended up closing Django DB connection first thing in the new process.

So that one will have no references to the connection used by the parent.

from multiprocessing import Pool

multi_core_arg = [[1,2,3], [4,5,6], [7,8,9]]
n_cpu = 4
pool = Pool(n_cpu)
pool.map(_etl_, multi_core_arg)
pool.close()
pool.join()

def _etl_(x):
    from django.db import connection
    connection.close()
    print(x)

OR

Process.start() calls a function which starts with

Some other suggest to use

from multiprocessing.dummy import Pool as ThreadPool

It solved my (2013, Lost connection) problem, but thread use GIL, when doing IO, to will release it when IO finish.

Comparatively, Process spawn a group of workers that communication each other, which may be slower.

I recommend you to time it.
A side tips is to use joblib which is backed by scikit-learn project.
some performance result shows it out perform the native Pool().. although it leave the responsibility to coder to verify the true run time cost.


问:
Find documents based on a Reference to the Parent in the Child with Pagination
There are  2 collections Movie and Rank Movie .This 2 collections having referenced relationship .

Movie model

```<code>var mongoose = require('mongoose');

var movieSchema = new mongoose.Schema({
    m_tmdb_id: {
        type: Number,
        unique: true,
        index: true
    },
    m_adult: {
        type: Boolean
    },
    m_backdrop_path: {
        type: String,
    },
    m_title: {
        type: Number
    },
    m_genres: {
        type: Array
    }

});
var MovieModel = mongoose.model('Movie', movieSchema);
module.exports = {
    movie: MovieModel
}
</code>```

Rank movie model

```<code>var mongoose = require('mongoose');
var rankMovieSchema = new mongoose.Schema({
    movie: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Movie',
        unique: true
    },
    rank: {
        type: Number
    },
    count: {
        type: Number
    }
});
var RankMovieModel = mongoose.model('RankMovie', rankMovieSchema);
module.exports = {
    rankmovie: RankMovieModel
}
</code>```

I need to select all the top 10 items in each query [Pagination] from the collection rank movie having a particular m_genres name[Condition on movie collection ].

Ex:

Movie collection

```<code>[{
    "_id": ObjectId("5930ea4806fb9e365e0d55b5"),
    "m_tmdb_id": 888724,
    "m_imdb_id": "sd2806",
    "m_title": "Mechanic: Resurrection",
    "m_genres": [{
        "name": "Action",
        "id": 28
    }, {
        "name": "Crime",
        "id": 80
    }, {
        "name": "Thriller",
        "id": 53
    }]
}, {
    "_id": ObjectId("583e3bd69e2ea90c69c5a254"),
    "m_tmdb_id": 23924,
    "m_imdb_id": "tt3d2806",
    "m_title": "Inter",
    "m_genres": [{
        "name": "Drama",
        "id": 32
    }, {
        "name": "Crime",
        "id": 80
    }]
}, {
    "_id": ObjectId("5930eaa706fb9e365e0d55c8"),
    "m_tmdb_id": 378924,
    "m_imdb_id": "sdstt3522806",
    "m_title": "Spiderman",
    "m_genres": [{
        "name": "Action",
        "id": 28
    }, {
        "name": "Crime",
        "id": 80
    }, {
        "name": "Thriller",
        "id": 53
    }]
}]
</code>```

Rank Movie Collection

```<code>[{
    "_id": ObjectId("59398daaad49f32c20115422"),
    "movie": ObjectId("5930ea4806fb9e365e0d55b5"),
    "count": 5
}, {
    "_id": ObjectId("59397f7095f0b91ffbdeb1f8"),
    "movie": ObjectId("583e3bd69e2ea90c69c5a254"),
    "count": 1
}, {
    "_id": ObjectId("59397f6695f0b91ffbdeb1f6"),
    "movie": ObjectId("5930eaa706fb9e365e0d55c8"),
    "count": 5
}]
</code>```

If i am giving m_genres names as Crime,Thriller.The query should fetch top 10 items from rank movie which having m_genres names Crime,Thriller.How can i achieve this?

My JS Code

```<code>RankMovie
    .find(queryOptions)
    .limit(10)
    .skip(1 * 10)
    .populate('movie', 'm_tmdb_id  m_title m_generes ')
    .sort('-count')
    .exec(function(err, movies) {
        if(err){
            return res.status(404).json(err);
        }
        return res.status(200).json(movies);
    }).catch(function(error) {
        return res.status(500).json(error);
    });
</code>```

答:
Actually this "still" has the best method using .aggregate() with $lookup to join the data.

```<code>var wantedGenres = ["Action","Crime"];
var page = 1;

RankMovie.aggregate([
  { "$lookup": {
    "from": Movie.collection.name,
    "localField": "movie",
    "foreignField": "_id",
    "as": "movie"
  }},
  { "$unwind": "$movie" },
  { "$match": { "movie.m_genres.name": { "$in": wantedGenres }  }},
  { "$sort": { "count": -1 } },
  { "$project": {
    "movie": {
      "m_title": "$movie.m_title",
      "m_tmdb_id": "$movie.m_tmdb_id",
      "m_genres": "$movie.m_genres",
    },
    "count": 1
  }},
  { "$skip": 10*page },
  { "$limit": 10 },
])
</code>```

This works out to be efficient since the $unwind and $match get combined into the $lookup itself, and only return the items that actually matched the given criteria in the $match as opposed to "ALL" related data. This is explained in the Answer to your previous question in full.

But this is what happens to those three stages:

```<code>    {
        "$lookup" : {
            "from" : "movies",
            "as" : "movie",
            "localField" : "movie",
            "foreignField" : "_id",
            "unwinding" : {
                "preserveNullAndEmptyArrays" : false
            },
            "matching" : {
                "m_genres.name" : {
                    "$in" : [
                        "Action",
                        "Crime"
                    ]
                }
            }
        }
    }
</code>```

Of course then we $sort in order to have the matching results in the correct and wanted order. Then it simply is a matter of selecting the wanted fields with $project ( note that $addFields will not work here, since we want to "overwrite" ) and performing the $skip and $limit for the pagination.

Trying to do this "client side" as .populate() does would be next to impossible and practically impossible in real situations. The problem of course being that the "selection by genres" needs to happen "before" you actually begin to "paginate".

So the only way that could possibly happen is with a "relatively small" list of "movies", because you would indeed need to make the selection on the "genres" first and then do the rest of the query.

The "totally impractical" way would look something like:

```<code>var wantedGenres = ["Action","Crime"];
var page = 1;

Movie.find({ "m_genres.name": { "$in": wantedGenres } })
  .select({ "_id": 1 })
  .exec()
  .then(movies =>
    RankMovie.find({ "movie": { "$in": movies.map(m => m._id) })
      .populate('movie', 'm_tmdb_id  m_title m_genres')
      .sort('-count')
      .skip(10*page)
      .limit(10)
      .exec()
  ).then(rankings => {
    // deal with response
  })
  .catch(err => res.status(500).json(err))
</code>```

But of course that pulls "ALL" the matching "movies" over the wire to the client before issuing the query. And possibly breaks the BSON limit on request with the $in argument of ids.

The aggregate statement on the other hand, will not have the same limitation.

Body:
There are  2 collections Movie and Rank Movie .This 2 collections having referenced relationship .

Movie model

var mongoose = require('mongoose');

var movieSchema = new mongoose.Schema({
    m_tmdb_id: {
        type: Number,
        unique: true,
        index: true
    },
    m_adult: {
        type: Boolean
    },
    m_backdrop_path: {
        type: String,
    },
    m_title: {
        type: Number
    },
    m_genres: {
        type: Array
    }

});
var MovieModel = mongoose.model('Movie', movieSchema);
module.exports = {
    movie: MovieModel
}

Rank movie model

var mongoose = require('mongoose');
var rankMovieSchema = new mongoose.Schema({
    movie: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Movie',
        unique: true
    },
    rank: {
        type: Number
    },
    count: {
        type: Number
    }
});
var RankMovieModel = mongoose.model('RankMovie', rankMovieSchema);
module.exports = {
    rankmovie: RankMovieModel
}

I need to select all the top 10 items in each query [Pagination] from the collection rank movie having a particular m_genres name[Condition on movie collection ].

Ex:

Movie collection

[{
    "_id": ObjectId("5930ea4806fb9e365e0d55b5"),
    "m_tmdb_id": 888724,
    "m_imdb_id": "sd2806",
    "m_title": "Mechanic: Resurrection",
    "m_genres": [{
        "name": "Action",
        "id": 28
    }, {
        "name": "Crime",
        "id": 80
    }, {
        "name": "Thriller",
        "id": 53
    }]
}, {
    "_id": ObjectId("583e3bd69e2ea90c69c5a254"),
    "m_tmdb_id": 23924,
    "m_imdb_id": "tt3d2806",
    "m_title": "Inter",
    "m_genres": [{
        "name": "Drama",
        "id": 32
    }, {
        "name": "Crime",
        "id": 80
    }]
}, {
    "_id": ObjectId("5930eaa706fb9e365e0d55c8"),
    "m_tmdb_id": 378924,
    "m_imdb_id": "sdstt3522806",
    "m_title": "Spiderman",
    "m_genres": [{
        "name": "Action",
        "id": 28
    }, {
        "name": "Crime",
        "id": 80
    }, {
        "name": "Thriller",
        "id": 53
    }]
}]

Rank Movie Collection

[{
    "_id": ObjectId("59398daaad49f32c20115422"),
    "movie": ObjectId("5930ea4806fb9e365e0d55b5"),
    "count": 5
}, {
    "_id": ObjectId("59397f7095f0b91ffbdeb1f8"),
    "movie": ObjectId("583e3bd69e2ea90c69c5a254"),
    "count": 1
}, {
    "_id": ObjectId("59397f6695f0b91ffbdeb1f6"),
    "movie": ObjectId("5930eaa706fb9e365e0d55c8"),
    "count": 5
}]

If i am giving m_genres names as Crime,Thriller.The query should fetch top 10 items from rank movie which having m_genres names Crime,Thriller.How can i achieve this?

My JS Code

RankMovie
    .find(queryOptions)
    .limit(10)
    .skip(1 * 10)
    .populate('movie', 'm_tmdb_id  m_title m_generes ')
    .sort('-count')
    .exec(function(err, movies) {
        if(err){
            return res.status(404).json(err);
        }
        return res.status(200).json(movies);
    }).catch(function(error) {
        return res.status(500).json(error);
    });

Body:
Actually this "still" has the best method using .aggregate() with $lookup to join the data.

var wantedGenres = ["Action","Crime"];
var page = 1;

RankMovie.aggregate([
  { "$lookup": {
    "from": Movie.collection.name,
    "localField": "movie",
    "foreignField": "_id",
    "as": "movie"
  }},
  { "$unwind": "$movie" },
  { "$match": { "movie.m_genres.name": { "$in": wantedGenres }  }},
  { "$sort": { "count": -1 } },
  { "$project": {
    "movie": {
      "m_title": "$movie.m_title",
      "m_tmdb_id": "$movie.m_tmdb_id",
      "m_genres": "$movie.m_genres",
    },
    "count": 1
  }},
  { "$skip": 10*page },
  { "$limit": 10 },
])

This works out to be efficient since the $unwind and $match get combined into the $lookup itself, and only return the items that actually matched the given criteria in the $match as opposed to "ALL" related data. This is explained in the Answer to your previous question in full.

But this is what happens to those three stages:

    {
        "$lookup" : {
            "from" : "movies",
            "as" : "movie",
            "localField" : "movie",
            "foreignField" : "_id",
            "unwinding" : {
                "preserveNullAndEmptyArrays" : false
            },
            "matching" : {
                "m_genres.name" : {
                    "$in" : [
                        "Action",
                        "Crime"
                    ]
                }
            }
        }
    }

Of course then we $sort in order to have the matching results in the correct and wanted order. Then it simply is a matter of selecting the wanted fields with $project ( note that $addFields will not work here, since we want to "overwrite" ) and performing the $skip and $limit for the pagination.

Trying to do this "client side" as .populate() does would be next to impossible and practically impossible in real situations. The problem of course being that the "selection by genres" needs to happen "before" you actually begin to "paginate".

So the only way that could possibly happen is with a "relatively small" list of "movies", because you would indeed need to make the selection on the "genres" first and then do the rest of the query.

The "totally impractical" way would look something like:

var wantedGenres = ["Action","Crime"];
var page = 1;

Movie.find({ "m_genres.name": { "$in": wantedGenres } })
  .select({ "_id": 1 })
  .exec()
  .then(movies =>
    RankMovie.find({ "movie": { "$in": movies.map(m => m._id) })
      .populate('movie', 'm_tmdb_id  m_title m_genres')
      .sort('-count')
      .skip(10*page)
      .limit(10)
      .exec()
  ).then(rankings => {
    // deal with response
  })
  .catch(err => res.status(500).json(err))

But of course that pulls "ALL" the matching "movies" over the wire to the client before issuing the query. And possibly breaks the BSON limit on request with the $in argument of ids.

The aggregate statement on the other hand, will not have the same limitation.


问:
How to place image correctly in input tag
I created a input tag with two images cross and arrow.

Here is my code.

```<code><div id="chart_line" style="position: relative;">
    <input type="text" id="myInput" list="myUL" onclick="openingList()" onkeyup="openingList()" style="width:30%;">
        <div id="triggers">
            <img class="trigger" onclick="deleteValue()" src="css/clearT.png" id="cross">
            <img class="trigger" src="css/combo_arrow.png" onclick="openingList()" id="arrow">
        </div>
</div>
</code>```

Here is my fiddle :

Fiddle

I am facing two problem here.

I want my image should be at the end with respect to input tag. Right now I am giving manually in CSS. You can see

#triggers {
      position: absolute;
      left : 110px;
      top: 5px;
    }

I am giving left : 110px How can I fix this always at end of input tag. Input tag width may change.

I want to restrict my input tag just before the image start. Right now text is coming below the image. Even cursor is also going below the image. Any idea how to fix that.

Here is image for your reference.

Thanks

答:
* {
  box-sizing: border-box;
}
.field {
  position: relative;
  width: 300px;
}
.field input {
  width: 100%;
  padding: 5px 50px 5px 10px;
  white-space: nowrap;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.field .triggers {
  position: absolute;
  top: 5px;
  right: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="field">
  <input type="text" value="some very long value to check what goes under the images">
  <div class="triggers">
    <img class="trigger trigger--cross" src="css/clearT.png">
    <img class="trigger trigger--arrow" src="css/combo_arrow.png">
  </div>
</div></code>```

Body:
I created a input tag with two images cross and arrow.

Here is my code.

    <input type="text" id="myInput" list="myUL" onclick="openingList()" onkeyup="openingList()" style="width:30%;">

Here is my fiddle :

Fiddle

I am facing two problem here.

I want my image should be at the end with respect to input tag. Right now I am giving manually in CSS. You can see

#triggers {
      position: absolute;
      left : 110px;
      top: 5px;
    }

I am giving left : 110px How can I fix this always at end of input tag. Input tag width may change.

I want to restrict my input tag just before the image start. Right now text is coming below the image. Even cursor is also going below the image. Any idea how to fix that.

Here is image for your reference.

Thanks

Body:
* {
  box-sizing: border-box;
}
.field {
  position: relative;
  width: 300px;
}
.field input {
  width: 100%;
  padding: 5px 50px 5px 10px;
  white-space: nowrap;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.field .triggers {
  position: absolute;
  top: 5px;
  right: 5px;
}

<div class="field">
  <input type="text" value="some very long value to check what goes under the images">
  <div class="triggers">
    <img class="trigger trigger--cross" src="css/clearT.png">
    <img class="trigger trigger--arrow" src="css/combo_arrow.png">
  </div>
</div>


问:
Apply function take 100 time longer than a For loop in R
I'm encountering a massive time difference between a for loop and an apply function.

I have a dataframe (alldat) that contain about 200k records with 73 columns I want to check what is the percent of NA in each column and return the result as a new DF for me to inspect. I have done it by 2 methods:

1) function with a for loop:

```<code>Nacheck = function(a){
    a <- as.data.frame(a)
    vecNA <- rep(NA, dim(a)[2])
    for (i in 1:dim(a)[2]){
        vecNA[i] <- sum(is.na(a[, i]))
        }
    rowss <- rep(nrow(a), length(vecNA))
    NA_PCT <- vecNA/rowss
    colna <- colnames(a)
    datacheck <- as.data.frame(t(rbind(colna, NA_PCT)))
    return(datacheck)
}
datacheck1 = Nacheck(alldat)
</code>```

2) apply function by column:

```<code>datacheck <- as.data.frame(apply(alldat,2,function (x) round(sum(is.na(x))/dim(alldat)[1], digits = 2)))
</code>```

the apply function take 4 sec and the for loop function takes less than 0.023 sec

```<code>start.time <- Sys.time()
datacheck <- as.data.frame(apply(alldat,2,function (x) round(sum(is.na(x))/dim(alldat)[1], digits = 2)))
end.time <- Sys.time()
time.takenapply <- end.time - start.time
time.takenapply
</code>```

Time difference of 4.304 secs

for loop time :

```<code>start.time <- Sys.time()
datacheck = Nacheck(alldat)
end.time <- Sys.time()
time.taken <- end.time - start.time
time.taken
</code>```

Time difference of 0.02399993 secs

Am I doing something wrong?  Any idea what causes this time difference?

答:
Dateframes are internally very similar to lists, with each column being a separate entry in the list. You can see this by using the $ operator. This allows you to specify a column, similar to specifying a named entry in a list.

When you do apply, as Natrave Drova already mentioned in the comments, you are implicitly converting your entiry dataframe into a matrix. If your dataframe then has different datatypes, like columns of numerics and columns of characters, it coerces all values into a common type (usually character). If your dataframe is big (and 200k * 73 values to be coerces counts as big) this can be a very costly operation.

So if you want to compare the *apply functions with for-loops properly, you should try it with lapply instead.

Body:
I'm encountering a massive time difference between a for loop and an apply function.

I have a dataframe (alldat) that contain about 200k records with 73 columns I want to check what is the percent of NA in each column and return the result as a new DF for me to inspect. I have done it by 2 methods:

1) function with a for loop:

Nacheck = function(a){
    a <- as.data.frame(a)
    vecNA <- rep(NA, dim(a)[2])
    for (i in 1:dim(a)[2]){
        vecNA[i] <- sum(is.na(a[, i]))
        }
    rowss <- rep(nrow(a), length(vecNA))
    NA_PCT <- vecNA/rowss
    colna <- colnames(a)
    datacheck <- as.data.frame(t(rbind(colna, NA_PCT)))
    return(datacheck)
}
datacheck1 = Nacheck(alldat)

2) apply function by column:

datacheck <- as.data.frame(apply(alldat,2,function (x) round(sum(is.na(x))/dim(alldat)[1], digits = 2)))

the apply function take 4 sec and the for loop function takes less than 0.023 sec

start.time <- Sys.time()
datacheck <- as.data.frame(apply(alldat,2,function (x) round(sum(is.na(x))/dim(alldat)[1], digits = 2)))
end.time <- Sys.time()
time.takenapply <- end.time - start.time
time.takenapply

Time difference of 4.304 secs

for loop time :

start.time <- Sys.time()
datacheck = Nacheck(alldat)
end.time <- Sys.time()
time.taken <- end.time - start.time
time.taken

Time difference of 0.02399993 secs

Am I doing something wrong?  Any idea what causes this time difference?


问:
how to store Spark Dataframe in hive in uncompressed text format
I am trying to store dataframe into an external hive table. When I perform the following action:

```<code> recordDF.write.option("path", "hdfs://quickstart.cloudera:8020/user/cloudera/hadoop/hive/warehouse/VerizonProduct").saveAsTable("productstoreHTable")
</code>```

At the hdfs location where the table was supposed to be present instead I get this:

-rw-r--r--   3 cloudera cloudera          0 2016-12-25 18:58 hadoop/hive/warehouse/VerizonProduct/_SUCCESS

-rw-r--r--   3 cloudera cloudera        482 2016-12-25 18:58 hadoop/hive/warehouse/VerizonProduct/part-r-00000-0acdcc6d-893b-4e9d-b1d6-50bf02bea96a.snappy.parquet

-rw-r--r--   3 cloudera cloudera        482 2016-12-25 18:58 hadoop/hive/warehouse/VerizonProduct/part-r-00001-0acdcc6d-893b-4e9d-b1d6-50bf02bea96a.snappy.parquet

-rw-r--r--   3 cloudera cloudera        482 2016-12-25 18:58 hadoop/hive/warehouse/VerizonProduct/part-r-00002-0acdcc6d-893b-4e9d-b1d6-50bf02bea96a.snappy.parquet

-rw-r--r--   3 cloudera cloudera        482 2016-12-25 18:58 hadoop/hive/warehouse/VerizonProduct/part-r-00003-0acdcc6d-893b-4e9d-b1d6-50bf02bea96a.snappy.parquet

How do I store it as uncompressed text format?

Thanks

答:
The above solution with format csv, threw a warning "Couldn't find corresponding Hive SerDe for data source provider csv.". The table is not created in the desired way. One solution could be create an external table as below
   sqlContext.sql("CREATE EXTERNAL TABLE test(col1 int,col2 string) STORED AS TEXTFILE LOCATION '/path/in/hdfs'") .

Then
    dataFrame.write.format("com.databricks.spark.csv").option("header", "true").save("/path/in/hdfs")

Body:
I am trying to store dataframe into an external hive table. When I perform the following action:

 recordDF.write.option("path", "hdfs://quickstart.cloudera:8020/user/cloudera/hadoop/hive/warehouse/VerizonProduct").saveAsTable("productstoreHTable")

At the hdfs location where the table was supposed to be present instead I get this:

-rw-r--r--   3 cloudera cloudera          0 2016-12-25 18:58 hadoop/hive/warehouse/VerizonProduct/_SUCCESS

-rw-r--r--   3 cloudera cloudera        482 2016-12-25 18:58 hadoop/hive/warehouse/VerizonProduct/part-r-00000-0acdcc6d-893b-4e9d-b1d6-50bf02bea96a.snappy.parquet

-rw-r--r--   3 cloudera cloudera        482 2016-12-25 18:58 hadoop/hive/warehouse/VerizonProduct/part-r-00001-0acdcc6d-893b-4e9d-b1d6-50bf02bea96a.snappy.parquet

-rw-r--r--   3 cloudera cloudera        482 2016-12-25 18:58 hadoop/hive/warehouse/VerizonProduct/part-r-00002-0acdcc6d-893b-4e9d-b1d6-50bf02bea96a.snappy.parquet

-rw-r--r--   3 cloudera cloudera        482 2016-12-25 18:58 hadoop/hive/warehouse/VerizonProduct/part-r-00003-0acdcc6d-893b-4e9d-b1d6-50bf02bea96a.snappy.parquet

How do I store it as uncompressed text format?

Thanks


问:
sleep(1) + fflush(stdout) works via curl. NOT via web browser
the pauses (sleep(1)), work fine when script is ran via curl command

rather than run on a web browser.

but via web browser.. it will pause the sum of all pauses (3 x sleep(1)) and then  print them all at once

what can be done to ensure the web browser behaves like curl ?

```<code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main() {
    printf("Content-type: text/plain\n\n");

    printf("%s\n", "test 1");
    fflush(stdout);

    sleep(1);

    printf("%s\n", "test 2");
    fflush(stdout);

    sleep(1);

    printf("%s\n", "test 3");
    fflush(stdout);

    sleep(1);

    printf("%s\n", "test 4");
    fflush(stdout);

    return 0;
}
</code>```

答:
HTTP is much more complex than what you believe, and CGI is obsolete (with HTML5 & AJAX applications). Consider using some HTTP server library like libonion (or make a FastCGI application...) and/or some HTTP client library like libcurl.

To make your thing work without any library (which IMHO is a mistake) you need to study more HTTP and add more headers in your HTTP request, notably Host:, and in the response: Content-Length:, Connection: close

I strongly recommend not coding all your HTTP protocol handling by yourself (so use an HTTP library).

what can be done to ensure the web browser behaves like curl ?

Nothing can be done; a browser is entitled to handle only complete HTTP messages, and there are good reasons for that. In addition, most browsers would open several connections (simultaneously) to the same HTTP service.

If you need an apparently interactive behavior of a modern browser (that is a browser window which evolves visually with time), you should consider using techniques like AJAX (with HTML5) & WebSockets, so program the browser using JavaScript (which might be generated on the server side). Read also about single-page applications. Look into the websocket example of libonion (it probably is quite relevant for your needs). BTW such a WebSockets & AJAX & HTML5 based approach has (over the answer provided by Felix Palmen) the advantage to enable some more visually fancy thing (e.g. counting and displaying line numbers), and also (with some extra Javascript code) to add the ability to clear the shown log lines (on the browser side only).

BTW, on Linux specifically (with a local file system like ext4) you may want to use inotify(7) facilities to be notified of a file change. You'll want some event loop around poll(2) (or the older select(2) ...), but most HTTP related libraries provide one.

It is important to understand that HTTP is not an interactive protocol (every request is browser initiated and gets exactly one response). To add interactivity (flowing to the server) you need more (e.g. WebSockets, which provides asynchronous messages from server to browser), or at least some "semi-busy polling" that is periodic Javascript (in the browser) doing AJAX requests.

Body:
the pauses (sleep(1)), work fine when script is ran via curl command

rather than run on a web browser.

but via web browser.. it will pause the sum of all pauses (3 x sleep(1)) and then  print them all at once

what can be done to ensure the web browser behaves like curl ?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main() {
    printf("Content-type: text/plain\n\n");

    printf("%s\n", "test 1");
    fflush(stdout);

    sleep(1);

    printf("%s\n", "test 2");
    fflush(stdout);

    sleep(1);

    printf("%s\n", "test 3");
    fflush(stdout);

    sleep(1);

    printf("%s\n", "test 4");
    fflush(stdout);

    return 0;
}


问:
Excel column cell data match
In Excel if a cell contain a certain String how can i compare and replace it.

I have a column in the Excel file called 1st contact person and all i want is if in the column 2nd Contact Person if it's says Same as 1st Contact Person than replace the name with the correct name else do nothing.

I have tried this query --

```<code>=IF(EXACT([1st Contact Person], "Same as 1st Contact Person"),[2nd Contact Person],"")
</code>```

Excel file ---

```<code>1st Contact Person   2nd Contact Person
Chris Johnsson       Same as 1st Contact Person
Henrik Johnsson      Same as 1st Contact Person
Johanna Nilsson      Christofer Hanssen
</code>```

No luck with my query !!

Can anyone tell me where i am doing something wrong .

答:
Try this formula in B2 cell

```<code>=IF($A2="","",IF($C2="Same as 1st Contact Person",$A2,IF(LEN($C2)>0,$C2,"")))
</code>```

Title: Excel column cell data match

Body:
In Excel if a cell contain a certain String how can i compare and replace it.

I have a column in the Excel file called 1st contact person and all i want is if in the column 2nd Contact Person if it's says Same as 1st Contact Person than replace the name with the correct name else do nothing.

I have tried this query --

=IF(EXACT([1st Contact Person], "Same as 1st Contact Person"),[2nd Contact Person],"")

Excel file ---

1st Contact Person   2nd Contact Person
Chris Johnsson       Same as 1st Contact Person
Henrik Johnsson      Same as 1st Contact Person
Johanna Nilsson      Christofer Hanssen

No luck with my query !!

Can anyone tell me where i am doing something wrong .

Body:
Try this formula in B2 cell

=IF($A2="","",IF($C2="Same as 1st Contact Person",$A2,IF(LEN($C2)>0,$C2,"")))


问:
How to add a form that appear only one time for new users and then back to regular form
I want to create a form with extra fields :

this is the models.py for regular form :

Boutique :

```<code>class Boutique(models.Model):
    name = models.CharField(max_length=250)
    user = models.ForeignKey(User, default=1)
    logo = models.FileField(max_length=250)

    def __str__(self):
        return self.name
</code>```

form.py :

```<code>class BoutiqueForm(forms.ModelForm):

    class Meta:
        model = Boutique
        fields = ['name', 'logo']
</code>```

Views.py :

```<code>def create_boutique(request):
    if not request.user.is_authenticated():
        return render(request, 'produit/login.html')
    else:
        form = BoutiqueForm(request.POST or None, request.FILES or None)
        if form.is_valid():
            boutique = form.save(commit=False)
            boutique.user = request.user
            boutique.logo = request.FILES['logo']
            file_type = boutique.logo.url.split('.')[-1]
            file_type = file_type.lower()
            if file_type not in IMAGE_FILE_TYPES:
                context = {
                    'boutique': boutique,
                    'form': form,
                    'error_message': 'Image file must be PNG, JPG, or JPEG',
                }
                return render(request, 'produit/create_boutique.html', context)
            boutique.save()
            return render(request, 'produit/detail.html', {'boutique': boutique})
        context = {
            "form": form,
        }
        return render(request, 'produit/create_boutique.html', context)
</code>```

form_template.html :

```<code>{% for field in form %}
<div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
        <span class="text-danger small">{{ field.errors }}</span>

    </div>
    <label class="control-label col-sm-2">{{ field.label_tag}}</label>
    <div class="col-sm-10">{{ field }}</div>
</div>{% endfor %}
</code>```

i want to add a table boutique_commerçant that containt 2 extra fields facebook_link and entreprise ... that appear in create_boutique.html only one time for new registred user...

答:
Have a look at this question and answer.

You can add an extra field which defaults to False and is set to True if your two fields are saved. This way you can check if the information exists, and only show the form when not.

Body:
I want to create a form with extra fields :

this is the models.py for regular form :

Boutique :

class Boutique(models.Model):
    name = models.CharField(max_length=250)
    user = models.ForeignKey(User, default=1)
    logo = models.FileField(max_length=250)

    def __str__(self):
        return self.name

form.py :

class BoutiqueForm(forms.ModelForm):

    class Meta:
        model = Boutique
        fields = ['name', 'logo']

Views.py :

def create_boutique(request):
    if not request.user.is_authenticated():
        return render(request, 'produit/login.html')
    else:
        form = BoutiqueForm(request.POST or None, request.FILES or None)
        if form.is_valid():
            boutique = form.save(commit=False)
            boutique.user = request.user
            boutique.logo = request.FILES['logo']
            file_type = boutique.logo.url.split('.')[-1]
            file_type = file_type.lower()
            if file_type not in IMAGE_FILE_TYPES:
                context = {
                    'boutique': boutique,
                    'form': form,
                    'error_message': 'Image file must be PNG, JPG, or JPEG',
                }
                return render(request, 'produit/create_boutique.html', context)
            boutique.save()
            return render(request, 'produit/detail.html', {'boutique': boutique})
        context = {
            "form": form,
        }
        return render(request, 'produit/create_boutique.html', context)

form_template.html :

{% for field in form %}

        {{ field.errors }}

    {{ field.label_tag}}

{{ field }}

{% endfor %}

i want to add a table boutique_commerçant that containt 2 extra fields facebook_link and entreprise ... that appear in create_boutique.html only one time for new registred user...