问:
changing label by clicking on button GTK C
I'm new to making GUI using GTK+ and I'm using glade to build the GUI and I am trying to simply change label by clicking on a button here is my code:

```<code>#include <stdlib.h>
#include <gtk/gtk.h>
#include <gdk/gdkkeysyms.h>
#include <glib/gprintf.h>

typedef struct {
GtkWidget *window1 ;
GtkWidget *button1;
GtkWidget *label1;
}AppWidgets;

G_MODULE_EXPORT void on_button1_clicked(GtkButton *button,
                    gpointer user_data)
{
  AppWidgets * app = (AppWidgets *) user_data;
  gtk_label_set_text(GTK_LABEL(app->label1),"Hello World!");
}

int main (int argc, char *argv[])
{

 GtkBuilder  *builder;
 AppWidgets  *app=g_slice_new(AppWidgets) ;
 GError  *err=NULL;

 gtk_init(&argc, &argv);

 builder = gtk_builder_new();
 gtk_builder_add_from_file (builder, "GUI", &err);

 #define appGET(xx) \
 app->xx=GTK_WIDGET(gtk_builder_get_object(builder,#xx))

 appGET(window1);
 appGET(button1);
 appGET(label1);

 gtk_builder_connect_signals(builder, &app);
 g_object_unref(G_OBJECT(builder));

 gtk_widget_show(app->window1);
 gtk_main ();
 return 0;
}
</code>```

and here is my .glade file:

```<code><?xml version="1.0"?>
<!-- Generated with glade 3.18.3 -->
<interface>
  <object class="GtkWindow" id="window1">
    <property name="can_focus">False</property>
    <property name="resizable">true</property>
    <property name="default_width">500</property>
    <property name="default_height">1000</property>
    <child>
      <object class="GtkBox" id="box1">
        <property name="visible">True</property>
        <property name="can_focus">False</property>
        <property name="orientation">vertical</property>
        <child>
          <object class="GtkButton" id="button1">
            <property name="label" translatable="yes">button</property>
            <property name="visible">True</property>
            <property name="can_focus">True</property>
            <property name="receives_default">True</property>
            <property name="relief">none</property>
            <property name="focus_on_click">False</property>
            <signal name="clicked" handler="on_button1_clicked" swapped="no"/>
          </object>
          <packing>
            <property name="expand">True</property>
            <property name="fill">True</property>
            <property name="position">0</property>
          </packing>
        </child>
        <child>
          <object class="GtkLabel" id="label1">
            <property name="visible">True</property>
            <property name="can_focus">False</property>
            <property name="label" translatable="yes">label</property>
          </object>
          <packing>
            <property name="expand">True</property>
            <property name="fill">True</property>
            <property name="position">1</property>
          </packing>
        </child>
      </object>
    </child>
  </object>
</interface>
</code>```

this code simply does nothing so what should i do to change the label text ?

答:
After compiling your code, with:

```<code>gcc -o test main.c -rdynamic `pkg-config --cflags --libs gtk+-3.0 gmodule-export-2.0`
</code>```

Probably gmodule-export-2.0 will be included by GTK so may be redundant.

The result is that the label won't change and the error thrown to the console is:

```<code>Gtk-CRITICAL **: gtk_label_set_text: assertion 'GTK_IS_LABEL (label)' failed
</code>```

Which means that app->label1 isn't a GtkLabel.

So the problem is on signal connection:

```<code>gtk_builder_connect_signals(builder, &app);
</code>```

Here you should change to:

```<code>gtk_builder_connect_signals(builder, app);
</code>```

From the C API:

void gtk_builder_connect_signals (GtkBuilder *builder,
                               gpointer user_data);

Body:
I'm new to making GUI using GTK+ and I'm using glade to build the GUI and I am trying to simply change label by clicking on a button here is my code:

#include <stdlib.h>
#include <gtk/gtk.h>
#include <gdk/gdkkeysyms.h>
#include <glib/gprintf.h>

typedef struct {
GtkWidget *window1 ;
GtkWidget *button1;
GtkWidget *label1;
}AppWidgets;

G_MODULE_EXPORT void on_button1_clicked(GtkButton *button,
                    gpointer user_data)
{
  AppWidgets * app = (AppWidgets *) user_data;
  gtk_label_set_text(GTK_LABEL(app->label1),"Hello World!");
}

int main (int argc, char *argv[])
{

 GtkBuilder  *builder;
 AppWidgets  *app=g_slice_new(AppWidgets) ;
 GError  *err=NULL;

 gtk_init(&argc, &argv);

 builder = gtk_builder_new();
 gtk_builder_add_from_file (builder, "GUI", &err);

 #define appGET(xx) \
 app->xx=GTK_WIDGET(gtk_builder_get_object(builder,#xx))

 appGET(window1);
 appGET(button1);
 appGET(label1);

 gtk_builder_connect_signals(builder, &app);
 g_object_unref(G_OBJECT(builder));

 gtk_widget_show(app->window1);
 gtk_main ();
 return 0;
}

and here is my .glade file:

<?xml version="1.0"?>

<interface>
  <object class="GtkWindow" id="window1">
    <property name="can_focus">False</property>
    <property name="resizable">true</property>
    <property name="default_width">500</property>
    <property name="default_height">1000</property>
    <child>
      <object class="GtkBox" id="box1">
        <property name="visible">True</property>
        <property name="can_focus">False</property>
        <property name="orientation">vertical</property>
        <child>
          <object class="GtkButton" id="button1">
            <property name="label" translatable="yes">button</property>
            <property name="visible">True</property>
            <property name="can_focus">True</property>
            <property name="receives_default">True</property>
            <property name="relief">none</property>
            <property name="focus_on_click">False</property>
            <signal name="clicked" handler="on_button1_clicked" swapped="no"/>
          </object>
          <packing>
            <property name="expand">True</property>
            <property name="fill">True</property>
            <property name="position">0</property>
          </packing>
        </child>
        <child>
          <object class="GtkLabel" id="label1">
            <property name="visible">True</property>
            <property name="can_focus">False</property>
            <property name="label" translatable="yes">label</property>
          </object>
          <packing>
            <property name="expand">True</property>
            <property name="fill">True</property>
            <property name="position">1</property>
          </packing>
        </child>
      </object>
    </child>
  </object>
</interface>

this code simply does nothing so what should i do to change the label text ?

Body:
After compiling your code, with:

gcc -o test main.c -rdynamic `pkg-config --cflags --libs gtk+-3.0 gmodule-export-2.0`

Probably gmodule-export-2.0 will be included by GTK so may be redundant.

The result is that the label won't change and the error thrown to the console is:

Gtk-CRITICAL **: gtk_label_set_text: assertion 'GTK_IS_LABEL (label)' failed

Which means that app->label1 isn't a GtkLabel.

So the problem is on signal connection:

gtk_builder_connect_signals(builder, &app);

Here you should change to:

gtk_builder_connect_signals(builder, app);

From the C API:

void gtk_builder_connect_signals (GtkBuilder *builder,
                               gpointer user_data);


来源: stackexchange

问:
How do I parse a PHP serialized datastructure in Java?
I have a system that combines the best and worst of Java and PHP. I am trying to migrate a component that was once written in PHP into a Java One.

Does anyone have some tips for how I can parse a PHP serialized datastructure in Java? By serialized I mean output from php's serialize function.

答:
I had the same issue and found this library:
http://code.google.com/p/serialized-php-parser/

It does exactly what you need

OwnerDisplayName: Allain Lalonde

ContentLicense: CC BY-SA 2.5


问:
nginx file_put_contents permission denied
I have a problem.
I use this box 'rasmus/php7dev',it works,no problem,But problem so...

system use nginx as default.
When I created a directory named 'apix' via vagrantfile.
it creates 'apix directory' in /usr/share/nginx/html

```<code>sudo touch /usr/share/nginx/html/index.php
</code>```

run above code on terminal.

```<code><?php
file_put_contents('foo.php',[]);

it does not work..
Warning: file_put_contents(foo.php): failed to open stream: Permission denied in /var/www/default/apix/index.php on line 3
</code>```

to solve it
  sudo chmod -R 777 /usr/share/nginx/html/apix

but the result is false!!!!!

what can I do?

答:
If others are getting these kind of errors, you have to make certain that every directory under the /usr/share/nginx/html directory should have chmoded with 777.

You can do this by first cd to /usr/share/nginx/html

```<code>cd /usr/share/nginx/html
</code>```

Then you have to run:

```<code>chmod 777 -R *
</code>```

Done.

And for the sake of completeness, If you are getting the below error (which is/was my real problem and google took me here wrong) from the /var/log/nginx/error.log then the commands I mentioned above can help you out.

2017/07/08 16:57:27 [error] 24573#0: *192 FastCGI sent in stderr: "PHP message: PHP Warning:  file_put_contents(file): failed to open stream: Permission denied in /usr/share/nginx/html/agentwebsite/index.php on line 106" while reading response header from upstream, client: x.x.x.x, server: example.com, request: "POST /agentwebsite/index.php HTTP/1.1", upstream: "fastcgi://unix:/var/run/php5-fpm.sock:", host: "example.com"

UPDATE:

Maybe I was wrong. but anyway you can follow the better approach:

You should rather create a user group containing the nginx and php users, and set that group as the owner of the directory and then do chmod g+srwx on those files.

ContentLicense: CC BY-SA 3.0

Body:
I have a problem.
I use this box 'rasmus/php7dev',it works,no problem,But problem so...

system use nginx as default.
When I created a directory named 'apix' via vagrantfile.
it creates 'apix directory' in /usr/share/nginx/html

sudo touch /usr/share/nginx/html/index.php

run above code on terminal.

<?php
file_put_contents('foo.php',[]);

it does not work..
Warning: file_put_contents(foo.php): failed to open stream: Permission denied in /var/www/default/apix/index.php on line 3

to solve it
  sudo chmod -R 777 /usr/share/nginx/html/apix

but the result is false!!!!!

what can I do?

Body:
If others are getting these kind of errors, you have to make certain that every directory under the /usr/share/nginx/html directory should have chmoded with 777.

You can do this by first cd to /usr/share/nginx/html

cd /usr/share/nginx/html

Then you have to run:

chmod 777 -R *

Done.

And for the sake of completeness, If you are getting the below error (which is/was my real problem and google took me here wrong) from the /var/log/nginx/error.log then the commands I mentioned above can help you out.

2017/07/08 16:57:27 [error] 24573#0: *192 FastCGI sent in stderr: "PHP message: PHP Warning:  file_put_contents(file): failed to open stream: Permission denied in /usr/share/nginx/html/agentwebsite/index.php on line 106" while reading response header from upstream, client: x.x.x.x, server: example.com, request: "POST /agentwebsite/index.php HTTP/1.1", upstream: "fastcgi://unix:/var/run/php5-fpm.sock:", host: "example.com"

UPDATE:

Maybe I was wrong. but anyway you can follow the better approach:

You should rather create a user group containing the nginx and php users, and set that group as the owner of the directory and then do chmod g+srwx on those files.


问:
Can not add backslash into input parameter using Python
I need to escape all special character and then add back slash () into input parameters using python. I have done something but it's not working. My code is below.

```<code>rname = request.POST.get('rname')
ename = re.escape(rname)
add_slash = ename + '\'
</code>```

Here I need to escape all special character first and then add the \ with that string.

答:
**Hello Satya, **

Your Solution

Try this below code,

```<code>rname = request.POST.get('rname')
ename = (re.escape(rname)) + "\\"
add_slash = ename
</code>```

More knowledge about string literal so read below link,

https://docs.python.org/2.0/ref/strings.html

I hope my answer is helpful.

If any query so c

ContentLicense: CC BY-SA 4.0

Body:
I need to escape all special character and then add back slash () into input parameters using python. I have done something but it's not working. My code is below.

rname = request.POST.get('rname')
ename = re.escape(rname)
add_slash = ename + '\'

Here I need to escape all special character first and then add the \ with that string.

Body:
**Hello Satya, **

Your Solution

Try this below code,

rname = request.POST.get('rname')
ename = (re.escape(rname)) + "\\"
add_slash = ename

More knowledge about string literal so read below link,

https://docs.python.org/2.0/ref/strings.html

I hope my answer is helpful.

If any query so c


问:
Loading data in view after click the button without reload all data in page asp.net mvc
I need to load all of comments after click button "all comments" without reload page.
I have "News" page with comments, after load page we can see one comment below the text news. All data situated in table rows. I have two rows. One row have button "All comments", second row have textbox from comments and button "Add new comment".
I need after click button "All comments" load all list comments (dynamic load rows with data) without reload page. And I need to add comment in database after click button "Add new comment" without reload page too.
I don't know how to do this.

I have combined model:

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

namespace NarkomApp.Models

{
    public class News_CommentsModel
    {
        public NEWS newsModel { get; set; }
    public List<COMMENTS> commentsModel { get; set; }

    public List<NEWS> recomendNewsModel { get; set; }
    public List<NEWS> waterShutOffModel { get; set; }
    }
}
</code>```

Code view:

```<code><tr class="trDiscussion">

                    <td colspan="2">
                        <div class="gray"></div>
                        <div class="interesting">
                            <p>Обсуждение</p>
                        </div>
                    </td>

                </tr>

                <tr class="trComments">

                    <td width="100%" height="auto" colspan="2">
                        <div class="comments">

                            @{
                                if (Model.commentsModel.Count != 0)
                                {
                                    for (int i = 0; i < Model.commentsModel.Count; i++)
                                    {
                                        <p>@Model.commentsModel[i].sUserName</p>
                                        <p><a class="date-comment">@Model.commentsModel[i].vDateTime</a></p>
                                        <p class="text-comment">@Model.commentsModel[i].vComment</p>
                                    }

                                }
                                else
                                {
                                    <p>Комментариев нет</p>
                                }
                            }

                        </div>
                    </td>

                </tr>

                <tr class="trButtonShowAllComments">

                    <td colspan="2" height="50px">
                        <div>
                            <a class="comm" role="button" href="#">Все комментарии</a>
                        </div>
                    </td>

                </tr>

                <tr class="trAddNewComment">

                    <td width="100%" height="auto" colspan="2">
                        @{
                            if (Session["iIdUsers"] == null)
                            {
                                <div class="new-comment">
                                    Вы не авторизированы, для того, чтобы оставлять коментарии войдите под своим аккаунтом: @Html.ActionLink("Войти", "LogIn", "Home")
                                </div>
                            }
                            else
                            {
                                <div class="new-comment">
                                    <p>Новый комментарий:</p>
                                </div>
                                <textarea class="message" size="40" name="search" placeholder=""></textarea>
                                <div>
                                    <a class="send" role="button" href="#">Отправить</a>
                                </div>
                            }
                        }
                    </td>
</code>```

答:
you can use jquery ajax post or get method to extract or send data using jquery.

sample jquery

sample asp mvc with jquery

hope I help you

Body:
I need to load all of comments after click button "all comments" without reload page.
I have "News" page with comments, after load page we can see one comment below the text news. All data situated in table rows. I have two rows. One row have button "All comments", second row have textbox from comments and button "Add new comment".
I need after click button "All comments" load all list comments (dynamic load rows with data) without reload page. And I need to add comment in database after click button "Add new comment" without reload page too.
I don't know how to do this.

I have combined model:

using System.Collections.Generic;

namespace NarkomApp.Models

{
    public class News_CommentsModel
    {
        public NEWS newsModel { get; set; }
    public List<COMMENTS> commentsModel { get; set; }

    public List<NEWS> recomendNewsModel { get; set; }
    public List<NEWS> waterShutOffModel { get; set; }
    }
}

Code view:

Обсуждение

                            @{
                                if (Model.commentsModel.Count != 0)
                                {
                                    for (int i = 0; i < Model.commentsModel.Count; i++)
                                    {

@Model.commentsModel[i].sUserName

@Model.commentsModel[i].vDateTime

@Model.commentsModel[i].vComment

                                    }

                                }
                                else
                                {

Комментариев нет

                                }
                            }

                            Все комментарии

                        @{
                            if (Session["iIdUsers"] == null)
                            {

                                    Вы не авторизированы, для того, чтобы оставлять коментарии войдите под своим аккаунтом: @Html.ActionLink("Войти", "LogIn", "Home")

                            }
                            else
                            {

Новый комментарий:

                                <textarea class="message" size="40" name="search" placeholder=""></textarea>

                                    Отправить

                            }
                        }


问:
How to minify php page html output?
I am looking for a php script or class that can minify my php page html output like google page speed does.

How can I do this?

答:
If you want to remove all new lines in the page, use this fast code:</p>

```<code>ob_start(function($b){
if(strpos($b, "<html")!==false) {
return str_replace(PHP_EOL,"",$b);
} else {return $b;}
});
</code>```

Title: How to minify php page html output?

Body:
If you want to remove all new lines in the page, use this fast code:

ob_start(function($b){
if(strpos($b, "<html")!==false) {
return str_replace(PHP_EOL,"",$b);
} else {return $b;}
});


问:
Swift Displaying Alerts best practices
I have various controllers in my app that all require validation, and when validation fails, I want to display an alert with the errors.  Is there some best practice/design pattern for doing this?  I could simply create a static function in a Helper class like so:

```<code>static func displayAlert(message: String, buttonTitle: String, vc: UIViewController)
{
    let alertController = UIAlertController(title: "", message: message, preferredStyle: .Alert)

    let okAction = UIAlertAction(title: buttonTitle, style: .Default, handler: nil)
    alertController.addAction(okAction)

    vc.presentViewController(alertController, animated: true, completion: nil)
}
</code>```

But then I need to pass the view controller..which seems like bad practice.  I could shoot off a notification and observe it, but that seems like overkill.  Am I overthinking this, or is there some more acceptable way to go about handling something like this?

答:
As original answer from itstrueimryan at https://stackoverflow.com/a/30714429/6822183

Update for Swift 3:

```<code>extension UIViewController {

    func alert(message: String, title: String = "") {
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        alertController.addAction(OKAction)
        self.present(alertController, animated: true, completion: nil)
    }
}
</code>```

Title: Swift Displaying Alerts best practices

Body:
I have various controllers in my app that all require validation, and when validation fails, I want to display an alert with the errors.  Is there some best practice/design pattern for doing this?  I could simply create a static function in a Helper class like so:

static func displayAlert(message: String, buttonTitle: String, vc: UIViewController)
{
    let alertController = UIAlertController(title: "", message: message, preferredStyle: .Alert)

    let okAction = UIAlertAction(title: buttonTitle, style: .Default, handler: nil)
    alertController.addAction(okAction)

    vc.presentViewController(alertController, animated: true, completion: nil)
}

But then I need to pass the view controller..which seems like bad practice.  I could shoot off a notification and observe it, but that seems like overkill.  Am I overthinking this, or is there some more acceptable way to go about handling something like this?

Body:
As original answer from itstrueimryan at https://stackoverflow.com/a/30714429/6822183

Update for Swift 3:

extension UIViewController {

    func alert(message: String, title: String = "") {
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        alertController.addAction(OKAction)
        self.present(alertController, animated: true, completion: nil)
    }
}


问:
Change the default color of materialize.css input fields. I have attached screenshot

I have tried to add custom css, but not worked. I need to change the color of text after selecting the input fields.

```<code><div class="input-field form-group">
    <input id="first_name" class="active validate form-control" name="first_name" type="text" value="">
    <label for="first_name" class="mat-label">First Name</label>
</div>
</code>```

答:
This is the CSS, you can change colors of materialize input animated text

```<code>input:not([type]):focus:not([readonly])+label,.form-wrap input[type=text]:not(.browser-default):focus:not([readonly])+label,.form-wrap input[type=password]:not(.browser-default):focus:not([readonly])+label,.form-wrap input[type=email]:not(.browser-default):focus:not([readonly])+label,.form-wrap input[type=url]:not(.browser-default):focus:not([readonly])+label,.form-wrap input[type=time]:not(.browser-default):focus:not([readonly])+label,.form-wrap input[type=date]:not(.browser-default):focus:not([readonly])+label,.form-wrap input[type=datetime]:not(.browser-default):focus:not([readonly])+label,.form-wrap input[type=datetime-local]:not(.browser-default):focus:not([readonly])+label,.form-wrap input[type=tel]:not(.browser-default):focus:not([readonly])+label,.form-wrap input[type=number]:not(.browser-default):focus:not([readonly])+label,.form-wrap input[type=search]:not(.browser-default):focus:not([readonly])+label,.form-wrap textarea.materialize-textarea:focus:not([readonly])+label{

    color: #4285F4; /* after animation color change css */

}
</code>```

```<code>.form-wrap input:focus:not([type]):not([readonly]),.form-wrap input[type="text"]:focus:not(.browser-default):not([readonly]),.form-wrap input[type="password"]:focus:not(.browser-default):not([readonly]), input[type="email"]:focus:not(.browser-default):not([readonly]),.form-wrap input[type="url"]:focus:not(.browser-default):not([readonly]), input[type="time"]:focus:not(.browser-default):not([readonly]),.form-wrap input[type="date"]:focus:not(.browser-default):not([readonly]), input[type="datetime"]:focus:not(.browser-default):not([readonly]),.form-wrap input[type="datetime-local"]:focus:not(.browser-default):not([readonly]), input[type="tel"]:focus:not(.browser-default):not([readonly]),.form-wrap input[type="number"]:focus:not(.browser-default):not([readonly]), input[type="search"]:focus:not(.browser-default):not([readonly]),.form-wrap textarea.materialize-textarea:focus:not([readonly]){

    border-bottom: 1px solid #4285F4;
    box-shadow: 0 1px 0 0 #4285F4; /* after animation color change css */

}
</code>```

Body:
I have tried to add custom css, but not worked. I need to change the color of text after selecting the input fields.

    <input id="first_name" class="active validate form-control" name="first_name" type="text" value="">
    First Name

Body:
This is the CSS, you can change colors of materialize input animated text

input:not([type]):focus:not([readonly])+label,.form-wrap input[type=text]:not(.browser-default):focus:not([readonly])+label,.form-wrap input[type=password]:not(.browser-default):focus:not([readonly])+label,.form-wrap input[type=email]:not(.browser-default):focus:not([readonly])+label,.form-wrap input[type=url]:not(.browser-default):focus:not([readonly])+label,.form-wrap input[type=time]:not(.browser-default):focus:not([readonly])+label,.form-wrap input[type=date]:not(.browser-default):focus:not([readonly])+label,.form-wrap input[type=datetime]:not(.browser-default):focus:not([readonly])+label,.form-wrap input[type=datetime-local]:not(.browser-default):focus:not([readonly])+label,.form-wrap input[type=tel]:not(.browser-default):focus:not([readonly])+label,.form-wrap input[type=number]:not(.browser-default):focus:not([readonly])+label,.form-wrap input[type=search]:not(.browser-default):focus:not([readonly])+label,.form-wrap textarea.materialize-textarea:focus:not([readonly])+label{

    color: #4285F4; /* after animation color change css */

}

.form-wrap input:focus:not([type]):not([readonly]),.form-wrap input[type="text"]:focus:not(.browser-default):not([readonly]),.form-wrap input[type="password"]:focus:not(.browser-default):not([readonly]), input[type="email"]:focus:not(.browser-default):not([readonly]),.form-wrap input[type="url"]:focus:not(.browser-default):not([readonly]), input[type="time"]:focus:not(.browser-default):not([readonly]),.form-wrap input[type="date"]:focus:not(.browser-default):not([readonly]), input[type="datetime"]:focus:not(.browser-default):not([readonly]),.form-wrap input[type="datetime-local"]:focus:not(.browser-default):not([readonly]), input[type="tel"]:focus:not(.browser-default):not([readonly]),.form-wrap input[type="number"]:focus:not(.browser-default):not([readonly]), input[type="search"]:focus:not(.browser-default):not([readonly]),.form-wrap textarea.materialize-textarea:focus:not([readonly]){

    border-bottom: 1px solid #4285F4;
    box-shadow: 0 1px 0 0 #4285F4; /* after animation color change css */

}


问:
Get a custom field value saved in Order items meta in a hooked function
I am able to add, validate, display on cart and checkout page a custom field on the Product Page.Please can someone tell me how can I retrieve the custom field values using woocommerce_order_status_completed hook?

I want to send an additional email including the custom field data after the confirmation email is sent to the user

```<code>static function sendCustomData($order_id) {
    $order = wc_get_order($order_id);
    $items = $order->get_items();

    foreach ($items as $item) {
        $product_id = $item['product_id'];

        $Id = get_post_meta($product_id, '_wpws_ID', true);
        $first_name = $order->get_billing_first_name();
        $billing_email = $order->get_billing_email();

        if (empty($Id))
        continue;

        $mail = new CustomMails();
        $mail->SendMailtoReaderOnWCOrderComplete($first_name, $billing_email, $Id);
    }
}
add_action('woocommerce_order_status_completed','sendCustomData');
</code>```

Saving custom order meta value

```<code>public static function tshirt_order_meta_handler( $item_id, $values, $cart_item_key ) {
    if( isset( $values['name_on_tshirt'] ) ) {
        wc_add_order_item_meta( $item_id, "name_on_tshirt", $values['name_on_tshirt'] );
    }
}
add_action( 'woocommerce_new_order_item', 'tshirt_order_meta_handler', 1, 3 );
</code>```

答: change if (empty($Id)) .. to if (empty($wbnId))

Body:
I am able to add, validate, display on cart and checkout page a custom field on the Product Page.Please can someone tell me how can I retrieve the custom field values using woocommerce_order_status_completed hook?

I want to send an additional email including the custom field data after the confirmation email is sent to the user

static function sendCustomData($order_id) {
    $order = wc_get_order($order_id);
    $items = $order->get_items();

    foreach ($items as $item) {
        $product_id = $item['product_id'];

        $Id = get_post_meta($product_id, '_wpws_ID', true);
        $first_name = $order->get_billing_first_name();
        $billing_email = $order->get_billing_email();

        if (empty($Id))
        continue;

        $mail = new CustomMails();
        $mail->SendMailtoReaderOnWCOrderComplete($first_name, $billing_email, $Id);
    }
}
add_action('woocommerce_order_status_completed','sendCustomData');

Saving custom order meta value

public static function tshirt_order_meta_handler( $item_id, $values, $cart_item_key ) {
    if( isset( $values['name_on_tshirt'] ) ) {
        wc_add_order_item_meta( $item_id, "name_on_tshirt", $values['name_on_tshirt'] );
    }
}
add_action( 'woocommerce_new_order_item', 'tshirt_order_meta_handler', 1, 3 );


问:
typeof() parameter - how does it work?
In the Code below:

```<code>string GetName(Type type)
{
    return ((type)this.obj).Name;
}

void Run()
{
    string name = GetName(typeof(MyClass));
}
</code>```

Im getting a "The type or name space cannot be found (are you missing using a directive or assembly reference?)" error. What should I do to correct this?

答:
You can't cast to an instance !

type is a instance of the Type class, if you want to cast to certain Type, use Generics

```<code>void GetName<T>() where T : IObjectWithName { return ((T)this.object).Name; }
</code>```

then you can call

```<code>string name = GetName<MyClass>();
</code>```

If that makes sens.

Title: typeof() parameter - how does it work?

Body:
In the Code below:

string GetName(Type type)
{
    return ((type)this.obj).Name;
}

void Run()
{
    string name = GetName(typeof(MyClass));
}

Im getting a "The type or name space cannot be found (are you missing using a directive or assembly reference?)" error. What should I do to correct this?

Body:
You can't cast to an instance !

type is a instance of the Type class, if you want to cast to certain Type, use Generics

void GetName<T>() where T : IObjectWithName { return ((T)this.object).Name; }

then you can call

string name = GetName<MyClass>();

If that makes sens.


问:
Loop that should print file names returns empty lines instead
I want to write a very basic script that return the file names of *txt files in the current directory. I wrote the following code:

```<code>#!/bin/bash
FILES=$(ls *txt)

for FILE in $FILES
do
echo "$File"
done
</code>```

The output of the script are 5 empty lines instead of the names of the 5 *txt files in the directoy.

答:
There are several things wrong with this script:

FILES is not an array.

Never use the output of ls programmatically.

FILE and File are two different variables; names are case-sensitive.

All-uppercase names are reserved for use by the shell.

Your code should be

```<code>files=( *txt )  # ( *.txt ) would probably be cleaner
for file in "${files[@]}"; do
  echo "$file"
done
</code>```

Be aware, though, that depending on your shell settings, the assignment to files can have three different outcomes if there are no matching files:

files could contain a single element, literally *txt (the default)

files could be empty (with nullglob set)

The pattern match could produce an error (with failglob set)

Body:
I want to write a very basic script that return the file names of *txt files in the current directory. I wrote the following code:

#!/bin/bash
FILES=$(ls *txt)

for FILE in $FILES
do
echo "$File"
done

The output of the script are 5 empty lines instead of the names of the 5 *txt files in the directoy.

Body:
There are several things wrong with this script:

FILES is not an array.

Never use the output of ls programmatically.

FILE and File are two different variables; names are case-sensitive.

All-uppercase names are reserved for use by the shell.

Your code should be

files=( *txt )  # ( *.txt ) would probably be cleaner
for file in "${files[@]}"; do
  echo "$file"
done

Be aware, though, that depending on your shell settings, the assignment to files can have three different outcomes if there are no matching files:

files could contain a single element, literally *txt (the default)

files could be empty (with nullglob set)

The pattern match could produce an error (with failglob set)


问:
GTX 970 bandwidth calculation
I am trying to calculate the theoretical bandwidth of gtx970. As per the specs given in:-

http://www.geforce.com/hardware/desktop-gpus/geforce-gtx-970/specifications

Memory clock is 7Gb/s
Memory bus width = 256

Bandwidth = 7*256*2/8  (*2 because it is a DDR)

```<code>      = 448 GB/s
</code>```

However, in the specs it is given as 224GB/s

Why is there a factor 2 difference? Am i making a mistake, if so please correct me.

Thanks

答:
The 7 Gbps seems to be the effective clock, i.e. including the data rate. Also note that the field explanation for this Wikipedia list says that "All DDR/GDDR memories operate at half this frequency, except for GDDR5, which operates at one quarter of this frequency", which suggests that all GDDR5 chips are in fact quad data rate, despite the DDR abbreviation.

Finally, let me point out this note from Wikipedia, which disqualifies the trivial effective clock * bus width formula:

For accessing its memory, the GTX 970 stripes data across 7 of its 8 32-bit physical memory lanes, at 196 GB/s. The last 1/8 of its memory (0.5 GiB on a 4 GiB card) is accessed on a non-interleaved solitary 32-bit connection at 28 GB/s, one seventh the speed of the rest of the memory space. Because this smaller memory pool uses the same connection as the 7th lane to the larger main pool, it contends with accesses to the larger block reducing the effective memory bandwidth not adding to it as an independent connection could.

Title: GTX 970 bandwidth calculation

Body:
I am trying to calculate the theoretical bandwidth of gtx970. As per the specs given in:-

http://www.geforce.com/hardware/desktop-gpus/geforce-gtx-970/specifications

Memory clock is 7Gb/s
Memory bus width = 256

Bandwidth = 7*256*2/8  (*2 because it is a DDR)

      = 448 GB/s

However, in the specs it is given as 224GB/s

Why is there a factor 2 difference? Am i making a mistake, if so please correct me.

Thanks


问:
Best way to remove multiple entries from kml file
I have a very large KML file (over 20000 placemarkers). They are named by numbers which go up in increments of 5 starting at about 7000 up to 27000.

```<code><Placemark>
    <name>7750</name>
    <description><![CDATA[converted by:</br><a href="http://gridreferencefinder.com/">GridReferenceFinder.com</a></br>]]></description>
    <Point>
        <coordinates>-0.99153654,52.225002,0</coordinates>
    </Point>
</Placemark>
</code>```

I would like to remove any placemarker that doesnt end in 00 or 50. Having a placemarker every 5 metres is slowing down some of the lower end devices on site.

Is there some script, command or whatever that will check the name and if it doesn't end in 00 or 50 delete from <Placemark> to </Placemark> for that entry?

You would literally be saving me 10 hours work deleting them individually.

答:
A Perl-one liner solution!

I would like to remove any placemarker that doesnt end in 00 or 50

First of all a solution for this; match anything except for ones end with 00 or 50

```<code>^(?:[7-9]\d|[1-2]\d\d)(?!00|50)\d\d$
</code>```

Demo:

^(?:[7-9]\d|[1-2]\d\d)(?!00|50)\d\d$

A fest test can be:

```<code>perl -le 'print for grep{ /^(?:[7-9]\d|[1-2]\d\d)(?=00|50)\d\d$/  } 7000..27000'
</code>```

then read the entire file once:

```<code>$/=undef;
</code>```

then read all matches with a while loop:

```<code>while/<Placemark>\s*?<name>(?:[7-9]\d|[1-2]\d\d)(?!00|50)\d\d.*?<\/Placemark>/sg
</code>```

s flag is for reading as a single line or . can match newline, and g for global search

then print the match (S&):

```<code>perl -lne '$/=undef;print $& while/<Placemark>\s*?<name>(?:[7-9]\d|[1-2]\d\d)(?!00|50)\d\d.*?<\/Placemark>/sg' file
</code>```

pattern for match:

```<code><Placemark>\s*?<name>(?:[7-9]\d|[1-2]\d\d)(?!00|50)\d\d.*?<\/Placemark>
</code>```

demo:

<Placemark>\s*?<name>(?:[7-9]\d|[1-2]\d\d)(?!00|50)\d\d.*?<\/Placemark>

NOTE:

If you notice this part (?!00|50) it is an exclude matcher that by using a lookahead, you can make it opposite, that means:

```<code>^(?:[7-9]\d|[1-2]\d\d)(?=00|50)\d\d$
</code>```

only matches things that end with 00 or 50.

So you can use this to switch between what you want and what you do not want.

print all patterns that does not end with 00 or 50

```<code>perl -lne '$/=undef;print $& while/<Placemark>\s*?<name>(?:[7-9]\d|[1-2]\d\d)(?!00|50)\d\d.*?<\/Placemark>/sg' file
</code>```

print all patterns that end with 00 or 50

```<code>perl -lne '$/=undef;print $& while/<Placemark>\s*?<name>(?:[7-9]\d|[1-2]\d\d)(?!00|50)\d\d.*?<\/Placemark>/sg' file
</code>```

How to Substitute

if you like, you can use operator: s/regex-match/substitute-string/

```<code>perl -pe '$/=undef;s/<Placemark>\s*?<name>(?:[7-9]\d|[1-2]\d\d)(?!00|50)\d\d.*?<\/Placemark>/==>DELETE<==/sg' file
</code>```

test:

input:

```<code>perl -le 'print for grep{ /^(?:[7-9]\d|[1-2]\d\d)(?=00|50)\d\d$/  } 7000..27000'
</code>```0

the output:

```<code>perl -le 'print for grep{ /^(?:[7-9]\d|[1-2]\d\d)(?=00|50)\d\d$/  } 7000..27000'
</code>```1

NOTE.2:

you can use -i for edit-in-place

```<code>perl -le 'print for grep{ /^(?:[7-9]\d|[1-2]\d\d)(?=00|50)\d\d$/  } 7000..27000'
</code>```2

It is better to use perl 5.22 or upper version

Body:
I have a very large KML file (over 20000 placemarkers). They are named by numbers which go up in increments of 5 starting at about 7000 up to 27000.

<Placemark>
    <name>7750</name>
    <description><![CDATA[converted by:
GridReferenceFinder.com
]]></description>
    <Point>
        <coordinates>-0.99153654,52.225002,0</coordinates>
    </Point>
</Placemark>

I would like to remove any placemarker that doesnt end in 00 or 50. Having a placemarker every 5 metres is slowing down some of the lower end devices on site.

Is there some script, command or whatever that will check the name and if it doesn't end in 00 or 50 delete from <Placemark> to </Placemark> for that entry?

You would literally be saving me 10 hours work deleting them individually.

Body:
A Perl-one liner solution!

I would like to remove any placemarker that doesnt end in 00 or 50

First of all a solution for this; match anything except for ones end with 00 or 50

^(?:[7-9]\d|[1-2]\d\d)(?!00|50)\d\d$

Demo:

^(?:[7-9]\d|[1-2]\d\d)(?!00|50)\d\d$

A fest test can be:

perl -le 'print for grep{ /^(?:[7-9]\d|[1-2]\d\d)(?=00|50)\d\d$/  } 7000..27000'

then read the entire file once:

$/=undef;

then read all matches with a while loop:

while/<Placemark>\s*?<name>(?:[7-9]\d|[1-2]\d\d)(?!00|50)\d\d.*?<\/Placemark>/sg

s flag is for reading as a single line or . can match newline, and g for global search

then print the match (S&):

perl -lne '$/=undef;print $& while/<Placemark>\s*?<name>(?:[7-9]\d|[1-2]\d\d)(?!00|50)\d\d.*?<\/Placemark>/sg' file

pattern for match:

<Placemark>\s*?<name>(?:[7-9]\d|[1-2]\d\d)(?!00|50)\d\d.*?<\/Placemark>

demo:

<Placemark>\s*?<name>(?:[7-9]\d|[1-2]\d\d)(?!00|50)\d\d.*?<\/Placemark>

NOTE:

If you notice this part (?!00|50) it is an exclude matcher that by using a lookahead, you can make it opposite, that means:

^(?:[7-9]\d|[1-2]\d\d)(?=00|50)\d\d$

only matches things that end with 00 or 50.

So you can use this to switch between what you want and what you do not want.

print all patterns that does not end with 00 or 50

perl -lne '$/=undef;print $& while/<Placemark>\s*?<name>(?:[7-9]\d|[1-2]\d\d)(?!00|50)\d\d.*?<\/Placemark>/sg' file

print all patterns that end with 00 or 50

perl -lne '$/=undef;print $& while/<Placemark>\s*?<name>(?:[7-9]\d|[1-2]\d\d)(?!00|50)\d\d.*?<\/Placemark>/sg' file

How to Substitute

if you like, you can use operator: s/regex-match/substitute-string/

perl -pe '$/=undef;s/<Placemark>\s*?<name>(?:[7-9]\d|[1-2]\d\d)(?!00|50)\d\d.*?<\/Placemark>/==>DELETE<==/sg' file

test:

input:

before...
<Placemark>
    <name>7700</name>
    <description><![CDATA[converted by:</br><a href="http://gridreferencefinder.com/">GridReferenceFinder.com</a></br>]]></description>
    <Point>
        <coordinates>-0.99153654,52.225002,0</coordinates>
    </Point>
</Placemark>
after...
---------
before...
<Placemark>
    <name>7701</name>
    <description><![CDATA[converted by:</br><a href="http://gridreferencefinder.com/">GridReferenceFinder.com</a></br>]]></description>
    <Point>
        <coordinates>-0.99153654,52.225002,0</coordinates>
    </Point>
</Placemark>
after...
--------
before...
<Placemark>
    <name>27650</name>
    <description><![CDATA[converted by:</br><a href="http://gridreferencefinder.com/">GridReferenceFinder.com</a></br>]]></description>
    <Point>
        <coordinates>-0.99153654,52.225002,0</coordinates>
    </Point>
</Placemark>
after...
--------
before...
<Placemark>
    <name>27651</name>
    <description><![CDATA[converted by:</br><a href="http://gridreferencefinder.com/">GridReferenceFinder.com</a></br>]]></description>
    <Point>
        <coordinates>-0.99153654,52.225002,0</coordinates>
    </Point>
</Placemark>
after...

end.

the output:

before...
<Placemark>
    <name>7700</name>
    <description><![CDATA[converted by:</br><a href="http://gridreferencefinder.com/">GridReferenceFinder.com</a></br>]]></description>
    <Point>
        <coordinates>-0.99153654,52.225002,0</coordinates>
    </Point>
</Placemark>
after...
---------
before...
==>DELETE<==
after...
--------
before...
<Placemark>
    <name>27650</name>
    <description><![CDATA[converted by:</br><a href="http://gridreferencefinder.com/">GridReferenceFinder.com</a></br>]]></description>
    <Point>
        <coordinates>-0.99153654,52.225002,0</coordinates>
    </Point>
</Placemark>
after...
--------
before...
==>DELETE<==
after...

end.

NOTE.2:

you can use -i for edit-in-place

perl -i.bak -pe ' ... the rest of the script ...' file

It is better to use perl 5.22 or upper version


问:
Running statistics on multiple lines in bash
I have multiple HTTP headers in one giant file, separated with one empty line.

```<code>Host
Connection
Accept
From
User-Agent
Accept-Encoding

Host
Connection
Accept
From
User-Agent
Accept-Encoding
X-Forwarded-For

cookie
Cache-Control
referer
x-fb-sim-hni
Host
Accept
user-agent
x-fb-net-sid
x-fb-net-hni
X-Purpose
accept-encoding
x-fb-http-engine
Connection

User-Agent
Host
Connection
Accept-Encoding
</code>```

I have approximately 10,000,000 of headers separated with an empty line.
If I want to discover trends, like header order, I want to do aggregate headers to a one-liner (how I can aggregate lines ending with an empty line and do that separately for all headers?):

Host,Connection,Accept,From,User-Agent,Accept-Encoding

and follow with: uniq -c|sort -nk1,
so I could receive:

```<code>197897 Host,Connection,Accept,From,User-Agent,Accept-Encoding
8732233 User-Agent,Host,Connection,Accept-Encoding
</code>```

What would be the best approach and most effective one to parse that massive file and get that data?

Thanks for hints.

答:
Using GNU awk for sorted_in, all you need is:

```<code>$ cat tst.awk
BEGIN { RS=""; FS="\n"; OFS="," }
{ $1=$1; cnt[$0]++ }
END {
    PROCINFO["sorted_in"] = "@val_num_desc"
    for (rec in cnt) {
        print cnt[rec] " " rec
    }
}
</code>```

After running dos2unix on the sample you posted (1.5milGETs.txt):

```<code>$ time awk -f tst.awk 1.5milGETs.txt > ou.awk

real    0m4.898s
user    0m4.758s
sys     0m0.108s

$ head -10 ou.awk
71639 Host,Accept,User-Agent,Pragma,Connection
70975 Host,ros-SecurityFlags,ros-SessionTicket,ros-Challenge,ros-HeadersHmac,Scs-Ticket,If-Modified-Since,User-Agent
40781 Host,Accept,User-Agent,Pragma,nnCoection,Connection,X-Forwarded-For
35485 Accept,ros-SecurityFlags,ros-SessionTicket,ros-Challenge,ros-HeadersHmac,Scs-Ticket,If-Modified-Since,User-Agent,Accept-Language,UA-CPU,Accept-Encoding,Host,Connection
34005 User-Agent,Host,Connection,Accept-Encoding
30668 Host,User-Agent,Accept-Encoding,Connection
25547 Host,Accept,Accept-Language,Connection,Accept-Encoding,User-Agent
22581 Host,User-Agent,Accept,Accept-Encoding
19311 Host,Connection,Accept,From,User-Agent,Accept-Encoding
14694 Host,Connection,User-Agent,Accept,Referer,Accept-Encoding,Accept-Language,Cookie
</code>```

Body:
I have multiple HTTP headers in one giant file, separated with one empty line.

Host
Connection
Accept
From
User-Agent
Accept-Encoding

Host
Connection
Accept
From
User-Agent
Accept-Encoding
X-Forwarded-For

cookie
Cache-Control
referer
x-fb-sim-hni
Host
Accept
user-agent
x-fb-net-sid
x-fb-net-hni
X-Purpose
accept-encoding
x-fb-http-engine
Connection

User-Agent
Host
Connection
Accept-Encoding

I have approximately 10,000,000 of headers separated with an empty line.
If I want to discover trends, like header order, I want to do aggregate headers to a one-liner (how I can aggregate lines ending with an empty line and do that separately for all headers?):

Host,Connection,Accept,From,User-Agent,Accept-Encoding

and follow with: uniq -c|sort -nk1,
so I could receive:

197897 Host,Connection,Accept,From,User-Agent,Accept-Encoding
8732233 User-Agent,Host,Connection,Accept-Encoding

What would be the best approach and most effective one to parse that massive file and get that data?

Thanks for hints.

Body:
Using GNU awk for sorted_in, all you need is:

$ cat tst.awk
BEGIN { RS=""; FS="\n"; OFS="," }
{ $1=$1; cnt[$0]++ }
END {
    PROCINFO["sorted_in"] = "@val_num_desc"
    for (rec in cnt) {
        print cnt[rec] " " rec
    }
}

After running dos2unix on the sample you posted (1.5milGETs.txt):

$ time awk -f tst.awk 1.5milGETs.txt > ou.awk

real    0m4.898s
user    0m4.758s
sys     0m0.108s

$ head -10 ou.awk
71639 Host,Accept,User-Agent,Pragma,Connection
70975 Host,ros-SecurityFlags,ros-SessionTicket,ros-Challenge,ros-HeadersHmac,Scs-Ticket,If-Modified-Since,User-Agent
40781 Host,Accept,User-Agent,Pragma,nnCoection,Connection,X-Forwarded-For
35485 Accept,ros-SecurityFlags,ros-SessionTicket,ros-Challenge,ros-HeadersHmac,Scs-Ticket,If-Modified-Since,User-Agent,Accept-Language,UA-CPU,Accept-Encoding,Host,Connection
34005 User-Agent,Host,Connection,Accept-Encoding
30668 Host,User-Agent,Accept-Encoding,Connection
25547 Host,Accept,Accept-Language,Connection,Accept-Encoding,User-Agent
22581 Host,User-Agent,Accept,Accept-Encoding
19311 Host,Connection,Accept,From,User-Agent,Accept-Encoding
14694 Host,Connection,User-Agent,Accept,Referer,Accept-Encoding,Accept-Language,Cookie


问:
Keep autolayout constraints active status on device rotation
I noticed that when I update my autolayout constraints programmatically, all changes are reverted when I rotate the screen.

Reproduce the issue:

Basic Storyboard interface with UIView and 2 constraints:

width equal superview.width (multiplier 1) active

width equal superview.width (multiplier 1/2) disabled

Create and link these 2 constraints with IBOutlet

Programmatically disable the first constraint and enable the second one.

Rotate the device, the first constraint is active and the second one disabled.

Seems like a bug to me.

What do you think ?

Screenshots:

Storyboard:

Constraint #1:

Constraint #2:

答:
You can do the necessary switch with the constraints created via IB for size classes. The trick is to keep the collapsed state in a variable and update constraints as on your button's event as also on trait collection change event.</p>

```<code>var collapsed: Bool {
    didSet {
        view.setNeedsUpdateConstraints()
    }
}

@IBAction func onButtonClick(sender: UISwitch) {
    view.layoutIfNeeded()
    collapsed = !collapsed
    UIView.animate(withDuration: 0.3) {
        view.layoutIfNeeded()
    }
}

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    super.traitCollectionDidChange(previousTraitCollection)
    view.setNeedsUpdateConstraints()
}

override func updateViewConstraints() {
    constraint1.isActive = !collapsed
    constraint2.isActive = collapsed
    super.updateViewConstraints()
}
</code>```

Body:
You can do the necessary switch with the constraints created via IB for size classes. The trick is to keep the collapsed state in a variable and update constraints as on your button's event as also on trait collection change event.

var collapsed: Bool {
    didSet {
        view.setNeedsUpdateConstraints()
    }
}

@IBAction func onButtonClick(sender: UISwitch) {
    view.layoutIfNeeded()
    collapsed = !collapsed
    UIView.animate(withDuration: 0.3) {
        view.layoutIfNeeded()
    }
}

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    super.traitCollectionDidChange(previousTraitCollection)
    view.setNeedsUpdateConstraints()
}

override func updateViewConstraints() {
    constraint1.isActive = !collapsed
    constraint2.isActive = collapsed
    super.updateViewConstraints()
}


问:
System.setOut() equivalent for PrintWriter
How to set a overridden printwriter class as a default printwriter class. whenever i create a printwriter object, the object created should be the object of the overridden printwriter class. Like setting system.setOut(), is there any function available to set printwriter too.</p>

答:
You can't do that. In your example a very specific object is "replaced". Only System.out behaves differently. No other stream is affected by that call.

In other words: there is no way to change of what a call like new X() will do. If you want something other than an X object - you have to call new Y() for example.


问:
Mockito: How to verify a method was called only once with exact parameters ignoring calls to other methods?
Using Mockito in Java how to verify a method was called only once with exact parameters ignoring calls to other methods?

Sample code:

```<code>public class MockitoTest {

    interface Foo {
        void add(String str);
        void clear();
    }

    @Test
    public void testAddWasCalledOnceWith1IgnoringAllOtherInvocations() throws Exception {
        // given
        Foo foo = Mockito.mock(Foo.class);

        // when
        foo.add("1"); // call to verify
        foo.add("2"); // !!! don't allow any other calls to add()
        foo.clear();  // calls to other methods should be ignored

        // then
        Mockito.verify(foo, Mockito.times(1)).add("1");
        // TODO: don't allow all other invocations with add()
        //       but ignore all other calls (i.e. the call to clear())
    }

}
</code>```

What should be done in the TODO: don't allow all other invocations with add() section?

Already unsuccessfully tried:

verifyNoMoreInteractions(foo);

Nope. It does not allow calls to other methods like clear().

verify(foo, times(0)).add(any());

Nope. It does not take into account that we allow one call to add("1").

答:
The previous answer can be simplified even further.

```<code>Mockito.verify(foo).add("1");
Mockito.verify(foo).add(Mockito.anyString());
</code>```

The single parameter verify method is just an alias to the times(1)implementation.

Body:
Using Mockito in Java how to verify a method was called only once with exact parameters ignoring calls to other methods?

Sample code:

public class MockitoTest {

    interface Foo {
        void add(String str);
        void clear();
    }

    @Test
    public void testAddWasCalledOnceWith1IgnoringAllOtherInvocations() throws Exception {
        // given
        Foo foo = Mockito.mock(Foo.class);

        // when
        foo.add("1"); // call to verify
        foo.add("2"); // !!! don't allow any other calls to add()
        foo.clear();  // calls to other methods should be ignored

        // then
        Mockito.verify(foo, Mockito.times(1)).add("1");
        // TODO: don't allow all other invocations with add()
        //       but ignore all other calls (i.e. the call to clear())
    }

}

What should be done in the TODO: don't allow all other invocations with add() section?

Already unsuccessfully tried:

verifyNoMoreInteractions(foo);

Nope. It does not allow calls to other methods like clear().

verify(foo, times(0)).add(any());

Nope. It does not take into account that we allow one call to add("1").

Body:
The previous answer can be simplified even further.

Mockito.verify(foo).add("1");
Mockito.verify(foo).add(Mockito.anyString());

The single parameter verify method is just an alias to the times(1)implementation.


问:
Move Rows Up and Down in ASP.NET GridView
I am trying to learn to move a row with in a gridview up and down the list by pressing either an up button or down button.

Below is my ASP.NET.

```<code><asp:GridView ID="gridChecks" runat="server" ShowFooter="true" AutoGenerateColumns="false" OnRowCreated="GridChecks_RowCreated" OnRowCommand="gridChecks_RowCommand" Style="margin: 0 auto; width: 850px; margin-top: 10px" CssClass="tableGlobalGenericStyle tableGlobalOption_AlternatingRow">
                        <Columns>
                            <asp:BoundField DataField="RowNumber" HeaderText="Check ID" HeaderStyle-Width="80px" />
                            <asp:TemplateField HeaderText="Check Title" HeaderStyle-Width="250px">
                                <ItemTemplate>
                                    <asp:TextBox ID="txtCheckTitle" runat="server" Width="240px"></asp:TextBox>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Effective From">
                                <ItemTemplate>
                                    <asp:textbox ID="txtDateFrom" runat="server" Width="150px"></asp:textbox>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Effective To">
                                <ItemTemplate>
                                    <asp:textbox ID="txtDateTo" runat="server" Width="150px"></asp:textbox>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Actions" HeaderStyle-Width="200px">
                                <ItemTemplate>
                                    <asp:Button ID="btnMoveUp" runat="server" CommandName="Up" CssClass="imageButton imageButton_UpArrow imageButton_Image" ToolTip="Click to add move check up the list" />
                                    <asp:Button ID="btnMoveDown" runat="server" CommandName="Down" CssClass="imageButton imageButton_DownArrow imageButton_Image" ToolTip="Click to add move check down the list" />
                                    <asp:Button ID="btnRemoveCheck" runat="server" OnClick="BtnRemove_Click" CssClass="imageButton imageButton_Remove imageButton_Image" ToolTip="Click to add remove check from the list" />
                                </ItemTemplate>
                                <FooterStyle HorizontalAlign="Center" />
                                <FooterTemplate>
                                    <asp:Button ID="btnAddCheck" runat="server" OnClick="BtnAddCheck_Click" CssClass="imageButton imageButton_Add" Text="Add Check" ToolTip="Click to add new check to the list" />
                                </FooterTemplate>
                            </asp:TemplateField>
                        </Columns>
                    </asp:GridView>
</code>```

I currently have a delete button that deletes it from the row and retains the number sequence ID.

Delete Button C#

```<code>protected void BtnRemove_Click(object sender, EventArgs e)
{
    Button lb = (Button)sender;
    GridViewRow gvRow = (GridViewRow)lb.NamingContainer;
    int rowID = gvRow.RowIndex;
    if (ViewState["CurrentTable"] != null)
    {
        DataTable dt = (DataTable)ViewState["CurrentTable"];
        if (dt.Rows.Count > 1)
        {
            if (gvRow.RowIndex < dt.Rows.Count - 1)
            {
                //Remove the Selected Row data and reset row number
                dt.Rows.Remove(dt.Rows[rowID]);
                ResetRowID(dt);
            }
        }

        //Store the current data in ViewState for future reference
        ViewState["CurrentTable"] = dt;

        //Re bind the GridView for the updated data
        gridChecks.DataSource = dt;
        gridChecks.DataBind();
    }

    //Set Previous Data on Postbacks
    SetPreviousData();
}
</code>```

I am trying to do something similar but move the row up or down in the list, also retaining the number sequence ID.

I have an understanding it will involve the indexes of the gridview and that i will need to rebind it once done.

Can someone please guide me in the right direction with an example. Thank you!!

答:
Following your example, given index is the index of the first of the two rows you want to swap:

create a new row

```<code>var firstRow = dt[index];
var newRow = dt.NewRow();
</code>```

populate newRow with data from the first row

```<code>for (int i=0; i<dt.Colums.Count(); i++)
  newRow[i]=firstRow[i]
</code>```

Remove firstRow

```<code>dt.RemoveAt[index];
</code>```

Now second row has rowIndex = index, so we add new row after it

```<code>dt.InsertAt[newRow, index + 1];
</code>```

In this way we have pulled up second row by 1 position

Body:
I am trying to learn to move a row with in a gridview up and down the list by pressing either an up button or down button.

Below is my ASP.NET.

<asp:GridView ID="gridChecks" runat="server" ShowFooter="true" AutoGenerateColumns="false" OnRowCreated="GridChecks_RowCreated" OnRowCommand="gridChecks_RowCommand" Style="margin: 0 auto; width: 850px; margin-top: 10px" CssClass="tableGlobalGenericStyle tableGlobalOption_AlternatingRow">
                        <Columns>
                            <asp:BoundField DataField="RowNumber" HeaderText="Check ID" HeaderStyle-Width="80px" />
                            <asp:TemplateField HeaderText="Check Title" HeaderStyle-Width="250px">
                                <ItemTemplate>
                                    <asp:TextBox ID="txtCheckTitle" runat="server" Width="240px"></asp:TextBox>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Effective From">
                                <ItemTemplate>
                                    <asp:textbox ID="txtDateFrom" runat="server" Width="150px"></asp:textbox>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Effective To">
                                <ItemTemplate>
                                    <asp:textbox ID="txtDateTo" runat="server" Width="150px"></asp:textbox>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Actions" HeaderStyle-Width="200px">
                                <ItemTemplate>
                                    <asp:Button ID="btnMoveUp" runat="server" CommandName="Up" CssClass="imageButton imageButton_UpArrow imageButton_Image" ToolTip="Click to add move check up the list" />
                                    <asp:Button ID="btnMoveDown" runat="server" CommandName="Down" CssClass="imageButton imageButton_DownArrow imageButton_Image" ToolTip="Click to add move check down the list" />
                                    <asp:Button ID="btnRemoveCheck" runat="server" OnClick="BtnRemove_Click" CssClass="imageButton imageButton_Remove imageButton_Image" ToolTip="Click to add remove check from the list" />
                                </ItemTemplate>
                                <FooterStyle HorizontalAlign="Center" />
                                <FooterTemplate>
                                    <asp:Button ID="btnAddCheck" runat="server" OnClick="BtnAddCheck_Click" CssClass="imageButton imageButton_Add" Text="Add Check" ToolTip="Click to add new check to the list" />
                                </FooterTemplate>
                            </asp:TemplateField>
                        </Columns>
                    </asp:GridView>

I currently have a delete button that deletes it from the row and retains the number sequence ID.

Delete Button C#

protected void BtnRemove_Click(object sender, EventArgs e)
{
    Button lb = (Button)sender;
    GridViewRow gvRow = (GridViewRow)lb.NamingContainer;
    int rowID = gvRow.RowIndex;
    if (ViewState["CurrentTable"] != null)
    {
        DataTable dt = (DataTable)ViewState["CurrentTable"];
        if (dt.Rows.Count > 1)
        {
            if (gvRow.RowIndex < dt.Rows.Count - 1)
            {
                //Remove the Selected Row data and reset row number
                dt.Rows.Remove(dt.Rows[rowID]);
                ResetRowID(dt);
            }
        }

        //Store the current data in ViewState for future reference
        ViewState["CurrentTable"] = dt;

        //Re bind the GridView for the updated data
        gridChecks.DataSource = dt;
        gridChecks.DataBind();
    }

    //Set Previous Data on Postbacks
    SetPreviousData();
}

I am trying to do something similar but move the row up or down in the list, also retaining the number sequence ID.

I have an understanding it will involve the indexes of the gridview and that i will need to rebind it once done.

Can someone please guide me in the right direction with an example. Thank you!!

Body:
Following your example, given index is the index of the first of the two rows you want to swap:

create a new row

var firstRow = dt[index];
var newRow = dt.NewRow();

populate newRow with data from the first row

for (int i=0; i<dt.Colums.Count(); i++)
  newRow[i]=firstRow[i]

Remove firstRow

dt.RemoveAt[index];

Now second row has rowIndex = index, so we add new row after it

dt.InsertAt[newRow, index + 1];

In this way we have pulled up second row by 1 position


问:
Cloud Functions for Firebase and third party api
My problem is to make use of an API along with Firebase Functions, the API in question is Coinbase, I use the API with node, if I test in the terminal with the node command it works, however when I use it with Firebase Functions Does not work at all, I've been trying to solve the problem for almost a week now.

The code is as follows>

```<code>    var functions = require('firebase-functions');

    var Client = require('coinbase').Client;
    var client = new Client({
        "apiKey": "xxxxxxxxxxxx",
        "apiSecret": "xxxxxxxxxxxxxxxxxxxxxxx"
    });

exports.helloWorld = functions.https.onRequest((request, response) => {

    this.client.getAccounts({}, function(err, accounts) {

        if(accounts){

            response.send(accounts);
         }else{
            response.send(err);

        }

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

The error: https://us-central1-investimentos-b7406.cloudfunctions.net/helloWorld

The Coinbase API: https://developers.coinbase.com/docs/wallet/guides/bitcoin-wallet

答:
There's a warning in the docs:

Firebase projects on the Spark plan can make only outbound requests to
  Google APIs. Requests to third-party APIs fail with an error. For more
  information about upgrading your project, see Pricing.

So you'll need to upgrade to a paid plan to use external APIs.

Body:
My problem is to make use of an API along with Firebase Functions, the API in question is Coinbase, I use the API with node, if I test in the terminal with the node command it works, however when I use it with Firebase Functions Does not work at all, I've been trying to solve the problem for almost a week now.

The code is as follows>

    var functions = require('firebase-functions');

    var Client = require('coinbase').Client;
    var client = new Client({
        "apiKey": "xxxxxxxxxxxx",
        "apiSecret": "xxxxxxxxxxxxxxxxxxxxxxx"
    });

exports.helloWorld = functions.https.onRequest((request, response) => {

    this.client.getAccounts({}, function(err, accounts) {

        if(accounts){

            response.send(accounts);
         }else{
            response.send(err);

        }

    });
});

The error: https://us-central1-investimentos-b7406.cloudfunctions.net/helloWorld

The Coinbase API: https://developers.coinbase.com/docs/wallet/guides/bitcoin-wallet


问:
Template Build in VMWare
Hi I am newbie to VMWare. Can someone let me know what is Template Build in VMWare.

I am aware of Basic VM Concepts and How to deploy vm from template. But I am not aware of template Build.

Thanks in advance.

答:
It is like a master copy of your machine and its configuration.
if u need to make frequent clones of a VM then a Template is created which is used to make copies</p>

Title: Template Build in VMWare


问:
Umbraco 4.5.2 admin UI broken
The Umbraco admin interface is broken for me, and in IE8 it shows couple of javascript errors. For a few hours it worked fine, but suddenly the css/style file appears to have gotten corrupted.

I had just finished with Master and home pages for my site, so I don't think it is related to my changes :).

Does any one know how to restore the css/style of admin interface?

I tried and reinstall 3 times, but after couple of hours it again behaves the same. It is frustrating as I am unable to develop further with out admin UI.
Does any one have any solutions?

I had raised this at http://our.umbraco.org/forum/using/ui-questions/12166-Admin-UI-Interface-is-broken-452#

答: I have recently had this issue and found that deleting the CacheDependency folder did not work for me. However, deleting the TEMP folder in the App_Data folder did work.</p>

Title: Umbraco 4.5.2 admin UI broken


问:
New records are saved in store, but show only after refresh of page
this a Sencha code which I am supposed to fix, however I don't understand why after creating new records to a store, they don't show immediately, but, only after refresh(?). Below are the relevant pieces of code.

Thank you.

Controller

```<code> click: function(button){
                var window = button.up('window');
                var form = window.down('form#formTemplateWindow');

                if(window.action == "add"){
                    if(form.isValid()){
                        var store = this.getDataViewList().getStore();
                        var zones = new Array();
                        Ext.each(form.zones, function(value, key){
                            zones.push(value.data.id);
                        });
                        var record = form.getValues();
                        record.zones = zones;
                        store.add(record);
                        store.sync();
                        button.up('window').close();
                    }
                }
</code>```

Model

```<code>Ext.define("web.model.Template", {
extend: "Ext.data.Model",
fields: [
    'id',
    'name',
    'layout_id',
    {
        name: 'reg_date',
        type: 'date',
        dateReadFormat: 'Y-m-d H:i:s',
        dateWriteFormat: 'Y-m-d H:i:s'
    },{
        name: 'background',
        type: 'auto'
    },{
        name: 'color1',
        type: 'string'
    },{
        name: 'color2',
        type: 'string'
    },{
        name: 'url',
        type: 'string'
    },{
        name: 'degree',
        type: 'string'
    },{
        name: 'playlists',
        type: 'auto'
    },{
        name: 'zones',
        type: 'auto'
    }
]
</code>```

});

Store

```<code>Ext.define("web.store.Template",{
extend:"Ext.data.Store",
autoSync: true,
autoLoad:false,
model:"web.model.Template",
proxy:{
    type:"rest",
    url:web.util.Config.TEMPLATE_URI,
    reader:{
        type:"json",
        root:"result"
    }
},

sorters: [
    {
        property: 'Name',
        direction: 'ASC'
    }
]
</code>```

});

答:
Change autoLoad property false to true

autoLoad:true

Body:
this a Sencha code which I am supposed to fix, however I don't understand why after creating new records to a store, they don't show immediately, but, only after refresh(?). Below are the relevant pieces of code.

Thank you.

Controller

 click: function(button){
                var window = button.up('window');
                var form = window.down('form#formTemplateWindow');

                if(window.action == "add"){
                    if(form.isValid()){
                        var store = this.getDataViewList().getStore();
                        var zones = new Array();
                        Ext.each(form.zones, function(value, key){
                            zones.push(value.data.id);
                        });
                        var record = form.getValues();
                        record.zones = zones;
                        store.add(record);
                        store.sync();
                        button.up('window').close();
                    }
                }

Model

Ext.define("web.model.Template", {
extend: "Ext.data.Model",
fields: [
    'id',
    'name',
    'layout_id',
    {
        name: 'reg_date',
        type: 'date',
        dateReadFormat: 'Y-m-d H:i:s',
        dateWriteFormat: 'Y-m-d H:i:s'
    },{
        name: 'background',
        type: 'auto'
    },{
        name: 'color1',
        type: 'string'
    },{
        name: 'color2',
        type: 'string'
    },{
        name: 'url',
        type: 'string'
    },{
        name: 'degree',
        type: 'string'
    },{
        name: 'playlists',
        type: 'auto'
    },{
        name: 'zones',
        type: 'auto'
    }
]

});

Store

Ext.define("web.store.Template",{
extend:"Ext.data.Store",
autoSync: true,
autoLoad:false,
model:"web.model.Template",
proxy:{
    type:"rest",
    url:web.util.Config.TEMPLATE_URI,
    reader:{
        type:"json",
        root:"result"
    }
},

sorters: [
    {
        property: 'Name',
        direction: 'ASC'
    }
]

});


问:
JavaFX Draw a straight line that updates itself when the user moves the moves
I want to draw a straight line that updates itself, kinda like what you've in Microsoft Paint. Currently I can draw it without the visual feedback, setting the starting x and y on the first click and when user clicks the mouse button again it sets the end x and y, and adds it to root children.

I found this answer how to draw a straight line in javafx that updates itself when the user moves the mouse?, which is basically what I would like to do and essentially solves my problem by using canvas. Other user's in that thread have suggested or implicated that it would be even easier to achieve without canvas, but have not provided examples.

Since I can't comment that question: Would someone show me an example of this without canvas? According user comments, it should be even easier, but I can't figure it out.

I hacked together this, which works but I feel like there is a better way to do this:

```<code>private void registerMouseEventHandlers() {
    final Toggle toggle = new Toggle();
    final CustomLineMouseEventHandler lineMouseEventHandler = new CustomLineMouseEventHandler();

    this.scene.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
        public void handle(MouseEvent event) {
            toggle.clickCount++;

            if (toggle.clickedTwice()) {
                lineMouseEventHandler.setEndXAndYAndAddToSceneGroup(event.getX(), event.getY());
            }
            else {
                lineMouseEventHandler.setCustomLine(new CustomLine());
                lineMouseEventHandler.setStartXAndY(event.getX(), event.getY());
            }

        }
    });
}

public class CustomLineMouseEventHandler {
private CustomLine customLine;
private List<CustomLine> customLines = new ArrayList<CustomLine>();

public void setCustomLine(CustomLine customLine) {
    this.customLine = customLine;
    this.customLine.setVisible(true);

}

public void setStartXAndY(double x, double y) {
    this.customLine.setStartX(x);
    this.customLine.setStartY(y);
    LineManipulator.getGroup().getChildren().add(this.customLine);
}

public void updateLine(double x, double y) {
    if (this.customLine != null) {
        this.customLine.setEndX(x);
        this.customLine.setEndY(y);
    }
}

public void setEndXAndYAndAddToSceneGroup(double x, double y) {
    this.customLine.setEndX(x);
    this.customLine.setEndY(y);
    this.customLines.add(customLine);
    LineManipulator.getGroup().getChildren().remove(LineManipulator.getGroup().getChildren().size() - 1);
    LineManipulator.getGroup().getChildren().add(this.customLine);
    this.customLine = null;
}
</code>```

}

答:
You can easily implement a click-drag-release user input style for this: add a new line to a pane when the mouse is pressed, and update its endpoint when the mouse is dragged:

```<code>import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Line;
import javafx.stage.Stage;

public class Draw extends Application {

    private Line currentLine ;

    @Override
    public void start(Stage primaryStage) {
        Pane pane = new Pane();

        pane.setOnMousePressed(e -> {
            currentLine = new Line(e.getX(), e.getY(), e.getX(), e.getY());
            pane.getChildren().add(currentLine);
        });

        pane.setOnMouseDragged(e -> {
            currentLine.setEndX(e.getX());
            currentLine.setEndY(e.getY());
        });

        Scene scene = new Scene(pane, 600, 600);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

If you prefer a click-move-click user experience to press-drag-release, replace the two event handlers with

```<code>    pane.setOnMouseClicked(e -> {
        if (currentLine == null) {
            currentLine = new Line(e.getX(), e.getY(), e.getX(), e.getY());
            pane.getChildren().add(currentLine);
        } else {
            currentLine = null ;
        }
    });

    pane.setOnMouseMoved(e -> {
        if (currentLine != null) {
            currentLine.setEndX(e.getX());
            currentLine.setEndY(e.getY());
        }
    });
</code>```

Body:
I want to draw a straight line that updates itself, kinda like what you've in Microsoft Paint. Currently I can draw it without the visual feedback, setting the starting x and y on the first click and when user clicks the mouse button again it sets the end x and y, and adds it to root children.

I found this answer how to draw a straight line in javafx that updates itself when the user moves the mouse?, which is basically what I would like to do and essentially solves my problem by using canvas. Other user's in that thread have suggested or implicated that it would be even easier to achieve without canvas, but have not provided examples.

Since I can't comment that question: Would someone show me an example of this without canvas? According user comments, it should be even easier, but I can't figure it out.

I hacked together this, which works but I feel like there is a better way to do this:

private void registerMouseEventHandlers() {
    final Toggle toggle = new Toggle();
    final CustomLineMouseEventHandler lineMouseEventHandler = new CustomLineMouseEventHandler();

    this.scene.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
        public void handle(MouseEvent event) {
            toggle.clickCount++;

            if (toggle.clickedTwice()) {
                lineMouseEventHandler.setEndXAndYAndAddToSceneGroup(event.getX(), event.getY());
            }
            else {
                lineMouseEventHandler.setCustomLine(new CustomLine());
                lineMouseEventHandler.setStartXAndY(event.getX(), event.getY());
            }

        }
    });
}

public class CustomLineMouseEventHandler {
private CustomLine customLine;
private List<CustomLine> customLines = new ArrayList<CustomLine>();

public void setCustomLine(CustomLine customLine) {
    this.customLine = customLine;
    this.customLine.setVisible(true);

}

public void setStartXAndY(double x, double y) {
    this.customLine.setStartX(x);
    this.customLine.setStartY(y);
    LineManipulator.getGroup().getChildren().add(this.customLine);
}

public void updateLine(double x, double y) {
    if (this.customLine != null) {
        this.customLine.setEndX(x);
        this.customLine.setEndY(y);
    }
}

public void setEndXAndYAndAddToSceneGroup(double x, double y) {
    this.customLine.setEndX(x);
    this.customLine.setEndY(y);
    this.customLines.add(customLine);
    LineManipulator.getGroup().getChildren().remove(LineManipulator.getGroup().getChildren().size() - 1);
    LineManipulator.getGroup().getChildren().add(this.customLine);
    this.customLine = null;
}

}

Body:
You can easily implement a click-drag-release user input style for this: add a new line to a pane when the mouse is pressed, and update its endpoint when the mouse is dragged:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Line;
import javafx.stage.Stage;

public class Draw extends Application {

    private Line currentLine ;

    @Override
    public void start(Stage primaryStage) {
        Pane pane = new Pane();

        pane.setOnMousePressed(e -> {
            currentLine = new Line(e.getX(), e.getY(), e.getX(), e.getY());
            pane.getChildren().add(currentLine);
        });

        pane.setOnMouseDragged(e -> {
            currentLine.setEndX(e.getX());
            currentLine.setEndY(e.getY());
        });

        Scene scene = new Scene(pane, 600, 600);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

If you prefer a click-move-click user experience to press-drag-release, replace the two event handlers with

    pane.setOnMouseClicked(e -> {
        if (currentLine == null) {
            currentLine = new Line(e.getX(), e.getY(), e.getX(), e.getY());
            pane.getChildren().add(currentLine);
        } else {
            currentLine = null ;
        }
    });

    pane.setOnMouseMoved(e -> {
        if (currentLine != null) {
            currentLine.setEndX(e.getX());
            currentLine.setEndY(e.getY());
        }
    });


问:
jquery random element id for every loop
sorry i'm new in jquery and i need help :-(
  i want to traverse all elements on html page with class parts
then go inside to two children and pass them a random number ( the same for them both)

for every element new random number is passed ( no repeat on page)
children classes are :
anot-head
anot-body
this is a sample code:

```<code>    $(document).ready(function() {

$.each($('.parts'), function(){
var ran=Math.floor(Math.random()* 1000000);

$( ".anot-head" ).attr( "data-toggle","collapse" ).attr( "href","#s"+ran );
$( ".anot-body" ).attr( "id","s"+ran );

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

答:
No need to use random.... use index of each

```<code>$('.parts').each(function(index){
  var $part = $(this);
  $part.find('.anot-head').attr({"data-toggle":"collapse","href":"#s"+index});
  $part.find('.anot-body').attr("id","s"+ index);
});
</code>```

Title: jquery random element id for every loop

Body:
sorry i'm new in jquery and i need help :-(
  i want to traverse all elements on html page with class parts
then go inside to two children and pass them a random number ( the same for them both)

for every element new random number is passed ( no repeat on page)
children classes are :
anot-head
anot-body
this is a sample code:

    $(document).ready(function() {

$.each($('.parts'), function(){
var ran=Math.floor(Math.random()* 1000000);

$( ".anot-head" ).attr( "data-toggle","collapse" ).attr( "href","#s"+ran );
$( ".anot-body" ).attr( "id","s"+ran );

});
});

Body:
No need to use random.... use index of each

$('.parts').each(function(index){
  var $part = $(this);
  $part.find('.anot-head').attr({"data-toggle":"collapse","href":"#s"+index});
  $part.find('.anot-body').attr("id","s"+ index);
});


问:
How to create name for the textField dynamically [SWIFT]?
How to create name for the textField dynamically for next parsing value, which will be the name of the textField? It will looks like UID_score.
UID - this is user id, which is fetching from CoreData.

答:
I'm not absolutely sure about what you want to achieve, but one way to generate a number of TextFields that match with the number of user Ids could be as follows. You can also set tag of the TextField to keep track of each user.

```<code>let userIds = [5, 8, 9, 10, 12]
let textFields = (0 ..< userIds.count).map { _ in UITextField() }
for i in 0..<userIds.count {
    textFields[i].frame = CGRect(x: 10 * i, y: 10, width: 30, height: 30)
    textFields[i].tag = userIds[i]
    view.addSubview(textFields[i])
}
</code>```

Body:
I'm not absolutely sure about what you want to achieve, but one way to generate a number of TextFields that match with the number of user Ids could be as follows. You can also set tag of the TextField to keep track of each user.

let userIds = [5, 8, 9, 10, 12]
let textFields = (0 ..< userIds.count).map { _ in UITextField() }
for i in 0..<userIds.count {
    textFields[i].frame = CGRect(x: 10 * i, y: 10, width: 30, height: 30)
    textFields[i].tag = userIds[i]
    view.addSubview(textFields[i])
}


问:
could not connect to aws services using aws-cli
I am new to aws, I am trying to use aws-cli to connect aws as I am confortable with commandline, and want to use to write the script to automate the process.

However I am getting error as below:

```<code>_
    attempt_number, caught_exception)
  File "/usr/local/lib/python2.7/site-packages/botocore/retryhandler.py", line 359, in _check_caught_exception
    raise caught_exception
EndpointConnectionError: Could not connect to the endpoint URL: "https://ec2.ap-southeast-1a.amazonaws.com/"
2017-07-08 20:30:52,763 - MainThread - awscli.clidriver - DEBUG - Exiting with rc 255

Could not connect to the endpoint URL: "https://ec2.ap-southeast-1a.amazonaws.com/"
</code>```

I have setup the profile user as in the config file.

```<code>[profile joey2]
output = json
region = ap-southeast-1a
</code>```

the credential such as api key and secret is configured properly.

Could someone help to figure out what is cause of this issue.
highly appreciate for any advice?

答:
ap-southeast-1a is not a valid AWS Region, you need to use ap-southeast-1 instead. You're getting that connection error because https://ec2.ap-southeast-1a.amazonaws.com/ (which is what your input region is attempting to resolve to) does not exist. You can verify this via the EC2 Region documentation.

Region Name: Asia Pacific (Singapore)

Region: ap-southeast-1

Endpoint: ec2.ap-southeast-1.amazonaws.com

Further Reading

AWS Regions and Endpoints

Body:
I am new to aws, I am trying to use aws-cli to connect aws as I am confortable with commandline, and want to use to write the script to automate the process.

However I am getting error as below:

_
    attempt_number, caught_exception)
  File "/usr/local/lib/python2.7/site-packages/botocore/retryhandler.py", line 359, in _check_caught_exception
    raise caught_exception
EndpointConnectionError: Could not connect to the endpoint URL: "https://ec2.ap-southeast-1a.amazonaws.com/"
2017-07-08 20:30:52,763 - MainThread - awscli.clidriver - DEBUG - Exiting with rc 255

Could not connect to the endpoint URL: "https://ec2.ap-southeast-1a.amazonaws.com/"

I have setup the profile user as in the config file.

[profile joey2]
output = json
region = ap-southeast-1a

the credential such as api key and secret is configured properly.

Could someone help to figure out what is cause of this issue.
highly appreciate for any advice?


问:
Why do we need to use `int main` and not `void main` in C++?
Why do we need to use int main and not void main in C++?

答:
Most Operating Systems report back to the user, or the calling process, if an application was successful or not.   This is especially useful in scripting, where the script can conditionally branch (if-then) on the results of a program.  Something along the lines of:

```<code>// pseudo-code
screenscrape  http://mydatasource.com > results.txt
if errorlevel == 0 then
   processfile results.txt
else
   echo Screen Scraping Failed!
end if
</code>```

This result status is done via the return value of main.

While some compilers allow for void main, for the sake of consistency and simplicity, the ANSI standard requires one single prototype of main:

```<code>int main(int argc, char *argv[]);
</code>```

Because in C, arguments are cleaned up by the caller, the author of main can neglect to declare or process the arguments argc & argv.  However, if the setup-routines that call main expect an int return value, and instead don't find one, behavior can undefined.

Short answer:

The return value of main is useful
for scripting.

The setup and cleanup routines that invoke main need a consistent interface to use.

OwnerDisplayName: kasperasky

Body:
Most Operating Systems report back to the user, or the calling process, if an application was successful or not.   This is especially useful in scripting, where the script can conditionally branch (if-then) on the results of a program.  Something along the lines of:

// pseudo-code
screenscrape  http://mydatasource.com > results.txt
if errorlevel == 0 then
   processfile results.txt
else
   echo Screen Scraping Failed!
end if

This result status is done via the return value of main.

While some compilers allow for void main, for the sake of consistency and simplicity, the ANSI standard requires one single prototype of main:

int main(int argc, char *argv[]);

Because in C, arguments are cleaned up by the caller, the author of main can neglect to declare or process the arguments argc & argv.  However, if the setup-routines that call main expect an int return value, and instead don't find one, behavior can undefined.

Short answer:

The return value of main is useful
for scripting.

The setup and cleanup routines that invoke main need a consistent interface to use.

OwnerDisplayName: abelenky

LastEditorDisplayName: abelenky


问:
YouTube: How to present embed video with sound muted
I'm trying to embed a video with the sound muted but I can not figure out how it make it work.

Currently I'm using this but doesn't work:

```<code><iframe src="https://www.youtube.com/embed/uNRGWVJ10gQ?rel=0&autoplay=1" width="560" height="315" frameborder="0" allowfullscreen></iframe>
</code>```

Any of you knows how can I make this work ?

答:
```<code><iframe width="560" height="315" src="https://www.youtube-nocookie.com/embed/ObHKvS2qSp8?list=PLF8tTShmRC6uppiZ_v-Xj-E1EtR3QCTox&autoplay=1&controls=1&loop=1&mute=1" frameborder="0" allowfullscreen></iframe>

<iframe width="560" height="315" src="https://www.youtube.com/embed/ObHKvS2qSp8?list=PLF8tTShmRC6uppiZ_v-Xj-E1EtR3QCTox&autoplay=1&controls=1&loop=1&mute=1" frameborder="0" allowfullscreen></iframe>
</code>```

Body:
I'm trying to embed a video with the sound muted but I can not figure out how it make it work.

Currently I'm using this but doesn't work:

Any of you knows how can I make this work ?


问:
Redirecting from subfolder to subdomain
Right now I have web api configured for my route web.site.com/v1/api. The subdomain api.site.com currently points to web.site.com. Is there any way to route requests made to api.site.com to web.site.com/v1/api, without redirects? I.e. I don't want to user to know they're actually sending requests to web.site.com/v1/api.

Is a rewrite rule with proxy the way to go here?

答:
Since both are same application,you can just rewrite only the URL part to  v1/api/{R:1}

This rule should work.

```<code><rule name="rewriteochildifapi">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{HTTP_HOST}" pattern="api.example.com" />
                    </conditions>
                    <action type="Rewrite" url="v1/api/{R:1}" />
                </rule>
</code>```

Title: Redirecting from subfolder to subdomain

Body:
Since both are same application,you can just rewrite only the URL part to  v1/api/{R:1}

This rule should work.

<rule name="rewriteochildifapi">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{HTTP_HOST}" pattern="api.example.com" />
                    </conditions>
                    <action type="Rewrite" url="v1/api/{R:1}" />
                </rule>


问:
PHP - Add leading zeros to number but keep maximum length
I have an Auto-Increment field in a database.

I want these numbers to be prepended by zeros, to a maximum length of seven.

Example:

Original number: 1  Desired result: 0000001

or

Original number 768 Desired result 0000768

How would I achieve this in PHP?

答:
Use str_pad function of PHP

```<code>$input = 1;
$number = str_pad($input, 7, "0", STR_PAD_LEFT);
</code>```

Body:
Use str_pad function of PHP

$input = 1;
$number = str_pad($input, 7, "0", STR_PAD_LEFT);


答:
You were very close with this line of code:

```<code>Max900.930am <- apply.daily(XTS1["T09:00/T09:30"], function(x) max(XTS1))
</code>```

But there's a crucial typo: max(XTS1) should be max(x). This error is why you get the maximum for the entire series, not just the day.  This would have worked:

```<code>Max900.930am <- apply.daily(XTS1["T09:00/T09:30"], max)
</code>```

And you can easily get both the max and the min with one call:

```<code>range0900.0930 <- apply.daily(XTS1["T09:00/T09:30"], range)
</code>```

Title: Get highest value in time range every day (xts)

Body:
XTS object XTS1 has about three days of data in 15 minute intervals. I want to find the maximum values registered every day between 900am and 930am, and then record such values on a vector. As shown in the example.

I would then do the same for the minimum. The objective is to record the daily opening range for a financial instrument (daily opening range = daily max & min during a time range). To keep it simple I'm ignoring the minimum on this example.

The question is very similar if not a duplicate of this one. Yet the solution provided there is for finding weekly maximums in a database with daily frequency, whereas this one is for finding hourly maximums in a database with intraday frequency. More importantly, the solution provided there does not work for this case (see below).

library('xts')
XTS1 <- structure(c(0.2284, 0.2283, 0.2284, 0.2288, 0.2307, 0.2319, 0.2322, 0.2327, 0.2328, 0.2327, 0.2327, 0.2327, 0.2331, 0.2338, 0.2338, 0.2346, 0.2348, 0.2348, 0.236, 0.2361, 0.2362, 0.236, 0.2365, 0.2364, 0.2363, 0.236, 0.2359, 0.2364, 0.2365, 0.2363, 0.2363, 0.2362, 0.2363, 0.2364, 0.2365, 0.2365, 0.2364, 0.2364, 0.2363, 0.2363, 0.2364, 0.2363, 0.2363, 0.2363, 0.2364, 0.2364, 0.2364, 0.2364, 0.2365, 0.2365, 0.2365, 0.2365, 0.2365, 0.2366, 0.2366, 0.2365, 0.2365, 0.2364, 0.2364, 0.2364, 0.2364, 0.2363, 0.2365, 0.2365, 0.2366, 0.2365, 0.2365, 0.2364, 0.2364, 0.2368, 0.2373,
                    0.2378, 0.2379, 0.2382, 0.2383, 0.2384, 0.2384, 0.2384, 0.2383, 0.2385, 0.2385, 0.2387, 0.2385, 0.2385, 0.2385, 0.2386, 0.2387, 0.2387, 0.24, 0.2394, 0.2396, 0.2394, 0.2398, 0.2394, 0.2396, 0.24, 0.24, 0.2401, 0.2397, 0.2399, 0.2492, 0.2398, 0.2203, 0.2104, 0.2104, 0.2404, 0.2398, 0.24, 0.2401, 0.2402, 0.2399, 0.24, 0.24, 0.2403, 0.2406, 0.2401, 0.2404, 0.2406, 0.2406, 0.2405, 0.241, 0.2411, 0.2411, 0.2411, 0.2411, 0.2411, 0.2411, 0.2411, 0.2411, 0.2411, 0.2411, 0.2411, 0.2411, 0.2411, 0.241, 0.2405, 0.2406, 0.2405, 0.2404, 0.2404, 0.2406, 0.2408, 0.2406, 0.2406, 0.2407, 0.2407, 0.2407, 0.2408, 0.2408, 0.2408, 0.2408, 0.2408, 0.2408, 0.2408, 0.2411, 0.241, 0.241, 0.2411, 0.2411, 0.2412, 0.2412, 0.2411, 0.2411, 0.2411, 0.2412, 0.2412, 0.2412, 0.2412, 0.2412, 0.2412, 0.2412, 0.2411, 0.2412, 0.2412, 0.2412, 0.2413, 0.2412, 0.2411, 0.2411, 0.241, 0.241, 0.2411, 0.2409, 0.2417, 0.2422, 0.2421, 0.2428, 0.2426, 0.2428, 0.2421, 0.2421, 0.2419, 0.2422, 0.2424, 0.2427, 0.2437, 0.2438, 0.2441, 0.2442), .Dim = c(199L, 1L), .indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "", tclass = c("POSIXct", "POSIXt"), tzone = "", class = c("xts", "zoo"), .CLASS = structure("double", class = "CLASS"), formattable = structure(list(formatter = "formatC", format = structure(list(format = "f", digits = 2), .Names = c("format", "digits")), preproc = "percent_preproc", postproc = "percent_postproc"), .Names = c("formatter", "format", "preproc", "postproc")), index = structure(c(1413981900, 1413982800, 1413983700, 1413984600, 1413985500, 1413986400, 1413987300, 1413988200, 1413989100, 1413990000, 1413990900, 1413991800, 1413992700, 1413993600, 1413994500, 1413995400, 1413996300, 1413997200, 1413998100, 1413999000, 1413999900, 1414000800, 1414001700, 1414002600, 1414003500, 1414004400, 1414005300, 1414006200, 1414007100, 1414008000, 1414009800, 1414010700, 1414011600, 1414015200, 1414016100, 1414017000, 1414017900, 1414018800, 1414019700, 1414020600, 1414021500, 1414022400, 1414023300, 1414024200, 1414025100, 1414026000, 1414026900, 1414027800, 1414028700, 1414029600, 1414030500, 1414031400, 1414032300, 1414033200, 1414034100, 1414035000, 1414035900, 1414036800, 1414037700, 1414038600, 1414039500, 1414040400, 1414041300, 1414042200, 1414043100, 1414044000, 1414044900, 1414045800, 1414046700, 1414047600, 1414048500, 1414049400, 1414050300, 1414051200, 1414052100, 1414053000, 1414053900, 1414054800, 1414055700, 1414056600, 1414057500, 1414058400, 1414059300, 1414060200, 1414061100, 1414062000, 1414062900, 1414063800, 1414064700, 1414065600, 1414066500, 1414067400, 1414068300, 1414069200, 1414070100, 1414071000, 1414071900, 1414072800, 1414073700, 1414074600, 1414075500, 1414076400, 1414077300, 1414078200, 1414079100, 1414080000, 1414080900, 1414081800, 1414082700, 1414083600, 1414084500, 1414085400, 1414086300, 1414087200, 1414088100, 1414089000, 1414089900, 1414090800, 1414091700, 1414092600, 1414093500, 1414094400, 1414096200, 1414097100, 1414098000, 1414101600, 1414102500, 1414103400, 1414104300, 1414105200, 1414106100, 1414107000, 1414107900, 1414108800, 1414109700, 1414110600, 1414111500, 1414112400, 1414113300, 1414114200, 1414115100, 1414116000, 1414116900, 1414117800, 1414118700, 1414119600, 1414120500, 1414121400, 1414122300, 1414123200, 1414124100, 1414125000, 1414125900, 1414126800, 1414127700, 1414128600, 1414129500, 1414130400, 1414131300, 1414132200, 1414133100, 1414134000, 1414134900, 1414135800, 1414136700, 1414137600, 1414138500, 1414139400, 1414140300, 1414141200, 1414142100, 1414143000, 1414143900, 1414144800, 1414145700, 1414146600, 1414147500, 1414148400, 1414149300, 1414150200, 1414151100, 1414152000, 1414152900, 1414153800, 1414154700, 1414155600, 1414156500, 1414157400, 1414158300, 1414159200, 1414160100, 1414161000, 1414161900, 1414162800, 1414163700, 1414164600, 1414165500, 1414166400, 1414167300), tzone = "", tclass = c("POSIXct", "POSIXt")))

#DESIRED OUTPUT
                      [,1]  Max900.930am
2014-10-22 08:45:00 0.2284            NA
2014-10-22 09:00:00 0.2283        0.2283
2014-10-22 09:15:00 0.2284        0.2284
2014-10-22 09:30:00 0.2288        0.2288
2014-10-22 09:45:00 0.2307        0.2288
2014-10-22 10:00:00 0.2319        0.2288
.....

#This records max on desired time range, but in whole database rather than for every day
max(XTS1['T09:00:00/T09:30:00'])

#This says "Error: width > 0 is not TRUE"
xxx = rollapply(data = XTS1, width = XTS1['T09:00:00/T09:30:00'], FUN = max)

#This is derived from solution by @JoshuaUlrich to the other question
#Doesn't work: records max on desired time range, in whole database rather than every day
 Max900.930am <- apply.daily(XTS1["T09:00/T09:30"], function(x) max(XTS1))
 y <- merge(XTS1, Max900.930am, fill = na.locf)

#Printout of Max900.930am, showing the problem
                      [,1]
2014-10-22 09:30:00 0.2492
2014-10-23 09:30:00 0.2492
2014-10-24 09:30:00 0.2492

Body:
You were very close with this line of code:

Max900.930am <- apply.daily(XTS1["T09:00/T09:30"], function(x) max(XTS1))

But there's a crucial typo: max(XTS1) should be max(x). This error is why you get the maximum for the entire series, not just the day.  This would have worked:

Max900.930am <- apply.daily(XTS1["T09:00/T09:30"], max)

And you can easily get both the max and the min with one call:

range0900.0930 <- apply.daily(XTS1["T09:00/T09:30"], range)