问:
How to solve server response issue for android apps
When i redirect android app to my local xampp server i am getting expected output from server. like below

Problem is when i redirect my app to a real ip or a domain server problem occurs. Here is my code.

```<code> protected String doInBackground(String[] paramparameterForURL) {

        try{
            //serv_url="http://www.eurekabd.com";//shakil/"+paramparameterForURL[0];
            URL url = new URL("http://www.eurekabd.com/shakil/home.php"/*serv_url*/);
            //URL url = new URL("http://192.168.0.109/shakil/shakil.php"/*serv_url*/);
            //URL url = new URL("http://144.48.2.11/shakil/shakil.php"/*serv_url*/);
            JSONObject postDataParams = new JSONObject();

            postDataParams.put("name", "abhay");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(300 /* milliseconds */);
            conn.setConnectTimeout(300 /* milliseconds */);
            //conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));
            writer.flush();
            writer.close();
            os.close();

            int responseCode=conn.getResponseCode();
            if (responseCode == HttpsURLConnection.HTTP_OK) {
                BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuffer sb = new StringBuffer("");
                String line="";

                while((line = in.readLine()) != null) {
                    sb.append(line);

                    break;
                }
                in.close();
                return sb.toString();
            }
            else {
                return new String("false : "+responseCode);
            }
        }
        catch(Exception e){
            return new String("Exception: " + e.getMessage());
        }
    }
</code>```

Problems are

1.Server WWW.eurecabd.com is returning exception NULL like below

2.real ip server is returning  empty like bellow

How to solve the issue or what is the issue? Is it in coding or in network protocol?

答:
The issue is the response of the different servers , also you should modified this :

```<code>conn.setConnectTimeout(300 /* milliseconds */);
</code>```

300 milliseconds is too low for a connection timeout , remember is in milliseconds.

Body:
When i redirect android app to my local xampp server i am getting expected output from server. like below

Problem is when i redirect my app to a real ip or a domain server problem occurs. Here is my code.

 protected String doInBackground(String[] paramparameterForURL) {

        try{
            //serv_url="http://www.eurekabd.com";//shakil/"+paramparameterForURL[0];
            URL url = new URL("http://www.eurekabd.com/shakil/home.php"/*serv_url*/);
            //URL url = new URL("http://192.168.0.109/shakil/shakil.php"/*serv_url*/);
            //URL url = new URL("http://144.48.2.11/shakil/shakil.php"/*serv_url*/);
            JSONObject postDataParams = new JSONObject();

            postDataParams.put("name", "abhay");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(300 /* milliseconds */);
            conn.setConnectTimeout(300 /* milliseconds */);
            //conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));
            writer.flush();
            writer.close();
            os.close();

            int responseCode=conn.getResponseCode();
            if (responseCode == HttpsURLConnection.HTTP_OK) {
                BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuffer sb = new StringBuffer("");
                String line="";

                while((line = in.readLine()) != null) {
                    sb.append(line);

                    break;
                }
                in.close();
                return sb.toString();
            }
            else {
                return new String("false : "+responseCode);
            }
        }
        catch(Exception e){
            return new String("Exception: " + e.getMessage());
        }
    }

Problems are

1.Server WWW.eurecabd.com is returning exception NULL like below

2.real ip server is returning  empty like bellow

How to solve the issue or what is the issue? Is it in coding or in network protocol?

Body:
The issue is the response of the different servers , also you should modified this :

conn.setConnectTimeout(300 /* milliseconds */);

300 milliseconds is too low for a connection timeout , remember is in milliseconds.


来源: stackexchange

问:
Textview size needs to change according to user's given value in EditText
Dynamically change the TextView size based on user input. If user changes the value, textview needs to change

```<code>     et0=(EditText)findViewById(R.id.EditText0);
     bt = (Button)findViewById(R.id.btn);

     bt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String text = ((et.getText().toString()));
                    float i=et0.getTextSize();

                    tv.setText(text);
                    tv.setTextSize(i) ;
        }
    }

//problem is value is changing one time if edit again text size is not changing
any help advance thanks
</code>```

答:
In your xml

```<code>    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/edtText"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/txtOutput"/>
</code>```

and implement textwatcher over edittext

```<code>      edtText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                txtOutput.setText(charSequence.toString());
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Dynamically change the TextView size based on user input. If user changes the value, textview needs to change

     et0=(EditText)findViewById(R.id.EditText0);
     bt = (Button)findViewById(R.id.btn);

     bt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String text = ((et.getText().toString()));
                    float i=et0.getTextSize();

                    tv.setText(text);
                    tv.setTextSize(i) ;
        }
    }

//problem is value is changing one time if edit again text size is not changing
any help advance thanks

Body:
In your xml

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/edtText"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/txtOutput"/>

and implement textwatcher over edittext

      edtText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                txtOutput.setText(charSequence.toString());
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    });


问:
How to properly return count(*) values from scalar valued function
Every time I execute my code I get "false" from method

```<code> public bool exists(int vpisna, string geslo)
    {
        bool a = false;
        Uspeh = true;

        cmd = new SqlCommand("SELECT dbo.fnExists(@Vpisna,@Geslo)", povezava);
        cmd.Parameters.AddWithValue("@Vpisna", vpisna);

        cmd.Parameters.AddWithValue("@Geslo", geslo);

        try
        {
            povezava.Open();
          int result =(int)cmd.ExecuteScalar();

            if (result==1)
            {
                a = true;
            }
        }
        catch (Exception e)
        {
            ex = e;
        }
        finally
        {
            povezava.Close();
        }

        return a;
    }
</code>```

My scalar valued function:

```<code>[dbo].[fnExists](
    @Vpisna int,
    @Geslo nvarchar(40)
)
RETURNS INT AS BEGIN

DECLARE @a int

SET @a = (
    SELECT
        COUNT(*)
    FROM
        Student
    WHERE
        ID = @Vpisna
        AND
        Geslo = CONVERT( nvarchar(40), HashBytes('SHA1', @Geslo ), 2 )
)

RETURN @a
END
</code>```

Everytime I get a false result, even when I try to manipulate data inside of the scalar valued function. When I try the SELECT statement on real data without a the function it works inside the SQL Management Studio.

答:
I think your code series is wrong. Before create sql command must open sql connection or must open from sqlcommand.
Use this;

```<code>        SqlConnection cnn = new SqlConnection("sql-connection-string");
        cnn.Open();
        SqlCommand cmd = new SqlCommand("select 1", cnn);
</code>```

or

```<code>        SqlConnection cnn = new SqlConnection("sql-connection-string");
        SqlCommand cmd = new SqlCommand("select 1", cnn);
        cmd.Connection.Open();
</code>```

Body:
Every time I execute my code I get "false" from method

 public bool exists(int vpisna, string geslo)
    {
        bool a = false;
        Uspeh = true;

        cmd = new SqlCommand("SELECT dbo.fnExists(@Vpisna,@Geslo)", povezava);
        cmd.Parameters.AddWithValue("@Vpisna", vpisna);

        cmd.Parameters.AddWithValue("@Geslo", geslo);

        try
        {
            povezava.Open();
          int result =(int)cmd.ExecuteScalar();

            if (result==1)
            {
                a = true;
            }
        }
        catch (Exception e)
        {
            ex = e;
        }
        finally
        {
            povezava.Close();
        }

        return a;
    }

My scalar valued function:

[dbo].[fnExists](
    @Vpisna int,
    @Geslo nvarchar(40)
)
RETURNS INT AS BEGIN

DECLARE @a int

SET @a = (
    SELECT
        COUNT(*)
    FROM
        Student
    WHERE
        ID = @Vpisna
        AND
        Geslo = CONVERT( nvarchar(40), HashBytes('SHA1', @Geslo ), 2 )
)

RETURN @a
END

Everytime I get a false result, even when I try to manipulate data inside of the scalar valued function. When I try the SELECT statement on real data without a the function it works inside the SQL Management Studio.

Body:
I think your code series is wrong. Before create sql command must open sql connection or must open from sqlcommand.
Use this;

        SqlConnection cnn = new SqlConnection("sql-connection-string");
        cnn.Open();
        SqlCommand cmd = new SqlCommand("select 1", cnn);

or

        SqlConnection cnn = new SqlConnection("sql-connection-string");
        SqlCommand cmd = new SqlCommand("select 1", cnn);
        cmd.Connection.Open();


问:
Storing AAC Audio and Retrieving
I would like to store a file which has AAC audio frames,

For that i used the below pipeline,

```<code>gst-launch-1.0 filesrc location=Test_44100Hz_2ch_s16le.wav ! "audio/x-raw,rate=44100,format=s16le,channels=2" ! audioparse format=raw raw-format=s16le rate=44100 channels=2 ! faac ! aacparse ! queue ! filesink location=a1
</code>```

While reading that file again to pulsesink using below pipeline,

```<code>gst-launch-1.0 filesrc location=a1 ! aacparse ! faad ! audioconvert ! audioresample ! pulsesink
</code>```

I am Receiving below error, I used GST_DEBUG=3, but i am not able find the solution.

```<code>0:00:00.031924804  3379      0x2231d60 WARN                 basesrc gstbasesrc.c:3483:gst_base_src_start_complete:<filesrc0> pad not activated yet
Pipeline is PREROLLING ...
0:00:00.033044700  3379      0x2231050 WARN               baseparse gstbaseparse.c:3255:gst_base_parse_loop:<aacparse0> error: No valid frames found before end of stream
ERROR: from element /GstPipeline:pipeline0/GstAacParse:aacparse0: No valid frames found before end of stream
Additional debug info:
gstbaseparse.c(3255): gst_base_parse_loop (): /GstPipeline:pipeline0/GstAacParse:aacparse0
ERROR: pipeline doesn't want to preroll.
</code>```

Can anybody help me, To solve this? I need to store AAC audio frames and need to stream that file as AAC audio stream.

答:
AAC Audio streams require a container in order to be useful within gstreamer

For decoder initialization it is necessary to know sampling frequency and Audio Object.  In gstreamer we are unable to pass this metadata directly to the parser or the decoder.  The parser collects this data instead from the mp4 header then the encoder inherits the frame structure/size and sample rate. So this is a deficiency in either aacparse(parser) or avdec_aac/faad(decoder), none of which have exposed parameters to specify frame size of a raw file, the afore mentioned metadata.  That being said, I haven't found a compelling reason why anyone would need to do this.  I found myself trying to do it before I discovered the aac simply needed to be muxed into an MP4(mp4mux) or another container to work and be portable.  The container/framing only adds a small amount of data to the stream.

Title: Storing AAC Audio and Retrieving

Body:
I would like to store a file which has AAC audio frames,

For that i used the below pipeline,

gst-launch-1.0 filesrc location=Test_44100Hz_2ch_s16le.wav ! "audio/x-raw,rate=44100,format=s16le,channels=2" ! audioparse format=raw raw-format=s16le rate=44100 channels=2 ! faac ! aacparse ! queue ! filesink location=a1

While reading that file again to pulsesink using below pipeline,

gst-launch-1.0 filesrc location=a1 ! aacparse ! faad ! audioconvert ! audioresample ! pulsesink

I am Receiving below error, I used GST_DEBUG=3, but i am not able find the solution.

0:00:00.031924804  3379      0x2231d60 WARN                 basesrc gstbasesrc.c:3483:gst_base_src_start_complete:<filesrc0> pad not activated yet
Pipeline is PREROLLING ...
0:00:00.033044700  3379      0x2231050 WARN               baseparse gstbaseparse.c:3255:gst_base_parse_loop:<aacparse0> error: No valid frames found before end of stream
ERROR: from element /GstPipeline:pipeline0/GstAacParse:aacparse0: No valid frames found before end of stream
Additional debug info:
gstbaseparse.c(3255): gst_base_parse_loop (): /GstPipeline:pipeline0/GstAacParse:aacparse0
ERROR: pipeline doesn't want to preroll.

Can anybody help me, To solve this? I need to store AAC audio frames and need to stream that file as AAC audio stream.


问:
Can't execute inline assembler with the instructions in a string variable
I'm trying to execute inline assembly, giving a variable as input

```<code>void main(void)
{
    char a[20] = "mov edx, 88";

    asm("%[a]" : : [a]"r"(a));
}
</code>```

But :

```<code>gcc a.c -masm=intel
Error: no such instruction: `eax'
</code>```

How can I make this work ?

答:
The instructions must be in a form of a string literal(actual written string, the name of a char array is a pointer btw).
Other than that you got the general idea:)

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

int main(int argc, char ** argv){
char a[20] = "nice try:)";
char * dst;

asm("mov %[dst], %[src]\n\t"
    : [dst]"=r" (dst) : [src]"r"(a));

printf("%s\n", dst);
return 0;
}
</code>```

and a useful link:
      https://dmalcolm.fedorapeople.org/gcc/2015-08-31/rst-experiment/how-to-use-inline-assembly-language-in-c-code.html

Body:
I'm trying to execute inline assembly, giving a variable as input

void main(void)
{
    char a[20] = "mov edx, 88";

    asm("%[a]" : : [a]"r"(a));
}

But :

gcc a.c -masm=intel
Error: no such instruction: `eax'

How can I make this work ?

Body:
The instructions must be in a form of a string literal(actual written string, the name of a char array is a pointer btw).
Other than that you got the general idea:)

#include <stdio.h>

int main(int argc, char ** argv){
char a[20] = "nice try:)";
char * dst;

asm("mov %[dst], %[src]\n\t"
    : [dst]"=r" (dst) : [src]"r"(a));

printf("%s\n", dst);
return 0;
}

and a useful link:
      https://dmalcolm.fedorapeople.org/gcc/2015-08-31/rst-experiment/how-to-use-inline-assembly-language-in-c-code.html


问:
How to install a Chrome Extension not in the Downloads folder in Chrome OS?
The file picker in Chrome OS only shows the Downloads folder. How can we load an unpacked extension in Chrome that isn't in the Downloads folder?</p>

答: My suggestion would be to create a project folder within the download folder and load it from there. I wanted to do the same thing but Chrome OS doesn't seem to be able to create folders outside of the download folder unless it's done in your Google Drive.</p>


问:
jQuery - dynamic content click event not working correctly
I am having an issue with getting a click event to work on some dynamic content.

It is a little more complicated than this but pretty much I have a select2 input which when the user types a search term will do an ajax request and add the returned data to a table.

I have some extra code which should run when the td element of this content is clicked. If there is only a small amount of ajax data returned then the click event will execute correctly and target the correct element, however, if there is a large amount of data added to the table and I have to scroll down the page and then click the td element the event will not execute, instead it will target the tbody element instead.

I am using code similar to this:

```<code>$( document ).on( 'click', function( e ) {
    var target = $( e.target );

    if( target.is( "#myId table tr td" ) ) {
        console.log("td element has been clicked!");
    }

});
</code>```

I have also tried the following:

```<code> $( document ).on( 'click', '#myId table tr td', function(e) {
    console.log( "td element has been clicked!" );
 });
</code>```

However, the results were the same as with the first section of code.

Is there any reason why scrolling and clicking a dynamically created element will target the tbody instead of the td element?

Results of console.log the target and the HTML structure:

答:
Always write functions to access dynamically created pages.
If you write the code in $(document).bla(),
your javascript code might have loaded even before the dynamic page loads.

Simply place an onclick event handler  on the td, to call on the function.

Body:
I am having an issue with getting a click event to work on some dynamic content.

It is a little more complicated than this but pretty much I have a select2 input which when the user types a search term will do an ajax request and add the returned data to a table.

I have some extra code which should run when the td element of this content is clicked. If there is only a small amount of ajax data returned then the click event will execute correctly and target the correct element, however, if there is a large amount of data added to the table and I have to scroll down the page and then click the td element the event will not execute, instead it will target the tbody element instead.

I am using code similar to this:

$( document ).on( 'click', function( e ) {
    var target = $( e.target );

    if( target.is( "#myId table tr td" ) ) {
        console.log("td element has been clicked!");
    }

});

I have also tried the following:

 $( document ).on( 'click', '#myId table tr td', function(e) {
    console.log( "td element has been clicked!" );
 });

However, the results were the same as with the first section of code.

Is there any reason why scrolling and clicking a dynamically created element will target the tbody instead of the td element?

Results of console.log the target and the HTML structure:

Body:
Always write functions to access dynamically created pages.
If you write the code in $(document).bla(),
your javascript code might have loaded even before the dynamic page loads.

Simply place an onclick event handler <td onclick='callFunction()'> on the td, to call on the function.


问:
Linux tool to uncompress any file compression format
Given a file named "foo" without any format

Is there a linux command tool to be able to detect and uncompress it accordingly to the file format?

I know i can use "file foo" and uncompress it accordingly. However, I would want and need a tool that can detect and uncompress any format

答:
Compression works by removing as much redundant information as possible, thus maximizing the entropy of the compressed output. In other words, in the general case, compressed information is indistinguishable from random noise, and thus indistinguishable from each other.

To put it bluntly: all compressed files look the same, it is not possible to figure out after the fact what they were compressed with, unless you have additional out-of-band information. Some compression formats specify a container format (such as .zip files or .gz files) with a header that tells you which compression algorithm was used to compress the file, and they also specify a couple of magic bytes at the beginning of the file that tell you which container format is used.

But, not all compressed files are stored in such containers, not all containers have magic bytes, not all containers have a header telling you the compression algorithm, and last but not least, the output of one compression algorithm could accidentally begin with the magic bytes of a particular container format specifying a different compression algorithm.

So, in short, no, it is not possible to determine the compression algorithm from just the compressed output. You need out-of-band information about the compression algorithm.


问:
Pass radio values without knowing the unique radio names
I created a list of radio groups and attached them to a product category. So what am doing is checking the groups that the category is meant to have then am going to then pick up the radio values in those groups available to the category and display them to the user to fill.

The next thing is I want to pass them to my ajax function which will then inject it into database. The problem is I can't get the unique name of the radio input in my ajax since I am loading it from the database.

```<code><?php $notarray = DataDB::getInstance()->select_from_where('pro_print_group','product_category_id',$cat);
    while ($row = mysqli_fetch_assoc($notarray)) {?>
     <div class="col-sm-12">
      <label for="quantity"><?php echo DataDB::getInstance()->get_name_from_id('group_n','print_type_group','print_type_group_id',$row['print_type_group_id']); ?></label>
      <div class="printd-group">
       <?php
       $not = DataDB::getInstance()->select_from_where('print_type','print_type_group_id',$row['print_type_group_id']);
       foreach($not as $ow):?>
        <label class="printd">
            <input name="prind<?php echo $row['print_type_group_id'] ;?>[]" id="prind<?php echo $row['print_type_group_id'] ;?>[]" value="<?php echo $ow['print_type_id'] ;?>" checked="" type="radio" class="name" data-price="0"> <?php echo $ow['name'] ;?>
        </label>
        <?php endforeach; ?>
      </div>
      </div>
      <?php } ?>
</code>```

Ajax Function
when form is submitted i call this function

```<code>function testpr() {
     document.getElementById("load").style.display = "block";
    var track = 'YU6758990';
    var printd = $('#printd').val();
     $.ajax({
         type: 'post',
         url: 'frverify.php',
        data: "track=" + track + "&printd=" + printd + "&ins=testp",
             success: function(data)
        {
            document.getElementById("load").style.display = "none";
            jQuery('#get_prresult').html(data).show();
            scroll_to('#messs');

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

PHP function
The ajax function then passes it to this php function where I am to receive the post request which in return inserts the selected radio values to the database and then returns the response back to my front end

```<code>function test(){
    $track = $_POST['tack'];
    $printd = $_POST['printd'];

    echo DataDB::getInstance()->testp($track,$printd);

 }
</code>```

答:
My guess is that there are more then one radiobutton generated, if that's the case you could try something like this.

```<code><input name="printd[<?php echo $row['print_type_group_id'] ;?>]" id="<?php echo $row['print_type_group_id'] ;?>" value="<?php echo $ow['print_type_id'] ;?>" checked="" type="radio" class="name" data-price="0"> <?php echo $ow['name'] ;?>
</code>```

Then in your Javascript change the way you retrieve the values of your form by using serialize.

```<code>data: "track=" + track + "&" + $('form#id.selector').serialize() + "&ins=testp"
</code>```

Then inside your PHP script iterate trough the values with some sort of foreach loop

```<code>function test(){
    $track = $_POST['tack'];
    foreach($_POST['printd'] as $key => $value){
        //$key => print_type_group_id
        //$value => print_type_id
    }
    echo DataDB::getInstance()->testp($track,$printd);
}
</code>```

Not sure what you want to do with the data and what it is you actually need but this should send you in the right direction.

Body:
I created a list of radio groups and attached them to a product category. So what am doing is checking the groups that the category is meant to have then am going to then pick up the radio values in those groups available to the category and display them to the user to fill.

The next thing is I want to pass them to my ajax function which will then inject it into database. The problem is I can't get the unique name of the radio input in my ajax since I am loading it from the database.

<?php $notarray = DataDB::getInstance()->select_from_where('pro_print_group','product_category_id',$cat);
    while ($row = mysqli_fetch_assoc($notarray)) {?>

      <?php echo DataDB::getInstance()->get_name_from_id('group_n','print_type_group','print_type_group_id',$row['print_type_group_id']); ?>

       <?php
       $not = DataDB::getInstance()->select_from_where('print_type','print_type_group_id',$row['print_type_group_id']);
       foreach($not as $ow):?>

            <input name="prind<?php echo $row['print_type_group_id'] ;?>[]" id="prind<?php echo $row['print_type_group_id'] ;?>[]" value="<?php echo $ow['print_type_id'] ;?>" checked="" type="radio" class="name" data-price="0"> <?php echo $ow['name'] ;?>

        <?php endforeach; ?>

      <?php } ?>

Ajax Function
when form is submitted i call this function

function testpr() {
     document.getElementById("load").style.display = "block";
    var track = 'YU6758990';
    var printd = $('#printd').val();
     $.ajax({
         type: 'post',
         url: 'frverify.php',
        data: "track=" + track + "&printd=" + printd + "&ins=testp",
             success: function(data)
        {
            document.getElementById("load").style.display = "none";
            jQuery('#get_prresult').html(data).show();
            scroll_to('#messs');

        }
    });
}

PHP function
The ajax function then passes it to this php function where I am to receive the post request which in return inserts the selected radio values to the database and then returns the response back to my front end

function test(){
    $track = $_POST['tack'];
    $printd = $_POST['printd'];

    echo DataDB::getInstance()->testp($track,$printd);

 }

Body:
My guess is that there are more then one radiobutton generated, if that's the case you could try something like this.

<input name="printd[<?php echo $row['print_type_group_id'] ;?>]" id="<?php echo $row['print_type_group_id'] ;?>" value="<?php echo $ow['print_type_id'] ;?>" checked="" type="radio" class="name" data-price="0"> <?php echo $ow['name'] ;?>

Then in your Javascript change the way you retrieve the values of your form by using serialize.

data: "track=" + track + "&" + $('form#id.selector').serialize() + "&ins=testp"

Then inside your PHP script iterate trough the values with some sort of foreach loop

function test(){
    $track = $_POST['tack'];
    foreach($_POST['printd'] as $key => $value){
        //$key => print_type_group_id
        //$value => print_type_id
    }
    echo DataDB::getInstance()->testp($track,$printd);
}

Not sure what you want to do with the data and what it is you actually need but this should send you in the right direction.


问:
Redirect hundreds of URLs with specific pattern
I'm not sure how to properly write the directives in .htaccess to get URLs like this:

```<code>www.domain.com/photo/weather/p1741-high-stress.html
www.domain.com/photo/cultural-practices/p1752-thermal-convection.html
www.domain.com/photo/turf-diseases/p1748-algae-and-viruses.html
</code>```

to:

```<code>www.domain.com/gallery/detail/high-stress
www.domain.com/gallery/detail/thermal-convection
www.domain.com/gallery/detail/algae-and-viruses
</code>```

So essentially:

changing the first segment from photo to gallery

changing the second segment from whatever to detail

stripping out the first part of the third segment (p#####-)

stripping out the .html at the end

答:
You can use:</p>

```<code>RewriteEngine on
RewriteRule ^photo/[^/]+/p\d+-(.+)\.html$ gallery/detail/$1 [NC,R=301,L]
</code>```

Body:
I'm not sure how to properly write the directives in .htaccess to get URLs like this:

www.domain.com/photo/weather/p1741-high-stress.html
www.domain.com/photo/cultural-practices/p1752-thermal-convection.html
www.domain.com/photo/turf-diseases/p1748-algae-and-viruses.html

to:

www.domain.com/gallery/detail/high-stress
www.domain.com/gallery/detail/thermal-convection
www.domain.com/gallery/detail/algae-and-viruses

So essentially:

changing the first segment from photo to gallery

changing the second segment from whatever to detail

stripping out the first part of the third segment (p#####-)

stripping out the .html at the end

Body:
You can use:

RewriteEngine on
RewriteRule ^photo/[^/]+/p\d+-(.+)\.html$ gallery/detail/$1 [NC,R=301,L]


问:
How to call mapStateToProps in react component to get Redux stores
I am trying to get the Redux state that is stored to be set to a component's props. My components implementation is below

```<code>import React, { Component } from 'react';
import {connect} from 'react-redux';

class Characters extends Component {
    render() {
        console.log('props', this.props);
        return(
            <div>
                <h4>Characters</h4>
            </div>
        )
    }
}

const mapStateToProps = state => {
    return {
        characters: state.characters
    }
}

export default connect()(Characters);
</code>```

I have my reducers set up like following. Now my console.log() is printing out a dispatch object not the props. I am not sure what else I need to do to set the component's props. I have tested my reducers and they seem to work fine. I am having trouble setting the component's props to the redux store. Below is my main reducer.

```<code>import { combineReducers } from 'redux';
import characters from './characters_reducer';
import heroes from './heroes_reducer';

const rootReducers = combineReducers({
    characters,
    heroes
});

export default rootReducers;
</code>```

Not sure what am I doing wrong here. A little help and a hinge to the right direction would help a lot. Thanks :)

答:
You forgot to pass mapStateToProps to connect:</p>

```<code>export default connect(mapStateToProps)(Characters);
</code>```

Body:
I am trying to get the Redux state that is stored to be set to a component's props. My components implementation is below

import React, { Component } from 'react';
import {connect} from 'react-redux';

class Characters extends Component {
    render() {
        console.log('props', this.props);
        return(

Characters

        )
    }
}

const mapStateToProps = state => {
    return {
        characters: state.characters
    }
}

export default connect()(Characters);

I have my reducers set up like following. Now my console.log() is printing out a dispatch object not the props. I am not sure what else I need to do to set the component's props. I have tested my reducers and they seem to work fine. I am having trouble setting the component's props to the redux store. Below is my main reducer.

import { combineReducers } from 'redux';
import characters from './characters_reducer';
import heroes from './heroes_reducer';

const rootReducers = combineReducers({
    characters,
    heroes
});

export default rootReducers;

Not sure what am I doing wrong here. A little help and a hinge to the right direction would help a lot. Thanks :)

Body:
You forgot to pass mapStateToProps to connect:

export default connect(mapStateToProps)(Characters);


问:
Is the term function overloading equivalent to method overloading in Java?
I recently took an online test for an interview. It was a multiple choice test and I got the following question:

Q) In a Java class we can write multiple methods with same name and
  different method signatures, this is called_____________

a) function overriding

  b) function overloading

  c) none of the above

I know that it is method overloading but in the options it's not there

Is the term function overloading equivalent to method overloading in Java?

答:
From a pragmatic point of view, I would go with function overloading.

But when thinking in pure Java terms, the one and only term is methods. Java does not know functions, only methods. Besides the interface Function.

Coming from there, it is not really clear if "none" or "function overloading" is the correct answer.


问:
Create Array without SourceFile using Exiftool
I would like to use Exiftool to create an array of -Artists for all files in a directory. Using the exiftool command below works but the output is not desirable:

```<code>C:\exiftool.exe -Artist Dir
</code>```

The output looks something like this:

```<code>======== E:/File1.jpg
Artist                          : user1
======== E:/File2.jpg
Artist                          : user2
    1 directories scanned
    2 image files read
</code>```

I would like the output to look something like this:

```<code>user1_user2
</code>```

Or at least a simple array or output like:

```<code>user1
user2
</code>```

答:
To expand upon the answer I posted in the exiftool forums :

exiftool -q -s3 -Artist DIR

This will output each Artist tag on a line by itself, like your second example.

-q - Suppresses normal informational messages.  This will suppress the file name listings.

-s3 - Short output format.  In this case, the addition of 3 to the option only prints the values of the tag.

Body:
I would like to use Exiftool to create an array of -Artists for all files in a directory. Using the exiftool command below works but the output is not desirable:

C:\exiftool.exe -Artist Dir

The output looks something like this:

======== E:/File1.jpg
Artist                          : user1
======== E:/File2.jpg
Artist                          : user2
    1 directories scanned
    2 image files read

I would like the output to look something like this:

user1_user2

Or at least a simple array or output like:

user1
user2


问:
How can I add an icon font on my web extension (Add-on, plugin)
I am trying to add an icon font but some web pages block my font because I was using external URLs like this:

```<code>/* fallback */
@font-face {
   font-family: 'Material Icons';
   font-style: normal;
   font-weight: 400;
   src: url(https://fonts.gstatic.com/s/materialicons/v31/2fcrYFNaTjcS6g4U3t-Y5UEw0lE80llgEseQY3FEmqw.woff2) format('woff2');
}

.material-icons {
   font-family: 'Material Icons', sans-serif, monospace, Arial,
   Helvetica, Verdana, Futura;
   font-weight: lighter;
   font-style: normal;
   font-size: 1.5em;
   line-height: 1;
   letter-spacing: normal;
   text-transform: none;
   display: inline-block;
   white-space: nowrap;
   word-wrap: normal;
   direction: ltr;
   -moz-font-feature-settings: 'liga';
   -moz-osx-font-smoothing: grayscale;
 }
</code>```

The console error is showing this:

Refused to load the font 'data:font/woff;base64,.....ZU=' because it violates the following Content Security Policy directive: "default-src 'self' *.mozilla.net *.mozilla.org *.mozilla.com". Note that 'font-src' was not explicitly set, so 'default-src' is used as a fallback.

I am not sure if I can load this font from an external server, so I have downloaded the font and I am trying to add this to my Add-on but I don't have success.

This is my root path:

```<code>- css
  - fonts
     - Material_Icons.woff2
     - msc-icons.css

- manifest.json
</code>```

My Material_Icons.woff2:

```<code>/* fallback */
@font-face {
  font-family: 'Material Icons';
  font-style: normal;
  font-weight: 400;
  src: url('Material_Icons.woff2') format('woff2');
}

.material-icons {
  font-family: 'Material Icons', sans-serif, monospace, Arial,
  Helvetica, Verdana, Futura;
}
</code>```

My manifest.json:

```<code>  {

  "manifest_version": 2,
  "name": "xxx",
  "version": "1.0",

  "description": "xxx",

  "icons": {
    "48": "icon/msc.ico",
    "98": "icon/msc-x2.ico"
  },

  "content_security_policy": "script-src 'self'
  https://*.fonts.gstatic.com/s/materialicons/v31/2fcrYFNaTjcS6g4U3t-
  Y5UEw0lE80llgEseQY3FEmqw.woff2; object-src 'self'",

  "web_accessible_resources": [
      "./css/fonts/Material_Icons.woff2"
  ],

  "content_scripts": [
      {
          "matches": ["<all_urls>"],
          "js": ["./js/vue.js", "./js/msc-scripts.js"],
          "css": ["./css/msc-styles.css", "./css/fonts/msc-icons.css",
          "./css/fonts/msc-fonts.css"]
      }
  ],

  "applications": {
      "gecko": {
      "id": "borderify@example.com"
      }
  }

}
</code>```

I have added this to solve my first problem:

content_security_polic

And I added to solve my second problem:

web_accessible_resources

But I don't have success already.

答:
In your manifest.json try to update this line with your own link.

```<code> https://*.fonts.gstatic.com/s/materialicons/v31/2fcrYFNaTjcS6g4U3t-
</code>```

Y5UEw0lE80llgEseQY3FEmqw.woff2

Body:
I am trying to add an icon font but some web pages block my font because I was using external URLs like this:

/* fallback */
@font-face {
   font-family: 'Material Icons';
   font-style: normal;
   font-weight: 400;
   src: url(https://fonts.gstatic.com/s/materialicons/v31/2fcrYFNaTjcS6g4U3t-Y5UEw0lE80llgEseQY3FEmqw.woff2) format('woff2');
}

.material-icons {
   font-family: 'Material Icons', sans-serif, monospace, Arial,
   Helvetica, Verdana, Futura;
   font-weight: lighter;
   font-style: normal;
   font-size: 1.5em;
   line-height: 1;
   letter-spacing: normal;
   text-transform: none;
   display: inline-block;
   white-space: nowrap;
   word-wrap: normal;
   direction: ltr;
   -moz-font-feature-settings: 'liga';
   -moz-osx-font-smoothing: grayscale;
 }

The console error is showing this:

Refused to load the font 'data:font/woff;base64,.....ZU=' because it violates the following Content Security Policy directive: "default-src 'self' *.mozilla.net *.mozilla.org *.mozilla.com". Note that 'font-src' was not explicitly set, so 'default-src' is used as a fallback.

I am not sure if I can load this font from an external server, so I have downloaded the font and I am trying to add this to my Add-on but I don't have success.

This is my root path:

- css
  - fonts
     - Material_Icons.woff2
     - msc-icons.css

- manifest.json

My Material_Icons.woff2:

/* fallback */
@font-face {
  font-family: 'Material Icons';
  font-style: normal;
  font-weight: 400;
  src: url('Material_Icons.woff2') format('woff2');
}

.material-icons {
  font-family: 'Material Icons', sans-serif, monospace, Arial,
  Helvetica, Verdana, Futura;
}

My manifest.json:

  {

  "manifest_version": 2,
  "name": "xxx",
  "version": "1.0",

  "description": "xxx",

  "icons": {
    "48": "icon/msc.ico",
    "98": "icon/msc-x2.ico"
  },

  "content_security_policy": "script-src 'self'
  https://*.fonts.gstatic.com/s/materialicons/v31/2fcrYFNaTjcS6g4U3t-
  Y5UEw0lE80llgEseQY3FEmqw.woff2; object-src 'self'",

  "web_accessible_resources": [
      "./css/fonts/Material_Icons.woff2"
  ],

  "content_scripts": [
      {
          "matches": ["<all_urls>"],
          "js": ["./js/vue.js", "./js/msc-scripts.js"],
          "css": ["./css/msc-styles.css", "./css/fonts/msc-icons.css",
          "./css/fonts/msc-fonts.css"]
      }
  ],

  "applications": {
      "gecko": {
      "id": "borderify@example.com"
      }
  }

}

I have added this to solve my first problem:

content_security_polic

And I added to solve my second problem:

web_accessible_resources

But I don't have success already.

Body:
In your manifest.json try to update this line with your own link.

 https://*.fonts.gstatic.com/s/materialicons/v31/2fcrYFNaTjcS6g4U3t-

Y5UEw0lE80llgEseQY3FEmqw.woff2


问:
Self update for tkinter project in python 2.7 loops forever?
I have searched and applied several of the suggestion on stack before posting this. None have worked, but the code below is the closest I have come to it working.

What I want to accomplish is to build a small GUI that monitors several servers' CPU, processes (currently the command is just ls), and CRON status. Everything works fine except for a feature where the application automatically updates. I already have an update button, and would like to be able to call the function refresh() that the button is attached to every minute.

I am new to tkinter and have some doubts about other practices that I have written into the program. If you see anything alarming please feel free to say something.

I currently receive no error, but the program loops forever with no planned delay.

Thanks in advance!

```<code>#!/usr/bin/python
import ttk, os, subprocess, datetime
import ConfigParser
from Tkinter import *

config = ConfigParser.ConfigParser()
config.read("p_watch.ini")

def main():
    root = Tk()
    root.title('Processor Watch')
    root.geometry('800x480')
    app = ProcessorWatch(root)
    root.mainloop()
    root.destroy()

def ConfigSectionMap(section):
    config_dict = {}
    options = config.options(section)
    for option in options:
        try:
            config_dict[option] = config.get(section, option)
            if config_dict[option] == -1:
                DebugPrint("skip: %s" % option)
        except:
            print("exception on %s!" % option)
            config_dict[option] = None
    return config_dict

class ProcessorWatch:

    def __init__(self, master):

        ### create tabs for different machines
        notebook = ttk.Notebook(master)
        notebook.pack(side='top', fill=BOTH, expand=True)
        frame1 = ttk.Frame(notebook)
        frame1.pack(fill=BOTH, expand=True)
        frame2 = ttk.Frame(notebook)
        frame2.pack(fill=BOTH, expand=True)
        frame3 = ttk.Frame(notebook)
        frame3.pack(fill=BOTH, expand=True)
        notebook.add(frame1, text='Processor1')
        notebook.add(frame2, text='Processor2')
        notebook.add(frame3, text='Processor3')
        notebook.grid(sticky = 'NSEW')

        frame1_creds = ConfigSectionMap('processor 1')
        frame2_creds = ConfigSectionMap('processor 2')
        frame3_creds = ConfigSectionMap('processor 3')

        frame1.host_string  = frame1_creds['user'] + '@' + frame1_creds['host']
        frame1.index        = 0
        frame2.host_string  = frame2_creds['user'] + '@' + frame1_creds['host']
        frame2.index        = 1
        frame3.host_string  = frame3_creds['user'] + '@' + frame1_creds['host']
        frame3.index        = 2
        frames = [frame1,frame2,frame3]

        self.cron_button = {}
        self.spinbox = {}
        self.refresh_num = {}
        self.cpu_usage = {}
        self.cpu_label = {}
        self.usage_label = {}
        self.quit_button = {}
        self.refresh_button = {}

        for frame in frames:

            master.grid_columnconfigure(0, weight=1)
            master.grid_rowconfigure(0, weight=1)

            process_count = 0

            ### execute terminal commands
            self.cpu_usage[frame.index] = os.popen(
                "ssh -t " + frame.host_string + " grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage \"%\"}'"
                ).read()
            grep_results = os.popen("ls")
            cron_activity = os.popen("ssh -t " + frame.host_string + " \'service cron status | grep Active\'").read()

            ### determine and display CRON activity
            if 'inactive (dead)' in cron_activity:
                self.cron_button[frame.index] = Button(frame, text='CRON (inactive)',fg='white',bg='red', command= lambda f=frame: self.start_cron(master,f))
                self.cron_button[frame.index].grid(padx=20, ipady=15, pady=3,row=0, column=0, sticky='EW')
            else :
                self.cron_button[frame.index] = Button(frame, text='CRON (active)',fg='white',bg='green', command= lambda f=frame: self.stop_cron(master,f))
                self.cron_button[frame.index].grid(padx=20, ipady=15, pady=3,row=0, column=0, sticky='EW')

            ### config and display CPU usage
            self.usage_label[frame.index] = Label(frame, text='CPU Usage \n' + str(self.cpu_usage[frame.index].rstrip()),fg='white',bg='red')
            self.usage_label[frame.index].grid(padx=20, ipady=10, pady=3,row=3, column=0, sticky='EW')

            ### set up buttons
            self.quit_button[frame.index] = Button(frame, text="QUIT", fg="red",  command=frame.quit)
            self.quit_button[frame.index].grid(padx=120, pady=60,row=6, column=0)
            self.refresh_button[frame.index] = Button(frame, text="REFRESH", fg="blue", command= lambda f=frame: self.refresh(master,f))
            self.refresh_button[frame.index].grid(padx=20, pady=3,row=5, column=0, sticky='EW')

            ### populate listbox
            self.listbox = Listbox(frame, height=28, width=60)
            self.scrollbar = ttk.Scrollbar(frame, orient=VERTICAL, command=self.listbox.yview)
            self.listbox['yscrollcommand'] = self.scrollbar.set
            for line in grep_results:
                self.listbox.insert('end', str(line).rstrip())
                process_count+=1
            self.scrollbar.grid(row = 0, column = 4, sticky='NSE', rowspan=8)
            self.listbox.grid(row = 0, column = 2, columnspan = 2, sticky='E', rowspan=8)

            ### config and display number of processes running
            self.count_label = Label(frame, text='Perl Processes \n' + str(process_count),fg='black',bg='grey').grid(padx=20, ipady=10, pady=3,row=1, column=0, sticky='EW')
            self.refresh_label = Label(frame, text='Last Refresh at ' + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') ,fg='black').grid(padx=0, ipady=0, pady=0,row=7, column=0, sticky='EW')

        self.update(master,frame)

    def refresh(self,master,frame):
        # if self.usage_label[frame.index] is not None:
        #     self.usage_label[frame.index].destroy()
        ### execute terminal commands
        self.cpu_usage[frame.index] = os.popen(
                "ssh -t " + frame.host_string + " grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage \"%\"}'"
                ).read()
        self.usage_label[frame.index].configure(text='CPU Usage \n' + str(self.cpu_usage[frame.index].rstrip()))
        grep_results = os.popen("ls")
        # grep_results = os.popen("ps aux | grep \"\.pl\" | grep -invertmatch grep")
        cron_activity = os.popen("ssh -t " + frame.host_string + " \'service cron status | grep Active\'").read()
        process_count = 0
        self.listbox.delete(0, END)
        # for line in grep_results:
        #     print line
        #     self.listbox.insert('end', str(line).rstrip())
        #     process_count+=1
        # self.listbox.grid(row = 0, column = 2, columnspan = 2, sticky='E', rowspan=8)
        self.count_label = Label(frame, text='Perl Processes \n' + str(process_count),fg='black',bg='grey').grid(padx=20, ipady=10, pady=3,row=1, column=0, sticky='EW')
        self.refresh_label = Label(frame, text='Last Refresh at ' + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') ,fg='black').grid(padx=0, ipady=0, pady=0,row=7, column=0, sticky='EW')

    # starting and stopping cron requires a password unless the user is configured not to
    def start_cron(self,master,frame):
        print "Starting Cron On " + frame.host_string
        try:
            os.system("ssh -t " + frame.host_string + " \'sudo service cron start\'")
            print "Cron Successfully Started On " + frame.host_string
            cron_activity = os.popen("ssh -t " + frame.host_string + " \'service cron status | grep Active\'").read()
            if 'active (running)' in cron_activity:
                self.cron_button[frame.index].configure(text='CRON (active)')
                self.cron_button[frame.index].configure(bg='green')
                self.cron_button[frame.index].configure(command= lambda: self.stop_cron(master,frame))
                master.update()
        except:
            print "Cron Failed On " + frame.host_string

    # starting and stopping cron requires a password unless the user is configured not to
    def stop_cron(self,master,frame):
        print "Stopping Cron On " + frame.host_string
        try:
            os.system("ssh -t " + frame.host_string + " \'sudo service cron stop\'")
            print "Cron Successfully Stopped On " + frame.host_string
            cron_activity = os.popen("ssh -t " + frame.host_string + " \'service cron status | grep Active\'").read()
            if 'inactive (dead)' in cron_activity:
                self.cron_button[frame.index].configure(text='CRON (inactive)')
                self.cron_button[frame.index].configure(bg='red')
                self.cron_button[frame.index].configure(command= lambda: self.start_cron(master,frame))
                master.update()
        except:
            print "Cron Failed On " + frame.host_string

    def update(self,master,frame):
        # While the pipe has data, read and update the StringVar
        self.refresh(master,frame)

        # set the update method to run again in 1 seconds time
        master.after(60000,self.update(master,frame))

if __name__ == "__main__":
    main()
</code>```

答:
The basic algorithm for running something periodically looks like this:

```<code>def refresh(root):
    <do whatever you want here>
    root.after(60000, refresh, root)
</code>```

When you call this function once, it will do whatever you want, then schedule itself to be called again in one minute.

You need to make sure that <do whatever you want here> takes only a few hundred milliseconds. Otherwise your application will get laggy, or freeze.

The mistake you made in your code is here:

```<code>master.after(60000,self.update(master,frame))
</code>```

This is identical to the following:

```<code>result = self.update(master, frame)
master.after(60000, result)
</code>```

The important thing to remember is that after requires a callable as the first argument after the number of milliseconds. If that callable needs arguments, they can be appended as additional arguments.

Body:
I have searched and applied several of the suggestion on stack before posting this. None have worked, but the code below is the closest I have come to it working.

What I want to accomplish is to build a small GUI that monitors several servers' CPU, processes (currently the command is just ls), and CRON status. Everything works fine except for a feature where the application automatically updates. I already have an update button, and would like to be able to call the function refresh() that the button is attached to every minute.

I am new to tkinter and have some doubts about other practices that I have written into the program. If you see anything alarming please feel free to say something.

I currently receive no error, but the program loops forever with no planned delay.

Thanks in advance!

#!/usr/bin/python
import ttk, os, subprocess, datetime
import ConfigParser
from Tkinter import *

config = ConfigParser.ConfigParser()
config.read("p_watch.ini")

def main():
    root = Tk()
    root.title('Processor Watch')
    root.geometry('800x480')
    app = ProcessorWatch(root)
    root.mainloop()
    root.destroy()

def ConfigSectionMap(section):
    config_dict = {}
    options = config.options(section)
    for option in options:
        try:
            config_dict[option] = config.get(section, option)
            if config_dict[option] == -1:
                DebugPrint("skip: %s" % option)
        except:
            print("exception on %s!" % option)
            config_dict[option] = None
    return config_dict

class ProcessorWatch:

    def __init__(self, master):

        ### create tabs for different machines
        notebook = ttk.Notebook(master)
        notebook.pack(side='top', fill=BOTH, expand=True)
        frame1 = ttk.Frame(notebook)
        frame1.pack(fill=BOTH, expand=True)
        frame2 = ttk.Frame(notebook)
        frame2.pack(fill=BOTH, expand=True)
        frame3 = ttk.Frame(notebook)
        frame3.pack(fill=BOTH, expand=True)
        notebook.add(frame1, text='Processor1')
        notebook.add(frame2, text='Processor2')
        notebook.add(frame3, text='Processor3')
        notebook.grid(sticky = 'NSEW')

        frame1_creds = ConfigSectionMap('processor 1')
        frame2_creds = ConfigSectionMap('processor 2')
        frame3_creds = ConfigSectionMap('processor 3')

        frame1.host_string  = frame1_creds['user'] + '@' + frame1_creds['host']
        frame1.index        = 0
        frame2.host_string  = frame2_creds['user'] + '@' + frame1_creds['host']
        frame2.index        = 1
        frame3.host_string  = frame3_creds['user'] + '@' + frame1_creds['host']
        frame3.index        = 2
        frames = [frame1,frame2,frame3]

        self.cron_button = {}
        self.spinbox = {}
        self.refresh_num = {}
        self.cpu_usage = {}
        self.cpu_label = {}
        self.usage_label = {}
        self.quit_button = {}
        self.refresh_button = {}

        for frame in frames:

            master.grid_columnconfigure(0, weight=1)
            master.grid_rowconfigure(0, weight=1)

            process_count = 0

            ### execute terminal commands
            self.cpu_usage[frame.index] = os.popen(
                "ssh -t " + frame.host_string + " grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage \"%\"}'"
                ).read()
            grep_results = os.popen("ls")
            cron_activity = os.popen("ssh -t " + frame.host_string + " \'service cron status | grep Active\'").read()

            ### determine and display CRON activity
            if 'inactive (dead)' in cron_activity:
                self.cron_button[frame.index] = Button(frame, text='CRON (inactive)',fg='white',bg='red', command= lambda f=frame: self.start_cron(master,f))
                self.cron_button[frame.index].grid(padx=20, ipady=15, pady=3,row=0, column=0, sticky='EW')
            else :
                self.cron_button[frame.index] = Button(frame, text='CRON (active)',fg='white',bg='green', command= lambda f=frame: self.stop_cron(master,f))
                self.cron_button[frame.index].grid(padx=20, ipady=15, pady=3,row=0, column=0, sticky='EW')

            ### config and display CPU usage
            self.usage_label[frame.index] = Label(frame, text='CPU Usage \n' + str(self.cpu_usage[frame.index].rstrip()),fg='white',bg='red')
            self.usage_label[frame.index].grid(padx=20, ipady=10, pady=3,row=3, column=0, sticky='EW')

            ### set up buttons
            self.quit_button[frame.index] = Button(frame, text="QUIT", fg="red",  command=frame.quit)
            self.quit_button[frame.index].grid(padx=120, pady=60,row=6, column=0)
            self.refresh_button[frame.index] = Button(frame, text="REFRESH", fg="blue", command= lambda f=frame: self.refresh(master,f))
            self.refresh_button[frame.index].grid(padx=20, pady=3,row=5, column=0, sticky='EW')

            ### populate listbox
            self.listbox = Listbox(frame, height=28, width=60)
            self.scrollbar = ttk.Scrollbar(frame, orient=VERTICAL, command=self.listbox.yview)
            self.listbox['yscrollcommand'] = self.scrollbar.set
            for line in grep_results:
                self.listbox.insert('end', str(line).rstrip())
                process_count+=1
            self.scrollbar.grid(row = 0, column = 4, sticky='NSE', rowspan=8)
            self.listbox.grid(row = 0, column = 2, columnspan = 2, sticky='E', rowspan=8)

            ### config and display number of processes running
            self.count_label = Label(frame, text='Perl Processes \n' + str(process_count),fg='black',bg='grey').grid(padx=20, ipady=10, pady=3,row=1, column=0, sticky='EW')
            self.refresh_label = Label(frame, text='Last Refresh at ' + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') ,fg='black').grid(padx=0, ipady=0, pady=0,row=7, column=0, sticky='EW')

        self.update(master,frame)

    def refresh(self,master,frame):
        # if self.usage_label[frame.index] is not None:
        #     self.usage_label[frame.index].destroy()
        ### execute terminal commands
        self.cpu_usage[frame.index] = os.popen(
                "ssh -t " + frame.host_string + " grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage \"%\"}'"
                ).read()
        self.usage_label[frame.index].configure(text='CPU Usage \n' + str(self.cpu_usage[frame.index].rstrip()))
        grep_results = os.popen("ls")
        # grep_results = os.popen("ps aux | grep \"\.pl\" | grep -invertmatch grep")
        cron_activity = os.popen("ssh -t " + frame.host_string + " \'service cron status | grep Active\'").read()
        process_count = 0
        self.listbox.delete(0, END)
        # for line in grep_results:
        #     print line
        #     self.listbox.insert('end', str(line).rstrip())
        #     process_count+=1
        # self.listbox.grid(row = 0, column = 2, columnspan = 2, sticky='E', rowspan=8)
        self.count_label = Label(frame, text='Perl Processes \n' + str(process_count),fg='black',bg='grey').grid(padx=20, ipady=10, pady=3,row=1, column=0, sticky='EW')
        self.refresh_label = Label(frame, text='Last Refresh at ' + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') ,fg='black').grid(padx=0, ipady=0, pady=0,row=7, column=0, sticky='EW')

    # starting and stopping cron requires a password unless the user is configured not to
    def start_cron(self,master,frame):
        print "Starting Cron On " + frame.host_string
        try:
            os.system("ssh -t " + frame.host_string + " \'sudo service cron start\'")
            print "Cron Successfully Started On " + frame.host_string
            cron_activity = os.popen("ssh -t " + frame.host_string + " \'service cron status | grep Active\'").read()
            if 'active (running)' in cron_activity:
                self.cron_button[frame.index].configure(text='CRON (active)')
                self.cron_button[frame.index].configure(bg='green')
                self.cron_button[frame.index].configure(command= lambda: self.stop_cron(master,frame))
                master.update()
        except:
            print "Cron Failed On " + frame.host_string

    # starting and stopping cron requires a password unless the user is configured not to
    def stop_cron(self,master,frame):
        print "Stopping Cron On " + frame.host_string
        try:
            os.system("ssh -t " + frame.host_string + " \'sudo service cron stop\'")
            print "Cron Successfully Stopped On " + frame.host_string
            cron_activity = os.popen("ssh -t " + frame.host_string + " \'service cron status | grep Active\'").read()
            if 'inactive (dead)' in cron_activity:
                self.cron_button[frame.index].configure(text='CRON (inactive)')
                self.cron_button[frame.index].configure(bg='red')
                self.cron_button[frame.index].configure(command= lambda: self.start_cron(master,frame))
                master.update()
        except:
            print "Cron Failed On " + frame.host_string

    def update(self,master,frame):
        # While the pipe has data, read and update the StringVar
        self.refresh(master,frame)

        # set the update method to run again in 1 seconds time
        master.after(60000,self.update(master,frame))

if __name__ == "__main__":
    main()

Body:
The basic algorithm for running something periodically looks like this:

def refresh(root):
    <do whatever you want here>
    root.after(60000, refresh, root)

When you call this function once, it will do whatever you want, then schedule itself to be called again in one minute.

You need to make sure that <do whatever you want here> takes only a few hundred milliseconds. Otherwise your application will get laggy, or freeze.

The mistake you made in your code is here:

master.after(60000,self.update(master,frame))

This is identical to the following:

result = self.update(master, frame)
master.after(60000, result)

The important thing to remember is that after requires a callable as the first argument after the number of milliseconds. If that callable needs arguments, they can be appended as additional arguments.


问:
Javascript to check whether a checkbox is being checked or unchecked
I have a javascript routine that is performing actions on a group of checkboxes, but the final action I want to set the clicked checkbox to checked or unchecked based on if the user was checking the box or unchecking.

Unfortunately, every time I check for whether it is being checked or unchecked, it returns "on" indicating the user is always checking the box!  Any help would be appreciated, I've also included the javascript.

```<code>// Uncheck all the checkboxs with the same Tax Credit
for (i=0; i<arrChecks.length; i++)
{
    var attribute = arrChecks[i].getAttribute("xid")
    if (attribute == elementName)
    {
        // if the current state is checked, unchecked and vice-versa
        if (arrChecks[i].value == "on")   // <-- This is always returning true, even if the box is being unchecked
        {
            arrChecks[i].checked = 1;
        } else {
            arrChecks[i].checked = 0;
        }

    } else {
        arrChecks[i].checked = 0;
    }
}
</code>```

答:
You should be evaluating against the checked property of the checkbox element. </p>

```<code>for (i=0; i<arrChecks.length; i++)
{
    var attribute = arrChecks[i].getAttribute("xid")
    if (attribute == elementName)
    {
        // if the current state is checked, unchecked and vice-versa
        if (arrChecks[i].checked)
        {
            arrChecks[i].checked = false;
        } else {
            arrChecks[i].checked = true;
        }

    } else {
        arrChecks[i].checked = false;
    }
}
</code>```

OwnerDisplayName: Mark K.

ContentLicense: CC BY-SA 2.5

Body:
I have a javascript routine that is performing actions on a group of checkboxes, but the final action I want to set the clicked checkbox to checked or unchecked based on if the user was checking the box or unchecking.

Unfortunately, every time I check for whether it is being checked or unchecked, it returns "on" indicating the user is always checking the box!  Any help would be appreciated, I've also included the javascript.

// Uncheck all the checkboxs with the same Tax Credit
for (i=0; i<arrChecks.length; i++)
{
    var attribute = arrChecks[i].getAttribute("xid")
    if (attribute == elementName)
    {
        // if the current state is checked, unchecked and vice-versa
        if (arrChecks[i].value == "on")   // <-- This is always returning true, even if the box is being unchecked
        {
            arrChecks[i].checked = 1;
        } else {
            arrChecks[i].checked = 0;
        }

    } else {
        arrChecks[i].checked = 0;
    }
}

Body:
You should be evaluating against the checked property of the checkbox element.

for (i=0; i<arrChecks.length; i++)
{
    var attribute = arrChecks[i].getAttribute("xid")
    if (attribute == elementName)
    {
        // if the current state is checked, unchecked and vice-versa
        if (arrChecks[i].checked)
        {
            arrChecks[i].checked = false;
        } else {
            arrChecks[i].checked = true;
        }

    } else {
        arrChecks[i].checked = false;
    }
}


问:
Lambda expression question
```<code>string[] fruits = { "apple", "banana", "mango", "orange",
                      "passionfruit", "grape" };

var query =
    fruits.Select((fruit, index) =>
                      new { index, str = fruit.Substring(0, index) });

foreach (var obj in query)
{
    Console.WriteLine("{0}", obj);
}

/*
 This code produces the following output:

 {index=0, str=}
 {index=1, str=b}
 {index=2, str=ma}
 {index=3, str=ora}
 {index=4, str=pass}
 {index=5, str=grape}
*/
</code>```

Could somebody explain, how "index" is associated here as array index of the elements?

Say, I need a query that instead of first letter returns me the whole object (string in this case) + associated index.

答: As for your first question, it is an overload for Select. See: http://msdn.microsoft.com/en-us/library/bb534869.aspx

Title: Lambda expression question

Body:
string[] fruits = { "apple", "banana", "mango", "orange",
                      "passionfruit", "grape" };

var query =
    fruits.Select((fruit, index) =>
                      new { index, str = fruit.Substring(0, index) });

foreach (var obj in query)
{
    Console.WriteLine("{0}", obj);
}

/*
 This code produces the following output:

 {index=0, str=}
 {index=1, str=b}
 {index=2, str=ma}
 {index=3, str=ora}
 {index=4, str=pass}
 {index=5, str=grape}
*/

Could somebody explain, how "index" is associated here as array index of the elements?

Say, I need a query that instead of first letter returns me the whole object (string in this case) + associated index.


问:
MS EDGE is URL encoding an AJAX POST call
I have an $.ajax call that is getting encoded with URL encoding.
One thing I need to specify is this only happens in Microsoft Edge.  Chrome and Firefox work fine with no issues.

Here is my Ajax call

```<code>var promise = $.ajax({
   url: "/webapp/CustomPricing/StartPricing",
   type: "POST",
   contentType: 'application/json',
   data: {
      "model": JSON.stringify(this.model),
      "numHandlingUnits": this.handlingUnitsCount,
      "handlingUnits": this.commoditiesCount
   },
   xhrFields: {
      withCredentials: true
   }
});
</code>```

Any ideas?

答:
Wrap JSON.stringify around data

```<code>JSON.stringify({
  "model": JSON.stringify(this.model),
  "numHandlingUnits": this.handlingUnitsCount,
  "handlingUnits": this.commoditiesCount
})
</code>```

Body:
I have an $.ajax call that is getting encoded with URL encoding.
One thing I need to specify is this only happens in Microsoft Edge.  Chrome and Firefox work fine with no issues.

Here is my Ajax call

var promise = $.ajax({
   url: "/webapp/CustomPricing/StartPricing",
   type: "POST",
   contentType: 'application/json',
   data: {
      "model": JSON.stringify(this.model),
      "numHandlingUnits": this.handlingUnitsCount,
      "handlingUnits": this.commoditiesCount
   },
   xhrFields: {
      withCredentials: true
   }
});

Any ideas?

Body:
Wrap JSON.stringify around data

JSON.stringify({
  "model": JSON.stringify(this.model),
  "numHandlingUnits": this.handlingUnitsCount,
  "handlingUnits": this.commoditiesCount
})


问:
Does using prepared statement to prevent SQL injection affect performance?
Apparently the best way to prevent SQL injection is to use prepared statements. However prepared statements are designed for something else altogether:

In database management systems, a prepared statement or parameterized
  statement is a feature used to execute the same or similar database
  statements repeatedly with high efficiency.

  [...]

  On the other hand, if a query is executed only once, server-side
  prepared statements can be slower because of the additional round-trip
  to the server. Implementation limitations may also lead to performance
  penalties: some versions of MySQL did not cache results of prepared
  queries, and some DBMSs such as PostgreSQL do not perform additional
  query optimization during execution.

I am guessing that prepared statements are primarily designed to be used inside tight loops in order to cut down the compile time of repeated statements. SQL injection prevention is just a bonus.

Assuming we are not using PDO or "emulated" prepared statements, does it make sense to use prepared statements for queries that are used only once on a page.

答:
The following applies to SQL Server

It is possible for an individual prepared statement to perform worse than an ad hoc query. However, the overall performance should be better.

Prepared statement performing worse than an ad hoc query

Suppose we have a table containing records for the past 10 years and 10 possible statuses. Assume that the data is evenly distributed and we have these queries:

```<code>... WHERE date >= '2017-01-01' AND status = 1
... WHERE date >= '2009-01-01' AND status = 1
... WHERE date >= ? AND status = ?
</code>```

For the first two queries (ad hoc) SQL Server could generate separate execution plans for each query e.g. using index on date column for the first query and using index on status column for second query.

For the third query (prepared) SQL Server will generate exactly one execution plan which could be best for most situations but not all. For example SQL Server might generate an execution plan that uses index on date column which would be efficient for recent dates but not past dates.

Ad hoc query performing worse than prepared statement

One of the problems with ad hoc queries is that they eventually lead to "plan cache bloat". When this happens, plans frequently get kicked out from the plan cache and recompiled when same query is executed again. Query compilation is an expensive process.

Observations

After converting my web application from ad hoc queries to prepared statements, I noticed a significant improvement in execution time. The plan cache bloat was eliminated and queries were not recompiled as often as they would with ad hoc queries saving precious CPU cycles and memory.

Body:
The following applies to SQL Server

It is possible for an individual prepared statement to perform worse than an ad hoc query. However, the overall performance should be better.

Prepared statement performing worse than an ad hoc query

Suppose we have a table containing records for the past 10 years and 10 possible statuses. Assume that the data is evenly distributed and we have these queries:

... WHERE date >= '2017-01-01' AND status = 1
... WHERE date >= '2009-01-01' AND status = 1
... WHERE date >= ? AND status = ?

For the first two queries (ad hoc) SQL Server could generate separate execution plans for each query e.g. using index on date column for the first query and using index on status column for second query.

For the third query (prepared) SQL Server will generate exactly one execution plan which could be best for most situations but not all. For example SQL Server might generate an execution plan that uses index on date column which would be efficient for recent dates but not past dates.

Ad hoc query performing worse than prepared statement

One of the problems with ad hoc queries is that they eventually lead to "plan cache bloat". When this happens, plans frequently get kicked out from the plan cache and recompiled when same query is executed again. Query compilation is an expensive process.

Observations

After converting my web application from ad hoc queries to prepared statements, I noticed a significant improvement in execution time. The plan cache bloat was eliminated and queries were not recompiled as often as they would with ad hoc queries saving precious CPU cycles and memory.


答:
You need to pass in your actionCreators and your mapStateToProps function to the connect function in order to be able to access the store from the component:

export default connect(mapStateToProps)(Characters);

Title: How to call mapStateToProps in react component to get Redux stores


问:
Granting rw permissions on cloudsql postgres
I have these users:

```<code>postgres | Create role, Create DB | {cloudsqlsuperuser}
proxyuser | Create role, Create DB | {cloudsqlsuperuser}
qa|Create role, Create DB | {cloudsqlsuperuser}
</code>```

And these tables:

```<code>                List of relations
 Schema |        Name        | Type  |   Owner
--------+--------------------+-------+-----------
 public | member_preferences | table | proxyuser
 public | message_queue      | table | proxyuser
 public | pubsub_queue       | table | proxyuser
</code>```

I am currently logged in as a postgres user and would like to give qa user permissions to read and write from any of those tables and any tables created in that schema in the future.

I was trying to follow this.

However, when I run
GRANT SELECT ON ALL TABLES IN SCHEMA public TO qa;
It responds with:
ERROR:  permission denied for relation message_queue

How do I troubleshoot this further? What am I missing?

PostgreSQL 9.6.1 on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4, 64-bit

is the version the instance displays

UPDATE:

I had to login as the proxyuser that was generating the tables in the first place to be able to give the permissions to the other user to read and write. This is really uncomfortable because all the users have the cloudsqlsuperuser role applied to them. As such, I expect the grant on the table to work from any of these users to any of them.

答:
I encountered an issue which may be similar to yours which is now resolved by the method below:

Login as the first user you made when setting up the instance (not postgres)

Use this user to grant privileges to subsequent users

Google appears to grant the first user all privileges but not subsequent users.. maybe?!

Body:
I have these users:

postgres | Create role, Create DB | {cloudsqlsuperuser}
proxyuser | Create role, Create DB | {cloudsqlsuperuser}
qa|Create role, Create DB | {cloudsqlsuperuser}

And these tables:

                List of relations
 Schema |        Name        | Type  |   Owner
--------+--------------------+-------+-----------
 public | member_preferences | table | proxyuser
 public | message_queue      | table | proxyuser
 public | pubsub_queue       | table | proxyuser

I am currently logged in as a postgres user and would like to give qa user permissions to read and write from any of those tables and any tables created in that schema in the future.

I was trying to follow this.

However, when I run
GRANT SELECT ON ALL TABLES IN SCHEMA public TO qa;
It responds with:
ERROR:  permission denied for relation message_queue

How do I troubleshoot this further? What am I missing?

PostgreSQL 9.6.1 on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4, 64-bit

is the version the instance displays

UPDATE:

I had to login as the proxyuser that was generating the tables in the first place to be able to give the permissions to the other user to read and write. This is really uncomfortable because all the users have the cloudsqlsuperuser role applied to them. As such, I expect the grant on the table to work from any of these users to any of them.


问:
assign values/string to cells using array vba
I am trying to assign values to column z using an array but I am not getting desire results. I am testing to assign cell Z1 = A, cell Z2 = B, cell Z3 = C
Right now my codes assign all 3 cells to C.  I have posted my desire results below.

```<code>Sub test()

Dim ws1 As Worksheet
Dim i, j As Long
Dim v As Variant

Set ws1 = Worksheets("Sheet1")
With ws1
    v = Array("A", "B", "C")
        For i = LBound(v) To UBound(v)
            For j = 1 To 3
                Cells(j, 26).Value = v(i)
            Next j
        Next i
End With

End Sub
</code>```

答:
To learn how to read and write 1D or 2D VBA arrays into cells look at the code below:

```<code>Public Sub TestArrayReadAndWrite()

    Dim ws As Worksheet
    Set ws = Worksheets("Sheet1")

    ' Set a 1D array in VBA
    ' Write the array to cells
    Dim v() As Variant
    v = Array("A", "B", "C")
    ws.Range("A1").Resize(3, 1).Value = WorksheetFunction.Transpose(v)
    ws.Range("A5").Resize(1, 3).Value = v

    ' Set a 3×3 array in VBA
    ' Write the array to cells
    Dim a() As Variant
    ReDim a(1 To 3, 1 To 3)
    a(1, 1) = "A11": a(1, 2) = "A12": a(1, 3) = "A13"
    a(2, 1) = "A21": a(2, 2) = "A22": a(2, 3) = "A13"
    a(3, 1) = "A31": a(3, 2) = "A32": a(3, 3) = "A13"

    ws.Range("C1").Resize(3, 3).Value = a

    ' Read Array 100×1 array of cells
    ' Modify the array by doubling the values
    ' Write the array back to the next column over
    Dim b() As Variant, i As Long
    b = ws.Range("G1").Resize(100, 1).Value
    For i = 1 To 100
        b(i, 1) = 2 * b(i, 1)
    Next i
    ws.Range("G1").Offset(0, 1).Resize(100, 1).Value = b
End Sub
</code>```

And the result:

It is a lot faster and concise to write entire arrays with one command by assigning to Range().Resize(n,m).Value = x then to loop through all the values and set them one at a time.

Body:
I am trying to assign values to column z using an array but I am not getting desire results. I am testing to assign cell Z1 = A, cell Z2 = B, cell Z3 = C
Right now my codes assign all 3 cells to C.  I have posted my desire results below.

Sub test()

Dim ws1 As Worksheet
Dim i, j As Long
Dim v As Variant

Set ws1 = Worksheets("Sheet1")
With ws1
    v = Array("A", "B", "C")
        For i = LBound(v) To UBound(v)
            For j = 1 To 3
                Cells(j, 26).Value = v(i)
            Next j
        Next i
End With

End Sub

Body:
To learn how to read and write 1D or 2D VBA arrays into cells look at the code below:

Public Sub TestArrayReadAndWrite()

    Dim ws As Worksheet
    Set ws = Worksheets("Sheet1")

    ' Set a 1D array in VBA
    ' Write the array to cells
    Dim v() As Variant
    v = Array("A", "B", "C")
    ws.Range("A1").Resize(3, 1).Value = WorksheetFunction.Transpose(v)
    ws.Range("A5").Resize(1, 3).Value = v

    ' Set a 3×3 array in VBA
    ' Write the array to cells
    Dim a() As Variant
    ReDim a(1 To 3, 1 To 3)
    a(1, 1) = "A11": a(1, 2) = "A12": a(1, 3) = "A13"
    a(2, 1) = "A21": a(2, 2) = "A22": a(2, 3) = "A13"
    a(3, 1) = "A31": a(3, 2) = "A32": a(3, 3) = "A13"

    ws.Range("C1").Resize(3, 3).Value = a

    ' Read Array 100×1 array of cells
    ' Modify the array by doubling the values
    ' Write the array back to the next column over
    Dim b() As Variant, i As Long
    b = ws.Range("G1").Resize(100, 1).Value
    For i = 1 To 100
        b(i, 1) = 2 * b(i, 1)
    Next i
    ws.Range("G1").Offset(0, 1).Resize(100, 1).Value = b
End Sub

And the result:

It is a lot faster and concise to write entire arrays with one command by assigning to Range().Resize(n,m).Value = x then to loop through all the values and set them one at a time.


问:
VBA - destroy a modeless UserForm instance properly
Intro:

I am aware that - showing UserForms - it's best practice to

handle QueryClose within the userform code (If CloseMode = vbFormControlMenu ...)

doing no Unload Me therein, just a timid Me.Hide instruction
(after preventing [x]-itting and eventual self-destruction via Cancel = True )

setting a related variable/[property] within the [class] code (e.g. .IsCancelled=True)

in order to be able to have the UF unloaded by the calling code.

Useful link

An outstanding overview "UserForm1.Show?" can be found at https://rubberduckvba.wordpress.com/2017/10/25/userform1-show/
as well as in numerous examplary SO answers (thx to Mathieu Guindon aka Mat's Mug and RubberDuck).

Further selection (►edit as of 5/1 2019)

Disadvantages in putting code into userforms instead of modules

Passing variable from form to module

Apply logic for userform dialog (Rubberduck)

The perfect userform (Vitosh academy)

1) Working examples for modal UserForms

As far as I understood - and I do try to learn -, the following code should be okay for modal UF's:

Case 1a) .. with a local variable for the UF instance, as often seen:

```<code>Public Sub ShowFormA
  Dim ufA As UserForm1
  Set ufA = New UserForm1
' show userform
  ufA.Show          ' equivalent to: ufA.Show vbModal

' handle data after user okay
  If Not ufA.IsCancelled Then
      '  do something ...
  End If

' >> object reference destroyed expressly (as seen in some examples)
  unload ufA
End Sub
</code>```

Case 1b) .. without a local variable, but using a With New codeblock:

```<code>' ----------------------------------------------------------
' >> no need to destruct object reference expressly,
'    as it will be destroyed whenever exiting the with block
' ----------------------------------------------------------
  With New UserForm1
      .Show         ' equivalent to: ufA.Show vbModal

    ' handle data after user okay
      If Not .IsCancelled Then
      '  do something ...
      End If
  End With
</code>```

2) Problem

Problems arise using a MODELESS UserForm instance.

Okay, the with block method (cf. 1b) should be sufficient to destroy any object reference after x-iting it:

```<code>  With New UserForm1
      .Show vbModeless  ' << show modeless uf
  End With
</code>```

If I try, however to

a) get information about a possible user cancelling as well as

b) to Unload a form if baptized using a local variable (e.g. "ufA") after the Show instruction,

all code lines will be executed at once for precisely the reason that the form is MODELESS:

code shows the form, the next moment ..

code finds no user cancelling, as there was no time for any user action, the next moment ..

[code unloads the form if using a local variable for the userform]

3) Question

How can I handle a) correctly reported UserForm cancels by the calling code of a MODELESS form as well as b) a (necessary?) unloading if using a local variable?

答:
I typically tie the lifetime of a modeless userform instance to the workbook's by putting code along those lines behind ThisWorkbook:

```<code>Option Explicit

Private m_MyForm As UserForm1

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    If Not m_MyForm Is Nothing Then
        Unload m_MyForm
        Set m_MyForm = Nothing
    End If
End Sub

Friend Property Get MyForm() As UserForm1
    If m_MyForm Is Nothing Then
        Set m_MyForm = New UserForm1
    End If

    Set MyForm = m_MyForm
End Property
</code>```

You can then refer to the modeless code throughout your code using e.g.

```<code>ThisWorkbook.MyForm.Show vbModeless
</code>```

etc.

ContentLicense: CC BY-SA 4.0

Body:
Intro:

I am aware that - showing UserForms - it's best practice to

handle QueryClose within the userform code (If CloseMode = vbFormControlMenu ...)

doing no Unload Me therein, just a timid Me.Hide instruction
(after preventing [x]-itting and eventual self-destruction via Cancel = True )

setting a related variable/[property] within the [class] code (e.g. .IsCancelled=True)

in order to be able to have the UF unloaded by the calling code.

Useful link

An outstanding overview "UserForm1.Show?" can be found at https://rubberduckvba.wordpress.com/2017/10/25/userform1-show/
as well as in numerous examplary SO answers (thx to Mathieu Guindon aka Mat's Mug and RubberDuck).

Further selection (►edit as of 5/1 2019)

Disadvantages in putting code into userforms instead of modules

Passing variable from form to module

Apply logic for userform dialog (Rubberduck)

The perfect userform (Vitosh academy)

1) Working examples for modal UserForms

As far as I understood - and I do try to learn -, the following code should be okay for modal UF's:

Case 1a) .. with a local variable for the UF instance, as often seen:

Public Sub ShowFormA
  Dim ufA As UserForm1
  Set ufA = New UserForm1
' show userform
  ufA.Show          ' equivalent to: ufA.Show vbModal

' handle data after user okay
  If Not ufA.IsCancelled Then
      '  do something ...
  End If

' >> object reference destroyed expressly (as seen in some examples)
  unload ufA
End Sub

Case 1b) .. without a local variable, but using a With New codeblock:

' ----------------------------------------------------------
' >> no need to destruct object reference expressly,
'    as it will be destroyed whenever exiting the with block
' ----------------------------------------------------------
  With New UserForm1
      .Show         ' equivalent to: ufA.Show vbModal

    ' handle data after user okay
      If Not .IsCancelled Then
      '  do something ...
      End If
  End With

2) Problem

Problems arise using a MODELESS UserForm instance.

Okay, the with block method (cf. 1b) should be sufficient to destroy any object reference after x-iting it:

  With New UserForm1
      .Show vbModeless  ' << show modeless uf
  End With

If I try, however to

a) get information about a possible user cancelling as well as

b) to Unload a form if baptized using a local variable (e.g. "ufA") after the Show instruction,

all code lines will be executed at once for precisely the reason that the form is MODELESS:

code shows the form, the next moment ..

code finds no user cancelling, as there was no time for any user action, the next moment ..

[code unloads the form if using a local variable for the userform]

3) Question

How can I handle a) correctly reported UserForm cancels by the calling code of a MODELESS form as well as b) a (necessary?) unloading if using a local variable?

Body:
I typically tie the lifetime of a modeless userform instance to the workbook's by putting code along those lines behind ThisWorkbook:

Option Explicit

Private m_MyForm As UserForm1

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    If Not m_MyForm Is Nothing Then
        Unload m_MyForm
        Set m_MyForm = Nothing
    End If
End Sub

Friend Property Get MyForm() As UserForm1
    If m_MyForm Is Nothing Then
        Set m_MyForm = New UserForm1
    End If

    Set MyForm = m_MyForm
End Property

You can then refer to the modeless code throughout your code using e.g.

ThisWorkbook.MyForm.Show vbModeless

etc.


问:
How to run examples of an API (which is already having workspace) using eclipse IDE
I am new to Java and I am not sure how apt is my question title. Please suggest any better title.

I have got a Java API which has many executable modules which do various things related to parsing MS Outlook's .pst files. And my problem is that I am getting this exception when I run the execute command to execute a .class file of one module of the API(java -classpath /opt/Java/libs/JPST/lib/jpst.jar /opt/Java/libs/JPST/examples/GetInboxMessages/bin/Example)-

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: /opt/Java/libs/JPST/examples/GetInboxMessages/bin/Example
Caused by: java.lang.ClassNotFoundException: .opt.Java.libs.JPST.examples.GetInboxMessages.bin.Example

        at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Could not find the main class: /opt/Java/libs/JPST/examples/GetInboxMessages/bin/Example.  Program will exit.
</code>```

So far ...

You can check my previous question where I concluded that I was correctly running the compile and execute commands. But I am still getting the above mentioned `exception.

I asked the API's developer who says that I should get Eclipse or Netbeans IDE. He said that the

examples folder inside the API's
  folder structure is entire Eclipse
  workspace.

and also said that

It is easier to compile and run all
  examples.

And now ...

So, I have setup Eclipse Helios for Java. Can anyone tell me how is it easy to compile and run all the examples (I think the modules inside the examples folder) using the IDE. I have earlier worked with Eclipse for PHP but never for Java.

Folder structure of the API

 I need to execute a .class file of one of those modules (many module folders are present inside examples directory). There are many such modules present inside the examples folder of the API. Each of these modules folders contain a bin folder (containing .class file) and src folder (containing .java file) . I need to execute one such .class file.

There is a lib directory containing a .jar file (which is needed to be referenced by my target .class file). The lib directory is at the same level as the examples directory.

Solution

I have verified that the solution given by Jonathan works (verified only without-using-elipse case). To make it more clear the classpath needs to include all the class locations in both compile and execute commands. So, if you need to compile and execute an Example.java file with a dependency Parent.jar do this:-

Compile

```<code>javac -classpath /path/to/Parent.jar/file/Parent.jar:/path/to/Example.java/file/ Example.java
</code>```

Execute

```<code>java -classpath /path/to/Parent.jar/file/Parent.jar:/path/to/Example.class/file Example
</code>```

And note the  separator - should be : for linux and ; for windows.

Thanks,

Sandeepan

答:
Sounds like a classpath issue.

Right click on your project in eclipse.

Go to buildPath > configure build path

Make sure the jar file is referenced in the libraries tab and if it isn't add it.

Body:
I am new to Java and I am not sure how apt is my question title. Please suggest any better title.

I have got a Java API which has many executable modules which do various things related to parsing MS Outlook's .pst files. And my problem is that I am getting this exception when I run the execute command to execute a .class file of one module of the API(java -classpath /opt/Java/libs/JPST/lib/jpst.jar /opt/Java/libs/JPST/examples/GetInboxMessages/bin/Example)-

Exception in thread "main" java.lang.NoClassDefFoundError: /opt/Java/libs/JPST/examples/GetInboxMessages/bin/Example
Caused by: java.lang.ClassNotFoundException: .opt.Java.libs.JPST.examples.GetInboxMessages.bin.Example

        at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Could not find the main class: /opt/Java/libs/JPST/examples/GetInboxMessages/bin/Example.  Program will exit.

So far ...

You can check my previous question where I concluded that I was correctly running the compile and execute commands. But I am still getting the above mentioned `exception.

I asked the API's developer who says that I should get Eclipse or Netbeans IDE. He said that the

examples folder inside the API's
  folder structure is entire Eclipse
  workspace.

and also said that

It is easier to compile and run all
  examples.

And now ...

So, I have setup Eclipse Helios for Java. Can anyone tell me how is it easy to compile and run all the examples (I think the modules inside the examples folder) using the IDE. I have earlier worked with Eclipse for PHP but never for Java.

Folder structure of the API

 I need to execute a .class file of one of those modules (many module folders are present inside examples directory). There are many such modules present inside the examples folder of the API. Each of these modules folders contain a bin folder (containing .class file) and src folder (containing .java file) . I need to execute one such .class file.

There is a lib directory containing a .jar file (which is needed to be referenced by my target .class file). The lib directory is at the same level as the examples directory.

Solution

I have verified that the solution given by Jonathan works (verified only without-using-elipse case). To make it more clear the classpath needs to include all the class locations in both compile and execute commands. So, if you need to compile and execute an Example.java file with a dependency Parent.jar do this:-

Compile

javac -classpath /path/to/Parent.jar/file/Parent.jar:/path/to/Example.java/file/ Example.java

Execute

java -classpath /path/to/Parent.jar/file/Parent.jar:/path/to/Example.class/file Example

And note the  separator - should be : for linux and ; for windows.

Thanks,

Sandeepan


问:
How to store Greasmonkey 4 Scripts in git
With the new update to Firefox 57 and Greasemonkey 4.0 it seems that the gm_scripts folder is no longer where the user.js scripts are stored.

Where are the scripts stored now?

Any suggestions for keeping these scripts in git?

答:
Where are the scripts stored now?

WebExtension API does not allow local file access so add-ons store data in their own storage area as an IndexDB at C:\Users\[Username]\AppData\Roaming\Mozilla\Firefox\Profiles\[Random].default\storage\default\moz-extension+++80728271-a923-4e37-a81d-68452721034c

The negative issues are:

You cant manually edit them with your own editor and you have to use the GM interface to edit them.

If you uninstal GM, all script will be gone and reinstalling GM wont bring them back.

At the moment GM doesn't have an Import (to manually load scripts) or Export (to create backups). Although you can export all scripts by copying the folder above.

You can copy scripts to Git and GM will (there are issues now) be able to get them from Git.

The gm_scripts folder should still be in the Firefox profile folder. GM4 doesn't delete it but it wont be able to use it.

https://superuser.com/questions/38093/where-are-the-greasemonkey-scripts-kept-in-portable-firefox

In XP: C:\Documents and Settings\user\Application
  Data\Mozilla\Firefox\Profiles\xxxxxxxx.default\gm_scripts

In Vista:
  c:\users\user\AppData\Roaming\Mozilla\Firefox\Profiles\xxxxxxxx.default\gm_scripts

Select the profile you want to use (if you only have one, it should
  look something like xxxxxxxx.default). Finally select the gm_scripts
  folder.

On a MAC: On a Mac, you can find your profile at ~/Library/Application
  Support/Firefox/Profiles